Files
hash-wallet/cw_bitcoin/lib/electrum_wallet.dart
T
+4 084fd6bb1e New design (#2797)
* refactor node form UI to use new ListItem model

* add new list item row types and widgets

* add style wrapper

* remove print [skip ci]

* Integrate new design mockup with ViewModel (#2653)

* feat: add Lightning Network support for Bitcoin wallets

* refactor: rename `fiatConvertationStore` to `fiatConversionStore` for consistency and update related occurrences across codebase

* feat: enhance address validation with Lightning Network invoice support for BTC & refactor wallet type/token checks in view model

* feat: add support for Lightning invoice detection, refactor MWEB deposit/withdraw actions, and integrate Lightning transaction creation with updated priority handling

* feat: add method to retrieve unused Spark deposit address for Bitcoin wallets

* feat: add Breez API key support and update secrets handling for Bitcoin Lightning wallet integration in workflows

* chore: update Breez SDK dependency to version 0.3.4 in pubspec files

* Add bitcoin secrets config [skip ci]

* feat: extend Lightning wallet functionality with transaction history fetching

* feat: add LNURL-pay address detection and support in address parsing flow for Bitcoin Lightning integration

* refactor: simplify `ReceivePageOption` logic

* refactor: centralize `PaymentURI` generation logic across wallet types

* feat: enhance `PaymentURI` handling with asynchronous support and Lightning-specific functionality

* refactor: streamline `PaymentURI` logic and remove redundant URI implementations across wallet types

* refactor: remove redundant debug print statement from `bitcoin_wallet_addresses.dart`

* refactor: improve consistency in widget styling and centralized label logic, add Bitcoin Lightning deposit/withdraw support

* feat: reload balance and tx history after sending a lightning transaction

* feat: improve address formatting for human-readable addresses and update the default LNURL domain

* fix: merge conflicts

* feat: add error handling for LightningWallet initialization and adjust transaction direction logic

* integrate homepage from new ui mockup

* fix import

* feat: add Lightning Network support for Bitcoin wallets

* refactor: rename `fiatConvertationStore` to `fiatConversionStore` for consistency and update related occurrences across codebase

* feat: enhance address validation with Lightning Network invoice support for BTC & refactor wallet type/token checks in view model

* feat: add support for Lightning invoice detection, refactor MWEB deposit/withdraw actions, and integrate Lightning transaction creation with updated priority handling

* feat: add method to retrieve unused Spark deposit address for Bitcoin wallets

* feat: add Breez API key support and update secrets handling for Bitcoin Lightning wallet integration in workflows

* chore: update Breez SDK dependency to version 0.3.4 in pubspec files

* Add bitcoin secrets config [skip ci]

* feat: extend Lightning wallet functionality with transaction history fetching

* feat: add LNURL-pay address detection and support in address parsing flow for Bitcoin Lightning integration

* refactor: simplify `ReceivePageOption` logic

* refactor: centralize `PaymentURI` generation logic across wallet types

* feat: enhance `PaymentURI` handling with asynchronous support and Lightning-specific functionality

* refactor: streamline `PaymentURI` logic and remove redundant URI implementations across wallet types

* refactor: remove redundant debug print statement from `bitcoin_wallet_addresses.dart`

* refactor: improve consistency in widget styling and centralized label logic, add Bitcoin Lightning deposit/withdraw support

* feat: reload balance and tx history after sending a lightning transaction

* feat: improve address formatting for human-readable addresses and update the default LNURL domain

* fix: merge conflicts

* feat: add error handling for LightningWallet initialization and adjust transaction direction logic

* integrate homepage from new ui mockup

* fix import

* add new-ui dir to pubspec_base

* minor layout fixes

* cleanup navbar logic

* Modify navbar behaviour

* smooth color change when selecting navbar options

* open old ui pages with new ui action buttons

* feat: working navbar in new ui

* fix: minor sizing tweaks

* CW-1266-integrate-bitcoin-lightning-through-spark-sdk (#2623)

* feat: add Lightning Network support for Bitcoin wallets

* refactor: rename `fiatConvertationStore` to `fiatConversionStore` for consistency and update related occurrences across codebase

* feat: enhance address validation with Lightning Network invoice support for BTC & refactor wallet type/token checks in view model

* feat: add support for Lightning invoice detection, refactor MWEB deposit/withdraw actions, and integrate Lightning transaction creation with updated priority handling

* feat: add method to retrieve unused Spark deposit address for Bitcoin wallets

* feat: add Breez API key support and update secrets handling for Bitcoin Lightning wallet integration in workflows

* chore: update Breez SDK dependency to version 0.3.4 in pubspec files

* Add bitcoin secrets config [skip ci]

* feat: extend Lightning wallet functionality with transaction history fetching

* feat: add LNURL-pay address detection and support in address parsing flow for Bitcoin Lightning integration

* refactor: simplify `ReceivePageOption` logic

* refactor: centralize `PaymentURI` generation logic across wallet types

* feat: enhance `PaymentURI` handling with asynchronous support and Lightning-specific functionality

* refactor: streamline `PaymentURI` logic and remove redundant URI implementations across wallet types

* refactor: remove redundant debug print statement from `bitcoin_wallet_addresses.dart`

* refactor: improve consistency in widget styling and centralized label logic, add Bitcoin Lightning deposit/withdraw support

* feat: reload balance and tx history after sending a lightning transaction

* feat: improve address formatting for human-readable addresses and update the default LNURL domain

* fix: merge conflicts

* feat: add error handling for LightningWallet initialization and adjust transaction direction logic

* feat: enable private transactions by default in LightningWallet and update Breez SDK version to 0.4.2

* minor fixes [skip ci]

* chore: fix some minor issues in comments (#2654)

Signed-off-by: black5box <black5box@outlook.com>

* fix: handle send-all functionality for LightningWallet transactions and adjust amount calculation logic

* fix-german (#2659)

* chore: update German localization strings for consistency and accuracy

* chore: update German localization strings for consistency and accuracy [skip-ci]

* feat: add LNURL support for address validation and LightningWallet compatibility, enhance error handling for OpenCryptoPay

* fix: adjust LightningWallet amount parsing from 9 to 8 decimal places

* feat: add LNURL support in LightningPaymentRequest and LightningWallet

* Fix navigation gradient (#2657)

* Fix navigation gradient

* Fix CONFIG_ARGS formatting in app_config.sh (#2660)

* fix: block wrongly parsed addresses (#2656)

* fix: block wrongly parsed addresses

* fix: move parsed address check into handlePaymentFlow method

* fix: Handle QR URLs separately for pay anything flow

* feat: add electrum seed support for Lightning

* refactor: improve `parseFixed` logic and add comprehensive unit tests for edge cases (#2661)

* Update cw_bitcoin/lib/bitcoin_wallet.dart [skip ci]

* resolve conflict issue

---------

Signed-off-by: black5box <black5box@outlook.com>
Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>
Co-authored-by: black5box <black5box@outlook.com>
Co-authored-by: tuxsudo <tuxsudo@tux.pizza>
Co-authored-by: cyan <cyjan@mrcyjanek.net>
Co-authored-by: David Adegoke <64401859+Blazebrain@users.noreply.github.com>

* remove old code [skip ci]

* fix: page widgets rebuilt every time

* chore: formatting

* remove unused navbar

* fix: lightning balance on balance card in lightning mode

* fix: return if uri == null

* feat: trade history in new ui

* feat: enhance balance model with secondary asset handling

* feat: unique card colors and icons for coins

* wip: card customization

* fix: merge conflict

* feat: customizable balance card

* Fix some spacings and test sizing

* Fix formatting

* feat: add Lightning Network support for send flow and fee handling adjustments

* refactor: remove unnecessary debug print statement in send flow for Lightning Network balance

* feat: integrate OpenCryptoPay QR handling in send flow and improve scan action handling logic

* feat: add maxDepositClaimFee parameter for Lightning wallet configuration

* Switch balance card to RoundedSuperellipse and set color list to Wrap

* Fix

* Switch to scroll view

* refactor: update navigation route from `receive` to `addressPage` in coin action row

* feat: bloc-based viewmodel for card customizer

* feat: mobx-independent balance card customizer vm

* minor fixes

* copyWith constructor for cleaner state changes

* refactor: wrap `HistorySection` with `Observer` for reactive state updates, update navigation for "Buy" action, and fix incorrect balance property

* feat: enhance Bitcoin receive flow with Lightning and SegWit options, update address page registration, and localize coin action labels

* feat: add helper methods for Lightning and SegWit receive page options in Bitcoin configuration

* feat: add Lightning transaction type handling and enable navigation to transaction details from history

* Add more special card types

* feat: new ui settings page

* feat: add Lightning actions to balance cards, refactor card rendering logic

* refactor: update settings page localization, hide unused settings items

* feat: add secrets generation for cw_bitcoin, including breezApiKey

* Lightning switcher animation (#2725)

* Properly animate bitcoin/lightning switcher

* Cleanup and fix sizing

* Final cleanup

* Fix action button colors (#2732)

* feat: add hardware wallet type handling and improve parsed address reset flow

* Refactor settings page to use generic row items (#2745)

* fix android back button in settings on android, force iphone-style transitions on all platforms

* move settings page to generic row impl

* fix imports

* Balance card fixes (#2729)

* Update balance card sizing

* Fix spacing

* Initial font changes (#2731)

* Initial font changes

* More font changes

* feat: integrate Lightning transaction support and improve transaction history UX

- Enhanced dashboard to compute confirmations using the first and last transactions.
- Updated `BitcoinWallet` to subscribe for and manage Lightning transactions.
- Improved `HistoryTile` layout and introduced new leading icons for Lightning transactions.

* feat: add unclaimed deposit actions and enhance Lightning event handling

* release changes [skip ci]

* Enhanced card customizer (#2744)

* enhanced card customizer

* Fix conflicts

* Add missing icons + adjust spacing

---------

Co-authored-by: tuxsudo <tuxsudo@tux.pizza>

* feat: enhance Lightning invoice handling and address validation

- Added support for identifying non-zero amount Lightning invoices.
- Refined invoice matching with updated regex patterns.
- Improved UI to conditionally display addresses in sending confirmations.
- Adjusted logic to handle zero-value Lightning invoices.

* feat: add `isPayjoinAvailable` computed property and update Payjoin visibility logic

* feat: improve Lightning wallet handling and block explorer logic

* update patch version [skip ci]

---------

Signed-off-by: black5box <black5box@outlook.com>
Co-authored-by: Konstantin Ullrich <konstantinullrich12@gmail.com>
Co-authored-by: OmarHatem <omarh.ismail1@gmail.com>
Co-authored-by: tuxsudo <tuxsudo@tux.pizza>
Co-authored-by: black5box <black5box@outlook.com>
Co-authored-by: cyan <cyjan@mrcyjanek.net>
Co-authored-by: David Adegoke <64401859+Blazebrain@users.noreply.github.com>

* minor new ui fixes

* padding for new row separators

* remove debug prints

* New design improve nav bar (#2763)

* tweak navigation bar touch targets and sizing

* feat: add tests for identifying zero and non-zero amount Lightning invoices (#2772)

* feat: add tests for identifying zero and non-zero amount Lightning invoices

- Added unit tests to validate recognition of Bolt11 zero-amount and non-zero-amount invoices.
- Enhanced `isBolt11ZeroInvoice` function to handle `lightning:` prefixed invoices.

* fix: correct currency selection logic for Lightning wallets in Send ViewModel

* feat: improve Lightning wallet initialization and address generation

- Updated `init` method in `LightningWallet` to return a boolean for initialization success, adding error handling for failed setups.
- Integrated dynamic name generation using `generateName` for Lightning wallet addresses.

* refactor: relocate `generate_name` to `cw_core` and update imports

* chore: update breez sdk (#2789)

* Wire tokens and NFTs to new Home page (#2804)

* wiring for assets on home page

* fix imports

* wire nft page in new ui

* fix nft display in new ui

* fix totalWidth calc

* add tokens button + bugfixes

* add tokens button + bugfixes

* fix late initialization

* fix history section exception

* fixes

* Add haptic feedback (#2813)

* Add haptic feedback

* Add haptic feedback to correct ActionButton

* Return bottom gradient (#2808)

* Add IgnorePointer to bottom nav gradient (#2822)

* New design send page (#2791)

* new ui send page (wip)

* coin control page improvements

* fee settings, new send confirmation modal

* minor aesthetic fixes

* load network name without cw_bitcoin import

* recipient dot cleanup

* minor logic fixes

* ui polish

* - add aliaspay support
- fix wording for max button
- fix back button action in modals

* Sizing changes

* dismiss transaction on modal close

* sizing fix

* - fix remove recipient icon
- properly round amounts
- fix coin control page spacing

* - fix remove recipient icon
- properly round amounts
- fix coin control page spacing

* - fix button sizing
- add description for fees page

* Update lib/view_model/unspent_coins/unspent_coins_list_view_model.dart [skip ci]

* Update lib/view_model/send/send_view_model.dart [skip ci]

---------

Co-authored-by: tuxsudo <tuxsudo@tux.pizza>
Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* Fix conflicts with dev

* Fix conflicts with dev

* Add zcash receive options to new design flow

* wire in missing settings in new ui

* up migration version

* formatting

* translations

* lint.sh

* New design receive page (#2834)

* feat: viewmodel on new receive page (wip)

* feat: address type selector for new ui receive page

* fix: minor fixes to touch targets and tap anims

* minor ui fix

* wip receive page changes

* receive page + address selection page

* receive page + address selection page

* add font

* add svg

* minor ui fixes

* receive page fixes/improvements

* change receive page modal design

* further ui polish

* icons for infobox

* fix restricted import

* fix closing label modal

* - fix balance card appearance on address page
- fix search bar position
- fix mweb position in address type selector

* receive page fixes

* fix anonpay

* remove restricted import

* fixes

* fix receive on zec

* simplify chain id

* lint fix

* fix migration numbering

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* fix migration version

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* fix settings

* readability

* fix formatting

* move dismiss infobox to vm

* disable addr rotation on zcash

* remove _setEffects

* translations

---------

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* New UI Sync bar (#2831)

* syncbar

* small styling fixes

* modify duration

* lint.sh

* syncHeavy wallet types

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* update translations, add pull-down refresh, separate top bar components to files

---------

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* alphabetize

* New design balance card icons (#2824)

* Add the other crypto card icons

* Update Zano, add Zcash and Arbitrum

* Update default card style and available gradients

* Fix broken preview

* Fix animation

* Color combinations fix

* Minor updates

* Add decred icon

* if(!mounted) return;

* New design minor fixes (#2842)

* More minor fixes

* Update modal sheet behaviour

* Update missing currency image links

* List row and navigation bar tweaks

* Minor navbar fix

* New UI Swap page (#2829)

* new ui send page (wip)

* coin control page improvements

* fee settings, new send confirmation modal

* minor aesthetic fixes

* load network name without cw_bitcoin import

* recipient dot cleanup

* minor logic fixes

* ui polish

* - add aliaspay support
- fix wording for max button
- fix back button action in modals

* Sizing changes

* dismiss transaction on modal close

* sizing fix

* - fix remove recipient icon
- properly round amounts
- fix coin control page spacing

* - fix remove recipient icon
- properly round amounts
- fix coin control page spacing

* - fix button sizing
- add description for fees page

* swap page

* fixes

* further fixes

* merge

* png -> svg

* minor condition changes

* lint.sh

* fix swapsxyz isCentralized

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* translations, readability improvements, remove debug rows

* cleanup

* alphabetize strings

* small bugfixes

---------

Co-authored-by: tuxsudo <tuxsudo@tux.pizza>
Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* fix new ui coin control page layout (#2843)

* New design lightning flows (#2821)

* new ui send page (wip)

* coin control page improvements

* fee settings, new send confirmation modal

* minor aesthetic fixes

* load network name without cw_bitcoin import

* recipient dot cleanup

* minor logic fixes

* ui polish

* - add aliaspay support
- fix wording for max button
- fix back button action in modals

* Sizing changes

* dismiss transaction on modal close

* sizing fix

* - fix remove recipient icon
- properly round amounts
- fix coin control page spacing

* - fix remove recipient icon
- properly round amounts
- fix coin control page spacing

* - fix button sizing
- add description for fees page

* lightning flow wip

* lightning flow wip #2

* lightning withdraw flow

* lightning deposit flow (wip, currently works but really janky)

* send from external + bugfixes

* merge fixes

* merge fixes

* fixes

* Update lib/new-ui/widgets/send_page/l2_action_wallet_selector.dart

---------

Co-authored-by: tuxsudo <tuxsudo@tux.pizza>
Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* fix covered create wallet button

* fix: close modal after transaction commitment in Send ViewModel (#2858)

* New design tweaks (#2847)

* Add more haptic feedback

* Fix background gradients and modify SafeArea in home_page.dart

* Fix history padding, fix divider color, disable Charts, update base_page.dart appbar style, fix nav bar border + height on iOS

* Lightning Username setup flow for new UI (#2845)

* lightning username edit/create flow

* fix button color

* fix layout

* fixes

* remove character limitation for internal builds

* remove dependency on cw_bitcoin

* fix username requirements

* fixes

* condition fix

* Update lib/new-ui/pages/lightning_username_page.dart

---------

Co-authored-by: OmarHatem <omarh.ismail1@gmail.com>

* keyboard hide overlay for iphone

* New design UI tweaks (#2870)

* Fix nav height on Android

* Fix blue gradient

* Update transactions view and minor UI tweaks

* CW1011-Allow-users-to-view-bitcoin-amounts-in-sats (#2678)

* feat: introduce `formatFixed` integration and sats display preference

* feat: enable display of Bitcoin amounts in satoshis and refactor amount formatting logic

* refactor: consolidate fee formatting logic and add support for MWEB availability check

* feat: add support for satoshi-based amount display and enhance fiat conversion logic

* feat: add support for satoshi-based amount parsing, formatting, and display preferences across buy/sell flow and UI adjustments

* feat: implement `AmountParsingProxy` with unit tests for parsing and formatting crypto amounts in various display modes

* feat: replace `preferBalanceInSats` with `displayAmountsInSatoshi` and introduce `AmountParsingProxy` for unified crypto amount handling across the app

* refactor: streamline amount formatting logic and enhance unspent coins handling with `AmountParsingProxy` integration for unified crypto processing

* refactor: replace direct bitcoin amount formatting with `AmountParsingProxy` and remove debug print in `exchange_view_model`

* refactor: replace `getIt<AmountParsingProxy>` with `_appStore.amountParsingProxy`, remove redundant dependencies across view models and adjust related imports

* refactor: remove redundant `AmountParsingProxy` registration in DI setup to simplify dependency management [skip ci]

* feat: add getCryptoSymbol to simplify the Symbol selection between Sats and Bitcoin

* fix: merge conflict

* Revert "fix: merge conflict"

This reverts commit 6debdaa0466747d6fcc85d6bd0be115e6fb4d856.

* fix import [skip ci]

* feat: remove number formatter from exchangeVM

* refactor: replace `SettingsStore` with `AppStore` across view models, integrate `AmountParsingProxy` for amount formatting, and clean up redundant imports

* refactor: remove debug print statements from `getCryptoOutputAmount` in `AmountParsingProxy`

* feat: enhance fee and deposit amount formatting with crypto symbols and improved parsing

* feat: integrate `AmountParsingProxy` for improved Bitcoin amount parsing in `PaymentURI` and fiat-to-crypto conversion

* feat: append crypto symbols to Bitcoin transaction amounts in dashboard view

* feat: improve crypto amount parsing in SendCard widget and Output view model using `AmountParsingProxy`

* feat: conditionally show Bitcoin amount display setting for Bitcoin wallets and refactor `DisplaySettingsViewModel` to use `AppStore`

* refactor: clean up redundant imports in `bitcoin_wallet.dart` and `electrum_wallet.dart`

* feat: append crypto symbols to fee values in send and cake pay card widgets for improved clarity

* refactor: replace `currencyTitle` with `currency` across widgets and integrate `AmountParsingProxy` for improved crypto amount formatting and parsing

* refactor: improve validation logic and amount parsing in SendCard and Output widgets

* refactor: standardize amount parsing and formatting logic with `AmountParsingProxy` across ViewModels and widgets

* refactor: `AppStore` remove debug prints

* refactor: rename amount parsing/formatting methods for better clarity in tests [skip ci]

* fix: AmountParsingProxy and optimize `cryptoAmount` handling in BuySellViewModel

* fix: adjust balance calculation for Monero and Wownero to exclude unlocked amount from full balance

* fix: correct `_appStore` usage and format adjustments in `SendViewModel`

* feat: enhance satoshi on new-ui

* feat: add computed property for `amountParsingProxy` in AppStore

* feat: localize Bitcoin amount display option and update asset history UI

* feat: improve exchange amount processing and refactor fiat conversion values

---------

Co-authored-by: OmarHatem <omarh.ismail1@gmail.com>

* New design unconfirmed balance widget (#2861)

* unconfirmed balance display widget for new ui

* unconfirmed balance display widget for new ui

* merge

* alphabetize translations

* New UI fixes (#2860)

* fix asset top bar

* improve wordmark in large qr mode on receive

* receive option fixes

* exchange -> swap

* send page fixes

* update pubspec base

* go to home on wallet change

* nicer card customizer

* don't show account name for single-account wallets

* special card design for lightning

* fiat amount bar improvement

* update translations

* add sending indicator

* fix non-number input to receive amount

* de-jank fiat input

* nicer balance card animation when switching btc-ln

* nicer balance card animation when switching btc-ln

* fix backup password input

* display time+date in history

* fix error on buy

* fix incorrect wallet showing in wallets tab

* fix wallet list layout

* only show coin control option on hasCoinControl

* better error on send page

* fiat value in coin control

* add zano to isSyncHeeavy

* fix keys in settings

* fix assets condition

* fix import

* remove BasePage dependency in RescanPage

* add missing settings

* show send/receive in swap confirm sheet

* fix receive background on ios

* fix assets spacing

* fix trade tile sizing

* fix padding

* fix icon in wallet select modal

* change text on swap initial modal

* spacing

* l2 send external modal styling

* fix null on swap confirm sheet

* change infobox text

* add chain icon to asset widgets

* add chain icon to asset widgets

* disable swap page reset

* fix wallet list page layout

* revert merge conflict issue [skip ci]

---------

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* Account Customizer for new UI Monero (#2859)

* new ui monero account management (wip)

* account reordering wip

* account reordering wip

* account reordering (works)

* cards view compact mode

* format

* translation

* name generation

* fix for non-xmr wallets

* }

* allow reset order, fallback on improperly saved order

* translation

* fix for pre-reorder wallet loading

* fix loading

* - save cards on modal slide-down
- always load active account as first

* fix card customizer close anim

* fixes

* fix condition

* merge

* fix migration versions

* use updated flutter rust bridge in lightning and payjoin

* mvp fixes

* new ui mweb mask/unmask

* fallback for balance card amount format

* New UI tweaks (#2872)

* Update lightning transaction history view

* Add BNB card design

* Color, padding,  and radius fixes

* Fix wallet list bottom section & gradient

*  Update Apps page

* reformat

* nicer sat picker

* fix keyboard

* chain badges

* enhance styling for card customizer

* mweb settings icon

* mweb chain badge

* update wording in settings

* bnb chain icon

* always round send amount

* always round all amount

* token placeholder

* Fix ModernButton colors (#2888)

* Fix ModernButton colors

* Minor

* guard for unconfirmed balance widget

* fix error on wallet switch

* New design mvp fixes (#2890)

* mvp fixes

* fallback for balance card amount format

* reformat

* nicer sat picker

* fix keyboard

* chain badges

* enhance styling for card customizer

* bnb chain icon

* always round send amount

* always round all amount

* guard for unconfirmed balance widget

* fix error on wallet switch

* Update lib/new-ui/pages/account_customizer.dart

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* fixes

---------

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* Install Protoc in reusable build workflow

Added step to install Protoc before building.

* Fix protobuf-compiler installation step

Update package list before installing protobuf-compiler.

* Modify Protoc installation command to handle update errors

Change the install command for Protoc to avoid failure on update.

* Streamline Lightning wallet balance management and crypto handling (#2893)

* refactor: streamline crypto amount handling and improve Lightning balance management

- Removed redundancy in balance calculations for Lightning wallets.
- Centralized crypto symbol creation with `selectedCryptoCurrencySymbol`.
- Enhanced crypto amount handling and formatting with `AmountParsingProxy`.
- Simplified logic for displaying Lightning balances across UI components.

* refactor: remove sats display logic and unused formatting from BalanceCard widget

* chore: update breez-sdk-spark-flutter to latest commit

* feat: enhance crypto amount formatting with localized separators and max decimals

* fixes

* fix: handle null balance records in Lightning wallet cards

* New design add validators (#2894)

* add validation, fix node form

* Add validator to send amount input field

Added a validator to the amount input field.

---------

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* Disable 'addresses' button on receive screen for BTC LN (#2896)

* feat: Disable addresses button on receive screen for BTC LN

* chore: remove debug print in uri computation

* feat: introduce swap action toggle and UI updates

* feat: conditionally display Zcash card setting for Zcash wallets in Display Settings

* Fix leading button color (#2898)

* fix amount format

* fix loadCards

* pre-beta fixes

* cyjan: fix: order being null for certain index

* pre-beta fixes v2 (#2905)

* minor context check [skip ci]

* persist fee priority for zcash (#2907)

* Add support for Zcash address detection and amount logic refactor (#2906)

* refactor: consolidate crypto amount handling with `displayAmount` and `cryptoCurrencySymbol`, improve fiat conversion logic, and optimize token currency management

* refactor: simplify `displayAmount` logic and remove unused `_rawAmount` property

* feat: add support for Zcash transparent address detection and simplify amount conversion logic

* Improve Lightning invoice handling and crypto formatting (#2908)

* fix: update Lightning address regex to support additional formats and prefixes

* fix: conditionally render advanced settings dropdown based on fees or coin control availability

* feat: enhance address detection, Lightning invoice handling, and crypto formatting

* feat: improve Lightning invoice parsing and crypto amount formatting on send page

* chore: remove unnecessary exception printing in `getBolt11Amount` function

* Fix lightning swap

* import fix (hide Mac;)

* parse -> tryParse

* Transaction Commited -> Transaction Sent!

* feat: enable clipboard paste for deposit and receive addresses in swap page (#2909)

* fix: resolving LNURLS (#2911)

* new UI pre-beta fixes (#2910)

* fixes

* parse -> tryParse

* change sat display settings style

* minor fix until hive is removed [skip ci]

* Remove redundant logic and improve send page features (#2913)

* fix: update crypto amount parsing logic in send confirmation sheet

* feat: Added checkbox to toggle Litecoin MWEB coins on the send page.
fix: LNUrlPayRecord

* fix: remove redundant `.withLocalSeperator()` from fiat balance formatting logic

* fix: update Bitcoin amount display titles to align with consistent formatting standards

* force boolean to update (#2916)

* force boolean to update

* fix bnb balance

* fixes #4 (#2917)

* only display sats for btc wallets in card customizer

* fix: resolve async handling of Lightning transaction history in `fetchTransactions` method (#2919)

* New design pre beta fixes 5 (#2918)

* improve l2 deposit/withdraw flow layouts

* add copied indicator

* SafeArea

* fix addr rotation

* fix styling of lightning switcher

* no raster graphics in new ui please

* optimization for assets/history section

* remove unused bloc provider

* optimize dashboard + fix duplicated name

* disable lightning mode on wallet change

* remove broken animation

* safearea around nodes page

* fix rescan page layout

* fix exception on really fast switching

* remove broken blur

* card customizer autosave

* remove debug print

* add better fallbacks for currency titles

* revert due to broken animation

* fix send page crash

* fix chain title for arb

* fix cupertino date picker

* Update lib/new-ui/widgets/receive_page/receive_bottom_buttons.dart [skip ci]

---------

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* feat: add focus management and external address validation to send page forms

- Introduced `focusNode` to `NewSendAddressInput` for better input handling.
- Enhanced address validation by synchronizing with parsed external addresses.
- Updated logic for non-MWEB unspent coin type in send actions.
- Suppressed unnecessary exception logs in Bitcoin wallet transactions.

* New design swap page fixes (#2923)

* swap page fixes

* add scroll controller

* comment

* tweak refresh pulldown (#2924)

* add copy button to l2 send external modal (#2925)

* account customizer padding

* feat: lightning transaction fetching and Lightning wallet integration (#2927)

- Allow nullable `height` in `ElectrumTransactionInfo`.
- Add `fromDate` support for filtered Lightning transaction history retrieval.
- Simplify Lightning address handling logic in wallet addresses.
- Optimize Lightning wallet transaction syncing based on the last Lightning transaction date.
- Clean up imports in `electrum_transaction_history.dart`.

* New balance handeling (#2931)

* feat: lightning transaction fetching and Lightning wallet integration

- Allow nullable `height` in `ElectrumTransactionInfo`.
- Add `fromDate` support for filtered Lightning transaction history retrieval.
- Simplify Lightning address handling logic in wallet addresses.
- Optimize Lightning wallet transaction syncing based on the last Lightning transaction date.
- Clean up imports in `electrum_transaction_history.dart`.

* feat: add support for Lightning balance in wallet snapshot and initialization

* Disable Lightning switcher for hardware wallets (#2932)

* fix: disable Lightning switcher for hardware wallets

* fix: update wallet type check to use `isSoftwareWallet` for Lightning support

* New design pre beta fixes 6 (#2929)

* fix swaps from ln

* prevent crash if ln balance isn't loaded yet

* fix currency icons disappearing on swap confirm sheet

* fix swap fiat validation

* display ln at top on swap currency selector in btc wallets

* update icon for card options

* display default fiat and crypto at top of currency picker

* fix fiat amount bar formatting

* add modal scroll controller to provider logs

* revert premature optimization (sizing issue)

* New design pre beta fixes 7 (#2935)

* fix swaps from ln

* prevent crash if ln balance isn't loaded yet

* fix currency icons disappearing on swap confirm sheet

* fix swap fiat validation

* display ln at top on swap currency selector in btc wallets

* update icon for card options

* display default fiat and crypto at top of currency picker

* fix fiat amount bar formatting

* add modal scroll controller to provider logs

* revert premature optimization (sizing issue)

* copyable trade id

* disable swaptrade on ln

* set isFixedRate properly

* update color

* display trocador provider on swap confirmation sheet

* add "exchange rate is fixed" text

---------

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* updated l2 modal (#2934)

* display names for send addr input (#2936)

* fix: MWEB toggle logic on send page (#2938)

* feat: add retry logic to `getAddress` in Lightning wallet (#2939)

* Enhance crypto address handling and add Lightning invoice support (#2937)

* feat: enhance crypto address handling and add Lightning invoice support

- Added `_overrideFromCryptoCurrency` and `_overrideToCryptoCurrency` for Zcash unified and shielded addresses.
- Improved Lightning invoice generation with `getLightningInvoice` for Bitcoin wallets.
- Updated error handling in exchange provider to accommodate API changes.
- Introduced Lightning invoice fallback for deposit and receive addresses in ExchangeViewModel.

* feat: Added `_overrideFromCryptoCurrency` and `_overrideToCryptoCurrency` for Zcash unified and shielded addresses.

* fix pay anything on paste button (#2940)

* Prevent multiple paste triggering any pay flow

* fixup fiat input (#2941)

* New design small fixes (#2920)

* Fix optical symmetry for swipe to send text

* Update nav bar icons

* Top bar and card tweaks

* Update paddings

---------

Co-authored-by: malik1004x <malikowskirobert@gmail.com>

* fix erc20 balance display (#2944)

* fix erc20 balance display

* route through cw_evm

* New design beta fixes (#2943)

* fix asset tile layout

* fix card customizer keyboard jumping

* fix cardsview exception

* fix swap modal height

* remove syncbar percentage

* add copy icon to trade id

* fix trade confirmation appearing twice

* remove useless mweb setting

* add tag to contact currency selector text

* prettify picker for ln

* fix receive crash

* always route to NewSendPage

* handle ln amount on paste

* handle ln amount on payment request creation

* prettify ln errors

* readd "blocks" word

* register deeplinks

* Enhance bitcoin error message [skip ci]

* fix support chat page (#2946)

* new-design-fix-confirm-sheet-parsing-error (#2950)

* feat: use bigint instead of doubles

* feat: use bigint instead of doubles

* feat: use bigint instead of doubles

* fix: also show sats in confirm sheet

* fix: also show sats in confirm sheet

* feat: localize amounts and cap amount in tx history (#2951)

* fix: linux CI

* feat: localize token balances (#2954)

* fix: send amount hww (#2955)

* chore: use latest breez sdk (#2953)

* fix addAddressWord

* fixes (#2957)

* receive fixes (#2959)

* fix: stabilize android build by increasing jvm heap size (#2958)

* fix: lighting by having the new SDK Save into a new location (#2961)

* New design rc fixes (#2960)

* additional safeguards for isSyncHeavy check

* fix account name getting reset

* update base icon

* fix units in swap

* readd memos to zec

* New design minor UI (#2956)

* Wrap text for list item widgets

* Update lightning address and QR icons

* Update near intents icon

* Fix share issue

* Fix (#2963)

* fix tx amount formatting

* rename currency

* change wording for zec memo

* fix base icon

* fix app icon script [skip ci]

* New design rc fixes 2 (#2965)

* fix account name changes

* fix spacing on addresses page

* add payjoin copy modal

* improve memo ui

* potential fix for ci

* Set default address for zcash and bitcoin for buy flow (#2979)

* new monero.com icons (#2980)

* parse and validate deposit amount from api (#2967)

* generic fixes

* minor context fix [skip ci]

* Generic fixes (#2982)

- solana send all bug
- pasting SOL address triggering payanything flow
- add more address types for payanything detection

* rescan fix

* about page (#2974)

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* update settings icons/wording (#2973)

* Changelog modal (New UI) (#2971)

* add new changelog modal

* typo

* print -> printV

* Update lib/new-ui/widgets/changelog_modal.dart [skip ci]

---------

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* fix node form (#2970)

* new-design-add-breez-logging (#2984)

* feat: add Lightning log export functionality for Bitcoin wallets

* feat: add multilingual support for Lightning log export strings

* feat: add Lightning support toggle in settings and translations for multiple languages

* refactor: simplify `setUseLightning` by removing redundant store update

* Update cw_bitcoin/lib/electrum_wallet.dart [skip ci]

---------

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* minor fixes [skip ci]

* minor context fixe [skip ci]

* fix: make walletinfoid unique to prevent duplicates (#2969)

* fix: walletconnect not working in new design builds (#2993)

* new-design-fix-mweb-coin-enabling (#2995)

* feat: add unspent coin type handling to asset details modal send button

* fix: improve German translations for wallet, seed, and Lightning-related strings

* fix: update Dutch translations to correct terminology and formatting #2992 (#2997)

* fix: drop gn (#3000)

* vulnerable seeds popup on new ui (#3004)

* update mac os monero.com icons (#3003)

* Add Payjoin log export and improve logging behavior (#2999)

* fix: suppress exception logging in `getAddress` method of Lightning wallet

- Added a try-catch block to avoid unnecessary exception logs during Lightning address retries.

* fix: update fallback message for missing Lightning address detection

* feat: add Payjoin log export and logging enhancements

* fix: localize "Export Payjoin Logs" string in settings page

* fix: litecoin mweb balance being included in the second asset (#2998)

* Minor fixes (#2994)

* Minor fixes

* Update lib/new-ui/new_dashboard.dart [skip ci]

---------

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* New design post release fixes (#3002)

* fix: only throw on deserialize if kDebugMode is true (#2976)

This closes #2972, in debug mode we will still catch these issues but if
somehow that happens on production it will fallback to safe default

* fix: update docs and dockerfile (#2975)

* fix: missing steps for linux build [skip ci] (#2985)

* move balance to bigint

* move balance to bigint

* fix electrum issue

* fix unconfirmed balance

* fixes

* Fix minor issue in Spanish translation (#2991)

* Fix minor issue in French translation (#2987)

* Fix minor issues in German translation (#2986)

* update constructor calls in configure.dart

* fixes

* remove expnded

* V6.0.1 Early Release Candidate

---------

Co-authored-by: cyan <cyjan@mrcyjanek.net>
Co-authored-by: Edwin den Boer <woordenboer@planet.nl>
Co-authored-by: OmarHatem <omarh.ismail1@gmail.com>

* Swaps xyz swap enhancements (#2615)

* refactor token cache and limit handling

* Improve SwapsXYZ external send logic

* Improve SwapsXYZ fixed-rate handling

* disable fixedRate for SwapsXyz

* SwapsXYZ contract call

* Add track url for swaps xyz

* add arbitrum support

* add check for unsupported source tokens

* enable SwapsXyzExchangeProvider in provider list

* refactor SwapsXYZ provider and trade flow handling

* Update exchange_trade_view_model.dart

* validate evm call-data

* Revert "validate evm call-data"

* fix msg value for ERC-20 transfers

* fix flag for swapsXYZ send check

* Update send_view_model.dart

* handle Swaps.xyz method selectors & approvals

* fix evm approvals

* Improve EVM token approval & receipt handling

* merge split token transfers in evm tx

* fix token allowance check for approvals

* add sourceToken validation to EVM tx creation

* prioritizing incoming transactions over fetched outgoing ones

* compute net flow when merging transactions

* add truncateTrailingText to list items and widgets

---------

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>
Co-authored-by: Serhii-Borodenko <17529954+Serhii-Borodenko@users.noreply.github.com>

* fix wownero balance (#3007)

* fix keyboard (#3006)

* fix android build

* check if stream is closed [skip ci]

* [skip ci] lint

* fix: populate amount field (#3009)

* fix address rotation exception (#3011)

* copy uri with amount from recieve page (#3010)

* add "transaction sent!" to swap confirmation sheet (#3012)

* fix wallet change on token swaps (#3013)

* Fix fee estimation and recipient logic in Lightning Network (#3014)

* fix: update `hasMultiRecipient` logic to include non-Lightning coin type check

* fix: Lightning Network fee estimation and parsing logic

* fix: adjust `sumByBigInt` logic to handle `sendAll` flag in send page

* fix: move sqlite migrations to sqlite.dart (#3008)

* fix: move sqlite migrations to sqlite.dart
fix: backup restore not initializing SQL properly

* Update cw_core/lib/db/sqlite.dart

---------

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* feat: update currency symbol handling and extend Electrum transaction details (#3016)

* Use isCentralized for truncation trade id [skip ci]

* fix: Incorrect token amount for tokens and filter out new spam transactions after swaps (#3015)

* New design release swap fixes (#3018)

* fix deserialize ln

* fix get wallet type for bnb tokens

* show extraId for swaps

* chore: translate using gpt-5.2 (#3021)

* add NEAR send-all validation

* tiny ui fixes (#3023)

* use double parsing for amount comparison[skip ci]

* adjust lightning address error message

* feat: add BTC LN support to available methods and payment data handling

* feat: add cached Lightning address handling for improved performance (#3025)

- Introduced `cachedAddress` field to store and reuse the last fetched Lightning address.
- Updated `getLightningAddress` method to fallback on `cachedAddress` if no new address is fetched.
- Extended wallet constructors and snapshots to include `cachedLightningAddress` for persistence.

* Revert transaction history color

* Minor

* Apply suggestion from @malik1004x

* new-design-post-release-fixes-3 (#3028)

* fix unnecessary account switching

* fix exception on bad payment amount

* fallback for currencies on external swap modal

* increase balance card touch target

* don't use lightning addresses for exchange

* increase max length for ln encoding

* don't show infobox on ln receive

* fix showing old tx details (null tx on createTransaction)

* remove unused import

* refactor: relocate `_logStream` declaration in `LightningWallet` for better code organization (#3029)

* monero build fix
update build numbers
fix best rate null [skip ci]

* hide swap on mweb asset

* minor context fix [skip ci]

* Fix Silent payment case

* new-ui: fix changelog typo (#3036)

Fix typo in changelog for account management.

* Modify date format to Month DD YYYY

* feat: docker based ci

* Fix 2FA continue button location (#3043)

* fix: Desktop wallet bugs (#2968)

* fix: Desktop wallet bugs
- repeated wallets post migration
- newly created wallets not showing up
- extra large components on desktop, needed maxwidth

* chore: Remove duplicate logic

* chore: remove formatting

* refactor: streamline updateList method and handle multiple calls with a future based mutex

* refactor: enhance swipe to confirm with dynamic width handling and improved drag threshold logic

* Improve error handling and duplicate invoice handling in Lightning wallet (#3047)

* fix: handle duplicate Lightning invoice payments gracefully

* fix: improved error handling in Lightning wallet

* General improvements (#3030)

* General Improvements
- Make borderRadius for CTAs uniform 18px
- Identify hardware wallets in title of Seeds/Keys page
- Make entire wallet tile clickable in wallet list

* chore: Simplify check

* Update lib/view_model/wallet_keys_view_model.dart [skip ci]

---------

Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>

* homescreen improvements (#3034)

* Homescreen improvements
- Increase touch area for card editing icon
- Tapping any card in the background should move it ino the foreground without closing the account tab
- make top left chain icon primary color with full opacity when syncing and 20% when done
- add tor indicator to top bar when enabled

* fix: remove unneeded color filter

* refactor: Adjust structure for tor and sync indicators

* minor fixes (#3045)

* Enhance LNURL payment integration (#3041)

* feat: enhance LNURL support and Lightning payment handling

- Improve LNURL decoding and encoding with expanded prefix handling.
- Add support for parsing and validating LNURL payment invoices.
- Introduce logic for fetching LNURL payment request amounts.
- Update payment flow to integrate LNURL and Lightning-specific conditions.
- Refactor BOLT11 prefix validation and amount extraction logic.

* fix: simplify LNURL invoice validation by removing redundant BOLT11 check

---------

Signed-off-by: black5box <black5box@outlook.com>
Co-authored-by: Serhii <borodenko.sv@gmail.com>
Co-authored-by: malik1004x <malikowskirobert@gmail.com>
Co-authored-by: Konstantin Ullrich <konstantinullrich12@gmail.com>
Co-authored-by: tuxsudo <tuxsudo@tux.pizza>
Co-authored-by: black5box <black5box@outlook.com>
Co-authored-by: cyan <cyjan@mrcyjanek.net>
Co-authored-by: David Adegoke <64401859+Blazebrain@users.noreply.github.com>
Co-authored-by: Konstantin Ullrich <konstantin@cakewallet.com>
Co-authored-by: Edwin den Boer <woordenboer@planet.nl>
Co-authored-by: Serhii <17529954+serhii-bor@users.noreply.github.com>
Co-authored-by: Serhii-Borodenko <17529954+Serhii-Borodenko@users.noreply.github.com>
Co-authored-by: rottenwheel <92872541+rottenwheel@users.noreply.github.com>
2026-03-11 04:26:57 +02:00

3444 lines
114 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:isolate';
import 'package:bitcoin_base/bitcoin_base.dart';
import 'package:cw_core/hardware/hardware_wallet_service.dart';
import 'package:cw_core/root_dir.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_bitcoin/bitcoin_wallet.dart';
import 'package:cw_bitcoin/litecoin_wallet.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:blockchain_utils/blockchain_utils.dart';
import 'package:collection/collection.dart';
import 'package:cw_bitcoin/address_from_output.dart';
import 'package:cw_bitcoin/bitcoin_address_record.dart';
import 'package:cw_bitcoin/bitcoin_transaction_credentials.dart';
import 'package:cw_bitcoin/bitcoin_transaction_priority.dart';
import 'package:cw_bitcoin/bitcoin_unspent.dart';
import 'package:cw_bitcoin/bitcoin_wallet_keys.dart';
import 'package:cw_bitcoin/electrum.dart' as electrum;
import 'package:cw_bitcoin/electrum_balance.dart';
import 'package:cw_bitcoin/electrum_derivations.dart';
import 'package:cw_bitcoin/electrum_transaction_history.dart';
import 'package:cw_bitcoin/electrum_transaction_info.dart';
import 'package:cw_bitcoin/electrum_wallet_addresses.dart';
import 'package:cw_bitcoin/exceptions.dart';
import 'package:cw_bitcoin/pending_bitcoin_transaction.dart';
import 'package:cw_bitcoin/utils.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/encryption_file_utils.dart';
import 'package:cw_core/get_height_by_date.dart';
import 'package:cw_core/node.dart';
import 'package:cw_core/output_info.dart';
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/pending_transaction.dart';
import 'package:cw_core/sync_status.dart';
import 'package:cw_core/transaction_direction.dart';
import 'package:cw_core/transaction_priority.dart';
import 'package:cw_core/unspent_coin_type.dart';
import 'package:cw_core/unspent_coins_info.dart';
import 'package:cw_core/utils/socket_health_logger.dart';
import 'package:cw_core/utils/tor/abstract.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/wallet_info.dart';
import 'package:cw_core/wallet_keys_file.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:flutter/foundation.dart';
import 'package:hex/hex.dart';
import 'package:hive/hive.dart';
import 'package:mobx/mobx.dart';
import 'package:rxdart/subjects.dart';
import 'package:sp_scanner/sp_scanner.dart';
part 'electrum_wallet.g.dart';
class ElectrumWallet = ElectrumWalletBase with _$ElectrumWallet;
abstract class ElectrumWalletBase
extends WalletBase<ElectrumBalance, ElectrumTransactionHistory, ElectrumTransactionInfo>
with Store, WalletKeysFile {
ElectrumWalletBase({
required String password,
required WalletInfo walletInfo,
required DerivationInfo derivationInfo,
required Box<UnspentCoinsInfo> unspentCoinsInfo,
required this.network,
required this.encryptionFileUtils,
String? xpub,
String? mnemonic,
Uint8List? seedBytes,
this.passphrase,
List<BitcoinAddressRecord>? initialAddresses,
electrum.ElectrumClient? electrumClient,
ElectrumBalance? initialBalance,
CryptoCurrency? currency,
bool? alwaysScan,
this.useLightning = true,
}) : _masterHD = getMasterHD(seedBytes, network, walletInfo.hardwareWalletType),
accountHD = getAccountHDWallet(
currency, network, seedBytes, xpub, derivationInfo, walletInfo.hardwareWalletType),
syncStatus = NotConnectedSyncStatus(),
_password = password,
_feeRates = <int>[],
_isTransactionUpdating = false,
isEnabledAutoGenerateSubaddress = true,
unspentCoins = [],
_scripthashesUpdateSubject = {},
this.alwaysScan = alwaysScan,
silentPaymentsScanningActive = alwaysScan ?? false,
balance = ObservableMap<CryptoCurrency, ElectrumBalance>.of(currency != null
? {
currency: initialBalance ??
ElectrumBalance(
confirmed: 0,
unconfirmed: 0,
frozen: 0,
)
}
: {}),
this.unspentCoinsInfo = unspentCoinsInfo,
this.isTestnet = !network.isMainnet,
this._mnemonic = mnemonic,
super(walletInfo, derivationInfo) {
this.electrumClient = electrumClient ?? electrum.ElectrumClient();
this.walletInfo = walletInfo;
this.derivationInfo = derivationInfo;
transactionHistory = ElectrumTransactionHistory(
walletInfo: walletInfo,
password: password,
encryptionFileUtils: encryptionFileUtils,
);
reaction((_) => syncStatus, _syncStatusReaction);
sharedPrefs.complete(SharedPreferences.getInstance());
}
static Bip32Slip10Secp256k1 getAccountHDWallet(
CryptoCurrency? currency,
BasedUtxoNetwork network,
Uint8List? seedBytes,
String? xpub,
DerivationInfo? derivationInfo,
HardwareWalletType? hardwareWalletType) {
if (seedBytes == null && xpub == null) {
throw Exception(
"To create a Wallet you need either a seed or an xpub. This should not happen");
}
if (seedBytes != null) {
switch (currency) {
case CryptoCurrency.btc:
case CryptoCurrency.ltc:
case CryptoCurrency.tbtc:
return Bip32Slip10Secp256k1.fromSeed(
seedBytes, getKeyNetVersion(network, hardwareWalletType))
.derivePath(
_hardenedDerivationPath(derivationInfo?.derivationPath ?? electrum_path))
as Bip32Slip10Secp256k1;
case CryptoCurrency.bch:
return bitcoinCashHDWallet(seedBytes);
case CryptoCurrency.doge:
return dogecoinHDWallet(seedBytes);
default:
throw Exception("Unsupported currency");
}
}
return Bip32Slip10Secp256k1.fromExtendedKey(
xpub!, getKeyNetVersion(network, hardwareWalletType));
}
static Bip32Slip10Secp256k1 bitcoinCashHDWallet(Uint8List seedBytes) =>
Bip32Slip10Secp256k1.fromSeed(seedBytes).derivePath("m/44'/145'/0'") as Bip32Slip10Secp256k1;
static Bip32Slip10Secp256k1 dogecoinHDWallet(Uint8List seedBytes) =>
Bip32Slip10Secp256k1.fromSeed(seedBytes).derivePath("m/44'/3'/0'") as Bip32Slip10Secp256k1;
static int estimatedTransactionSize(int inputsCount, int outputsCounts) =>
inputsCount * 68 + outputsCounts * 34 + 10;
static Bip32KeyNetVersions? getKeyNetVersion(BasedUtxoNetwork network,
[HardwareWalletType? hardwareWalletType]) {
switch (network) {
case LitecoinNetwork.mainnet:
if ([HardwareWalletType.ledger, HardwareWalletType.trezor].contains(hardwareWalletType))
return Bip44Conf.litecoinMainNet.altKeyNetVer;
return null;
default:
return null;
}
}
static Bip32Slip10Secp256k1? getMasterHD(Uint8List? seedBytes,
[BasedUtxoNetwork? network, HardwareWalletType? hardwareWalletType]) {
if (seedBytes == null) return null;
return Bip32Slip10Secp256k1.fromSeed(
seedBytes, network != null ? getKeyNetVersion(network, hardwareWalletType) : null);
}
@observable
bool? alwaysScan;
@observable
bool useLightning;
final Bip32Slip10Secp256k1? _masterHD;
final Bip32Slip10Secp256k1 accountHD;
final String? _mnemonic;
Bip32Slip10Secp256k1 get hd => accountHD.childKey(Bip32KeyIndex(0));
Bip32Slip10Secp256k1 get sideHd => accountHD.childKey(Bip32KeyIndex(1));
final EncryptionFileUtils encryptionFileUtils;
@override
final String? passphrase;
@override
@observable
bool isEnabledAutoGenerateSubaddress;
late electrum.ElectrumClient electrumClient;
Box<UnspentCoinsInfo> unspentCoinsInfo;
@override
late ElectrumWalletAddresses walletAddresses;
@override
@observable
late ObservableMap<CryptoCurrency, ElectrumBalance> balance;
@override
@observable
SyncStatus syncStatus;
Set<String> get addressesSet => walletAddresses.allAddresses
.where((element) => element.type != SegwitAddresType.mweb)
.map((addr) => addr.address)
.toSet();
List<String> get scriptHashes => walletAddresses.addressesByReceiveType
.where((addr) => RegexUtils.addressTypeFromStr(addr.address, network) is! MwebAddress)
.map((addr) => (addr as BitcoinAddressRecord).getScriptHash(network))
.toList();
List<String> get publicScriptHashes => walletAddresses.allAddresses
.where((addr) => !addr.isHidden)
.where((addr) => RegexUtils.addressTypeFromStr(addr.address, network) is! MwebAddress)
.map((addr) => addr.getScriptHash(network))
.toList();
String get xpub => accountHD.publicKey.toExtended;
@override
String? get seed => _mnemonic;
@override
WalletKeysData get walletKeysData =>
WalletKeysData(mnemonic: _mnemonic, xPub: xpub, passphrase: passphrase);
@override
String get password => _password;
BasedUtxoNetwork network;
@override
bool isTestnet;
bool get hasSilentPaymentsScanning => type == WalletType.bitcoin && keys.privateKey.isNotEmpty;
@observable
bool nodeSupportsSilentPayments = true;
@observable
bool silentPaymentsScanningActive = false;
bool _isTryingToConnect = false;
Completer<SharedPreferences> sharedPrefs = Completer();
Future<bool> checkIfMempoolAPIIsEnabled() async {
bool isMempoolAPIEnabled = (await sharedPrefs.future).getBool("use_mempool_fee_api") ?? true;
return isMempoolAPIEnabled;
}
@action
Future<void> setSilentPaymentsScanning(bool active) async {
silentPaymentsScanningActive = active;
if (active) {
syncStatus = AttemptingScanSyncStatus();
final tip = await getUpdatedChainTip();
if (tip == walletInfo.restoreHeight) {
syncStatus = SyncedTipSyncStatus(tip);
return;
}
if (tip > walletInfo.restoreHeight) {
_setListeners(walletInfo.restoreHeight, chainTipParam: currentChainTip);
}
} else {
alwaysScan = false;
_isolate?.then((value) => value.kill(priority: Isolate.immediate));
if (electrumClient.isConnected) {
syncStatus = SyncedSyncStatus();
} else {
syncStatus = NotConnectedSyncStatus();
}
}
}
int? currentChainTip;
Future<int> getCurrentChainTip() async {
if ((currentChainTip ?? 0) > 0) {
return currentChainTip!;
}
currentChainTip = await electrumClient.getCurrentBlockChainTip() ?? 0;
return currentChainTip!;
}
Future<int> getUpdatedChainTip() async {
final newTip = await electrumClient.getCurrentBlockChainTip();
if (newTip != null && newTip > (currentChainTip ?? 0)) {
currentChainTip = newTip;
}
return currentChainTip ?? 0;
}
@override
BitcoinWalletKeys get keys {
String? wif;
String? privateKey;
String? publicKey;
try {
wif = WifEncoder.encode(hd.privateKey.raw, netVer: network.wifNetVer);
} catch (_) {}
try {
privateKey = hd.privateKey.toHex();
} catch (_) {}
try {
publicKey = hd.publicKey.toHex();
} catch (_) {}
return BitcoinWalletKeys(
wif: wif ?? '',
privateKey: privateKey ?? '',
publicKey: publicKey ?? '',
xpub: xpub,
);
}
String _password;
List<BitcoinUnspent> unspentCoins;
List<int> _feeRates;
// ignore: prefer_final_fields
Map<String, BehaviorSubject<Object>?> _scripthashesUpdateSubject;
// ignore: prefer_final_fields
BehaviorSubject<Object>? _chainTipUpdateSubject;
bool _isTransactionUpdating;
Future<Isolate>? _isolate;
void Function(FlutterErrorDetails)? _onError;
Timer? _autoSaveTimer;
StreamSubscription<dynamic>? _receiveStream;
Timer? _updateFeeRateTimer;
static const int _autoSaveInterval = 1;
Future<void> init() async {
await walletAddresses.init();
await transactionHistory.init();
await cleanUpDuplicateUnspentCoins();
await save();
_autoSaveTimer =
Timer.periodic(Duration(minutes: _autoSaveInterval), (_) async => await save());
}
@action
Future<void> _setListeners(int height,
{int? chainTipParam, bool? doSingleScan, List<int>? rescanHeights}) async {
if (this is! BitcoinWallet) return;
if (isHardwareWallet) return;
if (seed?.isEmpty ?? true) return;
final chainTip = chainTipParam ?? await getUpdatedChainTip();
final shouldUpdateSyncStatus = rescanHeights == null || rescanHeights.isEmpty;
if (chainTip == height) {
syncStatus = SyncedSyncStatus();
return;
}
if (shouldUpdateSyncStatus) syncStatus = AttemptingScanSyncStatus();
if (_isolate != null) {
final runningIsolate = await _isolate!;
runningIsolate.kill(priority: Isolate.immediate);
}
final appDir = await getAppDir();
String debugLogPath = "${appDir.path}/logs/debug.log";
final receivePort = ReceivePort();
_isolate = Isolate.spawn(
_handleScanSilentPayments,
ScanData(
sendPort: receivePort.sendPort,
silentAddress: walletAddresses.silentAddress!,
masterHD: _masterHD!,
network: network,
height: height,
chainTip: chainTip,
electrumClient: electrum.ElectrumClient(),
transactionHistoryIds: transactionHistory.transactions.keys.toList(),
node: (await getNodeSupportsSilentPayments()) == true
? ScanNode(node!.uri, node!.useSSL)
: null,
labels: walletAddresses.labels,
labelIndexes: walletAddresses.silentAddresses
.where((addr) => addr.type == SilentPaymentsAddresType.p2sp && addr.index >= 1)
.map((addr) => addr.index)
.toList(),
isSingleScan: doSingleScan ?? false,
debugLogPath: debugLogPath,
rescanHeights: rescanHeights,
),
);
await _receiveStream?.cancel();
_receiveStream = receivePort.listen((var message) async {
if (message is Map<String, ElectrumTransactionInfo>) {
for (final map in message.entries) {
final txid = map.key;
final tx = map.value;
if (tx.unspents != null) {
final existingTxInfo = transactionHistory.transactions[txid];
final txAlreadyExisted = existingTxInfo != null;
// Updating tx after re-scanned
if (txAlreadyExisted) {
existingTxInfo.amount = tx.amount;
existingTxInfo.confirmations = tx.confirmations;
existingTxInfo.height = tx.height;
existingTxInfo.date = tx.date;
existingTxInfo.isReceivedSilentPayment = tx.isReceivedSilentPayment;
existingTxInfo.direction = tx.direction;
existingTxInfo.isPending = tx.isPending;
existingTxInfo.unspents = tx.unspents;
final newUnspents = tx.unspents!
.where((unspent) => !(existingTxInfo.unspents?.any((element) =>
element.hash.contains(unspent.hash) &&
element.vout == unspent.vout &&
element.value == unspent.value) ??
false))
.toList();
if (newUnspents.isNotEmpty) {
newUnspents.forEach(_updateSilentAddressRecord);
existingTxInfo.unspents ??= [];
existingTxInfo.unspents!.addAll(newUnspents);
final newAmount = newUnspents.length > 1
? newUnspents.map((e) => e.value).reduce((value, unspent) => value + unspent)
: newUnspents[0].value;
if (existingTxInfo.direction == TransactionDirection.incoming) {
existingTxInfo.amount += newAmount;
}
// Updates existing TX
transactionHistory.addOne(existingTxInfo);
// Update balance record
balance[currency]!.confirmed += newAmount;
}
} else {
// else: First time seeing this TX after scanning
tx.unspents!.forEach(_updateSilentAddressRecord);
// Add new TX record
transactionHistory.addMany(message);
// Update balance record
balance[currency]!.confirmed += tx.amount;
await save();
}
await updateAllUnspents();
}
}
}
if (message is SyncResponse) {
if (message.syncStatus is UnsupportedSyncStatus) {
nodeSupportsSilentPayments = false;
}
if (message.syncStatus is SyncingSyncStatus) {
var status = message.syncStatus as SyncingSyncStatus;
if (shouldUpdateSyncStatus) syncStatus = SyncingSyncStatus(status.blocksLeft, status.ptc);
} else {
if (shouldUpdateSyncStatus) syncStatus = message.syncStatus;
}
await walletInfo.updateRestoreHeight(message.height);
}
});
}
void _updateSilentAddressRecord(BitcoinSilentPaymentsUnspent unspent) {
final silentAddress = walletAddresses.silentAddress!;
final silentPaymentAddress = SilentPaymentAddress(
version: silentAddress.version,
B_scan: silentAddress.B_scan,
B_spend: unspent.silentPaymentLabel != null
? silentAddress.B_spend.tweakAdd(
BigintUtils.fromBytes(BytesUtils.fromHexString(unspent.silentPaymentLabel!)),
)
: silentAddress.B_spend,
);
final addressRecord = walletAddresses.silentAddresses
.firstWhereOrNull((address) => address.address == silentPaymentAddress.toString());
addressRecord?.txCount += 1;
addressRecord?.balance += unspent.value;
walletAddresses.addSilentAddresses(
[unspent.bitcoinAddressRecord as BitcoinSilentPaymentAddressRecord],
);
}
DateTime? _lastSilentPaymentsScan;
static const Duration _silentPaymentsScanDelay = Duration(minutes: 1);
@action
@override
Future<void> startSync() async {
try {
if (syncStatus is SyncronizingSyncStatus) {
return;
}
syncStatus = SyncronizingSyncStatus();
if (hasSilentPaymentsScanning) {
silentPaymentsScanningActive = alwaysScan ?? false;
await _setInitialHeight();
final now = DateTime.now();
final shouldForceRescan = _lastSilentPaymentsScan == null ||
now.difference(_lastSilentPaymentsScan!) >= _silentPaymentsScanDelay;
// Timer prevents server failure and this infinite looping and requesting
if (shouldForceRescan) {
_lastSilentPaymentsScan = now;
final rescanHeights = <int>[];
transactionHistory.transactions.values.forEach((tx) {
if (tx.unspents != null && tx.unspents!.isNotEmpty)
for (final unspent in tx.unspents!) {
if (unspent.silentPaymentTweak != null && tx.height != null && tx.height! > 0) {
rescanHeights.add(tx.height!);
break;
}
}
});
if (rescanHeights.isNotEmpty)
_setListeners(walletInfo.restoreHeight, rescanHeights: rescanHeights);
}
}
await subscribeForUpdates();
await updateTransactions();
await updateAllUnspents();
await updateBalance();
await updateFeeRates();
_updateFeeRateTimer ??=
Timer.periodic(const Duration(minutes: 1), (timer) async => await updateFeeRates());
if (alwaysScan == true) {
setSilentPaymentsScanning(true);
} else {
if (syncStatus is LostConnectionSyncStatus) {
return;
}
syncStatus = SyncedSyncStatus();
}
} catch (e, stacktrace) {
printV(stacktrace);
printV("startSync $e");
syncStatus = FailedSyncStatus();
}
}
@action
Future<void> updateFeeRates() async {
if (await checkIfMempoolAPIIsEnabled() && type == WalletType.bitcoin) {
try {
final response = await ProxyWrapper()
.get(clearnetUri: Uri.parse("https://mempool.cakewallet.com/api/v1/fees/recommended"))
.timeout(Duration(seconds: 15));
final result = json.decode(response.body) as Map<String, dynamic>;
final slowFee = (result['economyFee'] as num?)?.toInt() ?? 0;
int mediumFee = (result['hourFee'] as num?)?.toInt() ?? 0;
int fastFee = (result['fastestFee'] as num?)?.toInt() ?? 0;
if (slowFee == mediumFee) {
mediumFee++;
}
while (fastFee <= mediumFee) {
fastFee++;
}
_feeRates = [slowFee, mediumFee, fastFee];
return;
} catch (e) {
printV(e);
}
}
final feeRates = await electrumClient.feeRates(network: network);
if (feeRates != [0, 0, 0]) {
_feeRates = feeRates;
} else if (isTestnet) {
_feeRates = [1, 1, 1];
}
}
Node? node;
Future<bool> getNodeIsElectrs() async {
if (node == null) {
return false;
}
final version = await electrumClient.version();
if (version.isNotEmpty) {
final server = version[0];
if (server.toLowerCase().contains('electrs')) {
node!.isElectrs = true;
if (node!.isInBox) {
node!.save();
}
return node!.isElectrs!;
}
}
node!.isElectrs = false;
return node!.isElectrs!;
}
Future<bool> getNodeSupportsSilentPayments() async {
// As of today (august 2024), only ElectrumRS supports silent payments
if (!(await getNodeIsElectrs())) {
return false;
}
if (node == null) {
return false;
}
try {
final tweaksResponse = await electrumClient.getTweaks(height: 0);
if (tweaksResponse != null) {
node!.supportsSilentPayments = true;
node!.save();
return node!.supportsSilentPayments!;
}
} on electrum.RequestFailedTimeoutException catch (_) {
node!.supportsSilentPayments = false;
node!.save();
return node!.supportsSilentPayments!;
} catch (_) {}
node!.supportsSilentPayments = false;
node!.save();
return node!.supportsSilentPayments!;
}
@action
@override
Future<void> connectToNode({required Node node}) async {
this.node = node;
if (syncStatus is ConnectingSyncStatus) return;
try {
syncStatus = ConnectingSyncStatus();
await _receiveStream?.cancel();
await electrumClient.close();
electrumClient.onConnectionStatusChange = _onConnectionStatusChange;
await electrumClient.connectToUri(node.uri, useSSL: node.useSSL);
} catch (e, stacktrace) {
printV(stacktrace);
printV("connectToNode $e");
syncStatus = FailedSyncStatus();
}
}
int get networkDustAmount => 546;
bool _isBelowDust(int amount) => amount <= networkDustAmount && network != BitcoinNetwork.testnet;
UtxoDetails _createUTXOS({
required bool sendAll,
required bool paysToSilentPayment,
int credentialsAmount = 0,
int? inputsCount,
UnspentCoinType coinTypeToSpendFrom = UnspentCoinType.any,
}) {
List<UtxoWithAddress> utxos = [];
List<Outpoint> vinOutpoints = [];
List<ECPrivateInfo> inputPrivKeyInfos = [];
final publicKeys = <String, PublicKeyWithDerivationPath>{};
int allInputsAmount = 0;
bool spendsSilentPayment = false;
bool spendsUnconfirmedTX = false;
int leftAmount = credentialsAmount;
var availableInputs = unspentCoins.where((utx) {
if (!utx.isSending || utx.isFrozen) {
return false;
}
switch (coinTypeToSpendFrom) {
case UnspentCoinType.mweb:
return utx.bitcoinAddressRecord.type == SegwitAddresType.mweb;
case UnspentCoinType.nonMweb:
return utx.bitcoinAddressRecord.type != SegwitAddresType.mweb;
case UnspentCoinType.any:
case UnspentCoinType.lightning:
return true;
}
}).toList();
final unconfirmedCoins = availableInputs.where((utx) => utx.confirmations == 0).toList();
// sort the unconfirmed coins so that mweb coins are last:
availableInputs.sort((a, b) => a.bitcoinAddressRecord.type == SegwitAddresType.mweb ? 1 : -1);
for (int i = 0; i < availableInputs.length; i++) {
final utx = availableInputs[i];
if (!spendsUnconfirmedTX) spendsUnconfirmedTX = utx.confirmations == 0;
if (paysToSilentPayment) {
// Check inputs for shared secret derivation
if (utx.bitcoinAddressRecord.type == SegwitAddresType.p2wsh) {
throw BitcoinTransactionSilentPaymentsNotSupported();
}
}
allInputsAmount += utx.value;
leftAmount = leftAmount - utx.value;
final address = RegexUtils.addressTypeFromStr(utx.address, network);
ECPrivate? privkey;
bool? isSilentPayment = false;
final hd =
utx.bitcoinAddressRecord.isHidden ? walletAddresses.sideHd : walletAddresses.mainHd;
if (utx.bitcoinAddressRecord is BitcoinSilentPaymentAddressRecord) {
final unspentAddress = utx.bitcoinAddressRecord as BitcoinSilentPaymentAddressRecord;
privkey = ECPrivate.fromHex(
_masterHD!.derivePath(unspentAddress.spendDerivationPath).privateKey.toHex())
.tweakAdd(
BigintUtils.fromBytes(BytesUtils.fromHexString(unspentAddress.silentPaymentTweak!)),
);
spendsSilentPayment = true;
isSilentPayment = true;
} else if (!isHardwareWallet && keys.privateKey.isNotEmpty) {
privkey =
generateECPrivate(hd: hd, index: utx.bitcoinAddressRecord.index, network: network);
}
vinOutpoints.add(Outpoint(txid: utx.hash, index: utx.vout));
String pubKeyHex;
if (privkey != null) {
inputPrivKeyInfos.add(ECPrivateInfo(
privkey,
address.type == SegwitAddresType.p2tr,
tweak: !isSilentPayment,
));
pubKeyHex = privkey.getPublic().toHex();
} else {
pubKeyHex = hd.childKey(Bip32KeyIndex(utx.bitcoinAddressRecord.index)).publicKey.toHex();
}
final derivationPath =
"${_hardenedDerivationPath(derivationInfo.derivationPath ?? electrum_path)}"
"/${utx.bitcoinAddressRecord.isHidden ? "1" : "0"}"
"/${utx.bitcoinAddressRecord.index}";
publicKeys[address.pubKeyHash()] = PublicKeyWithDerivationPath(pubKeyHex, derivationPath);
utxos.add(
UtxoWithAddress(
utxo: BitcoinUtxo(
txHash: utx.hash,
value: BigInt.from(utx.value),
vout: utx.vout,
scriptType: _getScriptType(address),
isSilentPayment: isSilentPayment,
),
ownerDetails: UtxoAddressDetails(
publicKey: pubKeyHex,
address: address,
),
),
);
// sendAll continues for all inputs
if (!sendAll) {
bool amountIsAcquired = leftAmount <= 0;
if ((inputsCount == null && amountIsAcquired) || inputsCount == i + 1) {
break;
}
}
}
if (utxos.isEmpty) {
throw BitcoinTransactionNoInputsException();
}
return UtxoDetails(
availableInputs: availableInputs,
unconfirmedCoins: unconfirmedCoins,
utxos: utxos,
vinOutpoints: vinOutpoints,
inputPrivKeyInfos: inputPrivKeyInfos,
publicKeys: publicKeys,
allInputsAmount: allInputsAmount,
spendsSilentPayment: spendsSilentPayment,
spendsUnconfirmedTX: spendsUnconfirmedTX,
);
}
Future<EstimatedTxResult> estimateSendAllTx(
List<BitcoinOutput> outputs,
int feeRate, {
String? memo,
bool hasSilentPayment = false,
UnspentCoinType coinTypeToSpendFrom = UnspentCoinType.any,
}) async {
final utxoDetails = _createUTXOS(
sendAll: true,
paysToSilentPayment: hasSilentPayment,
coinTypeToSpendFrom: coinTypeToSpendFrom,
);
int fee = await calcFee(
utxos: utxoDetails.utxos,
outputs: outputs,
network: network,
memo: memo,
feeRate: feeRate,
inputPrivKeyInfos: utxoDetails.inputPrivKeyInfos,
vinOutpoints: utxoDetails.vinOutpoints,
);
if (fee == 0) {
throw BitcoinTransactionNoFeeException();
}
// Here, when sending all, the output amount equals to the input value - fee to fully spend every input on the transaction and have no amount left for change
int amount = utxoDetails.allInputsAmount - fee;
if (amount <= 0) {
throw BitcoinTransactionWrongBalanceException(amount: utxoDetails.allInputsAmount + fee);
}
// Attempting to send less than the dust limit
if (_isBelowDust(amount)) {
throw BitcoinTransactionNoDustException();
}
if (outputs.length == 1) {
outputs[0] = BitcoinOutput(
address: outputs.last.address,
value: BigInt.from(amount),
isSilentPayment: hasSilentPayment,
);
}
return EstimatedTxResult(
utxos: utxoDetails.utxos,
inputPrivKeyInfos: utxoDetails.inputPrivKeyInfos,
publicKeys: utxoDetails.publicKeys,
fee: fee,
amount: amount,
isSendAll: true,
hasChange: false,
memo: memo,
spendsUnconfirmedTX: utxoDetails.spendsUnconfirmedTX,
spendsSilentPayment: utxoDetails.spendsSilentPayment,
);
}
Future<EstimatedTxResult> estimateTxForAmount(
int credentialsAmount,
List<BitcoinOutput> outputs,
List<BitcoinOutput> updatedOutputs,
int feeRate, {
int? inputsCount,
String? memo,
bool? useUnconfirmed,
bool hasSilentPayment = false,
UnspentCoinType coinTypeToSpendFrom = UnspentCoinType.any,
}) async {
// Attempting to send less than the dust limit
if (_isBelowDust(credentialsAmount)) {
throw BitcoinTransactionNoDustException();
}
// if mweb isn't enabled, don't consider spending mweb coins:
if (this is LitecoinWallet) {
var mwebEnabled = (this as LitecoinWallet).mwebEnabled;
if (!mwebEnabled) {
coinTypeToSpendFrom = UnspentCoinType.nonMweb;
}
}
// If there is only one output, and the amount to send is more than the max spendable amount
// then it is actually a send all transaction
if (outputs.length == 1) {
final maxSpendable = await _maxSpendableNoChangeAmount(
initialOutput: outputs.first,
feeRate: feeRate,
memo: memo,
hasSilentPayment: hasSilentPayment,
coinTypeToSpendFrom: coinTypeToSpendFrom,
);
if (credentialsAmount > maxSpendable) {
throw BitcoinTransactionWrongBalanceException();
}
if (credentialsAmount >= maxSpendable) {
final estimateOutput = [
BitcoinOutput(
address: outputs.first.address,
value: BigInt.zero,
isSilentPayment: outputs.first.isSilentPayment,
)
];
return estimateSendAllTx(
estimateOutput,
feeRate,
memo: memo,
hasSilentPayment: hasSilentPayment,
coinTypeToSpendFrom: coinTypeToSpendFrom,
);
}
}
final utxoDetails = _createUTXOS(
sendAll: false,
credentialsAmount: credentialsAmount,
inputsCount: inputsCount,
paysToSilentPayment: hasSilentPayment,
coinTypeToSpendFrom: coinTypeToSpendFrom,
);
final spendingAllCoins = utxoDetails.availableInputs.length == utxoDetails.utxos.length;
final spendingAllConfirmedCoins = !utxoDetails.spendsUnconfirmedTX &&
utxoDetails.utxos.length ==
utxoDetails.availableInputs.length - utxoDetails.unconfirmedCoins.length;
// How much is being spent - how much is being sent
int amountLeftForChangeAndFee = utxoDetails.allInputsAmount - credentialsAmount;
if (amountLeftForChangeAndFee <= 0) {
if (!spendingAllCoins) {
return estimateTxForAmount(
credentialsAmount,
outputs,
updatedOutputs,
feeRate,
inputsCount: utxoDetails.utxos.length + 1,
memo: memo,
hasSilentPayment: hasSilentPayment,
coinTypeToSpendFrom: coinTypeToSpendFrom,
);
}
throw BitcoinTransactionWrongBalanceException();
}
final changeAddress = await walletAddresses.getChangeAddress(
inputs: utxoDetails.availableInputs,
outputs: updatedOutputs,
coinTypeToSpendFrom: coinTypeToSpendFrom,
);
final address = RegexUtils.addressTypeFromStr(changeAddress.address, network);
updatedOutputs.add(BitcoinOutput(
address: address,
value: BigInt.from(amountLeftForChangeAndFee),
isChange: true,
));
outputs.add(BitcoinOutput(
address: address,
value: BigInt.from(amountLeftForChangeAndFee),
isChange: true,
));
// Get Derivation path for change Address since it is needed in Litecoin and BitcoinCash hardware Wallets
final changeDerivationPath =
"${_hardenedDerivationPath(derivationInfo.derivationPath ?? "m/0'")}"
"/${changeAddress.isHidden ? "1" : "0"}"
"/${changeAddress.index}";
utxoDetails.publicKeys[address.pubKeyHash()] =
PublicKeyWithDerivationPath('', changeDerivationPath);
// calcFee updates the silent payment outputs to calculate the tx size accounting
// for taproot addresses, but if more inputs are needed to make up for fees,
// the silent payment outputs need to be recalculated for the new inputs
var temp = outputs.map((output) => output).toList();
int fee = await calcFee(
utxos: utxoDetails.utxos,
// Always take only not updated bitcoin outputs here so for every estimation
// the SP outputs are re-generated to the proper taproot addresses
outputs: temp,
network: network,
memo: memo,
feeRate: feeRate,
inputPrivKeyInfos: utxoDetails.inputPrivKeyInfos,
vinOutpoints: utxoDetails.vinOutpoints,
);
updatedOutputs.clear();
for (int i = 0; i < temp.length; i++) {
final output = temp[i];
final oldOutput = outputs[i];
updatedOutputs.add(BitcoinOutput(
address: output.address,
value: output.value,
isSilentPayment: oldOutput.isSilentPayment,
isChange: output.isChange,
));
}
if (fee == 0) {
throw BitcoinTransactionNoFeeException();
}
int amount = credentialsAmount;
final lastOutput = updatedOutputs.last;
final amountLeftForChange = amountLeftForChangeAndFee - fee;
if (_isBelowDust(amountLeftForChange)) {
// If has change that is lower than dust, will end up with tx rejected by network rules
// so remove the change amount
updatedOutputs.removeLast();
outputs.removeLast();
// If the computed change is negative or below dust:
// - negative: try a no-change tx (recalculate fee without change)
// - non-negative but dust: drop change and add remainder to fee
if (amountLeftForChange < 0) {
final tempNoChange = outputs.map((o) => o).toList();
final feeNoChange = await calcFee(
utxos: utxoDetails.utxos,
outputs: tempNoChange,
network: network,
memo: memo,
feeRate: feeRate,
inputPrivKeyInfos: utxoDetails.inputPrivKeyInfos,
vinOutpoints: utxoDetails.vinOutpoints,
);
final leftover = utxoDetails.allInputsAmount - credentialsAmount - feeNoChange;
if (leftover >= 0) {
final finalFee = feeNoChange + leftover; // absorb tiny remainder
return EstimatedTxResult(
utxos: utxoDetails.utxos,
inputPrivKeyInfos: utxoDetails.inputPrivKeyInfos,
publicKeys: utxoDetails.publicKeys,
fee: finalFee,
amount: amount,
hasChange: false,
isSendAll: spendingAllCoins,
memo: memo,
spendsUnconfirmedTX: utxoDetails.spendsUnconfirmedTX,
spendsSilentPayment: utxoDetails.spendsSilentPayment,
);
}
if (!spendingAllCoins) {
return estimateTxForAmount(
credentialsAmount,
outputs,
updatedOutputs,
feeRate,
inputsCount: utxoDetails.utxos.length + 1,
memo: memo,
useUnconfirmed: useUnconfirmed ?? spendingAllConfirmedCoins,
hasSilentPayment: hasSilentPayment,
coinTypeToSpendFrom: coinTypeToSpendFrom,
);
} else {
throw BitcoinTransactionWrongBalanceException();
}
}
// if the amount left for change is less than dust, but not less than 0
// then add it to the fees
fee += amountLeftForChange;
return EstimatedTxResult(
utxos: utxoDetails.utxos,
inputPrivKeyInfos: utxoDetails.inputPrivKeyInfos,
publicKeys: utxoDetails.publicKeys,
fee: fee,
amount: amount,
hasChange: false,
isSendAll: spendingAllCoins,
memo: memo,
spendsUnconfirmedTX: utxoDetails.spendsUnconfirmedTX,
spendsSilentPayment: utxoDetails.spendsSilentPayment,
);
} else {
// Here, lastOutput already is change, return the amount left without the fee to the user's address.
updatedOutputs[updatedOutputs.length - 1] = BitcoinOutput(
address: lastOutput.address,
value: BigInt.from(amountLeftForChange),
isSilentPayment: lastOutput.isSilentPayment,
isChange: true,
);
outputs[outputs.length - 1] = BitcoinOutput(
address: lastOutput.address,
value: BigInt.from(amountLeftForChange),
isSilentPayment: lastOutput.isSilentPayment,
isChange: true,
);
return EstimatedTxResult(
utxos: utxoDetails.utxos,
inputPrivKeyInfos: utxoDetails.inputPrivKeyInfos,
publicKeys: utxoDetails.publicKeys,
fee: fee,
amount: amount,
hasChange: true,
isSendAll: spendingAllCoins,
memo: memo,
spendsUnconfirmedTX: utxoDetails.spendsUnconfirmedTX,
spendsSilentPayment: utxoDetails.spendsSilentPayment,
);
}
}
Future<int> _maxSpendableNoChangeAmount({
required BitcoinOutput initialOutput,
required int feeRate,
String? memo,
bool hasSilentPayment = false,
UnspentCoinType coinTypeToSpendFrom = UnspentCoinType.any,
}) async {
final utxoDetailsAll = _createUTXOS(
sendAll: true,
paysToSilentPayment: hasSilentPayment,
coinTypeToSpendFrom: coinTypeToSpendFrom,
);
final output = [
BitcoinOutput(
address: initialOutput.address,
value: BigInt.zero,
isSilentPayment: initialOutput.isSilentPayment,
)
];
final feeNoChange = await calcFee(
utxos: utxoDetailsAll.utxos,
outputs: output,
network: network,
memo: memo,
feeRate: feeRate,
inputPrivKeyInfos: utxoDetailsAll.inputPrivKeyInfos,
vinOutpoints: utxoDetailsAll.vinOutpoints,
);
final maxSpendable = utxoDetailsAll.allInputsAmount - feeNoChange;
return maxSpendable > 0 ? maxSpendable : 0;
}
Future<int> calcFee({
required List<UtxoWithAddress> utxos,
required List<BitcoinBaseOutput> outputs,
required BasedUtxoNetwork network,
String? memo,
required int feeRate,
List<ECPrivateInfo>? inputPrivKeyInfos,
List<Outpoint>? vinOutpoints,
}) async {
int estimatedSize;
if (network is BitcoinCashNetwork) {
estimatedSize = ForkedTransactionBuilder.estimateTransactionSize(
utxos: utxos,
outputs: outputs,
network: network,
memo: memo,
);
} else {
estimatedSize = BitcoinTransactionBuilder.estimateTransactionSize(
utxos: utxos,
outputs: outputs,
network: network,
memo: memo,
inputPrivKeyInfos: inputPrivKeyInfos,
vinOutpoints: vinOutpoints,
);
}
return feeAmountWithFeeRate(feeRate, 0, 0, size: estimatedSize);
}
@override
Future<PendingTransaction> createTransaction(Object credentials) async {
try {
// start by updating unspent coins
await updateAllUnspents();
final outputs = <BitcoinOutput>[];
final transactionCredentials = credentials as BitcoinTransactionCredentials;
final hasMultiDestination = transactionCredentials.outputs.length > 1;
final sendAll = !hasMultiDestination && transactionCredentials.outputs.first.sendAll;
final memo = transactionCredentials.outputs.first.memo;
final coinTypeToSpendFrom = transactionCredentials.coinTypeToSpendFrom;
int credentialsAmount = 0;
bool hasSilentPayment = false;
for (final out in transactionCredentials.outputs) {
final outputAmount = out.formattedCryptoAmount!;
if (!sendAll && _isBelowDust(outputAmount)) {
throw BitcoinTransactionNoDustException();
}
if (hasMultiDestination) {
if (out.sendAll) {
throw BitcoinTransactionWrongBalanceException();
}
}
credentialsAmount += outputAmount;
final address = RegexUtils.addressTypeFromStr(
out.isParsedAddress ? out.extractedAddress! : out.address, network);
final isSilentPayment = address is SilentPaymentAddress;
if (isSilentPayment) {
hasSilentPayment = true;
}
if (sendAll) {
// The value will be changed after estimating the Tx size and deducting the fee from the total to be sent
outputs.add(BitcoinOutput(
address: address,
value: BigInt.from(0),
isSilentPayment: isSilentPayment,
));
} else {
outputs.add(BitcoinOutput(
address: address,
value: BigInt.from(outputAmount),
isSilentPayment: isSilentPayment,
));
}
}
final feeRateInt = transactionCredentials.feeRate != null
? transactionCredentials.feeRate!
: feeRate(transactionCredentials.priority!);
EstimatedTxResult estimatedTx;
final updatedOutputs = outputs
.map((e) => BitcoinOutput(
address: e.address,
value: e.value,
isSilentPayment: e.isSilentPayment,
isChange: e.isChange,
))
.toList();
if (sendAll) {
estimatedTx = await estimateSendAllTx(
updatedOutputs,
feeRateInt,
memo: memo,
hasSilentPayment: hasSilentPayment,
coinTypeToSpendFrom: coinTypeToSpendFrom,
);
} else {
estimatedTx = await estimateTxForAmount(
credentialsAmount,
outputs,
updatedOutputs,
feeRateInt,
memo: memo,
hasSilentPayment: hasSilentPayment,
coinTypeToSpendFrom: coinTypeToSpendFrom,
);
}
for (final output in updatedOutputs) {
// TODO: get from server
// if (output.isSilentPayment && output.value.toInt() > silentPaymentsMin) {
if (output.isSilentPayment && output.value.toInt() <= 1000) {
throw BitcoinTransactionNoDustException();
}
}
if (walletInfo.isHardwareWallet) {
final transaction = await buildHardwareWalletTransaction(
utxos: estimatedTx.utxos,
outputs: updatedOutputs,
publicKeys: estimatedTx.publicKeys,
fee: BigInt.from(estimatedTx.fee),
network: network,
memo: estimatedTx.memo,
outputOrdering: BitcoinOrdering.none,
enableRBF: true,
cwOutputs: transactionCredentials.outputs,
);
return PendingBitcoinTransaction(
transaction,
type,
electrumClient: electrumClient,
amount: estimatedTx.amount,
fee: estimatedTx.fee,
feeRate: feeRateInt.toString(),
network: network,
hasChange: estimatedTx.hasChange,
isSendAll: estimatedTx.isSendAll,
hasTaprootInputs: false, // ToDo: (Konsti) Support Taproot,
isViewOnly: false,
)..addListener((transaction) async {
transactionHistory.addOne(transaction);
await updateBalance();
await updateAllUnspents();
});
}
BasedBitcoinTransacationBuilder txb;
if (network is BitcoinCashNetwork) {
txb = ForkedTransactionBuilder(
utxos: estimatedTx.utxos,
outputs: updatedOutputs,
fee: BigInt.from(estimatedTx.fee),
network: network,
memo: estimatedTx.memo,
outputOrdering: BitcoinOrdering.none,
enableRBF: !estimatedTx.spendsUnconfirmedTX,
);
} else {
txb = BitcoinTransactionBuilder(
utxos: estimatedTx.utxos,
outputs: updatedOutputs,
fee: BigInt.from(estimatedTx.fee),
network: network,
memo: estimatedTx.memo,
outputOrdering: BitcoinOrdering.none,
enableRBF: !estimatedTx.spendsUnconfirmedTX,
);
}
bool hasTaprootInputs = false;
final transaction = txb.buildTransaction((txDigest, utxo, publicKey, sighash) {
if (keys.privateKey.isEmpty) return "";
String error = "Cannot find private key.";
ECPrivateInfo? key;
if (estimatedTx.inputPrivKeyInfos.isEmpty) {
error += "\nNo private keys generated.";
} else {
error += "\nAddress: ${utxo.ownerDetails.address.toAddress(network)}";
key = estimatedTx.inputPrivKeyInfos.firstWhereOrNull((element) {
final elemPubkey = element.privkey.getPublic().toHex();
if (elemPubkey == publicKey) {
return true;
} else {
error += "\nExpected: $publicKey";
error += "\nPubkey: $elemPubkey";
return false;
}
});
}
if (key == null) {
throw Exception(error);
}
if (utxo.utxo.isP2tr()) {
hasTaprootInputs = true;
return key.privkey.signTapRoot(
txDigest,
sighash: sighash,
tweak: utxo.utxo.isSilentPayment != true,
);
} else {
return key.privkey.signInput(txDigest, sigHash: sighash);
}
});
return PendingBitcoinTransaction(
transaction,
type,
electrumClient: electrumClient,
amount: estimatedTx.amount,
fee: estimatedTx.fee,
feeRate: feeRateInt.toString(),
network: network,
hasChange: estimatedTx.hasChange,
isSendAll: estimatedTx.isSendAll,
hasTaprootInputs: hasTaprootInputs,
utxos: estimatedTx.utxos,
publicKeys: estimatedTx.publicKeys,
isViewOnly: keys.privateKey.isEmpty,
)..addListener((transaction) async {
transactionHistory.addOne(transaction);
if (estimatedTx.spendsSilentPayment) {
transactionHistory.transactions.values.forEach((tx) {
tx.unspents?.removeWhere(
(unspent) => estimatedTx.utxos.any((e) => e.utxo.txHash == unspent.hash));
transactionHistory.addOne(tx);
});
}
unspentCoins
.removeWhere((utxo) => estimatedTx.utxos.any((e) => e.utxo.txHash == utxo.hash));
await updateBalance();
await updateAllUnspents();
});
} catch (e) {
throw e;
}
}
HardwareWalletService? hardwareWalletService;
Future<BtcTransaction> buildHardwareWalletTransaction({
required List<BitcoinBaseOutput> outputs,
required BigInt fee,
required BasedUtxoNetwork network,
required List<UtxoWithAddress> utxos,
required List<OutputInfo> cwOutputs,
required Map<String, PublicKeyWithDerivationPath> publicKeys,
String? memo,
bool enableRBF = false,
BitcoinOrdering inputOrdering = BitcoinOrdering.bip69,
BitcoinOrdering outputOrdering = BitcoinOrdering.bip69,
}) async =>
throw UnimplementedError();
String toJSON() => json.encode({
'mnemonic': _mnemonic,
'xpub': xpub,
'passphrase': passphrase ?? '',
'account_index': walletAddresses.currentReceiveAddressIndexByType,
'change_address_index': walletAddresses.currentChangeAddressIndexByType,
'addresses': walletAddresses.allAddresses.map((addr) => addr.toJSON()).toList(),
'address_page_type': walletInfo.addressPageType == null
? SegwitAddresType.p2wpkh.toString()
: walletInfo.addressPageType.toString(),
'balance': balance[currency]?.toJSON(),
'lightningBalance': balance[CryptoCurrency.btcln]?.toJSON(),
'derivationTypeIndex': derivationInfo.derivationType?.index,
'derivationPath': derivationInfo.derivationPath,
'silent_addresses': walletAddresses.silentAddresses.map((addr) => addr.toJSON()).toList(),
'silent_address_index': walletAddresses.currentSilentAddressIndex.toString(),
'mweb_addresses': walletAddresses.mwebAddresses.map((addr) => addr.toJSON()).toList(),
'alwaysScan': alwaysScan,
'useLightning': useLightning,
'cachedLightningAddress': walletAddresses.lightningAddress
});
int feeRate(TransactionPriority priority) {
try {
if (priority is BitcoinTransactionPriority) {
return _feeRates[priority.raw];
}
return 0;
} catch (_) {
return 0;
}
}
int feeAmountForPriority(TransactionPriority priority, int inputsCount, int outputsCount,
{int? size}) =>
feeRate(priority) * (size ?? estimatedTransactionSize(inputsCount, outputsCount));
int feeAmountWithFeeRate(int feeRate, int inputsCount, int outputsCount, {int? size}) =>
feeRate * (size ?? estimatedTransactionSize(inputsCount, outputsCount));
@override
int calculateEstimatedFee(TransactionPriority? priority, int? amount,
{int? outputsCount, int? size}) {
if (priority is BitcoinTransactionPriority) {
return calculateEstimatedFeeWithFeeRate(feeRate(priority), amount,
outputsCount: outputsCount, size: size);
}
return 0;
}
int calculateEstimatedFeeWithFeeRate(int feeRate, int? amount, {int? outputsCount, int? size}) {
if (size != null) {
return feeAmountWithFeeRate(feeRate, 0, 0, size: size);
}
int inputsCount = 0;
if (amount != null) {
int totalValue = 0;
for (final input in unspentCoins) {
if (totalValue >= amount) {
break;
}
if (input.isSending) {
totalValue += input.value;
inputsCount += 1;
}
}
if (totalValue < amount) return 0;
} else {
for (final input in unspentCoins) {
if (input.isSending) {
inputsCount += 1;
}
}
}
// If send all, then we have no change value
final _outputsCount = outputsCount ?? (amount != null ? 2 : 1);
return feeAmountWithFeeRate(feeRate, inputsCount, _outputsCount);
}
@override
Future<void> save() async {
if (!(await WalletKeysFile.hasKeysFile(walletInfo.name, walletInfo.type))) {
await saveKeysFile(_password, encryptionFileUtils);
saveKeysFile(_password, encryptionFileUtils, true);
}
final path = await makePath();
await encryptionFileUtils.write(path: path, password: _password, data: toJSON());
await transactionHistory.save();
}
@override
Future<void> renameWalletFiles(String newWalletName) async {
final currentWalletPath = await pathForWallet(name: walletInfo.name, type: type);
final currentWalletFile = File(currentWalletPath);
final currentDirPath = await pathForWalletDir(name: walletInfo.name, type: type);
final currentTransactionsFile = File('$currentDirPath/$transactionsHistoryFileName');
// Copies current wallet files into new wallet name's dir and files
if (currentWalletFile.existsSync()) {
final newWalletPath = await pathForWallet(name: newWalletName, type: type);
await currentWalletFile.copy(newWalletPath);
}
if (currentTransactionsFile.existsSync()) {
final newDirPath = await pathForWalletDir(name: newWalletName, type: type);
await currentTransactionsFile.copy('$newDirPath/$transactionsHistoryFileName');
}
// Delete old name's dir and files
await Directory(currentDirPath).delete(recursive: true);
}
@override
Future<void> changePassword(String password) async {
_password = password;
await save();
await transactionHistory.changePassword(password);
}
@action
@override
Future<void> rescan({required int height, bool? doSingleScan}) async {
if (keys.privateKey.isEmpty) return;
silentPaymentsScanningActive = true;
_setListeners(height, doSingleScan: doSingleScan);
}
@override
Future<void> close({bool shouldCleanup = false}) async {
try {
await _receiveStream?.cancel();
await electrumClient.close();
} catch (_) {}
_autoSaveTimer?.cancel();
_updateFeeRateTimer?.cancel();
}
@action
Future<void> updateAllUnspents() async {
List<BitcoinUnspent> updatedUnspentCoins = [];
final previousUnspentCoins = List<BitcoinUnspent>.from(unspentCoins.where((utxo) =>
utxo.bitcoinAddressRecord.type != SegwitAddresType.mweb &&
utxo.bitcoinAddressRecord is! BitcoinSilentPaymentAddressRecord));
if (hasSilentPaymentsScanning) {
// Update unspents stored from scanned silent payment transactions
transactionHistory.transactions.values.forEach((tx) {
if (tx.unspents != null) {
updatedUnspentCoins.addAll(tx.unspents!);
}
});
}
// Set the balance of all non-silent payment and non-mweb addresses to 0 before updating
walletAddresses.allAddresses
.where((element) => element.type != SegwitAddresType.mweb)
.forEach((addr) {
if (addr is! BitcoinSilentPaymentAddressRecord) addr.balance = 0;
});
final addressFutures = walletAddresses.allAddresses
.where((element) => element.type != SegwitAddresType.mweb)
.map((address) => fetchUnspent(address))
.toList();
final results = await Future.wait(addressFutures);
final failedCount = results.where((result) => result == null).length;
if (failedCount == 0) {
for (final result in results) {
updatedUnspentCoins.addAll(result!);
}
unspentCoins = updatedUnspentCoins;
} else {
if (updatedUnspentCoins.isEmpty) {
unspentCoins = handleFailedUtxoFetch(
failedCount: failedCount,
previousUnspentCoins: previousUnspentCoins,
updatedUnspentCoins: updatedUnspentCoins,
results: results,
);
} else {
unspentCoins = updatedUnspentCoins;
}
}
final currentWalletUnspentCoins =
unspentCoinsInfo.values.where((element) => element.walletId == id);
if (currentWalletUnspentCoins.length != updatedUnspentCoins.length) {
unspentCoins.forEach((coin) => addCoinInfo(coin));
}
await updateCoins(unspentCoins);
await _refreshUnspentCoinsInfo();
}
List<BitcoinUnspent> handleFailedUtxoFetch({
required int failedCount,
required List<BitcoinUnspent> previousUnspentCoins,
required List<BitcoinUnspent> updatedUnspentCoins,
required List<List<BitcoinUnspent>?> results,
}) {
if (failedCount == results.length) {
printV("All UTXOs failed to fetch, falling back to previous UTXOs");
return previousUnspentCoins;
}
final successfulUtxos = <BitcoinUnspent>[];
for (final result in results) {
if (result != null) {
successfulUtxos.addAll(result);
}
}
if (failedCount > 0 && successfulUtxos.isEmpty) {
printV("Some UTXOs failed, but no successful UTXOs, falling back to previous UTXOs");
return previousUnspentCoins;
}
if (failedCount > 0) {
printV("Some UTXOs failed, updating with successful UTXOs");
updatedUnspentCoins.addAll(successfulUtxos);
}
return updatedUnspentCoins;
}
Future<void> updateCoins(List<BitcoinUnspent> newUnspentCoins) async {
if (newUnspentCoins.isEmpty) {
return;
}
newUnspentCoins.forEach((coin) {
final coinInfoList = unspentCoinsInfo.values.where(
(element) =>
element.walletId.contains(id) &&
element.hash.contains(coin.hash) &&
element.vout == coin.vout,
);
if (coinInfoList.isNotEmpty) {
final coinInfo = coinInfoList.first;
coin.isFrozen = coinInfo.isFrozen;
coin.isSending = coinInfo.isSending;
coin.note = coinInfo.note;
if (coin.bitcoinAddressRecord is! BitcoinSilentPaymentAddressRecord)
coin.bitcoinAddressRecord.balance += coinInfo.value;
} else {
addCoinInfo(coin);
}
});
}
@action
Future<void> updateUnspentsForAddress(BitcoinAddressRecord address) async {
final newUnspentCoins = await fetchUnspent(address);
await updateCoins(newUnspentCoins ?? []);
}
@action
Future<List<BitcoinUnspent>?> fetchUnspent(BitcoinAddressRecord address) async {
List<BitcoinUnspent> updatedUnspentCoins = [];
final unspents = await electrumClient.getListUnspent(address.getScriptHash(network));
// Failed to fetch unspents
if (unspents == null) return null;
await Future.wait(unspents.map((unspent) async {
try {
final coin = BitcoinUnspent.fromJSON(address, unspent);
final tx = await fetchTransactionInfo(hash: coin.hash);
coin.isChange = address.isHidden;
coin.confirmations = tx?.confirmations;
coin.isPegOut = tx?.isHogEx;
updatedUnspentCoins.add(coin);
} catch (_) {}
}));
return updatedUnspentCoins;
}
@action
Future<void> addCoinInfo(BitcoinUnspent coin) async {
// Check if the coin is already in the unspentCoinsInfo for the wallet
final existingCoinInfo = unspentCoinsInfo.values
.firstWhereOrNull((element) => element.walletId == walletInfo.id && element == coin);
if (existingCoinInfo == null) {
final newInfo = UnspentCoinsInfo(
walletId: id,
hash: coin.hash,
isFrozen: coin.isFrozen,
isSending: coin.isSending,
noteRaw: coin.note,
address: coin.bitcoinAddressRecord.address,
value: coin.value,
vout: coin.vout,
isChange: coin.isChange,
isSilentPayment: coin is BitcoinSilentPaymentsUnspent,
);
await unspentCoinsInfo.add(newInfo);
}
}
Future<void> _refreshUnspentCoinsInfo() async {
try {
final List<dynamic> keys = [];
final currentWalletUnspentCoins =
unspentCoinsInfo.values.where((record) => record.walletId == id);
for (final element in currentWalletUnspentCoins) {
if (RegexUtils.addressTypeFromStr(element.address, network) is MwebAddress) continue;
final existUnspentCoins = unspentCoins.where((coin) => element == coin);
if (existUnspentCoins.isEmpty) {
keys.add(element.key);
}
}
if (keys.isNotEmpty) {
await unspentCoinsInfo.deleteAll(keys);
}
} catch (e) {
printV("refreshUnspentCoinsInfo $e");
}
}
Future<void> cleanUpDuplicateUnspentCoins() async {
final currentWalletUnspentCoins =
unspentCoinsInfo.values.where((element) => element.walletId == id);
final Map<String, UnspentCoinsInfo> uniqueUnspentCoins = {};
final List<dynamic> duplicateKeys = [];
for (final unspentCoin in currentWalletUnspentCoins) {
final key = '${unspentCoin.hash}:${unspentCoin.vout}';
if (!uniqueUnspentCoins.containsKey(key)) {
uniqueUnspentCoins[key] = unspentCoin;
} else {
duplicateKeys.add(unspentCoin.key);
}
}
if (duplicateKeys.isNotEmpty) await unspentCoinsInfo.deleteAll(duplicateKeys);
}
int transactionVSize(String transactionHex) => BtcTransaction.fromRaw(transactionHex).getVSize();
Future<String?> canReplaceByFee(ElectrumTransactionInfo tx) async {
try {
final bundle = await getTransactionExpanded(hash: tx.txHash);
_updateInputsAndOutputs(tx, bundle);
if (bundle.confirmations > 0) return null;
return bundle.originalTransaction.canReplaceByFee ? bundle.originalTransaction.toHex() : null;
} catch (e) {
return null;
}
}
Future<bool> isChangeSufficientForFee(String txId, int newFee) async {
final bundle = await getTransactionExpanded(hash: txId);
final outputs = bundle.originalTransaction.outputs;
final ownAddresses = walletAddresses.allAddresses.map((addr) => addr.address).toSet();
final receiverAmount = outputs
.where((output) =>
!ownAddresses.contains(addressFromOutputScript(output.scriptPubKey, network)))
.fold<int>(0, (sum, output) => sum + output.amount.toInt());
if (receiverAmount == 0) {
throw Exception("Receiver output not found.");
}
final availableInputs = unspentCoins.where((utxo) => utxo.isSending && !utxo.isFrozen).toList();
int totalBalance = availableInputs.fold<int>(
0, (previousValue, element) => previousValue + element.value.toInt());
int allInputsAmount = 0;
for (int i = 0; i < bundle.originalTransaction.inputs.length; i++) {
final input = bundle.originalTransaction.inputs[i];
final inputTransaction = bundle.ins[i];
final vout = input.txIndex;
final outTransaction = inputTransaction.outputs[vout];
allInputsAmount += outTransaction.amount.toInt();
}
int totalOutAmount = bundle.originalTransaction.outputs
.fold<int>(0, (previousValue, element) => previousValue + element.amount.toInt());
var currentFee = allInputsAmount - totalOutAmount;
int remainingFee = (newFee - currentFee > 0) ? newFee - currentFee : newFee;
return totalBalance - receiverAmount - remainingFee >= networkDustAmount;
}
Future<PendingBitcoinTransaction> replaceByFee(String hash, int newFee) async {
try {
final bundle = await getTransactionExpanded(hash: hash);
final utxos = <UtxoWithAddress>[];
final outputs = <BitcoinOutput>[];
List<ECPrivate> privateKeys = [];
var allInputsAmount = 0;
String? memo;
// Add original inputs
for (var i = 0; i < bundle.originalTransaction.inputs.length; i++) {
final input = bundle.originalTransaction.inputs[i];
final inputTransaction = bundle.ins[i];
final vout = input.txIndex;
final outTransaction = inputTransaction.outputs[vout];
final address = addressFromOutputScript(outTransaction.scriptPubKey, network);
allInputsAmount += outTransaction.amount.toInt();
final addressRecord =
walletAddresses.allAddresses.firstWhere((element) => element.address == address);
final btcAddress = RegexUtils.addressTypeFromStr(addressRecord.address, network);
final privkey = generateECPrivate(
hd: addressRecord.isHidden ? walletAddresses.sideHd : walletAddresses.mainHd,
index: addressRecord.index,
network: network);
privateKeys.add(privkey);
utxos.add(
UtxoWithAddress(
utxo: BitcoinUtxo(
txHash: input.txId,
value: outTransaction.amount,
vout: vout,
scriptType: _getScriptType(btcAddress),
),
ownerDetails:
UtxoAddressDetails(publicKey: privkey.getPublic().toHex(), address: btcAddress),
),
);
}
// Add original outputs
for (final out in bundle.originalTransaction.outputs) {
final script = out.scriptPubKey.script;
if (script.contains('OP_RETURN') && memo == null) {
final index = script.indexOf('OP_RETURN');
if (index + 1 <= script.length) {
try {
final opReturnData = script[index + 1].toString();
memo = utf8.decode(HEX.decode(opReturnData));
continue;
} catch (_) {
throw Exception('Cannot decode OP_RETURN data');
}
}
}
final address = addressFromOutputScript(out.scriptPubKey, network);
final btcAddress = RegexUtils.addressTypeFromStr(address, network);
outputs.add(BitcoinOutput(address: btcAddress, value: BigInt.from(out.amount.toInt())));
}
// Calculate the total amount and fees
int totalOutAmount =
outputs.fold<int>(0, (previousValue, output) => previousValue + output.value.toInt());
int currentFee = allInputsAmount - totalOutAmount;
int remainingFee = newFee - currentFee;
if (remainingFee <= 0) {
throw Exception("New fee must be higher than the current fee.");
}
// Deduct fee from change outputs first, if possible
if (remainingFee > 0) {
final changeAddresses = walletAddresses.allAddresses.where((element) => element.isHidden);
for (int i = outputs.length - 1; i >= 0; i--) {
final output = outputs[i];
final isChange = changeAddresses
.any((element) => element.address == output.address.toAddress(network));
if (isChange) {
int outputAmount = output.value.toInt();
if (outputAmount > networkDustAmount) {
int deduction = (outputAmount - networkDustAmount >= remainingFee)
? remainingFee
: outputAmount - networkDustAmount;
outputs[i] = BitcoinOutput(
address: output.address, value: BigInt.from(outputAmount - deduction));
remainingFee -= deduction;
if (remainingFee <= 0) break;
}
}
}
}
// If still not enough, add UTXOs until the fee is covered
if (remainingFee > 0) {
final unusedUtxos = unspentCoins
.where((utxo) => utxo.isSending && !utxo.isFrozen && utxo.confirmations! > 0)
.toList();
for (final utxo in unusedUtxos) {
final address = RegexUtils.addressTypeFromStr(utxo.address, network);
final privkey = generateECPrivate(
hd: utxo.bitcoinAddressRecord.isHidden
? walletAddresses.sideHd
: walletAddresses.mainHd,
index: utxo.bitcoinAddressRecord.index,
network: network,
);
privateKeys.add(privkey);
utxos.add(UtxoWithAddress(
utxo: BitcoinUtxo(
txHash: utxo.hash,
value: BigInt.from(utxo.value),
vout: utxo.vout,
scriptType: _getScriptType(address)),
ownerDetails:
UtxoAddressDetails(publicKey: privkey.getPublic().toHex(), address: address),
));
allInputsAmount += utxo.value;
remainingFee -= utxo.value;
if (remainingFee < 0) {
final changeOutput = outputs.firstWhereOrNull((output) => walletAddresses.allAddresses
.any((addr) => addr.address == output.address.toAddress(network)));
if (changeOutput != null) {
final newValue = changeOutput.value.toInt() + (-remainingFee);
outputs[outputs.indexOf(changeOutput)] =
BitcoinOutput(address: changeOutput.address, value: BigInt.from(newValue));
} else {
final changeAddress = await walletAddresses.getChangeAddress();
outputs.add(BitcoinOutput(
address: RegexUtils.addressTypeFromStr(changeAddress.address, network),
value: BigInt.from(-remainingFee)));
}
remainingFee = 0;
break;
}
if (remainingFee <= 0) break;
}
}
// Deduct from the receiver's output if remaining fee is still greater than 0
if (remainingFee > 0) {
for (int i = 0; i < outputs.length; i++) {
final output = outputs[i];
int outputAmount = output.value.toInt();
if (outputAmount > networkDustAmount) {
int deduction = (outputAmount - networkDustAmount >= remainingFee)
? remainingFee
: outputAmount - networkDustAmount;
outputs[i] = BitcoinOutput(
address: output.address, value: BigInt.from(outputAmount - deduction));
remainingFee -= deduction;
if (remainingFee <= 0) break;
}
}
}
// Final check if the remaining fee couldn't be deducted
if (remainingFee > 0) {
throw Exception("Not enough funds to cover the fee.");
}
// Identify all change outputs
final changeAddresses = walletAddresses.allAddresses.where((element) => element.isHidden);
final List<BitcoinOutput> changeOutputs = outputs
.where((output) => changeAddresses
.any((element) => element.address == output.address.toAddress(network)))
.toList();
int totalChangeAmount =
changeOutputs.fold<int>(0, (sum, output) => sum + output.value.toInt());
// The final amount that the receiver will receive
int sendingAmount = allInputsAmount - newFee - totalChangeAmount;
final txb = BitcoinTransactionBuilder(
utxos: utxos,
outputs: outputs,
fee: BigInt.from(newFee),
network: network,
memo: memo,
outputOrdering: BitcoinOrdering.none,
enableRBF: true,
);
final transaction = txb.buildTransaction((txDigest, utxo, publicKey, sighash) {
final key =
privateKeys.firstWhereOrNull((element) => element.getPublic().toHex() == publicKey);
if (key == null) {
throw Exception("Cannot find private key");
}
if (utxo.utxo.isP2tr()) {
return key.signTapRoot(txDigest, sighash: sighash);
} else {
return key.signInput(txDigest, sigHash: sighash);
}
});
return PendingBitcoinTransaction(
transaction,
type,
electrumClient: electrumClient,
amount: sendingAmount,
fee: newFee,
network: network,
hasChange: changeOutputs.isNotEmpty,
feeRate: newFee.toString(),
isViewOnly: keys.privateKey.isEmpty,
)..addListener((transaction) async {
transactionHistory.transactions.values.forEach((tx) {
if (tx.id == hash) {
tx.isReplaced = true;
tx.isPending = false;
transactionHistory.addOne(tx);
}
});
transactionHistory.addOne(transaction);
await updateBalance();
await updateAllUnspents();
});
} catch (e) {
throw e;
}
}
Future<ElectrumTransactionBundle> getTransactionExpanded(
{required String hash, int? height}) async {
String transactionHex;
int? time;
int? confirmations;
final verboseTransaction = await electrumClient.getTransactionVerbose(hash: hash);
if (verboseTransaction.isEmpty) {
transactionHex = await electrumClient.getTransactionHex(hash: hash);
if (height != null && height > 0 && await checkIfMempoolAPIIsEnabled()) {
try {
final blockHash = await ProxyWrapper()
.get(
clearnetUri: Uri.parse(
"https://mempool.cakewallet.com/api/v1/block-height/$height",
),
)
.timeout(Duration(seconds: 15));
if (blockHash.statusCode == 200 &&
blockHash.body.isNotEmpty &&
jsonDecode(blockHash.body) != null) {
final blockResponse = await ProxyWrapper()
.get(
clearnetUri: Uri.parse(
"https://mempool.cakewallet.com/api/v1/block/${blockHash.body}",
),
)
.timeout(Duration(seconds: 15));
if (blockResponse.statusCode == 200 &&
blockResponse.body.isNotEmpty &&
jsonDecode(blockResponse.body)['timestamp'] != null) {
time = int.parse(jsonDecode(blockResponse.body)['timestamp'].toString());
}
}
} catch (_) {}
}
} else {
transactionHex = verboseTransaction['hex'] as String;
time = verboseTransaction['time'] as int?;
confirmations = verboseTransaction['confirmations'] as int?;
}
if (height != null) {
if (time == null && height > 0) {
time = (getDateByBitcoinHeight(height).millisecondsSinceEpoch / 1000).round();
}
if (confirmations == null) {
final tip = await getUpdatedChainTip();
if (tip > 0 && height > 0) {
// Add one because the block itself is the first confirmation
confirmations = tip - height + 1;
}
}
}
final original = BtcTransaction.fromRaw(transactionHex);
final ins = <BtcTransaction>[];
for (final vin in original.inputs) {
final verboseTransaction = await electrumClient.getTransactionVerbose(hash: vin.txId);
final String inputTransactionHex;
if (verboseTransaction.isEmpty) {
inputTransactionHex = await electrumClient.getTransactionHex(hash: hash);
} else {
inputTransactionHex = verboseTransaction['hex'] as String;
}
ins.add(BtcTransaction.fromRaw(inputTransactionHex));
}
return ElectrumTransactionBundle(
original,
ins: ins,
time: time,
confirmations: confirmations ?? 0,
);
}
Future<ElectrumTransactionInfo?> fetchTransactionInfo(
{required String hash, int? height, bool? retryOnFailure}) async {
try {
return ElectrumTransactionInfo.fromElectrumBundle(
await getTransactionExpanded(hash: hash, height: height),
walletInfo.type,
network,
addresses: addressesSet,
height: height,
);
} catch (e) {
if (e is FormatException && retryOnFailure == true) {
await Future.delayed(const Duration(seconds: 2));
return fetchTransactionInfo(hash: hash, height: height);
}
return null;
}
}
bool isMine(Script script) {
final derivedAddress = addressFromOutputScript(script, network);
return addressesSet.contains(derivedAddress);
}
@override
Future<Map<String, ElectrumTransactionInfo>> fetchTransactions() async {
try {
final Map<String, ElectrumTransactionInfo> historiesWithDetails = {};
if (type == WalletType.bitcoin) {
await Future.wait(BITCOIN_ADDRESS_TYPES
.map((type) => fetchTransactionsForAddressType(historiesWithDetails, type)));
} else if (type == WalletType.bitcoinCash) {
await Future.wait(BITCOIN_CASH_ADDRESS_TYPES
.map((type) => fetchTransactionsForAddressType(historiesWithDetails, type)));
} else if (type == WalletType.litecoin) {
await Future.wait(LITECOIN_ADDRESS_TYPES
.where((type) => type != SegwitAddresType.mweb)
.map((type) => fetchTransactionsForAddressType(historiesWithDetails, type)));
} else if (type == WalletType.dogecoin) {
await Future.wait(DOGECOIN_ADDRESS_TYPES
.map((type) => fetchTransactionsForAddressType(historiesWithDetails, type)));
}
transactionHistory.transactions.values.forEach((tx) async {
final isPendingSilentPaymentUtxo =
(tx.isPending || tx.confirmations == 0) && historiesWithDetails[tx.id] == null;
if (isPendingSilentPaymentUtxo) {
final info =
await fetchTransactionInfo(hash: tx.id, height: tx.height, retryOnFailure: true);
if (info != null) {
tx.confirmations = info.confirmations;
tx.isPending = tx.confirmations == 0;
transactionHistory.addOne(tx);
await transactionHistory.save();
}
}
});
return historiesWithDetails;
} catch (e) {
printV("fetchTransactions $e");
return {};
}
}
Future<void> fetchTransactionsForAddressType(
Map<String, ElectrumTransactionInfo> historiesWithDetails,
BitcoinAddressType type,
) async {
final addressesByType = walletAddresses.allAddresses.where((addr) => addr.type == type);
final hiddenAddresses = addressesByType.where((addr) => addr.isHidden == true);
final receiveAddresses = addressesByType.where((addr) => addr.isHidden == false);
walletAddresses.hiddenAddresses.addAll(hiddenAddresses.map((e) => e.address));
await walletAddresses.saveAddressesInBox();
await Future.wait(addressesByType.map((addressRecord) async {
final history = await _fetchAddressHistory(addressRecord, await getCurrentChainTip());
if (history.isNotEmpty) {
addressRecord.txCount = history.length;
historiesWithDetails.addAll(history);
final matchedAddresses = addressRecord.isHidden ? hiddenAddresses : receiveAddresses;
final isUsedAddressUnderGap = matchedAddresses.toList().indexOf(addressRecord) >=
matchedAddresses.length -
(addressRecord.isHidden
? ElectrumWalletAddressesBase.defaultChangeAddressesCount
: ElectrumWalletAddressesBase.defaultReceiveAddressesCount);
if (isUsedAddressUnderGap) {
final prevLength = walletAddresses.allAddresses.length;
// Discover new addresses for the same address type until the gap limit is respected
await walletAddresses.discoverAddresses(
matchedAddresses.toList(),
addressRecord.isHidden,
(address) async {
await subscribeForUpdates();
return _fetchAddressHistory(address, await getCurrentChainTip())
.then((history) => history.isNotEmpty ? address.address : null);
},
type: type,
);
final newLength = walletAddresses.allAddresses.length;
if (newLength > prevLength) {
await fetchTransactionsForAddressType(historiesWithDetails, type);
}
}
}
}));
}
Future<Map<String, ElectrumTransactionInfo>> _fetchAddressHistory(
BitcoinAddressRecord addressRecord, int? currentHeight) async {
String txid = "";
try {
final Map<String, ElectrumTransactionInfo> historiesWithDetails = {};
final history = await electrumClient.getHistory(addressRecord.getScriptHash(network));
if (history.isNotEmpty) {
addressRecord.setAsUsed();
walletAddresses.clearLockIfMatches(addressRecord.type, addressRecord.address);
if(this is BitcoinWallet) {
//removes transactions no longer returned by the api, presumed replaced/invalid.
transactionHistory.transactions.removeWhere(
(hash, tx) =>
tx.outputAddresses != null &&
tx.outputAddresses!.contains(addressRecord.address) &&
!history.any((newTransaction) => newTransaction['tx_hash'] == hash),
);
}
await Future.wait(history.map((transaction) async {
txid = transaction['tx_hash'] as String;
final height = transaction['height'] as int;
final storedTx = transactionHistory.transactions[txid];
if (storedTx != null) {
if (height > 0) {
storedTx.height = height;
// the tx's block itself is the first confirmation so add 1
if ((currentHeight ?? 0) > 0) {
storedTx.confirmations = currentHeight! - height + 1;
}
storedTx.isPending = storedTx.confirmations == 0;
}
historiesWithDetails[txid] = storedTx;
} else {
final tx = await fetchTransactionInfo(hash: txid, height: height, retryOnFailure: true);
if (tx != null) {
historiesWithDetails[txid] = tx;
// Got a new transaction fetched, add it to the transaction history
// instead of waiting all to finish, and next time it will be faster
if (this is LitecoinWallet) {
// if we have a peg out transaction with the same value
// that matches this received transaction, mark it as being from a peg out:
for (final tx2 in transactionHistory.transactions.values) {
final heightDiff = ((tx2.height ?? 0) - (tx.height ?? 0)).abs();
// this isn't a perfect matching algorithm since we don't have the right input/output information from these transaction models (the addresses are in different formats), but this should be more than good enough for now as it's extremely unlikely a user receives the EXACT same amount from 2 different sources and one of them is a peg out and the other isn't WITHIN 5 blocks of each other
if (tx2.additionalInfo["isPegOut"] == true &&
tx2.amount == tx.amount &&
heightDiff <= 5) {
tx.additionalInfo["fromPegOut"] = true;
}
}
}
transactionHistory.addOne(tx);
await transactionHistory.save();
}
}
return Future.value(null);
}));
}
return historiesWithDetails;
} catch (e, stacktrace) {
_onError?.call(FlutterErrorDetails(
exception: "$txid - $e",
stack: stacktrace,
library: this.runtimeType.toString(),
));
return {};
}
}
Future<void> updateTransactions() async {
printV("updateTransactions() called!");
try {
if (_isTransactionUpdating) {
return;
}
currentChainTip = await getUpdatedChainTip();
bool updated = false;
transactionHistory.transactions.values.forEach((tx) {
if ((tx.height ?? 0) > 0 && (currentChainTip ?? 0) > 0) {
var confirmations = currentChainTip! - tx.height! + 1;
if (confirmations < 0) {
// if our chain tip is outdated then it could lead to negative confirmations so this is just a failsafe:
confirmations = 0;
}
if (confirmations != tx.confirmations) {
updated = true;
tx.confirmations = confirmations;
transactionHistory.addOne(tx);
}
}
});
if (updated) {
await transactionHistory.save();
}
_isTransactionUpdating = true;
await fetchTransactions();
walletAddresses.updateReceiveAddresses();
_isTransactionUpdating = false;
} catch (e, stacktrace) {
printV(stacktrace);
printV(e);
_isTransactionUpdating = false;
}
}
Future<void> subscribeForUpdates() async {
final unsubscribedScriptHashes = walletAddresses.allAddresses.where(
(address) =>
!_scripthashesUpdateSubject.containsKey(address.getScriptHash(network)) &&
address.type != SegwitAddresType.mweb,
);
await Future.wait(unsubscribedScriptHashes.map((address) async {
final sh = address.getScriptHash(network);
if (!(_scripthashesUpdateSubject[sh]?.isClosed ?? true)) {
try {
await _scripthashesUpdateSubject[sh]?.close();
} catch (e) {
printV("failed to close: $e");
}
}
try {
_scripthashesUpdateSubject[sh] = await electrumClient.scripthashUpdate(sh);
} catch (e) {
printV("failed scripthashUpdate: $e");
}
_scripthashesUpdateSubject[sh]?.listen((event) async {
try {
await updateUnspentsForAddress(address);
await updateBalance();
await _fetchAddressHistory(address, await getCurrentChainTip());
} catch (e, s) {
printV("sub error: $e");
_onError?.call(FlutterErrorDetails(
exception: e,
stack: s,
library: this.runtimeType.toString(),
));
}
}, onError: (e, s) {
printV("sub_listen error: $e $s");
});
}));
}
Future<ElectrumBalance> fetchBalances() async {
final addresses = walletAddresses.allAddresses
.where((address) => address.address.isNotEmpty)
.where((address) => RegexUtils.addressTypeFromStr(address.address, network) is! MwebAddress)
.toList();
final balanceFutures = <Future<Map<String, dynamic>>>[];
for (var i = 0; i < addresses.length; i++) {
final addressRecord = addresses[i];
final sh = addressRecord.getScriptHash(network);
final balanceFuture = electrumClient.getBalance(sh);
balanceFutures.add(balanceFuture);
}
var totalFrozen = 0;
var totalConfirmed = 0;
var totalUnconfirmed = 0;
if (hasSilentPaymentsScanning) {
// Add values from unspent coins that are not fetched by the address list
// i.e. scanned silent payments
transactionHistory.transactions.values.forEach((tx) {
if (tx.unspents != null) {
tx.unspents!.forEach((unspent) {
if (unspent.bitcoinAddressRecord is BitcoinSilentPaymentAddressRecord) {
if (unspent.isFrozen) totalFrozen += unspent.value;
totalConfirmed += unspent.value;
}
});
}
});
}
unspentCoinsInfo.values.forEach((info) {
unspentCoins.forEach((element) {
if (element.bitcoinAddressRecord is BitcoinSilentPaymentAddressRecord) return;
if (element.hash == info.hash &&
element.vout == info.vout &&
element.bitcoinAddressRecord.address == info.address &&
element.value == info.value) {
if (info.isFrozen) {
totalFrozen += element.value;
}
}
});
});
final balances = await Future.wait(balanceFutures);
if (balances.isNotEmpty && balances.first['confirmed'] == null) {
// if we got null balance responses from the server, set our connection status to lost and return our last known balance:
printV("got null balance responses from the server, setting connection status to lost");
syncStatus = LostConnectionSyncStatus();
return balance[currency] ?? ElectrumBalance(confirmed: 0, unconfirmed: 0, frozen: 0);
}
for (var i = 0; i < balances.length; i++) {
final addressRecord = addresses[i];
final balance = balances[i];
final confirmed = balance['confirmed'] as int? ?? 0;
final unconfirmed = balance['unconfirmed'] as int? ?? 0;
totalConfirmed += confirmed;
totalUnconfirmed += unconfirmed;
addressRecord.balance = confirmed + unconfirmed;
if (confirmed > 0 || unconfirmed > 0) {
addressRecord.setAsUsed();
walletAddresses.clearLockIfMatches(addressRecord.type, addressRecord.address);
}
}
return ElectrumBalance(
confirmed: totalConfirmed,
unconfirmed: totalUnconfirmed,
frozen: totalFrozen,
);
}
Future<void> updateBalance() async {
printV("updateBalance() called!");
balance[currency] = await fetchBalances();
await save();
}
@override
Future<bool> checkNodeHealth() async {
try {
final addresses = walletAddresses.allAddresses
.where(
(address) => RegexUtils.addressTypeFromStr(address.address, network) is! MwebAddress)
.toList();
if (addresses.isEmpty) {
return false;
}
final firstAddress = addresses.first;
final sh = firstAddress.getScriptHash(network);
await electrumClient.getBalance(sh, throwOnError: true);
return true;
} catch (e) {
return false;
}
}
@override
void setExceptionHandler(void Function(FlutterErrorDetails) onError) => _onError = onError;
@override
Future<String> signMessage(String message, {String? address = null}) async {
final index = address != null
? walletAddresses.allAddresses.firstWhere((element) => element.address == address).index
: null;
final HD = index == null ? hd : hd.childKey(Bip32KeyIndex(index));
final priv = ECPrivate.fromHex(HD.privateKey.privKey.toHex());
String messagePrefix = '\x18Bitcoin Signed Message:\n';
final hexEncoded = priv.signMessage(utf8.encode(message), messagePrefix: messagePrefix);
final decodedSig = hex.decode(hexEncoded);
return base64Encode(decodedSig);
}
@override
Future<bool> verifyMessage(String message, String signature, {String? address = null}) async {
if (address == null) {
return false;
}
List<int> sigDecodedBytes = [];
if (signature.endsWith('=')) {
sigDecodedBytes = base64.decode(signature);
} else {
sigDecodedBytes = hex.decode(signature);
}
if (sigDecodedBytes.length != 64 && sigDecodedBytes.length != 65) {
throw ArgumentException(
"signature must be 64 bytes without recover-id or 65 bytes with recover-id");
}
String messagePrefix = '\x18Bitcoin Signed Message:\n';
final messageHash = QuickCrypto.sha256Hash(
BitcoinSignerUtils.magicMessage(utf8.encode(message), messagePrefix));
List<int> correctSignature =
sigDecodedBytes.length == 65 ? sigDecodedBytes.sublist(1) : List.from(sigDecodedBytes);
List<int> rBytes = correctSignature.sublist(0, 32);
List<int> sBytes = correctSignature.sublist(32);
final sig = ECDSASignature(BigintUtils.fromBytes(rBytes), BigintUtils.fromBytes(sBytes));
List<int> possibleRecoverIds = [0, 1];
final baseAddress = RegexUtils.addressTypeFromStr(address, network);
for (int recoveryId in possibleRecoverIds) {
final pubKey = sig.recoverPublicKey(messageHash, Curves.generatorSecp256k1, recoveryId);
final recoveredPub = ECPublic.fromBytes(pubKey!.toBytes());
String? recoveredAddress;
if (baseAddress is P2pkAddress) {
recoveredAddress = recoveredPub.toP2pkAddress().toAddress(network);
} else if (baseAddress is P2pkhAddress) {
recoveredAddress = recoveredPub.toP2pkhAddress().toAddress(network);
} else if (baseAddress is P2wshAddress) {
recoveredAddress = recoveredPub.toP2wshAddress().toAddress(network);
} else if (baseAddress is P2wpkhAddress) {
recoveredAddress = recoveredPub.toP2wpkhAddress().toAddress(network);
}
if (recoveredAddress == address) {
return true;
}
}
return false;
}
Future<void> _setInitialHeight() async {
if (_chainTipUpdateSubject != null) return;
currentChainTip = await getUpdatedChainTip();
if ((currentChainTip == null || currentChainTip! == 0) && walletInfo.restoreHeight == 0) {
await walletInfo.updateRestoreHeight(currentChainTip!);
}
_chainTipUpdateSubject = electrumClient.chainTipSubscribe();
_chainTipUpdateSubject?.listen((e) async {
final event = e as Map<String, dynamic>;
final height = int.tryParse(event['height'].toString());
if (height != null) {
currentChainTip = height;
if (alwaysScan == true && syncStatus is SyncedSyncStatus) {
_setListeners(walletInfo.restoreHeight);
}
}
});
}
static String _hardenedDerivationPath(String derivationPath) =>
derivationPath.substring(0, derivationPath.lastIndexOf("'") + 1);
@action
void _onConnectionStatusChange(electrum.ConnectionStatus status) {
switch (status) {
case electrum.ConnectionStatus.connected:
if (syncStatus is NotConnectedSyncStatus ||
syncStatus is LostConnectionSyncStatus ||
syncStatus is ConnectingSyncStatus) {
syncStatus = ConnectedSyncStatus();
}
break;
case electrum.ConnectionStatus.disconnected:
// Always show disconnected status when connection is lost, regardless of current sync state
if (syncStatus is! NotConnectedSyncStatus) {
syncStatus = NotConnectedSyncStatus();
}
break;
case electrum.ConnectionStatus.failed:
if (syncStatus is! LostConnectionSyncStatus) {
syncStatus = LostConnectionSyncStatus();
}
break;
case electrum.ConnectionStatus.connecting:
if (syncStatus is! ConnectingSyncStatus) {
syncStatus = ConnectingSyncStatus();
}
break;
default:
}
}
void _syncStatusReaction(SyncStatus syncStatus) async {
printV("SYNC_STATUS_CHANGE: ${syncStatus}");
if (syncStatus is SyncingSyncStatus) {
return;
}
if (syncStatus is NotConnectedSyncStatus || syncStatus is LostConnectionSyncStatus) {
// Needs to re-subscribe to all scripthashes when reconnected
_scripthashesUpdateSubject = {};
if (_isTryingToConnect) return;
_isTryingToConnect = true;
Timer(Duration(seconds: 5), () {
if (this.syncStatus is NotConnectedSyncStatus ||
this.syncStatus is LostConnectionSyncStatus) {
this.electrumClient.connectToUri(
node!.uri,
useSSL: node!.useSSL ?? false,
);
}
_isTryingToConnect = false;
});
}
// Message is shown on the UI for 3 seconds, revert to synced
if (syncStatus is SyncedTipSyncStatus) {
Timer(Duration(seconds: 3), () {
if (this.syncStatus is SyncedTipSyncStatus) this.syncStatus = SyncedSyncStatus();
});
}
}
void _updateInputsAndOutputs(ElectrumTransactionInfo tx, ElectrumTransactionBundle bundle) {
tx.inputAddresses = tx.inputAddresses?.where((address) => address.isNotEmpty).toList();
if (tx.inputAddresses == null ||
tx.inputAddresses!.isEmpty ||
tx.outputAddresses == null ||
tx.outputAddresses!.isEmpty) {
List<String> inputAddresses = [];
List<String> outputAddresses = [];
for (int i = 0; i < bundle.originalTransaction.inputs.length; i++) {
final input = bundle.originalTransaction.inputs[i];
final inputTransaction = bundle.ins[i];
final vout = input.txIndex;
final outTransaction = inputTransaction.outputs[vout];
final address = addressFromOutputScript(outTransaction.scriptPubKey, network);
if (address.isNotEmpty) inputAddresses.add(address);
}
for (int i = 0; i < bundle.originalTransaction.outputs.length; i++) {
final out = bundle.originalTransaction.outputs[i];
final address = addressFromOutputScript(out.scriptPubKey, network);
if (address.isNotEmpty) outputAddresses.add(address);
// Check if the script contains OP_RETURN
final script = out.scriptPubKey.script;
if (script.contains('OP_RETURN')) {
final index = script.indexOf('OP_RETURN');
if (index + 1 <= script.length) {
try {
final opReturnData = script[index + 1].toString();
final decodedString = utf8.decode(HEX.decode(opReturnData));
outputAddresses.add('OP_RETURN:$decodedString');
} catch (_) {
outputAddresses.add('OP_RETURN:');
}
}
}
}
tx.inputAddresses = inputAddresses;
tx.outputAddresses = outputAddresses;
transactionHistory.addOne(tx);
}
}
@override
String formatCryptoAmount(String amount) {
final amountBigInt = BigInt.parse(amount);
return currency.formatAmount(amountBigInt);
}
/// Checks the health of the socket connection
/// and triggers a full reconnection if needed
@override
Future<bool> checkSocketHealth() async {
try {
SocketHealthLogger().logHealthCheck(
walletType: type,
walletName: name,
syncStatus: syncStatus.toString(),
wasReconnected: false,
trigger: 'socket_health_check_start',
);
if (!electrumClient.isConnected || !electrumClient.isInternalStateConsistent) {
if (!electrumClient.isConnected) {
SocketHealthLogger().logHealthCheck(
walletType: type,
walletName: name,
isHealthy: false,
syncStatus: syncStatus.toString(),
wasReconnected: false,
trigger: 'socket_health_check_socket_not_connected',
);
}
if (!electrumClient.isInternalStateConsistent) {
SocketHealthLogger().logHealthCheck(
walletType: type,
walletName: name,
isHealthy: false,
syncStatus: syncStatus.toString(),
wasReconnected: false,
trigger: 'socket_health_check_internal_state_inconsistent',
);
}
await _performFullReconnection();
SocketHealthLogger().logHealthCheck(
walletType: type,
walletName: name,
isHealthy: true,
syncStatus: syncStatus.toString(),
wasReconnected: true,
trigger:
'socket_health_check_reconnection_success_for_unhealthy_basic_check_or_internal_state_inconsistent',
);
return true;
}
// Make a call to the server to check if the connection is healthy
// If the call fails, we need to reconnect
try {
final result = await electrumClient.call(
method: 'server.version',
params: ['', '1.4'],
);
if (result == null) {
throw Exception('Call mechanism test returned null');
}
SocketHealthLogger().logHealthCheck(
walletType: type,
walletName: name,
isHealthy: true,
syncStatus: syncStatus.toString(),
wasReconnected: false,
trigger: 'socket_health_check_server_state_ok',
);
return true;
} catch (e) {
SocketHealthLogger().logHealthCheck(
walletType: type,
walletName: name,
isHealthy: false,
error: e.toString(),
syncStatus: syncStatus.toString(),
wasReconnected: false,
trigger: 'socket_health_check_server_state_failed',
);
await _performFullReconnection();
SocketHealthLogger().logHealthCheck(
walletType: type,
walletName: name,
isHealthy: true,
syncStatus: syncStatus.toString(),
wasReconnected: true,
trigger: 'socket_health_check_reconnection_success_for_server_state_failed',
);
return true;
}
} catch (e) {
return false;
}
}
Future<void> _performFullReconnection() async {
try {
SocketHealthLogger().logHealthCheck(
walletType: type,
walletName: name,
syncStatus: syncStatus.toString(),
wasReconnected: true,
trigger: 'full_reconnection_start',
);
await _receiveStream?.cancel();
await electrumClient.close();
if (node != null) {
electrumClient.onConnectionStatusChange = _onConnectionStatusChange;
await electrumClient.connectToUri(node!.uri, useSSL: node!.useSSL);
await startSync();
SocketHealthLogger().logHealthCheck(
walletType: type,
walletName: name,
isHealthy: true,
syncStatus: syncStatus.toString(),
wasReconnected: true,
trigger: 'full_reconnection_success',
);
}
} catch (e) {
SocketHealthLogger().logHealthCheck(
walletType: type,
walletName: name,
isHealthy: false,
error: e.toString(),
syncStatus: syncStatus.toString(),
wasReconnected: false,
trigger: 'full_reconnection_failed',
);
syncStatus = FailedSyncStatus();
}
}
}
class ScanNode {
final Uri uri;
final bool? useSSL;
ScanNode(this.uri, this.useSSL);
}
class ScanData {
final SendPort sendPort;
final SilentPaymentOwner silentAddress;
final Bip32Slip10Secp256k1 masterHD;
final int height;
final ScanNode? node;
final BasedUtxoNetwork network;
final int chainTip;
final electrum.ElectrumClient electrumClient;
final List<String> transactionHistoryIds;
final Map<String, String> labels;
final List<int> labelIndexes;
final bool isSingleScan;
final String debugLogPath;
final List<int>? rescanHeights;
ScanData({
required this.sendPort,
required this.silentAddress,
required this.masterHD,
required this.height,
required this.node,
required this.network,
required this.chainTip,
required this.electrumClient,
required this.transactionHistoryIds,
required this.labels,
required this.labelIndexes,
required this.isSingleScan,
required this.debugLogPath,
required this.rescanHeights,
});
factory ScanData.fromHeight(ScanData scanData, int newHeight) {
return ScanData(
sendPort: scanData.sendPort,
silentAddress: scanData.silentAddress,
masterHD: scanData.masterHD,
height: newHeight,
node: scanData.node,
network: scanData.network,
chainTip: scanData.chainTip,
transactionHistoryIds: scanData.transactionHistoryIds,
electrumClient: scanData.electrumClient,
labels: scanData.labels,
labelIndexes: scanData.labelIndexes,
isSingleScan: scanData.isSingleScan,
debugLogPath: scanData.debugLogPath,
rescanHeights: scanData.rescanHeights,
);
}
}
class SyncResponse {
final int height;
final SyncStatus syncStatus;
SyncResponse(this.height, this.syncStatus);
}
Future<void> _handleScanSilentPayments(ScanData scanData) async {
final shouldUpdateSyncStatus = scanData.rescanHeights == null || scanData.rescanHeights!.isEmpty;
final hasForcedRescanHeights = !shouldUpdateSyncStatus;
CakeTor.instance = await CakeTorInstance.getInstance();
var node = scanData.node?.uri ?? Uri.parse("tcp://electrs.cakewallet.com:50001");
void log(String message, LogLevel level) {
printV("[Scanning] $message", file: scanData.debugLogPath, level: level);
}
try {
// if (scanData.shouldSwitchNodes) {
var scanningClient = await ElectrumProvider.connect(
ElectrumTCPService.connect(node),
);
// }
log("connected to ${node.toString()}", LogLevel.info);
final receivers = [
Receiver(
scanData.silentAddress.b_scan.toHex(),
scanData.silentAddress.B_spend.toHex(),
scanData.network == BitcoinNetwork.testnet,
scanData.labelIndexes,
scanData.labelIndexes.length,
),
Receiver(
scanData.masterHD.derivePath(SILENT_PAYMENTS_SCAN_PATH_TESTNET).privateKey.toHex(),
scanData.masterHD.derivePath(SILENT_PAYMENTS_SPEND_PATH_TESTNET).publicKey.toHex(),
scanData.network == BitcoinNetwork.testnet,
scanData.labelIndexes,
scanData.labelIndexes.length,
)
];
log(
"using receiver: b_scan: ${scanData.silentAddress.b_scan.toHex()}, b_spend: ${scanData.silentAddress.B_spend.toHex()}, network: ${scanData.network.value}, labelIndexes: ${scanData.labelIndexes}",
LogLevel.info,
);
log(
"using receiver: b_scan: ${receivers[1].bScan}, b_spend: ${receivers[1].BSpend}, network: ${scanData.network.value}, labelIndexes: ${scanData.labelIndexes}",
LogLevel.info,
);
void scan(int syncHeight, bool isSingleScan) async {
int initialSyncHeight = syncHeight;
int getCountToScanPerRequest(int syncHeight) {
if (isSingleScan) {
return 1;
}
final amountLeft = scanData.chainTip - syncHeight + 1;
return amountLeft;
}
// Initial status UI update, send how many blocks in total to scan
if (shouldUpdateSyncStatus)
scanData.sendPort.send(SyncResponse(syncHeight, StartingScanSyncStatus(syncHeight)));
final req = ElectrumTweaksSubscribe(
height: syncHeight,
count: getCountToScanPerRequest(syncHeight),
historicalMode: hasForcedRescanHeights,
);
var _scanningStream = await scanningClient.subscribe(req);
log(
"initial request: height: $syncHeight, count: ${getCountToScanPerRequest(syncHeight)}",
LogLevel.info,
);
void endScanningSuccesfully() {
if (isSingleScan) {
scanData.sendPort.send(SyncResponse(syncHeight, SyncedSyncStatus()));
} else {
scanData.sendPort.send(
SyncResponse(syncHeight, SyncedTipSyncStatus(scanData.chainTip)),
);
}
_scanningStream?.close();
_scanningStream = null;
log(
"ended: syncHeight: $syncHeight, chainTip: ${scanData.chainTip}, isSingleScan: ${isSingleScan}",
LogLevel.info,
);
}
void listenFn(Map<String, dynamic> event, ElectrumTweaksSubscribe req) async {
final response = req.onResponse(event);
if (response == null || _scanningStream == null) {
log(
"ending: response = $response, stream = $_scanningStream",
LogLevel.error,
);
return;
}
// is success or error msg
final noData = response.message != null;
if (noData) {
if (isSingleScan) {
log("ending: noData and isSingleScan", LogLevel.info);
endScanningSuccesfully();
return;
}
// re-subscribe to continue receiving messages, starting from the next unscanned height
final nextHeight = syncHeight + 1;
if (nextHeight <= scanData.chainTip) {
log(
"resubscribing: nextHeight: $nextHeight, count: ${getCountToScanPerRequest(nextHeight)}",
LogLevel.info,
);
final nextStream = scanningClient.subscribe(
ElectrumTweaksSubscribe(
height: nextHeight,
count: getCountToScanPerRequest(nextHeight),
historicalMode: hasForcedRescanHeights,
),
);
if (nextStream != null) {
nextStream.listen((event) => listenFn(event, req));
} else {
if (shouldUpdateSyncStatus)
scanData.sendPort.send(
SyncResponse(scanData.height, LostConnectionSyncStatus()),
);
}
}
log(
"ending: resubscribing: nextHeight: $nextHeight, count: ${getCountToScanPerRequest(nextHeight)}",
LogLevel.info,
);
return;
}
final tweakHeight = response.block;
// Continuous status UI update, send how many blocks left to scan
final syncingStatus = isSingleScan
? SyncingSyncStatus(1, 0)
: SyncingSyncStatus.fromHeightValues(scanData.chainTip, initialSyncHeight, tweakHeight);
if (shouldUpdateSyncStatus) scanData.sendPort.send(SyncResponse(syncHeight, syncingStatus));
try {
final blockTweaks = response.blockTweaks;
var blockDate = DateTime.now();
bool isDateNow = true;
for (final txid in blockTweaks.keys) {
final tweakData = blockTweaks[txid];
final outputPubkeys = tweakData!.outputPubkeys;
final tweak = tweakData.tweak;
try {
final addToWallet = <String, dynamic>{};
receivers.forEach((receiver) {
final preparedList = outputPubkeys.keys.toList().map((e) => [e]).toList();
// NOTE: scanOutputs, from sp_scanner package, called from rust here
final scanResult = scanOutputs(preparedList, tweak, receiver);
if (scanResult.isEmpty) return;
if (addToWallet[receiver.BSpend] == null) {
addToWallet[receiver.BSpend] = scanResult;
} else {
addToWallet[receiver.BSpend].addAll(scanResult);
}
});
if (addToWallet.isEmpty) {
// no results tx, continue to next tx
continue;
}
log(
"FOUND: addToWallet: ${addToWallet.length}, txid: $txid, tweak: $tweak, height: $tweakHeight",
LogLevel.info,
);
// Every tx in the block has the same date (the block date)
// So, if blockDate exists, reuse
if (isDateNow) {
try {
final rootURL = "https://cake.mempool.space";
final tweakBlockHash = await ProxyWrapper()
.get(clearnetUri: Uri.parse("$rootURL/api/block-height/$tweakHeight"))
.timeout(Duration(seconds: 15));
final blockResponse = await ProxyWrapper()
.get(clearnetUri: Uri.parse("$rootURL/api/block/${tweakBlockHash.body}"))
.timeout(Duration(seconds: 15));
if (blockResponse.statusCode == 200 &&
blockResponse.body.isNotEmpty &&
jsonDecode(blockResponse.body)['timestamp'] != null) {
blockDate = DateTime.fromMillisecondsSinceEpoch(
int.parse(jsonDecode(blockResponse.body)['timestamp'].toString()) * 1000,
);
isDateNow = false;
}
} catch (e, stacktrace) {
printV(stacktrace);
printV(e.toString());
}
}
// initial placeholder ElectrumTransactionInfo object to update values based on new scanned unspent(s) on the following loop
final txInfo = ElectrumTransactionInfo(
WalletType.bitcoin,
id: txid,
height: tweakHeight,
amount: 0,
fee: 0,
direction: TransactionDirection.incoming,
isReplaced: false,
date: scanData.network == BitcoinNetwork.mainnet
? (isDateNow ? getDateByBitcoinHeight(tweakHeight) : blockDate)
: DateTime.now(),
confirmations: scanData.chainTip - tweakHeight + 1,
isReceivedSilentPayment: true,
isPending: false,
unspents: [],
);
List<BitcoinUnspent> unspents = [];
addToWallet.forEach((BSpend, scanResultPerLabel) {
scanResultPerLabel.forEach((label, scanOutput) {
final labelValue = label == "None" ? null : label.toString();
(scanOutput as Map<String, dynamic>).forEach((outputPubkey, tweak) {
final t_k = tweak as String;
final receivingOutputAddress = ECPublic.fromHex(outputPubkey)
.toTaprootAddress(tweak: false)
.toAddress(scanData.network);
final matchingOutput = outputPubkeys[outputPubkey]!;
final amount = matchingOutput.amount;
final pos = matchingOutput.vout;
final spent = matchingOutput.spendingInput;
final matchingReceiver =
receivers.indexWhere((receiver) => receiver.BSpend == BSpend);
// final labelIndex = labelValue != null ? scanData.labels[label] : 0;
// final balance = ElectrumBalance();
// balance.confirmed = amount;
final receivedAddressRecord = BitcoinSilentPaymentAddressRecord(
receivingOutputAddress,
index: 0,
isHidden: false,
isUsed: true,
network: scanData.network,
silentPaymentTweak: t_k,
type: SegwitAddresType.p2tr,
txCount: 1,
balance: amount,
spendDerivationPath: matchingReceiver == 0
? SILENT_PAYMENTS_SPEND_PATH
: SILENT_PAYMENTS_SPEND_PATH_TESTNET,
);
final unspent = BitcoinSilentPaymentsUnspent(
receivedAddressRecord,
txid,
amount,
pos,
silentPaymentTweak: t_k,
silentPaymentLabel: labelValue,
);
if (spent == null) {
unspents.add(unspent);
txInfo.unspents!.add(unspent);
}
txInfo.amount += unspent.value;
});
});
});
scanData.sendPort.send({txInfo.id: txInfo});
} catch (e, stacktrace) {
if (shouldUpdateSyncStatus)
scanData.sendPort.send(
SyncResponse(syncHeight, LostConnectionSyncStatus()),
);
log(stacktrace.toString(), LogLevel.error);
log(e.toString(), LogLevel.error);
return;
}
}
} catch (e, stacktrace) {
if (shouldUpdateSyncStatus)
scanData.sendPort.send(
SyncResponse(syncHeight, LostConnectionSyncStatus()),
);
log(stacktrace.toString(), LogLevel.error);
log(e.toString(), LogLevel.error);
return;
}
syncHeight = tweakHeight;
if ((tweakHeight >= scanData.chainTip) || isSingleScan) {
endScanningSuccesfully();
}
}
_scanningStream?.listen((event) => listenFn(event, req));
}
if (scanData.rescanHeights != null) {
for (final height in scanData.rescanHeights!) {
log("rescanning from height: $height", LogLevel.info);
scan(height, true);
}
} else {
scan(scanData.height, scanData.isSingleScan);
}
} catch (e) {
log("Error in _handleScanSilentPayments: $e", LogLevel.error);
if (shouldUpdateSyncStatus)
scanData.sendPort.send(SyncResponse(scanData.height, LostConnectionSyncStatus()));
}
}
class EstimatedTxResult {
EstimatedTxResult({
required this.utxos,
required this.inputPrivKeyInfos,
required this.publicKeys,
required this.fee,
required this.amount,
required this.hasChange,
required this.isSendAll,
this.memo,
required this.spendsSilentPayment,
required this.spendsUnconfirmedTX,
});
final List<UtxoWithAddress> utxos;
final List<ECPrivateInfo> inputPrivKeyInfos;
final Map<String, PublicKeyWithDerivationPath> publicKeys; // PubKey to derivationPath
final int fee;
final int amount;
final bool spendsSilentPayment;
// final bool sendsToSilentPayment;
final bool hasChange;
final bool isSendAll;
final String? memo;
final bool spendsUnconfirmedTX;
}
class PublicKeyWithDerivationPath {
const PublicKeyWithDerivationPath(this.publicKey, this.derivationPath);
final String derivationPath;
final String publicKey;
}
BitcoinAddressType _getScriptType(BitcoinBaseAddress type) {
if (type is P2pkhAddress) {
return P2pkhAddressType.p2pkh;
} else if (type is P2shAddress) {
return P2shAddressType.p2wpkhInP2sh;
} else if (type is P2wshAddress) {
return SegwitAddresType.p2wsh;
} else if (type is P2trAddress) {
return SegwitAddresType.p2tr;
} else if (type is MwebAddress) {
return SegwitAddresType.mweb;
} else if (type is SilentPaymentsAddresType) {
return SilentPaymentsAddresType.p2sp;
} else {
return SegwitAddresType.p2wpkh;
}
}
class UtxoDetails {
final List<BitcoinUnspent> availableInputs;
final List<BitcoinUnspent> unconfirmedCoins;
final List<UtxoWithAddress> utxos;
final List<Outpoint> vinOutpoints;
final List<ECPrivateInfo> inputPrivKeyInfos;
final Map<String, PublicKeyWithDerivationPath> publicKeys; // PubKey to derivationPath
final int allInputsAmount;
final bool spendsSilentPayment;
final bool spendsUnconfirmedTX;
UtxoDetails({
required this.availableInputs,
required this.unconfirmedCoins,
required this.utxos,
required this.vinOutpoints,
required this.inputPrivKeyInfos,
required this.publicKeys,
required this.allInputsAmount,
required this.spendsSilentPayment,
required this.spendsUnconfirmedTX,
});
}