Filecoin HD 钱包 Node.js 代码实现

HD wallet

引用包

HD Wallet 相关

npm install bip39
npm install ethereumjs-util
npm install ethereumjs-wallet

Filecoin Address 相关

npm install blake2
npm install --save base32-encode

引用文件

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

blake2 = require('blake2')
base32Encode = require('base32-encode')
base32Decode = require('base32-decode')

生成助记词seed,以及用助记词恢复seed

mnemonic = bip39.generateMnemonic();
'eight fit visual situate ritual silent fiber duty anchor outside venue electric'

seed = bip39.mnemonicToSeedSync(mnemonic)

生成HD Wallet,

hdWallet = hdkey.fromMasterSeed(seed);

获得子key和子key密钥对

key0 = hdWallet.deriveChild(0)
key1 = hdWallet.deriveChild(1)

privateKey0 = key0._hdkey._privateKey
privateKey1 = key1._hdkey._privateKey

publicKey0 = util.privateToPublic(privateKey0)

生成Filecoin 地址

function getAddress(pubKey) {
    pubKeyString = "04" + pubKey.toString('hex')
    pubKey1 = new Buffer(pubKeyString, 'hex')
    
    h1 = blake2.createHash('blake2b', {digestLength: 20});
    h1.update(pubKey1);
    address = h1.digest();
    addressS = "01"+ address.toString('hex')
    addressB = new Buffer(addressS, 'hex')
    
    h2 = blake2.createHash('blake2b', {digestLength: 4});
    h2.update(addressB);
    cksm = h2.digest();
    
    addr = address.toString('hex') + cksm.toString('hex')
    addrBuff = new Buffer(addr, 'hex')
  
    return base32Encode(addrBuff, 'RFC4648', { padding: false }).toLowerCase()
}

得到6j5iu4elnajlrrs4ugk5tjnd365b42csgh7b3hq
根据公钥属性,属于测试网(t),还是正式网(f),是钱包地址(1)还是合约地址(2)加上相应的前缀。
目前我们是做测试网钱包,所以这里在地址前面加上t1, 得到t16j5iu4elnajlrrs4ugk5tjnd365b42csgh7b3hq

你可能感兴趣的:(Filecoin HD 钱包 Node.js 代码实现)