Merge branch 'dev' into fix/cw-1633-cakepay-lightning-balance
What changed, and why it matters
This is a large merge commit that brings the 'dev' branch into a feature branch named 'fix/cw-1633-cakepay-lightning-balance'. The visible changes are almost entirely routine project maintenance: new CI/CD workflows for iOS, Linux and Android builds, translation and changelog updates, asset additions (logos, stock icons, font files), new Electrum/Tor server entries, and a Robinhood wallet URL scheme. None of the supplied diff content shows a security fix, vulnerability, malicious change, or disclosure of sensitive data. The commit title and message do not describe any security relevance.
No security action required. Treat as normal development merge. If reviewing for release, verify the new CI secrets handling and Docker-based build scripts separately, but those are not visible in this diff.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The diff is a merge of ‘dev’ into a feature branch. It adds/modifies GitHub Actions workflows (reusable build/test runners, iOS TestFlight, Linux/Android dockerized builds), updates .gitignore for signing artifacts, adds changelog entries in many languages, adds image/font assets, adds a Tor Electrum server for Bitcoin/Litecoin, and registers ‘robinhood*’ deep-link schemes in AndroidManifestBase.xml. No code-level security-sensitive changes are present in the supplied diff. The commit is not a security patch and contains no attribution or CVE references.
Changed components
.github/workflows/*assets/new-ui/changelog/text/*assets/images/*assets/fonts/*assets/bitcoin_electrum_server_list.ymlassets/litecoin_electrum_server_list.ymlandroid/app/src/main/AndroidManifestBase.xml.gitignoreREADME.mdInspect captured patch +44768 / −32473
### .github/workflows/are_translations_sane.yml
@@ -4,7 +4,7 @@ on: [pull_request]
jobs:
PR_test_build:
- runs-on: ubuntu-24.04
+ runs-on: puzl-ubuntu-latest
steps:
- uses: actions/checkout@v4
### .github/workflows/automated_integration_test.yml
@@ -1,487 +0,0 @@
-
-name: Automated Integration Tests
-
-# Temporarily disabled - uncomment to re-enable
-on:
- # push:
- # pull_request:
- # branches: [main]
- workflow_dispatch: # This is to manually trigger if needed
-defaults:
- run:
- shell: bash
-jobs:
- Automated_integration_test:
- runs-on: linux-amd64
- timeout-minutes: 90
- container:
- image: ghcr.io/cake-tech/cake_wallet:debian12-flutter3.27.0-go1.24.1-ruststablenightly
- env:
- STORE_PASS: test@cake_wallet
- KEY_PASS: test@cake_wallet
- MONEROC_CACHE_DIR_ROOT: /opt/generic_cache
- BRANCH_NAME: ${{ github.head_ref || github.ref_name }}
- ANDROID_AVD_HOME: /root/.android/avd
- volumes:
- - /opt/cw_cache_android/root/.cache:/root/.cache
- - /opt/cw_cache_android/root/.android/avd/:/root/.android/avd
- - /opt/cw_cache_android/root/.ccache:/root/.ccache
- - /opt/cw_cache_android/root/.pub-cache/:/root/.pub-cache
- - /opt/cw_cache_android/root/.gradle/:/root/.gradle
- - /opt/cw_cache_android/root/.android/:/root/.android
- - /opt/cw_cache_android/root/go/pkg:/root/go/pkg
- - /opt/cw_cache_android/opt/generic_cache:/opt/generic_cache
- - /dev/kvm:/dev/kvm
- strategy:
- matrix:
- api-level: [29]
-
- steps:
- - name: Fix github actions messing up $HOME...
- run: 'echo HOME=/root | sudo tee -a $GITHUB_ENV'
- - uses: actions/checkout@v4
- with:
- ref: ${{ github.event.pull_request.head.sha || github.sha }}
- - name: configure git
- run: |
- git config --global --add safe.directory '*'
- git config --global user.email "ci@cakewallet.com"
- git config --global user.name "CakeWallet CI"
- - name: Get the full commit message
- run: |
- FULL_MESSAGE="$(git log -1 --pretty=%B)"
- echo "message<<EOF" >> $GITHUB_ENV
- echo "$FULL_MESSAGE" >> $GITHUB_ENV
- echo "EOF" >> $GITHUB_ENV
-
- - name: Add secrets
- run: |
- touch cw_bitcoin/lib/.secrets.g.dart
- touch cw_evm/lib/.secrets.g.dart
- touch cw_solana/lib/.secrets.g.dart
- touch cw_core/lib/.secrets.g.dart
- touch cw_nano/lib/.secrets.g.dart
- touch cw_tron/lib/.secrets.g.dart
-
- echo "const polygonScanApiKey = '${{ secrets.POLYGON_SCAN_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
- echo "const etherScanApiKey = '${{ secrets.ETHER_SCAN_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
- echo "const moralisApiKey = '${{ secrets.MORALIS_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
- echo "const nowNodesApiKey = '${{ secrets.EVM_NOWNODES_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
- echo "const ankrApiKey = '${{ secrets.ANKR_API_KEY }}';" >> cw_solana/lib/.secrets.g.dart
- echo "const chainStackApiKey = '${{ secrets.CHAIN_STACK_API_KEY }}';" >> cw_solana/lib/.secrets.g.dart
- echo "const moralisApiKey = '${{ secrets.MORALIS_API_KEY }}';" >> cw_solana/lib/.secrets.g.dart
-
- echo "const nano2ApiKey = '${{ secrets.NANO2_API_KEY }}';" >> cw_nano/lib/.secrets.g.dart
- echo "const nanoNowNodesApiKey = '${{ secrets.NANO_NOW_NODES_API_KEY }}';" >> cw_nano/lib/.secrets.g.dart
-
- echo "const tronGridApiKey = '${{ secrets.TRON_GRID_API_KEY }}';" >> cw_tron/lib/.secrets.g.dart
- echo "const tronNowNodesApiKey = '${{ secrets.TRON_NOW_NODES_API_KEY }}';" >> cw_tron/lib/.secrets.g.dart
-
- echo "const breezApiKey = '${{ secrets.BREEZ_API_KEY }}';" >> cw_bitcoin/lib/.secrets.g.dart
-
- echo "${{ secrets.MAIN_SECRETS_FILE }}" | base64 --decode > lib/.secrets.g.dart
-
- - name: prepare monero_c and cache
- run: |
- export MONEROC_HASH=$(cat scripts/prepare_moneroc.sh | grep 'git checkout' | xargs | awk '{ print $3 }')
- echo MONEROC_HASH=$MONEROC_HASH >> /etc/environment
- mkdir -p "$MONEROC_CACHE_DIR_ROOT/moneroc-$MONEROC_HASH/monero_c"
- pushd scripts
- ln -s "$MONEROC_CACHE_DIR_ROOT/moneroc-$MONEROC_HASH/monero_c"
- ./prepare_moneroc.sh
- popd
- pushd scripts/monero_c
- mkdir -p "$MONEROC_CACHE_DIR_ROOT/_cache/contrib/depends/built" || true
- mkdir -p "$MONEROC_CACHE_DIR_ROOT/_cache/monero/contrib/depends/built" || true
- mkdir -p "$MONEROC_CACHE_DIR_ROOT/_cache/wownero/contrib/depends/built" || true
- mkdir -p "$MONEROC_CACHE_DIR_ROOT/_cache/contrib/depends/sources" || true
- mkdir -p "$MONEROC_CACHE_DIR_ROOT/_cache/monero/contrib/depends/sources" || true
- mkdir -p "$MONEROC_CACHE_DIR_ROOT/_cache/wownero/contrib/depends/sources" || true
-
- rm -rf "$PWD/contrib/depends/built" "$PWD/monero/contrib/depends/built" "$PWD/wownero/contrib/depends/built"
- rm -rf "$PWD/contrib/depends/sources" "$PWD/monero/contrib/depends/sources" "$PWD/wownero/contrib/depends/sources"
- mkdir -p contrib/depends || true
- ln -sf "$MONEROC_CACHE_DIR_ROOT/_cache/contrib/depends/built" "$PWD/contrib/depends/built"
- ln -sf "$MONEROC_CACHE_DIR_ROOT/_cache/monero/contrib/depends/built" "$PWD/monero/contrib/depends/built"
- ln -sf "$MONEROC_CACHE_DIR_ROOT/_cache/wownero/contrib/depends/built" "$PWD/wownero/contrib/depends/built"
- ln -sf "$MONEROC_CACHE_DIR_ROOT/_cache/contrib/depends/sources" "$PWD/contrib/depends/sources"
- ln -sf "$MONEROC_CACHE_DIR_ROOT/_cache/monero/contrib/depends/sources" "$PWD/monero/contrib/depends/sources"
- ln -sf "$MONEROC_CACHE_DIR_ROOT/_cache/wownero/contrib/depends/sources" "$PWD/wownero/contrib/depends/sources"
- popd
-
- - name: Generate KeyStore
- run: |
- pushd /opt/generic_cache
- if [[ ! -f key.jks ]];
- then
- keytool -genkey -v -keystore key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias testKey -noprompt -dname "CN=CakeWallet, OU=CakeWallet, O=CakeWallet, L=Florida, S=America, C=USA" -storepass $STORE_PASS -keypass $KEY_PASS
- else
- echo "$PWD/key.jks exist, not generating"
- fi
- popd
- cp /opt/generic_cache/key.jks android/app
-
- - name: Execute Build and Setup Commands
- run: |
- pushd scripts/android
- source ./app_env.sh cakewallet
- ./app_config.sh
- popd
-
- - name: Build monero_c
- run: |
- pushd scripts/android/
- source ./app_env.sh cakewallet
- ./build_monero_all.sh
- popd
-
- - name: Install Flutter dependencies
- run: |
- flutter pub get
-
- - name: Build mwebd
- run: |
- set -x -e
- export MWEBD_HASH=$(cat scripts/android/build_mwebd.sh | grep 'git reset --hard' | xargs | awk '{ print $4 }')
- echo MWEBD_HASH=$MWEBD_HASH >> /etc/environment
- pushd scripts/android
- gomobile init;
- ./build_mwebd.sh
- popd
-
- - name: Build Decred
- run: |
- set -x -e
- pushd scripts/android
- ./build_decred.sh
- popd
-
- - name: Build generated code
- run: |
- flutter --version
- flutter pub get
- ./model_generator.sh
-
- - name: Generate key properties
- run: |
- dart run tool/generate_android_key_properties.dart keyAlias=testKey storeFile=key.jks storePassword=$STORE_PASS keyPassword=$KEY_PASS
-
- - name: Generate localization
- run: |
- dart run tool/generate_localization.dart
-
- - name: Rename app
- run: |
- sanitized_branch_name=${BRANCH_NAME#origin/} # Remove 'origin/' prefix if it exists
- sanitized_branch_name=${sanitized_branch_name:0:16} # Take only the first 16 characters
- sanitized_branch_name=$(echo "$sanitized_branch_name" | tr '[:upper:]' '[:lower:]') # Convert to lowercase
- sanitized_branch_name=$(echo "$sanitized_branch_name" | sed 's/[^a-z0-9]//g') # Remove all special characters
-
- echo -e "id=com.cakewallet.test_${sanitized_branch_name}\nname=${BRANCH_NAME}" > android/app.properties
-
- - name: Build
- run: |
- flutter build apk --dart-define=hasDevOptions=true --release --split-per-abi
-
- - name: Rename apk file
- run: |
- sanitized_branch_name=$(grep '^id=' android/app.properties | cut -d'=' -f2 | sed 's/com\.cakewallet\.test_//')
- cd build/app/outputs/flutter-apk
- mkdir test-apk
-
- cp app-arm64-v8a-release.apk test-apk/${sanitized_branch_name}.apk
- cp app-x86_64-release.apk test-apk/${sanitized_branch_name}_x86.apk
- echo "APK files created: test-apk/${sanitized_branch_name}.apk and test-apk/${sanitized_branch_name}_x86.apk"
-
- - name: Find APK file
- id: find_apk
- run: |
- set -x
- # Read the sanitized branch name from the app.properties file
- sanitized_branch_name=$(grep '^id=' android/app.properties | cut -d'=' -f2 | sed 's/com\.cakewallet\.test_//')
-
- echo "Looking for APK file: build/app/outputs/flutter-apk/test-apk/${sanitized_branch_name}.apk"
- ls -la build/app/outputs/flutter-apk/test-apk/ || echo "test-apk directory not found"
- apk_file=$(ls build/app/outputs/flutter-apk/test-apk/${sanitized_branch_name}.apk || exit 1)
- echo "APK_FILE=$apk_file" >> $GITHUB_ENV
- echo "APK file found: $apk_file"
- ls -la "$apk_file"
-
- - name: 🔍 Debug System Environment
- run: |
- echo "=== System Information ==="
- uname -a
- echo "=== Container Info ==="
- cat /proc/version || echo "Cannot read /proc/version"
- echo "=== KVM Device Check ==="
- ls -la /dev/kvm || echo "KVM device not found"
- echo "=== udev Status ==="
- which udevadm || echo "udevadm not found"
- echo "=== Current User ==="
- whoami
- echo "=== Groups ==="
- groups
- echo "=== Environment ==="
- env | grep -E "(HOME|USER|PATH)" | sort
-
- - name: 🧹 Clean up existing emulators
- run: |
- echo "=== Cleaning up existing emulators ==="
- # Kill any existing emulator processes
- pkill -f emulator || echo "No emulator processes found"
- # Kill any existing adb processes
- pkill -f adb || echo "No adb processes found"
- # Wait a moment for processes to terminate
- sleep 2
- # Start adb server fresh
- adb start-server || echo "Failed to start adb server"
- # Kill adb server to ensure clean state
- adb kill-server || echo "Failed to kill adb server"
- echo "=== Cleanup complete ==="
-
- - name: 🔍 Verify AVD Configuration
- run: |
- echo "=== AVD Configuration Check ==="
-
- # Check if AVD directory exists
- echo "Checking AVD directory..."
- ls -la ~/.android/avd/ || echo "AVD directory not found"
-
- # List available AVDs
- echo "Available AVDs:"
- emulator -list-avds || echo "Failed to list AVDs"
-
- # Check Android SDK location
- echo "Android SDK location:"
- echo $ANDROID_HOME
- echo $ANDROID_SDK_ROOT
-
- # Check emulator binary
- echo "Emulator binary:"
- which emulator || echo "Emulator not found in PATH"
- emulator -version || echo "Failed to get emulator version"
-
- echo "=== AVD Check Complete ==="
-
- - name: 🦾 Enable KVM
- run: |
- echo "=== KVM Setup and Verification ==="
-
- # Check if KVM device exists
- if [ -e /dev/kvm ]; then
- echo "✅ KVM device found at /dev/kvm"
-
- # Check current permissions
- echo "Current KVM permissions:"
- ls -la /dev/kvm
-
- # Set proper permissions
- sudo chmod 666 /dev/kvm || echo "⚠️ Failed to set KVM permissions"
-
- # Verify permissions were set
- if [ -r /dev/kvm ] && [ -w /dev/kvm ]; then
- echo "✅ KVM is readable and writable"
- else
- echo "⚠️ KVM permissions may not be optimal"
- fi
-
- # Test KVM functionality
- echo "Testing KVM functionality..."
- if command -v kvm-ok >/dev/null 2>&1; then
- if kvm-ok 2>/dev/null; then
- echo "✅ KVM is working properly"
- else
- echo "⚠️ KVM check failed, but continuing..."
- fi
- else
- echo "ℹ️ kvm-ok command not available, testing manually..."
- # Manual KVM test
- if [ -r /dev/kvm ] && [ -w /dev/kvm ]; then
- echo "✅ KVM device is accessible"
- fi
- fi
-
- # Try to create udev rules (may fail in container, that's OK)
- echo "Setting up udev rules..."
- sudo mkdir -p /etc/udev/rules.d || echo "⚠️ Could not create udev directory"
- echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules || echo "⚠️ Could not create udev rule"
-
- # Try to reload udev rules (will likely fail in container, that's OK)
- sudo udevadm control --reload-rules || echo "ℹ️ udevadm control failed (expected in container)"
- sudo udevadm trigger --name-match=kvm || echo "ℹ️ udevadm trigger failed (expected in container)"
-
- else
- echo "❌ KVM device not found at /dev/kvm"
- echo "This will cause the emulator to run in software mode (slower)"
- fi
-
- # Check system resources
- echo "=== System Resources ==="
- echo "Memory:"
- free -h
- echo "Disk space:"
- df -h
- echo "CPU cores:"
- nproc
- echo "KVM module loaded:"
- lsmod | grep kvm || echo "KVM module not loaded (may be built-in)"
-
- echo "=== KVM Setup Complete ==="
-
- - name: 🦾 Cache gradle
- uses: gradle/actions/setup-gradle@v3
-
- - name: 🦾 Cache AVD
- uses: actions/cache@v4
- id: avd-cache
- with:
- path: |
- ~/.android/avd/*
- ~/.android/adb*
- key: avd-${{ matrix.api-level }}
-
- - name: 🔧 Prepare emulator utilities
- run: |
- # Create a helper script for emulator readiness checks
- cat > /tmp/emulator_ready.sh << 'EOF'
- #!/bin/bash
-
- echo "=== Emulator Readiness Check ==="
-
- # Wait for boot completion
- echo "1. Checking boot completion..."
- timeout 300 bash -c 'until adb shell getprop sys.boot_completed 2>/dev/null | grep -q "1"; do sleep 5; echo " Waiting for boot completion..."; done'
- if [ $? -eq 0 ]; then
- echo "✅ Boot completed"
- else
- echo "❌ Boot completion timeout"
- echo "⚠️ Continuing anyway..."
- fi
-
- # Wait for input service
- echo "2. Checking input service..."
- timeout 60 bash -c 'until adb shell service list 2>/dev/null | grep -q "input"; do sleep 2; echo " Waiting for input service..."; done'
- if [ $? -eq 0 ]; then
- echo "✅ Input service ready"
- else
- echo "❌ Input service timeout"
- echo "⚠️ Continuing anyway..."
- fi
-
- # Wait for package manager
- echo "3. Checking package manager..."
- timeout 60 bash -c 'until adb shell pm list packages 2>/dev/null >/dev/null; do sleep 2; echo " Waiting for package manager..."; done'
- if [ $? -eq 0 ]; then
- echo "✅ Package manager ready"
- else
- echo "❌ Package manager timeout"
- echo "⚠️ Continuing anyway..."
- fi
-
- # Wait for settings service
- echo "4. Checking settings service..."
- timeout 60 bash -c 'until adb shell settings get global window_animation_scale 2>/dev/null >/dev/null; do sleep 2; echo " Waiting for settings service..."; done'
- if [ $? -eq 0 ]; then
- echo "✅ Settings service ready"
- else
- echo "❌ Settings service timeout"
- echo "⚠️ Continuing anyway..."
- fi
-
- echo "✅ Emulator readiness check completed"
- EOF
-
- chmod +x /tmp/emulator_ready.sh
-
- - name: 🦾 Create AVD and generate snapshot for caching
- if: steps.avd-cache.outputs.cache-hit != 'true'
- uses: reactivecircus/android-emulator-runner@v2
- with:
- api-level: ${{ matrix.api-level }}
- force-avd-creation: false
- # arch: ${{ matrix.arch }}
- emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none -read-only -memory 1024 -no-snapshot-save
- working-directory: ${{ github.workspace }}
- disable-animations: false
- script: |
- echo "=== AVD Snapshot Generation ==="
-
- # Use the helper script to ensure emulator is fully ready
- /tmp/emulator_ready.sh
-
- # Manually disable animations with error handling
- echo "Disabling animations manually..."
- adb shell settings put global window_animation_scale 0.0 || echo "Failed to disable window animations"
- adb shell settings put global transition_animation_scale 0.0 || echo "Failed to disable transition animations"
- adb shell settings put global animator_duration_scale 0.0 || echo "Failed to disable animator duration"
-
- echo "=== Checking emulator status before termination ==="
- adb devices || echo "ADB devices check failed"
- echo "=== AVD snapshot generation complete ==="
-
- - name: 🚀 Integration tests on Android Emulator
- timeout-minutes: 60
- uses: reactivecircus/android-emulator-runner@v2
- with:
- api-level: ${{ matrix.api-level }}
- force-avd-creation: false
- emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none -read-only -memory 1024 -no-snapshot-save
- disable-animations: false
- working-directory: ${{ github.workspace }}
- script: |
- echo "=== Pre-test Environment Check ==="
- pwd
- ls -la integration_test_runner.sh || echo "integration_test_runner.sh not found"
-
- echo "=== Emulator Status Check ==="
- adb devices
-
- echo "=== Emulator Info ==="
- adb shell getprop ro.build.version.release || echo "Failed to get Android version"
- adb shell getprop ro.product.model || echo "Failed to get device model"
-
- echo "=== Checking Emulator Performance ==="
- adb shell cat /proc/cpuinfo | grep -i "model name" | head -1 || echo "Could not check CPU info"
- adb shell cat /proc/meminfo | grep -i "memtotal" || echo "Could not check memory info"
-
- echo "=== Checking Emulator Process ==="
- ps aux | grep emulator | grep -v grep || echo "Emulator process not found in ps output"
-
- echo "=== Making script executable ==="
- chmod a+rx integration_test_runner.sh
-
- echo "=== Running integration tests ==="
-
- echo "Final emulator readiness check..."
- /tmp/emulator_ready.sh || echo "Emulator readiness check failed, but continuing..."
-
- echo "Disabling animations for test performance..."
- adb shell settings put global window_animation_scale 0.0 || echo "Failed to disable window animations"
- adb shell settings put global transition_animation_scale 0.0 || echo "Failed to disable transition animations"
- adb shell settings put global animator_duration_scale 0.0 || echo "Failed to disable animator duration"
-
- echo "Starting integration test runner..."
- ./integration_test_runner.sh
- TEST_EXIT_CODE=$?
-
- if [ $TEST_EXIT_CODE -eq 0 ]; then
- echo "Integration tests completed successfully"
- else
- echo "Integration tests failed with exit code $TEST_EXIT_CODE"
- fi
-
- - name: 🧹 Post-test cleanup
- if: always()
- run: |
- echo "=== Post-test cleanup ==="
- # Kill any remaining emulator processes
- pkill -f emulator || echo "No emulator processes to kill"
- # Kill any remaining adb processes
- pkill -f adb || echo "No adb processes to kill"
- # Wait for processes to terminate
- sleep 2
- # Check for any remaining processes
- ps aux | grep -E "(emulator|adb)" | grep -v grep || echo "No remaining emulator/adb processes"
- echo "=== Cleanup complete ==="
- - name: cleanup
- run: rm -rf build/app/outputs/flutter-apk/test-apk/
### .github/workflows/compare_overrides.yml
@@ -10,7 +10,7 @@ permissions:
jobs:
compare-overrides:
- runs-on: ubuntu-24.04
+ runs-on: puzl-ubuntu-latest
steps:
- uses: actions/checkout@v4
### .github/workflows/funds_integration_tests.yml
@@ -0,0 +1,64 @@
+name: Funds Integration Tests
+
+permissions:
+ contents: read
+ packages: write
+
+# This test is never triggered automatically as it moves real funds
+on:
+ workflow_dispatch:
+ inputs:
+ flows:
+ description: "Which flows to run"
+ required: true
+ type: choice
+ options:
+ - all
+ - send
+ - swap
+ default: all
+ chains:
+ description: "Chains the send suites run on. auto discovers every funded chain, or a comma separated list of wallet type names"
+ required: true
+ type: string
+ default: auto
+ swap_from:
+ description: "Wallet type the swap deposits from. Empty takes the first funded chain"
+ required: false
+ type: string
+ default: ""
+ swap_to:
+ description: "Currency the swap receives, for example eth or btc. Empty leaves the swap page's own pairing"
+ required: false
+ type: string
+ default: ""
+ spend:
+ description: "Actually broadcast and create trades. Off runs the dry runs only"
+ required: true
+ type: boolean
+ default: false
+ record_screen:
+ description: "Record the emulator screen, uploaded GPG encrypted"
+ required: true
+ type: boolean
+ default: true
+
+concurrency:
+ group: funds-integration-tests
+ cancel-in-progress: false
+
+jobs:
+ funds-tests:
+ uses: ./.github/workflows/reusable-integration-test.yml
+ with:
+ environment: funds
+ ref: ${{ github.sha }}
+ suite_dir: integration_test/funds_suites
+ test_tier: all
+ write_funds_secrets: true
+ record_screen: ${{ inputs.record_screen }}
+ timeout_minutes: 120
+ slack_notify: true
+ extra_dart_defines: "FLOWS=${{ inputs.flows }};CHAINS=${{ inputs.chains }};SPEND=${{ inputs.spend }};SWAP_FROM=${{ inputs.swap_from }};SWAP_RECEIVE=${{ inputs.swap_to }}"
+ secrets: inherit
+
### .github/workflows/integration_tests.yml
@@ -0,0 +1,39 @@
+name: Integration Tests
+
+permissions:
+ contents: read
+ packages: write
+
+on:
+ workflow_dispatch:
+
+concurrency:
+ group: integration-tests-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ check-suites:
+ if: github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.fork == false
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ ref: ${{ github.event.pull_request.head.sha || github.sha }}
+ sparse-checkout: integration_test/suites
+
+ - name: Check the branch has the test suites
+ run: |
+ if [[ ! -d integration_test/suites/tier0 ]]; then
+ echo "::error::This branch has no integration test suites yet, sync it with dev to run them"
+ exit 1
+ fi
+
+ android-integration-tests:
+ needs: check-suites
+ uses: ./.github/workflows/reusable-integration-test.yml
+ with:
+ ref: ${{ github.event.pull_request.head.sha || github.sha }}
+ suite_dir: integration_test/suites
+ test_tier: tier0
+ slack_notify: true
+ secrets: inherit
### .github/workflows/lint.yml
@@ -73,13 +73,6 @@ jobs:
# rm ./reown_flutter.tar.gz
# popd
#
-# - name: Build Bitbox Flutter
-# run: |
-# set -x -e
-# pushd scripts
-# ./build_bitbox_flutter.sh
-# popd
-#
# - name: Prepare Zcash
# run: |
# set -x -e
@@ -112,4 +105,4 @@ jobs:
#
# - name: Lint
# run: |
-# ABORT_ON_CHANGE=yeah scripts/lint.sh
\ No newline at end of file
+# ABORT_ON_CHANGE=yeah scripts/lint.sh
### .github/workflows/no_http_imports.yaml
@@ -4,7 +4,7 @@ on: [pull_request]
jobs:
PR_test_build:
- runs-on: ubuntu-24.04
+ runs-on: puzl-ubuntu-latest
steps:
- uses: actions/checkout@v4
### .github/workflows/no_print_in_dart.yaml
@@ -4,7 +4,7 @@ on: [pull_request]
jobs:
PR_test_build:
- runs-on: ubuntu-24.04
+ runs-on: puzl-ubuntu-latest
steps:
- uses: actions/checkout@v4
### .github/workflows/no_restricted_imports.yaml
@@ -4,7 +4,7 @@ on: [pull_request]
jobs:
check_restricted_imports:
- runs-on: ubuntu-24.04
+ runs-on: puzl-ubuntu-latest
steps:
- uses: actions/checkout@v4
### .github/workflows/pr_test_build_android.yml
@@ -7,6 +7,10 @@ permissions:
contents: read
packages: write
+concurrency:
+ group: android-${{ github.event.pull_request.number }}
+ cancel-in-progress: true
+
jobs:
# -----------------------------------------
# PATH A: Internal PRs
### .github/workflows/pr_test_build_ios.yml
@@ -0,0 +1,477 @@
+name: Cake Wallet iOS
+
+on:
+ pull_request:
+
+permissions:
+ contents: read
+ packages: read
+
+concurrency:
+ group: ios-${{ github.head_ref || github.ref_name }}
+ cancel-in-progress: true
+
+defaults:
+ run:
+ shell: bash
+
+jobs:
+ # these are separate linux runners that put torch and monero in cache
+ # otherwise the macos build wouldn't finish withing the 6 hour gh time limit
+ torch:
+ if: github.event.pull_request.head.repo.fork == false
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
+ permissions:
+ contents: read
+ packages: write
+ env:
+ CW_DOCKER_REGISTRY: ghcr.io/cake-tech/cake_wallet
+ CW_DOCKER_USE_CLOUD: "true"
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Build torch
+ run: ./scripts/ios/docker/build.sh --only torch
+
+ monero:
+ if: github.event.pull_request.head.repo.fork == false
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
+ permissions:
+ contents: read
+ packages: write
+ env:
+ CW_DOCKER_REGISTRY: ghcr.io/cake-tech/cake_wallet
+ CW_DOCKER_USE_CLOUD: "true"
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Build monero_c
+ run: |
+ ./scripts/ios/docker/build.sh --only monero
+ ./scripts/ios/docker/build.sh --only monero --merge
+
+ build:
+ needs: [torch, monero]
+ if: github.event.pull_request.head.repo.fork == false
+ runs-on: macos-26
+
+ outputs:
+ build_number: ${{ steps.config.outputs.build_number }}
+ app_version: ${{ steps.config.outputs.app_version }}
+
+ env:
+ BRANCH_NAME: ${{ github.head_ref || github.ref_name }}
+ FLUTTER_VERSION: "3.41.9"
+ GO_VERSION: "1.24.1"
+
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+
+ - name: Configure git
+ run: |
+ git config --global user.email "ci@cakewallet.com"
+ git config --global user.name "CakeWallet CI"
+
+ - name: Authenticate git for GitHub clones
+ run: |
+ git config --global --unset-all credential.helper || true
+ git config --global url."https://x-access-token:${{ github.token }}@github.com/".insteadOf "https://github.com/"
+
+
+ - name: Identify the build
+ run: |
+ BRANCH="${BRANCH_NAME#origin/}"
+ # cw-1234-something -> 1234
+ TICKET="$(printf '%s' "$BRANCH" | tr 'A-Z' 'a-z' \
+ | grep -oE '(^|[^a-z0-9])cw-?[0-9]+' | head -1 | grep -oE '[0-9]+' || true)"
+
+ if [[ -n "$TICKET" ]]; then
+ TICKET=$((10#$TICKET)) # drop leading zeros, Apple dislikes them
+ echo "APP_DISPLAY_NAME=CW-$TICKET" >> $GITHUB_ENV
+ echo "APP_VERSION=6.$TICKET" >> $GITHUB_ENV
+ else
+ echo "APP_DISPLAY_NAME=Cake (CI)" >> $GITHUB_ENV
+ echo "APP_VERSION=" >> $GITHUB_ENV
+ fi
+ echo "BUILD_NUMBER=${{ github.run_number }}" >> $GITHUB_ENV
+
+ - uses: subosito/flutter-action@1a449444c387b1966244ae4d4f8c696479add0b2 # v2.23.0
+ with:
+ flutter-version: ${{ env.FLUTTER_VERSION }}
+ channel: stable
+
+ - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0
+ with:
+ go-version: ${{ env.GO_VERSION }}
+
+ - name: Add Rust iOS target
+ run: |
+ rustup target add aarch64-apple-ios
+
+ - name: Install protoc
+ env:
+ PROTOC_VERSION: "35.1"
+ run: |
+ set -euo pipefail
+ curl -sSL --retry 3 --retry-delay 5 -o "$RUNNER_TEMP/protoc.zip" \
+ "https://github.com/protocolbuffers/protobuf/releases/download/v${PROTOC_VERSION}/protoc-${PROTOC_VERSION}-osx-universal_binary.zip"
+ unzip -q -o "$RUNNER_TEMP/protoc.zip" -d "$RUNNER_TEMP/protoc"
+ rm -f "$RUNNER_TEMP/protoc.zip"
+ echo "$RUNNER_TEMP/protoc/bin" >> $GITHUB_PATH
+ "$RUNNER_TEMP/protoc/bin/protoc" --version
+
+ - name: Add secrets
+ run: |
+ touch cw_bitcoin/lib/.secrets.g.dart
+ touch cw_evm/lib/.secrets.g.dart
+ touch cw_solana/lib/.secrets.g.dart
+ touch cw_core/lib/.secrets.g.dart
+ touch cw_nano/lib/.secrets.g.dart
+ touch cw_tron/lib/.secrets.g.dart
+
+ echo "const polygonScanApiKey = '${{ secrets.POLYGON_SCAN_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
+ echo "const etherScanApiKey = '${{ secrets.ETHER_SCAN_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
+ echo "const moralisApiKey = '${{ secrets.MORALIS_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
+ echo "const nowNodesApiKey = '${{ secrets.EVM_NOWNODES_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
+ echo "const blinkApiKey = '${{ secrets.BLINK_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
+ echo "const ankrApiKey = '${{ secrets.ANKR_API_KEY }}';" >> cw_solana/lib/.secrets.g.dart
+ echo "const chainStackApiKey = '${{ secrets.CHAIN_STACK_API_KEY }}';" >> cw_solana/lib/.secrets.g.dart
+ echo "const moralisApiKey = '${{ secrets.MORALIS_API_KEY }}';" >> cw_solana/lib/.secrets.g.dart
+
+ echo "const nano2ApiKey = '${{ secrets.NANO2_API_KEY }}';" >> cw_nano/lib/.secrets.g.dart
+ echo "const nanoNowNodesApiKey = '${{ secrets.NANO_NOW_NODES_API_KEY }}';" >> cw_nano/lib/.secrets.g.dart
+
+ echo "const tronGridApiKey = '${{ secrets.TRON_GRID_API_KEY }}';" >> cw_tron/lib/.secrets.g.dart
+ echo "const tronNowNodesApiKey = '${{ secrets.TRON_NOW_NODES_API_KEY }}';" >> cw_tron/lib/.secrets.g.dart
+
+ echo "const breezApiKey = '${{ secrets.BREEZ_API_KEY }}';" >> cw_bitcoin/lib/.secrets.g.dart
+
+ echo "${{ secrets.MAIN_SECRETS_FILE }}" | base64 --decode > lib/.secrets.g.dart
+
+ - name: Set up crane
+ run: |
+ set -euo pipefail
+ echo "$(go env GOPATH)/bin" >> $GITHUB_PATH
+ export PATH="$PATH:$(go env GOPATH)/bin"
+ command -v crane >/dev/null || go install github.com/google/go-containerregistry/cmd/crane@v0.22.1
+ echo "${{ secrets.GITHUB_TOKEN }}" \
+ | crane auth login ghcr.io -u "${{ github.actor }}" --password-stdin
+
+ - name: Fetch prebuilt torch xcframework
+ env:
+ CW_DOCKER_REGISTRY: ghcr.io/cake-tech/cake_wallet
+ run: |
+ set -euo pipefail
+ IMAGE="$(./scripts/ios/docker/build.sh --image torch)"
+
+ TMP="$(mktemp -d)"
+ crane export "$IMAGE" - | tar -x -C "$TMP"
+ rsync -a "$TMP/w/" .
+ rm -rf "$TMP"
+
+ test -d scripts/torch_dart/ios/LibTorch.xcframework/ios-arm64 \
+ || { echo "restored xcframework has no ios-arm64 slice" >&2; exit 1; }
+
+ - name: Fetch prebuilt monero_c and generate xcframeworks
+ env:
+ CW_DOCKER_REGISTRY: ghcr.io/cake-tech/cake_wallet
+ run: |
+ set -euo pipefail
+ IMAGE="$(./scripts/ios/docker/build.sh --image monero)"
+
+ TMP="$(mktemp -d)"
+ crane export "$IMAGE" - | tar -x -C "$TMP"
+ rsync -a "$TMP/w/" .
+ rm -rf "$TMP"
+
+ MONEROC_TAG="$(ls scripts/monero_c/release)"
+ pushd scripts/ios
+ MONEROC_TAG="$MONEROC_TAG" ./gen_framework.sh
+ popd
+
+ test -f ios/MoneroWallet.xcframework/ios-arm64/MoneroWallet.framework/MoneroWallet \
+ || { echo "MoneroWallet.xcframework has no ios-arm64 slice" >&2; exit 1; }
+
+ # wownero and zano aren't built, their wallets fail to open instead of the build failing
+ sed -i '' \
+ -e '/WowneroWallet\.xcframework/d' \
+ -e '/ZanoWallet\.xcframework/d' \
+ ios/Runner.xcodeproj/project.pbxproj
+
+ - name: Prepare reown_flutter
+ run: ./scripts/prepare_reown.sh
+
+
+ - name: Execute Build and Setup Commands
+ id: config
+ run: |
+ pushd scripts/ios
+ source ./app_env.sh cakewallet
+ export APP_IOS_BUNDLE_ID="${{ vars.IOS_BUNDLE_ID }}"
+ export APP_IOS_NAME="$APP_DISPLAY_NAME"
+ export APP_IOS_BUILD_NUMBER="$BUILD_NUMBER"
+ if [[ -n "$APP_VERSION" ]]; then
+ export APP_IOS_VERSION="$APP_VERSION"
+ fi
+ ./app_config.sh
+ popd
+
+ for key in CFBundleDisplayName CFBundleIdentifier CFBundleShortVersionString CFBundleVersion; do
+ echo "$key = $(/usr/libexec/PlistBuddy -c "Print :$key" ios/Runner/Info.plist)"
+ done
+
+ {
+ echo "app_version=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' ios/Runner/Info.plist)"
+ echo "build_number=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleVersion' ios/Runner/Info.plist)"
+ } >> $GITHUB_OUTPUT
+
+ - name: Install Flutter dependencies
+ run: flutter pub get
+
+ - name: Build mwebd
+ run: |
+ pushd cw_mweb
+ flutter pub get
+ popd
+ pushd scripts/ios
+ ./build_mwebd.sh
+ popd
+
+ - name: Build decred
+ run: |
+ pushd cw_decred
+ flutter pub get
+ popd
+ pushd scripts/ios
+ ./build_decred.sh
+ popd
+
+ - name: Build generated code
+ run: ./model_generator.sh
+
+ - name: Generate localization
+ run: dart run tool/generate_localization.dart
+
+ - name: Compile graphics
+ run: ./compile_graphics.sh
+
+ - name: Replace email address
+ run: |
+ PATTERN1="support@cakewallet.com"
+ PATTERN1REP="dev.testflight.cakewallet@mrcyjanek.net"
+ for file in lib/utils/exception_handler.dart lib/view_model/support_view_model.dart; do
+ sed -i.bak -e "s|$PATTERN1|$PATTERN1REP|g" "$file"
+ rm -f "$file.bak"
+ done
+
+ - name: Build unsigned archive
+ run: |
+ flutter build ipa \
+ --release \
+ --no-codesign \
+ --dart-define=CI_COMMIT="$(git rev-parse HEAD)" \
+ --dart-define=CI_BRANCH="$BRANCH_NAME" \
+ --dart-define=hasDevOptions=true
+
+ - name: Pack archive
+ run: tar -cf "$RUNNER_TEMP/Runner.xcarchive.tar" -C build/ios/archive Runner.xcarchive
+
+ - name: Upload unsigned archive
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
+ with:
+ name: ios-xcarchive
+ path: ${{ runner.temp }}/Runner.xcarchive.tar
+ retention-days: 1
+ if-no-files-found: error
+
+ testflight:
+ needs: build
+ runs-on: macos-26
+ environment: testflight
+
+ steps:
+ - name: Download unsigned archive
+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
+ with:
+ name: ios-xcarchive
+
+ - name: Unpack archive
+ run: |
+ tar -xf Runner.xcarchive.tar
+ rm Runner.xcarchive.tar
+
+ - name: Install signing certificate and provisioning profile
+ env:
+ DIST_CERT_P12: ${{ secrets.IOS_DIST_CERT_P12 }}
+ DIST_CERT_PASSWORD: ${{ secrets.IOS_DIST_CERT_PASSWORD }}
+ PROVISIONING_PROFILE: ${{ secrets.IOS_PROVISIONING_PROFILE }}
+ run: |
+ set -euo pipefail
+
+ KEYCHAIN_PATH="$RUNNER_TEMP/cw-ios.keychain-db"
+ KEYCHAIN_PASSWORD="$(uuidgen)"
+ echo "KEYCHAIN_PATH=$KEYCHAIN_PATH" >> $GITHUB_ENV
+
+ echo -n "$DIST_CERT_P12" | base64 --decode > "$RUNNER_TEMP/dist.p12"
+ echo -n "$PROVISIONING_PROFILE" | base64 --decode > "$RUNNER_TEMP/profile.mobileprovision"
+
+ security create-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"
+ security set-keychain-settings -lut 21600 "$KEYCHAIN_PATH"
+ security unlock-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"
+
+ security import "$RUNNER_TEMP/dist.p12" \
+ -P "$DIST_CERT_PASSWORD" \
+ -x -T /usr/bin/codesign -t cert -f pkcs12 -k "$KEYCHAIN_PATH"
+
+ security set-key-partition-list \
+ -S apple-tool:,apple:,codesign: \
+ -s -k "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH" >/dev/null
+
+ security list-keychain -d user -s "$KEYCHAIN_PATH" login.keychain-db
+
+ PROFILE_NAME="$(security cms -D -i "$RUNNER_TEMP/profile.mobileprovision" | plutil -extract Name raw -)"
+ PROFILE_UUID="$(security cms -D -i "$RUNNER_TEMP/profile.mobileprovision" | plutil -extract UUID raw -)"
+ echo "PROFILE_NAME=$PROFILE_NAME" >> $GITHUB_ENV
+
+ mkdir -p "$HOME/Library/MobileDevice/Provisioning Profiles"
+ cp "$RUNNER_TEMP/profile.mobileprovision" \
+ "$HOME/Library/MobileDevice/Provisioning Profiles/$PROFILE_UUID.mobileprovision"
+
+ rm -f "$RUNNER_TEMP/dist.p12"
+ security find-identity -v -p codesigning "$KEYCHAIN_PATH"
+
+ - name: Write ExportOptions.plist
+ run: |
+ cat > ExportOptions.plist <<PLIST
+ <?xml version="1.0" encoding="UTF-8"?>
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+ <plist version="1.0">
+ <dict>
+ <key>method</key>
+ <string>app-store</string>
+ <key>teamID</key>
+ <string>${{ vars.APPLE_TEAM_ID }}</string>
+ <key>signingStyle</key>
+ <string>manual</string>
+ <key>signingCertificate</key>
+ <string>Apple Distribution</string>
+ <key>provisioningProfiles</key>
+ <dict>
+ <key>${{ vars.IOS_BUNDLE_ID }}</key>
+ <string>$PROFILE_NAME</string>
+ </dict>
+ <key>uploadSymbols</key>
+ <true/>
+ <key>stripSwiftSymbols</key>
+ <true/>
+ </dict>
+ </plist>
+ PLIST
+ cat ExportOptions.plist
+
+ - name: Sign IPA
+ run: |
+ xcodebuild -exportArchive \
+ -archivePath Runner.xcarchive \
+ -exportOptionsPlist ExportOptions.plist \
+ -exportPath ipa
+
+ - name: Locate IPA
+ run: |
+ IPA_PATH="$(ls ipa/*.ipa 2>/dev/null | head -1 || true)"
+ echo "IPA_PATH=$IPA_PATH" >> $GITHUB_ENV
+ ls -lh "$IPA_PATH"
+
+ - name: Upload to TestFlight
+ env:
+ ASC_KEY_ID: ${{ secrets.ASC_KEY_ID }}
+ ASC_ISSUER_ID: ${{ secrets.ASC_ISSUER_ID }}
+ ASC_KEY_P8: ${{ secrets.ASC_KEY_P8 }}
+ run: |
+ set -euo pipefail
+
+ mkdir -p "$HOME/.appstoreconnect/private_keys"
+ echo -n "$ASC_KEY_P8" | base64 --decode \
+ > "$HOME/.appstoreconnect/private_keys/AuthKey_${ASC_KEY_ID}.p8"
+
+ xcrun altool --upload-app \
+ --type ios \
+ --file "$IPA_PATH" \
+ --apiKey "$ASC_KEY_ID" \
+ --apiIssuer "$ASC_ISSUER_ID" \
+ --api-key-subject user
+
+ rm -f "$HOME/.appstoreconnect/private_keys/AuthKey_${ASC_KEY_ID}.p8"
+
+ - name: Upload IPA artifact to GitHub
+ if: always()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
+ with:
+ name: ios-ipa
+ path: ipa/*.ipa
+
+ - name: Clean up keychain and profiles
+ if: always()
+ run: |
+ security delete-keychain "$KEYCHAIN_PATH" || true
+ rm -rf "$HOME/Library/MobileDevice/Provisioning Profiles" || true
+ rm -rf "$HOME/.appstoreconnect/private_keys" || true
+
+ # posts the changelog to testflight
+ # this is a separate runner as the script waits for ocasionally 20+ minutes for the build to appear
+ changelog:
+ needs: [build, testflight]
+ runs-on: ubuntu-24.04
+ environment: testflight
+
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+
+ - uses: dart-lang/setup-dart@6afc89df92d6eb3834022f73cd65adc8cdfcb92d # v1.8.1
+
+ - name: Set TestFlight changelog
+ env:
+ ASC_KEY_ID: ${{ secrets.ASC_KEY_ID }}
+ ASC_KEY_P8: ${{ secrets.ASC_KEY_P8 }}
+ IOS_BUNDLE_ID: ${{ vars.IOS_BUNDLE_ID }}
+ BUILD_NUMBER: ${{ needs.build.outputs.build_number }}
+ APP_VERSION: ${{ needs.build.outputs.app_version }}
+ BRANCH_NAME: ${{ github.head_ref || github.ref_name }}
+ run: |
+ set -euo pipefail
+ export ASC_KEY_PATH="$RUNNER_TEMP/AuthKey_${ASC_KEY_ID}.p8"
+ trap 'rm -f "$ASC_KEY_PATH"' EXIT
+ echo -n "$ASC_KEY_P8" | base64 --decode > "$ASC_KEY_PATH"
+
+ {
+ printf '%s @ %s (PR #%s, build %s)\n\n' \
+ "$BRANCH_NAME" \
+ "$(git rev-parse --short=8 HEAD)" \
+ "${{ github.event.pull_request.number }}" \
+ "$BUILD_NUMBER"
+ git log -1 --pretty=%B
+ } | dart run tool/set_testflight_changelog.dart
### .github/workflows/pr_test_build_linux.yml
@@ -10,45 +10,222 @@ defaults:
run:
shell: bash
+env:
+ CW_DOCKER_REGISTRY: ghcr.io/cake-tech/cake_wallet
+ CW_DOCKER_USE_CLOUD: "true"
+ GITHUB_TOKEN: ${{ github.token }}
+
+concurrency:
+ group: linux-${{ github.event.pull_request.number }}
+ cancel-in-progress: true
+
jobs:
- PR_test_build:
+ guard:
# Fork PRs don't have access to repository secrets, so the generated
# lib/.secrets.g.dart would be empty and the build fails to compile.
# Skip for forks, mirroring the Android workflow's internal-build guard.
if: github.event.pull_request.head.repo.fork == false
- runs-on: [Linux, amd64, forlinux]
+ runs-on: puzl-ubuntu-latest
+ steps:
+ - run: echo "internal PR"
+
+ base:
+ needs: guard
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
+ steps:
+ - uses: actions/checkout@v4
+ if: ${{ env.ACT != 'true' }}
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ repository: ${{ github.event.pull_request.head.repo.full_name }}
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Build base
+ run: ./scripts/linux/docker/build.sh --only base
+
+ mwebd:
+ needs: base
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
+ steps:
+ - uses: actions/checkout@v4
+ if: ${{ env.ACT != 'true' }}
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ repository: ${{ github.event.pull_request.head.repo.full_name }}
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Build mwebd
+ run: ./scripts/linux/docker/build.sh --only mwebd
+
+ reown:
+ needs: base
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
+ steps:
+ - uses: actions/checkout@v4
+ if: ${{ env.ACT != 'true' }}
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ repository: ${{ github.event.pull_request.head.repo.full_name }}
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Build reown
+ run: ./scripts/linux/docker/build.sh --only reown
+
+ zcash:
+ needs: base
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
+ steps:
+ - uses: actions/checkout@v4
+ if: ${{ env.ACT != 'true' }}
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ repository: ${{ github.event.pull_request.head.repo.full_name }}
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Build zcash
+ run: ./scripts/linux/docker/build.sh --only zcash
+
+ torch:
+ needs: base
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
+ steps:
+ - uses: actions/checkout@v4
+ if: ${{ env.ACT != 'true' }}
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ repository: ${{ github.event.pull_request.head.repo.full_name }}
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Build torch
+ run: ./scripts/linux/docker/build.sh --only torch
+
+ monero:
+ needs: base
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
+ strategy:
+ matrix:
+ coin: [monero, wownero]
+ steps:
+ - uses: actions/checkout@v4
+ if: ${{ env.ACT != 'true' }}
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ repository: ${{ github.event.pull_request.head.repo.full_name }}
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Build monero
+ run: ./scripts/linux/docker/build.sh --only monero --coin ${{ matrix.coin }} --target x86_64-linux-gnu
+
+ monero_merge:
+ needs: monero
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
+ steps:
+ - uses: actions/checkout@v4
+ if: ${{ env.ACT != 'true' }}
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ repository: ${{ github.event.pull_request.head.repo.full_name }}
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Merge monero
+ run: ./scripts/linux/docker/build.sh --only monero --merge
+
+ final:
+ needs: [mwebd, reown, zcash, torch, monero_merge]
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
+ steps:
+ - uses: actions/checkout@v4
+ if: ${{ env.ACT != 'true' }}
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ repository: ${{ github.event.pull_request.head.repo.full_name }}
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Build final
+ run: ./scripts/linux/docker/build.sh --only final
+
+ app:
+ needs: final
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
container:
image: ghcr.io/cake-tech/cake_wallet:debian13-flutter3.41.9-ndkr28-go1.24.1-ruststablenightly
env:
STORE_PASS: test@cake_wallet
KEY_PASS: test@cake_wallet
- MONEROC_CACHE_DIR_ROOT: /opt/generic_cache
BRANCH_NAME: ${{ github.head_ref || github.ref_name }}
DESKTOP_FORCE_MOBILE: Y
volumes:
- - /opt/cw_cache_linux/root/.cache:/root/.cache
- - /opt/cw_cache_linux/root/.ccache:/root/.ccache
- - /opt/cw_cache_linux/root/.pub-cache/:/root/.pub-cache
- - /opt/cw_cache_linux/root/go/pkg:/root/go/pkg
- - /opt/cw_cache_linux/opt/generic_cache:/opt/generic_cache
- /var/run/docker.sock:/var/run/docker.sock
-
steps:
- name: Fix github actions messing up $HOME...
run: "echo HOME=/root | sudo tee -a $GITHUB_ENV"
- - name: Log in to GitHub Container Registry
- uses: docker/login-action@v3
- with:
- registry: ghcr.io
- username: ${{ github.actor }}
- password: ${{ secrets.GITHUB_TOKEN }}
-
- uses: actions/checkout@v4
+ if: ${{ env.ACT != 'true' }}
with:
ref: ${{ github.event.pull_request.head.sha }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
@@ -61,14 +238,8 @@ jobs:
git config --global --add safe.directory '*'
git config --global user.email "ci@cakewallet.com"
git config --global user.name "CakeWallet CI"
-
- - name: Get the full commit message
- run: |
- FULL_MESSAGE="$(git log -1 --pretty=%B)"
- echo "message<<EOF" >> $GITHUB_ENV
- echo "$FULL_MESSAGE" >> $GITHUB_ENV
- echo "EOF" >> $GITHUB_ENV
-
+ git config --global --unset-all credential.helper || true
+ git config --global url."https://x-access-token:${{ github.token }}@github.com/".insteadOf "https://github.com/"
- name: Add secrets
run: |
touch cw_bitcoin/lib/.secrets.g.dart
@@ -81,6 +252,7 @@ jobs:
echo "const polygonScanApiKey = '${{ secrets.POLYGON_SCAN_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
echo "const etherScanApiKey = '${{ secrets.ETHER_SCAN_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
echo "const moralisApiKey = '${{ secrets.MORALIS_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
+ echo "const alchemyApiKey = '${{ secrets.ALCHEMY_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
echo "const nowNodesApiKey = '${{ secrets.EVM_NOWNODES_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
echo "const blinkApiKey = '${{ secrets.BLINK_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
echo "const ankrApiKey = '${{ secrets.ANKR_API_KEY }}';" >> cw_solana/lib/.secrets.g.dart
@@ -97,12 +269,8 @@ jobs:
echo "${{ secrets.MAIN_SECRETS_FILE }}" | base64 --decode > lib/.secrets.g.dart
- - name: Build dependencies utilizing ghcr cache
- run: |
- env \
- CW_DOCKER_REGISTRY=ghcr.io/cake-tech/cake_wallet \
- CW_DOCKER_USE_CLOUD=true \
- ./scripts/linux/docker/build.sh
+ - name: Extract native dependencies
+ run: ./scripts/linux/docker/build.sh --extract
- name: Execute Build and Setup Commands
run: |
@@ -143,87 +311,95 @@ jobs:
path: ${{ github.workspace }}/build/linux/x64/release/cakewallet_linux.zip
name: cakewallet_linux
- - name: Prepare virtual desktop
- if: ${{ contains(env.message, 'run tests') }}
- run: |
- nohup Xvfb :99 -screen 0 720x1280x16 &
- echo DISPLAY=:99 | sudo tee -a $GITHUB_ENV
- dbus-daemon --system --fork
- nohup NetworkManager &
- nohup ffmpeg -framerate 60 -video_size 720x1280 -f x11grab -i :99 -c:v libx264 -c:a aac /opt/screen_grab.mkv &
-
- # Note for people adding tests:
- # - Tests are ran on Linux, with some things being mocked out.
- # - Screen recording is being provided for the entire length of the test, you can download it in github articats.
- # - Screen recordeding is encrypted, look at step "Stop screen recording, encrypt and upload", and add your key if you want
- # Reason for encryption is the fact that we restore the wallet from seed, and we don't want to leak that, while there
- # isn't much in those wallets anyway, we still wouldn't like to leak it to anyone who is able to access github.
-
- - name: Test [confirm_seeds_flow_test]
- if: ${{ contains(env.message, 'run tests') }}
- timeout-minutes: 20
- run: |
- xmessage -timeout 30 "confirm_seeds_flow_test" &
- rm -rf ~/.local/share/com.example.cake_wallet/ ~/Documents/cake_wallet/ ~/cake_wallet
- exec timeout --signal=SIGKILL 900 flutter drive --driver=test_driver/integration_test.dart --target=integration_test/test_suites/confirm_seeds_flow_test.dart
-
- - name: Test [create_wallet_flow_test]
- if: ${{ contains(env.message, 'run tests') }}
- timeout-minutes: 20
- run: |
- xmessage -timeout 30 "create_wallet_flow_test" &
- rm -rf ~/.local/share/com.example.cake_wallet/ ~/Documents/cake_wallet/ ~/cake_wallet
- exec timeout --signal=SIGKILL 900 flutter drive --driver=test_driver/integration_test.dart --target=integration_test/test_suites/create_wallet_flow_test.dart
-
- # - name: Test [exchange_flow_test]
- # if: ${{ contains(env.message, 'run tests') }}
- # timeout-minutes: 20
- # run: |
- # xmessage -timeout 30 "exchange_flow_test" &
- # rm -rf ~/.local/share/com.example.cake_wallet/ ~/Documents/cake_wallet/ ~/cake_wallet
- # exec timeout --signal=SIGKILL 900 flutter drive --driver=test_driver/integration_test.dart --target=integration_test/test_suites/exchange_flow_test.dart
-
- - name: Test [restore_wallet_through_seeds_flow_test]
- if: ${{ contains(env.message, 'run tests') }}
- timeout-minutes: 20
- run: |
- xmessage -timeout 30 "restore_wallet_through_seeds_flow_test" &
- rm -rf ~/.local/share/com.example.cake_wallet/ ~/Documents/cake_wallet/ ~/cake_wallet
- exec timeout --signal=SIGKILL 900 flutter drive --driver=test_driver/integration_test.dart --target=integration_test/test_suites/restore_wallet_through_seeds_flow_test.dart
-
- - name: Test [cw_core]
- timeout-minutes: 15
- run: cd cw_core && flutter test
-
- - name: Test [cw_monero]
- timeout-minutes: 15
- run: cd cw_monero && flutter test
-
- - name: Stop screen recording, encrypt and upload
- if: always()
- run: |
- if [[ ! -f "/opt/screen_grab.mkv" ]];
- then
- exit 0;
- fi
- killall ffmpeg
- sleep 5
- killall -9 ffmpeg || true
- sleep 5
- # Feel free to add your own public key if you wish
- gpg --keyserver hkps://keyserver.ubuntu.com --recv-keys 6B3199AD9B3D23B8 # konstantin@cakewallet.com
- gpg --keyserver hkps://keyserver.ubuntu.com --recv-keys 35C8DBAFB8D9ACAC # cyjan@mrcyjanek.net
- gpg --trust-model always --encrypt --output /opt/screen_grab.mkv.gpg \
- --recipient 6B3199AD9B3D23B8 \
- --recipient 35C8DBAFB8D9ACAC \
- /opt/screen_grab.mkv
- rm /opt/screen_grab.mkv
- mv /opt/screen_grab.mkv.gpg ./screen_grab.mkv.gpg
+ unit_tests:
+ needs: final
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 90
+ container:
+ image: ghcr.io/cake-tech/cake_wallet:debian13-flutter3.41.9-ndkr28-go1.24.1-ruststablenightly
+ volumes:
+ - /var/run/docker.sock:/var/run/docker.sock
+ steps:
+ - name: Fix github actions messing up $HOME...
+ run: "echo HOME=/root | sudo tee -a $GITHUB_ENV"
- - name: Upload Artifact to github
- if: always()
- continue-on-error: true
- uses: actions/upload-artifact@v4
+ - uses: actions/checkout@v4
+ if: ${{ env.ACT != 'true' }}
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ repository: ${{ github.event.pull_request.head.repo.full_name }}
+
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
with:
- path: ${{ github.workspace }}/screen_grab.mkv.gpg
- name: tests_screen_grab
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: configure git
+ run: |
+ git config --global --add safe.directory '*'
+ git config --global user.email "ci@cakewallet.com"
+ git config --global user.name "CakeWallet CI"
+ git config --global --unset-all credential.helper || true
+ git config --global url."https://x-access-token:${{ github.token }}@github.com/".insteadOf "https://github.com/"
+
+ - name: Extract native dependencies
+ run: ./scripts/linux/docker/build.sh --extract
+
+ - name: Execute Build and Setup Commands
+ run: |
+ pushd scripts/linux
+ source ./app_env.sh cakewallet
+ ./app_config.sh
+ popd
+
+ - name: Install Flutter dependencies
+ run: |
+ flutter pub get
+
+ # The tests must not depend on real API keys, so the placeholder generator is used
+ # instead of the repository secrets.
+ - name: Generate placeholder secrets
+ run: |
+ dart run tool/generate_new_secrets.dart
+
+ - name: Build generated code
+ run: |
+ ./model_generator.sh
+
+ - name: Generate localization
+ run: |
+ dart run tool/generate_localization.dart
+
+ - name: Compile graphics
+ run: |
+ ./compile_graphics.sh
+
+ # Every package with a test directory is run, and a failure in one package does not
+ # stop the others, so the summary names every package that is red.
+ - name: Run unit tests
+ run: |
+ failed=()
+ printf "| Package | Result |\n|---|---|\n" >> "$GITHUB_STEP_SUMMARY"
+ for pkg in . cw_*; do
+ if [[ ! -d "$pkg/test" ]]; then
+ continue
+ fi
+ name=$(basename "$(cd "$pkg" && pwd)")
+ echo "=== flutter test: $name ==="
+ if (cd "$pkg" && flutter test); then
+ echo "| $name | passed |" >> "$GITHUB_STEP_SUMMARY"
+ else
+ failed+=("$name")
+ echo "| $name | FAILED |" >> "$GITHUB_STEP_SUMMARY"
+ fi
+ done
+ if (( ${#failed[@]} > 0 )); then
+ echo "::error::Unit tests failed in: ${failed[*]}"
+ exit 1
+ fi
+ echo "All unit tests passed"
### .github/workflows/reusable-build.yml
@@ -17,39 +17,257 @@ on:
defaults:
run:
shell: bash
+
+env:
+ CW_DOCKER_REGISTRY: ghcr.io/cake-tech/cake_wallet
+ CW_DOCKER_USE_CLOUD: "true"
+ GITHUB_TOKEN: ${{ github.token }}
+
jobs:
- PR_test_build:
- runs-on: [Linux, amd64, android]
+ base:
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
+ steps:
+ - uses: actions/checkout@v4
+ if: ${{ env.ACT != 'true' }}
+ with:
+ ref: ${{ inputs.ref }}
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Build base
+ run: ./scripts/android/docker/build.sh --only base
+
+ mwebd:
+ needs: base
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
+ steps:
+ - uses: actions/checkout@v4
+ if: ${{ env.ACT != 'true' }}
+ with:
+ ref: ${{ inputs.ref }}
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Build mwebd
+ run: ./scripts/android/docker/build.sh --only mwebd
+
+ reown:
+ needs: base
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
+ steps:
+ - uses: actions/checkout@v4
+ if: ${{ env.ACT != 'true' }}
+ with:
+ ref: ${{ inputs.ref }}
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Build reown
+ run: ./scripts/android/docker/build.sh --only reown
+
+ zcash:
+ needs: base
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
+ steps:
+ - uses: actions/checkout@v4
+ if: ${{ env.ACT != 'true' }}
+ with:
+ ref: ${{ inputs.ref }}
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Build zcash
+ run: ./scripts/android/docker/build.sh --only zcash
+
+ torch:
+ needs: base
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
+ strategy:
+ matrix:
+ target:
+ - aarch64-linux-android
+ - armv7a-linux-androideabi
+ - x86_64-linux-android
+ steps:
+ - uses: actions/checkout@v4
+ if: ${{ env.ACT != 'true' }}
+ with:
+ ref: ${{ inputs.ref }}
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Build torch
+ run: ./scripts/android/docker/build.sh --only torch --target ${{ matrix.target }}
+
+ torch_merge:
+ needs: torch
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
+ steps:
+ - uses: actions/checkout@v4
+ if: ${{ env.ACT != 'true' }}
+ with:
+ ref: ${{ inputs.ref }}
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Merge torch
+ run: ./scripts/android/docker/build.sh --only torch --merge
+
+ monero:
+ needs: base
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
+ strategy:
+ matrix:
+ coin: [monero, wownero, zano]
+ target:
+ - aarch64-linux-android
+ - armv7a-linux-androideabi
+ - x86_64-linux-android
+ steps:
+ - uses: actions/checkout@v4
+ if: ${{ env.ACT != 'true' }}
+ with:
+ ref: ${{ inputs.ref }}
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Build monero
+ run: ./scripts/android/docker/build.sh --only monero --coin ${{ matrix.coin }} --target ${{ matrix.target }}
+
+ monero_merge:
+ needs: monero
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
+ steps:
+ - uses: actions/checkout@v4
+ if: ${{ env.ACT != 'true' }}
+ with:
+ ref: ${{ inputs.ref }}
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Merge monero
+ run: ./scripts/android/docker/build.sh --only monero --merge
+
+ decred:
+ needs: [base, torch_merge]
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
+ steps:
+ - uses: actions/checkout@v4
+ if: ${{ env.ACT != 'true' }}
+ with:
+ ref: ${{ inputs.ref }}
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Build decred
+ run: ./scripts/android/docker/build.sh --only decred
+
+ final:
+ needs: [mwebd, reown, zcash, torch_merge, monero_merge, decred]
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
+ steps:
+ - uses: actions/checkout@v4
+ if: ${{ env.ACT != 'true' }}
+ with:
+ ref: ${{ inputs.ref }}
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Build final
+ run: ./scripts/android/docker/build.sh --only final
+
+ integration-test:
+ needs: final
+ uses: ./.github/workflows/reusable-integration-test.yml
+ with:
+ ref: ${{ inputs.ref }}
+ suite_dir: integration_test/suites
+ test_tier: tier0
+ slack_notify: true
+ extract_only: true
+ secrets: inherit
+
+ app:
+ needs: final
+ runs-on: puzl-ubuntu-latest
+ timeout-minutes: 360
container:
image: ghcr.io/cake-tech/cake_wallet:debian13-flutter3.41.9-ndkr28-go1.24.1-ruststablenightly
env:
STORE_PASS: test@cake_wallet
KEY_PASS: test@cake_wallet
- MONEROC_CACHE_DIR_ROOT: /opt/generic_cache
BRANCH_NAME: ${{ github.head_ref || github.ref_name }}
- ANDROID_AVD_HOME: /root/.android/avd
volumes:
- - /opt/cw_cache_android/root/.cache:/root/.cache
- - /opt/cw_cache_android/root/.android/avd/:/root/.android/avd
- - /opt/cw_cache_android/root/.ccache:/root/.ccache
- - /opt/cw_cache_android/root/.pub-cache/:/root/.pub-cache
- - /opt/cw_cache_android/root/.gradle/:/root/.gradle
- - /opt/cw_cache_android/root/.android/:/root/.android
- - /opt/cw_cache_android/root/go/pkg:/root/go/pkg
- - /opt/cw_cache_android/opt/generic_cache:/opt/generic_cache
- - /dev/kvm:/dev/kvm
- /var/run/docker.sock:/var/run/docker.sock
- strategy:
- matrix:
- api-level: [29]
-
steps:
- name: Fix github actions messing up $HOME...
run: "echo HOME=/root | sudo tee -a $GITHUB_ENV"
- uses: actions/checkout@v4
+ if: ${{ env.ACT != 'true' }}
with:
ref: ${{ inputs.ref }}
-
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
@@ -78,6 +296,7 @@ jobs:
echo "const moralisApiKey = '${{ secrets.MORALIS_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
echo "const nowNodesApiKey = '${{ secrets.EVM_NOWNODES_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
echo "const blinkApiKey = '${{ secrets.BLINK_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
+ echo "const alchemyApiKey = '${{ secrets.ALCHEMY_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
echo "const ankrApiKey = '${{ secrets.ANKR_API_KEY }}';" >> cw_solana/lib/.secrets.g.dart
echo "const chainStackApiKey = '${{ secrets.CHAIN_STACK_API_KEY }}';" >> cw_solana/lib/.secrets.g.dart
echo "const moralisApiKey = '${{ secrets.MORALIS_API_KEY }}';" >> cw_solana/lib/.secrets.g.dart
@@ -94,22 +313,15 @@ jobs:
- name: Generate KeyStore
run: |
- pushd /opt/generic_cache
- if [[ ! -f key.jks ]];
- then
- keytool -genkey -v -keystore key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias testKey -noprompt -dname "CN=CakeWallet, OU=CakeWallet, O=CakeWallet, L=Florida, S=America, C=USA" -storepass $STORE_PASS -keypass $KEY_PASS
- else
- echo "$PWD/key.jks exist, not generating"
- fi
- popd
- cp /opt/generic_cache/key.jks android/app
+ ./scripts/android/generate_dev_keystore.sh android/app/key.jks
+
+ - name: Extract native dependencies
+ run: ./scripts/android/docker/build.sh --extract
- - name: Build dependencies utilizing ghcr cache
+ - name: Authenticate git for GitHub clones
run: |
- env \
- CW_DOCKER_REGISTRY=ghcr.io/cake-tech/cake_wallet \
- CW_DOCKER_USE_CLOUD=true \
- ./scripts/android/docker/build.sh
+ git config --global --unset-all credential.helper || true
+ git config --global url."https://x-access-token:${{ github.token }}@github.com/".insteadOf "https://github.com/"
- name: Execute Build and Setup Commands
run: |
@@ -127,7 +339,6 @@ jobs:
run: |
./model_generator.sh
-
- name: Generate key properties
run: |
dart run tool/generate_android_key_properties.dart keyAlias=testKey storeFile=key.jks storePassword=$STORE_PASS keyPassword=$KEY_PASS
@@ -168,49 +379,77 @@ jobs:
pushd $ANDROID_SDK_ROOT/ndk
ln -s 28.2.13676358 25.1.8937393
popd
- flutter build apk --dart-define=hasDevOptions=true --release --split-per-abi
+ flutter build apk --dart-define=hasDevOptions=true \
+ --dart-define=CI_COMMIT="$(git rev-parse HEAD)" \
+ --dart-define=CI_BRANCH="$BRANCH_NAME" \
+ --release --split-per-abi
- - name: Rename apk file
+ - name: Name apks after the branch
+ id: apks
run: |
- sanitized_branch_name=$(grep '^id=' android/app.properties | cut -d'=' -f2 | sed 's/com\.cakewallet\.test_//')
- cd build/app/outputs/flutter-apk
- mkdir test-apk
- cp app-arm64-v8a-release.apk test-apk/${sanitized_branch_name}.apk
- cp app-x86_64-release.apk test-apk/${sanitized_branch_name}_x86.apk
-
- - name: Find APK file
- id: find_apk
- run: |
- set -x
- sanitized_branch_name=$(grep '^id=' android/app.properties | cut -d'=' -f2 | sed 's/com\.cakewallet\.test_//')
- apk_file=$(ls build/app/outputs/flutter-apk/test-apk/${sanitized_branch_name}.apk || exit 1)
- echo "APK_FILE=$apk_file" >> $GITHUB_ENV
- - name: Write BRANCH_NAME to env
- run: echo "BRANCH_NAME=${BRANCH_NAME}" >> $GITHUB_ENV
-
- - name: Upload to slack step
- uses: vaporif/slack-file-upload-action@v1
- with:
- token: ${{ secrets.SLACK_APP_TOKEN }}
- initial_comment: ${{ env.message }}
- files: >
- [
- {"file": "${{ env.APK_FILE }}", "filename": "${{ env.BRANCH_NAME }}.apk"}
- ]
- channel_id: ${{ secrets.SLACK_APK_CHANNEL }}
-
- - name: cleanup
- run: rm -rf build/app/outputs/flutter-apk/test-apk/
-
- - name: Upload Artifact to github
+ # Artifact names reject / \ : * ? " < > |
+ safe_branch=$(printf '%s' "$BRANCH_NAME" | sed 's#[/\\:*?"<>|]#-#g' | tr -d '\r\n')
+ dir=build/app/outputs/flutter-apk/named
+ mkdir -p "$dir"
+ cp build/app/outputs/flutter-apk/app-arm64-v8a-release.apk "$dir/${safe_branch}.apk"
+ cp build/app/outputs/flutter-apk/app-armeabi-v7a-release.apk "$dir/${safe_branch}_v7a.apk"
+ cp build/app/outputs/flutter-apk/app-x86_64-release.apk "$dir/${safe_branch}_x86.apk"
+ echo "branch=$safe_branch" >> "$GITHUB_OUTPUT"
+
+ - name: Upload arm64 apk
+ uses: actions/upload-artifact@v4
+ with:
+ name: ${{ steps.apks.outputs.branch }}.apk
+ path: build/app/outputs/flutter-apk/named/${{ steps.apks.outputs.branch }}.apk
+ if-no-files-found: error
+
+ - name: Upload x86_64 apk
uses: actions/upload-artifact@v4
with:
- path: ${{ github.workspace }}/build/app/outputs/flutter-apk
- name: "android apk"
+ name: ${{ steps.apks.outputs.branch }}_x86.apk
+ path: build/app/outputs/flutter-apk/named/${{ steps.apks.outputs.branch }}_x86.apk
+ if-no-files-found: error
+
+ - name: Upload armeabi-v7a apk
+ uses: actions/upload-artifact@v4
+ with:
+ name: ${{ steps.apks.outputs.branch }}_v7a.apk
+ path: build/app/outputs/flutter-apk/named/${{ steps.apks.outputs.branch }}_v7a.apk
+ if-no-files-found: error
- name: 16KB align
run: |
cd build/app/outputs/flutter-apk
for i in arm64-v8a x86_64; do
../../../../scripts/android/check_16kb_align.sh app-$i-release.apk
done
+
+ - name: Post the build to slack
+ if: ${{ !cancelled() }}
+ env:
+ SLACK_TOKEN: ${{ secrets.SLACK_APP_TOKEN }}
+ SLACK_CHANNEL: ${{ secrets.SLACK_APK_CHANNEL }}
+ RUN_URL: https://nightly.link/${{ github.repository }}/actions/runs/${{ github.run_id }}
+ run: |
+ if [[ -z "$SLACK_TOKEN" || -z "$SLACK_CHANNEL" ]]; then
+ echo "::notice::No slack token or channel configured, skipping the report"
+ exit 0
+ fi
+
+ label=$(printf '%s' "$BRANCH_NAME" | tr '\n\r' ' ' | tr -d '<>|')
+ text=$(printf ':cw: <%s|%s>' "$RUN_URL" "$label")
+ if [[ -n "$message" ]]; then
+ text=$(printf '%s\n%s' "$text" "$message")
+ fi
+
+ response=$(curl -sS -X POST https://slack.com/api/chat.postMessage \
+ -H "Authorization: Bearer $SLACK_TOKEN" \
+ -H "Content-type: application/json; charset=utf-8" \
+ --data "$(jq -n --arg channel "$SLACK_CHANNEL" --arg text "$text" \
+ '{channel: $channel, text: $text}')")
+
+ if [[ "$(jq -r '.ok' <<< "$response")" != "true" ]]; then
+ error=$(jq -r '.error // "unknown"' <<< "$response")
+ echo "::warning::Slack rejected the build post: $error"
+ exit 0
+ fi
### .github/workflows/reusable-integration-test.yml
@@ -0,0 +1,590 @@
+name: Reusable Integration Test Logic
+
+permissions:
+ contents: read
+ packages: write
+
+on:
+ workflow_call:
+ inputs:
+ ref:
+ required: true
+ type: string
+ suite_dir:
+ required: false
+ type: string
+ default: "integration_test/suites"
+ test_tier:
+ required: false
+ type: string
+ default: "tier0"
+ extra_dart_defines:
+ required: false
+ type: string
+ default: ""
+ environment:
+ required: false
+ type: string
+ default: ""
+ record_screen:
+ required: false
+ type: boolean
+ default: false
+ write_funds_secrets:
+ required: false
+ type: boolean
+ default: false
+ timeout_minutes:
+ required: false
+ type: number
+ default: 240
+ slack_notify:
+ required: false
+ type: boolean
+ default: false
+ extract_only:
+ required: false
+ type: boolean
+ default: false
+
+defaults:
+ run:
+ shell: bash
+
+jobs:
+ integration-test:
+ runs-on: ubuntu-latest
+ environment: ${{ inputs.environment }}
+ timeout-minutes: ${{ inputs.timeout_minutes }}
+ env:
+ STORE_PASS: test@cake_wallet
+ KEY_PASS: test@cake_wallet
+ BRANCH_NAME: ${{ github.head_ref || github.ref_name }}
+ GITHUB_TOKEN: ${{ github.token }}
+
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ ref: ${{ inputs.ref }}
+ - name: Authenticate git for package clones
+ run: |
+ git config --global --unset-all credential.helper || true
+ git config --global url."https://x-access-token:${{ github.token }}@github.com/".insteadOf "https://github.com/"
+ - name: Free disk space
+ run: |
+ sudo rm -rf /usr/share/dotnet /opt/ghc /usr/local/.ghcup /usr/local/lib/node_modules /opt/hostedtoolcache/CodeQL
+ sudo rm -rf /usr/share/swift /usr/local/share/powershell /usr/share/miniconda /opt/az /usr/local/graalvm
+ sudo docker image prune -af > /dev/null
+ df -h /
+ - name: Enable KVM
+ run: |
+ echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
+ sudo udevadm control --reload-rules
+ sudo udevadm trigger --name-match=kvm
+ sudo chmod 666 /dev/kvm || true
+
+ if [[ ! -c /dev/kvm ]]; then
+ echo "::error::/dev/kvm is not a character device, this runner has no usable KVM"
+ exit 1
+ fi
+
+ - name: Install protobuf compiler
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y protobuf-compiler
+
+ - uses: actions/setup-java@v4
+ with:
+ distribution: temurin
+ java-version: "17"
+
+ - name: Restore flutter sdk
+ id: flutter-cache
+ uses: actions/cache/restore@v4
+ with:
+ path: ~/flutter
+ key: flutter-sdk-3.41.9-${{ runner.os }}
+
+ - name: Install Flutter
+ run: |
+ if [[ ! -d "$HOME/flutter/bin" ]]; then
+ git clone --branch 3.41.9 --depth 1 https://github.com/flutter/flutter.git "$HOME/flutter"
+ fi
+ echo "$HOME/flutter/bin" >> $GITHUB_PATH
+ export PATH="$PATH:$HOME/flutter/bin"
+ flutter --version
+
+ - name: Save flutter sdk
+ if: steps.flutter-cache.outputs.cache-hit != 'true'
+ continue-on-error: true
+ uses: actions/cache/save@v4
+ with:
+ path: ~/flutter
+ key: flutter-sdk-3.41.9-${{ runner.os }}
+
+ - name: Setup gradle
+ uses: gradle/actions/setup-gradle@v3
+ with:
+ cache-read-only: false
+
+ - name: Restore pub packages
+ id: pub-cache
+ uses: actions/cache/restore@v4
+ with:
+ path: ~/.pub-cache
+ key: pub-cache-${{ runner.os }}-${{ hashFiles('pubspec_base.yaml', 'cw_*/pubspec.yaml') }}
+ restore-keys: pub-cache-${{ runner.os }}-
+
+ - name: Docker sock permissions
+ run: sudo chmod 666 /var/run/docker.sock || true
+
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Add secrets
+ run: |
+ touch cw_bitcoin/lib/.secrets.g.dart
+ touch cw_evm/lib/.secrets.g.dart
+ touch cw_solana/lib/.secrets.g.dart
+ touch cw_core/lib/.secrets.g.dart
+ touch cw_nano/lib/.secrets.g.dart
+ touch cw_tron/lib/.secrets.g.dart
+
+ echo "const polygonScanApiKey = '${{ secrets.POLYGON_SCAN_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
+ echo "const etherScanApiKey = '${{ secrets.ETHER_SCAN_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
+ echo "const moralisApiKey = '${{ secrets.MORALIS_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
+ echo "const nowNodesApiKey = '${{ secrets.EVM_NOWNODES_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
+ echo "const alchemyApiKey = '${{ secrets.ALCHEMY_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
+ echo "const blinkApiKey = '${{ secrets.BLINK_API_KEY }}';" >> cw_evm/lib/.secrets.g.dart
+ echo "const ankrApiKey = '${{ secrets.ANKR_API_KEY }}';" >> cw_solana/lib/.secrets.g.dart
+ echo "const chainStackApiKey = '${{ secrets.CHAIN_STACK_API_KEY }}';" >> cw_solana/lib/.secrets.g.dart
+ echo "const moralisApiKey = '${{ secrets.MORALIS_API_KEY }}';" >> cw_solana/lib/.secrets.g.dart
+
+ echo "const nano2ApiKey = '${{ secrets.NANO2_API_KEY }}';" >> cw_nano/lib/.secrets.g.dart
+ echo "const nanoNowNodesApiKey = '${{ secrets.NANO_NOW_NODES_API_KEY }}';" >> cw_nano/lib/.secrets.g.dart
+
+ echo "const tronGridApiKey = '${{ secrets.TRON_GRID_API_KEY }}';" >> cw_tron/lib/.secrets.g.dart
+ echo "const tronNowNodesApiKey = '${{ secrets.TRON_NOW_NODES_API_KEY }}';" >> cw_tron/lib/.secrets.g.dart
+
+ echo "const breezApiKey = '${{ secrets.BREEZ_API_KEY }}';" >> cw_bitcoin/lib/.secrets.g.dart
+
+ echo "${{ secrets.MAIN_SECRETS_FILE }}" | base64 --decode > lib/.secrets.g.dart
+ - name: Add funded wallet secrets
+ if: ${{ inputs.write_funds_secrets }}
+ run: |
+ echo "${{ secrets.FUNDS_SECRETS_FILE }}" | base64 --decode > integration_test/core/funded_wallets.dart
+
+ - name: Build dependencies utilizing ghcr cache
+ if: ${{ !inputs.extract_only }}
+ run: |
+ env \
+ CW_DOCKER_REGISTRY=ghcr.io/cake-tech/cake_wallet \
+ CW_DOCKER_USE_CLOUD=true \
+ ./scripts/android/docker/build.sh
+
+ - name: Extract native dependencies
+ if: ${{ inputs.extract_only }}
+ run: |
+ env \
+ CW_DOCKER_REGISTRY=ghcr.io/cake-tech/cake_wallet \
+ CW_DOCKER_USE_CLOUD=true \
+ ./scripts/android/docker/build.sh --extract
+
+ - name: Reclaim the space the dependency images took
+ run: |
+ docker system prune -af --volumes > /dev/null
+ df -h /
+
+ - name: Execute Build and Setup Commands
+ run: |
+ pushd scripts/android
+ source ./app_env.sh cakewallet
+ ./app_config.sh
+ popd
+
+ - name: Install Flutter dependencies
+ run: |
+ flutter pub get
+
+ - name: Save pub packages
+ if: steps.pub-cache.outputs.cache-hit != 'true'
+ continue-on-error: true
+ uses: actions/cache/save@v4
+ with:
+ path: ~/.pub-cache
+ key: pub-cache-${{ runner.os }}-${{ hashFiles('pubspec_base.yaml', 'cw_*/pubspec.yaml') }}
+
+ - name: Build generated code
+ run: |
+ flutter --version
+ ./model_generator.sh
+
+ - name: Generate KeyStore
+ run: |
+ keytool -genkey -v -keystore android/app/key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias testKey -noprompt -dname "CN=CakeWallet, OU=CakeWallet, O=CakeWallet, L=Florida, S=America, C=USA" -storepass $STORE_PASS -keypass $KEY_PASS
+
+ - name: Generate key properties
+ run: |
+ dart run tool/generate_android_key_properties.dart keyAlias=testKey storeFile=key.jks storePassword=$STORE_PASS keyPassword=$KEY_PASS
+
+ - name: Generate localization
+ run: |
+ dart run tool/generate_localization.dart
+
+ - name: Compile graphics
+ run: |
+ ./compile_graphics.sh
+
+ - name: Compile assets/images graphics
+ run: |
+ while read -r dir; do
+ dart run vector_graphics_compiler --input-dir "$dir" --out-dir "$dir" > /dev/null &
+ done < <(find assets/images -type d)
+ wait
+
+ - name: Rename app
+ run: |
+ sanitized_branch_name=${BRANCH_NAME#origin/} # Remove 'origin/' prefix if it exists
+ sanitized_branch_name=${sanitized_branch_name:0:16} # Take only the first 16 characters
+ sanitized_branch_name=$(echo "$sanitized_branch_name" | tr '[:upper:]' '[:lower:]') # Convert to lowercase
+ sanitized_branch_name=$(echo "$sanitized_branch_name" | sed 's/[^a-z0-9]//g') # Remove all special characters
+
+ echo -e "id=com.cakewallet.test_${sanitized_branch_name}\nname=${BRANCH_NAME}" > android/app.properties
+
+ - name: Prime test build
+ env:
+ SUITE_DIR_INPUT: ${{ inputs.suite_dir }}
+ TEST_TIER_INPUT: ${{ inputs.test_tier }}
+ run: |
+ search_dir="$SUITE_DIR_INPUT"
+ if [[ "$TEST_TIER_INPUT" != "all" ]]; then
+ search_dir="$search_dir/$TEST_TIER_INPUT"
+ fi
+ first_suite=$(find "$search_dir" -name "*_test.dart" -type f | sort | head -1)
+ echo "Priming build with $first_suite"
+ flutter build apk --debug --target-platform android-x64 --target="$first_suite" --dart-define=CI_BUILD=true
+
+ - name: Cap the gradle heap for the test phase
+ run: |
+ sed -i 's/^org.gradle.jvmargs=.*/org.gradle.jvmargs=-Xmx3072M/' android/gradle.properties
+ grep '^org.gradle.jvmargs' android/gradle.properties
+ pkill -f GradleDaemon || echo "No gradle daemon to stop"
+ free -h || true
+ df -h / || true
+
+ - name: Integration tests on Android Emulator
+ uses: reactivecircus/android-emulator-runner@v2
+ env:
+ RECORD_SCREEN: ${{ inputs.record_screen }}
+ ENCRYPT_LOGS: ${{ inputs.write_funds_secrets }}
+ SUITE_DIR_INPUT: ${{ inputs.suite_dir }}
+ EXTRA_DART_DEFINES_INPUT: ${{ inputs.extra_dart_defines }}
+ with:
+ api-level: 31
+ target: google_apis
+ arch: x86_64
+ profile: pixel_5
+ force-avd-creation: false
+ emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none -read-only -memory 3072 -cores 4 -no-snapshot-save
+ disable-animations: false
+ working-directory: ${{ github.workspace }}
+ script: bash scripts/ci/run_integration_tests.sh ${{ inputs.test_tier }}
+
+ - name: Upload test logs
+ if: always()
+ continue-on-error: true
+ uses: actions/upload-artifact@v4
+ with:
+ name: integration-test-logs
+ path: |
+ ${{ github.workspace }}/${{ inputs.test_tier }}_run.log
+ ${{ github.workspace }}/${{ inputs.test_tier }}_run.log.gpg
+ ${{ github.workspace }}/${{ inputs.test_tier }}_logcat.txt
+ ${{ github.workspace }}/${{ inputs.test_tier }}_logcat.txt.gpg
+ ${{ github.workspace }}/recordings/*.gpg
+
+ - name: Integration tests on Android Emulator (tier1, non-blocking)
+ if: ${{ inputs.test_tier == 'tier0' }}
+ continue-on-error: true
+ uses: reactivecircus/android-emulator-runner@v2
+ env:
+ RECORD_SCREEN: ${{ inputs.record_screen }}
+ ENCRYPT_LOGS: ${{ inputs.write_funds_secrets }}
+ SUITE_DIR_INPUT: ${{ inputs.suite_dir }}
+ EXTRA_DART_DEFINES_INPUT: ${{ inputs.extra_dart_defines }}
+ with:
+ api-level: 31
+ target: google_apis
+ arch: x86_64
+ profile: pixel_5
+ force-avd-creation: false
+ emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none -read-only -memory 3072 -cores 4 -no-snapshot-save
+ disable-animations: false
+ working-directory: ${{ github.workspace }}
+ script: bash scripts/ci/run_integration_tests.sh tier1
+
+ - name: Upload tier1 logs
+ if: ${{ always() && inputs.test_tier == 'tier0' }}
+ continue-on-error: true
+ uses: actions/upload-artifact@v4
+ with:
+ name: integration-test-logs-tier1
+ path: |
+ ${{ github.workspace }}/tier1_run.log
+ ${{ github.workspace }}/tier1_run.log.gpg
+ ${{ github.workspace }}/tier1_logcat.txt
+ ${{ github.workspace }}/tier1_logcat.txt.gpg
+
+ # Superseded runs are cancelled on purpose, reporting those would be noise
+ - name: Report the run to slack
+ if: ${{ !cancelled() && inputs.slack_notify }}
+ continue-on-error: true
+ env:
+ SLACK_TOKEN: ${{ secrets.SLACK_TESTS_TOKEN }}
+ SLACK_CHANNEL: ${{ secrets.SLACK_TESTS_CHANNEL }}
+ BRANCH: ${{ github.head_ref || github.ref_name }}
+ PR_NUMBER: ${{ github.event.pull_request.number }}
+ PR_TITLE: ${{ github.event.pull_request.title }}
+ COMMIT: ${{ github.event.pull_request.head.sha || github.sha }}
+ ACTOR: ${{ github.actor }}
+ REPO_URL: ${{ github.server_url }}/${{ github.repository }}
+ RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
+ DART_DEFINES: ${{ inputs.extra_dart_defines }}
+ run: |
+ if [[ -z "$SLACK_TOKEN" || -z "$SLACK_CHANNEL" ]]; then
+ echo "::notice::No slack token or channel configured, skipping the report"
+ exit 0
+ fi
+
+ fmt() {
+ printf '%dm %02ds' $(( $1 / 60 )) $(( $1 % 60 ))
+ }
+
+ field() {
+ awk -F= -v key="$2" '$1 == key { print $2; exit }' "$1"
+ }
+
+ tier_line() {
+ local file="$1" label="$2" note="$3"
+
+ if [[ ! -f "$file" ]]; then
+ printf '*%s*\n%s' "$label" "$note"
+ return
+ fi
+
+ printf '*%s*\n%s/%s passed in %s' "$label" \
+ "$(field "$file" passed)" "$(field "$file" total)" \
+ "$(fmt "$(field "$file" duration)")"
+ }
+
+ # For scenarios where the suite never ran because of driver issues,
+ # we can't call it a failing test, so we just log it
+ failure_lines() {
+ local file="$1" label="$2"
+
+ [[ -f "$file" ]] || return 0
+
+ while IFS= read -r entry; do
+ [[ -n "$entry" ]] || continue
+
+ local rest="${entry#*|}"
+ local name="${entry%%|*}"
+ local duration="${rest%%|*}"
+ local reason="${rest#*|}"
+
+ if [[ "$reason" == "void" ]]; then
+ printf '\n• `%s` (%s) _%s, driver never attached, the suite did not run_' \
+ "$name" "$(fmt "$duration")" "$label"
+ else
+ printf '\n• `%s` (%s) _%s_' "$name" "$(fmt "$duration")" "$label"
+ fi
+ done < <(sed -n 's/^fail=//p' "$file")
+ }
+
+ # Adding the results for the funds suites to the report too, so we know if we need to topup
+ chain_lines() {
+ local status_wanted="$1" icon="$2" file
+ local seen=""
+
+ for file in *_summary.txt; do
+ [[ -f "$file" ]] || continue
+
+ while IFS= read -r entry; do
+ [[ -n "$entry" ]] || continue
+
+ local chain="${entry%%|*}"
+ local rest="${entry#*|}"
+ local status="${rest%%|*}"
+ local detail="${rest#*|}"
+
+ [[ "$status" == "$status_wanted" ]] || continue
+ [[ "$seen" == *"[$chain]"* ]] && continue
+ seen="$seen[$chain]"
+
+ printf '\n%s *%s* _%s_' "$icon" "$chain" "$detail"
+ done < <(sed -n 's/^chain=//p' "$file")
+ done
+ }
+
+ pass_names() {
+ local file="$1" label="$2"
+
+ [[ -f "$file" ]] || return 0
+
+ printf '*%s* (%s)' "$label" "$(field "$file" passed)"
+
+ while IFS= read -r entry; do
+ [[ -n "$entry" ]] || continue
+ printf '\n• %s _%s_' "${entry%%|*}" "$(fmt "${entry##*|}")"
+ done < <(sed -n 's/^pass=//p' "$file")
+ }
+
+ tier0_failed=1
+ tier1_failed=0
+ total_passed=0
+
+ if [[ -f all_summary.txt ]]; then
+ tier0_failed=$(field all_summary.txt failed)
+ else
+ [[ -f tier0_summary.txt ]] && tier0_failed=$(field tier0_summary.txt failed)
+ [[ -f tier1_summary.txt ]] && tier1_failed=$(field tier1_summary.txt failed)
+ fi
+
+ for file in tier0_summary.txt tier1_summary.txt; do
+ [[ -f "$file" ]] || continue
+ total_passed=$(( total_passed + $(field "$file" passed) ))
+ done
+
+ if (( tier0_failed > 0 )); then
+ headline=":x: Integration tests failed"
+ elif (( tier1_failed > 0 )); then
+ headline=":warning: Gate passed, tier1 has failures"
+ else
+ headline=":white_check_mark: Integration tests passed"
+ fi
+
+ if (( tier0_failed > 0 )); then
+ tier1_note="_skipped, tier0 failed_"
+ else
+ tier1_note="_did not run_"
+ fi
+
+ where="<$REPO_URL/tree/$BRANCH|$BRANCH>"
+ if [[ -n "$PR_NUMBER" ]]; then
+ where="$where · <$REPO_URL/pull/$PR_NUMBER|#$PR_NUMBER ${PR_TITLE:-}>"
+ fi
+
+ failures=$(printf '%s%s%s' \
+ "$(failure_lines tier0_summary.txt tier0)" \
+ "$(failure_lines tier1_summary.txt tier1)" \
+ "$(failure_lines all_summary.txt suites)")
+
+ if [[ -f all_summary.txt ]]; then
+ primary=$(tier_line all_summary.txt suites '')
+ secondary=""
+ else
+ primary=$(tier_line tier0_summary.txt tier0 '_did not run_')
+ secondary=$(tier_line tier1_summary.txt tier1 "$tier1_note")
+ fi
+
+ chains=$(printf '%s%s%s%s' \
+ "$(chain_lines ok ':white_check_mark:')" \
+ "$(chain_lines empty ':moneybag:')" \
+ "$(chain_lines waiting ':hourglass:')" \
+ "$(chain_lines failed ':x:')")
+
+ needs_funding=$(chain_lines empty ':moneybag:')
+ too_slow=$(chain_lines waiting ':hourglass:')
+
+ blocks=$(jq -n \
+ --arg headline "$headline" \
+ --arg where "$where" \
+ --arg primary "$primary" \
+ --arg secondary "$secondary" \
+ --arg failures "$failures" \
+ --arg chains "$chains" \
+ --arg funding "$needs_funding" \
+ --arg slow "$too_slow" \
+ --arg defines "$(printf '%s' "$DART_DEFINES" | tr ';' ' ')" \
+ --arg commit "${COMMIT:0:8}" \
+ --arg actor "$ACTOR" \
+ --arg repo "$REPO_URL" \
+ --arg run "$RUN_URL" \
+ '[
+ { type: "header", text: { type: "plain_text", text: $headline, emoji: true } },
+ { type: "section", text: { type: "mrkdwn", text: $where } },
+ { type: "section", fields: (
+ [ { type: "mrkdwn", text: $primary } ]
+ + (if $secondary == "" then [] else
+ [ { type: "mrkdwn", text: $secondary } ] end)
+ ) }
+ ]
+ + (if $failures == "" then [] else
+ [ { type: "section", text: { type: "mrkdwn",
+ text: ("*Did not pass*" + $failures) } } ]
+ end)
+ + (if $chains == "" then [] else
+ [ { type: "divider" },
+ { type: "section", text: { type: "mrkdwn",
+ text: ("*Chains*" + $chains) } } ]
+ end)
+ + (if $funding == "" then [] else
+ [ { type: "context", elements: [ { type: "mrkdwn",
+ text: ":moneybag: The chains above could not cover a send. Top those wallets up and re run the funds workflow, nothing there needs debugging :)." } ] } ]
+ end)
+ + (if $slow == "" then [] else
+ [ { type: "context", elements: [ { type: "mrkdwn",
+ text: ":hourglass: Still rescanning when the clock ran out, so nothing was proven either way and the run is not red for them." } ] } ]
+ end)
+ + [
+ { type: "context", elements: [
+ { type: "mrkdwn",
+ text: ("<" + $repo + "/commit/" + $commit + "|" + $commit + "> · " + $actor
+ + (if $defines == "" then "" else " · `" + $defines + "`" end)) }
+ ] },
+ { type: "actions", elements: [
+ { type: "button", url: $run,
+ text: { type: "plain_text", text: "View run", emoji: false } }
+ ] }
+ ]')
+
+ response=$(curl -sS -X POST https://slack.com/api/chat.postMessage \
+ -H "Authorization: Bearer $SLACK_TOKEN" \
+ -H "Content-type: application/json; charset=utf-8" \
+ --data "$(jq -n --arg channel "$SLACK_CHANNEL" --arg text "$headline" \
+ --argjson blocks "$blocks" \
+ '{channel: $channel, text: $text, blocks: $blocks}')")
+
+ if [[ "$(jq -r '.ok' <<< "$response")" != "true" ]]; then
+ error=$(jq -r '.error // "unknown"' <<< "$response")
+ needed=$(jq -r '.needed // empty' <<< "$response")
+
+ if [[ -n "$needed" ]]; then
+ echo "::warning::Slack rejected the report: $error, it wants the $needed scope"
+ else
+ echo "::warning::Slack rejected the report: $error"
+ fi
+
+ exit 0
+ fi
+
+ thread_ts=$(jq -r '.ts // empty' <<< "$response")
+
+ if [[ -z "$thread_ts" ]] || (( total_passed == 0 )); then
+ exit 0
+ fi
+
+ # So that the channel is not clutter (and uglyyyy), we put everything that passed in the thread
+ # and the short version is the one that shows up in the channel
+ passed=$(printf '%s\n\n%s' \
+ "$(pass_names tier0_summary.txt tier0)" "$(pass_names tier1_summary.txt tier1)")
+
+ curl -sS -X POST https://slack.com/api/chat.postMessage \
+ -H "Authorization: Bearer $SLACK_TOKEN" \
+ -H "Content-type: application/json; charset=utf-8" \
+ --data "$(jq -n --arg channel "$SLACK_CHANNEL" --arg ts "$thread_ts" --arg text "$passed" \
+ '{channel: $channel, thread_ts: $ts, text: $text}')" > /dev/null
### .gitignore
@@ -88,6 +88,11 @@ cw_monero/cw_monero/android/.cxx/
android/key.properties
android/app/key.jks
+# Signing secrets: keystore passwords and any stray keystore/cert material
+android/app/*.pwd
+*.keystore
+*.jks
+*.p12
**/tool/.secrets-prod.json
**/tool/.secrets-test.json
### README.md
@@ -108,6 +108,9 @@ com.cakewallet.cake_wallet
C5:40:53:AB:0F:10:D9:54:17:62:A3:DA:76:65:AE:3D:BA:5E:7C:74:3A:B4:F1:08:A5:34:9D:62:AC:10:6E:F5
```
+For signed checksums, the release key, and verification steps for every platform, see
+[Verifying Cake Wallet downloads](docs/VERIFY.md).
+
# Support
We have 24/7 free support. Please contact support@cakewallet.com
### android/app/src/main/AndroidManifestBase.xml
@@ -117,6 +117,9 @@
<data android:scheme="bsc" />
<data android:scheme="bsc-wallet" />
<data android:scheme="bsc_wallet" />
+ <data android:scheme="robinhood" />
+ <data android:scheme="robinhood-wallet" />
+ <data android:scheme="robinhood_wallet" />
<data android:scheme="zcash" />
<data android:scheme="zcash-wallet" />
<data android:scheme="lightning" />
### android/gradle.properties
@@ -2,4 +2,4 @@ org.gradle.jvmargs=-Xmx6144M
android.useAndroidX=true
android.enableJetifier=true
-android.ndk.suppressMinSdkVersionError=21
+android.ndk.suppressMinSdkVersionError=21
\ No newline at end of file
### assets/bitcoin_electrum_server_list.yml
@@ -9,6 +9,11 @@
uri: electrs.cakewallet.com:50001
isOfficial: true
label: "Cake Wallet Electrs"
+-
+ uri: cakebtc5pihzt3byjclxfumiwvtxj72auarshrsvmaatmwmr7dj6zyid.onion:50001
+ useSSL: false
+ isOfficial: true
+ label: "Cake Wallet (Tor)"
-
uri: fulcrum.sethforprivacy.com:50002
useSSL: true
### assets/fonts/IBM_Plex_Sans/IBMPlexSans-Medium.ttf
[binary or diff unavailable]
### assets/fonts/IBM_Plex_Sans/IBMPlexSans-Regular.ttf
[binary or diff unavailable]
### assets/fonts/Lato-Bold.ttf
[binary or diff unavailable]
### assets/fonts/Lato-Medium.ttf
[binary or diff unavailable]
### assets/fonts/Lato-Regular.ttf
[binary or diff unavailable]
### assets/fonts/Lato-Semibold.ttf
[binary or diff unavailable]
### assets/images/btcmap.png
[binary or diff unavailable]
### assets/images/discourse.png
[binary or diff unavailable]
### assets/images/letsexchange_icon.svg
@@ -1,5 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32" height="32">
- <path fill-rule="evenodd" clip-rule="evenodd"
- d="M16 1.37854C16 0.764286 16.6636 0.379192 17.1969 0.68395L23 4L29.4961 7.71208C29.8077 7.89012 30 8.22147 30 8.58032V16L23.9923 12.567C23.3774 12.2157 22.6226 12.2157 22.0077 12.567L16 16V8V1.37854ZM2 16V8.58032C2 8.22147 2.19229 7.89012 2.50386 7.71208L8.00772 4.56702C8.62259 4.21566 9.37741 4.21566 9.99228 4.56702L16 8L2 16ZM16 30.6215C16 31.2357 15.3364 31.6208 14.8031 31.3161L9 28L2.50386 24.2879C2.19229 24.1099 2 23.7785 2 23.4197V16L8.00772 19.433C8.62259 19.7843 9.37741 19.7843 9.99228 19.433L16 16V24V30.6215ZM22.0077 27.433C22.6226 27.7843 23.3774 27.7843 23.9923 27.433L29.4961 24.2879C29.8077 24.1099 30 23.7785 30 23.4197V16L16 24L22.0077 27.433Z"
- fill="#159DFF"></path>
-</svg>
\ No newline at end of file
### assets/images/monerocom_logo.svg
@@ -0,0 +1,25 @@
+<svg width="650" height="650" viewBox="187 187 650 650" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_3163_103)">
+<path d="M760.715 378.625C802.842 378.625 837.031 412.781 837.031 454.937V760.812C837.031 802.906 802.905 837.031 760.809 837.031H263.222C221.127 837.031 187 802.906 187 760.812V454.937C187 412.812 221.158 378.625 263.316 378.625H265.066C283.005 379.062 300.255 385.75 313.756 397.656L457.513 524.25C473.076 537.969 492.546 544.812 512.016 544.812C531.485 544.812 550.924 537.938 566.518 524.25L710.275 397.656C724.213 385.375 742.12 378.625 760.715 378.625Z" fill="url(#paint0_linear_3163_103)"/>
+<path d="M760.809 187C802.905 187 837.031 221.125 837.031 263.219V278.375C817.155 259.531 790.31 247.938 760.809 247.938H263.222C233.721 247.938 206.876 259.5 187 278.344V263.219C187 221.125 221.127 187 263.222 187H760.809Z" fill="url(#paint1_linear_3163_103)"/>
+<path d="M760.809 282.593H263.222C221.127 282.593 187.031 316.718 187.031 358.812V374.405C206.907 355.53 233.784 343.937 263.316 343.937C289.505 343.937 314.756 353.155 334.757 369.968L481.264 498.937C489.858 506.187 500.765 510.155 512.016 510.155C523.266 510.155 534.173 506.187 542.767 498.937L689.274 369.968C709.275 353.155 734.526 343.937 760.715 343.937C790.248 343.937 817.124 355.53 837 374.405V358.812C837 316.718 802.905 282.593 760.809 282.593Z" fill="url(#paint2_linear_3163_103)"/>
+</g>
+<defs>
+<linearGradient id="paint0_linear_3163_103" x1="512.016" y1="378.625" x2="512.016" y2="837.031" gradientUnits="userSpaceOnUse">
+<stop offset="0.00646752" stop-color="#403649"/>
+<stop offset="1" stop-color="#312938"/>
+</linearGradient>
+<linearGradient id="paint1_linear_3163_103" x1="496.415" y1="186.913" x2="487.404" y2="266.57" gradientUnits="userSpaceOnUse">
+<stop stop-color="#61C5FF"/>
+<stop offset="0.924264" stop-color="#2A92FA"/>
+</linearGradient>
+<linearGradient id="paint2_linear_3163_103" x1="512.016" y1="282.593" x2="512.016" y2="510.155" gradientUnits="userSpaceOnUse">
+<stop stop-color="#FF7D38"/>
+<stop offset="0.612828" stop-color="#FE6412"/>
+<stop offset="1" stop-color="#F25400"/>
+</linearGradient>
+<clipPath id="clip0_3163_103">
+<rect width="650" height="650" fill="white" transform="translate(187 187)"/>
+</clipPath>
+</defs>
+</svg>
### assets/images/robinhood_chain_QR.svg
@@ -0,0 +1,20 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="250" height="250" viewBox="0 0 250 250" fill="none">
+<g clip-path="url(#clip0_10809_45063)">
+<g>
+<path d="M0 71.1111C0 46.2199 0 33.7743 4.84415 24.2671C9.10519 15.9043 15.9043 9.10519 24.2671 4.84415C33.7743 0 46.2199 0 71.1111 0H178.889C203.78 0 216.226 0 225.733 4.84415C234.096 9.10519 240.895 15.9043 245.156 24.2671C250 33.7743 250 46.2199 250 71.1111V178.889C250 203.78 250 216.226 245.156 225.733C240.895 234.096 234.096 240.895 225.733 245.156C216.226 250 203.78 250 178.889 250H71.1111C46.2199 250 33.7743 250 24.2671 245.156C15.9043 240.895 9.10519 234.096 4.84415 225.733C0 216.226 0 203.78 0 178.889V71.1111Z" fill="white" />
+<path d="M178.89 238.889V250H71.11V238.889H178.89ZM238.889 178.89V71.11C238.889 58.4817 238.879 49.6759 238.319 42.8223C237.77 36.1003 236.744 32.2389 235.254 29.3132C232.058 23.0411 226.959 17.9419 220.687 14.7461C217.761 13.2555 213.9 12.2302 207.178 11.6808C200.324 11.1208 191.518 11.1111 178.89 11.1111H71.11C58.4817 11.1111 49.6759 11.1208 42.8223 11.6808C36.1003 12.2302 32.2389 13.2555 29.3132 14.7461C23.0411 17.9419 17.9419 23.0411 14.7461 29.3132C13.2555 32.2389 12.2302 36.1003 11.6808 42.8223C11.1208 49.6759 11.1111 58.4817 11.1111 71.11V178.89C11.1111 191.518 11.1208 200.324 11.6808 207.178C12.2302 213.9 13.2555 217.761 14.7461 220.687C17.9419 226.959 23.0411 232.058 29.3132 235.254C32.2389 236.744 36.1003 237.77 42.8223 238.319C49.6759 238.879 58.4817 238.889 71.11 238.889V250C47.7738 250 35.3773 249.999 26.0851 246.007L24.2676 245.155C16.4283 241.161 9.96351 234.936 5.67491 227.284L4.84483 225.732C0.606184 217.413 0.0770651 206.845 0.0108507 187.657L0 178.89V71.11C9.61996e-10 47.7738 0.000910626 35.3773 3.99306 26.0851L4.84483 24.2676C8.83916 16.4283 15.0637 9.96351 22.7159 5.67491L24.2676 4.84483C33.7746 0.000808636 46.2196 1.02606e-09 71.11 0H178.89L187.657 0.0108507C206.845 0.0770651 217.413 0.606184 225.732 4.84483C234.095 9.10587 240.894 15.9048 245.155 24.2676C249.999 33.7746 250 46.2196 250 71.11V178.89L249.989 187.657C249.923 206.845 249.394 217.413 245.155 225.732C240.894 234.095 234.095 240.894 225.732 245.155C217.413 249.394 206.845 249.923 187.657 249.989L178.89 250V238.889C191.518 238.889 200.324 238.879 207.178 238.319C213.9 237.77 217.761 236.744 220.687 235.254C226.959 232.058 232.058 226.959 235.254 220.687C236.744 217.761 237.77 213.9 238.319 207.178C238.879 200.324 238.889 191.518 238.889 178.89Z" fill="black" />
+</g>
+<g>
+<g>
+<path d="M141.616 72.2304C142.819 72.2304 143.181 72.9527 142.338 73.9158C121.873 96.5471 89.2506 134.346 59.2763 210.666C59.0356 211.268 58.3132 211.629 57.591 211.629H53.6183C52.7758 211.629 52.4145 211.124 52.6552 210.185C56.6277 195.499 62.0455 179.247 70.5924 155.292V122.067C70.5924 115.687 71.5556 111.233 75.4077 106.418L101.65 73.9158C102.577 72.7601 103.697 72.2304 105.021 72.2304H141.616Z" fill="black" />
+<path d="M148.839 81.3795C149.681 80.4169 150.524 80.8984 150.524 82.1018V128.087C150.524 128.689 150.404 129.532 150.042 130.254L133.309 157.821C131.263 161.191 128.88 162.901 124.643 164.201L87.0839 175.757C86.0005 176.118 85.4226 175.324 85.8801 174.433C104.057 138.921 123.679 109.428 148.839 81.3795Z" fill="black" />
+<path d="M142.699 34.7921C154.496 30.2177 180.017 30.4586 185.675 36.4775C192.055 43.2187 192.898 59.4701 191.453 70.0635C190.37 77.2862 189.166 78.8517 185.193 84.028L160.757 115.928C160.034 117.011 159.071 116.65 159.071 115.446V69.7023C159.071 65.9706 156.904 63.8035 153.172 63.8035H112.604C111.401 63.8033 111.039 62.9607 111.882 62.1182C118.743 54.8954 125.967 47.5525 136.801 38.2833C137.885 37.3563 140.244 35.7431 142.699 34.7921Z" fill="black" />
+</g>
+</g>
+</g>
+<defs>
+<clipPath id="clip0_10809_45063">
+<rect width="250" height="250" fill="white" />
+</clipPath>
+</defs>
+</svg>
### assets/images/robinhood_chain_mono.svg
@@ -0,0 +1,9 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="250" height="250" viewBox="0 0 250 250" fill="none">
+<g>
+<g>
+<path d="M149.564 62.0033C151.096 62.0033 151.558 62.9194 150.488 64.1442C124.434 92.9567 82.9033 141.085 44.742 238.251C44.4354 239.017 43.5073 239.482 42.5877 239.482H37.5299C36.4611 239.479 36.0063 238.828 36.3123 237.635C41.3697 218.938 48.2585 198.246 59.1393 167.749V125.453C59.1393 117.331 60.3767 111.66 65.281 105.53L98.6919 64.1442C99.8704 62.6777 101.291 62.0042 102.974 62.0033H149.564Z" fill="white" />
+<path d="M158.757 73.6443C159.829 72.4195 160.91 73.037 160.911 74.5675V133.12C160.91 133.886 160.754 134.959 160.296 135.877L138.994 170.974C136.389 175.263 133.349 177.441 127.955 179.096L80.1466 193.801C78.7673 194.261 78.0255 193.249 78.6079 192.115C101.749 146.905 126.727 109.353 158.757 73.6443Z" fill="white" />
+<path d="M150.943 14.3421C165.96 8.51918 198.445 8.82347 205.655 16.483C213.778 25.0655 214.854 45.7602 213.015 59.2469C211.636 68.4366 210.106 70.4318 205.053 77.0162L173.93 117.639C173.011 119.011 171.79 118.553 171.789 117.024V58.7786C171.787 54.0315 169.031 51.273 164.283 51.2722H112.634C111.103 51.2722 110.641 50.2033 111.711 49.1313C120.447 39.9361 129.644 30.5848 143.436 18.7844C144.815 17.605 147.818 15.5531 150.943 14.3421Z" fill="white" />
+</g>
+</g>
+</svg>
### assets/images/skrill.svg
@@ -1,9 +1,9 @@
-<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="256" height="256" viewBox="0 0 256 256" xml:space="preserve">
+<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="256" height="256" viewBox="0 0 256 256" xml:space="preserve">
<defs>
</defs>
<g style="stroke: none; stroke-width: 0; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: none; fill-rule: nonzero; opacity: 1;" transform="translate(1.4065934065934016 1.4065934065934016) scale(2.81 2.81)" >
- <circle cx="45" cy="45" r="45" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(127,33,99); fill-rule: nonzero; opacity: 1;" transform=" matrix(1 0 0 1 0 0) "/>
+ <rect x="0" y="0" width="90" height="90" rx="10" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(127,33,99); fill-rule: nonzero; opacity: 1;" transform=" matrix(1 0 0 1 0 0) "/>
<polygon points="69.59,36.9 69.59,54.86 74.5,54.86 74.5,36.02 " style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(249,249,249); fill-rule: nonzero; opacity: 1;" transform=" matrix(1 0 0 1 0 0) "/>
<polygon points="62.42,36.9 67.33,36.02 67.33,54.87 62.42,54.87 " style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(249,249,249); fill-rule: nonzero; opacity: 1;" transform=" matrix(1 0 0 1 0 0) "/>
<rect x="55.43" y="41.08" rx="0" ry="0" width="4.91" height="13.78" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(249,249,249); fill-rule: nonzero; opacity: 1;" transform=" matrix(1 0 0 1 0 0) "/>
### assets/images/stocks/amd.png
[binary or diff unavailable]
### assets/images/stocks/asml.png
[binary or diff unavailable]
### assets/images/stocks/baba.png
[binary or diff unavailable]
### assets/images/stocks/cost.png
[binary or diff unavailable]
### assets/images/stocks/ddog.png
[binary or diff unavailable]
### assets/images/stocks/dell.png
[binary or diff unavailable]
### assets/images/stocks/f.png
[binary or diff unavailable]
### assets/images/stocks/intu.png
[binary or diff unavailable]
### assets/images/stocks/lulu.png
[binary or diff unavailable]
### assets/images/stocks/mu.png
[binary or diff unavailable]
### assets/images/stocks/nu.png
[binary or diff unavailable]
### assets/images/stocks/qcom.png
[binary or diff unavailable]
### assets/images/stocks/rivn.png
[binary or diff unavailable]
### assets/images/stocks/shop.png
[binary or diff unavailable]
### assets/images/stocks/sofi.png
[binary or diff unavailable]
### assets/images/stocks/tsm.png
[binary or diff unavailable]
### assets/images/stocks/ttwo.png
[binary or diff unavailable]
### assets/images/stocks/ups.png
[binary or diff unavailable]
### assets/images/stocks/wday.png
[binary or diff unavailable]
### assets/images/usdg_icon.png
[binary or diff unavailable]
### assets/litecoin_electrum_server_list.yml
@@ -5,6 +5,11 @@
isOfficial: true
isEnabledForAutoSwitching: true
label: "Cake Wallet"
+-
+ uri: cakeltcnzbdxhk3dhlzxjnnylxbfhhbx2njegaluyh35t7dca35vcnqd.onion:50001
+ useSSL: false
+ isOfficial: true
+ label: "Cake Wallet (Tor)"
-
uri: litecoin.stackwallet.com:20063
useSSL: true
### assets/new-ui/changelog/text/changelog_ar.json
@@ -1 +1 @@
-[{"title":"تريزور أصلا لبيتكوين","description":"قم بإقران جهازك وتوقيع معاملات Bitcoin مباشرة في التطبيق"},{"title":"تحسينات Solana وNFTs","description":"أرسل Solana NFTs الخاصة بك، واحتفظ بالبطاقات المستوردة المحفوظة، واطلع في لمحة سريعة على تلك التي تحتوي عليها هذه المحفظة"},{"title":"تحسينات مزامنة مونيرو","description":"يستمر تقدم المزامنة في التحرك أثناء تسخين محفظتك، حتى تعرف دائمًا مكانها"},{"title":"إصلاحات الشوائب","description":"مزامنة جهات الاتصال، واختيار العقدة، وتسجيل الدخول إلى Cake Pay، والمزيد، تم سحقها جميعًا"}]
\ No newline at end of file
+[{"title":"Zcash على Ledger","description":"قم بتوصيل Ledger الخاص بك لتلقي ZEC وحمايته وإرساله"},{"title":"جاهز لـ Zcash NU7","description":"تعمل أجهزة ZEC الخاصة بك على الإرسال والحماية من خلال ترقية شبكة NU7"},{"title":"BitBox02 Nova على iOS","description":"استخدم BitBox02 Nova على iPhone وiPad عبر Bluetooth، مع التحقق من رمز الاقتران من أجل اتصال آمن"},{"title":"إطلاق أسرع","description":"يفتح التطبيق بشكل أسرع، ويتم تحميل المحافظ وتبديلها بشكل أسرع، خاصة على الهواتف القديمة أو مع العديد من المحافظ"},{"title":"BTC Map","description":"ابحث عن أماكن لقضاء sats أينما كنت، مباشرة من علامة التبويب \"التطبيقات\"."},{"title":"إصلاحات الشوائب والتحسينات","description":"حماية أقوى للمصادقة الثنائية والنسخ الاحتياطي، لا مزيد من محافظ Bitcoin وLitecoin عالقة في Connecting وMoonPay على Arbitrum والمزيد"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_bg.json
@@ -1 +1 @@
-[{"title":"Trezor първоначално за биткойн","description":"Сдвоете вашето устройство и подписвайте биткойн транзакции направо в приложението"},{"title":"Solana и подобрения на NFT","description":"Изпратете вашите Solana NFT, запазете импортираните и вижте с един поглед кои съхранява този портфейл"},{"title":"Подобрения в синхронизирането на Monero","description":"Прогресът на синхронизирането продължава да се движи, докато портфейлът ви загрява, така че винаги да знаете къде се намира"},{"title":"Поправки на грешки","description":"Синхронизиране на контакти, избор на възел, влизане в Cake Pay и други, всички смачкани"}]
\ No newline at end of file
+[{"title":"Zcash на Ledger","description":"Свържете вашия Ledger, за да получавате, екранирате и изпращате ZEC"},{"title":"Готов за Zcash NU7","description":"Вашите ZEC изпращания и екранирането продължават да работят чрез надстройката на мрежата NU7"},{"title":"BitBox02 Nova на iOS","description":"Използвайте своя BitBox02 Nova на iPhone и iPad през Bluetooth с проверка на кода за сдвояване за сигурна връзка"},{"title":"По-бързо стартиране","description":"Приложението се отваря по-бързо и портфейлите се зареждат и превключват по-бързо, особено на по-стари телефони или с много портфейли"},{"title":"BTC Map","description":"Намерете места, където да прекарате sats, където и да сте, направо от раздела Приложения"},{"title":"Поправки на грешки и подобрения","description":"По-силни 2FA и резервни защити, няма повече биткойн и лайткойн портфейли, заседнали на Connecting, MoonPay на Arbitrum и други"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_cs.json
@@ -1 +1 @@
-[{"title":"Trezor nativně pro bitcoiny","description":"Spárujte své zařízení a podepište bitcoinové transakce přímo v aplikaci"},{"title":"Solana a vylepšení NFT","description":"Pošlete své Solana NFT, mějte importované uložené a na první pohled uvidíte, které z nich tato peněženka obsahuje"},{"title":"Vylepšení synchronizace Monero","description":"Zatímco se vaše peněženka zahřívá, postup synchronizace se neustále pohybuje, takže vždy víte, kde se nachází"},{"title":"Opravy chyb","description":"Synchronizace kontaktů, výběr uzlů, přihlášení do Cake Pay a další, vše zmačkané"}]
\ No newline at end of file
+[{"title":"Zcash na Ledger","description":"Připojte svůj Ledger pro příjem, stínění a odesílání ZEC"},{"title":"Připraveno na Zcash NU7","description":"Vaše vysílání ZEC a stínění nadále fungují prostřednictvím upgradu sítě NU7"},{"title":"BitBox02 Nova na iOS","description":"Použijte svůj BitBox02 Nova na iPhone a iPad přes Bluetooth s kontrolou párovacího kódu pro bezpečné připojení"},{"title":"Rychlejší spuštění","description":"Aplikace se otevírá rychleji a peněženky se rychleji načítají a přepínají, zejména na starších telefonech nebo s mnoha peněženkami"},{"title":"BTC Map","description":"Najděte místa, kde můžete strávit sats, ať jste kdekoli, přímo na kartě Aplikace"},{"title":"Opravy chyb a vylepšení","description":"Silnější 2FA a zálohovací ochrana, žádné další bitcoinové a litecoinové peněženky přilepené na Connecting, MoonPay na Arbitrum a další"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_de.json
@@ -1 +1 @@
-[{"title":"Trezor nativ für Bitcoin","description":"Koppeln Sie Ihr Gerät und signieren Sie Bitcoin-Transaktionen direkt in der App"},{"title":"Verbesserungen bei Solana und NFTs","description":"Senden Sie Ihre Solana-NFTs, bewahren Sie importierte NFTs auf und sehen Sie auf einen Blick, welche in dieser Wallet gespeichert sind"},{"title":"Verbesserungen bei der Monero-Synchronisierung","description":"Der Synchronisierungsfortschritt läuft weiter, während sich Ihr Geldbeutel aufwärmt, sodass Sie immer wissen, wo er steht"},{"title":"Fehlerbehebungen","description":"Kontaktsynchronisierung, Knotenauswahl, Cake Pay-Anmeldung und mehr, alles gequetscht"}]
\ No newline at end of file
+[{"title":"Zcash im Ledger","description":"Verbinden Sie Ihr Ledger, um ZEC zu empfangen, abzuschirmen und zu senden"},{"title":"Bereit für Zcash NU7","description":"Ihre ZEC-Sendungen und -Abschirmung funktionieren auch nach dem NU7-Netzwerk-Upgrade weiterhin"},{"title":"BitBox02 Nova auf iOS","description":"Nutzen Sie Ihre BitBox02 Nova auf iPhone und iPad über Bluetooth, mit Pairing-Code-Prüfung für eine sichere Verbindung"},{"title":"Schnellerer Start","description":"Die App öffnet sich schneller und Wallets werden schneller geladen und gewechselt, insbesondere auf älteren Telefonen oder mit vielen Wallets"},{"title":"BTC Map","description":"Finden Sie Orte, an denen Sie sats ausgeben können, egal wo Sie sind, direkt auf der Registerkarte „Apps“."},{"title":"Fehlerbehebungen und Verbesserungen","description":"Stärkere 2FA- und Backup-Schutzfunktionen, keine Bitcoin- und Litecoin-Geldbörsen mehr, die beim Verbinden hängen bleiben, MoonPay bei Arbitrum und mehr"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_en.json
@@ -1,18 +1,26 @@
[
{
- "title": "Trezor natively for Bitcoin",
- "description": "Pair your device and sign Bitcoin transactions right in the app"
+ "title": "Zcash on Ledger",
+ "description": "Connect your Ledger to receive, shield and send ZEC"
},
{
- "title": "Solana and NFTs Improvements",
- "description": "Send your Solana NFTs, keep imported ones saved, and see at a glance which ones this wallet holds"
+ "title": "Ready for Zcash NU7",
+ "description": "Your ZEC sends and shielding keep working through the NU7 network upgrade"
},
{
- "title": "Monero sync improvements",
- "description": "Sync progress keeps moving while your wallet warms up, so you always know where it stands"
+ "title": "BitBox02 Nova on iOS",
+ "description": "Use your BitBox02 Nova on iPhone and iPad over Bluetooth, with a pairing code check for a secure connection"
},
{
- "title": "Bug fixes",
- "description": "Contact syncing, node selection, Cake Pay sign-in and more, all squashed"
+ "title": "Faster Launch",
+ "description": "The app opens quicker, and wallets load and switch faster, especially on older phones or with many wallets"
+ },
+ {
+ "title": "BTC Map",
+ "description": "Find places to spend sats wherever you are, right from the Apps tab"
+ },
+ {
+ "title": "Bug fixes & improvements",
+ "description": "Stronger 2FA and backup protections, no more Bitcoin and Litecoin wallets stuck on Connecting, MoonPay on Arbitrum and more"
}
-]
+]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_es.json
@@ -1 +1 @@
-[{"title":"Trezor de forma nativa para Bitcoin","description":"Empareja tu dispositivo y firma transacciones de Bitcoin directamente en la aplicación"},{"title":"Mejoras en Solana y NFT","description":"Envíe sus NFT de Solana, guarde los importados y vea de un vistazo cuáles contiene esta billetera"},{"title":"Mejoras en la sincronización de Monero","description":"El progreso de la sincronización continúa mientras tu billetera se calienta, para que siempre sepas dónde se encuentra"},{"title":"Corrección de errores","description":"Sincronización de contactos, selección de nodos, inicio de sesión de Cake Pay y más, todo aplastado"}]
\ No newline at end of file
+[{"title":"Zcash en Ledger","description":"Conecte su Ledger para recibir, proteger y enviar ZEC"},{"title":"Listo para Zcash NU7","description":"Sus envíos y blindajes ZEC siguen funcionando a través de la actualización de red NU7"},{"title":"BitBox02 Nova en iOS","description":"Utilice su BitBox02 Nova en iPhone y iPad a través de Bluetooth, con una verificación de código de emparejamiento para una conexión segura"},{"title":"Lanzamiento más rápido","description":"La aplicación se abre más rápido y las billeteras se cargan y cambian más rápido, especialmente en teléfonos más antiguos o con muchas billeteras."},{"title":"BTC Map","description":"Encuentra lugares para pasar sats estés donde estés, directamente desde la pestaña Aplicaciones"},{"title":"Corrección de errores y mejoras","description":"Protecciones de respaldo y 2FA más sólidas, no más billeteras Bitcoin y Litecoin atascadas en Connecting, MoonPay en Arbitrum y más"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_fa.json
@@ -1 +1 @@
-[{"title":"Trezor به صورت بومی برای بیت کوین","description":"دستگاه خود را جفت کنید و معاملات بیت کوین را مستقیماً در برنامه امضا کنید"},{"title":"بهبود سولانا و NFTs","description":"NFT های Solana خود را ارسال کنید، موارد وارداتی را ذخیره کنید و در یک نگاه ببینید که این کیف پول کدام یک را در خود جای می دهد."},{"title":"بهبود همگام سازی مونرو","description":"پیشرفت همگامسازی تا زمانی که کیف پول شما گرم میشود به حرکت خود ادامه میدهد، بنابراین همیشه میدانید کجا قرار دارد"},{"title":"رفع اشکال","description":"همگامسازی مخاطب، انتخاب گره، ورود به سیستم Cake Pay و موارد دیگر، همه له شدهاند"}]
\ No newline at end of file
+[{"title":"Zcash در Ledger","description":"Ledger خود را برای دریافت، محافظت و ارسال ZEC وصل کنید"},{"title":"آماده برای Zcash NU7","description":"ارسال های ZEC و محافظ شما از طریق ارتقاء شبکه NU7 به کار خود ادامه می دهند"},{"title":"BitBox02 Nova در iOS","description":"از BitBox02 Nova خود در iPhone و iPad از طریق بلوتوث، با بررسی کد جفتسازی برای اتصال ایمن استفاده کنید."},{"title":"راه اندازی سریعتر","description":"برنامه سریعتر باز میشود و کیف پولها سریعتر بار میشوند و جابهجا میشوند، مخصوصاً در تلفنهای قدیمی یا با کیف پولهای زیاد"},{"title":"BTC Map","description":"مکانهایی را برای گذراندن sats در هر کجا که هستید، مستقیماً از برگه برنامهها پیدا کنید"},{"title":"رفع اشکال و بهبود","description":"2FA و محافظت های پشتیبان قوی تر، دیگر کیف پول بیت کوین و لایت کوین در Connecting، MoonPay در Arbitrum و موارد دیگر گیر نمی کند."}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_fr.json
@@ -1 +1 @@
-[{"title":"Trezor nativement pour Bitcoin","description":"Associez votre appareil et signez des transactions Bitcoin directement dans l'application"},{"title":"Améliorations de Solana et des NFT","description":"Envoyez vos NFT Solana, conservez ceux importés et voyez en un coup d'œil lesquels contiennent ce portefeuille"},{"title":"Améliorations de la synchronisation Monero","description":"La progression de la synchronisation continue pendant que votre portefeuille se réchauffe, afin que vous sachiez toujours où il en est"},{"title":"Corrections de bugs","description":"Synchronisation des contacts, sélection des nœuds, connexion à Cake Pay et bien plus encore, le tout écrasé"}]
\ No newline at end of file
+[{"title":"Zcash sur Ledger","description":"Connectez votre Ledger pour recevoir, protéger et envoyer des ZEC"},{"title":"Prêt pour Zcash NU7","description":"Vos envois et votre blindage ZEC continuent de fonctionner grâce à la mise à niveau du réseau NU7"},{"title":"BitBox02 Nova sur iOS","description":"Utilisez votre BitBox02 Nova sur iPhone et iPad via Bluetooth, avec une vérification du code de couplage pour une connexion sécurisée"},{"title":"Lancement plus rapide","description":"L'application s'ouvre plus rapidement et les portefeuilles se chargent et changent plus rapidement, en particulier sur les téléphones plus anciens ou avec de nombreux portefeuilles."},{"title":"BTC Map","description":"Trouvez des endroits où passer des sats où que vous soyez, directement depuis l'onglet Applications"},{"title":"Corrections de bugs et améliorations","description":"Des protections 2FA et de sauvegarde renforcées, plus de portefeuilles Bitcoin et Litecoin bloqués sur Connecting, MoonPay sur Arbitrum et plus encore"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_gn.json
@@ -1 +1 @@
-[{"title":"Trezor nativamente Bitcoin-pe g̃uarã","description":"Embojoaju nde tembipuru ha efirma umi transacción Bitcoin rehegua pe app-pe voi"},{"title":"Solana ha NFTs Ñemyatyrõ","description":"Emondo nde NFT Solana, eñongatu umi ojeguerúva, ha ehecha peteĩ jesarekópe mávapa oguereko ko billetera"},{"title":"Monero sincronización ñemyatyrõ","description":"Progreso sincronización rehegua osegi omýi nde billetera oñembopiro’y aja, upéicha akóinte reikuaa moõpa oĩ"},{"title":"Umi mba’e’oka ñemyatyrõ","description":"Contacto ñembojoaju, nodo jeporavo, Cake Pay jeike ha hetave, opaite oñembotapykue"}]
\ No newline at end of file
+[{"title":"Zcash Ledger ári.","description":"Embojoaju ne Ledger eguerahauka, eñangareko ha emondo hag̃ua ZEC"},{"title":"Oĩma Zcash NU7-pe g̃uarã","description":"Nde ZEC omondo ha blindaje ombaꞌapo meme NU7 red ñembopyahu rupive"},{"title":"BitBox02 Nova iOS-pe","description":"Eipuru nde BitBox02 Nova iPhone ha iPad-pe Bluetooth rupive, peteĩ jesareko código de emparejamiento reheve peteĩ joaju seguro rehegua"},{"title":"Ñepyrũ pya’eve","description":"Pe aplicación ojeipe’a pya’eve, ha umi billetera okargávo ha oñemoambue pya’eve, ko’ýte umi teléfono itujavévape térã heta billetera reheve"},{"title":"BTC Map","description":"Eheka tenda rehasa hag̃ua sats reimehápe, pestaña Aplicaciones guive"},{"title":"Umi mba’e’oka ñemyatyrõ & ñemyatyrõ","description":"Imbaretevéva 2FA ha protección de copia de seguridad, ndaiporivéima Bitcoin ha Litecoin billetera ojejokóva Connecting-pe, MoonPay Arbitrum-pe ha hetave"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_ha.json
@@ -1 +1 @@
-[{"title":"Trezor na asali don Bitcoin","description":"Haɗa na'urarka kuma sanya hannu kan ma'amalar Bitcoin daidai a cikin ƙa'idar"},{"title":"Solana da NFTs Ingantawa","description":"Aika Solana NFT ɗinku, adana waɗanda aka shigo da su, sannan ku duba ɗaya daga cikin wallet ɗin."},{"title":"Monero sync inganta","description":"Ci gaban daidaitawa yana ci gaba da motsawa yayin da walat ɗin ku ke yin dumi, don haka koyaushe ku san inda yake tsaye"},{"title":"Gyaran kwaro","description":"Daidaita lamba, zaɓin kumburi, shigar da Biyan Kek da ƙari, duk an murƙushe"}]
\ No newline at end of file
+[{"title":"Zcash akan Ledger","description":"Haɗa Ledger ɗin ku don karɓa, garkuwa da aika ZEC"},{"title":"Shirye don Zcash NU7","description":"ZEC ɗinku yana aikawa da garkuwa suna ci gaba da aiki ta hanyar haɓaka hanyar sadarwar NU7"},{"title":"BitBox02 Nova akan iOS","description":"Yi amfani da BitBox02 Nova ɗin ku akan iPhone da iPad akan Bluetooth, tare da rajistan lambar haɗawa don amintaccen haɗi"},{"title":"Saurin Ƙaddamarwa","description":"App ɗin yana buɗewa da sauri, kuma wallet ɗin suna lodawa kuma suna canzawa cikin sauri, musamman akan tsofaffin wayoyi ko masu wallet ɗin da yawa"},{"title":"BTC Map","description":"Nemo wuraren da za ku kashe sats a duk inda kuke, tun daga shafin Apps"},{"title":"Gyaran kwaro & haɓakawa","description":"2FA mai ƙarfi da kariyar ajiya, babu sauran Bitcoin da walat ɗin Litecoin makale akan Haɗawa, MoonPay akan Arbitrum da ƙari."}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_hi.json
@@ -1 +1 @@
-[{"title":"ट्रेज़ोर मूल रूप से बिटकॉइन के लिए है","description":"अपने डिवाइस को पेयर करें और ऐप में ही बिटकॉइन लेनदेन पर हस्ताक्षर करें"},{"title":"सोलाना और एनएफटी सुधार","description":"अपने सोलाना एनएफटी भेजें, आयातित एनएफटी को सहेज कर रखें और एक नज़र में देखें कि इस वॉलेट में कौन से एनएफटी हैं"},{"title":"मोनेरो सिंक में सुधार","description":"जब आपका बटुआ गर्म हो जाता है तो सिंक प्रगति चलती रहती है, इसलिए आप हमेशा जानते हैं कि यह कहां खड़ा है"},{"title":"कंप्यूटर प्रोग्राम या प्रणाली में बग को दूर करना","description":"संपर्क सिंकिंग, नोड चयन, केक पे साइन-इन और बहुत कुछ, सब खत्म हो गया"}]
\ No newline at end of file
+[{"title":"Ledger पर ज़कैश","description":"ZEC प्राप्त करने, ढालने और भेजने के लिए अपना Ledger कनेक्ट करें"},{"title":"Zcash NU7 के लिए तैयार","description":"आपका ZEC भेजता है और परिरक्षण NU7 नेटवर्क अपग्रेड के माध्यम से काम करता रहता है"},{"title":"आईओएस पर BitBox02 Nova","description":"सुरक्षित कनेक्शन के लिए पेयरिंग कोड जांच के साथ ब्लूटूथ पर iPhone और iPad पर अपने BitBox02 Nova का उपयोग करें"},{"title":"तेज़ लॉन्च","description":"ऐप तेजी से खुलता है, और वॉलेट तेजी से लोड और स्विच होते हैं, खासकर पुराने फोन पर या कई वॉलेट के साथ"},{"title":"BTC Map","description":"आप जहां भी हों, sats बिताने के लिए स्थान सीधे ऐप्स टैब से ढूंढें"},{"title":"बग समाधान एवं सुधार","description":"Stronger 2FA and backup protections, no more Bitcoin and Litecoin wallets stuck on Connecting, MoonPay on Arbitrum and more"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_hr.json
@@ -1 +1 @@
-[{"title":"Trezor izvorno za Bitcoin","description":"Uparite svoj uređaj i potpisujte Bitcoin transakcije izravno u aplikaciji"},{"title":"Solana i poboljšanja NFT-a","description":"Pošaljite svoje Solana NFT-ove, sačuvajte uvezene i na prvi pogled pogledajte koje ovaj novčanik ima"},{"title":"Poboljšanja sinkronizacije Monera","description":"Napredak sinkronizacije nastavlja se kretati dok se vaš novčanik zagrijava, tako da uvijek znate gdje stoji"},{"title":"Ispravci grešaka","description":"Sinkronizacija kontakata, odabir čvora, Cake Pay prijava i više, sve zgnječeno"}]
\ No newline at end of file
+[{"title":"Zcash na Ledgeru","description":"Povežite svoj Ledger za primanje, zaštitu i slanje ZEC-a"},{"title":"Spremni za Zcash NU7","description":"Vaš ZEC šalje i zaštita nastavljaju raditi kroz nadogradnju mreže NU7"},{"title":"BitBox02 Nova na iOS-u","description":"Koristite svoj BitBox02 Nova na iPhoneu i iPadu preko Bluetootha, uz provjeru koda za uparivanje za sigurnu vezu"},{"title":"Brže pokretanje","description":"Aplikacija se otvara brže, a novčanici se brže učitavaju i mijenjaju, posebno na starijim telefonima ili s mnogo novčanika"},{"title":"BTC Map","description":"Pronađite mjesta za provesti sats gdje god bili, izravno na kartici Aplikacije"},{"title":"Ispravci programskih pogrešaka i poboljšanja","description":"Jača 2FA i sigurnosna zaštita, nema više Bitcoin i Litecoin novčanika zaglavljenih na Connectingu, MoonPay na Arbitrumu i više"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_hy.json
@@ -1 +1 @@
-[{"title":"Trezor բնիկ համար Bitcoin","description":"Զուգավորեք ձեր սարքը և ստորագրեք Bitcoin գործարքները հենց հավելվածում"},{"title":"Սոլանայի և NFT-ների բարելավումներ","description":"Ուղարկեք ձեր Solana NFT-ները, պահեք ներմուծվածները և մի հայացքով տեսեք, թե որոնք են պահում այս դրամապանակը"},{"title":"Monero-ի համաժամացման բարելավումներ","description":"Համաժամացման առաջընթացը շարունակվում է, մինչ ձեր դրամապանակը տաքանում է, այնպես որ դուք միշտ իմանաք, թե որտեղ է այն կանգնած"},{"title":"Սխալների շտկում","description":"Կոնտակտների համաժամացում, հանգույցների ընտրություն, Cake Pay-ի մուտք և ավելին, բոլորը սեղմված են"}]
\ No newline at end of file
+[{"title":"Zcash Ledger-ում","description":"Միացրեք ձեր Ledger-ը՝ ZEC ստանալու, պաշտպանելու և ուղարկելու համար"},{"title":"Պատրաստ է Zcash NU7-ին","description":"Ձեր ZEC ուղարկումները և պաշտպանությունը շարունակում են աշխատել NU7 ցանցի արդիականացման միջոցով"},{"title":"BitBox02 Nova iOS-ում","description":"Օգտագործեք ձեր BitBox02 Nova-ն iPhone-ում և iPad-ում Bluetooth-ի միջոցով՝ անվտանգ կապի համար զուգավորման կոդի ստուգմամբ։"},{"title":"Ավելի արագ գործարկում","description":"Հավելվածն ավելի արագ է բացվում, և դրամապանակներն ավելի արագ են բեռնվում և փոխարկվում, հատկապես հին հեռախոսներում կամ բազմաթիվ դրամապանակներով"},{"title":"BTC Map","description":"Գտեք sats-ի վայրեր, որտեղ էլ որ լինեք, անմիջապես «Հավելվածներ» ներդիրից"},{"title":"Սխալների շտկումներ և բարելավումներ","description":"Ավելի ուժեղ 2FA և պահուստային պաշտպանություն, այլևս չկա Bitcoin և Litecoin դրամապանակներ, որոնք խրված են Connecting-ում, MoonPay-ը Arbitrum-ում և այլն:"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_id.json
@@ -1 +1 @@
-[{"title":"Trezor aslinya untuk Bitcoin","description":"Pasangkan perangkat Anda dan tanda tangani transaksi Bitcoin langsung di aplikasi"},{"title":"Peningkatan Solana dan NFT","description":"Kirim NFT Solana Anda, simpan NFT yang diimpor, dan lihat sekilas mana yang disimpan dalam dompet ini"},{"title":"Peningkatan sinkronisasi Monero","description":"Kemajuan sinkronisasi terus berjalan saat dompet Anda memanas, sehingga Anda selalu tahu di mana posisinya"},{"title":"Perbaikan bug","description":"Sinkronisasi kontak, pemilihan node, proses masuk Cake Pay, dan banyak lagi, semuanya terhenti"}]
\ No newline at end of file
+[{"title":"Zcash di Ledger","description":"Hubungkan Ledger Anda untuk menerima, melindungi, dan mengirim ZEC"},{"title":"Siap untuk Zcash NU7","description":"Pengiriman dan pelindung ZEC Anda tetap berfungsi melalui peningkatan jaringan NU7"},{"title":"BitBox02 Nova di iOS","description":"Gunakan BitBox02 Nova Anda di iPhone dan iPad melalui Bluetooth, dengan pemeriksaan kode penyandingan untuk koneksi aman"},{"title":"Peluncuran Lebih Cepat","description":"Aplikasi ini terbuka lebih cepat, dan dompet memuat serta beralih lebih cepat, terutama pada ponsel lama atau dengan banyak dompet"},{"title":"BTC Map","description":"Temukan tempat untuk menghabiskan sats di mana pun Anda berada, langsung dari tab Aplikasi"},{"title":"Perbaikan & peningkatan bug","description":"Perlindungan 2FA dan cadangan yang lebih kuat, tidak ada lagi dompet Bitcoin dan Litecoin yang terjebak di Connecting, MoonPay di Arbitrum, dan banyak lagi"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_it.json
@@ -1 +1 @@
-[{"title":"Trezor nativo per Bitcoin","description":"Accoppia il tuo dispositivo e firma le transazioni Bitcoin direttamente nell'app"},{"title":"Miglioramenti di Solana e NFT","description":"Invia i tuoi NFT Solana, mantieni salvati quelli importati e scopri a colpo d'occhio quali sono contenuti in questo portafoglio"},{"title":"Miglioramenti alla sincronizzazione di Monero","description":"I progressi della sincronizzazione continuano a muoversi mentre il tuo portafoglio si riscalda, così sai sempre a che punto è"},{"title":"Correzioni di bug","description":"Sincronizzazione dei contatti, selezione dei nodi, accesso a Cake Pay e altro ancora, tutto schiacciato"}]
\ No newline at end of file
+[{"title":"Zcash su Ledger","description":"Collega il tuo Ledger per ricevere, proteggere e inviare ZEC"},{"title":"Pronto per Zcash NU7","description":"I tuoi invii ZEC e la schermatura continuano a funzionare attraverso l'aggiornamento della rete NU7"},{"title":"BitBox02 Nova su iOS","description":"Usa il tuo BitBox02 Nova su iPhone e iPad tramite Bluetooth, con un controllo del codice di accoppiamento per una connessione sicura"},{"title":"Lancio più veloce","description":"L'app si apre più velocemente e i portafogli si caricano e cambiano più velocemente, soprattutto sui telefoni più vecchi o con molti portafogli"},{"title":"BTC Map","description":"Trova posti dove trascorrere sats ovunque tu sia, direttamente dalla scheda Applicazioni"},{"title":"Correzioni di bug e miglioramenti","description":"2FA e protezioni di backup più forti, niente più portafogli Bitcoin e Litecoin bloccati su Connecting, MoonPay su Arbitrum e altro ancora"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_ja.json
@@ -1 +1 @@
-[{"title":"Trezor はビットコインにネイティブ対応","description":"デバイスをペアリングして、アプリ内で直接ビットコイン取引に署名します"},{"title":"Solana と NFT の改善","description":"Solana NFT を送信し、インポートされた NFT を保存し、このウォレットにどの NFT が保持されているかを一目で確認できます"},{"title":"Monero 同期の改善","description":"ウォレットがウォームアップしている間も同期の進行状況は継続するため、ウォレットの状態を常に把握できます"},{"title":"バグ修正","description":"連絡先の同期、ノードの選択、Cake Pay のサインインなど、すべてが潰されています"}]
\ No newline at end of file
+[{"title":"Ledger の Zcash","description":"Ledger を接続して ZEC を受信、シールド、送信します"},{"title":"Zcash NU7 の準備完了","description":"ZEC の送信とシールドは、NU7 ネットワークのアップグレード後も機能し続けます"},{"title":"iOS 上の BitBox02 Nova","description":"安全な接続のためのペアリング コード チェックを使用して、Bluetooth 経由で iPhone および iPad で BitBox02 Nova を使用します。"},{"title":"起動の高速化","description":"特に古い携帯電話や多くのウォレットを使用している場合、アプリがより速く開き、ウォレットの読み込みと切り替えがより速くなります。"},{"title":"BTC Map","description":"アプリタブから直接、どこにいても sats を過ごせる場所を見つけてください"},{"title":"バグ修正と改善","description":"より強力な 2FA とバックアップ保護、接続中にビットコインやライトコインのウォレットがスタックすることはもうありません、Arbitrum の MoonPay など"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_ko.json
@@ -1 +1 @@
-[{"title":"기본적으로 Bitcoin용 Trezor","description":"기기를 페어링하고 앱에서 바로 비트코인 거래에 서명하세요."},{"title":"솔라나 및 NFT 개선","description":"솔라나 NFT를 보내고, 가져온 NFT를 저장하고, 이 지갑에 어떤 NFT가 들어 있는지 한눈에 확인하세요"},{"title":"모네로 동기화 개선","description":"지갑이 준비되는 동안 동기화 진행이 계속 진행되므로 항상 현재 상태를 알 수 있습니다."},{"title":"버그 수정","description":"연락처 동기화, 노드 선택, Cake Pay 로그인 등이 모두 중단되었습니다."}]
\ No newline at end of file
+[{"title":"Ledger의 Zcash","description":"Ledger를 연결하여 ZEC를 수신, 보호 및 전송하세요."},{"title":"Zcash NU7을 위한 준비","description":"ZEC 전송 및 차폐는 NU7 네트워크 업그레이드를 통해 계속 작동합니다."},{"title":"iOS의 BitBox02 Nova","description":"보안 연결을 위해 페어링 코드 확인을 통해 Bluetooth를 통해 iPhone 및 iPad에서 BitBox02 Nova를 사용하세요."},{"title":"더 빠른 실행","description":"특히 구형 휴대폰이나 지갑이 많은 경우 앱이 더 빨리 열리고 지갑이 더 빠르게 로드 및 전환됩니다."},{"title":"BTC Map","description":"어디에 있든 앱 탭에서 바로 sats를 보낼 수 있는 장소를 찾아보세요."},{"title":"버그 수정 및 개선","description":"더 강력한 2FA 및 백업 보호, 더 이상 Connecting에 갇히지 않는 Bitcoin 및 Litecoin 지갑, Arbitrum의 MoonPay 등"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_my.json
@@ -1 +1 @@
-[{"title":"Bitcoin အတွက် မူရင်း Trezor","description":"သင့်စက်ကို တွဲချိတ်ပြီး အက်ပ်တွင် Bitcoin ငွေပေးငွေယူများကို လက်မှတ်ထိုးပါ။"},{"title":"Solana နှင့် NFTs တိုးတက်မှုများ","description":"သင်၏ Solana NFTs များကို ပေးပို့ပါ၊ တင်သွင်းထားသည့်အရာများကို သိမ်းဆည်းထားပါ၊ ဤပိုက်ဆံအိတ်တွင် မည်သည့်အရာများ ကိုင်ဆောင်ထားသည်ကို တစ်ချက်ကြည့်လိုက်ပါ။"},{"title":"Monero စင့်ခ်လုပ်ခြင်း တိုးတက်မှု","description":"သင့်ပိုက်ဆံအိတ် ပူနွေးလာချိန်တွင် စင့်ခ်လုပ်ဆောင်မှုသည် ဆက်လက်ရွေ့လျားနေသဖြင့် ၎င်းသည် မည်သည့်နေရာတွင် ရှိနေသည်ကို သင်အမြဲသိပါသည်။"},{"title":"ချွတ်ယွင်းချက်ပြင်ဆင်မှုများ","description":"အဆက်အသွယ်စင့်ခ်လုပ်ခြင်း၊ node ရွေးချယ်ခြင်း၊ Cake Pay လက်မှတ်ထိုးဝင်ခြင်းနှင့် အခြားအရာများအားလုံးကို ဖြိုခွဲလိုက်ပါပြီ။"}]
\ No newline at end of file
+[{"title":"Ledger တွင် Zcash","description":"ZEC ကိုလက်ခံရန်၊ အကာအကွယ်နှင့် ပေးပို့ရန် သင်၏ Ledger ကို ချိတ်ဆက်ပါ။"},{"title":"Zcash NU7 အတွက် အဆင်သင့်ဖြစ်နေပါပြီ။","description":"သင်၏ ZEC သည် NU7 ကွန်ရက် အဆင့်မြှင့်တင်မှုမှတစ်ဆင့် ဆက်လက်လုပ်ဆောင်နေပါသည်။"},{"title":"iOS တွင် BitBox02 Nova","description":"လုံခြုံသောချိတ်ဆက်မှုအတွက် ချိတ်ဆက်မှုကုဒ်ကို စစ်ဆေးခြင်းဖြင့် သင်၏ BitBox02 Nova ကို Bluetooth ဖြင့် iPhone နှင့် iPad တွင် အသုံးပြုပါ။"},{"title":"ပိုမိုမြန်ဆန်စွာ ပစ်လွှတ်ခြင်း။","description":"အပလီကေးရှင်းသည် ပိုမိုမြန်ဆန်စွာဖွင့်နိုင်ပြီး အထူးသဖြင့် ဖုန်းအဟောင်းများတွင် သို့မဟုတ် ပိုက်ဆံအိတ်များစွာဖြင့် ပိုက်ဆံအိတ်များတင်ကာ ကူးပြောင်းမှု ပိုမိုမြန်ဆန်သည်။"},{"title":"BTC Map","description":"သင် ဘယ်နေရာရောက်ရောက် အက်ပ်များတက်ဘ်မှနေ၍ sats သုံးစွဲရန် နေရာများကို ရှာပါ။"},{"title":"ချွတ်ယွင်းချက်ပြင်ဆင်မှုများနှင့် မြှင့်တင်မှုများ","description":"ပိုမိုအားကောင်းသော 2FA နှင့် အရန်ကာကွယ်မှုများ၊ Connecting တွင် ပိတ်မိနေသည့် Bitcoin နှင့် Litecoin ပိုက်ဆံအိတ်များ၊ Arbitrum ရှိ MoonPay နှင့် အခြားအရာများ"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_nl.json
@@ -1 +1 @@
-[{"title":"Trezor oorspronkelijk voor Bitcoin","description":"Koppel uw apparaat en onderteken Bitcoin-transacties rechtstreeks in de app"},{"title":"Verbeteringen aan Solana en NFT's","description":"Verstuur uw Solana NFT's, bewaar geïmporteerde NFT's en zie in één oogopslag welke deze portemonnee bevat"},{"title":"Verbeteringen voor de synchronisatie van Monero","description":"De voortgang van de synchronisatie blijft in beweging terwijl uw portemonnee opwarmt, zodat u altijd weet waar hij aan toe is"},{"title":"Bugfixes","description":"Contactsynchronisatie, knooppuntselectie, aanmelden bij Cake Pay en meer, allemaal platgedrukt"}]
\ No newline at end of file
+[{"title":"Zcash op Ledger","description":"Sluit uw Ledger aan om ZEC te ontvangen, af te schermen en te verzenden"},{"title":"Klaar voor Zcash NU7","description":"Je ZEC-verzending en afscherming blijven werken via de NU7-netwerkupgrade"},{"title":"BitBox02 Nova op iOS","description":"Gebruik uw BitBox02 Nova op iPhone en iPad via Bluetooth, met een koppelingscodecontrole voor een veilige verbinding"},{"title":"Snellere lancering","description":"De app opent sneller en portemonnees worden sneller geladen en gewisseld, vooral op oudere telefoons of met veel portemonnees"},{"title":"BTC Map","description":"Vind plekken waar je sats kunt doorbrengen, waar je ook bent, rechtstreeks vanaf het tabblad Apps"},{"title":"Bugfixes en verbeteringen","description":"Sterkere 2FA- en back-upbeveiligingen, geen Bitcoin- en Litecoin-wallets meer die vastlopen op Connecting, MoonPay op Arbitrum en meer"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_pl.json
@@ -1 +1 @@
-[{"title":"Trezor natywnie dla Bitcoin","description":"Sparuj swoje urządzenie i podpisuj transakcje Bitcoin bezpośrednio w aplikacji"},{"title":"Ulepszenia Solany i NFT","description":"Wysyłaj swoje Solana NFT, przechowuj zaimportowane i od razu zobacz, które z nich przechowuje ten portfel"},{"title":"Ulepszenia synchronizacji Monero","description":"Postęp synchronizacji stale się zmienia, podczas gdy Twój portfel się nagrzewa, więc zawsze wiesz, gdzie się znajduje"},{"title":"Poprawki błędów","description":"Synchronizacja kontaktów, wybór węzła, logowanie do Cake Pay i wiele więcej – wszystko to zmiażdżone"}]
\ No newline at end of file
+[{"title":"Zcash na Ledgerze","description":"Podłącz swój Ledger, aby odbierać, chronić i wysyłać ZEC"},{"title":"Gotowy na Zcash NU7","description":"Twoje wysyłanie i ekranowanie ZEC nadal działa poprzez aktualizację sieci NU7"},{"title":"BitBox02 Nova na iOS","description":"Używaj BitBox02 Nova na iPhonie i iPadzie przez Bluetooth, sprawdzając kod parowania, aby zapewnić bezpieczne połączenie"},{"title":"Szybsze uruchamianie","description":"Aplikacja otwiera się szybciej, a portfele ładują się i przełączają szybciej, szczególnie na starszych telefonach lub z wieloma portfelami"},{"title":"BTC Map","description":"Znajdź miejsca, w których możesz spędzić sats, gdziekolwiek jesteś, bezpośrednio z karty Aplikacje"},{"title":"Poprawki błędów i ulepszenia","description":"Silniejsze zabezpieczenia 2FA i kopie zapasowe, koniec z portfelami Bitcoin i Litecoin utkniętymi na Connecting, MoonPay na Arbitrum i nie tylko"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_pt.json
@@ -1 +1 @@
-[{"title":"Trezor nativamente para Bitcoin","description":"Emparelhe seu dispositivo e assine transações Bitcoin diretamente no aplicativo"},{"title":"Melhorias em Solana e NFTs","description":"Envie seus NFTs Solana, mantenha salvos os importados e veja rapidamente quais esta carteira contém"},{"title":"Melhorias na sincronização do Monero","description":"O progresso da sincronização continua avançando enquanto sua carteira aquece, para que você sempre saiba onde ela está"},{"title":"Correções de bugs","description":"Sincronização de contatos, seleção de nós, login no Cake Pay e muito mais, tudo esmagado"}]
\ No newline at end of file
+[{"title":"Zcash em Ledger","description":"Conecte seu Ledger para receber, proteger e enviar ZEC"},{"title":"Pronto para Zcash NU7","description":"Seus envios e blindagem ZEC continuam funcionando durante a atualização da rede NU7"},{"title":"BitBox02 Nova no iOS","description":"Use seu BitBox02 Nova no iPhone e iPad via Bluetooth, com uma verificação de código de emparelhamento para uma conexão segura"},{"title":"Lançamento mais rápido","description":"O aplicativo abre mais rápido e as carteiras carregam e trocam mais rapidamente, especialmente em telefones mais antigos ou com muitas carteiras"},{"title":"BTC Map","description":"Encontre lugares para passar sats onde quer que você esteja, diretamente na guia Aplicativos"},{"title":"Correções de bugs e melhorias","description":"Proteções 2FA e de backup mais fortes, chega de carteiras Bitcoin e Litecoin presas no Connecting, MoonPay no Arbitrum e muito mais"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_ru.json
@@ -1 +1 @@
-[{"title":"Trezor изначально для биткойнов","description":"Подключите свое устройство и подпишите транзакции Bitcoin прямо в приложении."},{"title":"Улучшения Соланы и NFT","description":"Отправляйте свои NFT Solana, сохраняйте импортированные и сразу смотрите, какие из них хранятся в этом кошельке."},{"title":"Улучшения синхронизации Monero","description":"Процесс синхронизации продолжается, пока ваш кошелек нагревается, поэтому вы всегда знаете, где он находится."},{"title":"Исправления ошибок","description":"Синхронизация контактов, выбор узла, вход в систему Cake Pay и многое другое — все раздавлено"}]
\ No newline at end of file
+[{"title":"Zcash в Ledger","description":"Подключите свой Ledger, чтобы получать, защищать и отправлять ZEC"},{"title":"Готов к Zcash NU7","description":"Отправки и экранирование вашего ZEC продолжают работать после обновления сети NU7."},{"title":"BitBox02 Nova на iOS","description":"Используйте BitBox02 Nova на iPhone и iPad через Bluetooth с проверкой кода сопряжения для безопасного соединения."},{"title":"Более быстрый запуск","description":"Приложение открывается быстрее, а кошельки загружаются и переключаются быстрее, особенно на старых телефонах или с большим количеством кошельков."},{"title":"BTC Map","description":"Найдите места, где можно потратить sats, где бы вы ни находились, прямо на вкладке «Приложения»."},{"title":"Исправления ошибок и улучшения","description":"Более надежная защита 2FA и резервного копирования, кошельки Bitcoin и Litecoin больше не зависают при подключении, MoonPay на Arbitrum и т. д."}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_th.json
@@ -1 +1 @@
-[{"title":"Trezor โดยกำเนิดสำหรับ Bitcoin","description":"จับคู่อุปกรณ์ของคุณและลงนามธุรกรรม Bitcoin ในแอป"},{"title":"การปรับปรุง Solana และ NFT","description":"ส่ง Solana NFT ของคุณ เก็บรายการที่นำเข้าบันทึกไว้ และดูได้อย่างรวดเร็วว่ากระเป๋าสตางค์นี้เก็บรายการใดบ้าง"},{"title":"การปรับปรุงการซิงค์ Monero","description":"ความคืบหน้าในการซิงค์จะดำเนินต่อไปในขณะที่กระเป๋าเงินของคุณอุ่นขึ้น ดังนั้นคุณจะรู้อยู่เสมอว่ามันอยู่ที่ไหน"},{"title":"แก้ไขข้อบกพร่อง","description":"การซิงค์ผู้ติดต่อ การเลือกโหนด การลงชื่อเข้าใช้ Cake Pay และอื่นๆ ทั้งหมดถูกแบน"}]
\ No newline at end of file
+[{"title":"Zcash บน Ledger","description":"เชื่อมต่อ Ledger ของคุณเพื่อรับ ป้องกัน และส่ง ZEC"},{"title":"พร้อมสำหรับ Zcash NU7","description":"ZEC ของคุณส่งและป้องกันให้ทำงานต่อไปผ่านการอัปเกรดเครือข่าย NU7"},{"title":"BitBox02 Nova บน iOS","description":"ใช้ BitBox02 Nova ของคุณบน iPhone และ iPad ผ่าน Bluetooth พร้อมตรวจสอบรหัสการจับคู่เพื่อการเชื่อมต่อที่ปลอดภัย"},{"title":"เปิดตัวเร็วขึ้น","description":"แอปเปิดเร็วขึ้น และกระเป๋าเงินก็โหลดและสลับเร็วขึ้น โดยเฉพาะบนโทรศัพท์รุ่นเก่าหรือมีกระเป๋าเงินจำนวนมาก"},{"title":"BTC Map","description":"ค้นหาสถานที่ที่จะใช้จ่าย sats ไม่ว่าคุณจะอยู่ที่ไหนจากแท็บแอพ"},{"title":"การแก้ไขข้อบกพร่องและการปรับปรุง","description":"การป้องกัน 2FA และการสำรองข้อมูลที่แข็งแกร่งยิ่งขึ้น ไม่มีกระเป๋าเงิน Bitcoin และ Litecoin ที่ติดอยู่กับการเชื่อมต่ออีกต่อไป MoonPay บน Arbitrum และอีกมากมาย"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_tl.json
@@ -1 +1 @@
-[{"title":"Trezor natively para sa Bitcoin","description":"Ipares ang iyong device at lagdaan ang mga transaksyon sa Bitcoin sa app mismo"},{"title":"Mga Pagpapabuti ng Solana at NFT","description":"Ipadala ang iyong mga Solana NFT, panatilihing naka-save ang mga na-import, at tingnan sa isang sulyap kung alin ang hawak ng wallet na ito"},{"title":"Mga pagpapabuti sa pag-sync ng Monero","description":"Patuloy na gumagalaw ang pag-unlad ng pag-sync habang umiinit ang iyong wallet, para lagi mong alam kung saan ito nakatayo"},{"title":"Mga pag-aayos ng bug","description":"Ang pag-sync ng contact, pagpili ng node, pag-sign in sa Cake Pay at higit pa, lahat ay lapirat"}]
\ No newline at end of file
+[{"title":"Zcash sa Ledger","description":"Ikonekta ang iyong Ledger para makatanggap, maprotektahan at magpadala ng ZEC"},{"title":"Handa na para sa Zcash NU7","description":"Ang iyong ZEC ay nagpapadala at nagsasanggalang ay patuloy na gumagana sa pamamagitan ng NU7 network upgrade"},{"title":"BitBox02 Nova sa iOS","description":"Gamitin ang iyong BitBox02 Nova sa iPhone at iPad sa Bluetooth, na may pagpapares ng code check para sa secure na koneksyon"},{"title":"Mas Mabilis na Paglunsad","description":"Ang app ay nagbubukas nang mas mabilis, at ang mga wallet ay naglo-load at lumilipat nang mas mabilis, lalo na sa mas lumang mga telepono o may maraming mga wallet"},{"title":"BTC Map","description":"Maghanap ng mga lugar na gagastusin sats nasaan ka man, mula mismo sa tab na Apps"},{"title":"Mga pag-aayos at pagpapahusay ng bug","description":"Mas malakas na 2FA at backup na mga proteksyon, wala nang Bitcoin at Litecoin na mga wallet na natigil sa Connecting, MoonPay sa Arbitrum at higit pa"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_tr.json
@@ -1 +1 @@
-[{"title":"Bitcoin için yerel olarak Trezor","description":"Cihazınızı eşleştirin ve Bitcoin işlemlerini doğrudan uygulamada imzalayın"},{"title":"Solana ve NFT İyileştirmeleri","description":"Solana NFT'lerinizi gönderin, içe aktarılanları saklayın ve bu cüzdanda hangilerinin bulunduğunu bir bakışta görün"},{"title":"Monero senkronizasyon iyileştirmeleri","description":"Cüzdanınız ısınırken senkronizasyon ilerlemesi devam eder, böylece nerede olduğunu her zaman bilirsiniz"},{"title":"Hata düzeltmeleri","description":"Kişi senkronizasyonu, düğüm seçimi, Cake Pay'de oturum açma ve daha fazlası, hepsi engellendi"}]
\ No newline at end of file
+[{"title":"Ledger'da Zcash","description":"ZEC almak, korumak ve göndermek için Ledger'ınızı bağlayın"},{"title":"Zcash NU7'ye hazır","description":"ZEC gönderimleriniz ve korumanız, NU7 ağ yükseltmesi aracılığıyla çalışmaya devam eder"},{"title":"iOS'ta BitBox02 Nova","description":"Güvenli bir bağlantı için eşleştirme kodu kontrolüyle BitBox02 Nova'nızı Bluetooth üzerinden iPhone ve iPad'de kullanın"},{"title":"Daha Hızlı Başlatma","description":"Özellikle eski telefonlarda veya çok sayıda cüzdanda uygulama daha hızlı açılır ve cüzdanlar daha hızlı yüklenir ve geçiş yapılır"},{"title":"BTC Map","description":"Nerede olursanız olun, doğrudan Uygulamalar sekmesinden sats harcayabileceğiniz yerleri bulun"},{"title":"Hata düzeltmeleri ve iyileştirmeler","description":"Daha güçlü 2FA ve yedekleme korumaları, Connecting'de artık Bitcoin ve Litecoin cüzdanları, Arbitrum'da MoonPay ve daha fazlası yok"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_uk.json
@@ -1 +1 @@
-[{"title":"Trezor спочатку для Bitcoin","description":"Підключіть свій пристрій і підписуйте транзакції Bitcoin прямо в додатку"},{"title":"Покращення Solana та NFT","description":"Надсилайте свої NFT Solana, зберігайте імпортовані та одразу дивіться, які з них зберігає цей гаманець"},{"title":"Покращення синхронізації Monero","description":"Процес синхронізації продовжується, поки ваш гаманець розігрівається, тож ви завжди знаєте, де він стоїть"},{"title":"Виправлення помилок","description":"Синхронізація контактів, вибір вузла, вхід у систему Cake Pay тощо – усе зіпсовано"}]
\ No newline at end of file
+[{"title":"Zcash на Ledger","description":"Підключіть Ledger, щоб отримувати, екранувати та надсилати ZEC"},{"title":"Готовий до Zcash NU7","description":"Ваш ZEC посилає та екранує продовжують працювати через оновлення мережі NU7"},{"title":"BitBox02 Nova на iOS","description":"Використовуйте BitBox02 Nova на iPhone та iPad через Bluetooth із перевіркою коду сполучення для безпечного з’єднання"},{"title":"Швидший запуск","description":"Програма відкривається швидше, а гаманці завантажуються та перемикаються швидше, особливо на старих телефонах або з великою кількістю гаманців"},{"title":"BTC Map","description":"Знаходьте місця, де можна витратити sats, де б ви не були, просто на вкладці \"Програми\"."},{"title":"Виправлення помилок і покращення","description":"Потужніше 2FA та захист від резервного копіювання, більше немає гаманців Bitcoin і Litecoin, які застрягли на Connecting, MoonPay на Arbitrum тощо"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_ur.json
@@ -1 +1 @@
-[{"title":"Trezor مقامی طور پر Bitcoin کے لیے","description":"اپنے آلے کو جوڑیں اور ایپ میں ہی بٹ کوائن کے لین دین پر دستخط کریں۔"},{"title":"سولانا اور NFTs میں بہتری","description":"اپنے سولانا NFTs بھیجیں، درآمد شدہ کو محفوظ رکھیں، اور ایک نظر میں دیکھیں کہ اس پرس میں کون سا ہے"},{"title":"Monero مطابقت پذیری میں بہتری","description":"آپ کے بٹوے کے گرم ہونے کے دوران مطابقت پذیری کی پیشرفت جاری رہتی ہے، لہذا آپ کو ہمیشہ معلوم ہوتا ہے کہ یہ کہاں کھڑا ہے۔"},{"title":"بگ کی اصلاحات","description":"رابطہ کی مطابقت پذیری، نوڈ کا انتخاب، کیک پے سائن ان اور بہت کچھ، سب کو کچل دیا گیا۔"}]
\ No newline at end of file
+[{"title":"Ledger کو Zcash","description":"ZEC وصول کرنے، شیلڈ کرنے اور بھیجنے کے لیے اپنے Ledger کو جوڑیں۔"},{"title":"Zcash NU7 کے لیے تیار ہیں۔","description":"NU7 نیٹ ورک اپ گریڈ کے ذریعے آپ کا ZEC بھیجتا ہے اور شیلڈنگ کام کرتی رہتی ہے۔"},{"title":"iOS پر BitBox02 Nova","description":"آئی فون اور آئی پیڈ پر بلوٹوتھ پر اپنا BitBox02 Nova استعمال کریں، جوڑا بنانے والے کوڈ کے ساتھ محفوظ کنکشن کے لیے چیک کریں"},{"title":"تیز تر لانچ","description":"ایپ تیزی سے کھلتی ہے، اور بٹوے تیزی سے لوڈ اور سوئچ ہوتے ہیں، خاص طور پر پرانے فونز پر یا بہت سے بٹوے کے ساتھ"},{"title":"BTC Map","description":"آپ جہاں کہیں بھی ہوں، سیدھا Apps ٹیب سے sats خرچ کرنے کے لیے جگہیں تلاش کریں۔"},{"title":"بگ کی اصلاحات اور بہتری","description":"مضبوط 2FA اور بیک اپ تحفظات، مزید Bitcoin اور Litecoin والیٹس کنیکٹنگ پر نہیں پھنسیں، Arbitrum پر MoonPay اور مزید"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_vi.json
@@ -1 +1 @@
-[{"title":"Trezor vốn dành cho Bitcoin","description":"Ghép nối thiết bị của bạn và ký các giao dịch Bitcoin ngay trong ứng dụng"},{"title":"Cải tiến Solana và NFT","description":"Gửi NFT Solana của bạn, lưu những cái đã nhập và xem nhanh những cái nào trong ví này chứa"},{"title":"Cải tiến đồng bộ hóa Monero","description":"Tiến trình đồng bộ hóa tiếp tục di chuyển trong khi ví của bạn ấm lên, vì vậy bạn luôn biết vị trí của nó"},{"title":"Sửa lỗi","description":"Đồng bộ hóa liên hệ, chọn nút, đăng nhập Cake Pay và hơn thế nữa, tất cả đều bị nén"}]
\ No newline at end of file
+[{"title":"Zcash trên Ledger","description":"Kết nối Ledger của bạn để nhận, bảo vệ và gửi ZEC"},{"title":"Sẵn sàng cho Zcash NU7","description":"ZEC của bạn gửi và bảo vệ tiếp tục hoạt động thông qua nâng cấp mạng NU7"},{"title":"BitBox02 Nova trên iOS","description":"Sử dụng BitBox02 Nova của bạn trên iPhone và iPad qua Bluetooth, bằng cách kiểm tra mã ghép nối để có kết nối an toàn"},{"title":"Khởi chạy nhanh hơn","description":"Ứng dụng mở nhanh hơn, đồng thời tải và chuyển đổi ví nhanh hơn, đặc biệt là trên điện thoại cũ hoặc có nhiều ví"},{"title":"BTC Map","description":"Tìm địa điểm để sử dụng sats mọi lúc mọi nơi, ngay từ tab Ứng dụng"},{"title":"Sửa lỗi và cải tiến","description":"Bảo vệ 2FA và sao lưu mạnh mẽ hơn, không còn ví Bitcoin và Litecoin bị kẹt khi Kết nối, MoonPay trên Arbitrum, v.v."}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_yo.json
@@ -1 +1 @@
-[{"title":"Trezor abinibi fun Bitcoin","description":"So ẹrọ rẹ pọ ki o forukọsilẹ awọn iṣowo Bitcoin ni ọtun ninu ohun elo naa"},{"title":"Solana ati NFTs Awọn ilọsiwaju","description":"Firanṣẹ awọn NFT Solana rẹ, tọju awọn ti a ko wọle si, ki o wo ni iwo kan kini awọn ti apamọwọ yii mu"},{"title":"Monero ìsiṣẹpọ","description":"Ilọsiwaju mimuṣiṣẹpọ n tẹsiwaju lakoko ti apamọwọ rẹ n gbona, nitorinaa o mọ ibiti o duro nigbagbogbo"},{"title":"Awọn atunṣe kokoro","description":"Imuṣiṣẹpọ olubasọrọ, yiyan ipade, Wọle isanwo Cake Pay ati diẹ sii, gbogbo wọn ti fọ"}]
\ No newline at end of file
+[{"title":"Zcash lori Ledger","description":"So Ledger rẹ pọ lati gba, daabobo ati firanṣẹ ZEC"},{"title":"Ṣetan fun Zcash NU7","description":"ZEC rẹ firanṣẹ ati idabobo tẹsiwaju ṣiṣẹ nipasẹ igbesoke nẹtiwọọki NU7"},{"title":"BitBox02 Nova lori iOS","description":"Lo BitBox02 Nova rẹ lori iPhone ati iPad lori Bluetooth, pẹlu ayẹwo koodu sisopọ fun asopọ to ni aabo"},{"title":"Yiyara Ifilọlẹ","description":"Ìfilọlẹ naa yoo yara sii, ati fifuye awọn apamọwọ ki o yipada ni iyara, paapaa lori awọn foonu agbalagba tabi pẹlu ọpọlọpọ awọn apamọwọ"},{"title":"BTC Map","description":"Wa awọn aaye lati lo sats nibikibi ti o ba wa, lati awọn Apps taabu"},{"title":"Awọn atunṣe kokoro & awọn ilọsiwaju","description":"2FA ti o lagbara ati awọn aabo afẹyinti, ko si diẹ sii Bitcoin ati awọn apamọwọ Litecoin ti o di lori Sisopọ, MoonPay lori Arbitrum ati diẹ sii"}]
\ No newline at end of file
### assets/new-ui/changelog/text/changelog_zh-cn.json
@@ -1 +1 @@
-[{"title":"Trezor 原生适用于比特币","description":"配对您的设备并直接在应用程序中签署比特币交易"},{"title":"Solana 和 NFT 的改进","description":"发送您的 Solana NFT,保存导入的 NFT,并一目了然地查看该钱包包含哪些 NFT"},{"title":"门罗币同步改进","description":"当您的钱包热身时,同步进度会不断变化,因此您始终知道进展情况"},{"title":"错误修复","description":"联系人同步、节点选择、Cake Pay 登录等全部被压缩"}]
\ No newline at end of file
+[{"title":"Ledger 上的 Zcash","description":"连接您的 Ledger 以接收、屏蔽和发送 ZEC"},{"title":"准备好 Zcash NU7","description":"您的ZEC发送和屏蔽在NU7网络升级后继续工作"},{"title":"iOS 上的 BitBox02 Nova","description":"通过蓝牙在 iPhone 和 iPad 上使用 BitBox02 Nova,并检查配对码以确保安全连接"},{"title":"更快的启动","description":"应用程序打开速度更快,钱包加载和切换速度更快,尤其是在旧手机或有许多钱包的情况下"},{"title":"BTC Map","description":"无论您身在何处,都可以直接从“应用程序”选项卡中查找消费 sats 的场所"},{"title":"错误修复和改进","description":"更强大的 2FA 和备份保护,不再有比特币和莱特币钱包卡在 Connecting、MoonPay on Arbitrum 等上"}]
\ No newline at end of file
### assets/new-ui/changelog/text/monerocom_changelog_en.json
@@ -0,0 +1,10 @@
+[
+ {
+ "title": "Faster Launch",
+ "description": "The app opens quicker and switches wallets faster, especially on older phones or with many wallets"
+ },
+ {
+ "title": "Bug fixes & improvements",
+ "description": "Stronger 2FA and backup protections, more reliable wallet deletion, steadier price charts over Tor and more"
+ }
+]
### assets/node_list.yml
@@ -7,8 +7,9 @@
useSSL: true
isEnabledForAutoSwitching: true
-
- label: "Cake Wallet (Onion)"
- uri: cakexmrl7bonq7ovjka5kuwuyd3f7qnkz6z6s6dmsy3uckwra7bvggyd.onion:18081
+ label: "Cake Wallet (Tor)"
+ uri: cakexmrkbd7ptshw7vfzhzqgg77xgeavdrxm6zbu57lppfkj3fczbrqd.onion:18081
+ isOfficial: true
-
label: "Seth For Privacy"
uri: node.sethforprivacy.com:443
### assets/robinhood_node_list.yml
@@ -0,0 +1,23 @@
+-
+ uri: robinhood-rpc.publicnode.com
+ isDefault: true
+ useSSL: true
+ isEnabledForAutoSwitching: true
+ label: "PublicNode"
+-
+ uri: robinhood.nownodes.io
+ useSSL: true
+ isEnabledForAutoSwitching: true
+ label: "NOWNodes"
+-
+ uri: rpc.mainnet.chain.robinhood.com
+ useSSL: true
+ isEnabledForAutoSwitching: true
+ label: "Robinhood"
+-
+ uri: robinhood-mainnet.g.alchemy.com
+ path: /v2
+ useSSL: true
+ isDefault: false
+ isEnabledForAutoSwitching: true
+ label: "Alchemy"
### assets/zcash_node_list.yml
@@ -11,10 +11,7 @@
isEnabledForAutoSwitching: true
label: "Zec.rocks"
-
- uri: 2c4whzg26j6hgjh22rxynj3oig4gm22ga7x74weclujywxye23v3u5id.onion:9067
+ uri: cakezecgh6enylxz3yya52pu4rq3bojy7zfhvnegqkq4qbbpzderjiqd.onion:9067
useSSL: false
- label: "Cake Wallet (Tor)"
--
- uri: bvp2l442g5ogma7rywzahm7eqyhpp3g26n3gvvxeioqn5csio2ir6myd.onion:9067
- useSSL: false
- label: "Cake Wallet (Tor #2)"
\ No newline at end of file
+ isOfficial: true
+ label: "Cake Wallet (Tor)"
\ No newline at end of file
### cakewallet.bat
@@ -1,5 +1,5 @@
@echo off
-set cw_win_app_config=--monero --bitcoin --ethereum --polygon --nano --bitcoinCash --solana --tron --dogecoin --base --arbitrum --bsc
+set cw_win_app_config=--monero --bitcoin --ethereum --polygon --nano --bitcoinCash --solana --tron --dogecoin --base --arbitrum --bsc --robinhood
set cw_root=%cd%
set cw_archive_name=Cake Wallet.zip
set cw_archive_path=%cw_root%\%cw_archive_name%
### cargokit_options.yaml
@@ -0,0 +1 @@
+use_precompiled_binaries: false
\ No newline at end of file
### compile_graphics.sh
@@ -9,12 +9,17 @@
src="res/pictures"
dst="assets/new-ui"
+tmp="$(mktemp -d)"
+trap 'rm -rf "$tmp"' EXIT
+
while read -r dir; do
rel="${dir#"$src"}"
outdir="$dst$rel"
+ indir="$(mktemp -d "$tmp/XXXXXX")"
mkdir -p "$outdir"
- dart run vector_graphics_compiler --input-dir "$dir" --out-dir "$outdir" >/dev/null &
+ find "$dir" -maxdepth 1 -type f -name '*.svg' -exec cp {} "$indir" ';'
+ dart run vector_graphics_compiler --input-dir "$indir" --out-dir "$outdir" >/dev/null &
done < <(find "$src" -type d)
wait
\ No newline at end of file
### cw_bitcoin/lib/bitcoin_address_record.dart
@@ -9,6 +9,7 @@ abstract class BaseBitcoinAddressRecord {
BaseBitcoinAddressRecord(
this.address, {
required this.index,
+ this.accountIndex = 0,
this.isHidden = false,
this.isLegacyDerivation = false,
int txCount = 0,
@@ -29,6 +30,7 @@ abstract class BaseBitcoinAddressRecord {
bool isHidden;
bool isLegacyDerivation;
final int index;
+ final int accountIndex;
int _txCount;
int _balance;
String _name;
@@ -63,7 +65,9 @@ class BitcoinAddressRecord extends BaseBitcoinAddressRecord {
BitcoinAddressRecord(
super.address, {
required super.index,
+ super.accountIndex = 0,
super.isHidden = false,
+ this.isHiddenChecked = false,
super.isLegacyDerivation = false,
super.txCount = 0,
super.balance = 0,
@@ -105,7 +109,9 @@ class BitcoinAddressRecord extends BaseBitcoinAddressRecord {
return BitcoinAddressRecord(
decoded['address'] as String,
index: decoded['index'] as int,
+ accountIndex: decoded['accountIndex'] as int? ?? 0,
isHidden: decoded['isHidden'] as bool? ?? false,
+ isHiddenChecked: decoded['isHiddenChecked'] as bool? ?? false,
isLegacyDerivation: parsedIsLegacy,
isUsed: decoded['isUsed'] as bool? ?? false,
txCount: decoded['txCount'] as int? ?? 0,
@@ -117,6 +123,10 @@ class BitcoinAddressRecord extends BaseBitcoinAddressRecord {
);
}
+ /// Whether [isHidden] has been checked against the wallet's keys. Records created from the
+ /// wallet's own keys are correct by construction; older ones are checked once on wallet open.
+ bool isHiddenChecked;
+
String? scriptHash;
static int _purposeForType(BitcoinAddressType type) {
@@ -162,7 +172,8 @@ class BitcoinAddressRecord extends BaseBitcoinAddressRecord {
final coinType = _coinTypeForNetwork();
final purpose = _purposeForType(type);
- final accountPath = isLegacyDerivation ? electrum_path : "m/$purpose'/$coinType'/0'";
+ final accountPath =
+ isLegacyDerivation ? electrum_path : "m/$purpose'/$coinType'/$accountIndex'";
final chain = isHidden ? 1 : 0;
return "$accountPath/$chain/$index";
@@ -172,7 +183,9 @@ class BitcoinAddressRecord extends BaseBitcoinAddressRecord {
String toJSON() => json.encode({
'address': address,
'index': index,
+ 'accountIndex': accountIndex,
'isHidden': isHidden,
+ 'isHiddenChecked': isHiddenChecked,
'isLegacyDerivation': isLegacyDerivation,
'isUsed': isUsed,
'txCount': txCount,
@@ -187,6 +200,7 @@ class BitcoinSilentPaymentAddressRecord extends BaseBitcoinAddressRecord {
BitcoinSilentPaymentAddressRecord(
super.address, {
required super.index,
+ super.accountIndex = 0,
super.isHidden = false,
super.txCount = 0,
super.balance = 0,
@@ -205,6 +219,7 @@ class BitcoinSilentPaymentAddressRecord extends BaseBitcoinAddressRecord {
return BitcoinSilentPaymentAddressRecord(
decoded['address'] as String,
index: decoded['index'] as int,
+ accountIndex: decoded['accountIndex'] as int? ?? 0,
isHidden: decoded['isHidden'] as bool? ?? false,
isUsed: decoded['isUsed'] as bool? ?? false,
txCount: decoded['txCount'] as int? ?? 0,
@@ -233,6 +248,7 @@ class BitcoinSilentPaymentAddressRecord extends BaseBitcoinAddressRecord {
String toJSON() => json.encode({
'address': address,
'index': index,
+ 'accountIndex': accountIndex,
'isHidden': isHidden,
'isUsed': isUsed,
'txCount': txCount,
### cw_bitcoin/lib/bitcoin_mnemonics_bip39.dart
@@ -1,12 +1,13 @@
import 'dart:typed_data';
import 'package:bip39/bip39.dart' as bip39;
+import 'package:cw_core/utils/bip39_seed.dart';
class MnemonicBip39 {
/// Generate bip39 mnemonic
static String generate({int strength = 128}) => bip39.generateMnemonic(strength: strength);
/// Create root seed from mnemonic
static Uint8List toSeed(String mnemonic, {String? passphrase}) =>
- bip39.mnemonicToSeed(mnemonic, passphrase: passphrase ?? '');
+ bip39MnemonicToSeed(mnemonic, passphrase: passphrase ?? '');
}
### cw_bitcoin/lib/bitcoin_transaction_priority.dart
@@ -1,3 +1,4 @@
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/transaction_priority.dart';
import 'package:flutter/foundation.dart';
@@ -28,7 +29,7 @@ class BitcoinTransactionPriority extends TransactionPriority {
return custom;
default:
if (kDebugMode) {
- throw Exception('Unexpected token: $raw for BitcoinTransactionPriority deserialize');
+ throw DeserializeException('Unexpected token: $raw for BitcoinTransactionPriority deserialize');
}
return medium;
}
@@ -88,7 +89,7 @@ class LitecoinTransactionPriority extends BitcoinTransactionPriority {
return fast;
default:
if (kDebugMode) {
- throw Exception('Unexpected token: $raw for LitecoinTransactionPriority deserialize');
+ throw DeserializeException('Unexpected token: $raw for LitecoinTransactionPriority deserialize');
}
return medium;
}
@@ -141,7 +142,7 @@ class BitcoinCashTransactionPriority extends BitcoinTransactionPriority {
return fast;
default:
if (kDebugMode) {
- throw Exception('Unexpected token: $raw for BitcoinCashTransactionPriority deserialize');
+ throw DeserializeException('Unexpected token: $raw for BitcoinCashTransactionPriority deserialize');
}
return medium;
}
### cw_bitcoin/lib/bitcoin_wallet.dart
@@ -1,6 +1,6 @@
import 'dart:convert';
-import 'package:bip39/bip39.dart' as bip39;
+import 'package:cw_core/utils/bip39_seed.dart';
import 'package:bitcoin_base/bitcoin_base.dart';
import 'package:blockchain_utils/blockchain_utils.dart';
import 'package:cw_bitcoin/.secrets.g.dart' as secrets;
@@ -14,7 +14,9 @@ import 'package:cw_bitcoin/electrum_balance.dart';
import 'package:cw_bitcoin/electrum_derivations.dart';
import 'package:cw_bitcoin/electrum_transaction_info.dart';
import 'package:cw_bitcoin/electrum_wallet.dart';
+import 'package:cw_bitcoin/electrum_wallet_addresses.dart';
import 'package:cw_bitcoin/electrum_wallet_snapshot.dart';
+import 'package:cw_bitcoin/unknown_derivation.dart';
import 'package:cw_bitcoin/locktime.dart';
import 'package:cw_bitcoin/hardware/bitcoin_hardware_wallet_service.dart';
import 'package:cw_bitcoin/lightning/lightning_wallet.dart';
@@ -30,6 +32,7 @@ import 'package:cw_bitcoin/psbt/v0_finalizer.dart';
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/output_info.dart';
import 'package:cw_core/payjoin_session.dart';
import 'package:cw_core/pending_transaction.dart';
@@ -128,8 +131,10 @@ abstract class BitcoinWalletBase extends ElectrumWallet with Store {
initialChangeAddressIndex: initialChangeAddressIndex,
initialSilentAddresses: initialSilentAddresses,
initialSilentAddressIndex: initialSilentAddressIndex,
- mainHdByType: mainHdByType,
- sideHdByType: sideHdByType,
+ mainHdByTypeAndAccount: mainHdByTypeAndAccount,
+ sideHdByTypeAndAccount: sideHdByTypeAndAccount,
+ accountIndexes: [currentAccountIndex],
+ currentAccountIndex: currentAccountIndex,
legacyMainHd: mainHd,
legacySideHd: sideHd,
network: networkParam ?? network,
@@ -157,9 +162,11 @@ abstract class BitcoinWalletBase extends ElectrumWallet with Store {
lnurlDomain: "cake.cash",
cachedAddress: cachedLightningAddress,
);
+ walletAddresses.lightningWallet = lightningWallet;
walletAddresses.setLightningAddress(walletInfo.name);
}
} else {
+ lightningWallet?.close();
lightningWallet = null;
}
});
@@ -197,10 +204,7 @@ abstract class BitcoinWalletBase extends ElectrumWallet with Store {
switch (derivationInfo.derivationType) {
case DerivationType.bip39:
- seedBytes = await bip39.mnemonicToSeed(
- mnemonic,
- passphrase: passphrase ?? "",
- );
+ seedBytes = bip39MnemonicToSeed(mnemonic, passphrase: passphrase ?? "");
break;
case DerivationType.electrum:
default:
@@ -278,16 +282,17 @@ abstract class BitcoinWalletBase extends ElectrumWallet with Store {
final derivationInfo = await walletInfo.getDerivationInfo();
// set the default if not present:
- derivationInfo.derivationPath ??= snp?.derivationPath ?? electrum_path;
derivationInfo.derivationType ??= snp?.derivationType ?? DerivationType.electrum;
if (derivationInfo.derivationType == DerivationType.unknown) {
- if (snp?.derivationPath == electrum_path || snp?.derivationType == DerivationType.electrum) {
- derivationInfo.derivationPath = electrum_path;
- derivationInfo.derivationType = DerivationType.electrum;
- } else {
- derivationInfo.derivationPath = segwit_path;
- derivationInfo.derivationType = DerivationType.bip39;
- }
+ resolveUnknownDerivation(
+ derivationInfo,
+ walletType: walletInfo.type,
+ mnemonic: keysData.mnemonic,
+ snapshotPath: snp?.derivationPath,
+ snapshotType: snp?.derivationType,
+ );
+ } else {
+ derivationInfo.derivationPath ??= snp?.derivationPath ?? electrum_path;
}
await derivationInfo.save();
@@ -302,10 +307,7 @@ abstract class BitcoinWalletBase extends ElectrumWallet with Store {
break;
case DerivationType.bip39:
default:
- seedBytes = await bip39.mnemonicToSeed(
- mnemonic,
- passphrase: passphrase ?? '',
- );
+ seedBytes = bip39MnemonicToSeed(mnemonic, passphrase: passphrase ?? '');
break;
}
}
@@ -423,7 +425,7 @@ abstract class BitcoinWalletBase extends ElectrumWallet with Store {
bool get hasPayjoinSupport => keys.privateKey.isNotEmpty;
@override
- bool get hasLightningSupport => lightningWallet?.sdk != null;
+ bool get hasLightningSupport => seed != null && LightningWallet.isAvailable;
bool get isPayjoinAvailable => unspentCoinsInfo.values
.where((element) => element.walletId == id && element.isSending && !element.isFrozen)
@@ -612,10 +614,12 @@ abstract class BitcoinWalletBase extends ElectrumWallet with Store {
return tx;
}
- List<UtxoWithPrivateKey> getUtxoWithPrivateKeys({bool confirmedOnly = false}) => unspentCoins
- .where((e) => e.isSending && !e.isFrozen && (!confirmedOnly || (e.confirmations ?? 0) > 0))
- .map((unspent) => UtxoWithPrivateKey.fromUnspent(unspent, this))
- .toList();
+ List<UtxoWithPrivateKey> getUtxoWithPrivateKeys({bool confirmedOnly = false}) =>
+ unspentCoinsForCurrentAccount
+ .where(
+ (e) => e.isSending && !e.isFrozen && (!confirmedOnly || (e.confirmations ?? 0) > 0))
+ .map((unspent) => UtxoWithPrivateKey.fromUnspent(unspent, this))
+ .toList();
Future<void> commitPsbt(String finalizedPsbt) {
final psbt = PsbtV2()..deserializeV0(base64.decode(finalizedPsbt));
@@ -625,6 +629,7 @@ abstract class BitcoinWalletBase extends ElectrumWallet with Store {
return PendingBitcoinTransaction(
btcTx,
type,
+ accountIndex: currentAccountIndex,
electrumClient: electrumClient,
amount: Money.zero(currency),
fee: Money.zero(currency),
@@ -657,7 +662,7 @@ abstract class BitcoinWalletBase extends ElectrumWallet with Store {
}
Future<void> commitPsbtUR(List<String> urCodes) async {
- if (urCodes.isEmpty) throw Exception("No QR code got scanned");
+ if (urCodes.isEmpty) throw ScanValueException("No QR code got scanned");
bool isUr = urCodes.any((str) {
return str.startsWith("ur:psbt/");
});
@@ -683,6 +688,7 @@ abstract class BitcoinWalletBase extends ElectrumWallet with Store {
return PendingBitcoinTransaction(
btcTx,
type,
+ accountIndex: currentAccountIndex,
electrumClient: electrumClient,
amount: Money.zero(currency),
fee: Money.zero(currency),
@@ -716,12 +722,24 @@ abstract class BitcoinWalletBase extends ElectrumWallet with Store {
@override
bool receiveOptionAvailable(ReceivePageOption option) {
- if(option == BitcoinReceivePageOption.lightning) {
- return hasLightningSupport;
+ final isExtraAccount = currentAccountIndex > 0;
+
+ if (option == BitcoinReceivePageOption.lightning) {
+ // Lightning is tied to the primary account only
+ return !isExtraAccount && hasLightningSupport && isLightningInitialized;
}
- if(option == BitcoinReceivePageOption.silent_payments) {
- return hasSilentPaymentsScanning;
+ if (option == BitcoinReceivePageOption.silent_payments) {
+ // Silent payments are tied to the primary account only
+ return !isExtraAccount && hasSilentPaymentsScanning;
+ }
+
+ // Restrict extra Bitcoin accounts (accountIndex > 0) to the allowed address types
+ if (isExtraAccount && option is BitcoinReceivePageOption) {
+ final addressType = option.toType();
+ if (!EXTRA_ACCOUNT_ADDRESS_TYPES.contains(addressType)) {
+ return false;
+ }
}
return true;
### cw_bitcoin/lib/bitcoin_wallet_addresses.dart
@@ -23,8 +23,10 @@ class BitcoinWalletAddresses = BitcoinWalletAddressesBase with _$BitcoinWalletAd
abstract class BitcoinWalletAddressesBase extends ElectrumWalletAddresses with Store {
BitcoinWalletAddressesBase(
WalletInfo walletInfo, {
- required super.mainHdByType,
- required super.sideHdByType,
+ required super.mainHdByTypeAndAccount,
+ required super.sideHdByTypeAndAccount,
+ required super.accountIndexes,
+ required super.currentAccountIndex,
required super.legacySideHd,
required super.legacyMainHd,
required super.network,
@@ -145,7 +147,12 @@ abstract class BitcoinWalletAddressesBase extends ElectrumWalletAddresses with S
try {
return super
.allAddresses
- .firstWhere((e) => e.type == SegwitAddresType.p2wpkh && !e.isHidden && !e.isUsed)
+ .firstWhere((e) =>
+ e.accountIndex == currentAccountIndex &&
+ e.type == SegwitAddresType.p2wpkh &&
+ !e.isHidden &&
+ !e.isUsed &&
+ !hiddenAddresses.contains(e.address))
.address;
} catch (_) {
return super.addressForBuy;
### cw_bitcoin/lib/bitcoin_wallet_service.dart
@@ -5,6 +5,7 @@ import 'package:cw_bitcoin/bitcoin_mnemonics_bip39.dart';
import 'package:cw_bitcoin/mnemonic_is_incorrect_exception.dart';
import 'package:cw_bitcoin/bitcoin_wallet_creation_credentials.dart';
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/payjoin_session.dart';
import 'package:cw_core/unspent_coins_info.dart';
import 'package:cw_core/utils/zpub.dart';
@@ -83,7 +84,7 @@ class BitcoinWalletService extends WalletService<
Future<BitcoinWallet> openWallet(String name, String password) async {
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
try {
final wallet = await BitcoinWalletBase.open(
@@ -117,7 +118,7 @@ class BitcoinWalletService extends WalletService<
File(await pathForWalletDir(name: wallet, type: getType())).delete(recursive: true);
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet, type: getType());
}
await WalletInfo.delete(walletInfo);
### cw_bitcoin/lib/electrum.dart
@@ -4,6 +4,7 @@ import 'dart:io';
import 'dart:typed_data';
import 'package:bitcoin_base/bitcoin_base.dart';
import 'package:cw_bitcoin/bitcoin_amount_format.dart';
+import "package:cw_bitcoin/electrum_wallet_exceptions.dart";
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/utils/proxy_socket/abstract.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
@@ -49,10 +50,13 @@ class ElectrumClient {
final Map<String, SocketTask> _tasks;
Map<String, SocketTask> get tasks => _tasks;
final Map<String, String> _errors;
- ConnectionStatus _connectionStatus = ConnectionStatus.disconnected;
Timer? _aliveTimer;
String unterminatedString;
+ // Bumped by every connect() and close(). An attempt that is no longer the latest when its
+ // socket arrives (node switch, reconnect, wallet closed) must not install it or report status.
+ int _connectAttempt = 0;
+
Uri? uri;
bool? useSSL;
@@ -65,6 +69,7 @@ class ElectrumClient {
}
Future<void> connect({required String host, required int port}) async {
+ final attempt = ++_connectAttempt;
_setConnectionStatus(ConnectionStatus.connecting);
// Reset internal state to ensure clean connection
@@ -73,37 +78,47 @@ class ElectrumClient {
try {
await socket?.close();
} catch (_) {}
+ if (attempt != _connectAttempt) {
+ return;
+ }
socket = null;
final ssl = !(useSSL == false || (useSSL == null && uri.toString().contains("btc-electrum")));
+ final ProxySocket newSocket;
try {
- socket = await ProxyWrapper()
+ newSocket = await ProxyWrapper()
.getSocksSocket(ssl, host, port, connectionTimeout: connectionTimeout);
} catch (e) {
printV("connect: $e");
- if (e is HandshakeException) {
- useSSL = !(useSSL ?? false);
+ if (attempt != _connectAttempt) {
+ return;
}
- if (_connectionStatus != ConnectionStatus.connecting) {
- _setConnectionStatus(ConnectionStatus.failed);
+ if (e is HandshakeException) {
+ useSSL = !(useSSL ?? false);
}
+ // Always report it: "connecting" is not retried by the wallet, so a failure left
+ // unreported keeps it on the spinner until the app is resumed or restarted.
+ _setConnectionStatus(ConnectionStatus.failed);
return;
}
- if (socket == null) {
- if (_connectionStatus != ConnectionStatus.connecting) {
- _setConnectionStatus(ConnectionStatus.failed);
- }
-
+ if (attempt != _connectAttempt) {
+ newSocket.destroy();
return;
}
+ socket = newSocket;
+
// use ping to determine actual connection status since we could've just not timed out yet:
// _setConnectionStatus(ConnectionStatus.connected);
- socket!.listen(
+ newSocket.listen(
(Uint8List event) {
+ // A replaced socket's late reply must not complete a same-id request of the new session.
+ if (!identical(socket, newSocket)) {
+ return;
+ }
try {
final msg = utf8.decode(event.toList());
final messagesList = msg.split("\n");
@@ -118,6 +133,10 @@ class ElectrumClient {
}
},
onError: (Object error) {
+ // A replaced socket's late error/close must not tear down its successor.
+ if (!identical(socket, newSocket)) {
+ return;
+ }
final errorMsg = error.toString();
printV(errorMsg);
unterminatedString = '';
@@ -127,6 +146,9 @@ class ElectrumClient {
},
onDone: () {
printV("SOCKET CLOSED!!!!!");
+ if (!identical(socket, newSocket)) {
+ return;
+ }
unterminatedString = '';
try {
_setConnectionStatus(ConnectionStatus.disconnected);
@@ -188,11 +210,23 @@ class ElectrumClient {
}
Future<void> ping() async {
+ // The keep-alive timer outlives a dropped socket, and callWithTimeout returns null when there
+ // is no socket, which must not count as a pong. A reply on a since-replaced socket says
+ // nothing about the current one either.
+ final pinged = socket;
+ if (pinged == null || pinged.isClosed) {
+ return;
+ }
+
try {
await callWithTimeout(method: 'server.ping');
- _setConnectionStatus(ConnectionStatus.connected);
+ if (identical(socket, pinged)) {
+ _setConnectionStatus(ConnectionStatus.connected);
+ }
} catch (_) {
- _setConnectionStatus(ConnectionStatus.disconnected);
+ if (identical(socket, pinged)) {
+ _setConnectionStatus(ConnectionStatus.disconnected);
+ }
}
}
@@ -213,7 +247,7 @@ class ElectrumClient {
}
if (throwOnError) {
- throw Exception('Invalid response format for getBalance');
+ throw ElectrumResponseException('Invalid response format for getBalance');
}
return <String, dynamic>{};
@@ -700,6 +734,7 @@ class ElectrumClient {
}
Future<void> close() async {
+ _connectAttempt++;
_aliveTimer?.cancel();
try {
await socket?.close();
@@ -776,7 +811,6 @@ class ElectrumClient {
void _setConnectionStatus(ConnectionStatus status) {
onConnectionStatusChange?.call(status);
- _connectionStatus = status;
if (!isConnected) {
try {
socket?.destroy();
### cw_bitcoin/lib/electrum_balance.dart
@@ -2,9 +2,17 @@ import 'dart:convert';
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/balance.dart';
+import "package:cw_core/crypto_currency.dart";
import 'package:cw_core/currency.dart';
class ElectrumBalance extends Balance {
+
+ factory ElectrumBalance.zero(CryptoCurrency currency) => ElectrumBalance(
+ confirmed: Money.zero(currency),
+ unconfirmed: Money.zero(currency),
+ frozen: Money.zero(currency),
+ );
+
ElectrumBalance({
required this.confirmed,
required this.unconfirmed,
@@ -28,6 +36,14 @@ class ElectrumBalance extends Balance {
@override
Money frozen;
+ ElectrumBalance copy() => ElectrumBalance(
+ confirmed: confirmed,
+ unconfirmed: unconfirmed,
+ frozen: frozen,
+ secondConfirmed: secondConfirmed,
+ secondUnconfirmed: secondUnconfirmed,
+ );
+
static ElectrumBalance? fromJSON(String? jsonSource, Currency currency) {
if (jsonSource == null) return null;
@@ -49,4 +65,26 @@ class ElectrumBalance extends Balance {
'secondConfirmed': secondAvailable?.amount.toInt() ?? 0,
'secondUnconfirmed': secondUnavailable?.amount.toInt() ?? 0,
});
+
+ // Value equality so instances can be compared/deduped (e.g. by MobX reactions via MapEquality)
+ @override
+ bool operator ==(Object other) =>
+ identical(this, other) ||
+ (other is ElectrumBalance &&
+ other.confirmed == confirmed &&
+ other.unconfirmed == unconfirmed &&
+ other.frozen == frozen &&
+ other.secondConfirmed == secondConfirmed &&
+ other.secondUnconfirmed == secondUnconfirmed);
+
+ @override
+ int get hashCode => Object.hash(
+ confirmed,
+ unconfirmed,
+ frozen,
+ secondConfirmed,
+ secondUnconfirmed,
+ );
}
+
+
### cw_bitcoin/lib/electrum_derivations.dart
@@ -1,7 +1,10 @@
import 'package:cw_core/wallet_info.dart';
-const SILENT_PAYMENTS_SCAN_PATH = "m/352'/0'/0'/1'/0";
-const SILENT_PAYMENTS_SPEND_PATH = "m/352'/0'/0'/0'/0";
+const SILENT_PAYMENTS_ACCOUNT_PATH = "m/352'/0'/0'";
+const SILENT_PAYMENTS_SCAN_SUBPATH = "1'/0";
+const SILENT_PAYMENTS_SPEND_SUBPATH = "0'/0";
+const SILENT_PAYMENTS_SCAN_PATH = "$SILENT_PAYMENTS_ACCOUNT_PATH/$SILENT_PAYMENTS_SCAN_SUBPATH";
+const SILENT_PAYMENTS_SPEND_PATH = "$SILENT_PAYMENTS_ACCOUNT_PATH/$SILENT_PAYMENTS_SPEND_SUBPATH";
const SILENT_PAYMENTS_SCAN_PATH_TESTNET = "m/352'/1'/0'/1'/0";
const SILENT_PAYMENTS_SPEND_PATH_TESTNET = "m/352'/1'/0'/0'/0";
@@ -116,3 +119,4 @@ Map<DerivationType, List<DerivationInfo>> electrum_derivations = {
String electrum_path = electrum_derivations[DerivationType.electrum]!.first.derivationPath!;
String segwit_path = "m/84'/0'/0'";
+String litecoin_segwit_path = "m/84'/2'/0'";
### cw_bitcoin/lib/electrum_transaction_info.dart
@@ -15,15 +15,18 @@ import 'package:hex/hex.dart';
class ElectrumTransactionBundle {
ElectrumTransactionBundle(this.originalTransaction,
- {required this.ins, required this.confirmations, this.time});
+ {required this.ins, required this.confirmations, this.time, this.hex, this.insHex});
final BtcTransaction originalTransaction;
final List<BtcTransaction?> ins;
final int? time;
final int confirmations;
+ final String? hex;
+ final List<String?>? insHex;
}
class ElectrumTransactionInfo extends TransactionInfo {
+ int? accountIndex;
List<BitcoinSilentPaymentsUnspent>? unspents;
bool isReceivedSilentPayment;
bool isHogEx;
@@ -41,6 +44,7 @@ class ElectrumTransactionInfo extends TransactionInfo {
bool isReplaced = false,
required DateTime date,
required int confirmations,
+ this.accountIndex,
String? to,
this.unspents,
this.isReceivedSilentPayment = false,
@@ -231,6 +235,7 @@ class ElectrumTransactionInfo extends TransactionInfo {
isPending: data['isPending'] as bool,
isReplaced: data['isReplaced'] as bool? ?? false,
confirmations: data['confirmations'] as int,
+ accountIndex: data['accountIndex'] as int?,
inputAddresses:
inputAddresses.isEmpty ? [] : inputAddresses.map((e) => e.toString()).toList(),
outputAddresses:
@@ -260,6 +265,7 @@ class ElectrumTransactionInfo extends TransactionInfo {
inputAddresses: inputAddresses,
outputAddresses: outputAddresses,
confirmations: info.confirmations,
+ accountIndex: accountIndex,
additionalInfo: additionalInfo);
}
@@ -273,6 +279,7 @@ class ElectrumTransactionInfo extends TransactionInfo {
m['isPending'] = isPending;
m['isReplaced'] = isReplaced;
m['confirmations'] = confirmations;
+ m['accountIndex'] = accountIndex;
m['fee'] = fee?.amount.toInt();
m['to'] = to;
m['unspents'] = unspents?.map((e) => e.toJson()).toList() ?? [];
@@ -284,6 +291,6 @@ class ElectrumTransactionInfo extends TransactionInfo {
}
String toString() {
- return 'ElectrumTransactionInfo(id: $id, height: $height, amount: $amount, fee: $fee, direction: $direction, date: $date, isPending: $isPending, isReplaced: $isReplaced, confirmations: $confirmations, to: $to, unspent: $unspents, inputAddresses: $inputAddresses, outputAddresses: $outputAddresses, additionalInfo: $additionalInfo)';
+ return 'ElectrumTransactionInfo(id: $id, height: $height, amount: $amount, fee: $fee, direction: $direction, date: $date, isPending: $isPending, isReplaced: $isReplaced, confirmations: $confirmations, accountIndex: $accountIndex, to: $to, unspent: $unspents, inputAddresses: $inputAddresses, outputAddresses: $outputAddresses, additionalInfo: $additionalInfo)';
}
}
### cw_bitcoin/lib/electrum_wallet.dart
@@ -1,10 +1,13 @@
import 'dart:async';
import 'dart:convert';
import 'dart:isolate';
-import 'dart:math' show Random;
+import 'dart:math' show Random, min;
import 'package:bitcoin_base/bitcoin_base.dart';
+import 'package:cw_bitcoin/lightning/lightning_addres_type.dart';
+import "package:cw_bitcoin/electrum_wallet_exceptions.dart";
import 'package:cw_bitcoin/lightning/lightning_wallet.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_bitcoin/locktime.dart';
import 'package:cw_core/hardware/hardware_wallet_service.dart';
import 'package:cw_core/root_dir.dart';
@@ -92,66 +95,23 @@ abstract class ElectrumWalletBase
_scripthashesUpdateSubject = {},
this.alwaysScan = alwaysScan,
silentPaymentsScanningActive = alwaysScan ?? false,
- balance = ObservableMap<CryptoCurrency, ElectrumBalance>.of(currency != null
- ? {
- currency: initialBalance ??
- ElectrumBalance(
- confirmed: Money.zero(currency),
- unconfirmed: Money.zero(currency),
- frozen: Money.zero(currency),
- )
- }
- : {}),
+ balance = ObservableMap<CryptoCurrency, ElectrumBalance>.of(
+ currency != null ? {currency: initialBalance ?? ElectrumBalance.zero(currency)} : {}),
this.unspentCoinsInfo = unspentCoinsInfo,
this.isTestnet = !network.isMainnet,
this._mnemonic = mnemonic,
+ this.electrumClient = electrumClient ?? electrum.ElectrumClient(),
_useLightning = useLightning,
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());
-
- final supportedTypes = supportedAddressTypes(walletInfo.type);
- mainHdByType = <BitcoinAddressType, Bip32Slip10Secp256k1>{};
- sideHdByType = <BitcoinAddressType, Bip32Slip10Secp256k1>{};
-
- final isElectrumDerivation = derivationInfo.derivationType == DerivationType.electrum;
-
- final canDeriveFromSeed = _masterHD != null && currency != null;
-
- if (isElectrumDerivation) {
- // Electrum derivation does not follow BIP44/49/84 etc. standards
- for (final type in supportedTypes) {
- mainHdByType[type] = mainHd; // accountHD.child(0)
- sideHdByType[type] = sideHd; // accountHD.child(1)
- }
- } else if (canDeriveFromSeed) {
- final coinType = _coinTypeFor(currency);
- final accountIndex = _parseAccountIndex(derivationInfo.derivationPath);
-
- for (final type in supportedTypes) {
- final purpose = _purposeForType(type);
- final accountPath = "m/$purpose'/$coinType'/$accountIndex'";
-
- mainHdByType[type] = _masterHD!.derivePath("$accountPath/0") as Bip32Slip10Secp256k1;
- sideHdByType[type] = _masterHD!.derivePath("$accountPath/1") as Bip32Slip10Secp256k1;
- }
- } else {
- // View-only wallet (xpub only)
- for (final type in supportedTypes) {
- mainHdByType[type] = mainHd;
- sideHdByType[type] = sideHd;
- }
- }
+ _prepareHdForAccount(currentAccountIndex, currency);
}
int _purposeForType(BitcoinAddressType type) {
@@ -200,8 +160,7 @@ abstract class ElectrumWalletBase
final coinType = _coinTypeFor(currency);
final purpose = _purposeForType(record.type);
- final accountIndex = _parseAccountIndex(derivationInfo.derivationPath);
- return "m/$purpose'/$coinType'/$accountIndex'";
+ return "m/$purpose'/$coinType'/${record.accountIndex}'";
}
List<BitcoinAddressType> supportedAddressTypes(WalletType type) {
@@ -227,7 +186,7 @@ abstract class ElectrumWalletBase
DerivationInfo? derivationInfo,
HardwareWalletType? hardwareWalletType) {
if (seedBytes == null && xpub == null) {
- throw Exception(
+ throw ArgumentError(
"To create a Wallet you need either a seed or an xpub. This should not happen");
}
@@ -246,7 +205,7 @@ abstract class ElectrumWalletBase
case CryptoCurrency.doge:
return dogecoinHDWallet(seedBytes);
default:
- throw Exception("Unsupported currency");
+ throw (currency == null ? ArgumentError("no currency") : BadCurrencyException("Unsupported currency",currency!));
}
}
@@ -317,16 +276,16 @@ abstract class ElectrumWalletBase
static const int addressHistoryChunkSize = 150;
static const int transactionChunkSize = 150;
- static const int inputTransactionChunkSize = 150;
static const int discoveryHistoryChunkSize = 20;
-
static const int transactionBatchTimeoutMs = 15000;
-
static const int batchTestTimeoutMs = 4000;
static const int batchTestHashesCount = 2;
-
static const bool useBatchForHistory = true;
+ static const int maxProbAccounts = 3;
+
+ final Map<String, Set<String>> _appliedCoinKeysByAddress = {};
+
@observable
bool? alwaysScan;
@@ -338,12 +297,15 @@ abstract class ElectrumWalletBase
@observable
bool _useLightning;
+ @observable
+ ObservableMap<int, ElectrumBalance> accountBalances = ObservableMap<int, ElectrumBalance>();
+
final Bip32Slip10Secp256k1? _masterHD;
final Bip32Slip10Secp256k1 accountHD;
final String? _mnemonic;
- late final Map<BitcoinAddressType, Bip32Slip10Secp256k1> mainHdByType;
- late final Map<BitcoinAddressType, Bip32Slip10Secp256k1> sideHdByType;
+ final mainHdByTypeAndAccount = <int, Map<BitcoinAddressType, Bip32Slip10Secp256k1>>{};
+ final sideHdByTypeAndAccount = <int, Map<BitcoinAddressType, Bip32Slip10Secp256k1>>{};
Bip32Slip10Secp256k1 get mainHd => accountHD.childKey(Bip32KeyIndex(0));
@@ -372,6 +334,149 @@ abstract class ElectrumWalletBase
@observable
SyncStatus syncStatus;
+ bool _hasCompleteUnspentSet = false;
+ bool _isSyncing = false;
+
+ Future<WalletInfoAccount> loadCurrentAccount() async {
+ final accounts = await walletInfo.getAccounts();
+ final current = accounts.firstWhere(
+ (account) => account.accountIndex == currentAccountIndex,
+ orElse: () => accounts.first,
+ );
+
+ return current;
+ }
+
+ Future<List<int>> loadAccountIndexes() async {
+ if (!hasAccountsSupport) return [0];
+
+ final accounts = await walletInfo.getAccounts();
+ return accounts.map((account) => account.accountIndex).toList();
+ }
+
+ void _prepareHdForAccount(int accountIndex, CryptoCurrency? currency) {
+ if (mainHdByTypeAndAccount.containsKey(accountIndex)) return;
+
+ // For the first account, we support all address types. For extra accounts, we only support SegwitAddresType.p2wpkh.
+ final supportedTypes =
+ accountIndex == 0 ? supportedAddressTypes(walletInfo.type) : EXTRA_ACCOUNT_ADDRESS_TYPES;
+ final isElectrumDerivation = derivationInfo.derivationType == DerivationType.electrum;
+ final canDeriveFromSeed = _masterHD != null && currency != null;
+
+ final mainMap = mainHdByTypeAndAccount[accountIndex] ??= {};
+ final sideMap = sideHdByTypeAndAccount[accountIndex] ??= {};
+
+ if (canDeriveFromSeed && !isElectrumDerivation) {
+ final coinType = _coinTypeFor(currency);
+ final accountHdByPath = <String, Bip32Slip10Secp256k1>{};
+
+ for (final type in supportedTypes) {
+ final accountPath = "m/${_purposeForType(type)}'/$coinType'/$accountIndex'";
+ final accountHd = accountHdByPath[accountPath] ??=
+ _masterHD!.derivePath(accountPath) as Bip32Slip10Secp256k1;
+
+ mainMap[type] = accountHd.childKey(Bip32KeyIndex(0));
+ sideMap[type] = accountHd.childKey(Bip32KeyIndex(1));
+ }
+ } else {
+ // case for Electrum derivation or when we don't have seed but only xpub (view only wallet)
+ for (final type in supportedTypes) {
+ mainMap[type] = mainHd; // accountHD.child(0)
+ sideMap[type] = sideHd; // accountHD.child(1)
+ }
+ }
+ }
+
+ ElectrumBalance balanceForAccount(int accountIndex) =>
+ accountBalances[accountIndex] ?? ElectrumBalance.zero(currency);
+
+ void _updateAccountBalancesFromUnspents() {
+ if (!_hasCompleteUnspentSet) return;
+
+ final newBalances = <int, ElectrumBalance>{};
+
+ for (final coin in unspentCoins) {
+ final accountIndex = coin.bitcoinAddressRecord.accountIndex;
+ final current = newBalances[accountIndex] ?? ElectrumBalance.zero(currency);
+ final amount = Money.fromInt(coin.value, currency);
+
+ if (coin.isFrozen) {
+ current.frozen += amount;
+ }
+
+ if (coin.confirmations != null && coin.confirmations! > 0) {
+ current.confirmed += amount;
+ } else {
+ current.unconfirmed += amount;
+ }
+
+ newBalances[accountIndex] = current;
+ }
+
+ for (final accountIndex in walletAddresses.accountIndexes) {
+ newBalances.putIfAbsent(accountIndex, () => ElectrumBalance.zero(currency));
+ }
+
+ accountBalances = ObservableMap<int, ElectrumBalance>.of(newBalances);
+ _updateCurrentAccountBalance();
+ }
+
+ void _updateCurrentAccountBalance({int? accountIndex}) {
+ if (type != WalletType.bitcoin) return;
+
+ final targetAccountIndex = accountIndex ?? currentAccountIndex;
+ final newBalance = accountBalances[targetAccountIndex];
+
+ if (newBalance == null) {
+ // If the account balance is not found, set it to zero for the current currency.
+ balance[currency] = ElectrumBalance.zero(currency);
+ return;
+ }
+
+ balance[currency] = newBalance.copy();
+ }
+
+ Map<int, Set<String>> get addressesSetByAccount {
+ final result = <int, Set<String>>{};
+ for (final addr in walletAddresses.allAddresses) {
+ if (addr.type == SegwitAddresType.mweb) continue;
+ (result[addr.accountIndex] ??= <String>{}).add(addr.address);
+ }
+ return result;
+ }
+
+ int? _accountForTransaction(
+ ElectrumTransactionBundle bundle,
+ Map<int, Set<String>> addressesByAccount,
+ ) {
+ if (type != WalletType.bitcoin) return null;
+
+ int? accountForAddress(String address) {
+ for (final entry in addressesByAccount.entries) {
+ if (entry.value.contains(address)) return entry.key;
+ }
+ return null;
+ }
+
+ for (var i = 0; i < bundle.originalTransaction.inputs.length; i++) {
+ final inputTransaction = bundle.ins[i];
+ if (inputTransaction == null) continue;
+
+ final outTransaction =
+ inputTransaction.outputs[bundle.originalTransaction.inputs[i].txIndex];
+ final account =
+ accountForAddress(addressFromOutputScript(outTransaction.scriptPubKey, network));
+ if (account != null) return account;
+ }
+
+ for (final out in bundle.originalTransaction.outputs) {
+ final account = accountForAddress(addressFromOutputScript(out.scriptPubKey, network));
+ if (account != null) return account;
+ }
+
+ return null;
+ }
+
Set<String> get addressesSet => walletAddresses.allAddresses
.where((element) => element.type != SegwitAddresType.mweb)
.map((addr) => addr.address)
@@ -390,8 +495,77 @@ abstract class ElectrumWalletBase
String get xpub => accountHD.publicKey.toExtended;
+ int get currentAccountIndex => walletInfo.currentAccountIndex;
+
+ @action
+ Future<void> setCurrentAccount(int accountIndex) async {
+
+ final isNewAccount = !walletAddresses.accountIndexes.contains(accountIndex);
+ if (isNewAccount) {
+ walletAddresses.accountIndexes.add(accountIndex);
+
+ accountBalances[accountIndex] = ElectrumBalance.zero(currency);
+ }
+
+ await walletInfo.setSelectedAccount(accountIndex);
+
+ _prepareHdForAccount(accountIndex, currency);
+
+ walletAddresses.currentAccountIndex = accountIndex;
+
+ final currentPageType = walletAddresses.addressPageType;
+ await walletAddresses.setAddressType(currentPageType);
+
+ // For extra accounts, we only prepare SegwitAddresType.p2wpkh type.
+ if (isNewAccount) {
+ await walletAddresses.prepareAccountAddresses(
+ accountIndex,
+ types: accountIndex == 0 ? BITCOIN_ADDRESS_TYPES : EXTRA_ACCOUNT_ADDRESS_TYPES,
+ );
+ await walletAddresses.updateAddressesInBox();
+ }
+
+ walletAddresses.updateReceiveAddresses();
+ walletAddresses.updateChangeAddresses();
+
+ _updateCurrentAccountBalance(accountIndex: accountIndex);
+
+ unawaited(() async {
+ try {
+ if (isNewAccount && !_isSyncing) {
+ final histories = <String, ElectrumTransactionInfo>{};
+
+ final typesToFetch = accountIndex == 0 ? BITCOIN_ADDRESS_TYPES : EXTRA_ACCOUNT_ADDRESS_TYPES;
+ // Explicit for clarity — fetchTransactionsForAddressTypeBatch already skips types
+ // with no addresses for this account, so this doesn't change RPC calls, just intent.
+
+ for (final addressType in typesToFetch) {
+ if (shouldUseBatchFetching) {
+ await fetchTransactionsForAddressTypeBatch(histories, addressType,
+ accountIndex: accountIndex);
+ } else {
+ await fetchTransactionsForAddressType(histories, addressType,
+ accountIndex: accountIndex);
+ }
+ }
+
+ await resolveQueuedTransactionDetails();
+ }
+
+ await updateAllUnspents();
+ } catch (e) {
+ printV('setCurrentAccount balance update failed: $e');
+ }
+ }());
+ }
+
bool get shouldUseBatchFetching => useBatchForHistory && _isBatchSupported == true;
+ bool get isInitialBitcoinAccountsSync =>
+ hasAccountsSupport &&
+ walletInfo.isMultiAccountsEnabled == true &&
+ (walletInfo.accountDiscoveryLimit ?? 0) < maxProbAccounts;
+
@override
String? get seed => _mnemonic;
@@ -410,14 +584,29 @@ abstract class ElectrumWalletBase
@override
bool get hasSilentPaymentsScanning => type == WalletType.bitcoin && keys.privateKey.isNotEmpty;
+ @override
+ bool get hasCoinControl => true;
+
+ @override
+ bool get hasAccountsSupport =>
+ type == WalletType.bitcoin &&
+ isSoftwareWallet &&
+ _masterHD != null && // xpub / watch-only: can't derive other (hardened) accounts
+ derivationInfo.derivationType != DerivationType.electrum;
+
@observable
bool nodeSupportsSilentPayments = true;
@observable
bool silentPaymentsScanningActive = false;
bool _isTryingToConnect = false;
+ Timer? _reconnectTimer;
+ bool _isClosed = false;
bool? _isBatchSupported;
DateTime? _syncBenchmarkStartTime;
+ DateTime? _syncStartedAt;
+
+ static const Duration maxSyncDuration = Duration(minutes: 2);
Completer<SharedPreferences> sharedPrefs = Completer();
@@ -449,7 +638,7 @@ abstract class ElectrumWalletBase
_isolate?.then((value) => value.kill(priority: Isolate.immediate));
if (electrumClient.isConnected) {
- syncStatus = SyncedSyncStatus();
+ if (!_isSyncing) syncStatus = SyncedSyncStatus();
} else {
syncStatus = NotConnectedSyncStatus();
}
@@ -490,7 +679,9 @@ abstract class ElectrumWalletBase
String? privateKey;
String? publicKey;
- final hd = mainHdByType[SegwitAddresType.p2wpkh] ?? mainHd;
+ // `keys` is wallet-level metadata
+ final hd =
+ mainHdByTypeAndAccount[0]?[SegwitAddresType.p2wpkh] ?? mainHd;
try {
wif = WifEncoder.encode(hd.privateKey.raw, netVer: network.wifNetVer);
@@ -523,16 +714,30 @@ abstract class ElectrumWalletBase
bool _isTransactionUpdating;
Future<Isolate>? _isolate;
+ final Map<String, Map<String, dynamic>> _missingHistoryQueue = {};
+
+ Future<void>? _resolveMissingHistoryFuture;
+ final Map<String, int> _unresolvedAccountRetryCount = {};
+ static const int _maxUnresolvedAccountRetries = 3;
+
void Function(FlutterErrorDetails)? _onError;
Timer? _autoSaveTimer;
StreamSubscription<dynamic>? _receiveStream;
Timer? _updateFeeRateTimer;
static const int _autoSaveInterval = 1;
Future<void> init() async {
- await walletAddresses.init();
+ final accountIndexes = await loadAccountIndexes();
+
+ for (final accountIndex in accountIndexes) {
+ _prepareHdForAccount(accountIndex, currency);
+ }
+
+
+ await walletAddresses.init(accountIndexes: accountIndexes);
await transactionHistory.init();
await cleanUpDuplicateUnspentCoins();
+ _seedAccountBalancesFromAddressRecords();
await save();
_autoSaveTimer =
@@ -699,14 +904,32 @@ abstract class ElectrumWalletBase
DateTime? _lastSilentPaymentsScan;
static const Duration _silentPaymentsScanDelay = Duration(minutes: 1);
+ Iterable<BitcoinUnspent> get unspentCoinsForCurrentAccount {
+ if (type != WalletType.bitcoin) {
+ return unspentCoins;
+ }
+
+ return unspentCoins
+ .where((coin) => coin.bitcoinAddressRecord.accountIndex == currentAccountIndex);
+ }
+
@action
@override
Future<void> startSync() async {
- try {
- if (syncStatus is SyncronizingSyncStatus) {
+ if (_isSyncing) {
+ final startedAt = _syncStartedAt;
+ if (startedAt != null && DateTime.now().difference(startedAt) > maxSyncDuration) {
+ printV('startSync: previous sync appears stuck, allowing a new one');
+ _isSyncing = false;
+ } else {
+ printV('startSync: already syncing, skipping');
return;
}
+ }
+ _isSyncing = true;
+ _syncStartedAt = DateTime.now();
+ try {
if (_syncBenchmarkStartTime == null) {
_syncBenchmarkStartTime = DateTime.now();
printV('[ELECTRUM_WALLET SYNC] Starting: ${_syncBenchmarkStartTime!}');
@@ -749,18 +972,12 @@ abstract class ElectrumWalletBase
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) {
+ _syncBenchmarkStartTime = null;
} else {
- if (syncStatus is LostConnectionSyncStatus) {
- return;
- }
-
final syncEnd = DateTime.now();
final totalMs = _syncBenchmarkStartTime != null
? syncEnd.difference(_syncBenchmarkStartTime!).inMilliseconds
@@ -771,6 +988,13 @@ abstract class ElectrumWalletBase
_syncBenchmarkStartTime = null;
syncStatus = SyncedSyncStatus();
}
+
+ await updateFeeRates();
+
+ _updateFeeRateTimer ??=
+ Timer.periodic(const Duration(minutes: 1), (timer) async => await updateFeeRates());
+
+ unawaited(resolveQueuedTransactionDetails());
} catch (e, stacktrace) {
final syncEnd = DateTime.now();
final totalMs = _syncBenchmarkStartTime != null
@@ -783,6 +1007,8 @@ abstract class ElectrumWalletBase
_syncBenchmarkStartTime = null;
syncStatus = FailedSyncStatus();
+ } finally {
+ _isSyncing = false;
}
}
@@ -794,7 +1020,11 @@ abstract class ElectrumWalletBase
if (await checkIfMempoolAPIIsEnabled() && type == WalletType.bitcoin) {
try {
final response = await ProxyWrapper()
- .get(clearnetUri: Uri.parse("https://mempool.cakewallet.com/api/v1/fees/recommended"))
+ .get(
+ clearnetUri: Uri.parse("https://mempool.cakewallet.com/api/v1/fees/recommended"),
+ onionUri: Uri.parse(
+ "http://cakememcninjdqbaub3tp2iswuigxqtdoevnpgzkolmy4gvhrrsub3yd.onion/api/v1/fees/recommended"),
+ )
.timeout(Duration(seconds: 15));
final result = json.decode(response.body) as Map<String, dynamic>;
@@ -823,6 +1053,7 @@ abstract class ElectrumWalletBase
}
Node? node;
+ bool? _connectingViaTor;
Future<bool> getNodeIsElectrs() async {
if (node == null) {
@@ -880,17 +1111,33 @@ abstract class ElectrumWalletBase
@action
@override
Future<void> connectToNode({required Node node}) async {
+ // A closed wallet is discarded; reconnecting it would leak a socket and its keep-alive.
+ if (_isClosed) {
+ return;
+ }
+ final viaTor = CakeTor.instance?.started ?? false;
+ final isSameConnection = node == this.node && viaTor == _connectingViaTor;
this.node = node;
_isBatchSupported = null;
- if (syncStatus is ConnectingSyncStatus) return;
+ // Only a repeat of the attempt in flight is skipped; dropping a different node or a Tor
+ // toggle here would leave the wallet on the old attempt.
+ if (syncStatus is ConnectingSyncStatus && isSameConnection) {
+ return;
+ }
+ _connectingViaTor = viaTor;
try {
syncStatus = ConnectingSyncStatus();
await _receiveStream?.cancel();
await electrumClient.close();
+ if (_isClosed) {
+ return;
+ }
_isBatchSupported = null;
+ // The new server session has no subscriptions yet.
+ _scripthashesUpdateSubject = {};
electrumClient.onConnectionStatusChange = _onConnectionStatusChange;
@@ -935,7 +1182,7 @@ abstract class ElectrumWalletBase
bool spendsUnconfirmedTX = false;
int leftAmount = credentialsAmount;
- var availableInputs = unspentCoins.where((utx) {
+ var availableInputs = unspentCoinsForCurrentAccount.where((utx) {
if (!utx.isSending || utx.isFrozen) {
return false;
}
@@ -1016,7 +1263,7 @@ abstract class ElectrumWalletBase
final address = RegexUtils.addressTypeFromStr(utx.address, network);
ECPrivate? privkey;
bool? isSilentPayment = false;
- final hd = _hdFor(record: utx.bitcoinAddressRecord);
+ final hd = _hdForAddressRecord(record: utx.bitcoinAddressRecord);
if (utx.bitcoinAddressRecord is BitcoinSilentPaymentAddressRecord) {
final unspentAddress = utx.bitcoinAddressRecord as BitcoinSilentPaymentAddressRecord;
@@ -1283,7 +1530,7 @@ abstract class ElectrumWalletBase
final changeDerivationPath = "${_hardenedDerivationPath(changeBaseDerivationPath)}"
"/${changeAddress.isHidden ? "1" : "0"}"
"/${changeAddress.index}";
- final changeHd = _hdFor(record: changeAddress).childKey(Bip32KeyIndex(changeAddress.index));
+ final changeHd = _hdForAddressRecord(record: changeAddress).childKey(Bip32KeyIndex(changeAddress.index));
final changePubKeyHex = changeHd.publicKey.toHex();
utxoDetails.publicKeys[address.pubKeyHash()] =
@@ -1613,6 +1860,7 @@ abstract class ElectrumWalletBase
return PendingBitcoinTransaction(
transaction,
type,
+ accountIndex: currentAccountIndex,
electrumClient: electrumClient,
amount: estimatedTx.amount,
fee: estimatedTx.fee,
@@ -1625,8 +1873,8 @@ abstract class ElectrumWalletBase
isViewOnly: false,
)..addListener((transaction) async {
transactionHistory.addOne(transaction);
- await updateBalance();
await updateAllUnspents();
+ await updateBalance();
});
}
@@ -1686,7 +1934,7 @@ abstract class ElectrumWalletBase
}
if (key == null) {
- throw Exception(error);
+ throw TransactionGenerationException(error);
}
if (utxo.utxo.isP2tr()) {
@@ -1704,6 +1952,7 @@ abstract class ElectrumWalletBase
return PendingBitcoinTransaction(
transaction,
type,
+ accountIndex: currentAccountIndex,
electrumClient: electrumClient,
amount: estimatedTx.amount,
fee: estimatedTx.fee,
@@ -1729,8 +1978,8 @@ abstract class ElectrumWalletBase
unspentCoins
.removeWhere((utxo) => estimatedTx.utxos.any((e) => e.utxo.txHash == utxo.hash));
- await updateBalance();
await updateAllUnspents();
+ await updateBalance();
});
} catch (e) {
throw e;
@@ -1815,7 +2064,7 @@ abstract class ElectrumWalletBase
if (amount != null) {
int totalValue = 0;
- for (final input in unspentCoins) {
+ for (final input in unspentCoinsForCurrentAccount) {
if (totalValue >= amount) {
break;
}
@@ -1828,7 +2077,7 @@ abstract class ElectrumWalletBase
if (totalValue < amount) return 0;
} else {
- for (final input in unspentCoins) {
+ for (final input in unspentCoinsForCurrentAccount) {
if (input.isSending) {
inputsCount += 1;
}
@@ -1871,6 +2120,13 @@ abstract class ElectrumWalletBase
@override
Future<void> close({bool shouldCleanup = false}) async {
+ _missingHistoryQueue.clear();
+ _unresolvedAccountRetryCount.clear();
+ // A pending or later reconnect (e.g. from a sync still running) would reopen the client of a
+ // closed wallet.
+ _isClosed = true;
+ _reconnectTimer?.cancel();
+ _isTryingToConnect = false;
try {
await _receiveStream?.cancel();
await electrumClient.close();
@@ -1882,6 +2138,7 @@ abstract class ElectrumWalletBase
@action
Future<void> updateAllUnspents() async {
+
List<BitcoinUnspent> updatedUnspentCoins = [];
final previousUnspentCoins = List<BitcoinUnspent>.from(unspentCoins.where((utxo) =>
@@ -1906,6 +2163,7 @@ abstract class ElectrumWalletBase
for (final addr in targetAddresses) {
if (addr is! BitcoinSilentPaymentAddressRecord) {
addr.balance = 0;
+ _appliedCoinKeysByAddress[addr.address]?.clear();
}
}
@@ -1920,6 +2178,7 @@ abstract class ElectrumWalletBase
updatedUnspentCoins.addAll(result!);
}
unspentCoins = updatedUnspentCoins;
+ _hasCompleteUnspentSet = true;
} else {
if (updatedUnspentCoins.isEmpty) {
unspentCoins = handleFailedUtxoFetch(
@@ -1941,6 +2200,7 @@ abstract class ElectrumWalletBase
}
await updateCoins(unspentCoins);
+ _updateAccountBalancesFromUnspents();
await _refreshUnspentCoinsInfo();
}
@@ -1961,11 +2221,13 @@ abstract class ElectrumWalletBase
final scriptHashes = byScriptHash.keys.toList();
try {
+ final failedScriptHashes = <String>{};
final unspentByScriptHash =
await _processChunksToMap<String, String, List<Map<String, dynamic>>>(
items: scriptHashes,
chunkSize: addressHistoryChunkSize,
processChunk: _getListUnspentBatch,
+ onChunkError: (chunk, _) => failedScriptHashes.addAll(chunk),
);
final txHashes = <String>{};
@@ -2003,6 +2265,8 @@ abstract class ElectrumWalletBase
return addresses.map((address) {
final scriptHash = address.getScriptHash(network);
+ if (failedScriptHashes.contains(scriptHash)) return null;
+ if (!unspentByScriptHash.containsKey(scriptHash)) return null;
return coinsByScriptHash[scriptHash] ?? <BitcoinUnspent>[];
}).toList();
} catch (e) {
@@ -2062,8 +2326,15 @@ abstract class ElectrumWalletBase
coin.isSending = coinInfo.isSending;
coin.note = coinInfo.note;
- if (coin.bitcoinAddressRecord is! BitcoinSilentPaymentAddressRecord)
- coin.bitcoinAddressRecord.balance += coinInfo.value;
+ if (coin.bitcoinAddressRecord is! BitcoinSilentPaymentAddressRecord) {
+ final addr = coin.bitcoinAddressRecord.address;
+ final coinKey = '${coin.hash}:${coin.vout}';
+ final appliedKeys = _appliedCoinKeysByAddress.putIfAbsent(addr, () => <String>{});
+
+ if (appliedKeys.add(coinKey)) {
+ coin.bitcoinAddressRecord.balance += coinInfo.value;
+ }
+ }
} else {
addCoinInfo(coin);
}
@@ -2171,11 +2442,47 @@ abstract class ElectrumWalletBase
if (duplicateKeys.isNotEmpty) await unspentCoinsInfo.deleteAll(duplicateKeys);
}
+ void _seedAccountBalancesFromAddressRecords() {
+ if (type != WalletType.bitcoin) return;
+ if (accountBalances.isNotEmpty) return;
+
+ final newBalances = <int, ElectrumBalance>{};
+
+ for (final addr in walletAddresses.allAddresses) {
+ if (addr.type == SegwitAddresType.mweb) continue;
+ final current = newBalances[addr.accountIndex] ?? ElectrumBalance.zero(currency);
+ current.confirmed += Money.fromInt(addr.balance, currency);
+ newBalances[addr.accountIndex] = current;
+ }
+
+ for (final accountIndex in walletAddresses.accountIndexes) {
+ newBalances.putIfAbsent(accountIndex, () => ElectrumBalance.zero(currency));
+ }
+
+ // balance[currency] came from the wallet file and is authoritative for the
+ // selected account — prefer it if the address records look stale.
+ final persisted = balance[currency];
+ final seeded = newBalances[currentAccountIndex];
+ if (persisted != null && seeded != null) {
+ final seededIsZero = seeded.confirmed == Money.zero(currency) &&
+ seeded.unconfirmed == Money.zero(currency);
+ final persistedIsNonZero = persisted.confirmed != Money.zero(currency) ||
+ persisted.unconfirmed != Money.zero(currency);
+ if (seededIsZero && persistedIsNonZero) {
+ newBalances[currentAccountIndex] = persisted;
+ }
+ }
+
+ accountBalances = ObservableMap<int, ElectrumBalance>.of(newBalances);
+ _updateCurrentAccountBalance();
+ }
+
int transactionVSize(String transactionHex) => BtcTransaction.fromRaw(transactionHex).getVSize();
Future<String?> canReplaceByFee(ElectrumTransactionInfo tx) async {
try {
final bundle = await getTransactionExpanded(hash: tx.txHash);
+ if (_parseRawTransaction(bundle.hex)?.txId != tx.txHash) return null;
_updateInputsAndOutputs(tx, bundle);
if (bundle.confirmations > 0) return null;
return bundle.originalTransaction.canReplaceByFee ? bundle.originalTransaction.toHex() : null;
@@ -2186,6 +2493,9 @@ abstract class ElectrumWalletBase
Future<bool> isChangeSufficientForFee(String txId, int newFee) async {
final bundle = await getTransactionExpanded(hash: txId);
+ if (_parseRawTransaction(bundle.hex)?.txId != txId) {
+ throw RbfException("Transaction does not match $txId");
+ }
final outputs = bundle.originalTransaction.outputs;
final ownAddresses = walletAddresses.allAddresses.map((addr) => addr.address).toSet();
@@ -2196,19 +2506,21 @@ abstract class ElectrumWalletBase
.fold<int>(0, (sum, output) => sum + output.amount.toInt());
if (receiverAmount == 0) {
- throw Exception("Receiver output not found.");
+ throw RbfException("Receiver output not found.");
}
- final availableInputs = unspentCoins.where((utxo) => utxo.isSending && !utxo.isFrozen).toList();
+ final availableInputs =
+ unspentCoinsForCurrentAccount.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];
- if (inputTransaction == null) {
- throw Exception("Missing input transaction for fee calculation");
+ if (inputTransaction == null ||
+ _parseRawTransaction(bundle.insHex?[i])?.txId != input.txId) {
+ throw RbfException("Missing input transaction for fee calculation");
}
final vout = input.txIndex;
final outTransaction = inputTransaction.outputs[vout];
@@ -2226,6 +2538,9 @@ abstract class ElectrumWalletBase
Future<PendingBitcoinTransaction> replaceByFee(String hash, int newFee) async {
try {
final bundle = await getTransactionExpanded(hash: hash);
+ if (_parseRawTransaction(bundle.hex)?.txId != hash) {
+ throw RbfException("Transaction does not match $hash");
+ }
final utxos = <UtxoWithAddress>[];
final outputs = <BitcoinOutput>[];
@@ -2238,8 +2553,9 @@ abstract class ElectrumWalletBase
for (var i = 0; i < bundle.originalTransaction.inputs.length; i++) {
final input = bundle.originalTransaction.inputs[i];
final inputTransaction = bundle.ins[i];
- if (inputTransaction == null) {
- throw Exception("Missing input transaction for replace-by-fee");
+ if (inputTransaction == null ||
+ _parseRawTransaction(bundle.insHex?[i])?.txId != input.txId) {
+ throw RbfException("Missing input transaction for replace-by-fee");
}
final vout = input.txIndex;
final outTransaction = inputTransaction.outputs[vout];
@@ -2250,7 +2566,7 @@ abstract class ElectrumWalletBase
walletAddresses.allAddresses.firstWhere((element) => element.address == address);
final btcAddress = RegexUtils.addressTypeFromStr(addressRecord.address, network);
- final hd = _hdFor(record: addressRecord);
+ final hd = _hdForAddressRecord(record: addressRecord);
final privkey = generateECPrivate(hd: hd, index: addressRecord.index, network: network);
@@ -2270,6 +2586,10 @@ abstract class ElectrumWalletBase
);
}
+ if (!_isSignedByOwnKey(bundle, utxos)) {
+ throw RbfException("Transaction is not signed by this wallet");
+ }
+
// Add original outputs
for (final out in bundle.originalTransaction.outputs) {
final script = out.scriptPubKey.script;
@@ -2281,7 +2601,7 @@ abstract class ElectrumWalletBase
memo = utf8.decode(HEX.decode(opReturnData));
continue;
} catch (_) {
- throw Exception('Cannot decode OP_RETURN data');
+ throw RbfException('Cannot decode OP_RETURN data');
}
}
}
@@ -2298,7 +2618,7 @@ abstract class ElectrumWalletBase
var remainingFee = BigInt.from(newFee - currentFee);
if (remainingFee <= BigInt.zero) {
- throw Exception("New fee must be higher than the current fee.");
+ throw ArgumentError("New fee must be higher than the current fee.");
}
// Deduct fee from change outputs first, if possible
@@ -2327,15 +2647,15 @@ abstract class ElectrumWalletBase
// If still not enough, add UTXOs until the fee is covered, drawing them at
// random instead of in the predictable wallet scan order (address, then age).
if (remainingFee > BigInt.zero) {
- final unusedUtxos = unspentCoins
+ final unusedUtxos = unspentCoinsForCurrentAccount
.where((utxo) => utxo.isSending && !utxo.isFrozen && utxo.confirmations! > 0)
.toList()
..shuffle(Random.secure());
for (final utxo in unusedUtxos) {
final address = RegexUtils.addressTypeFromStr(utxo.address, network);
- final hd = _hdFor(record: utxo.bitcoinAddressRecord);
+ final hd = _hdForAddressRecord(record: utxo.bitcoinAddressRecord);
final privkey = generateECPrivate(
hd: hd,
@@ -2400,7 +2720,7 @@ abstract class ElectrumWalletBase
// Final check if the remaining fee couldn't be deducted
if (remainingFee > BigInt.zero) {
- throw Exception("Not enough funds to cover the fee.");
+ throw RbfException("Not enough funds to cover the fee.");
}
// Identify all change outputs
@@ -2432,7 +2752,7 @@ abstract class ElectrumWalletBase
final key =
privateKeys.firstWhereOrNull((element) => element.getPublic().toHex() == publicKey);
if (key == null) {
- throw Exception("Cannot find private key");
+ throw WalletKeysException("Cannot find private key");
}
if (utxo.utxo.isP2tr()) {
@@ -2445,6 +2765,7 @@ abstract class ElectrumWalletBase
return PendingBitcoinTransaction(
transaction,
type,
+ accountIndex: transactionHistory.transactions[hash]?.accountIndex ?? currentAccountIndex,
electrumClient: electrumClient,
amount: Money.fromInt(sendingAmount, currency),
fee: Money.fromInt(newFee, currency),
@@ -2453,17 +2774,17 @@ abstract class ElectrumWalletBase
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();
+ transactionHistory.transactions.values.forEach((tx) {
+ if (tx.id == hash) {
+ tx.isReplaced = true;
+ tx.isPending = false;
+ transactionHistory.addOne(tx);
+ }
});
+ transactionHistory.addOne(transaction);
+ await updateAllUnspents();
+ await updateBalance();
+ });
} catch (e) {
throw e;
}
@@ -2530,6 +2851,7 @@ abstract class ElectrumWalletBase
final original = BtcTransaction.fromRaw(transactionHex);
final ins = <BtcTransaction?>[];
+ final insHex = <String?>[];
for (final vin in original.inputs) {
try {
@@ -2544,8 +2866,10 @@ abstract class ElectrumWalletBase
}
ins.add(inputTransactionHex.isEmpty ? null : BtcTransaction.fromRaw(inputTransactionHex));
+ insHex.add(inputTransactionHex);
} catch (_) {
ins.add(null);
+ insHex.add(null);
}
}
@@ -2554,19 +2878,27 @@ abstract class ElectrumWalletBase
ins: ins,
time: time,
confirmations: confirmations ?? 0,
+ hex: transactionHex,
+ insHex: insHex,
);
}
Future<ElectrumTransactionInfo?> fetchTransactionInfo(
{required String hash, int? height, bool? retryOnFailure}) async {
try {
- return ElectrumTransactionInfo.fromElectrumBundle(
- await getTransactionExpanded(hash: hash, height: height),
+ final bundle = await getTransactionExpanded(hash: hash, height: height);
+ final addressesByAccount = addressesSetByAccount;
+ final owner = _accountForTransaction(bundle, addressesByAccount);
+
+ final info = ElectrumTransactionInfo.fromElectrumBundle(
+ bundle,
walletInfo.type,
network,
- addresses: addressesSet,
+ addresses: owner != null ? addressesByAccount[owner]! : addressesSet,
height: height,
);
+ info.accountIndex = owner;
+ return info;
} catch (e) {
if (e is FormatException && retryOnFailure == true) {
await Future.delayed(const Duration(seconds: 2));
@@ -2585,14 +2917,17 @@ abstract class ElectrumWalletBase
Future<Map<String, ElectrumTransactionInfo>> fetchTransactions() async {
try {
final Map<String, ElectrumTransactionInfo> historiesWithDetails = {};
- ;
- printV('[BATCH_TEST] Fetching transactions with batch: $shouldUseBatchFetching');
+ printV("[BATCH_TEST] Fetching transactions with batch: $shouldUseBatchFetching");
if (type == WalletType.bitcoin) {
- await Future.wait(BITCOIN_ADDRESS_TYPES.map((type) => shouldUseBatchFetching
- ? fetchTransactionsForAddressTypeBatch(historiesWithDetails, type)
- : fetchTransactionsForAddressType(historiesWithDetails, type)));
+ if (isInitialBitcoinAccountsSync) {
+ await fetchBitcoinTransactionsForInitialRestore(historiesWithDetails);
+ } else {
+ await Future.wait(BITCOIN_ADDRESS_TYPES.map((type) => shouldUseBatchFetching
+ ? fetchTransactionsForAddressTypeBatch(historiesWithDetails, type)
+ : fetchTransactionsForAddressType(historiesWithDetails, type)));
+ }
} else if (type == WalletType.bitcoinCash) {
await Future.wait(BITCOIN_CASH_ADDRESS_TYPES.map((type) => shouldUseBatchFetching
? fetchTransactionsForAddressTypeBatch(historiesWithDetails, type)
@@ -2608,9 +2943,12 @@ abstract class ElectrumWalletBase
: fetchTransactionsForAddressType(historiesWithDetails, type)));
}
+ printV('[QUICK_SYNC] deferred ${_missingHistoryQueue.length} transactions to background');
+
transactionHistory.transactions.values.forEach((tx) async {
- final isPendingSilentPaymentUtxo =
- (tx.isPending || tx.confirmations == 0) && historiesWithDetails[tx.id] == null;
+ final isPendingSilentPaymentUtxo = (tx.isPending || tx.confirmations == 0) &&
+ historiesWithDetails[tx.id] == null &&
+ !_missingHistoryQueue.containsKey(tx.id);
if (isPendingSilentPaymentUtxo) {
final info =
@@ -2633,293 +2971,190 @@ abstract class ElectrumWalletBase
}
Future<void> fetchTransactionsForAddressType(
- Map<String, ElectrumTransactionInfo> historiesWithDetails,
- BitcoinAddressType type,
- ) async {
- final addressesByType =
- walletAddresses.allAddresses.where((addr) => addr.type == type).toList();
+ Map<String, ElectrumTransactionInfo> historiesWithDetails,
+ BitcoinAddressType type, {
+ int? accountIndex,
+ }) async {
+ final addressesByType = walletAddresses.allAddresses
+ .where((addr) => addr.type == type)
+ .where((addr) => accountIndex == null || addr.accountIndex == accountIndex)
+ .toList();
- final receiveStandard = getAddressBranchByType(hidden: false, legacy: false, type: type);
- final changeStandard = getAddressBranchByType(hidden: true, legacy: false, type: type);
- final receiveLegacy = getAddressBranchByType(hidden: false, legacy: true, type: type);
- final changeLegacy = getAddressBranchByType(hidden: true, legacy: true, type: type);
+
+ final branchCache = <String, List<BitcoinAddressRecord>>{};
+ List<BitcoinAddressRecord> branchFor(BitcoinAddressRecord record) =>
+ branchCache.putIfAbsent(
+ '${record.accountIndex}:${record.isHidden}:${record.isLegacyDerivation}',
+ () => getAddressBranchByType(
+ type: type,
+ hidden: record.isHidden,
+ legacy: record.isLegacyDerivation,
+ accountIndex: record.accountIndex,
+ ),
+ );
walletAddresses.hiddenAddresses
- .addAll([...changeStandard, ...changeLegacy].map((e) => e.address));
+ .addAll(addressesByType.where((addr) => addr.isHidden).map((e) => e.address));
await walletAddresses.saveAddressesInBox();
+
await Future.wait(addressesByType.map((addressRecord) async {
- final history = await _fetchAddressHistory(addressRecord, await getCurrentChainTip());
+ final result = await _fetchAddressHistory(addressRecord, await getCurrentChainTip());
- if (history.isNotEmpty) {
- addressRecord.txCount = history.length;
- historiesWithDetails.addAll(history);
+ if (result.hasHistory) {
+ historiesWithDetails.addAll(result.transactions);
- final matchedAddresses = addressRecord.isHidden
- ? (addressRecord.isLegacyDerivation ? changeLegacy : changeStandard)
- : (addressRecord.isLegacyDerivation ? receiveLegacy : receiveStandard);
- final isUsedAddressAboveGap = matchedAddresses.toList().indexOf(addressRecord) >=
- matchedAddresses.length -
+ final matchedAddresses = branchFor(addressRecord);
+ final isUsedAddressAboveGap = addressRecord.index >=
+ nextIndexOf(matchedAddresses) -
(addressRecord.isHidden
? ElectrumWalletAddressesBase.defaultChangeAddressesCount
: ElectrumWalletAddressesBase.defaultReceiveAddressesCount);
if (isUsedAddressAboveGap) {
- final prevLength = walletAddresses.allAddresses.length;
// Discover new addresses for the same address type until the gap limit is respected
await walletAddresses.discoverAddresses(
- matchedAddresses.toList(),
+ matchedAddresses,
addressRecord.isHidden,
- (address) async {
+ (address) async {
await subscribeForUpdates();
return _fetchAddressHistory(address, await getCurrentChainTip())
- .then((history) => history.isNotEmpty ? address.address : null);
+ .then((result) => result.hasHistory ? address.address : null);
},
type: type,
isLegacyDerivation: addressRecord.isLegacyDerivation,
+ accountIndex: addressRecord.accountIndex,
);
- 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 = {};
+ Future<AddressHistoryResult> _fetchAddressHistory(
+ BitcoinAddressRecord addressRecord, int? currentHeight) =>
+ _fetchAddressHistories([addressRecord], currentHeight, addressHistoryChunkSize);
- final history = await electrumClient.getHistory(addressRecord.getScriptHash(network));
+ Future<AddressHistoryResult> _fetchAddressHistories(
+ List<BitcoinAddressRecord> addressRecords,
+ int? currentHeight,
+ int historyChunkSize) async {
+ final scan = await _scanAddressHistories(addressRecords, historyChunkSize);
- if (history.isNotEmpty) {
- addressRecord.setAsUsed();
- walletAddresses.clearLockIfMatches(addressRecord.type, addressRecord.address);
+ final split = await _markUsedAndSplitHistory(scan, addressRecords, currentHeight);
- 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),
- );
- }
+ _enqueueMissingHistory(split.missingHistoryItems);
- await Future.wait(history.map((transaction) async {
- txid = transaction['tx_hash'] as String;
- final height = transaction['height'] as int;
- final storedTx = transactionHistory.transactions[txid];
+ return split;
+ }
- 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;
- }
+ void _enqueueMissingHistory(List<Map<String, dynamic>> missingHistoryItems) {
+ for (final item in missingHistoryItems) {
+ final txid = item['tx_hash'] as String?;
+ if (txid == null || txid.isEmpty) continue;
+ _missingHistoryQueue.putIfAbsent(txid, () => item);
+ }
+ }
- historiesWithDetails[txid] = storedTx;
- } else {
- final tx = await fetchTransactionInfo(hash: txid, height: height, retryOnFailure: true);
+ Future<void> resolveQueuedTransactionDetails() {
+ final inProgress = _resolveMissingHistoryFuture;
+ if (inProgress != null) return inProgress;
- if (tx != null) {
- historiesWithDetails[txid] = tx;
+ if (_missingHistoryQueue.isEmpty) return Future.value();
- // Got a new transaction fetched, add it to the transaction history
- // instead of waiting all to finish, and next time it will be faster
+ final future = _drainMissingHistoryQueue();
+ _resolveMissingHistoryFuture = future;
+ return future.whenComplete(() => _resolveMissingHistoryFuture = null);
+ }
- _applyLitecoinPegOutTag(tx);
- transactionHistory.addOne(tx);
- await transactionHistory.save();
- }
- }
+ Future<void> _drainMissingHistoryQueue() async {
+ final watch = Stopwatch()..start();
+ var resolvedCount = 0;
+ try {
+ printV('[QUICK_SYNC] resolving ${_missingHistoryQueue.length} deferred transactions');
- return Future.value(null);
- }));
+ while (_missingHistoryQueue.isNotEmpty) {
+ final queued = _missingHistoryQueue.values.toList(growable: false);
+ _missingHistoryQueue.clear();
+ final resolved = await _resolveTransactions(queued, addressHistoryChunkSize);
+ resolvedCount += resolved.length;
}
-
- return historiesWithDetails;
- } catch (e, stacktrace) {
- _onError?.call(FlutterErrorDetails(
- exception: "$txid - $e",
- stack: stacktrace,
- library: this.runtimeType.toString(),
- ));
- return {};
+ } finally {
+ printV(
+ '[QUICK_SYNC] resolved $resolvedCount deferred transactions in ${watch.elapsedMilliseconds} ms');
}
}
- Future<void> fetchTransactionsForAddressTypeBatch(
- Map<String, ElectrumTransactionInfo> historiesWithDetails, BitcoinAddressType type) async {
- final receiveStandard = getAddressBranchByType(hidden: false, legacy: false, type: type);
- final changeStandard = getAddressBranchByType(hidden: true, legacy: false, type: type);
- final receiveLegacy = getAddressBranchByType(hidden: false, legacy: true, type: type);
- final changeLegacy = getAddressBranchByType(hidden: true, legacy: true, type: type);
-
- walletAddresses.hiddenAddresses
- .addAll([...changeStandard, ...changeLegacy].map((e) => e.address));
- await walletAddresses.saveAddressesInBox();
+ Future<AddressHistoryScan> _scanAddressHistories(
+ List<BitcoinAddressRecord> addressRecords, int historyChunkSize) async {
+ final historyByScriptHash = <String, List<Map<String, dynamic>>>{};
+ var hadFailures = false;
- await fetchTransactionsForAddressesBranchBatch(
- historiesWithDetails,
- type,
- receiveStandard,
- isHidden: false,
- isLegacyDerivation: false,
- );
+ if (shouldUseBatchFetching) {
+ final scriptHashes = addressRecords.map((a) => a.getScriptHash(network)).toList();
- await fetchTransactionsForAddressesBranchBatch(
- historiesWithDetails,
- type,
- changeStandard,
- isHidden: true,
- isLegacyDerivation: false,
- );
+ historyByScriptHash.addAll(
+ await _processChunksToMap<String, String, List<Map<String, dynamic>>>(
+ items: scriptHashes,
+ chunkSize: historyChunkSize,
+ processChunk: _getHistoryBatch,
+ onChunkError: (chunk, error) {
+ hadFailures = true;
+ printV('address history scan failed for ${chunk.length} scripthashes: $error');
+ },
+ ),
+ );
- await fetchTransactionsForAddressesBranchBatch(
- historiesWithDetails,
- type,
- receiveLegacy,
- isHidden: false,
- isLegacyDerivation: true,
- );
-
- await fetchTransactionsForAddressesBranchBatch(
- historiesWithDetails,
- type,
- changeLegacy,
- isHidden: true,
- isLegacyDerivation: true,
- );
- }
-
- Future<void> fetchTransactionsForAddressesBranchBatch(
- Map<String, ElectrumTransactionInfo> historiesWithDetails,
- BitcoinAddressType type,
- List<BitcoinAddressRecord> branchAddresses, {
- required bool isHidden,
- required bool isLegacyDerivation,
- }) async {
- if (branchAddresses.isEmpty) return;
-
- final tip = await getCurrentChainTip();
- final currentBranch = [...branchAddresses];
-
- final initialHistory =
- await _processChunksToMap<BitcoinAddressRecord, String, ElectrumTransactionInfo>(
- items: currentBranch,
- chunkSize: addressHistoryChunkSize,
- processChunk: (chunk) => _fetchBatchAddressHistory(
- chunk,
- tip,
- addressHistoryChunkSize,
- ),
- );
-
- if (initialHistory.isNotEmpty) {
- historiesWithDetails.addAll(initialHistory);
+ return AddressHistoryScan(
+ historyByScriptHash: historyByScriptHash,
+ hadFailures: hadFailures,
+ );
}
- final gapLimit = isHidden
- ? ElectrumWalletAddressesBase.defaultChangeAddressesCount
- : ElectrumWalletAddressesBase.defaultReceiveAddressesCount;
+ await Future.wait(addressRecords.map((addressRecord) async {
+ final scriptHash = addressRecord.getScriptHash(network);
- final highestUsedIndex = _highestUsedIndex(currentBranch);
- final shouldDiscover =
- highestUsedIndex >= 0 && highestUsedIndex >= currentBranch.length - gapLimit;
-
- if (!shouldDiscover) return;
-
- final newAddresses = await walletAddresses.discoverAddressesBatch(
- currentBranch,
- isHidden,
- (newAddresses) async {
- final newHistory = await _fetchBatchAddressHistory(
- newAddresses,
- tip,
- discoveryHistoryChunkSize,
- );
-
- if (newHistory.isNotEmpty) {
- historiesWithDetails.addAll(newHistory);
- }
+ try {
+ historyByScriptHash[scriptHash] = await electrumClient.getHistory(scriptHash);
+ } catch (e) {
+ hadFailures = true;
+ printV('address history scan failed for ${addressRecord.address}: $e');
+ }
+ }));
- return newAddresses
- .where((addressRecord) => addressRecord.isUsed)
- .map((addressRecord) => addressRecord.address)
- .toSet();
- },
- type: type,
- isLegacyDerivation: isLegacyDerivation,
+ return AddressHistoryScan(
+ historyByScriptHash: historyByScriptHash,
+ hadFailures: hadFailures,
);
-
- if (newAddresses.isNotEmpty) {
- currentBranch.addAll(newAddresses);
-
- if (isHidden) {
- walletAddresses.hiddenAddresses.addAll(newAddresses.map((e) => e.address));
- await walletAddresses.saveAddressesInBox();
- }
- }
}
- List<BitcoinAddressRecord> getAddressBranchByType(
- {required bool hidden, required bool legacy, required BitcoinAddressType type}) =>
- walletAddresses.allAddresses
- .where((addr) =>
- addr.type == type && addr.isHidden == hidden && addr.isLegacyDerivation == legacy)
- .toList()
- ..sort((a, b) => a.index.compareTo(b.index));
-
- int _highestUsedIndex(List<BitcoinAddressRecord> addresses) {
- for (int i = addresses.length - 1; i >= 0; i--) {
- if (addresses[i].isUsed) return i;
- }
- return -1;
- }
+ Future<AddressHistoryResult> _markUsedAndSplitHistory(AddressHistoryScan scan,
+ List<BitcoinAddressRecord> addressRecords, int? currentHeight) async {
- Future<Map<String, ElectrumTransactionInfo>> _fetchBatchAddressHistory(
- List<BitcoinAddressRecord> addressRecords, int? currentHeight, int historyChunkSize) async {
String lastTxId = '';
bool didUpdateHistory = false;
try {
- final Map<String, ElectrumTransactionInfo> historiesWithDetails = {};
-
- // List of script hashes for the given address records
- final scriptHashes = addressRecords.map((a) => a.getScriptHash(network)).toList();
-
- final historyByScriptHash =
- await _processChunksToMap<String, String, List<Map<String, dynamic>>>(
- items: scriptHashes, chunkSize: historyChunkSize, processChunk: _getHistoryBatch);
+ final Map<String, ElectrumTransactionInfo> transactions = {};
+ final missingHistoryItems = <Map<String, dynamic>>[];
+ var hasHistory = false;
- // Map scriptHash -> addressRecord
final byScriptHash = <String, BitcoinAddressRecord>{};
for (final a in addressRecords) {
byScriptHash[a.getScriptHash(network)] = a;
}
- // Split into already-known txs vs missing txs
- final missingHistoryItems = <Map<String, dynamic>>[];
-
- for (final entry in historyByScriptHash.entries) {
+ for (final entry in scan.historyByScriptHash.entries) {
final sh = entry.key;
final addressRecord = byScriptHash[sh];
if (addressRecord == null) continue;
final history = entry.value;
if (history.isEmpty) continue;
+ hasHistory = true;
addressRecord.setAsUsed();
+ addressRecord.txCount = history.length;
walletAddresses.clearLockIfMatches(addressRecord.type, addressRecord.address);
//removes transactions no longer returned by the api, presumed replaced/invalid.
@@ -2935,7 +3170,6 @@ abstract class ElectrumWalletBase
}
}
- // For each transaction in the history, check if we already have it in our transaction history. If we do, update its details if necessary. If we don't, add it to the list of missing history items to fetch later.
for (final item in history) {
final txid = item['tx_hash'] as String?;
final height = item['height'] as int? ?? 0;
@@ -2944,14 +3178,27 @@ abstract class ElectrumWalletBase
lastTxId = txid;
final storedTx = transactionHistory.transactions[txid];
- if (storedTx != null) {
+ // If we've already tried resolving this tx's account owner
+ // several times and it still can't be determined, stop treating it
+ // as "missing" every scan - otherwise we'd refetch its full raw tx
+ // (and all its inputs' raw txs) forever with no chance of ever
+ // converging.
+ final hasExhaustedAccountRetries =
+ (_unresolvedAccountRetryCount[txid] ?? 0) >= _maxUnresolvedAccountRetries;
+ final needsAccount = type == WalletType.bitcoin &&
+ storedTx != null &&
+ storedTx.accountIndex == null &&
+ !hasExhaustedAccountRetries;
+
+ if (storedTx != null && !needsAccount) {
if (height > 0) {
final oldHeight = storedTx.height;
final oldConfs = storedTx.confirmations;
final oldPending = storedTx.isPending;
storedTx.height = height;
+ // the tx's block itself is the first confirmation so add 1
if ((currentHeight ?? 0) > 0) {
storedTx.confirmations = currentHeight! - height + 1;
}
@@ -2966,7 +3213,7 @@ abstract class ElectrumWalletBase
}
}
- historiesWithDetails[txid] = storedTx;
+ transactions[txid] = storedTx;
} else {
missingHistoryItems.add({
'tx_hash': txid,
@@ -2978,12 +3225,86 @@ abstract class ElectrumWalletBase
}
}
- // Batch fetch missing tx verbose details
- if (missingHistoryItems.isEmpty) {
- if (didUpdateHistory) await transactionHistory.save();
- return historiesWithDetails;
+ if (didUpdateHistory) {
+ await transactionHistory.save();
}
+ return AddressHistoryResult(
+ transactions: transactions,
+ missingHistoryItems: missingHistoryItems,
+ hasHistory: hasHistory,
+ hadFailures: scan.hadFailures,
+ );
+ } catch (e, stacktrace) {
+ final prefix = lastTxId.isNotEmpty ? '$lastTxId - ' : '';
+ _onError?.call(FlutterErrorDetails(
+ exception: '$prefix$e',
+ stack: stacktrace,
+ library: runtimeType.toString(),
+ ));
+ return AddressHistoryResult(
+ transactions: {},
+ missingHistoryItems: const [],
+ hasHistory: false,
+ hadFailures: true,
+ );
+ }
+ }
+
+ // Tracks how many times we've resolved a tx and still couldn't determine
+ // its owning account. Used by `_markUsedAndSplitHistory` to stop
+ // requeueing a tx forever when its account can never be determined.
+ void _trackAccountResolution(ElectrumTransactionInfo tx) {
+ if (type != WalletType.bitcoin) return;
+
+ if (tx.accountIndex == null) {
+ _unresolvedAccountRetryCount.update(tx.id, (count) => count + 1, ifAbsent: () => 1);
+ } else {
+ _unresolvedAccountRetryCount.remove(tx.id);
+ }
+ }
+
+ Future<Map<String, ElectrumTransactionInfo>> _resolveTransactions(
+ List<Map<String, dynamic>> missingHistoryItems, int historyChunkSize) async {
+ final Map<String, ElectrumTransactionInfo> resolved = {};
+
+ if (missingHistoryItems.isEmpty) return resolved;
+
+ if (!shouldUseBatchFetching) {
+ await Future.wait(missingHistoryItems.map((item) async {
+ final txid = (item['tx_hash'] as String).trim();
+ if (txid.isEmpty) return;
+
+ try {
+ final tx = await fetchTransactionInfo(
+ hash: txid,
+ height: item['height'] as int?,
+ retryOnFailure: true,
+ );
+
+ if (tx == null) return;
+
+ resolved[tx.id] = tx;
+
+ _trackAccountResolution(tx);
+
+ _applyLitecoinPegOutTag(tx);
+
+ transactionHistory.addOne(tx);
+ await transactionHistory.save();
+ } catch (e, stacktrace) {
+ _onError?.call(FlutterErrorDetails(
+ exception: '$txid - $e',
+ stack: stacktrace,
+ library: runtimeType.toString(),
+ ));
+ }
+ }));
+
+ return resolved;
+ }
+
+ try {
for (var i = 0; i < missingHistoryItems.length; i += historyChunkSize) {
final end = (i + historyChunkSize < missingHistoryItems.length)
? i + historyChunkSize
@@ -3006,35 +3327,235 @@ abstract class ElectrumWalletBase
retryDelay: const Duration(seconds: 1),
);
+ bool chunkUpdatedHistory = false;
+
for (final txid in hashes) {
final tx = infosByHash[txid];
if (tx == null) continue;
- historiesWithDetails[tx.id] = tx;
+ resolved[tx.id] = tx;
+
+ _trackAccountResolution(tx);
_applyLitecoinPegOutTag(tx);
transactionHistory.addOne(tx);
- didUpdateHistory = true;
+ chunkUpdatedHistory = true;
}
- }
- if (didUpdateHistory) {
- await transactionHistory.save();
+ if (chunkUpdatedHistory) {
+ await transactionHistory.save();
+ }
}
- return historiesWithDetails;
+ return resolved;
} catch (e, stacktrace) {
- final prefix = lastTxId.isNotEmpty ? '$lastTxId - ' : '';
_onError?.call(FlutterErrorDetails(
- exception: '$prefix$e',
+ exception: '$e',
stack: stacktrace,
library: runtimeType.toString(),
));
- return {};
+ return resolved;
+ }
+ }
+
+ Future<void> fetchBitcoinTransactionsForInitialRestore(
+ Map<String, ElectrumTransactionInfo> historiesWithDetails,
+ ) async {
+ int accountIndex = 0;
+
+ while (accountIndex < maxProbAccounts) {
+ final isAccountProbe = accountIndex > 0;
+
+ if (!mainHdByTypeAndAccount.containsKey(accountIndex)) {
+ _prepareHdForAccount(accountIndex, currency);
+ }
+
+ if (!walletAddresses.accountIndexes.contains(accountIndex)) {
+ walletAddresses.accountIndexes.add(accountIndex);
+ await walletAddresses.prepareAccountAddresses(
+ accountIndex,
+ types: isAccountProbe ? EXTRA_ACCOUNT_ADDRESS_TYPES : BITCOIN_ADDRESS_TYPES,
+ );
+ }
+
+ final probeTypes = isAccountProbe ? EXTRA_ACCOUNT_ADDRESS_TYPES : BITCOIN_ADDRESS_TYPES;
+
+ for (final addressType in probeTypes) {
+ if (shouldUseBatchFetching) {
+ await fetchTransactionsForAddressTypeBatch(
+ historiesWithDetails,
+ addressType,
+ accountIndex: accountIndex,
+ );
+ } else {
+ await fetchTransactionsForAddressType(
+ historiesWithDetails,
+ addressType,
+ accountIndex: accountIndex,
+ );
+ }
+ }
+
+ final accountHasHistory = walletAddresses.allAddresses
+ .where((addr) => addr.accountIndex == accountIndex)
+ .any((addr) => addr.isUsed);
+
+ if (!accountHasHistory) {
+ final persistedAccounts = await walletInfo.getAccounts();
+ final isUserAccount =
+ persistedAccounts.any((account) => account.accountIndex == accountIndex);
+
+ if (isAccountProbe && !isUserAccount) {
+ walletAddresses.accountIndexes.remove(accountIndex);
+ walletAddresses.removeAddressesForAccount(accountIndex);
+ }
+ break;
+ }
+
+ // If the account has history, add it to the wallet (if it's not the first account).
+ if (isAccountProbe) {
+ await walletInfo.addAccount(
+ accountIndex: accountIndex,
+ label: "Account $accountIndex",
+ );
+ }
+ // Move on to the next account index
+ accountIndex++;
+ }
+ if (electrumClient.isConnected) {
+ await walletInfo.setAccountDiscoveryLimit(maxProbAccounts);
}
}
+ Future<void> fetchTransactionsForAddressTypeBatch(
+ Map<String, ElectrumTransactionInfo> historiesWithDetails,
+ BitcoinAddressType type, {
+ int? accountIndex,
+ }) async {
+ final addressesByType = walletAddresses.allAddresses
+ .where((addr) => addr.type == type)
+ .where((addr) => accountIndex == null || addr.accountIndex == accountIndex)
+ .toList();
+
+ walletAddresses.hiddenAddresses
+ .addAll(addressesByType.where((addr) => addr.isHidden).map((e) => e.address));
+ await walletAddresses.saveAddressesInBox();
+
+ final accountIndexes = addressesByType.map((addr) => addr.accountIndex).toSet();
+
+ for (final account in accountIndexes) {
+ for (final isHidden in [false, true]) {
+ for (final isLegacyDerivation in [false, true]) {
+ await fetchTransactionsForAddressesBranchBatch(
+ historiesWithDetails,
+ type,
+ getAddressBranchByType(
+ type: type,
+ hidden: isHidden,
+ legacy: isLegacyDerivation,
+ accountIndex: account,
+ ),
+ isHidden: isHidden,
+ isLegacyDerivation: isLegacyDerivation,
+ accountIndex: account,
+ );
+ }
+ }
+ }
+ }
+
+
+ Future<void> fetchTransactionsForAddressesBranchBatch(
+ Map<String, ElectrumTransactionInfo> historiesWithDetails,
+ BitcoinAddressType type,
+ List<BitcoinAddressRecord> branchAddresses, {
+ required bool isHidden,
+ required bool isLegacyDerivation,
+ required int accountIndex,
+ }) async {
+ if (branchAddresses.isEmpty) return;
+
+ final tip = await getCurrentChainTip();
+ final currentBranch = [...branchAddresses];
+
+ final initialHistory =
+ await _processChunksToMap<BitcoinAddressRecord, String, ElectrumTransactionInfo>(
+ items: currentBranch,
+ chunkSize: addressHistoryChunkSize,
+ processChunk: (chunk) async =>
+ (await _fetchAddressHistories(chunk, tip, addressHistoryChunkSize)).transactions,
+ );
+
+ if (initialHistory.isNotEmpty) {
+ historiesWithDetails.addAll(initialHistory);
+ }
+
+ final gapLimit = isHidden
+ ? ElectrumWalletAddressesBase.defaultChangeAddressesCount
+ : ElectrumWalletAddressesBase.defaultReceiveAddressesCount;
+
+ final highestUsedIndex = _highestUsedIndex(currentBranch);
+ final shouldDiscover =
+ highestUsedIndex >= 0 && highestUsedIndex >= nextIndexOf(currentBranch) - gapLimit;
+
+ if (!shouldDiscover) return;
+
+ final newAddresses = await walletAddresses.discoverAddressesBatch(
+ currentBranch,
+ isHidden,
+ (newAddresses) async {
+ final newHistory =
+ await _fetchAddressHistories(newAddresses, tip, discoveryHistoryChunkSize);
+
+ if (newHistory.transactions.isNotEmpty) {
+ historiesWithDetails.addAll(newHistory.transactions);
+ }
+
+ return newAddresses
+ .where((addressRecord) => addressRecord.isUsed)
+ .map((addressRecord) => addressRecord.address)
+ .toSet();
+ },
+ type: type,
+ isLegacyDerivation: isLegacyDerivation,
+ accountIndex: accountIndex,
+ );
+
+ if (newAddresses.isNotEmpty) {
+ currentBranch.addAll(newAddresses);
+
+ if (isHidden) {
+ walletAddresses.hiddenAddresses.addAll(newAddresses.map((e) => e.address));
+ await walletAddresses.saveAddressesInBox();
+ }
+ }
+ }
+
+ List<BitcoinAddressRecord> getAddressBranchByType({
+ required BitcoinAddressType type,
+ required bool hidden,
+ required bool legacy,
+ int? accountIndex,
+ }) =>
+ walletAddresses.allAddresses
+ .where((addr) =>
+ addr.type == type &&
+ (accountIndex == null || addr.accountIndex == accountIndex) &&
+ addr.isHidden == hidden &&
+ addr.isLegacyDerivation == legacy)
+ .toList()
+ ..sort((a, b) => a.index.compareTo(b.index));
+
+ /// The derivation index of the highest used address, -1 when none is used.
+ /// [addresses] must be sorted by index, as [getAddressBranchByType] returns them.
+ int _highestUsedIndex(List<BitcoinAddressRecord> addresses) {
+ for (int i = addresses.length - 1; i >= 0; i--) {
+ if (addresses[i].isUsed) return addresses[i].index;
+ }
+ return -1;
+ }
+
Future<Map<String, Map<String, dynamic>>> _getTransactionVerboseBatch(List<String> hashes) {
return electrumClient.getBatchTransactionVerbose(
hashes,
@@ -3109,9 +3630,11 @@ abstract class ElectrumWalletBase
required Map<String, ElectrumTransactionInfo?> result,
required Map<String, int?>? heightsByHash,
}) async {
+ final addressesByAccount = addressesSetByAccount;
+
for (var i = 0; i < txIds.length; i += transactionChunkSize) {
final end =
- (i + transactionChunkSize < txIds.length) ? i + transactionChunkSize : txIds.length;
+ (i + transactionChunkSize < txIds.length) ? i + transactionChunkSize : txIds.length;
final chunk = txIds.sublist(i, end);
final bundlesByHash = await getTransactionExpandedBatch(
@@ -3127,14 +3650,17 @@ abstract class ElectrumWalletBase
continue;
}
+ final owner = _accountForTransaction(bundle, addressesByAccount);
+
final info = ElectrumTransactionInfo.fromElectrumBundle(
bundle,
walletInfo.type,
network,
- addresses: addressesSet,
+ addresses: owner != null ? addressesByAccount[owner]! : addressesSet,
height: heightsByHash?[txId],
);
info.id = txId;
+ info.accountIndex = owner;
result[txId] = info;
} catch (_) {
result[txId] = null;
@@ -3395,10 +3921,14 @@ abstract class ElectrumWalletBase
Future<void> updateTransactions() async {
printV("updateTransactions() called!");
+
+ if (_isTransactionUpdating) {
+ printV("updateTransactions: already running, skipping");
+ return;
+ }
+
+ _isTransactionUpdating = true;
try {
- if (_isTransactionUpdating) {
- return;
- }
currentChainTip = await getUpdatedChainTip();
bool updated = false;
@@ -3421,13 +3951,12 @@ abstract class ElectrumWalletBase
await transactionHistory.save();
}
- _isTransactionUpdating = true;
await fetchTransactions();
walletAddresses.updateReceiveAddresses();
- _isTransactionUpdating = false;
} catch (e, stacktrace) {
printV(stacktrace);
printV(e);
+ } finally {
_isTransactionUpdating = false;
}
}
@@ -3460,6 +3989,7 @@ abstract class ElectrumWalletBase
await updateBalance();
await _fetchAddressHistory(address, await getCurrentChainTip());
+ await resolveQueuedTransactionDetails();
} catch (e, s) {
printV("sub error: $e");
_onError?.call(FlutterErrorDetails(
@@ -3526,26 +4056,58 @@ abstract class ElectrumWalletBase
.where((address) => RegexUtils.addressTypeFromStr(address.address, network) is! MwebAddress)
.toList();
- final balances = shouldUseBatchFetching
- ? await fetchBalancesBatch(addresses)
- : await fetchBalancesRegular(addresses);
+ List<Map<String, dynamic>> balances;
+ try {
+ balances = shouldUseBatchFetching
+ ? await fetchBalancesBatch(addresses)
+ : await fetchBalancesRegular(addresses);
+ } catch (e) {
+ printV("fetchBalances network error, returning last known balance: $e");
+ syncStatus = LostConnectionSyncStatus();
+ return balance[currency] ??
+ ElectrumBalance(
+ confirmed: Money.zero(currency),
+ unconfirmed: Money.zero(currency),
+ frozen: Money.zero(currency),
+ );
+ }
printV(
'Fetched balances for ${addresses.length} addresses. Batch fetching: $shouldUseBatchFetching');
+ // If the balances list is empty (no addresses or all fetches silently returned nothing),
+ // preserve the last known balance rather than returning zero.
+ if (balances.isEmpty) {
+ return balance[currency] ??
+ ElectrumBalance(
+ confirmed: Money.zero(currency),
+ unconfirmed: Money.zero(currency),
+ frozen: Money.zero(currency),
+ );
+ }
+
var totalFrozen = 0;
var totalConfirmed = 0;
var totalUnconfirmed = 0;
+ final confirmedByAccount = <int, int>{};
+ final unconfirmedByAccount = <int, int>{};
+ final frozenByAccount = <int, int>{};
+
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;
+ final account = unspent.bitcoinAddressRecord.accountIndex;
+ if (unspent.isFrozen) {
+ totalFrozen += unspent.value;
+ frozenByAccount[account] = (frozenByAccount[account] ?? 0) + unspent.value;
+ }
totalConfirmed += unspent.value;
+ confirmedByAccount[account] = (confirmedByAccount[account] ?? 0) + unspent.value;
}
});
}
@@ -3562,12 +4124,16 @@ abstract class ElectrumWalletBase
element.value == info.value) {
if (info.isFrozen) {
totalFrozen += element.value;
+ final account = element.bitcoinAddressRecord.accountIndex;
+ frozenByAccount[account] = (frozenByAccount[account] ?? 0) + element.value;
}
}
});
});
- if (balances.isNotEmpty && balances.first['confirmed'] == null) {
+ // Check if ALL returned balances have null confirmed — indicates server is unreachable.
+ final allNull = balances.every((b) => b['confirmed'] == null);
+ if (allNull) {
// 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();
@@ -3587,24 +4153,100 @@ abstract class ElectrumWalletBase
totalConfirmed += confirmed;
totalUnconfirmed += unconfirmed;
+ final account = addressRecord.accountIndex;
+ confirmedByAccount[account] = (confirmedByAccount[account] ?? 0) + confirmed;
+ unconfirmedByAccount[account] = (unconfirmedByAccount[account] ?? 0) + unconfirmed;
+
addressRecord.balance = confirmed + unconfirmed;
if (confirmed > 0 || unconfirmed > 0) {
addressRecord.setAsUsed();
walletAddresses.clearLockIfMatches(addressRecord.type, addressRecord.address);
}
}
+ if (hasAccountsSupport) {
+ final perAccount = <int, ElectrumBalance>{};
+ final accounts = <int>{
+ ...confirmedByAccount.keys,
+ ...unconfirmedByAccount.keys,
+ ...frozenByAccount.keys,
+ ...walletAddresses.accountIndexes,
+ };
+
+ for (final account in accounts) {
+ perAccount[account] = ElectrumBalance(
+ confirmed: Money.fromInt(confirmedByAccount[account] ?? 0, currency),
+ unconfirmed: Money.fromInt(unconfirmedByAccount[account] ?? 0, currency),
+ frozen: Money.fromInt(frozenByAccount[account] ?? 0, currency),
+ );
+ }
+
+ accountBalances = ObservableMap<int, ElectrumBalance>.of(perAccount);
+ }
+
return ElectrumBalance(
confirmed: Money.fromInt(totalConfirmed, currency),
unconfirmed: Money.fromInt(totalUnconfirmed, currency),
frozen: Money.fromInt(totalFrozen, currency),
);
}
+ List<ElectrumTransactionInfo> get currentAccountBitcoinTransactions {
+ final all = transactionHistory.transactions.values;
+ if (!hasAccountsSupport) return all.toList();
+
+ final accountIndex = currentAccountIndex;
+ final accountAddresses = walletAddresses.allAddresses
+ .where((a) => a.accountIndex == accountIndex)
+ .map((a) => a.address)
+ .toSet();
+
+ return all.where((tx) {
+
+ if (tx.additionalInfo["isLightning"] == true) return accountIndex == 0;
+ if (tx.isReceivedSilentPayment) return accountIndex == 0;
+
+ // Locally created transactions store the account index explicitly,
+ // so use it first instead of checking the addresses.
+ if (tx.accountIndex != null) return tx.accountIndex == accountIndex;
+
+ return (tx.inputAddresses ?? const <String>[]).any(accountAddresses.contains) ||
+ (tx.outputAddresses ?? const <String>[]).any(accountAddresses.contains);
+ }).toList();
+ }
+
Future<void> updateBalance() async {
printV("updateBalance() called!");
- balance[currency] = await fetchBalances();
- await save();
+
+ if (!electrumClient.isConnected) {
+ printV("updateBalance: not connected, keeping existing balance");
+ return;
+ }
+
+ try {
+ final fetchedTotal = await fetchBalances();
+
+ if (!electrumClient.isConnected || syncStatus is LostConnectionSyncStatus) {
+ printV("updateBalance: connection lost during fetch, keeping existing balance");
+ return;
+ }
+
+ if (type == WalletType.bitcoin && hasAccountsSupport) {
+ // If the wallet has accounts support, we only want to update the balance for the current account.
+ final accountBalance = accountBalances[currentAccountIndex];
+ if (accountBalance != null) {
+ balance[currency] = accountBalance.copy();
+ } else {
+ printV("updateBalance: no balance for account $currentAccountIndex, keeping existing");
+ }
+ } else {
+ balance[currency] = fetchedTotal;
+ }
+
+ await save();
+ } catch (e) {
+ printV("updateBalance failed: $e");
+ }
}
@override
@@ -3642,7 +4284,7 @@ abstract class ElectrumWalletBase
}
final hd = addressRecord != null
- ? _hdFor(record: addressRecord).childKey(Bip32KeyIndex(addressRecord.index))
+ ? _hdForAddressRecord(record: addressRecord).childKey(Bip32KeyIndex(addressRecord.index))
: mainHd;
final priv = ECPrivate.fromHex(hd.privateKey.privKey.toHex());
@@ -3837,11 +4479,11 @@ abstract class ElectrumWalletBase
// Needs to re-subscribe to all scripthashes when reconnected
_scripthashesUpdateSubject = {};
- if (_isTryingToConnect) return;
+ if (_isTryingToConnect || _isClosed) return;
_isTryingToConnect = true;
- Timer(Duration(seconds: 5), () {
+ _reconnectTimer = Timer(Duration(seconds: 5), () {
if (this.syncStatus is NotConnectedSyncStatus ||
this.syncStatus is LostConnectionSyncStatus) {
this.electrumClient.connectToUri(
@@ -3970,7 +4612,7 @@ abstract class ElectrumWalletBase
);
if (result == null) {
- throw Exception('Call mechanism test returned null');
+ throw ElectrumResponseException('Call mechanism test returned null');
}
SocketHealthLogger().logHealthCheck(
@@ -4013,6 +4655,9 @@ abstract class ElectrumWalletBase
}
Future<void> _performFullReconnection() async {
+ if (_isClosed) {
+ return;
+ }
try {
SocketHealthLogger().logHealthCheck(
walletType: type,
@@ -4025,12 +4670,23 @@ abstract class ElectrumWalletBase
await _receiveStream?.cancel();
await electrumClient.close();
+ if (_isClosed) {
+ return;
+ }
+ // The new server session has no subscriptions yet.
+ _scripthashesUpdateSubject = {};
if (node != null) {
electrumClient.onConnectionStatusChange = _onConnectionStatusChange;
await electrumClient.connectToUri(node!.uri, useSSL: node!.useSSL);
+ // On failure the client reports `failed` and the 5 s retry takes over. Syncing with no
+ // socket would only fail.
+ if (!electrumClient.isConnected) {
+ return;
+ }
+
await startSync();
SocketHealthLogger().logHealthCheck(
@@ -4057,21 +4713,19 @@ abstract class ElectrumWalletBase
}
}
- Bip32Slip10Secp256k1 _hdFor({required BaseBitcoinAddressRecord record}) {
+ Bip32Slip10Secp256k1 _hdForAddressRecord({required BaseBitcoinAddressRecord record}) {
final addrType = record.type;
if (record.isLegacyDerivation) {
- if (record.isHidden) {
- return walletAddresses.legacySideHd;
- } else {
- return walletAddresses.legacyMainHd;
- }
+ return record.isHidden ? walletAddresses.legacySideHd : walletAddresses.legacyMainHd;
}
+ final accountIndex = record.accountIndex;
+
if (record.isHidden) {
- return sideHdByType[addrType] ?? sideHd;
+ return sideHdByTypeAndAccount[accountIndex]?[addrType] ?? sideHd;
} else {
- return mainHdByType[addrType] ?? mainHd;
+ return mainHdByTypeAndAccount[accountIndex]?[addrType] ?? mainHd;
}
}
}
@@ -4525,6 +5179,89 @@ class PublicKeyWithDerivationPath {
final String publicKey;
}
+({String txId, List<List<List<int>>> witnesses})? _parseRawTransaction(String? hex) {
+ try {
+ final raw = BytesUtils.fromHexString(hex!);
+ final isSegwit = raw[4] == 0 && raw[5] == 1;
+ var cursor = isSegwit ? 6 : 4;
+ final bodyStart = cursor;
+ int readVarint() {
+ final value = IntUtils.decodeVarint(raw.sublist(cursor, min(cursor + 9, raw.length)));
+ cursor += value.item2;
+ return value.item1;
+ }
+
+ final inputCount = readVarint();
+ for (var i = 0; i < inputCount; i++) {
+ cursor += 36;
+ final scriptLength = readVarint();
+ cursor += scriptLength + 4;
+ }
+ final outputCount = readVarint();
+ for (var i = 0; i < outputCount; i++) {
+ cursor += 8;
+ final scriptLength = readVarint();
+ cursor += scriptLength;
+ }
+ final body = raw.sublist(bodyStart, cursor);
+
+ final witnesses = <List<List<int>>>[];
+ for (var i = 0; isSegwit && i < inputCount; i++) {
+ final stack = <List<int>>[];
+ final itemCount = readVarint();
+ for (var j = 0; j < itemCount; j++) {
+ final length = readVarint();
+ stack.add(raw.sublist(cursor, cursor + length));
+ cursor += length;
+ }
+ witnesses.add(stack);
+ }
+ if (cursor + 4 != raw.length) return null;
+
+ final hash = QuickCrypto.sha256DoubleHash([...raw.sublist(0, 4), ...body, ...raw.sublist(cursor)]);
+ return (txId: BytesUtils.toHexString(hash.reversed.toList()), witnesses: witnesses);
+ } catch (_) {
+ return null;
+ }
+}
+
+bool _isSignedByOwnKey(ElectrumTransactionBundle bundle, List<UtxoWithAddress> utxos) {
+ final tx = bundle.originalTransaction;
+ final witnesses = _parseRawTransaction(bundle.hex)?.witnesses;
+ if (witnesses == null) return false;
+
+ final scriptPubKeys = utxos.map((utxo) => utxo.ownerDetails.address.toScriptPubKey()).toList();
+ final amounts = utxos.map((utxo) => utxo.utxo.value).toList();
+ for (var i = 0; i < utxos.length; i++) {
+ try {
+ final utxo = utxos[i].utxo;
+ final publicKey = utxos[i].public();
+ if (utxo.isP2tr()) {
+ final signature = witnesses[i].first;
+ final sighash =
+ signature.length == 65 ? signature.last : BitcoinOpCodeConst.TAPROOT_SIGHASH_ALL;
+ if (sighash > BitcoinOpCodeConst.SIGHASH_ALL) continue;
+ final digest = tx.getTransactionTaprootDigset(
+ txIndex: i, scriptPubKeys: scriptPubKeys, amounts: amounts, sighash: sighash);
+ if (publicKey.verifySchnorrTransactionSignature(digest, signature)) return true;
+ } else {
+ final signature = utxo.isSegwit()
+ ? witnesses[i][witnesses[i].length - 2]
+ : BytesUtils.fromHexString(tx.inputs[i].scriptSig.script.first as String);
+ if (signature.last != BitcoinOpCodeConst.SIGHASH_ALL) continue;
+ final script = utxo.scriptType == SegwitAddresType.p2wsh
+ ? publicKey.toP2wshRedeemScript()
+ : publicKey.toP2pkhAddress().toScriptPubKey();
+ final digest = utxo.isSegwit()
+ ? tx.getTransactionSegwitDigit(txInIndex: i, script: script, amount: utxo.value)
+ : tx.getTransactionDigest(txInIndex: i, script: script);
+ if (publicKey.verifyTransaactionSignature(digest, signature)) return true;
+ }
+ } catch (_) {}
+ }
+ return false;
+}
+
BitcoinAddressType _getScriptType(BitcoinBaseAddress type) {
if (type is P2pkhAddress) {
return P2pkhAddressType.p2pkh;
@@ -4566,3 +5303,27 @@ class UtxoDetails {
required this.spendsUnconfirmedTX,
});
}
+
+class AddressHistoryScan {
+ AddressHistoryScan({
+ required this.historyByScriptHash,
+ required this.hadFailures,
+ });
+
+ final Map<String, List<Map<String, dynamic>>> historyByScriptHash;
+ final bool hadFailures;
+}
+
+class AddressHistoryResult {
+ AddressHistoryResult({
+ required this.transactions,
+ required this.missingHistoryItems,
+ required this.hasHistory,
+ required this.hadFailures,
+ });
+
+ final Map<String, ElectrumTransactionInfo> transactions;
+ final List<Map<String, dynamic>> missingHistoryItems;
+ final bool hasHistory;
+ final bool hadFailures;
+}
\ No newline at end of file
### cw_bitcoin/lib/electrum_wallet_addresses.dart
@@ -1,13 +1,17 @@
+import 'dart:async' show Zone;
import 'dart:io' show Platform;
import 'dart:math';
+import "package:collection/collection.dart";
import 'package:bitcoin_base/bitcoin_base.dart';
import 'package:blockchain_utils/blockchain_utils.dart';
import 'package:breez_sdk_spark_flutter/breez_sdk_spark.dart';
import 'package:cw_bitcoin/bitcoin_address_record.dart';
import 'package:cw_bitcoin/bitcoin_unspent.dart';
+import "package:cw_bitcoin/electrum_wallet_exceptions.dart";
import 'package:cw_bitcoin/lightning/lightning_addres_type.dart';
import 'package:cw_bitcoin/lightning/lightning_wallet.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_bitcoin/electrum_derivations.dart';
import 'package:cw_core/unspent_coin_type.dart';
@@ -20,6 +24,10 @@ import 'package:mobx/mobx.dart';
part 'electrum_wallet_addresses.g.dart';
+class UnsupportedAddressTypeForAccountException extends CakeException {
+ UnsupportedAddressTypeForAccountException(super.message);
+}
+
abstract class ElectrumWalletAddresses = ElectrumWalletAddressesBase with _$ElectrumWalletAddresses;
const List<BitcoinAddressType> BITCOIN_ADDRESS_TYPES = [
@@ -30,6 +38,11 @@ const List<BitcoinAddressType> BITCOIN_ADDRESS_TYPES = [
P2shAddressType.p2wpkhInP2sh,
];
+const List<BitcoinAddressType> LEGACY_DUPLICATE_ADDRESS_TYPES = [
+ SegwitAddresType.p2wpkh,
+ SegwitAddresType.p2wsh,
+];
+
const List<BitcoinAddressType> LITECOIN_ADDRESS_TYPES = [
SegwitAddresType.p2wpkh,
SegwitAddresType.mweb,
@@ -43,11 +56,30 @@ const List<BitcoinAddressType> DOGECOIN_ADDRESS_TYPES = [
P2pkhAddressType.p2pkh,
];
+const List<BitcoinAddressType> EXTRA_ACCOUNT_ADDRESS_TYPES = [SegwitAddresType.p2wpkh];
+
+/// The index after the highest one on [branch] (0 when it's empty): where discovery continues.
+/// Counting the records instead falls short when lower indexes are missing, and runs ahead when an
+/// index appears twice.
+int nextIndexOf(Iterable<BaseBitcoinAddressRecord> branch) =>
+ branch.fold(-1, (int highest, record) => max(highest, record.index)) + 1;
+
+/// The lowest index not in [takenIndexes]: where a new address goes, so a branch grows without gaps.
+int firstFreeIndex(Set<int> takenIndexes) {
+ var index = 0;
+ while (takenIndexes.contains(index)) {
+ index++;
+ }
+ return index;
+}
+
abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
ElectrumWalletAddressesBase(
WalletInfo walletInfo, {
- required this.mainHdByType,
- required this.sideHdByType,
+ required this.mainHdByTypeAndAccount,
+ required this.sideHdByTypeAndAccount,
+ required this.accountIndexes,
+ required this.currentAccountIndex,
required this.legacyMainHd,
required this.legacySideHd,
required this.network,
@@ -72,12 +104,12 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
.toSet()),
currentReceiveAddressIndexByType = initialRegularAddressIndex ?? {},
currentChangeAddressIndexByType = initialChangeAddressIndex ?? {},
- _addressPageType = initialAddressPageType ??
- (walletInfo.addressPageType != null
- ? walletInfo.addressPageType == LightningAddressType.p2l.value
- ? LightningAddressType.p2l
- : BitcoinAddressType.fromValue(walletInfo.addressPageType!)
- : SegwitAddresType.p2wpkh),
+ _addressPageType = _resolveInitialAddressPageType(
+ initialAddressPageType: initialAddressPageType,
+ walletInfo: walletInfo,
+ mainHdByTypeAndAccount: mainHdByTypeAndAccount,
+ currentAccountIndex: currentAccountIndex,
+ ),
silentAddresses = ObservableList<BitcoinSilentPaymentAddressRecord>.of(
(initialSilentAddresses ?? []).toSet()),
currentSilentAddressIndex = initialSilentAddressIndex,
@@ -87,11 +119,13 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
lightningAddress = lightningWallet?.cachedAddress,
super(walletInfo) {
if (masterHd != null) {
+ final silentPaymentsHd = masterHd.derivePath(SILENT_PAYMENTS_ACCOUNT_PATH);
+
silentAddress = SilentPaymentOwner.fromPrivateKeys(
- b_scan:
- ECPrivate.fromHex(masterHd.derivePath(SILENT_PAYMENTS_SCAN_PATH).privateKey.toHex()),
- b_spend:
- ECPrivate.fromHex(masterHd.derivePath(SILENT_PAYMENTS_SPEND_PATH).privateKey.toHex()),
+ b_scan: ECPrivate.fromHex(
+ silentPaymentsHd.derivePath(SILENT_PAYMENTS_SCAN_SUBPATH).privateKey.toHex()),
+ b_spend: ECPrivate.fromHex(
+ silentPaymentsHd.derivePath(SILENT_PAYMENTS_SPEND_SUBPATH).privateKey.toHex()),
network: network,
);
@@ -142,12 +176,16 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
// TODO: add this variable in `litecoin_wallet_addresses` and just add a cast in cw_bitcoin to use it
final ObservableList<BitcoinAddressRecord> mwebAddresses;
final BasedUtxoNetwork network;
- Map<BitcoinAddressType, Bip32Slip10Secp256k1> mainHdByType;
- Map<BitcoinAddressType, Bip32Slip10Secp256k1> sideHdByType;
+ final Map<int, Map<BitcoinAddressType, Bip32Slip10Secp256k1>> mainHdByTypeAndAccount;
+ final Map<int, Map<BitcoinAddressType, Bip32Slip10Secp256k1>> sideHdByTypeAndAccount;
+ List<int> accountIndexes;
+
+ @observable
+ int currentAccountIndex;
final Bip32Slip10Secp256k1 legacyMainHd;
final Bip32Slip10Secp256k1 legacySideHd;
final bool isHardwareWallet;
- final LightningWallet? lightningWallet;
+ LightningWallet? lightningWallet;
@observable
ObservableMap<BitcoinAddressType, String> lockedReceiveAddressByType;
@@ -199,8 +237,16 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
"Error: Unable to fetch your Lightning address, please check your network connection.";
}
- final typeMatchingAddressesAll =
- _addresses.where((addr) => !addr.isHidden && _isAddressPageTypeMatch(addr)).toList();
+ final accountIndexForCheck = walletInfo.type == WalletType.bitcoin ? currentAccountIndex : 0;
+ if (!_isAddressTypeSupportedForAccount(addressPageType, accountIndexForCheck)) {
+ printV("addressPageType $addressPageType is not supported for account $accountIndexForCheck");
+ return "";
+ }
+
+ final typeMatchingAddressesAll = _addresses
+ .where((addr) =>
+ _isCurrentAccountAddress(addr) && !addr.isHidden && _isAddressPageTypeMatch(addr))
+ .toList();
// Prefer standard derivation addresses for the current/active address,
// but keep legacy addresses present in the overall address lists.
@@ -238,6 +284,7 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
final prev = previousAddressRecord;
if (prev != null &&
+ _isCurrentAccountAddress(prev) &&
prev.type == addressPageType &&
!prev.isUsed &&
!prev.isLegacyDerivation &&
@@ -303,8 +350,7 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
return silentAddress?.toString() ?? '';
}
- final mainHd = mainHdByType[addressPageType] ?? mainHdByType.values.first;
- return getAddress(index: 0, hd: mainHd, addressType: addressPageType);
+ return _firstAddressForType(addressPageType);
}
String get payjoinCompatibleAddress {
@@ -313,7 +359,18 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
? SegwitAddresType.p2wpkh
: addressPageType;
- final mainHd = mainHdByType[addrType] ?? mainHdByType.values.first;
+ return _firstAddressForType(addrType);
+ }
+
+ String _firstAddressForType(BitcoinAddressType addrType) {
+ final mainMap = walletInfo.type == WalletType.bitcoin
+ ? mainHdByTypeAndAccount[currentAccountIndex]
+ : mainHdByTypeAndAccount[0];
+
+ final mainHd = mainMap?[addrType] ?? mainMap?.values.first;
+
+ if (mainHd == null) return '';
+
return getAddress(index: 0, hd: mainHd, addressType: addrType);
}
@@ -355,7 +412,11 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
});
@override
- Future<void> init() async {
+ Future<void> init({List<int> accountIndexes = const []}) async {
+ final effectiveAccountIndexes =
+ accountIndexes.isNotEmpty ? accountIndexes : this.accountIndexes;
+
+ if (accountIndexes.isNotEmpty) this.accountIndexes = accountIndexes;
if (walletInfo.type == WalletType.bitcoinCash) {
await _generateInitialAddresses(type: P2pkhAddressType.p2pkh);
} else if (walletInfo.type == WalletType.litecoin) {
@@ -366,28 +427,20 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
} else if (walletInfo.type == WalletType.dogecoin) {
await _generateInitialAddresses(type: P2pkhAddressType.p2pkh);
} else if (walletInfo.type == WalletType.bitcoin) {
- await _generateInitialAddresses(isLegacyDerivation: true);
- await _generateInitialAddresses();
- if (!isHardwareWallet) {
- await _generateInitialAddresses(type: P2pkhAddressType.p2pkh, isLegacyDerivation: true);
- await _generateInitialAddresses(type: P2pkhAddressType.p2pkh);
-
- await _generateInitialAddresses(
- type: P2shAddressType.p2wpkhInP2sh, isLegacyDerivation: true);
- await _generateInitialAddresses(type: P2shAddressType.p2wpkhInP2sh);
-
- await _generateInitialAddresses(type: SegwitAddresType.p2tr, isLegacyDerivation: true);
- await _generateInitialAddresses(type: SegwitAddresType.p2tr);
+ for (final accountIndex in effectiveAccountIndexes) {
- await _generateInitialAddresses(type: SegwitAddresType.p2wsh, isLegacyDerivation: true);
- await _generateInitialAddresses(type: SegwitAddresType.p2wsh);
+ await prepareAccountAddresses(
+ accountIndex,
+ types: accountIndex == 0 ? BITCOIN_ADDRESS_TYPES : EXTRA_ACCOUNT_ADDRESS_TYPES,
+ includeLegacy: accountIndex == 0,
+ );
}
}
updateAddressesByMatch();
updateReceiveAddresses();
updateChangeAddresses();
- _validateAddresses();
+ await _validateAddresses();
await updateAddressesInBox();
if (currentReceiveAddressIndex >= receiveAddresses.length) {
@@ -407,9 +460,20 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
updateChangeAddresses();
if (changeAddresses.isEmpty) {
- final newAddresses = await _createNewAddresses(gap,
- startIndex: totalCountOfChangeAddresses > 0 ? totalCountOfChangeAddresses - 1 : 0,
- isHidden: true);
+ final takenIndexes = _takenStandardIndexes(
+ isHidden: true,
+ type: addressPageType,
+ accountIndex: currentAccountIndex,
+ );
+
+ final newAddresses = await _createNewAddresses(
+ gap,
+ startIndex: firstFreeIndex(takenIndexes),
+ isHidden: true,
+ type: addressPageType,
+ accountIndex: currentAccountIndex,
+ );
+
addAddresses(newAddresses);
}
@@ -423,6 +487,11 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
return address;
}
+ bool _isCurrentAccountAddress(BitcoinAddressRecord addressRecord) {
+ return walletInfo.type != WalletType.bitcoin ||
+ addressRecord.accountIndex == currentAccountIndex;
+ }
+
Map<String, String> get labels {
final G = ECPublic.fromBytes(BigintUtils.toBytes(Curves.generatorSecp256k1.x, length: 32));
final labels = <String, String>{};
@@ -440,10 +509,33 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
return labels;
}
+ Future<void> prepareAccountAddresses(
+ int accountIndex, {
+ List<BitcoinAddressType> types = BITCOIN_ADDRESS_TYPES,
+ bool includeLegacy = false,
+ }) async {
+ for (final type in types) {
+ final shouldSkipHardwareWalletType = isHardwareWallet && type != SegwitAddresType.p2wpkh;
+
+ if (shouldSkipHardwareWalletType) continue;
+
+ await _generateInitialAddresses(accountIndex: accountIndex, type: type);
+
+ // Legacy derivation for these types is identical to the standard one.
+ if (includeLegacy && !LEGACY_DUPLICATE_ADDRESS_TYPES.contains(type)) {
+ await _generateInitialAddresses(
+ accountIndex: accountIndex,
+ type: type,
+ isLegacyDerivation: true,
+ );
+ }
+ }
+ }
+
@action
BaseBitcoinAddressRecord generateNewAddress({String label = ''}) {
if (addressPageType is LightningAddressType) {
- throw Exception("Lightning addresses cannot be rotated");
+ throw ArgumentError("Lightning addresses cannot be rotated");
}
if (addressPageType == SilentPaymentsAddresType.p2sp && silentAddress != null) {
@@ -471,14 +563,24 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
return address;
}
- final newAddressIndex = addressesByReceiveType.fold(
- 0, (int acc, addressRecord) => addressRecord.isHidden == false ? acc + 1 : acc);
+ final accountIndex = walletInfo.type == WalletType.bitcoin ? currentAccountIndex : 0;
+
+ final newAddressIndex = firstFreeIndex(
+ _takenStandardIndexes(isHidden: false, type: addressPageType, accountIndex: accountIndex),
+ );
- final hd = _hdFor(isHidden: false, type: addressPageType, isLegacyDerivation: false);
+ final hd = _hdForAddressGeneration(
+ isHidden: false,
+ type: addressPageType,
+ isLegacyDerivation: false,
+ accountIndex: accountIndex,
+ );
final address = BitcoinAddressRecord(
getAddress(index: newAddressIndex, hd: hd, addressType: addressPageType),
index: newAddressIndex,
+ accountIndex: accountIndex,
isHidden: false,
+ isHiddenChecked: true,
isLegacyDerivation: false,
name: label,
type: addressPageType,
@@ -505,66 +607,75 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
}) async =>
getAddress(index: index, hd: hd, addressType: addressType);
- void addBitcoinAddressTypes() {
+ void addBitcoinAddressTypes(String activeAddress) {
final lastP2wpkh = _addresses
.where((addressRecord) =>
- _isUnusedReceiveAddressByType(addressRecord, SegwitAddresType.p2wpkh))
- .toList()
- .last;
- if (lastP2wpkh.address != address) {
- addressesMap[lastP2wpkh.address] = 'P2WPKH';
- } else {
- addressesMap[address] = 'Active - P2WPKH';
+ _isUnusedReceiveAddressByType(addressRecord, SegwitAddresType.p2wpkh))
+ .lastOrNull;
+ if (lastP2wpkh != null) {
+ if (lastP2wpkh.address != activeAddress) {
+ addressesMap[lastP2wpkh.address] = 'P2WPKH';
+ } else {
+ addressesMap[activeAddress] = 'Active - P2WPKH';
+ }
}
- final lastP2pkh = _addresses.firstWhere(
- (addressRecord) => _isUnusedReceiveAddressByType(addressRecord, P2pkhAddressType.p2pkh));
- if (lastP2pkh.address != address) {
- addressesMap[lastP2pkh.address] = 'P2PKH';
- } else {
- addressesMap[address] = 'Active - P2PKH';
+ final lastP2pkh = _addresses.firstWhereOrNull(
+ (addressRecord) => _isUnusedReceiveAddressByType(addressRecord, P2pkhAddressType.p2pkh));
+ if (lastP2pkh != null) {
+ if (lastP2pkh.address != activeAddress) {
+ addressesMap[lastP2pkh.address] = 'P2PKH';
+ } else {
+ addressesMap[activeAddress] = 'Active - P2PKH';
+ }
}
- final lastP2sh = _addresses.firstWhere((addressRecord) =>
+ final lastP2sh = _addresses.firstWhereOrNull((addressRecord) =>
_isUnusedReceiveAddressByType(addressRecord, P2shAddressType.p2wpkhInP2sh));
- if (lastP2sh.address != address) {
- addressesMap[lastP2sh.address] = 'P2SH';
- } else {
- addressesMap[address] = 'Active - P2SH';
+ if (lastP2sh != null) {
+ if (lastP2sh.address != activeAddress) {
+ addressesMap[lastP2sh.address] = 'P2SH';
+ } else {
+ addressesMap[activeAddress] = 'Active - P2SH';
+ }
}
- final lastP2tr = _addresses.firstWhere(
- (addressRecord) => _isUnusedReceiveAddressByType(addressRecord, SegwitAddresType.p2tr));
- if (lastP2tr.address != address) {
- addressesMap[lastP2tr.address] = 'P2TR';
- } else {
- addressesMap[address] = 'Active - P2TR';
+ final lastP2tr = _addresses.firstWhereOrNull(
+ (addressRecord) => _isUnusedReceiveAddressByType(addressRecord, SegwitAddresType.p2tr));
+ if (lastP2tr != null) {
+ if (lastP2tr.address != activeAddress) {
+ addressesMap[lastP2tr.address] = 'P2TR';
+ } else {
+ addressesMap[activeAddress] = 'Active - P2TR';
+ }
}
- final lastP2wsh = _addresses.firstWhere(
- (addressRecord) => _isUnusedReceiveAddressByType(addressRecord, SegwitAddresType.p2wsh));
- if (lastP2wsh.address != address) {
- addressesMap[lastP2wsh.address] = 'P2WSH';
- } else {
- addressesMap[address] = 'Active - P2WSH';
+ final lastP2wsh = _addresses.firstWhereOrNull(
+ (addressRecord) => _isUnusedReceiveAddressByType(addressRecord, SegwitAddresType.p2wsh));
+ if (lastP2wsh != null) {
+ if (lastP2wsh.address != activeAddress) {
+ addressesMap[lastP2wsh.address] = 'P2WSH';
+ } else {
+ addressesMap[activeAddress] = 'Active - P2WSH';
+ }
}
final firstSilentAddressRecord = silentAddresses.firstOrNull;
if (firstSilentAddressRecord != null) {
- if (firstSilentAddressRecord.address != address) {
+ if (firstSilentAddressRecord.address != activeAddress) {
addressesMap[firstSilentAddressRecord.address] = firstSilentAddressRecord.name.isEmpty
? "Silent Payments"
: "Silent Payments - ${firstSilentAddressRecord.name}";
} else {
- addressesMap[address] = 'Active - Silent Payments';
+ addressesMap[activeAddress] = 'Active - Silent Payments';
}
}
if (lightningAddress != null) {
- if (lightningAddress != address) {
+ if (lightningAddress != activeAddress) {
addressesMap[lightningAddress!] = 'LN';
} else {
- addressesMap[address] = 'Active - LN';
+ addressesMap[activeAddress] = 'Active - LN';
}
}
}
@@ -604,7 +715,11 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
Future<void> updateAddressesInBox() async {
try {
addressesMap.clear();
- addressesMap[address] = 'Active';
+ final activeAddress = addressPageType == LightningAddressType.p2l ||
+ addressPageType == SilentPaymentsAddresType.p2sp
+ ? addressForBuy
+ : address;
+ addressesMap[activeAddress] = 'Active';
allAddressesMap.clear();
_addresses.forEach((addressRecord) {
@@ -613,7 +728,7 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
switch (walletInfo.type) {
case WalletType.bitcoin:
- addBitcoinAddressTypes();
+ addBitcoinAddressTypes(activeAddress);
break;
case WalletType.litecoin:
addLitecoinAddressTypes();
@@ -678,22 +793,28 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
addressesByReceiveType.clear();
addressesByReceiveType.addAll(
- _addresses.where(_isAddressPageTypeMatch).toList(),
+ _addresses
+ .where((addressRecord) =>
+ _isCurrentAccountAddress(addressRecord) && _isAddressPageTypeMatch(addressRecord))
+ .toList(),
);
}
@action
void updateReceiveAddresses() {
receiveAddresses.removeRange(0, receiveAddresses.length);
- final newAddresses =
- _addresses.where((addressRecord) => !addressRecord.isHidden && !addressRecord.isUsed);
+ final newAddresses = _addresses.where((addressRecord) =>
+ _isCurrentAccountAddress(addressRecord) &&
+ !addressRecord.isHidden &&
+ !addressRecord.isUsed);
receiveAddresses.addAll(newAddresses);
}
@action
void updateChangeAddresses() {
changeAddresses.removeRange(0, changeAddresses.length);
final newAddresses = _addresses.where((addressRecord) =>
+ _isCurrentAccountAddress(addressRecord) &&
addressRecord.isHidden &&
!addressRecord.isUsed &&
// TODO: feature to change change address type. For now fixed to p2wpkh, the cheapest type
@@ -708,13 +829,15 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
Future<String?> Function(BitcoinAddressRecord) getAddressHistory, {
BitcoinAddressType type = SegwitAddresType.p2wpkh,
required bool isLegacyDerivation,
+ int accountIndex = 0,
}) async {
final newAddresses = await _createNewAddresses(
gap,
- startIndex: addressList.length,
+ startIndex: nextIndexOf(addressList),
isHidden: isHidden,
isLegacyDerivation: isLegacyDerivation,
type: type,
+ accountIndex: accountIndex,
);
addAddresses(newAddresses);
@@ -730,6 +853,7 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
getAddressHistory,
type: type,
isLegacyDerivation: isLegacyDerivation,
+ accountIndex: accountIndex,
);
}
}
@@ -741,13 +865,15 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
Future<Set<String>> Function(List<BitcoinAddressRecord>) getUsedAddresses, {
BitcoinAddressType type = SegwitAddresType.p2wpkh,
required bool isLegacyDerivation,
+ int accountIndex = 0,
}) async {
final newAddresses = await _createNewAddresses(
gap,
- startIndex: addressList.length,
+ startIndex: nextIndexOf(addressList),
isHidden: isHidden,
type: type,
isLegacyDerivation: isLegacyDerivation,
+ accountIndex: accountIndex,
);
addAddresses(newAddresses);
@@ -768,24 +894,26 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
getUsedAddresses,
type: type,
isLegacyDerivation: isLegacyDerivation,
+ accountIndex: accountIndex,
);
return [...newAddresses, ...moreNewAddresses];
}
- Future<void> _generateInitialAddresses(
- {BitcoinAddressType type = SegwitAddresType.p2wpkh, bool isLegacyDerivation = false}) async {
- // Legacy derivation produces the same addresses as standard for these types.
- // Don't generate a legacy set to avoid duplicates.
- if (isLegacyDerivation && (type == SegwitAddresType.p2wpkh || type == SegwitAddresType.p2wsh)) {
- return;
- }
+ Future<void> _generateInitialAddresses({
+ BitcoinAddressType type = SegwitAddresType.p2wpkh,
+ bool isLegacyDerivation = false,
+ int accountIndex = 0,
+ }) async {
+ if (isLegacyDerivation && accountIndex != 0) return;
var countOfReceiveAddresses = 0;
var countOfHiddenAddresses = 0;
_addresses.forEach((addr) {
- if (addr.type == type && addr.isLegacyDerivation == isLegacyDerivation) {
+ if (addr.accountIndex == accountIndex &&
+ addr.type == type &&
+ addr.isLegacyDerivation == isLegacyDerivation) {
if (addr.isHidden) {
countOfHiddenAddresses += 1;
} else {
@@ -800,7 +928,9 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
startIndex: countOfReceiveAddresses,
isHidden: false,
type: type,
- isLegacyDerivation: isLegacyDerivation);
+ isLegacyDerivation: isLegacyDerivation,
+ accountIndex: accountIndex);
+
addAddresses(newAddresses);
}
@@ -810,31 +940,49 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
startIndex: countOfHiddenAddresses,
isHidden: true,
type: type,
- isLegacyDerivation: isLegacyDerivation);
+ isLegacyDerivation: isLegacyDerivation,
+ accountIndex: accountIndex);
addAddresses(newAddresses);
}
}
- Future<List<BitcoinAddressRecord>> _createNewAddresses(int count,
- {int startIndex = 0,
- bool isHidden = false,
- BitcoinAddressType? type,
- bool isLegacyDerivation = false}) async {
+ Future<List<BitcoinAddressRecord>> _createNewAddresses(
+ int count, {
+ int startIndex = 0,
+ bool isHidden = false,
+ BitcoinAddressType? type,
+ bool isLegacyDerivation = false,
+ int accountIndex = 0,
+ }) async {
final list = <BitcoinAddressRecord>[];
for (var i = startIndex; i < count + startIndex; i++) {
final addrType = type ?? addressPageType;
- final hd = _hdFor(isHidden: isHidden, type: addrType, isLegacyDerivation: isLegacyDerivation);
- final address = BitcoinAddressRecord(
- await getAddressAsync(index: i, hd: hd, addressType: addrType),
- index: i,
- isHidden: isHidden,
- isLegacyDerivation: isLegacyDerivation,
- type: addrType,
- network: network,
- );
- list.add(address);
+ try {
+ final hd = _hdForAddressGeneration(
+ isHidden: isHidden,
+ type: addrType,
+ isLegacyDerivation: isLegacyDerivation,
+ accountIndex: accountIndex,
+ );
+
+ final address = BitcoinAddressRecord(
+ await getAddressAsync(index: i, hd: hd, addressType: addrType),
+ index: i,
+ isHidden: isHidden,
+ isHiddenChecked: true,
+ isLegacyDerivation: isLegacyDerivation,
+ type: addrType,
+ network: network,
+ accountIndex: accountIndex,
+ );
+ list.add(address);
+ } on UnsupportedAddressTypeForAccountException catch (e) {
+ printV("_createNewAddresses: skipping index $i, type $addrType, "
+ "account $accountIndex: $e");
+ return [];
+ }
}
return list;
@@ -869,35 +1017,72 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
updateAddressesByMatch();
}
- void _validateAddresses() {
- _addresses.forEach((element) async {
- if (element.type == SegwitAddresType.mweb) {
- // this would add a ton of startup lag for mweb addresses since we have 1000 of them
- return;
+ static const _validationTimeSlice = Duration(milliseconds: 16);
+
+ Future<void> _validateAddresses() async {
+ final addresses = _addresses.toList();
+ final slice = Stopwatch()..start();
+
+ for (final element in addresses) {
+ try {
+ await _validateAddress(element);
+ } catch (e, s) {
+ Zone.current.handleUncaughtError(e, s);
}
- final mainHd = _hdFor(
- isHidden: false, type: element.type, isLegacyDerivation: element.isLegacyDerivation);
- final sideHd = _hdFor(
- isHidden: true, type: element.type, isLegacyDerivation: element.isLegacyDerivation);
- if (!element.isHidden &&
- element.address !=
- await getAddressAsync(index: element.index, hd: mainHd, addressType: element.type)) {
- element.isHidden = true;
- } else if (element.isHidden &&
- element.address !=
- await getAddressAsync(index: element.index, hd: sideHd, addressType: element.type)) {
- element.isHidden = false;
+ if (slice.elapsed >= _validationTimeSlice) {
+ await Future<void>.delayed(Duration.zero);
+ slice.reset();
}
- });
+ }
+ }
+
+ Future<void> _validateAddress(BitcoinAddressRecord element) async {
+ if (element.isHiddenChecked) return;
+
+ if (element.type == SegwitAddresType.mweb) {
+ // this would add a ton of startup lag for mweb addresses since we have 1000 of them
+ return;
+ }
+
+ try {
+ // Relabel only when the address re-derives from the other chain. A record from a path these
+ // keys don't produce matches neither chain, so it keeps its label instead of flipping.
+ final otherChainHd = _hdForAddressGeneration(
+ isHidden: !element.isHidden,
+ type: element.type,
+ isLegacyDerivation: element.isLegacyDerivation,
+ accountIndex: element.accountIndex,
+ );
+ final otherChainAddress =
+ await getAddressAsync(index: element.index, hd: otherChainHd, addressType: element.type);
+ if (element.address == otherChainAddress) {
+ element.isHidden = !element.isHidden;
+ }
+ element.isHiddenChecked = true;
+ } on UnsupportedAddressTypeForAccountException catch (e) {
+ printV("_validateAddresses: skipping ${element.address}: $e");
+ }
}
@override
String get addressForBuy => super.addressForBuy;
@action
Future<void> setAddressType(BitcoinAddressType type) async {
- _addressPageType = type;
+
+ final needsAccountScopedHd =
+ type is! LightningAddressType && type != SilentPaymentsAddresType.p2sp;
+
+ BitcoinAddressType resolvedType = type;
+ if (needsAccountScopedHd) {
+ final accountIndex = walletInfo.type == WalletType.bitcoin ? currentAccountIndex : 0;
+ if (!_isAddressTypeSupportedForAccount(type, accountIndex)) {
+ resolvedType = EXTRA_ACCOUNT_ADDRESS_TYPES.first;
+ }
+ }
+
+ _addressPageType = resolvedType;
updateAddressesByMatch();
walletInfo.addressPageType = addressPageType.toString();
await walletInfo.save();
@@ -909,8 +1094,15 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
bool _isAddressByType(BitcoinAddressRecord addr, BitcoinAddressType type) => addr.type == type;
- bool _isUnusedReceiveAddressByType(BitcoinAddressRecord addr, BitcoinAddressType type) =>
- !addr.isHidden && !addr.isUsed && addr.type == type;
+ bool _isUnusedReceiveAddressByType(
+ BitcoinAddressRecord addressRecord,
+ BitcoinAddressType type,
+ ) {
+ return _isCurrentAccountAddress(addressRecord) &&
+ !addressRecord.isHidden &&
+ !addressRecord.isUsed &&
+ addressRecord.type == type;
+ }
@action
void deleteSilentPaymentAddress(String address) {
@@ -921,19 +1113,123 @@ abstract class ElectrumWalletAddressesBase extends WalletAddresses with Store {
updateAddressesByMatch();
}
- Bip32Slip10Secp256k1 _hdFor({
+ // Remove all addresses associated with a specific account index.
+ @action
+ Future<void> removeAddressesForAccount(int accountIndex) async {
+ _addresses.removeWhere((addr) => addr.accountIndex == accountIndex);
+ updateAddressesByMatch();
+ updateReceiveAddresses();
+ updateChangeAddresses();
+ await updateAddressesInBox();
+ }
+
+
+ bool _isAddressTypeSupportedForAccount(BitcoinAddressType type, int accountIndex) {
+ final effectiveAccountIndex = walletInfo.type == WalletType.bitcoin ? accountIndex : 0;
+ return mainHdByTypeAndAccount[effectiveAccountIndex]?.containsKey(type) ?? false;
+ }
+
+ static BitcoinAddressType _resolveInitialAddressPageType({
+ required BitcoinAddressType? initialAddressPageType,
+ required WalletInfo walletInfo,
+ required Map<int, Map<BitcoinAddressType, Bip32Slip10Secp256k1>> mainHdByTypeAndAccount,
+ required int currentAccountIndex,
+ }) {
+ final resolved = initialAddressPageType ??
+ (walletInfo.addressPageType != null
+ ? walletInfo.addressPageType == LightningAddressType.p2l.value
+ ? LightningAddressType.p2l
+ : BitcoinAddressType.fromValue(walletInfo.addressPageType!)
+ : SegwitAddresType.p2wpkh);
+
+ // Non-account-scoped address types (Lightning, Silent Payments) don't need
+ // an HD map entry.
+ if (resolved is LightningAddressType || resolved == SilentPaymentsAddresType.p2sp) {
+ return resolved;
+ }
+
+ final effectiveAccountIndex = walletInfo.type == WalletType.bitcoin ? currentAccountIndex : 0;
+
+ final isValid = mainHdByTypeAndAccount[effectiveAccountIndex]?.containsKey(resolved) ?? false;
+
+ if (!isValid) {
+ return EXTRA_ACCOUNT_ADDRESS_TYPES.first;
+ }
+
+ return resolved;
+ }
+
+ Bip32Slip10Secp256k1 _hdForAddressGeneration({
required bool isHidden,
required BitcoinAddressType type,
required bool isLegacyDerivation,
+ int accountIndex = 0,
}) {
- if (isLegacyDerivation) return isHidden ? legacySideHd : legacyMainHd;
+ if (isLegacyDerivation) {
+ if (accountIndex != 0) {
+ throw UnsupportedAddressTypeForAccountException(
+ "Legacy derivation is only supported for the first account");
+ }
+
+ return isHidden ? legacySideHd : legacyMainHd;
+ }
+
+ final effectiveAccountIndex = walletInfo.type == WalletType.bitcoin ? accountIndex : 0;
+
+ final map = isHidden
+ ? sideHdByTypeAndAccount[effectiveAccountIndex]
+ : mainHdByTypeAndAccount[effectiveAccountIndex];
+
+ if (map == null) {
+ throw UnsupportedAddressTypeForAccountException(
+ "HD map not found for account $effectiveAccountIndex");
+ }
- final map = isHidden ? sideHdByType : mainHdByType;
final hd = map[type];
- if (hd == null) throw Exception("HD not found for type $type");
+ if (hd == null) {
+ throw UnsupportedAddressTypeForAccountException(
+ "HD not found for account $accountIndex type $type");
+ }
+
return hd;
}
+ /// The indexes taken on the standard [type] chain of [accountIndex]: its own records, and the
+ /// legacy ones too when the legacy derivation has the same keys, since then they are the same
+ /// addresses.
+ Set<int> _takenStandardIndexes({
+ required bool isHidden,
+ required BitcoinAddressType type,
+ required int accountIndex,
+ }) {
+ var legacyIsSameChain = false;
+ try {
+ final standard = _hdForAddressGeneration(
+ isHidden: isHidden,
+ type: type,
+ isLegacyDerivation: false,
+ accountIndex: accountIndex,
+ );
+ final legacy = _hdForAddressGeneration(
+ isHidden: isHidden,
+ type: type,
+ isLegacyDerivation: true,
+ accountIndex: accountIndex,
+ );
+ legacyIsSameChain = standard.publicKey.toHex() == legacy.publicKey.toHex() &&
+ standard.chainCode.toHex() == legacy.chainCode.toHex();
+ } on UnsupportedAddressTypeForAccountException catch (_) {}
+
+ return {
+ for (final record in _addresses)
+ if (record.isHidden == isHidden &&
+ record.type == type &&
+ (walletInfo.type != WalletType.bitcoin || record.accountIndex == accountIndex) &&
+ (!record.isLegacyDerivation || legacyIsSameChain))
+ record.index,
+ };
+ }
+
@action
Future<void> setLightningAddress(String walletName, {String newAddress = ""}) async {
if (lightningWallet == null) return;
### cw_bitcoin/lib/electrum_wallet_exceptions.dart
@@ -0,0 +1,43 @@
+import "package:cw_core/exceptions/cake_exception.dart";
+import 'package:bitcoin_base/bitcoin_base.dart';
+
+class RbfException extends CakeException {
+ const RbfException(super.message);
+}
+
+class WalletKeysException extends CakeException {
+ const WalletKeysException(super.message);
+}
+
+class ElectrumResponseException extends ServerResponseException {
+ const ElectrumResponseException(super.message);
+}
+
+class PayjoinException extends CakeException {
+ const PayjoinException(super.message);
+}
+
+class PayjoinSenderInitException extends PayjoinException {
+ const PayjoinSenderInitException(super.message);
+}
+
+class PayjoinReceiverInitException extends PayjoinException {
+ const PayjoinReceiverInitException(super.message);
+}
+
+
+class PayjoinSenderException extends PayjoinException {
+ const PayjoinSenderException(super.message);
+}
+
+
+class BadAddressTypeException extends CakeException {
+ const BadAddressTypeException(super.message, this.addressType);
+
+ final BitcoinAddressType addressType;
+}
+
+
+class PayjoinReceiverException extends PayjoinException {
+ const PayjoinReceiverException(super.message);
+}
\ No newline at end of file
### cw_bitcoin/lib/hardware/bitbox_service.dart
@@ -1,47 +1,51 @@
-import 'dart:async';
-import 'dart:convert';
-import 'dart:developer';
-import 'dart:typed_data';
-
-import 'package:bitbox_flutter/bitbox_manager.dart';
-import 'package:bitcoin_base/bitcoin_base.dart';
-import 'package:blockchain_utils/blockchain_utils.dart';
-import 'package:cw_bitcoin/electrum_wallet.dart';
-import 'package:cw_bitcoin/hardware/bitcoin_hardware_wallet_service.dart';
-import 'package:cw_bitcoin/psbt/transaction_builder.dart';
-import 'package:cw_bitcoin/psbt/v0_deserialize.dart';
-import 'package:cw_bitcoin/psbt/v0_finalizer.dart';
-import 'package:cw_bitcoin/utils.dart';
-import 'package:cw_core/hardware/hardware_account_data.dart';
-import 'package:cw_core/hardware/hardware_wallet_service.dart';
-import 'package:ledger_bitcoin/psbt.dart';
+import "dart:async";
+import "dart:convert";
+import "dart:developer";
+import "dart:typed_data";
+
+import "package:bitbox_flutter/bitbox_flutter.dart";
+import "package:bitcoin_base/bitcoin_base.dart";
+import "package:blockchain_utils/blockchain_utils.dart";
+import "package:cw_bitcoin/electrum_wallet.dart";
+import "package:cw_bitcoin/hardware/bitcoin_hardware_wallet_service.dart";
+import "package:cw_bitcoin/psbt/transaction_builder.dart";
+import "package:cw_bitcoin/psbt/v0_deserialize.dart";
+import "package:cw_bitcoin/psbt/v0_finalizer.dart";
+import "package:cw_bitcoin/utils.dart";
+import "package:cw_core/hardware/hardware_account_data.dart";
+import "package:cw_core/hardware/hardware_wallet_service.dart";
+import "package:ledger_bitcoin/psbt.dart";
class BitcoinBitboxService extends HardwareWalletService with BitcoinHardwareWalletService {
BitcoinBitboxService(this.manager);
// https://github.com/BitBoxSwiss/bitbox02-api-go/blob/ae070b1d41bf1cf00588fa6f498b4734b5ecd6fc/api/firmware/messages/btc.pb.go#L40
static const int bitboxCoinType = 0;
- final BitboxManager manager;
+ final BitboxConnection manager;
+
+ BitboxBitcoin _getBitcoin() => BitboxBitcoin(manager.ffi, coinType: bitboxCoinType);
@override
Future<List<HardwareAccountData>> getAvailableAccounts({int index = 0, int limit = 5}) async {
final accounts = <HardwareAccountData>[];
final indexRange = List.generate(limit, (i) => i + index);
// https://github.com/BitBoxSwiss/bitbox02-api-go/blob/ae070b1d41bf1cf00588fa6f498b4734b5ecd6fc/api/firmware/messages/btc.pb.go#L252
- final keyType = 1; // xPUB
+ const keyType = 1; // xPUB
for (final i in indexRange) {
final derivationPath = "m/84'/0'/$i'";
- final xPub = await manager.getBTCXPub(bitboxCoinType, derivationPath, keyType);
+ final xPub = await _getBitcoin().getXPub(derivationPath, addressType: keyType);
final hd = Bip32Slip10Secp256k1.fromExtendedKey(xPub).childKey(Bip32KeyIndex(0));
final address = generateP2WPKHAddress(hd: hd, index: 0, network: BitcoinNetwork.mainnet);
- accounts.add(HardwareAccountData(
- address: address,
- accountIndex: i,
- derivationPath: derivationPath,
- xpub: xPub,
- ));
+ accounts.add(
+ HardwareAccountData(
+ address: address,
+ accountIndex: i,
+ derivationPath: derivationPath,
+ xpub: xPub,
+ ),
+ );
}
return accounts;
@@ -50,9 +54,9 @@ class BitcoinBitboxService extends HardwareWalletService with BitcoinHardwareWal
@override
Future<Uint8List> signTransaction({required String transaction}) async {
final psbt = PsbtV2()..deserialize(base64Decode(transaction));
- log(base64Encode(psbt.asPsbtV0()), name: 'PSBT');
- final signedPsbt = await manager.signBTCPsbt(bitboxCoinType, base64Encode(psbt.asPsbtV0()));
- log(signedPsbt, name: 'signed PSBT');
+ log(base64Encode(psbt.asPsbtV0()), name: "PSBT");
+ final signedPsbt = await _getBitcoin().signPsbt(base64Encode(psbt.asPsbtV0()));
+ log(signedPsbt, name: "signed PSBT");
final transactionRes = PsbtV2()
..deserializeV0(base64Decode(signedPsbt))
..finalizeV0();
@@ -61,48 +65,52 @@ class BitcoinBitboxService extends HardwareWalletService with BitcoinHardwareWal
@override
Future<Uint8List> signMessage({required Uint8List message, String? derivationPath}) =>
- manager.signBTCMessage(bitboxCoinType, derivationPath ?? "m/84'/0'/0'/0/0", message);
+ _getBitcoin().signMessage(derivationPath ?? "m/84'/0'/0'/0/0", message);
@override
- Future<Uint8List> getMasterFingerprint() => manager.getMasterFingerprint();
+ Future<Uint8List> getMasterFingerprint() => _getBitcoin().getMasterFingerprint();
}
class LitecoinBitboxService extends HardwareWalletService
with BitcoinHardwareWalletService, LitecoinHardwareWalletService {
LitecoinBitboxService(this.manager);
- final BitboxManager manager;
+ final BitboxConnection manager;
// https://github.com/BitBoxSwiss/bitbox02-api-go/blob/ae070b1d41bf1cf00588fa6f498b4734b5ecd6fc/api/firmware/messages/btc.pb.go#L40
static const int bitboxCoinType = 2;
+ BitboxBitcoin _getBitcoin() => BitboxBitcoin(manager.ffi, coinType: bitboxCoinType);
+
@override
Future<List<HardwareAccountData>> getAvailableAccounts({int index = 0, int limit = 5}) async {
final accounts = <HardwareAccountData>[];
final indexRange = List.generate(limit, (i) => i + index);
// https://github.com/BitBoxSwiss/bitbox02-api-go/blob/ae070b1d41bf1cf00588fa6f498b4734b5ecd6fc/api/firmware/messages/btc.pb.go#L252
- final keyType = 1; // xPUB
+ const keyType = 1; // xPUB
for (final i in indexRange) {
final derivationPath = "m/84'/2'/$i'";
- final xPub = await manager.getBTCXPub(bitboxCoinType, derivationPath, keyType);
+ final xPub = await _getBitcoin().getXPub(derivationPath, addressType: keyType);
final hd = Bip32Slip10Secp256k1.fromExtendedKey(xPub).childKey(Bip32KeyIndex(0));
final address = generateP2WPKHAddress(hd: hd, index: 0, network: LitecoinNetwork.mainnet);
- accounts.add(HardwareAccountData(
- address: address,
- accountIndex: i,
- derivationPath: derivationPath,
- xpub: xPub,
- ));
+ accounts.add(
+ HardwareAccountData(
+ address: address,
+ accountIndex: i,
+ derivationPath: derivationPath,
+ xpub: xPub,
+ ),
+ );
}
return accounts;
}
@override
Future<Uint8List> signMessage({required Uint8List message, String? derivationPath}) =>
- manager.signBTCMessage(bitboxCoinType, derivationPath ?? "m/84'/0'/0'/0/0", message);
+ _getBitcoin().signMessage(derivationPath ?? "m/84'/0'/0'/0/0", message);
@override
Future<String> signLitecoinTransaction({
@@ -112,7 +120,7 @@ class LitecoinBitboxService extends HardwareWalletService
}) async {
final psbt = PSBTTransactionBuild(inputs: inputs, outputs: outputs).psbt;
- final signedPsbt = await manager.signBTCPsbt(bitboxCoinType, base64Encode(psbt.asPsbtV0()));
+ final signedPsbt = await _getBitcoin().signPsbt(base64Encode(psbt.asPsbtV0()));
final transactionRes = PsbtV2()
..deserializeV0(base64Decode(signedPsbt))
..finalizeV0();
@@ -121,5 +129,5 @@ class LitecoinBitboxService extends HardwareWalletService
}
@override
- Future<Uint8List> getMasterFingerprint() => manager.getMasterFingerprint();
+ Future<Uint8List> getMasterFingerprint() => _getBitcoin().getMasterFingerprint();
}
### cw_bitcoin/lib/hardware/litecoin_trezor_service.dart
@@ -95,6 +95,6 @@ String _getScriptType(BitcoinAddressType addressType) {
case SegwitAddresType.p2wpkh:
return "PAYTOWITNESS";
default:
- throw Exception("Unknown Address Type");
+ throw ArgumentError("Unknown Address Type");
}
}
### cw_bitcoin/lib/lightning/lightning_wallet.dart
@@ -13,6 +13,21 @@ import 'package:cw_core/currency.dart';
import 'package:cw_core/transaction_direction.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_type.dart';
+import "dart:async";
+import "dart:io";
+import "dart:typed_data";
+
+import "package:breez_sdk_spark_flutter/breez_sdk_spark.dart";
+import "package:cw_bitcoin/bitcoin_transaction_priority.dart";
+import "package:cw_bitcoin/electrum_transaction_info.dart";
+import "package:cw_bitcoin/lightning/pending_lightning_transaction.dart";
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/currency.dart";
+import "package:cw_core/exceptions/cake_exception.dart";
+import "package:cw_core/transaction_direction.dart";
+import "package:cw_core/utils/print_verbose.dart";
+import "package:cw_core/wallet_type.dart";
bool _breezSdkSparkLibUninitialized = true;
Stream<LogEntry>? _logStream;
@@ -38,7 +53,7 @@ class LightningWallet {
String? cachedAddress;
- static int MAX_RETRIES = 10;
+ static int maxRetries = 10;
static bool get isAvailable => Platform.isIOS || Platform.isAndroid || Platform.isMacOS;
@@ -60,7 +75,10 @@ class LightningWallet {
if (!logFile.existsSync()) {
logFile.createSync(recursive: true);
}
- logFile.writeAsStringSync("[${logEntry.level}] ${logEntry.line}\n", mode: FileMode.append);
+ logFile.writeAsStringSync(
+ "${DateTime.now().toUtc().toIso8601String()} [${logEntry.level}] ${logEntry.line}\n",
+ mode: FileMode.append,
+ );
} catch (e) {
// Silently fail or use printV(e) so it doesn't crash the app
printV("Failed to write to log: $e");
@@ -70,7 +88,10 @@ class LightningWallet {
if (!logFile.existsSync()) {
logFile.createSync(recursive: true);
}
- logFile.writeAsStringSync("[ERROR] $e\n", mode: FileMode.append);
+ logFile.writeAsStringSync(
+ "${DateTime.now().toUtc().toIso8601String()} [ERROR] $e\n",
+ mode: FileMode.append,
+ );
} catch (err) {
printV("Failed to write error to log: $err");
}
@@ -122,16 +143,16 @@ class LightningWallet {
}
Future<void> close() async {
- _eventSubscription?.cancel();
+ unawaited(_eventSubscription?.cancel());
try {
await _sdk?.disconnect();
} catch (_) {}
- _logSubscription?.cancel();
+ unawaited(_logSubscription?.cancel());
}
Future<String?> getAddress() async {
var retries = 0;
- while (retries < MAX_RETRIES) {
+ while (retries < maxRetries) {
try {
final address = (await sdk.getLightningAddress())?.lightningAddress;
@@ -148,7 +169,9 @@ class LightningWallet {
}
Future<String> getDepositAddress() async => (await sdk.receivePayment(
- request: const ReceivePaymentRequest(paymentMethod: ReceivePaymentMethod.bitcoinAddress()),
+ request: const ReceivePaymentRequest(
+ paymentMethod: ReceivePaymentMethod.bitcoinAddress(newAddress: true),
+ ),
))
.paymentRequest;
@@ -251,7 +274,7 @@ class LightningWallet {
return res.payment.id;
} on SdkError_SparkError catch (e) {
if (e.field0.contains("AlreadyExists")) {
- throw Exception("Invoice already paid");
+ throw const TransactionSendingException("Invoice already paid");
}
rethrow;
}
@@ -321,7 +344,7 @@ class LightningWallet {
}
return PendingLightningTransaction(
- id: "", // ToDo: Find out where to get it
+ id: "",
amount: Money(prepareResponse.amount, currency),
fee: Money(fee, currency),
commitOverride: () async {
@@ -447,7 +470,8 @@ class LightningWallet {
} else if (sdkEvent is SdkEvent_ClaimedDeposits) {
onBalanceChangedEvent();
onUpdateDepositTransactionEvent(
- sdkEvent.claimedDeposits.map(_getElectrumTransactionInfoFromDepositInfo).toList());
+ sdkEvent.claimedDeposits.map(_getElectrumTransactionInfoFromDepositInfo).toList(),
+ );
} else if (sdkEvent is SdkEvent_UnclaimedDeposits) {
final unclaimedDeposits = <String, ElectrumTransactionInfo>{};
@@ -471,8 +495,8 @@ class LightningWallet {
}
String? preimage;
- if (payment.details != null && payment.details is PaymentDetails_Lightning) {
- preimage = (payment.details as PaymentDetails_Lightning).htlcDetails.preimage;
+ if (payment.details case final PaymentDetails_Lightning details) {
+ preimage = details.htlcDetails.preimage;
}
return ElectrumTransactionInfo(
### cw_bitcoin/lib/lightning/utils.dart
@@ -1,4 +1,4 @@
-import 'package:cw_core/lnurl.dart';
+import "package:cw_core/lnurl.dart";
String getLnurlOfLightningAddress(String lightningAddress) {
final parts = lightningAddress.split("@");
### cw_bitcoin/lib/litecoin_wallet.dart
@@ -5,15 +5,17 @@ import 'package:collection/collection.dart';
import 'package:crypto/crypto.dart';
import 'package:cw_bitcoin/address_from_output.dart';
import 'package:cw_bitcoin/bitcoin_transaction_credentials.dart';
+import "package:cw_bitcoin/electrum_wallet_exceptions.dart";
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/cake_hive.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/mweb_utxo.dart';
import 'package:cw_core/unspent_coin_type.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/node.dart';
import 'package:cw_mweb/mwebd.pbgrpc.dart';
import 'package:fixnum/fixnum.dart';
-import 'package:bip39/bip39.dart' as bip39;
+import 'package:cw_core/utils/bip39_seed.dart';
import 'package:bitcoin_base/bitcoin_base.dart';
import 'package:bitcoin_base/src/crypto/keypair/sign_utils.dart';
import 'package:blockchain_utils/blockchain_utils.dart';
@@ -28,6 +30,7 @@ import 'package:cw_bitcoin/electrum_derivations.dart';
import 'package:cw_bitcoin/electrum_transaction_info.dart';
import 'package:cw_bitcoin/electrum_wallet.dart';
import 'package:cw_bitcoin/electrum_wallet_snapshot.dart';
+import 'package:cw_bitcoin/unknown_derivation.dart';
import 'package:cw_bitcoin/hardware/bitcoin_hardware_wallet_service.dart';
import 'package:cw_bitcoin/litecoin_wallet_addresses.dart';
import 'package:cw_bitcoin/output_ordering.dart';
@@ -115,8 +118,10 @@ abstract class LitecoinWalletBase extends ElectrumWallet with Store {
initialRegularAddressIndex: initialRegularAddressIndex,
initialChangeAddressIndex: initialChangeAddressIndex,
initialMwebAddresses: initialMwebAddresses,
- mainHdByType: mainHdByType,
- sideHdByType: sideHdByType,
+ mainHdByTypeAndAccount: mainHdByTypeAndAccount,
+ sideHdByTypeAndAccount: sideHdByTypeAndAccount,
+ accountIndexes: [currentAccountIndex],
+ currentAccountIndex: currentAccountIndex,
legacyMainHd: mainHd,
legacySideHd: sideHd,
network: network,
@@ -203,10 +208,7 @@ abstract class LitecoinWalletBase extends ElectrumWallet with Store {
switch (derivationInfo.derivationType) {
case DerivationType.bip39:
- seedBytes = await bip39.mnemonicToSeed(
- mnemonic,
- passphrase: passphrase ?? "",
- );
+ seedBytes = bip39MnemonicToSeed(mnemonic, passphrase: passphrase ?? "");
break;
case DerivationType.electrum:
default:
@@ -278,16 +280,17 @@ abstract class LitecoinWalletBase extends ElectrumWallet with Store {
final derivationInfo = await walletInfo.getDerivationInfo();
// set the default if not present:
- derivationInfo.derivationPath ??= snp?.derivationPath ?? electrum_path;
derivationInfo.derivationType ??= snp?.derivationType ?? DerivationType.electrum;
if (derivationInfo.derivationType == DerivationType.unknown) {
- if (snp?.derivationPath == electrum_path || snp?.derivationType == DerivationType.electrum) {
- derivationInfo.derivationPath = electrum_path;
- derivationInfo.derivationType = DerivationType.electrum;
- } else {
- derivationInfo.derivationPath = segwit_path;
- derivationInfo.derivationType = DerivationType.bip39;
- }
+ resolveUnknownDerivation(
+ derivationInfo,
+ walletType: walletInfo.type,
+ mnemonic: keysData.mnemonic,
+ snapshotPath: snp?.derivationPath,
+ snapshotType: snp?.derivationType,
+ );
+ } else {
+ derivationInfo.derivationPath ??= snp?.derivationPath ?? electrum_path;
}
Uint8List? seedBytes = null;
@@ -297,10 +300,7 @@ abstract class LitecoinWalletBase extends ElectrumWallet with Store {
if (mnemonic != null) {
switch (derivationInfo.derivationType) {
case DerivationType.bip39:
- seedBytes = await bip39.mnemonicToSeed(
- mnemonic,
- passphrase: passphrase ?? "",
- );
+ seedBytes = bip39MnemonicToSeed(mnemonic, passphrase: passphrase ?? "");
break;
case DerivationType.electrum:
default:
@@ -648,7 +648,7 @@ abstract class LitecoinWalletBase extends ElectrumWallet with Store {
await _utxoStream?.cancel();
ResponseStream<Utxo>? responseStream = await CwMweb.utxos(req);
if (responseStream == null) {
- throw Exception("failed to get utxos stream!");
+ throw ElectrumResponseException("failed to get utxos stream!");
}
_utxoStream = responseStream.listen(
(Utxo sUtxo) async {
@@ -1026,7 +1026,7 @@ abstract class LitecoinWalletBase extends ElectrumWallet with Store {
bool isMweb = spendsMweb || paysToMweb;
if (isMweb && !mwebEnabled) {
- throw Exception("MWEB is not enabled! can't calculate fee without starting the mweb server!");
+ throw ArgumentError("MWEB is not enabled! can't calculate fee without starting the mweb server!");
// TODO: likely the change address is mweb and just not updated
}
@@ -1220,7 +1220,7 @@ abstract class LitecoinWalletBase extends ElectrumWallet with Store {
int confirmations = coin.confirmations ?? 0;
if (confirmations < 6) {
- throw Exception(
+ throw TransactionGenerationException(
"A transaction input is an MWEB peg-out and has less than 6 confirmations, please try again later.");
}
}
@@ -1283,7 +1283,7 @@ abstract class LitecoinWalletBase extends ElectrumWallet with Store {
printV(s);
if (e.toString().contains("commit failed")) {
printV(e);
- throw Exception("Transaction commit failed (no peers responded), please try again.");
+ throw TransactionSendingException("Transaction commit failed (no peers responded), please try again.");
}
rethrow;
}
@@ -1319,7 +1319,7 @@ abstract class LitecoinWalletBase extends ElectrumWallet with Store {
}
Future<void> commitPsbtUR(List<String> urCodes) async {
- if (urCodes.isEmpty) throw Exception("No QR code got scanned");
+ if (urCodes.isEmpty) throw ScanValueException("No QR code got scanned");
bool isUr = urCodes.any((str) {
return str.startsWith("ur:psbt/");
});
@@ -1365,6 +1365,7 @@ abstract class LitecoinWalletBase extends ElectrumWallet with Store {
final tx = PendingBitcoinTransaction(
btcTx,
type,
+ accountIndex: 0,
electrumClient: electrumClient,
amount: Money.zero(currency),
fee: Money.fromInt(resp.fee.toInt(), currency),
@@ -1384,7 +1385,7 @@ abstract class LitecoinWalletBase extends ElectrumWallet with Store {
printV(s);
if (e.toString().contains("commit failed")) {
printV(e);
- throw Exception("Transaction commit failed (no peers responded), please try again.");
+ throw TransactionSendingException("Transaction commit failed (no peers responded), please try again.");
}
rethrow;
}
### cw_bitcoin/lib/litecoin_wallet_addresses.dart
@@ -25,8 +25,10 @@ class LitecoinWalletAddresses = LitecoinWalletAddressesBase with _$LitecoinWalle
abstract class LitecoinWalletAddressesBase extends ElectrumWalletAddresses with Store {
LitecoinWalletAddressesBase(
WalletInfo walletInfo, {
- required super.mainHdByType,
- required super.sideHdByType,
+ required super.mainHdByTypeAndAccount,
+ required super.sideHdByTypeAndAccount,
+ required super.accountIndexes,
+ required super.currentAccountIndex,
required super.legacyMainHd,
required super.legacySideHd,
required super.network,
@@ -55,20 +57,22 @@ abstract class LitecoinWalletAddressesBase extends ElectrumWalletAddresses with
final String? scanSecretOverride;
final String? spendPubkeyOverride;
- List<int> get scanSecret => (scanSecretOverride != null && scanSecretOverride?.isNotEmpty == true)
- ? hex.decode(scanSecretOverride!)
- : mwebHd?.childKey(Bip32KeyIndex(0x80000000)).privateKey.privKey.raw ?? List.filled(32, 0);
+ late final List<int> scanSecret =
+ (scanSecretOverride != null && scanSecretOverride?.isNotEmpty == true)
+ ? hex.decode(scanSecretOverride!)
+ : mwebHd?.childKey(Bip32KeyIndex(0x80000000)).privateKey.privKey.raw ??
+ List.filled(32, 0);
- List<int> get spendPubkey =>
+ late final List<int> spendPubkey =
(spendPubkeyOverride != null && spendPubkeyOverride?.isNotEmpty == true)
? hex.decode(spendPubkeyOverride!)
: mwebHd?.childKey(Bip32KeyIndex(0x80000001)).publicKey.pubKey.compressed ??
List.filled(32, 0);
@override
- Future<void> init() async {
+ Future<void> init({List<int> accountIndexes = const []}) async {
if (!isHardwareWallet) await initMwebAddresses();
- await super.init();
+ await super.init(accountIndexes: accountIndexes);
}
@computed
@@ -227,6 +231,30 @@ abstract class LitecoinWalletAddressesBase extends ElectrumWalletAddresses with
return super.getChangeAddress();
}
+ // Not every sender can pay MWEB, so offer a regular address instead.
+ @override
+ String get addressForBuy {
+ if (addressPageType != SegwitAddresType.mweb) {
+ return super.addressForBuy;
+ }
+
+ try {
+ return super
+ .allAddresses
+ .firstWhere(
+ (e) =>
+ e.type == SegwitAddresType.p2wpkh &&
+ !e.isHidden &&
+ !e.isUsed &&
+ !e.isLegacyDerivation &&
+ !hiddenAddresses.contains(e.address),
+ )
+ .address;
+ } catch (_) {
+ return super.addressForBuy;
+ }
+ }
+
@override
String get addressForExchange {
// don't use mweb addresses for exchange refund address:
### cw_bitcoin/lib/litecoin_wallet_service.dart
@@ -3,6 +3,7 @@ import 'package:bitcoin_base/bitcoin_base.dart';
import 'package:cw_bitcoin/bitcoin_mnemonics_bip39.dart';
import 'package:cw_bitcoin/mnemonic_is_incorrect_exception.dart';
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/unspent_coins_info.dart';
import 'package:hive/hive.dart';
import 'package:cw_bitcoin/bitcoin_mnemonic.dart';
@@ -67,7 +68,7 @@ class LitecoinWalletService extends WalletService<
Future<LitecoinWallet> openWallet(String name, String password) async {
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
try {
@@ -100,7 +101,7 @@ class LitecoinWalletService extends WalletService<
File(await pathForWalletDir(name: wallet, type: getType())).delete(recursive: true);
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet, type: getType());
}
await WalletInfo.delete(walletInfo);
### cw_bitcoin/lib/payjoin/manager.dart
@@ -7,6 +7,7 @@ import 'dart:typed_data';
import 'package:bitcoin_base/bitcoin_base.dart';
import 'package:cw_bitcoin/bitcoin_wallet.dart';
import 'package:cw_bitcoin/bitcoin_wallet_addresses.dart';
+import "package:cw_bitcoin/electrum_wallet_exceptions.dart";
import 'package:cw_bitcoin/payjoin/payjoin_persister.dart';
import 'package:cw_bitcoin/payjoin/payjoin_receive_worker.dart';
import 'package:cw_bitcoin/payjoin/payjoin_send_worker.dart';
@@ -120,7 +121,7 @@ class PayjoinManager {
return Sender.load(token: senderToken, persister: persister);
} catch (e) {
- throw Exception('Error initializing Payjoin Sender: $e');
+ throw PayjoinSenderInitException('Error initializing Payjoin Sender: $e');
}
}
### cw_bitcoin/lib/payjoin/payjoin_persister.dart
@@ -1,3 +1,4 @@
+import "package:cw_bitcoin/electrum_wallet_exceptions.dart";
import 'package:payjoin_flutter/src/generated/api/receive.dart';
import 'package:payjoin_flutter/src/generated/api/send.dart';
@@ -21,7 +22,7 @@ class PayjoinSenderPersister implements DartSenderPersister {
Future<FfiSender> load({required SenderToken token}) async {
final sender = _store[token.toBytes().toString()];
if (sender == null) {
- throw Exception('Sender not found for the provided token.');
+ throw PayjoinSenderException('Sender not found for the provided token.');
}
return sender;
}
@@ -53,7 +54,7 @@ class PayjoinReceiverPersister implements DartReceiverPersister {
Future<FfiReceiver> load({required ReceiverToken token}) async {
final receiver = _store[token.toBytes().toString()];
if (receiver == null) {
- throw Exception('Receiver not found for the provided token.');
+ throw PayjoinReceiverException('Receiver not found for the provided token.');
}
return receiver;
}
### cw_bitcoin/lib/payjoin/payjoin_send_worker.dart
@@ -59,9 +59,9 @@ class PayjoinSenderWorker {
return await _runSenderV1(sender);
} else if (e is HttpException) {
printV(e);
- throw Exception(PayjoinSessionError.recoverable(e.toString()));
+ throw PayjoinSessionError.recoverable(e.toString());
} else {
- throw Exception(PayjoinSessionError.unrecoverable(e.toString()));
+ throw PayjoinSessionError.unrecoverable(e.toString());
}
}
}
### cw_bitcoin/lib/payjoin/payjoin_session_errors.dart
@@ -1,7 +1,7 @@
-class PayjoinSessionError {
- final String message;
+import "package:cw_core/exceptions/cake_exception.dart";
- const PayjoinSessionError._(this.message);
+class PayjoinSessionError extends CakeException{
+ const PayjoinSessionError._(super.message);
factory PayjoinSessionError.recoverable(String message) = RecoverableError;
factory PayjoinSessionError.unrecoverable(String message) = UnrecoverableError;
### cw_bitcoin/lib/pending_bitcoin_transaction.dart
@@ -21,6 +21,7 @@ class PendingBitcoinTransaction with PendingTransaction {
PendingBitcoinTransaction(
this._tx,
this.type, {
+ required this.accountIndex,
required this.electrumClient,
required this.amount,
required this.fee,
@@ -40,6 +41,7 @@ class PendingBitcoinTransaction with PendingTransaction {
final WalletType type;
final BtcTransaction _tx;
+ final int? accountIndex;
final ElectrumClient electrumClient;
final String feeRate;
final BasedUtxoNetwork? network;
@@ -182,6 +184,7 @@ class PendingBitcoinTransaction with PendingTransaction {
isPending: true,
isReplaced: false,
confirmations: 0,
+ accountIndex: accountIndex,
inputAddresses: _tx.inputs.map((input) => input.txId).toList(),
outputAddresses: outputAddresses,
fee: fee,
### cw_bitcoin/lib/psbt/signer.dart
@@ -6,6 +6,7 @@ import 'package:collection/collection.dart';
import 'package:cw_bitcoin/bitcoin_address_record.dart';
import 'package:cw_bitcoin/bitcoin_unspent.dart';
import 'package:cw_bitcoin/bitcoin_wallet.dart';
+import "package:cw_bitcoin/electrum_wallet_exceptions.dart";
import 'package:cw_bitcoin/utils.dart';
import 'package:ledger_bitcoin/psbt.dart';
import 'package:ledger_bitcoin/src/utils/buffer_writer.dart';
@@ -113,7 +114,7 @@ extension PsbtSigner on PsbtV2 {
Script _findLockingScript(UtxoWithAddress utxo, bool isTaproot) {
if (utxo.isMultiSig()) {
- throw Exception("MultiSig is not supported yet");
+ throw UnimplementedError("MultiSig is not supported yet");
}
final senderPub = utxo.public();
@@ -159,7 +160,7 @@ extension PsbtSigner on PsbtV2 {
}
return senderPub.toRedeemScript();
}
- throw Exception("invalid bitcoin address type");
+ throw BadAddressTypeException("invalid bitcoin address type", utxo.utxo.scriptType);
}
}
@@ -189,7 +190,7 @@ class UtxoWithPrivateKey extends UtxoWithAddress {
ECPrivateInfo? key;
if (inputPrivateKeyInfos.isEmpty) {
- throw Exception("No private keys generated.");
+ throw WalletKeysException("No private keys generated.");
} else {
key = inputPrivateKeyInfos.firstWhereOrNull((element) {
final elemPubkey = element.privkey.getPublic().toHex();
@@ -202,7 +203,7 @@ class UtxoWithPrivateKey extends UtxoWithAddress {
}
if (key == null) {
- throw Exception("${input.utxo.txHash} No Key found");
+ throw WalletKeysException("${input.utxo.txHash} No Key found");
}
return UtxoWithPrivateKey(
### cw_bitcoin/lib/psbt/v0_deserialize.dart
@@ -1,5 +1,6 @@
import 'package:bitcoin_base/bitcoin_base.dart';
import 'package:blockchain_utils/blockchain_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:flutter/foundation.dart';
import 'package:ledger_bitcoin/psbt.dart';
import 'package:ledger_bitcoin/src/psbt/map_extension.dart';
@@ -9,9 +10,8 @@ import 'package:ledger_bitcoin/src/utils/uint8list_extension.dart' as ext;
extension PsbtSigner on PsbtV2 {
void deserializeV0(Uint8List psbt) {
final bufferReader = BufferReader(psbt);
- if (!listEquals(
- bufferReader.readSlice(5), Uint8List.fromList([0x70, 0x73, 0x62, 0x74, 0xff]))) {
- throw Exception("Invalid magic bytes");
+ if (!listEquals(bufferReader.readSlice(5), Uint8List.fromList([0x70, 0x73, 0x62, 0x74, 0xff]))) {
+ throw DeserializeException("Invalid magic bytes");
}
while (_readKeyPair(globalMap, bufferReader)) {}
### cw_bitcoin/lib/unknown_derivation.dart
@@ -0,0 +1,61 @@
+import 'package:bip39/bip39.dart' as bip39;
+import 'package:collection/collection.dart';
+import 'package:cw_bitcoin/bitcoin_mnemonic.dart' as electrum_mnemonic;
+import 'package:cw_bitcoin/electrum_derivations.dart';
+import 'package:cw_core/wallet_info.dart';
+import 'package:cw_core/wallet_type.dart';
+
+/// Settles the derivation of a wallet whose saved type is [DerivationType.unknown], as left by the
+/// Hive → SQLite migration or by a wallet info row recreated without its derivation.
+///
+/// The seed type is the one the wallet file recorded ([snapshotType]); failing that, the one the
+/// mnemonic proves; failing that, the fallback the open code always had. A path that was saved is
+/// kept, so the wallet keeps deriving the addresses it had. Only a wallet with no saved path gets
+/// its type's default, which for Litecoin is Litecoin's own coin type.
+void resolveUnknownDerivation(
+ DerivationInfo derivationInfo, {
+ required WalletType walletType,
+ String? mnemonic,
+ String? snapshotPath,
+ DerivationType? snapshotType,
+}) {
+ final type = _recordedTypeOf(snapshotType) ??
+ _seedTypeOf(mnemonic) ??
+ (snapshotPath == electrum_path ? DerivationType.electrum : DerivationType.bip39);
+ final savedPath = [derivationInfo.derivationPath, snapshotPath]
+ .firstWhereOrNull((path) => path?.isNotEmpty ?? false);
+
+ derivationInfo.derivationType = type;
+ derivationInfo.derivationPath = savedPath ?? _defaultPath(type, walletType);
+}
+
+/// The type the wallet wrote into its own file at its last save, which is what it has been
+/// deriving with. The file loader reads a file that predates derivation tracking as electrum, and
+/// every such wallet was Electrum-stretched. Null when there is no file, or while the file still
+/// says `unknown` (v5.6.0–v5.6.4 wrote that for migrated rows).
+DerivationType? _recordedTypeOf(DerivationType? snapshotType) =>
+ snapshotType == DerivationType.electrum || snapshotType == DerivationType.bip39
+ ? snapshotType
+ : null;
+
+/// The seed type the mnemonic proves: an Electrum version prefix, or a valid BIP39 checksum. Null
+/// when it's both, neither, or there is no mnemonic (hardware and watch-only wallets).
+DerivationType? _seedTypeOf(String? mnemonic) {
+ if (mnemonic == null || mnemonic.isEmpty) {
+ return null;
+ }
+
+ final isElectrum = electrum_mnemonic.validateMnemonic(mnemonic);
+ final isBip39 = bip39.validateMnemonic(mnemonic);
+ if (isElectrum == isBip39) {
+ return null;
+ }
+ return isElectrum ? DerivationType.electrum : DerivationType.bip39;
+}
+
+String _defaultPath(DerivationType type, WalletType walletType) {
+ if (type == DerivationType.electrum) {
+ return electrum_path;
+ }
+ return walletType == WalletType.litecoin ? litecoin_segwit_path : segwit_path;
+}
### cw_bitcoin/pubspec.yaml
@@ -2,7 +2,6 @@ name: cw_bitcoin
description: A new Flutter package project.
version: 0.0.1
publish_to: none
-author: Cake Wallet
homepage: https://cakewallet.com
environment:
@@ -15,15 +14,10 @@ dependencies:
path_provider: ^2.0.11
http: ^1.1.0
mobx: ^2.6.0
- flutter_mobx: ^2.3.0
intl: any
shared_preferences: ^2.0.15
cw_core:
path: ../cw_core
- bitbox:
- git:
- url: https://github.com/cake-tech/bitbox-flutter.git
- ref: Add-Support-For-OP-Return-data
rxdart: ^0.28.0
cryptography: ^2.0.5
blockchain_utils:
@@ -57,15 +51,13 @@ dependencies:
ref: d1242cea90f84b00200e7bcab914a5af750e23fb
trezor_flutter:
git:
- url: https://github.com/cake-tech/trezor-flutter
- ref: f5121b1f3a06000ff836da8e6e6c83f53a9fa487
+ url: https://github.com/cake-tech/trezor-flutter.git
+ ref: 591d4b8c821b9c10561f848b866324a9a8dcb489
path: trezor-flutter
bitbox_flutter:
- path: ../scripts/bitbox_flutter
- socks_socket:
git:
- url: https://github.com/sneurlax/socks_socket
- ref: e6232c53c1595469931ababa878759a067c02e94
+ url: https://github.com/cake-tech/bitbox_flutter.git
+ ref: 3d1c607f14c6d5bace2971ec4c10b5201053cc56
ur:
git:
url: https://github.com/bukata-sa/bc-ur-dart
### cw_bitcoin/test/address_index_test.dart
@@ -0,0 +1,370 @@
+import "package:bitcoin_base/bitcoin_base.dart";
+import "package:blockchain_utils/blockchain_utils.dart";
+import "package:cw_bitcoin/bitcoin_address_record.dart";
+import "package:cw_bitcoin/bitcoin_wallet_addresses.dart";
+import "package:cw_bitcoin/electrum_wallet_addresses.dart";
+import "package:cw_bitcoin/payjoin/manager.dart";
+import "package:cw_bitcoin/utils.dart";
+import "package:cw_core/db/sqlite.dart";
+import "package:cw_core/wallet_info.dart";
+import "package:cw_core/wallet_type.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:sqflite_common_ffi/sqflite_ffi.dart";
+
+final Bip32Slip10Secp256k1 _master =
+ Bip32Slip10Secp256k1.fromSeed(List<int>.generate(64, (i) => i));
+
+Bip32Slip10Secp256k1 _hd(String path) => _master.derivePath(path) as Bip32Slip10Secp256k1;
+
+final Bip32Slip10Secp256k1 _p2wpkhReceiveHd = _hd("m/84'/0'/0'/0");
+final Bip32Slip10Secp256k1 _p2wpkhChangeHd = _hd("m/84'/0'/0'/1");
+final Bip32Slip10Secp256k1 _p2pkhReceiveHd = _hd("m/44'/0'/0'/0");
+final Bip32Slip10Secp256k1 _p2pkhChangeHd = _hd("m/44'/0'/0'/1");
+final Bip32Slip10Secp256k1 _legacyReceiveHd = _hd("m/0'/0");
+final Bip32Slip10Secp256k1 _legacyChangeHd = _hd("m/0'/1");
+
+BitcoinAddressRecord _record(
+ int index, {
+ BitcoinAddressType type = SegwitAddresType.p2wpkh,
+ bool isHidden = false,
+ bool isLegacyDerivation = false,
+ bool isUsed = false,
+ int accountIndex = 0,
+}) {
+ final Bip32Slip10Secp256k1 hd = _hd(
+ "m/1'/${type == P2pkhAddressType.p2pkh ? 44 : 84}'/$accountIndex'"
+ "/${isLegacyDerivation ? 1 : 0}'/${isHidden ? 1 : 0}",
+ );
+ final String address = type == P2pkhAddressType.p2pkh
+ ? generateP2PKHAddress(hd: hd, index: index, network: BitcoinNetwork.mainnet)
+ : generateP2WPKHAddress(hd: hd, index: index, network: BitcoinNetwork.mainnet);
+
+ return BitcoinAddressRecord(
+ address,
+ index: index,
+ type: type,
+ isHidden: isHidden,
+ isLegacyDerivation: isLegacyDerivation,
+ isUsed: isUsed,
+ accountIndex: accountIndex,
+ network: BitcoinNetwork.mainnet,
+ );
+}
+
+List<BitcoinAddressRecord> _range(
+ int start,
+ int end, {
+ BitcoinAddressType type = SegwitAddresType.p2wpkh,
+ bool isHidden = false,
+ bool isLegacyDerivation = false,
+ bool isUsed = false,
+ int accountIndex = 0,
+}) =>
+ [
+ for (int i = start; i < end; i++)
+ _record(
+ i,
+ type: type,
+ isHidden: isHidden,
+ isLegacyDerivation: isLegacyDerivation,
+ isUsed: isUsed,
+ accountIndex: accountIndex,
+ ),
+ ];
+
+class _NoPayjoin implements PayjoinManager {
+ @override
+ dynamic noSuchMethod(Invocation invocation) => throw UnimplementedError();
+}
+
+class _Addresses extends BitcoinWalletAddresses {
+ _Addresses(
+ super.walletInfo, {
+ required List<BitcoinAddressRecord> records,
+ required Bip32Slip10Secp256k1 legacyReceiveHd,
+ required Bip32Slip10Secp256k1 legacyChangeHd,
+ }) : super(
+ mainHdByTypeAndAccount: {
+ 0: {
+ SegwitAddresType.p2wpkh: _p2wpkhReceiveHd,
+ P2pkhAddressType.p2pkh: _p2pkhReceiveHd,
+ },
+ },
+ sideHdByTypeAndAccount: {
+ 0: {
+ SegwitAddresType.p2wpkh: _p2wpkhChangeHd,
+ P2pkhAddressType.p2pkh: _p2pkhChangeHd,
+ },
+ },
+ accountIndexes: [0],
+ currentAccountIndex: 0,
+ legacyMainHd: legacyReceiveHd,
+ legacySideHd: legacyChangeHd,
+ network: BitcoinNetwork.mainnet,
+ isHardwareWallet: false,
+ payjoinManager: _NoPayjoin(),
+ initialAddresses: records,
+ );
+
+ @override
+ Future<void> saveAddressesInBox() async {}
+}
+
+Future<_Addresses> _addresses(
+ List<BitcoinAddressRecord> records, {
+ BitcoinAddressType addressPageType = SegwitAddresType.p2wpkh,
+ bool legacyIsSameChain = false,
+}) async {
+ final WalletInfo walletInfo = WalletInfo.external(
+ id: "address_index_test",
+ name: "address_index_test",
+ type: WalletType.bitcoin,
+ isRecovery: false,
+ restoreHeight: 0,
+ date: DateTime(2026),
+ dirPath: "",
+ path: "",
+ address: "",
+ )..addressPageType = addressPageType.toString();
+
+ final _Addresses addresses = _Addresses(
+ walletInfo,
+ records: records,
+ legacyReceiveHd: legacyIsSameChain ? _p2wpkhReceiveHd : _legacyReceiveHd,
+ legacyChangeHd: legacyIsSameChain ? _p2wpkhChangeHd : _legacyChangeHd,
+ );
+ await walletInfo.getManualAddresses();
+ return addresses;
+}
+
+List<int> _indexes(Iterable<BaseBitcoinAddressRecord> records) =>
+ records.map((record) => record.index).toList();
+
+void main() {
+ setUpAll(() async {
+ sqfliteFfiInit();
+ db = await databaseFactoryFfi.openDatabase(inMemoryDatabasePath);
+ await db!.execute(
+ "CREATE TABLE IF NOT EXISTS walletInfoAddress "
+ "(walletInfoAddressId INTEGER PRIMARY KEY, walletInfoId INTEGER, type INTEGER, "
+ "address TEXT)",
+ );
+ });
+
+ group("nextIndexOf", () {
+ test("is 0 for an empty branch", () {
+ expect(nextIndexOf(<BitcoinAddressRecord>[]), 0);
+ });
+
+ test("is the length for a contiguous branch", () {
+ expect(nextIndexOf(_range(0, 22)), 22);
+ });
+
+ test("continues after the highest index when lower indexes are missing", () {
+ expect(nextIndexOf([..._range(0, 22), _record(44)]), 45);
+ });
+
+ test("is not pushed ahead by a duplicated index", () {
+ expect(nextIndexOf([..._range(0, 3), _record(2, isLegacyDerivation: true)]), 3);
+ });
+
+ test("does not depend on the order of the records", () {
+ expect(nextIndexOf([_record(7), _record(2), _record(5)]), 8);
+ });
+ });
+
+ group("firstFreeIndex", () {
+ test("is 0 when nothing is taken", () {
+ expect(firstFreeIndex(<int>{}), 0);
+ });
+
+ test("is the next index for a contiguous set", () {
+ expect(firstFreeIndex({0, 1, 2}), 3);
+ });
+
+ test("fills the lowest hole", () {
+ expect(firstFreeIndex({0, 1, 2, 4, 44}), 3);
+ });
+
+ test("is 0 when index 0 is missing", () {
+ expect(firstFreeIndex({1, 2, 3}), 0);
+ });
+ });
+
+ group("generateNewAddress", () {
+ test("ignores legacy records that derive different keys", () async {
+ final _Addresses addresses = await _addresses(
+ [
+ ..._range(0, 22, type: P2pkhAddressType.p2pkh),
+ ..._range(0, 22, type: P2pkhAddressType.p2pkh, isLegacyDerivation: true),
+ ],
+ addressPageType: P2pkhAddressType.p2pkh,
+ );
+
+ final BaseBitcoinAddressRecord address = addresses.generateNewAddress();
+
+ expect(address.index, 22);
+ expect(
+ address.address,
+ generateP2PKHAddress(hd: _p2pkhReceiveHd, index: 22, network: BitcoinNetwork.mainnet),
+ );
+ });
+
+ test("counts legacy records that derive the same keys", () async {
+ final _Addresses addresses = await _addresses(
+ [
+ ..._range(0, 3),
+ ..._range(0, 5, isLegacyDerivation: true),
+ ],
+ legacyIsSameChain: true,
+ );
+
+ expect(addresses.generateNewAddress().index, 5);
+ });
+
+ test("fills a hole left on the branch", () async {
+ final _Addresses addresses = await _addresses([..._range(0, 22), _record(44)]);
+
+ expect(addresses.generateNewAddress().index, 22);
+ await Future<void>.delayed(Duration.zero);
+ expect(addresses.generateNewAddress().index, 23);
+ });
+
+ test("ignores change records and other address types", () async {
+ final _Addresses addresses = await _addresses([
+ ..._range(0, 2),
+ ..._range(0, 10, isHidden: true),
+ ..._range(0, 10, type: P2pkhAddressType.p2pkh),
+ ]);
+
+ expect(addresses.generateNewAddress().index, 2);
+ });
+
+ test("ignores records of other accounts", () async {
+ final _Addresses addresses = await _addresses([
+ ..._range(0, 2),
+ ..._range(0, 10, accountIndex: 1),
+ ]);
+
+ expect(addresses.generateNewAddress().index, 2);
+ });
+
+ test("starts at 0 on an empty branch", () async {
+ final _Addresses addresses = await _addresses(<BitcoinAddressRecord>[]);
+
+ expect(addresses.generateNewAddress().index, 0);
+ });
+ });
+
+ group("getChangeAddress", () {
+ test("creates new change addresses from the lowest free index", () async {
+ final _Addresses addresses = await _addresses([
+ ..._range(0, 30),
+ ..._range(0, 3, isHidden: true, isUsed: true),
+ _record(5, isHidden: true, isUsed: true),
+ ]);
+
+ final BitcoinAddressRecord address = await addresses.getChangeAddress();
+
+ expect(address.index, 3);
+ expect(address.isHidden, isTrue);
+ expect(
+ address.address,
+ generateP2WPKHAddress(hd: _p2wpkhChangeHd, index: 3, network: BitcoinNetwork.mainnet),
+ );
+ });
+ });
+
+ group("discoverAddressesBatch", () {
+ test("starts at 0 on an empty branch", () async {
+ final _Addresses addresses = await _addresses(<BitcoinAddressRecord>[]);
+
+ final List<BitcoinAddressRecord> discovered = await addresses.discoverAddressesBatch(
+ <BitcoinAddressRecord>[],
+ false,
+ (_) async => <String>{},
+ isLegacyDerivation: false,
+ );
+
+ expect(_indexes(discovered), List<int>.generate(20, (i) => i));
+ });
+
+ test("continues at the length of a contiguous branch", () async {
+ final List<BitcoinAddressRecord> branch = _range(0, 22);
+ final _Addresses addresses = await _addresses(branch);
+
+ final List<BitcoinAddressRecord> discovered = await addresses.discoverAddressesBatch(
+ branch,
+ false,
+ (_) async => <String>{},
+ isLegacyDerivation: false,
+ );
+
+ expect(_indexes(discovered), List<int>.generate(20, (i) => 22 + i));
+ });
+
+ test("continues after the highest index of a branch with a hole", () async {
+ final List<BitcoinAddressRecord> branch = [..._range(0, 22), _record(44)];
+ final _Addresses addresses = await _addresses(branch);
+
+ final List<BitcoinAddressRecord> discovered = await addresses.discoverAddressesBatch(
+ branch,
+ false,
+ (_) async => <String>{},
+ isLegacyDerivation: false,
+ );
+
+ expect(_indexes(discovered), List<int>.generate(20, (i) => 45 + i));
+ });
+
+ test("keeps going from the highest index while the gap has a used address", () async {
+ final List<BitcoinAddressRecord> branch = [..._range(0, 22), _record(44)];
+ final _Addresses addresses = await _addresses(branch);
+ final String usedAddress =
+ generateP2WPKHAddress(hd: _p2wpkhReceiveHd, index: 50, network: BitcoinNetwork.mainnet);
+
+ final List<BitcoinAddressRecord> discovered = await addresses.discoverAddressesBatch(
+ branch,
+ false,
+ (_) async => {usedAddress},
+ isLegacyDerivation: false,
+ );
+
+ expect(_indexes(discovered), List<int>.generate(40, (i) => 45 + i));
+ });
+
+ test("continues after the highest change index", () async {
+ final List<BitcoinAddressRecord> branch = [
+ ..._range(0, 3, isHidden: true),
+ _record(9, isHidden: true),
+ ];
+ final _Addresses addresses = await _addresses(branch);
+
+ final List<BitcoinAddressRecord> discovered = await addresses.discoverAddressesBatch(
+ branch,
+ true,
+ (_) async => <String>{},
+ isLegacyDerivation: false,
+ );
+
+ expect(_indexes(discovered), List<int>.generate(20, (i) => 10 + i));
+ expect(discovered.every((record) => record.isHidden), isTrue);
+ });
+ });
+
+ group("discoverAddresses", () {
+ test("continues after the highest index of a branch with a hole", () async {
+ final List<BitcoinAddressRecord> branch = [..._range(0, 22), _record(44)];
+ final _Addresses addresses = await _addresses(branch);
+
+ await addresses.discoverAddresses(
+ branch,
+ false,
+ (_) async => null,
+ isLegacyDerivation: false,
+ );
+
+ expect(_indexes(branch.skip(23)), List<int>.generate(20, (i) => 45 + i));
+ });
+ });
+}
### cw_bitcoin/test/bitcoin_wallet_addresses_picker_test.dart
@@ -0,0 +1,194 @@
+import "package:bitcoin_base/bitcoin_base.dart";
+import "package:blockchain_utils/blockchain_utils.dart";
+import "package:cw_bitcoin/bitcoin_address_record.dart";
+import "package:cw_bitcoin/bitcoin_wallet_addresses.dart";
+import "package:cw_bitcoin/electrum_wallet_addresses.dart";
+import "package:cw_bitcoin/litecoin_wallet_addresses.dart";
+import "package:cw_bitcoin/payjoin/manager.dart";
+import "package:cw_bitcoin/utils.dart";
+import "package:cw_core/db/sqlite.dart";
+import "package:cw_core/wallet_info.dart";
+import "package:cw_core/wallet_type.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:sqflite_common_ffi/sqflite_ffi.dart";
+
+final _master = Bip32Slip10Secp256k1.fromSeed(List<int>.generate(64, (i) => i));
+
+Bip32Slip10Secp256k1 _hd(String path) => _master.derivePath(path) as Bip32Slip10Secp256k1;
+
+final _receiveHd = _hd("m/84'/0'/0'/0");
+final _changeHd = _hd("m/84'/0'/0'/1");
+final _receive = [
+ for (var i = 0; i < 5; i++)
+ generateP2WPKHAddress(hd: _receiveHd, network: BitcoinNetwork.mainnet, index: i),
+];
+
+final _ltcReceiveHd = _hd("m/84'/2'/0'/0");
+final _ltcChangeHd = _hd("m/84'/2'/0'/1");
+final _ltcReceive = [
+ for (var i = 0; i < 5; i++)
+ generateP2WPKHAddress(hd: _ltcReceiveHd, network: LitecoinNetwork.mainnet, index: i),
+];
+const _mweb = "ltcmweb1-placeholder";
+
+List<BitcoinAddressRecord> _records(List<String> receive, BasedUtxoNetwork network) => [
+ for (var i = 0; i < receive.length; i++)
+ BitcoinAddressRecord(
+ receive[i],
+ index: i,
+ type: SegwitAddresType.p2wpkh,
+ network: network,
+ ),
+ ];
+
+class _NoPayjoin implements PayjoinManager {
+ @override
+ dynamic noSuchMethod(Invocation invocation) => throw UnimplementedError();
+}
+
+class _BitcoinAddresses extends BitcoinWalletAddresses {
+ _BitcoinAddresses(super.walletInfo)
+ : super(
+ mainHdByTypeAndAccount: {
+ 0: {SegwitAddresType.p2wpkh: _receiveHd},
+ },
+ sideHdByTypeAndAccount: {
+ 0: {SegwitAddresType.p2wpkh: _changeHd},
+ },
+ accountIndexes: [0],
+ currentAccountIndex: 0,
+ legacyMainHd: _receiveHd,
+ legacySideHd: _changeHd,
+ network: BitcoinNetwork.mainnet,
+ isHardwareWallet: false,
+ payjoinManager: _NoPayjoin(),
+ masterHd: _master,
+ initialAddresses: [
+ ..._records(_receive, BitcoinNetwork.mainnet),
+ for (var i = 0; i < 3; i++)
+ BitcoinAddressRecord(
+ generateP2WPKHAddress(hd: _changeHd, network: BitcoinNetwork.mainnet, index: i),
+ index: i,
+ isHidden: true,
+ type: SegwitAddresType.p2wpkh,
+ network: BitcoinNetwork.mainnet,
+ ),
+ ],
+ );
+
+ @override
+ Future<void> saveAddressesInBox() async {}
+}
+
+class _LitecoinAddresses extends LitecoinWalletAddresses {
+ _LitecoinAddresses(super.walletInfo)
+ : super(
+ mainHdByTypeAndAccount: {
+ 0: {SegwitAddresType.p2wpkh: _ltcReceiveHd, SegwitAddresType.mweb: _ltcReceiveHd},
+ },
+ sideHdByTypeAndAccount: {
+ 0: {SegwitAddresType.p2wpkh: _ltcChangeHd, SegwitAddresType.mweb: _ltcChangeHd},
+ },
+ accountIndexes: [0],
+ currentAccountIndex: 0,
+ legacyMainHd: _ltcReceiveHd,
+ legacySideHd: _ltcChangeHd,
+ network: LitecoinNetwork.mainnet,
+ isHardwareWallet: false,
+ mwebHd: null,
+ mwebEnabled: true,
+ scanSecretOverride: null,
+ spendPubkeyOverride: null,
+ initialAddresses: [
+ ..._records(_ltcReceive, LitecoinNetwork.mainnet),
+ BitcoinAddressRecord(
+ _mweb,
+ index: 0,
+ type: SegwitAddresType.mweb,
+ network: LitecoinNetwork.mainnet,
+ ),
+ ],
+ );
+
+ @override
+ Future<void> saveAddressesInBox() async {}
+}
+
+WalletInfo _walletInfo(WalletType type, BitcoinAddressType? addressPageType) => WalletInfo.external(
+ id: "picker_test",
+ name: "picker_test",
+ type: type,
+ isRecovery: false,
+ restoreHeight: 0,
+ date: DateTime(2026),
+ dirPath: "",
+ path: "",
+ address: "",
+ )..addressPageType = addressPageType?.toString();
+
+Future<T> _ready<T extends ElectrumWalletAddresses>(T addresses) async {
+ // Lets the constructor's un-awaited used/hidden/manual loads land before the test edits them.
+ await addresses.walletInfo.getManualAddresses();
+ return addresses;
+}
+
+Future<_BitcoinAddresses> _bitcoin({BitcoinAddressType? addressPageType}) =>
+ _ready(_BitcoinAddresses(_walletInfo(WalletType.bitcoin, addressPageType)));
+
+Future<_LitecoinAddresses> _litecoin({BitcoinAddressType? addressPageType}) =>
+ _ready(_LitecoinAddresses(_walletInfo(WalletType.litecoin, addressPageType)));
+
+void main() {
+ setUpAll(() async {
+ sqfliteFfiInit();
+ db = await databaseFactoryFfi.openDatabase(inMemoryDatabasePath);
+ await db!.execute(
+ "CREATE TABLE walletInfoAddress "
+ "(walletInfoAddressId INTEGER PRIMARY KEY, walletInfoId INTEGER, type INTEGER, "
+ "address TEXT)",
+ );
+ });
+
+ test("addressForBuy skips hidden addresses", () async {
+ final addresses = await _bitcoin();
+ expect(addresses.addressForBuy, _receive[0]);
+
+ addresses.hiddenAddresses.add(_receive[0]);
+
+ expect(addresses.addressForBuy, _receive[1]);
+ });
+
+ test("on the Silent Payments page, the SegWit address is active", () async {
+ final addresses = await _bitcoin(addressPageType: SilentPaymentsAddresType.p2sp);
+ addresses.hiddenAddresses.add(_receive[0]);
+
+ await addresses.updateAddressesInBox();
+
+ expect(addresses.address, addresses.silentAddress.toString());
+ expect(addresses.addressesMap[_receive[1]], "Active");
+ expect(addresses.addressesMap[addresses.silentAddress.toString()], "Silent Payments");
+ expect(addresses.addressesMap.containsKey(_receive[0]), isFalse);
+ });
+
+ test("on the MWEB page, the MWEB address is active but buy uses a regular address", () async {
+ final addresses = await _litecoin(addressPageType: SegwitAddresType.mweb);
+ addresses.hiddenAddresses.add(_ltcReceive[0]);
+
+ await addresses.updateAddressesInBox();
+
+ expect(addresses.address, _mweb);
+ expect(addresses.addressesMap[_mweb], "Active - MWEB");
+ expect(addresses.addressesMap.values.where((label) => label.startsWith("Active")), hasLength(1));
+ expect(addresses.addressForBuy, _ltcReceive[1]);
+ });
+
+ test("on the Litecoin SegWit page, its own address stays active", () async {
+ final addresses = await _litecoin();
+
+ await addresses.updateAddressesInBox();
+
+ expect(addresses.addressForBuy, addresses.address);
+ expect(addresses.addressesMap[_ltcReceive[0]], "Active");
+ expect(addresses.addressesMap[_mweb], "MWEB");
+ });
+}
### cw_bitcoin/test/electrum_client_connect_test.dart
@@ -0,0 +1,280 @@
+import "dart:async";
+import "dart:convert";
+import "dart:io";
+
+import "package:cw_bitcoin/electrum.dart";
+import "package:cw_core/utils/proxy_socket/abstract.dart";
+import "package:cw_core/utils/proxy_wrapper.dart";
+import "package:cw_core/utils/tor/disabled.dart";
+import "package:cw_core/utils/tor/socks.dart";
+import "package:flutter_test/flutter_test.dart";
+
+/// Electrum server stand-in that answers every request with a null result.
+class _FakeServer {
+ _FakeServer._(this.server);
+
+ final ServerSocket server;
+ final clients = <Socket>[];
+
+ /// [closeDelay]: after the client closes its side, wait this long before closing ours.
+ static Future<_FakeServer> start({Duration closeDelay = Duration.zero}) async {
+ final fake = _FakeServer._(await ServerSocket.bind(InternetAddress.loopbackIPv4, 0));
+ fake.server.listen((c) {
+ fake.clients.add(c);
+ c.cast<List<int>>().transform(utf8.decoder).transform(const LineSplitter()).listen(
+ (line) {
+ final id = (json.decode(line) as Map)["id"];
+ c.write('{"jsonrpc":"2.0","result":null,"id":${json.encode(id)}}\n');
+ },
+ onDone: () => Future.delayed(closeDelay, () => c.destroy()),
+ onError: (_) {},
+ );
+ });
+ return fake;
+ }
+
+ Uri get uri => Uri.parse("tcp://127.0.0.1:${server.port}");
+}
+
+Future<int> _refusedPort() async {
+ final s = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
+ final port = s.port;
+ await s.close();
+ return port;
+}
+
+/// SOCKS5 stand-in for Tor. [connectReply] null = never answer CONNECT, as Tor does while it has
+/// no circuit. On 0x00 the stream is piped to 127.0.0.1:[pipeToPort] after [replyDelay].
+/// [closed] gets one future per accepted client, completing when that client goes away.
+Future<ServerSocket> _fakeTor({
+ int? connectReply,
+ int? pipeToPort,
+ Duration replyDelay = Duration.zero,
+ List<Future<void>>? closed,
+}) async {
+ final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
+ server.listen((c) {
+ final gone = Completer<void>();
+ closed?.add(gone.future);
+ var stage = 0;
+ Socket? upstream;
+ c.listen(
+ (data) async {
+ if (stage == 0) {
+ stage = 1;
+ c.add([0x05, 0x00]);
+ } else if (stage == 1) {
+ stage = 2;
+ if (connectReply == null) {
+ return;
+ }
+ await Future.delayed(replyDelay);
+ c.add([0x05, connectReply, 0x00, 0x01, 0, 0, 0, 0, 0, 0]);
+ if (connectReply == 0x00 && pipeToPort != null) {
+ upstream = await Socket.connect(InternetAddress.loopbackIPv4, pipeToPort);
+ upstream!.listen(c.add, onDone: () => c.destroy(), onError: (_) {});
+ }
+ } else {
+ upstream?.add(data);
+ }
+ },
+ onError: (_) {},
+ onDone: () {
+ upstream?.destroy();
+ if (!gone.isCompleted) {
+ gone.complete();
+ }
+ },
+ );
+ });
+ return server;
+}
+
+ElectrumClient _client(List<ConnectionStatus> log) =>
+ ElectrumClient()..onConnectionStatusChange = log.add;
+
+void main() {
+ setUp(() => CakeTor.instance = CakeTorDisabled());
+
+ test("a refused connection is reported as failed", () async {
+ final log = <ConnectionStatus>[];
+ final client = _client(log);
+
+ await client.connectToUri(Uri.parse("tcp://127.0.0.1:${await _refusedPort()}"), useSSL: false);
+
+ expect(log, [ConnectionStatus.connecting, ConnectionStatus.failed]);
+ });
+
+ test(
+ "a TLS handshake that never finishes fails at the clearnet deadline",
+ () async {
+ final silent = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
+ silent.listen((c) => c.listen((_) {}, onError: (_) {}));
+ final log = <ConnectionStatus>[];
+ final client = _client(log);
+ final stopwatch = Stopwatch()..start();
+
+ await client.connectToUri(Uri.parse("ssl://127.0.0.1:${silent.port}"), useSSL: true);
+
+ expect(log, [ConnectionStatus.connecting, ConnectionStatus.failed]);
+ expect(stopwatch.elapsed, greaterThanOrEqualTo(ProxySocket.clearnetConnectDeadline));
+ expect(
+ stopwatch.elapsed,
+ lessThan(ProxySocket.clearnetConnectDeadline + const Duration(seconds: 3)),
+ );
+ await silent.close();
+ },
+ timeout: const Timeout(Duration(seconds: 40)),
+ );
+
+ test(
+ "Tor never answering CONNECT fails at the Tor deadline and closes the proxy socket",
+ () async {
+ final closed = <Future<void>>[];
+ final tor = await _fakeTor(closed: closed);
+ CakeTor.instance = CakeTorSocks(tor.port);
+ final log = <ConnectionStatus>[];
+ final client = _client(log);
+ final stopwatch = Stopwatch()..start();
+
+ await client.connectToUri(Uri.parse("tcp://example.onion:50001"), useSSL: false);
+
+ expect(log, [ConnectionStatus.connecting, ConnectionStatus.failed]);
+ expect(stopwatch.elapsed, greaterThanOrEqualTo(ProxySocket.torConnectDeadline));
+ expect(
+ stopwatch.elapsed,
+ lessThan(ProxySocket.torConnectDeadline + const Duration(seconds: 3)),
+ );
+ await closed.single.timeout(const Duration(seconds: 3));
+ await tor.close();
+ },
+ timeout: const Timeout(Duration(seconds: 90)),
+ );
+
+ test("Tor refusing CONNECT is reported as failed and the Tor session is closed", () async {
+ final closed = <Future<void>>[];
+ final tor = await _fakeTor(connectReply: 0x04, closed: closed);
+ CakeTor.instance = CakeTorSocks(tor.port);
+ final log = <ConnectionStatus>[];
+ final client = _client(log);
+
+ await client.connectToUri(Uri.parse("tcp://example.onion:50001"), useSSL: false);
+
+ expect(log, [ConnectionStatus.connecting, ConnectionStatus.failed]);
+ await closed.single.timeout(const Duration(seconds: 3));
+ await tor.close();
+ });
+
+ test(
+ "after the server drops the connection, the keep-alive does not report connected",
+ () async {
+ final server = await _FakeServer.start();
+ final log = <ConnectionStatus>[];
+ final client = _client(log);
+ await client.connectToUri(server.uri, useSSL: false);
+ await Future.delayed(const Duration(seconds: 6));
+ expect(log.last, ConnectionStatus.connected);
+
+ for (final c in server.clients) {
+ c.destroy();
+ }
+ await server.server.close();
+ await Future.delayed(const Duration(seconds: 11)); // two keep-alive ticks
+
+ expect(log, [
+ ConnectionStatus.connecting,
+ ConnectionStatus.connected,
+ ConnectionStatus.disconnected,
+ ]);
+ expect(client.isConnected, isFalse);
+ await client.close();
+ },
+ timeout: const Timeout(Duration(seconds: 40)),
+ );
+
+ test(
+ "reconnecting: the old socket closing late does not tear down the new one",
+ () async {
+ final a = await _FakeServer.start(closeDelay: const Duration(milliseconds: 500));
+ final b = await _FakeServer.start();
+ final log = <ConnectionStatus>[];
+ final client = _client(log);
+ await client.connectToUri(a.uri, useSSL: false);
+ await Future.delayed(const Duration(seconds: 6));
+
+ // The wallet's 5 s retry reconnects like this, without close().
+ await client.connectToUri(b.uri, useSSL: false);
+ await Future.delayed(const Duration(seconds: 6)); // A closes after 500 ms; B gets pinged
+
+ expect(client.isConnected, isTrue);
+ expect(log.skip(2), [ConnectionStatus.connecting, ConnectionStatus.connected]);
+ await client.close();
+ await a.server.close();
+ await b.server.close();
+ },
+ timeout: const Timeout(Duration(seconds: 40)),
+ );
+
+ test(
+ "a connect superseded by a newer one does not install its late socket",
+ () async {
+ final target = await _FakeServer.start();
+ final slowClosed = <Future<void>>[];
+ final slowTor = await _fakeTor(
+ connectReply: 0x00,
+ pipeToPort: target.server.port,
+ replyDelay: const Duration(seconds: 2),
+ closed: slowClosed,
+ );
+ final fastTor = await _fakeTor(connectReply: 0x00, pipeToPort: target.server.port);
+ final log = <ConnectionStatus>[];
+ final client = _client(log);
+
+ CakeTor.instance = CakeTorSocks(slowTor.port);
+ unawaited(client.connectToUri(Uri.parse("tcp://old-node.onion:50001"), useSSL: false));
+ await Future.delayed(const Duration(milliseconds: 300));
+ CakeTor.instance = CakeTorSocks(fastTor.port);
+ await client.connectToUri(Uri.parse("tcp://new-node.onion:50001"), useSSL: false);
+ final current = client.socket;
+ await Future.delayed(const Duration(seconds: 7)); // the old attempt completes at ~2 s
+
+ expect(identical(client.socket, current), isTrue);
+ expect(client.isConnected, isTrue);
+ expect(log, [
+ ConnectionStatus.connecting,
+ ConnectionStatus.connecting,
+ ConnectionStatus.connected,
+ ]);
+ await slowClosed.single.timeout(const Duration(seconds: 3)); // the late socket was destroyed
+ await client.close();
+ await slowTor.close();
+ await fastTor.close();
+ await target.server.close();
+ },
+ timeout: const Timeout(Duration(seconds: 40)),
+ );
+
+ test(
+ "close() during a connect: the late socket is not installed",
+ () async {
+ final target = await _FakeServer.start();
+ final tor = await _fakeTor(
+ connectReply: 0x00,
+ pipeToPort: target.server.port,
+ replyDelay: const Duration(seconds: 2),
+ );
+ CakeTor.instance = CakeTorSocks(tor.port);
+ final client = _client([]);
+
+ unawaited(client.connectToUri(Uri.parse("tcp://node.onion:50001"), useSSL: false));
+ await Future.delayed(const Duration(milliseconds: 300));
+ await client.close();
+ await Future.delayed(const Duration(seconds: 4)); // the connect completes at ~2 s
+
+ expect(client.socket, isNull);
+ await tor.close();
+ await target.server.close();
+ },
+ timeout: const Timeout(Duration(seconds: 30)),
+ );
+}
### cw_bitcoin/test/electrum_wallet_connection_test.dart
@@ -0,0 +1,420 @@
+import "dart:async";
+import "dart:convert";
+import "dart:io";
+import "dart:typed_data";
+
+import "package:bitcoin_base/bitcoin_base.dart";
+import "package:blockchain_utils/blockchain_utils.dart";
+import "package:cw_bitcoin/bitcoin_address_record.dart";
+import "package:cw_bitcoin/bitcoin_wallet_addresses.dart";
+import "package:cw_bitcoin/electrum_wallet.dart";
+import "package:cw_bitcoin/payjoin/manager.dart";
+import "package:cw_bitcoin/utils.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/db/sqlite.dart";
+import "package:cw_core/encryption_file_utils.dart";
+import "package:cw_core/node.dart";
+import "package:cw_core/sync_status.dart";
+import "package:cw_core/unspent_coins_info.dart";
+import "package:cw_core/utils/proxy_wrapper.dart";
+import "package:cw_core/utils/tor/disabled.dart";
+import "package:cw_core/utils/tor/socks.dart";
+import "package:cw_core/wallet_info.dart";
+import "package:cw_core/wallet_type.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:hive/hive.dart";
+import "package:mobx/mobx.dart";
+import "package:shared_preferences/shared_preferences.dart";
+import "package:sqflite_common_ffi/sqflite_ffi.dart";
+
+final _master = Bip32Slip10Secp256k1.fromSeed(List<int>.generate(64, (i) => i));
+final _receiveHd = _master.derivePath("m/84'/0'/0'/0") as Bip32Slip10Secp256k1;
+final _changeHd = _master.derivePath("m/84'/0'/0'/1") as Bip32Slip10Secp256k1;
+const _addressCount = 3;
+
+class _NoPayjoin implements PayjoinManager {
+ @override
+ dynamic noSuchMethod(Invocation invocation) => throw UnimplementedError();
+}
+
+class _NoUnspentsBox implements Box<UnspentCoinsInfo> {
+ @override
+ dynamic noSuchMethod(Invocation invocation) => throw UnimplementedError();
+}
+
+class _Addresses extends BitcoinWalletAddresses {
+ _Addresses(super.walletInfo)
+ : super(
+ mainHdByTypeAndAccount: {
+ 0: {SegwitAddresType.p2wpkh: _receiveHd},
+ },
+ sideHdByTypeAndAccount: {
+ 0: {SegwitAddresType.p2wpkh: _changeHd},
+ },
+ accountIndexes: [0],
+ currentAccountIndex: 0,
+ legacyMainHd: _receiveHd,
+ legacySideHd: _changeHd,
+ network: BitcoinNetwork.mainnet,
+ isHardwareWallet: false,
+ payjoinManager: _NoPayjoin(),
+ masterHd: _master,
+ initialAddresses: [
+ for (var i = 0; i < _addressCount; i++)
+ BitcoinAddressRecord(
+ generateP2WPKHAddress(hd: _receiveHd, network: BitcoinNetwork.mainnet, index: i),
+ index: i,
+ type: SegwitAddresType.p2wpkh,
+ network: BitcoinNetwork.mainnet,
+ ),
+ ],
+ );
+
+ @override
+ Future<void> saveAddressesInBox() async {}
+}
+
+/// Electrum server stand-in: answers requests with a null result (a block height for
+/// blockchain.headers.subscribe, so a sync gets past its first step), leaves batch requests
+/// unanswered, and counts address subscriptions.
+class _FakeNode {
+ _FakeNode._(this._server);
+
+ final ServerSocket _server;
+ int subscribes = 0;
+
+ static Future<_FakeNode> start({int port = 0}) async {
+ final node = _FakeNode._(await ServerSocket.bind(InternetAddress.loopbackIPv4, port));
+ node._server.listen((c) {
+ c.cast<List<int>>().transform(utf8.decoder).transform(const LineSplitter()).listen(
+ (line) {
+ final request = json.decode(line);
+ if (request is! Map) {
+ return;
+ }
+ if (request["method"] == "blockchain.scripthash.subscribe") {
+ node.subscribes++;
+ }
+ final result =
+ request["method"] == "blockchain.headers.subscribe" ? '{"height":800000}' : "null";
+ c.write('{"jsonrpc":"2.0","result":$result,"id":${json.encode(request['id'])}}\n');
+ },
+ onDone: () => c.destroy(),
+ onError: (_) {},
+ );
+ });
+ return node;
+ }
+
+ int get port => _server.port;
+
+ Future<void> close() => _server.close();
+}
+
+/// Accepts connections and never answers, so a TLS handshake to it never finishes.
+Future<ServerSocket> _silentServer(List<Socket> accepted) async {
+ final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
+ server.listen((c) {
+ accepted.add(c);
+ c.listen((_) {}, onError: (_) {});
+ });
+ return server;
+}
+
+Future<int> _refusedPort() async {
+ final s = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
+ final port = s.port;
+ await s.close();
+ return port;
+}
+
+/// SOCKS5 stand-in for Tor that sends every CONNECT to 127.0.0.1:[targetPort].
+Future<ServerSocket> _fakeTor(int targetPort, {required void Function() onConnect}) async {
+ final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
+ server.listen((c) {
+ var stage = 0;
+ Socket? upstream;
+ c.listen(
+ (data) async {
+ if (stage == 0) {
+ stage = 1;
+ c.add([0x05, 0x00]);
+ } else if (stage == 1) {
+ stage = 2;
+ onConnect();
+ c.add([0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0]);
+ upstream = await Socket.connect(InternetAddress.loopbackIPv4, targetPort);
+ upstream!.listen(c.add, onDone: () => c.destroy(), onError: (_) {});
+ } else {
+ upstream?.add(data);
+ }
+ },
+ onError: (_) {},
+ onDone: () => upstream?.destroy(),
+ );
+ });
+ return server;
+}
+
+Node _node(int port, {bool useSSL = false}) =>
+ Node(uri: "127.0.0.1:$port", type: WalletType.bitcoin, useSSL: useSSL);
+
+ElectrumWallet _wallet() {
+ final walletInfo = WalletInfo.external(
+ id: "connection_test",
+ name: "connection_test",
+ type: WalletType.bitcoin,
+ isRecovery: false,
+ restoreHeight: 0,
+ date: DateTime(2026),
+ dirPath: "",
+ path: "",
+ address: "",
+ );
+ return ElectrumWallet(
+ password: "",
+ walletInfo: walletInfo,
+ derivationInfo: DerivationInfo(
+ derivationType: DerivationType.bip39,
+ derivationPath: "m/84'/0'/0'",
+ ),
+ unspentCoinsInfo: _NoUnspentsBox(),
+ network: BitcoinNetwork.mainnet,
+ encryptionFileUtils: encryptionFileUtilsFor(false),
+ seedBytes: Uint8List.fromList(List<int>.generate(64, (i) => i)),
+ currency: CryptoCurrency.btc,
+ )..walletAddresses = _Addresses(walletInfo);
+}
+
+Future<void> _waitFor(bool Function() done, Duration max) async {
+ final end = DateTime.now().add(max);
+ while (!done() && DateTime.now().isBefore(end)) {
+ await Future.delayed(const Duration(milliseconds: 100));
+ }
+}
+
+bool _connectedTo(ElectrumWallet wallet, int port) =>
+ wallet.syncStatus is ConnectedSyncStatus &&
+ wallet.electrumClient.isConnected &&
+ wallet.electrumClient.uri?.port == port;
+
+void main() {
+ setUpAll(() async {
+ sqfliteFfiInit();
+ db = await databaseFactoryFfi.openDatabase(inMemoryDatabasePath);
+ await db!.execute(
+ "CREATE TABLE walletInfoAddress "
+ "(walletInfoAddressId INTEGER PRIMARY KEY, walletInfoId INTEGER, type INTEGER, "
+ "address TEXT)",
+ );
+ });
+
+ setUp(() {
+ SharedPreferences.setMockInitialValues({});
+ CakeTor.instance = CakeTorDisabled();
+ });
+
+ test("a node that refuses the connection ends in Lost connection, not Connecting", () async {
+ final wallet = _wallet();
+
+ await wallet.connectToNode(node: _node(await _refusedPort()));
+
+ expect(wallet.syncStatus, isA<LostConnectionSyncStatus>());
+ await wallet.close();
+ });
+
+ test(
+ "after a failed connect, the wallet retries and connects once the node is back",
+ () async {
+ final port = await _refusedPort();
+ final wallet = _wallet();
+ await wallet.connectToNode(node: _node(port));
+
+ final node = await _FakeNode.start(port: port);
+ await _waitFor(() => _connectedTo(wallet, port), const Duration(seconds: 15));
+
+ expect(_connectedTo(wallet, port), isTrue);
+ await wallet.close();
+ await node.close();
+ },
+ timeout: const Timeout(Duration(seconds: 30)),
+ );
+
+ test(
+ "selecting another node while a connect hangs connects to it right away",
+ () async {
+ final accepted = <Socket>[];
+ final stalled = await _silentServer(accepted);
+ final good = await _FakeNode.start();
+ final wallet = _wallet();
+
+ unawaited(wallet.connectToNode(node: _node(stalled.port, useSSL: true)));
+ await _waitFor(() => accepted.isNotEmpty, const Duration(seconds: 3));
+ expect(wallet.syncStatus, isA<ConnectingSyncStatus>());
+
+ await wallet.connectToNode(node: _node(good.port));
+ await _waitFor(() => _connectedTo(wallet, good.port), const Duration(seconds: 8));
+
+ expect(_connectedTo(wallet, good.port), isTrue);
+ await wallet.close();
+ await good.close();
+ await stalled.close();
+ },
+ timeout: const Timeout(Duration(seconds: 30)),
+ );
+
+ test(
+ "selecting the same node again while connecting does not start a second connect",
+ () async {
+ final accepted = <Socket>[];
+ final stalled = await _silentServer(accepted);
+ final wallet = _wallet();
+ final node = _node(stalled.port, useSSL: true);
+
+ unawaited(wallet.connectToNode(node: node));
+ await _waitFor(() => accepted.isNotEmpty, const Duration(seconds: 3));
+ unawaited(wallet.connectToNode(node: node));
+ await Future.delayed(const Duration(seconds: 1));
+
+ expect(accepted, hasLength(1));
+ await wallet.close();
+ await stalled.close();
+ },
+ timeout: const Timeout(Duration(seconds: 30)),
+ );
+
+ test(
+ "turning Tor on while connecting reconnects through Tor",
+ () async {
+ final accepted = <Socket>[];
+ final silent = await _silentServer(accepted);
+ final good = await _FakeNode.start();
+ var torConnects = 0;
+ final tor = await _fakeTor(good.port, onConnect: () => torConnects++);
+ final wallet = _wallet();
+ final node = _node(silent.port);
+
+ // Plain TCP to a server that never answers: the wallet stays on Connecting.
+ await wallet.connectToNode(node: node);
+ expect(wallet.syncStatus, isA<ConnectingSyncStatus>());
+
+ CakeTor.instance = CakeTorSocks(tor.port);
+ await wallet.connectToNode(node: node);
+
+ expect(torConnects, 1);
+ await _waitFor(() => wallet.syncStatus is ConnectedSyncStatus, const Duration(seconds: 8));
+ expect(wallet.syncStatus, isA<ConnectedSyncStatus>());
+ await wallet.close();
+ await tor.close();
+ await good.close();
+ await silent.close();
+ },
+ timeout: const Timeout(Duration(seconds: 30)),
+ );
+
+ test("app resume with an unreachable node does not start a sync", () async {
+ final wallet = _wallet();
+ await wallet.connectToNode(node: _node(await _refusedPort()));
+ final statuses = <SyncStatus>[];
+ final dispose = reaction((_) => wallet.syncStatus, statuses.add);
+
+ await wallet.checkSocketHealth();
+
+ dispose();
+ expect(statuses.whereType<SyncronizingSyncStatus>(), isEmpty);
+ expect(wallet.syncStatus, isA<LostConnectionSyncStatus>());
+ await wallet.close();
+ });
+
+ test(
+ "app resume on an unresponsive session re-subscribes the addresses",
+ () async {
+ final node = await _FakeNode.start();
+ final wallet = _wallet();
+ await wallet.connectToNode(node: _node(node.port));
+ await _waitFor(() => _connectedTo(wallet, node.port), const Duration(seconds: 8));
+ await wallet.subscribeForUpdates();
+ await Future.delayed(const Duration(milliseconds: 300));
+ final firstSession = node.subscribes;
+ expect(firstSession, greaterThanOrEqualTo(_addressCount));
+
+ // The fake answers server.version with null, which the health check treats as a dead
+ // session: it reconnects and starts a sync.
+ unawaited(wallet.checkSocketHealth());
+ await _waitFor(() => node.subscribes == 2 * firstSession, const Duration(seconds: 8));
+
+ expect(node.subscribes, 2 * firstSession);
+ await wallet.close();
+ await node.close();
+ },
+ timeout: const Timeout(Duration(seconds: 30)),
+ );
+
+ test(
+ "a closed wallet does not reconnect on its own",
+ () async {
+ final port = await _refusedPort();
+ final wallet = _wallet();
+ await wallet.connectToNode(node: _node(port)); // fails, so a retry is scheduled
+ await wallet.close();
+
+ final node = await _FakeNode.start(port: port);
+ await Future.delayed(const Duration(seconds: 7)); // past the 5 s retry
+
+ expect(wallet.electrumClient.isConnected, isFalse);
+ await node.close();
+ },
+ timeout: const Timeout(Duration(seconds: 30)),
+ );
+
+ test(
+ "closing a wallet while it syncs does not reconnect it",
+ () async {
+ final node = await _FakeNode.start();
+ final wallet = _wallet();
+ await wallet.connectToNode(node: _node(node.port));
+ await _waitFor(() => _connectedTo(wallet, node.port), const Duration(seconds: 8));
+
+ unawaited(wallet.startSync());
+ await Future.delayed(const Duration(milliseconds: 200));
+ await wallet.close();
+ // The sync still running against the closed client fails on its own.
+ await _waitFor(
+ () => wallet.syncStatus is NotConnectedSyncStatus,
+ const Duration(seconds: 20),
+ );
+ expect(wallet.syncStatus, isA<NotConnectedSyncStatus>());
+ await Future.delayed(const Duration(seconds: 7)); // past the 5 s retry
+
+ expect(wallet.electrumClient.isConnected, isFalse);
+ await node.close();
+ },
+ timeout: const Timeout(Duration(seconds: 60)),
+ );
+
+ test(
+ "switching between two working nodes subscribes the addresses on the new node",
+ () async {
+ final a = await _FakeNode.start();
+ final b = await _FakeNode.start();
+ final wallet = _wallet();
+
+ await wallet.connectToNode(node: _node(a.port));
+ await _waitFor(() => _connectedTo(wallet, a.port), const Duration(seconds: 8));
+ await wallet.subscribeForUpdates(); // what startSync does once connected
+ await Future.delayed(const Duration(milliseconds: 300));
+ expect(a.subscribes, greaterThanOrEqualTo(_addressCount));
+
+ await wallet.connectToNode(node: _node(b.port));
+ await _waitFor(() => _connectedTo(wallet, b.port), const Duration(seconds: 8));
+ await wallet.subscribeForUpdates();
+ await Future.delayed(const Duration(milliseconds: 300));
+
+ expect(b.subscribes, a.subscribes);
+ await wallet.close();
+ await a.close();
+ await b.close();
+ },
+ timeout: const Timeout(Duration(seconds: 30)),
+ );
+}
### cw_bitcoin/test/unknown_derivation_test.dart
@@ -0,0 +1,161 @@
+import 'package:bip39/bip39.dart' as bip39;
+import 'package:cw_bitcoin/bitcoin_mnemonic.dart' as electrum_mnemonic;
+import 'package:cw_bitcoin/electrum_derivations.dart';
+import 'package:cw_bitcoin/unknown_derivation.dart';
+import 'package:cw_core/wallet_info.dart';
+import 'package:cw_core/wallet_type.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+/// Electrum segwit version prefix, invalid BIP39 checksum: what every pre-2024 Cake wallet has.
+const _electrumSeed = 'flag maid surge feel hundred awkward burger logic '
+ 'maple whale monkey road ribbon practice inside provide '
+ 'insane letter sorry choice zebra purse copy mention';
+
+/// Valid BIP39 checksum, no Electrum version prefix.
+const _bip39Seed = 'abandon abandon abandon abandon abandon abandon '
+ 'abandon abandon abandon abandon abandon about';
+
+/// Valid BIP39 checksum whose version hash also carries a prefix the Electrum validator accepts:
+/// the mnemonic proves nothing.
+const _ambiguousSeed = 'immune boat rice detect proof link disagree help '
+ 'crouch multiply poet glove fabric fee begin lesson '
+ 'hospital forum web beyond army blossom never brother';
+
+DerivationInfo _unknown({String? path}) =>
+ DerivationInfo(derivationType: DerivationType.unknown, derivationPath: path);
+
+void main() {
+ test('fixtures are what they claim', () {
+ expect(electrum_mnemonic.validateMnemonic(_electrumSeed), isTrue);
+ expect(bip39.validateMnemonic(_electrumSeed), isFalse);
+ expect(electrum_mnemonic.validateMnemonic(_bip39Seed), isFalse);
+ expect(bip39.validateMnemonic(_bip39Seed), isTrue);
+ expect(electrum_mnemonic.validateMnemonic(_ambiguousSeed), isTrue);
+ expect(bip39.validateMnemonic(_ambiguousSeed), isTrue);
+ });
+
+ group('type', () {
+ test("the wallet file's recorded type wins over the mnemonic", () {
+ // A BIP39 phrase restored with Electrum stretching, whose row was recreated without its
+ // derivation: the file still says what the wallet has been deriving with.
+ final electrum = _unknown();
+ resolveUnknownDerivation(electrum,
+ walletType: WalletType.bitcoin,
+ mnemonic: _bip39Seed,
+ snapshotType: DerivationType.electrum,
+ snapshotPath: electrum_path);
+ expect(electrum.derivationType, DerivationType.electrum);
+ expect(electrum.derivationPath, electrum_path);
+
+ final litecoin = _unknown();
+ resolveUnknownDerivation(litecoin,
+ walletType: WalletType.litecoin,
+ mnemonic: _bip39Seed,
+ snapshotType: DerivationType.bip39,
+ snapshotPath: "m/84'/2'/0'");
+ expect(litecoin.derivationType, DerivationType.bip39);
+ expect(litecoin.derivationPath, "m/84'/2'/0'");
+ });
+
+ test('a file that predates derivation tracking loads as electrum, which such wallets used', () {
+ for (final seed in [_electrumSeed, _ambiguousSeed]) {
+ final wallet = _unknown();
+ resolveUnknownDerivation(wallet,
+ walletType: WalletType.bitcoin,
+ mnemonic: seed,
+ // ElectrumWalletSnapshot.load defaults absent fields to these.
+ snapshotType: DerivationType.electrum,
+ snapshotPath: electrum_path);
+ expect(wallet.derivationType, DerivationType.electrum, reason: seed);
+ expect(wallet.derivationPath, electrum_path, reason: seed);
+ }
+ });
+
+ test('the mnemonic decides when the file still says unknown or there is no file', () {
+ // v5.6.0–v5.6.4 saved migrated rows as (unknown, '').
+ final dormant = _unknown(path: '');
+ resolveUnknownDerivation(dormant,
+ walletType: WalletType.bitcoin,
+ mnemonic: _electrumSeed,
+ snapshotType: DerivationType.unknown,
+ snapshotPath: '');
+ expect(dormant.derivationType, DerivationType.electrum);
+ expect(dormant.derivationPath, electrum_path);
+
+ final noFileElectrum = _unknown();
+ resolveUnknownDerivation(noFileElectrum,
+ walletType: WalletType.bitcoin, mnemonic: _electrumSeed);
+ expect(noFileElectrum.derivationType, DerivationType.electrum);
+ expect(noFileElectrum.derivationPath, electrum_path);
+
+ final noFileBip39 = _unknown();
+ resolveUnknownDerivation(noFileBip39, walletType: WalletType.bitcoin, mnemonic: _bip39Seed);
+ expect(noFileBip39.derivationType, DerivationType.bip39);
+ expect(noFileBip39.derivationPath, segwit_path);
+ });
+
+ test('without a usable mnemonic the old fallback applies', () {
+ // Hardware and watch-only wallets have no mnemonic; an ambiguous one proves nothing.
+ final electrumPath = _unknown();
+ resolveUnknownDerivation(electrumPath,
+ walletType: WalletType.bitcoin,
+ snapshotType: DerivationType.unknown,
+ snapshotPath: electrum_path);
+ expect(electrumPath.derivationType, DerivationType.electrum);
+ expect(electrumPath.derivationPath, electrum_path);
+
+ final ambiguousNoFile = _unknown();
+ resolveUnknownDerivation(ambiguousNoFile,
+ walletType: WalletType.bitcoin, mnemonic: _ambiguousSeed);
+ expect(ambiguousNoFile.derivationType, DerivationType.bip39);
+ expect(ambiguousNoFile.derivationPath, segwit_path);
+
+ final nothing = _unknown();
+ resolveUnknownDerivation(nothing, walletType: WalletType.bitcoin);
+ expect(nothing.derivationType, DerivationType.bip39);
+ expect(nothing.derivationPath, segwit_path);
+ });
+ });
+
+ group('path', () {
+ test("a saved path is kept, the row's before the wallet file's", () {
+ final fromRow = _unknown(path: "m/44'/0'/0'");
+ resolveUnknownDerivation(fromRow,
+ walletType: WalletType.bitcoin,
+ mnemonic: _bip39Seed,
+ snapshotType: DerivationType.bip39,
+ snapshotPath: segwit_path);
+ expect(fromRow.derivationPath, "m/44'/0'/0'");
+
+ final fromFile = _unknown(path: '');
+ resolveUnknownDerivation(fromFile,
+ walletType: WalletType.litecoin,
+ mnemonic: _bip39Seed,
+ snapshotType: DerivationType.bip39,
+ snapshotPath: "m/84'/2'/0'");
+ expect(fromFile.derivationPath, "m/84'/2'/0'");
+ });
+
+ test("with no path anywhere the type's default applies, Litecoin on its own coin type", () {
+ final bitcoin = _unknown(path: '');
+ resolveUnknownDerivation(bitcoin,
+ walletType: WalletType.bitcoin,
+ mnemonic: _bip39Seed,
+ snapshotType: DerivationType.unknown,
+ snapshotPath: '');
+ expect(bitcoin.derivationPath, segwit_path);
+
+ final litecoin = _unknown();
+ resolveUnknownDerivation(litecoin,
+ walletType: WalletType.litecoin,
+ mnemonic: _bip39Seed,
+ snapshotType: DerivationType.unknown,
+ snapshotPath: '');
+ expect(litecoin.derivationPath, litecoin_segwit_path);
+
+ final electrum = _unknown();
+ resolveUnknownDerivation(electrum, walletType: WalletType.litecoin, mnemonic: _electrumSeed);
+ expect(electrum.derivationPath, electrum_path);
+ });
+ });
+}
### cw_bitcoin_cash/lib/src/bitcoin_cash_wallet.dart
@@ -56,8 +56,10 @@ abstract class BitcoinCashWalletBase extends ElectrumWallet with Store {
initialAddresses: initialAddresses,
initialRegularAddressIndex: initialRegularAddressIndex,
initialChangeAddressIndex: initialChangeAddressIndex,
- mainHdByType: mainHdByType,
- sideHdByType: sideHdByType,
+ mainHdByTypeAndAccount: mainHdByTypeAndAccount,
+ sideHdByTypeAndAccount: sideHdByTypeAndAccount,
+ accountIndexes: [currentAccountIndex],
+ currentAccountIndex: currentAccountIndex,
legacyMainHd: mainHd,
legacySideHd: sideHd,
network: network,
@@ -148,6 +150,7 @@ abstract class BitcoinCashWalletBase extends ElectrumWallet with Store {
addr.address,
index: addr.index,
isHidden: addr.isHidden,
+ isHiddenChecked: addr.isHiddenChecked,
name: addr.name,
type: P2pkhAddressType.p2pkh,
network: BitcoinCashNetwork.mainnet,
@@ -157,6 +160,7 @@ abstract class BitcoinCashWalletBase extends ElectrumWallet with Store {
AddressUtils.getCashAddrFormat(addr.address),
index: addr.index,
isHidden: addr.isHidden,
+ isHiddenChecked: addr.isHiddenChecked,
name: addr.name,
type: P2pkhAddressType.p2pkh,
network: BitcoinCashNetwork.mainnet,
### cw_bitcoin_cash/lib/src/bitcoin_cash_wallet_addresses.dart
@@ -13,8 +13,10 @@ class BitcoinCashWalletAddresses = BitcoinCashWalletAddressesBase with _$Bitcoin
abstract class BitcoinCashWalletAddressesBase extends ElectrumWalletAddresses with Store {
BitcoinCashWalletAddressesBase(
WalletInfo walletInfo, {
- required super.mainHdByType,
- required super.sideHdByType,
+ required super.mainHdByTypeAndAccount,
+ required super.sideHdByTypeAndAccount,
+ required super.accountIndexes,
+ required super.currentAccountIndex,
required super.legacyMainHd,
required super.legacySideHd,
required super.network,
### cw_bitcoin_cash/lib/src/bitcoin_cash_wallet_service.dart
@@ -4,6 +4,7 @@ import 'package:bip39/bip39.dart';
import 'package:cw_bitcoin/bitcoin_mnemonics_bip39.dart';
import 'package:cw_bitcoin_cash/cw_bitcoin_cash.dart';
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/unspent_coins_info.dart';
import 'package:cw_core/wallet_info.dart';
@@ -50,7 +51,7 @@ class BitcoinCashWalletService extends WalletService<
Future<BitcoinCashWallet> openWallet(String name, String password) async {
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
try {
@@ -83,7 +84,7 @@ class BitcoinCashWalletService extends WalletService<
File(await pathForWalletDir(name: wallet, type: getType())).delete(recursive: true);
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet, type: getType());
}
await WalletInfo.delete(walletInfo);
### cw_bitcoin_cash/pubspec.yaml
@@ -2,7 +2,6 @@ name: cw_bitcoin_cash
description: A new Flutter package project.
version: 0.0.1
publish_to: none
-author: Cake Wallet
homepage: https://cakewallet.com
environment:
@@ -13,10 +12,7 @@ dependencies:
flutter:
sdk: flutter
bip39: ^1.0.6
- bip32: ^2.0.0
- path_provider: ^2.0.11
mobx: ^2.6.0
- flutter_mobx: ^2.3.0
cw_core:
path: ../cw_core
cw_bitcoin:
### cw_core/lib/account.dart
@@ -1,12 +1,32 @@
class Account {
- Account({required this.id, required this.label, this.balance});
+ Account({
+ required this.id,
+ required this.label,
+ String? balance,
+ }) : balance = balance ?? "0.00";
- Account.fromMap(Map<String, Object> map)
- : this.id = map['id'] == null ? 0 : int.parse(map['id'] as String),
- this.label = (map['label'] ?? '') as String,
- this.balance = (map['balance'] ?? '0.00') as String;
+ Account.fromMap(Map<String, Object?> map)
+ : id = map["id"] is int ? map["id"] as int : int.tryParse(map["id"]?.toString() ?? "") ?? 0,
+ label = (map["label"] ?? "") as String,
+ balance = (map["balance"] ?? "0.00") as String;
final int id;
final String label;
- final String? balance;
+ final String balance;
+
+ Account copyWith({
+ int? id,
+ String? label,
+ String? balance,
+ }) => Account(
+ id: id ?? this.id,
+ label: label ?? this.label,
+ balance: balance ?? this.balance,
+ );
+
+ Map<String, Object> toMap() => {
+ "id": id.toString(),
+ "label": label,
+ "balance": balance,
+ };
}
### cw_core/lib/account_list.dart
@@ -1,15 +0,0 @@
-import 'package:mobx/mobx.dart';
-
-abstract class AccountList<T> {
- ObservableList<T> get accounts;
-
- void update();
-
- List<T> getAll();
-
- Future<void> addAccount({required String label});
-
- Future<void> setLabelAccount({required int accountIndex, required String label});
-
- void refresh();
-}
### cw_core/lib/amount/money.dart
@@ -1,6 +1,7 @@
import "dart:math";
import "package:cw_core/amount/utils.dart";
+import "package:cw_core/crypto_amount_format.dart";
import "package:cw_core/crypto_currency.dart";
import "package:cw_core/currency.dart";
import "package:cw_core/format_fixed.dart";
@@ -58,6 +59,14 @@ class Money implements Comparable<Money> {
}
}
+ static Money? trySafeParse(source, Currency currency, {bool isBaseUnit = false}) {
+ final amount = isBaseUnit
+ ? BigInt.tryParse(source.toString())
+ : tryParseFixed(source.toString().withDecimals(currency.decimals), currency.decimals);
+
+ return amount != null ? Money(amount, currency) : null;
+ }
+
final BigInt amount;
final Currency currency;
@@ -183,9 +192,7 @@ class Money implements Comparable<Money> {
///
/// The result is again [Money].
Money operator /(BigInt other) {
- if (other == BigInt.zero) {
- throw Exception("Division by zero.");
- }
+ if (other == BigInt.zero) throw ArgumentError('Division by zero.');
final neg = (amount.isNegative) ^ (other.isNegative);
final A = amount.abs();
@@ -207,7 +214,9 @@ class Money implements Comparable<Money> {
/// If just [currency] is provided and the decimals missmatch
/// the amount will be transformed to keep its canonical representation
Money copyWith({BigInt? amount, Currency? currency, int? decimals}) {
- if (currency != null && amount == null && decimals == null &&
+ if (currency != null &&
+ amount == null &&
+ decimals == null &&
currency.decimals != this.decimals) {
return Money(
_transformAmount(this.amount, this.decimals, currency.decimals),
@@ -221,7 +230,8 @@ class Money implements Comparable<Money> {
void _assertSameCurrency(Money other, [String? message]) {
if (currency != other.currency) {
- throw ArgumentError(message ?? "Cannot operate with money values in different currencies.");
+ throw ArgumentError(message ??
+ "Cannot operate with money values in different currencies. $currency - ${other.currency}");
}
}
@@ -280,19 +290,40 @@ class Money implements Comparable<Money> {
return withSymbolPrefix ? "$symbol $amount" : "$amount $symbol";
}
+ /// [meaningfulDecimals]: for non-zero values below 1, show that many digits
+ /// after the leading fraction zeros (e.g. 0.00001234 -> 0.000012 for 2),
+ /// up to 12 fraction digits, when that is more than would be shown otherwise.
+ /// Can't be combined with [useBaseUnit]; with [fractionalDigits] it only ever
+ /// shows more digits than [fractionalDigits] would, never fewer.
String toStringWithPrecision({
int? fractionalDigits,
bool trimZeros = true,
bool useBaseUnit = false,
- }) =>
- formatFixed(
- decimals != currency.decimals
- ? _transformAmount(amount, decimals, currency.decimals)
- : amount,
- useBaseUnit ? 0 : currency.decimals,
- fractionalDigits: fractionalDigits,
- trimZeros: trimZeros,
- );
+ int? meaningfulDecimals,
+ }) {
+ if (meaningfulDecimals != null && useBaseUnit) {
+ throw ArgumentError("meaningfulDecimals can't be used together with useBaseUnit");
+ }
+ if (meaningfulDecimals != null && !isZero) {
+ final digits = amount.abs().toString().length;
+ if (digits <= decimals) {
+ final meaningfulDigits = min(decimals - digits + meaningfulDecimals, 12);
+ if (meaningfulDigits > min(fractionalDigits ?? currency.decimals, currency.decimals)) {
+ return formatFixed(amount, decimals,
+ fractionalDigits: meaningfulDigits, trimZeros: trimZeros);
+ }
+ }
+ }
+
+ return formatFixed(
+ decimals != currency.decimals
+ ? _transformAmount(amount, decimals, currency.decimals)
+ : amount,
+ useBaseUnit ? 0 : currency.decimals,
+ fractionalDigits: fractionalDigits,
+ trimZeros: trimZeros,
+ );
+ }
// To Override the symbol with the ticker of the base unit
String getSymbol({required bool useBaseUnit}) {
@@ -301,4 +332,7 @@ class Money implements Comparable<Money> {
}
return currency.symbol;
}
+
+ /// new [Money] with absolute value of this instance
+ Money abs() => copyWith(amount: amount.abs());
}
### cw_core/lib/amount/money_local.dart
@@ -1,5 +1,5 @@
import "package:cw_core/amount/money.dart";
-import "package:intl/intl.dart";
+import "package:cw_core/crypto_amount_format.dart";
extension WithLocalSeparator on Money {
String toLocalStringWithSymbol({
@@ -37,10 +37,7 @@ extension WithLocalSeparator on Money {
String _withLocalSeparator(String amount, {String? locale}) {
final isNegative = amount.startsWith("-");
- final formater = NumberFormat("#,###", locale);
- final parts = (isNegative ? amount.substring(1) : amount).split(".");
- final formatted = [formater.format(int.tryParse(parts.first) ?? 0), ...parts.sublist(1)]
- .join(formater.symbols.DECIMAL_SEP);
+ final formatted = (isNegative ? amount.substring(1) : amount).withLocalSeperator(locale);
return isNegative ? "-$formatted" : formatted;
}
### cw_core/lib/balance_card_layout.dart
@@ -0,0 +1,125 @@
+import "package:cw_core/balance_card_style_settings.dart";
+
+class BalanceCardLayout {
+ BalanceCardLayout._(
+ this._settings, {
+ required List<int> visible,
+ required List<int> hidden,
+ required this.needsRepair,
+ }) : visible = List<int>.unmodifiable(visible),
+ hidden = List<int>.unmodifiable(hidden);
+
+ factory BalanceCardLayout.resolve({
+ required List<int> accountIndices,
+ required List<BalanceCardStyleSettings> settings,
+ }) {
+ final List<int> accounts = [];
+ for (final accountIndex in accountIndices) {
+ if (!accounts.contains(accountIndex)) {
+ accounts.add(accountIndex);
+ }
+ }
+
+ final settingsByAccount = <int, BalanceCardStyleSettings>{};
+ for (final setting in settings) {
+ if (accounts.contains(setting.accountIndex)) {
+ settingsByAccount.putIfAbsent(setting.accountIndex, () => setting);
+ }
+ }
+
+ final hidden = [
+ for (final accountIndex in accounts)
+ if (settingsByAccount[accountIndex]?.hidden ?? false) accountIndex,
+ ]..sort();
+
+ final visible = [
+ for (final accountIndex in accounts)
+ if (!hidden.contains(accountIndex)) accountIndex,
+ ];
+
+ visible.sort((a, b) => _compareStackPosition(a, b, settingsByAccount));
+
+ var needsRepair = false;
+ for (var position = 0; position < visible.length; position++) {
+ final stored = settingsByAccount[visible[position]];
+ if (stored != null && stored.cardOrder != position) {
+ needsRepair = true;
+ }
+ }
+
+ return BalanceCardLayout._(
+ settingsByAccount,
+ visible: visible,
+ hidden: hidden,
+ needsRepair: needsRepair,
+ );
+ }
+
+ final Map<int, BalanceCardStyleSettings> _settings;
+
+ final List<int> visible;
+ final List<int> hidden;
+
+ // flag when db order is broken
+ final bool needsRepair;
+
+ List<int> get designOrder => designOrderOf(visible);
+
+ static List<int> stackFromOrder(Map<int, int> cardOrder, {bool forceSingleCard = false}) {
+ final positions = cardOrder.keys.toList()..sort();
+ final accountIndices = [for (final position in positions) cardOrder[position]!];
+
+ if (accountIndices.isEmpty || !forceSingleCard) {
+ return accountIndices;
+ }
+ return [accountIndices.first];
+ }
+
+ static List<int> designOrderOf(Iterable<int> accountIndices) =>
+ List<int>.of(accountIndices)..sort();
+
+ Map<int, int> get orders =>
+ {for (var position = 0; position < visible.length; position++) visible[position]: position};
+
+ BalanceCardStyleSettings? settingFor(int accountIndex) => _settings[accountIndex];
+
+ BalanceCardLayout unhiding(int accountIndex) {
+ if (!hidden.contains(accountIndex)) {
+ return this;
+ }
+
+ return BalanceCardLayout._(
+ _settings,
+ visible: [...visible, accountIndex],
+ hidden: [
+ for (final hiddenAccount in hidden)
+ if (hiddenAccount != accountIndex) hiddenAccount,
+ ],
+ needsRepair: true,
+ );
+ }
+
+ static int _compareStackPosition(
+ int a,
+ int b,
+ Map<int, BalanceCardStyleSettings> settingsByAccount,
+ ) {
+ final orderA = _storedOrder(settingsByAccount[a]);
+ final orderB = _storedOrder(settingsByAccount[b]);
+
+ if (orderA != orderB) {
+ if (orderA == null) {
+ return 1;
+ }
+ if (orderB == null) {
+ return -1;
+ }
+ return orderA.compareTo(orderB);
+ }
+
+ return a.compareTo(b);
+ }
+
+ static int? _storedOrder(BalanceCardStyleSettings? setting) =>
+ setting == null || setting.cardOrder < 0 ? null : setting.cardOrder;
+}
### cw_core/lib/balance_card_style_settings.dart
@@ -7,6 +7,7 @@ class BalanceCardStyleSettings {
final int accountIndex;
final int gradientIndex;
final bool useSpecialDesign;
+ final bool hidden;
final String backgroundImagePath;
final int iconStyleIndex;
final bool isGradientOnly;
@@ -17,6 +18,7 @@ class BalanceCardStyleSettings {
required this.accountIndex,
required this.gradientIndex,
required this.useSpecialDesign,
+ required this.hidden,
required this.backgroundImagePath,
this.iconStyleIndex = 0,
this.isGradientOnly = false,
@@ -29,6 +31,7 @@ class BalanceCardStyleSettings {
"walletInfoId": walletInfoId,
"accountIndex": accountIndex,
"gradientIndex": gradientIndex,
+ "hidden": hidden ? 1 : 0,
"useSpecialDesign": useSpecialDesign ? 1 : 0,
"backgroundImagePath": backgroundImagePath,
"iconStyleIndex": iconStyleIndex,
@@ -42,6 +45,7 @@ class BalanceCardStyleSettings {
return BalanceCardStyleSettings(
walletInfoId: json["walletInfoId"] as int,
accountIndex: json["accountIndex"] as int,
+ hidden: json["hidden"] == 1,
gradientIndex: json["gradientIndex"] as int,
useSpecialDesign: json["useSpecialDesign"] == 1,
backgroundImagePath: json["backgroundImagePath"] as String? ?? "",
@@ -51,13 +55,38 @@ class BalanceCardStyleSettings {
);
}
+ BalanceCardStyleSettings copyWith({
+ int? walletInfoId,
+ int? accountIndex,
+ int? gradientIndex,
+ int? iconStyleIndex,
+ bool? isGradientOnly,
+ bool? useSpecialDesign,
+ bool? hidden,
+ String? backgroundImagePath,
+ int? cardOrder,
+ }) {
+ return BalanceCardStyleSettings(
+ walletInfoId: walletInfoId ?? this.walletInfoId,
+ accountIndex: accountIndex ?? this.accountIndex,
+ gradientIndex: gradientIndex ?? this.gradientIndex,
+ useSpecialDesign: useSpecialDesign ?? this.useSpecialDesign,
+ hidden: hidden ?? this.hidden,
+ backgroundImagePath: backgroundImagePath ?? this.backgroundImagePath,
+ cardOrder: cardOrder ?? this.cardOrder,
+ iconStyleIndex: iconStyleIndex ?? this.iconStyleIndex,
+ isGradientOnly: isGradientOnly ?? this.isGradientOnly
+ );
+ }
+
static BalanceCardStyleSettings fromCardDesign({
required int walletInfoId,
required int accountIndex,
required int cardOrder,
required CardDesign design,
int iconStyleIndex = 0,
int? gradientIndexOverride,
+ bool hidden = false
}) {
final int gradientIndex =
gradientIndexOverride ?? CardDesign.allGradients.indexOf(design.gradient);
@@ -66,6 +95,7 @@ class BalanceCardStyleSettings {
accountIndex: accountIndex,
gradientIndex: gradientIndex,
useSpecialDesign: design.backgroundType == CardDesignBackgroundTypes.svgFull,
+ hidden: hidden,
backgroundImagePath:
design.backgroundType == CardDesignBackgroundTypes.image ? design.imagePath : "",
iconStyleIndex: iconStyleIndex,
@@ -98,6 +128,58 @@ class BalanceCardStyleSettings {
}
Future<void> insert() async {
- db!.insert(tableName, toJson(), conflictAlgorithm: ConflictAlgorithm.replace);
+ await db!.insert(tableName, toJson(), conflictAlgorithm: ConflictAlgorithm.replace);
}
+
+ static Future<void> setVisibleOrder(int walletInfoId, Map<int, int> orderByAccountIndex) =>
+ _setOrder(walletInfoId, orderByAccountIndex, unhide: true);
+
+ static Future<void> setOrder(int walletInfoId, Map<int, int> orderByAccountIndex) =>
+ _setOrder(walletInfoId, orderByAccountIndex, unhide: false);
+
+ static Future<void> _setOrder(
+ int walletInfoId,
+ Map<int, int> orderByAccountIndex, {
+ required bool unhide,
+ }) async {
+ if (orderByAccountIndex.isEmpty) {
+ return;
+ }
+
+ final entries = orderByAccountIndex.entries.toList();
+ final batch = db!.batch();
+
+ for (final entry in entries) {
+ batch.update(
+ tableName,
+ {"cardOrder": entry.value, if (unhide) "hidden": 0},
+ where: "walletInfoId = ? AND accountIndex = ?",
+ whereArgs: [walletInfoId, entry.key],
+ );
+ }
+
+ final updatedRowCounts = await batch.commit();
+
+ for (int i = 0; i < entries.length; i++) {
+ if (updatedRowCounts[i] == 0) {
+ await db!.insert(
+ tableName,
+ positionOnly(walletInfoId, entries[i].key, entries[i].value).toJson(),
+ conflictAlgorithm: ConflictAlgorithm.ignore,
+ );
+ }
+ }
+ }
+
+ static BalanceCardStyleSettings positionOnly(
+ int walletInfoId, int accountIndex, int cardOrder) =>
+ BalanceCardStyleSettings(
+ walletInfoId: walletInfoId,
+ accountIndex: accountIndex,
+ gradientIndex: -1,
+ useSpecialDesign: true,
+ hidden: false,
+ backgroundImagePath: "",
+ cardOrder: cardOrder,
+ );
}
### cw_core/lib/card_design.dart
@@ -168,6 +168,8 @@ class CardDesign {
static const bnb = CardDesign(imagePath: "assets/new-ui/balance_card_icons/bnb.svg");
+ static const robinhood = CardDesign(imagePath: "assets/new-ui/balance_card_icons/robinhood.svg");
+
static const ethSpecial = CardDesign(
gradient: const LinearGradient(
colors: <Color>[Color(0xFF6259FF), Color(0xFF3B20E6)],
@@ -323,6 +325,14 @@ class CardDesign {
backgroundType: CardDesignBackgroundTypes.svgFull,
imagePath: "assets/new-ui/balance_card_backgrounds/bnb.svg");
+ static const robinhoodSpecial = CardDesign(
+ gradient: const LinearGradient(
+ colors: <Color>[Color(0xFFBDFE00), Color(0xFF85BE00)],
+ begin: Alignment.topCenter,
+ end: Alignment.bottomCenter),
+ backgroundType: CardDesignBackgroundTypes.svgFull,
+ imagePath: "assets/new-ui/balance_card_backgrounds/robinhood.svg");
+
CardDesign withGradient(Gradient gradient) => CardDesign(
gradient: gradient,
colors: preferredColorCombinations[gradient] ?? colors,
@@ -357,6 +367,7 @@ class CardDesign {
CryptoCurrency.arbEth: _CurrencyIconNames(ticker: 'arb', longName: 'arbitrum'),
CryptoCurrency.baseEth:
_CurrencyIconNames(ticker: 'base', longName: 'base', chainFile: 'base_icon'),
+ CryptoCurrency.robEth: _CurrencyIconNames(ticker: "rob", longName: "robinhood"),
CryptoCurrency.bch:
_CurrencyIconNames(ticker: 'bch', longName: 'bitcoin_cash', chainFile: 'bitcoin-cash'),
CryptoCurrency.btc: _CurrencyIconNames(ticker: 'btc', longName: 'bitcoin', outlineFile: 'BTC'),
@@ -409,6 +420,7 @@ class CardDesign {
arbitrum,
zec,
bnb,
+ robinhood,
ethSpecial,
btcSpecial,
xmrSpecial,
@@ -423,7 +435,8 @@ class CardDesign {
zanoSpecial,
arbitrumSpecial,
zecSpecial,
- bnbSpecial
+ bnbSpecial,
+ robinhoodSpecial,
];
static CardDesign forCurrencySpecial(CryptoCurrency currency) {
@@ -453,6 +466,7 @@ class CardDesign {
CryptoCurrency.zec: zec,
CryptoCurrency.dcr: dcr,
CryptoCurrency.bnb: bnb,
+ CryptoCurrency.robEth: robinhood,
};
static const Map<CryptoCurrency, CardDesign> specialDesignsForCurrencies = {
@@ -474,6 +488,7 @@ class CardDesign {
CryptoCurrency.arbEth: arbitrumSpecial,
CryptoCurrency.zec: zecSpecial,
CryptoCurrency.bnb: bnbSpecial,
+ CryptoCurrency.robEth: robinhoodSpecial,
};
static Map<Gradient, CardColorCombination> preferredColorCombinations = {
### cw_core/lib/crypto_amount_format.dart
@@ -67,7 +67,10 @@ extension MaxDecimals on String {
return [parts.first.withLocalSeperator(locale), ...parts.sublist(1)].join(" ");
}
- final formater = NumberFormat("#,###", locale);
+ final formater = NumberFormat(
+ "#,###",
+ Intl.verifiedLocale(locale, NumberFormat.localeExists, onFailure: (_) => "en"),
+ );
final parts = replaceAll(",", "").split(".");
if (parts.first.contains("< 0")) parts.first = "0";
### cw_core/lib/crypto_currency.dart
@@ -45,6 +45,11 @@ class CryptoCurrency extends EnumerableItem<int> with Serializable<int> implemen
@override
String get symbol => title;
+ @override
+ String get apiString => "crypto.$title";
+
+ String get network => tag ?? title;
+
set enabled(bool value) => this.enabled = value;
static const all = [
@@ -141,6 +146,7 @@ class CryptoCurrency extends EnumerableItem<int> with Serializable<int> implemen
CryptoCurrency.arbEth,
CryptoCurrency.usdcArb,
CryptoCurrency.usdtArb,
+ CryptoCurrency.robEth,
];
static const havenCurrencies = [
@@ -972,6 +978,16 @@ class CryptoCurrency extends EnumerableItem<int> with Serializable<int> implemen
name: 'ltcmweb',
iconPath: 'assets/new-ui/crypto_full_icons/litecoin.svg',
decimals: 8);
+ static const robEth = CryptoCurrency(
+ title: "ETH",
+ tag: "ROB",
+ fullName: "Ethereum",
+ raw: 111,
+ name: "robeth",
+ iconPath: "assets/new-ui/crypto_full_icons/ethereum.svg",
+ decimals: 18,
+ flatIconPath: "assets/new-ui/balance_card_icons/robinhood.svg",
+ chainIconPath: "assets/new-ui/chain_badges/robinhood.svg");
static final Map<int, CryptoCurrency> _rawCurrencyMap = [
...all,
@@ -997,7 +1013,14 @@ class CryptoCurrency extends EnumerableItem<int> with Serializable<int> implemen
...zcashCurrencies
].fold<Map<String, CryptoCurrency>>(<String, CryptoCurrency>{}, (acc, item) {
if (item.fullName != null) {
- acc.addAll({item.fullName!.toLowerCase(): item});
+ final fullName = item.fullName!.toLowerCase();
+ final existing = acc[fullName];
+
+ // Mainnet ETH and the L2 ETHs share the "Ethereum" full name,
+ // so we make the untagged coin keeps the name
+ if (existing == null || existing.tag != null) {
+ acc[fullName] = item;
+ }
}
return acc;
});
@@ -1012,6 +1035,7 @@ class CryptoCurrency extends EnumerableItem<int> with Serializable<int> implemen
'secret': scrt,
'stellar': xlm,
'avalanche': avaxc,
+ 'avax': avaxc,
'binance': bnb,
'tether': usdt,
'usdcoin': usdc,
@@ -1023,6 +1047,8 @@ class CryptoCurrency extends EnumerableItem<int> with Serializable<int> implemen
'base': baseEth,
'arbitrum': arbEth,
'bsc': bnb,
+ "rob": robEth,
+ "robinhood": robEth,
};
static CryptoCurrency deserialize({required int raw}) {
### cw_core/lib/currency.dart
@@ -20,4 +20,5 @@ abstract class Currency {
@override
int get hashCode => decimals.hashCode ^ symbol.hashCode ^ tag.hashCode;
+ String get apiString;
}
### cw_core/lib/currency_for_wallet_type.dart
@@ -1,4 +1,5 @@
import 'package:cw_core/crypto_currency.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/wallet_type.dart';
CryptoCurrency walletTypeToCryptoCurrency(WalletType type, {bool isTestnet = false, int? chainId}) {
@@ -26,6 +27,8 @@ CryptoCurrency walletTypeToCryptoCurrency(WalletType type, {bool isTestnet = fal
return CryptoCurrency.arbEth;
case WalletType.bsc:
return CryptoCurrency.bnb;
+ case WalletType.robinhood:
+ return CryptoCurrency.robEth;
case WalletType.bitcoinCash:
return CryptoCurrency.bch;
case WalletType.nano:
@@ -49,8 +52,8 @@ CryptoCurrency walletTypeToCryptoCurrency(WalletType type, {bool isTestnet = fal
case WalletType.zcash:
return CryptoCurrency.zec;
case WalletType.none:
- throw Exception(
- 'Unexpected wallet type: ${type.toString()} for CryptoCurrency walletTypeToCryptoCurrency');
+ throw BadWalletTypeException(
+ 'Unexpected wallet type: ${type.toString()} for CryptoCurrency walletTypeToCryptoCurrency', type);
}
}
@@ -66,6 +69,8 @@ CryptoCurrency getCryptoCurrencyByChainId(int chainId) {
return CryptoCurrency.arbEth;
case 56:
return CryptoCurrency.bnb;
+ case 4663:
+ return CryptoCurrency.robEth;
default:
return CryptoCurrency.eth;
}
@@ -85,6 +90,8 @@ int? getChainIdByCryptoCurrency(CryptoCurrency currency) {
return 42161;
case CryptoCurrency.bnb:
return 56;
+ case CryptoCurrency.robEth:
+ return 4663;
default:
return null;
}
@@ -109,6 +116,10 @@ String getCryptoCurrencyIconForWalletListItem(WalletType type,
return "assets/new-ui/crypto_full_icons/base.svg";
}
+ if (type == WalletType.robinhood) {
+ return "assets/new-ui/crypto_full_icons/robinhood.svg";
+ }
+
return walletTypeToCryptoCurrency(type, isTestnet: isTestnet, chainId: chainId).iconPath ?? "";
}
@@ -133,6 +144,8 @@ String? symbolIconPathForWalletType(WalletType type) {
return "$prefix/bch-symbol.svg";
case WalletType.polygon:
return "$prefix/pol-symbol.svg";
+ case WalletType.robinhood:
+ return "$prefix/rob-symbol.svg";
case WalletType.solana:
return "$prefix/sol-symbol.svg";
case WalletType.tron:
### cw_core/lib/db/sqlite.dart
@@ -1,26 +1,28 @@
-import 'dart:io';
+import "dart:io";
-import 'package:cw_core/db/sqlite_debug.dart';
-import 'package:cw_core/root_dir.dart';
-import 'package:cw_core/utils/print_verbose.dart';
-import 'package:flutter/foundation.dart';
-import 'package:sqflite_common_ffi/sqflite_ffi.dart';
-import 'package:path/path.dart' as p;
+import "package:cw_core/db/sqlite_debug.dart";
+import "package:cw_core/exceptions/cake_exception.dart";
+import "package:cw_core/root_dir.dart";
+import "package:cw_core/utils/print_verbose.dart";
+import "package:cw_core/wallet_type.dart";
+import "package:flutter/foundation.dart";
+import "package:path/path.dart" as p;
+import "package:sqflite_common_ffi/sqflite_ffi.dart";
Database? db;
Future<void> _addColumnIfNotExists(
- Database db, {
- required String table,
- required String column,
- required String definition,
-}) async {
+ Database db, {
+ required String table,
+ required String column,
+ required String definition,
+ }) async {
final result = await db.rawQuery("PRAGMA table_info($table)");
- final columnExists = result.any((row) => row['name'] == column);
+ final columnExists = result.any((row) => row["name"] == column);
if (!columnExists) {
await db.execute(
- 'ALTER TABLE $table ADD COLUMN $column $definition;',
+ "ALTER TABLE $table ADD COLUMN $column $definition;",
);
}
}
@@ -31,6 +33,10 @@ Future<File> sqliteDebugMarkerFile() async {
return File(dbDebugMarker);
}
+class DebugMarkerException extends CakeException {
+ const DebugMarkerException() : super("Debug marker is present");
+}
+
Future<void> initDb({String? pathOverride}) async {
if (!kDebugMode && !kProfileMode) {
await _initDb(pathOverride: pathOverride);
@@ -39,7 +45,7 @@ Future<void> initDb({String? pathOverride}) async {
final dbDebugMarker = await sqliteDebugMarkerFile();
try {
if (dbDebugMarker.existsSync()) {
- throw Exception("Debug marker is present");
+ throw const DebugMarkerException();
}
await _initDb(pathOverride: pathOverride);
} catch (e, s) {
@@ -63,11 +69,13 @@ Future<void> _initDb({String? pathOverride}) async {
}
}
await db?.close();
- db = await openDatabase(dbFile.path, version: 11,
- onUpgrade: (Database db, int oldVersion, int newVersion) async {
- printV("migrating: $oldVersion, $newVersion");
- if (oldVersion <= 1) {
- await db.execute('''
+ db = await openDatabase(
+ dbFile.path,
+ version: 15,
+ onUpgrade: (db, oldVersion, newVersion) async {
+ printV("migrating: $oldVersion, $newVersion");
+ if (oldVersion <= 1) {
+ await db.execute("""
DELETE FROM WalletInfo
WHERE walletInfoId NOT IN (
SELECT MIN(walletInfoId)
@@ -77,10 +85,10 @@ WHERE walletInfoId NOT IN (
CREATE UNIQUE INDEX IF NOT EXISTS idx_walletinfo_id_unique
ON WalletInfo (id);
-''');
- }
- if (oldVersion <= 2) {
- await db.execute('''
+""");
+ }
+ if (oldVersion <= 2) {
+ await db.execute('''
CREATE TABLE IF NOT EXISTS BalanceCardStyleSettings (
walletInfoId INTEGER,
accountIndex INTEGER DEFAULT -1,
@@ -91,73 +99,116 @@ CREATE TABLE IF NOT EXISTS BalanceCardStyleSettings (
FOREIGN KEY (walletInfoId) REFERENCES WalletInfo(walletInfoId)
);
''');
- await _addColumnIfNotExists(
- db,
- table: 'WalletInfo',
- column: 'receiveInfoboxDismissed',
- definition: 'BOOLEAN DEFAULT FALSE',
- );
-
- await _addColumnIfNotExists(
- db,
- table: 'BalanceCardStyleSettings',
- column: 'cardOrder',
- definition: 'INTEGER DEFAULT 0',
- );
- }
- if (oldVersion <= 3) {
- await _addColumnIfNotExists(db,
- table: "WalletInfo", column: "showCombinedBalance", definition: "BOOLEAN DEFAULT TRUE");
- // null - primary token (eth, sol etc)
- // not null - address of fav token
- // if address doesn't correspond to a valid token, fallback to primary token
- await _addColumnIfNotExists(db,
- table: "WalletInfo", column: "favoriteTokenAddress", definition: "TEXT DEFAULT NULL");
- }
+ await _addColumnIfNotExists(
+ db,
+ table: "WalletInfo",
+ column: "receiveInfoboxDismissed",
+ definition: "BOOLEAN DEFAULT FALSE",
+ );
- if (oldVersion <= 4) {
- await _createBridgeTransferTable(db);
- }
+ await _addColumnIfNotExists(
+ db,
+ table: 'BalanceCardStyleSettings',
+ column: 'cardOrder',
+ definition: 'INTEGER DEFAULT 0',
+ );
+ }
+ if (oldVersion <= 3) {
+ await _addColumnIfNotExists(db,
+ table: "WalletInfo", column: "showCombinedBalance", definition: "BOOLEAN DEFAULT TRUE");
+ // null - primary token (eth, sol etc)
+ // not null - address of fav token
+ // if address doesn't correspond to a valid token, fallback to primary token
+ await _addColumnIfNotExists(db,
+ table: "WalletInfo", column: "favoriteTokenAddress", definition: "TEXT DEFAULT NULL");
+ }
- if (oldVersion <= 5) {
- await _createTradeTable(db);
- }
- if (oldVersion <= 6) {
- await _addColumnIfNotExists(
- db,
- table: 'Trade',
- column: 'toAddressExtraId',
- definition: 'TEXT',
- );
- }
- if (oldVersion <= 7) {
- await _createNodeTable(db);
- }
- if (oldVersion <= 8) {
- await _addColumnIfNotExists(
- db,
- table: 'BalanceCardStyleSettings',
- column: 'iconStyleIndex',
- definition: 'INTEGER DEFAULT 0',
- );
- await _addColumnIfNotExists(
- db,
- table: 'BalanceCardStyleSettings',
- column: 'isGradientOnly',
- definition: 'BOOLEAN DEFAULT FALSE',
- );
- }
- if (oldVersion <= 9) {
- await _createErc20TokenTable(db);
- await _createSplTokenTable(db);
- await _createTronTokenTable(db);
- }
+ if (oldVersion <= 4) {
+ await _createBridgeTransferTable(db);
+ }
- if (oldVersion <= 10) {
- await _createImportedNFTTable(db);
- }
- }, onCreate: (Database db, int version) async {
- await db.execute('''
+ if (oldVersion <= 5) {
+ await _createTradeTable(db);
+ }
+ if (oldVersion <= 6) {
+ await _addColumnIfNotExists(
+ db,
+ table: 'Trade',
+ column: 'toAddressExtraId',
+ definition: 'TEXT',
+ );
+ }
+ if (oldVersion <= 7) {
+ await _createNodeTable(db);
+ }
+ if (oldVersion <= 8) {
+ await _addColumnIfNotExists(
+ db,
+ table: 'BalanceCardStyleSettings',
+ column: 'iconStyleIndex',
+ definition: 'INTEGER DEFAULT 0',
+ );
+ await _addColumnIfNotExists(
+ db,
+ table: 'BalanceCardStyleSettings',
+ column: 'isGradientOnly',
+ definition: 'BOOLEAN DEFAULT FALSE',
+ );
+ }
+ if (oldVersion <= 9) {
+ await _createErc20TokenTable(db);
+ await _createSplTokenTable(db);
+ await _createTronTokenTable(db);
+ }
+ if (oldVersion <= 10) {
+ await _createImportedNFTTable(db);
+ }
+ if (oldVersion <= 11) {
+ await _addColumnIfNotExists(
+ db,
+ table: "WalletInfo",
+ column: "showSeedBackupReminder",
+ definition: "BOOLEAN DEFAULT FALSE",
+ );
+ }
+ if (oldVersion <= 12) {
+ await _createChartsTables(db);
+ }
+
+ if (oldVersion <= 13) {
+ await _createWalletInfoAccountTable(db);
+ await _addColumnIfNotExists(
+ db,
+ table: "WalletInfo",
+ column: "accountDiscoveryLimit",
+ definition: "INTEGER DEFAULT NULL",
+ );
+ await _addColumnIfNotExists(
+ db,
+ table: "WalletInfo",
+ column: "isMultiAccountsEnabled",
+ definition: "INTEGER DEFAULT NULL",
+ );
+ await _addColumnIfNotExists(
+ db,
+ table: "WalletInfo",
+ column: "currentAccountIndex",
+ definition: "INTEGER NOT NULL DEFAULT 0",
+ );
+
+ await _migrateBitcoinCardStylesForAccounts(db);
+ }
+ if(oldVersion <= 14) {
+ await _addColumnIfNotExists(
+ db,
+ table: "BalanceCardStyleSettings",
+ column: "hidden",
+ definition: "BOOLEAN DEFAULT FALSE",
+ );
+ }
+ },
+ onCreate: (Database db, int version) async {
+ await db.execute('''
CREATE TABLE WalletInfo (
walletInfoId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
id TEXT NOT NULL,
@@ -180,13 +231,17 @@ CREATE TABLE WalletInfo (
hashedWalletIdentifier TEXT,
isNonSeedWallet INTEGER DEFAULT (0) NOT NULL,
sortOrder INTEGER DEFAULT (0) NOT NULL,
+ currentAccountIndex INTEGER NOT NULL DEFAULT 0,
receiveInfoboxDismissed BOOLEAN DEFAULT FALSE,
showCombinedBalance BOOLEAN DEFAULT TRUE,
- favoriteTokenAddress TEXT DEFAULT NULL
+ favoriteTokenAddress TEXT DEFAULT NULL,
+ accountDiscoveryLimit INTEGER DEFAULT NULL,
+ isMultiAccountsEnabled INTEGER DEFAULT NULL,
+ showSeedBackupReminder BOOLEAN DEFAULT FALSE
);
''');
- await db.execute('''
+ await db.execute("""
CREATE TABLE WalletInfoDerivationInfo (
walletInfoDerivationInfoId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
address TEXT NOT NULL,
@@ -197,9 +252,9 @@ CREATE TABLE WalletInfoDerivationInfo (
scriptType TEXT,
description TEXT
);
-''');
+""");
- await db.execute('''
+ await db.execute('''
CREATE TABLE WalletInfoAddress (
walletInfoAddressId INTEGER PRIMARY KEY AUTOINCREMENT,
walletInfoId INTEGER,
@@ -209,7 +264,7 @@ CREATE TABLE WalletInfoAddress (
);
''');
- await db.execute('''
+ await db.execute("""
CREATE TABLE WalletInfoAddressInfo (
walletInfoAddressInfoId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
walletInfoId INTEGER NOT NULL,
@@ -219,9 +274,9 @@ CREATE TABLE WalletInfoAddressInfo (
mapValueLabel TEXT NOT NULL,
CONSTRAINT WalletInfoAddressInfo_WalletInfo_FK FOREIGN KEY (walletInfoId) REFERENCES WalletInfo(walletInfoId)
);
-''');
+""");
- await db.execute('''
+ await db.execute('''
CREATE TABLE "WalletInfoAddressMap" (
walletInfoAddressMapId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
walletInfoId INTEGER NOT NULL,
@@ -230,11 +285,11 @@ CREATE TABLE "WalletInfoAddressMap" (
CONSTRAINT WalletInfoAddress_WalletInfo_FK FOREIGN KEY (walletInfoId) REFERENCES WalletInfo(walletInfoId)
);
''');
- await db.execute('''
+ await db.execute("""
CREATE UNIQUE INDEX IF NOT EXISTS idx_walletinfo_id_unique
ON WalletInfo (id);
-''');
- await db.execute('''
+""");
+ await db.execute('''
CREATE TABLE BalanceCardStyleSettings (
walletInfoId INTEGER,
accountIndex INTEGER DEFAULT -1,
@@ -244,22 +299,44 @@ CREATE TABLE BalanceCardStyleSettings (
iconStyleIndex INTEGER DEFAULT 0,
isGradientOnly BOOLEAN DEFAULT FALSE,
cardOrder INTEGER DEFAULT 0,
+ hidden BOOLEAN DEFAULT FALSE,
PRIMARY KEY (walletInfoId, accountIndex),
FOREIGN KEY (walletInfoId) REFERENCES WalletInfo(walletInfoId)
);
''');
- await _createBridgeTransferTable(db);
- await _createNodeTable(db);
- await _createTradeTable(db);
- await _createErc20TokenTable(db);
- await _createSplTokenTable(db);
- await _createTronTokenTable(db);
- await _createImportedNFTTable(db);
- });
+ await _createBridgeTransferTable(db);
+ await _createNodeTable(db);
+ await _createTradeTable(db);
+ await _createChartsTables(db);
+ await _createErc20TokenTable(db);
+ await _createSplTokenTable(db);
+ await _createTronTokenTable(db);
+ await _createImportedNFTTable(db);
+ await _createWalletInfoAccountTable(db);
+ },
+ );
+}
+
+Future<void> _createChartsTables(Database db) async {
+ await db.execute("""
+CREATE TABLE PriceData (
+ fromCurrency TEXT NOT NULL,
+ toCurrency TEXT NOT NULL,
+ timestamp INTEGER NOT NULL,
+ price TEXT NOT NULL,
+ PRIMARY KEY (fromCurrency, toCurrency, timestamp)
+);
+""");
+ await db.execute("""
+CREATE TABLE ChartsAssets (
+ asset TEXT PRIMARY KEY,
+ isFavorite BOOLEAN DEFAULT FALSE
+);
+ """);
}
Future<void> _createTradeTable(Database db) async {
- await db.execute('''
+ await db.execute("""
CREATE TABLE IF NOT EXISTS Trade (
tradeId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
id TEXT NOT NULL,
@@ -314,11 +391,48 @@ CREATE TABLE IF NOT EXISTS Trade (
chainId INTEGER,
fee REAL
);
-''');
- await db.execute('''
+""");
+ await db.execute("""
CREATE UNIQUE INDEX IF NOT EXISTS idx_trade_id_unique
ON Trade (id);
-''');
+""");
+}
+
+Future<void> _createWalletInfoAccountTable(Database db) async {
+ await db.execute("""
+CREATE TABLE IF NOT EXISTS WalletInfoAccount (
+ walletInfoId INTEGER NOT NULL,
+ accountIndex INTEGER NOT NULL,
+ label TEXT NOT NULL,
+ PRIMARY KEY (walletInfoId, accountIndex),
+ CONSTRAINT WalletInfoAccount_WalletInfo_FK FOREIGN KEY (walletInfoId) REFERENCES WalletInfo(walletInfoId)
+);
+""");
+
+ await db.execute("""
+CREATE INDEX IF NOT EXISTS idx_walletinfoaccount_walletinfoid
+ON WalletInfoAccount(walletInfoId);
+""");
+}
+
+
+Future<void> _migrateBitcoinCardStylesForAccounts(Database db) async {
+ const bitcoinWallets = 'SELECT walletInfoId FROM WalletInfo WHERE "type" = ?';
+ final btc = WalletType.bitcoin.index;
+
+ // Lightning: 0 -> -2 (first, so accountIndex 0 is free for the Bitcoin card)
+ await db.rawUpdate(
+ "UPDATE OR REPLACE BalanceCardStyleSettings SET accountIndex = -2 "
+ "WHERE accountIndex = 0 AND walletInfoId IN ($bitcoinWallets)",
+ [btc],
+ );
+
+ // Bitcoin: -1 -> 0 (primary account, first in order)
+ await db.rawUpdate(
+ "UPDATE OR REPLACE BalanceCardStyleSettings SET accountIndex = 0, cardOrder = 0 "
+ "WHERE accountIndex = -1 AND walletInfoId IN ($bitcoinWallets)",
+ [btc],
+ );
}
Future<Map<String, dynamic>> dumpDb() async {
@@ -334,7 +448,7 @@ Future<Map<String, dynamic>> dumpDb() async {
Future<List<String>> _getTableNames(Database db) async {
final tableNames = await db.rawQuery('SELECT name FROM sqlite_master WHERE type = "table"');
- return tableNames.map((e) => (e["name"]).toString()).toList();
+ return tableNames.map((e) => e["name"].toString()).toList();
}
Future<Map<String, dynamic>> _dumpDb() async {
@@ -357,7 +471,7 @@ Future<Map<String, dynamic>> dumpCustomDb(String path) async {
}
Future<void> _createBridgeTransferTable(Database db) async {
- await db.execute('''
+ await db.execute("""
CREATE TABLE IF NOT EXISTS BridgeTransfer (
id TEXT NOT NULL PRIMARY KEY,
wallet_id TEXT NOT NULL,
@@ -376,11 +490,11 @@ CREATE TABLE IF NOT EXISTS BridgeTransfer (
error_message TEXT,
status_message TEXT
);
-''');
- await db.execute('''
+""");
+ await db.execute("""
CREATE INDEX IF NOT EXISTS idx_bridgetransfer_wallet_id
ON BridgeTransfer(wallet_id);
-''');
+""");
}
Future<void> _createErc20TokenTable(Database db) async {
@@ -469,7 +583,7 @@ ON TronToken (walletName, contractAddress);
}
Future<void> _createNodeTable(Database db) async {
- db.execute("""
+ await db.execute("""
CREATE TABLE Node (
NodeId INTEGER PRIMARY KEY,
uri TEXT NOT NULL,
### cw_core/lib/encryption_file_utils.dart
@@ -1,41 +1,34 @@
-import 'dart:io';
-import 'dart:typed_data';
import 'package:cw_core/utils/file.dart' as file;
-import 'package:cake_backup/backup.dart' as cwb;
-EncryptionFileUtils encryptionFileUtilsFor(bool direct) =>
- direct ? XChaCha20EncryptionFileUtils() : Salsa20EncryhptionFileUtils();
+EncryptionFileUtils encryptionFileUtilsFor(bool isDirect) =>
+ XChaCha20MigratingEncryptionFileUtils(isDirect: isDirect);
abstract class EncryptionFileUtils {
Future<void> write({required String path, required String password, required String data});
Future<String> read({required String path, required String password});
}
-class Salsa20EncryhptionFileUtils extends EncryptionFileUtils {
- // Requires legacy complex key + iv as password
- @override
- Future<void> write(
- {required String path, required String password, required String data}) async =>
- await file.write(path: path, password: password, data: data);
+class XChaCha20MigratingEncryptionFileUtils extends EncryptionFileUtils {
+ XChaCha20MigratingEncryptionFileUtils({required this.isDirect});
- // Requires legacy complex key + iv as password
- @override
- Future<String> read({required String path, required String password}) async =>
- await file.read(path: path, password: password);
-}
+ final bool isDirect;
-class XChaCha20EncryptionFileUtils extends EncryptionFileUtils {
@override
- Future<void> write({required String path, required String password, required String data}) async {
- final encrypted = await cwb.encrypt(password, Uint8List.fromList(data.codeUnits));
- await File(path).writeAsBytes(encrypted);
+ Future<void> write({required String path, required String password, required String data}) {
+ return file.write(
+ path: path,
+ password: password,
+ data: data,
+ highEntropyPassphrase: !isDirect,
+ );
}
@override
- Future<String> read({required String path, required String password}) async {
- final file = File(path);
- final encrypted = await file.readAsBytes();
- final bytes = await cwb.decrypt(password, encrypted);
- return String.fromCharCodes(bytes);
+ Future<String> read({required String path, required String password}) {
+ return file.read(
+ path: path,
+ password: password,
+ highEntropyPassphrase: !isDirect,
+ );
}
}
### cw_core/lib/enumerable_item.dart
@@ -9,6 +9,6 @@ abstract class EnumerableItem<T> {
}
mixin Serializable<T> on EnumerableItem<T> {
- static Serializable deserialize<T>({required T raw}) => throw Exception('Unimplemented');
+ static Serializable deserialize<T>({required T raw}) => throw UnimplementedError();
T serialize() => raw;
}
### cw_core/lib/erc20_token.dart
@@ -15,6 +15,7 @@ class Erc20Token extends CryptoCurrency {
this.id = 0,
this.walletName,
this.chainId,
+ Set<String> groups = const {},
}) : _enabled = enabled,
super(
name: symbol.toLowerCase(),
@@ -24,6 +25,7 @@ class Erc20Token extends CryptoCurrency {
iconPath: iconPath,
decimals: decimal,
isPotentialScam: isPotentialScam,
+ groups: groups,
);
Erc20Token.copyWith(
@@ -51,6 +53,7 @@ class Erc20Token extends CryptoCurrency {
iconPath: icon,
decimals: other.decimal,
isPotentialScam: other.isPotentialScam,
+ groups: other.groups,
);
Erc20Token.fromMap(Map<String, Object?> map)
@@ -187,4 +190,7 @@ class Erc20Token extends CryptoCurrency {
@override
int get hashCode => contractAddress.hashCode;
+
+ @override
+ String get apiString => "evm.$contractAddress";
}
### cw_core/lib/exceptions.dart
@@ -1,89 +1,128 @@
import 'package:cw_core/crypto_currency.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
+
+class TransactionWrongBalanceException extends TransactionGenerationException {
+ TransactionWrongBalanceException(this.currency, {this.amount}) : super( "wrong balance: ${currency.symbol} $amount");
-class TransactionWrongBalanceException implements Exception {
- TransactionWrongBalanceException(this.currency, {this.amount});
final CryptoCurrency currency;
final int? amount;
}
-class TransactionNoInputsException implements Exception {}
+class TransactionNoInputsException extends TransactionGenerationException {
-class TransactionNoFeeException implements Exception {}
+ TransactionNoInputsException() : super("Not enough inputs available. Please select more under Coin Control");
-class TransactionNoDustException implements Exception {}
+}
+class TransactionNoFeeException extends TransactionGenerationException {
+ TransactionNoFeeException() : super("cannot send with zero fee");
+}
-class TransactionNoDustOnChangeException implements Exception {
- TransactionNoDustOnChangeException(this.max, this.min);
+class TransactionNoDustException extends TransactionGenerationException {
+ TransactionNoDustException()
+ : super("The transaction is rejected by sending an amount too small. Please try increasing the amount.");
+}
+class TransactionNoDustOnChangeException extends TransactionGenerationException {
final String max;
final String min;
+
+ TransactionNoDustOnChangeException(this.max, this.min)
+ : super("The transaction is rejected with this amount. With these coins you can send ${min} without change or ${max} that returns change.");
}
-class TransactionCommitFailed implements Exception {
+class TransactionCommitFailed extends TransactionSendingException {
final String? errorMessage;
- TransactionCommitFailed({this.errorMessage});
-
- @override
- String toString() => errorMessage ?? "unknown error";
+ TransactionCommitFailed({this.errorMessage}) : super(errorMessage ?? "unknown error");
}
-class TransactionCommitFailedDustChange implements Exception {}
+class TransactionCommitFailedDustChange extends TransactionSendingException {
+ TransactionCommitFailedDustChange()
+ : super("Transaction rejected by network rules, low change amount (dust). Try sending ALL or reducing the amount.");
+}
-class TransactionCommitFailedDustOutput implements Exception {}
+class TransactionCommitFailedDustOutput extends TransactionSendingException {
+ TransactionCommitFailedDustOutput()
+ : super("Transaction rejected by network rules, low output amount (dust). Please increase the amount.");
+}
-class TransactionCommitFailedDustOutputSendAll implements Exception {}
+class TransactionCommitFailedDustOutputSendAll extends TransactionSendingException {
+ TransactionCommitFailedDustOutputSendAll()
+ : super("Transaction rejected by network rules, low output amount (dust). Please check the balance of coins selected under Coin Control.");
+}
-class TransactionCommitFailedVoutNegative implements Exception {}
+class TransactionCommitFailedVoutNegative extends TransactionSendingException {
+ TransactionCommitFailedVoutNegative()
+ : super("Not enough balance to pay for this transaction's fees. Please check the balance of coins under Coin Control.");
+}
-class TransactionCommitFailedBIP68Final implements Exception {}
+class TransactionCommitFailedBIP68Final extends TransactionSendingException {
+ TransactionCommitFailedBIP68Final()
+ : super("Transaction has unconfirmed inputs and failed to replace by fee.");
+}
-class TransactionCommitFailedLessThanMin implements Exception {}
+class TransactionCommitFailedLessThanMin extends TransactionSendingException {
+ TransactionCommitFailedLessThanMin()
+ : super("Selected Fee is less than the minimum, please increase the fees to be able to send the transaction");
+}
-class TransactionInputNotSupported implements Exception {}
+class TransactionInputNotSupported extends TransactionSendingException {
+ TransactionInputNotSupported()
+ : super("You are using the wrong input type for this type of payment");
+}
-class SignNativeTokenTransactionRentException implements Exception {}
+class SignNativeTokenTransactionRentException extends TransactionGenerationException {
+ SignNativeTokenTransactionRentException()
+ : super("Transaction cannot be completed. Insufficient SOL left for rent after transaction. Kindly top up your SOL balance or reduce the amount of SOL you are sending.");
+}
-class CreateAssociatedTokenAccountException implements Exception {
+class CreateAssociatedTokenAccountException extends CakeException {
final String errorMessage;
- CreateAssociatedTokenAccountException(this.errorMessage);
+ CreateAssociatedTokenAccountException(this.errorMessage)
+ : super("Error creating associated token account for receipient address. " + errorMessage);
}
-class SignSPLTokenTransactionRentException implements Exception {}
+class SignSPLTokenTransactionRentException extends CakeException {
+ SignSPLTokenTransactionRentException()
+ : super("Transaction cannot be completed. Insufficient SOL left for rent after transaction. Kindly top up your SOL balance.");
+}
-class NoAssociatedTokenAccountException implements Exception {}
+class NoAssociatedTokenAccountException extends CakeException {
+ NoAssociatedTokenAccountException()
+ : super("There is no associated token account for this address.");
+}
-class NotAnNFTException implements Exception {}
+class NotAnNFTException extends CakeException {
+ NotAnNFTException() : super("Not an NFT.");
+}
-class AmbiguousTokenSymbolException implements Exception {
- AmbiguousTokenSymbolException(this.symbol);
+class UnrecognizedTokenProgramException extends CakeException {
+ UnrecognizedTokenProgramException(this.programId)
+ : super("Unrecognized token program: $programId");
- final String symbol;
+ final String programId;
}
-class RestoreFromSeedException implements Exception {
- final String message;
+class AmbiguousTokenSymbolException extends CakeException {
+ AmbiguousTokenSymbolException(this.symbol) : super("Ambigous token: $symbol");
- RestoreFromSeedException(this.message);
+ final String symbol;
+}
+
+class RestoreFromSeedException extends CakeException {
+ RestoreFromSeedException(String message) : super(message);
}
-class WalletDeprecationException implements Exception {
+class WalletDeprecationException extends CakeException {
final String seed;
final CryptoCurrency curr;
- @override
- String toString() => "Wallet type no longer supported";
-
- WalletDeprecationException({required this.seed, required this.curr});
+ WalletDeprecationException({required this.seed, required this.curr})
+ : super("Wallet type no longer supported");
}
-class WalletSwitchException implements Exception {
- WalletSwitchException(this.message);
-
- final String message;
-
- @override
- String toString() => message;
+class WalletSwitchException extends CakeException {
+ WalletSwitchException(super.message);
}
### cw_core/lib/exceptions/cake_exception.dart
@@ -0,0 +1,122 @@
+
+import "package:cw_core/currency.dart";
+import "package:cw_core/wallet_type.dart";
+
+abstract class CakeException implements Exception {
+ const CakeException(this.message);
+
+ final String message;
+
+ @override
+ String toString() => message;
+}
+
+class BadWalletTypeException extends CakeException {
+ const BadWalletTypeException(super.message, this.walletType);
+
+ final WalletType walletType;
+}
+
+class BadCurrencyException extends CakeException {
+
+ const BadCurrencyException(super.message, this.curr);
+ final Currency curr;
+}
+
+class BadCurrencyPairException extends CakeException {
+ const BadCurrencyPairException(super.message, this.from, this.to);
+
+ final Currency from;
+ final Currency to;
+}
+
+class ConnectionException extends CakeException {
+ const ConnectionException(super.message);
+}
+
+class ServerResponseException extends CakeException {
+ const ServerResponseException(super.message);
+}
+
+mixin ResponseCodeException {
+ int get code;
+}
+
+class CurrencyParseException extends CakeException {
+ const CurrencyParseException(super.message);
+}
+
+class DeserializeException extends CakeException {
+ const DeserializeException(super.message);
+}
+
+class WalletOpenException extends CakeException {
+ const WalletOpenException(super.message);
+}
+
+class WalletExistsException extends CakeException {
+ const WalletExistsException(super.message);
+}
+
+class WalletNotFoundException extends WalletOpenException {
+ const WalletNotFoundException({this.type, required this.name})
+ : super("Wallet not found");
+
+ final WalletType? type;
+ final String name;
+}
+
+class AccountNotFoundException extends CakeException {
+ const AccountNotFoundException(String name)
+ : name = name,
+ super("Account not found: $name");
+ final String name;
+}
+
+class WalletCreationException extends CakeException {
+ const WalletCreationException(super.message);
+}
+
+class BadWalletDataException extends WalletCreationException {
+ const BadWalletDataException(super.message);
+}
+
+class BadKeysException extends BadWalletDataException {
+ const BadKeysException(super.message);
+}
+
+class BadMnemonicException extends BadWalletDataException {
+ const BadMnemonicException(super.message);
+}
+
+class TransactionGenerationException extends CakeException {
+ const TransactionGenerationException(super.message);
+}
+
+class TransactionSendingException extends CakeException {
+ const TransactionSendingException(super.message);
+}
+
+class ScanValueException extends CakeException {
+ const ScanValueException(super.message);
+}
+
+class NodeLookupException extends CakeException {
+ const NodeLookupException(super.message);
+}
+
+class BadChainIdException extends CakeException {
+ const BadChainIdException(super.message);
+}
+
+class MessageSignException extends CakeException {
+ const MessageSignException(super.message);
+}
+
+class HardwareWalletNotConnectedException extends CakeException {
+ const HardwareWalletNotConnectedException(super.message);
+}
+
+class HardwareWalletResponseException extends CakeException {
+ const HardwareWalletResponseException(super.message);
+}
\ No newline at end of file
### cw_core/lib/get_height_by_date.dart
@@ -1,13 +1,13 @@
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/utils/proxy_wrapper.dart';
-import 'package:cw_core/utils/print_verbose.dart';
import 'package:intl/intl.dart';
import 'package:cw_core/get_height_by_date_xmr.dart';
import 'dart:convert';
// FIXME: Hardcoded values; Works only for monero
int getMoneroHeigthByDate({required DateTime date}) =>
- MoneroHeight.getBlockHeightByTime(date..subtract(Duration(days: 1)));
+ MoneroHeight.getBlockHeightByTime(date.subtract(const Duration(days: 1)));
const havenDates = {
"2023-05": 1352995,
@@ -96,7 +96,7 @@ Future<int> getHavenCurrentHeight() async {
final info = jsonDecode(stringResponse);
return info['data']['height'] as int;
} else {
- throw Exception('Failed to load current blockchain height');
+ throw ServerResponseException('Failed to load current blockchain height');
}
}
### cw_core/lib/get_height_by_date_zec.dart
@@ -1,343 +1,364 @@
class ZcashHeight {
- // for i in $(seq 1 331); do echo "_Checkpoint($(date -j -f "%Y-%m-%d %H:%M:%S" "$(curl -s "https://mainnet.zcashexplorer.app/blocks/${i}0000" | grep -oE '[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}')" "+%s"), ${i}0000),"; done > points.txt
+ // for i in $(seq 1 350); do echo "_Checkpoint($(curl -s "https://api.blockchair.com/zcash/raw/block/${i}0000" | grep -oE '"time":[0-9]+' | head -1 | cut -d: -f2), ${i}0000),"; sleep 1; done > points.txt
static final List<_Checkpoint> _points = [
- _Checkpoint(1479114667, 10000),
- _Checkpoint(1480618460, 20000),
- _Checkpoint(1482129143, 30000),
- _Checkpoint(1483635610, 40000),
- _Checkpoint(1485145514, 50000),
- _Checkpoint(1486655742, 60000),
- _Checkpoint(1488163642, 70000),
- _Checkpoint(1489668244, 80000),
- _Checkpoint(1491175107, 90000),
- _Checkpoint(1492681094, 100000),
- _Checkpoint(1494185626, 110000),
- _Checkpoint(1495691260, 120000),
- _Checkpoint(1497196465, 130000),
- _Checkpoint(1498702428, 140000),
- _Checkpoint(1500209116, 150000),
- _Checkpoint(1501716823, 160000),
- _Checkpoint(1503222893, 170000),
- _Checkpoint(1504730866, 180000),
- _Checkpoint(1506236963, 190000),
- _Checkpoint(1507744233, 200000),
- _Checkpoint(1509254578, 210000),
- _Checkpoint(1510768449, 220000),
- _Checkpoint(1512275502, 230000),
- _Checkpoint(1513783951, 240000),
- _Checkpoint(1515292290, 250000),
- _Checkpoint(1516799219, 260000),
- _Checkpoint(1518306180, 270000),
- _Checkpoint(1519813817, 280000),
- _Checkpoint(1521319150, 290000),
- _Checkpoint(1522828107, 300000),
- _Checkpoint(1524336223, 310000),
- _Checkpoint(1525844954, 320000),
- _Checkpoint(1527354342, 330000),
- _Checkpoint(1528860301, 340000),
- _Checkpoint(1530365206, 350000),
- _Checkpoint(1531873693, 360000),
- _Checkpoint(1533380392, 370000),
- _Checkpoint(1534888873, 380000),
- _Checkpoint(1536393381, 390000),
- _Checkpoint(1537899117, 400000),
- _Checkpoint(1539406330, 410000),
- _Checkpoint(1540912214, 420000),
- _Checkpoint(1542422891, 430000),
- _Checkpoint(1543931111, 440000),
- _Checkpoint(1545437758, 450000),
- _Checkpoint(1546945529, 460000),
- _Checkpoint(1548450107, 470000),
- _Checkpoint(1549957767, 480000),
- _Checkpoint(1551466960, 490000),
- _Checkpoint(1552969806, 500000),
- _Checkpoint(1554477648, 510000),
- _Checkpoint(1555981451, 520000),
- _Checkpoint(1557489241, 530000),
- _Checkpoint(1558997282, 540000),
- _Checkpoint(1560503840, 550000),
- _Checkpoint(1562011717, 560000),
- _Checkpoint(1563518091, 570000),
- _Checkpoint(1565027136, 580000),
- _Checkpoint(1566532760, 590000),
- _Checkpoint(1568039395, 600000),
- _Checkpoint(1569547911, 610000),
- _Checkpoint(1571051853, 620000),
- _Checkpoint(1572559831, 630000),
- _Checkpoint(1574069743, 640000),
- _Checkpoint(1575576895, 650000),
- _Checkpoint(1576603014, 660000),
- _Checkpoint(1577356346, 670000),
- _Checkpoint(1578109375, 680000),
- _Checkpoint(1578863180, 690000),
- _Checkpoint(1579616443, 700000),
- _Checkpoint(1580369806, 710000),
- _Checkpoint(1581122786, 720000),
- _Checkpoint(1581876634, 730000),
- _Checkpoint(1582630471, 740000),
- _Checkpoint(1583383678, 750000),
- _Checkpoint(1584133944, 760000),
- _Checkpoint(1584887940, 770000),
- _Checkpoint(1585641057, 780000),
- _Checkpoint(1586395543, 790000),
- _Checkpoint(1587148500, 800000),
- _Checkpoint(1587901493, 810000),
- _Checkpoint(1588655183, 820000),
- _Checkpoint(1589408476, 830000),
- _Checkpoint(1590163464, 840000),
- _Checkpoint(1590916379, 850000),
- _Checkpoint(1591669786, 860000),
- _Checkpoint(1592423887, 870000),
- _Checkpoint(1593176771, 880000),
- _Checkpoint(1593930930, 890000),
- _Checkpoint(1594684380, 900000),
- _Checkpoint(1595439209, 910000),
- _Checkpoint(1596192463, 920000),
- _Checkpoint(1596946009, 930000),
- _Checkpoint(1597700256, 940000),
- _Checkpoint(1598453538, 950000),
- _Checkpoint(1599207483, 960000),
- _Checkpoint(1599960598, 970000),
- _Checkpoint(1600714563, 980000),
- _Checkpoint(1601467884, 990000),
- _Checkpoint(1602220941, 1000000),
- _Checkpoint(1602974722, 1010000),
- _Checkpoint(1603728848, 1020000),
- _Checkpoint(1604485637, 1030000),
- _Checkpoint(1605238381, 1040000),
- _Checkpoint(1605992807, 1050000),
- _Checkpoint(1606747750, 1060000),
- _Checkpoint(1607500606, 1070000),
- _Checkpoint(1608255278, 1080000),
- _Checkpoint(1609008684, 1090000),
- _Checkpoint(1609763782, 1100000),
- _Checkpoint(1610517871, 1110000),
- _Checkpoint(1611271575, 1120000),
- _Checkpoint(1612025546, 1130000),
- _Checkpoint(1612779940, 1140000),
- _Checkpoint(1613533993, 1150000),
- _Checkpoint(1614287669, 1160000),
- _Checkpoint(1615042297, 1170000),
- _Checkpoint(1615792993, 1180000),
- _Checkpoint(1616546145, 1190000),
- _Checkpoint(1617299867, 1200000),
- _Checkpoint(1618054038, 1210000),
- _Checkpoint(1618808513, 1220000),
- _Checkpoint(1619563243, 1230000),
- _Checkpoint(1620318159, 1240000),
- _Checkpoint(1621071298, 1250000),
- _Checkpoint(1621826156, 1260000),
- _Checkpoint(1622580237, 1270000),
- _Checkpoint(1623335553, 1280000),
- _Checkpoint(1624090141, 1290000),
- _Checkpoint(1624844712, 1300000),
- _Checkpoint(1625597720, 1310000),
- _Checkpoint(1626351652, 1320000),
- _Checkpoint(1627106054, 1330000),
- _Checkpoint(1627860648, 1340000),
- _Checkpoint(1628614015, 1350000),
- _Checkpoint(1629368398, 1360000),
- _Checkpoint(1630122679, 1370000),
- _Checkpoint(1630877190, 1380000),
- _Checkpoint(1631631884, 1390000),
- _Checkpoint(1632385851, 1400000),
- _Checkpoint(1633141006, 1410000),
- _Checkpoint(1633895592, 1420000),
- _Checkpoint(1634649550, 1430000),
- _Checkpoint(1635403121, 1440000),
- _Checkpoint(1636157669, 1450000),
- _Checkpoint(1636915133, 1460000),
- _Checkpoint(1637670036, 1470000),
- _Checkpoint(1638424121, 1480000),
- _Checkpoint(1639177413, 1490000),
- _Checkpoint(1639931234, 1500000),
- _Checkpoint(1640684476, 1510000),
- _Checkpoint(1641438827, 1520000),
- _Checkpoint(1642192402, 1530000),
- _Checkpoint(1642946383, 1540000),
- _Checkpoint(1643700901, 1550000),
- _Checkpoint(1644455522, 1560000),
- _Checkpoint(1645208504, 1570000),
- _Checkpoint(1645962081, 1580000),
- _Checkpoint(1646715150, 1590000),
- _Checkpoint(1647465727, 1600000),
- _Checkpoint(1648219045, 1610000),
- _Checkpoint(1648973131, 1620000),
- _Checkpoint(1649727422, 1630000),
- _Checkpoint(1650481408, 1640000),
- _Checkpoint(1651234287, 1650000),
- _Checkpoint(1651989865, 1660000),
- _Checkpoint(1652743327, 1670000),
- _Checkpoint(1653497455, 1680000),
- _Checkpoint(1654252094, 1690000),
- _Checkpoint(1655005944, 1700000),
- _Checkpoint(1655759708, 1710000),
- _Checkpoint(1656513765, 1720000),
- _Checkpoint(1657268358, 1730000),
- _Checkpoint(1658022453, 1740000),
- _Checkpoint(1658777019, 1750000),
- _Checkpoint(1659531133, 1760000),
- _Checkpoint(1660283907, 1770000),
- _Checkpoint(1661037645, 1780000),
- _Checkpoint(1661791977, 1790000),
- _Checkpoint(1662544394, 1800000),
- _Checkpoint(1663298018, 1810000),
- _Checkpoint(1664051450, 1820000),
- _Checkpoint(1664805547, 1830000),
- _Checkpoint(1665558994, 1840000),
- _Checkpoint(1666312456, 1850000),
- _Checkpoint(1667066473, 1860000),
- _Checkpoint(1667823393, 1870000),
- _Checkpoint(1668576623, 1880000),
- _Checkpoint(1669330657, 1890000),
- _Checkpoint(1670084156, 1900000),
- _Checkpoint(1670837831, 1910000),
- _Checkpoint(1671591094, 1920000),
- _Checkpoint(1672343975, 1930000),
- _Checkpoint(1673097703, 1940000),
- _Checkpoint(1673852016, 1950000),
- _Checkpoint(1674605810, 1960000),
- _Checkpoint(1675360050, 1970000),
- _Checkpoint(1676113710, 1980000),
- _Checkpoint(1676867174, 1990000),
- _Checkpoint(1677620242, 2000000),
- _Checkpoint(1678374852, 2010000),
- _Checkpoint(1679125063, 2020000),
- _Checkpoint(1679878121, 2030000),
- _Checkpoint(1680632254, 2040000),
- _Checkpoint(1681386518, 2050000),
- _Checkpoint(1682140381, 2060000),
- _Checkpoint(1682894564, 2070000),
- _Checkpoint(1683648178, 2080000),
- _Checkpoint(1684401932, 2090000),
- _Checkpoint(1685156464, 2100000),
- _Checkpoint(1685910040, 2110000),
- _Checkpoint(1686663406, 2120000),
- _Checkpoint(1687417875, 2130000),
- _Checkpoint(1688172069, 2140000),
- _Checkpoint(1688925610, 2150000),
- _Checkpoint(1689679500, 2160000),
- _Checkpoint(1690432691, 2170000),
- _Checkpoint(1691186349, 2180000),
- _Checkpoint(1691940901, 2190000),
- _Checkpoint(1692694780, 2200000),
- _Checkpoint(1693449743, 2210000),
- _Checkpoint(1694203665, 2220000),
- _Checkpoint(1694957643, 2230000),
- _Checkpoint(1695710712, 2240000),
- _Checkpoint(1696465787, 2250000),
- _Checkpoint(1697218701, 2260000),
- _Checkpoint(1697973031, 2270000),
- _Checkpoint(1698726864, 2280000),
- _Checkpoint(1699483348, 2290000),
- _Checkpoint(1700237650, 2300000),
- _Checkpoint(1700991210, 2310000),
- _Checkpoint(1701745742, 2320000),
- _Checkpoint(1702500723, 2330000),
- _Checkpoint(1703253121, 2340000),
- _Checkpoint(1704007238, 2350000),
- _Checkpoint(1704760935, 2360000),
- _Checkpoint(1705514669, 2370000),
- _Checkpoint(1706268087, 2380000),
- _Checkpoint(1707021423, 2390000),
- _Checkpoint(1707776257, 2400000),
- _Checkpoint(1708529542, 2410000),
- _Checkpoint(1709283065, 2420000),
- _Checkpoint(1710037165, 2430000),
- _Checkpoint(1710787780, 2440000),
- _Checkpoint(1711541488, 2450000),
- _Checkpoint(1712294996, 2460000),
- _Checkpoint(1713048843, 2470000),
- _Checkpoint(1713803486, 2480000),
- _Checkpoint(1714557127, 2490000),
- _Checkpoint(1715311181, 2500000),
- _Checkpoint(1716064271, 2510000),
- _Checkpoint(1716818792, 2520000),
- _Checkpoint(1717572765, 2530000),
- _Checkpoint(1718326333, 2540000),
- _Checkpoint(1719080275, 2550000),
- _Checkpoint(1719834297, 2560000),
- _Checkpoint(1720588042, 2570000),
- _Checkpoint(1721341832, 2580000),
- _Checkpoint(1722095122, 2590000),
- _Checkpoint(1722848604, 2600000),
- _Checkpoint(1723602357, 2610000),
- _Checkpoint(1724355843, 2620000),
- _Checkpoint(1725110085, 2630000),
- _Checkpoint(1725863681, 2640000),
- _Checkpoint(1726616892, 2650000),
- _Checkpoint(1727371443, 2660000),
- _Checkpoint(1728124893, 2670000),
- _Checkpoint(1728878141, 2680000),
- _Checkpoint(1729631572, 2690000),
- _Checkpoint(1730385888, 2700000),
- _Checkpoint(1731142437, 2710000),
- _Checkpoint(1731896266, 2720000),
- _Checkpoint(1732650193, 2730000),
- _Checkpoint(1733403626, 2740000),
- _Checkpoint(1734157390, 2750000),
- _Checkpoint(1734911442, 2760000),
- _Checkpoint(1735665720, 2770000),
- _Checkpoint(1736419845, 2780000),
- _Checkpoint(1737173511, 2790000),
- _Checkpoint(1737926795, 2800000),
- _Checkpoint(1738681511, 2810000),
- _Checkpoint(1739434236, 2820000),
- _Checkpoint(1740188214, 2830000),
- _Checkpoint(1740941352, 2840000),
- _Checkpoint(1741692338, 2850000),
- _Checkpoint(1742445247, 2860000),
- _Checkpoint(1743198927, 2870000),
- _Checkpoint(1743952947, 2880000),
- _Checkpoint(1744706370, 2890000),
- _Checkpoint(1745461377, 2900000),
- _Checkpoint(1746214735, 2910000),
- _Checkpoint(1746967908, 2920000),
- _Checkpoint(1747722271, 2930000),
- _Checkpoint(1748474582, 2940000),
- _Checkpoint(1749228582, 2950000),
- _Checkpoint(1749983372, 2960000),
- _Checkpoint(1750737278, 2970000),
- _Checkpoint(1751490762, 2980000),
- _Checkpoint(1752243931, 2990000),
- _Checkpoint(1752997873, 3000000),
- _Checkpoint(1753751756, 3010000),
- _Checkpoint(1754504935, 3020000),
- _Checkpoint(1755259449, 3030000),
- _Checkpoint(1756012904, 3040000),
- _Checkpoint(1756765335, 3050000),
- _Checkpoint(1757519206, 3060000),
- _Checkpoint(1758272484, 3070000),
- _Checkpoint(1759025597, 3080000),
- _Checkpoint(1759778957, 3090000),
- _Checkpoint(1760532780, 3100000),
- _Checkpoint(1761286210, 3110000),
- _Checkpoint(1762039783, 3120000),
- _Checkpoint(1762796627, 3130000),
- _Checkpoint(1763550532, 3140000),
- _Checkpoint(1764303860, 3150000),
- _Checkpoint(1765057381, 3160000),
- _Checkpoint(1765811222, 3170000),
- _Checkpoint(1766564356, 3180000),
- _Checkpoint(1767318326, 3190000),
- _Checkpoint(1768071956, 3200000),
- _Checkpoint(1768824957, 3210000),
- _Checkpoint(1769578781, 3220000),
- _Checkpoint(1770332206, 3230000),
- _Checkpoint(1771086265, 3240000),
- _Checkpoint(1771840180, 3250000),
- _Checkpoint(1772592783, 3260000),
- _Checkpoint(1773343947, 3270000),
- _Checkpoint(1774097085, 3280000),
- _Checkpoint(1774850161, 3290000),
- _Checkpoint(1775603525, 3300000),
- _Checkpoint(1776358117, 3310000),
+ _Checkpoint(1479096667, 10000),
+ _Checkpoint(1480600460, 20000),
+ _Checkpoint(1482111143, 30000),
+ _Checkpoint(1483617610, 40000),
+ _Checkpoint(1485127514, 50000),
+ _Checkpoint(1486637742, 60000),
+ _Checkpoint(1488145642, 70000),
+ _Checkpoint(1489653844, 80000),
+ _Checkpoint(1491160707, 90000),
+ _Checkpoint(1492666694, 100000),
+ _Checkpoint(1494171226, 110000),
+ _Checkpoint(1495676860, 120000),
+ _Checkpoint(1497182065, 130000),
+ _Checkpoint(1498688028, 140000),
+ _Checkpoint(1500194716, 150000),
+ _Checkpoint(1501702423, 160000),
+ _Checkpoint(1503208493, 170000),
+ _Checkpoint(1504716466, 180000),
+ _Checkpoint(1506222563, 190000),
+ _Checkpoint(1507729833, 200000),
+ _Checkpoint(1509240178, 210000),
+ _Checkpoint(1510750449, 220000),
+ _Checkpoint(1512257502, 230000),
+ _Checkpoint(1513765951, 240000),
+ _Checkpoint(1515274290, 250000),
+ _Checkpoint(1516781219, 260000),
+ _Checkpoint(1518288180, 270000),
+ _Checkpoint(1519795817, 280000),
+ _Checkpoint(1521304750, 290000),
+ _Checkpoint(1522813707, 300000),
+ _Checkpoint(1524321823, 310000),
+ _Checkpoint(1525830554, 320000),
+ _Checkpoint(1527339942, 330000),
+ _Checkpoint(1528845901, 340000),
+ _Checkpoint(1530350806, 350000),
+ _Checkpoint(1531859293, 360000),
+ _Checkpoint(1533365992, 370000),
+ _Checkpoint(1534874473, 380000),
+ _Checkpoint(1536378981, 390000),
+ _Checkpoint(1537884717, 400000),
+ _Checkpoint(1539391930, 410000),
+ _Checkpoint(1540897814, 420000),
+ _Checkpoint(1542404891, 430000),
+ _Checkpoint(1543913111, 440000),
+ _Checkpoint(1545419758, 450000),
+ _Checkpoint(1546927529, 460000),
+ _Checkpoint(1548432107, 470000),
+ _Checkpoint(1549939767, 480000),
+ _Checkpoint(1551448960, 490000),
+ _Checkpoint(1552955406, 500000),
+ _Checkpoint(1554463248, 510000),
+ _Checkpoint(1555967051, 520000),
+ _Checkpoint(1557474841, 530000),
+ _Checkpoint(1558982882, 540000),
+ _Checkpoint(1560489440, 550000),
+ _Checkpoint(1561997317, 560000),
+ _Checkpoint(1563503691, 570000),
+ _Checkpoint(1565012736, 580000),
+ _Checkpoint(1566518360, 590000),
+ _Checkpoint(1568024995, 600000),
+ _Checkpoint(1569533511, 610000),
+ _Checkpoint(1571037453, 620000),
+ _Checkpoint(1572545431, 630000),
+ _Checkpoint(1574051743, 640000),
+ _Checkpoint(1575558895, 650000),
+ _Checkpoint(1576585014, 660000),
+ _Checkpoint(1577338346, 670000),
+ _Checkpoint(1578091375, 680000),
+ _Checkpoint(1578845180, 690000),
+ _Checkpoint(1579598443, 700000),
+ _Checkpoint(1580351806, 710000),
+ _Checkpoint(1581104786, 720000),
+ _Checkpoint(1581858634, 730000),
+ _Checkpoint(1582612471, 740000),
+ _Checkpoint(1583365678, 750000),
+ _Checkpoint(1584119544, 760000),
+ _Checkpoint(1584873540, 770000),
+ _Checkpoint(1585626657, 780000),
+ _Checkpoint(1586381143, 790000),
+ _Checkpoint(1587134100, 800000),
+ _Checkpoint(1587887093, 810000),
+ _Checkpoint(1588640783, 820000),
+ _Checkpoint(1589394076, 830000),
+ _Checkpoint(1590149064, 840000),
+ _Checkpoint(1590901979, 850000),
+ _Checkpoint(1591655386, 860000),
+ _Checkpoint(1592409487, 870000),
+ _Checkpoint(1593162371, 880000),
+ _Checkpoint(1593916530, 890000),
+ _Checkpoint(1594669980, 900000),
+ _Checkpoint(1595424809, 910000),
+ _Checkpoint(1596178063, 920000),
+ _Checkpoint(1596931609, 930000),
+ _Checkpoint(1597685856, 940000),
+ _Checkpoint(1598439138, 950000),
+ _Checkpoint(1599193083, 960000),
+ _Checkpoint(1599946198, 970000),
+ _Checkpoint(1600700163, 980000),
+ _Checkpoint(1601453484, 990000),
+ _Checkpoint(1602206541, 1000000),
+ _Checkpoint(1602960322, 1010000),
+ _Checkpoint(1603714448, 1020000),
+ _Checkpoint(1604467637, 1030000),
+ _Checkpoint(1605220381, 1040000),
+ _Checkpoint(1605974807, 1050000),
+ _Checkpoint(1606729750, 1060000),
+ _Checkpoint(1607482606, 1070000),
+ _Checkpoint(1608237278, 1080000),
+ _Checkpoint(1608990684, 1090000),
+ _Checkpoint(1609745782, 1100000),
+ _Checkpoint(1610499871, 1110000),
+ _Checkpoint(1611253575, 1120000),
+ _Checkpoint(1612007546, 1130000),
+ _Checkpoint(1612761940, 1140000),
+ _Checkpoint(1613515993, 1150000),
+ _Checkpoint(1614269669, 1160000),
+ _Checkpoint(1615024297, 1170000),
+ _Checkpoint(1615778593, 1180000),
+ _Checkpoint(1616531745, 1190000),
+ _Checkpoint(1617285467, 1200000),
+ _Checkpoint(1618039638, 1210000),
+ _Checkpoint(1618794113, 1220000),
+ _Checkpoint(1619548843, 1230000),
+ _Checkpoint(1620303759, 1240000),
+ _Checkpoint(1621056898, 1250000),
+ _Checkpoint(1621811756, 1260000),
+ _Checkpoint(1622565837, 1270000),
+ _Checkpoint(1623321153, 1280000),
+ _Checkpoint(1624075741, 1290000),
+ _Checkpoint(1624830312, 1300000),
+ _Checkpoint(1625583320, 1310000),
+ _Checkpoint(1626337252, 1320000),
+ _Checkpoint(1627091654, 1330000),
+ _Checkpoint(1627846248, 1340000),
+ _Checkpoint(1628599615, 1350000),
+ _Checkpoint(1629353998, 1360000),
+ _Checkpoint(1630108279, 1370000),
+ _Checkpoint(1630862790, 1380000),
+ _Checkpoint(1631617484, 1390000),
+ _Checkpoint(1632371451, 1400000),
+ _Checkpoint(1633126606, 1410000),
+ _Checkpoint(1633881192, 1420000),
+ _Checkpoint(1634635150, 1430000),
+ _Checkpoint(1635388721, 1440000),
+ _Checkpoint(1636143269, 1450000),
+ _Checkpoint(1636897133, 1460000),
+ _Checkpoint(1637652036, 1470000),
+ _Checkpoint(1638406121, 1480000),
+ _Checkpoint(1639159413, 1490000),
+ _Checkpoint(1639913234, 1500000),
+ _Checkpoint(1640666476, 1510000),
+ _Checkpoint(1641420827, 1520000),
+ _Checkpoint(1642174402, 1530000),
+ _Checkpoint(1642928383, 1540000),
+ _Checkpoint(1643682901, 1550000),
+ _Checkpoint(1644437522, 1560000),
+ _Checkpoint(1645190504, 1570000),
+ _Checkpoint(1645944081, 1580000),
+ _Checkpoint(1646697150, 1590000),
+ _Checkpoint(1647451327, 1600000),
+ _Checkpoint(1648204645, 1610000),
+ _Checkpoint(1648958731, 1620000),
+ _Checkpoint(1649713022, 1630000),
+ _Checkpoint(1650467008, 1640000),
+ _Checkpoint(1651219887, 1650000),
+ _Checkpoint(1651975465, 1660000),
+ _Checkpoint(1652728927, 1670000),
+ _Checkpoint(1653483055, 1680000),
+ _Checkpoint(1654237694, 1690000),
+ _Checkpoint(1654991544, 1700000),
+ _Checkpoint(1655745308, 1710000),
+ _Checkpoint(1656499365, 1720000),
+ _Checkpoint(1657253958, 1730000),
+ _Checkpoint(1658008053, 1740000),
+ _Checkpoint(1658762619, 1750000),
+ _Checkpoint(1659516733, 1760000),
+ _Checkpoint(1660269507, 1770000),
+ _Checkpoint(1661023245, 1780000),
+ _Checkpoint(1661777577, 1790000),
+ _Checkpoint(1662529994, 1800000),
+ _Checkpoint(1663283618, 1810000),
+ _Checkpoint(1664037050, 1820000),
+ _Checkpoint(1664791147, 1830000),
+ _Checkpoint(1665544594, 1840000),
+ _Checkpoint(1666298056, 1850000),
+ _Checkpoint(1667052073, 1860000),
+ _Checkpoint(1667805393, 1870000),
+ _Checkpoint(1668558623, 1880000),
+ _Checkpoint(1669312657, 1890000),
+ _Checkpoint(1670066156, 1900000),
+ _Checkpoint(1670819831, 1910000),
+ _Checkpoint(1671573094, 1920000),
+ _Checkpoint(1672325975, 1930000),
+ _Checkpoint(1673079703, 1940000),
+ _Checkpoint(1673834016, 1950000),
+ _Checkpoint(1674587810, 1960000),
+ _Checkpoint(1675342050, 1970000),
+ _Checkpoint(1676095710, 1980000),
+ _Checkpoint(1676849174, 1990000),
+ _Checkpoint(1677602242, 2000000),
+ _Checkpoint(1678356852, 2010000),
+ _Checkpoint(1679110663, 2020000),
+ _Checkpoint(1679863721, 2030000),
+ _Checkpoint(1680617854, 2040000),
+ _Checkpoint(1681372118, 2050000),
+ _Checkpoint(1682125981, 2060000),
+ _Checkpoint(1682880164, 2070000),
+ _Checkpoint(1683633778, 2080000),
+ _Checkpoint(1684387532, 2090000),
+ _Checkpoint(1685142064, 2100000),
+ _Checkpoint(1685895640, 2110000),
+ _Checkpoint(1686649006, 2120000),
+ _Checkpoint(1687403475, 2130000),
+ _Checkpoint(1688157669, 2140000),
+ _Checkpoint(1688911210, 2150000),
+ _Checkpoint(1689665100, 2160000),
+ _Checkpoint(1690418291, 2170000),
+ _Checkpoint(1691171949, 2180000),
+ _Checkpoint(1691926501, 2190000),
+ _Checkpoint(1692680380, 2200000),
+ _Checkpoint(1693435343, 2210000),
+ _Checkpoint(1694189265, 2220000),
+ _Checkpoint(1694943243, 2230000),
+ _Checkpoint(1695696312, 2240000),
+ _Checkpoint(1696451387, 2250000),
+ _Checkpoint(1697204301, 2260000),
+ _Checkpoint(1697958631, 2270000),
+ _Checkpoint(1698712464, 2280000),
+ _Checkpoint(1699465348, 2290000),
+ _Checkpoint(1700219650, 2300000),
+ _Checkpoint(1700973210, 2310000),
+ _Checkpoint(1701727742, 2320000),
+ _Checkpoint(1702482723, 2330000),
+ _Checkpoint(1703235121, 2340000),
+ _Checkpoint(1703989238, 2350000),
+ _Checkpoint(1704742935, 2360000),
+ _Checkpoint(1705496669, 2370000),
+ _Checkpoint(1706250087, 2380000),
+ _Checkpoint(1707003423, 2390000),
+ _Checkpoint(1707758257, 2400000),
+ _Checkpoint(1708511542, 2410000),
+ _Checkpoint(1709265065, 2420000),
+ _Checkpoint(1710019165, 2430000),
+ _Checkpoint(1710773380, 2440000),
+ _Checkpoint(1711527088, 2450000),
+ _Checkpoint(1712280596, 2460000),
+ _Checkpoint(1713034443, 2470000),
+ _Checkpoint(1713789086, 2480000),
+ _Checkpoint(1714542727, 2490000),
+ _Checkpoint(1715296781, 2500000),
+ _Checkpoint(1716049871, 2510000),
+ _Checkpoint(1716804392, 2520000),
+ _Checkpoint(1717558365, 2530000),
+ _Checkpoint(1718311933, 2540000),
+ _Checkpoint(1719065875, 2550000),
+ _Checkpoint(1719819897, 2560000),
+ _Checkpoint(1720573642, 2570000),
+ _Checkpoint(1721327432, 2580000),
+ _Checkpoint(1722080722, 2590000),
+ _Checkpoint(1722834204, 2600000),
+ _Checkpoint(1723587957, 2610000),
+ _Checkpoint(1724341443, 2620000),
+ _Checkpoint(1725095685, 2630000),
+ _Checkpoint(1725849281, 2640000),
+ _Checkpoint(1726602492, 2650000),
+ _Checkpoint(1727357043, 2660000),
+ _Checkpoint(1728110493, 2670000),
+ _Checkpoint(1728863741, 2680000),
+ _Checkpoint(1729617172, 2690000),
+ _Checkpoint(1730371488, 2700000),
+ _Checkpoint(1731124437, 2710000),
+ _Checkpoint(1731878266, 2720000),
+ _Checkpoint(1732632193, 2730000),
+ _Checkpoint(1733385626, 2740000),
+ _Checkpoint(1734139390, 2750000),
+ _Checkpoint(1734893442, 2760000),
+ _Checkpoint(1735647720, 2770000),
+ _Checkpoint(1736401845, 2780000),
+ _Checkpoint(1737155511, 2790000),
+ _Checkpoint(1737908795, 2800000),
+ _Checkpoint(1738663511, 2810000),
+ _Checkpoint(1739416236, 2820000),
+ _Checkpoint(1740170214, 2830000),
+ _Checkpoint(1740923352, 2840000),
+ _Checkpoint(1741677938, 2850000),
+ _Checkpoint(1742430847, 2860000),
+ _Checkpoint(1743184527, 2870000),
+ _Checkpoint(1743938547, 2880000),
+ _Checkpoint(1744691970, 2890000),
+ _Checkpoint(1745446977, 2900000),
+ _Checkpoint(1746200335, 2910000),
+ _Checkpoint(1746953508, 2920000),
+ _Checkpoint(1747707871, 2930000),
+ _Checkpoint(1748460182, 2940000),
+ _Checkpoint(1749214182, 2950000),
+ _Checkpoint(1749968972, 2960000),
+ _Checkpoint(1750722878, 2970000),
+ _Checkpoint(1751476362, 2980000),
+ _Checkpoint(1752229531, 2990000),
+ _Checkpoint(1752983473, 3000000),
+ _Checkpoint(1753737356, 3010000),
+ _Checkpoint(1754490535, 3020000),
+ _Checkpoint(1755245049, 3030000),
+ _Checkpoint(1755998504, 3040000),
+ _Checkpoint(1756750935, 3050000),
+ _Checkpoint(1757504806, 3060000),
+ _Checkpoint(1758258084, 3070000),
+ _Checkpoint(1759011197, 3080000),
+ _Checkpoint(1759764557, 3090000),
+ _Checkpoint(1760518380, 3100000),
+ _Checkpoint(1761271810, 3110000),
+ _Checkpoint(1762025383, 3120000),
+ _Checkpoint(1762778627, 3130000),
+ _Checkpoint(1763532532, 3140000),
+ _Checkpoint(1764285860, 3150000),
+ _Checkpoint(1765039381, 3160000),
+ _Checkpoint(1765793222, 3170000),
+ _Checkpoint(1766546356, 3180000),
+ _Checkpoint(1767300326, 3190000),
+ _Checkpoint(1768053956, 3200000),
+ _Checkpoint(1768806957, 3210000),
+ _Checkpoint(1769560781, 3220000),
+ _Checkpoint(1770314206, 3230000),
+ _Checkpoint(1771068265, 3240000),
+ _Checkpoint(1771822180, 3250000),
+ _Checkpoint(1772574783, 3260000),
+ _Checkpoint(1773329547, 3270000),
+ _Checkpoint(1774082685, 3280000),
+ _Checkpoint(1774835761, 3290000),
+ _Checkpoint(1775589125, 3300000),
+ _Checkpoint(1776343717, 3310000),
+ _Checkpoint(1777097332, 3320000),
+ _Checkpoint(1777851068, 3330000),
+ _Checkpoint(1778604451, 3340000),
+ _Checkpoint(1779359129, 3350000),
+ _Checkpoint(1780112204, 3360000),
+ _Checkpoint(1780866005, 3370000),
+ _Checkpoint(1781619712, 3380000),
+ _Checkpoint(1782372852, 3390000),
+ _Checkpoint(1783127340, 3400000),
+ _Checkpoint(1783880610, 3410000),
+ _Checkpoint(1784633685, 3420000),
+ _Checkpoint(1785388067, 3430000),
+ _Checkpoint(1786141366, 3440000),
+ _Checkpoint(1786894060, 3450000),
+ _Checkpoint(1787649147, 3460000),
+ _Checkpoint(1788402205, 3470000),
+ _Checkpoint(1789155008, 3480000),
+ _Checkpoint(1789909130, 3490000),
+ _Checkpoint(1790662825, 3500000),
];
static int getBlockHeightByTime(DateTime time) {
final t = time.toUtc().millisecondsSinceEpoch;
- if (_points.isEmpty) return 0;
+ if (_points.isEmpty) {
+ return 0;
+ }
if (t <= _points.first.timeMs) {
return 1;
@@ -369,7 +390,10 @@ class ZcashHeight {
}
static DateTime getTimeByBlockHeight(int height) {
- if (_points.isEmpty) return DateTime.fromMillisecondsSinceEpoch(0, isUtc: true);
+ if (_points.isEmpty) {
+ return DateTime.fromMillisecondsSinceEpoch(0, isUtc: true);
+ }
+
if (height <= 1) {
return DateTime.fromMillisecondsSinceEpoch(_points.first.timeMs, isUtc: true);
}
@@ -409,8 +433,8 @@ class ZcashHeight {
}
class _Checkpoint {
+ _Checkpoint(int timeSec, this.height) : timeMs = timeSec * 1000;
+
final int timeMs;
final int height;
-
- _Checkpoint(int timeSec, this.height) : timeMs = timeSec * 1000;
}
### cw_core/lib/hardware/device_connection_type.dart
@@ -1,13 +1,15 @@
-import 'package:cw_core/wallet_info.dart';
-import 'package:cw_core/wallet_type.dart';
+import "package:cw_core/wallet_info.dart";
+import "package:cw_core/wallet_type.dart";
enum DeviceConnectionType {
usb,
ble;
static List<DeviceConnectionType> supportedConnectionTypes(
- WalletType walletType, HardwareWalletType hardwareType,
- [bool isIOS = false]) {
+ WalletType walletType,
+ HardwareWalletType hardwareType, {
+ bool isIOS = false,
+ }) {
bool isSupported = false;
switch (hardwareType) {
case HardwareWalletType.bitbox:
@@ -25,6 +27,7 @@ enum DeviceConnectionType {
WalletType.litecoin,
WalletType.ethereum,
WalletType.polygon,
+ WalletType.zcash,
].contains(walletType);
break;
case HardwareWalletType.trezor:
@@ -54,9 +57,9 @@ enum DeviceConnectionType {
String get iconString {
switch (this) {
case ble:
- return 'assets/images/bluetooth.png';
+ return "assets/images/bluetooth.png";
case usb:
- return 'assets/images/usb.png';
+ return "assets/images/usb.png";
}
}
}
### cw_core/lib/key.dart
@@ -1,35 +1,8 @@
import 'package:encrypt/encrypt.dart' as encrypt;
-const ivEncodedStringLength = 12;
-
String generateKey() {
final key = encrypt.Key.fromSecureRandom(512);
final iv = encrypt.IV.fromSecureRandom(8);
return key.base64 + iv.base64;
}
-
-List<String> extractKeys(String key) {
- final _key = key.substring(0, key.length - ivEncodedStringLength);
- final iv = key.substring(key.length - ivEncodedStringLength);
-
- return [_key, iv];
-}
-
-Future<String> encode(
- {required encrypt.Key key, required encrypt.IV iv, required String data}) async {
- final encrypter = encrypt.Encrypter(encrypt.Salsa20(key));
- final encrypted = encrypter.encrypt(data, iv: iv);
-
- return encrypted.base64;
-}
-
-Future<String> decode({required String password, required String data}) async {
- final keys = extractKeys(password);
- final key = encrypt.Key.fromBase64(keys.first);
- final iv = encrypt.IV.fromBase64(keys.last);
- final encrypter = encrypt.Encrypter(encrypt.Salsa20(key));
- final encrypted = encrypter.decrypt64(data, iv: iv);
-
- return encrypted;
-}
### cw_core/lib/keychain_read_status_native.dart
@@ -0,0 +1,16 @@
+import "dart:io";
+
+import "package:flutter/services.dart";
+
+Future<int?> keychainReadStatusNative(String key) async {
+ if (!Platform.isIOS) {
+ return null;
+ }
+
+ try {
+ const utils = MethodChannel("com.cake_wallet/native_utils");
+ return await utils.invokeMethod<int>("keychain_read_status", {"key": key});
+ } catch (_) {
+ return null;
+ }
+}
### cw_core/lib/lnurl.dart
@@ -3,11 +3,16 @@ import "dart:convert";
import "package:bech32/bech32.dart";
import "package:cw_core/amount/money.dart";
import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/exceptions/cake_exception.dart";
import "package:cw_core/utils/proxy_wrapper.dart";
const _BOLT_PREFIXES = ["lnbcrt", "lntbs", "lnbc", "lntb"];
const _LUD17_PREFIXES = ["lnurlw", "lnurlc", "lnurlp", "keyauth"];
+class Bech32EncodeException extends CakeException {
+ const Bech32EncodeException(super.message);
+}
+
bool isBolt11ZeroInvoice(String invoice) {
try {
final request =
@@ -80,7 +85,8 @@ Money? getBolt11Amount(String invoice) {
class LNURL {
static Future<Money?> getPayRequestAmount(String lnurl) async {
final url = decode(lnurl);
- final response = await ProxyWrapper().get(clearnetUri: url);
+ final response =
+ await ProxyWrapper().get(clearnetUri: url).timeout(const Duration(seconds: 10));
if (response.statusCode != 200) {
return null;
@@ -258,10 +264,10 @@ List<int> _convert(List<int> data, int inBits, int outBits, bool pad) {
}
} else {
if (bits >= inBits) {
- throw Exception("[BECH32] Excess padding");
+ throw Bech32EncodeException("Excess padding");
}
if ((value << (outBits - bits)) & maxV > 0) {
- throw Exception("[BECH32] Non-zero padding");
+ throw Bech32EncodeException("Non-zero padding");
}
}
### cw_core/lib/monero_transaction_priority.dart
@@ -1,3 +1,4 @@
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/transaction_priority.dart';
import 'package:flutter/foundation.dart';
@@ -32,7 +33,7 @@ class MoneroTransactionPriority extends TransactionPriority {
return fastest;
default:
if (kDebugMode) {
- throw Exception('Unexpected token: $raw for MoneroTransactionPriority deserialize');
+ throw DeserializeException('Unexpected token: $raw for MoneroTransactionPriority deserialize');
}
return medium;
}
### cw_core/lib/node.dart
@@ -3,6 +3,7 @@ import 'dart:io';
import 'dart:math' as math;
import 'package:blockchain_utils/hex/hex.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/node_list.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/utils/proxy_socket/abstract.dart';
@@ -292,6 +293,7 @@ class Node {
case WalletType.polygon:
case WalletType.base:
case WalletType.bsc:
+ case WalletType.robinhood:
case WalletType.arbitrum:
case WalletType.solana:
case WalletType.tron:
@@ -300,7 +302,7 @@ class Node {
return Uri.parse(
"http${isSSL ? "s" : ""}://$uriRaw${path!.startsWith("/") || path!.isEmpty ? path : "/$path"}");
case WalletType.none:
- throw Exception('Unexpected type ${type.toString()} for Node uri');
+ throw BadWalletTypeException('Unexpected type ${type.toString()} for Node uri', type);
}
}
@@ -353,6 +355,7 @@ class Node {
case WalletType.base:
case WalletType.arbitrum:
case WalletType.bsc:
+ case WalletType.robinhood:
case WalletType.solana:
case WalletType.tron:
case WalletType.dogecoin:
@@ -513,7 +516,7 @@ class Node {
data["error"] != null ||
data["balance"] == null ||
data["receivable"] == null) {
- throw Exception(
+ throw ServerResponseException(
"Error while trying to get balance! ${data["error"] != null ? data["error"] : ""}");
}
return true;
@@ -661,7 +664,7 @@ class DaemonRpc {
if (initialResponse.statusCode != 401 ||
!initialResponse.headers.containsKey('www-authenticate')) {
- throw Exception('Unexpected response: ${initialResponse.body}');
+ throw ServerResponseException('Unexpected response: ${initialResponse.body}');
}
// Extract Digest details from `WWW-Authenticate` header.
@@ -688,13 +691,13 @@ class DaemonRpc {
);
if (authenticatedResponse.statusCode != 200) {
- throw Exception('RPC call failed: ${authenticatedResponse.body}');
+ throw ServerResponseException('RPC call failed: ${authenticatedResponse.body}');
}
final Map<String, dynamic> result =
jsonDecode(authenticatedResponse.body) as Map<String, dynamic>;
if (result['error'] != null) {
- throw Exception('RPC Error: ${result['error']}');
+ throw ServerResponseException('RPC Error: ${result['error']}');
}
return result['result'] as Map<String, dynamic>;
### cw_core/lib/node_legacy.dart
@@ -183,6 +183,7 @@ class Node extends HiveObject with Keyable {
case WalletType.polygon:
case WalletType.base:
case WalletType.bsc:
+ case WalletType.robinhood:
case WalletType.arbitrum:
case WalletType.solana:
case WalletType.tron:
### cw_core/lib/node_list.dart
@@ -61,6 +61,9 @@ Future<List<Node>> loadDefaultNodes(WalletType type) async {
case WalletType.bsc:
path = 'assets/bsc_node_list.yml';
break;
+ case WalletType.robinhood:
+ path = "assets/robinhood_node_list.yml";
+ break;
case WalletType.banano:
case WalletType.none:
path = '';
@@ -126,6 +129,7 @@ Future<List<Node>> loadAllDefaultNodes() async {
final arbitrumNodes = await loadDefaultNodes(WalletType.arbitrum);
final zcashNodes = await loadDefaultNodes(WalletType.zcash);
final bscNodes = await loadDefaultNodes(WalletType.bsc);
+ final robinhoodNodes = await loadDefaultNodes(WalletType.robinhood);
return moneroNodes +
bitcoinElectrumServerList +
@@ -143,7 +147,8 @@ Future<List<Node>> loadAllDefaultNodes() async {
baseNodes +
arbitrumNodes +
zcashNodes +
- bscNodes;
+ bscNodes +
+ robinhoodNodes;
}
Future<void> resetToDefault() async {
### cw_core/lib/pathForWallet.dart
@@ -1,4 +1,5 @@
import 'dart:io';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/root_dir.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:path/path.dart' as p;
@@ -47,11 +48,11 @@ Future<void> copyWalletFilesTo({
final typeRoot = await pathForWalletTypeDir(type: type);
final sourceDir = Directory(p.join(typeRoot, fromName));
if (!sourceDir.existsSync()) {
- throw "Source wallet not found: $fromName $type";
+ throw WalletNotFoundException(name: fromName, type: type);
}
if (Directory(p.join(typeRoot, toName)).existsSync()) {
- throw Exception('Cannot rename wallet: "$toName" already exists');
+ throw WalletExistsException('Cannot rename wallet: "$toName" already exists');
}
final destinationDir = Directory(p.join(typeRoot, toName));
### cw_core/lib/receive_page_option.dart
@@ -3,8 +3,6 @@ import 'package:cw_core/enumerate.dart';
class ReceivePageOption implements Enumerate {
static const mainnet = ReceivePageOption._('mainnet');
static const testnet = ReceivePageOption._('testnet');
- static const anonPayInvoice = ReceivePageOption._('anonPayInvoice');
- static const anonPayDonationLink = ReceivePageOption._('anonPayDonationLink');
const ReceivePageOption._(this.value,
{this.iconPath, this.description, this.isCommon = false, this.addAddressWord = false});
@@ -22,7 +20,4 @@ class ReceivePageOption implements Enumerate {
const ReceivePageOptions = [
ReceivePageOption.mainnet,
- // FIXME anonpay disabed for new ui beta. restore after screens are ready
- // ReceivePageOption.anonPayInvoice,
- // ReceivePageOption.anonPayDonationLink
];
### cw_core/lib/spl_token.dart
@@ -197,4 +197,7 @@ class SPLToken extends CryptoCurrency {
@override
int get hashCode => mintAddress.hashCode;
+
+ @override
+ String get apiString => "sol.$mintAddress";
}
### cw_core/lib/transaction_direction.dart
@@ -1,3 +1,5 @@
+import "package:cw_core/exceptions/cake_exception.dart";
+
enum TransactionDirection { incoming, outgoing }
TransactionDirection parseTransactionDirectionFromInt(int raw) {
@@ -7,8 +9,7 @@ TransactionDirection parseTransactionDirectionFromInt(int raw) {
case 1:
return TransactionDirection.outgoing;
default:
- throw Exception(
- 'Unexpected token: raw for TransactionDirection parseTransactionDirectionFromInt');
+ throw DeserializeException('Unexpected token: raw for TransactionDirection parseTransactionDirectionFromInt');
}
}
@@ -19,7 +20,6 @@ TransactionDirection parseTransactionDirectionFromNumber(String raw) {
case "1":
return TransactionDirection.outgoing;
default:
- throw Exception(
- 'Unexpected token: raw for TransactionDirection parseTransactionDirectionFromNumber');
+ throw DeserializeException('Unexpected token: raw for TransactionDirection parseTransactionDirectionFromNumber');
}
}
### cw_core/lib/tron_token.dart
@@ -175,4 +175,7 @@ class TronToken extends CryptoCurrency {
@override
int get hashCode => contractAddress.hashCode;
+
+ @override
+ String get apiString => "trx.$contractAddress";
}
### cw_core/lib/utils/bip39_seed.dart
@@ -0,0 +1,11 @@
+import "dart:convert";
+import "dart:typed_data";
+
+import "package:blockchain_utils/blockchain_utils.dart";
+
+Uint8List bip39MnemonicToSeed(String mnemonic, {String passphrase = ""}) =>
+ Uint8List.fromList(QuickCrypto.pbkdf2DeriveKey(
+ password: Uint8List.fromList(mnemonic.codeUnits),
+ salt: utf8.encode("mnemonic$passphrase"),
+ iterations: 2048,
+ ));
### cw_core/lib/utils/file.dart
@@ -1,21 +1,84 @@
+import 'dart:convert';
import 'dart:io';
-import 'package:cw_core/key.dart';
+import 'dart:typed_data';
+
+import 'package:cake_backup/backup.dart' as cwb;
import 'package:encrypt/encrypt.dart' as encrypt;
-Future<void> write({required String path, required String password, required String data}) async =>
- writeData(path: path, password: password, data: data);
+const _ivEncodedStringLength = 12;
-Future<void> writeData(
- {required String path, required String password, required String data}) async {
- final keys = extractKeys(password);
- final key = encrypt.Key.fromBase64(keys.first);
- final iv = encrypt.IV.fromBase64(keys.last);
- final encrypted = await encode(key: key, iv: iv, data: data);
- final f = File(path);
- f.writeAsStringSync(encrypted);
+Future<void> write({
+ required String path,
+ required String password,
+ required String data,
+ bool? highEntropyPassphrase,
+}) async {
+ await _writeXChaCha20(
+ path: path,
+ password: password,
+ data: data,
+ highEntropyPassphrase: highEntropyPassphrase ?? !Platform.isLinux,
+ );
}
-Future<String> read({required String path, required String password}) async {
+Future<String> read({
+ required String path,
+ required String password,
+ bool? highEntropyPassphrase,
+}) async {
+ final useHighEntropy = highEntropyPassphrase ?? !Platform.isLinux;
+ try {
+ return await _readXChaCha20(path: path, password: password);
+ } catch (e) {
+ final encrypted = await File(path).readAsBytes();
+ if (encrypted.isNotEmpty &&
+ (encrypted[0] == cwb.lowEntropyVersion || encrypted[0] == cwb.highEntropyVersion)) {
+ rethrow;
+ }
+
+ final String data;
+ try {
+ data = await _readLegacy(path: path, password: password);
+ } catch (_) {
+ throw Exception('Failed to decrypt legacy file: invalid password or corrupted data');
+ }
+ if (data.isEmpty) {
+ throw Exception('Failed to read data');
+ }
+
+ // Salsa20 is unauthenticated, so a wrong password decrypts to garbage instead of
+ // failing. Every payload written here is a JSON object with at least one key, so a
+ // correctly decrypted file always starts with '{"' and anything else is a bad
+ // password.
+ // There's 1 in 2^16 chance that this will be a false positive, but check later
+ // prevents any damage to the file caused by re-encryption.
+ if (!data.startsWith('{"')) {
+ throw Exception('Failed to decrypt legacy file: invalid password or corrupted data');
+ }
+
+ if (_isJson(data)) {
+ await _writeXChaCha20(
+ path: path,
+ password: password,
+ data: data,
+ highEntropyPassphrase: useHighEntropy,
+ );
+ }
+
+ return data;
+ }
+}
+
+bool _isJson(String data) {
+ try {
+ json.decode(data);
+ return true;
+ } catch (_) {
+ return false;
+ }
+}
+
+Future<String> _readLegacy({required String path, required String password}) async {
final file = File(path);
if (!file.existsSync()) {
@@ -24,5 +87,57 @@ Future<String> read({required String path, required String password}) async {
final encrypted = file.readAsStringSync();
- return decode(password: password, data: encrypted);
+ return _decode(password: password, data: encrypted);
+}
+
+Future<void> _writeXChaCha20({
+ required String path,
+ required String password,
+ required String data,
+ required bool highEntropyPassphrase,
+}) async {
+ final encrypted = await cwb.encrypt(
+ password,
+ Uint8List.fromList(utf8.encode(data)),
+ highEntropyPassphrase: highEntropyPassphrase,
+ );
+
+ final tmpFile = File('$path.tmp');
+ tmpFile.writeAsBytesSync(encrypted, flush: true);
+ tmpFile.renameSync(path);
+}
+
+Future<String> _readXChaCha20({
+ required String path,
+ required String password,
+}) async {
+ final encrypted = await File(path).readAsBytes();
+ final bytes = await cwb.decrypt(password, encrypted);
+ return _decodeUtf8(bytes);
+}
+
+// Linux wallets written by the old XChaCha20EncryptionFileUtils stored one byte per
+// UTF-16 code unit, so bytes above 0x7F in those files are Latin-1 rather than UTF-8.
+String _decodeUtf8(Uint8List bytes) {
+ try {
+ return utf8.decode(bytes);
+ } on FormatException {
+ return String.fromCharCodes(bytes);
+ }
+}
+
+List<String> _extractKeys(String key) {
+ final k = key.substring(0, key.length - _ivEncodedStringLength);
+ final iv = key.substring(key.length - _ivEncodedStringLength);
+
+ return [k, iv];
+}
+
+Future<String> _decode({required String password, required String data}) async {
+ final keys = _extractKeys(password);
+ final key = encrypt.Key.fromBase64(keys.first);
+ final iv = encrypt.IV.fromBase64(keys.last);
+ final encrypter = encrypt.Encrypter(encrypt.Salsa20(key));
+
+ return encrypter.decrypt64(data, iv: iv);
}
### cw_core/lib/utils/proxy_socket/abstract.dart
@@ -16,28 +16,68 @@ class ProxyAddress {
}
abstract class ProxySocket {
+ // [connectionTimeout] only covers DNS + TCP; these bound the whole connect, including the SOCKS
+ // and TLS handshakes, which otherwise can wait forever. Tor needs time to build a circuit.
+ static const clearnetConnectDeadline = Duration(seconds: 20);
+ static const torConnectDeadline = Duration(seconds: 60);
+
static Future<ProxySocket> connect(bool sslEnabled, ProxyAddress address,
- {Duration? connectionTimeout}) async {
+ {Duration? connectionTimeout}) {
if (CakeTor.instance!.started) {
- var socksSocket = await SOCKSSocket.create(
- proxyHost: InternetAddress.loopbackIPv4.address,
- proxyPort: CakeTor.instance!.port,
- sslEnabled: sslEnabled,
+ SOCKSSocket? socksSocket;
+ Future<ProxySocket> open() async {
+ final socket = socksSocket = await SOCKSSocket.create(
+ proxyHost: InternetAddress.loopbackIPv4.address,
+ proxyPort: CakeTor.instance!.port,
+ sslEnabled: sslEnabled,
+ );
+ try {
+ await socket.connect();
+ await socket.connectTo(address.host, address.port);
+ } catch (_) {
+ // On a failure reply the library leaves its connection to Tor open.
+ unawaited(socket.close().catchError((_) {}));
+ rethrow;
+ }
+ return ProxySocketSocks(socket);
+ }
+
+ // Closing the SOCKS socket also fails a handshake that is still waiting on Tor.
+ return _withDeadline(
+ open(),
+ torConnectDeadline,
+ onTimeout: () => unawaited(socksSocket?.close().catchError((_) {})),
);
- await socksSocket.connect();
- await socksSocket.connectTo(address.host, address.port);
- return ProxySocketSocks(socksSocket);
}
if (sslEnabled == false) {
- return ProxySocketInsecure(
- await Socket.connect(address.host, address.port, timeout: connectionTimeout));
+ return _withDeadline(
+ Socket.connect(address.host, address.port, timeout: connectionTimeout)
+ .then(ProxySocketInsecure.new),
+ clearnetConnectDeadline,
+ );
} else {
- return ProxySocketSecure(await SecureSocket.connect(
- address.host,
- address.port,
- timeout: connectionTimeout,
- onBadCertificate: (_) => true,
- ));
+ return _withDeadline(
+ SecureSocket.connect(
+ address.host,
+ address.port,
+ timeout: connectionTimeout,
+ onBadCertificate: (_) => true,
+ ).then(ProxySocketSecure.new),
+ clearnetConnectDeadline,
+ );
+ }
+ }
+
+ /// Fails with a [TimeoutException] once [deadline] passes; a socket that still connects after
+ /// that is destroyed instead of leaking.
+ static Future<ProxySocket> _withDeadline(Future<ProxySocket> pending, Duration deadline,
+ {void Function()? onTimeout}) async {
+ try {
+ return await pending.timeout(deadline);
+ } on TimeoutException {
+ onTimeout?.call();
+ unawaited(pending.then((socket) => socket.destroy(), onError: (_) {}));
+ rethrow;
}
}
### cw_core/lib/utils/proxy_wrapper.dart
@@ -2,6 +2,7 @@ import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/utils/proxy_logger/abstract.dart';
import 'package:cw_core/utils/proxy_socket/abstract.dart';
import 'package:cw_core/utils/tor/abstract.dart';
@@ -213,7 +214,7 @@ class ProxyWrapper {
}
}
- throw Exception("Unable to connect to server");
+ throw ConnectionException("Unable to connect to server");
}
Future<Response> post({
@@ -223,6 +224,7 @@ class ProxyWrapper {
Uri? onionUri,
String? body,
bool allowMitmMoneroBypassSSLCheck = false,
+ bool preferIPv6 = false,
}) async {
HttpClient? torHttpClient;
HttpClient cleatnetHttpClient = HttpClient();
@@ -276,6 +278,23 @@ class ProxyWrapper {
}
if (clearnetUri != null) {
+ if (preferIPv6) {
+ final ipv6Client = ioc.IOClient(_ipv6OnlyHttpClient());
+ try {
+ return await _make(
+ method: RequestMethod.post,
+ client: ipv6Client,
+ uri: clearnetUri,
+ headers: headers,
+ body: body,
+ ).timeout(const Duration(seconds: 10));
+ } catch (_) {
+ // No working IPv6 route: fall back to the request below, which Dart sends over IPv4
+ } finally {
+ ipv6Client.close();
+ }
+ }
+
try {
return HttpOverrides.runZoned(
() async {
@@ -293,9 +312,27 @@ class ProxyWrapper {
}
}
- throw Exception("Unable to connect to server");
+ throw ConnectionException("Unable to connect to server");
}
+ /// [HttpClient] that only connects over native IPv6. It fails at once on networks without IPv6,
+ /// and after [HttpClient.connectionTimeout] (which covers the TLS handshake) when IPv6 is broken.
+ HttpClient _ipv6OnlyHttpClient() => HttpClient()
+ ..connectionTimeout = const Duration(seconds: 3)
+ ..connectionFactory = (uri, proxyHost, proxyPort) async {
+ final addresses = (await InternetAddress.lookup(uri.host, type: InternetAddressType.IPv6)
+ .timeout(const Duration(seconds: 2)))
+ // Apple platforms answer with ::ffff:a.b.c.d on IPv4-only networks, which would silently
+ // connect over IPv4.
+ .where((address) => !address.address.startsWith("::ffff:"));
+ if (addresses.isEmpty) {
+ throw SocketException("No IPv6 address for ${uri.host}");
+ }
+ return uri.isScheme("https")
+ ? SecureSocket.startConnect(addresses.first, uri.port)
+ : Socket.startConnect(addresses.first, uri.port);
+ };
+
Future<Response> put({
Map<String, String>? headers,
int? portOverride,
@@ -360,7 +397,7 @@ class ProxyWrapper {
}
}
- throw Exception("Unable to connect to server");
+ throw ConnectionException("Unable to connect to server");
}
Future<Response> delete({
@@ -432,7 +469,7 @@ class ProxyWrapper {
}
}
- throw Exception("Unable to connect to server");
+ throw ConnectionException("Unable to connect to server");
}
}
### cw_core/lib/wallet_addresses.dart
@@ -71,12 +71,13 @@ abstract class WalletAddresses {
Future<void> saveAddressesInBox() async {
try {
walletInfo.address = address;
- // TODO: check if it will affect the performance of each wallet
- await walletInfo.setAddresses(addressesMap);
- await walletInfo.setAddressInfos(addressInfos);
- await walletInfo.setUsedAddresses(usedAddresses.toList());
- await walletInfo.setHiddenAddresses(hiddenAddresses.toList());
- await walletInfo.setManualAddresses(manualAddresses.toList());
+ await walletInfo.setAddressesInBatch(
+ addresses: addressesMap,
+ addressInfos: addressInfos,
+ usedAddresses: usedAddresses.toList(),
+ hiddenAddresses: hiddenAddresses.toList(),
+ manualAddresses: manualAddresses.toList(),
+ );
await walletInfo.save();
} catch (e) {
### cw_core/lib/wallet_base.dart
@@ -142,6 +142,11 @@ abstract class WalletBase<BalanceType extends Balance, HistoryType extends Trans
bool get hasLightningSupport => false;
bool get hasSilentPaymentsScanning => false;
+ bool get hasCoinControl => false;
+ bool get hasAccountsSupport => false;
+ bool get hasNativeAccounts => false;
+ bool get canToggleMultiAccounts => hasAccountsSupport && !hasNativeAccounts;
+
// hardware wallet - bitbox, ledger, trezor.
// we also have airgap wallets but those can't sign messages
bool get canSignMessages => walletInfo.hardwareWalletType == null || walletInfo.isHardwareWallet;
### cw_core/lib/wallet_info.dart
@@ -90,15 +90,33 @@ class WalletInfoAddressInfo {
required String address,
required String label,
}) async {
- return await db!.insert(tableName, {
- "walletInfoId": walletInfoId,
- "mapKey": mapKey,
- "mapValueAccountIndex": accountIndex,
- "mapValueAddress": address,
- "mapValueLabel": label,
- });
+ return await db!.insert(
+ tableName,
+ row(
+ walletInfoId: walletInfoId,
+ mapKey: mapKey,
+ accountIndex: accountIndex,
+ address: address,
+ label: label,
+ ),
+ );
}
+ static Map<String, Object> row({
+ required int walletInfoId,
+ required int mapKey,
+ required int accountIndex,
+ required String address,
+ required String label,
+ }) =>
+ {
+ "walletInfoId": walletInfoId,
+ "mapKey": mapKey,
+ "mapValueAccountIndex": accountIndex,
+ "mapValueAddress": address,
+ "mapValueLabel": label,
+ };
+
Map<String, dynamic> toJson() {
return {
selfIdColumn: id,
@@ -149,13 +167,15 @@ class WalletInfoAddressMap {
}
static Future<int> insert(int walletInfoId, String addressKey, String addressValue) async {
- return await db!.insert(tableName, {
- "walletInfoId": walletInfoId,
- "addressKey": addressKey,
- "addressValue": addressValue,
- });
+ return await db!.insert(tableName, row(walletInfoId, addressKey, addressValue));
}
+ static Map<String, Object> row(int walletInfoId, String addressKey, String addressValue) => {
+ "walletInfoId": walletInfoId,
+ "addressKey": addressKey,
+ "addressValue": addressValue,
+ };
+
Map<String, dynamic> toJson() {
return {
selfIdColumn: id,
@@ -218,13 +238,15 @@ class WalletInfoAddress {
if (select.isNotEmpty) {
return select[0][selfIdColumn] as int;
}
- return await db!.insert(tableName, {
- "walletInfoId": walletInfoId,
- "type": type.index,
- "address": address,
- });
+ return await db!.insert(tableName, row(walletInfoId, type, address));
}
+ static Map<String, Object> row(int walletInfoId, WalletInfoAddressType type, String address) => {
+ "walletInfoId": walletInfoId,
+ "type": type.index,
+ "address": address,
+ };
+
Map<String, dynamic> toJson() {
return {
selfIdColumn: id,
@@ -244,6 +266,68 @@ class WalletInfoAddress {
}
}
+class WalletInfoAccount {
+ WalletInfoAccount({
+ required this.walletInfoId,
+ required this.accountIndex,
+ required this.label,
+ });
+
+ factory WalletInfoAccount.fromJson(Map<String, dynamic> json) => WalletInfoAccount(
+ walletInfoId: json["walletInfoId"] as int,
+ accountIndex: json["accountIndex"] as int,
+ label: json["label"] as String,
+ );
+
+ int walletInfoId;
+ int accountIndex;
+ String label;
+
+ static String get tableName => "walletInfoAccount";
+
+ static Future<List<WalletInfoAccount>> selectList(int walletInfoId) async {
+ final query = await db!.query(
+ tableName,
+ where: "walletInfoId = ?",
+ whereArgs: [walletInfoId],
+ orderBy: "accountIndex ASC",
+ );
+
+ return List.generate(query.length, (index) => WalletInfoAccount.fromJson(query[index]));
+ }
+
+ static Future<int> deleteByWalletInfoId(int walletInfoId) async =>
+ await db!.delete(tableName, where: "walletInfoId = ?", whereArgs: [walletInfoId]);
+
+ static Future<int> insertOrUpdate({
+ required int walletInfoId,
+ required int accountIndex,
+ required String label,
+ }) async =>
+ await db!.transaction((txn) async {
+ final updated = await txn.update(
+ tableName,
+ {"label": label},
+ where: "walletInfoId = ? AND accountIndex = ?",
+ whereArgs: [walletInfoId, accountIndex],
+ );
+
+ if (updated > 0) return updated;
+
+ return await txn.insert(tableName, {
+ "walletInfoId": walletInfoId,
+ "accountIndex": accountIndex,
+ "label": label,
+ });
+ });
+
+ Map<String, dynamic> toJson() => {
+ "walletInfoId": walletInfoId,
+ "accountIndex": accountIndex,
+ "label": label,
+ };
+}
+
class DerivationInfo {
DerivationInfo({
this.id = 0,
@@ -346,58 +430,73 @@ class WalletInfo {
this.hashedWalletIdentifier,
this.isNonSeedWallet,
this.sortOrder,
+ this.currentAccountIndex,
this.addressPageType,
this.receiveInfoboxDismissed,
this.showCombinedBalance,
- this.favoriteTokenAddress)
+ this.favoriteTokenAddress,
+ this.showSeedBackupReminder)
: _yatLastUsedAddressController = StreamController<String>.broadcast();
- factory WalletInfo.external(
- {required String id,
- required String name,
- required WalletType type,
- required bool isRecovery,
- required int restoreHeight,
- required DateTime date,
- required String dirPath,
- required String path,
- required String address,
- bool? showIntroCakePayCard,
- String yatEid = '',
- String yatLastUsedAddressRaw = '',
- int? derivationInfoId,
- HardwareWalletType? hardwareWalletType,
- String? parentAddress,
- String? hashedWalletIdentifier,
- bool? isNonSeedWallet,
- int? sortOrder,
- bool? receiveInfoboxDismissed,
- bool? showCombinedBalance,
- String? favoriteTokenAddress}) {
- return WalletInfo(
- 0,
- id,
- name,
- type,
- isRecovery,
- restoreHeight,
- date.millisecondsSinceEpoch,
- dirPath,
- path,
- address,
- yatEid,
- yatLastUsedAddressRaw,
- showIntroCakePayCard,
- derivationInfoId ?? -1,
- hardwareWalletType,
- parentAddress,
- hashedWalletIdentifier,
- isNonSeedWallet ?? false,
- sortOrder ?? 0,
- null,
- receiveInfoboxDismissed ?? false,
- showCombinedBalance ?? true,
- favoriteTokenAddress);
+ factory WalletInfo.external({
+ required String id,
+ required String name,
+ required WalletType type,
+ required bool isRecovery,
+ required int restoreHeight,
+ required DateTime date,
+ required String dirPath,
+ required String path,
+ required String address,
+ bool? showIntroCakePayCard,
+ String yatEid = "",
+ String yatLastUsedAddressRaw = "",
+ int? derivationInfoId,
+ HardwareWalletType? hardwareWalletType,
+ String? parentAddress,
+ String? hashedWalletIdentifier,
+ bool? isNonSeedWallet,
+ int? sortOrder,
+ int currentAccountIndex = 0,
+ bool? receiveInfoboxDismissed,
+ bool? showCombinedBalance,
+ String? favoriteTokenAddress,
+ }) {
+ final wi = WalletInfo(
+ 0,
+ id,
+ name,
+ type,
+ isRecovery,
+ restoreHeight,
+ date.millisecondsSinceEpoch,
+ dirPath,
+ path,
+ address,
+ yatEid.isNotEmpty ? yatEid : null,
+ yatLastUsedAddressRaw.isNotEmpty ? yatLastUsedAddressRaw : null,
+ showIntroCakePayCard ?? false,
+ derivationInfoId ?? -1,
+ hardwareWalletType,
+ parentAddress,
+ hashedWalletIdentifier,
+ isNonSeedWallet ?? false,
+ sortOrder ?? 0,
+ currentAccountIndex,
+ null,
+ receiveInfoboxDismissed ?? false,
+ showCombinedBalance ?? true,
+ favoriteTokenAddress?.isNotEmpty == true ? favoriteTokenAddress : null,
+ false,
+ );
+
+ if (type == WalletType.bitcoin) {
+ wi.isMultiAccountsEnabled = false;
+ } else if (type == WalletType.monero || type == WalletType.wownero) {
+ wi.isMultiAccountsEnabled = true;
+ }
+
+ return wi;
}
static String get tableName => 'walletInfo';
@@ -406,6 +505,8 @@ class WalletInfo {
int internalId;
+ int currentAccountIndex;
+
String id;
String name;
WalletType type;
@@ -418,20 +519,73 @@ class WalletInfo {
bool receiveInfoboxDismissed;
bool showCombinedBalance;
String? favoriteTokenAddress;
+ bool showSeedBackupReminder;
Future<Map<String, String>> getAddresses() async {
final list = await WalletInfoAddressMap.selectList(internalId);
return Map.fromEntries(list.map((e) => MapEntry(e.addressKey, e.addressValue)));
}
- Future<void> setAddresses(Map<String, String> addresses) async {
- await WalletInfoAddressMap.deleteByWalletInfoId(internalId);
- final entries = addresses.entries.toList();
- for (final entry in entries) {
- await WalletInfoAddressMap.insert(internalId, entry.key, entry.value);
+ Future<void> setAddresses(Map<String, String> addresses) =>
+ _commitBatch((batch) => _batchAddresses(batch, addresses));
+
+ Future<void> _commitBatch(void Function(Batch batch) fill) async {
+ final batch = db!.batch();
+ fill(batch);
+ await batch.commit(noResult: true);
+ }
+
+ void _batchAddresses(Batch batch, Map<String, String> addresses) {
+ batch.delete(WalletInfoAddressMap.tableName,
+ where: 'walletInfoId = ?', whereArgs: [internalId]);
+ for (final entry in addresses.entries.toList()) {
+ batch.insert(
+ WalletInfoAddressMap.tableName, WalletInfoAddressMap.row(internalId, entry.key, entry.value));
+ }
+ }
+
+ void _batchAddressInfos(Batch batch, Map<int, List<WalletInfoAddressInfo>> addressInfos) {
+ batch.delete(WalletInfoAddressInfo.tableName,
+ where: 'walletInfoId = ?', whereArgs: [internalId]);
+ for (final addressInfo in addressInfos.entries.toList()) {
+ for (final info in addressInfo.value.toList()) {
+ batch.insert(
+ WalletInfoAddressInfo.tableName,
+ WalletInfoAddressInfo.row(
+ walletInfoId: internalId,
+ mapKey: addressInfo.key,
+ accountIndex: info.accountIndex,
+ address: info.address,
+ label: info.label,
+ ),
+ );
+ }
}
}
+ void _batchAddressesOfType(Batch batch, WalletInfoAddressType type, List<String> addresses) {
+ batch.delete(WalletInfoAddress.tableName,
+ where: 'walletInfoId = ? AND type = ?', whereArgs: [internalId, type.index]);
+ for (final address in addresses.toSet()) {
+ batch.insert(WalletInfoAddress.tableName, WalletInfoAddress.row(internalId, type, address));
+ }
+ }
+
+ Future<void> setAddressesInBatch({
+ required Map<String, String> addresses,
+ required Map<int, List<WalletInfoAddressInfo>> addressInfos,
+ required List<String> usedAddresses,
+ required List<String> hiddenAddresses,
+ required List<String> manualAddresses,
+ }) =>
+ _commitBatch((batch) {
+ _batchAddresses(batch, addresses);
+ _batchAddressInfos(batch, addressInfos);
+ _batchAddressesOfType(batch, WalletInfoAddressType.used, usedAddresses);
+ _batchAddressesOfType(batch, WalletInfoAddressType.hidden, hiddenAddresses);
+ _batchAddressesOfType(batch, WalletInfoAddressType.manual, manualAddresses);
+ });
+
String? yatEid;
String? yatLastUsedAddressRaw;
bool? showIntroCakePayCard;
@@ -446,65 +600,107 @@ class WalletInfo {
return ret;
}
- Future<void> setAddressInfos(Map<int, List<WalletInfoAddressInfo>> addressInfos) async {
- await WalletInfoAddressInfo.deleteByWalletInfoId(internalId);
- final entries = addressInfos.entries.toList();
- for (final addressInfo in entries) {
- final infoList = addressInfo.value.toList();
- for (final info in infoList) {
- await WalletInfoAddressInfo.insert(
- walletInfoId: internalId,
- mapKey: addressInfo.key,
- accountIndex: info.accountIndex,
- address: info.address,
- label: info.label,
- );
- }
- }
- }
+ Future<void> setAddressInfos(Map<int, List<WalletInfoAddressInfo>> addressInfos) =>
+ _commitBatch((batch) => _batchAddressInfos(batch, addressInfos));
Future<Set<String>> getUsedAddresses() async {
final list = await WalletInfoAddress.selectList(internalId, WalletInfoAddressType.used);
return list.map((e) => e.address).toSet();
}
- Future<void> setUsedAddresses(List<String> addresses) async {
- await WalletInfoAddress.deleteByType(internalId, WalletInfoAddressType.used);
- for (final address in addresses) {
- await WalletInfoAddress.insert(internalId, WalletInfoAddressType.used, address);
- }
- }
+ Future<void> setUsedAddresses(List<String> addresses) =>
+ _commitBatch((batch) => _batchAddressesOfType(batch, WalletInfoAddressType.used, addresses));
Future<Set<String>> getHiddenAddresses() async {
final list = await WalletInfoAddress.selectList(internalId, WalletInfoAddressType.hidden);
return list.map((e) => e.address).toSet();
}
- Future<void> setHiddenAddresses(List<String> addresses) async {
- await WalletInfoAddress.deleteByType(internalId, WalletInfoAddressType.hidden);
- for (final address in addresses) {
- await WalletInfoAddress.insert(internalId, WalletInfoAddressType.hidden, address);
- }
- }
+ Future<void> setHiddenAddresses(List<String> addresses) =>
+ _commitBatch((batch) => _batchAddressesOfType(batch, WalletInfoAddressType.hidden, addresses));
Future<Set<String>> getManualAddresses() async {
final list = await WalletInfoAddress.selectList(internalId, WalletInfoAddressType.manual);
return list.map((e) => e.address).toSet();
}
- Future<void> setManualAddresses(List<String> addresses) async {
- await WalletInfoAddress.deleteByType(internalId, WalletInfoAddressType.manual);
- for (final address in addresses) {
- await WalletInfoAddress.insert(internalId, WalletInfoAddressType.manual, address);
- }
- }
+ Future<void> setManualAddresses(List<String> addresses) =>
+ _commitBatch((batch) => _batchAddressesOfType(batch, WalletInfoAddressType.manual, addresses));
Future<void> addAddress(String address, WalletInfoAddressType type) async {
await WalletInfoAddress.insert(internalId, type, address);
}
+ Future<List<WalletInfoAccount>> getAccounts() async {
+ var accounts = await WalletInfoAccount.selectList(internalId);
+
+ if (accounts.isEmpty) {
+ await WalletInfoAccount.insertOrUpdate(
+ walletInfoId: internalId,
+ accountIndex: 0,
+ label: "Primary account",
+ );
+
+ accounts = await WalletInfoAccount.selectList(internalId);
+ }
+
+ if (!accounts.any((a) => a.accountIndex == currentAccountIndex)) {
+ currentAccountIndex = accounts.first.accountIndex;
+ await save();
+ }
+
+ return accounts;
+ }
+
+ Future<void> setSelectedAccount(int accountIndex) async {
+ currentAccountIndex = accountIndex;
+ await save();
+ }
+
+ Future<void> setAccounts(List<WalletInfoAccount> accounts) async {
+ await WalletInfoAccount.deleteByWalletInfoId(internalId);
+
+ for (final account in accounts) {
+ await WalletInfoAccount.insertOrUpdate(
+ walletInfoId: internalId,
+ accountIndex: account.accountIndex,
+ label: account.label,
+ );
+ }
+
+ if (accounts.isNotEmpty && !accounts.any((a) => a.accountIndex == currentAccountIndex)) {
+ currentAccountIndex = accounts.first.accountIndex;
+ await save();
+ }
+ }
+
+ Future<void> addAccount({
+ required int accountIndex,
+ required String label,
+ }) async {
+ await WalletInfoAccount.insertOrUpdate(
+ walletInfoId: internalId,
+ accountIndex: accountIndex,
+ label: label,
+ );
+ }
+
+ Future<void> renameAccount({
+ required int accountIndex,
+ required String label,
+ }) async {
+ await WalletInfoAccount.insertOrUpdate(
+ walletInfoId: internalId,
+ accountIndex: accountIndex,
+ label: label,
+ );
+ }
+
String? addressPageType;
String? network;
+ int? accountDiscoveryLimit;
+ bool? isMultiAccountsEnabled;
+
int derivationInfoId;
DerivationInfo? _derivationInfo;
@@ -583,11 +779,16 @@ class WalletInfo {
"hashedWalletIdentifier": hashedWalletIdentifier,
"isNonSeedWallet": isNonSeedWallet ? 1 : 0,
"sortOrder": sortOrder,
+ "currentAccountIndex": currentAccountIndex,
"addressPageType": addressPageType,
"receiveInfoboxDismissed": receiveInfoboxDismissed ? 1 : 0,
"showCombinedBalance": showCombinedBalance ? 1 : 0,
"favoriteTokenAddress": favoriteTokenAddress,
+ "showSeedBackupReminder": showSeedBackupReminder ? 1 : 0,
"network": network,
+ "accountDiscoveryLimit": accountDiscoveryLimit,
+ "isMultiAccountsEnabled":
+ isMultiAccountsEnabled == null ? null : (isMultiAccountsEnabled! ? 1 : 0),
};
factory WalletInfo.fromJson(Map<String, dynamic> json) {
@@ -613,11 +814,17 @@ class WalletInfo {
json['hashedWalletIdentifier'] as String?,
(json['isNonSeedWallet'] as int) == 1,
json['sortOrder'] as int? ?? 0,
+ json['currentAccountIndex'] as int? ?? 0,
json['addressPageType'] as String? ?? null,
json['receiveInfoboxDismissed'] != 0,
json["showCombinedBalance"] != 0,
- json["favoriteTokenAddress"] as String? ?? null);
+ json["favoriteTokenAddress"] as String? ?? null,
+ json["showSeedBackupReminder"] == 1);
info.network = json['network'] as String?;
+ info.accountDiscoveryLimit = json['accountDiscoveryLimit'] as int?;
+ final rawIsMultiAccountsEnabled = json['isMultiAccountsEnabled'];
+ info.isMultiAccountsEnabled =
+ rawIsMultiAccountsEnabled == null ? null : (rawIsMultiAccountsEnabled as int) == 1;
return info;
}
@@ -634,7 +841,8 @@ class WalletInfo {
}
static Future<int> delete(WalletInfo walletInfo) async {
- return await db!.delete(tableName, where: 'id = ?', whereArgs: [walletInfo.id]);
+ final deleted = await db!.delete(tableName, where: 'id = ?', whereArgs: [walletInfo.id]);
+ return deleted;
}
static Future<List<WalletInfo>> selectList(String where, List<dynamic> whereArgs,
@@ -664,4 +872,21 @@ class WalletInfo {
restoreHeight = height;
await save();
}
+
+ Future<void> setAccountDiscoveryLimit(int limit) async {
+ accountDiscoveryLimit = limit;
+ await save();
+ }
+
+ Future<void> clearSeedBackupReminder() async {
+ final previous = showSeedBackupReminder;
+ showSeedBackupReminder = false;
+
+ try {
+ await save();
+ } catch (e) {
+ showSeedBackupReminder = previous;
+ printV("Failed to save the seed backup reminder flag: $e");
+ }
+ }
}
### cw_core/lib/wallet_info_legacy.dart
@@ -248,7 +248,9 @@ class WalletInfo extends HiveObject {
id: 0,
derivationType:
derivationInfo?.derivationType ?? derivationType ?? newWi.DerivationType.unknown,
- derivationPath: derivationInfo?.derivationPath ?? derivationPath ?? '',
+ // No path stays null, not '': wallet open fills a missing path with the wallet type's
+ // default, while '' would derive from the master key itself.
+ derivationPath: derivationInfo?.derivationPath ?? derivationPath,
);
final derivationInfoId = await di.save();
final walletInfo = newWi.WalletInfo(
@@ -271,10 +273,12 @@ class WalletInfo extends HiveObject {
hashedWalletIdentifier,
isNonSeedWallet,
0,
+ 0,
addressPageType,
false,
true,
- null)
+ null,
+ false)
..network = network;
final wiId = await walletInfo.save();
for (final address in usedAddresses ?? <String>[]) {
### cw_core/lib/wallet_keys_file.dart
@@ -4,6 +4,7 @@ import 'dart:io';
import 'package:cw_core/balance.dart';
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/transaction_history.dart';
import 'package:cw_core/transaction_info.dart';
@@ -69,7 +70,7 @@ mixin WalletKeysFile<BalanceType extends Balance, HistoryType extends Transactio
var readPath = "$path.keys";
try {
- if (!File(readPath).existsSync()) throw Exception("No .keys file found for $name $type");
+ if (!File(readPath).existsSync()) throw WalletOpenException("No .keys file found for $name $type");
final jsonSource = await encryptionFileUtils.read(path: readPath, password: password);
final data = json.decode(jsonSource) as Map<String, dynamic>;
@@ -79,7 +80,7 @@ mixin WalletKeysFile<BalanceType extends Balance, HistoryType extends Transactio
readPath = "$readPath.backup";
if (!File(readPath).existsSync())
- throw Exception("No .keys nor a .keys.backup file found for $name $type");
+ throw WalletOpenException("No .keys nor a .keys.backup file found for $name $type");
final jsonSource = await encryptionFileUtils.read(path: readPath, password: password);
final data = json.decode(jsonSource) as Map<String, dynamic>;
### cw_core/lib/wallet_service.dart
@@ -1,17 +1,19 @@
import "dart:convert";
import "dart:io";
-import "package:cw_core/imported_nft.dart";
-import "package:cw_core/pathForWallet.dart";
-import "package:cw_core/spl_token.dart";
-import "package:cw_core/tron_token.dart";
-import "package:cw_core/utils/file.dart";
-import "package:cw_core/utils/print_verbose.dart";
-import "package:cw_core/wallet_base.dart";
-import "package:cw_core/wallet_credentials.dart";
-import "package:cw_core/wallet_info.dart";
-import "package:cw_core/wallet_type.dart";
-import "package:path/path.dart" as p;
+import 'package:cw_core/encryption_file_utils.dart';
+import 'package:cw_core/imported_nft.dart';
+import 'package:cw_core/pathForWallet.dart';
+import 'package:cw_core/spl_token.dart';
+import 'package:cw_core/tron_token.dart';
+import 'package:cw_core/utils/print_verbose.dart';
+import 'package:cw_core/wallet_keys_file.dart';
+import 'package:cw_core/wallet_base.dart';
+import 'package:cw_core/wallet_credentials.dart';
+import 'package:cw_core/wallet_info.dart';
+import 'package:cw_core/wallet_type.dart';
+import 'package:path/path.dart' as p;
+import "package:cw_core/exceptions/cake_exception.dart";
abstract class WalletService<N extends WalletCredentials, RFS extends WalletCredentials,
RFK extends WalletCredentials, RFH extends WalletCredentials> {
@@ -38,7 +40,7 @@ abstract class WalletService<N extends WalletCredentials, RFS extends WalletCred
final currentWalletInfo = await WalletInfo.get(currentName, getType());
if (currentWalletInfo == null) {
- throw Exception("Wallet not found");
+ throw WalletNotFoundException(name: currentName, type: getType());
}
await copyWalletFilesTo(fromName: currentName, toName: newName, type: getType());
@@ -95,8 +97,15 @@ abstract class WalletService<N extends WalletCredentials, RFS extends WalletCred
Future<String> getSeeds(String name, String password, WalletType type) async {
try {
+ final encryption = encryptionFileUtilsFor(Platform.isLinux);
+
+ if (await WalletKeysFile.hasKeysFile(name, type)) {
+ final keysData = await WalletKeysFile.readKeysFile(name, type, password, encryption);
+ return keysData.mnemonic ?? keysData.altMnemonic ?? keysData.privateKey ?? '';
+ }
+
final path = await pathForWallet(name: name, type: type);
- final jsonSource = await read(path: path, password: password);
+ final jsonSource = await encryption.read(path: path, password: password);
try {
final data = json.decode(jsonSource) as Map;
return data["mnemonic"] as String? ?? "";
### cw_core/lib/wallet_type.dart
@@ -1,4 +1,5 @@
import 'package:cw_core/crypto_currency.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/hive_type_ids.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:hive/hive.dart';
@@ -24,6 +25,7 @@ const walletTypes = [
WalletType.arbitrum,
WalletType.zcash,
WalletType.bsc,
+ WalletType.robinhood,
];
const electrumWalletTypes = [
@@ -38,7 +40,8 @@ const evmWalletTypes = [
WalletType.polygon,
WalletType.base,
WalletType.arbitrum,
- WalletType.bsc
+ WalletType.bsc,
+ WalletType.robinhood
];
// @HiveType(typeId: WALLET_TYPE_TYPE_ID)
@@ -102,6 +105,9 @@ enum WalletType {
// @HiveField(19)
bsc,
+
+ // @HiveField(20)
+ robinhood,
}
int serializeToInt(WalletType type) {
@@ -144,6 +150,8 @@ int serializeToInt(WalletType type) {
return 17;
case WalletType.bsc:
return 18;
+ case WalletType.robinhood:
+ return 19;
case WalletType.none:
return -1;
}
@@ -189,8 +197,10 @@ WalletType deserializeFromInt(int raw) {
return WalletType.zcash;
case 18:
return WalletType.bsc;
+ case 19:
+ return WalletType.robinhood;
default:
- throw Exception('Unexpected token: $raw for WalletType deserializeFromInt');
+ throw DeserializeException('Unexpected token: $raw for WalletType deserializeFromInt');
}
}
@@ -234,6 +244,8 @@ String walletTypeToString(WalletType type) {
return 'Zcash';
case WalletType.bsc:
return 'BNB Smart Chain';
+ case WalletType.robinhood:
+ return "Robinhood Chain";
case WalletType.none:
return '';
}
@@ -259,6 +271,7 @@ String walletTypeToDisplayName(WalletType type) => switch (type) {
WalletType.arbitrum => 'Arbitrum',
WalletType.zcash => 'Zcash',
WalletType.bsc => 'BNB Smart Chain',
+ WalletType.robinhood => "Robinhood Chain",
WalletType.none => ''
};
@@ -282,6 +295,7 @@ String walletTypeToDisplayTicker(WalletType type) => switch (type) {
WalletType.arbitrum => 'ARB',
WalletType.zcash => 'ZEC',
WalletType.bsc => 'BNB',
+ WalletType.robinhood => "",
WalletType.none => ''
};
@@ -327,6 +341,8 @@ WalletType? _cryptoCurrencyToWalletType(CryptoCurrency type) {
return WalletType.dogecoin;
case CryptoCurrency.zec:
return WalletType.zcash;
+ case CryptoCurrency.robEth:
+ return WalletType.robinhood;
default:
return null;
}
### cw_core/lib/wallet_type.part.dart
@@ -53,6 +53,8 @@ class WalletTypeAdapter extends TypeAdapter<WalletType> {
return WalletType.zcash;
case 19:
return WalletType.bsc;
+ case 20:
+ return WalletType.robinhood;
default:
return WalletType.monero;
}
@@ -121,6 +123,9 @@ class WalletTypeAdapter extends TypeAdapter<WalletType> {
case WalletType.bsc:
writer.writeByte(19);
break;
+ case WalletType.robinhood:
+ writer.writeByte(20);
+ break;
}
}
### cw_core/pubspec.yaml
@@ -12,18 +12,14 @@ dependencies:
flutter:
sdk: flutter
http: ^1.1.0
- file: ^7.0.0
path_provider: ^2.1.5
mobx: ^2.6.0
- flutter_mobx: ^2.3.0
intl: any
encrypt: ^5.0.1
- decimal: ^2.3.3
cake_backup:
git:
url: https://github.com/cake-tech/cake_backup.git
- ref: main
- version: 1.0.0
+ ref: b5d86a2a21e1c186cd0baa4df1f3a4f3f9413056
socks5_proxy:
git:
url: https://github.com/LacticWhale/socks_dart
### cw_core/test/amount/money_local_test.dart
@@ -23,6 +23,10 @@ void main() {
expect(_btcGrouping.toLocalStringWithPrecision(locale: "de_DE"), "1.234,5");
});
+ test("formats as English when intl has no number data for the locale (yo)", () {
+ expect(_btcGrouping.toLocalStringWithPrecision(locale: "yo"), "1,234.5");
+ });
+
test("base unit renders integer sats with grouping", () {
expect(
_btc012.toLocalStringWithPrecision(useBaseUnit: true, locale: "en_US"),
### cw_core/test/amount/money_test.dart
@@ -265,7 +265,7 @@ void main() {
test("throws Exception on division by zero", () {
expect(
() => Money(BigInt.from(5), CryptoCurrency.btc) / BigInt.zero,
- throwsA(isA<Exception>()),
+ throwsA(isA<ArgumentError>()),
);
});
### cw_core/test/amount/non_finite_amount_test.dart
@@ -0,0 +1,127 @@
+import "package:cw_core/amount/money.dart";
+import "package:cw_core/amount/money_double.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/parse_fixed.dart";
+import "package:flutter_test/flutter_test.dart";
+
+/// Every non-finite spelling that `double.tryParse` accepts.
+///
+/// These matter because a `double`-based amount guard cannot reject them:
+/// `Infinity <= 0` is false and *every* comparison against `NaN` is false, so a
+/// non-finite amount sails through an `if (amount <= 0) throw` check and then
+/// collapses to zero once it reaches Money/BigInt -- i.e. a zero-amount
+/// transaction that passed validation. The Money layer is the enforcement point
+/// for that invariant, so pin it here.
+const nonFiniteSpellings = <String>[
+ "Infinity",
+ "+Infinity",
+ "-Infinity",
+ "NaN",
+ "1e999", // overflows to Infinity as a double
+ "1E400",
+ " Infinity ",
+];
+
+void main() {
+ group("non-finite amounts", () {
+ test("double.tryParse accepts them (this is why Money must reject them)", () {
+ for (final spelling in nonFiniteSpellings) {
+ final parsed = double.tryParse(spelling);
+ expect(parsed, isNotNull, reason: "double.tryParse rejected $spelling");
+ expect(parsed!.isFinite, isFalse, reason: "$spelling parsed as finite");
+ // The point of the whole exercise: a `<= 0` guard does not stop these.
+ if (!parsed.isNegative) {
+ expect(parsed <= 0, isFalse, reason: "$spelling was caught by a <= 0 guard");
+ }
+ }
+ });
+
+ test("Money.tryParse returns null for every non-finite spelling", () {
+ for (final spelling in nonFiniteSpellings) {
+ expect(
+ Money.tryParse(spelling, CryptoCurrency.btc),
+ isNull,
+ reason: "Money.tryParse accepted $spelling",
+ );
+ expect(
+ Money.tryParse(spelling, CryptoCurrency.btc, strictParsing: false),
+ isNull,
+ reason: "Money.tryParse(strictParsing: false) accepted $spelling",
+ );
+ }
+ });
+
+ test("Money.parse throws for every non-finite spelling", () {
+ for (final spelling in nonFiniteSpellings) {
+ expect(
+ () => Money.parse(spelling, CryptoCurrency.btc),
+ throwsA(isA<FormatException>()),
+ reason: "Money.parse accepted $spelling",
+ );
+ }
+ });
+
+ test("CryptoCurrency.tryParseAmount returns null, parseAmount throws", () {
+ for (final spelling in nonFiniteSpellings) {
+ expect(CryptoCurrency.btc.tryParseAmount(spelling), isNull, reason: spelling);
+ expect(
+ () => CryptoCurrency.btc.parseAmount(spelling),
+ throwsA(isA<FormatException>()),
+ reason: spelling,
+ );
+ }
+ });
+
+ test("tryParseFixed returns null / parseFixed throws (the underlying gate)", () {
+ for (final spelling in nonFiniteSpellings) {
+ expect(tryParseFixed(spelling, 8), isNull, reason: spelling);
+ expect(
+ () => parseFixed(spelling, 8),
+ throwsA(isA<FormatException>()),
+ reason: spelling,
+ );
+ }
+ });
+
+ test("double.tryToMoney returns null for non-finite doubles", () {
+ // Relied on by ExchangeViewModel.changeReceiveAmount/changeDepositAmount, which
+ // divide by `bestRate` and can produce Infinity when the rate is still 0.
+ expect(double.infinity.tryToMoney(CryptoCurrency.btc), isNull);
+ expect(double.negativeInfinity.tryToMoney(CryptoCurrency.btc), isNull);
+ expect(double.nan.tryToMoney(CryptoCurrency.btc), isNull);
+ });
+
+ test("a rejected amount funnels to Money.zero, which is the sweep-all sentinel", () {
+ // Why the cw_monero/cw_wownero guards exist. MONERO_Wallet_createTransaction:
+ // Monero::optional<uint64_t> optAmount;
+ // if (amount != 0) { optAmount = amount; }
+ // so amount == 0 means "no amount given" and wallet2 sweeps the whole account.
+ // Output.cryptoAmountMoney falls back to Money.zero on any parse failure, and a
+ // zero Money stringifies to an all-zeros decimal -- exactly the value the native
+ // layer reads as "send everything". Nothing between them may treat 0 as an amount.
+ for (final spelling in nonFiniteSpellings) {
+ final fallback =
+ CryptoCurrency.btc.tryParseAmount(spelling) ?? Money.zero(CryptoCurrency.xmr);
+ expect(fallback.amount, BigInt.zero, reason: spelling);
+ }
+
+ final zeroXmr = Money.zero(CryptoCurrency.xmr);
+ expect(zeroXmr.amount, BigInt.zero);
+ expect(double.tryParse(zeroXmr.toString()), 0.0,
+ reason: "a zero Money must stringify to a numeric zero, i.e. the sweep-all sentinel");
+ expect(RegExp(r"^0(\.0+)?$").hasMatch(zeroXmr.toString()), isTrue,
+ reason: "unexpected zero rendering: ${zeroXmr.toString()}");
+
+ // One piconero is NOT zero -- the guards must not reject genuine dust.
+ expect(Money(BigInt.one, CryptoCurrency.xmr).sign, 1);
+ expect(double.parse(Money(BigInt.one, CryptoCurrency.xmr).toString()) > 0, isTrue);
+ });
+
+ test("finite amounts still round-trip (guard did not over-reject)", () {
+ expect(Money.tryParse("0", CryptoCurrency.btc)!.amount, BigInt.zero);
+ expect(Money.tryParse("1", CryptoCurrency.btc)!.amount, BigInt.from(100000000));
+ expect(Money.tryParse("0.00000001", CryptoCurrency.btc)!.amount, BigInt.one);
+ expect(1.5.tryToMoney(CryptoCurrency.btc)!.amount, BigInt.from(150000000));
+ });
+ });
+}
### cw_core/test/amount/utils.dart
@@ -29,6 +29,9 @@ class FiatCurrency implements Currency {
@override
String? get tag => throw UnimplementedError();
+ @override
+ String get apiString => "fiat.$symbol";
+
@override
Money parseAmount(String value) => Money.parse(value, this);
### cw_core/test/bip39_seed_test.dart
@@ -0,0 +1,329 @@
+import "package:cw_core/utils/bip39_seed.dart";
+import "package:flutter_test/flutter_test.dart";
+
+// Expected seeds come from the anicdh/bip39 fork (3633daa) the app used before this helper.
+// Non-ASCII is written as escapes so NFC/NFD and invisible characters survive editors.
+final _vectors = <(String, String, String, String)>[
+ (
+ "BIP39 reference vector 1 (abandon...about, TREZOR)",
+ "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",
+ "TREZOR",
+ "c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04",
+ ),
+ (
+ "BIP39 reference vector 2 (legal winner, TREZOR)",
+ "legal winner thank year wave sausage worth useful legal winner thank yellow",
+ "TREZOR",
+ "2e8905819b8723fe2c1d161860e5ee1830318dbf49a83bd451cfb8440c28bd6fa457fe1296106559a3c80937a1c1069be3a3a5bd381ee6260e8d9739fce1f607",
+ ),
+ (
+ "BIP39 reference vector 24 words (zoo...vote, TREZOR)",
+ "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo vote",
+ "TREZOR",
+ "dd48c104698c30cfe2b6142103248622fb7bb0ff692eebb00089b32d22484e1613912f0a5b694407be899ffd31ed3992c456cdf60f5d4564b8ba3f05a69890ad",
+ ),
+ (
+ "12 words, no passphrase",
+ "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",
+ "",
+ "5eb00bbddcf069084889a8ab9155568165f5c453ccb85e70811aaed6f6da5fc19a5ac40b389cd370d086206dec8aa6c43daea6690f20ad3d8d48b2d2ce9e38e4",
+ ),
+ (
+ "12 words",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "",
+ "4da7517731e772905678260a8643e9f9e166ade16ed3cc44e8d68edbacffc18ba0e5e42750cf02fb525b99f41d7c67559ccd937fe13b8bf279e412ffb4fcf3fd",
+ ),
+ (
+ "24 words",
+ "dance puzzle basic eternal ride alcohol best announce hint time level salute deer minimum glass kind corn athlete unusual mushroom because tomorrow game quiz",
+ "",
+ "084fb98f94346353c502d4938c3a903e0f7057564becdcc2f97ce101f07253eca9523f941eb8fc5c66f61c15b448e7d0f897ad467dfce8c9b97ea9c68dfb273a",
+ ),
+ (
+ "24 words, ascii passphrase",
+ "dance puzzle basic eternal ride alcohol best announce hint time level salute deer minimum glass kind corn athlete unusual mushroom because tomorrow game quiz",
+ "correct horse battery staple",
+ "fb56021fb17dacae79c7d4240bce48a7387114e54355957636ad09edfaafa79317c521a091c5c6c41e48f15f236db6f3ee815ffa433a195d7b985def82b6198d",
+ ),
+ (
+ "electrum seed through the bip39 function (derivation discovery)",
+ "will hedgehog multiply duck blood marble little asset eagle online clock soap",
+ "",
+ "e2a33f8be2ebb262a542a4623c4b96624ff98e3482a15b51f1186a093d26d1106f632e8a668a4cc8a7a4c9aae914e78f1316bb8bd06676892b5b22ac7687672b",
+ ),
+ (
+ "electrum seed, passphrase",
+ "will hedgehog multiply duck blood marble little asset eagle online clock soap",
+ "TREZOR",
+ "2bd74194201fd47d6be8b24353dbdac742f6c8f7a96113d514aa1480295ebb3496f293c2a222492c66cf202c42334da70b48afbf0f152bc16d9b9a749d68c249",
+ ),
+ (
+ "passphrase: printable ascii",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ " !\u0022#\u0024%&'()*+,-./0123456789:;<=>?@ABCXYZ[\u005C]^_`abcxyz{|}~",
+ "7297b44e9b1aeeeefe80f9938a1c0672568edbeb637724d2683f27fbd08150a17b096d99a1bf10a2d8a9453886a877b692be70198eab0cdfe4ecf7470a54d20f",
+ ),
+ (
+ "passphrase: leading and trailing spaces",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ " pass ",
+ "6dc4ada6bbd10d08dda6af2619a7189d48aee62459d431c6f767f3087744f9fe6f272043158af4b91376fe79b224572ef5123cfbcbf41f94ad48d27d52c593c2",
+ ),
+ (
+ "passphrase: newline and tab",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "pa\u000Ass\u0009word",
+ "70cbd66b7837ee304f7f876a22e38024eeb9a3548359421d84fa02fb50a8da6561a4c5a42943b04b91e58cf8b1cfe6d6d8209e52644c9914cd1cf23f177f8c59",
+ ),
+ (
+ "passphrase: precomposed accents (NFC, not NFKD-normalised)",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "p\u00E4ssw\u00F6rd",
+ "9feac44dbec67d0712f7a7addd5f75490bba1f6bf9d7de7723efe96835ba552309cb3ccc11d41ad912219b662f690bcaa760efb55b41cf8d86f99e466e41c2b1",
+ ),
+ (
+ "passphrase: decomposed accents (NFD)",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "pa\u0308sswo\u0308rd",
+ "9f39d98813742b332e42334137e8f5ccfb549f7e639811eba9b56d1c220c7da2008f9227f2be5492355738797b861a62d2ee7438c849745189e4bbc94bceeab2",
+ ),
+ (
+ "passphrase: german sharp s",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "stra\u00DFe",
+ "1027e4cb54dffe5d2d4dbbd106301f6af32c2af87a6657ee40f481617c48ce2a4067ff6706890cf5bb3353325fecf4c1b44625f42d7e98f501e812060330c725",
+ ),
+ (
+ "passphrase: ligature fi (not NFKD-normalised)",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "\uFB01nance",
+ "6c9b433ac0be41e6475f77a33361480d14dd52b7dc34af4ef3f38b65cc3ae69fadddaac6418611159ff0be7b1064c84afc48cb2b28328ad2729e41d5d0357731",
+ ),
+ (
+ "passphrase: fullwidth latin (not NFKD-normalised)",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "\uFF34\uFF32\uFF25\uFF3A\uFF2F\uFF32",
+ "31887488fd9d4e64d4010ee6567d6f722946960f07407fb76e53cd98a79a33bfc27aad51b1f8ac6dd85bb1b216f2f65f47c42d6ec4e33f8b6fbe7b60be6e9135",
+ ),
+ (
+ "passphrase: japanese BIP39 test passphrase (not NFKD-normalised)",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "\u334D\u30AC\u30D0\u30F4\u30A1\u3071\u3070\u3050\u309E\u3061\u3062\u5341\u4EBA\u5341\u8272",
+ "9eb067b2a3c26901a3b48a6a856cc284927a445f07f7f12441fcddd57615cba293b6f23bc0183edca6b7e3bd08a7a34a883b5510519c5de24ea9d2ff70bc9699",
+ ),
+ (
+ "passphrase: korean hangul (not NFKD-normalised)",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "\uBE44\uBC00\uBC88\uD638",
+ "7bf1bd9a4190d4fc9cb44c16d706a9e1d4b03095e05f43e439a444d2ee6c64379674ca7444550dd2a92eb41b076b47d34886fe5dcdce68824a4af7be3e147cc5",
+ ),
+ (
+ "passphrase: chinese",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "\u5BC6\u7801\u77ED\u8BED\u6D4B\u8BD5",
+ "8c5e6dd4bae7fed236efd94b6c51216bc0499b8cd91539d65ab46eb038e42b9f1f7450388e96024e3f90d23eb68e103599d9d7fdd63bfeb5d8c674f2ab287606",
+ ),
+ (
+ "passphrase: cyrillic",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "\u043F\u0430\u0440\u043E\u043B\u044C",
+ "7a56b5d58dbd6af5e4a45cc393862f33fda06dd4b20d0a94eca5415d40349356110a65cb16c22fb1784b8878f2aace061ffc86c56b903af84e7265ddb0268ba9",
+ ),
+ (
+ "passphrase: greek with tonos (not NFKD-normalised)",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "\u03BA\u03C9\u03B4\u03B9\u03BA\u03CC\u03C2",
+ "0683a8329b0a4ac5640e27d650e72db1a179d54b94fb5667c19fef8a1fb133312e144478f55754f94919244561508fb35bc806467c5f78040170463f15214295",
+ ),
+ (
+ "passphrase: arabic",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "\u0643\u0644\u0645\u0629 \u0627\u0644\u0633\u0631",
+ "0b63245ecec1407fef264875fddb0768d66ddc9b4f2f07b78ca27238c0ccce751535b830ed4ba6258fb6846a89ea6f4b502532b7532aa723963fbfccb631fc4a",
+ ),
+ (
+ "passphrase: emoji surrogate pairs",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "\uD83D\uDD11\uD83D\uDE80\uD83D\uDC8E",
+ "7ef53e74ea2791d67a0d87fd52b2d08a87de9f1bda7f8d24577beac28fdeecd4424eef144cce52c54e9d78b8652677195546e187fedb3a78c20982f1b3ed5769",
+ ),
+ (
+ "passphrase: emoji ZWJ sequence",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "\uD83D\uDC68\u200D\uD83D\uDC69\u200D\uD83D\uDC67\u200D\uD83D\uDC66",
+ "db038c57d85e8b864f02510c55758d37e4a1246fdd6663bc2ad1eee1da8957c473b0240ab283ca06c07adea56484d40c56a27c69abbb78108ea796d7121c9355",
+ ),
+ (
+ "passphrase: zero-width space",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "pass\u200Bword",
+ "79c534bbb56f7bb219eb85151d94f0ee26666ba46cb8276f4eca0e2cb02f734a3066e826fe1f3f643c46feb1b1478a3006f2d430bf5c1faf39016061311e6957",
+ ),
+ (
+ "passphrase: no-break space (not NFKD-normalised)",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "pass\u00A0word",
+ "46ae8ef85368282d6f482f06c81ee4f8b8824912848ee79b9e37e2d609a0ea6af581f6f1002358098c6e00cd2220f58724609e491f8c6447b1fcb16f5c9dad9c",
+ ),
+ (
+ "passphrase: NUL character",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "pa\u0000ss",
+ "6f2f9b3284f65048734c0ece7b81e953ba76e06413ed4644ffd5fc6319c46fa8589a186c033da9a11c415b2839f00e9a269ef29807eaa294e21c316f757c01de",
+ ),
+ (
+ "passphrase: lone surrogate",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "pa\uD800ss",
+ "dcf34b77fb5638e8f216815ff53037c9cae6ecb2314dd061646007e883361bb8be5c4a70b9dc1ec0e8b0939756cc0a8e82c589cba1c95c53ca6950ff33ff3d87",
+ ),
+ (
+ "passphrase: byte order mark",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "\uFEFFpass",
+ "25d536412299561451e536bd5eb803bf3fac90beefbf5bc6e3d33bf7b3aa6461e9ae87950f30ec6f8aca6714d74d3417a1f8079b968641bb928d3a9505e635d8",
+ ),
+ (
+ "passphrase: 1000 characters",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "x" * 1000,
+ "53fe285f6eb736f45b35c5ab62eba15c092292f40492ed8731530941de32a7b814f9362aef0867da3e7cbe7b9de8e4657450b80ffebca90c3cfda17d139c7e7c",
+ ),
+ (
+ "passphrase: 300 CJK characters",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "\u5BC6" * 300,
+ "95e58d6974f998821f3e7a2a52cf6f30dad9d5678c7ad9cf9fe1f6e968fe539561baad8fa7d4348168d6c8d7de197a843a1d89636f6104e8f2f22a4ce68be5a6",
+ ),
+ (
+ "mnemonic: uppercase",
+ "INFANT DEGREE SALMON UNFOLD MUST OIL FOCUS LEGAL IMPROVE FORGET TATTOO SNAP",
+ "",
+ "536e8c0a32b02200373423c055753ab47247282fbd79d1b2a176a8550e4af1fd3c2a59df5ad33eaca074b0bf0f39808bfa75171587e33ac2bd9d46aabc802c7d",
+ ),
+ (
+ "mnemonic: double spaces",
+ "infant degree salmon unfold must oil focus legal improve forget tattoo snap",
+ "",
+ "0dac2d137e74fc78e8fadbea8b47c3c60466554634da35c8c4fc575cb5e1bf16b361feab97cab996eef03ffab35c8b815f5d2ed79bf9ece80ecaeab8d217ef7f",
+ ),
+ (
+ "mnemonic: leading and trailing spaces",
+ " infant degree salmon unfold must oil focus legal improve forget tattoo snap ",
+ "",
+ "35d250c6dd6d0e5c381abeeed490411334a64f067ed2e5f8b752a18a5b9064eefbc787781b3b5cd3c3636206612cd29243bcf69ff74934e498074090fbcc50f0",
+ ),
+ (
+ "mnemonic: newline separated",
+ "infant\u000Adegree\u000Asalmon\u000Aunfold\u000Amust\u000Aoil\u000Afocus\u000Alegal\u000Aimprove\u000Aforget\u000Atattoo\u000Asnap",
+ "",
+ "8695b39c10a3598c91fa115a3a8071ee21088650b7fa7960f05d9a367c3a75f5427ad7f9afa6ddaf981612009633b20af6b229b2b17bcb4e2e2c3c13ad71ab33",
+ ),
+ (
+ "mnemonic: no-break space separated",
+ "infant\u00A0degree\u00A0salmon\u00A0unfold\u00A0must\u00A0oil\u00A0focus\u00A0legal\u00A0improve\u00A0forget\u00A0tattoo\u00A0snap",
+ "",
+ "99f62381c4292efb7c633114a2076532f198c863eacd372ed07318218d6e213a5d675e7d5ae3b5de46467f188381a84cf68b84bb20b4d796c4d38108fb2df0eb",
+ ),
+ (
+ "mnemonic: ideographic space separated",
+ "infant\u3000degree\u3000salmon\u3000unfold\u3000must\u3000oil\u3000focus\u3000legal\u3000improve\u3000forget\u3000tattoo\u3000snap",
+ "",
+ "fcd7eb56ddcd30d716bed06080f674fbcc3964bf72cf9d2c21f00e4ee43c5611c45a8a19b2f9260c214200bff3254e98b7a3fcf233e5974ae9301b1f89a2f612",
+ ),
+ (
+ "mnemonic: japanese wordlist, ideographic spaces",
+ "\u3048\u304B\u3099\u304A\u3000\u306F\u3044\u305B\u3093\u3000\u307F\u3068\u3081\u308B\u3000\u304B\u3075\u3099\u304B\u3000\u3042\u308F\u305B\u308B\u3000\u3055\u304D\u3099\u3087\u3046\u3000\u306B\u308F\u3068\u308A\u3000\u3055\u3068\u3057\u3000\u306B\u305B\u3082\u306E\u3000\u3055\u3068\u308B\u3000\u304D\u305B\u3064\u3000\u305B\u3093\u306C\u304D",
+ "\u334D\u30AC\u30D0\u30F4\u30A1\u3071\u3070\u3050\u309E\u3061\u3062\u5341\u4EBA\u5341\u8272",
+ "926db930e88d63a1d7cdcb369efc437d60cf94fbc22c26a781650b6d98a3cf3cac9e29022317df85da7515b7cf4e6bbd6fe88388fac1788d8aefb4942360bd87",
+ ),
+ (
+ "mnemonic: japanese wordlist, ascii spaces",
+ "\u3048\u304B\u3099\u304A \u306F\u3044\u305B\u3093 \u307F\u3068\u3081\u308B \u304B\u3075\u3099\u304B \u3042\u308F\u305B\u308B \u3055\u304D\u3099\u3087\u3046 \u306B\u308F\u3068\u308A \u3055\u3068\u3057 \u306B\u305B\u3082\u306E \u3055\u3068\u308B \u304D\u305B\u3064 \u305B\u3093\u306C\u304D",
+ "",
+ "02c2b6becf2f292952226eb8f989a5fc972386316c295d74680344b2a45669a52af268501eb10e5f05db662ec407d987280f6474814db4ab3e541228561fdb3f",
+ ),
+ (
+ "mnemonic: spanish wordlist NFC",
+ "perico imagen olivo l\u00E1piz seguir semilla audaz cuesta relleno gavil\u00E1n lancha ocurrir",
+ "",
+ "43300a0f0aa6c3ed53f644b751e9d56dc6b32c620e6e9947d938fa5a14b27b4777ad849e1e2f55923a6f943c15f987f48291f7c15182055d8483812d39c30bf0",
+ ),
+ (
+ "mnemonic: spanish wordlist NFD",
+ "perico imagen olivo la\u0301piz seguir semilla audaz cuesta relleno gavila\u0301n lancha ocurrir",
+ "",
+ "aa02a320acabbdf85c919dadb87b706560d85408fc8971d4bc8416918b29817b1ea62f77846c5afe2534258364be1000a8b8598bfa6889886882882ef2032ac1",
+ ),
+ (
+ "mnemonic: french wordlist",
+ "mascotte infusion tailler e\u0301cume tailler chenille mouche vorace justice infini substrat cubique",
+ "TREZOR",
+ "d4fac24db32d00bb1f8df9360c54dfb1266dc17fc87a79b88259ace89fe46cc1da5541e0fa04eea67cd5e429cb46c600750303be3bd17d55ab176a89f857ab35",
+ ),
+ (
+ "mnemonic: chinese wordlist",
+ "\u6B66 \u5EAD \u7EA7 \u6000 \u848B \u5FEB \u7684 \u91CA \u57FA \u8D76 \u732E \u903B",
+ "",
+ "d7c630a61c84f73882624c53a4ab8248915158c925baa7ea9dbfdd7a6dbaeeff02eaa6cf7950c7b1c25ed23b271f0c1b86fde63e805b2b8500c3fd272b019011",
+ ),
+ (
+ "mnemonic: korean wordlist",
+ "\u1109\u1169\u1112\u1167\u11BC \u110E\u1169\u11BC\u1105\u1175 \u1109\u116E\u1103\u1161\u11AB \u1109\u116E\u11A8\u1102\u1167 \u1109\u1165\u11AF\u1110\u1161\u11BC \u1112\u1167\u11AF\u110B\u1162\u11A8 \u1107\u1165\u11B7\u110C\u116C \u1112\u1167\u11AB\u110C\u1175 \u1102\u1161\u1106\u116E\u11AF \u110B\u1167\u110C\u1165\u11AB\u1112\u1175 \u1106\u1162\u11A8\u110C\u116E \u1112\u1161\u11B7\u1101\u1166",
+ "",
+ "70de5f094062d4dbebcf1512390aea9eb5e96483df86d0883a960735054f621bf545ba4c11830ca6450b9113c360f02ab7ca809c20c3a506bd64afd6a01a7901",
+ ),
+ (
+ "mnemonic: empty",
+ "",
+ "",
+ "4ed8d4b17698ddeaa1f1559f152f87b5d472f725ca86d341bd0276f1b61197e21dd5a391f9f5ed7340ff4d4513aab9cce44f9497a5e7ed85fd818876b6eb402e",
+ ),
+ (
+ "mnemonic: 127 bytes",
+ "a" * 127,
+ "",
+ "a69c3d03fc62bff17455af98a7b1a3c77d7939550e905a30f9237207c7992a7b4fe3b5ef77befcbc49ff3716efb5f65d3807e1a8b9f53e94ceb80dc204c81c63",
+ ),
+ (
+ "mnemonic: 128 bytes",
+ "a" * 128,
+ "",
+ "e03cb086c2fd2795ac49a6f9e5130be066f5f0efe131fc79d5219ed652f5faec69a3a9d13270d5d580846ce0e6e56716c6de27151b0d107e2b443c9d7f3b7e33",
+ ),
+ (
+ "mnemonic: 129 bytes",
+ "a" * 129,
+ "",
+ "c56e21da2e04cb3687c915c4997bff79a469cff09fee004eb30c655ddf2580c23ad96723207f00dcaab84c2e642e876ac326cffdab71f79fb18755c53d21455d",
+ ),
+ (
+ "mnemonic: 128 CJK code units",
+ "\u5BC6" * 128,
+ "",
+ "4cb23ca53f5bde8fabc190b61222cc3b0bf6a72a6916f9068ef733fa9fa54b395e4ad04a7e5652e70316fe6566d252f641d262de44fb647fdb9b3bac6a6a592a",
+ ),
+ (
+ "mnemonic: 64 emoji (128 code units)",
+ "\uD83D\uDE00" * 64,
+ "",
+ "d3ac13d601b7ebfb399a434b1d7f861843d1adf66ad01f518f55f398aaffc780b6d50f88e3d4b39153e492d33fc5bab914e534facc2c4116245faaf7d10c9c03",
+ ),
+ (
+ "mnemonic: lone surrogates",
+ "\uD800\uDBFF\uDC00",
+ "",
+ "1219f6e97b044678a0031f7cf262abab00977e09a73dfec5626000a7aae99fca64e8793370d319c7db642c0559960d7351cbae68893d83930751d2d8b8cfe39f",
+ ),
+];
+
+void main() {
+ group("bip39MnemonicToSeed matches the previous bip39 fork", () {
+ for (final (label, mnemonic, passphrase, seed) in _vectors) {
+ test(label, () => expect(_hex(bip39MnemonicToSeed(mnemonic, passphrase: passphrase)), seed));
+ }
+ });
+}
+
+String _hex(List<int> bytes) => bytes.map((b) => b.toRadixString(16).padLeft(2, "0")).join();
### cw_core/test/crypto_amount_format_test.dart
@@ -108,6 +108,15 @@ void main() {
});
});
+ group("Locale without intl number data", () {
+ test("should format as English instead of throwing (ha)", () {
+ const input = "1123.4567";
+ final result = input.withLocalSeperator("ha");
+
+ expect(result, equals("1,123.4567"));
+ });
+ });
+
group('With XMR Suffix', () {
const locale = 'de_CH';
### cw_core/test/encryption_file_utils_test.dart
@@ -0,0 +1,380 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:typed_data';
+
+import 'package:cake_backup/backup.dart' as cwb;
+import 'package:cw_core/encryption_file_utils.dart';
+import 'package:cw_core/key.dart';
+import 'package:cw_core/utils/file.dart' as encrypted_file;
+import 'package:cw_core/wallet_keys_file.dart';
+import 'package:encrypt/encrypt.dart' as encrypt;
+import 'package:flutter_test/flutter_test.dart';
+
+void main() {
+ late Directory tmpDir;
+
+ setUp(() {
+ tmpDir = Directory.systemTemp.createTempSync('cw_enc_');
+ });
+
+ tearDown(() {
+ if (tmpDir.existsSync()) {
+ tmpDir.deleteSync(recursive: true);
+ }
+ });
+
+ String path([String name = 'wallet.json']) => '${tmpDir.path}/$name';
+
+ const walletJson = '{"mnemonic":"abandon ability able","privateKey":null}';
+
+ group('XChaCha20 round-trip', () {
+ test('writes and reads JSON with a generated high-entropy password', () async {
+ final password = generateKey();
+ await encrypted_file.write(
+ path: path(),
+ password: password,
+ data: walletJson,
+ highEntropyPassphrase: true,
+ );
+
+ expect(await encrypted_file.read(path: path(), password: password), walletJson);
+ expect(File('${path()}.tmp').existsSync(), isFalse);
+ });
+
+ test('uses high-entropy (v3) vs low-entropy (v2) version bytes', () async {
+ final password = generateKey();
+
+ await encrypted_file.write(
+ path: path('high'),
+ password: password,
+ data: walletJson,
+ highEntropyPassphrase: true,
+ );
+ expect(File(path('high')).readAsBytesSync().first, cwb.highEntropyVersion);
+
+ await encrypted_file.write(
+ path: path('low'),
+ password: password,
+ data: walletJson,
+ highEntropyPassphrase: false,
+ );
+ expect(File(path('low')).readAsBytesSync().first, cwb.lowEntropyVersion);
+
+ expect(await encrypted_file.read(path: path('high'), password: password), walletJson);
+ expect(await encrypted_file.read(path: path('low'), password: password), walletJson);
+ });
+
+ test('read ignores highEntropyPassphrase because version is in the file', () async {
+ final password = generateKey();
+ await encrypted_file.write(
+ path: path(),
+ password: password,
+ data: walletJson,
+ highEntropyPassphrase: true,
+ );
+
+ expect(
+ await encrypted_file.read(
+ path: path(),
+ password: password,
+ highEntropyPassphrase: false,
+ ),
+ walletJson,
+ );
+ });
+
+ test('round-trips UTF-8 JSON with non-ASCII characters', () async {
+ final password = generateKey();
+ const data = '{"name":"Café","mnemonic":"abandon"}';
+ await encrypted_file.write(
+ path: path(),
+ password: password,
+ data: data,
+ highEntropyPassphrase: true,
+ );
+
+ expect(await encrypted_file.read(path: path(), password: password), data);
+ });
+
+ test('wrong password does not fall back to Salsa20 or rewrite the file', () async {
+ final password = generateKey();
+ await encrypted_file.write(
+ path: path(),
+ password: password,
+ data: walletJson,
+ highEntropyPassphrase: true,
+ );
+ final before = File(path()).readAsBytesSync();
+
+ await expectLater(
+ encrypted_file.read(path: path(), password: generateKey()),
+ throwsA(anything),
+ );
+ expect(File(path()).readAsBytesSync(), before);
+ });
+
+ test('corrupt XChaCha20 blob is not treated as a legacy Salsa20 file', () async {
+ final password = generateKey();
+ await encrypted_file.write(
+ path: path(),
+ password: password,
+ data: walletJson,
+ highEntropyPassphrase: true,
+ );
+ final bytes = File(path()).readAsBytesSync();
+ bytes[bytes.length - 1] = bytes[bytes.length - 1] ^ 0xFF;
+ File(path()).writeAsBytesSync(bytes);
+
+ await expectLater(
+ encrypted_file.read(path: path(), password: password),
+ throwsA(anything),
+ );
+ expect(File(path()).readAsBytesSync().first, cwb.highEntropyVersion);
+ });
+ });
+
+ group('encryptionFileUtilsFor', () {
+ test('isDirect=false (generated password) writes high-entropy v3', () async {
+ final password = generateKey();
+ final encryption = encryptionFileUtilsFor(false);
+ await encryption.write(path: path(), password: password, data: walletJson);
+
+ expect(File(path()).readAsBytesSync().first, cwb.highEntropyVersion);
+ expect(await encryption.read(path: path(), password: password), walletJson);
+ });
+
+ test('isDirect=true (user password) writes low-entropy v2', () async {
+ const password = 'user-chosen-passphrase';
+ final encryption = encryptionFileUtilsFor(true);
+ await encryption.write(path: path(), password: password, data: walletJson);
+
+ expect(File(path()).readAsBytesSync().first, cwb.lowEntropyVersion);
+ expect(await encryption.read(path: path(), password: password), walletJson);
+ });
+
+ test('WalletKeysData JSON survives a write/read used by getSeeds', () async {
+ final password = generateKey();
+ final keys = WalletKeysData(
+ mnemonic: 'abandon ability able about above absent absorb abstract',
+ privateKey: 'deadbeef',
+ );
+ final encryption = encryptionFileUtilsFor(false);
+ await encryption.write(path: path(), password: password, data: keys.toJSON());
+
+ final decoded = json.decode(await encryption.read(path: path(), password: password))
+ as Map<String, dynamic>;
+ final restored = WalletKeysData.fromJSON(decoded);
+ expect(restored.mnemonic, keys.mnemonic);
+ expect(restored.privateKey, keys.privateKey);
+ });
+ });
+
+ group('legacy Salsa20 migration', () {
+ test('reads a Salsa20 wallet file and re-encrypts it as XChaCha20', () async {
+ final password = generateKey();
+ File(path()).writeAsStringSync(_salsa20Encrypt(password, walletJson));
+ expect(File(path()).readAsBytesSync().first, isNot(cwb.lowEntropyVersion));
+ expect(File(path()).readAsBytesSync().first, isNot(cwb.highEntropyVersion));
+
+ final result = await encrypted_file.read(
+ path: path(),
+ password: password,
+ highEntropyPassphrase: true,
+ );
+
+ expect(result, walletJson);
+ expect(File(path()).readAsBytesSync().first, cwb.highEntropyVersion);
+ expect(await encrypted_file.read(path: path(), password: password), walletJson);
+ });
+
+ test('migrated file can be opened with EncryptionFileUtils', () async {
+ final password = generateKey();
+ File(path()).writeAsStringSync(_salsa20Encrypt(password, walletJson));
+
+ final encryption = encryptionFileUtilsFor(false);
+ expect(await encryption.read(path: path(), password: password), walletJson);
+ expect(await encryption.read(path: path(), password: password), walletJson);
+ });
+
+ test('wrong password does not rewrite the Salsa20 file', () async {
+ final password = generateKey();
+ final salsa = _salsa20Encrypt(password, walletJson);
+ File(path()).writeAsStringSync(salsa);
+
+ await expectLater(
+ encrypted_file.read(path: path(), password: generateKey()),
+ throwsLegacyDecryptError,
+ );
+ expect(File(path()).readAsStringSync(), salsa);
+ });
+
+ test('short or malformed password does not leak _readLegacy errors', () async {
+ final password = generateKey();
+ final salsa = _salsa20Encrypt(password, walletJson);
+ File(path()).writeAsStringSync(salsa);
+
+ await expectLater(
+ encrypted_file.read(path: path(), password: 'user-pass'),
+ throwsLegacyDecryptError,
+ );
+ expect(File(path()).readAsStringSync(), salsa);
+ });
+
+ test('corrupt non-base64 file does not leak _readLegacy errors', () async {
+ File(path()).writeAsStringSync('not-valid-base64!!!');
+
+ await expectLater(
+ encrypted_file.read(path: path(), password: generateKey()),
+ throwsLegacyDecryptError,
+ );
+ expect(File(path()).readAsStringSync(), 'not-valid-base64!!!');
+ });
+
+ test('invalid UTF-8 legacy bytes do not leak _readLegacy errors', () async {
+ File(path()).writeAsBytesSync(const [0x00, 0xFF, 0xFE, 0x01]);
+
+ await expectLater(
+ encrypted_file.read(path: path(), password: generateKey()),
+ throwsLegacyDecryptError,
+ );
+ expect(File(path()).readAsBytesSync(), const [0x00, 0xFF, 0xFE, 0x01]);
+ });
+
+ test('rejects Salsa20 plaintext that does not start with {"', () async {
+ final password = generateKey();
+ File(path()).writeAsStringSync(_salsa20Encrypt(password, 'not-json-payload'));
+
+ await expectLater(
+ encrypted_file.read(path: path(), password: password),
+ throwsLegacyDecryptError,
+ );
+ expect(File(path()).readAsBytesSync().first, isNot(cwb.highEntropyVersion));
+ expect(File(path()).readAsBytesSync().first, isNot(cwb.lowEntropyVersion));
+ });
+
+ test('does not re-encrypt Salsa20 data that starts with {" but is not JSON', () async {
+ final password = generateKey();
+ const garbage = '{"not valid json';
+ File(path()).writeAsStringSync(_salsa20Encrypt(password, garbage));
+
+ expect(await encrypted_file.read(path: path(), password: password), garbage);
+ expect(File(path()).readAsBytesSync().first, isNot(cwb.highEntropyVersion));
+ expect(File(path()).readAsBytesSync().first, isNot(cwb.lowEntropyVersion));
+ });
+
+ test(
+ 'wrong password that decrypts to {" does not rewrite the file',
+ () async {
+ final password = generateKey();
+ final salsa = _salsa20Encrypt(password, walletJson);
+ File(path()).writeAsStringSync(salsa);
+
+ final collision = _findWrongPasswordWithJsonObjectPrefix(salsa);
+ expect(collision, isNot(password));
+ expect(_salsa20Decrypt(collision, salsa).startsWith('{"'), isTrue);
+ expect(() => json.decode(_salsa20Decrypt(collision, salsa)), throwsA(anything));
+
+ final result = await encrypted_file.read(path: path(), password: collision);
+
+ expect(result.startsWith('{"'), isTrue);
+ expect(result, isNot(walletJson));
+ expect(File(path()).readAsStringSync(), salsa);
+ },
+ );
+ });
+
+ group('legacy Linux XChaCha20 Latin-1 payloads', () {
+ test('decodes files stored as one byte per UTF-16 code unit', () async {
+ final password = generateKey();
+ const data = '{"name":"Café","mnemonic":"abandon"}';
+ // Old XChaCha20EncryptionFileUtils used String.codeUnits instead of utf8.encode.
+ final encrypted = await cwb.encrypt(
+ password,
+ Uint8List.fromList(data.codeUnits),
+ highEntropyPassphrase: true,
+ );
+ File(path()).writeAsBytesSync(encrypted);
+
+ expect(await encrypted_file.read(path: path(), password: password), data);
+ });
+ });
+
+ group('generateKey', () {
+ test('produces unique passwords that still encrypt and decrypt', () async {
+ final a = generateKey();
+ final b = generateKey();
+ expect(a, isNot(b));
+ expect(a.length, greaterThan(12));
+
+ await encrypted_file.write(
+ path: path(),
+ password: a,
+ data: walletJson,
+ highEntropyPassphrase: true,
+ );
+ expect(await encrypted_file.read(path: path(), password: a), walletJson);
+ });
+ });
+}
+
+final throwsLegacyDecryptError = throwsA(
+ isA<Exception>().having(
+ (e) => e.toString(),
+ 'message',
+ contains('Failed to decrypt legacy file'),
+ ),
+);
+
+({encrypt.Key key, encrypt.IV iv}) _salsa20Keys(String password) {
+ const ivEncodedStringLength = 12;
+ return (
+ key: encrypt.Key.fromBase64(password.substring(0, password.length - ivEncodedStringLength)),
+ iv: encrypt.IV.fromBase64(password.substring(password.length - ivEncodedStringLength)),
+ );
+}
+
+encrypt.Encrypter _salsa20(String password) {
+ final keys = _salsa20Keys(password);
+ return encrypt.Encrypter(encrypt.Salsa20(keys.key));
+}
+
+String _salsa20Encrypt(String password, String data) {
+ final keys = _salsa20Keys(password);
+ return _salsa20(password).encrypt(data, iv: keys.iv).base64;
+}
+
+String _salsa20Decrypt(String password, String data) {
+ final keys = _salsa20Keys(password);
+ return _salsa20(password).decrypt64(data, iv: keys.iv);
+}
+
+List<int> _salsa20DecryptBytes(String password, String data) {
+ final keys = _salsa20Keys(password);
+ return _salsa20(password).decryptBytes(encrypt.Encrypted.fromBase64(data), iv: keys.iv);
+}
+
+String _passwordFromNonce(int nonce) {
+ final ivBytes = Uint8List(8);
+ ivBytes.buffer.asByteData().setUint64(0, nonce, Endian.little);
+ return encrypt.Key(Uint8List(32)).base64 + encrypt.IV(ivBytes).base64;
+}
+
+/// Salsa20 has no MAC, so a wrong key decrypts to garbage. The first two bytes
+/// are `{"` about once in 2^16 tries; keep going until that happens, then skip
+/// the much rarer case where the garbage is also valid JSON (that would rewrite).
+String _findWrongPasswordWithJsonObjectPrefix(String ciphertext) {
+ const maxAttempts = 1 << 20;
+ for (var nonce = 0; nonce < maxAttempts; nonce++) {
+ final candidate = _passwordFromNonce(nonce);
+ final bytes = _salsa20DecryptBytes(candidate, ciphertext);
+ if (bytes.length < 2 || bytes[0] != 0x7b || bytes[1] != 0x22) {
+ continue;
+ }
+ try {
+ json.decode(_salsa20Decrypt(candidate, ciphertext));
+ } catch (_) {
+ return candidate;
+ }
+ }
+ fail('no Salsa20 {" prefix collision in $maxAttempts attempts');
+}
### cw_core/test/proxy_wrapper_prefer_ipv6_test.dart
@@ -0,0 +1,60 @@
+import "dart:io";
+
+import "package:cw_core/utils/proxy_wrapper.dart";
+import "package:cw_core/utils/tor/disabled.dart";
+import "package:flutter_test/flutter_test.dart";
+
+/// Answers every request with the client address the server saw.
+Future<HttpServer> _clientAddressEchoServer(InternetAddress address) async {
+ final server = await HttpServer.bind(address, 0);
+ server.listen((request) async {
+ await request.drain<void>();
+ request.response.write(request.connectionInfo!.remoteAddress.address);
+ await request.response.close();
+ });
+ return server;
+}
+
+void main() {
+ setUpAll(() => CakeTor.instance = CakeTorDisabled());
+
+ test("preferIPv6 falls back to the normal request when IPv6 cannot connect", () async {
+ // IPv4 loopback only: the IPv6 attempt to [::1] is refused, or never starts without IPv6.
+ final server = await _clientAddressEchoServer(InternetAddress.loopbackIPv4);
+ addTearDown(() => server.close(force: true));
+
+ final response = await ProxyWrapper().post(
+ clearnetUri: Uri.parse("http://localhost:${server.port}/"),
+ body: "{}",
+ preferIPv6: true,
+ );
+
+ expect(response.statusCode, 200);
+ expect(response.body, "127.0.0.1");
+ });
+
+ test("preferIPv6 connects over IPv6 when it works", () async {
+ final HttpServer server;
+ try {
+ // Dual-stack: accepts both families and reports which one the client used.
+ server = await _clientAddressEchoServer(InternetAddress.anyIPv6);
+ } on SocketException {
+ return; // No IPv6 on this machine (some CI containers).
+ }
+ addTearDown(() => server.close(force: true));
+ final localhost = await InternetAddress.lookup("localhost", type: InternetAddressType.IPv6)
+ .catchError((Object _) => <InternetAddress>[]);
+ if (!localhost.any((address) => address.address == "::1")) {
+ return;
+ }
+
+ final response = await ProxyWrapper().post(
+ clearnetUri: Uri.parse("http://localhost:${server.port}/"),
+ body: "{}",
+ preferIPv6: true,
+ );
+
+ expect(response.statusCode, 200);
+ expect(response.body, "::1");
+ });
+}
### cw_custom_lints/lib/main.dart
@@ -8,6 +8,7 @@ import "package:cw_custom_lints/money_amount_to_string/money_amount_to_string_ru
import "package:cw_custom_lints/print_verbose/print_verbose_fix.dart";
import "package:cw_custom_lints/print_verbose/print_verbose_rule.dart";
import "package:cw_custom_lints/restricted_imports/restricted_imports_rule.dart";
+import "package:cw_custom_lints/use_cake_exception/use_cake_exception_rule.dart";
final plugin = CwCustomLintsPlugin();
@@ -23,6 +24,7 @@ class CwCustomLintsPlugin extends Plugin {
registry.registerWarningRule(ModernButtonSemanticsRule());
registry.registerWarningRule(ModalTopBarSemanticsRule());
registry.registerWarningRule(MoneyAmountToStringRule());
+ registry.registerWarningRule(UseCakeExceptionRule());
registry.registerFixForRule(PrintVerboseRule.code, ReplaceWithPrintV.new);
registry.registerFixForRule(MoneyAmountToStringRule.code, ReplaceWithMoneyToString.new);
### cw_custom_lints/lib/use_cake_exception/use_cake_exception_rule.dart
@@ -0,0 +1,51 @@
+import "package:analyzer/analysis_rule/analysis_rule.dart";
+import "package:analyzer/analysis_rule/rule_context.dart";
+import "package:analyzer/analysis_rule/rule_visitor_registry.dart";
+import "package:analyzer/dart/ast/ast.dart";
+import "package:analyzer/dart/ast/visitor.dart";
+import "package:analyzer/error/error.dart";
+
+class UseCakeExceptionRule extends AnalysisRule {
+ UseCakeExceptionRule()
+ : super(name: "use_cake_exception", description: "please use a CakeException subclass instead");
+
+ static const LintCode code = LintCode(
+ "use_cake_exception",
+ "please use a CakeException subclass instead",
+ severity: DiagnosticSeverity.WARNING,
+ );
+
+ @override
+ LintCode get diagnosticCode => code;
+
+ @override
+ void registerNodeProcessors(RuleVisitorRegistry registry, RuleContext context) {
+ registry.addThrowExpression(this, _Visitor(this));
+ }
+}
+
+class _Visitor extends SimpleAstVisitor<void> {
+ _Visitor(this.rule);
+
+ final AnalysisRule rule;
+
+ @override
+ void visitThrowExpression(ThrowExpression node) {
+ final thrown = node.expression;
+ if (thrown is! InstanceCreationExpression) {
+ return;
+ }
+
+ final type = thrown.constructorName.type;
+ if (type.name.lexeme != "Exception") {
+ return;
+ }
+
+ final library = type.element?.library;
+ if (library != null && !library.isDartCore) {
+ return;
+ }
+
+ rule.reportAtNode(node);
+ }
+}
### cw_decred/lib/api/libdcrwallet.dart
@@ -441,7 +441,9 @@ class Libwallet {
}
Future<String> syncStatus(String walletName) async {
- if (_closed) throw StateError('Closed');
+ if (_closed) {
+ return "closed";
+ }
final completer = Completer<Object?>.sync();
final id = _idCounter++;
_activeRequests[id] = completer;
@@ -466,7 +468,7 @@ class Libwallet {
_commands.send((id, req));
final res = await completer.future as PayloadResult;
try {
- return jsonDecode(res.payload);
+ return jsonDecode(res.payload) as Map<String, dynamic>;
} catch (_) {
if (throwOnError) {
rethrow;
@@ -632,7 +634,9 @@ class Libwallet {
// nothing.
return null;
}
- checkErr(res.err);
+ if(res.err.isNotEmpty) {
+ throw DecredPayloadExecutionException(res.err);
+ }
return res.payload;
}
### cw_decred/lib/api/util.dart
@@ -1,4 +1,5 @@
import 'dart:ffi';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:ffi/ffi.dart';
import 'dart:convert';
@@ -10,6 +11,10 @@ class PayloadResult {
const PayloadResult(this.payload, this.err, this.errCode);
}
+class DecredPayloadExecutionException extends CakeException {
+ const DecredPayloadExecutionException(super.message);
+}
+
// Executes the provided fn and converts the string response to a PayloadResult.
// Returns payload, error code, and error.
PayloadResult executePayloadFn({
@@ -19,16 +24,16 @@ PayloadResult executePayloadFn({
}) {
final jsonStr = fn().toDartString();
freePointers(ptrsToFree);
- if (jsonStr == null) throw Exception("no json return from wallet library");
+ if (jsonStr == null) throw DecredPayloadExecutionException("no json return from wallet library");
final decoded = json.decode(jsonStr);
- final err = decoded["error"] ?? "";
- if (!skipErrorCheck) {
- checkErr(err);
+ final err = decoded["error"] as String? ?? "";
+ if (!skipErrorCheck && (err as String? ?? "").isNotEmpty) {
+ throw DecredPayloadExecutionException(err);
}
- final payload = decoded["payload"] ?? "";
- final errCode = decoded["errorcode"] ?? -1;
+ final payload = decoded["payload"] as String? ?? "";
+ final errCode = decoded["errorcode"] as int? ?? -1;
return new PayloadResult(payload, err, errCode);
}
@@ -38,10 +43,6 @@ void freePointers(List<Pointer> ptrsToFree) {
}
}
-void checkErr(String err) {
- if (err == "") return;
- throw Exception(err);
-}
extension StringUtil on String {
Pointer<Char> toCString() => toNativeUtf8().cast<Char>();
### cw_decred/lib/transaction_priority.dart
@@ -1,3 +1,4 @@
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/transaction_priority.dart';
import 'package:flutter/foundation.dart';
@@ -21,7 +22,7 @@ class DecredTransactionPriority extends TransactionPriority {
return fast;
default:
if (kDebugMode) {
- throw Exception('Unexpected token: $raw for DecredTransactionPriority deserialize');
+ throw DeserializeException('Unexpected token: $raw for DecredTransactionPriority deserialize');
}
return medium;
}
### cw_decred/lib/wallet.dart
@@ -234,13 +234,13 @@ abstract class DecredWalletBase
final syncStatusJSON = await _libwallet.syncStatus(walletInfo.name);
final decoded = json.decode(syncStatusJSON.isEmpty ? "{}" : syncStatusJSON);
- final syncStatusCode = decoded["syncstatuscode"] ?? 0;
+ final syncStatusCode = decoded["syncstatuscode"] as int? ?? 0;
// final syncStatusStr = decoded["syncstatus"] ?? "";
- final targetHeight = decoded["targetheight"] ?? 1;
+ final targetHeight = decoded["targetheight"] as int? ?? 1;
final numPeers = decoded["numpeers"] ?? 0;
// final cFiltersHeight = decoded["cfiltersheight"] ?? 0;
- final headersHeight = decoded["headersheight"] ?? 0;
- final rescanHeight = decoded["rescanheight"] ?? 0;
+ final headersHeight = decoded["headersheight"] as int? ?? 0;
+ final rescanHeight = decoded["rescanheight"] as int? ?? 0;
if (numPeers == 0) {
syncStatus = NotConnectedSyncStatus();
@@ -421,18 +421,18 @@ abstract class DecredWalletBase
};
final res = await _libwallet.createSignedTransaction(walletInfo.name, jsonEncode(signReq));
final decoded = json.decode(res);
- final signedHex = decoded["hex"];
+ final signedHex = decoded["hex"] as String? ?? "";
final send = () async {
await _libwallet.sendRawTransaction(walletInfo.name, signedHex);
await updateBalance();
};
- final fee = decoded["fee"] ?? 0;
+ final fee = decoded["fee"] as int? ?? 0;
if (sendAll) {
totalAmt = (totalAmt - fee).round();
}
return DecredPendingTransaction(
- txId: decoded["txid"] ?? "",
+ txId: decoded["txid"] as String? ?? "",
amount: Money.fromInt(totalAmt, currency),
fee: Money.fromInt(fee, currency),
rawHex: signedHex,
@@ -497,18 +497,20 @@ abstract class DecredWalletBase
final decoded = json.decode(res);
final txs = <String, DecredTransactionInfo>{};
- for (final d in decoded) {
- final txid = uniqueTxID(d["txid"] ?? "", d["vout"] ?? 0);
+ for (final d in decoded as Iterable<dynamic>) {
+ final txid = uniqueTxID(d["txid"] as String? ?? "", d["vout"] as int? ?? 0);
var direction = TransactionDirection.outgoing;
if (d["category"] == "receive") {
direction = TransactionDirection.incoming;
}
- final amountDouble = d["amount"] ?? 0.0;
+ // amount and fee are Go float64s, and Go writes whole values without a decimal point
+ // (1, not 1.0), so they can decode as int. Cast to num, never double.
+ final amountDouble = d["amount"] as num? ?? 0.0;
final amount = (amountDouble * 1e8).round().abs();
- final feeDouble = d["fee"] ?? 0.0;
+ final feeDouble = d["fee"] as num? ?? 0.0;
final fee = (feeDouble * 1e8).round().abs();
- final confs = d["confirmations"] ?? 0;
- final sendTime = d["time"] ?? 0;
+ final confs = d["confirmations"] as int? ?? 0;
+ final sendTime = d["time"] as int? ?? 0;
txs[txid] = DecredTransactionInfo(
id: txid,
@@ -517,9 +519,9 @@ abstract class DecredWalletBase
direction: direction,
isPending: confs == 0,
date: DateTime.fromMillisecondsSinceEpoch(sendTime * 1000, isUtc: false),
- height: d["height"] ?? 0,
+ height: d["height"] as int? ?? 0,
confirmations: confs,
- to: d["address"] ?? "",
+ to: d["address"] as String? ?? "",
);
}
return txs;
@@ -543,6 +545,9 @@ abstract class DecredWalletBase
@override
bool get hasRescan => walletBirthdayBlockHeight() != -1;
+ @override
+ bool get hasCoinControl => true;
+
@override
Future<void> rescan({required int height}) async {
// The required height is not used. A birthday time is recorded in the
@@ -600,8 +605,8 @@ abstract class DecredWalletBase
});
balance[CryptoCurrency.dcr] = DecredBalance(
- confirmed: Money.fromInt(balanceMap["confirmed"] ?? 0, currency),
- unconfirmed: Money.fromInt(balanceMap["unconfirmed"] ?? 0, currency),
+ confirmed: Money.fromInt(balanceMap["confirmed"] as int? ?? 0, currency),
+ unconfirmed: Money.fromInt(balanceMap["unconfirmed"] as int? ?? 0, currency),
frozen: Money.fromInt(totalFrozen, currency),
);
}
@@ -669,15 +674,22 @@ abstract class DecredWalletBase
final res = await _libwallet.listUnspents(walletInfo.name);
final decoded = json.decode(res);
final unspents = <Unspent>[];
- for (final d in decoded) {
- final spendable = d["spendable"] ?? false;
+ for (final d in decoded as Iterable<dynamic>) {
+ final spendable = d["spendable"] as bool? ?? false;
if (!spendable) {
continue;
}
- final amountDouble = d["amount"] ?? 0.0;
+ // A Go float64, so it can decode as int (see fetchFiveTransactions): num, not double.
+ final amountDouble = d["amount"] as num? ?? 0.0;
final amount = (amountDouble * 1e8).round().abs();
- final utxo = Unspent(d["address"] ?? "", d["txid"] ?? "", amount, d["vout"] ?? 0, null);
- utxo.isChange = d["ischange"] ?? false;
+ final utxo = Unspent(
+ d["address"] as String? ?? "",
+ d["txid"] as String? ?? "",
+ amount,
+ d["vout"] as int? ?? 0,
+ null,
+ );
+ utxo.isChange = d["ischange"] as bool? ?? false;
unspents.add(utxo);
}
_unspents = unspents;
@@ -762,7 +774,7 @@ abstract class DecredWalletBase
if (decoded["setfromheight"] == true || decoded["setfromtime"] == true) {
return -1;
}
- return decoded["height"] ?? 0;
+ return decoded["height"] as int? ?? 0;
} on FormatException catch (_) {
return 0;
}
### cw_decred/lib/wallet_addresses.dart
@@ -44,7 +44,7 @@ abstract class DecredWalletAddressesBase extends WalletAddresses with Store {
@override
Future<void> updateAddressesInBox() async {
final addrs = await _libAddresses();
- final allAddrs = List.from(addrs.usedAddrs)..addAll(addrs.unusedAddrs);
+ final allAddrs = List<String>.from(addrs.usedAddrs)..addAll(addrs.unusedAddrs);
// Add all addresses.
allAddrs.forEach((addr) {
@@ -99,10 +99,10 @@ abstract class DecredWalletAddressesBase extends WalletAddresses with Store {
try {
final res = await _libwallet.addresses(walletInfo.name, nUsed, nUnused);
final decoded = json.decode(res);
- final usedAddrs = List<String>.from(decoded["used"] ?? []);
- final unusedAddrs = List<String>.from(decoded["unused"] ?? []);
+ final usedAddrs = List<String>.from(decoded["used"] as Iterable<dynamic>? ?? []);
+ final unusedAddrs = List<String>.from(decoded["unused"] as Iterable<dynamic>? ?? []);
// index is the index of the first unused address.
- final index = decoded["index"] ?? 0;
+ final index = decoded["index"] as int? ?? 0;
return _LibAddresses(usedAddrs, unusedAddrs, index);
} catch (e) {
printV(e);
### cw_decred/lib/wallet_service.dart
@@ -3,6 +3,7 @@ import 'dart:io';
import 'package:bip39/bip39.dart' as bip39;
import 'package:cw_core/encryption_file_utils.dart';
import 'package:cw_core/wallet_keys_file.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_decred/api/libdcrwallet.dart';
import 'package:cw_decred/mnemonic_validation.dart';
import 'package:cw_decred/wallet_creation_credentials.dart';
@@ -133,7 +134,7 @@ class DecredWalletService extends WalletService<
Future<DecredWallet> openWallet(String name, String password) async {
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
final di = await walletInfo.getDerivationInfo();
if (walletInfo.network == null || walletInfo.network == "") {
@@ -182,7 +183,7 @@ class DecredWalletService extends WalletService<
File(await pathForWalletDir(name: wallet, type: getType())).delete(recursive: true);
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet, type: getType());
}
await WalletInfo.delete(walletInfo);
}
@@ -191,7 +192,7 @@ class DecredWalletService extends WalletService<
Future<void> rename(String currentName, String password, String newName) async {
final currentWalletInfo = await WalletInfo.get(currentName, getType());
if (currentWalletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: currentName, type: getType());
}
final di = await currentWalletInfo.getDerivationInfo();
final network =
### cw_dogecoin/lib/src/dogecoin_transaction_priority.dart
@@ -1,5 +1,7 @@
import 'package:cw_bitcoin/bitcoin_transaction_priority.dart';
import 'package:flutter/foundation.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
+
class DogecoinTransactionPriority extends BitcoinTransactionPriority {
const DogecoinTransactionPriority({required String title, required int raw})
@@ -23,7 +25,7 @@ class DogecoinTransactionPriority extends BitcoinTransactionPriority {
return fast;
default:
if (kDebugMode) {
- throw Exception('Unexpected token: $raw for DogecoinTransactionPriority deserialize');
+ throw DeserializeException('Unexpected token: $raw for DogecoinTransactionPriority deserialize');
}
return medium;
}
### cw_dogecoin/lib/src/dogecoin_wallet.dart
@@ -54,8 +54,10 @@ abstract class DogeCoinWalletBase extends ElectrumWallet with Store {
initialAddresses: initialAddresses,
initialRegularAddressIndex: initialRegularAddressIndex,
initialChangeAddressIndex: initialChangeAddressIndex,
- mainHdByType: mainHdByType,
- sideHdByType: sideHdByType,
+ mainHdByTypeAndAccount: mainHdByTypeAndAccount,
+ sideHdByTypeAndAccount: sideHdByTypeAndAccount,
+ accountIndexes: [currentAccountIndex],
+ currentAccountIndex: currentAccountIndex,
legacyMainHd: mainHd,
legacySideHd: sideHd,
network: network,
### cw_dogecoin/lib/src/dogecoin_wallet_addresses.dart
@@ -13,8 +13,10 @@ class DogeCoinWalletAddresses = DogeCoinWalletAddressesBase with _$DogeCoinWalle
abstract class DogeCoinWalletAddressesBase extends ElectrumWalletAddresses with Store {
DogeCoinWalletAddressesBase(
WalletInfo walletInfo, {
- required super.mainHdByType,
- required super.sideHdByType,
+ required super.mainHdByTypeAndAccount,
+ required super.sideHdByTypeAndAccount,
+ required super.accountIndexes,
+ required super.currentAccountIndex,
required super.legacyMainHd,
required super.legacySideHd,
required super.network,
### cw_dogecoin/lib/src/dogecoin_wallet_service.dart
@@ -3,6 +3,7 @@ import 'dart:io';
import 'package:bip39/bip39.dart';
import 'package:cw_bitcoin/bitcoin_mnemonics_bip39.dart';
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/unspent_coins_info.dart';
import 'package:cw_core/wallet_info.dart';
@@ -51,7 +52,7 @@ class DogeCoinWalletService extends WalletService<
Future<DogeCoinWallet> openWallet(String name, String password) async {
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
try {
final wallet = await DogeCoinWalletBase.open(
@@ -83,7 +84,7 @@ class DogeCoinWalletService extends WalletService<
File(await pathForWalletDir(name: wallet, type: getType())).delete(recursive: true);
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet, type: getType());
}
await WalletInfo.delete(walletInfo);
@@ -114,7 +115,7 @@ class DogeCoinWalletService extends WalletService<
Future<DogeCoinWallet> restoreFromSeed(DogeCoinRestoreWalletFromSeedCredentials credentials,
{bool? isTestnet}) async {
if (!validateMnemonic(credentials.mnemonic)) {
- throw Exception('Invalid mnemonic: ${credentials.mnemonic}');
+ throw BadMnemonicException('Invalid mnemonic: ${credentials.mnemonic}');
}
final wallet = await DogeCoinWalletBase.create(
### cw_dogecoin/pubspec.yaml
@@ -2,7 +2,6 @@ name: cw_dogecoin
description: "A new Flutter package project."
version: 0.0.1
publish_to: none
-author: Cake Wallet
homepage: https://cakewallet.com
environment:
@@ -13,10 +12,7 @@ dependencies:
flutter:
sdk: flutter
bip39: ^1.0.6
- bip32: ^2.0.0
- path_provider: ^2.0.11
mobx: ^2.6.0
- flutter_mobx: ^2.3.0
cw_core:
path: ../cw_core
cw_bitcoin:
### cw_evm/lib/clients/evm_chain_client.dart
@@ -5,6 +5,7 @@ import 'dart:developer';
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/erc20_token.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/node.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
@@ -52,20 +53,20 @@ class EVMChainClient {
final jsonResponse = json.decode(response.body) as Map<String, dynamic>;
if (jsonResponse['result'] is String) {
- log(jsonResponse['result']);
+ log(jsonResponse['result'] as String);
return [];
}
if (response.statusCode >= 200 && response.statusCode < 300 && jsonResponse['status'] != 0) {
- final res = (jsonResponse['result'] as List);
+ final res = jsonResponse["result"] as List;
res.removeWhere((e) => e['value'] == '0');
// Filter out spam native transactions below 0.00001 ETH (10000000000000 wei)
if (contractAddress == null) {
final spamThresholdWei = BigInt.from(10000000000000);
res.removeWhere((e) {
try {
- final value = BigInt.parse(e['value'] ?? '0');
+ final value = BigInt.parse(e['value'] as String? ?? '0');
final isIncoming = e['to']?.toLowerCase() == address.toLowerCase() &&
e['from']?.toLowerCase() != address.toLowerCase();
return isIncoming && value < spamThresholdWei;
@@ -84,7 +85,7 @@ class EVMChainClient {
if (mergedMap.containsKey(key)) {
try {
final currentNet = getNetFlow(mergedMap[key]!, address);
- final newNet = getNetFlow(tx, address);
+ final newNet = getNetFlow(tx as Map<String, dynamic>, address);
final totalNet = currentNet + newNet;
mergedMap[key]!['value'] = totalNet.abs().toString();
@@ -98,7 +99,7 @@ class EVMChainClient {
printV('Error merging transaction values: $e');
}
} else {
- mergedMap[key] = Map<String, dynamic>.from(tx);
+ mergedMap[key] = Map<String, dynamic>.from(tx as Map<dynamic, dynamic>);
}
}
@@ -119,7 +120,7 @@ class EVMChainClient {
}
BigInt getNetFlow(Map<String, dynamic> txData, String address) {
- final val = BigInt.parse(txData['value'] ?? '0');
+ final val = BigInt.parse(txData['value'] as String? ?? '0');
final isIncoming = txData['to']?.toLowerCase() == address.toLowerCase();
final isOutgoing = txData['from']?.toLowerCase() == address.toLowerCase();
@@ -175,17 +176,31 @@ class EVMChainClient {
try {
Uri? rpcUri;
bool isModifiedNodeUri = false;
+ final nodeHost = Uri.parse("https://${node.uriRaw}").host;
+ final pathSegments =
+ (node.path ?? "").split("/").where((segment) => segment.isNotEmpty).toList();
- if (node.uriRaw.contains('nownodes.io')) {
+ if (nodeHost.endsWith(".nownodes.io") && pathSegments.isEmpty) {
isModifiedNodeUri = true;
String nowNodeApiKey = secrets.nowNodesApiKey;
if (nowNodeApiKey.isEmpty) {
- printV('NowNodes API key is empty, cannot connect to ${node.uriRaw}');
+ printV("NowNodes API key is empty, cannot connect to ${node.uriRaw}");
return false;
}
rpcUri = Uri.https(node.uriRaw, '/$nowNodeApiKey');
+ } else if (nodeHost.endsWith(".g.alchemy.com") &&
+ (pathSegments.isEmpty || (pathSegments.length == 1 && pathSegments.first == "v2"))) {
+ isModifiedNodeUri = true;
+ String alchemyApiKey = "";
+
+ if (alchemyApiKey.isEmpty) {
+ printV("Alchemy API key is empty, cannot connect to ${node.uriRaw}");
+ return false;
+ }
+
+ rpcUri = Uri.https(node.uriRaw, "/v2/$alchemyApiKey");
}
_client = Web3Client(isModifiedNodeUri ? rpcUri!.toString() : node.uri.toString(), client);
@@ -318,14 +333,16 @@ class EVMChainClient {
currency == CryptoCurrency.baseEth ||
currency == CryptoCurrency.arbEth ||
currency == CryptoCurrency.bnb ||
+ currency == CryptoCurrency.robEth ||
contractAddress != null);
final isNativeToken = [
CryptoCurrency.eth,
CryptoCurrency.maticpoly,
CryptoCurrency.baseEth,
CryptoCurrency.arbEth,
- CryptoCurrency.bnb
+ CryptoCurrency.bnb,
+ CryptoCurrency.robEth
].contains(currency);
// Get nonce with "pending" block tag to include pending transactions
@@ -531,27 +548,29 @@ class EVMChainClient {
return EVMChainERC20Balance(Money(balance, token));
} on RangeError catch (_) {
- throw Exception('Invalid token contract for this network.');
+ throw BadCurrencyException('Invalid token contract for this network.', token);
} catch (e) {
if (e.toString().contains("hostUnreachable")) {
return EVMChainERC20Balance(Money.zero(token));
}
- throw Exception('Could not fetch balances: ${e.toString()}');
+ throw ServerResponseException('Could not fetch balances: ${e.toString()}');
}
}
- Future<Erc20Token?> getErc20Token(String contractAddress, String chainName) async {
+ Future<Erc20Token?> getErc20Token(String contractAddress, String? chainName) async {
try {
- final token = await getErc20TokenFromMoralis(contractAddress, chainName);
+ if (chainName != null) {
+ final token = await getErc20TokenFromMoralis(contractAddress, chainName);
- if (token == null || token.name.isEmpty || token.symbol.isEmpty) {
- return await getErcTokenInfoFromNode(contractAddress, chainName);
+ if (token != null && token.name.isNotEmpty && token.symbol.isNotEmpty) {
+ return token;
+ }
}
- return token;
+ return await getErcTokenInfoFromNode(contractAddress);
} catch (e) {
try {
- return await getErcTokenInfoFromNode(contractAddress, chainName);
+ return await getErcTokenInfoFromNode(contractAddress);
} catch (e) {
return null;
}
@@ -586,8 +605,8 @@ class EVMChainClient {
String filteredSymbol = symbol.replaceFirst(RegExp('^\\\$'), '');
final name = (decodedResponse['name'] ?? '').toString();
- final decimal = decodedResponse['decimals'] ?? '0';
- final iconPath = decodedResponse['logo'] ?? '';
+ final decimal = (decodedResponse['decimals'] ?? '0') as String;
+ final iconPath = (decodedResponse['logo'] ?? '') as String;
return Erc20Token(
name: name,
@@ -598,7 +617,7 @@ class EVMChainClient {
);
}
- Future<Erc20Token?> getErcTokenInfoFromNode(String contractAddress, String chainName) async {
+ Future<Erc20Token?> getErcTokenInfoFromNode(String contractAddress) async {
final erc20 = ERC20(address: EthereumAddress.fromHex(contractAddress), client: _client!);
final name = await erc20.name();
final symbol = await erc20.symbol();
### cw_evm/lib/clients/robinhood_client.dart
@@ -0,0 +1,42 @@
+import "package:cw_evm/clients/evm_chain_client.dart";
+import "package:flutter/foundation.dart";
+import "package:web3dart/web3dart.dart";
+
+class RobinhoodClient extends EVMChainClient {
+ RobinhoodClient() : super(chainId: 4663);
+
+ @override
+ Transaction createTransaction({
+ required EthereumAddress from,
+ required EthereumAddress to,
+ required EtherAmount amount,
+ EtherAmount? maxPriorityFeePerGas,
+ Uint8List? data,
+ int? maxGas,
+ EtherAmount? gasPrice,
+ EtherAmount? maxFeePerGas,
+ int? nonce,
+ }) {
+ EtherAmount? finalGasPrice = gasPrice;
+
+ if (gasPrice == null && maxFeePerGas != null) {
+ finalGasPrice = maxFeePerGas;
+ }
+
+ return Transaction(
+ from: from,
+ to: to,
+ value: amount,
+ data: data,
+ maxGas: maxGas,
+ gasPrice: finalGasPrice,
+ nonce: nonce,
+ );
+ }
+
+ @override
+ Uint8List prepareSignedTransactionForSending(Uint8List signedTransaction) => signedTransaction;
+
+ @override
+ int get chainId => 4663;
+}
### cw_evm/lib/evm_chain_client_factory.dart
@@ -1,6 +1,8 @@
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_evm/clients/arbitrum_client.dart';
import 'package:cw_evm/clients/base_client.dart';
import 'package:cw_evm/clients/bsc_client.dart';
+import "package:cw_evm/clients/robinhood_client.dart";
import 'package:cw_evm/clients/ethereum_client.dart';
import 'package:cw_evm/clients/polygon_client.dart';
import 'package:cw_evm/clients/evm_chain_client.dart';
@@ -17,7 +19,7 @@ class EVMChainClientFactory {
final config = _registry.getChainConfig(chainId);
if (config == null) {
- throw Exception('Chain config not found for chainId: $chainId');
+ throw BadChainIdException('Chain config not found for chainId: $chainId');
}
// Check if chain needs custom client
@@ -32,6 +34,8 @@ class EVMChainClientFactory {
return ArbitrumClient();
case 56:
return BSCClient();
+ case 4663:
+ return RobinhoodClient();
default:
return EVMChainClient(chainId: chainId);
}
### cw_evm/lib/evm_chain_default_tokens.dart
@@ -1,28 +1,56 @@
-import 'package:cw_core/erc20_token.dart';
-import 'package:cw_evm/tokens/arbitrum_tokens.dart';
-import 'package:cw_evm/tokens/base_tokens.dart';
-import 'package:cw_evm/tokens/bsc_tokens.dart';
-import 'package:cw_evm/tokens/ethereum_tokens.dart';
-import 'package:cw_evm/tokens/polygon_tokens.dart';
+import "package:cw_core/erc20_token.dart";
+import "package:cw_evm/tokens/arbitrum_tokens.dart";
+import "package:cw_evm/tokens/base_tokens.dart";
+import "package:cw_evm/tokens/bsc_tokens.dart";
+import "package:cw_evm/tokens/ethereum_tokens.dart";
+import "package:cw_evm/tokens/polygon_tokens.dart";
+import "package:cw_evm/tokens/robinhood_tokens.dart";
/// Default ERC20 tokens for each EVM chain and utility methods for interacting with them
class EVMChainDefaultTokens {
- static List<Erc20Token> getDefaultTokensByChainId(int chainId) {
- return switch (chainId) {
- 1 => EthereumTokens.tokens,
- 137 => PolygonTokens.tokens,
- 8453 => BaseTokens.tokens,
- 42161 => ArbitrumTokens.tokens,
- 56 => BSCTokens.tokens,
- _ => [],
- };
- }
+ static List<Erc20Token> getDefaultTokensByChainId(int chainId) => switch (chainId) {
+ 1 => EthereumTokens.tokens,
+ 137 => PolygonTokens.tokens,
+ 8453 => BaseTokens.tokens,
+ 42161 => ArbitrumTokens.tokens,
+ 56 => BSCTokens.tokens,
+ 4663 => RobinhoodTokens.tokens,
+ _ => [],
+ };
+
+ static List<String> getDefaultTokenAddresses(int chainId) =>
+ getDefaultTokensByChainId(chainId).map((token) => token.contractAddress).toList();
+
+ static List<String> getDefaultTokenSymbols(int chainId) =>
+ getDefaultTokensByChainId(chainId).map((token) => token.symbol.toUpperCase()).toList();
+
+ static final Map<int, Map<String, String>> _iconPathsByAddress = {};
+
+ static String? getDefaultIconPathByAddress(int chainId, String contractAddress) {
+ final iconPaths = _iconPathsByAddress.putIfAbsent(chainId, () {
+ final paths = <String, String>{};
- static List<String> getDefaultTokenAddresses(int chainId) {
- return getDefaultTokensByChainId(chainId).map((token) => token.contractAddress).toList();
+ for (final token in getDefaultTokensByChainId(chainId)) {
+ final iconPath = token.iconPath;
+
+ if (iconPath != null && iconPath.isNotEmpty) {
+ paths[token.contractAddress.toLowerCase()] = iconPath;
+ }
+ }
+
+ return paths;
+ });
+
+ return iconPaths[contractAddress.toLowerCase()];
}
- static List<String> getDefaultTokenSymbols(int chainId) {
- return getDefaultTokensByChainId(chainId).map((token) => token.symbol.toUpperCase()).toList();
+ static Set<String> getDefaultGroupsByAddress(int chainId, String contractAddress) {
+ for (final token in getDefaultTokensByChainId(chainId)) {
+ if (token.contractAddress.toLowerCase() == contractAddress.toLowerCase()) {
+ return token.groups;
+ }
+ }
+
+ return const {};
}
}
### cw_evm/lib/evm_chain_exceptions.dart
@@ -1,61 +1,46 @@
-import 'package:cw_core/crypto_currency.dart';
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/exceptions/cake_exception.dart";
class EVMChainMnemonicIsIncorrectException implements Exception {
@override
String toString() =>
- 'EVM mnemonic has incorrect format. Mnemonic should contain 12 or 24 words separated by space.';
+ "EVM mnemonic has incorrect format. Mnemonic should contain 12 or 24 words separated by space.";
}
-class EVMChainTransactionCreationException implements Exception {
- final String exceptionMessage;
-
+class EVMChainTransactionCreationException extends TransactionGenerationException {
EVMChainTransactionCreationException(CryptoCurrency currency)
- : exceptionMessage = 'Wrong balance. Not enough ${currency.title} on your balance.';
-
- EVMChainTransactionCreationException.fromMessage(this.exceptionMessage);
+ : super("Wrong balance. Not enough ${currency.title} on your balance.");
- @override
- String toString() => exceptionMessage;
+ EVMChainTransactionCreationException.fromMessage(super.message);
}
-class EVMChainTransactionFeesException implements Exception {
- final String exceptionMessage;
-
- EVMChainTransactionFeesException(String message) : exceptionMessage = message;
+class EVMChainTransactionFeesException extends TransactionGenerationException {
+ EVMChainTransactionFeesException(super.message);
EVMChainTransactionFeesException.fromCurrency(String currency)
- : exceptionMessage =
- 'Transaction failed due to insufficient $currency balance to cover the fees.';
-
- @override
- String toString() => exceptionMessage;
+ : super("Transaction failed due to insufficient $currency balance to cover the fees.");
}
-class InsufficientGasFeeException implements Exception {
- final String exceptionMessage;
- final BigInt? requiredGasFee;
- final BigInt? currentBalance;
-
+class InsufficientGasFeeException extends TransactionGenerationException {
InsufficientGasFeeException({
this.requiredGasFee,
this.currentBalance,
- }) : exceptionMessage = _buildMessage(requiredGasFee, currentBalance);
+ }) : super(_buildMessage(requiredGasFee, currentBalance));
+ final BigInt? requiredGasFee;
+ final BigInt? currentBalance;
static String _buildMessage(BigInt? requiredGasFee, BigInt? currentBalance) {
- const baseMessage = 'Insufficient ETH for gas fees.';
- const addEthMessage = ' Please add ETH to your wallet to cover transaction fees.';
+ const baseMessage = "Insufficient ETH for gas fees.";
+ const addEthMessage = " Please add ETH to your wallet to cover transaction fees.";
if (requiredGasFee != null) {
final requiredEth = (requiredGasFee / BigInt.from(10).pow(18)).toStringAsFixed(8);
final balanceInfo = currentBalance != null
- ? ', Available: ${(currentBalance / BigInt.from(10).pow(18)).toStringAsFixed(8)} ETH'
- : '';
- return '$baseMessage Required: ~$requiredEth ETH$balanceInfo.$addEthMessage';
+ ? ", Available: ${(currentBalance / BigInt.from(10).pow(18)).toStringAsFixed(8)} ETH"
+ : "";
+ return "$baseMessage Required: ~$requiredEth ETH$balanceInfo.$addEthMessage";
}
- return '$baseMessage$addEthMessage';
+ return "$baseMessage$addEthMessage";
}
-
- @override
- String toString() => exceptionMessage;
}
### cw_evm/lib/evm_chain_registry.dart
@@ -190,6 +190,36 @@ class EvmChainRegistry {
WalletType.bsc,
'BSC',
);
+
+ // Robinhood Chain
+ _registerChain(
+ const ChainConfig(
+ chainId: 4663,
+ name: "Robinhood Chain",
+ shortCode: "robinhood",
+ caip2: "eip155:4663",
+ nativeCurrency: CryptoCurrency.robEth,
+ capabilities: ChainCapabilities(
+ supportsERC20: true,
+ supportsEIP1559: true,
+ supportsInternalTx: true,
+ supportsSubscriptions: false,
+ supportsENS: false,
+ ),
+ defaultRpcEndpoints: [
+ "rpc.mainnet.chain.robinhood.com",
+ ],
+ explorerUrls: [
+ "https://robinhoodchain.blockscout.com",
+ ],
+ feeModel: FeeModel(
+ type: FeeType.eip1559,
+ defaultGasLimit: 21000,
+ ),
+ ),
+ WalletType.robinhood,
+ "ROB",
+ );
}
void _registerChain(
### cw_evm/lib/evm_chain_transaction_model.dart
@@ -38,21 +38,21 @@ class EVMChainTransactionModel {
factory EVMChainTransactionModel.fromJson(
Map<String, dynamic> json, String defaultSymbol, int chainId) =>
EVMChainTransactionModel(
- date: DateTime.fromMillisecondsSinceEpoch(int.parse(json["timeStamp"]) * 1000),
- hash: json["hash"] ?? "",
- from: json["from"] ?? "",
- to: json["to"] ?? "",
- amount: BigInt.parse(json["value"] ?? "0"),
- gasUsed: int.parse(json["gasUsed"] ?? "0"),
- gasPrice: BigInt.parse(json["gasPrice"] ?? "0"),
- contractAddress: json["contractAddress"] ?? "",
- confirmations: int.parse(json["confirmations"] ?? "0"),
- blockNumber: int.parse(json["blockNumber"] ?? "0"),
- tokenSymbol: json["tokenSymbol"] ?? defaultSymbol,
- tokenDecimal: int.tryParse(json["tokenDecimal"] ?? ""),
+ date: DateTime.fromMillisecondsSinceEpoch(int.parse(json["timeStamp"] as String) * 1000),
+ hash: json["hash"] as String? ?? "",
+ from: json["from"] as String? ?? "",
+ to: json["to"] as String? ?? "",
+ amount: BigInt.parse(json["value"] as String? ?? "0"),
+ gasUsed: int.parse(json["gasUsed"] as String? ?? "0"),
+ gasPrice: BigInt.parse(json["gasPrice"] as String? ?? "0"),
+ contractAddress: json["contractAddress"] as String? ?? "",
+ confirmations: int.parse(json["confirmations"] as String? ?? "0"),
+ blockNumber: int.parse(json["blockNumber"] as String? ?? "0"),
+ tokenSymbol: json["tokenSymbol"] as String? ?? defaultSymbol,
+ tokenDecimal: int.tryParse(json["tokenDecimal"] as String? ?? ""),
isError: json["isError"] == "1",
- input: json["input"] ?? "",
- evmSignatureName: json["evmSignatureName"],
+ input: json["input"] as String? ?? "",
+ evmSignatureName: json["evmSignatureName"] as String?,
chainId: chainId,
);
}
### cw_evm/lib/evm_chain_transaction_priority.dart
@@ -1,3 +1,4 @@
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/transaction_priority.dart';
import 'package:flutter/foundation.dart';
@@ -25,7 +26,7 @@ class EVMChainTransactionPriority extends TransactionPriority {
return fast;
default:
if (kDebugMode) {
- throw Exception('Unexpected token: $raw for EVMChainTransactionPriority deserialize');
+ throw DeserializeException('Unexpected token: $raw for EVMChainTransactionPriority deserialize');
}
return medium;
}
### cw_evm/lib/evm_chain_wallet.dart
@@ -3,11 +3,12 @@ import 'dart:convert';
import 'dart:typed_data';
import 'package:bip32/bip32.dart' as bip32;
-import 'package:bip39/bip39.dart' as bip39;
+import 'package:cw_core/utils/bip39_seed.dart';
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/encryption_file_utils.dart';
import 'package:cw_core/erc20_token.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/node.dart';
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/pending_transaction.dart';
@@ -41,7 +42,6 @@ import 'package:mobx/mobx.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:web3dart/crypto.dart';
import 'package:web3dart/web3dart.dart';
-import 'package:eth_sig_util/eth_sig_util.dart';
import 'contract/erc20.dart';
import 'evm_chain_transaction_info.dart';
@@ -194,7 +194,7 @@ abstract class EVMChainWalletBase
@action
Future<void> selectChain(int chainId, {required Node node}) async {
if (EvmChainRegistry().getChainConfig(chainId) == null) {
- throw Exception('Chain config not found for chainId: $chainId');
+ throw BadChainIdException('Chain config not found for chainId: $chainId');
}
if (selectedChainId == chainId) return;
@@ -268,7 +268,13 @@ abstract class EVMChainWalletBase
Future<bool> checkIfScanProviderIsEnabled() async {
final key = EVMChainUtils.getScanProviderPreferenceKey(selectedChainId);
- return (await sharedPrefs.future).getBool(key) ?? true;
+
+ try {
+ return (await sharedPrefs.future).getBool(key) ?? true;
+ } catch (e) {
+ printV("Could not read the $key preference: $e");
+ return false;
+ }
}
EVMChainTransactionInfo getTransactionInfo(
@@ -318,6 +324,10 @@ abstract class EVMChainWalletBase
isPotentialScam: token.isPotentialScam,
walletName: walletInfo.name,
chainId: selectedChainId,
+ groups: EVMChainDefaultTokens.getDefaultGroupsByAddress(
+ selectedChainId,
+ token.contractAddress,
+ ),
);
}
@@ -334,14 +344,16 @@ abstract class EVMChainWalletBase
);
}
- String _getUSDCContractAddress() {
+ String? _getUSDCContractAddress() {
return switch (selectedChainId) {
1 => "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
137 => "0x2791bca1f2de4661ed88a30c99a7a9449aa84174",
8453 => "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
42161 => "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
56 => "0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d",
- _ => throw Exception("Unsupported chain ID: $selectedChainId"),
+ // Robinhood Chain does not have USDC so using USDG in its place
+ 4663 => "0x5fc5360d0400a0fd4f2af552add042d716f1d168",
+ _ => null,
};
}
@@ -350,10 +362,13 @@ abstract class EVMChainWalletBase
try {
await _client.getBalance(_evmChainPrivateKey.address);
- final usdcContractAddress = Erc20Token(
- name: "USDC", symbol: "USDC", contractAddress: _getUSDCContractAddress(), decimal: 6);
+ final usdcAddress = _getUSDCContractAddress();
+ if (usdcAddress != null) {
+ final usdcContractAddress =
+ Erc20Token(name: "USDC", symbol: "USDC", contractAddress: usdcAddress, decimal: 6);
- await _client.fetchERC20Balances(_evmChainPrivateKey.address, usdcContractAddress);
+ await _client.fetchERC20Balances(_evmChainPrivateKey.address, usdcContractAddress);
+ }
return true;
} catch (e) {
@@ -539,7 +554,10 @@ abstract class EVMChainWalletBase
final address = walletAddresses.address;
if (address.isEmpty) return MoralisDiscoveryResult.empty;
- final chainName = EVMChainUtils.getDefaultTokenSymbol(selectedChainId).toLowerCase();
+ final chainName = EVMChainUtils.getMoralisChainName(selectedChainId);
+ if (chainName == null) {
+ return MoralisDiscoveryResult.empty;
+ }
final walletTokens = await _client.fetchWalletTokensFromMoralis(address, chainName);
if (walletTokens.isEmpty) return MoralisDiscoveryResult.empty;
@@ -787,7 +805,7 @@ abstract class EVMChainWalletBase
final isConnected = _client.connect(node);
if (!isConnected) {
- throw Exception("${walletInfo.type.name.toUpperCase()} Node connection failed");
+ throw ConnectionException("${walletInfo.type.name.toUpperCase()} Node connection failed");
}
_client.setListeners(_evmChainPrivateKey.address, _onNewTransaction);
@@ -846,8 +864,8 @@ abstract class EVMChainWalletBase
currency.title == _credentials.currency.title &&
(currency.tag == _credentials.currency.tag ||
currency.tag == _credentials.currency.title),
- orElse: () => throw Exception(
- 'Currency ${_credentials.currency.title} ${_credentials.currency.tag} is not accessible in the wallet, try to enable it first.'));
+ orElse: () => throw BadCurrencyException(
+ 'Currency ${_credentials.currency.title} ${_credentials.currency.tag} is not accessible in the wallet, try to enable it first.', _credentials.currency));
final currencyBalance = balance[transactionCurrency]!;
final toAddress = _credentials.outputs.first.isParsedAddress
@@ -983,6 +1001,7 @@ abstract class EVMChainWalletBase
56 => CryptoCurrency.bnb,
8453 => CryptoCurrency.baseEth,
42161 => CryptoCurrency.arbEth,
+ 4663 => CryptoCurrency.robEth,
_ => CryptoCurrency.eth,
};
@@ -1010,7 +1029,7 @@ abstract class EVMChainWalletBase
}
if (requiredNative > nativeBal) {
- throw Exception('Not enough ${nativeCurrency.title} to cover value and fees.');
+ throw TransactionGenerationException('Not enough ${nativeCurrency.title} to cover value and fees.');
}
final cleanAddress = sourceTokenAddress?.toLowerCase() ?? '';
@@ -1024,14 +1043,14 @@ abstract class EVMChainWalletBase
.where((k) => k is Erc20Token && k.contractAddress.toLowerCase() == cleanAddress);
if (matchingTokens.isEmpty) {
- throw Exception('Insufficient token balance (Token not found in wallet).');
+ throw TransactionGenerationException('Insufficient token balance (Token not found in wallet).');
}
final tokenKey = matchingTokens.first;
final tokenBalance = balance[tokenKey]?.available ?? Money.zero(tokenKey);
if (tokenBalance < Money(sourceTokenAmount, tokenKey)) {
- throw Exception('Insufficient ${tokenKey.symbol} balance to cover the transaction amount.');
+ throw TransactionGenerationException('Insufficient ${tokenKey.symbol} balance to cover the transaction amount.');
}
}
@@ -1056,7 +1075,7 @@ abstract class EVMChainWalletBase
useBlinkProtection: useBlinkProtection,
);
} catch (_) {
- throw Exception('Failed to create the transaction.');
+ throw TransactionGenerationException('Failed to create the transaction.');
}
}
@@ -1125,6 +1144,10 @@ abstract class EVMChainWalletBase
@override
Future<Map<String, EVMChainTransactionInfo>> fetchTransactions() async {
+ if (!await checkIfScanProviderIsEnabled()) {
+ return {};
+ }
+
final List<EVMChainTransactionModel> transactions = [];
final List<Future<List<EVMChainTransactionModel>>> erc20TokensTransactions = [];
@@ -1369,7 +1392,7 @@ abstract class EVMChainWalletBase
return EthPrivateKey.fromHex(privateKey);
}
- final seed = bip39.mnemonicToSeed(mnemonic!, passphrase: passphrase ?? '');
+ final seed = bip39MnemonicToSeed(mnemonic!, passphrase: passphrase ?? '');
final root = bip32.BIP32.fromSeed(seed);
@@ -1394,19 +1417,30 @@ abstract class EVMChainWalletBase
String? iconPath;
if ((token.iconPath == null || token.iconPath!.isEmpty) && !token.isPotentialScam) {
- try {
- iconPath = CryptoCurrency.all
- .firstWhere((element) => element.title.toUpperCase() == token.symbol.toUpperCase())
- .iconPath;
- } catch (_) {}
+ iconPath = EVMChainDefaultTokens.getDefaultIconPathByAddress(
+ selectedChainId,
+ token.contractAddress,
+ );
+
+ if (iconPath == null || iconPath.isEmpty) {
+ try {
+ iconPath = CryptoCurrency.all
+ .firstWhere((element) => element.title.toUpperCase() == token.symbol.toUpperCase())
+ .iconPath;
+ } catch (_) {}
+ }
} else if (!token.isPotentialScam) {
iconPath = token.iconPath;
}
final newToken = createNewErc20TokenObject(token, iconPath);
if (newToken.enabled) {
- balance[newToken] = await _client.fetchERC20Balances(_evmChainPrivateKey.address, newToken);
+ try {
+ balance[newToken] = await _client.fetchERC20Balances(_evmChainPrivateKey.address, newToken);
+ } catch (_) {
+ balance[newToken] = EVMChainERC20Balance(Money.zero(newToken));
+ }
await newToken.save();
} else {
@@ -1439,7 +1473,7 @@ abstract class EVMChainWalletBase
await transactionHistory.save();
}
- Future<Erc20Token?> getErc20Token(String contractAddress, String chainName) async {
+ Future<Erc20Token?> getErc20Token(String contractAddress, String? chainName) async {
try {
return await _client.getErc20Token(contractAddress, chainName);
} catch (e) {
@@ -1499,15 +1533,15 @@ abstract class EVMChainWalletBase
// Get chainId from wallet type, use saved chainId if available (for chain switching)
final defaultChainId = registry.getChainConfigByWalletType(walletInfo.type)?.chainId;
if (defaultChainId == null) {
- throw Exception('Chain config not found for wallet type: ${walletInfo.type}');
+ throw BadWalletTypeException('Chain config not found for wallet type: ${walletInfo.type}', walletInfo.type);
}
// Use saved chainId if available, otherwise default to wallet type's chainId
final chainId = savedChainId ?? defaultChainId;
final chainConfig = registry.getChainConfig(chainId);
if (chainConfig == null) {
- throw Exception('Chain config not found for chainId: $chainId');
+ throw BadChainIdException('Chain config not found for chainId: $chainId');
}
final client = EVMChainClientFactory.createClient(chainId);
@@ -1558,26 +1592,46 @@ abstract class EVMChainWalletBase
if (isEnabled) {
_updateTransactions();
_setTransactionUpdateTimer();
- } else {
- _transactionsUpdateTimer?.cancel();
}
}
@override
- Future<String> signMessage(String message, {String? address}) async {
- return bytesToHex(await _evmChainPrivateKey.signPersonalMessage(ascii.encode(message)));
- }
+ Future<String> signMessage(String message, {String? address}) async =>
+ bytesToHex(await _evmChainPrivateKey.signPersonalMessage(utf8.encode(message)));
@override
Future<bool> verifyMessage(String message, String signature, {String? address}) async {
- if (address == null) {
+ if (address == null || address.isEmpty) {
+ return false;
+ }
+
+ try {
+ final signatureBytes = hexToBytes(signature.trim().toLowerCase());
+ if (signatureBytes.length != 65) {
+ return false;
+ }
+
+ final messageBytes = utf8.encode(message);
+ final prefixedMessage = Uint8List.fromList(
+ ascii.encode("\x19Ethereum Signed Message:\n${messageBytes.length}") + messageBytes,
+ );
+ final v = signatureBytes[64] < 27 ? signatureBytes[64] + 27 : signatureBytes[64];
+ final publicKey = ecRecover(
+ keccak256(prefixedMessage),
+ MsgSignature(
+ bytesToUnsignedInt(signatureBytes.sublist(0, 32)),
+ bytesToUnsignedInt(signatureBytes.sublist(32, 64)),
+ v,
+ ),
+ );
+
+ final paddedPublicKey = Uint8List(64)..setRange(64 - publicKey.length, 64, publicKey);
+ final recoveredAddress = EthereumAddress.fromPublicKey(paddedPublicKey);
+ return recoveredAddress.hexNo0x == strip0x(address.trim().toLowerCase());
+ } catch (e) {
+ printV("Failed to verify EVM message signature: $e");
return false;
}
- final recoveredAddress = EthSigUtil.recoverPersonalSignature(
- message: ascii.encode(message),
- signature: signature,
- );
- return recoveredAddress.toUpperCase() == address.toUpperCase();
}
Web3Client? getWeb3Client() => _client.getWeb3Client();
### cw_evm/lib/evm_chain_wallet_service.dart
@@ -2,6 +2,7 @@ import "dart:io";
import 'package:bip39/bip39.dart' as bip39;
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import "package:cw_core/erc20_token.dart";
import "package:cw_core/imported_nft.dart";
import 'package:cw_core/pathForWallet.dart';
@@ -65,7 +66,7 @@ class EVMChainWalletService extends WalletService<
Future<void> saveBackup(String name, {WalletInfo? walletInfo}) async {
final info = walletInfo ?? await _findWalletByName(name);
if (info == null) {
- throw Exception("Wallet not found: $name");
+ throw WalletNotFoundException(name: name);
}
final backupWalletDirPath = await pathForWalletDir(name: "$name.backup", type: info.type);
@@ -81,7 +82,7 @@ class EVMChainWalletService extends WalletService<
Future<void> restoreWalletFilesFromBackup(String name) async {
final walletInfo = await _findWalletByName(name);
if (walletInfo == null) {
- throw Exception("Wallet not found: $name");
+ throw WalletNotFoundException(name: name);
}
final backupWalletDirPath = await pathForWalletDir(name: "$name.backup", type: walletInfo.type);
@@ -102,7 +103,7 @@ class EVMChainWalletService extends WalletService<
// Get chainId from wallet type
final chainConfig = _registry.getChainConfigByWalletType(walletInfo.type);
if (chainConfig == null) {
- throw Exception("Chain config not found for wallet type: ${walletInfo.type}");
+ throw BadWalletTypeException('Chain config not found for wallet type: ${walletInfo.type}', walletInfo.type);
}
final initialChainId = chainConfig.chainId;
@@ -130,16 +131,14 @@ class EVMChainWalletService extends WalletService<
);
await wallet.init();
- await wallet.addInitialTokens();
- await wallet.save();
return wallet;
}
@override
Future<EVMChainWallet> openWallet(String name, String password) async {
final walletInfo = await _findWalletByName(name);
if (walletInfo == null) {
- throw Exception("Wallet not found");
+ throw WalletNotFoundException(name: name);
}
try {
@@ -151,8 +150,6 @@ class EVMChainWalletService extends WalletService<
);
await wallet.init();
- await wallet.addInitialTokens();
- await wallet.save();
await saveBackup(name);
return wallet;
} catch (_) {
@@ -166,8 +163,6 @@ class EVMChainWalletService extends WalletService<
);
await wallet.init();
- await wallet.addInitialTokens();
- await wallet.save();
return wallet;
}
}
@@ -178,7 +173,7 @@ class EVMChainWalletService extends WalletService<
final currentWalletInfo = await _findWalletByName(currentName);
if (currentWalletInfo == null) {
- throw Exception("Wallet not found");
+ throw WalletNotFoundException(name: currentName);
}
final type = currentWalletInfo.type;
@@ -231,7 +226,7 @@ class EVMChainWalletService extends WalletService<
// Get chainId from wallet type
final chainConfig = _registry.getChainConfigByWalletType(walletInfo.type);
if (chainConfig == null) {
- throw Exception("Chain config not found for wallet type: ${walletInfo.type}");
+ throw BadWalletTypeException('Chain config not found for wallet type: ${walletInfo.type}', walletInfo.type);
}
final initialChainId = chainConfig.chainId;
@@ -257,8 +252,6 @@ class EVMChainWalletService extends WalletService<
);
await wallet.init();
- await wallet.addInitialTokens();
- await wallet.save();
return wallet;
}
@@ -272,7 +265,7 @@ class EVMChainWalletService extends WalletService<
// Get chainId from wallet type
final chainConfig = _registry.getChainConfigByWalletType(walletInfo.type);
if (chainConfig == null) {
- throw Exception("Chain config not found for wallet type: ${walletInfo.type}");
+ throw BadWalletTypeException('Chain config not found for wallet type: ${walletInfo.type}', walletInfo.type);
}
final initialChainId = chainConfig.chainId;
@@ -297,8 +290,6 @@ class EVMChainWalletService extends WalletService<
);
await wallet.init();
- await wallet.addInitialTokens();
- await wallet.save();
return wallet;
}
@@ -311,7 +302,7 @@ class EVMChainWalletService extends WalletService<
// Get chainId from wallet type
final chainConfig = _registry.getChainConfigByWalletType(walletInfo.type);
if (chainConfig == null) {
- throw Exception("Chain config not found for wallet type: ${walletInfo.type}");
+ throw BadWalletTypeException('Chain config not found for wallet type: ${walletInfo.type}', walletInfo.type);
}
final initialChainId = chainConfig.chainId;
@@ -335,8 +326,6 @@ class EVMChainWalletService extends WalletService<
);
await wallet.init();
- await wallet.addInitialTokens();
- await wallet.save();
return wallet;
}
@@ -354,7 +343,7 @@ class EVMChainWalletService extends WalletService<
Future<void> remove(String wallet) async {
final walletInfo = await _findWalletByName(wallet);
if (walletInfo == null) {
- throw Exception("Wallet not found");
+ throw WalletNotFoundException(name: wallet);
}
File(await pathForWalletDir(name: wallet, type: walletInfo.type)).delete(recursive: true);
@@ -381,7 +370,7 @@ class EVMChainWalletService extends WalletService<
final chainConfig = _registry.getChainConfigByWalletType(walletType);
if (chainConfig == null) {
- throw Exception("Chain config not found for wallet type: $walletType");
+ throw BadWalletTypeException('Chain config not found for wallet type: $walletType', walletInfo.type);
}
return EVMChainWallet(
### cw_evm/lib/evm_erc20_balance.dart
@@ -15,7 +15,7 @@ class EVMChainERC20Balance extends Balance {
final decoded = json.decode(jsonSource) as Map;
try {
- return EVMChainERC20Balance(Money(BigInt.parse(decoded["balanceInWei"]), currency));
+ return EVMChainERC20Balance(Money(BigInt.parse(decoded["balanceInWei"] as String), currency));
} catch (e) {
return EVMChainERC20Balance(Money.zero(currency));
}
### cw_evm/lib/hardware/evm_chain_bitbox_credentials.dart
@@ -1,23 +1,25 @@
-import 'dart:async';
-import 'dart:typed_data';
+import "dart:async";
+import "dart:typed_data";
-import 'package:bitbox_flutter/bitbox_manager.dart';
-import 'package:cw_core/hardware/device_not_connected_exception.dart' as exception;
-import 'package:web3dart/crypto.dart';
-import 'package:web3dart/web3dart.dart';
+import "package:bitbox_flutter/bitbox_flutter.dart";
+import "package:cw_core/hardware/device_not_connected_exception.dart" as exception;
+import "package:web3dart/crypto.dart";
+import "package:web3dart/web3dart.dart";
class EvmBitboxCredentials extends CredentialsWithKnownAddress {
- final String _address;
+ EvmBitboxCredentials(this._address);
- BitboxManager? bitboxManager;
+ BitboxConnection? bitboxManager;
String? derivationPath;
+ final String _address;
- EvmBitboxCredentials(this._address);
+ BitboxEthereum _getEthereum(int? chainId) =>
+ BitboxEthereum(bitboxManager!.ffi, chainId: chainId ?? 1);
@override
EthereumAddress get address => EthereumAddress.fromHex(_address);
- void setBitbox(BitboxManager connection, [String? derivationPath_]) {
+ void setBitbox(BitboxConnection connection, [String? derivationPath_]) {
bitboxManager = connection;
derivationPath = derivationPath_ ?? "m/44'/60'/0'/0/0";
}
@@ -27,15 +29,20 @@ class EvmBitboxCredentials extends CredentialsWithKnownAddress {
throw UnimplementedError("EvmLedgerCredentials.signToEcSignature");
@override
- Future<MsgSignature> signToSignature(Uint8List payload,
- {int? chainId, bool isEIP1559 = false}) async {
+ Future<MsgSignature> signToSignature(
+ Uint8List payload, {
+ int? chainId,
+ bool isEIP1559 = false,
+ }) async {
if (bitboxManager == null) {
throw exception.DeviceNotConnectedException();
}
- if (isEIP1559) payload = payload.sublist(1);
- final sig = await bitboxManager!
- .signETHRLPTransaction(chainId ?? 1, derivationPath!, bytesToHex(payload), isEIP1559);
+ if (isEIP1559) {
+ payload = payload.sublist(1);
+ }
+ final sig = await _getEthereum(chainId)
+ .signRLPTransaction(derivationPath!, bytesToHex(payload), isEIP1559);
final r = bytesToHex(sig.sublist(0, 32));
final s = bytesToHex(sig.sublist(32, 32 + 32));
@@ -66,9 +73,11 @@ class EvmBitboxCredentials extends CredentialsWithKnownAddress {
}
@override
- Future<Uint8List> signPersonalMessage(Uint8List payload, {int? chainId}) async {
- if (isNotConnected) throw exception.DeviceNotConnectedException();
- return await bitboxManager!.signETHMessage(chainId ?? 1, derivationPath!, payload);
+ Future<Uint8List> signPersonalMessage(Uint8List payload, {int? chainId}) {
+ if (isNotConnected) {
+ throw exception.DeviceNotConnectedException();
+ }
+ return _getEthereum(chainId).signMessage(derivationPath!, payload);
}
@override
### cw_evm/lib/hardware/evm_chain_bitbox_service.dart
@@ -1,13 +1,13 @@
-import 'dart:async';
+import "dart:async";
-import 'package:bitbox_flutter/bitbox_manager.dart';
-import 'package:cw_core/hardware/hardware_account_data.dart';
-import 'package:cw_core/hardware/hardware_wallet_service.dart';
+import "package:bitbox_flutter/bitbox_flutter.dart";
+import "package:cw_core/hardware/hardware_account_data.dart";
+import "package:cw_core/hardware/hardware_wallet_service.dart";
class EVMChainBitboxService extends HardwareWalletService {
EVMChainBitboxService(this.manager, {this.chainId = 1});
- final BitboxManager manager;
+ final BitboxConnection manager;
final int chainId;
@override
@@ -17,13 +17,16 @@ class EVMChainBitboxService extends HardwareWalletService {
for (final i in indexRange) {
final derivationPath = "m/44'/60'/0'/0/$i";
- final address = await manager.getETHAddress(chainId, derivationPath);
+ final address =
+ await BitboxEthereum(manager.ffi, chainId: chainId).getAddress(derivationPath);
- accounts.add(HardwareAccountData(
- address: address,
- accountIndex: i,
- derivationPath: derivationPath,
- ));
+ accounts.add(
+ HardwareAccountData(
+ address: address,
+ accountIndex: i,
+ derivationPath: derivationPath,
+ ),
+ );
}
return accounts;
### cw_evm/lib/hardware/evm_chain_ledger_credentials.dart
@@ -1,7 +1,9 @@
import 'dart:async';
import 'dart:typed_data';
-import 'package:cw_core/hardware/device_not_connected_exception.dart' as exception;
+import "package:cw_core/exceptions/cake_exception.dart";
+import 'package:cw_core/hardware/device_not_connected_exception.dart'
+ as exception;
import 'package:cw_core/utils/print_verbose.dart';
import 'package:ledger_ethereum/ledger_ethereum.dart';
import 'package:ledger_flutter_plus/ledger_flutter_plus.dart';
@@ -71,7 +73,7 @@ class EvmLedgerCredentials extends CredentialsWithKnownAddress {
final sig = await ethereumLedgerApp!.signMessage(payload);
- if (sig.isEmpty) throw Exception("No Signature received from device!");
+ if (sig.isEmpty) throw HardwareWalletResponseException("No Signature received from device!");
final r = sig.sublist(1, 1 + 32);
final s = sig.sublist(1 + 32, 1 + 32 + 32);
### cw_evm/lib/hardware/evm_chain_trezor_credentials.dart
@@ -41,14 +41,14 @@ class EvmTrezorCredentials extends CredentialsWithKnownAddress {
TrezorEthereumTransaction tx;
if (isEIP1559) {
- final chainId = data[0][0];
- final nonce = bytesToHex(data[1], include0x: true);
- final maxPriorityFeePerGas = bytesToHex(data[2], include0x: true);
- final maxFeePerGas = bytesToHex(data[3], include0x: true);
- final maxGas = bytesToHex(data[4], include0x: true);
- final to = bytesToHex(data[5], include0x: true);
- final value = bytesToHex(data[6], include0x: true);
- final txData = bytesToHex(data[7], include0x: true);
+ final chainId = data[0][0] as int;
+ final nonce = bytesToHex(data[1] as List<int>, include0x: true);
+ final maxPriorityFeePerGas = bytesToHex(data[2] as List<int>, include0x: true);
+ final maxFeePerGas = bytesToHex(data[3] as List<int>, include0x: true);
+ final maxGas = bytesToHex(data[4] as List<int>, include0x: true);
+ final to = bytesToHex(data[5] as List<int>, include0x: true);
+ final value = bytesToHex(data[6] as List<int>, include0x: true);
+ final txData = bytesToHex(data[7] as List<int>, include0x: true);
tx = TrezorEthereumTransaction(
to: to,
@@ -61,12 +61,12 @@ class EvmTrezorCredentials extends CredentialsWithKnownAddress {
data: txData,
);
} else {
- final nonce = bytesToHex(data[0]);
- final gasPrice = bytesToHex(data[1]);
- final maxGas = bytesToHex(data[2]);
- final to = bytesToHex(data[3]);
- final value = bytesToHex(data[4]);
- final txData = bytesToHex(data[5]);
+ final nonce = bytesToHex(data[0] as List<int>);
+ final gasPrice = bytesToHex(data[1] as List<int>);
+ final maxGas = bytesToHex(data[2] as List<int>);
+ final to = bytesToHex(data[3] as List<int>);
+ final value = bytesToHex(data[4] as List<int>);
+ final txData = bytesToHex(data[5] as List<int>);
tx = TrezorEthereumTransaction(
to: to,
value: value,
### cw_evm/lib/tokens/robinhood_tokens.dart
@@ -0,0 +1,409 @@
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/currency_groups.dart";
+import "package:cw_core/erc20_token.dart";
+
+class RobinhoodTokens {
+ static List<Erc20Token> get tokens {
+ final tokens = [
+ Erc20Token(
+ name: "Global Dollar",
+ symbol: "USDG",
+ contractAddress: "0x5fc5360d0400a0fd4f2af552add042d716f1d168",
+ decimal: 6,
+ enabled: true,
+ iconPath: "assets/images/usdg_icon.png",
+ groups: const {CurrencyGroups.stablecoin},
+ ),
+ Erc20Token(
+ name: "Ethena USDe",
+ symbol: "USDe",
+ contractAddress: "0x5d3a1ff2b6bab83b63cd9ad0787074081a52ef34",
+ decimal: 18,
+ enabled: true,
+ groups: const {CurrencyGroups.stablecoin},
+ ),
+ Erc20Token(
+ name: "WETH",
+ symbol: "WETH",
+ contractAddress: "0x0bd7d308f8e1639fab988df18a8011f41eacad73",
+ decimal: 18,
+ enabled: false,
+ ),
+ Erc20Token(
+ name: "Apple",
+ symbol: "AAPL",
+ contractAddress: "0xaf3d76f1834a1d425780943c99ea8a608f8a93f9",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/apple.webp",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "AMD",
+ symbol: "AMD",
+ contractAddress: "0x86923f96303d656e4aa86d9d42d1e57ad2023fdc",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/amd.png",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Amazon",
+ symbol: "AMZN",
+ contractAddress: "0x12f190a9f9d7d37a250758b26824b97ce941bf54",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/amznx.webp",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "ASML Holding NV",
+ symbol: "ASML",
+ contractAddress: "0x47f93d52cbec7c6d2cfc080e154002370a60daea",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/asml.png",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Broadcom",
+ symbol: "AVGO",
+ contractAddress: "0x156e175dd063a8ce274c50654ef40e0032b3fbcf",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/avgox.webp",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Alibaba",
+ symbol: "BABA",
+ contractAddress: "0xad25ac6c84d497db898fa1e8387bf6af3532a1c4",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/baba.png",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Coinbase",
+ symbol: "COIN",
+ contractAddress: "0x6330d8c3178a418788df01a47479c0ce7ccf450b",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/coinx.webp",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Costco",
+ symbol: "COST",
+ contractAddress: "0x4ea005168d7f09a7a0ba9d1def21a479950e44c2",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/cost.png",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Circle Internet Group",
+ symbol: "CRCL",
+ contractAddress: "0xdf0992e440dd0be65bd8439b609d6d4366bf1cb5",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/crclx.webp",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Datadog",
+ symbol: "DDOG",
+ contractAddress: "0x27c99fbde9d0d2aa4f4bfb4943f237843ddf6958",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/ddog.png",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Dell",
+ symbol: "DELL",
+ contractAddress: "0x941ae714ec6d8130c7b75d67160ca08f1e7d11dd",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/dell.png",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Ford Motor",
+ symbol: "F",
+ contractAddress: "0x25c288e6d899b9bc30160965ad9644c67e73be0c",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/f.png",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "GameStop",
+ symbol: "GME",
+ contractAddress: "0x1b0e319c6a659f002271b69db8a7df2f911c153e",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/gmex.webp",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Alphabet Class A",
+ symbol: "GOOGL",
+ contractAddress: "0x2e0847e8910a9732eb3fb1bb4b70a580adad4fe3",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/googlx.webp",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Intel",
+ symbol: "INTC",
+ contractAddress: "0xc72b96e0e48ecd4dc75e1e45396e26300bc39681",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/intcx.webp",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Intuit",
+ symbol: "INTU",
+ contractAddress: "0x56d23bee5f41a7120170b0c603dae30128e460e9",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/intu.png",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Eli Lilly",
+ symbol: "LLY",
+ contractAddress: "0x8005d266423c7ea827372c9c864491e5786600ea",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/llyx.webp",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Lululemon",
+ symbol: "LULU",
+ contractAddress: "0x4e62068525ab11fe768e29dfd00ef909b9803016",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/lulu.png",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Meta Platforms",
+ symbol: "META",
+ contractAddress: "0xc0d6457c16cc70d6790dd43521c899c87ce02f35",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/metax.webp",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Marvell Technology",
+ symbol: "MRVL",
+ contractAddress: "0x62fd0668e10d8b72339be2dcf7643001688ff13b",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/mrvlx.webp",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Microsoft",
+ symbol: "MSFT",
+ contractAddress: "0xe93237c50d904957cf27e7b1133b510c669c2e74",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/msftx.webp",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Strategy Inc.",
+ symbol: "MSTR",
+ contractAddress: "0xec262a75e413fafd0df80480274532c79d42da09",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/mstrx.webp",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Micron Technology",
+ symbol: "MU",
+ contractAddress: "0xff080c8ce2e5feadaca0da81314ae59d232d4afd",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/mu.png",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Netflix",
+ symbol: "NFLX",
+ contractAddress: "0xe0444ef8bf4ed74f74fd73686e2ddf4c1c5591e8",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/nflxx.webp",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Nu",
+ symbol: "NU",
+ contractAddress: "0x408c14038a04f7bd235329e26d2bf569ee20e250",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/nu.png",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "NVIDIA",
+ symbol: "NVDA",
+ contractAddress: "0xd0601ce157db5bdc3162bbac2a2c8af5320d9eec",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/nvdax.webp",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Oracle",
+ symbol: "ORCL",
+ contractAddress: "0xb0992820e760d836549ba69bc7598b4af75dee03",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/orclx.webp",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Palantir Technologies",
+ symbol: "PLTR",
+ contractAddress: "0x894e1ec2d74ffe5aef8dc8a9e84686accb964f2a",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/pltrx.webp",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Qualcomm",
+ symbol: "QCOM",
+ contractAddress: "0x0f17206447090e464c277571124dd2688e48aea9",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/qcom.png",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Invesco QQQ",
+ symbol: "QQQ",
+ contractAddress: "0xd5f3879160bc7c32ebb4dc785f8a4f505888de68",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/qqqx.webp",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Rivian Automotive",
+ symbol: "RIVN",
+ contractAddress: "0xb1bf26c1d20ff267a4f93550d1e0d06ac40a114b",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/rivn.png",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Shopify",
+ symbol: "SHOP",
+ contractAddress: "0xf53f66751b1eff985311b693531e3290f600c410",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/shop.png",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "SoFi Technologies",
+ symbol: "SOFI",
+ contractAddress: "0x98e75885157c80992a8d41b696d8c9c6fb30a926",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/sofi.png",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "SPDR S&P 500 ETF Trust",
+ symbol: "SPY",
+ contractAddress: "0x117cc2133c37b721f49de2a7a74833232b3b4c0c",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/spyx.webp",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Tesla",
+ symbol: "TSLA",
+ contractAddress: "0x322f0929c4625ed5bad873c95208d54e1c003b2d",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/tslax.webp",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Taiwan Semiconductor Manufacturing",
+ symbol: "TSM",
+ contractAddress: "0x58ffe4a942d3885baa22d7520691f611ef09e7aa",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/tsm.png",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Take-Two Interactive Software",
+ symbol: "TTWO",
+ contractAddress: "0x5e81213613b6b86eab4c6c50d718d34359459786",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/ttwo.png",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "UPS",
+ symbol: "UPS",
+ contractAddress: "0xf23250dac154d05bb671cb0d0ebef3c635c79ce2",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/ups.png",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "Workday",
+ symbol: "WDAY",
+ contractAddress: "0x82da4646242e1d962e96e932269dc644c94a9caa",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/wday.png",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ Erc20Token(
+ name: "ExxonMobil Holdings Corporation",
+ symbol: "XOM",
+ contractAddress: "0xf9b46d3d1b22199d4d1025a9cedb540a33f1a2d5",
+ decimal: 18,
+ enabled: false,
+ iconPath: "assets/images/stocks/xomx.webp",
+ groups: const {CurrencyGroups.tokenizedStock},
+ ),
+ ];
+
+ return tokens.map((token) {
+ String? iconPath;
+ if (token.iconPath?.isEmpty ?? true) {
+ try {
+ iconPath = CryptoCurrency.all
+ .firstWhere((element) => element.title.toUpperCase() == token.symbol.toUpperCase())
+ .iconPath;
+ } catch (_) {}
+ } else {
+ iconPath = token.iconPath;
+ }
+
+ return Erc20Token.copyWith(token, icon: iconPath, tag: "ROB");
+ }).toList();
+ }
+}
### cw_evm/lib/usdt0/usdt0_service.dart
@@ -1,5 +1,6 @@
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/erc20_token.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/pending_transaction.dart';
import 'package:cw_evm/contract/erc20.dart';
import 'package:cw_evm/contract/oft.dart';
@@ -23,9 +24,15 @@ class USDT0Service {
final oftAddress = USDT0Config.getOftContractAddress(sourceChainId);
final dstEid = USDT0Config.getEndpointId(destinationChainId);
- if (oftAddress == null || dstEid == null) {
- throw Exception(
- 'USDT0 not supported for chain $sourceChainId -> $destinationChainId',
+ if (oftAddress == null) {
+ throw BadChainIdException(
+ 'USDT0 not supported for chain $sourceChainId'
+ );
+ }
+
+ if(dstEid == null) {
+ throw BadChainIdException(
+ 'USDT0 not supported for chain $destinationChainId'
);
}
@@ -58,9 +65,15 @@ class USDT0Service {
final oftAddress = USDT0Config.getOftContractAddress(sourceChainId);
final dstEid = USDT0Config.getEndpointId(destinationChainId);
- if (oftAddress == null || dstEid == null) {
- throw Exception(
- 'USDT0 not supported for chain $sourceChainId -> $destinationChainId',
+ if (oftAddress == null) {
+ throw BadChainIdException(
+ 'USDT0 not supported for chain $sourceChainId'
+ );
+ }
+
+ if(dstEid == null) {
+ throw BadChainIdException(
+ 'USDT0 not supported for chain $destinationChainId'
);
}
### cw_evm/lib/utils/evm_chain_utils.dart
@@ -3,19 +3,22 @@ import "package:web3dart/web3dart.dart" show EtherAmount, EtherUnit;
/// Utility class for chain-specific EVM chain operations
class EVMChainUtils {
- static int getTotalPriorityFee(EVMChainTransactionPriority priority, int chainId) => switch (chainId) {
- 1 => _ethereumPriorityFee(priority),
- 137 => _polygonPriorityFee(priority),
- 8453 => _basePriorityFee(priority),
- 56 => _ethereumPriorityFee(priority),
- 42161 => 0, // Arbitrum doesn't use priority fees
- _ => _ethereumPriorityFee(priority),
- };
+ static int getTotalPriorityFee(EVMChainTransactionPriority priority, int chainId) =>
+ switch (chainId) {
+ 1 => _ethereumPriorityFee(priority),
+ 137 => _polygonPriorityFee(priority),
+ 8453 => _basePriorityFee(priority),
+ 56 => _ethereumPriorityFee(priority),
+ 42161 => 0, // Arbitrum doesn't use priority fees
+ 4663 => 0, // Robinhood Chain (Arbitrum Orbit) doesn't use priority fees
+ _ => _ethereumPriorityFee(priority),
+ };
static bool hasPriorityFee(int chainId) => switch (chainId) {
- 42161 => false, // Arbitrum doesn't use priority fees
- _ => true,
- };
+ 42161 => false, // Arbitrum doesn't use priority fees
+ 4663 => false, // Robinhood Chain (Arbitrum Orbit) doesn't use priority fees
+ _ => true,
+ };
static int computeBufferedMaxFeePerGasWei({
required int? gasBaseFee,
@@ -34,52 +37,67 @@ class EVMChainUtils {
}
static String getTransactionHistoryFileName(int chainId) => switch (chainId) {
- 1 => "transactions.json", // Ethereum
- 137 => "polygon_transactions.json",
- 8453 => "base_transactions.json",
- 42161 => "arbitrum_transactions.json",
- 56 => "bsc_transactions.json",
- _ => "transactions_$chainId.json", // Generic format for other chains
- };
+ 1 => "transactions.json", // Ethereum
+ 137 => "polygon_transactions.json",
+ 8453 => "base_transactions.json",
+ 42161 => "arbitrum_transactions.json",
+ 56 => "bsc_transactions.json",
+ 4663 => "robinhood_transactions.json",
+ _ => "transactions_$chainId.json", // Generic format for other chains
+ };
/// Get scan provider preference key for a wallet type
static String getScanProviderPreferenceKey(int chainId) => switch (chainId) {
- 1 => "use_etherscan",
- 137 => "use_polygonscan",
- 8453 => "use_basescan",
- 42161 => "use_arbiscan",
- 56 => "use_bscscan",
- _ => "use_etherscan",
- };
+ 1 => "use_etherscan",
+ 137 => "use_polygonscan",
+ 8453 => "use_base_scan",
+ 42161 => "use_arbitrum_scan",
+ 56 => "use_bscscan",
+ 4663 => "use_robinhood_scan",
+ _ => "use_etherscan",
+ };
static String getDefaultTokenTag(int chainId) => switch (chainId) {
- 1 => "ETH",
- 137 => "POL",
- 8453 => "BASE",
- 42161 => "ARB",
- 56 => "BSC",
- _ => "ETH",
- };
+ 1 => "ETH",
+ 137 => "POL",
+ 8453 => "BASE",
+ 42161 => "ARB",
+ 56 => "BSC",
+ 4663 => "ROB",
+ _ => "ETH",
+ };
static String getFeeCurrency(int chainId) => switch (chainId) {
- 1 => "ETH",
- 137 => "POL",
- 8453 => "ETH",
- 42161 => "ETH",
- 56 => "BNB",
- _ => "ETH",
- };
+ 1 => "ETH",
+ 137 => "POL",
+ 8453 => "ETH",
+ 42161 => "ETH",
+ 56 => "BNB",
+ 4663 => "ETH",
+ _ => "ETH",
+ };
static String getDefaultTokenSymbol(int chainId) => switch (chainId) {
- 1 => "ETH",
- 137 => "POL",
- 8453 => "BASE",
- 42161 => "ARBITRUM",
- 56 => "BSC",
- _ => "ETH",
- };
+ 1 => "ETH",
+ 137 => "POL",
+ 8453 => "BASE",
+ 42161 => "ARBITRUM",
+ 56 => "BSC",
+ 4663 => "ETH",
+ _ => "ETH",
+ };
- static int _ethereumPriorityFee(EVMChainTransactionPriority priority) => EtherAmount.fromInt(EtherUnit.gwei, priority.tip).getInWei.toInt();
+ static String? getMoralisChainName(int chainId) => switch (chainId) {
+ 1 => "eth",
+ 137 => "polygon",
+ 8453 => "base",
+ 42161 => "arbitrum",
+ 56 => "bsc",
+ _ => null,
+ };
+
+ static int _ethereumPriorityFee(EVMChainTransactionPriority priority) =>
+ EtherAmount.fromInt(EtherUnit.gwei, priority.tip).getInWei.toInt();
// Polygon priority fee calculation (minimum 25 gwei + additional based on priority)
static int _polygonPriorityFee(EVMChainTransactionPriority priority) {
@@ -98,9 +116,10 @@ class EVMChainUtils {
}
static int _basePriorityFee(EVMChainTransactionPriority priority) => switch (priority) {
- EVMChainTransactionPriority.fast => EtherAmount.fromInt(EtherUnit.mwei, 5).getInWei.toInt(),
- EVMChainTransactionPriority.medium => EtherAmount.fromInt(EtherUnit.mwei, 3).getInWei.toInt(),
- EVMChainTransactionPriority.slow => EtherAmount.fromInt(EtherUnit.mwei, 1).getInWei.toInt(),
- _ => EtherAmount.fromInt(EtherUnit.mwei, 1).getInWei.toInt(),
- };
+ EVMChainTransactionPriority.fast => EtherAmount.fromInt(EtherUnit.mwei, 5).getInWei.toInt(),
+ EVMChainTransactionPriority.medium =>
+ EtherAmount.fromInt(EtherUnit.mwei, 3).getInWei.toInt(),
+ EVMChainTransactionPriority.slow => EtherAmount.fromInt(EtherUnit.mwei, 1).getInWei.toInt(),
+ _ => EtherAmount.fromInt(EtherUnit.mwei, 1).getInWei.toInt(),
+ };
}
### cw_evm/lib/utils/rlp_decode.dart
@@ -1,11 +1,16 @@
import 'dart:typed_data';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:web3dart/crypto.dart';
/// RLP Decode
///
/// Adapted from https://github.com/ethereumjs/ethereumjs-monorepo/tree/master/packages/rlp
+class RlpDecodeException extends CakeException {
+ const RlpDecodeException(super.message);
+}
+
class _Decoded {
Uint8List remainder;
List data;
@@ -14,7 +19,7 @@ class _Decoded {
}
int _decodeLength(Uint8List v) {
- if (v[0] == 0) throw Exception('invalid RLP: extra zeros');
+ if (v[0] == 0) throw RlpDecodeException('invalid RLP: extra zeros');
return int.parse(bytesToHex(v), radix: 16);
}
@@ -33,7 +38,7 @@ _Decoded _decode(Uint8List input) {
final data = firstByte == 0x80 ? Uint8List(0) : input.sublist(1, length);
if (length == 2 && data[0] < 0x80) {
- throw Exception('invalid RLP encoding: invalid prefix, single byte < 0x80 are not prefixed');
+ throw RlpDecodeException('invalid RLP encoding: invalid prefix, single byte < 0x80 are not prefixed');
}
return _Decoded(data, input.sublist(length));
@@ -42,12 +47,12 @@ _Decoded _decode(Uint8List input) {
// followed by the length, followed by the string
final lLength = firstByte - 0xb6;
if (input.length - 1 < lLength) {
- throw Exception('invalid RLP: not enough bytes for string length');
+ throw RlpDecodeException('invalid RLP: not enough bytes for string length');
}
final length = _decodeLength(input.sublist(1, lLength));
if (length <= 55) {
- throw Exception('invalid RLP: expected string length to be greater than 55');
+ throw RlpDecodeException('invalid RLP: expected string length to be greater than 55');
}
final data = input.sublist(lLength, length + lLength);
@@ -71,12 +76,12 @@ _Decoded _decode(Uint8List input) {
final length = _decodeLength(input.sublist(1, lLength));
if (length < 56) {
- throw Exception('invalid RLP: encoded list too short');
+ throw RlpDecodeException('invalid RLP: encoded list too short');
}
final totalLength = lLength + length;
if (totalLength > input.length) {
- throw Exception('invalid RLP: total length is larger than the data');
+ throw RlpDecodeException('invalid RLP: total length is larger than the data');
}
var innerRemainder = input.sublist(lLength, totalLength);
@@ -95,7 +100,7 @@ _Decoded _decode(Uint8List input) {
List decode(Uint8List input) {
final decoded = _decode(input);
- if (decoded.remainder.isNotEmpty) throw Exception('invalid RLP: remainder must be zero');
+ if (decoded.remainder.isNotEmpty) throw RlpDecodeException('invalid RLP: remainder must be zero');
return decoded.data;
}
### cw_evm/pubspec.yaml
@@ -2,7 +2,6 @@ name: cw_evm
description: A new Flutter package project.
version: 0.0.1
publish_to: none
-author: Cake Wallet
homepage: https://cakewallet.com
environment:
@@ -13,14 +12,9 @@ dependencies:
flutter:
sdk: flutter
web3dart: ^2.7.1
- eth_sig_util: ^0.0.9
- erc20: ^1.0.1
bip39: ^1.0.6
bip32: ^2.0.0
hex: ^0.2.0
- http: ^1.1.0
- hive: ^2.2.3
- collection: ^1.17.1
path: ^1.8.0
shared_preferences: ^2.0.15
mobx: ^2.0.7+4
@@ -33,7 +27,9 @@ dependencies:
path: packages/ledger-ethereum
ref: f4761cd5171d4c1e2e42fd3298261650539fb2db
bitbox_flutter:
- path: ../scripts/bitbox_flutter
+ git:
+ url: https://github.com/cake-tech/bitbox_flutter.git
+ ref: 3d1c607f14c6d5bace2971ec4c10b5201053cc56
trezor_connect:
git:
url: https://github.com/cake-tech/trezor_connect
### cw_evm/test/robinhood_tokens_test.dart
@@ -0,0 +1,91 @@
+import "package:cw_core/currency_groups.dart";
+import "package:cw_evm/tokens/robinhood_tokens.dart";
+import "package:cw_evm/utils/evm_chain_utils.dart";
+import "package:flutter_test/flutter_test.dart";
+
+void main() {
+ group("RobinhoodTokens integrity", () {
+ final tokens = RobinhoodTokens.tokens;
+ final addressPattern = RegExp(r"^0x[0-9a-f]{40}$");
+
+ test("token list is non-empty", () => expect(tokens.isNotEmpty, isTrue));
+
+ test("every contract address is a lowercased 0x-prefixed 40-hex-char address", () {
+ for (final token in tokens) {
+ expect(
+ addressPattern.hasMatch(token.contractAddress),
+ isTrue,
+ reason: "bad address for ${token.symbol}: ${token.contractAddress}",
+ );
+ }
+ });
+
+ test("every token has a non-empty name and symbol", () {
+ for (final token in tokens) {
+ expect(token.name.trim(), isNotEmpty, reason: "empty name for ${token.contractAddress}");
+ expect(
+ token.symbol.trim(),
+ isNotEmpty,
+ reason: "empty symbol for ${token.contractAddress}",
+ );
+ }
+ });
+
+ test("every decimal is within the 0..18 range", () {
+ for (final token in tokens) {
+ expect(
+ token.decimal,
+ inInclusiveRange(0, 18),
+ reason: "bad decimal for ${token.symbol}: ${token.decimal}",
+ );
+ }
+ });
+
+ test("no duplicate contract addresses", () {
+ final seen = <String>{};
+ for (final token in tokens) {
+ final addr = token.contractAddress.toLowerCase();
+ expect(seen.add(addr), isTrue, reason: "duplicate address $addr (${token.symbol})");
+ }
+ });
+
+ test("USDG is the 6-decimal stablecoin and is enabled by default", () {
+ final usdg = tokens.firstWhere((t) => t.symbol == "USDG");
+ expect(usdg.decimal, 6);
+ expect(usdg.enabled, isTrue);
+ });
+
+ test("tokenized stock tokens exist and ship disabled", () {
+ final stocks = tokens.where((t) => t.groups.contains(CurrencyGroups.tokenizedStock)).toList();
+ expect(stocks, isNotEmpty);
+ expect(stocks.every((t) => !t.enabled), isTrue);
+ });
+ });
+
+ group("EVMChainUtils Robinhood chain params", () {
+ test("getMoralisChainName is null for Robinhood (Moralis does not index 4663)", () {
+ expect(EVMChainUtils.getMoralisChainName(4663), isNull);
+ });
+
+ test("getMoralisChainName maps supported chains to Moralis slugs", () {
+ expect(EVMChainUtils.getMoralisChainName(1), "eth");
+ expect(EVMChainUtils.getMoralisChainName(137), "polygon");
+ expect(EVMChainUtils.getMoralisChainName(8453), "base");
+ expect(EVMChainUtils.getMoralisChainName(42161), "arbitrum");
+ expect(EVMChainUtils.getMoralisChainName(56), "bsc");
+ });
+
+ test("getMoralisChainName is null for unknown chains", () {
+ expect(EVMChainUtils.getMoralisChainName(999999), isNull);
+ });
+
+ test("Robinhood is an Orbit chain with no priority fee", () {
+ expect(EVMChainUtils.hasPriorityFee(4663), isFalse);
+ });
+
+ test("Robinhood default token tag is ROB and fee currency is ETH", () {
+ expect(EVMChainUtils.getDefaultTokenTag(4663), "ROB");
+ expect(EVMChainUtils.getFeeCurrency(4663), "ETH");
+ });
+ });
+}
### cw_monero/lib/api/exceptions/wallet_creation_exception.dart
@@ -1,8 +0,0 @@
-class WalletCreationException implements Exception {
- WalletCreationException({required this.message});
-
- final String message;
-
- @override
- String toString() => message;
-}
### cw_monero/lib/api/structs/pending_transaction.dart
@@ -4,11 +4,13 @@ class PendingTransactionDescription {
required this.fee,
required this.hash,
required this.hex,
- required this.pointerAddress});
+ required this.pointerAddress,
+ required this.txCount});
final int amount;
final int fee;
final String hash;
final String hex;
final int pointerAddress;
+ final int txCount;
}
### cw_monero/lib/api/transaction_history.dart
@@ -132,12 +132,15 @@ Future<Transaction> getTransaction(String txId) async {
return txCache[currentWallet!.ffiAddress()]![txId]!;
}
await txHistoryMutex.acquire();
- final tx = txhistory!.transactionById(txId);
- final txDart = Transaction(txInfo: tx);
- txCache[currentWallet!.ffiAddress()] ??= {};
- txCache[currentWallet!.ffiAddress()]![txId] = txDart;
- txHistoryMutex.release();
- return txDart;
+ try {
+ final tx = txhistory!.transactionById(txId);
+ final txDart = Transaction(txInfo: tx);
+ txCache[currentWallet!.ffiAddress()] ??= {};
+ txCache[currentWallet!.ffiAddress()]![txId] = txDart;
+ return txDart;
+ } finally {
+ txHistoryMutex.release();
+ }
}
Future<PendingTransactionDescription> createTransactionSync(
@@ -149,6 +152,11 @@ Future<PendingTransactionDescription> createTransactionSync(
List<String> preferredInputs = const []}) async {
final amt = amount == null ? 0 : currentWallet!.amountFromString(amount);
+ if (amount != null && amt == 0) {
+ throw MoneroTransactionCreationException(
+ 'Refusing to create a transaction with a zero amount: 0 is the sweep-all ');
+ }
+
final waddr = currentWallet!.ffiAddress();
// force reconnection in case the os killed the connection?
@@ -211,6 +219,7 @@ Future<PendingTransactionDescription> createTransactionSync(
fee: rFee,
hash: rHash,
hex: rHex,
+ txCount: pendingTx.txCount(),
pointerAddress: pendingTx.ffiAddress(),
);
}
@@ -255,6 +264,7 @@ Future<PendingTransactionDescription> createTransactionMultDest(
hash: tx.txid(''),
hex: tx.hex(''),
pointerAddress: tx.ffiAddress(),
+ txCount: tx.txCount(),
);
}
### cw_monero/lib/api/wallet.dart
@@ -10,6 +10,7 @@ import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_monero/api/account_list.dart';
import 'package:cw_monero/api/exceptions/setup_wallet_exception.dart';
import 'package:cw_monero/api/get_all_unspent.dart';
+import "package:cw_monero/exceptions/monero_exceptions.dart";
import 'package:monero/monero.dart' as monero;
import 'package:mutex/mutex.dart';
import 'package:polyseed/polyseed.dart';
@@ -309,7 +310,7 @@ void setPasswordSync(String password) {
final status = currentWallet!.status();
if (status != 0) {
- throw Exception(currentWallet!.errorString());
+ throw MoneroWalletException(currentWallet!.errorString());
}
}
@@ -472,7 +473,7 @@ Map<String, dynamic> getWalletCacheDebug() {
monero.MONERO_Wallet_serializeCacheToJson(Pointer.fromAddress(currentWallet!.ffiAddress()));
final blob = json.decode(jsonString);
blob['cake:unspent'] = getAllUnspent();
- return blob;
+ return blob as Map<String, dynamic>;
} catch (e) {
return {
"error": e.toString(),
### cw_monero/lib/api/wallet_manager.dart
@@ -2,6 +2,7 @@ import 'dart:ffi';
import 'dart:io';
import 'dart:isolate';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_monero/api/account_list.dart';
import 'package:cw_monero/api/exceptions/wallet_creation_exception.dart';
@@ -91,7 +92,7 @@ void createWallet(
int status = newW.status();
if (status != 0) {
- throw WalletCreationException(message: newW.errorString());
+ throw WalletCreationException(newW.errorString());
}
newW.store(path: path);
setupBackgroundSync(password, newW);
@@ -101,7 +102,6 @@ void createWallet(
currentWallet!.setCacheAttribute(key: "cakewallet.passphrase", value: passphrase);
currentWallet!.store(path: path);
openedWalletsByPath[path] = currentWallet!;
- _lastOpenedWallet = path;
}
bool isWalletExist({required String path}) {
@@ -147,7 +147,6 @@ void restoreWalletFromSeedSync(
openedWalletsByPath[path] = currentWallet!;
currentWallet!.store(path: path);
- _lastOpenedWallet = path;
}
void storePassphrase({required String path, required String passphrase}) {
@@ -219,8 +218,12 @@ void restoreWalletFromKeys(
currentWallet = newW;
+ if (restoreHeight > 0) {
+ setRefreshFromBlockHeight(height: restoreHeight);
+ currentWallet!.store(path: path);
+ }
+
openedWalletsByPath[path] = currentWallet!;
- _lastOpenedWallet = path;
}
// English only, because normalization.
@@ -303,18 +306,19 @@ void restoreWalletFromSpendKeySync(
currentWallet = newW;
+ if (restoreHeight > 0) {
+ setRefreshFromBlockHeight(height: restoreHeight);
+ currentWallet!.store(path: path);
+ }
currentWallet!.setCacheAttribute(key: "cakewallet.seed", value: seed);
storeSync();
setupBackgroundSync(password, currentWallet!);
openedWalletsByPath[path] = currentWallet!;
- _lastOpenedWallet = path;
}
-String _lastOpenedWallet = "";
-
Future<void> restoreWalletFromHardwareWallet(
{required String path,
required String password,
@@ -338,8 +342,10 @@ Future<void> restoreWalletFromHardwareWallet(
}
currentWallet = newW;
+
+ setRefreshFromBlockHeight(height: restoreHeight);
+
currentWallet!.store(path: path);
- _lastOpenedWallet = path;
openedWalletsByPath[path] = currentWallet!;
}
@@ -351,72 +357,70 @@ Future<void> loadWallet({required String path, required String password, int net
currentWallet = openedWalletsByPath[path]!;
return;
}
- if (currentWallet == null || path != _lastOpenedWallet) {
- if (currentWallet != null) {
- final addr = currentWallet!.ffiAddress();
- Isolate.run(() {
- monero.Wallet_store(Pointer.fromAddress(addr));
- });
- }
- txhistory = null;
- /// Get the device type
- /// 0: Software Wallet
- /// 1: Ledger
- /// 2: Trezor
- var deviceType = 0;
+ if (currentWallet != null) {
+ final addr = currentWallet!.ffiAddress();
+ Isolate.run(() {
+ monero.Wallet_store(Pointer.fromAddress(addr));
+ });
+ }
+ txhistory = null;
- if (Platform.isAndroid || Platform.isIOS) {
- deviceType = wmPtr.queryWalletDevice(
- keysFileName: "$path.keys",
- password: password,
- kdfRounds: 1,
- );
- final status = wmPtr.errorString();
- if (status != "") {
- printV("loadWallet:" + status);
- // This is most likely closeWallet call leaking error. This is fine.
- if (status.contains("failed to save file")) {
- printV("loadWallet: error leaked: $status");
- deviceType = 0;
- } else {
- throw WalletOpeningException(message: status);
- }
+ /// Get the device type
+ /// 0: Software Wallet
+ /// 1: Ledger
+ /// 2: Trezor
+ var deviceType = 0;
+
+ if (Platform.isAndroid || Platform.isIOS) {
+ deviceType = wmPtr.queryWalletDevice(
+ keysFileName: "$path.keys",
+ password: password,
+ kdfRounds: 1,
+ );
+ final status = wmPtr.errorString();
+ if (status != "") {
+ printV("loadWallet:" + status);
+ // This is most likely closeWallet call leaking error. This is fine.
+ if (status.contains("failed to save file")) {
+ printV("loadWallet: error leaked: $status");
+ deviceType = 0;
+ } else {
+ throw WalletOpeningException(message: status);
}
- } else {
- deviceType = 0;
}
+ } else {
+ deviceType = 0;
+ }
if (deviceType == 1) {
if (gLedger == null) {
- throw Exception("Tried to open a ledger wallet with no ledger connected");
- }
- enableLedgerExchange(gLedger!);
+ throw HardwareWalletNotConnectedException("Tried to open a ledger wallet with no ledger connected");
}
+ enableLedgerExchange(gLedger!);
+ }
- final addr = wmPtr.ffiAddress();
- final newWptrAddr = await Isolate.run(() {
- return monero.WalletManager_openWallet(Pointer.fromAddress(addr),
- path: path, password: password)
- .address;
- });
-
- final newW = MoneroWallet(Pointer.fromAddress(newWptrAddr));
+ final addr = wmPtr.ffiAddress();
+ final newWptrAddr = await Isolate.run(() {
+ return monero.WalletManager_openWallet(Pointer.fromAddress(addr),
+ path: path, password: password)
+ .address;
+ });
- int status = newW.status();
- if (status != 0) {
- final err = newW.errorString();
- printV("loadWallet:" + err);
- throw WalletOpeningException(message: err);
- }
- if (deviceType == 0) {
- setupBackgroundSync(password, newW);
- }
+ final newW = MoneroWallet(Pointer.fromAddress(newWptrAddr));
- currentWallet = newW;
- _lastOpenedWallet = path;
- openedWalletsByPath[path] = currentWallet!;
+ int status = newW.status();
+ if (status != 0) {
+ final err = newW.errorString();
+ printV("loadWallet:" + err);
+ throw WalletOpeningException(message: err);
}
+ if (deviceType == 0) {
+ setupBackgroundSync(password, newW);
+ }
+
+ currentWallet = newW;
+ openedWalletsByPath[path] = currentWallet!;
}
void setupBackgroundSync(String password, Wallet2Wallet wallet) {
### cw_monero/lib/bip39_seed.dart
@@ -2,14 +2,15 @@ import 'dart:typed_data';
import 'package:bip32/bip32.dart' as bip32;
import 'package:bip39/bip39.dart' as bip39;
+import 'package:cw_core/utils/bip39_seed.dart';
import 'package:polyseed/polyseed.dart';
bool isBip39Seed(String mnemonic) => bip39.validateMnemonic(mnemonic);
String getBip39Seed() => bip39.generateMnemonic();
String getLegacySeedFromBip39(String mnemonic, {int accountIndex = 0, String passphrase = ""}) {
- final seed = bip39.mnemonicToSeed(mnemonic, passphrase: passphrase);
+ final seed = bip39MnemonicToSeed(mnemonic, passphrase: passphrase);
final bip32KeyPair = bip32.BIP32.fromSeed(seed).derivePath("m/44'/128'/$accountIndex'/0/0");
### cw_monero/lib/exceptions/monero_exceptions.dart
@@ -0,0 +1,14 @@
+
+import "package:cw_core/exceptions/cake_exception.dart";
+
+class MoneroNodeResponseException extends ServerResponseException {
+ const MoneroNodeResponseException(super.message);
+}
+
+class KeyImageException extends CakeException {
+ const KeyImageException(super.message);
+}
+
+class MoneroWalletException extends CakeException {
+ const MoneroWalletException(super.message);
+}
\ No newline at end of file
### cw_monero/lib/exceptions/monero_transaction_creation_exception.dart
@@ -1,8 +1,5 @@
-class MoneroTransactionCreationException implements Exception {
- MoneroTransactionCreationException(this.message);
+import "package:cw_core/exceptions/cake_exception.dart";
- final String message;
-
- @override
- String toString() => message;
+class MoneroTransactionCreationException extends TransactionGenerationException {
+ const MoneroTransactionCreationException(super.message);
}
### cw_monero/lib/exceptions/monero_transaction_no_inputs_exception.dart
@@ -1,9 +1,9 @@
-class MoneroTransactionNoInputsException implements Exception {
- MoneroTransactionNoInputsException(this.inputsSize);
+import "package:cw_monero/exceptions/monero_transaction_creation_exception.dart";
- int inputsSize;
+class MoneroTransactionNoInputsException extends MoneroTransactionCreationException {
+ MoneroTransactionNoInputsException(int inputsSize)
+ : inputsSize = inputsSize,
+ super("Not enough inputs ($inputsSize) selected. Please select more under Coin Control");
- @override
- String toString() =>
- 'Not enough inputs ($inputsSize) selected. Please select more under Coin Control';
+ int inputsSize;
}
### cw_monero/lib/ledger.dart
@@ -53,10 +53,10 @@ Future<Uint8List> exchange(LedgerConnection connection, Uint8List data) async =>
connection.sendOperation<Uint8List>(ExchangeOperation(data));
class ExchangeOperation extends LedgerRawOperation<Uint8List> {
- final Uint8List inputData;
-
ExchangeOperation(this.inputData);
+ final Uint8List inputData;
+
@override
Future<Uint8List> read(ByteDataReader reader) async => reader.read(reader.remainingLength);
### cw_monero/lib/monero_wallet.dart
@@ -4,6 +4,7 @@ import 'dart:io';
import 'dart:isolate';
import 'package:cw_core/amount/money.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/transaction_priority.dart';
import 'package:cw_core/account.dart';
@@ -27,6 +28,7 @@ import 'package:cw_monero/api/structs/pending_transaction.dart';
import 'package:cw_monero/api/transaction_history.dart' as transaction_history;
import 'package:cw_monero/api/wallet.dart' as monero_wallet;
import 'package:cw_monero/api/wallet_manager.dart';
+import "package:cw_monero/exceptions/monero_exceptions.dart";
import 'package:cw_monero/exceptions/monero_transaction_creation_exception.dart';
import 'package:cw_monero/ledger.dart';
import 'package:cw_monero/monero_balance.dart';
@@ -120,6 +122,15 @@ abstract class MoneroWalletBase
@override
bool get hasRescan => true;
+ @override
+ bool get hasCoinControl => true;
+
+ @override
+ bool get hasAccountsSupport => true;
+
+ @override
+ bool get hasNativeAccounts => true;
+
@override
String get seed => monero_wallet.getSeed();
String seedLegacy(String? language) => monero_wallet.getSeedLegacy(language);
@@ -346,7 +357,7 @@ abstract class MoneroWalletBase
final status = currentWallet!.status();
if (status != 0) {
final err = currentWallet!.errorString();
- throw Exception("unable to import key images: $err");
+ throw KeyImageException("unable to import key images: $err");
}
return retStatus;
}
@@ -385,30 +396,20 @@ abstract class MoneroWalletBase
MoneroTrezorService? trezorService;
- Future<Trezor> _getTrezor() async {
- if (trezorService == null) throw Exception("Trezor not connected");
-
- final trezor = Trezor(trezorService!);
- await trezor.newPassphraseSession(passphrase);
- return trezor;
- }
+ Trezor _getTrezor() => Trezor(trezorService ?? (throw HardwareWalletNotConnectedException("Trezor not connected")));
Future<void> syncTrezor() async {
- if (trezorService == null) throw Exception("Trezor not connected");
+ if (trezorService == null) throw HardwareWalletNotConnectedException("Trezor not connected");
final ptr = Pointer<Void>.fromAddress(currentWallet!.ffiAddress());
final tdis = monero.Wallet_exportTrezorTdis(ptr);
- final trezor = await _getTrezor();
- final response = await trezor.keyImageSync(tdis);
+ final response = await _getTrezor().keyImageSync(tdis);
final success = monero.Wallet_importTrezorEncryptedKeyImagesJson(ptr, response);
- if (!success) throw Exception(monero.Wallet_errorString(ptr));
+ if (!success) throw MoneroWalletException(monero.Wallet_errorString(ptr));
}
- Future<String> signTrezorTransaction(String json) async {
- final trezor = await _getTrezor();
- return trezor.signTransaction(json);
- }
+ Future<String> signTrezorTransaction(String json) => _getTrezor().signTransaction(json);
@override
Future<PendingTransaction> createTransaction(Object credentials) async {
@@ -476,6 +477,11 @@ abstract class MoneroWalletBase
} else {
final output = outputs.first;
final address = output.isParsedAddress ? output.extractedAddress : output.address;
+
+ if (!output.sendAll && output.cryptoAmount.amount <= BigInt.zero) {
+ throw MoneroTransactionCreationException('Amount must be greater than 0.');
+ }
+
final amount = output.sendAll ? null : output.cryptoAmount.toString();
// if ((formattedAmount != null && unlockedBalance < formattedAmount) ||
@@ -496,7 +502,10 @@ abstract class MoneroWalletBase
paymentId: '');
}
- // final status = monero.PendingTransaction_status(pendingTransactionDescription);
+ if (pendingTransactionDescription.txCount != 1) {
+ throw MoneroTransactionCreationException(
+ "This payment would be split into ${pendingTransactionDescription.txCount} transactions. Send smaller transaction to yourself first.",);
+ }
return PendingMoneroTransaction(pendingTransactionDescription, this);
}
@@ -653,11 +662,19 @@ abstract class MoneroWalletBase
await walletInfo.save();
}
- Future<void> updateUnspent() async {
+ Future<void>? _updateUnspentInFlight;
+
+ /// Concurrent callers share one run: two runs at once work on the same [unspentCoins] list, and
+ /// the clean up of the one then deletes the coin infos of the other.
+ Future<void> updateUnspent() => _updateUnspentInFlight ??=
+ _updateUnspent().whenComplete(() => _updateUnspentInFlight = null);
+
+ Future<void> _updateUnspent() async {
try {
refreshCoins(walletAddresses.account!.id);
- unspentCoins.clear();
+ // Collected separately, so nobody ever sees a half filled list
+ final unspentCoins = <MoneroUnspent>[];
final coinCount = await countOfCoins();
for (var i = 0; i < coinCount; i++) {
@@ -675,35 +692,60 @@ abstract class MoneroWalletBase
);
// TODO: double-check the logic here
if (unspent.hash.isNotEmpty) {
- final tx = await transaction_history.getTransaction(unspent.hash);
- unspent.isChange = tx.isSpend == true;
+ try {
+ final tx = await transaction_history.getTransaction(unspent.hash);
+ unspent.isChange = tx.isSpend == true;
+ } catch (e) {
+ // The transaction may not be in the (not yet refreshed) history, that must not
+ // keep the output, and all the ones after it, out of coin control.
+ printV("isChange lookup failed for ${unspent.hash}: $e");
+ }
}
unspentCoins.add(unspent);
}
}
+ this.unspentCoins
+ ..clear()
+ ..addAll(unspentCoins);
if (unspentCoinsInfo.isEmpty) {
unspentCoins.forEach((coin) => _addCoinInfo(coin));
return;
}
if (unspentCoins.isNotEmpty) {
- unspentCoins.forEach((coin) {
- final coinInfoList = unspentCoinsInfo.values.where((element) =>
- element.walletId.contains(id) &&
- element.accountIndex == walletAddresses.account!.id &&
- element.keyImage!.contains(coin.keyImage!));
+ final usedInfoKeys = <dynamic>{};
+ for (final coin in unspentCoins) {
+ final coinInfoList = unspentCoinsInfo.values
+ .where((element) =>
+ element.walletId.contains(id) &&
+ element.accountIndex == walletAddresses.account!.id &&
+ !usedInfoKeys.contains(element.key) &&
+ _isSameCoin(element, coin))
+ .toList();
if (coinInfoList.isNotEmpty) {
- final coinInfo = coinInfoList.first;
+ // The key image only breaks a tie between identical outputs of one transaction
+ final coinInfo = coinInfoList.firstWhere(
+ (element) => element.keyImage == coin.keyImage,
+ orElse: () => coinInfoList.first,
+ );
+ usedInfoKeys.add(coinInfo.key);
coin.isFrozen = coinInfo.isFrozen;
coin.isSending = coinInfo.isSending;
coin.note = coinInfo.note;
+
+ // The key image of a hardware wallet's output is only known after syncing with the
+ // device; keep the existing info (frozen state, note) instead of orphaning it.
+ if (coinInfo.keyImage != coin.keyImage) {
+ coinInfo.keyImage = coin.keyImage;
+ await coinInfo.save();
+ }
} else {
- _addCoinInfo(coin);
+ await _addCoinInfo(coin);
}
- });
+ }
}
await _refreshUnspentCoinsInfo();
@@ -718,6 +760,12 @@ abstract class MoneroWalletBase
}
}
+ /// The key image can't identify an output: a hardware wallet doesn't know the key images of its
+ /// outputs until they are synced with the device, until then they all carry the same
+ /// placeholder, which made every output match the info of the first one.
+ bool _isSameCoin(UnspentCoinsInfo info, MoneroUnspent coin) =>
+ info.hash == coin.hash && info.address == coin.address && info.value == coin.value;
+
Future<void> _addCoinInfo(MoneroUnspent coin) async {
final newInfo = UnspentCoinsInfo(
walletId: id,
@@ -743,8 +791,7 @@ abstract class MoneroWalletBase
if (currentWalletUnspentCoins.isNotEmpty) {
currentWalletUnspentCoins.forEach((element) {
- final existUnspentCoins =
- unspentCoins.where((coin) => element.keyImage!.contains(coin.keyImage!));
+ final existUnspentCoins = unspentCoins.where((coin) => _isSameCoin(element, coin));
if (existUnspentCoins.isEmpty) {
keys.add(element.key);
@@ -842,7 +889,7 @@ abstract class MoneroWalletBase
// the restore height is probably correct, so we do nothing:
if (height > MIN_RESTORE_HEIGHT) return;
- throw Exception("height isn't > $MIN_RESTORE_HEIGHT!");
+ throw MoneroWalletException("height isn't > $MIN_RESTORE_HEIGHT!");
}
void _setHeightFromDate({int tryNum = 0}) {
@@ -854,7 +901,7 @@ abstract class MoneroWalletBase
try {
height = _getHeightByDate(walletInfo.date.subtract(Duration(days: 14)));
if (height <= 0) {
- throw Exception("height is <= 0");
+ throw MoneroWalletException("height is <= 0");
}
monero_wallet.setRefreshFromBlockHeight(height: height);
} catch (_) {
@@ -885,7 +932,7 @@ abstract class MoneroWalletBase
if (nodeHeight <= 0) {
// the node returned 0 (an error state)
- throw Exception("nodeHeight is <= 0!");
+ throw MoneroWalletException("nodeHeight is <= 0!");
}
return nodeHeight - heightDistance;
### cw_monero/lib/monero_wallet_service.dart
@@ -3,6 +3,7 @@ import 'dart:ffi';
import 'dart:io';
import 'dart:isolate';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/get_height_by_date.dart';
import 'package:cw_core/hardware/hardware_wallet_service.dart';
import 'package:cw_core/monero_wallet_utils.dart';
@@ -184,7 +185,7 @@ class MoneroWalletService extends WalletService<
await monero_wallet_manager.openWallet(path: path, password: password);
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
final wallet = MoneroWallet(
walletInfo: walletInfo,
@@ -220,13 +221,20 @@ class MoneroWalletService extends WalletService<
Future<void> remove(String wallet) async {
final path = await pathForWalletDir(name: wallet, type: getType());
if (openedWalletsByPath["$path/$wallet"] != null) {
- // NOTE: this is realistically only required on windows.
printV("closing wallet");
final w = openedWalletsByPath["$path/$wallet"]!;
final wmaddr = wmPtr.ffiAddress();
final waddr = w.ffiAddress();
openedWalletsByPath.remove("$path/$wallet");
- await closeWalletAwaitIfShould(wmaddr, waddr);
+ if (currentWallet?.ffiAddress() == waddr) {
+ currentWallet = null;
+ }
+ // must finish before deleting the files, a pending close stores the cache mid-deletion
+ await Isolate.run(() {
+ monero.WalletManager_closeWallet(
+ Pointer.fromAddress(wmaddr), Pointer.fromAddress(waddr), false);
+ monero.WalletManager_errorString(Pointer.fromAddress(wmaddr));
+ });
printV("wallet closed");
}
@@ -239,7 +247,7 @@ class MoneroWalletService extends WalletService<
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet, type: getType());
}
await WalletInfo.delete(walletInfo);
}
@@ -248,7 +256,7 @@ class MoneroWalletService extends WalletService<
Future<void> rename(String currentName, String password, String newName) async {
final currentWalletInfo = await WalletInfo.get(currentName, getType());
if (currentWalletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: currentName, type: getType());
}
final currentWallet = MoneroWallet(
walletInfo: currentWalletInfo,
@@ -310,13 +318,9 @@ class MoneroWalletService extends WalletService<
restoreHeight: credentials.height!,
deviceName: 'Ledger',
);
- } else if (credentials.hardwareWalletService case MoneroTrezorService service) {
+ } else if (credentials.hardwareWalletService case final MoneroTrezorService service) {
final trezor = Trezor(service);
- if (credentials.passphrase != null) {
- await trezor.newPassphraseSession(credentials.passphrase);
- }
-
final watchCredentials = await trezor.getWatchCredentials();
monero_wallet_manager.restoreWalletFromKeys(
@@ -560,7 +564,7 @@ class MoneroWalletService extends WalletService<
await monero_wallet_manager.openWallet(path: path, password: password);
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
final wallet = MoneroWallet(
walletInfo: walletInfo,
### cw_monero/lib/trezor.dart
@@ -1,12 +1,17 @@
import "dart:convert";
import "package:cw_core/hardware/hardware_wallet_service.dart";
+import "package:mutex/mutex.dart";
import "package:trezor_flutter/trezor_flutter.dart";
class MoneroTrezorService extends HardwareWalletService {
MoneroTrezorService(this.client);
final TrezorClient client;
+
+ static final Mutex _mutex = Mutex();
+
+ static Future<T> runBlocking<T>(Future<T> Function() operation) => _mutex.protect(operation);
}
class MoneroTrezorWatchCredentials {
@@ -21,18 +26,8 @@ class Trezor {
final MoneroTrezorService service;
- String? _sessionPassphrase;
-
- Future<void> newPassphraseSession(String? passphrase) async {
- if (passphrase == null) return;
-
- if (_sessionPassphrase == passphrase) return;
- _sessionPassphrase = passphrase;
- return service.client.createChannel(passphrase: _sessionPassphrase);
- }
-
Future<MoneroTrezorWatchCredentials> getWatchCredentials() async {
- final credentials = await TrezorMonero(service.client).getWatchCredentials();
+ final credentials = await MoneroTrezorService.runBlocking(TrezorMonero(service.client).getWatchCredentials);
return MoneroTrezorWatchCredentials(credentials.$1, credentials.$2);
}
@@ -55,11 +50,15 @@ class Trezor {
),
);
}
- final keyImages = await TrezorMonero(service.client).syncKeyImages(txIds);
+ final keyImages = await MoneroTrezorService.runBlocking(
+ () => TrezorMonero(service.client).syncKeyImages(txIds),
+ );
return jsonEncode(keyImages.toMap());
}
- Future<String> signTransaction(String json) =>
- TrezorMonero(service.client).signTransaction(jsonDecode(json) as Map<String, dynamic>);
+ Future<String> signTransaction(String json) => MoneroTrezorService.runBlocking(
+ () =>
+ TrezorMonero(service.client).signTransaction(jsonDecode(json) as Map<String, dynamic>),
+ );
}
### cw_monero/pubspec.yaml
@@ -14,26 +14,21 @@ dependencies:
bip39: ^1.0.6
bip32: ^2.0.0
ffi: ^2.0.1
- http: ^1.1.0
- path_provider: ^2.0.11
mobx: ^2.6.0
- flutter_mobx: ^2.3.0
- intl: any
- encrypt: ^5.0.1
polyseed: ^0.0.7
cw_core:
path: ../cw_core
monero:
git:
url: https://github.com/mrcyjanek/monero_c.git
- ref: cd4fe366cc8d3c188c91de279f43b29c0e044b15
+ ref: 33671871de3d51696b66ffb3bd94f744e26974f6
path: impls/monero.dart
mutex: ^3.1.0
ledger_flutter_plus: ^1.4.1
trezor_flutter:
git:
- url: https://github.com/cake-tech/trezor-flutter
- ref: f5121b1f3a06000ff836da8e6e6c83f53a9fa487
+ url: https://github.com/cake-tech/trezor-flutter.git
+ ref: 591d4b8c821b9c10561f848b866324a9a8dcb489
path: trezor-flutter
dev_dependencies:
### cw_mweb/lib/cw_mweb.dart
@@ -4,6 +4,7 @@ import 'dart:developer';
import 'dart:io';
import 'dart:typed_data';
+import "package:cw_mweb/mweb_exceptions.dart";
import 'package:cw_mweb/mweb_ffi.dart';
import 'package:cw_mweb/print_verbose.dart';
import 'package:grpc/grpc.dart';
@@ -59,7 +60,7 @@ class CwMweb {
_port = MWebFfi.instance.start(appDir.path, nodeUriOverride ?? ltcNodeUri);
if (_port == null || _port == 0) {
- throw Exception("Failed to start server");
+ throw MwebConnectionException("Failed to start server");
}
printV("Attempting to connect to server on port: $_port");
@@ -83,7 +84,7 @@ class CwMweb {
final status = await _rpcClient!
.status(StatusRequest(), options: CallOptions(timeout: TIMEOUT_DURATION));
if (status.blockTime == 0) {
- throw Exception("blockTime shouldn't be 0! (this connection is likely broken)");
+ throw MwebConnectionException("blockTime shouldn't be 0! (this connection is likely broken)");
}
return _rpcClient!;
} on GrpcError catch (e) {
@@ -100,7 +101,7 @@ class CwMweb {
await Future.delayed(const Duration(seconds: 3));
}
}
- throw Exception("Failed to connect after $maxRetries attempts");
+ throw MwebConnectionException("Failed to connect after $maxRetries attempts");
}
static Future<void> stop() async {
### cw_mweb/lib/mweb_exceptions.dart
@@ -0,0 +1,8 @@
+class MwebConnectionException implements Exception {
+ const MwebConnectionException(this.message);
+
+ final String message;
+
+ @override
+ String toString() => message;
+}
\ No newline at end of file
### cw_mweb/pubspec.yaml
@@ -12,7 +12,6 @@ dependencies:
sdk: flutter
grpc: 4.0.1
path_provider: ^2.1.2
- plugin_platform_interface: ^2.0.2
ffi: ^2.1.0
protobuf: ^3.1.0
fixnum: ^1.1.1
### cw_nano/.gitignore
@@ -0,0 +1,28 @@
+# Miscellaneous
+*.class
+*.log
+*.pyc
+*.swp
+.DS_Store
+.atom/
+.buildlog/
+.history
+.svn/
+migrate_working_dir/
+
+# IntelliJ related
+*.iml
+*.ipr
+*.iws
+.idea/
+
+# The .vscode folder contains launch configuration and tasks you configure in
+# VS Code which you may wish to be included in version control, so this line
+# is commented out by default.
+#.vscode/
+
+# Flutter/Dart/Pub related
+**/doc/api/
+.dart_tool/
+.packages
+build/
### cw_nano/lib/nano_client.dart
@@ -3,12 +3,14 @@ import 'dart:convert';
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/crypto_currency.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/nano_account_info_response.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_nano/nano_block_info_response.dart';
import 'package:cw_core/n2_node.dart';
import 'package:cw_nano/nano_balance.dart';
+import "package:cw_nano/nano_exceptions.dart";
import 'package:cw_nano/nano_transaction_model.dart';
import 'package:cw_core/node.dart';
import 'package:nanoutil/nanoutil.dart';
@@ -84,7 +86,7 @@ class NanoClient {
data["error"] != null ||
data["balance"] == null ||
data["receivable"] == null) {
- throw Exception(
+ throw ServerResponseException(
"Error while trying to get balance! ${data["error"] != null ? data["error"] : ""}");
}
final currentBalance = data["balance"] as String;
@@ -149,7 +151,7 @@ class NanoClient {
AccountInfoResponse? accountInfo = await getAccountInfo(ourAddress);
if (accountInfo == null) {
- throw Exception(
+ throw NanoChangeRepException(
"error while getting account info, you can't change the rep of an unopened account");
}
@@ -184,7 +186,7 @@ class NanoClient {
try {
return await processBlock(changeBlock, "change");
} catch (e) {
- throw Exception("error while changing representative: $e");
+ throw NanoChangeRepException("error while changing representative: $e");
}
}
@@ -203,11 +205,11 @@ class NanoClient {
if (response.statusCode == 200) {
final decoded = jsonDecode(response.body) as Map<String, dynamic>;
if (decoded.containsKey("error")) {
- throw Exception("Received error ${decoded["error"]}");
+ throw ServerResponseException("Received error ${decoded["error"]}");
}
return decoded["work"] as String;
} else {
- throw Exception("Received work error ${response.body}");
+ throw ServerResponseException("Received work error ${response.body}");
}
}
@@ -241,7 +243,7 @@ class NanoClient {
final Map<String, dynamic> decoded = jsonDecode(processResponse.body) as Map<String, dynamic>;
if (decoded.containsKey("error")) {
- throw Exception("Received error ${decoded["error"]}");
+ throw ServerResponseException("Received error ${decoded["error"]}");
}
// return the hash of the transaction:
@@ -268,7 +270,7 @@ class NanoClient {
// get the account info (we need the frontier and representative):
AccountInfoResponse? infoResponse = await getAccountInfo(publicAddress);
if (infoResponse == null) {
- throw Exception(
+ throw ServerResponseException(
"error while getting account info! (we probably don't have an open account yet)");
}
@@ -341,7 +343,7 @@ class NanoClient {
}
if ((BigInt.tryParse(amountRaw) ?? BigInt.zero) <= BigInt.zero) {
- throw Exception("amountRaw must be greater than zero");
+ throw ArgumentError("amountRaw must be greater than zero");
}
BlockContentsResponse? frontierContents;
@@ -351,7 +353,7 @@ class NanoClient {
frontierContents = await getBlockContents(frontier);
if (frontierContents == null) {
- throw Exception("error while getting frontier block info");
+ throw NanoBlockException("error while getting frontier block info");
}
final String frontierHash = NanoSignatures.computeStateHash(
@@ -370,7 +372,7 @@ class NanoClient {
);
if (!valid) {
- throw Exception(
+ throw NanoBlockException(
"Frontier block signature is invalid! Potentially malicious block detected!");
}
}
@@ -439,7 +441,7 @@ class NanoClient {
);
final Map<String, dynamic> decoded = json.decode(processResponse.body) as Map<String, dynamic>;
if (decoded.containsKey("error")) {
- throw Exception("Received error ${decoded["error"]}");
+ throw ServerResponseException("Received error ${decoded["error"]}");
}
}
### cw_nano/lib/nano_exceptions.dart
@@ -0,0 +1,11 @@
+
+
+import "package:cw_core/exceptions/cake_exception.dart";
+
+class NanoChangeRepException extends CakeException {
+ const NanoChangeRepException(super.message);
+}
+
+class NanoBlockException extends CakeException {
+ const NanoBlockException(super.message);
+}
\ No newline at end of file
### cw_nano/lib/nano_mnemonic.dart
@@ -1,5 +1,9 @@
import 'package:bip39/bip39.dart' as bip39;
+import "package:cw_core/exceptions/cake_exception.dart";
+import "package:cw_core/utils/bip39_seed.dart";
+import "package:hex/hex.dart";
import 'package:nanodart/nanodart.dart';
+import "package:nanoutil/nanoutil.dart" show NanoDerivations;
class NanoMnemonicIsIncorrectException implements Exception {
@override
@@ -11,7 +15,7 @@ class NanoMnemomics {
/// Converts a nano seed to a 24-word mnemonic word list
static List<String> seedToMnemonic(String seed) {
if (!NanoSeeds.isValidSeed(seed)) {
- throw Exception('Invalid Seed');
+ throw BadMnemonicException('Invalid Seed');
}
String words = bip39.entropyToMnemonic(seed);
return words.split(' ');
@@ -20,11 +24,19 @@ class NanoMnemomics {
/// Convert a 24-word mnemonic word list to a nano seed
static String mnemonicListToSeed(List<String> words) {
if (words.length != 24) {
- throw Exception('Expected a 24-word list, got a ${words.length} list');
+ throw BadMnemonicException('Expected a 24-word list, got a ${words.length} list');
}
return bip39.mnemonicToEntropy(words.join(' ')).toUpperCase();
}
+ /// BIP39 seed (hex) of an HD mnemonic, same as [NanoDerivations.hdMnemonicListToSeed] but through
+ /// [bip39MnemonicToSeed]. Non-ASCII input keeps the nanoutil path, which UTF-8 encodes where
+ /// [bip39MnemonicToSeed] takes code units.
+ static Future<String> hdMnemonicToSeed(String mnemonic) async =>
+ mnemonic.codeUnits.every((unit) => unit < 0x80)
+ ? HEX.encode(bip39MnemonicToSeed(mnemonic))
+ : await NanoDerivations.hdMnemonicListToSeed(mnemonic.split(' '));
+
/// Validate a mnemonic word list
static bool validateMnemonic(List<String> words) {
return bip39.validateMnemonic(words.join(' '));
### cw_nano/lib/nano_wallet.dart
@@ -7,6 +7,7 @@ import 'package:cw_core/amount/money.dart';
import 'package:cw_core/cake_hive.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/n2_node.dart';
import 'package:cw_core/nano_account.dart';
import 'package:cw_core/nano_account_info_response.dart';
@@ -22,6 +23,8 @@ import 'package:cw_core/wallet_info.dart';
import 'package:cw_core/wallet_keys_file.dart';
import 'package:cw_nano/nano_balance.dart';
import 'package:cw_nano/nano_client.dart';
+import 'package:cw_nano/nano_mnemonic.dart';
+import "package:cw_nano/nano_exceptions.dart";
import 'package:cw_nano/nano_transaction_credentials.dart';
import 'package:cw_nano/nano_transaction_history.dart';
import 'package:cw_nano/nano_transaction_info.dart';
@@ -124,7 +127,7 @@ abstract class NanoWalletBase
if (_derivationType == DerivationType.nano) {
_hexSeed = bip39.mnemonicToEntropy(_mnemonic).toUpperCase();
} else {
- _hexSeed = await NanoDerivations.hdMnemonicListToSeed(_mnemonic.split(' '));
+ _hexSeed = await NanoMnemomics.hdMnemonicToSeed(_mnemonic);
}
}
@@ -167,7 +170,7 @@ abstract class NanoWalletBase
syncStatus = ConnectingSyncStatus();
final isConnected = _client.connect(node);
if (!isConnected) {
- throw Exception("Nano Node connection failed");
+ throw ConnectionException("Nano Node connection failed");
}
try {
@@ -208,9 +211,8 @@ abstract class NanoWalletBase
amt = txOut.cryptoAmount.amount;
}
- if (balance[currency]?.currentBalance != null &&
- amt > balance[currency]!.currentBalance.amount) {
- throw Exception("Trying to send more than entire balance!");
+ if (balance[currency]?.currentBalance != null && amt > balance[currency]!.currentBalance.amount) {
+ throw TransactionGenerationException("Trying to send more than entire balance!");
}
runningBalance = runningBalance - amt;
@@ -236,9 +238,8 @@ abstract class NanoWalletBase
}
try {
- if (runningAmount > balance[currency]!.currentBalance.amount ||
- runningBalance < BigInt.zero) {
- throw Exception(("Trying to send more than entire balance!"));
+ if (runningAmount > balance[currency]!.currentBalance.amount || runningBalance < BigInt.zero) {
+ throw TransactionGenerationException(("Trying to send more than entire balance!"));
}
} catch (e) {
rethrow;
@@ -490,7 +491,7 @@ abstract class NanoWalletBase
} catch (e) {
// account not found:
_representativeAddress = await _client.getRepFromPrefs();
- throw Exception("Failed to get representative address $e");
+ throw NanoChangeRepException("Failed to get representative address $e");
}
repScore = await _client.getRepScore(_representativeAddress!);
@@ -526,7 +527,7 @@ abstract class NanoWalletBase
_representativeAddress = address;
}
} catch (e) {
- throw Exception("Failed to change representative address $e");
+ throw NanoChangeRepException("Failed to change representative address $e");
}
}
### cw_nano/lib/nano_wallet_service.dart
@@ -1,5 +1,6 @@
import 'dart:io';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/encryption_file_utils.dart';
import 'package:cw_core/wallet_base.dart';
@@ -69,7 +70,7 @@ class NanoWalletService extends WalletService<
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet, type: getType());
}
await WalletInfo.delete(walletInfo);
}
@@ -78,7 +79,7 @@ class NanoWalletService extends WalletService<
Future<void> rename(String currentName, String password, String newName) async {
final currentWalletInfo = await WalletInfo.get(currentName, getType());
if (currentWalletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: currentName, type: getType());
}
String randomWords =
@@ -105,10 +106,10 @@ class NanoWalletService extends WalletService<
Future<NanoWallet> restoreFromKeys(NanoRestoreWalletFromKeysCredentials credentials,
{bool? isTestnet}) async {
if (credentials.seedKey.contains(' ')) {
- throw Exception("Invalid key!");
+ throw BadKeysException("Invalid key!");
} else {
if (credentials.seedKey.length != 64 && credentials.seedKey.length != 128) {
- throw Exception("Invalid key length!");
+ throw BadKeysException("Invalid key length!");
}
}
@@ -119,7 +120,7 @@ class NanoWalletService extends WalletService<
try {
mnemonic = NanoDerivations.standardSeedToMnemonic(credentials.seedKey);
} catch (e) {
- throw Exception("Wasn't a valid nano style seed!");
+ throw BadMnemonicException("Wasn't a valid nano style seed!");
}
}
final derivationInfo = await credentials.walletInfo!.getDerivationInfo();
@@ -159,7 +160,7 @@ class NanoWalletService extends WalletService<
}
} else {
if (credentials.mnemonic.length != 64 && credentials.mnemonic.length != 128) {
- throw Exception("Invalid seed length");
+ throw BadMnemonicException("invalid seed length");
}
}
@@ -190,7 +191,7 @@ class NanoWalletService extends WalletService<
Future<NanoWallet> openWallet(String name, String password) async {
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
try {
### cw_nano/pubspec.yaml
@@ -2,7 +2,6 @@ name: cw_nano
description: A new Flutter package project.
version: 0.0.1
publish_to: none
-author: Cake Wallet
homepage: https://cakewallet.com
environment:
@@ -14,12 +13,7 @@ dependencies:
sdk: flutter
mobx: ^2.6.0
bip39: ^1.0.6
- bip32: ^2.0.0
- decimal: ^2.3.3
- libcrypto: ^0.2.2
- ed25519_hd_key: ^2.2.0
hex: ^0.2.0
- http: ^1.1.0
shared_preferences: ^2.0.15
nanoutil:
git:
### cw_nano/test/hd_seed_test.dart
@@ -0,0 +1,16 @@
+import "package:bip39/bip39.dart" as bip39;
+import "package:cw_nano/nano_mnemonic.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:nanoutil/nanoutil.dart" show NanoDerivations;
+
+void main() {
+ test("hdMnemonicToSeed matches nanoutil", () async {
+ for (var i = 0; i < 20; i++) {
+ final mnemonic = bip39.generateMnemonic(strength: i.isEven ? 128 : 256);
+ expect(
+ await NanoMnemomics.hdMnemonicToSeed(mnemonic),
+ await NanoDerivations.hdMnemonicListToSeed(mnemonic.split(" ")),
+ );
+ }
+ });
+}
### cw_solana/lib/pending_solana_transaction.dart
@@ -30,7 +30,7 @@ class PendingSolanaTransaction with PendingTransaction {
@override
Future<void> commit() async {
- _sig = await sendTransaction();
+ _sig = await sendTransaction() as String?;
}
@override
### cw_solana/lib/solana_balance.dart
@@ -15,7 +15,7 @@ class SolanaBalance extends Balance {
final decoded = json.decode(jsonSource) as Map;
try {
- return SolanaBalance(currency.parseAmount(decoded["balance"]));
+ return SolanaBalance(currency.parseAmount(decoded["balance"] as String));
} catch (e) {
return SolanaBalance(Money.zero(currency));
}
### cw_solana/lib/solana_client.dart
@@ -85,7 +85,7 @@ class SolanaWalletClient {
final balance = await _provider!.requestWithContext(
SolanaRPCGetBalance(account: SolAddress(walletAddress)),
);
- return Money(balance.result, CryptoCurrency.sol);
+ return Money(balance.result as BigInt, CryptoCurrency.sol);
} catch (_) {
if (throwOnError) {
rethrow;
@@ -439,14 +439,16 @@ class SolanaWalletClient {
return walletSent && walletReceived;
}
+ static const unresolvedTokenTitle = "TOKEN";
+
static CryptoCurrency currencyForRawAmount(SPLToken? token, int mintDecimals) {
if (token != null && token.decimals == mintDecimals) {
return token;
}
return CryptoCurrency(
- name: (token?.title ?? "TOKEN").toLowerCase(),
- title: token?.title ?? "TOKEN",
+ name: (token?.title ?? unresolvedTokenTitle).toLowerCase(),
+ title: token?.title ?? unresolvedTokenTitle,
decimals: mintDecimals,
);
}
@@ -1103,7 +1105,7 @@ class SolanaWalletClient {
try {
return await _provider!.request(
SolanaRPCGetTransaction(
- transactionSignature: signature['signature'],
+ transactionSignature: signature['signature'] as String,
encoding: SolanaRPCEncoding.jsonParsed,
maxSupportedTransactionVersion: 1,
skipVerification: true,
@@ -1272,7 +1274,10 @@ class SolanaWalletClient {
},
);
- if (response.statusCode != 200) return null;
+ if (response.statusCode != 200) {
+ throw Exception("Moralis token metadata returned ${response.statusCode}");
+ }
+
final decodedResponse = jsonDecode(response.body) as Map<String, dynamic>;
final symbol = decodedResponse['symbol'] ?? '';
@@ -1294,11 +1299,11 @@ class SolanaWalletClient {
}
return SPLToken(
- name: name,
- mint: symbol,
- symbol: filteredTokenSymbol,
+ name: name as String,
+ mint: symbol as String,
+ symbol: filteredTokenSymbol as String,
mintAddress: mintAddress,
- iconPath: iconPath,
+ iconPath: iconPath as String?,
decimal: decimals,
);
} catch (e, s) {
@@ -1702,24 +1707,34 @@ class SolanaWalletClient {
/// Gets the token program ID for a given mint address.
/// Returns the standard SPL Token program ID if the mint account cannot be fetched.
Future<SolAddress> _getTokenProgramId(SolAddress mintAddress) async {
+ SolanaAccountInfo? mintAccountInfo;
try {
- final mintAccountInfo = await _provider!.request(
+ mintAccountInfo = await _provider!.request(
SolanaRPCGetAccountInfo(
account: mintAddress,
commitment: Commitment.confirmed,
),
);
-
- // Determine the token program ID from the mint account owner
- if (mintAccountInfo != null) {
- return mintAccountInfo.owner;
- }
} catch (e) {
// If we can't fetch mint info, default to standard SPL Token program
printV('Warning: Could not fetch mint account info: $e');
}
- return SPLTokenProgramConst.tokenProgramId;
+ if (mintAccountInfo == null) {
+ return SPLTokenProgramConst.tokenProgramId;
+ }
+
+ final mintOwner = mintAccountInfo.owner.address;
+
+ if (mintOwner == SPLTokenProgramConst.tokenProgramId.address) {
+ return SPLTokenProgramConst.tokenProgramId;
+ }
+
+ if (mintOwner == SPLTokenProgramConst.token2022ProgramId.address) {
+ return SPLTokenProgramConst.token2022ProgramId;
+ }
+
+ throw SolanaUnrecognizedTokenProgramException(mintOwner);
}
Future<ProgramDerivedAddress?> _findAssociatedTokenAccount({
@@ -1797,7 +1812,6 @@ class SolanaWalletClient {
tokenProgramId: tokenProgramId,
);
- // Verify the account exists and get the actual program ID that owns it
final accountInfo = await _provider!.request(
SolanaRPCGetAccountInfo(
account: associatedSenderAccount.address,
@@ -1806,11 +1820,16 @@ class SolanaWalletClient {
);
if (accountInfo != null) {
- senderTokenProgramId = accountInfo.owner;
+ if (accountInfo.owner.address != tokenProgramId.address) {
+ throw SolanaUnrecognizedTokenProgramException(accountInfo.owner.address);
+ }
+
senderAccountSpace = accountInfo.space;
} else {
associatedSenderAccount = null;
}
+ } on SolanaUnrecognizedTokenProgramException {
+ rethrow;
} catch (e) {
associatedSenderAccount = null;
}
@@ -1833,11 +1852,17 @@ class SolanaWalletClient {
);
if (accountInfo != null) {
- senderTokenProgramId = accountInfo.owner;
+ if (accountInfo.owner.address != SPLTokenProgramConst.tokenProgramId.address) {
+ throw SolanaUnrecognizedTokenProgramException(accountInfo.owner.address);
+ }
+
+ senderTokenProgramId = SPLTokenProgramConst.tokenProgramId;
senderAccountSpace = accountInfo.space;
} else {
associatedSenderAccount = null;
}
+ } on SolanaUnrecognizedTokenProgramException {
+ rethrow;
} catch (_) {
associatedSenderAccount = null;
}
@@ -1854,10 +1879,28 @@ class SolanaWalletClient {
bool shouldCreateRecipientAccount = false;
try {
+ final recipientOwner = SolAddress(destinationAddress);
+ final isOffCurveRecipient = !recipientOwner.isOnCurve;
+
+ if (isOffCurveRecipient) {
+ final destinationInfo = await _provider!.request(
+ SolanaRPCGetAccountInfo(account: recipientOwner, commitment: Commitment.confirmed),
+ );
+
+ final destinationOwnerProgram = destinationInfo?.owner.address;
+ if (destinationOwnerProgram == SPLTokenProgramConst.tokenProgramId.address ||
+ destinationOwnerProgram == SPLTokenProgramConst.token2022ProgramId.address) {
+ throw SolanaCreateAssociatedTokenAccountException(
+ "Recipient $destinationAddress is a token account, not a wallet address",
+ );
+ }
+ }
+
final recipientPDA = AssociatedTokenAccountProgramUtils.associatedTokenAccount(
mint: mintAddress,
- owner: SolAddress(destinationAddress),
+ owner: recipientOwner,
tokenProgramId: senderTokenProgramId,
+ allowOwnerOffCurve: isOffCurveRecipient,
);
SolanaAccountInfo? recipientInfo;
@@ -2012,7 +2055,7 @@ class SolanaWalletClient {
final jsonResponse = json.decode(response.body) as Map<String, dynamic>;
if (response.statusCode >= 200 && response.statusCode < 300) {
- return jsonResponse['image'];
+ return jsonResponse['image'] as String?;
} else {
return null;
}
### cw_solana/lib/solana_exceptions.dart
@@ -39,6 +39,10 @@ class SolanaNoAssociatedTokenAccountException extends NoAssociatedTokenAccountEx
final String mint;
}
+class SolanaUnrecognizedTokenProgramException extends UnrecognizedTokenProgramException {
+ SolanaUnrecognizedTokenProgramException(super.programId);
+}
+
class SolanaAmbiguousTokenSymbolException extends AmbiguousTokenSymbolException {
SolanaAmbiguousTokenSymbolException(super.symbol);
}
### cw_solana/lib/solana_transaction_info.dart
@@ -48,9 +48,9 @@ class SolanaTransactionInfo extends TransactionInfo {
direction: parseTransactionDirectionFromInt(data['direction'] as int),
date: DateTime.fromMillisecondsSinceEpoch(data['blockTime'] as int),
isPending: data['isPending'] as bool,
- to: data['to'],
- from: data['from'],
- fee: Money.parse(data['txFee'], CryptoCurrency.sol),
+ to: data['to'] as String?,
+ from: data['from'] as String?,
+ fee: Money.parse(data['txFee'] as String, CryptoCurrency.sol),
);
}
### cw_solana/lib/solana_wallet.dart
@@ -4,6 +4,7 @@ import 'dart:convert';
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/node.dart';
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/pending_transaction.dart';
@@ -30,7 +31,7 @@ import 'package:hex/hex.dart';
import 'package:mobx/mobx.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:on_chain/solana/solana.dart' hide Store;
-import 'package:bip39/bip39.dart' as bip39;
+import 'package:cw_core/utils/bip39_seed.dart';
import 'package:blockchain_utils/blockchain_utils.dart';
part 'solana_wallet.g.dart';
@@ -182,7 +183,7 @@ abstract class SolanaWalletBase
assert(mnemonic != null || privateKey != null);
if (mnemonic != null) {
- final seed = bip39.mnemonicToSeed(mnemonic, passphrase: passphrase ?? '');
+ final seed = bip39MnemonicToSeed(mnemonic, passphrase: passphrase ?? '');
// Derive a Solana private key from the seed
final bip44 = Bip44.fromSeed(seed, Bip44Coins.solana);
@@ -222,7 +223,7 @@ abstract class SolanaWalletBase
final isConnected = _client.connect(node);
if (!isConnected) {
- throw Exception("Solana Node connection failed");
+ throw ConnectionException("Solana Node connection failed");
}
_setTransactionUpdateTimer();
@@ -311,8 +312,9 @@ abstract class SolanaWalletBase
.toList(growable: false);
if (matches.isEmpty) {
- throw Exception(
- "Currency ${requestedCurrency.title} ${requestedCurrency.tag} is not accessible in the wallet, try to enable it first.",
+ throw BadCurrencyException(
+ "Currency ${requestedCurrency.title} ${requestedCurrency
+ .tag} is not accessible in the wallet, try to enable it first.", requestedCurrency,
);
}
@@ -360,6 +362,9 @@ abstract class SolanaWalletBase
@override
Future<void> updateTransactionsHistory({List<String>? specificTokenMints}) async {
+ _seedTokenInfoCache();
+ await _reparseUnresolvedTokenTransactionsOnce();
+
await Future.wait([
_updateNativeSOLTransactions(),
updateSPLTokenTransactions(specificMints: specificTokenMints),
@@ -393,6 +398,32 @@ abstract class SolanaWalletBase
await prefs.remove(_lastSyncedSignatureKey(source));
}
+ void _seedTokenInfoCache() {
+ for (final token in _splTokens) {
+ _client.tokenInfoCache[token.mintAddress] = token;
+ }
+ }
+
+ Future<void> _reparseUnresolvedTokenTransactionsOnce() async {
+ final prefs = await _sharedPrefs.future;
+ final key = "solana_unresolved_token_reparse_done_${walletInfo.name}";
+
+ if (prefs.getBool(key) ?? false) {
+ return;
+ }
+
+ final hasUnresolvedTransactions = transactionHistory.transactions.values.any(
+ (transaction) =>
+ transaction.amount.currency.symbol == SolanaWalletClient.unresolvedTokenTitle,
+ );
+
+ if (hasUnresolvedTransactions) {
+ await _clearLastSyncedSignature(_nativeSource);
+ }
+
+ await prefs.setBool(key, true);
+ }
+
/// Polls for a specific transaction by signature with exponential backoff
/// I'm using this in case we make the call to fetch the transaction and it has not finished its confirmations on the solana network and been indexed by the node networks we use.
Future<void> pollForTransaction({
@@ -401,6 +432,7 @@ abstract class SolanaWalletBase
int maxRetries = 5,
}) async {
final walletAddress = _solanaPublicKey.toAddress().address;
+ _seedTokenInfoCache();
for (int i = 0; i < maxRetries; i++) {
await Future.delayed(initialDelay * (i + 1));
### cw_solana/lib/solana_wallet_service.dart
@@ -4,6 +4,7 @@ import 'package:bip39/bip39.dart' as bip39;
import 'package:cw_core/encryption_file_utils.dart';
import 'package:cw_core/balance.dart';
import "package:cw_core/imported_nft.dart";
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/spl_token.dart';
import 'package:cw_core/transaction_history.dart';
@@ -58,7 +59,7 @@ class SolanaWalletService extends WalletService<
Future<SolanaWallet> openWallet(String name, String password) async {
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
try {
@@ -96,7 +97,7 @@ class SolanaWalletService extends WalletService<
await File(await pathForWalletDir(name: wallet, type: getType())).delete(recursive: true);
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet, type: getType());
}
await WalletInfo.delete(walletInfo);
final nameStillUsed = await WalletInfo.get(wallet, getType()) != null;
### cw_solana/pubspec.yaml
@@ -13,12 +13,9 @@ dependencies:
sdk: flutter
cw_core:
path: ../cw_core
- http: ^1.1.0
- hive: ^2.2.3
bip39: ^1.0.6
mobx: ^2.3.0+1
shared_preferences: ^2.0.15
- bip32: ^2.0.0
hex: ^0.2.0
on_chain:
git:
### cw_tron/lib/tron_balance.dart
@@ -17,7 +17,7 @@ class TronBalance extends Balance {
final decoded = json.decode(jsonSource) as Map;
try {
- return TronBalance(Money(BigInt.parse(decoded['balance']), currency));
+ return TronBalance(Money(BigInt.parse(decoded['balance'] as String), currency));
} catch (e) {
return TronBalance(Money.zero(currency));
}
### cw_tron/lib/tron_client.dart
@@ -6,12 +6,14 @@ import 'package:blockchain_utils/blockchain_utils.dart';
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/currency.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/node.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_tron/default_tron_tokens.dart';
import 'package:cw_tron/pending_tron_transaction.dart';
import 'package:cw_tron/tron_abi.dart';
import 'package:cw_tron/tron_balance.dart';
+import "package:cw_tron/tron_fee_estimate.dart";
import 'package:cw_tron/tron_http_provider.dart';
import 'package:cw_core/tron_token.dart';
import 'package:cw_tron/tron_transaction_model.dart';
@@ -27,6 +29,8 @@ class TronClient {
// This is an internal tracker, so we don't have to "refetch".
int _nativeTxEstimatedFee = 0;
+ static const _historyRequestTimeout = Duration(seconds: 30);
+
Future<List<TronTransactionModel>> fetchTransactions(String address,
{String? contractAddress}) async {
try {
@@ -43,7 +47,7 @@ class TronClient {
'Content-Type': 'application/json',
'TRON-PRO-API-KEY': secrets.tronGridApiKey,
},
- );
+ ).timeout(_historyRequestTimeout);
final jsonResponse = json.decode(response.body) as Map<String, dynamic>;
if (response.statusCode >= 200 &&
@@ -76,15 +80,17 @@ class TronClient {
'Content-Type': 'application/json',
'TRON-PRO-API-KEY': secrets.tronGridApiKey,
},
- );
+ ).timeout(_historyRequestTimeout);
final jsonResponse = json.decode(response.body) as Map<String, dynamic>;
if (response.statusCode >= 200 &&
response.statusCode < 300 &&
jsonResponse['status'] != false) {
- return (jsonResponse['data'] as List).map((e) {
- return TronTRC20TransactionModel.fromJson(e as Map<String, dynamic>);
- }).toList();
+ return (jsonResponse["data"] as List<dynamic>)
+ .cast<Map<String, dynamic>>()
+ .where((e) => e["type"] == "Transfer")
+ .map(TronTRC20TransactionModel.fromJson)
+ .toList();
}
return [];
@@ -118,12 +124,13 @@ class TronClient {
}
}
- Future<int> getFeeLimit(
+ Future<TronFeeEstimate> getFeeEstimate(
TransactionRaw rawTransaction,
TronAddress address,
TronAddress receiverAddress, {
int energyUsed = 0,
bool isEstimatedFeeFlow = false,
+ bool throwOnError = false,
}) async {
try {
// Get the tron chain parameters.
@@ -144,52 +151,40 @@ class TronClient {
final transactionSize = fakeTransaction.length + 64;
// Assign the calculated size to the variable representing the required bandwidth.
- int neededBandWidth = transactionSize;
+ final neededBandWidth = transactionSize;
log('Initial Needed Bandwidth: $neededBandWidth');
-
- int neededEnergy = energyUsed;
- log('Initial Needed Energy: $neededEnergy');
+ log("Initial Needed Energy: $energyUsed");
// Fetch account resources to assess the available bandwidth and energy
final accountResource =
await _provider!.request(TronRequestGetAccountResource(address: address));
- neededEnergy -= accountResource.howManyEnergy.toInt();
- log('Account resource energy: ${accountResource.howManyEnergy.toInt()}');
- log('Needed Energy after deducting from account resource energy: $neededEnergy');
+ final availableEnergy = accountResource.howManyEnergy.toInt();
+ log("Account resource energy: $availableEnergy");
- // Deduct the bandwidth from the account's available bandwidth.
final BigInt accountBandWidth = accountResource.howManyBandwIth;
- log('Account resource bandwidth: ${accountResource.howManyBandwIth.toInt()}');
-
- if (accountBandWidth >= BigInt.from(neededBandWidth) && !isEstimatedFeeFlow) {
- log('Account has more bandwidth than required');
- neededBandWidth = 0;
- }
-
- if (neededEnergy < 0) {
- neededEnergy = 0;
- }
-
- final energyBurn = neededEnergy * energyInSun.toInt();
- log('Energy Burn: $energyBurn');
-
- final bandWidthBurn = neededBandWidth * bandWidthInSun;
- log('Bandwidth Burn: $bandWidthBurn');
+ log("Account resource bandwidth: ${accountBandWidth.toInt()}");
+
+ final feeEstimate = TronFeeEstimate.calculate(
+ energyUsed: energyUsed,
+ availableEnergy: availableEnergy,
+ energyPrice: energyInSun.toInt(),
+ bandwidthUsed: neededBandWidth,
+ isBandwidthBurned: isEstimatedFeeFlow || accountBandWidth < BigInt.from(neededBandWidth),
+ bandwidthPrice: bandWidthInSun,
+ memoFee: rawTransaction.data != null ? chainParams.getMemoFee! : 0,
+ );
- int totalBurn = energyBurn + bandWidthBurn;
- log('Total Burn: $totalBurn');
+ log("Fee limit: ${feeEstimate.feeLimit}");
+ log("Estimated burn: ${feeEstimate.estimatedBurn}");
- /// If there is a note (memo), calculate the memo fee.
- if (rawTransaction.data != null) {
- totalBurn += chainParams.getMemoFee!;
+ return feeEstimate;
+ } catch (e) {
+ log("Tron fee estimate failed: $e");
+ if (throwOnError) {
+ rethrow;
}
-
- log('Final total burn: $totalBurn');
-
- return totalBurn;
- } catch (_) {
- return 0;
+ return const TronFeeEstimate.zero();
}
}
@@ -224,12 +219,13 @@ class TronClient {
timestamp: block.blockHeader.rawData.timestamp,
);
- final estimatedFee = await getFeeLimit(
+ final feeEstimate = await getFeeEstimate(
rawTransaction,
ownerAddress,
ownerAddress,
isEstimatedFeeFlow: true,
);
+ final estimatedFee = feeEstimate.estimatedBurn;
_nativeTxEstimatedFee = estimatedFee;
@@ -256,13 +252,15 @@ class TronClient {
log("Tron TRC20 error: ${request.error} \n ${request.respose}");
}
- return getFeeLimit(
+ final feeEstimate = await getFeeEstimate(
request.transactionRaw!,
ownerAddress,
ownerAddress,
energyUsed: request.energyUsed ?? 0,
isEstimatedFeeFlow: true,
);
+
+ return feeEstimate.estimatedBurn;
}
Future<PendingTronTransaction> signTransaction({
@@ -281,7 +279,7 @@ class TronClient {
final isNativeTransaction = amount.currency == CryptoCurrency.trx;
Money totalAmount;
- TransactionRaw rawTransaction;
+ _PreparedTronTransaction preparedTransaction;
if (isNativeTransaction) {
if (sendAll) {
final accountResource =
@@ -301,7 +299,7 @@ class TronClient {
} else {
totalAmount = amount;
}
- rawTransaction = await _signNativeTransaction(
+ preparedTransaction = await _signNativeTransaction(
ownerAddress,
receiverAddress,
totalAmount,
@@ -311,7 +309,7 @@ class TronClient {
} else {
final tokenAddress = (amount.currency as TronToken).contractAddress;
totalAmount = amount;
- rawTransaction = await _signTrcTokenTransaction(
+ preparedTransaction = await _signTrcTokenTransaction(
ownerAddress,
receiverAddress,
totalAmount,
@@ -320,6 +318,7 @@ class TronClient {
);
}
+ final rawTransaction = preparedTransaction.rawTransaction;
final signature = ownerPrivKey.sign(rawTransaction.toBuffer());
sendTx() async => await sendTransaction(
@@ -330,12 +329,12 @@ class TronClient {
return PendingTronTransaction(
signedTransaction: signature,
amount: totalAmount,
- fee: Money(rawTransaction.feeLimit ?? BigInt.zero, CryptoCurrency.trx),
+ fee: Money(BigInt.from(preparedTransaction.estimatedFee), CryptoCurrency.trx),
sendTransaction: sendTx,
id: rawTransaction.txID);
}
- Future<TransactionRaw> _signNativeTransaction(
+ Future<_PreparedTronTransaction> _signNativeTransaction(
TronAddress ownerAddress,
TronAddress receiverAddress,
Money amount,
@@ -372,21 +371,25 @@ class TronClient {
timestamp: block.blockHeader.rawData.timestamp,
);
- final feeLimit = await getFeeLimit(rawTransaction, ownerAddress, receiverAddress);
+ final feeEstimate = await getFeeEstimate(rawTransaction, ownerAddress, receiverAddress);
+ final feeLimit = feeEstimate.estimatedBurn;
final feeLimitToUse = feeLimit != 0 ? feeLimit : defaultFeeLimit;
final tronBalanceInt = tronBalance.toInt();
if (feeLimit > tronBalanceInt) {
final feeInTrx = TronHelper.fromSun(BigInt.parse(feeLimit.toString()));
- throw Exception(
+ throw TransactionGenerationException(
'You don\'t have enough TRX to cover the transaction fee for this transaction. Please top up.\nTransaction fee: $feeInTrx TRX',
);
}
- return rawTransaction.copyWith(feeLimit: BigInt.from(feeLimitToUse));
+ return _PreparedTronTransaction(
+ rawTransaction: rawTransaction.copyWith(feeLimit: BigInt.from(feeLimitToUse)),
+ estimatedFee: feeLimitToUse,
+ );
}
- Future<TransactionRaw> _signTrcTokenTransaction(
+ Future<_PreparedTronTransaction> _signTrcTokenTransaction(
TronAddress ownerAddress,
TronAddress receiverAddress,
Money amount,
@@ -407,24 +410,36 @@ class TronClient {
if (!request.isSuccess) {
log("Tron TRC20 error: ${request.error} \n ${request.respose}");
- throw Exception('An error occurred while creating the transfer request. Please try again.');
+ throw TransactionGenerationException('An error occurred while creating the transfer request. Please try again.');
}
- final feeLimit = await getFeeLimit(
+ // A zero fee limit gives the call no energy at all, so a missing estimate stops the send.
+ final energyUsed = request.energyUsed;
+ if (energyUsed == null) {
+ throw TransactionGenerationException(
+ "Could not estimate the energy for this transfer. Please try again.",
+ );
+ }
+
+ final feeEstimate = await getFeeEstimate(
request.transactionRaw!,
ownerAddress,
receiverAddress,
- energyUsed: request.energyUsed ?? 0,
+ energyUsed: energyUsed,
+ throwOnError: true,
);
- if (feeLimit > tronBalance.toInt()) {
- final feeInTrx = TronHelper.fromSun(BigInt.parse(feeLimit.toString()));
- throw Exception(
+ if (feeEstimate.estimatedBurn > tronBalance.toInt()) {
+ final feeInTrx = TronHelper.fromSun(BigInt.from(feeEstimate.estimatedBurn));
+ throw TransactionGenerationException(
'You don\'t have enough TRX to cover the transaction fee for this transaction. Please top up. Transaction fee: $feeInTrx TRX',
);
}
- return request.transactionRaw!.copyWith(feeLimit: BigInt.from(feeLimit));
+ return _PreparedTronTransaction(
+ rawTransaction: request.transactionRaw!.copyWith(feeLimit: BigInt.from(feeEstimate.feeLimit)),
+ estimatedFee: feeEstimate.estimatedBurn,
+ );
}
Future<String> sendTransaction({
@@ -441,11 +456,11 @@ class TronClient {
if (txBroadcastResult.isSuccess) {
return txBroadcastResult.txId!;
} else {
- throw Exception(txBroadcastResult.error);
+ throw TransactionSendingException(txBroadcastResult.error??"");
}
} catch (e) {
log('Send block Exception: ${e.toString()}');
- throw Exception(e);
+ throw TransactionSendingException(e.toString());
}
}
@@ -466,7 +481,7 @@ class TronClient {
),
);
- final outputResult = request.outputResult?.first ?? BigInt.zero;
+ final outputResult = request.outputResult?.first as BigInt? ?? BigInt.zero;
return TronBalance(Money(outputResult, currency));
} catch (_) {
@@ -534,3 +549,13 @@ class TronClient {
}
}
}
+
+class _PreparedTronTransaction {
+ const _PreparedTronTransaction({
+ required this.rawTransaction,
+ required this.estimatedFee,
+ });
+
+ final TransactionRaw rawTransaction;
+ final int estimatedFee;
+}
### cw_tron/lib/tron_fee_estimate.dart
@@ -0,0 +1,31 @@
+class TronFeeEstimate {
+ const TronFeeEstimate({
+ required this.feeLimit,
+ required this.estimatedBurn,
+ });
+
+ const TronFeeEstimate.zero()
+ : feeLimit = 0,
+ estimatedBurn = 0;
+
+ factory TronFeeEstimate.calculate({
+ required int energyUsed,
+ required int availableEnergy,
+ required int energyPrice,
+ required int bandwidthUsed,
+ required bool isBandwidthBurned,
+ required int bandwidthPrice,
+ int memoFee = 0,
+ }) {
+ final energyToBurn = energyUsed > availableEnergy ? energyUsed - availableEnergy : 0;
+ final bandwidthToBurn = isBandwidthBurned ? bandwidthUsed : 0;
+
+ return TronFeeEstimate(
+ feeLimit: energyUsed * energyPrice * 120 ~/ 100, // the 20% covers any dynamic energy increase that can happen
+ estimatedBurn: energyToBurn * energyPrice + bandwidthToBurn * bandwidthPrice + memoFee,
+ );
+ }
+
+ final int feeLimit;
+ final int estimatedBurn;
+}
### cw_tron/lib/tron_transaction_info.dart
@@ -46,13 +46,13 @@ class TronTransactionInfo extends TransactionInfo {
return TronTransactionInfo(
id: data['id'] as String,
- amount: Money(BigInt.parse(data['tronAmount']), currency),
+ amount: Money(BigInt.parse(data['tronAmount'] as String), currency),
fee: Money.tryParse(data['txFee']?.toString() ?? '0', CryptoCurrency.trx, isBaseUnit: true),
direction: parseTransactionDirectionFromInt(data['direction'] as int),
blockTime: DateTime.fromMillisecondsSinceEpoch(data['blockTime'] as int),
- to: data['to'],
- from: data['from'],
- isPending: data['isPending'],
+ to: data['to'] as String?,
+ from: data['from'] as String?,
+ isPending: data['isPending'] as bool,
);
}
### cw_tron/lib/tron_transaction_model.dart
@@ -44,13 +44,13 @@ class TronTRC20TransactionModel extends TronTransactionModel {
});
TronTRC20TransactionModel.fromJson(Map<String, dynamic> json) {
- transactionId = json['transaction_id'];
- tokenSymbol = json['token_info'] != null ? json['token_info']['symbol'] : null;
- decimals = json['token_info'] != null ? json['token_info']['decimals'] : null;
- timestamp = json['block_timestamp'];
- from = json['from'];
- to = json['to'];
- value = json['value'];
+ transactionId = json['transaction_id'] as String?;
+ tokenSymbol = json['token_info'] != null ? json['token_info']['symbol'] as String? : null;
+ decimals = json['token_info'] != null ? json['token_info']['decimals'] as int? : null;
+ timestamp = json['block_timestamp'] as int?;
+ from = json['from'] as String?;
+ to = json['to'] as String?;
+ value = json['value'] as String?;
}
}
@@ -82,6 +82,8 @@ class TronTransactionModel {
String? get contractAddress => contracts?.first.parameter?.value?.contractAddress;
+ bool get isTrc20TransferCall => contracts?.first.parameter?.value?.isTrc20TransferCall ?? false;
+
TronTransactionModel({
this.ret,
this.txID,
@@ -93,11 +95,11 @@ class TronTransactionModel {
if (json['ret'] != null) {
ret = <Ret>[];
json['ret'].forEach((v) {
- ret!.add(Ret.fromJson(v));
+ ret!.add(Ret.fromJson(v as Map<String, dynamic>));
});
}
- txID = json['txID'];
- blockTimestamp = json['block_timestamp'];
+ txID = json['txID'] as String?;
+ blockTimestamp = json['block_timestamp'] as int?;
contracts = json['raw_data'] != null
? (json['raw_data']['contract'] as List)
.map((e) => Contract.fromJson(e as Map<String, dynamic>))
@@ -113,8 +115,8 @@ class Ret {
Ret({this.contractRet, this.fee});
Ret.fromJson(Map<String, dynamic> json) {
- contractRet = json['contractRet'];
- fee = json['fee'];
+ contractRet = json['contractRet'] as String?;
+ fee = json['fee'] as int?;
}
}
@@ -125,8 +127,10 @@ class Contract {
Contract({this.parameter, this.type});
Contract.fromJson(Map<String, dynamic> json) {
- parameter = json['parameter'] != null ? Parameter.fromJson(json['parameter']) : null;
- type = json['type'];
+ parameter = json['parameter'] != null
+ ? Parameter.fromJson(json['parameter'] as Map<String, dynamic>)
+ : null;
+ type = json['type'] as String?;
}
}
@@ -137,8 +141,8 @@ class Parameter {
Parameter({this.value, this.typeUrl});
Parameter.fromJson(Map<String, dynamic> json) {
- value = json['value'] != null ? Value.fromJson(json['value']) : null;
- typeUrl = json['type_url'];
+ value = json['value'] != null ? Value.fromJson(json['value'] as Map<String, dynamic>) : null;
+ typeUrl = json['type_url'] as String?;
}
}
@@ -147,66 +151,92 @@ class Value {
String? ownerAddress;
String? contractAddress;
int? amount;
+ int? callValue;
String? toAddress;
String? assetName;
+ /// Function selector of TRC20 `transfer(address,uint256)`.
+ static const _transferSelector = "a9059cbb";
+
+ /// Hex length of `transfer` calldata: the selector plus two 32-byte arguments.
+ static const _transferCallDataLength = 8 + 64 + 64;
+
+ String? get _callData {
+ final callData = data?.toLowerCase();
+ if (callData != null && callData.startsWith("0x")) {
+ return callData.substring(2);
+ }
+
+ return callData;
+ }
+
+ /// Only a TRC20 `transfer` carries a receiver and a token amount in its calldata.
+ /// Any other contract call (approve, swaps, deposit(), claim(), ...) has a different layout.
+ bool get isTrc20TransferCall {
+ final callData = _callData;
+
+ return contractAddress != null &&
+ callData != null &&
+ callData.length >= _transferCallDataLength &&
+ callData.startsWith(_transferSelector);
+ }
+
//Getters to extract address for tron transactions
/// If the contract address is null, it returns the toAddress
- /// If it's not null, it decodes the data field and gets the receiver address.
+ /// For a TRC20 transfer, it decodes the data field and gets the receiver address.
+ /// For any other contract call, it returns the called contract.
String? get receiverAddress {
if (contractAddress == null) return toAddress;
- if (data == null) return null;
+ if (!isTrc20TransferCall) return contractAddress;
- return _decodeAddressFromEncodedDataField(data!);
+ return _decodeAddressFromEncodedDataField(_callData!);
}
//Getters to extract amount for tron transactions
/// If the contract address is null, it returns the amount
- /// If it's not null, it decodes the data field and gets the tx amount.
+ /// For a TRC20 transfer, it decodes the data field and gets the token amount.
+ /// For any other contract call, it returns the TRX sent along with the call.
BigInt? get txAmount {
if (contractAddress == null) return BigInt.from(amount ?? 0);
- if (data == null) return null;
+ if (!isTrc20TransferCall) return BigInt.from(callValue ?? 0);
- return _decodeAmountInvolvedFromEncodedDataField(data!);
+ return _decodeAmountInvolvedFromEncodedDataField(_callData!);
}
Value(
{this.data,
this.ownerAddress,
this.contractAddress,
this.amount,
+ this.callValue,
this.toAddress,
this.assetName});
Value.fromJson(Map<String, dynamic> json) {
- data = json['data'];
- ownerAddress = json['owner_address'];
- contractAddress = json['contract_address'];
- amount = json['amount'];
- toAddress = json['to_address'];
- assetName = json['asset_name'];
+ data = json['data'] as String?;
+ ownerAddress = json['owner_address'] as String?;
+ contractAddress = json['contract_address'] as String?;
+ amount = json['amount'] as int?;
+ callValue = int.tryParse(json['call_value']?.toString() ?? "");
+ toAddress = json['to_address'] as String?;
+ assetName = json['asset_name'] as String?;
}
/// To get the address from the encoded data field
String _decodeAddressFromEncodedDataField(String output) {
// To get the receiver address from the encoded params
- output = output.replaceFirst('0x', '').substring(8);
+ output = output.substring(8);
final abiCoder = ABICoder.fromType('address');
final decoded = abiCoder.decode(AbiParameter.bytes, hex.decode(output));
final tronAddress = TronAddress.fromEthAddress((decoded.result as ETHAddress).toBytes());
return tronAddress.toString();
}
- /// To get the amount from the encoded data field
- BigInt _decodeAmountInvolvedFromEncodedDataField(String output) {
- output = output.replaceFirst('0x', '').substring(72);
- final amountAbiCoder = ABICoder.fromType('uint256');
- final decodedA = amountAbiCoder.decode(AbiParameter.uint256, hex.decode(output));
- final amount = decodedA.result as BigInt;
-
- return amount;
- }
+ /// To get the amount from the encoded data field.
+ /// Parsed directly, as on_chain's uint256 decoder rejects any value of 2^255 or more.
+ BigInt _decodeAmountInvolvedFromEncodedDataField(String output) =>
+ BigInt.parse(output.substring(72, _transferCallDataLength), radix: 16);
}
### cw_tron/lib/tron_wallet.dart
@@ -2,17 +2,19 @@ import 'dart:async';
import 'dart:convert';
import 'dart:developer';
-import 'package:bip39/bip39.dart' as bip39;
+import 'package:cw_core/utils/bip39_seed.dart';
import 'package:blockchain_utils/blockchain_utils.dart';
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/node.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/utils/print_verbose.dart";
import 'package:cw_core/wallet_addresses.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/wallet_info.dart';
@@ -30,6 +32,7 @@ import 'package:cw_tron/tron_transaction_info.dart';
import 'package:cw_tron/tron_wallet_addresses.dart';
import 'package:mobx/mobx.dart';
import 'package:on_chain/on_chain.dart';
+import "package:shared_preferences/shared_preferences.dart";
part 'tron_wallet.g.dart';
@@ -83,6 +86,11 @@ abstract class TronWalletBase
Timer? _transactionsUpdateTimer;
+ bool _isTimerUpdatingHistory = false;
+
+ /// TRC20 symbol and decimals by contract address; they never change on-chain.
+ final Map<String, CryptoCurrency> _trc20Currencies = {};
+
@override
WalletAddresses walletAddresses;
@@ -219,7 +227,7 @@ abstract class TronWalletBase
if (privateKey != null) return TronPrivateKey(privateKey);
- final seed = bip39.mnemonicToSeed(mnemonic!, passphrase: passphrase ?? '');
+ final seed = bip39MnemonicToSeed(mnemonic!, passphrase: passphrase ?? '');
// Derive a TRON private key from the seed
final bip44 = Bip44.fromSeed(seed, Bip44Coins.tron);
@@ -247,7 +255,7 @@ abstract class TronWalletBase
final isConnected = _client.connect(node);
if (!isConnected) {
- throw Exception("${walletInfo.type.name.toUpperCase()} Node connection failed");
+ throw ConnectionException("${walletInfo.type.name.toUpperCase()} Node connection failed");
}
_getEstimatedFees();
@@ -303,8 +311,14 @@ abstract class TronWalletBase
return;
}
await _updateBalance();
- await fetchTransactions();
- fetchTrc20ExcludedTransactions();
+
+ // History is best-effort: a TronGrid or parsing failure must not fail the sync.
+ try {
+ await fetchTransactions();
+ fetchTrc20ExcludedTransactions();
+ } catch (e) {
+ printV("Failed to fetch the Tron transaction history: $e");
+ }
syncStatus = SyncedSyncStatus();
} catch (e) {
@@ -324,7 +338,7 @@ abstract class TronWalletBase
(currency) =>
currency.title == tronCredentials.currency.title &&
currency.tag == tronCredentials.currency.tag,
- orElse: () => throw Exception(
+ orElse: () => throw TransactionGenerationException(
'Currency ${tronCredentials.currency.title} ${tronCredentials.currency.tag} is not accessible in the wallet, try to enable it first.'));
final walletBalanceForCurrency = balance[transactionCurrency]!.balance;
@@ -373,8 +387,21 @@ abstract class TronWalletBase
]);
}
+ Future<bool> checkIfScanProviderIsEnabled() async {
+ try {
+ return (await SharedPreferences.getInstance()).getBool("use_trongrid") ?? true;
+ } catch (e) {
+ printV("Could not read the TronGrid preference: $e");
+ return false;
+ }
+ }
+
@override
Future<Map<String, TronTransactionInfo>> fetchTransactions() async {
+ if (!await checkIfScanProviderIsEnabled()) {
+ return transactionHistory.transactions;
+ }
+
final address = _tronAddress;
final transactions = await _client.fetchTransactions(address);
@@ -385,52 +412,51 @@ abstract class TronWalletBase
final ownerAddress = TronAddress(_tronAddress);
+ // Looked up once per token contract in this update, not once per transaction.
+ final Map<String, CryptoCurrency> trc20Currencies = {};
+
for (var transactionModel in transactions) {
- if (transactionModel.isError) {
- continue;
- }
+ // A transaction that can't be parsed must not drop the rest of the history.
+ try {
+ if (transactionModel.isError) {
+ continue;
+ }
- // Filter out spam transactions that involve receiving TRC10 assets transaction, we deal with TRX and TRC20 transactions
- if (transactionModel.contracts?.first.type == "TransferAssetContract") {
- continue;
- }
+ // Filter out spam transactions that involve receiving TRC10 assets transaction, we deal with TRX and TRC20 transactions
+ if (transactionModel.contracts?.first.type == "TransferAssetContract") {
+ continue;
+ }
- var txCurrency = currency;
- if (transactionModel.contractAddress != null) {
- final tokenAddress = TronAddress(transactionModel.contractAddress!);
-
- final tokenSymbol = (await _client.getTokenDetail(
- contract,
- "symbol",
- ownerAddress,
- tokenAddress,
- ) as String?) ??
- '';
-
- final decimals = (await _client.getTokenDetail(
- contract,
- "decimals",
- ownerAddress,
- tokenAddress,
- ) as BigInt?)
- ?.toInt() ??
- txCurrency.decimals;
-
- txCurrency = CryptoCurrency(name: tokenSymbol, title: tokenSymbol, decimals: decimals);
- }
+ final saved = transactionHistory.transactions[transactionModel.hash];
+ if (!transactionModel.isTrc20TransferCall &&
+ saved != null &&
+ saved.amount.currency.symbol != currency.symbol) {
+ continue;
+ }
- result[transactionModel.hash] = TronTransactionInfo(
- id: transactionModel.hash,
- amount: Money(transactionModel.amount ?? BigInt.zero, txCurrency),
- direction: TronAddress(transactionModel.from!, visible: false).toAddress() == address
- ? TransactionDirection.outgoing
- : TransactionDirection.incoming,
- blockTime: transactionModel.date,
- fee: transactionModel.fee != null ? Money.fromInt(transactionModel.fee!, currency) : null,
- to: transactionModel.to,
- from: transactionModel.from,
- isPending: false,
- );
+ // Only a TRC20 transfer moves tokens, any other contract call is a TRX transaction.
+ var txCurrency = currency;
+ if (transactionModel.isTrc20TransferCall) {
+ final contractAddress = transactionModel.contractAddress!;
+ txCurrency = trc20Currencies[contractAddress] ??=
+ await _getTrc20Currency(contractAddress, contract, ownerAddress);
+ }
+
+ result[transactionModel.hash] = TronTransactionInfo(
+ id: transactionModel.hash,
+ amount: Money(transactionModel.amount ?? BigInt.zero, txCurrency),
+ direction: TronAddress(transactionModel.from!, visible: false).toAddress() == address
+ ? TransactionDirection.outgoing
+ : TransactionDirection.incoming,
+ blockTime: transactionModel.date,
+ fee: transactionModel.fee != null ? Money.fromInt(transactionModel.fee!, currency) : null,
+ to: transactionModel.to,
+ from: transactionModel.from,
+ isPending: false,
+ );
+ } catch (e) {
+ printV("Skipping Tron transaction ${transactionModel.txID}: $e");
+ }
}
transactionHistory.addMany(result);
@@ -440,30 +466,84 @@ abstract class TronWalletBase
return transactionHistory.transactions;
}
+ Future<CryptoCurrency> _getTrc20Currency(
+ String contractAddress,
+ ContractABI contract,
+ TronAddress ownerAddress,
+ ) async {
+ final cachedCurrency = _trc20Currencies[contractAddress];
+ if (cachedCurrency != null) {
+ return cachedCurrency;
+ }
+
+ final tokenAddress = TronAddress(contractAddress);
+
+ final tokenSymbol = await _client.getTokenDetail(
+ contract,
+ "symbol",
+ ownerAddress,
+ tokenAddress,
+ ) as String?;
+
+ final decimals = (await _client.getTokenDetail(
+ contract,
+ "decimals",
+ ownerAddress,
+ tokenAddress,
+ ) as BigInt?)
+ ?.toInt();
+
+ final txCurrency = CryptoCurrency(
+ name: tokenSymbol ?? "",
+ title: tokenSymbol ?? "",
+ decimals: decimals ?? currency.decimals,
+ );
+
+ // Failed lookups aren't cached, so the next history update retries them.
+ if (tokenSymbol != null && decimals != null) {
+ _trc20Currencies[contractAddress] = txCurrency;
+ }
+
+ return txCurrency;
+ }
+
Future<void> fetchTrc20ExcludedTransactions() async {
+ if (!await checkIfScanProviderIsEnabled()) {
+ return;
+ }
+
final address = _tronAddress;
final transactions = await _client.fetchTrc20ExcludedTransactions(address);
final Map<String, TronTransactionInfo> result = {};
for (final transactionModel in transactions) {
- if (transactionHistory.transactions.containsKey(transactionModel.hash)) {
- continue;
- }
+ try {
+ final saved = transactionHistory.transactions[transactionModel.hash];
+ if (saved != null && saved.amount.currency.symbol != currency.symbol) {
+ continue;
+ }
- result[transactionModel.hash] = TronTransactionInfo(
- id: transactionModel.hash,
- amount: Money(transactionModel.amount ?? BigInt.zero, transactionModel.currency),
- direction: transactionModel.from! == address
- ? TransactionDirection.outgoing
- : TransactionDirection.incoming,
- blockTime: transactionModel.date,
- fee: transactionModel.fee != null ? Money.fromInt(transactionModel.fee!, currency) : null,
- to: transactionModel.to,
- from: transactionModel.from,
- isPending: false,
- );
+ result[transactionModel.hash] = TronTransactionInfo(
+ id: transactionModel.hash,
+ amount: Money(transactionModel.amount ?? BigInt.zero, transactionModel.currency),
+ direction: transactionModel.from! == address
+ ? TransactionDirection.outgoing
+ : TransactionDirection.incoming,
+ blockTime: transactionModel.date,
+ // The TRC20 index has no real fee (its model reports 0), so keep the saved TRX row's.
+ fee: saved?.fee ??
+ (transactionModel.fee != null
+ ? Money.fromInt(transactionModel.fee!, currency)
+ : null),
+ to: transactionModel.to,
+ from: transactionModel.from,
+ isPending: false,
+ );
+ } catch (e) {
+ printV("Skipping Tron TRC20 transaction ${transactionModel.transactionId}: $e");
+ }
}
transactionHistory.addMany(result);
@@ -620,8 +700,21 @@ abstract class TronWalletBase
_transactionsUpdateTimer = Timer.periodic(const Duration(seconds: 30), (_) async {
_updateBalance();
- await fetchTransactions();
- fetchTrc20ExcludedTransactions();
+
+ // A history update can outlast the period; don't stack another one on top of it.
+ if (_isTimerUpdatingHistory) {
+ return;
+ }
+
+ _isTimerUpdatingHistory = true;
+ try {
+ await fetchTransactions();
+ await fetchTrc20ExcludedTransactions();
+ } catch (e) {
+ printV("Failed to update the Tron transaction history: $e");
+ } finally {
+ _isTimerUpdatingHistory = false;
+ }
});
}
@@ -645,8 +738,6 @@ abstract class TronWalletBase
fetchTransactions();
fetchTrc20ExcludedTransactions();
_setTransactionUpdateTimer();
- } else {
- _transactionsUpdateTimer?.cancel();
}
}
### cw_tron/lib/tron_wallet_service.dart
@@ -3,6 +3,7 @@ import 'dart:io';
import 'package:bip39/bip39.dart' as bip39;
import 'package:cw_core/balance.dart';
import 'package:cw_core/encryption_file_utils.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/transaction_history.dart';
import 'package:cw_core/transaction_info.dart';
@@ -56,7 +57,7 @@ class TronWalletService extends WalletService<
Future<TronWallet> openWallet(String name, String password) async {
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
try {
@@ -143,7 +144,7 @@ class TronWalletService extends WalletService<
File(await pathForWalletDir(name: wallet, type: getType())).delete(recursive: true);
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet, type: getType());
}
await WalletInfo.delete(walletInfo);
final nameStillUsed = await WalletInfo.get(wallet, getType()) != null;
### cw_tron/pubspec.yaml
@@ -13,8 +13,6 @@ dependencies:
sdk: flutter
cw_core:
path: ../cw_core
- cw_evm:
- path: ../cw_evm
on_chain:
git:
url: https://github.com/cake-tech/on_chain.git
@@ -25,7 +23,7 @@ dependencies:
ref: 59fdf29d72068e0522a96a8953ed7272833a9f57
mobx: ^2.3.0+1
bip39: ^1.0.6
- hive: ^2.2.3
+ shared_preferences: ^2.0.15
dev_dependencies:
flutter_test:
### cw_tron/test/tron_fee_estimate_test.dart
@@ -0,0 +1,74 @@
+import "package:cw_tron/tron_fee_estimate.dart";
+import "package:flutter_test/flutter_test.dart";
+
+void main() {
+ const usdtTransferEnergy = 64285;
+ const energyPrice = 210;
+ const transactionBytes = 339;
+ const bandwidthPrice = 1000;
+
+ TronFeeEstimate estimate({
+ required int availableEnergy,
+ bool isBandwidthBurned = true,
+ int memoFee = 0,
+ }) =>
+ TronFeeEstimate.calculate(
+ energyUsed: usdtTransferEnergy,
+ availableEnergy: availableEnergy,
+ energyPrice: energyPrice,
+ bandwidthUsed: transactionBytes,
+ isBandwidthBurned: isBandwidthBurned,
+ bandwidthPrice: bandwidthPrice,
+ memoFee: memoFee,
+ );
+
+ test("rented energy that covers the call still gets a fee limit for the whole call", () {
+ final result = estimate(availableEnergy: 130000);
+
+ expect(result.feeLimit ~/ energyPrice, greaterThanOrEqualTo(usdtTransferEnergy));
+ expect(result.feeLimit, 16199820);
+ expect(result.estimatedBurn, 339000);
+ });
+
+ test("rented energy and free bandwidth burn nothing but keep the fee limit", () {
+ final result = estimate(availableEnergy: 130000, isBandwidthBurned: false);
+
+ expect(result.feeLimit, 16199820);
+ expect(result.estimatedBurn, 0);
+ });
+
+ test("partial energy only lowers the burn", () {
+ final result = estimate(availableEnergy: 20000);
+
+ expect(result.feeLimit, 16199820);
+ expect(result.estimatedBurn, 44285 * energyPrice + 339000);
+ });
+
+ test("no energy burns the whole call", () {
+ final result = estimate(availableEnergy: 0);
+
+ expect(result.feeLimit, 16199820);
+ expect(result.estimatedBurn, usdtTransferEnergy * energyPrice + 339000);
+ });
+
+ test("memo fee adds to the burn and not to the fee limit", () {
+ final result = estimate(availableEnergy: 130000, isBandwidthBurned: false, memoFee: 1000000);
+
+ expect(result.feeLimit, 16199820);
+ expect(result.estimatedBurn, 1000000);
+ });
+
+ test("native transfers use no energy", () {
+ final result = TronFeeEstimate.calculate(
+ energyUsed: 0,
+ availableEnergy: 0,
+ energyPrice: energyPrice,
+ bandwidthUsed: 268,
+ isBandwidthBurned: true,
+ bandwidthPrice: bandwidthPrice,
+ );
+
+ expect(result.feeLimit, 0);
+ expect(result.estimatedBurn, 268000);
+ });
+}
### cw_tron/test/tron_transaction_model_test.dart
@@ -0,0 +1,179 @@
+import "package:cw_tron/tron_transaction_model.dart";
+import "package:flutter_test/flutter_test.dart";
+
+// Wallet TCFuFnoos25WL99j9y3u92LR67mVwrTvrQ and the USDT contract TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t.
+const _owner = "41191882614f605dd84703252b196c0c006b5482f8";
+const _usdtContract = "41a614f803b6fd780986a42c78ec9c7f77e6ded13c";
+
+// Real TronGrid entries of TCFuFnoos25WL99j9y3u92LR67mVwrTvrQ.
+const _unlimitedApprove = {
+ "ret": [
+ {"contractRet": "SUCCESS", "fee": 9976400},
+ ],
+ "txID": "fc20c9c9489842cf105c56c80e9fce540e55f1158d68459bc625332bae5b9806",
+ "block_timestamp": 1769113440000,
+ "raw_data": {
+ "contract": [
+ {
+ "parameter": {
+ "value": {
+ "data": "095ea7b3000000000000000000000000bbbd3bd87c268b8030bc2edae7021830af599ed2"
+ "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
+ "owner_address": _owner,
+ "contract_address": _usdtContract,
+ },
+ "type_url": "type.googleapis.com/protocol.TriggerSmartContract",
+ },
+ "type": "TriggerSmartContract",
+ },
+ ],
+ },
+};
+
+const _usdtTransfer = {
+ "ret": [
+ {"contractRet": "SUCCESS", "fee": 6428500},
+ ],
+ "txID": "0584051e5208526f48d05965a4e15c48f6ec84c23c71441ed6e38a8a49c17faf",
+ "block_timestamp": 1768779375000,
+ "raw_data": {
+ "contract": [
+ {
+ "parameter": {
+ "value": {
+ "data": "a9059cbb000000000000000000000000ca5125c5947162497b1b924d6c5e282282e3351f"
+ "00000000000000000000000000000000000000000000000000000000139c2440",
+ "owner_address": _owner,
+ "contract_address": _usdtContract,
+ },
+ "type_url": "type.googleapis.com/protocol.TriggerSmartContract",
+ },
+ "type": "TriggerSmartContract",
+ },
+ ],
+ },
+};
+
+const _trxTransfer = {
+ "ret": [
+ {"contractRet": "SUCCESS", "fee": 0},
+ ],
+ "txID": "a5bf8fb4aa16496e53ad36fcfbe3f49c92c0e0cc0caffc97d3cc2fe8a9e16ede",
+ "block_timestamp": 1791643617000,
+ "raw_data": {
+ "contract": [
+ {
+ "parameter": {
+ "value": {
+ "amount": 1,
+ "owner_address": "415576b7edd2a7cb0ebb6f794d7f2c28aa5dc85a82",
+ "to_address": _owner,
+ },
+ "type_url": "type.googleapis.com/protocol.TransferContract",
+ },
+ "type": "TransferContract",
+ },
+ ],
+ },
+};
+
+TronTransactionModel _contractCall(String? data, {Object? callValue}) =>
+ TronTransactionModel.fromJson({
+ "ret": [
+ {"contractRet": "SUCCESS", "fee": 1},
+ ],
+ "txID": "test",
+ "block_timestamp": 1,
+ "raw_data": {
+ "contract": [
+ {
+ "parameter": {
+ "value": {
+ if (data != null) "data": data,
+ if (callValue != null) "call_value": callValue,
+ "owner_address": _owner,
+ "contract_address": _usdtContract,
+ },
+ },
+ "type": "TriggerSmartContract",
+ },
+ ],
+ },
+ });
+
+String _word(String hex) => hex.padLeft(64, "0");
+
+void main() {
+ group("TronTransactionModel", () {
+ test("decodes the receiver and token amount of a TRC20 transfer", () {
+ final transaction = TronTransactionModel.fromJson(_usdtTransfer);
+
+ expect(transaction.isTrc20TransferCall, isTrue);
+ expect(transaction.amount, BigInt.from(329000000));
+ expect(transaction.to, "TUQxi3DkhbrL9qL5EHEfAmkZbsPBGP1UnH");
+ expect(transaction.from, _owner);
+ expect(transaction.contractAddress, _usdtContract);
+ });
+
+ test("reads an unlimited approve as a TRX call to the contract instead of throwing", () {
+ final transaction = TronTransactionModel.fromJson(_unlimitedApprove);
+
+ expect(transaction.isError, isFalse);
+ expect(transaction.isTrc20TransferCall, isFalse);
+ expect(transaction.amount, BigInt.zero);
+ expect(transaction.to, _usdtContract);
+ expect(transaction.fee, 9976400);
+ });
+
+ test("decodes transfer amounts of 2^255 and above", () {
+ final maxUint256 = (BigInt.one << 256) - BigInt.one;
+ final transaction = _contractCall(
+ "a9059cbb${_word("ca5125c5947162497b1b924d6c5e282282e3351f")}${"f" * 64}",
+ );
+
+ expect(transaction.isTrc20TransferCall, isTrue);
+ expect(transaction.amount, maxUint256);
+ });
+
+ test("decodes 0x-prefixed, upper-case transfer calldata", () {
+ final transaction = _contractCall(
+ "0xA9059CBB${_word("CA5125C5947162497B1B924D6C5E282282E3351F")}${_word("139C2440")}",
+ );
+
+ expect(transaction.isTrc20TransferCall, isTrue);
+ expect(transaction.amount, BigInt.from(329000000));
+ expect(transaction.to, "TUQxi3DkhbrL9qL5EHEfAmkZbsPBGP1UnH");
+ });
+
+ test("reads other contract calls as the TRX sent with them", () {
+ final deposit = _contractCall("d0e30db0", callValue: 5000000);
+ final withdraw = _contractCall("2e1a7d4d${_word("3e8")}");
+ final noCalldata = _contractCall(null, callValue: 7);
+ final truncatedTransfer =
+ _contractCall("a9059cbb${_word("ca5125c5947162497b1b924d6c5e282282e3351f")}");
+
+ for (final transaction in [deposit, withdraw, noCalldata, truncatedTransfer]) {
+ expect(transaction.isTrc20TransferCall, isFalse);
+ expect(transaction.to, _usdtContract);
+ }
+ expect(deposit.amount, BigInt.from(5000000));
+ expect(withdraw.amount, BigInt.zero);
+ expect(noCalldata.amount, BigInt.from(7));
+ expect(truncatedTransfer.amount, BigInt.zero);
+ });
+
+ test("parses call_value sent as a string", () {
+ expect(_contractCall("d0e30db0", callValue: "42").amount, BigInt.from(42));
+ });
+
+ test("keeps TRX transfers unchanged", () {
+ final transaction = TronTransactionModel.fromJson(_trxTransfer);
+
+ expect(transaction.isTrc20TransferCall, isFalse);
+ expect(transaction.contractAddress, isNull);
+ expect(transaction.amount, BigInt.one);
+ expect(transaction.to, _owner);
+ expect(transaction.from, "415576b7edd2a7cb0ebb6f794d7f2c28aa5dc85a82");
+ });
+ });
+}
### cw_wownero/lib/api/wallet_manager.dart
@@ -100,7 +100,7 @@ void restoreWalletFromSeedSync(
required String seed,
int nettype = 0,
int restoreHeight = 0}) {
- var newWptr;
+ final wownero.wallet newWptr;
if (seed.split(" ").length == 14) {
txhistory = null;
newWptr = wownero.WOWNERO_deprecated_restore14WordSeed(
### cw_wownero/lib/wownero_wallet.dart
@@ -137,6 +137,12 @@ abstract class WowneroWalletBase
@override
bool get hasRescan => true;
+ @override
+ bool get hasCoinControl => true;
+
+ @override
+ bool get hasAccountsSupport => true;
+
@override
MoneroWalletKeys get keys => MoneroWalletKeys(
primaryAddress: wownero_wallet.getAddress(accountIndex: 0, addressIndex: 0),
### cw_wownero/lib/wownero_wallet_service.dart
@@ -1,6 +1,7 @@
import 'dart:ffi';
import 'dart:io';
import 'package:cw_core/exceptions.dart' show WalletDeprecationException;
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/monero_wallet_utils.dart';
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/unspent_coins_info.dart';
@@ -231,7 +232,7 @@ class WowneroWalletService extends WalletService<
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet);
}
await WalletInfo.delete(walletInfo);
}
@@ -240,7 +241,7 @@ class WowneroWalletService extends WalletService<
Future<void> rename(String currentName, String password, String newName) async {
final currentWalletInfo = await WalletInfo.get(currentName, getType());
if (currentWalletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: currentName);
}
final currentWallet = WowneroWallet(
walletInfo: currentWalletInfo,
### cw_wownero/pubspec.yaml
@@ -12,19 +12,14 @@ dependencies:
flutter:
sdk: flutter
ffi: ^2.0.1
- http: ^1.1.0
- path_provider: ^2.0.11
mobx: ^2.6.0
- flutter_mobx: ^2.3.0
- intl: any
- encrypt: ^5.0.1
polyseed: ^0.0.7
cw_core:
path: ../cw_core
monero:
git:
url: https://github.com/mrcyjanek/monero_c.git
- ref: cd4fe366cc8d3c188c91de279f43b29c0e044b15
+ ref: 33671871de3d51696b66ffb3bd94f744e26974f6
path: impls/monero.dart
mutex: ^3.1.0
### cw_zano/lib/bip39_seed.dart
@@ -3,6 +3,7 @@ import 'dart:typed_data';
import 'package:bip32/bip32.dart' as bip32;
import 'package:bip39/bip39.dart' as bip39;
import 'package:bip39/src/wordlists/english.dart' as bip39_english;
+import 'package:cw_core/utils/bip39_seed.dart';
bool isBip39Seed(String mnemonic) => bip39.validateMnemonic(mnemonic);
@@ -12,7 +13,7 @@ String generateBip39Mnemonic({int strength = 128}) =>
bip39.generateMnemonic(strength: strength);
String getSecretDerivationFromBip39(String mnemonic, {String passphrase = ''}) {
- final seed = bip39.mnemonicToSeed(mnemonic, passphrase: passphrase);
+ final seed = bip39MnemonicToSeed(mnemonic, passphrase: passphrase);
final bip32KeyPair = bip32.BIP32.fromSeed(seed).derivePath("m/44'/128'/0'/0/0");
### cw_zano/lib/zano_wallet.dart
@@ -122,6 +122,7 @@ abstract class ZanoWalletBase
bool _isTransactionUpdating;
bool _hasSyncAfterStartup;
Timer? _autoSaveTimer;
+ bool _isClosed = false;
/// number of transactions in each request
static final int _txChunkSize = (pow(2, 32) - 1).toInt();
@@ -422,6 +423,7 @@ abstract class ZanoWalletBase
@override
Future<void> close({bool shouldCleanup = true}) async {
+ _isClosed = true;
closeWallet(null);
_updateSyncInfoTimer?.cancel();
_autoSaveTimer?.cancel();
@@ -534,6 +536,9 @@ abstract class ZanoWalletBase
await walletAddresses.init();
await walletAddresses.updateAddress(address);
await updateTransactions();
+ if (_isClosed) {
+ return;
+ }
_autoSaveTimer = Timer.periodic(Duration(seconds: _autoSaveIntervalSeconds), (_) async {
await save();
});
### cw_zano/lib/zano_wallet_api.dart
@@ -3,6 +3,7 @@ import 'dart:ffi';
import 'dart:io';
import 'dart:isolate';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/transaction_priority.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/zano_asset.dart';
@@ -458,6 +459,13 @@ mixin ZanoWalletApi {
static Map<String, CreateWalletResult> openWalletCache = {};
+ static Future<void> closeCachedWallet(String path) async {
+ final cached = openWalletCache.remove(path);
+ if (cached != null) {
+ await _closeWallet(cached.walletId);
+ }
+ }
+
Future<TransferResult> transfer(
List<Destination> destinations, BigInt fee, String comment) async {
final params = TransferParams(
@@ -498,18 +506,18 @@ mixin ZanoWalletApi {
if (responseData['error'] != null) {
printV('ZANO sign_message error: ${responseData['error']}');
- throw Exception('Zano sign_message failed: ${responseData['error']}');
+ throw MessageSignException('Zano sign_message failed: ${responseData['error']}');
}
final result = responseData['result'] as Map<String, dynamic>?;
if (result == null) {
- throw Exception('Invalid response from sign_message');
+ throw MessageSignException('Invalid response from sign_message');
}
final signature = result['sig'] as String?;
if (signature == null) {
- throw Exception('No signature in response');
+ throw MessageSignException('No signature in response');
}
return signature;
### cw_zano/lib/zano_wallet_service.dart
@@ -1,6 +1,7 @@
import 'dart:io';
import 'package:collection/collection.dart';
+import "package:cw_core/exceptions/cake_exception.dart";
import 'package:cw_core/encryption_file_utils.dart';
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/utils/print_verbose.dart';
@@ -88,7 +89,7 @@ class ZanoWalletService extends WalletService<
Future<ZanoWallet> openWallet(String name, String password) async {
final walletInfo = await WalletInfo.get(name, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: name, type: getType());
}
try {
final wallet =
@@ -112,6 +113,7 @@ class ZanoWalletService extends WalletService<
@override
Future<void> remove(String wallet) async {
+ await ZanoWalletApi.closeCachedWallet(await pathForWallet(name: wallet, type: getType()));
final path = await pathForWalletDir(name: wallet, type: getType());
final file = Directory(path);
final isExist = file.existsSync();
@@ -122,7 +124,7 @@ class ZanoWalletService extends WalletService<
final walletInfo = await WalletInfo.get(wallet, getType());
if (walletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: wallet, type: getType());
}
await WalletInfo.delete(walletInfo);
}
@@ -131,7 +133,7 @@ class ZanoWalletService extends WalletService<
Future<void> rename(String currentName, String password, String newName) async {
final currentWalletInfo = await WalletInfo.get(currentName, getType());
if (currentWalletInfo == null) {
- throw Exception('Wallet not found');
+ throw WalletNotFoundException(name: currentName, type: getType());
}
final currentWallet =
ZanoWallet(currentWalletInfo, await currentWalletInfo.getDerivationInfo(), password,
### cw_zano/pubspec.yaml
@@ -14,10 +14,7 @@ dependencies:
bip39: ^1.0.6
bip32: ^2.0.0
ffi: ^2.0.1
- http: ^1.1.0
- path_provider: ^2.0.11
mobx: ^2.6.0
- flutter_mobx: ^2.3.0
intl: any
decimal: ^2.3.3
cw_core:
@@ -27,7 +24,7 @@ dependencies:
monero:
git:
url: https://github.com/mrcyjanek/monero_c.git
- ref: cd4fe366cc8d3c188c91de279f43b29c0e044b15
+ ref: 33671871de3d51696b66ffb3bd94f744e26974f6
path: impls/monero.dart
dev_dependencies:
flutter_test:
### cw_zcash/lib/src/hardware/zcash_hardware_wallet_service.dart
@@ -0,0 +1,11 @@
+import "package:cw_core/hardware/hardware_wallet_service.dart";
+import "package:zkool/src/rust/api/coin.dart" as zkool_coin;
+
+abstract class ZcashHardwareWalletService extends HardwareWalletService {
+ ZcashHardwareWalletService(this.coin);
+
+ final zkool_coin.Coin? coin;
+
+ ZcashHardwareWalletService withCoin(zkool_coin.Coin coin, {int? account}) =>
+ throw UnimplementedError();
+}
### cw_zcash/lib/src/hardware/zcash_ledger_service.dart
@@ -0,0 +1,230 @@
+import 'dart:async';
+import "dart:convert";
+import 'dart:typed_data';
+
+import "package:cw_core/exceptions/cake_exception.dart";
+import 'package:cw_core/hardware/hardware_account_data.dart';
+import 'package:cw_core/utils/print_verbose.dart';
+import "package:cw_zcash/src/hardware/zcash_hardware_wallet_service.dart";
+import 'package:cw_zcash/src/zcash_network.dart';
+import 'package:cw_zcash/src/zcash_wallet.dart';
+import 'package:ledger_flutter_plus/ledger_flutter_plus.dart';
+import 'package:ledger_flutter_plus/ledger_flutter_plus_dart.dart';
+import 'package:zkool/src/rust/api/coin.dart' as zkool_coin;
+import 'package:zkool/src/rust/api/ledger.dart' as zkool_ledger;
+import 'package:zkool/src/rust/api/pay.dart' as zkool_pay;
+
+class ZcashLedgerException extends CakeException {
+ const ZcashLedgerException(super.message);
+}
+
+const _notConnected =
+ "The Ledger is not connected. Make sure it is unlocked and nearby, then try again.";
+
+class ZcashLedgerService extends ZcashHardwareWalletService {
+ ZcashLedgerService(
+ this.connection, {
+ this.network = ZcashNetwork.mainnet,
+ zkool_coin.Coin? coin,
+ this.account,
+ }) : super(coin);
+
+ final LedgerConnection connection;
+ final ZcashNetwork network;
+
+ /// zkool database account id used when the device signs.
+ final int? account;
+
+ @override
+ ZcashLedgerService withCoin(zkool_coin.Coin coin, {int? account}) => ZcashLedgerService(
+ connection,
+ network: network,
+ coin: coin,
+ account: account ?? this.account,
+ );
+
+ /// Ironwood/v6 signing shipped in app-zcash 3.9.2.
+ static const (int, int, int) minAppVersion = (3, 9, 2);
+
+ Object? lastTransportError;
+
+ Future<Uint8List> exchange(final Uint8List apdu) async {
+ try {
+ final reply = await connection.sendOperation<Uint8List>(_ExchangeOperation(apdu));
+ lastTransportError = null;
+ return reply;
+ } on LedgerDeviceException catch (e) {
+ printV(
+ "ledger: status ${e.errorCode.toRadixString(16)} for ins ${apdu[1].toRadixString(16)}");
+ return Uint8List.fromList([(e.errorCode >> 8) & 0xff, e.errorCode & 0xff]);
+ } catch (e) {
+ printV("ledger transport error: $e");
+ lastTransportError = e;
+ return Uint8List(0);
+ }
+ }
+
+ Future<String> appVersion() => _guard(() => zkool_ledger.ledgerAppVersion(exchange: exchange));
+
+ /// Fails unless the Zcash app is open and new enough to sign Ironwood.
+ Future<void> ensureZcashApp() async {
+ final String version;
+ try {
+ version = await appVersion();
+ } on ZcashLedgerException {
+ rethrow;
+ } catch (e) {
+ throw ZcashLedgerException(
+ "Open the Zcash app on your Ledger, then try again (${_trimRustException(e.toString())})");
+ }
+ final parts = version.split(".").map(int.tryParse).toList();
+ if (parts.length < 3 || parts.any((final p) => p == null)) {
+ throw ZcashLedgerException("Could not read the Zcash app version on the Ledger ($version)");
+ }
+ final (major, minor, patch) = minAppVersion;
+ final current = (parts[0]!, parts[1]!, parts[2]!);
+ final tooOld =
+ current.$1 < major ||
+ (current.$1 == major && current.$2 < minor) ||
+ (current.$1 == major && current.$2 == minor && current.$3 < patch);
+ if (tooOld) {
+ throw ZcashLedgerException(
+ "Zcash app $version on the Ledger is too old for shielded transactions");
+ }
+ }
+
+ Future<void> _ensureServiceReadiness() async {
+ await ZcashWalletBase.ensureRustLib();
+ await ensureZcashApp();
+ if (coin == null) {
+ throw ZcashLedgerException("Zcash coin not set, please contact support");
+ }
+ }
+
+ @override
+ Future<List<HardwareAccountData>> getAvailableAccounts({int index = 0, int limit = 5}) async {
+ await _ensureServiceReadiness();
+ final ufvk = await _guard(
+ () => zkool_ledger.ledgerGetUfvk(aindex: index, c: coin!, exchange: exchange),
+ );
+ final address = zkool_ledger.ufvkDefaultAddress(ufvk: ufvk, c: coin!);
+ return [
+ HardwareAccountData(
+ address: address,
+ accountIndex: index,
+ derivationPath: "m/44'/${network == ZcashNetwork.mainnet ? 133 : 1}'/$index'",
+ xpub: ufvk,
+ ),
+ ];
+ }
+
+ @override
+ Future<Uint8List> signTransaction({required String transaction}) async {
+ await _ensureServiceReadiness();
+ final txPlan = await zkool_pay.unpackTransaction(bytes: base64Decode(transaction));
+
+ await for (final event in _sign(txPlan, coin!)) {
+ switch (event) {
+ case zkool_pay.SigningEvent_Progress(:final field0):
+ printV("ledger: $field0");
+ case zkool_pay.SigningEvent_Result(:final field0):
+ return zkool_pay.packTransaction(pczt: field0);
+ }
+ }
+ throw ZcashLedgerException("Ledger did not sign the transaction");
+ }
+
+ Stream<zkool_pay.SigningEvent> _sign(
+ final zkool_pay.PcztPackage package,
+ final zkool_coin.Coin coin,
+ ) async* {
+ final accountId = account;
+ if (accountId == null) {
+ throw const ZcashLedgerException("Zcash account not set, please contact support");
+ }
+ lastTransportError = null;
+ yield* zkool_ledger
+ .ledgerSignTransaction(package: package, account: accountId, c: coin, exchange: exchange)
+ .handleError((final Object e) => throw _withTransportCause(e));
+ }
+
+ Future<T> _guard<T>(final Future<T> Function() call) async {
+ if (connection.isDisconnected) {
+ throw ZcashLedgerException(_notConnected);
+ }
+ lastTransportError = null;
+ try {
+ return await call();
+ } catch (e) {
+ throw _withTransportCause(e);
+ }
+ }
+
+ Object _withTransportCause(final Object error) {
+ if (error is ZcashLedgerException) {
+ return error;
+ }
+ if (lastTransportError != null) {
+ printV("ledger transport failure: $lastTransportError");
+ return ZcashLedgerException(_notConnected);
+ }
+
+ final sw = _ledgerStatusWordOf(error);
+ return sw == null ? error : ZcashLedgerException(_interpretLedgerErrorCode(sw));
+ }
+
+ int? _ledgerStatusWordOf(final Object error) {
+ final m = RegExp(r"Error Executing Instruction \d+: (\d+)").firstMatch(error.toString());
+ return m == null ? null : int.tryParse(m.group(1)!);
+ }
+
+ String _interpretLedgerErrorCode(int sw) {
+ switch (sw) {
+ case 0x5515:
+ return "Your Ledger is locked. Unlock it and open the Zcash app, then try again.";
+ case 0x6e00:
+ case 0x6e01:
+ case 0x6d00:
+ case 0x6d02:
+ return "Open the Zcash app on your Ledger, then try again.";
+ case 0x6985:
+ case 0x6986:
+ return "The transaction was rejected on the Ledger.";
+ case 0x6a80:
+ case 0x6a86:
+ case 0x6a87:
+ return "The Ledger could not read the transaction. Update the Zcash app in Ledger Live and try again.";
+ case 0x6f00:
+ case 0x6f01:
+ return "The Zcash app on the Ledger ran into an internal error. Close and reopen the app, then try again.";
+ default:
+ return "The Ledger returned an error (0x${sw.toRadixString(16).padLeft(4, '0')}). Make sure the Zcash app is open and up to date, then try again.";
+ }
+ }
+
+ String _trimRustException(String error) {
+ if (error.startsWith("Exception: ")) {
+ error = error.substring("Exception: ".length);
+ }
+ final cut = error.indexOf("\n\nStack backtrace");
+ if (cut != -1) {
+ error = error.substring(0, cut);
+ }
+ return error
+ .trim()
+ .replaceFirst(RegExp(r"^AnyhowException\("), "")
+ .replaceFirst(RegExp(r"\)$"), "");
+ }
+}
+
+class _ExchangeOperation extends LedgerRawOperation<Uint8List> {
+ _ExchangeOperation(this.inputData);
+
+ final Uint8List inputData;
+
+ @override
+ Future<Uint8List> read(ByteDataReader reader) async => reader.read(reader.remainingLength);
+
+ @override
+ Future<List<Uint8List>> write(ByteDataWriter writer) async => [inputData];
+}
### cw_zcash/lib/src/migrate.dart
@@ -5,6 +5,7 @@ import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:cw_zcash/cw_zcash.dart';
+import "package:cw_zcash/src/util/exceptions.dart";
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:path/path.dart' as p;
@@ -48,13 +49,13 @@ class YwalletAccountInfo {
final String ivk;
final String address;
static YwalletAccountInfo fromJson(final Map<String, dynamic> j) => YwalletAccountInfo(
- idAccount: j['id_account'],
- name: j['name'],
- seed: j['seed'],
- aindex: j['aindex'],
- sk: j['sk'],
- ivk: j['ivk'],
- address: j['address'],
+ idAccount: j['id_account'] as int,
+ name: j['name'] as String,
+ seed: j['seed'] as String,
+ aindex: j['aindex'] as int,
+ sk: j['sk'] as String,
+ ivk: j['ivk'] as String,
+ address: j['address'] as String,
);
}
@@ -92,5 +93,5 @@ Future<void> migrateOldSqliteToZkool2({required final String walletName}) async
return;
}
- throw Exception("migration not finished (wallet name: $walletName not found)");
+ throw MigrationException("migration not finished (wallet name: $walletName not found)");
}
### cw_zcash/lib/src/models.dart
@@ -1,3 +1,4 @@
+import "package:cw_core/hardware/hardware_wallet_service.dart";
import 'package:cw_core/wallet_credentials.dart';
class ZcashNewWalletCredentials extends WalletCredentials {
@@ -45,3 +46,16 @@ class ZcashFromKeysWalletCredentials extends WalletCredentials {
final String? privateKey;
int network;
}
+
+class ZcashRestoreWalletFromHardware extends WalletCredentials {
+ ZcashRestoreWalletFromHardware({
+ required super.name,
+ required super.height,
+ required this.hardwareWalletService,
+ this.accountIndex = 0,
+ this.network = 0,
+ });
+ final HardwareWalletService hardwareWalletService;
+ final int accountIndex;
+ int network;
+}
### cw_zcash/lib/src/pending_zcash_transaction.dart
@@ -1,25 +1,29 @@
+import 'dart:async';
+
import 'package:cw_core/amount/money.dart';
import 'package:cw_core/exceptions.dart';
import 'package:cw_core/pending_transaction.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_zcash/cw_zcash.dart';
import 'package:zkool/src/rust/api/pay.dart' as zkool_pay;
-import 'package:zkool/src/rust/api/network.dart' as zkool_network;
class PendingZcashTransaction with PendingTransaction {
PendingZcashTransaction({
required this.zcashWallet,
- required this.credentials,
+ required this.amount,
required this.txPlan,
required this.fee,
required this.availableBalance,
+ this.signedTxPackage,
+ this.isShieldingTx = false,
});
final ZcashWallet zcashWallet;
- final ZcashTransactionCredentials credentials;
final zkool_pay.PcztPackage txPlan;
+ final zkool_pay.PcztPackage? signedTxPackage;
String? _txId;
final Money availableBalance;
+ final bool isShieldingTx;
@override
String get id => _txId ?? '';
@@ -28,15 +32,7 @@ class PendingZcashTransaction with PendingTransaction {
String get hex => '';
@override
- Money get amount {
- final isAll = credentials.outputs.fold<bool>(false, (final a, final b) => a || (b.sendAll));
- if (isAll) {
- return availableBalance - fee;
- }
- return credentials.outputs
- .map((final output) => output.cryptoAmount)
- .reduce((final a, final b) => a + b);
- }
+ final Money amount;
@override
String get amountFormatted => amount.toString();
@@ -49,12 +45,15 @@ class PendingZcashTransaction with PendingTransaction {
await ZcashWalletBase.runWithCoin(
accountId: zcashWallet.accountId,
func: (coin) async {
- final signTx = await zkool_pay.signTransaction(pczt: txPlan, c: coin);
- final txBytes = await zkool_pay.extractTransaction(package: signTx);
- final currentHeight = await zkool_network.getCurrentHeight(c: coin);
- final result = await zkool_pay.broadcastTransaction(
- height: currentHeight,
- txBytes: txBytes,
+ final signed = signedTxPackage ??
+ await zkool_pay.signTransaction(
+ pczt: txPlan,
+ account: zcashWallet.accountId,
+ c: coin,
+ );
+ final result = await zkool_pay.broadcast(
+ package: signed,
+ account: zcashWallet.accountId,
c: coin,
);
printV("result: $result");
@@ -63,11 +62,21 @@ class PendingZcashTransaction with PendingTransaction {
throw TransactionCommitFailed(errorMessage: result);
}
_txId = txId;
- zcashWallet.rememberPendingOutgoingAmount(txId, amount);
+ if (isShieldingTx) {
+ zcashWallet.noteShieldBroadcast();
+ await ZcashWalletService.addShieldedTx(txId);
+ } else {
+ zcashWallet.rememberPendingOutgoingAmount(txId, amount);
+ }
},
);
- await zcashWallet.updateTransactions();
- await zcashWallet.updateBalance();
+
+
+ unawaited(zcashWallet.updateTransactions());
+ unawaited(zcashWallet.updateBalance(
+ runAutoShield: !isShieldingTx,
+ runIronwoodMigrate: !isShieldingTx,
+ ));
}
@override
### cw_zcash/lib/src/util/crc32.dart
@@ -20,11 +20,11 @@ class CRC32 {
crc = crc ^ (0xffffffff);
- for (final byte in input) {
- if (!(byte >= -128 && byte <= 255))
+ for (final byte in input as Iterable<dynamic>) {
+ if (!((byte >= -128) as bool && (byte <= 255) as bool))
throw new FormatException("Invalid value in input: $byte");
- final x = CRC32._table[(crc ^ byte) & 0xff];
+ final x = CRC32._table[(crc ^ (byte as int)) & 0xff];
crc = (crc & 0xffffffff) >> 8; // crc >>> 8 (32-bit unsigned integer)
crc ^= x;
}
### cw_zcash/lib/src/util/exceptions.dart
@@ -0,0 +1,23 @@
+
+
+import "package:cw_core/exceptions/cake_exception.dart";
+
+class WalletLockedException extends CakeException {
+ const WalletLockedException() : super("Zcash wallet locked! Please contact support");
+}
+
+class UpdateException extends CakeException {
+ const UpdateException(super.message);
+}
+
+class ZcashAccountException extends CakeException {
+ const ZcashAccountException(super.message);
+}
+
+class AddressRotationException extends CakeException {
+ const AddressRotationException(super.message);
+}
+
+class MigrationException extends CakeException {
+ const MigrationException(super.message);
+}
\ No newline at end of file
### cw_zcash/lib/src/zcash_mempool.dart
[binary or diff unavailable]
### cw_zcash/lib/src/zcash_taddress_rotation.dart
[binary or diff unavailable]
### cw_zcash/lib/src/zcash_wallet.dart
[binary or diff unavailable]
### cw_zcash/lib/src/zcash_wallet_addresses.dart
[binary or diff unavailable]
### cw_zcash/lib/src/zcash_wallet_service.dart
[binary or diff unavailable]
### cw_zcash/lib/src/zkooltx.dart
[binary or diff unavailable]
### cw_zcash/pubspec.yaml
[binary or diff unavailable]
### docs/ADDING_EVM_L2_WALLET_NETWORK_TYPES.md
[binary or diff unavailable]
### docs/INTEGRATION_TESTS.md
[binary or diff unavailable]
### docs/VERIFY.md
[binary or diff unavailable]
### docs/builds/ANDROID.md
[binary or diff unavailable]
### docs/builds/LINUX.md
[binary or diff unavailable]
### integration_test/components/common_test_cases.dart
[binary or diff unavailable]
### integration_test/components/common_test_constants.dart
[binary or diff unavailable]
### integration_test/components/common_test_flows.dart
[binary or diff unavailable]
### integration_test/core/app_launcher.dart
[binary or diff unavailable]
### integration_test/core/base_robot.dart
[binary or diff unavailable]
### integration_test/core/benign_errors.dart
[binary or diff unavailable]
### integration_test/core/funded_wallet.dart
[binary or diff unavailable]
### integration_test/core/funded_wallets.dart
[binary or diff unavailable]
### integration_test/core/funds_outcome.dart
[binary or diff unavailable]
### integration_test/core/test_config.dart
[binary or diff unavailable]
### integration_test/core/test_wallets.dart
[binary or diff unavailable]
### integration_test/flows/auth_flows.dart
[binary or diff unavailable]
### integration_test/flows/funds_flows.dart
[binary or diff unavailable]
### integration_test/flows/onboarding_flows.dart
[binary or diff unavailable]Why this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.