Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
98b8afa
docs(crypto): clarify digest padding documentation
Federico2014 Nov 16, 2026
8dd4511
fix(crypto): override Keccak state copying
Federico2014 Nov 16, 2026
4ca2f9e
fix(crypto): clear Keccak buffers on reset
Federico2014 Nov 16, 2026
fe95ef6
fix(crypto): reject incompatible digest copies
Federico2014 Nov 16, 2026
72da735
fix(crypto): initialize digest length eagerly
Federico2014 Nov 16, 2026
4663fae
fix(keystore): reject corrupted password input
Federico2014 Nov 17, 2026
26b6908
fix(keystore): make wallet filename helper private
Federico2014 Nov 17, 2026
bda8eb6
fix(keystore): sync wallet files and directories
Federico2014 Nov 17, 2026
05d1465
fix(keystore): avoid reopening temporary files
Federico2014 Nov 17, 2026
8655178
fix(keystore): reject malformed wallet files
Federico2014 Nov 17, 2026
2de697b
docs(keystore): clarify discovery validation
Federico2014 Nov 17, 2026
3ffe91d
fix(keystore): validate wallet creation inputs
Federico2014 Nov 17, 2026
9b6228e
fix(keystore): guard console errors and salt size
Federico2014 Nov 17, 2026
3a3538d
fix(crypto): keep Miller loop points in homogeneous type
Federico2014 Nov 17, 2026
64722ab
fix(crypto): use BouncyCastle for provider-less jce helpers
Federico2014 Nov 17, 2026
0048edb
fix(crypto): validate blake2f output buffer before compression
Federico2014 Nov 17, 2026
b94a357
fix(crypto): stop declaring blake2f digest cloneable
Federico2014 Nov 18, 2026
2757b3f
fix(crypto): honor offset in blake2f digest output
Federico2014 Nov 18, 2026
d8b5152
fix(crypto): include recovery id in ECDSA signature equality
Federico2014 Nov 18, 2026
cd85109
fix(crypto): tolerate invalid recId candidates when signing
Federico2014 Nov 18, 2026
92c1093
fix(crypto): make missing private key an IllegalStateException
Federico2014 Nov 18, 2026
e3657d6
docs(crypto): document recovery exceptions in ECKey
Federico2014 Nov 18, 2026
316f88e
fix(crypto): validate public key format in computeAddress
Federico2014 Nov 18, 2026
a61724b
fix(crypto): reject point at infinity in computeAddress
Federico2014 Nov 18, 2026
aa73cc6
fix(crypto): correct Fp2 representation and toString
Federico2014 Nov 18, 2026
342ed30
perf(crypto): specialize Fp2 arithmetic
Federico2014 Nov 18, 2026
c61e533
refactor(crypto): unify zksnark non-residue definitions
Federico2014 Nov 18, 2026
52de7b8
perf(crypto): use endomorphism for G2 subgroup check
Federico2014 Nov 18, 2026
8d49862
fix(crypto): reject negative scalars in BN128.mul
Federico2014 Nov 18, 2026
04d35bf
fix(crypto): address review comments
Federico2014 Nov 18, 2026
cf8f5d4
fix(crypto): remove directory syncing
Federico2014 Nov 18, 2026
66540cd
refactor(crypto): split BN128 optimizations
Federico2014 Nov 18, 2026
f21fcc1
fix(crypto): stop declaring ECKey serializable
Federico2014 Nov 19, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions common/src/main/java/org/tron/common/utils/StringUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down Expand Up @@ -148,10 +148,15 @@ 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) {
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
throw new IllegalArgumentException("Output buffer too small for the digest");
}

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();
Expand Down
37 changes: 27 additions & 10 deletions crypto/src/main/java/org/tron/common/crypto/ECKey.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
* along with the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/

import java.io.Serializable;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.KeyPair;
Expand Down Expand Up @@ -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.
Expand All @@ -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.
Expand Down Expand Up @@ -501,15 +499,15 @@ public static boolean isPubKeyCanonical(byte[] pubkey) {
/**
* Recovers the public key using SEC1v2 section 4.1.6.
*
* <p>Replaces the three-argument overload; pass {@code false} for legacy recovery and rebuild
* downstream callers.</p>
*
* @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 when
* strict validation is disabled
*/
@Nullable
public static byte[] recoverPubBytesFromSignature(int recId,
Expand Down Expand Up @@ -816,7 +814,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;
Expand All @@ -826,6 +830,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;
}
Expand Down Expand Up @@ -927,6 +934,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) {

Expand Down Expand Up @@ -1007,6 +1020,9 @@ public boolean equals(Object o) {

ECDSASignature signature = (ECDSASignature) o;

if (v != signature.v) {
return false;
}
if (!r.equals(signature.r)) {
return false;
}
Expand All @@ -1017,12 +1033,13 @@ public boolean equals(Object o) {
public int hashCode() {
int result = r.hashCode();
result = 31 * result + s.hashCode();
result = 31 * result + (int) v;
return result;
}
}

@SuppressWarnings("serial")
public static class MissingPrivateKeyException extends RuntimeException {
public static class MissingPrivateKeyException extends IllegalStateException {

}

Expand Down
14 changes: 14 additions & 0 deletions crypto/src/main/java/org/tron/common/crypto/Hash.java
Original file line number Diff line number Diff line change
Expand Up @@ -177,10 +177,24 @@ 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));
}

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));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@

import java.security.DigestException;
import java.security.MessageDigest;
import java.util.Arrays;

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;

Expand All @@ -45,6 +47,7 @@ public DigestEngine(String alg) {
* state.
*/
protected void engineReset() {
Arrays.fill(inputBuf, (byte) 0);
inputLen = 0;
blockCount = 0;
}
Expand All @@ -57,33 +60,26 @@ 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
*/
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();
Expand All @@ -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");
}
Expand Down Expand Up @@ -227,18 +222,22 @@ 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,
* 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 || digestLen != dest.digestLen || 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,
inputBuf.length);
adjustDigestLen();
dest.adjustDigestLen();
return dest;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@

package org.tron.common.crypto.cryptohash;

import java.util.Arrays;

abstract class KeccakCore extends DigestEngine {

private static final long[] RC = {
Expand Down Expand Up @@ -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;
}
Expand All @@ -540,9 +543,14 @@ private final void doReset() {
A[20] = 0xFFFFFFFFFFFFFFFFL;
}

protected Digest copyState(KeccakCore dst) {
System.arraycopy(A, 0, dst.A, 0, 25);
return super.copyState(dst);
@Override
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 dst;
}

public String toString() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,11 @@ public BN128<T> add(BN128<T> o) {

public BN128<T> 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();
}
Expand Down
Loading
Loading