前面我们离线生成了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,我们可以把公共方法抽取出来,这里就不演示啦~