trufflesuite / truffle-hdwallet-provider

HD Wallet-enabled Web3 provider
MIT License
400 stars 167 forks source link

Retrieving the private/ public key for a specific path with web3js: different outputs for same mnemonic/path passed as provider #112

Closed Jdodo45 closed 3 years ago

Jdodo45 commented 3 years ago

What I am trying to do

I am trying to create an ethereum wallet based  on a mnemonic phrase and I would like to retrieve private/public keys for several specific paths from this wallet.

Steps to Reproduce

This is my code which I run several time in different node console in a cmd.

Before starting the node console, I start a cmd with geth --rpc --rpcport 8545 while internet is turned off so that I don't have to download/sync the blockchain


const mnemonicPhrase = 'some words ... '

const HDWalletProvider = require("@truffle/hdwallet-provider");
Web3 = require('web3');

provider = new HDWalletProvider({
  mnemonic: mnemonicPhrase,
  providerOrUrl: "http://localhost:8545",
  numberOfAddresses: 1,
  shareNonce: true,
  derivationPath: "m/44'/0'/0'/0/"
});

const web3 = new Web3(provider);
web3.eth.accounts.create() 

Actual Results

When I run this code several time with the same mnemonic phrase and the same path, the private/public key given by web3.eth.accounts.create() is different, which it very confusing. I am new to the Ethereum world so I am probably missing something here but to have different private/public keys generated from the same mnemonic phrase and the same path doesn't sound right to me. It is as if the variable provider is not used by web3js .

Expected Behavior

Each time I am run this code in a new console wit the same mnemonic phrase and the same path, I should (at least as I understood it), get the same private/public key.

Thanks for your help!

Environment

Jdodo45 commented 3 years ago

I shouldnt have use web3.eth.accounts.create() but web3.eth.accounts.

But in the end, I finally gave up using truffle and web3js and use ethereumjs-util instead.

Here is the code mainly from Harsha Goli

bip39 = require('bip39');
ethUtil = require('ethereumjs-util');
hdkey = require('hdkey');

const mnemonic = bip39.generateMnemonic(256); // if you already have a mnemonic you can put it here
const seed = bip39.mnemonicToSeedSync(mnemonic);
const root = hdkey.fromMasterSeed(seed);
const masterPrivateKey = root.privateKey.toString('hex');

var path = "m/44'/60'/0'/0/0"  // change path 
var addrNode = root.derive(path); 
var pubKey = ethUtil.privateToPublic(addrNode._privateKey);
var addr =  '0x' +  ethUtil.publicToAddress(pubKey).toString('hex');
var address = ethUtil.toChecksumAddress(addr);

console.log( "\n", "\n", "\n","ACCOUNT ", path, "\n", "private key : 0x", addrNode._privateKey.toString('hex'), "\n", "public key : ",pubKey.toString('hex'), "\n", "address : ", address)