trustwallet / wallet-core

Cross-platform, cross-blockchain wallet library.
https://developer.trustwallet.com/wallet-core
Apache License 2.0
2.84k stars 1.59k forks source link

Wrong Bitcoin addresses generating for legacy, SegWit and Native SegWit (BIP44|49|84) #2774

Closed EvgenV closed 1 year ago

EvgenV commented 1 year ago

I tried to test possibility to generate additional addresses for different versions of Bitcoin's addresses. I decided to use final public func getKey(coin: WalletCore.CoinType, derivationPath: String) -> WalletCore.PrivateKey So idea is to specify custom index, e.g. "m/44\'/0\'/0\'/0/2" or custom account "m/44\'/0\'/2\'/0/0"

But I was stuck at the generating default address for legacy format. I use Swift

let mnemonicPhrase = "foster shallow problem poverty similar theme rule ignore camp van chuckle odor" // Metamask
guard let wallet = HDWallet(mnemonic: mnemonicPhrase, passphrase: "") else {
    throw HDWalletError.impossibleToGenerateWallet
}
let bitcoinDerivationPathLegacy = "m/44\'/0\'/0\'/0/0"
let bitcoinKeyLegacy = wallet.getKey(coin: .bitcoin, derivationPath: bitcoinDerivationPathLegacy)
let bitcoinAddressLegacy = CoinType.bitcoin.deriveAddress(privateKey: bitcoinKeyLegacy)
print("\(bitcoinDerivationPathLegacy): \(bitcoinAddressLegacy)")
// m/44'/0'/0'/0/0: bc1qy3laaxl4f9022vn49s0a3ptnz25pj967l96g5e

let bitcoinDerivationPathSegwit = "m/49\'/0\'/0\'/0/0"
let bitcoinKeySegwit = wallet.getKey(coin: .bitcoin, derivationPath: bitcoinDerivationPathSegwit)
let bitcoinAddressSegwit = CoinType.bitcoin.deriveAddress(privateKey: bitcoinKeySegwit)
print("\(bitcoinDerivationPathSegwit): \(bitcoinAddressSegwit)")
// m/49'/0'/0'/0/0: bc1qfv0xyycjr59rfhdy4k48ch039p442hh3j33vd4

let bitcoinDerivationPathNativeSegwit = "m/84\'/0\'/0\'/0/0"
let bitcoinKeyNativeSegwit = wallet.getKey(coin: .bitcoin, derivationPath: bitcoinDerivationPathNativeSegwit)
let bitcoinAddressNativeSegwit = CoinType.bitcoin.deriveAddress(privateKey: bitcoinKeyNativeSegwit)
print("\(bitcoinDerivationPathNativeSegwit): \(bitcoinAddressNativeSegwit)")
// m/84'/0'/0'/0/0: bc1qaky53wlhtfvm6zup8hhfr3vcg2uvg23mrs9p7s

I expected that address generated with derivationPath m/44'/0'/0'/0/0 starts from 1 address generated with derivationPath m/49'/0'/0'/0/0 starts from 3

What I am doing wrong?

Milerius commented 1 year ago

Converting to discussion as it's a question