前面我們離線生成了ETH的賬戶,這是一種賬戶生成辦法,另外一種就是用戶提供助記詞,我們通過助記詞生成一個錢包。其實這和創建錢包是同一套流程
原來創建是:seed種子(隨機生成助記詞)--->私鑰--->公鑰
那導入就是:seed種子(用戶提供)--->私鑰--->公鑰
我們看代碼
/**
* 通過助記詞導入錢包
*
* @param path 助記詞路徑 用戶提供使用什麼協議生成
* @param list 助記詞
* @param password 密碼
* @return
*/
public void importByMnemonic(String path,List<String> mnemonics,String password) {
//協議跟路徑這個是有規定的,這裏也要校驗一下
if (!path.startsWith("m") && !path.startsWith("M")) {
//throw new RuntimeException("請輸入正確路徑啦~~~~");
}
//TODO 密碼長度這邊校驗一下 一般大於8就可以了 還有助記詞校驗
String[] pathArray =path.split("/");
long creationTimeSeconds = System.currentTimeMillis() / 1000;
//主要就是這裏會有不同,原來是隨機生成,這次我們替換成用戶助記詞構建
DeterministicSeed ds = new DeterministicSeed(mnemonics, 128, "", creationTimeSeconds);
//根私鑰
byte[] seedBytes = ds.getSeedBytes();
//助記詞
List<String> mnemonic = ds.getMnemonicCode();
try {
//助記詞種子
byte[] mnemonicSeedBytes = MnemonicCode.INSTANCE.toEntropy(mnemonic);
ECKeyPair mnemonicKeyPair = ECKeyPair.create(mnemonicSeedBytes);
WalletFile walletFile = Wallet.createLight(password, mnemonicKeyPair);
ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
//存這個keystore 用完後刪除
String jsonStr = objectMapper.writeValueAsString(walletFile);
//驗證
WalletFile checkWalletFile = objectMapper.readValue(jsonStr, WalletFile.class);
ECKeyPair ecKeyPair = Wallet.decrypt(password, checkWalletFile);
byte[] checkMnemonicSeedBytes = Numeric.hexStringToByteArray(ecKeyPair.getPrivateKey().toString(16));
List<String> checkMnemonic = MnemonicCode.INSTANCE.toMnemonic(checkMnemonicSeedBytes);
} catch (MnemonicException.MnemonicLengthException | MnemonicException.MnemonicWordException | MnemonicException.MnemonicChecksumException | CipherException | IOException e) {
logger.error("賬號生成異常了!!!{}", e);
}
if (seedBytes == null) return;
DeterministicKey dkKey = HDKeyDerivation.createMasterPrivateKey(seedBytes);
for (int i = 1; i < pathArray.length; i++) {
ChildNumber childNumber;
if (pathArray[i].endsWith("'")) {
int number = Integer.parseInt(pathArray[i].substring(0,
pathArray[i].length() - 1));
childNumber = new ChildNumber(number, true);
} else {
int number = Integer.parseInt(pathArray[i]);
childNumber = new ChildNumber(number, false);
}
dkKey = HDKeyDerivation.deriveChildKey(dkKey, childNumber);
}
ECKeyPair keyPair = ECKeyPair.create(dkKey.getPrivKeyBytes());
EthWalletModel ethHDWallet = null;
try {
WalletFile walletFile = Wallet.createLight(password, keyPair);
ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
//keystore
String jsonStr = objectMapper.writeValueAsString(walletFile);
//私鑰
String privateKey=keyPair.getPrivateKey().toString(16);
//公鑰
String publicKey=keyPair.getPublicKey().toString(16);
//根地址
String rpath = dkKey.getPathAsString();
//地址
String address="0x" + walletFile.getAddress();
} catch (CipherException | JsonProcessingException e) {
logger.error("創建賬戶異常了!!!{}", e);
}
}
好啦 ,大部分方法都是一樣的,就是構建種子那裏會有不同。基於java的oop,我們可以把公共方法抽取出來,這裏就不演示啦~