From 98b8afa91726b0b9c568309f662be871c6163082 Mon Sep 17 00:00:00 2001 From: federico Date: Mon, 16 Nov 2026 11:05:58 +0800 Subject: [PATCH 01/33] docs(crypto): clarify digest padding documentation --- .../java/org/tron/common/crypto/cryptohash/DigestEngine.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crypto/src/main/java/org/tron/common/crypto/cryptohash/DigestEngine.java b/crypto/src/main/java/org/tron/common/crypto/cryptohash/DigestEngine.java index b13e1d14ea2..f752ecccee4 100644 --- a/crypto/src/main/java/org/tron/common/crypto/cryptohash/DigestEngine.java +++ b/crypto/src/main/java/org/tron/common/crypto/cryptohash/DigestEngine.java @@ -57,9 +57,7 @@ protected void engineReset() { protected abstract void processBlock(byte[] data); /** - * Perform the final padding and store the result in the provided buffer. This method shall call - * {@link #flush} and then {@link #update} with the appropriate padding data in order to getData - * the full input data. + * Perform the final padding and store the resulting digest in the provided buffer. * * @param buf the output buffer * @param off the output offset From 8dd4511a885f7ed7dbb21c646c85ecdd167bfeb4 Mon Sep 17 00:00:00 2001 From: federico Date: Mon, 16 Nov 2026 11:24:06 +0800 Subject: [PATCH 02/33] fix(crypto): override Keccak state copying --- .../common/crypto/cryptohash/KeccakCore.java | 8 +++-- .../common/crypto/cryptohash/KeccakTest.java | 29 +++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/crypto/src/main/java/org/tron/common/crypto/cryptohash/KeccakCore.java b/crypto/src/main/java/org/tron/common/crypto/cryptohash/KeccakCore.java index c8919f64904..924b3f47be6 100644 --- a/crypto/src/main/java/org/tron/common/crypto/cryptohash/KeccakCore.java +++ b/crypto/src/main/java/org/tron/common/crypto/cryptohash/KeccakCore.java @@ -540,8 +540,12 @@ private final void doReset() { A[20] = 0xFFFFFFFFFFFFFFFFL; } - protected Digest copyState(KeccakCore dst) { - System.arraycopy(A, 0, dst.A, 0, 25); + @Override + protected Digest copyState(DigestEngine dst) { + if (!(dst instanceof KeccakCore)) { + throw new IllegalArgumentException("Destination must be a KeccakCore"); + } + System.arraycopy(A, 0, ((KeccakCore) dst).A, 0, 25); return super.copyState(dst); } diff --git a/framework/src/test/java/org/tron/common/crypto/cryptohash/KeccakTest.java b/framework/src/test/java/org/tron/common/crypto/cryptohash/KeccakTest.java index c3d1a96ba2e..6b8916d9b72 100644 --- a/framework/src/test/java/org/tron/common/crypto/cryptohash/KeccakTest.java +++ b/framework/src/test/java/org/tron/common/crypto/cryptohash/KeccakTest.java @@ -2,7 +2,9 @@ import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; +import static org.mockito.Mockito.mock; import java.nio.ByteBuffer; import java.security.DigestException; @@ -300,6 +302,33 @@ public void testCopy() throws Exception { assertArrayEquals(referenceDigest(Arrays.copyOf(input, 151)), copy.digest()); } + @Test + public void testCopyStateWithDigestEngineTarget() throws Exception { + DigestEngine digest = (DigestEngine) newDigest(); + DigestEngine copy = (DigestEngine) newDigest(); + byte[] input = inputBytes(); + digest.update(input, 0, 200); + copy.update(input); + + assertSame(copy, digest.copyState(copy)); + + digest.update(input, 200, input.length - 200); + assertArrayEquals(referenceDigest(input), digest.digest()); + assertArrayEquals(referenceDigest(Arrays.copyOf(input, 200)), copy.digest()); + } + + @Test + public void testCopyStateRejectsInvalidTarget() throws Exception { + DigestEngine digest = (DigestEngine) newDigest(); + byte[] input = inputBytes(); + digest.update(input); + DigestEngine invalidTarget = mock(DigestEngine.class); + + assertThrows(IllegalArgumentException.class, () -> digest.copyState(invalidTarget)); + assertThrows(IllegalArgumentException.class, () -> digest.copyState(null)); + assertArrayEquals(referenceDigest(input), digest.digest()); + } + private MessageDigest newDigest() throws Exception { return MessageDigest.getInstance("TRON-KECCAK-" + bits, TronCastleProvider.getInstance()); } From 4ca2f9ea71cd7a0eb799f52dcf82d79ccb52a6bb Mon Sep 17 00:00:00 2001 From: federico Date: Mon, 16 Nov 2026 11:39:58 +0800 Subject: [PATCH 03/33] fix(crypto): clear Keccak buffers on reset --- .../crypto/cryptohash/DigestEngine.java | 2 + .../common/crypto/cryptohash/KeccakCore.java | 3 ++ .../common/crypto/cryptohash/KeccakTest.java | 50 +++++++++++++++++++ 3 files changed, 55 insertions(+) diff --git a/crypto/src/main/java/org/tron/common/crypto/cryptohash/DigestEngine.java b/crypto/src/main/java/org/tron/common/crypto/cryptohash/DigestEngine.java index f752ecccee4..35ef20fa322 100644 --- a/crypto/src/main/java/org/tron/common/crypto/cryptohash/DigestEngine.java +++ b/crypto/src/main/java/org/tron/common/crypto/cryptohash/DigestEngine.java @@ -20,6 +20,7 @@ import java.security.DigestException; import java.security.MessageDigest; +import java.util.Arrays; public abstract class DigestEngine extends MessageDigest implements Digest { @@ -45,6 +46,7 @@ public DigestEngine(String alg) { * state. */ protected void engineReset() { + Arrays.fill(inputBuf, (byte) 0); inputLen = 0; blockCount = 0; } diff --git a/crypto/src/main/java/org/tron/common/crypto/cryptohash/KeccakCore.java b/crypto/src/main/java/org/tron/common/crypto/cryptohash/KeccakCore.java index 924b3f47be6..40463572e00 100644 --- a/crypto/src/main/java/org/tron/common/crypto/cryptohash/KeccakCore.java +++ b/crypto/src/main/java/org/tron/common/crypto/cryptohash/KeccakCore.java @@ -18,6 +18,8 @@ package org.tron.common.crypto.cryptohash; +import java.util.Arrays; + abstract class KeccakCore extends DigestEngine { private static final long[] RC = { @@ -529,6 +531,7 @@ public int getBlockLength() { } private final void doReset() { + Arrays.fill(tmpOut, (byte) 0); for (int i = 0; i < 25; i++) { A[i] = 0; } diff --git a/framework/src/test/java/org/tron/common/crypto/cryptohash/KeccakTest.java b/framework/src/test/java/org/tron/common/crypto/cryptohash/KeccakTest.java index 6b8916d9b72..94458655762 100644 --- a/framework/src/test/java/org/tron/common/crypto/cryptohash/KeccakTest.java +++ b/framework/src/test/java/org/tron/common/crypto/cryptohash/KeccakTest.java @@ -15,6 +15,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; +import org.springframework.test.util.ReflectionTestUtils; import org.tron.common.crypto.jce.TronCastleProvider; @RunWith(Parameterized.class) @@ -291,6 +292,48 @@ public void testSpiResetBeforeNewInput() throws Exception { assertArrayEquals(referenceDigest(nextInput), digest.digest()); } + @Test + public void testResetClearsBuffers() throws Exception { + for (boolean spi : new boolean[]{false, true}) { + DigestEngine digest = (DigestEngine) newDigest(); + byte[] input = inputBytes(); + digest.update(input); + byte[] output = new byte[bits / 8]; + digest.doPadding(output, 0); + assertArrayEquals(referenceDigest(input), output); + assertArrayEquals(output, (byte[]) ReflectionTestUtils.getField(digest, "tmpOut")); + + if (spi) { + digest.engineReset(); + } else { + digest.reset(); + } + + assertBuffersCleared(digest); + assertArrayEquals(referenceDigest(new byte[0]), digest.digest()); + assertArrayEquals(referenceDigest(input), digest.digest(input)); + } + } + + @Test + public void testDigestClearsBuffers() throws Exception { + DigestEngine digest = (DigestEngine) newDigest(); + int blockLength = digest.getBlockLength(); + for (int length : new int[]{0, 1, blockLength - 1, blockLength, blockLength + 1, + 2 * blockLength + 3}) { + byte[] input = Arrays.copyOf(inputBytes(), length); + byte[] expected = referenceDigest(input); + assertArrayEquals(expected, digest.digest(input)); + assertBuffersCleared(digest); + + digest.update(input); + byte[] output = new byte[expected.length + 4]; + assertEquals(expected.length, digest.digest(output, 2, expected.length)); + assertArrayEquals(expected, Arrays.copyOfRange(output, 2, output.length - 2)); + assertBuffersCleared(digest); + } + } + @Test public void testCopy() throws Exception { DigestEngine digest = (DigestEngine) newDigest(); @@ -329,6 +372,13 @@ public void testCopyStateRejectsInvalidTarget() throws Exception { assertArrayEquals(referenceDigest(input), digest.digest()); } + private void assertBuffersCleared(DigestEngine digest) { + byte[] inputBuffer = digest.getBlockBuffer(); + byte[] outputBuffer = (byte[]) ReflectionTestUtils.getField(digest, "tmpOut"); + assertArrayEquals(new byte[inputBuffer.length], inputBuffer); + assertArrayEquals(new byte[outputBuffer.length], outputBuffer); + } + private MessageDigest newDigest() throws Exception { return MessageDigest.getInstance("TRON-KECCAK-" + bits, TronCastleProvider.getInstance()); } From fe95ef66e716d91989b28626cad856f5297d8b86 Mon Sep 17 00:00:00 2001 From: federico Date: Mon, 16 Nov 2026 12:17:39 +0800 Subject: [PATCH 04/33] fix(crypto): reject incompatible digest copies --- .../crypto/cryptohash/DigestEngine.java | 8 ++- .../common/crypto/cryptohash/KeccakCore.java | 3 +- .../common/crypto/cryptohash/KeccakTest.java | 49 +++++++++++++++++++ 3 files changed, 58 insertions(+), 2 deletions(-) diff --git a/crypto/src/main/java/org/tron/common/crypto/cryptohash/DigestEngine.java b/crypto/src/main/java/org/tron/common/crypto/cryptohash/DigestEngine.java index 35ef20fa322..66e143792fb 100644 --- a/crypto/src/main/java/org/tron/common/crypto/cryptohash/DigestEngine.java +++ b/crypto/src/main/java/org/tron/common/crypto/cryptohash/DigestEngine.java @@ -227,12 +227,18 @@ protected long getBlockCount() { /** * This function copies the internal buffering state to some other instance of a class extending * {@code DigestEngine}. It returns a reference to the copy. This method is intended to be called - * by the implementation of the {@link #copy} method. + * by the implementation of the {@link #copy} method. The destination must use the same algorithm + * and internal block length. * * @param dest the copy * @return the value {@code dest} + * @throws IllegalArgumentException if the destination is null or incompatible */ protected Digest copyState(DigestEngine dest) { + if (dest == null || blockLen != dest.blockLen + || !getAlgorithm().equals(dest.getAlgorithm())) { + throw new IllegalArgumentException("Incompatible digest destination"); + } dest.inputLen = inputLen; dest.blockCount = blockCount; System.arraycopy(inputBuf, 0, dest.inputBuf, 0, diff --git a/crypto/src/main/java/org/tron/common/crypto/cryptohash/KeccakCore.java b/crypto/src/main/java/org/tron/common/crypto/cryptohash/KeccakCore.java index 40463572e00..1ba0612a2ce 100644 --- a/crypto/src/main/java/org/tron/common/crypto/cryptohash/KeccakCore.java +++ b/crypto/src/main/java/org/tron/common/crypto/cryptohash/KeccakCore.java @@ -548,8 +548,9 @@ protected Digest copyState(DigestEngine dst) { if (!(dst instanceof KeccakCore)) { throw new IllegalArgumentException("Destination must be a KeccakCore"); } + super.copyState(dst); System.arraycopy(A, 0, ((KeccakCore) dst).A, 0, 25); - return super.copyState(dst); + return dst; } public String toString() { diff --git a/framework/src/test/java/org/tron/common/crypto/cryptohash/KeccakTest.java b/framework/src/test/java/org/tron/common/crypto/cryptohash/KeccakTest.java index 94458655762..6c44a890654 100644 --- a/framework/src/test/java/org/tron/common/crypto/cryptohash/KeccakTest.java +++ b/framework/src/test/java/org/tron/common/crypto/cryptohash/KeccakTest.java @@ -372,6 +372,55 @@ public void testCopyStateRejectsInvalidTarget() throws Exception { assertArrayEquals(referenceDigest(input), digest.digest()); } + @Test + public void testCopyStateRejectsDifferentAlgorithm() throws Exception { + DigestEngine digest = (DigestEngine) newDigest(); + DigestEngine target = bits == 256 ? new Keccak512() : new Keccak256(); + byte[] input = inputBytes(); + byte[] targetInput = Arrays.copyOfRange(input, 31, 4099); + MessageDigest targetReference = bits == 256 ? new Keccak512() : new Keccak256(); + byte[] expectedTarget = targetReference.digest(targetInput); + digest.update(input, 0, 200); + target.update(targetInput, 0, 173); + + assertThrows(IllegalArgumentException.class, () -> digest.copyState(target)); + + digest.update(input, 200, input.length - 200); + target.update(targetInput, 173, targetInput.length - 173); + assertArrayEquals(referenceDigest(input), digest.digest()); + assertArrayEquals(expectedTarget, target.digest()); + } + + @Test + public void testCopyStateRejectsDifferentBlockLength() throws Exception { + DigestEngine digest = (DigestEngine) newDigest(); + DigestEngine target = bits == 256 ? new Keccak256() { + @Override + protected int getInternalBlockLength() { + return super.getInternalBlockLength() + 8; + } + } : new Keccak512() { + @Override + protected int getInternalBlockLength() { + return super.getInternalBlockLength() + 8; + } + }; + byte[] input = inputBytes(); + digest.update(input, 0, 200); + target.update(input, 0, 17); + byte[] targetBuffer = target.getBlockBuffer().clone(); + long[] targetState = ((long[]) ReflectionTestUtils.getField(target, "A")).clone(); + + assertThrows(IllegalArgumentException.class, () -> digest.copyState(target)); + + assertArrayEquals(targetBuffer, target.getBlockBuffer()); + assertArrayEquals(targetState, (long[]) ReflectionTestUtils.getField(target, "A")); + assertEquals(17, target.flush()); + assertEquals(0, target.getBlockCount()); + digest.update(input, 200, input.length - 200); + assertArrayEquals(referenceDigest(input), digest.digest()); + } + private void assertBuffersCleared(DigestEngine digest) { byte[] inputBuffer = digest.getBlockBuffer(); byte[] outputBuffer = (byte[]) ReflectionTestUtils.getField(digest, "tmpOut"); From 72da735b1ff0236feebc3805b4f4da3e50fb362a Mon Sep 17 00:00:00 2001 From: federico Date: Tue, 17 Nov 2026 00:26:33 +0800 Subject: [PATCH 05/33] fix(crypto): initialize digest length eagerly --- .../crypto/cryptohash/DigestEngine.java | 27 ++++----- .../common/crypto/cryptohash/KeccakTest.java | 59 +++++++++++++++++++ 2 files changed, 69 insertions(+), 17 deletions(-) diff --git a/crypto/src/main/java/org/tron/common/crypto/cryptohash/DigestEngine.java b/crypto/src/main/java/org/tron/common/crypto/cryptohash/DigestEngine.java index 66e143792fb..4444556e759 100644 --- a/crypto/src/main/java/org/tron/common/crypto/cryptohash/DigestEngine.java +++ b/crypto/src/main/java/org/tron/common/crypto/cryptohash/DigestEngine.java @@ -24,7 +24,8 @@ public abstract class DigestEngine extends MessageDigest implements Digest { - private int digestLen, blockLen, inputLen; + private final int digestLen; + private int blockLen, inputLen; private byte[] inputBuf; private long blockCount; @@ -67,23 +68,18 @@ protected void engineReset() { protected abstract void doPadding(byte[] buf, int off); /** - * This function is called at object creation time; the implementation should use it to perform - * initialization tasks. After this method is called, the implementation should be ready to - * process data or meaningfully honour calls such as {@link #engineGetDigestLength} + * Called by the DigestEngine constructor before subclass initializers and constructor bodies run. + * Initialize any state required by {@link #engineGetDigestLength()} and + * {@link #getInternalBlockLength()}. After this method returns, both methods must return correct, + * fixed lengths without relying on later subclass initialization. The input buffer is allocated + * only after this method returns. */ protected abstract void doInit(); - private void adjustDigestLen() { - if (digestLen == 0) { - digestLen = engineGetDigestLength(); - } - } - /** * @see Digest */ public byte[] digest() { - adjustDigestLen(); byte[] result = new byte[digestLen]; doPadding(result, 0); reset(); @@ -108,7 +104,6 @@ public int digest(byte[] buf, int offset, int len) throws DigestException { if (offset < 0 || len < 0 || offset > buf.length || len > buf.length - offset) { throw new IllegalArgumentException("Invalid output buffer range"); } - adjustDigestLen(); if (len < digestLen) { throw new DigestException("Partial digests are not returned"); } @@ -227,15 +222,15 @@ protected long getBlockCount() { /** * This function copies the internal buffering state to some other instance of a class extending * {@code DigestEngine}. It returns a reference to the copy. This method is intended to be called - * by the implementation of the {@link #copy} method. The destination must use the same algorithm - * and internal block length. + * by the implementation of the {@link #copy} method. The destination must use the same algorithm, + * digest length and internal block length. * * @param dest the copy * @return the value {@code dest} * @throws IllegalArgumentException if the destination is null or incompatible */ protected Digest copyState(DigestEngine dest) { - if (dest == null || blockLen != dest.blockLen + if (dest == null || digestLen != dest.digestLen || blockLen != dest.blockLen || !getAlgorithm().equals(dest.getAlgorithm())) { throw new IllegalArgumentException("Incompatible digest destination"); } @@ -243,8 +238,6 @@ protected Digest copyState(DigestEngine dest) { dest.blockCount = blockCount; System.arraycopy(inputBuf, 0, dest.inputBuf, 0, inputBuf.length); - adjustDigestLen(); - dest.adjustDigestLen(); return dest; } } diff --git a/framework/src/test/java/org/tron/common/crypto/cryptohash/KeccakTest.java b/framework/src/test/java/org/tron/common/crypto/cryptohash/KeccakTest.java index 6c44a890654..e5861113e3a 100644 --- a/framework/src/test/java/org/tron/common/crypto/cryptohash/KeccakTest.java +++ b/framework/src/test/java/org/tron/common/crypto/cryptohash/KeccakTest.java @@ -32,6 +32,22 @@ public static Collection parameters() { return Arrays.asList(new Object[][]{{256}, {512}}); } + @Test + public void testReadyAfterConstruction() throws Exception { + DigestEngine digest = (DigestEngine) newDigest(); + assertEquals(bits / 8, digest.getDigestLength()); + assertEquals(bits == 256 ? 136 : 72, digest.getBlockLength()); + assertEquals(digest.getBlockLength(), digest.getBlockBuffer().length); + Digest copy = digest.copy(); + assertEquals(digest.getDigestLength(), copy.getDigestLength()); + assertEquals(digest.getBlockLength(), copy.getBlockLength()); + assertArrayEquals(referenceDigest(new byte[0]), digest.digest()); + assertArrayEquals(referenceDigest(new byte[0]), copy.digest()); + byte[] input = inputBytes(); + assertArrayEquals(referenceDigest(input), digest.digest(input)); + assertArrayEquals(referenceDigest(input), copy.digest(input)); + } + @Test public void testByteArrayDigest() throws Exception { byte[] input = inputBytes(); @@ -421,6 +437,49 @@ protected int getInternalBlockLength() { assertArrayEquals(referenceDigest(input), digest.digest()); } + @Test + public void testCopyStateRejectsDifferentDigestLength() throws Exception { + DigestEngine digest = (DigestEngine) newDigest(); + DigestEngine target = bits == 256 ? new Keccak256() { + @Override + public int engineGetDigestLength() { + return 40; + } + + @Override + protected int getInternalBlockLength() { + return 136; + } + } : new Keccak512() { + @Override + public int engineGetDigestLength() { + return 72; + } + + @Override + protected int getInternalBlockLength() { + return 72; + } + }; + assertEquals(digest.getAlgorithm(), target.getAlgorithm()); + assertEquals(digest.getBlockBuffer().length, target.getBlockBuffer().length); + byte[] input = inputBytes(); + digest.update(input, 0, 200); + target.update(input, 0, 17); + byte[] targetBuffer = target.getBlockBuffer().clone(); + long[] targetState = ((long[]) ReflectionTestUtils.getField(target, "A")).clone(); + + assertThrows(IllegalArgumentException.class, () -> digest.copyState(target)); + + assertArrayEquals(targetBuffer, target.getBlockBuffer()); + assertArrayEquals(targetState, (long[]) ReflectionTestUtils.getField(target, "A")); + assertEquals(bits / 8 + 8, target.getDigestLength()); + assertEquals(17, target.flush()); + assertEquals(0, target.getBlockCount()); + digest.update(input, 200, input.length - 200); + assertArrayEquals(referenceDigest(input), digest.digest()); + } + private void assertBuffersCleared(DigestEngine digest) { byte[] inputBuffer = digest.getBlockBuffer(); byte[] outputBuffer = (byte[]) ReflectionTestUtils.getField(digest, "tmpOut"); From 4663faea7fcc961735300d2ca83074800f620ad7 Mon Sep 17 00:00:00 2001 From: federico Date: Tue, 17 Nov 2026 11:12:31 +0800 Subject: [PATCH 06/33] fix(keystore): reject corrupted password input --- .../java/org/tron/keystore/WalletUtils.java | 87 +++++++++++++++++- .../WalletUtilsInputPasswordTest.java | 88 ++++++++++++++++++- .../org/tron/plugins/KeystoreCliUtils.java | 21 ++--- .../org/tron/plugins/KeystoreUpdate.java | 38 ++++---- .../tron/plugins/KeystoreCliUtilsTest.java | 21 +++++ .../org/tron/plugins/KeystoreNewTest.java | 17 ++++ .../org/tron/plugins/KeystoreUpdateTest.java | 23 +++++ 7 files changed, 260 insertions(+), 35 deletions(-) diff --git a/crypto/src/main/java/org/tron/keystore/WalletUtils.java b/crypto/src/main/java/org/tron/keystore/WalletUtils.java index 7c15ab8207b..e5015c4f96b 100644 --- a/crypto/src/main/java/org/tron/keystore/WalletUtils.java +++ b/crypto/src/main/java/org/tron/keystore/WalletUtils.java @@ -6,6 +6,11 @@ import java.io.Console; import java.io.File; import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.file.AtomicMoveNotSupportedException; import java.nio.file.Files; import java.nio.file.LinkOption; @@ -17,6 +22,7 @@ import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; +import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.NoSuchElementException; @@ -220,18 +226,77 @@ static synchronized void resetSharedStdinScanner() { private static synchronized Scanner getSharedStdinScanner() { if (sharedStdinScanner == null) { - sharedStdinScanner = new Scanner(System.in); + // CharsetDecoder defaults to REPORT: never replace malformed password bytes. + sharedStdinScanner = new Scanner(new InputStreamReader(System.in, + StandardCharsets.UTF_8.newDecoder())); } return sharedStdinScanner; } + /** + * Decode a UTF-8 password file without silently replacing malformed bytes. + */ + public static String decodePassword(byte[] bytes) throws IOException { + try { + return StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString(); + } catch (CharacterCodingException e) { + throw new IOException("Password input must be valid UTF-8", e); + } + } + + /** + * Read with echo disabled, rejecting potentially corrupted console input. + * The caller must clear the returned array; EOF is returned as {@code null}. + */ + public static char[] readConsolePassword(Console console, String prompt) throws IOException { + char[] password = console.readPassword("%s", prompt); + if (password == null) { + return null; + } + try { + validateConsolePassword(password, consoleCharset(console)); + return password; + } catch (IOException e) { + Arrays.fill(password, '\0'); + throw e; + } + } + + private static Charset consoleCharset(Console console) throws IOException { + try { + // Console.charset() was added in JDK 17; keep the JDK 8 build compatible. + return (Charset) Console.class.getMethod("charset").invoke(console); + } catch (NoSuchMethodException e) { + // On supported JDK 8 Linux/macOS runtimes Console uses the default charset. + String os = System.getProperty("os.name"); + return "Linux".equals(os) || "Mac OS X".equals(os) ? Charset.defaultCharset() : null; + } catch (ReflectiveOperationException | SecurityException e) { + throw new IOException("Cannot determine console encoding; use UTF-8 password input", e); + } + } + + static void validateConsolePassword(char[] password, Charset charset) throws IOException { + for (char c : password) { + // Console decoders replace malformed bytes; the original input cannot be recovered. + if (c == '\uFFFD' || (c > 0x7f && !StandardCharsets.UTF_8.equals(charset))) { + throw new IOException("Password may be corrupted by the console encoding; " + + "use a UTF-8 terminal or UTF-8 password file/stdin"); + } + } + } + public static String inputPassword() { String password; Console cons = System.console(); Scanner in = cons == null ? getSharedStdinScanner() : null; while (true) { if (cons != null) { - char[] pwd = cons.readPassword("password: "); + char[] pwd; + try { + pwd = readConsolePassword(cons, "password: "); + } catch (IOException e) { + throw new TronError(e.getMessage(), e, TronError.ErrCode.WITNESS_KEYSTORE_LOAD); + } // Console EOF (e.g. Ctrl+D) returns null; fail fast instead of // crashing with a raw NullPointerException. if (pwd == null) { @@ -240,7 +305,11 @@ public static String inputPassword() { + "restart with --password or provide an interactive TTY", TronError.ErrCode.WITNESS_KEYSTORE_LOAD); } - password = String.valueOf(pwd); + try { + password = String.valueOf(pwd); + } finally { + Arrays.fill(pwd, '\0'); + } } else { // Preserve the full password including embedded whitespace. // The previous implementation applied trim() + split("\\s+")[0] @@ -252,6 +321,9 @@ public static String inputPassword() { try { line = in.nextLine(); } catch (NoSuchElementException e) { + if (in.ioException() != null) { + throw passwordInputError(in.ioException()); + } // Piped stdin reached EOF before a password line was available; // fail fast instead of leaking a raw NoSuchElementException. throw new TronError( @@ -259,6 +331,10 @@ public static String inputPassword() { + "line; restart with --password or provide an interactive TTY", e, TronError.ErrCode.WITNESS_KEYSTORE_LOAD); } + // Scanner treats reader failures as EOF and can return a partial line. + if (in.ioException() != null) { + throw passwordInputError(in.ioException()); + } password = stripPasswordLine(line); } if (passwordValid(password)) { @@ -268,4 +344,9 @@ public static String inputPassword() { } } + private static TronError passwordInputError(IOException cause) { + return new TronError("Cannot read password input; stdin must contain valid UTF-8", cause, + TronError.ErrCode.WITNESS_KEYSTORE_LOAD); + } + } diff --git a/framework/src/test/java/org/tron/keystore/WalletUtilsInputPasswordTest.java b/framework/src/test/java/org/tron/keystore/WalletUtilsInputPasswordTest.java index bca7f8a2caf..7b1d82b1bdb 100644 --- a/framework/src/test/java/org/tron/keystore/WalletUtilsInputPasswordTest.java +++ b/framework/src/test/java/org/tron/keystore/WalletUtilsInputPasswordTest.java @@ -1,12 +1,19 @@ package org.tron.keystore; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import java.io.ByteArrayInputStream; +import java.io.Console; +import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; +import java.util.Arrays; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -97,15 +104,88 @@ public void testInputPasswordPreservesLeadingAndTrailingSpaces() { " with spaces ", pw); } - // ---------- EOF fail-fast tests ---------- + // ---------- encoding validation ---------- + + @Test(timeout = 5000) + public void testInputPasswordPreservesUtf8AcrossReads() { + String password = "密码测试 é🔑"; + System.setIn(new ByteArrayInputStream( + (password + "\n" + password + "\n").getBytes(StandardCharsets.UTF_8))); + + assertEquals(password, WalletUtils.inputPassword()); + assertEquals(password, WalletUtils.inputPassword()); + } + + @Test(timeout = 5000) + public void testInputPasswordRejectsMalformedUtf8() { + System.setIn(new ByteArrayInputStream(new byte[]{(byte) 0xc3, 0x28, '\n'})); + + TronError error = assertThrows(TronError.class, WalletUtils::inputPassword); + assertTrue(error.getMessage().contains("UTF-8")); + assertEquals(TronError.ErrCode.WITNESS_KEYSTORE_LOAD, error.getErrCode()); + } + + @Test(timeout = 5000) + public void testInputPasswordRejectsPartialLineOnDecoderFailure() { + // Scanner can buffer a valid prefix before treating a decoder error as EOF. + byte[] bytes = new byte[9001]; + Arrays.fill(bytes, (byte) 'a'); + bytes[bytes.length - 1] = (byte) 0xc3; + System.setIn(new ByteArrayInputStream(bytes)); + + TronError error = assertThrows(TronError.class, WalletUtils::inputPassword); + assertTrue(error.getMessage().contains("UTF-8")); + } + + @Test + public void testConsolePasswordEncodingValidation() throws Exception { + char[] unicode = "密码测试 é🔑".toCharArray(); + WalletUtils.validateConsolePassword(unicode, StandardCharsets.UTF_8); + WalletUtils.validateConsolePassword("ascii password".toCharArray(), + StandardCharsets.US_ASCII); + WalletUtils.validateConsolePassword("ascii password".toCharArray(), null); + + assertThrows(IOException.class, + () -> WalletUtils.validateConsolePassword(unicode, StandardCharsets.US_ASCII)); + assertThrows(IOException.class, + () -> WalletUtils.validateConsolePassword(unicode, StandardCharsets.ISO_8859_1)); + assertThrows(IOException.class, + () -> WalletUtils.validateConsolePassword(unicode, null)); + // Even a UTF-8 console may have already replaced malformed input bytes. + char[] replaced = "pass\uFFFDword".toCharArray(); // U+FFFD: decoder replacement. + assertThrows(IOException.class, + () -> WalletUtils.validateConsolePassword(replaced, StandardCharsets.UTF_8)); + } + + @Test + public void testDecodePasswordRejectsMalformedUtf8() { + assertThrows(IOException.class, () -> WalletUtils.decodePassword( + new byte[]{'p', 'a', 's', 's', (byte) 0xc3})); + } + + @Test + public void testConsoleReadRejectsAndClearsCorruptedPassword() { + Console console = mock(Console.class); + char[] password = "secret\uFFFD".toCharArray(); // U+FFFD: decoder replacement. + when(console.readPassword("%s", "password: ")).thenReturn(password); + + IOException error = assertThrows(IOException.class, + () -> WalletUtils.readConsolePassword(console, "password: ")); + assertTrue(error.getMessage().contains("UTF-8")); + assertArrayEquals(new char[password.length], password); + } + + @Test + public void testConsoleReadPreservesEof() throws Exception { + Console console = mock(Console.class); + assertNull(WalletUtils.readConsolePassword(console, "password: ")); + } @Test(timeout = 5000) public void testInputPasswordPipedStdinEofThrowsTronError() { // Non-TTY branch: Scanner.nextLine() throws NoSuchElementException at // EOF; it must be translated into a fail-fast TronError. - // (The TTY branch's Console.readPassword() null-on-EOF check cannot be - // exercised under JUnit, where System.console() is always null and - // java.io.Console is final — covered by code review only.) + // Console EOF is covered separately using a mocked Console. System.setIn(new ByteArrayInputStream(new byte[0])); TronError err = assertThrows(TronError.class, WalletUtils::inputPassword); diff --git a/plugins/src/main/java/common/org/tron/plugins/KeystoreCliUtils.java b/plugins/src/main/java/common/org/tron/plugins/KeystoreCliUtils.java index 9d7f3c5a92e..c91bb86ad8c 100644 --- a/plugins/src/main/java/common/org/tron/plugins/KeystoreCliUtils.java +++ b/plugins/src/main/java/common/org/tron/plugins/KeystoreCliUtils.java @@ -7,7 +7,6 @@ import java.io.PrintWriter; import java.nio.ByteBuffer; import java.nio.channels.SeekableByteChannel; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.NoSuchFileException; @@ -127,7 +126,7 @@ static String readPassword(File passwordFile, PrintWriter err) throws IOExceptio } try { String password = WalletUtils.stripPasswordLine( - new String(bytes, StandardCharsets.UTF_8)); + WalletUtils.decodePassword(bytes)); // Reject multi-line password files. stripPasswordLine only trims // trailing terminators; any remaining \n/\r means the file had // interior line breaks. A common mistake is passing a two-line @@ -158,18 +157,18 @@ static String readPassword(File passwordFile, PrintWriter err) throws IOExceptio return null; } - char[] pwd1 = console.readPassword("Enter password: "); + char[] pwd1 = WalletUtils.readConsolePassword(console, "Enter password: "); if (pwd1 == null) { err.println("Password input cancelled."); return null; } - char[] pwd2 = console.readPassword("Confirm password: "); - if (pwd2 == null) { - Arrays.fill(pwd1, '\0'); - err.println("Password input cancelled."); - return null; - } + char[] pwd2 = null; try { + pwd2 = WalletUtils.readConsolePassword(console, "Confirm password: "); + if (pwd2 == null) { + err.println("Password input cancelled."); + return null; + } if (!Arrays.equals(pwd1, pwd2)) { err.println("Passwords do not match."); return null; @@ -182,7 +181,9 @@ static String readPassword(File passwordFile, PrintWriter err) throws IOExceptio return password; } finally { Arrays.fill(pwd1, '\0'); - Arrays.fill(pwd2, '\0'); + if (pwd2 != null) { + Arrays.fill(pwd2, '\0'); + } } } diff --git a/plugins/src/main/java/common/org/tron/plugins/KeystoreUpdate.java b/plugins/src/main/java/common/org/tron/plugins/KeystoreUpdate.java index 06e98462d68..8eeab7c1ac8 100644 --- a/plugins/src/main/java/common/org/tron/plugins/KeystoreUpdate.java +++ b/plugins/src/main/java/common/org/tron/plugins/KeystoreUpdate.java @@ -4,7 +4,6 @@ import java.io.Console; import java.io.File; import java.io.PrintWriter; -import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.concurrent.Callable; import org.tron.common.crypto.SignInterface; @@ -69,7 +68,7 @@ public Integer call() { return 1; } try { - String content = new String(bytes, StandardCharsets.UTF_8); + String content = WalletUtils.decodePassword(bytes); // Strip UTF-8 BOM if present (Windows Notepad) if (content.length() > 0 && content.charAt(0) == '\uFEFF') { content = content.substring(1); @@ -99,25 +98,24 @@ public Integer call() { + "Use --password-file to provide passwords."); return 1; } - char[] oldPwd = console.readPassword("Enter current password: "); + char[] oldPwd = WalletUtils.readConsolePassword(console, "Enter current password: "); if (oldPwd == null) { err.println(INPUT_CANCELLED); return 1; } - char[] newPwd = console.readPassword("Enter new password: "); - if (newPwd == null) { - Arrays.fill(oldPwd, '\0'); - err.println(INPUT_CANCELLED); - return 1; - } - char[] confirmPwd = console.readPassword("Confirm new password: "); - if (confirmPwd == null) { - Arrays.fill(oldPwd, '\0'); - Arrays.fill(newPwd, '\0'); - err.println(INPUT_CANCELLED); - return 1; - } + char[] newPwd = null; + char[] confirmPwd = null; try { + newPwd = WalletUtils.readConsolePassword(console, "Enter new password: "); + if (newPwd == null) { + err.println(INPUT_CANCELLED); + return 1; + } + confirmPwd = WalletUtils.readConsolePassword(console, "Confirm new password: "); + if (confirmPwd == null) { + err.println(INPUT_CANCELLED); + return 1; + } oldPassword = new String(oldPwd); newPassword = new String(newPwd); String confirmPassword = new String(confirmPwd); @@ -127,8 +125,12 @@ public Integer call() { } } finally { Arrays.fill(oldPwd, '\0'); - Arrays.fill(newPwd, '\0'); - Arrays.fill(confirmPwd, '\0'); + if (newPwd != null) { + Arrays.fill(newPwd, '\0'); + } + if (confirmPwd != null) { + Arrays.fill(confirmPwd, '\0'); + } } } diff --git a/plugins/src/test/java/org/tron/plugins/KeystoreCliUtilsTest.java b/plugins/src/test/java/org/tron/plugins/KeystoreCliUtilsTest.java index 6507ec28f86..5c273dcb1b6 100644 --- a/plugins/src/test/java/org/tron/plugins/KeystoreCliUtilsTest.java +++ b/plugins/src/test/java/org/tron/plugins/KeystoreCliUtilsTest.java @@ -4,6 +4,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import java.io.File; @@ -172,6 +173,26 @@ public void testReadPasswordFromFile() throws Exception { assertEquals("goodpassword", pw); } + @Test + public void testReadPasswordFilePreservesUnicode() throws Exception { + File pwFile = tempFolder.newFile("pw-unicode.txt"); + String password = "密码测试 é🔑"; + Files.write(pwFile.toPath(), (password + "\n").getBytes(StandardCharsets.UTF_8)); + makeOwnerOnly(pwFile); + assertEquals(password, KeystoreCliUtils.readPassword(pwFile, + new PrintWriter(new StringWriter()))); + } + + @Test + public void testReadPasswordFileRejectsMalformedUtf8() throws Exception { + File pwFile = tempFolder.newFile("pw-malformed.txt"); + Files.write(pwFile.toPath(), new byte[]{'s', 'e', 'c', 'r', 'e', 't', (byte) 0xff}); + makeOwnerOnly(pwFile); + IOException error = assertThrows(IOException.class, + () -> KeystoreCliUtils.readPassword(pwFile, new PrintWriter(new StringWriter()))); + assertTrue(error.getMessage().contains("UTF-8")); + } + @Test public void testReadPasswordFromFileWithLineEndings() throws Exception { File pwFile = tempFolder.newFile("pw-crlf.txt"); diff --git a/plugins/src/test/java/org/tron/plugins/KeystoreNewTest.java b/plugins/src/test/java/org/tron/plugins/KeystoreNewTest.java index 3d71b667ba4..24aaedbd774 100644 --- a/plugins/src/test/java/org/tron/plugins/KeystoreNewTest.java +++ b/plugins/src/test/java/org/tron/plugins/KeystoreNewTest.java @@ -206,6 +206,23 @@ public void testNewKeystoreDirIsFile() throws Exception { assertEquals("Should fail when dir is a file", 1, exitCode); } + @Test + public void testMalformedPasswordDoesNotCreateKeystore() throws Exception { + File dir = tempFolder.newFolder("keystore-malformed"); + File pwFile = tempFolder.newFile("malformed-password.txt"); + Files.write(pwFile.toPath(), new byte[]{'s', 'e', 'c', 'r', 'e', 't', (byte) 0xff}); + makeOwnerOnly(pwFile); + StringWriter err = new StringWriter(); + CommandLine cmd = new CommandLine(new Toolkit()); + cmd.setErr(new PrintWriter(err)); + + assertEquals(1, cmd.execute("keystore", "new", + "--keystore-dir", dir.getAbsolutePath(), + "--password-file", pwFile.getAbsolutePath())); + assertTrue(err.toString().contains("UTF-8")); + assertEquals(0, dir.listFiles().length); + } + @Test public void testNewKeystorePasswordFileTooLarge() throws Exception { File dir = tempFolder.newFolder("keystore-bigpw"); diff --git a/plugins/src/test/java/org/tron/plugins/KeystoreUpdateTest.java b/plugins/src/test/java/org/tron/plugins/KeystoreUpdateTest.java index c750ec8575e..8c3f6739de9 100644 --- a/plugins/src/test/java/org/tron/plugins/KeystoreUpdateTest.java +++ b/plugins/src/test/java/org/tron/plugins/KeystoreUpdateTest.java @@ -31,6 +31,29 @@ public class KeystoreUpdateTest { private static final ObjectMapper MAPPER = new ObjectMapper(); + @Test + public void testMalformedNewPasswordDoesNotOverwriteKeystore() throws Exception { + File dir = tempFolder.newFolder("keystore-malformed"); + SignInterface key = SignUtils.getGeneratedRandomSign(SecureRandom.getInstance("NativePRNG")); + File keystore = new File(dir, WalletUtils.generateWalletFile("oldpass123", key, dir, false)); + byte[] original = Files.readAllBytes(keystore.toPath()); + String address = MAPPER.readValue(original, WalletFile.class).getAddress(); + File pwFile = tempFolder.newFile("malformed-passwords.txt"); + byte[] passwords = "oldpass123\nnewpass456X".getBytes(StandardCharsets.UTF_8); + passwords[passwords.length - 1] = (byte) 0xff; + Files.write(pwFile.toPath(), passwords); + makeOwnerOnly(pwFile); + StringWriter err = new StringWriter(); + CommandLine cmd = new CommandLine(new Toolkit()); + cmd.setErr(new PrintWriter(err)); + + assertEquals(1, cmd.execute("keystore", "update", address, + "--keystore-dir", dir.getAbsolutePath(), + "--password-file", pwFile.getAbsolutePath())); + assertTrue(err.toString().contains("UTF-8")); + assertArrayEquals(original, Files.readAllBytes(keystore.toPath())); + } + @Test public void testUpdatePassword() throws Exception { File dir = tempFolder.newFolder("keystore"); From 26b69081312fbb7b1d68d938ac1a9fce09554212 Mon Sep 17 00:00:00 2001 From: federico Date: Tue, 17 Nov 2026 11:22:03 +0800 Subject: [PATCH 07/33] fix(keystore): make wallet filename helper private --- crypto/src/main/java/org/tron/keystore/WalletUtils.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crypto/src/main/java/org/tron/keystore/WalletUtils.java b/crypto/src/main/java/org/tron/keystore/WalletUtils.java index e5015c4f96b..8ef7e41a513 100644 --- a/crypto/src/main/java/org/tron/keystore/WalletUtils.java +++ b/crypto/src/main/java/org/tron/keystore/WalletUtils.java @@ -159,7 +159,7 @@ private static void warnIfSymbolicLink(File source) { } } - public static String getWalletFileName(WalletFile walletFile) { + private static String getWalletFileName(WalletFile walletFile) { DateTimeFormatter format = DateTimeFormatter.ofPattern( "'UTC--'yyyy-MM-dd'T'HH-mm-ss.nVV'--'"); ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); From bda8eb6a176369b8e3dfd13821408e59eaa8d9ac Mon Sep 17 00:00:00 2001 From: federico Date: Tue, 17 Nov 2026 11:47:28 +0800 Subject: [PATCH 08/33] fix(keystore): sync wallet files and directories --- .../java/org/tron/keystore/WalletUtils.java | 26 ++++- .../tron/keystore/WalletUtilsWriteTest.java | 97 +++++++++++++++++++ 2 files changed, 122 insertions(+), 1 deletion(-) diff --git a/crypto/src/main/java/org/tron/keystore/WalletUtils.java b/crypto/src/main/java/org/tron/keystore/WalletUtils.java index 8ef7e41a513..d1515050adc 100644 --- a/crypto/src/main/java/org/tron/keystore/WalletUtils.java +++ b/crypto/src/main/java/org/tron/keystore/WalletUtils.java @@ -1,13 +1,16 @@ package org.tron.keystore; +import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.Console; import java.io.File; +import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; @@ -16,6 +19,7 @@ import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; @@ -72,6 +76,10 @@ public static String generateWalletFile( /** * Write a WalletFile to the given destination path with owner-only (0600) * permissions, using a temp file + atomic rename. + * The temporary file is synced before replacement, then the destination directory + * and its ancestors are synced to persist newly created directory entries too. + * Directory syncing requires filesystem support. A sync failure after replacement + * is reported to the caller, but does not roll back the replacement. * *

On POSIX filesystems, the temp file is created atomically with 0600 * permissions via {@link Files#createTempFile(Path, String, String, @@ -109,7 +117,12 @@ public static void writeWalletFile(WalletFile walletFile, File destination) } try { - objectMapper.writeValue(tmp.toFile(), walletFile); + try (FileOutputStream output = new FileOutputStream(tmp.toFile())) { + // Keep the stream open until all serialized bytes have been synced. + objectMapper.writer().without(JsonGenerator.Feature.AUTO_CLOSE_TARGET) + .writeValue(output, walletFile); + output.getChannel().force(true); + } try { Files.move(tmp, destination.toPath(), StandardCopyOption.REPLACE_EXISTING, @@ -117,6 +130,17 @@ public static void writeWalletFile(WalletFile walletFile, File destination) } catch (AtomicMoveNotSupportedException e) { Files.move(tmp, destination.toPath(), StandardCopyOption.REPLACE_EXISTING); } + try { + // Callers may have just created the directory, so sync the whole ancestor chain. + // Resolve symlinks to sync the actual directory hierarchy containing the file. + for (Path current = dir.toRealPath(); current != null; current = current.getParent()) { + try (FileChannel directory = FileChannel.open(current, StandardOpenOption.READ)) { + directory.force(true); + } + } + } catch (IOException e) { + throw new IOException("Keystore was replaced, but directory sync failed: " + dir, e); + } } catch (Exception e) { try { Files.deleteIfExists(tmp); diff --git a/framework/src/test/java/org/tron/keystore/WalletUtilsWriteTest.java b/framework/src/test/java/org/tron/keystore/WalletUtilsWriteTest.java index 28463a8000a..ff7a1c82c02 100644 --- a/framework/src/test/java/org/tron/keystore/WalletUtilsWriteTest.java +++ b/framework/src/test/java/org/tron/keystore/WalletUtilsWriteTest.java @@ -1,22 +1,37 @@ package org.tron.keystore; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import java.io.File; +import java.io.FileOutputStream; import java.io.IOException; +import java.nio.channels.FileChannel; import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; import java.nio.file.attribute.PosixFilePermission; import java.util.EnumSet; import java.util.Locale; import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; import org.junit.Assume; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; import org.tron.common.crypto.SignInterface; import org.tron.common.crypto.SignUtils; import org.tron.common.utils.Utils; @@ -168,6 +183,88 @@ public void testWriteWalletFileCleansUpTempOnFailure() throws Exception { assertEquals("Temp file must be cleaned up on failure", 0, tempFiles.length); } + @Test + public void testFileSyncFailurePreservesExistingKeystore() throws Exception { + File dir = tempFolder.newFolder("file-sync-fail"); + File destination = new File(dir, "wallet.json"); + WalletFile original = lightWalletFile("password123"); + WalletUtils.writeWalletFile(original, destination); + byte[] before = Files.readAllBytes(destination.toPath()); + WalletFile replacement = lightWalletFile("newpassword"); + FileChannel channel = mock(FileChannel.class); + doThrow(new IOException("file sync failed")).when(channel).force(true); + AtomicReference walletOutput = new AtomicReference<>(); + + try (MockedConstruction outputs = mockConstruction(FileOutputStream.class, + (output, context) -> { + Object target = context.arguments().get(0); + if (target instanceof File && ((File) target).getName().startsWith("keystore-")) { + walletOutput.set(output); + when(output.getChannel()).thenReturn(channel); + } + })) { + IOException error = assertThrows(IOException.class, + () -> WalletUtils.writeWalletFile(replacement, destination)); + assertEquals("file sync failed", error.getMessage()); + assertNotNull(walletOutput.get()); + verify(walletOutput.get()).close(); + } + assertArrayEquals(before, Files.readAllBytes(destination.toPath())); + assertEquals("Only the original wallet should remain", 1, dir.list().length); + } + + @Test + public void testDirectorySyncFailureReportsCompletedReplacement() throws Exception { + File dir = tempFolder.newFolder("directory-sync-fail"); + File destination = new File(dir, "wallet.json"); + WalletUtils.writeWalletFile(lightWalletFile("oldpassword"), destination); + WalletFile replacement = lightWalletFile("newpassword"); + Path realDir = dir.toPath().toRealPath(); + FileChannel channel = mock(FileChannel.class); + doThrow(new IOException("directory sync failed")).when(channel).force(true); + + try (MockedStatic channels = mockStatic(FileChannel.class)) { + channels.when(() -> FileChannel.open(realDir, StandardOpenOption.READ)) + .thenReturn(channel); + IOException error = assertThrows(IOException.class, + () -> WalletUtils.writeWalletFile(replacement, destination)); + assertTrue(error.getMessage().contains("Keystore was replaced")); + assertEquals("directory sync failed", error.getCause().getMessage()); + } + verify(channel).close(); + assertEquals(replacement.getAddress(), + WalletUtils.loadCredentials("newpassword", destination).getAddress()); + assertEquals("No temporary file should remain", 1, dir.list().length); + } + + @Test + public void testAncestorSyncFailureIsNotIgnored() throws Exception { + File base = tempFolder.newFolder("ancestor-sync-fail"); + File destination = new File(base, "a/b/c/wallet.json"); + // Match CLI callers which create directories before calling writeWalletFile. + Files.createDirectories(destination.toPath().getParent()); + WalletFile wallet = lightWalletFile("password123"); + FileChannel directory = mock(FileChannel.class); + FileChannel ancestor = mock(FileChannel.class); + doThrow(new IOException("ancestor sync failed")).when(ancestor).force(true); + Path realDir = destination.toPath().getParent().toRealPath(); + + try (MockedStatic channels = mockStatic(FileChannel.class)) { + channels.when(() -> FileChannel.open(realDir, StandardOpenOption.READ)) + .thenReturn(directory); + channels.when(() -> FileChannel.open(realDir.getParent(), StandardOpenOption.READ)) + .thenReturn(ancestor); + IOException error = assertThrows(IOException.class, + () -> WalletUtils.writeWalletFile(wallet, destination)); + assertEquals("ancestor sync failed", error.getCause().getMessage()); + } + verify(directory).force(true); + verify(directory).close(); + verify(ancestor).close(); + assertEquals(wallet.getAddress(), + WalletUtils.loadCredentials("password123", destination).getAddress()); + } + // ---------- loadCredentials symlink behavior ---------- @Test From 05d14652133f227559ebfb962112c66ac84851c6 Mon Sep 17 00:00:00 2001 From: federico Date: Tue, 17 Nov 2026 12:06:01 +0800 Subject: [PATCH 09/33] fix(keystore): avoid reopening temporary files --- .../java/org/tron/keystore/WalletUtils.java | 47 +++--- .../tron/keystore/WalletUtilsWriteTest.java | 137 +++++++++++++++--- 2 files changed, 131 insertions(+), 53 deletions(-) diff --git a/crypto/src/main/java/org/tron/keystore/WalletUtils.java b/crypto/src/main/java/org/tron/keystore/WalletUtils.java index d1515050adc..a334503302e 100644 --- a/crypto/src/main/java/org/tron/keystore/WalletUtils.java +++ b/crypto/src/main/java/org/tron/keystore/WalletUtils.java @@ -6,10 +6,10 @@ import com.fasterxml.jackson.databind.ObjectMapper; import java.io.Console; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.ByteBuffer; +import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; @@ -32,6 +32,7 @@ import java.util.NoSuchElementException; import java.util.Scanner; import java.util.Set; +import java.util.UUID; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.tron.common.crypto.SignInterface; @@ -81,18 +82,14 @@ public static String generateWalletFile( * Directory syncing requires filesystem support. A sync failure after replacement * is reported to the caller, but does not roll back the replacement. * - *

On POSIX filesystems, the temp file is created atomically with 0600 - * permissions via {@link Files#createTempFile(Path, String, String, - * java.nio.file.attribute.FileAttribute[])}, avoiding any window where the - * file is world-readable. + *

The temporary file is atomically created with 0600 permissions and written + * through the same channel, without reopening its path. Filesystems that cannot + * atomically set these permissions are not supported. * - *

On non-POSIX filesystems (e.g. Windows) the fallback uses - * {@link File#setReadable(boolean, boolean)} / - * {@link File#setWritable(boolean, boolean)} which is best-effort — these - * methods manipulate only DOS-style attributes on Windows and may not update - * file ACLs. The sensitive keystore JSON is written only after the narrowing - * calls, so no confidential data is exposed during the window, but callers - * on Windows should not infer strict owner-only ACL enforcement from this. + *

The destination must be in a trusted directory hierarchy. Keeping the channel + * open prevents a replaced temporary path from redirecting the wallet bytes, but + * users able to modify directory entries can still replace or remove the file + * before or after the move. * * @param walletFile the keystore to serialize * @param destination the final target file (existing file will be replaced) @@ -102,26 +99,18 @@ public static void writeWalletFile(WalletFile walletFile, File destination) Path dir = destination.getAbsoluteFile().getParentFile().toPath(); Files.createDirectories(dir); - Path tmp; - try { - tmp = Files.createTempFile(dir, "keystore-", ".tmp", - PosixFilePermissions.asFileAttribute(OWNER_ONLY)); - } catch (UnsupportedOperationException e) { - // Windows / non-POSIX fallback — best-effort narrowing only (see JavaDoc) - tmp = Files.createTempFile(dir, "keystore-", ".tmp"); - File tf = tmp.toFile(); - tf.setReadable(false, false); - tf.setReadable(true, true); - tf.setWritable(false, false); - tf.setWritable(true, true); - } + Path tmp = dir.resolve("keystore-" + UUID.randomUUID() + ".tmp"); + // Open before entering cleanup: a CREATE_NEW collision must not delete an existing file. + FileChannel channel = FileChannel.open(tmp, + EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE), + PosixFilePermissions.asFileAttribute(OWNER_ONLY)); try { - try (FileOutputStream output = new FileOutputStream(tmp.toFile())) { - // Keep the stream open until all serialized bytes have been synced. + try (FileChannel output = channel) { + // Keep the creating channel open until all serialized bytes have been synced. objectMapper.writer().without(JsonGenerator.Feature.AUTO_CLOSE_TARGET) - .writeValue(output, walletFile); - output.getChannel().force(true); + .writeValue(Channels.newOutputStream(output), walletFile); + output.force(true); } try { Files.move(tmp, destination.toPath(), diff --git a/framework/src/test/java/org/tron/keystore/WalletUtilsWriteTest.java b/framework/src/test/java/org/tron/keystore/WalletUtilsWriteTest.java index ff7a1c82c02..b1997fab7b4 100644 --- a/framework/src/test/java/org/tron/keystore/WalletUtilsWriteTest.java +++ b/framework/src/test/java/org/tron/keystore/WalletUtilsWriteTest.java @@ -9,15 +9,14 @@ import static org.junit.Assert.fail; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; +import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; @@ -30,7 +29,6 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; -import org.mockito.MockedConstruction; import org.mockito.MockedStatic; import org.tron.common.crypto.SignInterface; import org.tron.common.crypto.SignUtils; @@ -191,18 +189,18 @@ public void testFileSyncFailurePreservesExistingKeystore() throws Exception { WalletUtils.writeWalletFile(original, destination); byte[] before = Files.readAllBytes(destination.toPath()); WalletFile replacement = lightWalletFile("newpassword"); - FileChannel channel = mock(FileChannel.class); - doThrow(new IOException("file sync failed")).when(channel).force(true); - AtomicReference walletOutput = new AtomicReference<>(); - - try (MockedConstruction outputs = mockConstruction(FileOutputStream.class, - (output, context) -> { - Object target = context.arguments().get(0); - if (target instanceof File && ((File) target).getName().startsWith("keystore-")) { - walletOutput.set(output); - when(output.getChannel()).thenReturn(channel); - } - })) { + AtomicReference walletOutput = new AtomicReference<>(); + + try (MockedStatic channels = mockStatic(FileChannel.class, invocation -> { + FileChannel output = (FileChannel) invocation.callRealMethod(); + if (invocation.getArguments().length == 3 + && ((Set) invocation.getArgument(1)).contains(StandardOpenOption.CREATE_NEW)) { + output = spy(output); + doThrow(new IOException("file sync failed")).when(output).force(true); + walletOutput.set(output); + } + return output; + })) { IOException error = assertThrows(IOException.class, () -> WalletUtils.writeWalletFile(replacement, destination)); assertEquals("file sync failed", error.getMessage()); @@ -223,9 +221,8 @@ public void testDirectorySyncFailureReportsCompletedReplacement() throws Excepti FileChannel channel = mock(FileChannel.class); doThrow(new IOException("directory sync failed")).when(channel).force(true); - try (MockedStatic channels = mockStatic(FileChannel.class)) { - channels.when(() -> FileChannel.open(realDir, StandardOpenOption.READ)) - .thenReturn(channel); + try (MockedStatic channels = mockStatic(FileChannel.class, invocation -> + realDir.equals(invocation.getArgument(0)) ? channel : invocation.callRealMethod())) { IOException error = assertThrows(IOException.class, () -> WalletUtils.writeWalletFile(replacement, destination)); assertTrue(error.getMessage().contains("Keystore was replaced")); @@ -249,11 +246,16 @@ public void testAncestorSyncFailureIsNotIgnored() throws Exception { doThrow(new IOException("ancestor sync failed")).when(ancestor).force(true); Path realDir = destination.toPath().getParent().toRealPath(); - try (MockedStatic channels = mockStatic(FileChannel.class)) { - channels.when(() -> FileChannel.open(realDir, StandardOpenOption.READ)) - .thenReturn(directory); - channels.when(() -> FileChannel.open(realDir.getParent(), StandardOpenOption.READ)) - .thenReturn(ancestor); + try (MockedStatic channels = mockStatic(FileChannel.class, invocation -> { + Path path = invocation.getArgument(0); + if (realDir.equals(path)) { + return directory; + } + if (realDir.getParent().equals(path)) { + return ancestor; + } + return invocation.callRealMethod(); + })) { IOException error = assertThrows(IOException.class, () -> WalletUtils.writeWalletFile(wallet, destination)); assertEquals("ancestor sync failed", error.getCause().getMessage()); @@ -265,6 +267,93 @@ public void testAncestorSyncFailureIsNotIgnored() throws Exception { WalletUtils.loadCredentials("password123", destination).getAddress()); } + @Test + public void testReplacedTemporaryFileDoesNotReceiveWalletBytes() throws Exception { + assertTemporaryPathReplacementDoesNotReceiveWalletBytes(false); + } + + @Test + public void testReplacedTemporarySymlinkDoesNotReceiveWalletBytes() throws Exception { + assertTemporaryPathReplacementDoesNotReceiveWalletBytes(true); + } + + private void assertTemporaryPathReplacementDoesNotReceiveWalletBytes(boolean symlink) + throws Exception { + File dir = tempFolder.newFolder("replace-temp"); + File destination = new File(dir, "wallet.json"); + Path original = dir.toPath().resolve("original.tmp"); + Path attacker = dir.toPath().resolve("attacker-file"); + byte[] marker = new byte[] {1, 2, 3}; + Files.write(attacker, marker); + WalletFile wallet = lightWalletFile("password123"); + + try (MockedStatic channels = mockStatic(FileChannel.class, invocation -> { + FileChannel channel = (FileChannel) invocation.callRealMethod(); + if (invocation.getArguments().length == 3 + && ((Set) invocation.getArgument(1)).contains(StandardOpenOption.CREATE_NEW)) { + // Replace the directory entry after creation, before serialization starts. + Path tmp = invocation.getArgument(0); + Files.move(tmp, original); + if (symlink) { + Files.createSymbolicLink(tmp, attacker); + } else { + Files.write(tmp, marker); + } + } + return channel; + })) { + WalletUtils.writeWalletFile(wallet, destination); + } + assertArrayEquals(marker, Files.readAllBytes(attacker)); + assertArrayEquals(marker, Files.readAllBytes(destination.toPath())); + assertEquals(wallet.getAddress(), + WalletUtils.loadCredentials("password123", original.toFile()).getAddress()); + assertEquals(EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE), + Files.getPosixFilePermissions(original)); + } + + @Test + public void testTemporaryNameCollisionLeavesExistingFileUntouched() throws Exception { + File dir = tempFolder.newFolder("temp-collision"); + File destination = new File(dir, "wallet.json"); + AtomicReference existing = new AtomicReference<>(); + byte[] marker = new byte[] {1, 2, 3}; + WalletFile wallet = lightWalletFile("password123"); + try (MockedStatic channels = mockStatic(FileChannel.class, invocation -> { + if (invocation.getArguments().length == 3 + && ((Set) invocation.getArgument(1)).contains(StandardOpenOption.CREATE_NEW)) { + Path path = invocation.getArgument(0); + Files.write(path, marker); + existing.set(path); + } + return invocation.callRealMethod(); + })) { + assertThrows(FileAlreadyExistsException.class, + () -> WalletUtils.writeWalletFile(wallet, destination)); + } + assertNotNull(existing.get()); + assertArrayEquals(marker, Files.readAllBytes(existing.get())); + assertFalse(destination.exists()); + } + + @Test + public void testUnsupportedAtomicPermissionsDoesNotFallBack() throws Exception { + File dir = tempFolder.newFolder("unsupported-permissions"); + File destination = new File(dir, "wallet.json"); + WalletFile wallet = lightWalletFile("password123"); + try (MockedStatic channels = mockStatic(FileChannel.class, invocation -> { + if (invocation.getArguments().length == 3 + && ((Set) invocation.getArgument(1)).contains(StandardOpenOption.CREATE_NEW)) { + throw new UnsupportedOperationException("Atomic permissions unavailable"); + } + return invocation.callRealMethod(); + })) { + assertThrows(UnsupportedOperationException.class, + () -> WalletUtils.writeWalletFile(wallet, destination)); + } + assertEquals("No wallet or temporary file should be created", 0, dir.list().length); + } + // ---------- loadCredentials symlink behavior ---------- @Test From 8655178d4a8f6c869a949320ee1cde95365b22c5 Mon Sep 17 00:00:00 2001 From: federico Date: Tue, 17 Nov 2026 15:14:44 +0800 Subject: [PATCH 10/33] fix(keystore): reject malformed wallet files --- .../main/java/org/tron/keystore/Wallet.java | 118 +++++++--- .../args/WitnessInitializerKeystoreTest.java | 2 +- .../keystore/WalletAddressValidationTest.java | 2 +- .../keystore/WalletDecryptBoundsTest.java | 67 +++--- .../keystore/WalletSchemaValidationTest.java | 221 ++++++++++++++++++ .../tron/plugins/KeystoreCliUtilsTest.java | 36 ++- .../org/tron/plugins/KeystoreUpdateTest.java | 2 +- 7 files changed, 368 insertions(+), 80 deletions(-) create mode 100644 framework/src/test/java/org/tron/keystore/WalletSchemaValidationTest.java diff --git a/crypto/src/main/java/org/tron/keystore/Wallet.java b/crypto/src/main/java/org/tron/keystore/Wallet.java index 6baa24a3cf7..2c3b8d38e8b 100644 --- a/crypto/src/main/java/org/tron/keystore/Wallet.java +++ b/crypto/src/main/java/org/tron/keystore/Wallet.java @@ -21,7 +21,9 @@ import org.tron.common.crypto.Hash; import org.tron.common.crypto.SignInterface; import org.tron.common.crypto.SignUtils; +import org.tron.common.utils.Base58; import org.tron.common.utils.ByteArray; +import org.tron.common.utils.DecodeUtil; import org.tron.common.utils.StringUtil; import org.tron.core.exception.CipherException; @@ -30,20 +32,8 @@ * Web3 Secret Storage Definition or the * Go Ethereum client implementation.

* - *

Note: the Bouncy Castle Scrypt implementation {@link SCrypt}, fails to - * comply - * with the following Ethereum reference - * Scrypt test vector:

- * - *
- * {@code
- * // Only value of r that cost (as an int) could be exceeded for is 1
- * if (r == 1 && N_STANDARD > 65536)
- * {
- *     throw new IllegalArgumentException("Cost parameter N_STANDARD must be > 1 and < 65536.");
- * }
- * }
- * 
+ *

Scrypt parameters are checked against RFC 7914 and the supported resource limits + * before invoking {@link SCrypt}.

*/ public class Wallet { @@ -155,7 +145,7 @@ private static byte[] generateDerivedScryptKey( } private static byte[] generateAes128CtrDerivedKey( - byte[] password, byte[] salt, int c, String prf) throws CipherException { + byte[] password, byte[] salt, int c, String prf, int dklen) throws CipherException { if (!"hmac-sha256".equals(prf)) { throw new CipherException("Unsupported prf:" + prf); @@ -166,7 +156,7 @@ private static byte[] generateAes128CtrDerivedKey( PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest()); gen.init(password, salt, c); - return ((KeyParameter) gen.generateDerivedParameters(256)).getKey(); + return ((KeyParameter) gen.generateDerivedParameters(dklen * 8)).getKey(); } private static byte[] performCipherOperation( @@ -235,7 +225,8 @@ public static SignInterface decrypt(String password, WalletFile walletFile) byte[] salt = ByteArray.fromHexString(aes128CtrKdfParams.getSalt()); try { - derivedKey = generateAes128CtrDerivedKey(password.getBytes(UTF_8), salt, c, prf); + derivedKey = generateAes128CtrDerivedKey(password.getBytes(UTF_8), salt, c, prf, + aes128CtrKdfParams.getDklen()); } catch (RuntimeException e) { throw new CipherException("Pbkdf2 key derivation failed", e); } @@ -290,8 +281,8 @@ public static SignInterface decrypt(String password, WalletFile walletFile) /** * Returns a description of the first schema violation found in * {@code walletFile}, or {@code null} if the file matches the supported - * V3 keystore shape (current version, known cipher, known KDF, and KDF - * cost parameters within safe bounds). + * V3 keystore shape, including required fields, encodings, lengths, and KDF + * parameters within supported bounds. This does not verify the password or MAC. * *

KDF cost bounds are enforced here — the single chokepoint shared by * {@link #validate(WalletFile)} (which throws the message) and @@ -301,9 +292,17 @@ public static SignInterface decrypt(String password, WalletFile walletFile) * exhaustion, or engine-level crashes before {@link #decrypt} runs. */ private static String validationError(WalletFile walletFile) { + if (walletFile == null) { + return "Missing wallet file"; + } if (walletFile.getVersion() != CURRENT_VERSION) { return "Wallet version is not supported"; } + String address = walletFile.getAddress(); + // An absent address remains supported for imported keystores. + if (address != null && !address.isEmpty() && !validAddress(address)) { + return "Invalid keystore address"; + } WalletFile.Crypto crypto = walletFile.getCrypto(); if (crypto == null) { return "Missing crypto section"; @@ -312,30 +311,87 @@ private static String validationError(WalletFile walletFile) { if (cipher == null || !cipher.equals(CIPHER)) { return "Wallet cipher is not supported"; } + if (crypto.getCipherparams() == null) { + return "Missing cipherparams"; + } + if (!validHex(crypto.getCipherparams().getIv(), 16)) { + return "IV must be 16 bytes of hex"; + } + if (!validHex(crypto.getCiphertext(), 32)) { + return "Ciphertext must be 32 bytes of hex"; + } + if (!validHex(crypto.getMac(), 32)) { + return "MAC must be 32 bytes of hex"; + } String kdf = crypto.getKdf(); if (kdf == null || (!kdf.equals(PBKDF2) && !kdf.equals(SCRYPT))) { return "KDF type is not supported"; } WalletFile.KdfParams kdfParams = crypto.getKdfparams(); if (kdfParams == null) { - // Structural stubs (e.g. tooling fixtures) may omit kdfparams entirely; - // there are no cost parameters to bound. Real keystores always carry them. - return null; + return "Missing kdfparams"; } if (SCRYPT.equals(kdf)) { if (!(kdfParams instanceof WalletFile.ScryptKdfParams)) { return "Scrypt KDF params are missing or malformed"; } WalletFile.ScryptKdfParams params = (WalletFile.ScryptKdfParams) kdfParams; + if (!validHex(params.getSalt(), -1)) { + return "Scrypt salt must be non-empty hex"; + } return scryptKdfParamsError(params.getDklen(), params.getN(), params.getR(), params.getP()); } if (!(kdfParams instanceof WalletFile.Aes128CtrKdfParams)) { return "Pbkdf2 KDF params are missing or malformed"; } WalletFile.Aes128CtrKdfParams params = (WalletFile.Aes128CtrKdfParams) kdfParams; + if (!validHex(params.getSalt(), -1)) { + return "Pbkdf2 salt must be non-empty hex"; + } + if (!"hmac-sha256".equals(params.getPrf())) { + return "Unsupported prf: " + params.getPrf(); + } return pbkdf2KdfParamsError(params.getDklen(), params.getC()); } + private static boolean validHex(String value, int byteLength) { + if (value == null) { + return false; + } + // Preserve the existing optional 0x prefix, but reject padding and non-ASCII digits. + int start = value.startsWith("0x") ? 2 : 0; + int length = value.length() - start; + if (length == 0 || (length & 1) != 0 + || (byteLength >= 0 && length != byteLength * 2)) { + return false; + } + for (int i = start; i < value.length(); i++) { + char c = value.charAt(i); + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') + || (c >= 'A' && c <= 'F'))) { + return false; + } + } + return true; + } + + private static boolean validAddress(String address) { + // Bound Base58 decoding before allocating or doing quadratic conversion work. + if (address.length() > 34) { + return false; + } + try { + byte[] decoded = Base58.decode(address); + if (decoded.length != 25) { + return false; + } + byte[] payload = Arrays.copyOf(decoded, 21); + return DecodeUtil.addressValid(payload) && StringUtil.encode58Check(payload).equals(address); + } catch (IllegalArgumentException e) { + return false; + } + } + private static String scryptKdfParamsError(int dklen, int n, int r, int p) { // dklen must yield at least 32 bytes: generateMac copies derivedKey[16..32) // and AES-128 needs bytes [0..16); smaller keys throw raw ArrayIndexOutOfBoundsException. @@ -349,6 +405,10 @@ private static String scryptKdfParamsError(int dklen, int n, int r, int p) { if (r < 1 || r > SCRYPT_R_MAX) { return "Scrypt r is out of range [1, " + SCRYPT_R_MAX + "]: " + r; } + // RFC 7914 requires n < 2^(16*r); for r >= 2 the n cap already ensures this. + if (r == 1 && n >= (1 << 16)) { + return "Scrypt n must be less than 65536 when r is 1"; + } if (p < 1 || p > SCRYPT_P_MAX) { return "Scrypt p is out of range [1, " + SCRYPT_P_MAX + "]: " + p; } @@ -362,8 +422,8 @@ private static String scryptKdfParamsError(int dklen, int n, int r, int p) { } private static String pbkdf2KdfParamsError(int dklen, int c) { - if (dklen < 1 || dklen > KDF_DKLEN_MAX) { - return "Pbkdf2 dklen is out of range [1, " + KDF_DKLEN_MAX + "]: " + dklen; + if (dklen < 32 || dklen > KDF_DKLEN_MAX) { + return "Pbkdf2 dklen is out of range [32, " + KDF_DKLEN_MAX + "]: " + dklen; } if (c < 1 || c > PBKDF2_C_MAX) { return "Pbkdf2 iteration count c is out of range [1, " + PBKDF2_C_MAX + "]: " + c; @@ -379,15 +439,15 @@ static void validate(WalletFile walletFile) throws CipherException { } /** - * Returns {@code true} iff {@code walletFile} has the shape of a - * decryptable V3 keystore: non-null address, supported version, non-null - * crypto section with a supported cipher and KDF. Intended for - * discovery-style filtering (e.g. listing or duplicate detection) where - * we want to skip JSON stubs that would later fail {@link #validate}. + * Returns {@code true} iff {@code walletFile} has a non-empty address and passes + * the same structural checks as {@link #validate}. Intended for discovery-style + * filtering (e.g. listing or duplicate detection). Password correctness, MAC + * authenticity and address/private-key consistency are checked only by decrypt. */ public static boolean isValidKeystoreFile(WalletFile walletFile) { return walletFile != null && walletFile.getAddress() != null + && !walletFile.getAddress().isEmpty() && validationError(walletFile) == null; } diff --git a/framework/src/test/java/org/tron/core/config/args/WitnessInitializerKeystoreTest.java b/framework/src/test/java/org/tron/core/config/args/WitnessInitializerKeystoreTest.java index 988f20c7acb..875dd0c646d 100644 --- a/framework/src/test/java/org/tron/core/config/args/WitnessInitializerKeystoreTest.java +++ b/framework/src/test/java/org/tron/core/config/args/WitnessInitializerKeystoreTest.java @@ -171,7 +171,7 @@ public void testTamperedKeystoreRejectedAtSrLoading() throws Exception { ObjectMapper mapper = new ObjectMapper().configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); WalletFile wf = mapper.readValue(keystoreFile, WalletFile.class); - String spoofedAddress = "TSpoofedSrAddressXXXXXXXXXXXXXXXXXXX"; + String spoofedAddress = "T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb"; wf.setAddress(spoofedAddress); mapper.writeValue(keystoreFile, wf); diff --git a/framework/src/test/java/org/tron/keystore/WalletAddressValidationTest.java b/framework/src/test/java/org/tron/keystore/WalletAddressValidationTest.java index 563377527e3..bf628998d28 100644 --- a/framework/src/test/java/org/tron/keystore/WalletAddressValidationTest.java +++ b/framework/src/test/java/org/tron/keystore/WalletAddressValidationTest.java @@ -48,7 +48,7 @@ public void testDecryptRejectsSpoofedAddress() throws Exception { WalletFile walletFile = Wallet.createStandard(password, keyPair); // Tamper with the address to simulate a spoofed keystore - walletFile.setAddress("TTamperedAddressXXXXXXXXXXXXXXXXXX"); + walletFile.setAddress("T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb"); byte[] expectedPrivateKey = keyPair.getPrivateKey(); AtomicReference decryptedPrivateKey = new AtomicReference<>(); diff --git a/framework/src/test/java/org/tron/keystore/WalletDecryptBoundsTest.java b/framework/src/test/java/org/tron/keystore/WalletDecryptBoundsTest.java index aab7b640b9d..9ba5fc624f1 100644 --- a/framework/src/test/java/org/tron/keystore/WalletDecryptBoundsTest.java +++ b/framework/src/test/java/org/tron/keystore/WalletDecryptBoundsTest.java @@ -2,15 +2,16 @@ import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import org.tron.common.crypto.SignInterface; import org.tron.common.crypto.SignUtils; +import org.tron.common.utils.ByteArray; import org.tron.common.utils.Utils; import org.tron.core.exception.CipherException; @@ -32,17 +33,22 @@ public class WalletDecryptBoundsTest { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + private static final String ADDRESS = "T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb"; + private static final String IV = ByteArray.toHexString(new byte[16]); + private static final String WORD = ByteArray.toHexString(new byte[32]); private static final String SCRYPT_TEMPLATE = - "{\"version\":3,\"address\":\"addr\",\"id\":\"test\",\"crypto\":{" - + "\"cipher\":\"aes-128-ctr\",\"ciphertext\":\"00\"," - + "\"cipherparams\":{\"iv\":\"00\"},\"mac\":\"00\",\"kdf\":\"scrypt\"," + "{\"version\":3,\"address\":\"" + ADDRESS + "\",\"id\":\"test\",\"crypto\":{" + + "\"cipher\":\"aes-128-ctr\",\"ciphertext\":\"" + WORD + "\"," + + "\"cipherparams\":{\"iv\":\"" + IV + "\"},\"mac\":\"" + WORD + + "\",\"kdf\":\"scrypt\"," + "\"kdfparams\":{\"dklen\":%d,\"n\":%d,\"r\":%d,\"p\":%d,\"salt\":\"00\"}}}"; private static final String PBKDF2_TEMPLATE = - "{\"version\":3,\"address\":\"addr\",\"id\":\"test\",\"crypto\":{" - + "\"cipher\":\"aes-128-ctr\",\"ciphertext\":\"00\"," - + "\"cipherparams\":{\"iv\":\"00\"},\"mac\":\"00\",\"kdf\":\"pbkdf2\"," + "{\"version\":3,\"address\":\"" + ADDRESS + "\",\"id\":\"test\",\"crypto\":{" + + "\"cipher\":\"aes-128-ctr\",\"ciphertext\":\"" + WORD + "\"," + + "\"cipherparams\":{\"iv\":\"" + IV + "\"},\"mac\":\"" + WORD + + "\",\"kdf\":\"pbkdf2\"," + "\"kdfparams\":{\"dklen\":%d,\"c\":%d,\"prf\":\"hmac-sha256\",\"salt\":\"00\"}}}"; private static WalletFile parseKeystore(String json) throws Exception { @@ -147,14 +153,14 @@ private static WalletFile walletWithKdfparams( String kdf, WalletFile.KdfParams kdfParams) { WalletFile walletFile = new WalletFile(); walletFile.setVersion(3); - walletFile.setAddress("addr"); + walletFile.setAddress(ADDRESS); WalletFile.Crypto crypto = new WalletFile.Crypto(); crypto.setCipher("aes-128-ctr"); - crypto.setCiphertext("00"); + crypto.setCiphertext(WORD); WalletFile.CipherParams cipherParams = new WalletFile.CipherParams(); - cipherParams.setIv("00"); + cipherParams.setIv(IV); crypto.setCipherparams(cipherParams); - crypto.setMac("00"); + crypto.setMac(WORD); crypto.setKdf(kdf); crypto.setKdfparams(kdfParams); walletFile.setCrypto(crypto); @@ -162,28 +168,19 @@ private static WalletFile walletWithKdfparams( } @Test - public void testValidateToleratesMissingScryptKdfparams() { - // Structural stubs without kdfparams are tolerated (KeystoreCliUtilsTest - // fixture contract); decrypt() still fails safely because the - // ClassCastException (RuntimeException) is wrapped into CipherException. + public void testValidateRejectsMissingScryptKdfparams() { WalletFile walletFile = walletWithKdfparams("scrypt", null); - try { - Wallet.validate(walletFile); - } catch (CipherException e) { - fail("missing kdfparams must be tolerated, got: " + e.getMessage()); - } + assertThrows(CipherException.class, () -> Wallet.validate(walletFile)); + assertFalse(Wallet.isValidKeystoreFile(walletFile)); assertThrows(CipherException.class, () -> Wallet.decrypt("password123", walletFile)); } @Test - public void testValidateToleratesMissingPbkdf2Kdfparams() { + public void testValidateRejectsMissingPbkdf2Kdfparams() { WalletFile walletFile = walletWithKdfparams("pbkdf2", null); - try { - Wallet.validate(walletFile); - } catch (CipherException e) { - fail("missing kdfparams must be tolerated, got: " + e.getMessage()); - } + assertThrows(CipherException.class, () -> Wallet.validate(walletFile)); + assertFalse(Wallet.isValidKeystoreFile(walletFile)); assertThrows(CipherException.class, () -> Wallet.decrypt("password123", walletFile)); } @@ -249,9 +246,7 @@ public void testDecryptCorruptedKeystoreThrowsCipherException() throws Exception // In-bounds low-cost scrypt params (fast), but tampered MAC: // decrypt must fail with a clean CipherException, never leak a raw // RuntimeException stack. - String json = String.format(SCRYPT_TEMPLATE, 32, 1 << 12, 1, 1) - .replace("\"mac\":\"00\"", - "\"mac\":\"0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20\""); + String json = String.format(SCRYPT_TEMPLATE, 32, 1 << 12, 1, 1); WalletFile walletFile = parseKeystore(json); Wallet.validate(walletFile); @@ -261,21 +256,15 @@ public void testDecryptCorruptedKeystoreThrowsCipherException() throws Exception } @Test - public void testDecryptWrapsScryptRuntimeException() throws Exception { - // r=1 with n=131072 passes every validation bound (n is a power of 2 in - // [2^12, 2^20], r=1, p=1, 128*r*n = 16 MiB, dklen=32), but Bouncy - // Castle's SCrypt.generate itself rejects r==1 with n >= 65536 and throws - // a raw IllegalArgumentException. decrypt() must wrap that runtime KDF - // engine failure into a clean CipherException, preserving the cause. + public void testRejectsScryptR1CostBeforeDerivation() throws Exception { WalletFile walletFile = parseKeystore(String.format(SCRYPT_TEMPLATE, 32, 1 << 17, 1, 1)); - Wallet.validate(walletFile); + assertThrows(CipherException.class, () -> Wallet.validate(walletFile)); + assertFalse(Wallet.isValidKeystoreFile(walletFile)); CipherException err = assertThrows(CipherException.class, () -> Wallet.decrypt("password123", walletFile)); - assertEquals("Scrypt key derivation failed", err.getMessage()); - assertTrue("cause must be the SCrypt IllegalArgumentException", - err.getCause() instanceof IllegalArgumentException); + assertTrue(err.getMessage().contains("less than 65536")); } // ---------- create(): KDF params validated symmetric with decrypt() ---------- diff --git a/framework/src/test/java/org/tron/keystore/WalletSchemaValidationTest.java b/framework/src/test/java/org/tron/keystore/WalletSchemaValidationTest.java new file mode 100644 index 00000000000..8f0c8f92213 --- /dev/null +++ b/framework/src/test/java/org/tron/keystore/WalletSchemaValidationTest.java @@ -0,0 +1,221 @@ +package org.tron.keystore; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.List; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator; +import org.bouncycastle.crypto.generators.SCrypt; +import org.bouncycastle.crypto.params.KeyParameter; +import org.junit.Test; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.StringUtil; +import org.tron.core.exception.CipherException; + +public class WalletSchemaValidationTest { + + private static String hex(int bytes) { + return ByteArray.toHexString(new byte[bytes]); + } + + private static WalletFile validWallet(boolean pbkdf2) { + WalletFile wallet = new WalletFile(); + wallet.setVersion(3); + wallet.setAddress("T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb"); + WalletFile.Crypto crypto = new WalletFile.Crypto(); + crypto.setCipher("aes-128-ctr"); + crypto.setCiphertext(hex(32)); + crypto.setMac(hex(32)); + WalletFile.CipherParams cipher = new WalletFile.CipherParams(); + cipher.setIv(hex(16)); + crypto.setCipherparams(cipher); + if (pbkdf2) { + crypto.setKdf("pbkdf2"); + WalletFile.Aes128CtrKdfParams params = new WalletFile.Aes128CtrKdfParams(); + params.setDklen(32); + params.setC(1); + params.setPrf("hmac-sha256"); + params.setSalt("00"); + crypto.setKdfparams(params); + } else { + crypto.setKdf("scrypt"); + WalletFile.ScryptKdfParams params = new WalletFile.ScryptKdfParams(); + params.setDklen(32); + params.setN(4096); + params.setR(8); + params.setP(1); + params.setSalt("00"); + crypto.setKdfparams(params); + } + wallet.setCrypto(crypto); + return wallet; + } + + private static void assertRejected(WalletFile wallet) { + try (MockedStatic scrypt = mockStatic(SCrypt.class); + MockedConstruction pbkdf2 = + mockConstruction(PKCS5S2ParametersGenerator.class)) { + assertFalse(Wallet.isValidKeystoreFile(wallet)); + assertThrows(CipherException.class, () -> Wallet.validate(wallet)); + assertThrows(CipherException.class, () -> Wallet.decrypt("password", wallet)); + scrypt.verifyNoInteractions(); + assertTrue("Malformed input must be rejected before PBKDF2", pbkdf2.constructed().isEmpty()); + } + } + + @Test + public void testMissingRequiredSectionsAreRejectedBeforeKdf() { + assertRejected(null); + List> mutations = Arrays.asList( + w -> w.setCrypto(null), + w -> w.getCrypto().setCipher(null), + w -> w.getCrypto().setCipherparams(null), + w -> w.getCrypto().setKdf(null), + w -> w.getCrypto().setKdfparams(null)); + for (boolean pbkdf2 : new boolean[] {false, true}) { + for (Consumer mutation : mutations) { + WalletFile wallet = validWallet(pbkdf2); + mutation.accept(wallet); + assertRejected(wallet); + } + } + } + + @Test + public void testMalformedHexFieldsAreRejectedBeforeKdf() { + List> fields = Arrays.asList( + (w, s) -> w.getCrypto().setCiphertext(s), + (w, s) -> w.getCrypto().setMac(s), + (w, s) -> w.getCrypto().getCipherparams().setIv(s), + (w, s) -> { + WalletFile.KdfParams params = w.getCrypto().getKdfparams(); + if (params instanceof WalletFile.ScryptKdfParams) { + ((WalletFile.ScryptKdfParams) params).setSalt(s); + } else { + ((WalletFile.Aes128CtrKdfParams) params).setSalt(s); + } + }); + for (boolean pbkdf2 : new boolean[] {false, true}) { + for (BiConsumer field : fields) { + for (String value : new String[] {null, "", "0x", "0", "zz", "00 00", "00"}) { + WalletFile wallet = validWallet(pbkdf2); + field.accept(wallet, value); + assertRejected(wallet); + } + } + } + } + + @Test + public void testInvalidFixedLengthsAreRejectedBeforeKdf() { + for (int length : new int[] {0, 1, 15, 17, 31, 33}) { + WalletFile wallet = validWallet(false); + wallet.getCrypto().getCipherparams().setIv(hex(length)); + assertRejected(wallet); + wallet = validWallet(false); + wallet.getCrypto().setMac(hex(length)); + assertRejected(wallet); + wallet = validWallet(false); + wallet.getCrypto().setCiphertext(hex(length)); + assertRejected(wallet); + } + } + + @Test + public void testInvalidAddressesAreRejectedBeforeKdf() { + for (String address : new String[] {"T0", "../wallet", hex(64), + "T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwa", StringUtil.encode58Check(new byte[21])}) { + WalletFile wallet = validWallet(false); + wallet.setAddress(address); + assertRejected(wallet); + } + } + + @Test + public void testAbsentAddressIsValidForDecryptButNotDiscovery() throws Exception { + for (String address : new String[] {null, ""}) { + WalletFile wallet = validWallet(false); + wallet.setAddress(address); + Wallet.validate(wallet); + assertFalse(Wallet.isValidKeystoreFile(wallet)); + } + } + + @Test + public void testKdfTypeMismatchIsRejectedBeforeDerivation() { + for (boolean pbkdf2 : new boolean[] {false, true}) { + WalletFile wallet = validWallet(pbkdf2); + wallet.getCrypto().setKdf(pbkdf2 ? "scrypt" : "pbkdf2"); + assertRejected(wallet); + } + } + + @Test + public void testPbkdf2ParametersAreRejectedBeforeDerivation() { + for (int dklen : new int[] {-1, 0, 1, 31, 129, Integer.MAX_VALUE}) { + WalletFile wallet = validWallet(true); + ((WalletFile.Aes128CtrKdfParams) wallet.getCrypto().getKdfparams()).setDklen(dklen); + assertRejected(wallet); + } + for (int c : new int[] {-1, 0, (1 << 20) + 1}) { + WalletFile wallet = validWallet(true); + ((WalletFile.Aes128CtrKdfParams) wallet.getCrypto().getKdfparams()).setC(c); + assertRejected(wallet); + } + for (String prf : new String[] {null, "", "hmac-sha1"}) { + WalletFile wallet = validWallet(true); + ((WalletFile.Aes128CtrKdfParams) wallet.getCrypto().getKdfparams()).setPrf(prf); + assertRejected(wallet); + } + } + + @Test + public void testScryptR1Boundary() throws Exception { + WalletFile wallet = validWallet(false); + WalletFile.ScryptKdfParams params = + (WalletFile.ScryptKdfParams) wallet.getCrypto().getKdfparams(); + params.setR(1); + params.setN(1 << 15); + Wallet.validate(wallet); + params.setN(1 << 16); + assertRejected(wallet); + } + + @Test + public void testPbkdf2UsesDeclaredKeyLength() throws Exception { + WalletFile wallet = validWallet(true); + ((WalletFile.Aes128CtrKdfParams) wallet.getCrypto().getKdfparams()).setDklen(64); + try (MockedConstruction generators = mockConstruction( + PKCS5S2ParametersGenerator.class, (generator, context) -> + when(generator.generateDerivedParameters(512)).thenReturn( + new KeyParameter(new byte[64])))) { + CipherException error = assertThrows(CipherException.class, + () -> Wallet.decrypt("password", wallet)); + assertEquals("Invalid password provided", error.getMessage()); + assertEquals(1, generators.constructed().size()); + verify(generators.constructed().get(0)).generateDerivedParameters(512); + } + } + + @Test + public void testPrefixedAndUppercaseHexRemainAccepted() throws Exception { + WalletFile wallet = validWallet(false); + wallet.getCrypto().getCipherparams().setIv("0xAABBCCDDEEFF00112233445566778899"); + wallet.getCrypto().setMac("0x" + hex(32)); + wallet.getCrypto().setCiphertext("0x" + hex(32)); + ((WalletFile.ScryptKdfParams) wallet.getCrypto().getKdfparams()).setSalt("0xAABB"); + Wallet.validate(wallet); + assertTrue(Wallet.isValidKeystoreFile(wallet)); + } +} diff --git a/plugins/src/test/java/org/tron/plugins/KeystoreCliUtilsTest.java b/plugins/src/test/java/org/tron/plugins/KeystoreCliUtilsTest.java index 5c273dcb1b6..e13798772d2 100644 --- a/plugins/src/test/java/org/tron/plugins/KeystoreCliUtilsTest.java +++ b/plugins/src/test/java/org/tron/plugins/KeystoreCliUtilsTest.java @@ -18,6 +18,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; +import org.tron.common.utils.ByteArray; import org.tron.keystore.WalletFile; public class KeystoreCliUtilsTest { @@ -53,13 +54,25 @@ private static WalletFile.Crypto supportedCrypto() { WalletFile.Crypto crypto = new WalletFile.Crypto(); crypto.setCipher("aes-128-ctr"); crypto.setKdf("scrypt"); + crypto.setCiphertext(ByteArray.toHexString(new byte[32])); + crypto.setMac(ByteArray.toHexString(new byte[32])); + WalletFile.CipherParams cipher = new WalletFile.CipherParams(); + cipher.setIv(ByteArray.toHexString(new byte[16])); + crypto.setCipherparams(cipher); + WalletFile.ScryptKdfParams params = new WalletFile.ScryptKdfParams(); + params.setDklen(32); + params.setN(4096); + params.setR(8); + params.setP(1); + params.setSalt("00"); + crypto.setKdfparams(params); return crypto; } @Test public void testIsValidKeystoreFileValid() { WalletFile wf = new WalletFile(); - wf.setAddress("TAddr"); + wf.setAddress("T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb"); wf.setVersion(3); wf.setCrypto(supportedCrypto()); assertTrue(KeystoreCliUtils.isValidKeystoreFile(wf)); @@ -76,7 +89,7 @@ public void testIsValidKeystoreFileNullAddress() { @Test public void testIsValidKeystoreFileNullCrypto() { WalletFile wf = new WalletFile(); - wf.setAddress("TAddr"); + wf.setAddress("T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb"); wf.setVersion(3); assertFalse(KeystoreCliUtils.isValidKeystoreFile(wf)); } @@ -84,7 +97,7 @@ public void testIsValidKeystoreFileNullCrypto() { @Test public void testIsValidKeystoreFileWrongVersion() { WalletFile wf = new WalletFile(); - wf.setAddress("TAddr"); + wf.setAddress("T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb"); wf.setVersion(2); wf.setCrypto(supportedCrypto()); assertFalse(KeystoreCliUtils.isValidKeystoreFile(wf)); @@ -95,7 +108,7 @@ public void testIsValidKeystoreFileRejectsEmptyCryptoStub() { // {"address":"T...","version":3,"crypto":{}} — passes the old checks // but Wallet.validate would later reject it. Discovery should skip it. WalletFile wf = new WalletFile(); - wf.setAddress("TAddr"); + wf.setAddress("T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb"); wf.setVersion(3); wf.setCrypto(new WalletFile.Crypto()); assertFalse(KeystoreCliUtils.isValidKeystoreFile(wf)); @@ -104,7 +117,7 @@ public void testIsValidKeystoreFileRejectsEmptyCryptoStub() { @Test public void testIsValidKeystoreFileRejectsUnsupportedCipher() { WalletFile wf = new WalletFile(); - wf.setAddress("TAddr"); + wf.setAddress("T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb"); wf.setVersion(3); WalletFile.Crypto crypto = new WalletFile.Crypto(); crypto.setCipher("des"); @@ -116,7 +129,7 @@ public void testIsValidKeystoreFileRejectsUnsupportedCipher() { @Test public void testIsValidKeystoreFileRejectsUnsupportedKdf() { WalletFile wf = new WalletFile(); - wf.setAddress("TAddr"); + wf.setAddress("T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb"); wf.setVersion(3); WalletFile.Crypto crypto = new WalletFile.Crypto(); crypto.setCipher("aes-128-ctr"); @@ -129,11 +142,16 @@ public void testIsValidKeystoreFileRejectsUnsupportedKdf() { public void testIsValidKeystoreFileAcceptsPbkdf2Kdf() { // pbkdf2 is the other supported KDF (used by some Ethereum keystores). WalletFile wf = new WalletFile(); - wf.setAddress("TAddr"); + wf.setAddress("T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb"); wf.setVersion(3); - WalletFile.Crypto crypto = new WalletFile.Crypto(); - crypto.setCipher("aes-128-ctr"); + WalletFile.Crypto crypto = supportedCrypto(); crypto.setKdf("pbkdf2"); + WalletFile.Aes128CtrKdfParams params = new WalletFile.Aes128CtrKdfParams(); + params.setDklen(32); + params.setC(262144); + params.setPrf("hmac-sha256"); + params.setSalt("00"); + crypto.setKdfparams(params); wf.setCrypto(crypto); assertTrue(KeystoreCliUtils.isValidKeystoreFile(wf)); } diff --git a/plugins/src/test/java/org/tron/plugins/KeystoreUpdateTest.java b/plugins/src/test/java/org/tron/plugins/KeystoreUpdateTest.java index 8c3f6739de9..fe19cf283ab 100644 --- a/plugins/src/test/java/org/tron/plugins/KeystoreUpdateTest.java +++ b/plugins/src/test/java/org/tron/plugins/KeystoreUpdateTest.java @@ -619,7 +619,7 @@ public void testUpdateRejectsTamperedAddressKeystore() throws Exception { File keystoreFile = new File(dir, fileName); String realAddress = Credentials.create(keyPair).getAddress(); - String spoofedAddress = "TSpoofedAddressXXXXXXXXXXXXXXXXXXXX"; + String spoofedAddress = "T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb"; com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper() From 2de697b3f4e6a3b4a59d86fbfc36a7581d180deb Mon Sep 17 00:00:00 2001 From: federico Date: Tue, 17 Nov 2026 15:28:02 +0800 Subject: [PATCH 11/33] docs(keystore): clarify discovery validation --- .../java/common/org/tron/plugins/KeystoreCliUtils.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/plugins/src/main/java/common/org/tron/plugins/KeystoreCliUtils.java b/plugins/src/main/java/common/org/tron/plugins/KeystoreCliUtils.java index c91bb86ad8c..8600efa7cb9 100644 --- a/plugins/src/main/java/common/org/tron/plugins/KeystoreCliUtils.java +++ b/plugins/src/main/java/common/org/tron/plugins/KeystoreCliUtils.java @@ -311,11 +311,9 @@ static void printSecurityTips(PrintWriter out, String address, String fileName) } /** - * Check if a WalletFile represents a decryptable V3 keystore. - * Delegates to {@link Wallet#isValidKeystoreFile(WalletFile)} so the - * discovery predicate stays in sync with decryption-time validation — - * a JSON stub with empty or unsupported cipher/KDF is rejected here - * rather than silently showing up as a "keystore" and failing later. + * Checks keystore structure and requires a non-empty, valid address for discovery. + * Unlike decryption, discovery excludes missing or empty addresses. + * See {@link Wallet#isValidKeystoreFile(WalletFile)}; decryption may still fail. */ static boolean isValidKeystoreFile(WalletFile wf) { return org.tron.keystore.Wallet.isValidKeystoreFile(wf); From 3ffe91d2d063359a830ce4b2381268e56939743d Mon Sep 17 00:00:00 2001 From: federico Date: Tue, 17 Nov 2026 16:14:10 +0800 Subject: [PATCH 12/33] fix(keystore): validate wallet creation inputs --- .../org/tron/common/utils/StringUtil.java | 11 +- .../main/java/org/tron/keystore/Wallet.java | 69 ++++--- .../core/config/args/LocalWitnessTest.java | 13 +- .../args/WitnessInitializerKeystoreTest.java | 9 +- .../keystore/WalletCreateValidationTest.java | 186 ++++++++++++++++++ .../org/tron/keystore/WalletFileTest.java | 6 +- .../keystore/WalletSchemaValidationTest.java | 21 +- 7 files changed, 267 insertions(+), 48 deletions(-) create mode 100644 framework/src/test/java/org/tron/keystore/WalletCreateValidationTest.java diff --git a/common/src/main/java/org/tron/common/utils/StringUtil.java b/common/src/main/java/org/tron/common/utils/StringUtil.java index d4958475394..2d19f1f62d6 100644 --- a/common/src/main/java/org/tron/common/utils/StringUtil.java +++ b/common/src/main/java/org/tron/common/utils/StringUtil.java @@ -44,17 +44,22 @@ public static ByteString hexString2ByteString(String hexString) { return ByteString.copyFrom(ByteArray.fromHexString(hexString)); } + /** + * Checks for non-empty, even-length ASCII hex with an optional {@code 0x} prefix. + */ public static boolean isHexadecimal(String str) { if (str == null || str.isEmpty()) { return false; } - if (str.length() % 2 != 0) { + int start = str.startsWith("0x") ? 2 : 0; + if (str.length() == start || str.length() % 2 != 0) { return false; } - for (int i = 0; i < str.length(); i++) { + for (int i = start; i < str.length(); i++) { char c = str.charAt(i); - if (Character.digit(c, 16) == -1) { + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') + || (c >= 'A' && c <= 'F'))) { return false; } } diff --git a/crypto/src/main/java/org/tron/keystore/Wallet.java b/crypto/src/main/java/org/tron/keystore/Wallet.java index 2c3b8d38e8b..4b7542d632c 100644 --- a/crypto/src/main/java/org/tron/keystore/Wallet.java +++ b/crypto/src/main/java/org/tron/keystore/Wallet.java @@ -18,6 +18,7 @@ import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator; import org.bouncycastle.crypto.generators.SCrypt; import org.bouncycastle.crypto.params.KeyParameter; +import org.tron.common.crypto.ECKey; import org.tron.common.crypto.Hash; import org.tron.common.crypto.SignInterface; import org.tron.common.crypto.SignUtils; @@ -68,9 +69,19 @@ public class Wallet { private static final int KDF_DKLEN_MAX = 128; private static final int PBKDF2_C_MAX = 1 << 20; + /** + * Creates a keystore. The caller must ensure the signing key's address matches its private key. + */ public static WalletFile create(String password, SignInterface sign, int n, int p) throws CipherException { + if (!WalletUtils.passwordValid(password)) { + throw new CipherException("Password must be at least 6 characters"); + } + if (sign == null) { + throw new CipherException("Missing signing key"); + } + // Keep create() symmetric with validate()/decrypt(): reject KDF cost // parameters that the decryption path would refuse, so create() can // never produce a wallet file that only this class rejects. @@ -79,15 +90,23 @@ public static WalletFile create(String password, SignInterface sign, int n, int throw new CipherException(paramError); } + byte[] privateKeyBytes = sign.getPrivateKey(); + if (!ECKey.isValidPrivateKey(privateKeyBytes)) { + throw new CipherException("Invalid private key"); + } + byte[] salt = generateRandomBytes(32); - byte[] derivedKey = generateDerivedScryptKey(password.getBytes(UTF_8), salt, n, R, p, DKLEN); + byte[] derivedKey; + try { + derivedKey = generateDerivedScryptKey(password.getBytes(UTF_8), salt, n, R, p, DKLEN); + } catch (RuntimeException e) { + throw new CipherException("Scrypt key derivation failed", e); + } byte[] encryptKey = Arrays.copyOfRange(derivedKey, 0, 16); byte[] iv = generateRandomBytes(16); - byte[] privateKeyBytes = sign.getPrivateKey(); - byte[] cipherText = performCipherOperation(Cipher.ENCRYPT_MODE, iv, encryptKey, privateKeyBytes); @@ -314,13 +333,22 @@ private static String validationError(WalletFile walletFile) { if (crypto.getCipherparams() == null) { return "Missing cipherparams"; } - if (!validHex(crypto.getCipherparams().getIv(), 16)) { + String iv = crypto.getCipherparams().getIv(); + if (iv == null || iv.length() > 34 || !StringUtil.isHexadecimal(iv) + || ByteArray.fromHexString(iv).length != 16) { return "IV must be 16 bytes of hex"; } - if (!validHex(crypto.getCiphertext(), 32)) { - return "Ciphertext must be 32 bytes of hex"; - } - if (!validHex(crypto.getMac(), 32)) { + String ciphertext = crypto.getCiphertext(); + // Allow the private-key encodings accepted by ECKey; validate the scalar after decryption. + if (ciphertext == null + || ciphertext.length() > 68 + || !StringUtil.isHexadecimal(ciphertext) + || ByteArray.fromHexString(ciphertext).length > 33) { + return "Ciphertext must be 1 to 33 bytes of hex"; + } + String mac = crypto.getMac(); + if (mac == null || mac.length() > 66 || !StringUtil.isHexadecimal(mac) + || ByteArray.fromHexString(mac).length != 32) { return "MAC must be 32 bytes of hex"; } String kdf = crypto.getKdf(); @@ -336,7 +364,7 @@ private static String validationError(WalletFile walletFile) { return "Scrypt KDF params are missing or malformed"; } WalletFile.ScryptKdfParams params = (WalletFile.ScryptKdfParams) kdfParams; - if (!validHex(params.getSalt(), -1)) { + if (!StringUtil.isHexadecimal(params.getSalt())) { return "Scrypt salt must be non-empty hex"; } return scryptKdfParamsError(params.getDklen(), params.getN(), params.getR(), params.getP()); @@ -345,7 +373,7 @@ private static String validationError(WalletFile walletFile) { return "Pbkdf2 KDF params are missing or malformed"; } WalletFile.Aes128CtrKdfParams params = (WalletFile.Aes128CtrKdfParams) kdfParams; - if (!validHex(params.getSalt(), -1)) { + if (!StringUtil.isHexadecimal(params.getSalt())) { return "Pbkdf2 salt must be non-empty hex"; } if (!"hmac-sha256".equals(params.getPrf())) { @@ -354,27 +382,6 @@ private static String validationError(WalletFile walletFile) { return pbkdf2KdfParamsError(params.getDklen(), params.getC()); } - private static boolean validHex(String value, int byteLength) { - if (value == null) { - return false; - } - // Preserve the existing optional 0x prefix, but reject padding and non-ASCII digits. - int start = value.startsWith("0x") ? 2 : 0; - int length = value.length() - start; - if (length == 0 || (length & 1) != 0 - || (byteLength >= 0 && length != byteLength * 2)) { - return false; - } - for (int i = start; i < value.length(); i++) { - char c = value.charAt(i); - if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') - || (c >= 'A' && c <= 'F'))) { - return false; - } - } - return true; - } - private static boolean validAddress(String address) { // Bound Base58 decoding before allocating or doing quadratic conversion work. if (address.length() > 34) { diff --git a/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java b/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java index 1b613dc3320..5059b0b84ee 100644 --- a/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java +++ b/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java @@ -161,12 +161,13 @@ private void assertTronError(LocalWitnesses localWitnesses, String privateKey, @Test public void testHexStringFormat() { - Assert.assertTrue(StringUtil.isHexadecimal("0123456789abcdefABCDEF")); - Assert.assertFalse(StringUtil.isHexadecimal(null)); - Assert.assertFalse(StringUtil.isHexadecimal("")); - Assert.assertFalse(StringUtil.isHexadecimal("abc")); - Assert.assertFalse(StringUtil.isHexadecimal(" ")); - Assert.assertFalse(StringUtil.isHexadecimal("123xyz")); + for (String value : new String[] {"0123456789abcdefABCDEF", "0x12", "0xabcdefABCDEF"}) { + Assert.assertTrue("Expected valid hex: " + value, StringUtil.isHexadecimal(value)); + } + for (String value : new String[] {null, "", "abc", " ", "123xyz", "0x", "0x1", + "0x0x12", "0X12", "0x12", "00 00", "12", "AB", "١٢"}) { + Assert.assertFalse("Expected invalid hex: " + value, StringUtil.isHexadecimal(value)); + } } @Test diff --git a/framework/src/test/java/org/tron/core/config/args/WitnessInitializerKeystoreTest.java b/framework/src/test/java/org/tron/core/config/args/WitnessInitializerKeystoreTest.java index 875dd0c646d..77261301518 100644 --- a/framework/src/test/java/org/tron/core/config/args/WitnessInitializerKeystoreTest.java +++ b/framework/src/test/java/org/tron/core/config/args/WitnessInitializerKeystoreTest.java @@ -193,11 +193,16 @@ public void testTamperedKeystoreRejectedAtSrLoading() throws Exception { @Test public void testInvalidPrivateKeyLoadError() throws Exception { - // Only mock the source of bytes for encryption. Decryption and key validation are real. + // Bypass creation validation to build an invalid fixture; loading uses real key validation. SignInterface invalidKey = mock(SignInterface.class); when(invalidKey.getPrivateKey()).thenReturn(new byte[32]); when(invalidKey.getAddress()).thenReturn(ECKey.fromPrivate(BigInteger.ONE).getAddress()); - WalletFile walletFile = Wallet.createLight(PASSWORD, invalidKey); + WalletFile walletFile; + try (MockedStatic ecKey = org.mockito.Mockito.mockStatic(ECKey.class)) { + ecKey.when(() -> ECKey.isValidPrivateKey(org.mockito.ArgumentMatchers.any(byte[].class))) + .thenReturn(true); + walletFile = Wallet.createLight(PASSWORD, invalidKey); + } String fileName = DIR_NAME + "/invalid-key.json"; new ObjectMapper().writeValue(new File(System.getProperty("user.dir"), fileName), walletFile); diff --git a/framework/src/test/java/org/tron/keystore/WalletCreateValidationTest.java b/framework/src/test/java/org/tron/keystore/WalletCreateValidationTest.java new file mode 100644 index 00000000000..1c1b5606c4e --- /dev/null +++ b/framework/src/test/java/org/tron/keystore/WalletCreateValidationTest.java @@ -0,0 +1,186 @@ +package org.tron.keystore; + +import static java.nio.charset.StandardCharsets.UTF_8; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.math.BigInteger; +import java.util.Arrays; +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import org.bouncycastle.crypto.generators.SCrypt; +import org.junit.Test; +import org.mockito.MockedStatic; +import org.tron.common.crypto.ECKey; +import org.tron.common.crypto.Hash; +import org.tron.common.crypto.SignInterface; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.StringUtil; +import org.tron.core.exception.CipherException; + +public class WalletCreateValidationTest { + + private static final String PASSWORD = "123456"; + + private static void assertRejected(String password, SignInterface sign, int n, int p) { + try (MockedStatic scrypt = mockStatic(SCrypt.class)) { + assertThrows(CipherException.class, () -> Wallet.create(password, sign, n, p)); + scrypt.verifyNoInteractions(); + } + } + + @Test + public void testInvalidPasswordsAreRejectedBeforeKdf() { + ECKey key = ECKey.fromPrivate(BigInteger.ONE); + for (String password : new String[] {null, "", "12345"}) { + assertRejected(password, key, 4096, 1); + try (MockedStatic scrypt = mockStatic(SCrypt.class)) { + assertThrows(CipherException.class, () -> Wallet.createLight(password, key)); + assertThrows(CipherException.class, () -> Wallet.createStandard(password, key)); + scrypt.verifyNoInteractions(); + } + } + } + + @Test + public void testMissingAndPublicOnlyKeysAreRejectedBeforeKdf() { + assertRejected(PASSWORD, null, 4096, 1); + ECKey key = ECKey.fromPrivate(BigInteger.ONE); + assertRejected(PASSWORD, ECKey.fromPublicOnly(key.getPubKey()), 4096, 1); + } + + @Test + public void testInvalidPrivateKeysAreRejectedBeforeKdf() { + byte[] order = ByteArray.fromHexString( + "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); + byte[] aboveOrder = order.clone(); + aboveOrder[31]++; + for (byte[] bytes : new byte[][] {null, new byte[0], new byte[] {0}, new byte[31], + new byte[33], new byte[34], new byte[32], order, aboveOrder}) { + SignInterface sign = mock(SignInterface.class); + when(sign.getPrivateKey()).thenReturn(bytes); + assertRejected(PASSWORD, sign, 4096, 1); + } + } + + @Test + public void testInvalidCostsAreRejectedBeforeKdf() { + ECKey key = ECKey.fromPrivate(BigInteger.ONE); + for (int n : new int[] {0, 2, 4095, 4097, 1 << 21}) { + assertRejected(PASSWORD, key, n, 1); + } + for (int p : new int[] {-1, 0, 9}) { + assertRejected(PASSWORD, key, 4096, p); + } + } + + @Test + public void testCreateAcceptsConsistentSigningKey() throws Exception { + ECKey key = ECKey.fromPrivate(BigInteger.ONE); + byte[] privateKey = key.getPrivateKey(); + SignInterface sign = mock(SignInterface.class); + when(sign.getPrivateKey()).thenReturn(privateKey); + when(sign.getAddress()).thenReturn(key.getAddress()); + + WalletFile wallet = Wallet.create(PASSWORD, sign, 4096, 1); + + assertEquals(StringUtil.encode58Check(key.getAddress()), wallet.getAddress()); + assertArrayEquals(privateKey, Wallet.decrypt(PASSWORD, wallet).getPrivateKey()); + assertArrayEquals(key.getPrivateKey(), privateKey); + verify(sign).getPrivateKey(); + verify(sign).getAddress(); + } + + @Test + public void testValidPrivateKeyEncodingsRoundTrip() throws Exception { + byte[] shortKey = new byte[31]; + shortKey[30] = 1; + byte[] signedKey = BigInteger.ONE.shiftLeft(255).toByteArray(); + for (byte[] bytes : new byte[][] {new byte[] {1}, shortKey, + ECKey.fromPrivate(BigInteger.ONE).getPrivateKey(), signedKey}) { + ECKey key = ECKey.fromPrivate(bytes); + SignInterface sign = mock(SignInterface.class); + when(sign.getPrivateKey()).thenReturn(bytes); + when(sign.getAddress()).thenReturn(key.getAddress()); + + WalletFile wallet = Wallet.create(PASSWORD, sign, 4096, 1); + + assertEquals(bytes.length, + ByteArray.fromHexString(wallet.getCrypto().getCiphertext()).length); + assertArrayEquals(key.getPrivateKey(), Wallet.decrypt(PASSWORD, wallet).getPrivateKey()); + } + } + + @Test + public void testInvalidDecryptedKeysStillThrowCipherException() throws Exception { + ECKey key = ECKey.fromPrivate(BigInteger.ONE); + byte[] invalidSignByte = new byte[33]; + invalidSignByte[0] = 1; + byte[] unnecessarySignByte = new byte[33]; + unnecessarySignByte[32] = 1; + byte[] order = ByteArray.fromHexString( + "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); + for (byte[] bytes : new byte[][] {new byte[1], new byte[31], new byte[32], + invalidSignByte, unnecessarySignByte, order}) { + WalletFile wallet = Wallet.create(PASSWORD, key, 4096, 1); + encryptPrivateKey(wallet, PASSWORD, bytes); + + CipherException error = assertThrows(CipherException.class, + () -> Wallet.decrypt(PASSWORD, wallet)); + assertEquals("Invalid private key in keystore", error.getMessage()); + } + } + + @Test + public void testKdfFailureIsWrapped() { + ECKey key = ECKey.fromPrivate(BigInteger.ONE); + IllegalArgumentException cause = new IllegalArgumentException("KDF failure"); + try (MockedStatic scrypt = mockStatic(SCrypt.class)) { + scrypt.when(() -> SCrypt.generate(any(byte[].class), any(byte[].class), + anyInt(), anyInt(), anyInt(), anyInt())).thenThrow(cause); + CipherException error = assertThrows(CipherException.class, + () -> Wallet.create(PASSWORD, key, 4096, 1)); + assertEquals("Scrypt key derivation failed", error.getMessage()); + assertSame(cause, error.getCause()); + } + } + + @Test + public void testLegacyShortPasswordsStillDecrypt() throws Exception { + ECKey key = ECKey.fromPrivate(BigInteger.ONE); + for (String password : new String[] {"", "short"}) { + WalletFile wallet = Wallet.create(PASSWORD, key, 4096, 1); + encryptPrivateKey(wallet, password, key.getPrivateKey()); + + assertArrayEquals(key.getPrivateKey(), Wallet.decrypt(password, wallet).getPrivateKey()); + } + } + + private static void encryptPrivateKey(WalletFile wallet, String password, byte[] privateKey) + throws Exception { + WalletFile.Crypto crypto = wallet.getCrypto(); + WalletFile.ScryptKdfParams params = (WalletFile.ScryptKdfParams) crypto.getKdfparams(); + byte[] derived = SCrypt.generate(password.getBytes(UTF_8), + ByteArray.fromHexString(params.getSalt()), params.getN(), params.getR(), params.getP(), + params.getDklen()); + Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding"); + cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(Arrays.copyOf(derived, 16), "AES"), + new IvParameterSpec(ByteArray.fromHexString(crypto.getCipherparams().getIv()))); + byte[] ciphertext = cipher.doFinal(privateKey); + byte[] macInput = new byte[16 + ciphertext.length]; + System.arraycopy(derived, 16, macInput, 0, 16); + System.arraycopy(ciphertext, 0, macInput, 16, ciphertext.length); + crypto.setCiphertext(ByteArray.toHexString(ciphertext)); + crypto.setMac(ByteArray.toHexString(Hash.sha3(macInput))); + } +} diff --git a/framework/src/test/java/org/tron/keystore/WalletFileTest.java b/framework/src/test/java/org/tron/keystore/WalletFileTest.java index 272a29e6838..4d9715fb510 100644 --- a/framework/src/test/java/org/tron/keystore/WalletFileTest.java +++ b/framework/src/test/java/org/tron/keystore/WalletFileTest.java @@ -13,9 +13,9 @@ public class WalletFileTest { @Test public void testGetAddress() throws NoSuchAlgorithmException, CipherException { - WalletFile walletFile1 = Wallet.createStandard("", SignUtils.getGeneratedRandomSign( + WalletFile walletFile1 = Wallet.createStandard("password123", SignUtils.getGeneratedRandomSign( SecureRandom.getInstance("NativePRNG"))); - WalletFile walletFile2 = Wallet.createStandard("", SignUtils.getGeneratedRandomSign( + WalletFile walletFile2 = Wallet.createStandard("password123", SignUtils.getGeneratedRandomSign( SecureRandom.getInstance("NativePRNG"))); WalletFile walletFile3 = (WalletFile) getSame(walletFile1); Assert.assertNotEquals(walletFile1.getAddress(), walletFile2.getAddress()); @@ -72,4 +72,4 @@ private Object getSame(Object obj) { return obj; } -} \ No newline at end of file +} diff --git a/framework/src/test/java/org/tron/keystore/WalletSchemaValidationTest.java b/framework/src/test/java/org/tron/keystore/WalletSchemaValidationTest.java index 8f0c8f92213..c18899df3b7 100644 --- a/framework/src/test/java/org/tron/keystore/WalletSchemaValidationTest.java +++ b/framework/src/test/java/org/tron/keystore/WalletSchemaValidationTest.java @@ -126,9 +126,24 @@ public void testInvalidFixedLengthsAreRejectedBeforeKdf() { wallet = validWallet(false); wallet.getCrypto().setMac(hex(length)); assertRejected(wallet); - wallet = validWallet(false); - wallet.getCrypto().setCiphertext(hex(length)); - assertRejected(wallet); + } + } + + @Test + public void testCiphertextLengthBounds() throws Exception { + for (boolean pbkdf2 : new boolean[] {false, true}) { + for (String prefix : new String[] {"", "0x"}) { + for (int length : new int[] {0, 34, 35, 64}) { + WalletFile wallet = validWallet(pbkdf2); + wallet.getCrypto().setCiphertext(prefix + hex(length)); + assertRejected(wallet); + } + for (int length : new int[] {1, 31, 32, 33}) { + WalletFile wallet = validWallet(pbkdf2); + wallet.getCrypto().setCiphertext(prefix + hex(length)); + Wallet.validate(wallet); + } + } } } From 9b6228ec62a47f6b6edd9f67fbc24ccf8c4c1482 Mon Sep 17 00:00:00 2001 From: federico Date: Tue, 17 Nov 2026 17:04:03 +0800 Subject: [PATCH 13/33] fix(keystore): guard console errors and salt size --- .../main/java/org/tron/keystore/Wallet.java | 6 ++++ .../java/org/tron/keystore/WalletUtils.java | 11 ++++-- .../keystore/WalletSchemaValidationTest.java | 24 +++++++++++++ .../WalletUtilsInputPasswordTest.java | 35 +++++++++++++++++++ 4 files changed, 74 insertions(+), 2 deletions(-) diff --git a/crypto/src/main/java/org/tron/keystore/Wallet.java b/crypto/src/main/java/org/tron/keystore/Wallet.java index 4b7542d632c..b15722de20b 100644 --- a/crypto/src/main/java/org/tron/keystore/Wallet.java +++ b/crypto/src/main/java/org/tron/keystore/Wallet.java @@ -67,6 +67,7 @@ public class Wallet { private static final int SCRYPT_P_MAX = 8; private static final long SCRYPT_MEMORY_MAX_BYTES = 1L << 30; // 128 * r * n cap = 1 GiB private static final int KDF_DKLEN_MAX = 128; + private static final int KDF_SALT_MAX_BYTES = 1024; private static final int PBKDF2_C_MAX = 1 << 20; /** @@ -359,6 +360,11 @@ private static String validationError(WalletFile walletFile) { if (kdfParams == null) { return "Missing kdfparams"; } + String salt = kdfParams.getSalt(); + if (salt != null + && salt.length() > 2 * KDF_SALT_MAX_BYTES + (salt.startsWith("0x") ? 2 : 0)) { + return "KDF salt exceeds " + KDF_SALT_MAX_BYTES + " bytes"; + } if (SCRYPT.equals(kdf)) { if (!(kdfParams instanceof WalletFile.ScryptKdfParams)) { return "Scrypt KDF params are missing or malformed"; diff --git a/crypto/src/main/java/org/tron/keystore/WalletUtils.java b/crypto/src/main/java/org/tron/keystore/WalletUtils.java index a334503302e..bfbb8b467ff 100644 --- a/crypto/src/main/java/org/tron/keystore/WalletUtils.java +++ b/crypto/src/main/java/org/tron/keystore/WalletUtils.java @@ -281,8 +281,15 @@ private static Charset consoleCharset(Console console) throws IOException { return (Charset) Console.class.getMethod("charset").invoke(console); } catch (NoSuchMethodException e) { // On supported JDK 8 Linux/macOS runtimes Console uses the default charset. - String os = System.getProperty("os.name"); - return "Linux".equals(os) || "Mac OS X".equals(os) ? Charset.defaultCharset() : null; + try { + String os = System.getProperty("os.name"); + if ("Linux".equals(os) || "Mac OS X".equals(os)) { + return Charset.defaultCharset(); + } + return null; + } catch (SecurityException ex) { + throw new IOException("Cannot determine console encoding; use UTF-8 password input", ex); + } } catch (ReflectiveOperationException | SecurityException e) { throw new IOException("Cannot determine console encoding; use UTF-8 password input", e); } diff --git a/framework/src/test/java/org/tron/keystore/WalletSchemaValidationTest.java b/framework/src/test/java/org/tron/keystore/WalletSchemaValidationTest.java index c18899df3b7..33686cfa72a 100644 --- a/framework/src/test/java/org/tron/keystore/WalletSchemaValidationTest.java +++ b/framework/src/test/java/org/tron/keystore/WalletSchemaValidationTest.java @@ -147,6 +147,30 @@ public void testCiphertextLengthBounds() throws Exception { } } + @Test + public void testSaltLengthBounds() throws Exception { + for (boolean pbkdf2 : new boolean[] {false, true}) { + for (String prefix : new String[] {"", "0x"}) { + for (int length : new int[] {1, 32, 1023, 1024, 1025, 2048}) { + WalletFile wallet = validWallet(pbkdf2); + String salt = prefix + hex(length); + WalletFile.KdfParams params = wallet.getCrypto().getKdfparams(); + if (pbkdf2) { + ((WalletFile.Aes128CtrKdfParams) params).setSalt(salt); + } else { + ((WalletFile.ScryptKdfParams) params).setSalt(salt); + } + if (length <= 1024) { + Wallet.validate(wallet); + assertTrue(Wallet.isValidKeystoreFile(wallet)); + } else { + assertRejected(wallet); + } + } + } + } + } + @Test public void testInvalidAddressesAreRejectedBeforeKdf() { for (String address : new String[] {"T0", "../wallet", hex(64), diff --git a/framework/src/test/java/org/tron/keystore/WalletUtilsInputPasswordTest.java b/framework/src/test/java/org/tron/keystore/WalletUtilsInputPasswordTest.java index 7b1d82b1bdb..afb7e6c8084 100644 --- a/framework/src/test/java/org/tron/keystore/WalletUtilsInputPasswordTest.java +++ b/framework/src/test/java/org/tron/keystore/WalletUtilsInputPasswordTest.java @@ -3,8 +3,10 @@ import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -13,6 +15,7 @@ import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; +import java.security.Permission; import java.util.Arrays; import org.junit.After; import org.junit.Before; @@ -175,6 +178,38 @@ public void testConsoleReadRejectsAndClearsCorruptedPassword() { assertArrayEquals(new char[password.length], password); } + @Test + public void testConsoleReadClearsPasswordWhenOsPropertyDenied() { + assumeTrue("1.8".equals(System.getProperty("java.specification.version"))); + Console console = mock(Console.class); + char[] password = "secret password".toCharArray(); + when(console.readPassword("%s", "password: ")).thenReturn(password); + SecurityException denied = new SecurityException("os.name access denied"); + SecurityManager original = System.getSecurityManager(); + try { + System.setSecurityManager(new SecurityManager() { + @Override + public void checkPermission(Permission permission) { + // Only deny the property read under test. + } + + @Override + public void checkPropertyAccess(String key) { + if ("os.name".equals(key)) { + throw denied; + } + } + }); + + IOException error = assertThrows(IOException.class, + () -> WalletUtils.readConsolePassword(console, "password: ")); + assertSame(denied, error.getCause()); + assertArrayEquals(new char[password.length], password); + } finally { + System.setSecurityManager(original); + } + } + @Test public void testConsoleReadPreservesEof() throws Exception { Console console = mock(Console.class); From 3a3538d9d9f94d371bcbfa3b74bfd43a81fdabbe Mon Sep 17 00:00:00 2001 From: federico Date: Tue, 17 Nov 2026 23:35:45 +0800 Subject: [PATCH 14/33] fix(crypto): keep Miller loop points in homogeneous type --- .../common/crypto/zksnark/PairingCheck.java | 47 +++++++++++++++---- .../crypto/zksnark/PairingCheckTest.java | 27 +++++++++++ 2 files changed, 66 insertions(+), 8 deletions(-) create mode 100644 framework/src/test/java/org/tron/common/crypto/zksnark/PairingCheckTest.java diff --git a/crypto/src/main/java/org/tron/common/crypto/zksnark/PairingCheck.java b/crypto/src/main/java/org/tron/common/crypto/zksnark/PairingCheck.java index 3e91e141739..ca0d6179395 100644 --- a/crypto/src/main/java/org/tron/common/crypto/zksnark/PairingCheck.java +++ b/crypto/src/main/java/org/tron/common/crypto/zksnark/PairingCheck.java @@ -100,7 +100,7 @@ private static List calcEllCoeffs(BN128G2 base) { List coeffs = new ArrayList<>(); - BN128G2 addend = base; + G2Homogeneous addend = G2Homogeneous.fromAffine(base); // for each bit except most significant one for (int i = LOOP_COUNT.bitLength() - 2; i >= 0; i--) { @@ -132,7 +132,8 @@ private static List calcEllCoeffs(BN128G2 base) { return coeffs; } - private static Precomputed flippedMillerLoopMixedAddition(BN128G2 base, BN128G2 addend) { + private static Precomputed flippedMillerLoopMixedAddition(BN128G2 base, + G2Homogeneous addend) { Fp2 x1 = addend.x, y1 = addend.y, z1 = addend.z; Fp2 x2 = base.x, y2 = base.y; @@ -154,12 +155,12 @@ private static Precomputed flippedMillerLoopMixedAddition(BN128G2 base, BN128G2 Fp2 ellVW = d; // ell_VW = d return Precomputed.of( - new BN128G2(x3, y3, z3), + new G2Homogeneous(x3, y3, z3), new EllCoeffs(ell0, ellVW, ellVV) ); } - private static Precomputed flippedMillerLoopDoubling(BN128G2 g2) { + private static Precomputed flippedMillerLoopDoubling(G2Homogeneous g2) { Fp2 x = g2.x, y = g2.y, z = g2.z; @@ -184,7 +185,7 @@ private static Precomputed flippedMillerLoopDoubling(BN128G2 g2) { Fp2 ellVV = j.add(j).add(j); // ell_VV = 3 * j return Precomputed.of( - new BN128G2(rx, ry, rz), + new G2Homogeneous(rx, ry, rz), new EllCoeffs(ell0, ellVW, ellVV) ); } @@ -257,19 +258,49 @@ public int result() { static class Precomputed { - BN128G2 g2; + G2Homogeneous g2; EllCoeffs coeffs; - Precomputed(BN128G2 g2, EllCoeffs coeffs) { + Precomputed(G2Homogeneous g2, EllCoeffs coeffs) { this.g2 = g2; this.coeffs = coeffs; } - static Precomputed of(BN128G2 g2, EllCoeffs coeffs) { + static Precomputed of(G2Homogeneous g2, EllCoeffs coeffs) { return new Precomputed(g2, coeffs); } } + /** + * Running point of the flipped Miller loop, stored in homogeneous projective coordinates: the + * affine point it denotes is {@code (x / z, y / z)}. This differs from {@link BN128G2}, which is + * Jacobian ({@code (x / z^2, y / z^3)}), so the two must never be mixed. The type deliberately + * exposes no group operations. + */ + static final class G2Homogeneous { + + final Fp2 x; + final Fp2 y; + final Fp2 z; + + private G2Homogeneous(Fp2 x, Fp2 y, Fp2 z) { + this.x = x; + this.y = y; + this.z = z; + } + + /** + * Creates the running point from a curve point in affine coordinates, i.e. one with + * {@code z = 1}, where homogeneous and Jacobian coordinates agree. + */ + static G2Homogeneous fromAffine(BN128G2 p) { + if (!Fp2._1.equals(p.z)) { + throw new IllegalArgumentException("expected an affine point (z = 1)"); + } + return new G2Homogeneous(p.x, p.y, p.z); + } + } + static class Pair { BN128G1 g1; diff --git a/framework/src/test/java/org/tron/common/crypto/zksnark/PairingCheckTest.java b/framework/src/test/java/org/tron/common/crypto/zksnark/PairingCheckTest.java new file mode 100644 index 00000000000..f71ae33d9a4 --- /dev/null +++ b/framework/src/test/java/org/tron/common/crypto/zksnark/PairingCheckTest.java @@ -0,0 +1,27 @@ +package org.tron.common.crypto.zksnark; + +import java.math.BigInteger; +import org.junit.Assert; +import org.junit.Test; + +public class PairingCheckTest { + + @Test + public void testHomogeneousAcceptsAffinePoint() { + BN128G2 affine = new BN128G2(Fp2._1, Fp2._1, Fp2._1); + + PairingCheck.G2Homogeneous point = PairingCheck.G2Homogeneous.fromAffine(affine); + + Assert.assertEquals(Fp2._1, point.x); + Assert.assertEquals(Fp2._1, point.y); + Assert.assertEquals(Fp2._1, point.z); + } + + @Test(expected = IllegalArgumentException.class) + public void testHomogeneousRejectsJacobianPoint() { + BN128G2 nonAffine = + new BN128G2(Fp2._1, Fp2._1, Fp2.create(BigInteger.valueOf(2), BigInteger.ZERO)); + + PairingCheck.G2Homogeneous.fromAffine(nonAffine); + } +} From 64722ab8271fc6a9a56630a479e34c62edec2dab Mon Sep 17 00:00:00 2001 From: federico Date: Wed, 18 Nov 2026 00:01:33 +0800 Subject: [PATCH 15/33] fix(crypto): use BouncyCastle for provider-less jce helpers --- .../common/crypto/jce/ECKeyPairGenerator.java | 3 ++- .../common/crypto/jce/ECSignatureFactory.java | 3 ++- .../crypto/jce/TronCastleProviderTest.java | 20 +++++++++++++++++++ 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/crypto/src/main/java/org/tron/common/crypto/jce/ECKeyPairGenerator.java b/crypto/src/main/java/org/tron/common/crypto/jce/ECKeyPairGenerator.java index 61a5b90faec..cebce98cffa 100644 --- a/crypto/src/main/java/org/tron/common/crypto/jce/ECKeyPairGenerator.java +++ b/crypto/src/main/java/org/tron/common/crypto/jce/ECKeyPairGenerator.java @@ -82,7 +82,8 @@ private static class Holder { static { try { - INSTANCE = KeyPairGenerator.getInstance(ALGORITHM); + // SunEC dropped secp256k1 in JDK 16, so never fall back to the default provider. + INSTANCE = KeyPairGenerator.getInstance(ALGORITHM, TronCastleProvider.getInstance()); INSTANCE.initialize(SECP256K1_CURVE); } catch (NoSuchAlgorithmException ex) { throw new AssertionError(algorithmAssertionMsg, ex); diff --git a/crypto/src/main/java/org/tron/common/crypto/jce/ECSignatureFactory.java b/crypto/src/main/java/org/tron/common/crypto/jce/ECSignatureFactory.java index 9953e0ebf70..1dafb64d91f 100644 --- a/crypto/src/main/java/org/tron/common/crypto/jce/ECSignatureFactory.java +++ b/crypto/src/main/java/org/tron/common/crypto/jce/ECSignatureFactory.java @@ -35,7 +35,8 @@ private ECSignatureFactory() { public static Signature getRawInstance() { try { - return Signature.getInstance(RAW_ALGORITHM); + // SunEC dropped secp256k1 in JDK 16, so never fall back to the default provider. + return Signature.getInstance(RAW_ALGORITHM, TronCastleProvider.getInstance()); } catch (NoSuchAlgorithmException ex) { throw new AssertionError(rawAlgorithmAssertionMsg, ex); } diff --git a/framework/src/test/java/org/tron/common/crypto/jce/TronCastleProviderTest.java b/framework/src/test/java/org/tron/common/crypto/jce/TronCastleProviderTest.java index 81fd0e3b952..1f0a0a43643 100644 --- a/framework/src/test/java/org/tron/common/crypto/jce/TronCastleProviderTest.java +++ b/framework/src/test/java/org/tron/common/crypto/jce/TronCastleProviderTest.java @@ -6,14 +6,19 @@ import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; import java.net.URL; import java.net.URLClassLoader; +import java.security.KeyPair; import java.security.MessageDigest; import java.security.Provider; import java.security.SecureRandom; import java.security.Security; +import java.security.Signature; import java.util.Arrays; +import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey; +import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.util.encoders.Hex; import org.junit.Test; @@ -32,6 +37,21 @@ public void testNoRegisteredProvider() throws Exception { assertProviderIsolation(null); } + @Test + public void testKeyPairGenerationUsesTronCastleProvider() { + KeyPair keyPair = ECKeyPairGenerator.generateKeyPair(); + + assertTrue(keyPair.getPrivate() instanceof BCECPrivateKey); + assertTrue(keyPair.getPublic() instanceof BCECPublicKey); + } + + @Test + public void testRawSignatureUsesTronCastleProvider() { + Signature signature = ECSignatureFactory.getRawInstance(); + + assertSame(TronCastleProvider.getInstance(), signature.getProvider()); + } + private void assertProviderIsolation(Provider existing) throws Exception { Provider original = Security.getProvider("BC"); int position = Arrays.asList(Security.getProviders()).indexOf(original) + 1; From 0048edb57f74aac24d59f4e5a3ad1b2cdc50875c Mon Sep 17 00:00:00 2001 From: federico Date: Wed, 18 Nov 2026 00:08:41 +0800 Subject: [PATCH 16/33] fix(crypto): validate blake2f output buffer before compression --- .../common/crypto/Blake2bfMessageDigest.java | 5 +++ .../crypto/Blake2bfMessageDigestTest.java | 34 +++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 framework/src/test/java/org/tron/common/crypto/Blake2bfMessageDigestTest.java diff --git a/crypto/src/main/java/org/tron/common/crypto/Blake2bfMessageDigest.java b/crypto/src/main/java/org/tron/common/crypto/Blake2bfMessageDigest.java index d15ea5b2f56..7be0d7297d3 100644 --- a/crypto/src/main/java/org/tron/common/crypto/Blake2bfMessageDigest.java +++ b/crypto/src/main/java/org/tron/common/crypto/Blake2bfMessageDigest.java @@ -148,6 +148,11 @@ public int doFinal(final byte[] out, final int offset) { throw new IllegalStateException("The buffer must be filled with 213 bytes"); } + // Validate before compress() so a bad output buffer cannot leave the instance tainted. + if (out == null || offset < 0 || offset > out.length - DIGEST_LENGTH) { + throw new IllegalArgumentException("Output buffer too small for the digest"); + } + compress(); for (int i = 0; i < h.length; i++) { diff --git a/framework/src/test/java/org/tron/common/crypto/Blake2bfMessageDigestTest.java b/framework/src/test/java/org/tron/common/crypto/Blake2bfMessageDigestTest.java new file mode 100644 index 00000000000..4727580fb1b --- /dev/null +++ b/framework/src/test/java/org/tron/common/crypto/Blake2bfMessageDigestTest.java @@ -0,0 +1,34 @@ +package org.tron.common.crypto; + +import java.security.MessageDigest; +import org.junit.Assert; +import org.junit.Test; + +public class Blake2bfMessageDigestTest { + + @Test + public void testFailedDigestDoesNotTaintState() throws Exception { + byte[] input = new byte[Blake2bfMessageDigest.Blake2bfDigest.MESSAGE_LENGTH_BYTES]; + input[3] = 12; // rounds + input[212] = 1; // final block flag + + byte[] expected = digest(input); + + MessageDigest digest = new Blake2bfMessageDigest(); + digest.update(input); + try { + digest.digest(new byte[32], -32, 64); + Assert.fail("Expected the undersized output buffer to be rejected"); + } catch (IllegalArgumentException expectedFailure) { + // the output buffer is too small, so digesting must fail before touching the state + } + + Assert.assertArrayEquals(expected, digest.digest()); + } + + private byte[] digest(byte[] input) { + MessageDigest digest = new Blake2bfMessageDigest(); + digest.update(input); + return digest.digest(); + } +} From b94a35786e3fd09a42ebc866323e207efbc6a82a Mon Sep 17 00:00:00 2001 From: federico Date: Wed, 18 Nov 2026 11:10:06 +0800 Subject: [PATCH 17/33] fix(crypto): stop declaring blake2f digest cloneable --- .../org/tron/common/crypto/Blake2bfMessageDigest.java | 2 +- .../tron/common/crypto/Blake2bfMessageDigestTest.java | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/crypto/src/main/java/org/tron/common/crypto/Blake2bfMessageDigest.java b/crypto/src/main/java/org/tron/common/crypto/Blake2bfMessageDigest.java index 7be0d7297d3..66ed228d924 100644 --- a/crypto/src/main/java/org/tron/common/crypto/Blake2bfMessageDigest.java +++ b/crypto/src/main/java/org/tron/common/crypto/Blake2bfMessageDigest.java @@ -7,7 +7,7 @@ import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Pack; -public class Blake2bfMessageDigest extends BCMessageDigest implements Cloneable { +public class Blake2bfMessageDigest extends BCMessageDigest { public Blake2bfMessageDigest() { super(new Blake2bfDigest()); diff --git a/framework/src/test/java/org/tron/common/crypto/Blake2bfMessageDigestTest.java b/framework/src/test/java/org/tron/common/crypto/Blake2bfMessageDigestTest.java index 4727580fb1b..5f39e8f665e 100644 --- a/framework/src/test/java/org/tron/common/crypto/Blake2bfMessageDigestTest.java +++ b/framework/src/test/java/org/tron/common/crypto/Blake2bfMessageDigestTest.java @@ -26,6 +26,17 @@ public void testFailedDigestDoesNotTaintState() throws Exception { Assert.assertArrayEquals(expected, digest.digest()); } + @Test + public void testCloneIsNotSupported() throws Exception { + MessageDigest digest = new Blake2bfMessageDigest(); + try { + digest.clone(); + Assert.fail("Expected cloning to be unsupported"); + } catch (CloneNotSupportedException expectedFailure) { + // the digest deliberately does not implement Cloneable + } + } + private byte[] digest(byte[] input) { MessageDigest digest = new Blake2bfMessageDigest(); digest.update(input); From 2757b3f2bb2a6bca80794d857f38eccd1ba62fc0 Mon Sep 17 00:00:00 2001 From: federico Date: Wed, 18 Nov 2026 11:20:52 +0800 Subject: [PATCH 18/33] fix(crypto): honor offset in blake2f digest output --- .../common/crypto/Blake2bfMessageDigest.java | 2 +- .../crypto/Blake2bfMessageDigestTest.java | 24 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crypto/src/main/java/org/tron/common/crypto/Blake2bfMessageDigest.java b/crypto/src/main/java/org/tron/common/crypto/Blake2bfMessageDigest.java index 66ed228d924..127544f58ce 100644 --- a/crypto/src/main/java/org/tron/common/crypto/Blake2bfMessageDigest.java +++ b/crypto/src/main/java/org/tron/common/crypto/Blake2bfMessageDigest.java @@ -156,7 +156,7 @@ public int doFinal(final byte[] out, final int offset) { compress(); for (int i = 0; i < h.length; i++) { - System.arraycopy(Pack.longToLittleEndian(h[i]), 0, out, i * 8, 8); + System.arraycopy(Pack.longToLittleEndian(h[i]), 0, out, offset + i * 8, 8); } reset(); diff --git a/framework/src/test/java/org/tron/common/crypto/Blake2bfMessageDigestTest.java b/framework/src/test/java/org/tron/common/crypto/Blake2bfMessageDigestTest.java index 5f39e8f665e..ea76a214a16 100644 --- a/framework/src/test/java/org/tron/common/crypto/Blake2bfMessageDigestTest.java +++ b/framework/src/test/java/org/tron/common/crypto/Blake2bfMessageDigestTest.java @@ -1,6 +1,7 @@ package org.tron.common.crypto; import java.security.MessageDigest; +import java.util.Arrays; import org.junit.Assert; import org.junit.Test; @@ -26,6 +27,29 @@ public void testFailedDigestDoesNotTaintState() throws Exception { Assert.assertArrayEquals(expected, digest.digest()); } + @Test + public void testDigestHonorsOutputOffset() throws Exception { + byte[] input = new byte[Blake2bfMessageDigest.Blake2bfDigest.MESSAGE_LENGTH_BYTES]; + input[3] = 12; // rounds + input[212] = 1; // final block flag + byte[] expected = digest(input); + + int offset = 16; + byte[] out = new byte[offset + expected.length + 8]; + Arrays.fill(out, (byte) 0x5A); + + MessageDigest digest = new Blake2bfMessageDigest(); + digest.update(input); + + Assert.assertEquals(64, digest.digest(out, offset, 64)); + Assert.assertArrayEquals(expected, Arrays.copyOfRange(out, offset, offset + 64)); + for (int i = 0; i < out.length; i++) { + if (i < offset || i >= offset + 64) { + Assert.assertEquals(0x5A, out[i] & 0xFF); + } + } + } + @Test public void testCloneIsNotSupported() throws Exception { MessageDigest digest = new Blake2bfMessageDigest(); From d8b515228f94f774ebafce29e83adecc7d9e2f02 Mon Sep 17 00:00:00 2001 From: federico Date: Wed, 18 Nov 2026 11:38:46 +0800 Subject: [PATCH 19/33] fix(crypto): include recovery id in ECDSA signature equality --- .../main/java/org/tron/common/crypto/ECKey.java | 4 ++++ .../java/org/tron/common/crypto/ECKeyTest.java | 14 ++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/crypto/src/main/java/org/tron/common/crypto/ECKey.java b/crypto/src/main/java/org/tron/common/crypto/ECKey.java index 4a6e1f00a0a..9bd0d3db926 100644 --- a/crypto/src/main/java/org/tron/common/crypto/ECKey.java +++ b/crypto/src/main/java/org/tron/common/crypto/ECKey.java @@ -1007,6 +1007,9 @@ public boolean equals(Object o) { ECDSASignature signature = (ECDSASignature) o; + if (v != signature.v) { + return false; + } if (!r.equals(signature.r)) { return false; } @@ -1017,6 +1020,7 @@ public boolean equals(Object o) { public int hashCode() { int result = r.hashCode(); result = 31 * result + s.hashCode(); + result = 31 * result + (int) v; return result; } } diff --git a/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java b/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java index 984e3bc7e18..b0e3cb5495c 100644 --- a/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java +++ b/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java @@ -468,4 +468,18 @@ public void testNodeId() { assertEquals(key, ECKey.fromNodeId(key.getNodeId())); } + + @Test + public void testSignatureEqualityIncludesRecoveryId() { + byte[] r = BigInteger.ONE.toByteArray(); + byte[] s = BigInteger.valueOf(2).toByteArray(); + + ECDSASignature low = new ECDSASignature(r, s, (byte) 27); + ECDSASignature high = new ECDSASignature(r, s, (byte) 28); + + assertEquals(low, new ECDSASignature(r, s, (byte) 27)); + assertEquals(low.hashCode(), new ECDSASignature(r, s, (byte) 27).hashCode()); + assertNotEquals(low, high); + assertNotEquals(low.hashCode(), high.hashCode()); + } } From cd85109258e6c27baed10f69683ed9da5a391acd Mon Sep 17 00:00:00 2001 From: federico Date: Wed, 18 Nov 2026 11:56:44 +0800 Subject: [PATCH 20/33] fix(crypto): tolerate invalid recId candidates when signing --- .../main/java/org/tron/common/crypto/ECKey.java | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/crypto/src/main/java/org/tron/common/crypto/ECKey.java b/crypto/src/main/java/org/tron/common/crypto/ECKey.java index 9bd0d3db926..59c728994a3 100644 --- a/crypto/src/main/java/org/tron/common/crypto/ECKey.java +++ b/crypto/src/main/java/org/tron/common/crypto/ECKey.java @@ -816,7 +816,13 @@ public ECDSASignature sign(byte[] messageHash) { int recId = -1; byte[] thisKey = this.pub.getEncoded(/* compressed */ false); for (int i = 0; i < 4; i++) { - byte[] k = ECKey.recoverPubBytesFromSignature(i, sig, messageHash, true); + byte[] k; + try { + k = ECKey.recoverPubBytesFromSignature(i, sig, messageHash, true); + } catch (IllegalArgumentException e) { + // x = r + (i / 2) * n is not a valid curve point; try the next recId. + continue; + } if (k != null && Arrays.equals(k, thisKey)) { recId = i; break; @@ -826,6 +832,9 @@ public ECDSASignature sign(byte[] messageHash) { throw new RuntimeException("Could not construct a recoverable key" + ". This should never happen."); } + // recId 2 or 3 gives v = 29 or 30. It occurs only when n <= x(R) < p (probability about + // 2^-127.65) and is valid for transaction signatures; validateComponents restricts the + // precompile path to recIds 0 and 1. sig.v = (byte) (recId + 27); return sig; } @@ -927,6 +936,12 @@ public static ECDSASignature fromComponents(byte[] r, byte[] s, byte return signature; } + /** + * Validates signature components for the precompile path, which accepts only recovery ids 0 + * and 1 (v = 27 or 28). Transaction signatures may also use recovery ids 2 and 3 (v = 29 or + * 30) and are validated through {@link ECKey#signatureToKeyBytes(byte[], ECDSASignature, + * boolean)}. + */ public static boolean validateComponents(BigInteger r, BigInteger s, byte v) { From 92c10932b6709bb34dac2e0a13642e9c2086356b Mon Sep 17 00:00:00 2001 From: federico Date: Wed, 18 Nov 2026 14:03:52 +0800 Subject: [PATCH 21/33] fix(crypto): make missing private key an IllegalStateException --- crypto/src/main/java/org/tron/common/crypto/ECKey.java | 2 +- .../src/test/java/org/tron/common/crypto/ECKeyTest.java | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/crypto/src/main/java/org/tron/common/crypto/ECKey.java b/crypto/src/main/java/org/tron/common/crypto/ECKey.java index 59c728994a3..928cec4650a 100644 --- a/crypto/src/main/java/org/tron/common/crypto/ECKey.java +++ b/crypto/src/main/java/org/tron/common/crypto/ECKey.java @@ -1041,7 +1041,7 @@ public int hashCode() { } @SuppressWarnings("serial") - public static class MissingPrivateKeyException extends RuntimeException { + public static class MissingPrivateKeyException extends IllegalStateException { } diff --git a/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java b/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java index b0e3cb5495c..8c6da10ce7e 100644 --- a/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java +++ b/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java @@ -469,6 +469,14 @@ public void testNodeId() { assertEquals(key, ECKey.fromNodeId(key.getNodeId())); } + @Test + public void testMissingPrivateKeyIsIllegalStateException() { + ECKey publicOnly = ECKey.fromPublicOnly(pubKey); + + assertThrows(IllegalStateException.class, publicOnly::getPrivKey); + assertThrows(IllegalStateException.class, () -> publicOnly.sign(new byte[32])); + } + @Test public void testSignatureEqualityIncludesRecoveryId() { byte[] r = BigInteger.ONE.toByteArray(); From e3657d65567304fab50071648e4821a68d6aec34 Mon Sep 17 00:00:00 2001 From: federico Date: Wed, 18 Nov 2026 14:18:25 +0800 Subject: [PATCH 22/33] docs(crypto): document recovery exceptions in ECKey --- crypto/src/main/java/org/tron/common/crypto/ECKey.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/crypto/src/main/java/org/tron/common/crypto/ECKey.java b/crypto/src/main/java/org/tron/common/crypto/ECKey.java index 928cec4650a..6783a5d6a70 100644 --- a/crypto/src/main/java/org/tron/common/crypto/ECKey.java +++ b/crypto/src/main/java/org/tron/common/crypto/ECKey.java @@ -501,15 +501,14 @@ public static boolean isPubKeyCanonical(byte[] pubkey) { /** * Recovers the public key using SEC1v2 section 4.1.6. * - *

Replaces the three-argument overload; pass {@code false} for legacy recovery and rebuild - * downstream callers.

- * * @param recId recovery selector, from 0 to 3 * @param sig signature components * @param messageHash hash of the signed data - * @param strictValidation whether to enforce strict ECDSA validation; consensus callers use - * the applicable proposal state + * @param strictValidation whether to enforce strict ECDSA validation * @return encoded public key, or {@code null} if recovery is not possible + * @throws IllegalArgumentException if an argument is invalid or the candidate point is not on + * the curve + * @throws ArithmeticException if {@code r} is not invertible modulo the curve order */ @Nullable public static byte[] recoverPubBytesFromSignature(int recId, From 316f88e5ffb2cfcf23a6830a18640ee09940e239 Mon Sep 17 00:00:00 2001 From: federico Date: Wed, 18 Nov 2026 14:41:53 +0800 Subject: [PATCH 23/33] fix(crypto): validate public key format in computeAddress --- .../java/org/tron/common/crypto/Hash.java | 10 ++++++++++ .../org/tron/common/crypto/ECKeyTest.java | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/crypto/src/main/java/org/tron/common/crypto/Hash.java b/crypto/src/main/java/org/tron/common/crypto/Hash.java index 7af0f2c06fb..cfc23f0f38e 100644 --- a/crypto/src/main/java/org/tron/common/crypto/Hash.java +++ b/crypto/src/main/java/org/tron/common/crypto/Hash.java @@ -181,6 +181,16 @@ public static byte[] computeAddress(ECPoint pubPoint) { } public static byte[] computeAddress(byte[] pubBytes) { + if (pubBytes == null) { + throw new IllegalArgumentException("Public key must not be null"); + } + if (pubBytes.length == 1 && pubBytes[0] == 0) { + // Legacy signature recovery encodes the point at infinity as a single zero byte. + return sha3omit12(new byte[0]); + } + if (pubBytes.length != 65 || pubBytes[0] != 0x04) { + throw new IllegalArgumentException("Expected a 65-byte uncompressed public key"); + } return sha3omit12( Arrays.copyOfRange(pubBytes, 1, pubBytes.length)); } diff --git a/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java b/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java index 8c6da10ce7e..8dfcc203d1f 100644 --- a/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java +++ b/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java @@ -469,6 +469,25 @@ public void testNodeId() { assertEquals(key, ECKey.fromNodeId(key.getNodeId())); } + @Test + public void testComputeAddressRejectsMalformedPublicKey() { + assertThrows(IllegalArgumentException.class, () -> Hash.computeAddress(new byte[33])); + assertThrows(IllegalArgumentException.class, () -> Hash.computeAddress(new byte[65])); + + ECKey key = ECKey.fromPrivate(privateKey); + assertArrayEquals(key.getAddress(), Hash.computeAddress(key.getPubKey())); + } + + @Test + public void testLegacyPointAtInfinityAddressUnchanged() { + // The address derived from the Keccak-256 hash of the empty input, as documented before the + // change: legacy recovery encoded the point at infinity as the single byte 0x00. + byte[] expected = Hex.decode("41dcc703c0e500b653ca82273b7bfad8045d85a470"); + + assertArrayEquals(expected, Hash.computeAddress(new byte[]{0})); + assertArrayEquals(expected, Hash.sha3omit12(new byte[0])); + } + @Test public void testMissingPrivateKeyIsIllegalStateException() { ECKey publicOnly = ECKey.fromPublicOnly(pubKey); From a61724bc7668bcd616ef7b382e55a8a374b3f3af Mon Sep 17 00:00:00 2001 From: federico Date: Wed, 18 Nov 2026 14:58:18 +0800 Subject: [PATCH 24/33] fix(crypto): reject point at infinity in computeAddress --- crypto/src/main/java/org/tron/common/crypto/Hash.java | 4 ++++ .../src/test/java/org/tron/common/crypto/ECKeyTest.java | 8 ++++++++ 2 files changed, 12 insertions(+) diff --git a/crypto/src/main/java/org/tron/common/crypto/Hash.java b/crypto/src/main/java/org/tron/common/crypto/Hash.java index cfc23f0f38e..3c7b458a057 100644 --- a/crypto/src/main/java/org/tron/common/crypto/Hash.java +++ b/crypto/src/main/java/org/tron/common/crypto/Hash.java @@ -177,6 +177,10 @@ public static byte[] encodeElement(byte[] srcData) { } public static byte[] computeAddress(ECPoint pubPoint) { + if (pubPoint == null || pubPoint.isInfinity()) { + throw new IllegalArgumentException( + "Public key must not be null or the point at infinity"); + } return computeAddress(pubPoint.getEncoded(/* uncompressed */ false)); } diff --git a/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java b/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java index 8dfcc203d1f..2d5b0db5d13 100644 --- a/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java +++ b/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java @@ -17,6 +17,7 @@ import java.util.Arrays; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.asn1.sec.SECNamedCurves; +import org.bouncycastle.math.ec.ECPoint; import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.encoders.Hex; @@ -488,6 +489,13 @@ public void testLegacyPointAtInfinityAddressUnchanged() { assertArrayEquals(expected, Hash.sha3omit12(new byte[0])); } + @Test + public void testComputeAddressRejectsPointAtInfinity() { + assertThrows(IllegalArgumentException.class, + () -> Hash.computeAddress(ECKey.CURVE.getCurve().getInfinity())); + assertThrows(IllegalArgumentException.class, () -> Hash.computeAddress((ECPoint) null)); + } + @Test public void testMissingPrivateKeyIsIllegalStateException() { ECKey publicOnly = ECKey.fromPublicOnly(pubKey); From aa73cc6df3d01fc7cfd8d1320debd2c2574791e5 Mon Sep 17 00:00:00 2001 From: federico Date: Wed, 18 Nov 2026 15:13:27 +0800 Subject: [PATCH 25/33] fix(crypto): correct Fp2 representation and toString --- crypto/src/main/java/org/tron/common/crypto/zksnark/Fp2.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp2.java b/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp2.java index 162a5b13b30..0255caeda1f 100644 --- a/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp2.java +++ b/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp2.java @@ -23,7 +23,7 @@ * Arithmetic in F_p2

* * "p" equals 21888242871839275222246405745257275088696311157297823662689037894645226208583, - * elements of F_p2 are represented as a polynomials "a * i + b" modulo "i^2 + 1" from the ring + * elements of F_p2 are represented as polynomials "a + b * i" modulo "i^2 + 1" from the ring * F_p[i]

* * Field arithmetic is ported from libff @@ -181,6 +181,6 @@ Fp2 mulByNonResidue() { @Override public String toString() { - return String.format("%si + %s", a.toString(), b.toString()); + return String.format("%s + %si", a.toString(), b.toString()); } } From 342ed30e5386ef089a55dfc76b15c6c0bf20d71c Mon Sep 17 00:00:00 2001 From: federico Date: Wed, 18 Nov 2026 15:14:36 +0800 Subject: [PATCH 26/33] perf(crypto): specialize Fp2 arithmetic --- .../java/org/tron/common/crypto/zksnark/Fp2.java | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp2.java b/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp2.java index 0255caeda1f..0eaf8aa1f81 100644 --- a/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp2.java +++ b/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp2.java @@ -79,9 +79,7 @@ public Fp2 squared() { Fp ab = a.mul(b); - Fp ra = a.add(b).mul(b.mul(Fp.NON_RESIDUE).add(a)) - .sub(ab) - .sub(ab.mul(Fp.NON_RESIDUE)); // ra = (a + b)(a + NON_RESIDUE * b) - ab - NON_RESIDUE * b + Fp ra = a.add(b).mul(a.sub(b)); // i^2 = -1, so ra = a^2 - b^2 Fp rb = ab.dbl(); return new Fp2(ra, rb); @@ -93,7 +91,7 @@ public Fp2 mul(Fp2 o) { Fp aa = a.mul(o.a); Fp bb = b.mul(o.b); - Fp ra = bb.mul(Fp.NON_RESIDUE).add(aa); // ra = a1 * a2 + NON_RESIDUE * b1 * b2 + Fp ra = aa.sub(bb); // ra = a1 * a2 - b1 * b2 Fp rb = a.add(b).mul(o.a.add(o.b)).sub(aa) .sub(bb); // rb = (a1 + b1)(a2 + b2) - a1 * a2 - b1 * b2 @@ -120,7 +118,7 @@ public Fp2 inverse() { Fp t0 = a.squared(); Fp t1 = b.squared(); - Fp t2 = t0.sub(Fp.NON_RESIDUE.mul(t1)); + Fp t2 = t0.add(t1); Fp t3 = t2.inverse(); Fp ra = a.mul(t3); // ra = a * t3 @@ -176,7 +174,10 @@ Fp2 frobeniusMap(int power) { } Fp2 mulByNonResidue() { - return NON_RESIDUE.mul(this); + // (a + bi)(9 + i) = (9a - b) + (a + 9b)i + Fp a9 = a.dbl().dbl().dbl().add(a); + Fp b9 = b.dbl().dbl().dbl().add(b); + return new Fp2(a9.sub(b), a.add(b9)); } @Override From c61e533f50db0450374fdb595abac16b9703a954 Mon Sep 17 00:00:00 2001 From: federico Date: Wed, 18 Nov 2026 15:16:07 +0800 Subject: [PATCH 27/33] refactor(crypto): unify zksnark non-residue definitions --- .../java/org/tron/common/crypto/zksnark/Fp.java | 1 + .../org/tron/common/crypto/zksnark/Fp12.java | 16 ++++++++-------- .../java/org/tron/common/crypto/zksnark/Fp2.java | 2 ++ .../java/org/tron/common/crypto/zksnark/Fp6.java | 4 ++-- 4 files changed, 13 insertions(+), 10 deletions(-) diff --git a/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp.java b/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp.java index 768a23e4fda..203491a1094 100644 --- a/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp.java +++ b/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp.java @@ -32,6 +32,7 @@ public class Fp implements Field { static final Fp ZERO = new Fp(BigInteger.ZERO); static final Fp _1 = new Fp(BigInteger.ONE); + // beta = -1 defines the next extension Fp2, where i^2 = beta. static final Fp NON_RESIDUE = new Fp(new BigInteger( "21888242871839275222246405745257275088696311157297823662689037894645226208582")); diff --git a/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp12.java b/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp12.java index 8733d2297fb..1f4c4d8fd60 100644 --- a/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp12.java +++ b/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp12.java @@ -136,14 +136,14 @@ Fp12 mulBy024(Fp2 ell0, Fp2 ellVW, Fp2 ellVV) { // For z.a_.a_ = z0. s1 = z1.mul(x2); t3 = s1.add(d4); - t4 = Fp6.NON_RESIDUE.mul(t3).add(d0); + t4 = t3.mulByNonResidue().add(d0); z0 = t4; // For z.a_.b_ = z1 t3 = z5.mul(x4); s1 = s1.add(t3); t3 = t3.add(d2); - t4 = Fp6.NON_RESIDUE.mul(t3); + t4 = t3.mulByNonResidue(); t3 = z1.mul(x0); s1 = s1.add(t3); t4 = t4.add(t3); @@ -161,7 +161,7 @@ Fp12 mulBy024(Fp2 ell0, Fp2 ellVW, Fp2 ellVV) { z2 = t3; t1 = x2.add(x4); t3 = t0.mul(t1).sub(d2).sub(d4); - t4 = Fp6.NON_RESIDUE.mul(t3); + t4 = t3.mulByNonResidue(); t3 = z3.mul(x0); s1 = s1.add(t3); t4 = t4.add(t3); @@ -170,7 +170,7 @@ Fp12 mulBy024(Fp2 ell0, Fp2 ellVW, Fp2 ellVV) { // For z.b_.b_ = z4 t3 = z5.mul(x2); s1 = s1.add(t3); - t4 = Fp6.NON_RESIDUE.mul(t3); + t4 = t3.mulByNonResidue(); t0 = x0.add(x4); t3 = t2.mul(t0).sub(d0).sub(d4); t4 = t4.add(t3); @@ -259,15 +259,15 @@ Fp12 cyclotomicSquared() { // t0 + t1*y = (z0 + z1*y)^2 = a^2 tmp = z0.mul(z1); - t0 = z0.add(z1).mul(z0.add(Fp6.NON_RESIDUE.mul(z1))).sub(tmp).sub(Fp6.NON_RESIDUE.mul(tmp)); + t0 = z0.add(z1).mul(z0.add(z1.mulByNonResidue())).sub(tmp).sub(tmp.mulByNonResidue()); t1 = tmp.add(tmp); // t2 + t3*y = (z2 + z3*y)^2 = b^2 tmp = z2.mul(z3); - t2 = z2.add(z3).mul(z2.add(Fp6.NON_RESIDUE.mul(z3))).sub(tmp).sub(Fp6.NON_RESIDUE.mul(tmp)); + t2 = z2.add(z3).mul(z2.add(z3.mulByNonResidue())).sub(tmp).sub(tmp.mulByNonResidue()); t3 = tmp.add(tmp); // t4 + t5*y = (z4 + z5*y)^2 = c^2 tmp = z4.mul(z5); - t4 = z4.add(z5).mul(z4.add(Fp6.NON_RESIDUE.mul(z5))).sub(tmp).sub(Fp6.NON_RESIDUE.mul(tmp)); + t4 = z4.add(z5).mul(z4.add(z5.mulByNonResidue())).sub(tmp).sub(tmp.mulByNonResidue()); t5 = tmp.add(tmp); // for A @@ -284,7 +284,7 @@ Fp12 cyclotomicSquared() { // for B // z2 = 3 * (xi * t5) + 2 * z2 - tmp = Fp6.NON_RESIDUE.mul(t5); + tmp = t5.mulByNonResidue(); z2 = tmp.add(z2); z2 = z2.add(z2); z2 = z2.add(tmp); diff --git a/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp2.java b/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp2.java index 0eaf8aa1f81..641cf2a643c 100644 --- a/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp2.java +++ b/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp2.java @@ -36,6 +36,7 @@ class Fp2 implements Field { static final Fp2 ZERO = new Fp2(Fp.ZERO, Fp.ZERO); static final Fp2 _1 = new Fp2(Fp._1, Fp.ZERO); + // xi = 9 + i defines the next extension Fp6, where v^3 = xi. static final Fp2 NON_RESIDUE = new Fp2(BigInteger.valueOf(9), BigInteger.ONE); static final Fp[] FROBENIUS_COEFFS_B = new Fp[]{ @@ -173,6 +174,7 @@ Fp2 frobeniusMap(int power) { return new Fp2(ra, rb); } + /** Multiplies this Fp2 element by xi = 9 + i, the defining parameter of Fp6. */ Fp2 mulByNonResidue() { // (a + bi)(9 + i) = (9a - b) + (a + 9b)i Fp a9 = a.dbl().dbl().dbl().add(a); diff --git a/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp6.java b/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp6.java index fb863bb6b34..7a1e1749783 100644 --- a/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp6.java +++ b/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp6.java @@ -34,7 +34,6 @@ class Fp6 implements Field { static final Fp6 ZERO = new Fp6(Fp2.ZERO, Fp2.ZERO, Fp2.ZERO); static final Fp6 _1 = new Fp6(Fp2._1, Fp2.ZERO, Fp2.ZERO); - static final Fp2 NON_RESIDUE = new Fp2(BigInteger.valueOf(9), BigInteger.ONE); static final Fp2[] FROBENIUS_COEFFS_B = { new Fp2(BigInteger.ONE, @@ -148,9 +147,10 @@ Fp6 mul(Fp2 o) { return new Fp6(ra, rb, rc); } + /** Multiplies by v, where v^3 = Fp2.NON_RESIDUE and Fp12 is defined by w^2 = v. */ Fp6 mulByNonResidue() { - Fp2 ra = NON_RESIDUE.mul(c); + Fp2 ra = c.mulByNonResidue(); Fp2 rb = a; Fp2 rc = b; From 52de7b8a4cf190bb8601d713796ff89a138b9b22 Mon Sep 17 00:00:00 2001 From: federico Date: Wed, 18 Nov 2026 15:17:44 +0800 Subject: [PATCH 28/33] perf(crypto): use endomorphism for G2 subgroup check --- .../tron/common/crypto/zksnark/BN128G2.java | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/crypto/src/main/java/org/tron/common/crypto/zksnark/BN128G2.java b/crypto/src/main/java/org/tron/common/crypto/zksnark/BN128G2.java index cfa514bde9b..36247145737 100644 --- a/crypto/src/main/java/org/tron/common/crypto/zksnark/BN128G2.java +++ b/crypto/src/main/java/org/tron/common/crypto/zksnark/BN128G2.java @@ -17,12 +17,10 @@ */ package org.tron.common.crypto.zksnark; -import static org.tron.common.crypto.zksnark.Params.R; +import static org.tron.common.crypto.zksnark.Params.PAIRING_FINAL_EXPONENT_Z; import static org.tron.common.crypto.zksnark.Params.TWIST_MUL_BY_P_X; import static org.tron.common.crypto.zksnark.Params.TWIST_MUL_BY_P_Y; -import java.math.BigInteger; - /** * Implementation of specific cyclic subgroup of points belonging to {@link BN128Fp2}
Members * of this subgroup are passed as a second param to pairing input {@link @@ -39,8 +37,6 @@ */ public class BN128G2 extends BN128Fp2 { - static final BigInteger FR_NEG_ONE = BigInteger.ONE.negate().mod(R); - BN128G2(BN128 p) { super(p.x, p.y, p.z); } @@ -71,8 +67,20 @@ public static BN128G2 create(byte[] a, byte[] b, byte[] c, byte[] d) { } private static boolean isGroupMember(BN128 p) { - BN128 left = p.mul(FR_NEG_ONE).add(p); - return left.isZero(); // should satisfy condition: -1 * p + p == 0, where -1 belongs to F_r + if (p.isZero()) { + return true; + } + // For this BN curve, [r]P = O iff [z+1]P + psi([z]P) + psi^2([z]P) + // equals psi^3([2z]P), where psi is mulByP and z is the 63-bit BN seed. + // See https://eprint.iacr.org/2022/348, Sections 3 and 5.1. + BN128G2 zp = new BN128G2(p.mul(PAIRING_FINAL_EXPONENT_Z)); + BN128G2 a = zp.mulByP(); + BN128G2 b = a.mulByP(); + BN128G2 c = b.mulByP(); + BN128 left = zp.add(p).add(a).add(b); + BN128 right = c.add(c); + // equals() compares raw Jacobian coordinates, so compare points by subtraction. + return left.add(new BN128G2(right.x, right.y.negate(), right.z)).isZero(); } @Override From 8d49862b57d80ba28a4397eb75b1140ca6ffbeb4 Mon Sep 17 00:00:00 2001 From: federico Date: Wed, 18 Nov 2026 15:33:52 +0800 Subject: [PATCH 29/33] fix(crypto): reject negative scalars in BN128.mul --- .../java/org/tron/common/crypto/zksnark/BN128.java | 6 +++++- .../java/org/tron/common/crypto/zksnark/FpTest.java | 10 ++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/crypto/src/main/java/org/tron/common/crypto/zksnark/BN128.java b/crypto/src/main/java/org/tron/common/crypto/zksnark/BN128.java index 516b72e4831..a91c7fce5c9 100644 --- a/crypto/src/main/java/org/tron/common/crypto/zksnark/BN128.java +++ b/crypto/src/main/java/org/tron/common/crypto/zksnark/BN128.java @@ -161,7 +161,11 @@ public BN128 add(BN128 o) { public BN128 mul(BigInteger s) { - if (s.compareTo(BigInteger.ZERO) == 0) // P * 0 = 0 + if (s.signum() < 0) { + throw new IllegalArgumentException("Scalar must be non-negative"); + } + + if (s.signum() == 0) // P * 0 = 0 { return zero(); } diff --git a/framework/src/test/java/org/tron/common/crypto/zksnark/FpTest.java b/framework/src/test/java/org/tron/common/crypto/zksnark/FpTest.java index a99b10bb1e6..3d760afb71d 100644 --- a/framework/src/test/java/org/tron/common/crypto/zksnark/FpTest.java +++ b/framework/src/test/java/org/tron/common/crypto/zksnark/FpTest.java @@ -87,6 +87,16 @@ public void testRejectsOutOfRangeCoordinates() { Assert.assertNull(BN128Fp.create(one, outOfRange)); } + @Test + public void testMulRejectsNegativeScalar() { + BN128 point = BN128Fp.create(BigInteger.ONE.toByteArray(), + BigInteger.valueOf(2).toByteArray()); + Assert.assertNotNull(point); + + Assert.assertThrows(IllegalArgumentException.class, + () -> point.mul(BigInteger.valueOf(-1))); + } + private void assertInitializesWithoutCurveParameters(String name) throws Exception { URL location = Fp.class.getProtectionDomain().getCodeSource().getLocation(); // A fresh loader exercises first use even if another test already initialized these classes. From 04d35bfb09b20a62f70bec1deae7f6f6e9054f50 Mon Sep 17 00:00:00 2001 From: federico Date: Wed, 18 Nov 2026 15:58:27 +0800 Subject: [PATCH 30/33] fix(crypto): address review comments --- .../java/org/tron/common/crypto/ECKey.java | 3 +- .../java/org/tron/keystore/WalletUtils.java | 28 ++- .../org/tron/common/crypto/ECKeyTest.java | 1 - .../crypto/jce/TronCastleProviderTest.java | 12 +- .../common/crypto/zksnark/BN128G2Test.java | 162 ++++++++++++++++++ .../java/org/tron/core/db/ManagerTest.java | 4 +- .../tron/keystore/WalletUtilsWriteTest.java | 55 ++++-- 7 files changed, 239 insertions(+), 26 deletions(-) create mode 100644 framework/src/test/java/org/tron/common/crypto/zksnark/BN128G2Test.java diff --git a/crypto/src/main/java/org/tron/common/crypto/ECKey.java b/crypto/src/main/java/org/tron/common/crypto/ECKey.java index 6783a5d6a70..4086baf111a 100644 --- a/crypto/src/main/java/org/tron/common/crypto/ECKey.java +++ b/crypto/src/main/java/org/tron/common/crypto/ECKey.java @@ -508,7 +508,8 @@ public static boolean isPubKeyCanonical(byte[] pubkey) { * @return encoded public key, or {@code null} if recovery is not possible * @throws IllegalArgumentException if an argument is invalid or the candidate point is not on * the curve - * @throws ArithmeticException if {@code r} is not invertible modulo the curve order + * @throws ArithmeticException if {@code r} is not invertible modulo the curve order when + * strict validation is disabled */ @Nullable public static byte[] recoverPubBytesFromSignature(int recId, diff --git a/crypto/src/main/java/org/tron/keystore/WalletUtils.java b/crypto/src/main/java/org/tron/keystore/WalletUtils.java index bfbb8b467ff..5e1439fba28 100644 --- a/crypto/src/main/java/org/tron/keystore/WalletUtils.java +++ b/crypto/src/main/java/org/tron/keystore/WalletUtils.java @@ -26,9 +26,11 @@ import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; +import java.util.List; import java.util.NoSuchElementException; import java.util.Scanner; import java.util.Set; @@ -77,10 +79,11 @@ public static String generateWalletFile( /** * Write a WalletFile to the given destination path with owner-only (0600) * permissions, using a temp file + atomic rename. - * The temporary file is synced before replacement, then the destination directory - * and its ancestors are synced to persist newly created directory entries too. - * Directory syncing requires filesystem support. A sync failure after replacement - * is reported to the caller, but does not roll back the replacement. + * The temporary file is synced before replacement, then the destination directory and + * the directories whose entries this call created are synced to persist them. Existing + * ancestors above the first pre-existing directory are not opened, so they do not need + * read permission. Directory syncing requires filesystem support. A sync failure after + * replacement is reported to the caller, but does not roll back the replacement. * *

The temporary file is atomically created with 0600 permissions and written * through the same channel, without reopening its path. Filesystems that cannot @@ -97,6 +100,16 @@ public static String generateWalletFile( public static void writeWalletFile(WalletFile walletFile, File destination) throws IOException { Path dir = destination.getAbsoluteFile().getParentFile().toPath(); + // Sync the destination directory and only the ancestors whose entries this call + // (re)creates. Existing ancestors above the first pre-existing directory are not + // opened, so they do not need read permission. + List dirsToSync = new ArrayList<>(); + for (Path current = dir; current != null; current = current.getParent()) { + dirsToSync.add(current); + if (Files.exists(current)) { + break; + } + } Files.createDirectories(dir); Path tmp = dir.resolve("keystore-" + UUID.randomUUID() + ".tmp"); @@ -120,10 +133,9 @@ public static void writeWalletFile(WalletFile walletFile, File destination) Files.move(tmp, destination.toPath(), StandardCopyOption.REPLACE_EXISTING); } try { - // Callers may have just created the directory, so sync the whole ancestor chain. - // Resolve symlinks to sync the actual directory hierarchy containing the file. - for (Path current = dir.toRealPath(); current != null; current = current.getParent()) { - try (FileChannel directory = FileChannel.open(current, StandardOpenOption.READ)) { + for (Path current : dirsToSync) { + try (FileChannel directory = FileChannel.open(current.toRealPath(), + StandardOpenOption.READ)) { directory.force(true); } } diff --git a/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java b/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java index 2d5b0db5d13..9fbe894bfee 100644 --- a/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java +++ b/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java @@ -515,6 +515,5 @@ public void testSignatureEqualityIncludesRecoveryId() { assertEquals(low, new ECDSASignature(r, s, (byte) 27)); assertEquals(low.hashCode(), new ECDSASignature(r, s, (byte) 27).hashCode()); assertNotEquals(low, high); - assertNotEquals(low.hashCode(), high.hashCode()); } } diff --git a/framework/src/test/java/org/tron/common/crypto/jce/TronCastleProviderTest.java b/framework/src/test/java/org/tron/common/crypto/jce/TronCastleProviderTest.java index 1f0a0a43643..e18dc7c6742 100644 --- a/framework/src/test/java/org/tron/common/crypto/jce/TronCastleProviderTest.java +++ b/framework/src/test/java/org/tron/common/crypto/jce/TronCastleProviderTest.java @@ -8,9 +8,11 @@ import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; +import java.lang.reflect.Field; import java.net.URL; import java.net.URLClassLoader; import java.security.KeyPair; +import java.security.KeyPairGenerator; import java.security.MessageDigest; import java.security.Provider; import java.security.SecureRandom; @@ -38,11 +40,19 @@ public void testNoRegisteredProvider() throws Exception { } @Test - public void testKeyPairGenerationUsesTronCastleProvider() { + public void testKeyPairGenerationUsesTronCastleProvider() throws Exception { KeyPair keyPair = ECKeyPairGenerator.generateKeyPair(); assertTrue(keyPair.getPrivate() instanceof BCECPrivateKey); assertTrue(keyPair.getPublic() instanceof BCECPublicKey); + + // Assert the generator itself was created with TronCastleProvider, not a globally + // registered Bouncy Castle provider. + Class holder = Class.forName(ECKeyPairGenerator.class.getName() + "$Holder"); + Field instance = holder.getDeclaredField("INSTANCE"); + instance.setAccessible(true); + assertSame(TronCastleProvider.getInstance(), + ((KeyPairGenerator) instance.get(null)).getProvider()); } @Test diff --git a/framework/src/test/java/org/tron/common/crypto/zksnark/BN128G2Test.java b/framework/src/test/java/org/tron/common/crypto/zksnark/BN128G2Test.java new file mode 100644 index 00000000000..65ec31ef9d3 --- /dev/null +++ b/framework/src/test/java/org/tron/common/crypto/zksnark/BN128G2Test.java @@ -0,0 +1,162 @@ +package org.tron.common.crypto.zksnark; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.lang.reflect.Method; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; +import org.junit.Test; + +/** + * Verifies the G2 subgroup acceptance rule used when decoding pairing inputs. The private + * predicate is compared against the full-order oracle {@code [r]P = O} for affine, projective, + * infinity, and non-subgroup points. + */ +public class BN128G2Test { + + private static final BigInteger TWO = BigInteger.valueOf(2); + private static final BigInteger P = Params.P; + private static final BigInteger SQRT_EXPONENT = P.add(BigInteger.ONE).shiftRight(2); + + // Standard alt_bn128 G2 generator, with Fp2 elements represented as a + b * i. + private static final BigInteger G2_X_A = new BigInteger( + "10857046999023057135944570762232829481370756359578518086990519993285655852781"); + private static final BigInteger G2_X_B = new BigInteger( + "11559732032986387107991004021392285783925812861821192530917403151452391805634"); + private static final BigInteger G2_Y_A = new BigInteger( + "8495653923123431417604973247489272438418190587263600148770280649306958101930"); + private static final BigInteger G2_Y_B = new BigInteger( + "4082367875863433681332203403145435568316851327593401208105741076214120093531"); + + @Test + public void testInfinityIsGroupMember() { + assertNotNull(BN128G2.create(bytes(0), bytes(0), bytes(0), bytes(0))); + } + + @Test + public void testGeneratorIsGroupMember() { + assertNotNull(createG2(G2_X_A, G2_X_B, G2_Y_A, G2_Y_B)); + } + + @Test + public void testPredicateMatchesFullOrderMultiplication() throws Exception { + List> points = new ArrayList<>(); + BN128 generator = createAffine(G2_X_A, G2_X_B, G2_Y_A, G2_Y_B); + assertNotNull(generator); + points.add(generator); + points.addAll(curvePoints(6)); + + boolean sawNonSubgroup = false; + for (BN128 point : points) { + boolean inSubgroup = point.mul(Params.R).isZero(); + assertEquals("predicate disagrees with [r]P = O for " + point, + inSubgroup, isGroupMember(point)); + + BN128G2 accepted = createG2( + new BigInteger(1, point.x.a.bytes()), new BigInteger(1, point.x.b.bytes()), + new BigInteger(1, point.y.a.bytes()), new BigInteger(1, point.y.b.bytes())); + assertEquals("[r]P = O disagrees with create() for " + point, inSubgroup, accepted != null); + + if (!inSubgroup) { + sawNonSubgroup = true; + } + } + assertTrue("expected at least one non-subgroup point", sawNonSubgroup); + } + + @Test + public void testPredicateMatchesFullOrderForProjectiveInputs() throws Exception { + BN128 generator = createAffine(G2_X_A, G2_X_B, G2_Y_A, G2_Y_B); + assertNotNull(generator); + for (int k = 1; k <= 4; k++) { + BN128 point = generator.mul(BigInteger.valueOf(k)); + assertEquals("projective input " + k, + point.mul(Params.R).isZero(), isGroupMember(point)); + } + } + + private static BN128G2 createG2(BigInteger xa, BigInteger xb, BigInteger ya, BigInteger yb) { + return BN128G2.create(xa.toByteArray(), xb.toByteArray(), ya.toByteArray(), yb.toByteArray()); + } + + private static BN128 createAffine(BigInteger xa, BigInteger xb, BigInteger ya, + BigInteger yb) { + return BN128Fp2.create(xa.toByteArray(), xb.toByteArray(), ya.toByteArray(), yb.toByteArray()); + } + + private static boolean isGroupMember(BN128 point) throws Exception { + Method method = BN128G2.class.getDeclaredMethod("isGroupMember", BN128.class); + method.setAccessible(true); + return (Boolean) method.invoke(null, point); + } + + /** + * Returns ordinary twist points that are on the curve but, with overwhelming probability, + * outside the order-r subgroup. + */ + private static List> curvePoints(int limit) { + List> points = new ArrayList<>(); + for (int i = 1; i <= 500 && points.size() < limit; i++) { + Fp2 x = new Fp2(BigInteger.valueOf(i), BigInteger.ZERO); + Fp2 rhs = x.squared().mul(x).add(Params.B_Fp2); + Fp2 y = sqrt(rhs); + if (y == null || !y.squared().equals(rhs)) { + continue; + } + BN128 point = BN128Fp2.create(x.a.bytes(), x.b.bytes(), y.a.bytes(), y.b.bytes()); + if (point != null && !point.isZero()) { + points.add(point); + } + } + return points; + } + + /** Computes a square root in Fp2, or null when the value is not a square. */ + private static Fp2 sqrt(Fp2 value) { + BigInteger a = new BigInteger(1, value.a.bytes()); + BigInteger b = new BigInteger(1, value.b.bytes()); + BigInteger norm = a.multiply(a).add(b.multiply(b)).mod(P); + BigInteger c = sqrtFp(norm); + if (c == null) { + return null; + } + Fp2 result = sqrtWith(value, c); + return result != null ? result : sqrtWith(value, c.negate().mod(P)); + } + + private static Fp2 sqrtWith(Fp2 value, BigInteger c) { + BigInteger a = new BigInteger(1, value.a.bytes()); + BigInteger b = new BigInteger(1, value.b.bytes()); + BigInteger twoInv = TWO.modInverse(P); + BigInteger realRoot = sqrtFp(a.add(c).multiply(twoInv).mod(P)); + BigInteger imagRoot = sqrtFp(c.subtract(a).multiply(twoInv).mod(P)); + if (realRoot == null || imagRoot == null) { + return null; + } + BigInteger imaginary = realRoot.multiply(imagRoot).shiftLeft(1).mod(P); + if (imaginary.equals(b.mod(P))) { + return new Fp2(new Fp(realRoot), new Fp(imagRoot)); + } + if (imaginary.negate().mod(P).equals(b.mod(P))) { + return new Fp2(new Fp(realRoot), new Fp(imagRoot.negate().mod(P))); + } + return null; + } + + /** Square root in Fp for p = 3 (mod 4), or null when the value is not a square. */ + private static BigInteger sqrtFp(BigInteger value) { + BigInteger v = value.mod(P); + if (v.signum() == 0) { + return BigInteger.ZERO; + } + BigInteger root = v.modPow(SQRT_EXPONENT, P); + return root.multiply(root).mod(P).equals(v) ? root : null; + } + + private static byte[] bytes(long value) { + return BigInteger.valueOf(value).toByteArray(); + } +} diff --git a/framework/src/test/java/org/tron/core/db/ManagerTest.java b/framework/src/test/java/org/tron/core/db/ManagerTest.java index fb21935552a..bfa01e0a939 100755 --- a/framework/src/test/java/org/tron/core/db/ManagerTest.java +++ b/framework/src/test/java/org/tron/core/db/ManagerTest.java @@ -615,7 +615,7 @@ public void pushSwitchFork() .put(addressByte.toByteArray(), accountCapsule); WitnessCapsule sr1 = new WitnessCapsule( - ByteString.copyFrom(address), "www.tron.net/first"); + ByteString.copyFrom(ecKey.getPubKey()), "www.tron.net/first"); sr1.setVoteCount(1000000000L); @@ -623,7 +623,7 @@ public void pushSwitchFork() final ECKey ecKey2 = ECKey.fromPrivate(privateKey2); byte[] address2 = ecKey2.getAddress(); WitnessCapsule sr2 = new WitnessCapsule( - ByteString.copyFrom(address2), "www.tron.net/second"); + ByteString.copyFrom(ecKey2.getPubKey()), "www.tron.net/second"); sr2.setVoteCount(100000L); chainManager.getWitnessStore().put(address, sr1); WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(address)); diff --git a/framework/src/test/java/org/tron/keystore/WalletUtilsWriteTest.java b/framework/src/test/java/org/tron/keystore/WalletUtilsWriteTest.java index b1997fab7b4..153396bfd8d 100644 --- a/framework/src/test/java/org/tron/keystore/WalletUtilsWriteTest.java +++ b/framework/src/test/java/org/tron/keystore/WalletUtilsWriteTest.java @@ -235,34 +235,63 @@ public void testDirectorySyncFailureReportsCompletedReplacement() throws Excepti } @Test - public void testAncestorSyncFailureIsNotIgnored() throws Exception { - File base = tempFolder.newFolder("ancestor-sync-fail"); - File destination = new File(base, "a/b/c/wallet.json"); - // Match CLI callers which create directories before calling writeWalletFile. - Files.createDirectories(destination.toPath().getParent()); + public void testParentSyncFailureForNewDirectoryIsNotIgnored() throws Exception { + File base = tempFolder.newFolder("new-directory-parent-sync-fail"); + Path baseReal = base.toPath().toRealPath(); + Path newDir = baseReal.resolve("newdir"); + File destination = new File(base, "newdir/wallet.json"); WalletFile wallet = lightWalletFile("password123"); FileChannel directory = mock(FileChannel.class); - FileChannel ancestor = mock(FileChannel.class); - doThrow(new IOException("ancestor sync failed")).when(ancestor).force(true); - Path realDir = destination.toPath().getParent().toRealPath(); + FileChannel parent = mock(FileChannel.class); + doThrow(new IOException("parent sync failed")).when(parent).force(true); try (MockedStatic channels = mockStatic(FileChannel.class, invocation -> { Path path = invocation.getArgument(0); - if (realDir.equals(path)) { + if (newDir.equals(path)) { return directory; } - if (realDir.getParent().equals(path)) { - return ancestor; + if (baseReal.equals(path)) { + return parent; } return invocation.callRealMethod(); })) { IOException error = assertThrows(IOException.class, () -> WalletUtils.writeWalletFile(wallet, destination)); - assertEquals("ancestor sync failed", error.getCause().getMessage()); + assertEquals("parent sync failed", error.getCause().getMessage()); } verify(directory).force(true); verify(directory).close(); - verify(ancestor).close(); + verify(parent).close(); + assertEquals(wallet.getAddress(), + WalletUtils.loadCredentials("password123", destination).getAddress()); + } + + @Test + public void testExistingDirectoryDoesNotOpenAncestors() throws Exception { + File base = tempFolder.newFolder("existing-dir-no-ancestor-sync"); + File dir = new File(base, "wallet"); + assertTrue(dir.mkdir()); + File destination = new File(dir, "wallet.json"); + WalletFile wallet = lightWalletFile("password123"); + Path realDir = dir.toPath().toRealPath(); + Path realParent = realDir.getParent(); + assertNotNull(realParent); + FileChannel directory = mock(FileChannel.class); + + try (MockedStatic channels = mockStatic(FileChannel.class, invocation -> { + Path path = invocation.getArgument(0); + if (realDir.equals(path)) { + return directory; + } + if (realParent.equals(path)) { + // An execute-only ancestor would fail here; existing directories must not be opened. + throw new IOException("unexpected ancestor sync"); + } + return invocation.callRealMethod(); + })) { + WalletUtils.writeWalletFile(wallet, destination); + } + verify(directory).force(true); assertEquals(wallet.getAddress(), WalletUtils.loadCredentials("password123", destination).getAddress()); } From cf8f5d4e71eb8c4e8d33d454fdeab4eaf3ebf140 Mon Sep 17 00:00:00 2001 From: federico Date: Wed, 18 Nov 2026 17:03:10 +0800 Subject: [PATCH 31/33] fix(crypto): remove directory syncing --- .../java/org/tron/keystore/WalletUtils.java | 27 ------- .../tron/keystore/WalletUtilsWriteTest.java | 77 ++----------------- .../tron/plugins/KeystoreCliUtilsTest.java | 9 ++- 3 files changed, 13 insertions(+), 100 deletions(-) diff --git a/crypto/src/main/java/org/tron/keystore/WalletUtils.java b/crypto/src/main/java/org/tron/keystore/WalletUtils.java index 5e1439fba28..a28f36a5729 100644 --- a/crypto/src/main/java/org/tron/keystore/WalletUtils.java +++ b/crypto/src/main/java/org/tron/keystore/WalletUtils.java @@ -26,11 +26,9 @@ import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; -import java.util.List; import java.util.NoSuchElementException; import java.util.Scanner; import java.util.Set; @@ -79,11 +77,6 @@ public static String generateWalletFile( /** * Write a WalletFile to the given destination path with owner-only (0600) * permissions, using a temp file + atomic rename. - * The temporary file is synced before replacement, then the destination directory and - * the directories whose entries this call created are synced to persist them. Existing - * ancestors above the first pre-existing directory are not opened, so they do not need - * read permission. Directory syncing requires filesystem support. A sync failure after - * replacement is reported to the caller, but does not roll back the replacement. * *

The temporary file is atomically created with 0600 permissions and written * through the same channel, without reopening its path. Filesystems that cannot @@ -100,16 +93,6 @@ public static String generateWalletFile( public static void writeWalletFile(WalletFile walletFile, File destination) throws IOException { Path dir = destination.getAbsoluteFile().getParentFile().toPath(); - // Sync the destination directory and only the ancestors whose entries this call - // (re)creates. Existing ancestors above the first pre-existing directory are not - // opened, so they do not need read permission. - List dirsToSync = new ArrayList<>(); - for (Path current = dir; current != null; current = current.getParent()) { - dirsToSync.add(current); - if (Files.exists(current)) { - break; - } - } Files.createDirectories(dir); Path tmp = dir.resolve("keystore-" + UUID.randomUUID() + ".tmp"); @@ -132,16 +115,6 @@ public static void writeWalletFile(WalletFile walletFile, File destination) } catch (AtomicMoveNotSupportedException e) { Files.move(tmp, destination.toPath(), StandardCopyOption.REPLACE_EXISTING); } - try { - for (Path current : dirsToSync) { - try (FileChannel directory = FileChannel.open(current.toRealPath(), - StandardOpenOption.READ)) { - directory.force(true); - } - } - } catch (IOException e) { - throw new IOException("Keystore was replaced, but directory sync failed: " + dir, e); - } } catch (Exception e) { try { Files.deleteIfExists(tmp); diff --git a/framework/src/test/java/org/tron/keystore/WalletUtilsWriteTest.java b/framework/src/test/java/org/tron/keystore/WalletUtilsWriteTest.java index 153396bfd8d..fec7b3f838e 100644 --- a/framework/src/test/java/org/tron/keystore/WalletUtilsWriteTest.java +++ b/framework/src/test/java/org/tron/keystore/WalletUtilsWriteTest.java @@ -8,7 +8,6 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -212,86 +211,20 @@ public void testFileSyncFailurePreservesExistingKeystore() throws Exception { } @Test - public void testDirectorySyncFailureReportsCompletedReplacement() throws Exception { - File dir = tempFolder.newFolder("directory-sync-fail"); - File destination = new File(dir, "wallet.json"); - WalletUtils.writeWalletFile(lightWalletFile("oldpassword"), destination); - WalletFile replacement = lightWalletFile("newpassword"); - Path realDir = dir.toPath().toRealPath(); - FileChannel channel = mock(FileChannel.class); - doThrow(new IOException("directory sync failed")).when(channel).force(true); - - try (MockedStatic channels = mockStatic(FileChannel.class, invocation -> - realDir.equals(invocation.getArgument(0)) ? channel : invocation.callRealMethod())) { - IOException error = assertThrows(IOException.class, - () -> WalletUtils.writeWalletFile(replacement, destination)); - assertTrue(error.getMessage().contains("Keystore was replaced")); - assertEquals("directory sync failed", error.getCause().getMessage()); - } - verify(channel).close(); - assertEquals(replacement.getAddress(), - WalletUtils.loadCredentials("newpassword", destination).getAddress()); - assertEquals("No temporary file should remain", 1, dir.list().length); - } - - @Test - public void testParentSyncFailureForNewDirectoryIsNotIgnored() throws Exception { - File base = tempFolder.newFolder("new-directory-parent-sync-fail"); - Path baseReal = base.toPath().toRealPath(); - Path newDir = baseReal.resolve("newdir"); - File destination = new File(base, "newdir/wallet.json"); + public void testWriteWalletFileDoesNotOpenDirectories() throws Exception { + File base = tempFolder.newFolder("write-without-directory-reads"); + File destination = new File(base, "a/b/wallet.json"); WalletFile wallet = lightWalletFile("password123"); - FileChannel directory = mock(FileChannel.class); - FileChannel parent = mock(FileChannel.class); - doThrow(new IOException("parent sync failed")).when(parent).force(true); try (MockedStatic channels = mockStatic(FileChannel.class, invocation -> { Path path = invocation.getArgument(0); - if (newDir.equals(path)) { - return directory; - } - if (baseReal.equals(path)) { - return parent; - } - return invocation.callRealMethod(); - })) { - IOException error = assertThrows(IOException.class, - () -> WalletUtils.writeWalletFile(wallet, destination)); - assertEquals("parent sync failed", error.getCause().getMessage()); - } - verify(directory).force(true); - verify(directory).close(); - verify(parent).close(); - assertEquals(wallet.getAddress(), - WalletUtils.loadCredentials("password123", destination).getAddress()); - } - - @Test - public void testExistingDirectoryDoesNotOpenAncestors() throws Exception { - File base = tempFolder.newFolder("existing-dir-no-ancestor-sync"); - File dir = new File(base, "wallet"); - assertTrue(dir.mkdir()); - File destination = new File(dir, "wallet.json"); - WalletFile wallet = lightWalletFile("password123"); - Path realDir = dir.toPath().toRealPath(); - Path realParent = realDir.getParent(); - assertNotNull(realParent); - FileChannel directory = mock(FileChannel.class); - - try (MockedStatic channels = mockStatic(FileChannel.class, invocation -> { - Path path = invocation.getArgument(0); - if (realDir.equals(path)) { - return directory; - } - if (realParent.equals(path)) { - // An execute-only ancestor would fail here; existing directories must not be opened. - throw new IOException("unexpected ancestor sync"); + if (Files.isDirectory(path)) { + throw new IOException("directory reads are unsupported"); } return invocation.callRealMethod(); })) { WalletUtils.writeWalletFile(wallet, destination); } - verify(directory).force(true); assertEquals(wallet.getAddress(), WalletUtils.loadCredentials("password123", destination).getAddress()); } diff --git a/plugins/src/test/java/org/tron/plugins/KeystoreCliUtilsTest.java b/plugins/src/test/java/org/tron/plugins/KeystoreCliUtilsTest.java index e13798772d2..2818a929fce 100644 --- a/plugins/src/test/java/org/tron/plugins/KeystoreCliUtilsTest.java +++ b/plugins/src/test/java/org/tron/plugins/KeystoreCliUtilsTest.java @@ -6,11 +6,13 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mockStatic; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; +import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Locale; @@ -18,6 +20,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; +import org.mockito.MockedStatic; import org.tron.common.utils.ByteArray; import org.tron.keystore.WalletFile; @@ -268,7 +271,11 @@ public void testReadPasswordFileNotFound() throws Exception { public void testEnsureDirectoryCreatesNested() throws Exception { File dir = new File(tempFolder.getRoot(), "a/b/c"); assertFalse(dir.exists()); - KeystoreCliUtils.ensureDirectory(dir); + try (MockedStatic channels = mockStatic(FileChannel.class, invocation -> { + throw new IOException("directory reads are unsupported"); + })) { + KeystoreCliUtils.ensureDirectory(dir); + } assertTrue(dir.exists()); assertTrue(dir.isDirectory()); } From 66540cd11347612b91c1afe737c51cf1006cc844 Mon Sep 17 00:00:00 2001 From: federico Date: Wed, 18 Nov 2026 18:04:38 +0800 Subject: [PATCH 32/33] refactor(crypto): split BN128 optimizations --- .../tron/common/crypto/zksnark/BN128G2.java | 22 +-- .../org/tron/common/crypto/zksnark/Fp.java | 1 - .../org/tron/common/crypto/zksnark/Fp12.java | 16 +- .../org/tron/common/crypto/zksnark/Fp2.java | 19 +- .../org/tron/common/crypto/zksnark/Fp6.java | 4 +- .../common/crypto/zksnark/BN128G2Test.java | 162 ------------------ 6 files changed, 25 insertions(+), 199 deletions(-) delete mode 100644 framework/src/test/java/org/tron/common/crypto/zksnark/BN128G2Test.java diff --git a/crypto/src/main/java/org/tron/common/crypto/zksnark/BN128G2.java b/crypto/src/main/java/org/tron/common/crypto/zksnark/BN128G2.java index 36247145737..cfa514bde9b 100644 --- a/crypto/src/main/java/org/tron/common/crypto/zksnark/BN128G2.java +++ b/crypto/src/main/java/org/tron/common/crypto/zksnark/BN128G2.java @@ -17,10 +17,12 @@ */ package org.tron.common.crypto.zksnark; -import static org.tron.common.crypto.zksnark.Params.PAIRING_FINAL_EXPONENT_Z; +import static org.tron.common.crypto.zksnark.Params.R; import static org.tron.common.crypto.zksnark.Params.TWIST_MUL_BY_P_X; import static org.tron.common.crypto.zksnark.Params.TWIST_MUL_BY_P_Y; +import java.math.BigInteger; + /** * Implementation of specific cyclic subgroup of points belonging to {@link BN128Fp2}
Members * of this subgroup are passed as a second param to pairing input {@link @@ -37,6 +39,8 @@ */ public class BN128G2 extends BN128Fp2 { + static final BigInteger FR_NEG_ONE = BigInteger.ONE.negate().mod(R); + BN128G2(BN128 p) { super(p.x, p.y, p.z); } @@ -67,20 +71,8 @@ public static BN128G2 create(byte[] a, byte[] b, byte[] c, byte[] d) { } private static boolean isGroupMember(BN128 p) { - if (p.isZero()) { - return true; - } - // For this BN curve, [r]P = O iff [z+1]P + psi([z]P) + psi^2([z]P) - // equals psi^3([2z]P), where psi is mulByP and z is the 63-bit BN seed. - // See https://eprint.iacr.org/2022/348, Sections 3 and 5.1. - BN128G2 zp = new BN128G2(p.mul(PAIRING_FINAL_EXPONENT_Z)); - BN128G2 a = zp.mulByP(); - BN128G2 b = a.mulByP(); - BN128G2 c = b.mulByP(); - BN128 left = zp.add(p).add(a).add(b); - BN128 right = c.add(c); - // equals() compares raw Jacobian coordinates, so compare points by subtraction. - return left.add(new BN128G2(right.x, right.y.negate(), right.z)).isZero(); + BN128 left = p.mul(FR_NEG_ONE).add(p); + return left.isZero(); // should satisfy condition: -1 * p + p == 0, where -1 belongs to F_r } @Override diff --git a/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp.java b/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp.java index 203491a1094..768a23e4fda 100644 --- a/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp.java +++ b/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp.java @@ -32,7 +32,6 @@ public class Fp implements Field { static final Fp ZERO = new Fp(BigInteger.ZERO); static final Fp _1 = new Fp(BigInteger.ONE); - // beta = -1 defines the next extension Fp2, where i^2 = beta. static final Fp NON_RESIDUE = new Fp(new BigInteger( "21888242871839275222246405745257275088696311157297823662689037894645226208582")); diff --git a/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp12.java b/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp12.java index 1f4c4d8fd60..8733d2297fb 100644 --- a/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp12.java +++ b/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp12.java @@ -136,14 +136,14 @@ Fp12 mulBy024(Fp2 ell0, Fp2 ellVW, Fp2 ellVV) { // For z.a_.a_ = z0. s1 = z1.mul(x2); t3 = s1.add(d4); - t4 = t3.mulByNonResidue().add(d0); + t4 = Fp6.NON_RESIDUE.mul(t3).add(d0); z0 = t4; // For z.a_.b_ = z1 t3 = z5.mul(x4); s1 = s1.add(t3); t3 = t3.add(d2); - t4 = t3.mulByNonResidue(); + t4 = Fp6.NON_RESIDUE.mul(t3); t3 = z1.mul(x0); s1 = s1.add(t3); t4 = t4.add(t3); @@ -161,7 +161,7 @@ Fp12 mulBy024(Fp2 ell0, Fp2 ellVW, Fp2 ellVV) { z2 = t3; t1 = x2.add(x4); t3 = t0.mul(t1).sub(d2).sub(d4); - t4 = t3.mulByNonResidue(); + t4 = Fp6.NON_RESIDUE.mul(t3); t3 = z3.mul(x0); s1 = s1.add(t3); t4 = t4.add(t3); @@ -170,7 +170,7 @@ Fp12 mulBy024(Fp2 ell0, Fp2 ellVW, Fp2 ellVV) { // For z.b_.b_ = z4 t3 = z5.mul(x2); s1 = s1.add(t3); - t4 = t3.mulByNonResidue(); + t4 = Fp6.NON_RESIDUE.mul(t3); t0 = x0.add(x4); t3 = t2.mul(t0).sub(d0).sub(d4); t4 = t4.add(t3); @@ -259,15 +259,15 @@ Fp12 cyclotomicSquared() { // t0 + t1*y = (z0 + z1*y)^2 = a^2 tmp = z0.mul(z1); - t0 = z0.add(z1).mul(z0.add(z1.mulByNonResidue())).sub(tmp).sub(tmp.mulByNonResidue()); + t0 = z0.add(z1).mul(z0.add(Fp6.NON_RESIDUE.mul(z1))).sub(tmp).sub(Fp6.NON_RESIDUE.mul(tmp)); t1 = tmp.add(tmp); // t2 + t3*y = (z2 + z3*y)^2 = b^2 tmp = z2.mul(z3); - t2 = z2.add(z3).mul(z2.add(z3.mulByNonResidue())).sub(tmp).sub(tmp.mulByNonResidue()); + t2 = z2.add(z3).mul(z2.add(Fp6.NON_RESIDUE.mul(z3))).sub(tmp).sub(Fp6.NON_RESIDUE.mul(tmp)); t3 = tmp.add(tmp); // t4 + t5*y = (z4 + z5*y)^2 = c^2 tmp = z4.mul(z5); - t4 = z4.add(z5).mul(z4.add(z5.mulByNonResidue())).sub(tmp).sub(tmp.mulByNonResidue()); + t4 = z4.add(z5).mul(z4.add(Fp6.NON_RESIDUE.mul(z5))).sub(tmp).sub(Fp6.NON_RESIDUE.mul(tmp)); t5 = tmp.add(tmp); // for A @@ -284,7 +284,7 @@ Fp12 cyclotomicSquared() { // for B // z2 = 3 * (xi * t5) + 2 * z2 - tmp = t5.mulByNonResidue(); + tmp = Fp6.NON_RESIDUE.mul(t5); z2 = tmp.add(z2); z2 = z2.add(z2); z2 = z2.add(tmp); diff --git a/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp2.java b/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp2.java index 641cf2a643c..162a5b13b30 100644 --- a/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp2.java +++ b/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp2.java @@ -23,7 +23,7 @@ * Arithmetic in F_p2

* * "p" equals 21888242871839275222246405745257275088696311157297823662689037894645226208583, - * elements of F_p2 are represented as polynomials "a + b * i" modulo "i^2 + 1" from the ring + * elements of F_p2 are represented as a polynomials "a * i + b" modulo "i^2 + 1" from the ring * F_p[i]

* * Field arithmetic is ported from libff @@ -36,7 +36,6 @@ class Fp2 implements Field { static final Fp2 ZERO = new Fp2(Fp.ZERO, Fp.ZERO); static final Fp2 _1 = new Fp2(Fp._1, Fp.ZERO); - // xi = 9 + i defines the next extension Fp6, where v^3 = xi. static final Fp2 NON_RESIDUE = new Fp2(BigInteger.valueOf(9), BigInteger.ONE); static final Fp[] FROBENIUS_COEFFS_B = new Fp[]{ @@ -80,7 +79,9 @@ public Fp2 squared() { Fp ab = a.mul(b); - Fp ra = a.add(b).mul(a.sub(b)); // i^2 = -1, so ra = a^2 - b^2 + Fp ra = a.add(b).mul(b.mul(Fp.NON_RESIDUE).add(a)) + .sub(ab) + .sub(ab.mul(Fp.NON_RESIDUE)); // ra = (a + b)(a + NON_RESIDUE * b) - ab - NON_RESIDUE * b Fp rb = ab.dbl(); return new Fp2(ra, rb); @@ -92,7 +93,7 @@ public Fp2 mul(Fp2 o) { Fp aa = a.mul(o.a); Fp bb = b.mul(o.b); - Fp ra = aa.sub(bb); // ra = a1 * a2 - b1 * b2 + Fp ra = bb.mul(Fp.NON_RESIDUE).add(aa); // ra = a1 * a2 + NON_RESIDUE * b1 * b2 Fp rb = a.add(b).mul(o.a.add(o.b)).sub(aa) .sub(bb); // rb = (a1 + b1)(a2 + b2) - a1 * a2 - b1 * b2 @@ -119,7 +120,7 @@ public Fp2 inverse() { Fp t0 = a.squared(); Fp t1 = b.squared(); - Fp t2 = t0.add(t1); + Fp t2 = t0.sub(Fp.NON_RESIDUE.mul(t1)); Fp t3 = t2.inverse(); Fp ra = a.mul(t3); // ra = a * t3 @@ -174,16 +175,12 @@ Fp2 frobeniusMap(int power) { return new Fp2(ra, rb); } - /** Multiplies this Fp2 element by xi = 9 + i, the defining parameter of Fp6. */ Fp2 mulByNonResidue() { - // (a + bi)(9 + i) = (9a - b) + (a + 9b)i - Fp a9 = a.dbl().dbl().dbl().add(a); - Fp b9 = b.dbl().dbl().dbl().add(b); - return new Fp2(a9.sub(b), a.add(b9)); + return NON_RESIDUE.mul(this); } @Override public String toString() { - return String.format("%s + %si", a.toString(), b.toString()); + return String.format("%si + %s", a.toString(), b.toString()); } } diff --git a/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp6.java b/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp6.java index 7a1e1749783..fb863bb6b34 100644 --- a/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp6.java +++ b/crypto/src/main/java/org/tron/common/crypto/zksnark/Fp6.java @@ -34,6 +34,7 @@ class Fp6 implements Field { static final Fp6 ZERO = new Fp6(Fp2.ZERO, Fp2.ZERO, Fp2.ZERO); static final Fp6 _1 = new Fp6(Fp2._1, Fp2.ZERO, Fp2.ZERO); + static final Fp2 NON_RESIDUE = new Fp2(BigInteger.valueOf(9), BigInteger.ONE); static final Fp2[] FROBENIUS_COEFFS_B = { new Fp2(BigInteger.ONE, @@ -147,10 +148,9 @@ Fp6 mul(Fp2 o) { return new Fp6(ra, rb, rc); } - /** Multiplies by v, where v^3 = Fp2.NON_RESIDUE and Fp12 is defined by w^2 = v. */ Fp6 mulByNonResidue() { - Fp2 ra = c.mulByNonResidue(); + Fp2 ra = NON_RESIDUE.mul(c); Fp2 rb = a; Fp2 rc = b; diff --git a/framework/src/test/java/org/tron/common/crypto/zksnark/BN128G2Test.java b/framework/src/test/java/org/tron/common/crypto/zksnark/BN128G2Test.java deleted file mode 100644 index 65ec31ef9d3..00000000000 --- a/framework/src/test/java/org/tron/common/crypto/zksnark/BN128G2Test.java +++ /dev/null @@ -1,162 +0,0 @@ -package org.tron.common.crypto.zksnark; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.lang.reflect.Method; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import org.junit.Test; - -/** - * Verifies the G2 subgroup acceptance rule used when decoding pairing inputs. The private - * predicate is compared against the full-order oracle {@code [r]P = O} for affine, projective, - * infinity, and non-subgroup points. - */ -public class BN128G2Test { - - private static final BigInteger TWO = BigInteger.valueOf(2); - private static final BigInteger P = Params.P; - private static final BigInteger SQRT_EXPONENT = P.add(BigInteger.ONE).shiftRight(2); - - // Standard alt_bn128 G2 generator, with Fp2 elements represented as a + b * i. - private static final BigInteger G2_X_A = new BigInteger( - "10857046999023057135944570762232829481370756359578518086990519993285655852781"); - private static final BigInteger G2_X_B = new BigInteger( - "11559732032986387107991004021392285783925812861821192530917403151452391805634"); - private static final BigInteger G2_Y_A = new BigInteger( - "8495653923123431417604973247489272438418190587263600148770280649306958101930"); - private static final BigInteger G2_Y_B = new BigInteger( - "4082367875863433681332203403145435568316851327593401208105741076214120093531"); - - @Test - public void testInfinityIsGroupMember() { - assertNotNull(BN128G2.create(bytes(0), bytes(0), bytes(0), bytes(0))); - } - - @Test - public void testGeneratorIsGroupMember() { - assertNotNull(createG2(G2_X_A, G2_X_B, G2_Y_A, G2_Y_B)); - } - - @Test - public void testPredicateMatchesFullOrderMultiplication() throws Exception { - List> points = new ArrayList<>(); - BN128 generator = createAffine(G2_X_A, G2_X_B, G2_Y_A, G2_Y_B); - assertNotNull(generator); - points.add(generator); - points.addAll(curvePoints(6)); - - boolean sawNonSubgroup = false; - for (BN128 point : points) { - boolean inSubgroup = point.mul(Params.R).isZero(); - assertEquals("predicate disagrees with [r]P = O for " + point, - inSubgroup, isGroupMember(point)); - - BN128G2 accepted = createG2( - new BigInteger(1, point.x.a.bytes()), new BigInteger(1, point.x.b.bytes()), - new BigInteger(1, point.y.a.bytes()), new BigInteger(1, point.y.b.bytes())); - assertEquals("[r]P = O disagrees with create() for " + point, inSubgroup, accepted != null); - - if (!inSubgroup) { - sawNonSubgroup = true; - } - } - assertTrue("expected at least one non-subgroup point", sawNonSubgroup); - } - - @Test - public void testPredicateMatchesFullOrderForProjectiveInputs() throws Exception { - BN128 generator = createAffine(G2_X_A, G2_X_B, G2_Y_A, G2_Y_B); - assertNotNull(generator); - for (int k = 1; k <= 4; k++) { - BN128 point = generator.mul(BigInteger.valueOf(k)); - assertEquals("projective input " + k, - point.mul(Params.R).isZero(), isGroupMember(point)); - } - } - - private static BN128G2 createG2(BigInteger xa, BigInteger xb, BigInteger ya, BigInteger yb) { - return BN128G2.create(xa.toByteArray(), xb.toByteArray(), ya.toByteArray(), yb.toByteArray()); - } - - private static BN128 createAffine(BigInteger xa, BigInteger xb, BigInteger ya, - BigInteger yb) { - return BN128Fp2.create(xa.toByteArray(), xb.toByteArray(), ya.toByteArray(), yb.toByteArray()); - } - - private static boolean isGroupMember(BN128 point) throws Exception { - Method method = BN128G2.class.getDeclaredMethod("isGroupMember", BN128.class); - method.setAccessible(true); - return (Boolean) method.invoke(null, point); - } - - /** - * Returns ordinary twist points that are on the curve but, with overwhelming probability, - * outside the order-r subgroup. - */ - private static List> curvePoints(int limit) { - List> points = new ArrayList<>(); - for (int i = 1; i <= 500 && points.size() < limit; i++) { - Fp2 x = new Fp2(BigInteger.valueOf(i), BigInteger.ZERO); - Fp2 rhs = x.squared().mul(x).add(Params.B_Fp2); - Fp2 y = sqrt(rhs); - if (y == null || !y.squared().equals(rhs)) { - continue; - } - BN128 point = BN128Fp2.create(x.a.bytes(), x.b.bytes(), y.a.bytes(), y.b.bytes()); - if (point != null && !point.isZero()) { - points.add(point); - } - } - return points; - } - - /** Computes a square root in Fp2, or null when the value is not a square. */ - private static Fp2 sqrt(Fp2 value) { - BigInteger a = new BigInteger(1, value.a.bytes()); - BigInteger b = new BigInteger(1, value.b.bytes()); - BigInteger norm = a.multiply(a).add(b.multiply(b)).mod(P); - BigInteger c = sqrtFp(norm); - if (c == null) { - return null; - } - Fp2 result = sqrtWith(value, c); - return result != null ? result : sqrtWith(value, c.negate().mod(P)); - } - - private static Fp2 sqrtWith(Fp2 value, BigInteger c) { - BigInteger a = new BigInteger(1, value.a.bytes()); - BigInteger b = new BigInteger(1, value.b.bytes()); - BigInteger twoInv = TWO.modInverse(P); - BigInteger realRoot = sqrtFp(a.add(c).multiply(twoInv).mod(P)); - BigInteger imagRoot = sqrtFp(c.subtract(a).multiply(twoInv).mod(P)); - if (realRoot == null || imagRoot == null) { - return null; - } - BigInteger imaginary = realRoot.multiply(imagRoot).shiftLeft(1).mod(P); - if (imaginary.equals(b.mod(P))) { - return new Fp2(new Fp(realRoot), new Fp(imagRoot)); - } - if (imaginary.negate().mod(P).equals(b.mod(P))) { - return new Fp2(new Fp(realRoot), new Fp(imagRoot.negate().mod(P))); - } - return null; - } - - /** Square root in Fp for p = 3 (mod 4), or null when the value is not a square. */ - private static BigInteger sqrtFp(BigInteger value) { - BigInteger v = value.mod(P); - if (v.signum() == 0) { - return BigInteger.ZERO; - } - BigInteger root = v.modPow(SQRT_EXPONENT, P); - return root.multiply(root).mod(P).equals(v) ? root : null; - } - - private static byte[] bytes(long value) { - return BigInteger.valueOf(value).toByteArray(); - } -} From f21fcc1eeb2208885c4c07f26f3d4b4809a2d6de Mon Sep 17 00:00:00 2001 From: federico Date: Thu, 19 Nov 2026 10:45:48 +0800 Subject: [PATCH 33/33] fix(crypto): stop declaring ECKey serializable --- crypto/src/main/java/org/tron/common/crypto/ECKey.java | 4 +--- .../src/test/java/org/tron/common/crypto/ECKeyTest.java | 6 ++++++ 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/crypto/src/main/java/org/tron/common/crypto/ECKey.java b/crypto/src/main/java/org/tron/common/crypto/ECKey.java index 4086baf111a..bc1cce6f363 100644 --- a/crypto/src/main/java/org/tron/common/crypto/ECKey.java +++ b/crypto/src/main/java/org/tron/common/crypto/ECKey.java @@ -17,7 +17,6 @@ * along with the ethereumJ library. If not, see . */ -import java.io.Serializable; import java.math.BigInteger; import java.nio.charset.Charset; import java.security.KeyPair; @@ -64,7 +63,7 @@ * low-S signatures. */ @Slf4j(topic = "crypto") -public class ECKey implements Serializable, SignInterface { +public class ECKey implements SignInterface { /** * The parameters of the secp256k1 curve. @@ -88,7 +87,6 @@ public class ECKey implements Serializable, SignInterface { private static final BigInteger SECP256K1N = new BigInteger("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16); private static final SecureRandom secureRandom; - private static final long serialVersionUID = -728224901792295832L; static { // All clients must agree on the curve to use by agreement. diff --git a/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java b/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java index 9fbe894bfee..90479e7a833 100644 --- a/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java +++ b/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java @@ -496,6 +496,12 @@ public void testComputeAddressRejectsPointAtInfinity() { assertThrows(IllegalArgumentException.class, () -> Hash.computeAddress((ECPoint) null)); } + @Test + public void testECKeyIsNotSerializable() { + ECKey key = ECKey.fromPrivate(privateKey); + assertFalse(key instanceof java.io.Serializable); + } + @Test public void testMissingPrivateKeyIsIllegalStateException() { ECKey publicOnly = ECKey.fromPublicOnly(pubKey);