以太坊开发(三十)创建钱包时同时生成助记词

字数 158阅读 403

前言

之前我们使用Node.js+Web3.js,创建钱包的时候,只返回了addressprivateKeykeystore,其实还应该返回助记词mnemonic。助记词,私钥,公钥,地址,密码的关系,这里就不再解释了,大家可以去自行了解。

老版本创建钱包代码(不返回助记词)

/**
 * 创建钱包
 * 
 * 参数:1.password: 钱包密码
 * 
 * 返回:1.address: 账号地址
 *     2.privateKey: 私钥
 *     3.keystore: keystore
 *   
 */
router.get('/eth/account/createWallet', async(ctx, next) => {

    if (typeof(ctx.request.query.password) == 'undefined' || 
        ctx.request.query.password == '') {
        ctx.body = await Promise.resolve({
            code: 1,
            data: {},
            message: 'Missing parameter: password.',
        })
        return
    } 

    try {
        let account = web3.eth.accounts.create()

        let response = web3.eth.accounts.encrypt(account.privateKey, 
        ctx.request.query.password)

        ctx.body = await Promise.resolve({
            code: 0,
            address: account.address,
            privateKey: account.privateKey.substr(2),
            keystore: response,
            message: 'Success',
        })
    } catch (error) {
        ctx.body = await Promise.resolve({
            code: 1,
            data: {},
            message: error.stack,
        })
    }
})

新版本创建钱包代码(同时返回助记词)

/**
 * 创建钱包
 * 
 * 参数:1.password: 钱包密码
 * 
 * 返回:1.address: 地址
 *     2.password: 钱包密码
 *     3.privateKey: 私钥
 *     4.publicKey: 公钥
 *     5.keystore: keystore
 *     6.mnemonic:助记词
 *   
 */
router.get('/eth/account/createWallet', async(ctx, next) => {

    if (typeof(ctx.request.query.password) == 'undefined' || 
        ctx.request.query.password == '') {
        ctx.body = await Promise.resolve({
            code: 1,
            data: {},
            message: 'Missing parameter: password.',
        })
        return
    } 

    try {
        // 1.生成助记词
        let mnemonic = bip39.generateMnemonic()

        //2.将助记词转成seed
        let seed = bip39.mnemonicToSeedSync(mnemonic)

        //3.通过hdkey将seed生成HD Wallet
        let hdWallet = hdkey.fromMasterSeed(seed)

        //4.生成钱包中在m/44'/60'/0'/0/0路径的keypair
        let key = hdWallet.derivePath("m/44'/60'/0'/0/0")

        //5.从keypair中获取私钥
        let privateKey = util.bufferToHex(key._hdkey._privateKey)

        //6.从keypair中获取公钥
        let publicKey = util.bufferToHex(key._hdkey._publicKey)

        //7.使用keypair中的公钥生成地址
        let address = util.pubToAddress(publicKey, true)
        address = util.toChecksumAddress(address.toString('hex'))

        //8.生成keystore
        let keystore = web3.eth.accounts.encrypt(privateKey, 
            ctx.request.query.password)

        ctx.body = await Promise.resolve({
            code: 0,
            address: address,
            password: ctx.request.query.password,
            privateKey: privateKey.substr(2),
            publicKey: publicKey,
            keystore: keystore,
            mnemonic: mnemonic,
            message: 'Success',
        })
    } catch (error) {
        ctx.body = await Promise.resolve({
            code: 1,
            data: {},
            message: error.stack,
        })
    }
})

需要使用三个新的包bip39ethereumjs-wallet/hdkeyethereumjs-util

首先安装三个包:

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

然后代码里引用包:

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

根据助记词获取钱包信息

/**
 * 根据password和助记词返回address, privateKey, publicKey, keystore
 *
 * 参数:1.password: 钱包密码
 *     2.助记词: 助记词
 * 
 * 返回:1.address: address 
 *     2.privateKey: privateKey
 *     3.publicKey: publicKey
 *     4.keystore: keystore
 *
 */
 router.get('/eth/account/getAccount', async(ctx, next) => {
    
    let { password, mnemonic } = ctx.request.query

    if (typeof(password) == 'undefined' || 
        password == '') {
        ctx.body = await Promise.resolve({
            code: 1,
            data: {},
            message: 'Missing parameter: password.',
        })
        return
    } 

    if (typeof(mnemonic) == 'undefined' || 
        mnemonic == '') {
        ctx.body = await Promise.resolve({
            code: 1,
            data: {},
            message: 'Missing parameter: mnemonic.',
        })
        return
    } 

    try {
         //将助记词转成seed
        let seed = bip39.mnemonicToSeedSync(mnemonic)

        //通过hdkey将seed生成HDWallet
        let hdWallet = hdkey.fromMasterSeed(seed)

         //生成钱包中在m/44'/60'/0'/0/0路径的keypair
        let key = hdWallet.derivePath("m/44'/60'/0'/0/0")

        //从keypair中获取私钥
        let privateKey = util.bufferToHex(key._hdkey._privateKey)

        //从keypair中获取公钥
        let publicKey = util.bufferToHex(key._hdkey._publicKey)

        //使用keypair中的公钥生成地址
        let address = util.pubToAddress(publicKey, true)
        address = util.toChecksumAddress(address.toString('hex'))

        //生成keystore
        let keystore = web3.eth.accounts.encrypt(privateKey, password)

        ctx.body = await Promise.resolve({
            code: 0,
            address: address,
            privateKey: privateKey.substr(2),
            publicKey: publicKey,
            keystore: keystore,
            message: 'Success',
        })
    } catch (error) {
        ctx.body = await Promise.resolve({
            code: 1,
            data: {},
            message: error.stack,
        })
    }
})

推荐阅读更多精彩内容