基于 BIP39 协议创建 Ethereum HD Wallet

基于 BIP39协议创建 Ethereum HD Wallet

初始化 Ethereum HD Wallet 项目

  1. 在终端创建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$
  1. 初始化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 ` 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编写钱包程序

代码示例:


var bip39 = require('bip39');
var hdkey = require('ethereumjs-wallet/hdkey');
var util = require('ethereumjs-util');


var mnemonic = bip39.generateMnemonic();
console.log("助记词" + mnemonic);


var seed = bip39.mnemonicToSeed(mnemonic);


var hdWallet = hdkey.fromMasterSeed(seed);

var key1 = hdWallet.derivePath("m/44'/60'/0'/0/0");


var address1 = util.pubToAddress(key1._hdkey._publicKey, true);
console.log("以太地址-转换前" + address1);


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

你可能感兴趣的:(BlockChain)