step 1 装依赖的包(npm/yarn 自己选一个):
yarn add bip39 ethereumjs-wallet ethereumjs-util
npm install bip39 ethereumjs-wallet ethereumjs-util
step 2 演示代码:
const bip39 = require('bip39')
const {hdkey} = require('ethereumjs-wallet')
const util = require('ethereumjs-util')
//1 生成助记词 ;1.1 和 1.2 自己按需。
// 1.1 生成助记词 ;这里用生成的.
// let mnemonic = bip39.generateMnemonic()
// 1.2 生成助记词 ;这里用写死的.
let mnemonic = "hold scale hybrid tank dilemma bullet ship language attitude rug tennis host"
console.log(mnemonic)
//2.将助记词转成seed
getSeed = async ()=>{
let seed = await bip39.mnemonicToSeed(mnemonic)
console.log("seed:" + util.bufferToHex(seed))
return seed
}
//3.提取私钥,公钥,账户
obtainAccount = async ()=>{
let seed = await getSeed()
//3.通过hdkey将seed生成HD Wallet
let hdWallet = await hdkey.fromMasterSeed(seed)
for (let i = 0; i < 10; i++) {
//4.生成钱包中在m/44'/60'/0'/0/i路径的keypair
let key = await hdWallet.derivePath("m/44'/60'/0'/0/" + i)
//5.从keypair中获取私钥
console.log("私钥:" + util.bufferToHex(key._hdkey._privateKey))
//6.从keypair中获取公钥
console.log("公钥:" + util.bufferToHex(key._hdkey._publicKey))
//7.使用keypair中的公钥生成地址
let address = await util.pubToAddress(key._hdkey._publicKey, true)
//编码地址
console.log('account',i+1,'0x'+address.toString('hex'))
//分割线 console.log("__________________________________________________________")
}
}
obtainAccount()
step 3 运行结果截图:
来源:oschina
链接:https://my.oschina.net/u/4385631/blog/4387415