-
Notifications
You must be signed in to change notification settings - Fork 1.7k
feat(plugins): migrate keystore CLI from FullNode to Toolkit #6637
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
barbatos2011
wants to merge
24
commits into
tronprotocol:develop
Choose a base branch
from
barbatos2011:001-keystore-toolkit-migration
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
0526128
refactor(crypto): extract keystore library from framework module
7f0c0ba
feat(plugins): add keystore new and import commands to Toolkit
2bced5f
feat(plugins): add keystore list and update commands, deprecate --key…
1a641b4
fix(plugins): handle duplicate-address keystores and add import warning
791d91f
fix(plugins): block duplicate import, improve error messages and secu…
3c0f8eb
style(plugins): use picocli output streams and address review findings
cf823df
fix(plugins): secure keystore file creation and improve robustness
ce482cb
test(plugins): improve keystore test coverage and assertions
115e226
fix(plugins): unify keystore validation and fix inconsistent error me…
b079839
test(plugins): improve coverage for keystore validation and edge cases
b083fc6
test(plugins): add direct unit tests for KeystoreCliUtils
241590c
test(framework): expand coverage for WalletFile POJO and KeystoreFactory
cdb038f
ci: re-trigger build after transient apt mirror failure
4e19b0b
ci: re-trigger after transient infrastructure failure
368d104
fix(crypto): enforce keystore address consistency in Wallet.decrypt
c383a83
fix(plugins): prevent address spoofing in keystore update command
5a76ed8
docs(plugins): document keystore list address trust model
070316c
refactor(crypto): centralize secure keystore file writing in WalletUtils
40ec5ce
fix(plugins): reject symlinked password/key files to prevent file dis…
e5bbc20
fix(crypto): preserve whitespace in non-TTY password input
4bcb850
feat(plugins): hint at legacy password-truncation on keystore update …
f681124
feat(framework): hint at legacy password-truncation on SR startup fai…
99159e2
test(crypto): move keystore tests to framework for jacoco coverage
340669c
fix(plugins): reject symlinks in keystore directory scans
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
294 changes: 294 additions & 0 deletions
294
crypto/src/main/java/org/tron/keystore/WalletUtils.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,294 @@ | ||
| package org.tron.keystore; | ||
|
|
||
| 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.IOException; | ||
| import java.nio.file.AtomicMoveNotSupportedException; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Path; | ||
| import java.nio.file.StandardCopyOption; | ||
| import java.nio.file.attribute.PosixFilePermission; | ||
| import java.nio.file.attribute.PosixFilePermissions; | ||
| import java.security.InvalidAlgorithmParameterException; | ||
| import java.security.NoSuchAlgorithmException; | ||
| import java.security.NoSuchProviderException; | ||
| import java.time.ZoneOffset; | ||
| import java.time.ZonedDateTime; | ||
| import java.time.format.DateTimeFormatter; | ||
| import java.util.Collections; | ||
| import java.util.EnumSet; | ||
| import java.util.Scanner; | ||
| import java.util.Set; | ||
| import org.apache.commons.lang3.StringUtils; | ||
| import org.tron.common.crypto.SignInterface; | ||
| import org.tron.common.crypto.SignUtils; | ||
| import org.tron.common.utils.Utils; | ||
| import org.tron.core.exception.CipherException; | ||
|
|
||
| /** | ||
| * Utility functions for working with Wallet files. | ||
| */ | ||
| public class WalletUtils { | ||
|
|
||
| private static final ObjectMapper objectMapper = new ObjectMapper(); | ||
|
|
||
| private static final Set<PosixFilePermission> OWNER_ONLY = | ||
| Collections.unmodifiableSet(EnumSet.of( | ||
| PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)); | ||
|
|
||
| static { | ||
| objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); | ||
| objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); | ||
| } | ||
|
|
||
| public static String generateFullNewWalletFile(String password, File destinationDirectory, | ||
| boolean ecKey) | ||
| throws NoSuchAlgorithmException, NoSuchProviderException, | ||
| InvalidAlgorithmParameterException, CipherException, IOException { | ||
|
|
||
| return generateNewWalletFile(password, destinationDirectory, true, ecKey); | ||
| } | ||
|
|
||
| public static String generateLightNewWalletFile(String password, File destinationDirectory, | ||
| boolean ecKey) | ||
| throws NoSuchAlgorithmException, NoSuchProviderException, | ||
| InvalidAlgorithmParameterException, CipherException, IOException { | ||
|
|
||
| return generateNewWalletFile(password, destinationDirectory, false, ecKey); | ||
| } | ||
|
|
||
| public static String generateNewWalletFile( | ||
| String password, File destinationDirectory, boolean useFullScrypt, boolean ecKey) | ||
| throws CipherException, IOException, InvalidAlgorithmParameterException, | ||
| NoSuchAlgorithmException, NoSuchProviderException { | ||
|
|
||
| SignInterface ecKeyPair = SignUtils.getGeneratedRandomSign(Utils.getRandom(), ecKey); | ||
| return generateWalletFile(password, ecKeyPair, destinationDirectory, useFullScrypt); | ||
| } | ||
|
|
||
| public static String generateWalletFile( | ||
| String password, SignInterface ecKeyPair, File destinationDirectory, boolean useFullScrypt) | ||
| throws CipherException, IOException { | ||
|
|
||
| WalletFile walletFile; | ||
| if (useFullScrypt) { | ||
| walletFile = Wallet.createStandard(password, ecKeyPair); | ||
| } else { | ||
| walletFile = Wallet.createLight(password, ecKeyPair); | ||
| } | ||
|
|
||
| String fileName = getWalletFileName(walletFile); | ||
| File destination = new File(destinationDirectory, fileName); | ||
| writeWalletFile(walletFile, destination); | ||
|
|
||
| return fileName; | ||
| } | ||
|
|
||
| /** | ||
| * Write a WalletFile to the given destination path with owner-only (0600) | ||
| * permissions, using a temp file + atomic rename. | ||
| * | ||
| * <p>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. | ||
| * | ||
| * <p>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. | ||
| * | ||
| * @param walletFile the keystore to serialize | ||
| * @param destination the final target file (existing file will be replaced) | ||
| */ | ||
| public static void writeWalletFile(WalletFile walletFile, File destination) | ||
| throws IOException { | ||
| 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); | ||
| } | ||
|
|
||
| try { | ||
| objectMapper.writeValue(tmp.toFile(), walletFile); | ||
| try { | ||
| Files.move(tmp, destination.toPath(), | ||
| StandardCopyOption.REPLACE_EXISTING, | ||
| StandardCopyOption.ATOMIC_MOVE); | ||
| } catch (AtomicMoveNotSupportedException e) { | ||
| Files.move(tmp, destination.toPath(), StandardCopyOption.REPLACE_EXISTING); | ||
| } | ||
| } catch (Exception e) { | ||
| try { | ||
| Files.deleteIfExists(tmp); | ||
| } catch (IOException suppress) { | ||
| e.addSuppressed(suppress); | ||
| } | ||
| throw e; | ||
| } | ||
| } | ||
|
|
||
| public static Credentials loadCredentials(String password, File source, boolean ecKey) | ||
| throws IOException, CipherException { | ||
| WalletFile walletFile = objectMapper.readValue(source, WalletFile.class); | ||
| return Credentials.create(Wallet.decrypt(password, walletFile, ecKey)); | ||
| } | ||
|
|
||
| public static String getWalletFileName(WalletFile walletFile) { | ||
| DateTimeFormatter format = DateTimeFormatter.ofPattern( | ||
| "'UTC--'yyyy-MM-dd'T'HH-mm-ss.nVV'--'"); | ||
| ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); | ||
|
|
||
| return now.format(format) + walletFile.getAddress() + ".json"; | ||
| } | ||
|
|
||
| public static String getDefaultKeyDirectory() { | ||
| return getDefaultKeyDirectory(System.getProperty("os.name")); | ||
| } | ||
|
|
||
| static String getDefaultKeyDirectory(String osName1) { | ||
| String osName = osName1.toLowerCase(); | ||
|
|
||
| if (osName.startsWith("mac")) { | ||
| return String.format( | ||
| "%s%sLibrary%sEthereum", System.getProperty("user.home"), File.separator, | ||
| File.separator); | ||
| } else if (osName.startsWith("win")) { | ||
| return String.format("%s%sEthereum", System.getenv("APPDATA"), File.separator); | ||
| } else { | ||
| return String.format("%s%s.ethereum", System.getProperty("user.home"), File.separator); | ||
| } | ||
| } | ||
|
|
||
| public static String getTestnetKeyDirectory() { | ||
| return String.format( | ||
| "%s%stestnet%skeystore", getDefaultKeyDirectory(), File.separator, File.separator); | ||
| } | ||
|
|
||
| public static String getMainnetKeyDirectory() { | ||
| return String.format("%s%skeystore", getDefaultKeyDirectory(), File.separator); | ||
| } | ||
|
|
||
| /** | ||
| * Strip trailing line terminators ({@code \n}/{@code \r}) and a leading | ||
| * UTF-8 BOM ({@code \uFEFF}) from a line of input. Unlike | ||
| * {@link String#trim()} this preserves internal whitespace, so passwords | ||
| * containing spaces (e.g. passphrases) survive intact. | ||
| * | ||
| * <p>Intended as the canonical helper for normalizing raw user-provided | ||
| * password/line input across both CLI console and file-driven paths. | ||
| * Returns {@code null} if the input is {@code null}. | ||
| */ | ||
| public static String stripPasswordLine(String s) { | ||
| if (s == null) { | ||
| return null; | ||
| } | ||
| if (s.length() > 0 && s.charAt(0) == '\uFEFF') { | ||
| s = s.substring(1); | ||
| } | ||
| int end = s.length(); | ||
| while (end > 0) { | ||
| char c = s.charAt(end - 1); | ||
| if (c == '\n' || c == '\r') { | ||
| end--; | ||
| } else { | ||
| break; | ||
| } | ||
| } | ||
| return s.substring(0, end); | ||
| } | ||
|
|
||
| public static boolean passwordValid(String password) { | ||
| if (StringUtils.isEmpty(password)) { | ||
| return false; | ||
| } | ||
| if (password.length() < 6) { | ||
| return false; | ||
| } | ||
| //Other rule; | ||
| return true; | ||
| } | ||
|
|
||
| /** | ||
| * Lazily-initialized Scanner shared across successive | ||
| * {@link #inputPassword()} calls on the non-TTY path so that | ||
| * {@link #inputPassword2Twice()} can read two lines in sequence | ||
| * without losing data. Each call to {@code new Scanner(System.in)} | ||
| * internally buffers bytes from the underlying {@link BufferedReader}; | ||
| * constructing a second Scanner after the first has been discarded | ||
| * drops any buffered bytes the first pulled from stdin, causing | ||
| * {@code NoSuchElementException}. | ||
| */ | ||
| private static Scanner sharedStdinScanner; | ||
|
|
||
| /** | ||
| * Visible for testing: reset the cached Scanner so subsequent calls | ||
| * see a freshly rebound {@link System#in}. | ||
| */ | ||
| static synchronized void resetSharedStdinScanner() { | ||
| sharedStdinScanner = null; | ||
| } | ||
|
|
||
| private static synchronized Scanner getSharedStdinScanner() { | ||
| if (sharedStdinScanner == null) { | ||
| sharedStdinScanner = new Scanner(System.in); | ||
| } | ||
| return sharedStdinScanner; | ||
| } | ||
|
|
||
| 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: "); | ||
| password = String.valueOf(pwd); | ||
| } else { | ||
| // Preserve the full password including embedded whitespace. | ||
| // The previous implementation applied trim() + split("\\s+")[0] | ||
| // which silently truncated passwords like "correct horse battery | ||
| // staple" to "correct" when piped via stdin (e.g. echo ... | java). | ||
| // stripPasswordLine only removes the UTF-8 BOM and trailing line | ||
| // terminators — internal whitespace is part of the password. | ||
| password = stripPasswordLine(in.nextLine()); | ||
| } | ||
| if (passwordValid(password)) { | ||
| return password; | ||
| } | ||
| System.out.println("Invalid password, please input again."); | ||
| } | ||
| } | ||
|
|
||
| public static String inputPassword2Twice() { | ||
| String password0; | ||
| while (true) { | ||
| System.out.println("Please input password."); | ||
| password0 = inputPassword(); | ||
| System.out.println("Please input password again."); | ||
| String password1 = inputPassword(); | ||
| if (password0.equals(password1)) { | ||
| break; | ||
| } | ||
| System.out.println("Two passwords do not match, please input again."); | ||
| } | ||
| return password0; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
#6588 has already decided to remove the unused SM2 algorithm and related configuration. Why is this PR still adding compatibility for it (e.g., the
boolean ecKeyparameter and--sm2option)?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@halibobo1205 It has currently been decided to retain SM2. See: #6627 (comment)