diff --git a/.github/workflows/android-diagnostic-build.yml b/.github/workflows/android-diagnostic-build.yml new file mode 100644 index 0000000000..a272100d6d --- /dev/null +++ b/.github/workflows/android-diagnostic-build.yml @@ -0,0 +1,115 @@ +name: Android diagnostic build + +on: + pull_request: + branches: + - 'release/**' + - sprint + - dev + - main + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: android-diagnostic-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + build: + runs-on: ubuntu-24.04 + timeout-minutes: 90 + + steps: + - name: Check out source + uses: actions/checkout@v4 + + - name: Set up Node + uses: actions/setup-node@v4 + with: + node-version: 22.23.3 + + - name: Set up Java + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + + - name: Set up Android SDK tools + uses: android-actions/setup-android@v4 + with: + packages: '' + + - name: Install Android build packages + run: sdkmanager 'platforms;android-36' 'build-tools;35.0.0' 'ndk;27.1.12297006' 'cmake;3.22.1' + + - name: Install JavaScript dependencies without the iOS setup hook + run: | + npm install --global yarn@1.22.22 + yarn install --frozen-lockfile --ignore-scripts --non-interactive + ./node_modules/.bin/patch-package + ./node_modules/.bin/rn-nodeify --install buffer,events,process,stream,inherits,path,assert,crypto --hack --yarn + + - name: Create diagnostic configuration + run: | + cat > "$RUNNER_TEMP/keeper-diagnostic.env" <<'EOF' + CHANNEL_URL=https://channel.bitcoinkeeper.app/ + ENVIRONMENT=PRODUCTION + HEXA_ID_MAINNET=0000000000000000000000000000000000000000000000000000000000000000 + HEXA_ID_TESTNET=0000000000000000000000000000000000000000000000000000000000000000 + RELAY=https://example.invalid/ + SIGNING_SERVER_MAINNET=https://example.invalid/ + SIGNING_SERVER_TESTNET=https://example.invalid/ + EOF + node scripts/verify-channel-config.cjs "$RUNNER_TEMP/keeper-diagnostic.env" + printf 'sdk.dir=%s\n' "$ANDROID_SDK_ROOT" > android/local.properties + + - name: Confirm Gradle rejects a retired mobile credential + run: | + cp "$RUNNER_TEMP/keeper-diagnostic.env" "$RUNNER_TEMP/keeper-rejected.env" + printf 'GASFREE_API_KEY=diagnostic-only\n' >> "$RUNNER_TEMP/keeper-rejected.env" + if (cd android && ENVFILE="$RUNNER_TEMP/keeper-rejected.env" ./gradlew :app:help --no-daemon --console=plain > "$RUNNER_TEMP/rejected-build.log" 2>&1); then + echo 'Gradle accepted a retired mobile credential' >&2 + exit 1 + fi + if ! grep -q 'Retired API credentials must not be included in an Android build' "$RUNNER_TEMP/rejected-build.log"; then + tail -80 "$RUNNER_TEMP/rejected-build.log" + exit 1 + fi + + - name: Build APK and AAB with the public debug key + env: + STORE_PASSWORD: android + KEY_ALIAS: androiddebugkey + KEY_PASSWORD: android + run: | + export ENVFILE="$RUNNER_TEMP/keeper-diagnostic.env" + export KEEPER_ANDROID_KEYSTORE="$GITHUB_WORKSPACE/android/app/debug.keystore" + cd android + ./gradlew :app:assembleProductionRelease :app:bundleProductionRelease --no-daemon --console=plain + + - name: Check diagnostic artifacts + run: | + apk=android/app/build/outputs/apk/production/release/app-production-release.apk + aab=android/app/build/outputs/bundle/productionRelease/app-production-release.aab + test -s "$apk" + test -s "$aab" + "$ANDROID_SDK_ROOT/build-tools/35.0.0/apksigner" verify "$apk" + badging=$("$ANDROID_SDK_ROOT/build-tools/35.0.0/aapt2" dump badging "$apk") + version=$(node -p 'require("./release/version.json").version') + version_code=$(node -p 'require("./release/version.json").androidVersionCode') + grep -Fq "package: name='io.hexawallet.bitcoinkeeper' versionCode='$version_code' versionName='$version'" <<< "$badging" + if ! jarsigner -verify -verbose -certs "$aab" > "$RUNNER_TEMP/aab-signature.log" 2>&1; then + tail -80 "$RUNNER_TEMP/aab-signature.log" + exit 1 + fi + if ! grep -Fxq 'jar verified.' "$RUNNER_TEMP/aab-signature.log" || grep -Fq '? = unsigned entry' "$RUNNER_TEMP/aab-signature.log"; then + tail -80 "$RUNNER_TEMP/aab-signature.log" + echo 'AAB is unsigned or contains unsigned entries' >&2 + exit 1 + fi + unzip -tq "$apk" >/dev/null + unzip -tq "$aab" >/dev/null + sha256sum "$apk" "$aab" + echo 'Diagnostic APK/AAB built with placeholder config and debug signing; no reproducibility verdict.' diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml deleted file mode 100644 index dd2225e91d..0000000000 --- a/.github/workflows/build.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: Build -on: - push: - branches: - - sprint - pull_request: - types: [opened, synchronize, reopened] -jobs: - sonarcloud: - name: SonarCloud - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis - - name: SonarCloud Scan - uses: SonarSource/sonarcloud-github-action@master - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index dbff68d1af..01d2a849bf 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -30,5 +30,13 @@ jobs: - name: Install dependencies run: yarn install + - name: Check USDT pause and retired build inputs + run: | + node --test tests/services/usdtPause.test.cjs tests/recovery/usdtBackup.test.cjs \ + scripts/verify-channel-config.test.cjs ios/scripts/verify-retired-env.test.cjs + - name: Run tests run: npm run test + + - name: Test Android reproducibility tools + run: python3 -B -m unittest scripts/test_compare_android_apks.py reproducibility/test_verify_android_inputs.py diff --git a/android/app/build.gradle b/android/app/build.gradle index b73b4caad3..498a073274 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -2,6 +2,13 @@ apply plugin: "com.android.application" apply plugin: "com.facebook.react" apply plugin: 'com.google.gms.google-services' apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle" +// react-native-config embeds every selected env key, even when JavaScript does not use it. +// Check the resolved env map so direct Gradle builds cannot package retired credentials. +def retiredCredentialKeys = ['GASFREE_API_KEY', 'GASFREE_API_SECRET', + 'LETS_EXCHANGE_API_KEY'].collectMany { [it, "RN_${it}"] } +if (retiredCredentialKeys.any { project.ext.env.containsKey(it) }) { + throw new GradleException('Retired API credentials must not be included in an Android build') +} apply plugin: 'kotlin-android' /** @@ -205,4 +212,4 @@ dependencies { implementation 'com.itextpdf:itextg:5.5.10' -} \ No newline at end of file +} diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties index d4081da476..a54add3199 100644 --- a/android/gradle/wrapper/gradle-wrapper.properties +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +distributionSha256Sum=bd71102213493060956ec229d946beee57158dbd89d0e62b91bca0fa2c5f3531 networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/appcenter-pre-build.sh b/appcenter-pre-build.sh index 6adc321a73..3705a26b9a 100644 --- a/appcenter-pre-build.sh +++ b/appcenter-pre-build.sh @@ -1,8 +1,19 @@ #!/usr/bin/env bash # Creates an .env from ENV variables for use with react-native-config +set -eu + +if [ -n "${RN_GASFREE_API_KEY+x}" ] || [ -n "${RN_GASFREE_API_SECRET+x}" ] || [ -n "${RN_LETS_EXCHANGE_API_KEY+x}" ]; then + printf "Retired API credentials must not be included in a mobile build\n" >&2 + exit 1 +fi + ENV_WHITELIST=${ENV_WHITELIST:-"^RN_"} printf "Creating an .env file with the following whitelist:\n" printf "%s\n" $ENV_WHITELIST set | egrep -e $ENV_WHITELIST | sed 's/^RN_//g' > .env -printf "\n.env created with contents:\n\n" -cat .env \ No newline at end of file +if grep -Eq '^(RN_)?(GASFREE_API_(KEY|SECRET)|LETS_EXCHANGE_API_KEY)=' .env; then + rm .env + printf "Retired API credentials must not be included in a mobile build\n" >&2 + exit 1 +fi +printf ".env created\n" diff --git a/ios/Podfile b/ios/Podfile index b0e96375f5..bbda6b4095 100644 --- a/ios/Podfile +++ b/ios/Podfile @@ -86,6 +86,17 @@ post_install do |installer| # :ccache_enabled => true ) + # react-native-config logs and embeds every key from its selected .env file. + # Run the guard in that pod's own phase before its code generator starts. + config_target = installer.pods_project.targets.find { |target| target.name == 'react-native-config' } + config_codegen = config_target&.shell_script_build_phases&.find { |phase| phase.name == '[CP-User] Config codegen' } + raise 'react-native-config codegen phase not found; release credential guard cannot be installed' unless config_codegen + + config_codegen.shell_script = <<~SCRIPT + config_codegen.shell_script + set -e + ruby "${PODS_ROOT}/../scripts/verify-retired-env.rb" "${PODS_TARGET_SRCROOT}/ios/ReactNativeConfig" "${SRCROOT}/../.." + SCRIPT + # fixes release issue with xCode 16, bitcode is stripped by default. bitcode_strip_path = `xcrun --find bitcode_strip`.chop! def strip_bitcode_from_framework(bitcode_strip_path, framework_relative_path) diff --git a/ios/scripts/verify-retired-env.rb b/ios/scripts/verify-retired-env.rb new file mode 100644 index 0000000000..413497ce62 --- /dev/null +++ b/ios/scripts/verify-retired-env.rb @@ -0,0 +1,17 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# Use react-native-config's own reader so this checks the same ENVFILE, +# /tmp/envfile override, and .env fallback that its code generator will use. +reader_directory, environment_root = ARGV +abort('Missing react-native-config environment inputs') unless reader_directory && environment_root + +retired_names = %w[GASFREE_API_KEY GASFREE_API_SECRET LETS_EXCHANGE_API_KEY] +retired_names += retired_names.map { |name| "RN_#{name}" } +failure = 'Retired API credentials must not be included in an iOS build' + +abort(failure) if retired_names.any? { |name| ENV.key?(name) } + +require File.join(reader_directory, 'ReadDotEnv') +dotenv, = read_dot_env(environment_root) +abort(failure) if retired_names.any? { |name| dotenv.key?(name) } diff --git a/ios/scripts/verify-retired-env.test.cjs b/ios/scripts/verify-retired-env.test.cjs new file mode 100644 index 0000000000..d25f96564d --- /dev/null +++ b/ios/scripts/verify-retired-env.test.cjs @@ -0,0 +1,58 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); + +const verifier = path.join(__dirname, 'verify-retired-env.rb'); +const reader = process.env.KEEPER_TEST_RN_CONFIG_READER || + path.join(__dirname, '..', '..', 'node_modules', 'react-native-config', 'ios', 'ReactNativeConfig'); +const secret = 'synthetic-secret-not-for-output'; +const retiredNames = ['GASFREE_API_KEY', 'GASFREE_API_SECRET', 'LETS_EXCHANGE_API_KEY']; +retiredNames.push(...retiredNames.map(name => `RN_${name}`)); + +function verify(contents, additionalEnv = {}) { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'keeper-ios-env-')); + try { + const envFile = path.join(directory, '.env.test'); + fs.writeFileSync(envFile, contents); + return spawnSync('ruby', [verifier, reader, directory], { + cwd: directory, + env: { PATH: process.env.PATH, ENVFILE: envFile, ...additionalEnv }, + encoding: 'utf8', + }); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } +} + +test('iOS pod guard accepts config without retired credentials', () => { + assert.ok(fs.existsSync(reader), 'Install react-native-config before running this test'); + const result = verify('CHANNEL_URL=https://channel.bitcoinkeeper.app/\n'); + assert.equal(result.status, 0, result.stderr); +}); + +for (const name of retiredNames) { + test(`iOS pod guard rejects ${name} in selected ENVFILE before logging its value`, + () => { + const result = verify(`CHANNEL_URL=https://channel.bitcoinkeeper.app/\n${name}=${secret}\n`); + assert.notEqual(result.status, 0); + assert.doesNotMatch(result.stdout + result.stderr, /synthetic-secret-not-for-output/); + }); +} + +test('iOS pod guard rejects exported retired credentials', () => { + const result = verify(`export GASFREE_API_KEY=${secret}\n`); + assert.notEqual(result.status, 0); + assert.doesNotMatch(result.stdout + result.stderr, /synthetic-secret-not-for-output/); +}); + +test('iOS pod guard rejects a retired process variable before logging its value', + () => { + const result = verify('CHANNEL_URL=https://channel.bitcoinkeeper.app/\n', { + RN_GASFREE_API_SECRET: secret, + }); + assert.notEqual(result.status, 0); + assert.doesNotMatch(result.stdout + result.stderr, /synthetic-secret-not-for-output/); + }); diff --git a/package.json b/package.json index ad0eeb2c1e..b0344c35d7 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "iosProd": "npx react-native run-ios --scheme=hexa_keeper --simulator 'iPhone 16' ", "start": "react-native start", "test": "jest", - "test:release": "node --test scripts/release-version.test.cjs && python3 -B -m unittest discover -s scripts -p 'test_release_artifact.py'", + "test:release": "node --test scripts/release-version.test.cjs scripts/verify-channel-config.test.cjs && python3 -B -m unittest discover -s scripts -p 'test_release_artifact.py'", "version:inspect": "node scripts/release-version.cjs inspect", "version:check": "node scripts/release-version.cjs check", "version:apply": "node scripts/release-version.cjs apply", diff --git a/reproducibility/README.md b/reproducibility/README.md new file mode 100644 index 0000000000..32e7f0eb42 --- /dev/null +++ b/reproducibility/README.md @@ -0,0 +1,175 @@ +# Android reproducibility status + +This directory records the inputs needed to compare a Bitcoin Keeper Android +release with a build from its public source. The comparison tool in +[`scripts/compare-android-apks.py`](../scripts/compare-android-apks.py) is an +inspection aid. It is **not** a WalletScrutiny build script, and this repository +does not yet establish a reproducibility verdict for v2.6.3. + +The [Android diagnostic build workflow](../.github/workflows/android-diagnostic-build.yml) +is set up to compile an APK and AAB from the combined draft with the live public +channel URL and `ENVIRONMENT=PRODUCTION`, dummy service endpoints and IDs, and +the checked-in debug key. It also checks that Gradle rejects a retired GasFree +credential. A successful run would verify that the draft compiles in a clean CI +checkout; its outputs cannot be compared to a production release for a +reproducibility verdict. The workflow does not publish the diagnostic artifacts. + +## v2.6.3 reference and measured result + +The public source tag is [`v2.6.3`](https://github.com/KeeperCommunity/bitcoin-keeper/releases/tag/v2.6.3), +commit `872cbc4b16ddcb0a8f3b5b1d7ebcde28e06ed096`. The GitHub release APK +`Bitcoin_Keeper_v2.6.3.apk` has SHA-256 +`a20d934ebd80ece779d3c171c7906bb4aff010337989ec1b826cab55c50eba46`. +Its package is `io.hexawallet.bitcoinkeeper`, version `2.6.3`, version code +`626`. + +An isolated build of that tag with a placeholder production configuration and +the checked-in debug signing key produced a valid 2.6.3 APK. Its SHA-256 was +`cc4102251a11cbbfa104808adc4906a3a0e3b2efd9a14ab0785d66f5c9d5143b`. +Comparing uncompressed APK entries found **1,424 matching payload entries and +192 differences**: one manifest, one baseline profile, one Hermes bundle, five +DEX files, 56 native libraries, and 128 resources. The placeholder +configuration and different build environment can affect these files. This is +a diagnostic mismatch, not evidence that the published binary was built from +different source. The measured result and remaining work are tracked in +[#6097](https://github.com/KeeperCommunity/bitcoin-keeper/issues/6097). + +For an SDK 33, arm64-v8a, xxhdpi, English-only profile, the four official +Play-generated APKs were also retrieved and verified. All 42 corresponding +code entries (six DEX files, Hermes, and 35 arm64 libraries) match the GitHub +release APK byte for byte. This establishes published-channel code parity for +that profile, not a rebuild from public source. A rebuilt AAB and split-set +comparison are still needed. + +| Play split | SHA-256 | +| --- | --- | +| SDK 29+ base | `e384b966359aa4937bf4353316ddda471adf1e17f6bb08fe53f9945e8ea9bc1d` | +| arm64-v8a | `11740257e813455501301d5dc0f9870dc476e15947d912523e051d9a3400ab8c` | +| xxhdpi | `da3b93b89e98cff52bbea6c593fc26193139d53f400139ebd44ac51118f08195` | +| English | `a5cae92f6e9c2d725bcf8fc3ebcfb397573fda38e1413dde7e40c395430f0a73` | + +## Compare two APKs + +Run with Python 3 and no extra packages: + +```sh +python3 scripts/compare-android-apks.py published.apk rebuilt.apk > comparison.json +``` + +Exit code 0 means all **uncompressed ZIP file entries** match after the narrow +signing exceptions below. Exit code 1 means at least one payload difference; +exit code 2 means invalid input. JSON includes whole-APK SHA-256 hashes, entry +counts, and every changed, added, or removed file path. ZIP directory records, +compression, entry order, and APK v2/v3 signing blocks are outside this payload +comparison. The tool assumes its inputs are APKs; verify their signatures, +package names, and versions separately. + +The only exempt entries are root-level JAR/v1 signature material +(`META-INF/MANIFEST.MF`, `META-INF/*.SF`, `*.RSA`, `*.DSA`, `*.EC`) and Play's +root `stamp-cert-sha256`. Their differences still appear in +`ignored_signing_entries`. DEX, Hermes, native libraries, manifests, resource +tables and files, baseline profiles, other assets, and other `META-INF` files +remain comparison-critical. A payload match does not authenticate either +signer or prove that the APK came from the claimed source. + +Synthetic tests cover signing exceptions, each payload category, added and +removed files, duplicate ZIP paths, and CLI exit codes: + +```sh +python3 -m unittest scripts/test_compare_android_apks.py +``` + +Compare one APK with one APK. Google Play delivers APKs generated from an AAB; +a Play base split cannot be equated with a standalone GitHub APK. Play +verification needs the complete delivered split set and corresponding splits +from a rebuilt AAB, with transformations examined separately. + +## Inputs needed for an independent build + +The tagged production lane requires an ignored `.env.production`. Its exact +v2.6.3 contents are not public. Names-only inspection of the published APK +found 13 environment-derived fields in `BuildConfig`. `react-native-config` +embeds supplied environment values in Android build outputs, including fields +outside the app's TypeScript configuration object. Placeholder values cannot +support an exact payload verdict. Some fields appear credential-bearing and +require owner security review before public build inputs are released; do not +commit an unchecked production environment file. + +The source pins Gradle wrapper 8.14.3, Android Gradle Plugin 8.8.0, Android +SDK/target 36, Build Tools 35.0.0, NDK 27.1.12297006, and React Native +0.83.9. The locked Realm dependency requests CMake 3.22.1. The dependency +tree is recorded in `yarn.lock` and checked-in `patch-package` patches. The +successful diagnostic used Node +22.23.3, Yarn 1.22.22, and JDK 17.0.19; these are measured diagnostic inputs, +not a claim about the publisher's complete toolchain. A third-party recipe +still needs a digest-pinned Linux container image, exact JDK/Node/Yarn and SDK +package checksums, a fixed checkout and dependency layout, and verified build +commands. The Gradle wrapper now has a distribution checksum pin, but the +Android project has no dependency lock or verification metadata. The published +Hermes bundle contains a Node 25.9.0 +literal injected by `rn-nodeify` and a path through a sibling +`keeper-release-2.5.15/node_modules` directory. These historical build inputs +must be investigated; copying them into a future release recipe would not by +itself reproduce v2.6.3. Realm and Screens also have native executable/data +differences in the placeholder rebuild. + +For the Android-only path, the diagnostic installed JavaScript packages with +`yarn install --frozen-lockfile --ignore-scripts`, then ran the checked-in +`patch-package` patches and the Android `rn-nodeify` step before invoking +`./gradlew :app:assembleProductionRelease`. The root `setup.sh` cannot serve +as a Linux build recipe unchanged: it runs iOS CocoaPods and writes a macOS SDK +path. A future container recipe needs a Linux `local.properties`, the verified +production environment input, and a disposable signing identity. It should +also run `:app:bundleProductionRelease` for Play split comparisons. These +commands describe the diagnostic path; they are not a complete reproducible +build recipe. + +The release Fastlane lane validates time-sensitive store baselines and uploads +an AAB to Play. An independent verifier should build locally without store +access or upload. It can use a disposable signing key and compare payloads +while explicitly accounting for signing differences. A complete recipe must +then build the production APK and AAB under pinned tools and compare the +actual distributed artifacts. + +[WalletScrutiny's script rules](https://github.com/WalletScrutiny/WalletScrutinyCom/blob/master/docs/script_verifications.md) +require Docker, Podman, or Nix; a script ending in `build.sh`; a `--binary` +argument; and an adjacent `COMPARISON_RESULTS.yaml`. No such script or results +file is included here because the exact production input and complete +third-party build path have not yet been established. + +## Fail closed on future build inputs + +`android-inputs.json` pins the Node, Yarn, JDK, Gradle wrapper, lockfile, and +Android SDK package versions chosen for the next independent build attempt. +These are **chosen future inputs**, not a reconstruction of the v2.6.3 +publisher's environment. Before any production build, run: + +```sh +python3 reproducibility/verify-android-inputs.py \ + --source-commit \ + --env-file /path/to/reviewed/.env.production \ + --android-sdk-root /path/to/android-sdk +``` + +The tracked manifest contains seven source-audited environment names and no +values. This is a **provisional future-release allowlist**: the GasFree pause +is included in [combined draft PR #7035](https://github.com/KeeperCommunity/bitcoin-keeper/pull/7035), +and integration checks for four candidate omissions must be reviewed before +using it for a release. Changing the list requires a tracked source change. +The checker rejects +missing or extra names, a dirty or wrong source checkout, changed dependency +hashes, mismatched tool versions, missing SDK packages, a symlinked +`node_modules` root, and links from dependencies to files outside the checkout. +It does not output environment values. A local dependency install is necessary; +linking to a sibling `node_modules` directory recreates an observed historical +build-path dependency and fails this check. + +This check does not yet pin the container image, Android command-line tools +download, Maven artifacts, or every transitive native input. It does not run +the build or compare a binary and is not a WalletScrutiny `build.sh`. The exact +production environment names and values still need release-owner review before +any public recipe or verdict. Run its focused tests with: + +```sh +python3 -m unittest reproducibility/test_verify_android_inputs.py +``` diff --git a/reproducibility/android-inputs.json b/reproducibility/android-inputs.json new file mode 100644 index 0000000000..14c9bfc290 --- /dev/null +++ b/reproducibility/android-inputs.json @@ -0,0 +1,26 @@ +{ + "node": "22.23.3", + "yarn": "1.22.22", + "java": "17.0.19", + "yarn_lock_sha256": "b257e6d81f2850ca1c12ce3ddb559d39cd3113a51c09a9eb71ca11c81bf5a245", + "gradle_wrapper_jar_sha256": "0336f591bc0ec9aa0c9988929b93ecc916b3c1d52aed202c7381db144aa0ef15", + "gradle_distribution_sha256": "bd71102213493060956ec229d946beee57158dbd89d0e62b91bca0fa2c5f3531", + "android_packages": { + "build-tools/35.0.0": "35.0.0", + "ndk/27.1.12297006": "27.1.12297006", + "cmake/3.22.1": "3.22.1" + }, + "android_platform": { + "path": "platforms/android-36", + "revision": "2" + }, + "environment_names": [ + "CHANNEL_URL", + "ENVIRONMENT", + "HEXA_ID_MAINNET", + "HEXA_ID_TESTNET", + "RELAY", + "SIGNING_SERVER_MAINNET", + "SIGNING_SERVER_TESTNET" + ] +} diff --git a/reproducibility/test_verify_android_inputs.py b/reproducibility/test_verify_android_inputs.py new file mode 100644 index 0000000000..ad629ccd4b --- /dev/null +++ b/reproducibility/test_verify_android_inputs.py @@ -0,0 +1,69 @@ +import importlib.util +from pathlib import Path +import tempfile +import unittest + + +SCRIPT = Path(__file__).with_name("verify-android-inputs.py") +SPEC = importlib.util.spec_from_file_location("verify_android_inputs", SCRIPT) +MODULE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(MODULE) + + +class AndroidInputTests(unittest.TestCase): + def test_unapproved_environment_name_is_rejected_without_value(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + env = root / ".env.production" + env.write_text("ENVIRONMENT=production\nUNREVIEWED_TOKEN=private-example-value\n") + with self.assertRaises(MODULE.InputError) as caught: + MODULE.check_env_names(env, ["ENVIRONMENT"]) + self.assertIn("UNREVIEWED_TOKEN", str(caught.exception)) + self.assertNotIn("private-example-value", str(caught.exception)) + + def test_missing_or_duplicate_approved_name_is_rejected(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + env = root / ".env.production" + env.write_text("ENVIRONMENT=production\n") + with self.assertRaisesRegex(MODULE.InputError, "missing environment names: RELAY"): + MODULE.check_env_names(env, ["ENVIRONMENT", "RELAY"]) + with self.assertRaisesRegex(MODULE.InputError, "duplicate pinned environment name"): + MODULE.check_env_names(env, ["ENVIRONMENT", "ENVIRONMENT"]) + + def test_external_or_root_dependency_symlink_is_rejected(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + outside = root / "outside" + outside.mkdir() + dependencies = root / "checkout/node_modules" + dependencies.parent.mkdir() + dependencies.symlink_to(outside, target_is_directory=True) + with self.assertRaisesRegex(MODULE.InputError, "real directory"): + MODULE.check_local_dependencies(dependencies.parent) + dependencies.unlink() + dependencies.mkdir() + (dependencies / "escaped").symlink_to(outside, target_is_directory=True) + with self.assertRaisesRegex(MODULE.InputError, "outside this checkout"): + MODULE.check_local_dependencies(dependencies.parent) + + def test_internal_dependency_symlink_is_allowed(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + dependencies = root / "node_modules" + package = dependencies / "some-package" + package.mkdir(parents=True) + bin_directory = dependencies / ".bin" + bin_directory.mkdir() + (bin_directory / "some-package").symlink_to(package, target_is_directory=True) + MODULE.check_local_dependencies(root) + + def test_sdk_revision_accepts_android_property_spacing(self): + with tempfile.TemporaryDirectory() as temporary: + package = Path(temporary) + (package / "source.properties").write_text("Pkg.Revision = 3.22.1\n") + self.assertEqual(MODULE.sdk_revision(package), "3.22.1") + + +if __name__ == "__main__": + unittest.main() diff --git a/reproducibility/verify-android-inputs.py b/reproducibility/verify-android-inputs.py new file mode 100644 index 0000000000..08e0fcc775 --- /dev/null +++ b/reproducibility/verify-android-inputs.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +"""Fail closed on known path, configuration, and toolchain drift before an Android build. + +This is an input check, not a complete build recipe or reproducibility verdict. +Environment values are never printed or written to an output file. +""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import sys + + +class InputError(Exception): + pass + + +KEY_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") +ASSIGNMENT_RE = re.compile(r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=") + + +def sha256(path): + digest = hashlib.sha256() + with path.open("rb") as source: + for chunk in iter(lambda: source.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def read_env_names(path): + """Read only names; deliberately never retain or show the values.""" + names = set() + for line_number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): + stripped = line.strip() + if not stripped or stripped.startswith("#"): + continue + match = ASSIGNMENT_RE.match(stripped) + if not match: + raise InputError(f"invalid environment assignment at line {line_number}") + name = match.group(1) + if name in names: + raise InputError(f"duplicate environment name: {name}") + names.add(name) + return names + + +def expected_env_names(expected): + if not isinstance(expected, list) or not expected: + raise InputError("pinned environment name list is missing or empty") + names = set() + for name in expected: + if not isinstance(name, str) or not KEY_RE.fullmatch(name): + raise InputError("invalid pinned environment name") + if name in names: + raise InputError(f"duplicate pinned environment name: {name}") + names.add(name) + return names + + +def check_env_names(env_file, expected_names): + actual = read_env_names(env_file) + approved = expected_env_names(expected_names) + unexpected = sorted(actual - approved) + missing = sorted(approved - actual) + if unexpected or missing: + parts = [] + if unexpected: + parts.append("unexpected environment names: " + ", ".join(unexpected)) + if missing: + parts.append("missing environment names: " + ", ".join(missing)) + raise InputError("; ".join(parts)) + + +def check_local_dependencies(repo): + dependencies = repo / "node_modules" + if dependencies.is_symlink() or not dependencies.is_dir(): + raise InputError("node_modules must be a real directory inside this checkout") + root = dependencies.resolve() + for current, directories, files in os.walk(dependencies, followlinks=False): + for name in directories + files: + path = Path(current) / name + if path.is_symlink(): + try: + target = path.resolve(strict=True) + except (OSError, RuntimeError): + raise InputError("node_modules contains a broken or cyclic symlink") from None + if not target.is_relative_to(root): + raise InputError("node_modules contains a symlink outside this checkout") + + +def run(*command, cwd=None): + try: + result = subprocess.run(command, cwd=cwd, check=True, capture_output=True, text=True) + except (OSError, subprocess.CalledProcessError): + raise InputError(f"cannot run required command: {command[0]}") from None + return result.stdout + result.stderr + + +def check_source(repo, commit): + if not re.fullmatch(r"[0-9a-f]{40}", commit): + raise InputError("expected source commit must be a full 40-character SHA") + actual = run("git", "rev-parse", "HEAD", cwd=repo).strip() + if actual != commit: + raise InputError("checkout HEAD differs from expected source commit") + if run("git", "status", "--porcelain=v1", "--untracked-files=normal", cwd=repo).strip(): + raise InputError("source checkout has uncommitted files") + + +def check_hash(path, expected, label): + if not path.is_file() or sha256(path) != expected: + raise InputError(f"{label} differs from the pinned hash") + + +def check_gradle_distribution(repo, expected): + wrapper = (repo / "android/gradle/wrapper/gradle-wrapper.properties").read_text(encoding="utf-8") + if f"distributionSha256Sum={expected}" not in wrapper.splitlines(): + raise InputError("Gradle distribution checksum differs from the pinned hash") + + +def sdk_revision(path): + properties = path / "source.properties" + if not properties.is_file(): + raise InputError(f"Android SDK package missing: {path.name}") + for line in properties.read_text(encoding="utf-8").splitlines(): + match = re.fullmatch(r"Pkg\.Revision\s*=\s*(\S+)\s*", line) + if match: + return match.group(1) + raise InputError(f"Android SDK package has no revision: {path.name}") + + +def check_toolchain(inputs, sdk_root): + node = run("node", "--version").strip().removeprefix("v") + yarn = run("yarn", "--version").strip() + java_output = run("java", "-XshowSettings:properties", "-version") + java_match = re.search(r"^\s*java\.version\s*=\s*(\S+)\s*$", java_output, re.MULTILINE) + if (node, yarn, java_match.group(1) if java_match else None) != ( + inputs["node"], inputs["yarn"], inputs["java"] + ): + raise InputError("Node, Yarn, or JDK version differs from pinned Android inputs") + for package, revision in inputs["android_packages"].items(): + if sdk_revision(sdk_root / package) != revision: + raise InputError(f"Android SDK package revision differs: {package}") + platform = inputs["android_platform"] + if sdk_revision(sdk_root / platform["path"]) != platform["revision"]: + raise InputError("Android platform revision differs from pinned Android inputs") + if not (sdk_root / platform["path"] / "android.jar").is_file(): + raise InputError("pinned Android platform is missing") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--repo", type=Path, default=Path(__file__).resolve().parent.parent) + parser.add_argument("--source-commit", required=True) + parser.add_argument("--env-file", type=Path, required=True) + parser.add_argument("--android-sdk-root", type=Path, default=None) + args = parser.parse_args() + repo = args.repo.resolve() + sdk_root = args.android_sdk_root or os.environ.get("ANDROID_HOME") or os.environ.get("ANDROID_SDK_ROOT") + if not sdk_root: + raise InputError("ANDROID_HOME or ANDROID_SDK_ROOT is required") + sdk_root = Path(sdk_root).resolve() + inputs = json.loads((repo / "reproducibility/android-inputs.json").read_text(encoding="utf-8")) + check_source(repo, args.source_commit) + check_hash(repo / "yarn.lock", inputs["yarn_lock_sha256"], "yarn.lock") + check_hash( + repo / "android/gradle/wrapper/gradle-wrapper.jar", + inputs["gradle_wrapper_jar_sha256"], + "Gradle wrapper JAR", + ) + check_gradle_distribution(repo, inputs["gradle_distribution_sha256"]) + check_local_dependencies(repo) + check_env_names(args.env_file, inputs["environment_names"]) + check_toolchain(inputs, sdk_root) + print("Android build inputs verified; this is not a reproducibility verdict.") + + +if __name__ == "__main__": + try: + main() + except (InputError, OSError, ValueError, KeyError, json.JSONDecodeError) as error: + print(f"Android input check failed: {error}", file=sys.stderr) + sys.exit(1) diff --git a/scripts/compare-android-apks.py b/scripts/compare-android-apks.py new file mode 100755 index 0000000000..e92f8fa7ca --- /dev/null +++ b/scripts/compare-android-apks.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +"""Compare the uncompressed payload entries of two Android APKs. + +This is an inspection aid, not a WalletScrutiny build script or a Play attestation. +It never extracts archive entries to the filesystem. +""" + +from __future__ import annotations + +import argparse +from collections import Counter +import hashlib +import json +from pathlib import Path +import re +import sys +import zipfile + + +CHUNK_SIZE = 1024 * 1024 +MAX_ENTRIES = 100_000 +MAX_ENTRY_BYTES = 2 * 1024**3 +MAX_TOTAL_BYTES = 4 * 1024**3 + +# APK Signature Scheme v2/v3 blocks are outside ZIP entries. These names cover +# only root-level JAR/v1 signature material plus Play's certificate stamp. +JAR_SIGNATURE = re.compile(r"^META-INF/[^/]+\.(?:SF|RSA|DSA|EC)$") +DEX_FILE = re.compile(r"(?:^|/)classes\d*\.dex$") + + +def is_signing_only(name: str) -> bool: + return ( + name == "META-INF/MANIFEST.MF" + or name == "stamp-cert-sha256" + or JAR_SIGNATURE.fullmatch(name) is not None + ) + + +def category(name: str) -> str: + if DEX_FILE.search(name) or name.endswith(".dex"): + return "dex" + if name.startswith("assets/dexopt/") and name.endswith((".prof", ".profm")): + return "baseline_profile" + if name.startswith("lib/") and name.endswith(".so"): + return "native_library" + if name.endswith((".jsbundle", ".bundle")) or ( + name.startswith("assets/") and name.endswith(".js") + ): + return "javascript_bundle" + if name == "AndroidManifest.xml": + return "manifest" + if name == "resources.arsc" or name.startswith("res/"): + return "resource" + if name.startswith("META-INF/"): + return "metadata" + if name.startswith("assets/"): + return "asset" + return "other" + + +def file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(CHUNK_SIZE), b""): + digest.update(chunk) + return digest.hexdigest() + + +def inspect_apk(path: Path) -> dict: + if not path.is_file(): + raise ValueError(f"Not a regular file: {path}") + + with zipfile.ZipFile(path) as archive: + infos = archive.infolist() + if len(infos) > MAX_ENTRIES: + raise ValueError(f"Too many ZIP entries in {path}: {len(infos)}") + + names = [info.filename for info in infos] + duplicates = sorted(name for name, count in Counter(names).items() if count > 1) + if duplicates: + raise ValueError(f"Duplicate ZIP entry names in {path}: {duplicates}") + + files = [info for info in infos if not info.is_dir()] + total_bytes = sum(info.file_size for info in files) + if total_bytes > MAX_TOTAL_BYTES: + raise ValueError(f"Declared uncompressed ZIP size exceeds limit in {path}") + + entries = {} + for info in files: + if info.file_size > MAX_ENTRY_BYTES: + raise ValueError(f"ZIP entry exceeds size limit in {path}: {info.filename}") + digest = hashlib.sha256() + measured = 0 + # Passing ZipInfo selects the exact entry; reading to EOF checks its CRC. + with archive.open(info) as stream: + for chunk in iter(lambda: stream.read(CHUNK_SIZE), b""): + measured += len(chunk) + if measured > MAX_ENTRY_BYTES: + raise ValueError(f"ZIP entry exceeds size limit in {path}: {info.filename}") + digest.update(chunk) + if measured != info.file_size: + raise ValueError(f"Incorrect ZIP entry size in {path}: {info.filename}") + entries[info.filename] = {"sha256": digest.hexdigest(), "size": measured} + + return { + "path": str(path.resolve()), + "apk_sha256": file_sha256(path), + "payload_entry_count": len(entries), + "entries": entries, + } + + +def compare(reference: dict, rebuilt: dict) -> dict: + reference_entries = reference["entries"] + rebuilt_entries = rebuilt["entries"] + differences = [] + ignored_signing_entries = [] + matching_payload_entries = 0 + + for name in sorted(reference_entries.keys() | rebuilt_entries.keys()): + before = reference_entries.get(name) + after = rebuilt_entries.get(name) + if before == after: + if not is_signing_only(name): + matching_payload_entries += 1 + continue + + status = ( + "only_reference" if after is None else + "only_rebuilt" if before is None else + "content_mismatch" + ) + detail = { + "path": name, + "status": status, + "category": "signing_only" if is_signing_only(name) else category(name), + "reference": before, + "rebuilt": after, + } + if is_signing_only(name): + ignored_signing_entries.append(detail) + else: + differences.append(detail) + + return { + "schema_version": 1, + "verdict": "match" if not differences else "mismatch", + "scope": "one APK versus one APK; uncompressed ZIP file entries", + "reference": {key: value for key, value in reference.items() if key != "entries"}, + "rebuilt": {key: value for key, value in rebuilt.items() if key != "entries"}, + "summary": { + "matching_payload_entries": matching_payload_entries, + "payload_differences": len(differences), + "ignored_signing_differences": len(ignored_signing_entries), + }, + "differences": differences, + "ignored_signing_entries": ignored_signing_entries, + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("reference_apk", type=Path, help="Published reference APK") + parser.add_argument("rebuilt_apk", type=Path, help="APK rebuilt from source") + args = parser.parse_args() + + try: + report = compare(inspect_apk(args.reference_apk), inspect_apk(args.rebuilt_apk)) + except (OSError, ValueError, RuntimeError, EOFError, NotImplementedError, zipfile.BadZipFile) as error: + report = {"schema_version": 1, "verdict": "invalid_input", "error": str(error)} + + json.dump(report, sys.stdout, indent=2, sort_keys=True) + sys.stdout.write("\n") + return {"match": 0, "mismatch": 1, "invalid_input": 2}[report["verdict"]] + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/test_compare_android_apks.py b/scripts/test_compare_android_apks.py new file mode 100644 index 0000000000..8841cf0092 --- /dev/null +++ b/scripts/test_compare_android_apks.py @@ -0,0 +1,149 @@ +"""Synthetic APK tests for the payload comparison aid.""" + +import contextlib +import importlib.util +import io +import json +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch +import warnings +import zipfile + + +spec = importlib.util.spec_from_file_location( + "compare_android_apks", Path(__file__).with_name("compare-android-apks.py") +) +comparator = importlib.util.module_from_spec(spec) +spec.loader.exec_module(comparator) + + +class ApkComparisonTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.directory = Path(temporary.name) + + def apk(self, name, entries, *, compression=zipfile.ZIP_STORED): + path = self.directory / name + with zipfile.ZipFile(path, "w", compression=compression) as archive: + for entry_name, content in entries.items(): + archive.writestr(entry_name, content) + return path + + def result(self, reference, rebuilt): + return comparator.compare( + comparator.inspect_apk(reference), comparator.inspect_apk(rebuilt) + ) + + def test_only_root_signing_material_is_excluded(self): + common = { + "classes.dex": b"same dex", + "META-INF/services/provider": b"same non-signing metadata", + } + reference = self.apk("published.apk", { + **common, + "META-INF/MANIFEST.MF": b"original manifest digest", + "META-INF/CERT.SF": b"original signature file", + "META-INF/CERT.RSA": b"original certificate", + "stamp-cert-sha256": b"original stamp", + }) + rebuilt = self.apk("rebuilt.apk", { + **common, + "META-INF/MANIFEST.MF": b"different manifest digest", + "META-INF/CERT.SF": b"different signature file", + "META-INF/CERT.RSA": b"different certificate", + "stamp-cert-sha256": b"different stamp", + }, compression=zipfile.ZIP_DEFLATED) + + result = self.result(reference, rebuilt) + self.assertEqual(result["verdict"], "match") + self.assertEqual(result["summary"], { + "matching_payload_entries": 2, + "payload_differences": 0, + "ignored_signing_differences": 4, + }) + self.assertNotEqual(result["reference"]["apk_sha256"], result["rebuilt"]["apk_sha256"]) + + def test_every_executable_and_resource_category_remains_critical(self): + entries = { + "AndroidManifest.xml": "manifest", + "resources.arsc": "resource", + "res/drawable/icon.png": "resource", + "classes.dex": "dex", + "assets/index.android.bundle": "javascript_bundle", + "lib/arm64-v8a/librealm.so": "native_library", + "assets/dexopt/baseline.prof": "baseline_profile", + "META-INF/com.android.tools.build.gradle/app-metadata.properties": "metadata", + } + reference = self.apk("published.apk", {name: b"old" for name in entries}) + rebuilt = self.apk("rebuilt.apk", {name: b"new" for name in entries}) + + result = self.result(reference, rebuilt) + self.assertEqual(result["verdict"], "mismatch") + self.assertEqual(result["summary"]["payload_differences"], len(entries)) + self.assertEqual(result["summary"]["ignored_signing_differences"], 0) + self.assertEqual( + {entry["path"]: entry["category"] for entry in result["differences"]}, + entries, + ) + self.assertTrue(all(entry["status"] == "content_mismatch" for entry in result["differences"])) + + def test_added_removed_and_nested_signature_named_entries_are_reported(self): + reference = self.apk("published.apk", { + "classes.dex": b"same", + "assets/META-INF/CERT.RSA": b"old nested asset", + "assets/retired.dat": b"removed", + }) + rebuilt = self.apk("rebuilt.apk", { + "classes.dex": b"same", + "assets/META-INF/CERT.RSA": b"new nested asset", + "assets/added.dat": b"added", + }) + + result = self.result(reference, rebuilt) + self.assertEqual(result["verdict"], "mismatch") + self.assertEqual(result["summary"]["matching_payload_entries"], 1) + self.assertEqual(result["summary"]["payload_differences"], 3) + self.assertEqual(result["ignored_signing_entries"], []) + self.assertEqual( + {entry["path"]: entry["status"] for entry in result["differences"]}, + { + "assets/META-INF/CERT.RSA": "content_mismatch", + "assets/retired.dat": "only_reference", + "assets/added.dat": "only_rebuilt", + }, + ) + + def test_duplicate_zip_paths_are_rejected(self): + path = self.directory / "duplicate.apk" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) + with zipfile.ZipFile(path, "w") as archive: + archive.writestr("classes.dex", b"first") + archive.writestr("classes.dex", b"second") + with self.assertRaisesRegex(ValueError, "Duplicate ZIP entry names"): + comparator.inspect_apk(path) + + def test_cli_exit_codes_and_machine_readable_reports(self): + reference = self.apk("published.apk", {"classes.dex": b"same"}) + rebuilt = self.apk("rebuilt.apk", {"classes.dex": b"different"}) + invalid = self.directory / "invalid.apk" + invalid.write_bytes(b"not an APK") + + for candidate, expected_code, expected_verdict in ( + (reference, 0, "match"), + (rebuilt, 1, "mismatch"), + (invalid, 2, "invalid_input"), + ): + with self.subTest(candidate=candidate.name), patch.object( + sys, "argv", ["compare-android-apks.py", str(reference), str(candidate)] + ), contextlib.redirect_stdout(io.StringIO()) as output: + self.assertEqual(comparator.main(), expected_code) + self.assertEqual(json.loads(output.getvalue())["verdict"], expected_verdict) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/verify-channel-config.cjs b/scripts/verify-channel-config.cjs index 18ecc31734..cee7d7ffdc 100644 --- a/scripts/verify-channel-config.cjs +++ b/scripts/verify-channel-config.cjs @@ -7,7 +7,12 @@ if (!envFile || !fs.existsSync(envFile)) { throw new Error('Production environment file is missing'); } -const matches = fs.readFileSync(envFile, 'utf8') +const envContents = fs.readFileSync(envFile, 'utf8'); +if (/^\s*(?:export\s+)?(?:RN_)?(?:GASFREE_API_(?:KEY|SECRET)|LETS_EXCHANGE_API_KEY)\s*=/m.test(envContents)) { + throw new Error('Retired API credentials must not be included in a release environment'); +} + +const matches = envContents .split(/\r?\n/) .map(line => line.match(/^\s*(?:export\s+)?CHANNEL_URL\s*=\s*(.*?)\s*$/)) .filter(Boolean) @@ -17,4 +22,14 @@ if (matches.length !== 1 || matches[0] !== expected) { throw new Error(`Production CHANNEL_URL must be ${expected}`); } -console.log('Production channel URL verified'); +const stages = envContents + .split(/\r?\n/) + .map(line => line.match(/^\s*(?:export\s+)?ENVIRONMENT\s*=\s*(.*?)\s*$/)) + .filter(Boolean) + .map(match => match[1].replace(/^['"]|['"]$/g, '')); + +if (stages.length !== 1 || stages[0] !== 'PRODUCTION') { + throw new Error('Production ENVIRONMENT must be PRODUCTION'); +} + +console.log('Production channel URL and environment verified'); diff --git a/scripts/verify-channel-config.test.cjs b/scripts/verify-channel-config.test.cjs new file mode 100644 index 0000000000..adf9ba3d76 --- /dev/null +++ b/scripts/verify-channel-config.test.cjs @@ -0,0 +1,81 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); + +const verifier = path.join(__dirname, 'verify-channel-config.cjs'); +const prebuild = path.join(__dirname, '..', 'appcenter-pre-build.sh'); +const channel = 'CHANNEL_URL=https://channel.bitcoinkeeper.app/\nENVIRONMENT=PRODUCTION\n'; + +function withTempDirectory(run) { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'keeper-usdt-env-')); + try { + return run(directory); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } +} + +test('release env accepts reviewed channel without retired credentials', () => + withTempDirectory((directory) => { + const envFile = path.join(directory, '.env.production'); + fs.writeFileSync(envFile, channel); + const result = spawnSync(process.execPath, [verifier, envFile], { encoding: 'utf8' }); + assert.equal(result.status, 0, result.stderr); + })); + +for (const [caseName, stage] of [ + ['missing', ''], + ['development', 'ENVIRONMENT=DEVELOPMENT\n'], + ['duplicate', 'ENVIRONMENT=PRODUCTION\nENVIRONMENT=PRODUCTION\n'], +]) { + test(`release env rejects ${caseName} production stage`, () => + withTempDirectory((directory) => { + const envFile = path.join(directory, '.env.production'); + fs.writeFileSync(envFile, `CHANNEL_URL=https://channel.bitcoinkeeper.app/\n${stage}`); + const result = spawnSync(process.execPath, [verifier, envFile], { encoding: 'utf8' }); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /Production ENVIRONMENT must be PRODUCTION/); + })); +} + +for (const name of ['GASFREE_API_KEY', 'GASFREE_API_SECRET', 'RN_GASFREE_API_KEY', + 'LETS_EXCHANGE_API_KEY', 'RN_LETS_EXCHANGE_API_KEY']) { + test(`release env rejects ${name} without logging its value`, () => + withTempDirectory((directory) => { + const envFile = path.join(directory, '.env.production'); + const secret = 'synthetic-secret-not-for-output'; + fs.writeFileSync(envFile, `${channel}${name}=${secret}\n`); + const result = spawnSync(process.execPath, [verifier, envFile], { encoding: 'utf8' }); + assert.notEqual(result.status, 0); + assert.doesNotMatch(result.stdout + result.stderr, /synthetic-secret-not-for-output/); + })); +} + +test('AppCenter rejects retired credential input before writing .env', () => + withTempDirectory((directory) => { + const secret = 'synthetic-secret-not-for-output'; + const result = spawnSync('bash', [prebuild], { + cwd: directory, + env: { PATH: process.env.PATH, RN_GASFREE_API_SECRET: secret }, + encoding: 'utf8', + }); + assert.notEqual(result.status, 0); + assert.equal(fs.existsSync(path.join(directory, '.env')), false); + assert.doesNotMatch(result.stdout + result.stderr, /synthetic-secret-not-for-output/); + })); + +test('AppCenter rejects retired swap credential input before writing .env', () => + withTempDirectory((directory) => { + const secret = 'synthetic-secret-not-for-output'; + const result = spawnSync('bash', [prebuild], { + cwd: directory, + env: { PATH: process.env.PATH, RN_LETS_EXCHANGE_API_KEY: secret }, + encoding: 'utf8', + }); + assert.notEqual(result.status, 0); + assert.equal(fs.existsSync(path.join(directory, '.env')), false); + assert.doesNotMatch(result.stdout + result.stderr, /synthetic-secret-not-for-output/); + })); diff --git a/sonar-project.properties b/sonar-project.properties deleted file mode 100644 index f7cea55e60..0000000000 --- a/sonar-project.properties +++ /dev/null @@ -1,8 +0,0 @@ -sonar.projectKey=bithyve_bitcoin-keeper -sonar.organization=bithyve - -sonar.coverage.exclusions=**/android/**/*.*,**/ios/**/*.* -sonar.exclusions=**/android/**/*.*,**/ios/**/*.* - -sonar.javascript.file.suffixes=.js,.jsx -sonar.typescript.file.suffixes=.ts,.tsx \ No newline at end of file diff --git a/src/components/TransactionElement.tsx b/src/components/TransactionElement.tsx index a5adda3fac..401e0f0121 100644 --- a/src/components/TransactionElement.tsx +++ b/src/components/TransactionElement.tsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { useContext } from 'react'; import { Box, useColorMode } from '@gluestack-ui/themed-native-base'; import { StyleSheet, TouchableOpacity } from 'react-native'; import moment from 'moment'; @@ -21,10 +21,16 @@ import Colors from 'src/theme/Colors'; import useLabelsNew from 'src/hooks/useLabelsNew'; import { Wallet } from 'src/services/wallets/interfaces/wallet'; import { Vault } from 'src/services/wallets/interfaces/vault'; -import { USDTTransaction } from 'src/services/wallets/operations/dollars/USDT'; +import { + isHistoricalUnverifiedUSDTRequest, + isUSDTStatusUnavailable, + USDTTransaction, +} from 'src/services/wallets/operations/dollars/USDT'; +import { GasFreeTransferStatus } from 'src/services/wallets/operations/dollars/GasFree'; import { EntityKind } from 'src/services/wallets/enums'; import { USDTWallet } from 'src/services/wallets/factories/USDTWalletFactory'; import ThemedColor from './ThemedColor/ThemedColor'; +import { LocalizationContext } from 'src/context/Localization/LocContext'; function TransactionElement({ transaction, @@ -44,12 +50,19 @@ function TransactionElement({ let amount: number; let confirmations: number; let transactionType: string; + const legacyUSDTRequest = + wallet.entityKind === EntityKind.USDT_WALLET && + isHistoricalUnverifiedUSDTRequest(transaction as USDTTransaction); + const unavailableUSDTStatus = + wallet.entityKind === EntityKind.USDT_WALLET && + isUSDTStatusUnavailable(transaction as USDTTransaction); if (wallet.entityKind === EntityKind.USDT_WALLET) { transactionId = (transaction as USDTTransaction).txId || (transaction as USDTTransaction).traceId; date = (transaction as USDTTransaction).timestamp; amount = parseFloat((transaction as USDTTransaction).amount); - confirmations = (transaction as USDTTransaction).blockNumber ? 6 : 0; // Assuming 6 confirmations for USDT transactions(no. of conf on Tron doesn't really make any finality sense) + confirmations = + (transaction as USDTTransaction).status === GasFreeTransferStatus.CHAIN_CONFIRMED ? 1 : 0; if ( (transaction as USDTTransaction).to === (wallet as USDTWallet).accountStatus.gasFreeAddress ) { @@ -65,6 +78,7 @@ function TransactionElement({ const { labels } = useLabelsNew({ txid: transactionId }); const { colorMode } = useColorMode(); + const { translations } = useContext(LocalizationContext); const formattedDate = moment(date)?.format('DD MMM YY . HH:mm A'); const viewAll_color = ThemedColor({ name: 'viewAll_color' }); @@ -73,6 +87,7 @@ function TransactionElement({ - {confirmations === 0 && !isCached && ( + {confirmations === 0 && !isCached && !unavailableUSDTStatus && ( )} - {isCached ? ( + {legacyUSDTRequest ? null : isCached ? ( ) : transactionType === 'Received' ? ( colorMode === 'light' ? ( @@ -104,15 +119,22 @@ function TransactionElement({ - {labels[transactionId]?.[0]?.name || transactionId} + {legacyUSDTRequest + ? translations.usdtWalletText.legacyRequestTitle + : labels[transactionId]?.[0]?.name || transactionId} {formattedDate} + {unavailableUSDTStatus && ( + + {translations.usdtWalletText.statusUnavailable} + + )} {(transaction as Transaction).tags?.includes('potential-dust-spend') && ( @@ -123,15 +145,17 @@ function TransactionElement({ - + {!legacyUSDTRequest && ( + + )} {colorMode === 'dark' ? : } @@ -145,11 +169,17 @@ const styles = StyleSheet.create({ container: { flexDirection: 'row', borderRadius: 10, - height: hp(76), justifyContent: 'space-between', alignItems: 'center', borderBottomWidth: 1, }, + standardContainer: { + height: hp(76), + }, + legacyContainer: { + minHeight: hp(76), + paddingVertical: hp(8), + }, rowCenter: { marginHorizontal: wp(10), flexDirection: 'row', @@ -167,6 +197,12 @@ const styles = StyleSheet.create({ marginHorizontal: 3, lineHeight: 17, }, + legacyStatus: { + fontSize: 10, + width: wp(125), + marginHorizontal: 3, + lineHeight: 13, + }, transactionIdText: { marginHorizontal: 4, fontSize: 14, diff --git a/src/context/Localization/language/en.json b/src/context/Localization/language/en.json index 3a451be678..1f0aecf80f 100644 --- a/src/context/Localization/language/en.json +++ b/src/context/Localization/language/en.json @@ -2153,6 +2153,15 @@ "psbtMissingSignature": "This PSBT does not include a signature for the selected signer" }, "usdtWalletText": { + "pausedTitle": "USDT activity is limited", + "pausedBody": "New USDT wallets, sending, buying, selling and swapping are paused. This wallet, its balance and history remain available.", + "sendingPausedTitle": "USDT sending is paused", + "sendingPausedBody": "Keeper cannot send USDT from this wallet right now. Your wallet details, balance and transaction history remain available.", + "receivePausedWarning": "This is your wallet's saved receive address. Keeper cannot send USDT from this wallet while sending is paused. Funds received here cannot be sent through Keeper during the pause. Do not deposit new USDT unless you understand this limitation.", + "statusUnavailable": "Status unavailable", + "legacyRequestTitle": "Earlier USDT request", + "legacyRequestNotice": "Keeper can no longer verify this earlier USDT request. If it completed, it may also appear as a separate on-chain transaction.", + "requestedAmount": "Requested Amount", "pickWalletType": "Pick Your Wallet Type", "selectCurrency": "Select the currency you would like to use", "bitcoinWallet": "Bitcoin Wallet", diff --git a/src/context/Localization/language/es.json b/src/context/Localization/language/es.json index 4670ae75db..1df00a4afa 100644 --- a/src/context/Localization/language/es.json +++ b/src/context/Localization/language/es.json @@ -2134,6 +2134,15 @@ "psbtMissingSignature": "This PSBT does not include a signature for the selected signer" }, "usdtWalletText": { + "pausedTitle": "La actividad de USDT está limitada", + "pausedBody": "La creación de carteras de USDT, el envío, la compra, la venta y el intercambio están pausados. Esta cartera, su saldo e historial siguen disponibles.", + "sendingPausedTitle": "El envío de USDT está pausado", + "sendingPausedBody": "Keeper no puede enviar USDT desde esta cartera ahora mismo. Los detalles, el saldo y el historial de transacciones de la cartera siguen disponibles.", + "receivePausedWarning": "Esta es la dirección de recepción guardada de tu cartera. Keeper no puede enviar USDT desde esta cartera mientras el envío esté pausado. Los fondos recibidos aquí no se pueden enviar mediante Keeper durante la pausa. No deposites nuevos USDT a menos que comprendas esta limitación.", + "statusUnavailable": "Estado no disponible", + "legacyRequestTitle": "Solicitud anterior de USDT", + "legacyRequestNotice": "Keeper ya no puede verificar esta solicitud de USDT anterior. Si se completó, también puede aparecer como una transacción separada en la cadena.", + "requestedAmount": "Importe solicitado", "pickWalletType": "Pick Your Wallet Type", "selectCurrency": "Select the currency you would like to use", "bitcoinWallet": "Bitcoin Wallet", diff --git a/src/hooks/useUSDTWallets.ts b/src/hooks/useUSDTWallets.ts index 12578e9f78..f10f538f58 100644 --- a/src/hooks/useUSDTWallets.ts +++ b/src/hooks/useUSDTWallets.ts @@ -32,6 +32,9 @@ export interface UseUSDTWalletsOptions { includeHidden?: boolean; } +// Existing USDT wallets remain readable, but new wallet creation and import are paused. +export const USDT_WALLET_CREATION_PAUSED = true; + export interface UseUSDTWalletsReturn { usdtWallets: USDTWallet[]; error: string | null; @@ -101,6 +104,10 @@ export const useUSDTWallets = (options: UseUSDTWalletsOptions = {}): UseUSDTWall primaryMnemonic?: string; importDetails?: USDTWalletImportDetails; }): Promise<{ newWallet?: USDTWallet; error?: string }> => { + if (USDT_WALLET_CREATION_PAUSED) { + return { error: 'USDT wallet setup is paused' }; + } + try { setError(null); const walletNetworkType = USDTWalletSupportedNetwork; diff --git a/src/navigation/Navigator.tsx b/src/navigation/Navigator.tsx index dd9327ee96..b89ab6a517 100644 --- a/src/navigation/Navigator.tsx +++ b/src/navigation/Navigator.tsx @@ -154,13 +154,8 @@ import SetupAdditionalServerKey from 'src/screens/SigningDevices/SetupAdditional import { MultiUserScreen } from 'src/screens/AppSettings/MultiUserScreen'; import { AddMultipleXpubFiles } from 'src/screens/AddSigner/AddMultipleXpubFiles'; import { SignMessageScreen } from 'src/screens/WalletDetails/SignMessageScreen'; -import AddUsdtWallet from 'src/screens/USDT/UsdtAddWallet'; import UsdtDetails from 'src/screens/USDT/UsdtDetails'; import RecieveUsdt from 'src/screens/USDT/RecieveUsdt'; -import BuyUstd from 'src/screens/USDT/BuyUstd'; -import SendUsdt from 'src/screens/USDT/SendUsdt'; -import UsdtAmount from 'src/screens/USDT/UsdtAmount'; -import UsdtSendConfirmation from 'src/screens/USDT/UsdtSendConfirmation'; import UsdtTransactionDetail from 'src/screens/USDT/UsdtTransactionDetail'; import UsdtTransactionHistory from 'src/screens/USDT/UsdtTransactionHistory'; import Usdtsetting from 'src/screens/USDT/Usdtsetting'; @@ -170,8 +165,6 @@ import KeeperSupport from 'src/screens/KeeperConcierge/KeeperSupport'; import Advisors from 'src/screens/Advisors/Advisors'; import FilterAdvisor from 'src/screens/Advisors/FilterAdvisor'; import AdvisorDetail from 'src/screens/Advisors/AdvisorDetail'; -import { Swaps } from 'src/screens/Home/components/buyBtc/Swap/Swaps'; -import { SwapDetails } from 'src/screens/Home/components/buyBtc/Swap/SwapDetails'; import { SwapHistory } from 'src/screens/Home/components/buyBtc/Swap/SwapHistory'; import { SwapHistoryDetail } from 'src/screens/Home/components/buyBtc/Swap/SwapHistoryDetail'; import { SwapAllHistory } from 'src/screens/Home/components/buyBtc/Swap/SwapAllHistory'; @@ -295,13 +288,8 @@ function AppStack() { - - - - - @@ -384,8 +372,6 @@ function AppStack() { - - diff --git a/src/screens/Home/components/Wallet/HomeWallet.tsx b/src/screens/Home/components/Wallet/HomeWallet.tsx index f277a0b79a..95978a0004 100644 --- a/src/screens/Home/components/Wallet/HomeWallet.tsx +++ b/src/screens/Home/components/Wallet/HomeWallet.tsx @@ -1,7 +1,6 @@ import { Box, useColorMode, View } from '@gluestack-ui/themed-native-base'; import React, { useContext, useState, useEffect } from 'react'; import { FlatList, StyleSheet, TouchableOpacity } from 'react-native'; -import DashedCta from 'src/components/DashedCta'; import WalletCard from './WalletCard'; import Colors from 'src/theme/Colors'; import useWallets from 'src/hooks/useWallets'; @@ -10,11 +9,11 @@ import { Wallet } from 'src/services/wallets/interfaces/wallet'; import { Vault } from 'src/services/wallets/interfaces/vault'; import useWalletAsset from 'src/hooks/useWalletAsset'; -import { EntityKind, VisibilityType, WalletType } from 'src/services/wallets/enums'; -import { useNavigation, useFocusEffect, CommonActions } from '@react-navigation/native'; +import { EntityKind, VisibilityType } from 'src/services/wallets/enums'; +import { useNavigation } from '@react-navigation/native'; import KeeperModal from 'src/components/KeeperModal'; import Text from 'src/components/KeeperText'; -import { hp, windowWidth, wp } from 'src/constants/responsive'; +import { hp, wp } from 'src/constants/responsive'; import NewWalletIcon from 'src/assets/images/wallet-white-small.svg'; import ImportWalletIcon from 'src/assets/images/import.svg'; @@ -23,26 +22,18 @@ import CollaborativeWalletIcon from 'src/assets/images/collaborative_vault_white import { useAppSelector } from 'src/store/hooks'; import { resetCollaborativeSession } from 'src/store/reducers/vaults'; import { useDispatch } from 'react-redux'; -import { autoSyncWallets, refreshWallets } from 'src/store/sagaActions/wallets'; +import { autoSyncWallets } from 'src/store/sagaActions/wallets'; import { RefreshControl } from 'react-native'; import { ELECTRUM_CLIENT } from 'src/services/electrum/client'; import ActivityIndicatorView from 'src/components/AppActivityIndicator/ActivityIndicatorView'; import CircleIconWrapper from 'src/components/CircleIconWrapper'; -import ThemedColor from 'src/components/ThemedColor/ThemedColor'; -import ThemedSvg from 'src/components/ThemedSvg.tsx/ThemedSvg'; import { LocalizationContext } from 'src/context/Localization/LocContext'; -import BitCoinWalletLogo from 'src/assets/images/bitcoin-wallet-logo.svg'; -import UsdtWalletLogo from 'src/assets/images/usdt-wallet-logo.svg'; import { useUSDTWallets } from 'src/hooks/useUSDTWallets'; import { getAvailableBalanceUSDTWallet, USDTWallet, - USDTWalletSupportedNetwork, - USDTWalletType, } from 'src/services/wallets/factories/USDTWalletFactory'; import useToastMessage from 'src/hooks/useToastMessage'; -import TickIcon from 'src/assets/images/icon_tick.svg'; -import ToastErrorIcon from 'src/assets/images/toast_error.svg'; import Fab from 'src/components/Fab'; import AddIcon from 'src/assets/images/add_white.svg'; import { useUTXOSpendability } from 'src/hooks/useUTXOSpendability'; @@ -105,28 +96,24 @@ function WalletCardItem({ const HomeWallet = () => { const { colorMode } = useColorMode(); - const isDarkMode = colorMode === 'dark'; const navigation = useNavigation(); const { wallets } = useWallets({ getAll: true }); const { translations } = useContext(LocalizationContext); - const { wallet: walletText, home, common, usdtWalletText } = translations; + const { wallet: walletText, home, common } = translations; const { getWalletCardGradient, getWalletTags } = useWalletAsset(); const { allVaults } = useVault({ includeArchived: false, getFirst: true, getHiddenWallets: false, }); - const { usdtWallets, createWallet } = useUSDTWallets(); + const { usdtWallets } = useUSDTWallets(); const { collaborativeSession } = useAppSelector((state) => state.vault); - const { bitcoinNetworkType } = useAppSelector((state) => state.settings); const dispatch = useDispatch(); const [showAddWalletModal, setShowAddWalletModal] = useState(false); const [collabSessionExistsModalVisible, setCollabSessionExistsModalVisible] = useState(false); const [pullRefresh, setPullRefresh] = useState(false); const { walletSyncing } = useAppSelector((state) => state.wallet); - const [pickWalletType, setPickWalletType] = useState(false); - const [createUsdtWallet, setCreateUsdtWallet] = useState(false); const syncing = ELECTRUM_CLIENT.isClientConnected && Object.values(walletSyncing).some((isSyncing) => isSyncing); @@ -140,12 +127,6 @@ const HomeWallet = () => { ...usdtWallets, ].filter((item) => item !== null); const [isShowAmount, setIsShowAmount] = useState(false); - const DashedCta_hexagonBackgroundColor = ThemedColor({ - name: 'DashedCta_hexagonBackgroundColor', - }); - const dashed_CTA_background = ThemedColor({ - name: 'dashed_CTA_background', - }); const { showToast } = useToastMessage(); const pendingDustToast = useAppSelector((state: any) => state.utxos.pendingDustToast); @@ -176,35 +157,6 @@ const HomeWallet = () => { setPullRefresh(false); }; - const importUSDTWallet = async (mnemonic) => { - try { - const { newWallet, error } = await createWallet({ - type: USDTWalletType.IMPORTED, - name: 'USDT Wallet', - description: 'Imported USDT Wallet', - importDetails: { - mnemonic, - }, - }); - - if (newWallet) { - showToast('USDT wallet imported successfully!', ); - setTimeout(() => { - navigation.dispatch( - CommonActions.navigate({ - name: 'Home', - params: { selectedOption: 'Wallets' }, - }) - ); - }, 900); - } else { - throw new Error(error); - } - } catch (err) { - showToast(`Failed to import USDT wallet: ${err.message}`, ); - } - }; - const CREATE_WALLET_OPTIONS = [ { title: walletText.createWallet, @@ -234,38 +186,6 @@ const HomeWallet = () => { id: 'collaborativeWallet', }, ]; - const CREATE_USDT_WALLET_OPTIONS = [ - { - title: walletText.createWallet, - subtitle: 'Create a new USDT wallet', - icon: , - onPress: () => { - navigation.navigate('addUsdtWallet'); - setCreateUsdtWallet(false); - }, - id: 'usdtnewWallet', - }, - { - title: home.ImportWallet, - subtitle: walletText.restoreExistingWallet, - icon: , - onPress: () => { - setCreateUsdtWallet(false); - navigation.dispatch( - CommonActions.navigate({ - name: 'EnterSeedScreen', - params: { - isImport: true, - isUSDTWallet: true, - importSeedCta: importUSDTWallet, - }, - }) - ); - }, - id: 'usdtimportWallet', - }, - ]; - const renderWalletCard = ({ item }: { item: Wallet | Vault | USDTWallet }) => ( { } - onPress={() => setPickWalletType(true)} + onPress={() => setShowAddWalletModal(true)} /> { )} /> - setCreateUsdtWallet(false)} - textColor={`${colorMode}.textGreen`} - subTitleColor={`${colorMode}.modalSubtitleBlack`} - showCloseIcon - Content={() => ( - - {CREATE_USDT_WALLET_OPTIONS.map((option, index) => ( - - ))} - - )} - /> setCollabSessionExistsModalVisible(false)} @@ -343,63 +247,6 @@ const HomeWallet = () => { navigation.navigate('SetupCollaborativeWallet'); }} /> - setPickWalletType(false)} - title={usdtWalletText.pickWalletType} - subTitle={usdtWalletText.selectCurrency} - textColor={`${colorMode}.textGreen`} - subTitleColor={`${colorMode}.modalSubtitleBlack`} - modalBackground={`${colorMode}.modalWhiteBackground`} - Content={() => ( - - { - setShowAddWalletModal(true); - setPickWalletType(false); - }} - > - - } - backgroundColor={Colors.BrightOrange} - /> - - {usdtWalletText.bitcoinWallet} - - - - {bitcoinNetworkType === USDTWalletSupportedNetwork ? ( - { - setCreateUsdtWallet(true); - setPickWalletType(false); - }} - > - - } - backgroundColor={Colors.DesaturatedTeal} - /> - - {usdtWalletText.dollarWallet} - - - - ) : null} - - )} - /> ); }; @@ -457,26 +304,4 @@ const styles = StyleSheet.create({ borderRadius: 12, borderWidth: 1, }, - customStyle: { - marginBottom: hp(10), - }, - DashedCtaStyle: { - width: windowWidth * 0.88, - }, - walletTypeContainer: { - gap: wp(15), - marginBottom: hp(10), - flexDirection: 'row', - justifyContent: 'center', - alignContent: 'center', - }, - typeCard: { - width: wp(148), - height: hp(104), - alignItems: 'center', - borderWidth: 1, - justifyContent: 'center', - borderRadius: 12, - gap: wp(10), - }, }); diff --git a/src/screens/Home/components/buyBtc/BuyBtc.tsx b/src/screens/Home/components/buyBtc/BuyBtc.tsx index ecb21234a9..060c20ef4a 100644 --- a/src/screens/Home/components/buyBtc/BuyBtc.tsx +++ b/src/screens/Home/components/buyBtc/BuyBtc.tsx @@ -19,11 +19,11 @@ import useToastMessage from 'src/hooks/useToastMessage'; import ToastErrorIcon from 'src/assets/images/toast_error.svg'; import AcquireCard from './AcquireCard'; import BtcAcquireIcon from 'src/assets/images/bitcoin-acquire-icon.svg'; -import UsdtWalletLogo from 'src/assets/images/usdt-wallet-logo.svg'; -import { useUSDTWallets } from 'src/hooks/useUSDTWallets'; -import { fetchSellBtcLink, fetchSellUsdtLink } from 'src/services/thirdparty/ramp'; -import Buttons from 'src/components/Buttons'; +import { fetchSellBtcLink } from 'src/services/thirdparty/ramp'; import ActivityIndicatorView from 'src/components/AppActivityIndicator/ActivityIndicatorView'; +import { useQuery } from '@realm/react'; +import { RealmSchema } from 'src/storage/realm/enum'; +import { SwapHistory } from './Swap/SwapHistory'; const BuyBtc = () => { const { colorMode } = useColorMode(); @@ -35,21 +35,17 @@ const BuyBtc = () => { const { buyBTC: buyBTCText, common } = translations; const [visibleBuyBtc, setVisibleBuyBtc] = useState(false); const [selectedWallet, setSelectedWallet] = useState(null); - const [selectedUsdtWallet, setSelectedUsdtWallet] = useState(null); const navigation = useNavigation(); const [graphData, setGraphData] = useState([]); const [error, setError] = useState(false); const [stats, setStats] = useState(null); const [visibleSellBtc, setVisibleSellBtc] = useState(false); - const [visibleSellUsdt, setVisibleSellUsdt] = useState(false); - const [visibleBuyUsdt, setVisibleBuyUsdt] = useState(false); const { wallets } = useWallets(); const { allVaults } = useVault({ getHiddenWallets: false }); const { showToast } = useToastMessage(); const allWallets = [...wallets, ...allVaults]; - const { usdtWallets } = useUSDTWallets(); - const [usdtPrice, setUsdtPrice] = useState(null); + const previousSwaps = useQuery(RealmSchema.SwapHistory); const [loading, setLoading] = useState(false); useEffect(() => { @@ -58,13 +54,9 @@ const BuyBtc = () => { const loadBtcPrice = async () => { try { - let [usdtData, btcPrice] = await Promise.all([ - Relay.getUsdtPrice(currencyCode), - Relay.getBtcPrice(currencyCode), - ]); + const btcPrice = await Relay.getBtcPrice(currencyCode); const { dailyPrice, high24h, latestPrice, low24h, percentChange, valueChange } = manipulateBitcoinPrices(btcPrice?.prices); - setUsdtPrice(usdtData[0].current_price.toFixed(2)); setGraphData(dailyPrice); setStats({ high24h, low24h, latestPrice, percentChange, valueChange }); } catch (error) { @@ -106,31 +98,8 @@ const BuyBtc = () => { }} graphContent={} /> - } - amount={`${BtcPrice?.symbol} ${usdtPrice ?? '--'} `} - buyCallback={() => { - if (usdtWallets.length) setVisibleBuyUsdt(true); - else showToast('Please create a USDT wallet to proceed.', ); - }} - sellCallback={() => { - if (usdtWallets.length > 0) { - setVisibleSellUsdt(true); - } else showToast("You don't have USDT yet.", ); - }} - /> + {previousSwaps.length > 0 && } - - { - navigation.dispatch(CommonActions.navigate('Swaps')); - }} - fullWidth - /> - {buyBTCText.transactionOnRamp} @@ -164,30 +133,6 @@ const BuyBtc = () => { ); }} /> - setVisibleBuyUsdt(false)} - title={buyBTCText.selectWallet} - subTitle={buyBTCText.selectWalletDesc} - modalBackground={`${colorMode}.modalWhiteBackground`} - textColor={`${colorMode}.textGreen`} - subTitleColor={`${colorMode}.modalSubtitleBlack`} - Content={() => ( - - )} - buttonText={selectedUsdtWallet ? common.proceed : null} - buttonCallback={() => { - if (!selectedUsdtWallet) return; - setVisibleBuyUsdt(false); - navigation.dispatch( - CommonActions.navigate({ name: 'buyUstd', params: { usdtWallet: selectedUsdtWallet } }) - ); - }} - /> setVisibleSellBtc(false)} @@ -218,36 +163,6 @@ const BuyBtc = () => { } }} /> - setVisibleSellUsdt(false)} - title={buyBTCText.proceedToRamp} - modalBackground={`${colorMode}.modalWhiteBackground`} - textColor={`${colorMode}.textGreen`} - subTitleColor={`${colorMode}.modalSubtitleBlack`} - Content={() => ( - - {buyBTCText.rediredctToRampPage} - - )} - buttonText={common.confirm} - buttonCallback={async () => { - try { - setLoading(true); - setVisibleSellUsdt(false); - const url = await fetchSellUsdtLink(); - Linking.openURL(url.toString()); - } catch (error) { - showToast('Error while fetching ramp url'); - } finally { - setLoading(false); - } - }} - /> ); @@ -296,11 +211,6 @@ const styles = StyleSheet.create({ width: wp(160), borderRadius: 8, }, - button_container: { - width: windowWidth, - marginVertical: hp(10), - paddingHorizontal: wp(12), - }, info_container: { maxWidth: windowWidth, paddingHorizontal: wp(12), diff --git a/src/screens/Home/components/buyBtc/Swap/SwapHistoryDetail.tsx b/src/screens/Home/components/buyBtc/Swap/SwapHistoryDetail.tsx index 9d4683f5d9..d658f6a45e 100644 --- a/src/screens/Home/components/buyBtc/Swap/SwapHistoryDetail.tsx +++ b/src/screens/Home/components/buyBtc/Swap/SwapHistoryDetail.tsx @@ -8,7 +8,7 @@ import useToastMessage from 'src/hooks/useToastMessage'; import ToastErrorIcon from 'src/assets/images/toast_error.svg'; import { useDispatch } from 'react-redux'; import { getTnxDetails } from 'src/store/sagaActions/swap'; -import { CoinLogo } from './Swaps'; +import { CoinLogo } from './component/CoinLogo'; import { StyleSheet } from 'react-native'; import CircleIconWrapper from 'src/components/CircleIconWrapper'; import { hp, wp } from 'src/constants/responsive'; diff --git a/src/screens/Home/components/buyBtc/Swap/Swaps.tsx b/src/screens/Home/components/buyBtc/Swap/Swaps.tsx index 1b382f2676..9bcc6d6ffa 100644 --- a/src/screens/Home/components/buyBtc/Swap/Swaps.tsx +++ b/src/screens/Home/components/buyBtc/Swap/Swaps.tsx @@ -14,8 +14,6 @@ import { useAppSelector } from 'src/store/hooks'; import ToastErrorIcon from 'src/assets/images/toast_error.svg'; import Checked from 'src/assets/images/tick_icon.svg'; import { createSwapTnx, getSwapQuote, loadCoinDetails } from 'src/store/sagaActions/swap'; -import BtcAcquireIcon from 'src/assets/images/bitcoin-acquire-icon.svg'; -import UsdtWalletLogo from 'src/assets/images/usdt-wallet-logo.svg'; import Colors from 'src/theme/Colors'; import { useUSDTWallets } from 'src/hooks/useUSDTWallets'; import useVault from 'src/hooks/useVault'; @@ -23,41 +21,11 @@ import useWallets from 'src/hooks/useWallets'; import KeeperModal from 'src/components/KeeperModal'; import BuyBtcModalContent from '../BuyBtcModalContent'; import { SwapHistory } from './SwapHistory'; -import CircleIconWrapper from 'src/components/CircleIconWrapper'; import ThemedSvg from 'src/components/ThemedSvg.tsx/ThemedSvg'; import { LocalizationContext } from 'src/context/Localization/LocContext'; import { EntityKind } from 'src/services/wallets/enums'; +import { CoinLogo } from './component/CoinLogo'; -export const CoinLogo = ({ - code, - CircleWidth, - logoWidth, - logoHeight, -}: { - code: string; - isLarge?: boolean; - CircleWidth?: number; - logoWidth?: number; - logoHeight?: number; -}) => { - const isBtc = code === 'BTC'; - - return ( - - - ) : ( - - ) - } - backgroundColor={isBtc ? Colors.BrightOrange : Colors.DesaturatedTeal} - width={CircleWidth} - /> - - ); -}; export const SwitchButton = ({ onPress, coinData }) => { const { colorMode } = useColorMode(); diff --git a/src/screens/Home/components/buyBtc/Swap/component/CoinLogo.tsx b/src/screens/Home/components/buyBtc/Swap/component/CoinLogo.tsx new file mode 100644 index 0000000000..a5f4383630 --- /dev/null +++ b/src/screens/Home/components/buyBtc/Swap/component/CoinLogo.tsx @@ -0,0 +1,36 @@ +import { Box } from '@gluestack-ui/themed-native-base'; +import React from 'react'; +import BtcAcquireIcon from 'src/assets/images/bitcoin-acquire-icon.svg'; +import UsdtWalletLogo from 'src/assets/images/usdt-wallet-logo.svg'; +import CircleIconWrapper from 'src/components/CircleIconWrapper'; +import Colors from 'src/theme/Colors'; + +export const CoinLogo = ({ + code, + CircleWidth, + logoWidth, + logoHeight, +}: { + code: string; + CircleWidth?: number; + logoWidth?: number; + logoHeight?: number; +}) => { + const isBtc = code === 'BTC'; + + return ( + + + ) : ( + + ) + } + backgroundColor={isBtc ? Colors.BrightOrange : Colors.DesaturatedTeal} + width={CircleWidth} + /> + + ); +}; diff --git a/src/screens/Home/components/buyBtc/Swap/component/SwapTransactionCard.tsx b/src/screens/Home/components/buyBtc/Swap/component/SwapTransactionCard.tsx index 0cc07b9234..ec600bec8c 100644 --- a/src/screens/Home/components/buyBtc/Swap/component/SwapTransactionCard.tsx +++ b/src/screens/Home/components/buyBtc/Swap/component/SwapTransactionCard.tsx @@ -15,7 +15,7 @@ import SwapConfirmingIcon from '../../../../../../assets/images/swap-confirmint. import SwapProcessingIcon from '../../../../../../assets/images/swap-processing.svg'; import SwapSuccessIcon from '../../../../../../assets/images/swap-success.svg'; import SwapOverDueIcon from '../../../../../../assets/images/swap-overDue.svg'; -import { CoinLogo } from '../Swaps'; +import { CoinLogo } from './CoinLogo'; import SwapPriceArrow from 'src/assets/images/swap-price-arrow.svg'; import SwapPriceArrowWhite from 'src/assets/images/swap-price-arrow-white.svg'; diff --git a/src/screens/USDT/RecieveUsdt.tsx b/src/screens/USDT/RecieveUsdt.tsx index 68cdbd2c1f..b7c0637aa0 100644 --- a/src/screens/USDT/RecieveUsdt.tsx +++ b/src/screens/USDT/RecieveUsdt.tsx @@ -1,6 +1,6 @@ import { Box, useColorMode } from '@gluestack-ui/themed-native-base'; import React, { useContext } from 'react'; -import { StyleSheet } from 'react-native'; +import { ScrollView, StyleSheet } from 'react-native'; import KeeperQRCode from 'src/components/KeeperQRCode'; import Text from 'src/components/KeeperText'; import ScreenWrapper from 'src/components/ScreenWrapper'; @@ -19,9 +19,22 @@ const RecieveUsdt = ({ route }) => { return ( - + + + + {usdtWalletText.sendingPausedTitle} + + + {usdtWalletText.receivePausedWarning} + + + { {usdtWalletText.sendOnlyUsdt} - + ); }; @@ -54,6 +67,20 @@ const RecieveUsdt = ({ route }) => { export default RecieveUsdt; const styles = StyleSheet.create({ + scrollContent: { + flexGrow: 1, + }, + warning: { + borderWidth: 1, + borderRadius: 10, + marginHorizontal: 16, + marginTop: hp(12), + paddingHorizontal: 16, + paddingVertical: hp(12), + }, + warningBody: { + marginTop: hp(6), + }, container: { alignItems: 'center', marginTop: hp(20), diff --git a/src/screens/USDT/UsdtDetails.tsx b/src/screens/USDT/UsdtDetails.tsx index 745964ce3e..c8e751b50e 100644 --- a/src/screens/USDT/UsdtDetails.tsx +++ b/src/screens/USDT/UsdtDetails.tsx @@ -13,10 +13,8 @@ import { getAvailableBalanceUSDTWallet } from 'src/services/wallets/factories/US import WalletDetailHeader from '../WalletDetails/components/WalletDetailHeader'; import DetailCards from '../WalletDetails/components/DetailCards'; import ThemedColor from 'src/components/ThemedColor/ThemedColor'; -import MoreCard from '../WalletDetails/components/MoreCard'; -import KeeperModal from 'src/components/KeeperModal'; -import SwapSvg from 'src/assets/images/swap.svg'; import ActivityIndicatorView from 'src/components/AppActivityIndicator/ActivityIndicatorView'; +import KeeperModal from 'src/components/KeeperModal'; function TransactionsAndUTXOs({ transactions, setPullRefresh, pullRefresh, wallet }) { const [initialLoading, setInitialLoading] = useState(false); @@ -39,14 +37,14 @@ const UsdtDetails = ({ route }) => { const { colorMode } = useColorMode(); const navigation = useNavigation(); const { translations } = useContext(LocalizationContext); - const { common } = translations; + const { common, usdtWalletText } = translations; const { getWalletCardGradient, getWalletTags } = useWalletAsset(); const [pullRefresh, setPullRefresh] = useState(false); const { usdtWalletId } = route.params || {}; const { getWalletById } = useUSDTWallets(); const usdtWallet = getWalletById(usdtWalletId); - const [showmore, setShowMore] = useState(false); const viewAll_color = ThemedColor({ name: 'viewAll_color' }); + const [showSendPaused, setShowSendPaused] = useState(false); return ( @@ -64,21 +62,26 @@ const UsdtDetails = ({ route }) => { - navigation.dispatch(CommonActions.navigate('sendUsdt', { usdtWallet })) - } + sendCallback={() => setShowSendPaused(true)} receiveCallback={() => navigation.dispatch(CommonActions.navigate('usdtReceive', { usdtWallet })) } - buyCallback={() => - navigation.dispatch(CommonActions.navigate('buyUstd', { usdtWallet })) - } wallet={usdtWallet} /> + + + {usdtWalletText.pausedTitle} + + + {usdtWalletText.pausedBody} + + {usdtWallet ? ( { )} setShowMore(false)} - title={common.moreOptions} - subTitleColor={`${colorMode}.modalSubtitleBlack`} - textColor={`${colorMode}.textGreen`} + visible={showSendPaused} + close={() => setShowSendPaused(false)} + title={usdtWalletText.sendingPausedTitle} + subTitle={usdtWalletText.sendingPausedBody} modalBackground={`${colorMode}.modalWhiteBackground`} - Content={() => { - return ( - - { - setShowMore(false); - }} - Icon={} - /> - - ); - }} + textColor={`${colorMode}.textGreen`} + subTitleColor={`${colorMode}.modalSubtitleBlack`} + buttonText={common.ok} + buttonCallback={() => setShowSendPaused(false)} /> ); @@ -168,7 +161,7 @@ const styles = StyleSheet.create({ paddingHorizontal: 18, }, walletContainer: { - paddingTop: wp(30), + paddingTop: hp(8), paddingBottom: 20, flex: 1, justifyContent: 'space-between', @@ -227,6 +220,21 @@ const styles = StyleSheet.create({ justifyContent: 'center', marginTop: hp(20), }, + pausedNotice: { + marginHorizontal: wp(22), + marginTop: hp(65), + paddingHorizontal: wp(16), + paddingVertical: hp(12), + borderWidth: 1, + borderRadius: 10, + }, + pausedTitle: { + fontSize: wp(14), + }, + pausedBody: { + fontSize: wp(12), + marginTop: hp(6), + }, detailCardsContainer: { zIndex: 1000, }, diff --git a/src/screens/USDT/UsdtTransactionDetail.tsx b/src/screens/USDT/UsdtTransactionDetail.tsx index 521ac6f099..3b1e0778b6 100644 --- a/src/screens/USDT/UsdtTransactionDetail.tsx +++ b/src/screens/USDT/UsdtTransactionDetail.tsx @@ -18,13 +18,15 @@ import Edit from 'src/assets/images/edit.svg'; import EditDark from 'src/assets/images/edit-white.svg'; import { current } from '@reduxjs/toolkit'; import StatusContent from './components/StatusContent'; -import { USDTTransaction } from 'src/services/wallets/operations/dollars/USDT'; +import { + isHistoricalUnverifiedUSDTRequest, + isUSDTStatusUnavailable, + USDTTransaction, +} from 'src/services/wallets/operations/dollars/USDT'; import { USDTWallet } from 'src/services/wallets/factories/USDTWalletFactory'; import Link from 'src/assets/images/link.svg'; import LinkDark from 'src/assets/images/link-white.svg'; import openLink from 'src/utils/OpenLink'; -import useToastMessage from 'src/hooks/useToastMessage'; -import ToastErrorIcon from 'src/assets/images/toast_error.svg'; export function EditNoteContent({ existingNote, noteRef }: { existingNote: string; noteRef }) { const updateNote = useCallback((text) => { @@ -52,6 +54,10 @@ const UsdtTransactionDetail = ({ route }) => { const transactionId = transaction.txId || transaction.traceId; const date = transaction.timestamp; const amount = parseFloat(transaction.amount); + // A trace without a chain transaction ID is a historical provider request. + // Its final result cannot be established after the provider was retired. + const legacyRequest = isHistoricalUnverifiedUSDTRequest(transaction); + const unavailableStatus = isUSDTStatusUnavailable(transaction); const status = transaction.status; let transactionType: string; if (transaction.to === wallet.accountStatus.gasFreeAddress) { @@ -66,7 +72,6 @@ const UsdtTransactionDetail = ({ route }) => { const [visible, setVisible] = useState(false); const [updatingLabel, setUpdatingLabel] = useState(false); const close = () => setVisible(false); - const { showToast } = useToastMessage(); function InfoCard({ title, @@ -120,12 +125,14 @@ const UsdtTransactionDetail = ({ route }) => { - {transactionType === 'Received' ? ( + {legacyRequest ? null : transactionType === 'Received' ? ( colorMode === 'dark' ? ( ) : ( @@ -146,6 +153,11 @@ const UsdtTransactionDetail = ({ route }) => { + {legacyRequest && ( + + {usdtWalletText.requestedAmount} + + )} {amount} USDT @@ -182,14 +194,10 @@ const UsdtTransactionDetail = ({ route }) => { */} { if (transaction.txId) { redirectToBlockExplorer(transaction.txId); - } else if (transaction.traceId) { - showToast( - 'Transaction is being processed and does not have a Transaction ID yet.', - - ); } }} > @@ -213,8 +221,15 @@ const UsdtTransactionDetail = ({ route }) => { title={usdtWalletText.status} showIcon={false} letterSpacing={2.4} - Content={() => } + Content={() => } /> + {legacyRequest && ( + + )} {transactionType === 'Sent' && ( { title={ transactionType === 'Received' ? usdtWalletText.recievedAmount + : legacyRequest + ? usdtWalletText.requestedAmount : usdtWalletText.sendingAmount } describtion={`${amount} USDT`} showIcon={false} letterSpacing={2.4} /> - {transaction.transferFee || transaction.fee ? ( + {!legacyRequest && (transaction.transferFee || transaction.fee) ? ( { letterSpacing={2.4} /> ) : null} - {transaction.activateFee ? ( + {!legacyRequest && transaction.activateFee ? ( { +const StatusContent = ({ status, unavailable = false }) => { const { colorMode } = useColorMode(); - const containerbackgroundColor = - status === GasFreeTransferStatus.SUCCEED - ? Colors.PaleTropicalTeal - : status === GasFreeTransferStatus.CONFIRMING - ? Colors.lightOrange - : Colors.lightindigoblue; + const { translations } = useContext(LocalizationContext); + // A legacy SUCCEED value is not proof of a confirmed chain transaction. + const statusUnavailable = + unavailable || + status === GasFreeTransferStatus.SUCCEED || + status === GasFreeTransferStatus.UNVERIFIED; + const chainConfirmed = status === GasFreeTransferStatus.CHAIN_CONFIRMED; + const containerbackgroundColor = statusUnavailable + ? Colors.lightindigoblue + : chainConfirmed + ? Colors.PaleTropicalTeal + : status === GasFreeTransferStatus.CONFIRMING + ? Colors.lightOrange + : Colors.lightindigoblue; - const textColor = - status === GasFreeTransferStatus.SUCCEED - ? Colors.TropicalTeal - : status === GasFreeTransferStatus.CONFIRMING - ? Colors.darkOrange - : Colors.indigoblue; + const textColor = statusUnavailable + ? Colors.indigoblue + : chainConfirmed + ? Colors.TropicalTeal + : status === GasFreeTransferStatus.CONFIRMING + ? Colors.darkOrange + : Colors.indigoblue; return ( { style={styles.container} > - {status === GasFreeTransferStatus.SUCCEED ? 'SUCCESS' : status} + {statusUnavailable + ? translations.usdtWalletText.statusUnavailable + : chainConfirmed + ? 'SUCCESS' + : status} ); @@ -40,7 +54,8 @@ const styles = StyleSheet.create({ container: { borderWidth: 1, borderRadius: 30, - width: wp(80), + minWidth: wp(80), + paddingHorizontal: wp(8), height: hp(20), justifyContent: 'center', alignItems: 'center', diff --git a/src/services/rest/SwapClient.ts b/src/services/rest/SwapClient.ts deleted file mode 100644 index 405f6e4605..0000000000 --- a/src/services/rest/SwapClient.ts +++ /dev/null @@ -1,30 +0,0 @@ -import axios from 'axios'; -import config from 'src/utils/service-utilities/config'; - -export const swapApi = axios.create({ - baseURL: config.LETS_EXCHANGE_BASE_URL, -}); - -swapApi.interceptors.request.use( - (req) => { - req.headers.Authorization = `Bearer ${config.LETS_EXCHANGE_API_KEY}`; - if (req.method === 'post') { - req.data = { - ...req.data, - affiliate_id: config.LETS_EXCHANGE_AFFILIATE_ID, - }; - } - - return req; - }, - (error) => { - return Promise.reject(error); - } -); - -export const swapEndpoints = { - coins: 'v1/coins', - coinsInfo: 'v1/info/bulk', - quote: '/v1/info', - tnx: 'v1/transaction', -}; diff --git a/src/services/wallets/factories/USDTWalletFactory.ts b/src/services/wallets/factories/USDTWalletFactory.ts index 2b2744abf8..ffbad27df4 100644 --- a/src/services/wallets/factories/USDTWalletFactory.ts +++ b/src/services/wallets/factories/USDTWalletFactory.ts @@ -5,9 +5,9 @@ import { DEFAULT_TRON_DERIVATION_PATH, } from '../operations/dollars/Tron'; import USDT, { USDTAccountStatus, USDTTransaction } from '../operations/dollars/USDT'; +import { GasFreeTransferStatus } from '../operations/dollars/GasFree'; import BIP85 from '../operations/BIP85'; import { BIP85Config } from '../interfaces'; -import { GasFreeTransferStatus } from '../operations/dollars/GasFree'; import config from 'src/utils/service-utilities/config'; export const USDTWalletSupportedNetwork = config.isDevMode() @@ -187,22 +187,22 @@ export const checkUSDTWalletExists = (address: string, existingWallets: USDTWall }; /** - * Update USDT wallet specs with latest account status + * Preserve stored account information. The retired provider is no longer + * queried, and the saved GasFree address is needed for chain reads. */ export const updateUSDTWalletAccountStatus = async ( wallet: USDTWallet ): Promise => { - try { - return USDT.getAccountStatus(wallet.specs.address, wallet.networkType); - } catch (error) { - return wallet.accountStatus; - } + return wallet.accountStatus; }; /** * Syncs USDT wallet w/ latest balance */ export const syncUSDTWalletBalance = async (wallet: USDTWallet) => { + if (!wallet.accountStatus?.gasFreeAddress) { + throw new Error('Stored USDT address is unavailable'); + } const balance = await USDT.getUSDTBalance( wallet.accountStatus.gasFreeAddress, wallet.networkType @@ -215,7 +215,9 @@ export const syncUSDTWalletBalance = async (wallet: USDTWallet) => { * Evaluates USDT wallet's available balance */ export const getAvailableBalanceUSDTWallet = (wallet: USDTWallet): number => { - return wallet.specs.balance - wallet.accountStatus.frozen; // frozen amount is currently under process w/ the GasFree service provider(in-process permit transfers) + // Provider-reported frozen funds cannot be refreshed after retirement. + // The on-chain balance is the amount shown for the existing wallet. + return wallet.specs.balance; }; /** @@ -224,51 +226,25 @@ export const getAvailableBalanceUSDTWallet = (wallet: USDTWallet): number => { export const syncUSDTWalletTransactions = async (wallet: USDTWallet) => { const existingTransactions = wallet.specs.transactions || []; - // Step 1: Update existing transactions that have traceId but no txId - const updatedExistingTransactions = await Promise.all( - existingTransactions.map(async (existingTx) => { - // If transaction has traceId but no txId, try to fetch the txId - if (existingTx.traceId && !existingTx.txId) { - try { - const transferStatus = await USDT.getTransferStatus( - existingTx.traceId, - wallet.networkType - ); - // Update transaction with new information if available - if (transferStatus.transactionHash) { - const blockNumber = transferStatus.blockInfo?.blockNumber || existingTx.blockNumber; - const status = blockNumber - ? GasFreeTransferStatus.SUCCEED - : transferStatus.status || existingTx.status; - return { - ...existingTx, - txId: transferStatus.transactionHash || existingTx.txId, - status, - blockNumber: blockNumber, - // Update timestamp if we got block timestamp - timestamp: transferStatus.blockInfo?.blockTimestamp - ? transferStatus.blockInfo.blockTimestamp - : existingTx.timestamp, - }; - } - } catch (error) { - // If fetch fails, keep the original transaction - console.warn(`Failed to update transaction with traceId ${existingTx.traceId}:`, error); - } - } + if (!wallet.accountStatus?.gasFreeAddress) { + throw new Error('Stored USDT address is unavailable'); + } - // Return original transaction if no update needed or failed - return existingTx; - }) + // Older builds could mark a provider-reported transfer successful before it + // appeared in confirmed chain history. Keep the record but withdraw that claim. + const updatedExistingTransactions = existingTransactions.map((transaction) => + transaction.status === GasFreeTransferStatus.SUCCEED + ? { ...transaction, status: GasFreeTransferStatus.UNVERIFIED } + : transaction ); - // Step 2: Fetch new transactions from USDT service + // Fetch new transactions directly from TRON. const { transactions: newTransactions } = await USDT.getUSDTTransactions( wallet.accountStatus.gasFreeAddress, wallet.networkType ); - // Step 3: Merge transactions using updated existing transactions + // Merge chain transactions with the stored history. const mergedTransactions = [...updatedExistingTransactions]; // Process each new transaction @@ -292,9 +268,9 @@ export const syncUSDTWalletTransactions = async (wallet: USDTWallet) => { if (existingTx.amount === newTx.amount) { // there are two transactions for every gas-free transfer, one for the actual transfer and one for paying the fee(both of them have the same txid, skipping the fee transfer) + // Reconcile cached status with the matching confirmed chain entry. const shouldUpdate = - // Update if new transaction has blockNumber but existing doesn't (confirmed) - newTx.blockNumber && !existingTx.blockNumber; + existingTx.status !== newTx.status || existingTx.blockNumber !== newTx.blockNumber; if (shouldUpdate) { mergedTransactions[existingIndex] = { @@ -304,9 +280,7 @@ export const syncUSDTWalletTransactions = async (wallet: USDTWallet) => { to: newTx.to, timestamp: newTx.timestamp, blockNumber: newTx.blockNumber, - status: newTx.blockNumber - ? GasFreeTransferStatus.SUCCEED - : GasFreeTransferStatus.CONFIRMING, + status: newTx.status, }; } } diff --git a/src/services/wallets/operations/dollars/GasFree.ts b/src/services/wallets/operations/dollars/GasFree.ts index ad41f62fab..7c73a63eae 100644 --- a/src/services/wallets/operations/dollars/GasFree.ts +++ b/src/services/wallets/operations/dollars/GasFree.ts @@ -1,544 +1,11 @@ -import { AxiosResponse } from 'axios'; -import { NetworkType } from 'src/services/wallets/enums'; -import RestClient from '../../../rest/RestClient'; -import * as crypto from 'crypto'; -import config from '../../../../utils/service-utilities/config'; -import { createTronWeb } from './Tron'; -import idx from 'idx'; - -// GasFree API endpoints -const GASFREE_ENDPOINTS = { - [NetworkType.MAINNET]: 'https://open.gasfree.io/tron/', - [NetworkType.TESTNET]: 'https://open-test.gasfree.io/nile/', -}; - -// Network parameters for signature -const NETWORK_PARAMS = { - [NetworkType.MAINNET]: { - chainId: 728126428, - verifyingContract: 'TFFAMQLZybALaLb4uxHA9RBE7pxhUAjF3U', - }, - [NetworkType.TESTNET]: { - chainId: 3448148188, - verifyingContract: 'THQGuFzL87ZqhxkgqYEryRAd7gqFqL5rdc', - }, -}; - -// GasFree Interfaces -export interface GasFreeToken { - tokenAddress: string; - createdAt: string; - updatedAt: string; - activateFee: number; - transferFee: number; - supported: boolean; - symbol: string; - decimal: number; -} - -export interface GasFreeProvider { - address: string; - name: string; - icon: string; - website: string; - config: { - maxPendingTransfer: number; - minDeadlineDuration: number; - maxDeadlineDuration: number; - defaultDeadlineDuration: number; - }; -} - -export interface GasFreeAccountInfo { - accountAddress: string; - gasFreeAddress: string; - active: boolean; - nonce: number; - allowSubmit: boolean; - assets: Array<{ - tokenAddress: string; - tokenSymbol: string; - activateFee: number; - transferFee: number; - decimal: number; - frozen: number; - }>; -} - -export interface GasFreeTransferRequest { - token: string; - serviceProvider: string; - user: string; - receiver: string; - value: string; - maxFee: string; - deadline: string; - version: number; - nonce: number; - sig: string; -} - +/** Historical transfer states remain in stored USDT transactions. */ export enum GasFreeTransferStatus { WAITING = 'WAITING', INPROGRESS = 'INPROGRESS', CONFIRMING = 'CONFIRMING', + // SUCCEED was also written for provider-reported results in older builds. SUCCEED = 'SUCCEED', + UNVERIFIED = 'UNVERIFIED', + CHAIN_CONFIRMED = 'CONFIRMED', FAILED = 'FAILED', } - -export interface GasFreeTransferResponse { - id: string; - createdAt: string; - updatedAt: string; - accountAddress: string; - gasFreeAddress: string; - providerAddress: string; - targetAddress: string; - tokenAddress: string; - amount: string; - maxFee: string; - signature: string; - version: number; - nonce: number; - expiredAt: string; - state: GasFreeTransferStatus; - estimatedActivateFee: number; - estimatedTransferFee: number; -} - -export interface GasFreeTransferDetails extends GasFreeTransferResponse { - estimatedTotalFee: number; - estimatedTotalCost: number; - txnHash?: string; - txnBlockNum?: number; - txnBlockTimestamp?: number; - txnState?: 'INIT' | 'NOT_ON_CHAIN' | 'ON_CHAIN' | 'SOLIDITY' | 'ON_CHAIN_FAILED'; - txnActivateFee?: number; - txnTransferFee?: number; - txnTotalFee?: number; - txnAmount?: string; - txnTotalCost?: number; -} - -export interface GasFreeSignaturePayload { - token: string; - serviceProvider: string; - user: string; - receiver: string; - value: string; - maxFee: string; - deadline: string; - version: number; - nonce: number; -} - -export interface GasFreeAPIResponse { - code: number; - reason: string | null; - message: string | null; - data: T; -} - -export interface GasFreeAPICredentials { - apiKey: string; - apiSecret: string; -} - -// TIP-712 Signing Types for GasFree -export interface TIP712Domain { - name: string; - version: string; - chainId: number; - verifyingContract: string; -} - -export interface TIP712TypeProperty { - name: string; - type: string; -} - -export interface TIP712MessageTypes { - PermitTransfer: TIP712TypeProperty[]; -} - -export interface Permit712MessageDomain extends TIP712Domain { - name: 'GasFreeController'; - version: 'V1.0.0'; - chainId: number; // Network specific chain ID in decimal - verifyingContract: string; // GasFreeController contract address -} - -export interface Permit712MessageTypes extends TIP712MessageTypes { - PermitTransfer: [ - { name: 'token'; type: 'address' }, - { name: 'serviceProvider'; type: 'address' }, - { name: 'user'; type: 'address' }, - { name: 'receiver'; type: 'address' }, - { name: 'value'; type: 'uint256' }, - { name: 'maxFee'; type: 'uint256' }, - { name: 'deadline'; type: 'uint256' }, - { name: 'version'; type: 'uint256' }, - { name: 'nonce'; type: 'uint256' } - ]; -} - -export default class GasFree { - private static credentials: GasFreeAPICredentials = { - // Mainnet ONLY – Testnet access is not available to end users - apiKey: config.GASFREE_API_KEY, - apiSecret: config.GASFREE_API_SECRET, - }; - - // TIP-712 Constants - private static readonly TIP712_MESSAGE_TYPES: Permit712MessageTypes = { - PermitTransfer: [ - { name: 'token', type: 'address' }, - { name: 'serviceProvider', type: 'address' }, - { name: 'user', type: 'address' }, - { name: 'receiver', type: 'address' }, - { name: 'value', type: 'uint256' }, - { name: 'maxFee', type: 'uint256' }, - { name: 'deadline', type: 'uint256' }, - { name: 'version', type: 'uint256' }, - { name: 'nonce', type: 'uint256' }, - ], - }; - - // Fixed values as per GasFree documentation - private static readonly TIP712_DOMAIN_NAME = 'GasFreeController'; - private static readonly TIP712_DOMAIN_VERSION = 'V1.0.0'; - private static readonly SIGNATURE_VERSION = 1; - - /** - * Get the appropriate endpoint URL based on network type - */ - private static getEndpointURL(networkType?: NetworkType): string { - const network = networkType || NetworkType.MAINNET; - return GASFREE_ENDPOINTS[network]; - } - - /** - * Get network parameters for signing - */ - private static getNetworkParams(networkType?: NetworkType) { - const network = networkType || NetworkType.MAINNET; - return NETWORK_PARAMS[network]; - } - - /** - * Extract network path from baseURL - * e.g., 'https://open-test.gasfree.io/nile/' -> '/nile/' - * e.g., 'https://open.gasfree.io/tron/' -> '/tron/' - */ - private static extractNetworkPath(baseURL: string): string { - try { - // Remove protocol and domain: 'https://open-test.gasfree.io/nile/' -> '/nile/' - const pathStartIndex = baseURL.indexOf('/', baseURL.indexOf('://') + 3); - if (pathStartIndex === -1) return ''; - - let pathname = baseURL.substring(pathStartIndex); - return pathname; - } catch (error) { - throw new Error('Error extracting network path: ' + error?.message); - } - } - - /** - * Generate authentication headers for API requests - */ - private static generateAuthHeaders(method: string, path: string): Record { - if (!GasFree.credentials) { - throw new Error('GasFree API credentials not set. Call setCredentials() first.'); - } - - const timestamp = Math.floor(Date.now() / 1000); - const message = `${method}${path}${timestamp}`; - const signature = crypto - .createHmac('sha256', GasFree.credentials.apiSecret) - .update(message) - .digest('base64'); - - return { - Timestamp: timestamp.toString(), - Authorization: `ApiKey ${GasFree.credentials.apiKey}:${signature}`, - }; - } - - /** - * Make an authenticated API request - */ - private static async makeAuthenticatedRequest( - method: 'GET' | 'POST', - path: string, - body?: any, - networkType?: NetworkType - ): Promise> { - try { - const baseURL = GasFree.getEndpointURL(networkType); - const url = `${baseURL}${path}`; - const networkPrefix = GasFree.extractNetworkPath(baseURL); - const authHeaders = GasFree.generateAuthHeaders(method, networkPrefix + path); - - let response: AxiosResponse; - - if (method === 'GET') { - response = (await RestClient.get(url, { - ...authHeaders, - })) as AxiosResponse; - } else { - response = (await RestClient.post(url, body, { - ...authHeaders, - })) as AxiosResponse; - } - - return response.data; - } catch (err) { - const errorMessage = idx(err, (_) => _.response.data); - throw new Error(`GasFree API request failed: ${errorMessage || err.message || err}`); - } - } - - /** - * Get all supported tokens - */ - public static async getSupportedTokens(networkType?: NetworkType): Promise { - try { - const response = await GasFree.makeAuthenticatedRequest<{ tokens: GasFreeToken[] }>( - 'GET', - 'api/v1/config/token/all', - undefined, - networkType - ); - - if (response.code !== 200) { - throw new Error(response.message || 'Failed to fetch supported tokens'); - } - - return response.data.tokens; - } catch (err) { - throw new Error(`Failed to fetch supported tokens: ${err.message || err}`); - } - } - - /** - * Get all available service providers - */ - public static async getServiceProviders(networkType?: NetworkType): Promise { - try { - const response = await GasFree.makeAuthenticatedRequest<{ providers: GasFreeProvider[] }>( - 'GET', - 'api/v1/config/provider/all', - undefined, - networkType - ); - - if (response.code !== 200) { - throw new Error(response.message || 'Failed to fetch service providers'); - } - - return response.data.providers; - } catch (err) { - throw new Error(`Failed to fetch service providers: ${err.message || err}`); - } - } - - /** - * Get GasFree account information for a given address - */ - public static async getAccountInfo( - accountAddress: string, - networkType?: NetworkType - ): Promise { - try { - const response = await GasFree.makeAuthenticatedRequest( - 'GET', - `api/v1/address/${accountAddress}`, - undefined, - networkType - ); - - if (response.code !== 200) { - throw new Error(response.message || 'Failed to fetch account information'); - } - - return response.data; - } catch (err) { - throw new Error(`Failed to fetch account info: ${err.message || err}`); - } - } - - /** - * Generate signature payload for TIP-712 compatible signing - */ - public static generateSignaturePayload( - transferRequest: Omit, - networkType?: NetworkType - ): { - domain: Permit712MessageDomain; - types: Permit712MessageTypes; - message: GasFreeSignaturePayload; - } { - const params = GasFree.getNetworkParams(networkType); - - const domain: Permit712MessageDomain = { - name: GasFree.TIP712_DOMAIN_NAME, - version: GasFree.TIP712_DOMAIN_VERSION, - chainId: params.chainId, - verifyingContract: params.verifyingContract, - }; - - const types: Permit712MessageTypes = GasFree.TIP712_MESSAGE_TYPES; - - const message: GasFreeSignaturePayload = { - ...transferRequest, - version: GasFree.SIGNATURE_VERSION, - }; - - return { domain, types, message }; - } - - /** - * Sign GasFree transfer payload using TIP-712 standard - * @param privateKey - Private key in hex format for signing - * @param signaturePayload - Signature payload containing domain, types, and message - * @param networkType - Network type (mainnet/testnet) - * @returns Promise - Signature without 0x prefix - */ - public static async signTransferPayload( - privateKey: string, - signaturePayload: { - domain: Permit712MessageDomain; - types: Permit712MessageTypes; - message: GasFreeSignaturePayload; - }, - networkType: NetworkType - ): Promise { - try { - const tronWeb = createTronWeb(networkType); - tronWeb.setPrivateKey(privateKey); - - // Sign using TronWeb's TIP-712 implementation - const { domain, types, message } = signaturePayload; - const signature = await tronWeb.trx._signTypedData(domain, types, message); - - // Remove 0x prefix if present (as per GasFree documentation) - const cleanSignature = signature.startsWith('0x') ? signature.slice(2) : signature; - return cleanSignature; - } catch (error) { - throw new Error(`Failed to sign transfer payload: ${error.message}`); - } - } - - /** - * Submit a GasFree transfer authorization - */ - public static async submitTransfer( - transferRequest: GasFreeTransferRequest, - networkType?: NetworkType - ): Promise { - try { - const response = await GasFree.makeAuthenticatedRequest( - 'POST', - 'api/v1/gasfree/submit', - transferRequest, - networkType - ); - - if (response.code !== 200) { - throw new Error(response.message || 'Failed to submit transfer'); - } - - return response.data; - } catch (err) { - throw new Error(`Failed to submit transfer: ${err.message || err}`); - } - } - - /** - * Get transfer status by trace ID - */ - public static async getTransferStatus( - traceId: string, - networkType?: NetworkType - ): Promise { - try { - const response = await GasFree.makeAuthenticatedRequest( - 'GET', - `api/v1/gasfree/${traceId}`, - undefined, - networkType - ); - - if (response.code !== 200) { - throw new Error(response.message || 'Failed to fetch transfer status'); - } - - return response.data; - } catch (err) { - throw new Error(`Failed to fetch transfer status: ${err.message || err}`); - } - } - - /** - * Calculate deadline timestamp - */ - public static calculateDeadline(durationInSeconds: number = 180): string { - const deadline = Math.floor(Date.now() / 1000) + durationInSeconds; - return deadline.toString(); - } - - /** - * Format token amount to smallest unit (e.g., USDT to 6 decimal places) - */ - public static formatTokenAmount(amount: number, decimals: number): string { - return Math.ceil(amount * Math.pow(10, decimals)).toString(); - } - - /** - * Parse token amount from smallest unit to readable format - */ - public static parseTokenAmount(amount: string, decimals: number): number { - return parseInt(amount) / Math.pow(10, decimals); - } - - /** - * Monitor transfer until completion or failure - */ - public static async monitorTransfer( - traceId: string, - onStatusUpdate?: (status: GasFreeTransferDetails) => void, - networkType?: NetworkType, - maxAttempts: number = 60, - intervalMs: number = 5000 - ): Promise { - let attempts = 0; - - const poll = async (): Promise => { - try { - const status = await GasFree.getTransferStatus(traceId, networkType); - - if (onStatusUpdate) { - onStatusUpdate(status); - } - - // Check if final state - if (status.state === 'SUCCEED' || status.state === 'FAILED') { - return status; - } - - attempts++; - if (attempts >= maxAttempts) { - throw new Error('Transfer monitoring timeout'); - } - - // Wait and poll again - await new Promise((resolve) => setTimeout(resolve, intervalMs)); - return poll(); - } catch (err) { - throw err; - } - }; - - return poll(); - } -} diff --git a/src/services/wallets/operations/dollars/Tron.ts b/src/services/wallets/operations/dollars/Tron.ts index 08ed3a5f6e..c776e48ccd 100644 --- a/src/services/wallets/operations/dollars/Tron.ts +++ b/src/services/wallets/operations/dollars/Tron.ts @@ -221,6 +221,7 @@ export async function getTrc20Transactions( const params = new URLSearchParams({ limit: limit.toString(), contract_address: tokenContract, + only_confirmed: 'true', }); if (fingerprint) { @@ -262,7 +263,9 @@ export async function getTrc20Transactions( value: rawValue, formattedValue, contractAddress: tx.token_info?.address || tokenContract, - confirmed: tx.confirmed || false, + // The TRC20 response row need not carry a confirmation flag. The + // request filter establishes it unless a row explicitly contradicts it. + confirmed: tx.confirmed !== false, tokenInfo: tx.token_info ? { symbol: tx.token_info.symbol, diff --git a/src/services/wallets/operations/dollars/USDT.ts b/src/services/wallets/operations/dollars/USDT.ts index 85b5d4edd0..24c4741be8 100644 --- a/src/services/wallets/operations/dollars/USDT.ts +++ b/src/services/wallets/operations/dollars/USDT.ts @@ -1,28 +1,21 @@ -import GasFree, { - GasFreeProvider, - GasFreeTransferRequest, - GasFreeSignaturePayload, - GasFreeTransferStatus, - Permit712MessageTypes, - Permit712MessageDomain, -} from './GasFree'; +import { GasFreeTransferStatus } from './GasFree'; import { NetworkType } from 'src/services/wallets/enums'; import { isValidTronAddress, getTrc20Balance, getTrc20Transactions } from './Tron'; import { USDTWallet } from '../../factories/USDTWalletFactory'; -// USDT Token addresses +// Keep these addresses for existing wallets' balance and history reads. const USDT_ADDRESSES = { - [NetworkType.MAINNET]: 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', // USDT TRC-20 on mainnet - [NetworkType.TESTNET]: 'TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf', // USDT TRC-20 on Nile testnet + [NetworkType.MAINNET]: 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', + [NetworkType.TESTNET]: 'TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf', }; -// USDT GasFree Fee addresses export const USDT_GASFREE_FEE_ADDRESSES = { - [NetworkType.MAINNET]: 'TLntW9Z59LYY5KEi9cmwk3PKjQga828ird', // GasFree fee address for USDT on mainnet - [NetworkType.TESTNET]: 'TCETRh3aED4kdkaYQY7CcxeTJtrQvwBpNT', // GasFree fee address for USDT on testnet + [NetworkType.MAINNET]: 'TLntW9Z59LYY5KEi9cmwk3PKjQga828ird', + [NetworkType.TESTNET]: 'TCETRh3aED4kdkaYQY7CcxeTJtrQvwBpNT', }; -export const DEFAULT_DEADLINE_SECONDS = 300; // Default deadline for permit transactions (5 minutes) +export const DEFAULT_DEADLINE_SECONDS = 300; +export const USDT_ACTIVITY_PAUSED = 'USDT activity is paused'; export interface USDTTransferOptions { source: USDTWallet; @@ -42,27 +35,25 @@ export interface USDTTransferResult { transaction?: USDTTransaction; } +// Stored account fields are retained for Realm and encrypted backup compatibility. export interface USDTAccountStatus { address: string; gasFreeAddress: string; isActive: boolean; - frozen: number; // Frozen amount in pending transfers + frozen: number; canTransfer: boolean; nextNonce: number; - fees: { - transferFee: number; - activateFee: number; - }; + fees: { transferFee: number; activateFee: number }; } export interface USDTTransaction { - txId?: string; // available post processing - traceId?: string; // available via GasFree API + txId?: string; + traceId?: string; from: string; to: string; amount: string; - transferFee?: number; // Estimated transfer fee - activateFee?: number; // Estimated activation fee + transferFee?: number; + activateFee?: number; fee?: string; status: GasFreeTransferStatus; timestamp: number; @@ -70,393 +61,113 @@ export interface USDTTransaction { isGasFree: boolean; } +export const isHistoricalUnverifiedUSDTRequest = ( + transaction: Pick +): boolean => Boolean(transaction.traceId && !transaction.txId); + +export const isUSDTStatusUnavailable = ( + transaction: Pick +): boolean => + isHistoricalUnverifiedUSDTRequest(transaction) || + transaction.status === GasFreeTransferStatus.SUCCEED || + transaction.status === GasFreeTransferStatus.UNVERIFIED; + export default class USDT { - /** - * Get USDT token address for the specified network - */ private static getUSDTAddress(networkType?: NetworkType): string { - const network = networkType || NetworkType.MAINNET; - return USDT_ADDRESSES[network]; + return USDT_ADDRESSES[networkType || NetworkType.MAINNET]; } - /** - * Get USDT GasFree fee address for the specified network - */ public static getUSDTGasFreeFeeAddress(networkType?: NetworkType): string { - const network = networkType || NetworkType.MAINNET; - return USDT_GASFREE_FEE_ADDRESSES[network]; + return USDT_GASFREE_FEE_ADDRESSES[networkType || NetworkType.MAINNET]; } - /** - * Check if GasFree supports USDT transfers on the specified network - */ - public static async isGasFreeSupported(networkType?: NetworkType): Promise { - try { - const tokens = await GasFree.getSupportedTokens(networkType); - const usdtAddress = USDT.getUSDTAddress(networkType); - - return tokens.some( - (token) => token.tokenAddress.toLowerCase() === usdtAddress.toLowerCase() && token.supported - ); - } catch (err) { - throw new Error('Failed to check GasFree support for USDT on the specified network'); - } + // Retired provider operations fail closed, including calls from stale routes. + public static async isGasFreeSupported(_networkType?: NetworkType): Promise { + return false; } - /** - * Get available service providers for USDT transfers - */ - public static async getServiceProviders(networkType?: NetworkType): Promise { - try { - return await GasFree.getServiceProviders(networkType); - } catch (err) { - throw new Error('Failed to fetch service providers'); - } + public static async getServiceProviders(_networkType?: NetworkType): Promise { + return []; } - /** - * Get USDT account status and balance information - */ public static async getAccountStatus( - address: string, - networkType?: NetworkType + _address: string, + _networkType?: NetworkType ): Promise { - try { - const accountInfo = await GasFree.getAccountInfo(address, networkType); - const usdtAddress = USDT.getUSDTAddress(networkType); - - // Find USDT asset in account - const usdtAsset = accountInfo.assets.find( - (asset) => asset.tokenAddress.toLowerCase() === usdtAddress.toLowerCase() - ); - - if (!usdtAsset) throw new Error('USDT asset not found in account'); - const frozen = GasFree.parseTokenAmount(usdtAsset.frozen.toString(), usdtAsset.decimal); - - return { - address: accountInfo.accountAddress, - gasFreeAddress: accountInfo.gasFreeAddress, - isActive: accountInfo.active, - frozen, - canTransfer: accountInfo.allowSubmit, - nextNonce: accountInfo.nonce, - fees: { - transferFee: GasFree.parseTokenAmount( - usdtAsset.transferFee.toString(), - usdtAsset.decimal - ), - activateFee: GasFree.parseTokenAmount( - usdtAsset.activateFee.toString(), - usdtAsset.decimal - ), - }, - }; - } catch (err) { - throw err; - } + throw new Error(USDT_ACTIVITY_PAUSED); } - /** - * Prepare USDT transfer parameters and validate - */ - public static async prepareTransfer(options: USDTTransferOptions): Promise<{ + public static async prepareTransfer(_options: USDTTransferOptions): Promise<{ isValid: boolean; error?: string; - signaturePayload?: { - domain: Permit712MessageDomain; - types: Permit712MessageTypes; - message: GasFreeSignaturePayload; - }; - fees?: { - transferFee: number; - activateFee: number; - totalFee: number; - }; + signaturePayload?: unknown; + fees?: { transferFee: number; activateFee: number; totalFee: number }; }> { - try { - const usdtAddress = USDT.getUSDTAddress(options.networkType); - - // Get service providers if not specified - let serviceProviderAddress = options.serviceProviderAddress; - if (!serviceProviderAddress) { - const providers = await GasFree.getServiceProviders(options.networkType); - if (providers.length === 0) { - return { isValid: false, error: 'No service providers available' }; - } - serviceProviderAddress = providers[0].address; - } - - // Calculate fees - const { source } = options; - const fees = USDT.evaluateTransferFee(source.accountStatus); - const maxFee = GasFree.formatTokenAmount(options.maxFeeInUSDT || fees.totalFee, 6); - - // Format amount to smallest unit - const formattedAmount = GasFree.formatTokenAmount(options.amount, 6); - - // Check if account allows submission - if (!source.accountStatus.canTransfer) { - return { - isValid: false, - error: 'Account is not allowed to submit transfers at this time', - }; - } - - // Generate signature payload - const deadline = GasFree.calculateDeadline( - options.deadlineInSeconds || DEFAULT_DEADLINE_SECONDS - ); // Default to 5 minutes - - const transferData = { - token: usdtAddress, - serviceProvider: serviceProviderAddress, - user: options.source.specs.address, - receiver: options.toAddress, - value: formattedAmount, - maxFee, - deadline, - nonce: source.accountStatus.nextNonce, - }; - - const signaturePayload = GasFree.generateSignaturePayload(transferData, options.networkType); - return { - isValid: true, - signaturePayload, - fees: { - transferFee: GasFree.parseTokenAmount(fees.transferFee.toString(), 6), - activateFee: GasFree.parseTokenAmount(fees.activateFee.toString(), 6), - totalFee: GasFree.parseTokenAmount(fees.totalFee.toString(), 6), - }, - }; - } catch (err) { - return { isValid: false, error: err.message || 'Failed to prepare transfer' }; - } + return { isValid: false, error: USDT_ACTIVITY_PAUSED }; } - /** - * Submit USDT transfer with signature - */ public static async submitTransfer( - source: USDTWallet, - signaturePayload: { - domain: Permit712MessageDomain; - types: Permit712MessageTypes; - message: GasFreeSignaturePayload; - } + _source: USDTWallet, + _signaturePayload: unknown ): Promise { - try { - // Create and Sign transfer request - const transferRequest: GasFreeTransferRequest = { - ...signaturePayload.message, - sig: await GasFree.signTransferPayload( - source.specs.privateKey, - signaturePayload, - source.networkType - ), - }; - - // Submit transfer - const response = await GasFree.submitTransfer(transferRequest, source.networkType); - const transferFee = GasFree.parseTokenAmount(response.estimatedTransferFee.toString(), 6); - const activateFee = GasFree.parseTokenAmount(response.estimatedActivateFee.toString(), 6); - const fee = transferFee + activateFee; - const amount = GasFree.parseTokenAmount(response.amount.toString(), 6); - const transaction: USDTTransaction = { - traceId: response.id, - from: transferRequest.user, - to: transferRequest.receiver, - amount: amount.toString(), - transferFee: transferFee, - activateFee: activateFee, - fee: fee.toString(), - status: response.state, - timestamp: Date.now(), - isGasFree: true, - }; - - return { - success: true, - traceId: response.id, - transaction, - }; - } catch (err) { - return { - success: false, - error: err || 'Failed to submit transfer', - }; - } + return { success: false, error: USDT_ACTIVITY_PAUSED }; } - /** - * Track USDT transfer status - */ public static async getTransferStatus( - traceId: string, - networkType?: NetworkType - ): Promise<{ - status: GasFreeTransferStatus; - transactionHash?: string; - amount?: number; - fees?: { - actualTransferFee?: number; - actualActivateFee?: number; - actualTotalFee?: number; - }; - blockInfo?: { - blockNumber?: number; - blockTimestamp?: number; - }; - error?: string; - }> { - try { - const details = await GasFree.getTransferStatus(traceId, networkType); - - return { - status: details.state, - transactionHash: details.txnHash, - amount: details.txnAmount ? GasFree.parseTokenAmount(details.txnAmount, 6) : undefined, - fees: { - actualTransferFee: details.txnTransferFee - ? GasFree.parseTokenAmount(details.txnTransferFee.toString(), 6) - : undefined, - actualActivateFee: details.txnActivateFee - ? GasFree.parseTokenAmount(details.txnActivateFee.toString(), 6) - : undefined, - actualTotalFee: details.txnTotalFee - ? GasFree.parseTokenAmount(details.txnTotalFee.toString(), 6) - : undefined, - }, - blockInfo: { - blockNumber: details.txnBlockNum, - blockTimestamp: details.txnBlockTimestamp, - }, - }; - } catch (err) { - return { - status: GasFreeTransferStatus.FAILED, - error: err.message || 'Failed to fetch transfer status', - }; - } + _traceId: string, + _networkType?: NetworkType + ): Promise { + throw new Error(USDT_ACTIVITY_PAUSED); } - /** - * Monitor USDT transfer until completion - */ public static async monitorTransfer( traceId: string, - onStatusUpdate?: (status: any) => void, - networkType?: NetworkType + _onStatusUpdate?: (status: any) => void, + _networkType?: NetworkType ): Promise { - try { - const pollIn = 15; // Poll every 15 seconds - const maxAttempts = DEFAULT_DEADLINE_SECONDS / 15; // default deadline: 5 mins -- poll every 15 seconds, max attempts is 20 - - const finalStatus = await GasFree.monitorTransfer( - traceId, - (details) => { - if (onStatusUpdate) { - onStatusUpdate({ - status: details.state, - transactionHash: details.txnHash, - amount: details.txnAmount - ? GasFree.parseTokenAmount(details.txnAmount, 6) - : undefined, - }); - } - }, - networkType, - maxAttempts, - pollIn * 1000 // Poll every 15 seconds, in milliseconds - ); - - if (finalStatus.state === GasFreeTransferStatus.SUCCEED) { - return { - success: true, - traceId, - transactionHash: finalStatus.txnHash, - }; - } else { - return { - success: false, - traceId, - error: 'Transfer failed or was rejected', - }; - } - } catch (err) { - return { - success: false, - traceId, - error: err.message || 'Transfer monitoring failed', - }; - } + return { success: false, traceId, error: USDT_ACTIVITY_PAUSED }; } - /** - * Evaluates transfer fees - */ + // Retain old fee information for historical transaction screens. public static evaluateTransferFee(accountStatus: USDTAccountStatus): { transferFee: number; activateFee: number; totalFee: number; } { - try { - const { activateFee, transferFee } = accountStatus.fees; - const activationFee = accountStatus.isActive ? 0 : activateFee; - const totalFee = activationFee + transferFee; - return { - transferFee, - activateFee, - totalFee: totalFee, - }; - } catch (err) { - throw new Error(`Failed to evaluate transfer fees: ${err.message || err}`); - } + const { activateFee, transferFee } = accountStatus.fees; + return { + transferFee, + activateFee, + totalFee: transferFee + (accountStatus.isActive ? 0 : activateFee), + }; } - /** - * Validate address format using TronWeb - */ public static isValidAddress(address: string, networkType: NetworkType): boolean { return isValidTronAddress(address, networkType); } - /** - * Format USDT amount for display - */ public static formatUSDTAmount(amount: number, decimals: number = 2): string { return amount.toFixed(decimals); } - /** - * Parse USDT amount from string input - */ public static parseUSDTAmount(amountString: string): number { const parsed = parseFloat(amountString); - if (isNaN(parsed) || parsed <= 0) { - throw new Error('Invalid USDT amount'); - } + if (isNaN(parsed) || parsed <= 0) throw new Error('Invalid USDT amount'); return parsed; } - /** - * Get USDT balance directly from TRON blockchain - */ public static async getUSDTBalance( address: string, networkType: NetworkType = NetworkType.MAINNET ): Promise { try { - const usdtAddress = USDT.getUSDTAddress(networkType); - const balanceResult = await getTrc20Balance(address, usdtAddress, networkType); - return balanceResult.balance; + const result = await getTrc20Balance(address, USDT.getUSDTAddress(networkType), networkType); + return result.balance; } catch (error) { throw new Error(`Failed to fetch USDT balance: ${error.message || error}`); } } - /** - * Get USDT transactions for a USDT wallet - */ public static async getUSDTTransactions( address: string, networkType: NetworkType, @@ -464,34 +175,27 @@ export default class USDT { fingerprint?: string ): Promise<{ transactions: USDTTransaction[]; - meta: { - fingerprint: string; - hasMore: boolean; - }; + meta: { fingerprint: string; hasMore: boolean }; }> { - const usdtContractAddress = USDT.getUSDTAddress(networkType); - const trc20Transactions = await getTrc20Transactions( - address, - usdtContractAddress, - networkType, - limit, - fingerprint - ); - - const updatedTransactions = trc20Transactions.transactions.map((txn) => ({ - txId: txn.transactionId, - from: txn.from, - to: txn.to, - amount: txn.formattedValue.toString(), - status: txn.blockNumber ? GasFreeTransferStatus.SUCCEED : GasFreeTransferStatus.CONFIRMING, - timestamp: txn.blockTimestamp, - blockNumber: txn.blockNumber, - isGasFree: txn.to === address ? false : true, // incoming transactions are not GasFree in the similar sense as outgoing - })); - - return { - transactions: updatedTransactions, - meta: trc20Transactions.meta, - }; + const contract = USDT.getUSDTAddress(networkType); + const result = await getTrc20Transactions(address, contract, networkType, limit, fingerprint); + const transactions = result.transactions.map((txn) => { + // TronGrid can return a timestamp for an unconfirmed transfer. Require + // both fields so the stored status and pending indicator agree. + const confirmed = Boolean(txn.confirmed && txn.blockNumber); + return { + txId: txn.transactionId, + from: txn.from, + to: txn.to, + amount: txn.formattedValue.toString(), + status: confirmed + ? GasFreeTransferStatus.CHAIN_CONFIRMED + : GasFreeTransferStatus.CONFIRMING, + timestamp: txn.blockTimestamp, + blockNumber: confirmed ? txn.blockNumber : 0, + isGasFree: txn.to !== address, + }; + }); + return { transactions, meta: result.meta }; } } diff --git a/src/utils/service-utilities/config.ts b/src/utils/service-utilities/config.ts index 999bbc3ae7..f6191f3b3a 100644 --- a/src/utils/service-utilities/config.ts +++ b/src/utils/service-utilities/config.ts @@ -84,15 +84,10 @@ class Configuration { ? config.CHANNEL_URL.trim() : DEFAULT_CONFIG.CHANNEL_URL.trim(); - public GASFREE_API_KEY: string = config.GASFREE_API_KEY?.trim(); - public GASFREE_API_SECRET: string = config.GASFREE_API_SECRET?.trim(); - public RENEWAL_WINDOW: number; public LETS_EXCHANGE_BASE_URL: string = config.LETS_EXCHANGE_BASE_URL?.trim(); - public LETS_EXCHANGE_API_KEY: string = config.LETS_EXCHANGE_API_KEY?.trim(); - public LETS_EXCHANGE_AFFILIATE_ID: string = DEFAULT_CONFIG.LETS_EXCHANGE_AFFILIATE_ID; public ADDRESS: Address; diff --git a/tests/components/usdtCacheStatusPresentation.test.cjs b/tests/components/usdtCacheStatusPresentation.test.cjs new file mode 100644 index 0000000000..69578d7aea --- /dev/null +++ b/tests/components/usdtCacheStatusPresentation.test.cjs @@ -0,0 +1,156 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const ts = require('typescript'); + +const root = path.join(__dirname, '../..'); +const translations = { usdtWalletText: { statusUnavailable: 'Status unavailable' } }; +const React = { + createElement: (type, props, ...children) => ({ type, props, children }), + useContext: () => ({ translations }), +}; + +function loadSource(file, imports) { + const source = fs.readFileSync(path.join(root, file), 'utf8'); + const code = ts.transpileModule(source, { + compilerOptions: { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2020, + jsx: ts.JsxEmit.React, + esModuleInterop: true, + }, + }).outputText; + const module = { exports: {} }; + vm.runInNewContext(`(function (require, module, exports) { ${code}\n})`)( + (specifier) => { + if (!(specifier in imports)) throw new Error(`Unexpected import: ${specifier}`); + return imports[specifier]; + }, + module, + module.exports + ); + return module.exports; +} + +function nodes(tree) { + if (tree == null || tree === false) return []; + if (Array.isArray(tree)) return tree.flatMap(nodes); + if (typeof tree !== 'object') return [tree]; + return [tree, ...nodes(tree.children)]; +} + +const statuses = loadSource('src/services/wallets/operations/dollars/GasFree.ts', {}); +const { GasFreeTransferStatus } = statuses; +const usdt = loadSource('src/services/wallets/operations/dollars/USDT.ts', { + './GasFree': statuses, + 'src/services/wallets/enums': { NetworkType: { MAINNET: 'MAINNET' } }, + './Tron': {}, +}); + +const uiImports = { + react: React, + '@gluestack-ui/themed-native-base': { + Box: 'Box', + useColorMode: () => ({ colorMode: 'light' }), + }, + 'react-native': { + StyleSheet: { create: (styles) => styles }, + TouchableOpacity: 'TouchableOpacity', + }, + 'src/constants/responsive': { hp: (value) => value, wp: (value) => value }, + 'src/components/KeeperText': 'Text', + 'src/theme/Colors': {}, + 'src/context/Localization/LocContext': { LocalizationContext: {} }, + 'src/services/wallets/operations/dollars/GasFree': statuses, + 'src/services/wallets/operations/dollars/USDT': usdt, +}; + +const StatusContent = loadSource( + 'src/screens/USDT/components/StatusContent.tsx', + uiImports +).default; + +const rowImports = { + ...uiImports, + moment: () => ({ format: () => 'saved date' }), + 'src/screens/Home/components/CurrencyInfo': 'CurrencyInfo', + 'src/hooks/useLabelsNew': () => ({ labels: {} }), + 'src/services/wallets/enums': { EntityKind: { USDT_WALLET: 'USDT_WALLET' } }, + './ThemedColor/ThemedColor': () => 'color', +}; +for (const icon of [ + 'icon_sent_red', + 'icon_recieved_red', + 'icon_recieved_dark', + 'transaction_pending', + 'cache_icon', + 'icon_arrow_grey', + 'icon_arrow_white', +]) { + rowImports[`src/assets/images/${icon}.svg`] = icon; +} +const TransactionElement = loadSource('src/components/TransactionElement.tsx', rowImports).default; + +const wallet = { + entityKind: 'USDT_WALLET', + accountStatus: { gasFreeAddress: 'TStoredGasFreeAddress' }, +}; +const storedTransaction = { + txId: 'saved-chain-id', + traceId: 'saved-provider-trace', + from: 'TStoredGasFreeAddress', + to: 'TRecipient', + amount: '2', + timestamp: 100, + blockNumber: 100, + status: GasFreeTransferStatus.SUCCEED, + isGasFree: true, +}; + +test('offline legacy success with txId shows unavailable in the row and detail badge', () => { + assert.equal(usdt.isHistoricalUnverifiedUSDTRequest(storedTransaction), false); + assert.equal(usdt.isUSDTStatusUnavailable(storedTransaction), true); + + const row = nodes( + TransactionElement({ + transaction: storedTransaction, + wallet, + isCached: false, + }) + ); + assert.ok(row.includes('Status unavailable')); + assert.equal( + row.some((node) => node.type === 'transaction_pending'), + false + ); + + // The badge stays safe even if a caller forgets to pass `unavailable`. + const badge = nodes(StatusContent({ status: storedTransaction.status })); + assert.ok(badge.includes('Status unavailable')); + assert.equal(badge.includes('SUCCESS'), false); +}); + +test('only a confirmed chain status shows SUCCESS; actual pending rows keep the icon', () => { + const confirmed = { ...storedTransaction, status: GasFreeTransferStatus.CHAIN_CONFIRMED }; + assert.equal(usdt.isUSDTStatusUnavailable(confirmed), false); + const row = nodes(TransactionElement({ transaction: confirmed, wallet, isCached: false })); + assert.equal(row.includes('Status unavailable'), false); + assert.equal( + row.some((node) => node.type === 'transaction_pending'), + false + ); + assert.ok(nodes(StatusContent({ status: confirmed.status })).includes('SUCCESS')); + + const pending = { + ...storedTransaction, + status: GasFreeTransferStatus.CONFIRMING, + blockNumber: 0, + }; + const pendingRow = nodes(TransactionElement({ transaction: pending, wallet, isCached: false })); + assert.equal( + pendingRow.some((node) => node.type === 'transaction_pending'), + true + ); +}); diff --git a/tests/recovery/usdtBackup.test.cjs b/tests/recovery/usdtBackup.test.cjs index aedac01595..f328e81cfb 100644 --- a/tests/recovery/usdtBackup.test.cjs +++ b/tests/recovery/usdtBackup.test.cjs @@ -87,7 +87,15 @@ const usdtWallet = (type = 'DEFAULT') => ({ presentationData: { name: 'Before edit', description: 'Before', visibility: 'DEFAULT' }, specs: { address: 'disposable-tron-address', privateKey: 'fixture-only-private-key', balance: 10, transactions: [], hasNewUpdates: false, lastSynched: 1 }, - accountStatus: { isActive: true, nextNonce: 0 }, + accountStatus: { + address: 'disposable-tron-address', + gasFreeAddress: 'saved-fixture-receive-address', + isActive: true, + frozen: 0, + canTransfer: true, + nextNonce: 0, + fees: { transferFee: 1, activateFee: 2 }, + }, createdAt: 1, }); @@ -149,7 +157,7 @@ test('USDT balance, transaction and account sync avoids redundant backup uploads const synced = { ...original, specs: { ...original.specs, balance: 12, transactions: [{ txId: 'fixture-tx' }], hasNewUpdates: true, lastSynched: 2 }, - accountStatus: { isActive: true, nextNonce: 1 }, + accountStatus: { ...original.accountStatus, nextNonce: 1 }, }; assert.equal(await f.update(synced), true); assert.deepEqual(copy(f.collections.USDTWallet), [synced]); diff --git a/tests/services/client.test.ts b/tests/services/client.test.ts index 7b1381530b..a9b548153e 100644 --- a/tests/services/client.test.ts +++ b/tests/services/client.test.ts @@ -3,24 +3,88 @@ import ElectrumClient from '../../src/services/electrum/client'; import { predefinedTestnetNodes } from '../../src/services/electrum/predefinedNodes'; import * as bitcoinJS from 'bitcoinjs-lib'; +const mockClients: any[] = []; +const mockTxid = '24913105c497b4bb4ccf81b03857c8306aba0e58ccde792d981f6c18efdb24b8'; + +// Exercise the real ElectrumClient facade against deterministic protocol replies. +// A public Electrum server is outside the control of CI. +jest.mock('electrum-client', () => ({ + __esModule: true, + default: jest.fn().mockImplementation((_net, _tls, _port, host) => { + const client = { + host, + initElectrum: jest.fn(async () => { + if (host === 'blackie.c3-soft.com') { + throw new Error('connect ECONNREFUSED 127.0.0.1:50002'); + } + return ['fixture-server', '1.4']; + }), + close: jest.fn(), + onError: null, + server_ping: jest.fn(async () => undefined), + server_features: jest.fn(async () => ({ + server_version: 'fixture-server', + protocol_min: '1.4', + protocol_max: '1.4.3', + })), + blockchainScripthash_listunspentBatch: jest.fn(async (hashes) => + hashes.map((param, index) => ({ + param, + result: index === 0 ? [{ tx_hash: mockTxid, tx_pos: 1, value: 12345, height: 100 }] : [], + })) + ), + blockchainScripthash_getHistoryBatch: jest.fn(async (hashes) => + hashes.map((param, index) => ({ + param, + result: index === 0 ? [{ tx_hash: mockTxid, height: 100 }] : [], + })) + ), + blockchainEstimatefee: jest.fn(async () => 0.00002), + blockchainTransaction_getBatch: jest.fn(async (txids) => + txids.map((param) => ({ + param, + result: { + txid: param, + hex: 'fixture-hex', + vout: [{ scriptPubKey: { address: 'tb1qfixture' } }], + }, + })) + ), + }; + mockClients.push(client); + return client; + }), +})); + jest.mock('src/store/store', () => ({ store: { getState: () => ({ - settings: { - bitcoinNetwork: 'testnet', - }, + settings: { bitcoinNetworkType: 'TESTNET' }, }), }, })); -beforeAll(async () => { - try { - ElectrumClient.setActivePeer(predefinedTestnetNodes); - await ElectrumClient.connect(); - } catch (err) { - console.log('failed to connect to Electrum:', err); - process.exit(1); - } +const onlineNode = { + ...predefinedTestnetNodes[0], + id: 337, + host: 'electrum-fixture.test', + isConnected: true, +}; +const offlineNode = { + ...predefinedTestnetNodes[0], + isConnected: true, +}; +const addresses = [ + 'tb1qd2u9tvuqzadgeh02vppd33e7u2fatuwrw7h4q5', + 'tb1qwdm8hdyvv5jn05qq858lgnk50heucvxvqtl4sx', +]; + +beforeEach(async () => { + mockClients.length = 0; + ElectrumClient.setActivePeer([onlineNode], onlineNode); + ElectrumClient.resetCurrentPeerIndex(); + const connection = await ElectrumClient.connect(); + assert.ok(connection.connected); }); afterAll(() => { @@ -30,23 +94,33 @@ afterAll(() => { describe('ElectrumClient', () => { describe('Connection Tests', () => { it('should test connection successfully', async () => { - const result = await ElectrumClient.testConnection(predefinedTestnetNodes[0]); + const result = await ElectrumClient.testConnection(onlineNode); assert.ok(result.connected); }); it('should fail connection when node is unreachable', async () => { - const unreachableNode = { ...predefinedTestnetNodes[0], host: 'invalid.host' }; - const result = await ElectrumClient.testConnection(unreachableNode); + const result = await ElectrumClient.testConnection(offlineNode); assert.ok(!result.connected); assert.ok(result.error); + assert.strictEqual(result.errorType, 'network'); }); it('should reconnect to the next peer when connection fails', async () => { - ElectrumClient.setActivePeer(predefinedTestnetNodes); + ElectrumClient.setActivePeer([offlineNode, onlineNode], offlineNode); + ElectrumClient.resetCurrentPeerIndex(); + const result = await ElectrumClient.connect(); + assert.ok(result.connected); + assert.strictEqual(result.connectedTo, onlineNode.host); + assert.strictEqual(ElectrumClient.getActivePeer()?.host, onlineNode.host); + + assert.ok(mockClients.some((client) => client.host === offlineNode.host)); + }); + + it('should reconnect after explicit disconnection', async () => { ElectrumClient.forceDisconnect(); const result = await ElectrumClient.reconnect(); assert.ok(result.connected); - assert.ok(result.connectedTo); + assert.strictEqual(result.connectedTo, onlineNode.host); }); }); @@ -60,51 +134,50 @@ describe('ElectrumClient', () => { describe('Feature Tests', () => { it('should retrieve server features', async () => { const features = await ElectrumClient.serverFeatures(); - assert.ok(features.server_version); - assert.ok(features.protocol_min); - assert.ok(features.protocol_max); + assert.strictEqual(features.server_version, 'fixture-server'); + assert.strictEqual(features.protocol_min, '1.4'); + assert.strictEqual(features.protocol_max, '1.4.3'); }); }); describe('UTXO and History Tests', () => { it('should sync UTXOs by address', async () => { - const addresses = [ - 'tb1qd2u9tvuqzadgeh02vppd33e7u2fatuwrw7h4q5', - 'tb1qwdm8hdyvv5jn05qq858lgnk50heucvxvqtl4sx', - ]; const utxos = await ElectrumClient.syncUTXOByAddress(addresses, bitcoinJS.networks.testnet); - assert.ok(Object.keys(utxos).length > 0); + assert.deepStrictEqual(utxos[addresses[0]], [ + { txId: mockTxid, vout: 1, value: 12345, height: 100, address: addresses[0] }, + ]); + assert.deepStrictEqual(utxos[addresses[1]], []); }); it('should sync history by address', async () => { - const addresses = [ - 'tb1qd2u9tvuqzadgeh02vppd33e7u2fatuwrw7h4q5', - 'tb1qwdm8hdyvv5jn05qq858lgnk50heucvxvqtl4sx', - ]; const history = await ElectrumClient.syncHistoryByAddress( addresses, bitcoinJS.networks.testnet ); - assert.ok(Object.keys(history.historyByAddress).length > 0); - assert.ok(history.txids.length > 0); + assert.deepStrictEqual(history.historyByAddress[addresses[0]], [ + { tx_hash: mockTxid, height: 100 }, + ]); + assert.deepStrictEqual(history.historyByAddress[addresses[1]], []); + assert.deepStrictEqual(history.txids, [mockTxid]); + assert.strictEqual(history.txidToAddress[mockTxid], addresses[0]); }); }); describe('Transaction Tests', () => { it('should estimate fee', async () => { const fee = await ElectrumClient.estimateFee(1); - assert.ok(fee > 0); + assert.strictEqual(fee, 2); }); it('should fetch transactions by ID', async () => { - const txids = [ - '24913105c497b4bb4ccf81b03857c8306aba0e58ccde792d981f6c18efdb24b8', - '9a15008af30580039bc7a07d36c3544902a2e1618ad31f4dda94fe0044a8dcce', - ]; + const txids = [mockTxid, '9a15008af30580039bc7a07d36c3544902a2e1618ad31f4dda94fe0044a8dcce']; const transactions = await ElectrumClient.getTransactionsById(txids); - assert.ok(Object.keys(transactions).length === txids.length); - assert.deepStrictEqual(transactions[txids[0]].txid, txids[0]); - assert.deepStrictEqual(transactions[txids[1]].txid, txids[1]); + assert.deepStrictEqual(Object.keys(transactions), txids); + for (const txid of txids) { + assert.strictEqual(transactions[txid].txid, txid); + assert.strictEqual(transactions[txid].hex, undefined); + assert.deepStrictEqual(transactions[txid].vout[0].scriptPubKey.addresses, ['tb1qfixture']); + } }); }); }); diff --git a/tests/services/electrumWalletFixture.ts b/tests/services/electrumWalletFixture.ts new file mode 100644 index 0000000000..466523c6ed --- /dev/null +++ b/tests/services/electrumWalletFixture.ts @@ -0,0 +1,79 @@ +import ElectrumClient from 'src/services/electrum/client'; +import WalletOperations from 'src/services/wallets/operations'; + +const fundingTxid = '608710eb040d935dedb6c4d6321369382b2bd45533a7442a6fa98add3860d46b'; +const previousTxid = '89b193b61f7681ee588939932219f3d92e54a1873a9fb823647038f3879fba00'; +const externalAddress = 'tb1ql7w62elx9ucw4pj5lgw4l028hmuw80sndtntxt'; + +// The wallet and vault suites exercise address scanning, transaction parsing, coin selection, +// and PSBT signing. Give each generated wallet one funded testnet address without using a +// public Electrum server or a mutable public wallet balance. +export const installElectrumWalletFixture = () => { + let fundedAddress: string | null = null; + const syncWallets = WalletOperations.syncWalletsViaElectrumClient; + + jest.spyOn(WalletOperations, 'syncWalletsViaElectrumClient').mockImplementation((...args) => { + fundedAddress = null; + return syncWallets(...args); + }); + jest.spyOn(WalletOperations, 'fetchFeeRatesByPriority').mockImplementation(async () => + WalletOperations.mockFeeRates() + ); + + jest.spyOn(ElectrumClient, 'setActivePeer').mockImplementation(() => undefined); + jest.spyOn(ElectrumClient, 'connect').mockResolvedValue({ + connected: true, + connectedTo: 'fixture.electrum.test', + }); + jest.spyOn(ElectrumClient, 'forceDisconnect').mockImplementation(() => undefined); + jest.spyOn(ElectrumClient, 'getBlockchainHeaders').mockResolvedValue({ height: 85172, hex: '00' }); + jest.spyOn(ElectrumClient, 'syncUTXOByAddress').mockImplementation(async (addresses) => { + if (!fundedAddress) fundedAddress = addresses[0]; + return Object.fromEntries( + addresses.map((address) => [ + address, + address === fundedAddress + ? [{ txId: fundingTxid, vout: 1, value: 6000, height: 85000, address }] + : [], + ]) + ); + }); + jest.spyOn(ElectrumClient, 'syncHistoryByAddress').mockImplementation(async (addresses) => { + const hasFunding = addresses.includes(fundedAddress); + return { + historyByAddress: Object.fromEntries( + addresses.map((address) => [ + address, + hasFunding && address === fundedAddress ? [{ tx_hash: fundingTxid, height: 85000 }] : [], + ]) + ), + txids: hasFunding ? [fundingTxid] : [], + txidToAddress: hasFunding ? { [fundingTxid]: fundedAddress } : {}, + }; + }); + jest.spyOn(ElectrumClient, 'getTransactionsById').mockImplementation(async (txids) => { + const transactions: Record = {}; + for (const txid of txids) { + if (txid === fundingTxid) { + transactions[txid] = { + txid, + vin: [{ txid: previousTxid, vout: 0 }], + vout: [ + { value: 0.00001, scriptPubKey: { addresses: [externalAddress] } }, + { value: 0.00006, scriptPubKey: { addresses: [fundedAddress] } }, + ], + confirmations: 12, + time: 1700000000, + blocktime: 1700000000, + }; + } else if (txid === previousTxid) { + transactions[txid] = { + txid, + vin: [], + vout: [{ value: 0.0001, scriptPubKey: { addresses: [externalAddress] } }], + }; + } + } + return transactions; + }); +}; diff --git a/tests/services/encryption.test.ts b/tests/services/encryption.test.ts index 24a89e6a57..2c395c4ae2 100644 --- a/tests/services/encryption.test.ts +++ b/tests/services/encryption.test.ts @@ -82,7 +82,13 @@ describe('Testing cryptographic primitives', () => { test('Decryption::Incorrect key', () => { const incorrectKey = 'a'.repeat(64); - const decrypted = decrypt(incorrectKey, encrypted); + let decrypted: string; + try { + decrypted = decrypt(incorrectKey, encrypt(key, message)); + } catch (error) { + expect(error).toEqual(new Error('Malformed UTF-8 data')); + return; + } expect(decrypted).not.toBe(message); }); }); diff --git a/tests/services/tronConfirmedHistory.test.cjs b/tests/services/tronConfirmedHistory.test.cjs new file mode 100644 index 0000000000..ffcf754af0 --- /dev/null +++ b/tests/services/tronConfirmedHistory.test.cjs @@ -0,0 +1,127 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const ts = require('typescript'); + +const source = fs.readFileSync( + path.join(__dirname, '../../src/services/wallets/operations/dollars/Tron.ts'), + 'utf8' +); +const code = ts.transpileModule(source, { + compilerOptions: { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2020, + esModuleInterop: true, + }, +}).outputText; + +test('TRC20 history requests confirmed rows and keeps the pagination filter', async () => { + const requested = []; + const imports = { + '../../enums': { NetworkType: { MAINNET: 'MAINNET', TESTNET: 'TESTNET' } }, + bip39: {}, + bip32: () => ({}), + '../taproot-utils/noble_ecc': {}, + 'bitcoinjs-lib': {}, + tronweb: { + TronWeb: class { + isAddress() { + return true; + } + }, + }, + }; + const fetch = async (url) => { + requested.push(url); + return { + ok: true, + json: async () => ({ + success: true, + data: [ + { + transaction_id: 'disposable-confirmed', + block_timestamp: 100000, + from: 'TFrom', + to: 'TTo', + type: 'Transfer', + value: '2000000', + token_info: { address: 'TContract', decimals: 6 }, + }, + ], + meta: { fingerprint: 'next-page', page_size: 2 }, + }), + }; + }; + const module = { exports: {} }; + vm.runInNewContext(`(function (require, module, exports) { ${code}\n})`, { + URLSearchParams, + fetch, + })( + (name) => { + if (!(name in imports)) throw new Error(`Unexpected import: ${name}`); + return imports[name]; + }, + module, + module.exports + ); + + const result = await module.exports.getTrc20Transactions( + 'TStoredAddress', + 'TContract', + 'MAINNET', + 2, + 'prior-page' + ); + const url = new URL(requested[0]); + assert.equal(url.searchParams.get('only_confirmed'), 'true'); + assert.equal(url.searchParams.has('only_unconfirmed'), false); + assert.equal(url.searchParams.get('fingerprint'), 'prior-page'); + assert.equal(url.searchParams.get('limit'), '2'); + assert.equal(url.searchParams.get('contract_address'), 'TContract'); + assert.equal(result.transactions[0].confirmed, true); + assert.equal(result.transactions[0].blockNumber, 100); + assert.equal(result.meta.fingerprint, 'next-page'); + assert.equal(result.meta.hasMore, true); + + const usdtSource = fs.readFileSync( + path.join(__dirname, '../../src/services/wallets/operations/dollars/USDT.ts'), + 'utf8' + ); + const usdtCode = ts.transpileModule(usdtSource, { + compilerOptions: { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2020, + esModuleInterop: true, + }, + }).outputText; + const usdtModule = { exports: {} }; + vm.runInNewContext(`(function (require, module, exports) { ${usdtCode}\n})`)( + (name) => { + if (name === './Tron') return module.exports; + if (name === './GasFree') + return { + GasFreeTransferStatus: { + CHAIN_CONFIRMED: 'CONFIRMED', + CONFIRMING: 'CONFIRMING', + }, + }; + if (name === 'src/services/wallets/enums') return imports['../../enums']; + throw new Error(`Unexpected import: ${name}`); + }, + usdtModule, + usdtModule.exports + ); + const mapped = await usdtModule.exports.default.getUSDTTransactions( + 'TStoredAddress', + 'MAINNET', + 2, + 'prior-page' + ); + assert.equal(mapped.transactions[0].status, 'CONFIRMED'); + assert.equal(mapped.transactions[0].blockNumber, 100); + assert.equal(mapped.meta.fingerprint, 'next-page'); + assert.equal(new URL(requested[1]).searchParams.get('only_confirmed'), 'true'); + assert.equal(new URL(requested[1]).searchParams.get('fingerprint'), 'prior-page'); +}); diff --git a/tests/services/usdtPause.test.cjs b/tests/services/usdtPause.test.cjs new file mode 100644 index 0000000000..ff9f2c12a1 --- /dev/null +++ b/tests/services/usdtPause.test.cjs @@ -0,0 +1,264 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const ts = require('typescript'); + +const root = path.join(__dirname, '../..'); +function loadTypeScript(relativePath, imports = {}) { + const source = fs.readFileSync(path.join(root, relativePath), 'utf8'); + const code = ts.transpileModule(source, { + compilerOptions: { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2020, + esModuleInterop: true, + }, + }).outputText; + const module = { exports: {} }; + const loadImport = (specifier) => { + if (!(specifier in imports)) throw new Error(`Unexpected import: ${specifier}`); + return imports[specifier]; + }; + const run = vm.runInNewContext(`(function (require, module, exports) { ${code}\n})`, { + Date, + Error, + Promise, + }); + run(loadImport, module, module.exports); + return module.exports; +} + +const network = { MAINNET: 'MAINNET', TESTNET: 'TESTNET' }; +const historical = loadTypeScript('src/services/wallets/operations/dollars/GasFree.ts'); +const balanceCalls = []; +const historyCalls = []; +const tron = { + isValidTronAddress: () => true, + getTrc20Balance: async (...args) => { + balanceCalls.push(args); + return { balance: 42, decimals: 6 }; + }, + getTrc20Transactions: async (...args) => { + historyCalls.push(args); + return { + transactions: [ + { + transactionId: 'chain-1', + from: 'TStoredGasFreeAddress', + to: 'TRecipient', + formattedValue: 2, + confirmed: true, + blockNumber: 1, + blockTimestamp: 100, + }, + { + transactionId: 'chain-no-time', + from: 'TStoredGasFreeAddress', + to: 'TRecipient', + formattedValue: 1, + confirmed: true, + blockNumber: 0, + blockTimestamp: 0, + }, + ], + meta: { fingerprint: '', hasMore: false }, + }; + }, +}; +const usdtModule = loadTypeScript('src/services/wallets/operations/dollars/USDT.ts', { + './GasFree': historical, + 'src/services/wallets/enums': { NetworkType: network }, + './Tron': tron, +}); +const service = usdtModule.default; + +const wallet = { + networkType: network.MAINNET, + accountStatus: { + address: 'TOwner', + gasFreeAddress: 'TStoredGasFreeAddress', + frozen: 3, + isActive: true, + canTransfer: true, + nextNonce: 2, + fees: { transferFee: 1, activateFee: 0 }, + }, + specs: { + address: 'TOwner', + privateKey: 'fixture-only', + balance: 10, + transactions: [ + { + traceId: 'historical-trace', + from: 'TStoredGasFreeAddress', + to: 'TRecipient', + amount: '2', + status: historical.GasFreeTransferStatus.WAITING, + timestamp: 50, + isGasFree: true, + }, + ], + hasNewUpdates: false, + lastSynched: 1, + }, +}; + +const factory = loadTypeScript('src/services/wallets/factories/USDTWalletFactory.ts', { + 'crypto-js': { SHA256: () => ({ toString: () => 'fixture-id' }) }, + '../enums': { + NetworkType: network, + EntityKind: { USDT_WALLET: 'USDT_WALLET' }, + VisibilityType: { DEFAULT: 'DEFAULT' }, + }, + '../operations/dollars/Tron': {}, + '../operations/dollars/USDT': { __esModule: true, default: service }, + '../operations/BIP85': { __esModule: true, default: {} }, + '../operations/dollars/GasFree': historical, + 'src/utils/service-utilities/config': { + __esModule: true, + default: { isDevMode: () => false }, + }, +}); + +test('retired provider operations fail closed without a provider import', async () => { + assert.equal(await service.isGasFreeSupported(network.MAINNET), false); + assert.equal((await service.getServiceProviders(network.MAINNET)).length, 0); + await assert.rejects(service.getAccountStatus('TOwner'), /USDT activity is paused/); + assert.equal((await service.prepareTransfer({ source: wallet })).isValid, false); + assert.equal((await service.submitTransfer(wallet, {})).success, false); + await assert.rejects(service.getTransferStatus('historical-trace'), /USDT activity is paused/); + assert.equal((await service.monitorTransfer('historical-trace')).success, false); +}); + +test('stored address, chain reads and ambiguous historical request survive the pause', async () => { + assert.equal(await factory.updateUSDTWalletAccountStatus(wallet), wallet.accountStatus); + assert.equal(await factory.syncUSDTWalletBalance(wallet), 42); + assert.equal(balanceCalls[0][0], wallet.accountStatus.gasFreeAddress); + assert.equal(factory.getAvailableBalanceUSDTWallet(wallet), 10); + + const transactions = await factory.syncUSDTWalletTransactions(wallet); + assert.equal(historyCalls[0][0], wallet.accountStatus.gasFreeAddress); + assert.equal(transactions.length, 3); + assert.equal(transactions[0].txId, 'chain-1'); + assert.equal(transactions[0].status, historical.GasFreeTransferStatus.CHAIN_CONFIRMED); + assert.equal(transactions[1].traceId, 'historical-trace'); + assert.equal(transactions[0].to, transactions[1].to); + assert.equal(transactions[0].amount, transactions[1].amount); + assert.equal(transactions[1].txId, undefined); + assert.equal(usdtModule.isHistoricalUnverifiedUSDTRequest(transactions[0]), false); + assert.equal(usdtModule.isHistoricalUnverifiedUSDTRequest(transactions[1]), true); + assert.equal(transactions[1].status, historical.GasFreeTransferStatus.WAITING); + assert.equal(transactions[2].txId, 'chain-no-time'); + assert.equal(transactions[2].status, historical.GasFreeTransferStatus.CONFIRMING); + assert.equal(transactions[2].blockNumber, 0); + assert.equal(usdtModule.isUSDTStatusUnavailable(transactions[0]), false); + assert.equal(usdtModule.isUSDTStatusUnavailable(transactions[1]), true); + assert.equal( + usdtModule.isHistoricalUnverifiedUSDTRequest({ + traceId: 'old-request', + status: historical.GasFreeTransferStatus.SUCCEED, + }), + true, + 'a stored provider status is not independent proof of an on-chain transfer' + ); +}); + +test('refresh upgrades a cached pending entry when its confirmed chain record appears', async () => { + const cached = { + ...wallet, + specs: { + ...wallet.specs, + transactions: [ + ...wallet.specs.transactions, + { + txId: 'chain-1', + traceId: 'saved-provider-trace', + from: 'TStoredGasFreeAddress', + to: 'TRecipient', + amount: '2', + status: historical.GasFreeTransferStatus.CONFIRMING, + timestamp: 90, + blockNumber: 0, + isGasFree: true, + }, + ], + }, + }; + const transactions = await factory.syncUSDTWalletTransactions(cached); + const confirmed = transactions.find((tx) => tx.txId === 'chain-1'); + assert.equal(confirmed.status, historical.GasFreeTransferStatus.CHAIN_CONFIRMED); + assert.equal(confirmed.blockNumber, 1); + assert.equal(confirmed.traceId, 'saved-provider-trace'); + assert.equal( + transactions.find((tx) => tx.traceId === 'historical-trace').status, + historical.GasFreeTransferStatus.WAITING + ); +}); + +test('an unmatched legacy success stays in history but loses its success claim', async () => { + const legacySuccess = { + txId: 'older-than-first-page', + traceId: 'saved-provider-trace', + from: 'TStoredGasFreeAddress', + to: 'TRecipient', + amount: '3', + status: historical.GasFreeTransferStatus.SUCCEED, + timestamp: 20, + blockNumber: 20, + isGasFree: true, + }; + const cached = { + ...wallet, + specs: { ...wallet.specs, transactions: [...wallet.specs.transactions, legacySuccess] }, + }; + + // The UI must be truthful before refresh too, including when offline. + assert.equal(usdtModule.isUSDTStatusUnavailable(legacySuccess), true); + const transactions = await factory.syncUSDTWalletTransactions(cached); + const retained = transactions.find((tx) => tx.txId === legacySuccess.txId); + assert.equal(transactions.length, 4); + assert.equal(retained.status, historical.GasFreeTransferStatus.UNVERIFIED); + assert.equal(retained.traceId, legacySuccess.traceId); + assert.equal(retained.timestamp, legacySuccess.timestamp); + assert.equal(retained.blockNumber, legacySuccess.blockNumber); + assert.equal(usdtModule.isUSDTStatusUnavailable(retained), true); + assert.equal(legacySuccess.status, historical.GasFreeTransferStatus.SUCCEED); +}); + +test('matching confirmed history corrects a cached legacy success without losing its trace', async () => { + const cached = { + ...wallet, + specs: { + ...wallet.specs, + transactions: [ + ...wallet.specs.transactions, + { + txId: 'chain-1', + traceId: 'saved-provider-trace', + from: 'TStoredGasFreeAddress', + to: 'TRecipient', + amount: '2', + status: historical.GasFreeTransferStatus.SUCCEED, + timestamp: 80, + blockNumber: 1, + isGasFree: true, + }, + ], + }, + }; + + const transactions = await factory.syncUSDTWalletTransactions(cached); + const confirmed = transactions.filter((tx) => tx.txId === 'chain-1'); + assert.equal(confirmed.length, 1); + assert.equal(confirmed[0].status, historical.GasFreeTransferStatus.CHAIN_CONFIRMED); + assert.equal(confirmed[0].traceId, 'saved-provider-trace'); + assert.equal(confirmed[0].blockNumber, 1); + assert.equal(usdtModule.isUSDTStatusUnavailable(confirmed[0]), false); +}); + +test('missing saved address is never replaced by the owner address', async () => { + const missing = { ...wallet, accountStatus: { ...wallet.accountStatus, gasFreeAddress: '' } }; + await assert.rejects(factory.syncUSDTWalletBalance(missing), /Stored USDT address/); + await assert.rejects(factory.syncUSDTWalletTransactions(missing), /Stored USDT address/); +}); diff --git a/tests/services/vault.test.ts b/tests/services/vault.test.ts index ed6cf6f13b..7b102a7917 100644 --- a/tests/services/vault.test.ts +++ b/tests/services/vault.test.ts @@ -43,6 +43,7 @@ import { generateOutputDescriptors, parseTextforVaultConfig, } from 'src/utils/service-utilities/utils'; +import { installElectrumWalletFixture } from './electrumWalletFixture'; jest.mock('src/store/store', () => ({ store: { @@ -56,6 +57,10 @@ jest.mock('src/store/store', () => ({ jest.mock('realm', () => ({})); +beforeAll(() => { + installElectrumWalletFixture(); +}); + const connectToElectrumClient = async () => { try { ElectrumClient.setActivePeer(predefinedTestnetNodes); @@ -67,6 +72,10 @@ const connectToElectrumClient = async () => { } }; +afterAll(() => { + ElectrumClient.forceDisconnect(); +}); + describe('Vault: Single-Sig(1-of-1)', () => { let primaryMnemonic: string; let vault: Vault; diff --git a/tests/services/wallet.test.ts b/tests/services/wallet.test.ts index dc92142d4f..b366993e46 100644 --- a/tests/services/wallet.test.ts +++ b/tests/services/wallet.test.ts @@ -12,6 +12,7 @@ import { TransactionPrerequisite, } from 'src/services/wallets/interfaces'; import { Wallet } from 'src/services/wallets/interfaces/wallet'; +import { installElectrumWalletFixture } from './electrumWalletFixture'; jest.mock('src/store/store', () => ({ store: { @@ -25,6 +26,10 @@ jest.mock('src/store/store', () => ({ jest.mock('realm', () => ({})); +beforeAll(() => { + installElectrumWalletFixture(); +}); + describe('Wallet Functionality Tests', () => { let primaryMnemonic: string; let wallet: Wallet;