Ethers.js-批量生成钱包

Ethers.js-批量生成钱包

HD钱包

HD钱包(Hierarchical Deterministic Wallet,多层确定性钱包)是一种数字钱包 ,通常用于存储比特币和以太坊等加密货币持有者的数字密钥。通过它,用户可以从一个随机种子创建一系列密钥对,更加便利、安全、隐私。要理解HD钱包,我们需要简单了解比特币的BIP32,BIP44,和BIP39。

批量生成钱包

import {
    
     ethers } from "ethers";

// 生成随机助记词
const mnemonic = ethers.utils.entropyToMnemonic(ethers.utils.randomBytes(32))
// 创建HD基钱包
// 基路径:"m / purpose' / coin_type' / account' / change"
const basePath = "44'/60'/0'/0"
const baseWallet = ethers.utils.HDNode.fromMnemonic(mnemonic, basePath)
console.log('1.创建HD钱包')
console.log(baseWallet);


const numWallet = 20
// 派生路径:基路径 + "/ address_index"
// 我们只需要提供最后一位address_index的字符串格式,就可以从baseWallet派生出新钱包。V6中不需要重复提供基路径!
let wallets = [];
for (let i = 0; i < numWallet; i++) {
    
    
    let baseWalletNew = baseWallet.derivePath(i.toString());
    console.log('2.通过HD钱包派生20个钱包')
    console.log(`${
      
      i+1}个钱包地址: ${
      
      baseWalletNew.address}`)
    wallets.push(baseWalletNew);
}

const wallet = ethers.Wallet.fromMnemonic(mnemonic)
console.log('3.保存钱包(加密json)')
console.log("通过助记词创建钱包:")
console.log(wallet)
// 加密json用的密码,可以更改成别的
const pwd = "password"
const json = await wallet.encrypt(pwd)
console.log("钱包的加密json:")
console.log(json)

const wallet2 = await ethers.Wallet.fromEncryptedJson(json, pwd);
console.log("\n4. 从加密json读取钱包:")
console.log(wallet2)

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Geoffrey_Zhu/article/details/143425173