Summary
Validate keys when they enter ECKey, protect its cached values from accidental modification, and clear temporary private-key bytes after keystore decryption.
What is the problem?
ECKey represents a secp256k1 key pair and is used for operations such as transaction and witness signing. Several entry points handle invalid input or key state inconsistently:
- Invalid keys can fail too late. Private-key input is not consistently checked for size and numeric range before conversion or curve calculations. Public-key construction does not consistently enforce the supported encoding, curve, and point-validity rules.
- A private key can be paired with the wrong public key. For example, an object can contain private key A and public key B. Its address is derived from B, while signature generation uses A.
sign() then tries to match the recovered public key to B; if no match is found, it throws. This can cause recoverable signing to fail after the object has already been constructed.
- Callers can change cached values.
getAddress() and getNodeId() return their internal arrays. Modifying a returned array also changes what the object returns later.
- Equality can be asymmetric. A public-only key and a full key pair can represent the same public key, yet
publicOnly.equals(fullKey) can be true while fullKey.equals(publicOnly) is false. This violates the symmetry required by Java's equals() contract.
- Some APIs promise unsupported behavior or expose secrets. Constructors accept arbitrary cryptographic providers, although signing expects Bouncy Castle keys.
toStringWithPrivate() includes the private key in its output and can expose it if logged.
- Keystore errors and cleanup need a consistent boundary. ECDSA private-key validation failures during keystore decryption can escape as
IllegalArgumentException instead of CipherException. The temporary array containing the decrypted private key is not explicitly cleared.
Expected behavior
| Area |
Required behavior |
| Private keys |
Interpret byte arrays as unsigned big-endian integers and check their length before numeric conversion. Accept only values in 1 <= key < n, where n is the secp256k1 group order. Private-key import methods reject null and empty input. |
| Public keys |
Accept 33-byte encodings starting with 0x02 or 0x03, or 65-byte encodings starting with 0x04. Decode bytes on secp256k1 and reject invalid points and the point at infinity. For ECPoint input, also verify that its curve is secp256k1. |
| Key pairs |
When both components are supplied, verify that the public key is derived from the private key. Preserve public-only construction with a valid public key and no private key. |
| Cached values and equality |
Return copies of address and node ID arrays. Define equality by public-key identity, consistently with hashCode(), regardless of private-key presence or the public key's input encoding. |
| Providers and helper APIs |
Use Bouncy Castle for key generation and signing. Remove APIs that bypass key-pair checks or include private keys in string output. |
| Keystore decryption |
Wrap ECDSA private-key validation failures in CipherException, preserving the cause. Clear the temporary decrypted private-key array on success, private-key validation failure, and declared-address mismatch. Shared cleanup applies to both ECDSA and SM2 decryption. |
Private-key byte arrays of 1–32 bytes remain supported when their value is valid. Also accept a valid 33-byte representation produced by BigInteger.toByteArray(): one leading 0x00 followed by a 32-byte magnitude whose high bit is set. That extra byte marks a positive number; it does not make the key invalid. Other encodings longer than 32 bytes are rejected.
The validation scope includes these helper entry points:
publicKeyFromPrivate() validates the private scalar before deriving the public key.
fromNodeId() requires a 64-byte X/Y representation and applies public-key validation through fromPublicOnly().
signatureToKey() and recoverFromSignature() apply the strengthened public-key invariants when constructing a returned ECKey.
These requirements do not imply identical exception types for every malformed argument to every helper. In particular, the existing fromNodeId(null) behavior is not being standardized by this change.
Clearing the temporary array reduces how long that copy remains in memory. The returned key object still retains the private key needed for signing.
Compatibility and migration
This changes the public Java API. Downstream callers using removed methods must update their code and recompile. Changes to equality and returned-array sharing can also affect callers that still compile successfully.
| Existing usage |
Required change |
Provider-based ECKey constructors |
Use ECKey(SecureRandom) for generation, or the supported import constructors/factories. Arbitrary-provider support is removed. |
fromPrivateAndPrecalculatedPublic |
Use the validated ECKey(BigInteger, ECPoint) constructor when supplying both components. |
toStringWithPrivate() |
Removed without a private-key-printing replacement. Use toString() for diagnostic output. |
Expecting fromPrivate(byte[]) to return null for null or empty input |
Validate the input or handle IllegalArgumentException. |
| Handling invalid decrypted ECDSA keystore keys |
Handle CipherException; the original validation exception is retained as its cause. |
Distinguishing public-only and full keys using equals(), sets, or map keys |
Both now have the same identity when their public keys match. Check private-key availability separately if needed. |
Relying on shared arrays from getAddress() or getNodeId() |
Returned arrays are independent copies. Modifying them no longer changes the object's cached value; use content comparison rather than array reference identity. |
Preserve the existing signing and recovery results for valid inputs. This work must not change transaction/block signature acceptance or TVM ecrecover behavior. Recovery helpers that return ECKey must enforce the strengthened public-key invariants, so malformed inputs may be rejected differently.
Configuration, consensus rules, and on-chain behavior remain unchanged. SM2 algorithm and key-validation changes are outside this issue; temporary-buffer cleanup applies to the shared keystore decryption path.
Validation
The acceptance criteria are:
- Input boundaries: Cover invalid scalar values, unsigned byte interpretation, oversized encodings, and valid 33-byte sign-padded keys. Reject malformed public-key encodings, invalid points, points on another curve supplied as
ECPoint, and mismatched key pairs. Accept valid pairs and public-only construction. Exercise publicKeyFromPrivate() and fromNodeId() as well as constructors and import factories.
- Equality and cached values: Check equality in both directions between public-only and full keys, and between keys constructed from compressed and uncompressed encodings. Equal keys must have equal hash codes. Modifying returned address or node ID arrays must not change cached values.
- Signing and recovery: Verify signing and recovery results for valid inputs, including existing signature vectors. Verify that
signatureToKey() and recoverFromSignature() reject recovered public points that violate the new invariants. Cover transaction/block signature acceptance and TVM ecrecover compatibility.
- Real invalid ECDSA keystores: Use a correct password, a valid MAC, and decryptable ciphertext whose plaintext is an invalid private scalar, such as zero or
n. Confirm that failure comes from private-key validation and is wrapped in CipherException, rather than from password, MAC, or file errors.
- Temporary-buffer cleanup: Inspect the actual decrypted array after success and declared-address mismatch for both ECDSA and SM2, and after ECDSA private-key validation failure. Mocking or instrumentation may be used to observe that array, but must not replace all real invalid-key import coverage.
- Witness loading: Load a keystore containing a real invalid ECDSA private key through the witness initialization path. Confirm
WITNESS_KEYSTORE_LOAD with CipherException and the original validation exception in the cause chain. Keep the existing WitnessInitializer production logic; an injected exception alone does not satisfy this end-to-end acceptance case.
Summary
Validate keys when they enter
ECKey, protect its cached values from accidental modification, and clear temporary private-key bytes after keystore decryption.What is the problem?
ECKeyrepresents a secp256k1 key pair and is used for operations such as transaction and witness signing. Several entry points handle invalid input or key state inconsistently:sign()then tries to match the recovered public key to B; if no match is found, it throws. This can cause recoverable signing to fail after the object has already been constructed.getAddress()andgetNodeId()return their internal arrays. Modifying a returned array also changes what the object returns later.publicOnly.equals(fullKey)can betruewhilefullKey.equals(publicOnly)isfalse. This violates the symmetry required by Java'sequals()contract.toStringWithPrivate()includes the private key in its output and can expose it if logged.IllegalArgumentExceptioninstead ofCipherException. The temporary array containing the decrypted private key is not explicitly cleared.Expected behavior
1 <= key < n, wherenis the secp256k1 group order. Private-key import methods reject null and empty input.0x02or0x03, or 65-byte encodings starting with0x04. Decode bytes on secp256k1 and reject invalid points and the point at infinity. ForECPointinput, also verify that its curve is secp256k1.hashCode(), regardless of private-key presence or the public key's input encoding.CipherException, preserving the cause. Clear the temporary decrypted private-key array on success, private-key validation failure, and declared-address mismatch. Shared cleanup applies to both ECDSA and SM2 decryption.Private-key byte arrays of 1–32 bytes remain supported when their value is valid. Also accept a valid 33-byte representation produced by
BigInteger.toByteArray(): one leading0x00followed by a 32-byte magnitude whose high bit is set. That extra byte marks a positive number; it does not make the key invalid. Other encodings longer than 32 bytes are rejected.The validation scope includes these helper entry points:
publicKeyFromPrivate()validates the private scalar before deriving the public key.fromNodeId()requires a 64-byte X/Y representation and applies public-key validation throughfromPublicOnly().signatureToKey()andrecoverFromSignature()apply the strengthened public-key invariants when constructing a returnedECKey.These requirements do not imply identical exception types for every malformed argument to every helper. In particular, the existing
fromNodeId(null)behavior is not being standardized by this change.Clearing the temporary array reduces how long that copy remains in memory. The returned key object still retains the private key needed for signing.
Compatibility and migration
This changes the public Java API. Downstream callers using removed methods must update their code and recompile. Changes to equality and returned-array sharing can also affect callers that still compile successfully.
ECKeyconstructorsECKey(SecureRandom)for generation, or the supported import constructors/factories. Arbitrary-provider support is removed.fromPrivateAndPrecalculatedPublicECKey(BigInteger, ECPoint)constructor when supplying both components.toStringWithPrivate()toString()for diagnostic output.fromPrivate(byte[])to returnnullfor null or empty inputIllegalArgumentException.CipherException; the original validation exception is retained as its cause.equals(), sets, or map keysgetAddress()orgetNodeId()Preserve the existing signing and recovery results for valid inputs. This work must not change transaction/block signature acceptance or TVM
ecrecoverbehavior. Recovery helpers that returnECKeymust enforce the strengthened public-key invariants, so malformed inputs may be rejected differently.Configuration, consensus rules, and on-chain behavior remain unchanged. SM2 algorithm and key-validation changes are outside this issue; temporary-buffer cleanup applies to the shared keystore decryption path.
Validation
The acceptance criteria are:
ECPoint, and mismatched key pairs. Accept valid pairs and public-only construction. ExercisepublicKeyFromPrivate()andfromNodeId()as well as constructors and import factories.signatureToKey()andrecoverFromSignature()reject recovered public points that violate the new invariants. Cover transaction/block signature acceptance and TVMecrecovercompatibility.n. Confirm that failure comes from private-key validation and is wrapped inCipherException, rather than from password, MAC, or file errors.WITNESS_KEYSTORE_LOADwithCipherExceptionand the original validation exception in the cause chain. Keep the existingWitnessInitializerproduction logic; an injected exception alone does not satisfy this end-to-end acceptance case.