| 1 | import 'dart:async'; |
| 2 | import 'dart:convert'; |
| 3 | import 'dart:typed_data'; |
| 4 | |
| 5 | import 'package:bitcoin_base/bitcoin_base.dart'; |
| 6 | import 'package:blockchain_utils/blockchain_utils.dart'; |
| 7 | import 'package:cw_bitcoin/hardware/bitcoin_hardware_wallet_service.dart'; |
| 8 | import 'package:cw_bitcoin/utils.dart'; |
| 9 | import 'package:cw_core/hardware/hardware_account_data.dart'; |
| 10 | import 'package:cw_core/hardware/hardware_wallet_service.dart'; |
| 11 | import 'package:ledger_bitcoin/ledger_bitcoin.dart'; |
| 12 | import 'package:ledger_flutter_plus/ledger_flutter_plus.dart'; |
| 13 | |
| 14 | class BitcoinLedgerService extends HardwareWalletService with BitcoinHardwareWalletService { |
| 15 | BitcoinLedgerService(this.ledgerConnection) |
| 16 | : bitcoinLedgerApp = BitcoinLedgerApp(ledgerConnection); |
| 17 | |
| 18 | final LedgerConnection ledgerConnection; |
| 19 | final BitcoinLedgerApp bitcoinLedgerApp; |
| 20 | |
| 21 | void setAccountDerivationPath(String derivationPath) { |
| 22 | bitcoinLedgerApp.derivationPath = derivationPath; |
| 23 | } |
| 24 | |
| 25 | @override |
| 26 | Future<List<HardwareAccountData>> getAvailableAccounts({int index = 0, int limit = 5}) async { |
| 27 | final masterFp = await bitcoinLedgerApp.getMasterFingerprint(); |
| 28 | |
| 29 | final accounts = <HardwareAccountData>[]; |
| 30 | final indexRange = List.generate(limit, (i) => i + index); |
| 31 | |
| 32 | for (final i in indexRange) { |
| 33 | final derivationPath = "m/84'/0'/$i'"; |
| 34 | final xPub = await bitcoinLedgerApp.getXPubKey(derivationPath: derivationPath); |
| 35 | final hd = Bip32Slip10Secp256k1.fromExtendedKey(xPub).childKey(Bip32KeyIndex(0)); |
| 36 | |
| 37 | final address = generateP2WPKHAddress(hd: hd, index: 0, network: BitcoinNetwork.mainnet); |
| 38 | |
| 39 | accounts.add(HardwareAccountData( |
| 40 | address: address, |
| 41 | accountIndex: i, |
| 42 | derivationPath: derivationPath, |
| 43 | masterFingerprint: masterFp, |
| 44 | xpub: xPub, |
| 45 | )); |
| 46 | } |
| 47 | |
| 48 | return accounts; |
| 49 | } |
| 50 | |
| 51 | @override |
| 52 | Future<Uint8List> signTransaction({required String transaction}) => |
| 53 | bitcoinLedgerApp.signPsbt(psbt: PsbtV2()..deserialize(base64Decode(transaction))); |
| 54 | |
| 55 | @override |
| 56 | Future<Uint8List> getMasterFingerprint() => bitcoinLedgerApp.getMasterFingerprint(); |
| 57 | |
| 58 | @override |
| 59 | Future<Uint8List> signMessage({required Uint8List message, String? derivationPath}) => |
| 60 | bitcoinLedgerApp.signMessage(message: message, signDerivationPath: derivationPath); |
| 61 | } |