基于 BIP39协议创建 Ethereum HD Wallet
初始化 Ethereum HD Wallet 项目
- 在终端创建
wallet文件夹,并进入该文件夹下面
shanglishuaideMacBook-Pro:workspace shanglishuai$ mkdir wallet
shanglishuaideMacBook-Pro:workspace shanglishuai$ cd wallet/
shanglishuaideMacBook-Pro:wallet shanglishuai$ pwd
/Users/shanglishuai/workspace/wallet
shanglishuaideMacBook-Pro:wallet shanglishuai$
初始化
wallet项目- 语法:
npm init - 示例:
- 语法:
shanglishuaideMacBook-Pro:wallet shanglishuai$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (wallet) wallet
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to /Users/shanglishuai/workspace/wallet/package.json:
{
"name": "wallet",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes) yes
shanglishuaideMacBook-Pro:wallet shanglishuai$
引入javaScript套件
语法:npm install bip39 ethereumjs-wallet ethereumjs-util --save
说明:
bip39 :实作 BIP39,随机产生新的 mnemonic code(助记词),并可以将其转成 binary 的 seed。
ethereumjs-wallet :产生和管理公私钥,我使用其中的 hdkey 子套件来创建 HD Wallet。
ethereumjs-util:集合许多 Ethereum 需要的运算功能。
创建wallet.js编写钱包程序
代码示例:
<!-- 引入bip相关套件 -->
var bip39 = require('bip39');
var hdkey = require('ethereumjs-wallet/hdkey');
var util = require('ethereumjs-util');
<!-- 随机生成助记词 -->
var mnemonic = bip39.generateMnemonic();
console.log("助记词" + mnemonic);
<!-- 根据助记词产生二进制seed -->
var seed = bip39.mnemonicToSeed(mnemonic);
<!-- 使用 seed 产生 HD Wallet。如果要说更明确,就是产生 Master Key 并记录起来。 -->
var hdWallet = hdkey.fromMasterSeed(seed);
var key1 = hdWallet.derivePath("m/44'/60'/0'/0/0");
<!-- 使用 keypair 中的公钥产生 address。 -->
var address1 = util.pubToAddress(key1._hdkey._publicKey, true);
console.log("以太地址-转换前" + address1);
<!-- 基于BIP55协议对地址进行再次编码,获取最终ETH地址 -->
address1 = util.toChecksumAddress(address1.toString('hex'));
console.log("以太地址-转换后:" + address1);
运行测试
语法:node wallet.js
示例:
shanglishuaideMacBook-Pro:wallet shanglishuai$ node wallet.js
助记词:lyrics miracle muffin harsh unfair congress window soldier lady strategy debris basket
以太地址-转换前:x��hL��*���
r�S��
以太地址转换后:0x78c4db684CA3Ff2a9ae398ea0A72dC531BaCAc2B
shanglishuaideMacBook-Pro:wallet shanglishuai$
参考链接:
https://ethfans.org/posts/from-BIP-to-ethereum-HD-wallet
源代码链接:
https://github.com/myNameIssls/blockchain-study/tree/master/wallet
本文介绍如何基于BIP39协议创建Ethereum HD Wallet。通过生成助记词、产生二进制seed并创建Master Key,最终生成以太坊地址。文章提供了详细的步骤和代码示例。
6066

被折叠的 条评论
为什么被折叠?



