dart-bitcoin / bitcoin_flutter

A dart Bitcoin library for Flutter.
MIT License
165 stars 123 forks source link

How do I use the library to generate native segwit addresses with BIP84 derivation paths? #32

Closed RohanKapurDEV closed 4 years ago

RohanKapurDEV commented 4 years ago

For example, let's assume I want to generate addresses under the following BIP84 (BIP44 for native segwit) derivation paths:

m / 84' / 0' / 0' / 0 / 0 m / 84' / 0' / 0' / 1 / 0

And let's suppose that all I have is the wallet mnemonic. I know that I can get to the node by using the following (i think):

final seed = bip39.mnemonicToSeed(await secureStore.read(key: 'mnemonic'));
final root = bip32.BIP32.fromSeed(seed);
final node = root.derivePath("m/84'/0'/0'/0/0");

You can assume that the secureStore read call always returns a valid mnemonic. How do I generate a native segwit address from what I have using this library?

Thanks once again

RohanKapurDEV commented 4 years ago

I believe I have the solution. Heres a working function for those that care to understand. Keep in mind that this solution assumes that you're using Flutter with Dart:

  Future<String> generateReceivingAddress(int index) async {
    final secureStore = new FlutterSecureStorage();
    final seed = bip39.mnemonicToSeed(await secureStore.read(key: 'mnemonic'));
    final root = bip32.BIP32.fromSeed(seed);
    final node = root.derivePath("m/84'/0'/0'/0/$index");

    final address = P2WPKH(data: new PaymentData(pubkey: node.publicKey)).data.address;
    return address;
  }