Skip to content

feat: don't return change with CoinJoin Send unless there is a high fee - #1460

Merged
HashEngineering merged 39 commits into
masterfrom
feat/coinjoin-no-change
Feb 17, 2026
Merged

HashEngineering merged 39 commits into
masterfrom
feat/coinjoin-no-change

Conversation

@HashEngineering

@HashEngineering HashEngineering commented Feb 4, 2026 •

Copy link
Copy Markdown
Collaborator

Issue being fixed or feature implemented

Related PR's and Dependencies

Screenshots / Videos

How Has This Been Tested?

  • QA (Mobile Team)

Checklist:

  • I have performed a self-review of my own code and added comments where necessary
  • I have added or updated relevant unit/integration/functional/e2e tests

Summary by CodeRabbit

  • New Features

    • Expanded payment support: BIP70/BIP270 and direct-pay flows; improved fee heuristics and greedy coin-selection handling
    • UI: clearer payee verification state ("secured by" vs "connected to (not secured)") and ability to hide cancel on payment error
  • Bug Fixes

    • Improved payment error handling, retry/rollback for direct payments, and dust/fee retry behavior
  • Documentation

    • Added comprehensive payment methodology guide
  • Tests

    • New BIP70/BIP70-like payment protocol unit tests
  • Chores

    • Analytics DI wiring and test analytics replacement added

@coderabbitai

coderabbitai Bot commented Feb 4, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds BIP70/BIP270 payment flows and direct HTTP payments, moves payment background work from HandlerThreads to coroutines, introduces CoinJoin greedy dry‑run and fee-threshold logic, restructures Analytics DI for prod/tests, updates UI/resources, and adds documentation plus extensive BIP70 tests.

Changes

Cohort / File(s) Summary
Build & deps
build.gradle, wallet/build.gradle
Bumped dashjVersion to 21.2.0-SNAPSHOT; bumped org.dashj.android:dashj-scrypt-android to 1.0.1; added test deps (mockwebserver, robolectric).
Core payment API & stubs
SendPaymentService
common/src/main/java/org/dash/wallet/common/services/SendPaymentService.kt, features/exploredash/.../FakeDashSpendService.kt
Added fun isFeeTooHigh(tx: Transaction): Boolean to SendPaymentService; stubbed override returning false in fake service.
SendCoins task & direct payment flows
wallet/src/de/schildbach/wallet/payments/SendCoinsTaskRunner.kt
Added fetch/validation for BIP70/BIP270 payment requests, direct HTTP payment submission/ack handling (directPay/sendDirectPayment), coin‑selector greedy flag plumbing, dust/fee retry logic, MAX_NO_CHANGE_FEE/isFeeTooHigh coinjoin logic, and new overloads exposing greedy options.
ViewModels & threading refactor
wallet/src/de/schildbach/wallet/ui/send/PaymentProtocolViewModel.kt, wallet/src/de/schildbach/wallet/ui/send/SendCoinsViewModel.kt
Replaced HandlerThread-based background work with coroutines (viewModelScope/Dispatchers.IO); simplified constructors; changed direct payment ACK type to Transaction; moved IO into suspending functions; added dry‑run greedy detection and short ANR watchdog in SendCoinsViewModel.
UI, layout & resources
wallet/src/de/schildbach/wallet/ui/send/PaymentProtocolFragment.kt, wallet/src/de/schildbach/wallet/ui/widget/PaymentRequestWaitErrorView.kt, wallet/res/layout/view_payment_request_details.xml, wallet/res/values/strings-extra.xml
Fragment now displays transaction ACK data and shows payee verification/host for unsecured; added hideCancelButton() API; added secured_by TextView and dialog_confirm_connected_to_unsecured string; adjusted alignment attributes.
DI & test DI
wallet/src/de/schildbach/wallet/di/AnalyticsModule.kt, wallet/src/de/schildbach/wallet/di/AppModule.kt, wallet/test/de/schildbach/wallet/TestAnalyticsModule.kt, wallet/test/de/schildbach/wallet/FakeAnalyticsService.kt
Moved Analytics binding into new AnalyticsModule (@Binds); removed bind from AppModule; added TestAnalyticsModule to replace AnalyticsModule in tests and a FakeAnalyticsService test implementation.
Tests: BIP70 suite
wallet/test/de/schildbach/wallet/payments/SendCoinsTaskRunnerBIP70Test.kt
Added comprehensive Robolectric/Hilt tests using MockWebServer to validate fetchPaymentRequest, payWithDashUrl, sendDirectPayment, ACK handling, headers/content types, expiration/validation, and error paths.
Docs
docs/payment-methodology.md
Added extensive payment methodology documentation describing SendCoinsTaskRunner, SendCoinsViewModel, PaymentProtocolViewModel, CoinJoin greedy/dry‑run logic, fee handling, and example flows.
Misc
common/src/main/java/org/dash/wallet/common/util/Constants.kt
Added BuildConfig import.
UI helper change
wallet/src/de/schildbach/wallet/ui/widget/PaymentRequestWaitErrorView.kt
Added hideCancelButton() to control cancel visibility.

Sequence Diagram

sequenceDiagram
    participant User as User
    participant Frag as PaymentProtocolFragment
    participant VM as PaymentProtocolViewModel
    participant Runner as SendCoinsTaskRunner
    participant Wallet as Wallet
    participant Server as PaymentServer

    User->>Frag: initiate payment (BIP70/BIP270)
    Frag->>VM: requestPaymentRequest(basePaymentIntent)
    VM->>Runner: fetchPaymentRequest(basePaymentIntent)
    Runner->>Server: HTTP GET payment request
    Server-->>Runner: PaymentRequest (protobuf)
    Runner->>Runner: validate, trust-check, build PaymentIntent
    Runner-->>VM: PaymentRequest result
    VM->>Wallet: create SendRequest (coin selection)
    Wallet-->>VM: SendRequest
    Frag->>VM: sendPayment()
    VM->>Runner: sendDirectPayment(sendRequest, paymentIntent)
    Runner->>Wallet: sign transaction (propagate wallet context)
    Wallet-->>Runner: Signed tx
    Runner->>Server: HTTP POST Payment (signed tx)
    Server-->>Runner: PaymentACK (may include Transaction)
    Runner-->>VM: Transaction result
    VM-->>Frag: directPaymentAckLiveData updated
    Frag-->>User: display transaction / confirmation
Loading

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I hopped through docs and coroutine light,

BIP70 fetched, ACKs took flight.
Greedy dry‑runs chase fees at night,
Analytics moved to test delight,
A rabbit cheers — payments now right!

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 19.35% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly and accurately describes the main feature being implemented: preventing change return in CoinJoin Send transactions except when fees are high, which is the core objective across the changeset.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/coinjoin-no-change

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@HashEngineering

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Feb 4, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Fix all issues with AI agents
In `@wallet/src/de/schildbach/wallet/payments/SendCoinsTaskRunner.kt`:
- Around line 305-319: Remove the large commented-out fee-checking block inside
SendCoinsTaskRunner (the code referencing isFeeTooHigh, createSendRequest,
wallet.completeTx, finalPaymentIntent and sendRequest); delete the commented
lines entirely so only active logic remains (rely on VCS to restore if needed)
and ensure no leftover commented fragments or TODOs remain around the
sendRequest handling.

In `@wallet/src/de/schildbach/wallet/service/CoinJoinService.kt`:
- Around line 135-139: The change lowering DEFAULT_ROUNDS from its previous
value to 1 in the CoinJoinMixingService companion (symbol DEFAULT_ROUNDS in
CoinJoinMixingService) reduces INTERMEDIATE/ADVANCED privacy; confirm with
product/privacy whether this is intentional and either (a) revert DEFAULT_ROUNDS
to the previous value, (b) conditionally set DEFAULT_ROUNDS based on mix mode or
fee (e.g., keep higher rounds for INTERMEDIATE/ADVANCED), or (c) add a clear
comment and opt-in flag documenting the privacy tradeoff; update companion
constants (DEFAULT_ROUNDS, DEFAULT_SESSIONS, DEFAULT_MULTISESSION) and any
docs/config help text to reflect the chosen approach.

In `@wallet/src/de/schildbach/wallet/ui/send/PaymentProtocolViewModel.kt`:
- Around line 176-199: In sendPayment() the coroutine runs on Dispatchers.IO but
sets directPaymentAckLiveData.value = Resource.loading(null) which must only be
used on the main thread; change that assignment to
directPaymentAckLiveData.postValue(Resource.loading(null)) so the loading state
is posted from the background thread (other uses in sendPayment already use
postValue), keeping the rest of the error/success postValue logic intact.

In `@wallet/src/de/schildbach/wallet/ui/send/SendCoinsViewModel.kt`:
- Around line 277-279: The error message inside the conditional that checks
isAssetLock is inverted: when entering the branch if (!isAssetLock) the message
wrongly says "but is true". Update the message where the code throws error to
read "isAssetLock must be true, but is false" (locate the conditional using the
isAssetLock variable in SendCoinsViewModel and replace the incorrect string).

In `@wallet/test/de/schildbach/wallet/FakeAnalyicsService.kt`:
- Around line 1-15: Rename the file to fix the typo and remove the misleading
comment: rename FakeAnalyicsService.kt to FakeAnalyticsService.kt so the
filename matches the class FakeAnalyticsService, and delete the incorrect
comment line "// src/test/java/.../FakeAnalyticsService.kt" in the file; no code
changes to the class implementation are required.
🧹 Nitpick comments (10)
wallet/src/de/schildbach/wallet/di/AppModule.kt (1)

134-137: Remove commented-out code.

The analytics binding has been moved to AnalyticsModule.kt. Consider removing the commented-out code rather than leaving it in place, along with the now-unused FirebaseAnalyticsServiceImpl import on line 57.

🧹 Proposed cleanup
-import org.dash.wallet.common.services.analytics.FirebaseAnalyticsServiceImpl
-//    `@Binds`
-//    abstract fun bindAnalyticsService(
-//        analyticsService: FirebaseAnalyticsServiceImpl
-//    ): AnalyticsService
docs/payment-methodology.md (1)

7-25: Add language specifiers to ASCII diagram code blocks.

The ASCII art diagrams would benefit from a language specifier (e.g., text or plaintext) to satisfy linting rules and improve rendering consistency.

📝 Example fix for the first diagram
-```
+```text
 ┌─────────────────────────────────────────────────────────────────┐
 │                        UI Layer                                 │

Apply similar changes to other ASCII diagram blocks at lines 107, 117, 152, 308, and 384.

wallet/test/de/schildbach/wallet/payments/SendCoinsTaskRunnerBIP70Test.kt (4)

20-20: Remove unused import.

FirebaseApp is imported but never used in this test file.

-import com.google.firebase.FirebaseApp

484-496: Clean up debug output and improve exception handling.

The println(tx) and e.printStackTrace() are debug artifacts. Consider using structured logging or removing them. Additionally, catching a broad Exception and only printing the stack trace makes test failures harder to diagnose.

Suggested improvement
         try {
             val tx = sendCoinsTaskRunner.payWithDashUrl(bip72Uri, "TestService")
-            println(tx)
+            // Successfully processed the BIP72 URI
             // If we get here without exception, the request was processed
             // (though it may fail later due to wallet mocking limitations)
         } catch (e: Exception) {
             // Expected - wallet operations are mocked
             // Verify the payment request was fetched
             val request = mockWebServer.takeRequest()
             assertEquals("GET", request.method)
             assertTrue(request.path?.contains("/request") == true)
-            e.printStackTrace()
         }

625-638: Consider adding assertions for expected exception scenarios.

The catch block at line 627-629 swallows exceptions without verification. If the test fails for unexpected reasons, this will mask the actual cause. Consider adding a comment or logging when an exception is expected due to mocking limitations.

         try {
             sendCoinsTaskRunner.sendDirectPayment(sendRequest, paymentIntent, "TestService")
         } catch (e: Exception) {
-            // May fail due to wallet completion mocking, but verify HTTP was attempted
+            // Expected to fail due to wallet completion mocking (transaction signing)
+            // Continue to verify HTTP request was attempted
         }

678-688: Strengthen NACK response test assertion.

The catch block for non-DirectPayException does nothing (line 685-687), which means if a different exception type is thrown, the test silently passes. Consider failing explicitly for unexpected exception types.

Suggested improvement
         try {
             sendCoinsTaskRunner.sendDirectPayment(sendRequest, paymentIntent)
             // If no exception, the nack was not properly handled
         } catch (e: org.dash.wallet.common.services.DirectPayException) {
             // Expected - NACK should throw DirectPayException
             assertTrue(e.message?.contains("not acknowledged") == true)
         } catch (e: Exception) {
-            // Other exceptions may occur due to mocking
+            // Other exceptions may occur due to wallet mocking - this is acceptable
+            // but log for debugging purposes
+            log.debug("Non-DirectPayException caught (expected due to mocking): ${e.message}")
         }
wallet/src/de/schildbach/wallet/ui/send/SendCoinsViewModel.kt (1)

406-408: Remove commented-out parameter.

Dead code should be removed. If this parameter might be needed later, it can be retrieved from version control.

     private fun createSendRequest(
         mayEditAmount: Boolean,
         paymentIntent: PaymentIntent,
         signInputs: Boolean,
         forceEnsureMinRequiredFee: Boolean
-        //useGreedyAlgorithm: Boolean = true
     ): SendRequest {
wallet/src/de/schildbach/wallet/payments/SendCoinsTaskRunner.kt (3)

435-437: Consider safer null handling for wallet access.

Multiple uses of walletData.wallet!! could throw NPE if the wallet becomes null unexpectedly. Consider capturing the wallet reference at the start of the method with a null check.

Suggested improvement
     fun createSendRequest(
         mayEditAmount: Boolean,
         paymentIntent: PaymentIntent,
         signInputs: Boolean,
         forceEnsureMinRequiredFee: Boolean
     ): SendRequest {
+        val wallet = walletData.wallet ?: throw RuntimeException(WALLET_EXCEPTION_MESSAGE)
         val firstSendRequest = createSendRequest(
             mayEditAmount,
             paymentIntent,
             signInputs = true,
             forceEnsureMinRequiredFee,
             useCoinJoinGreedy = true
         )
         signSendRequest(firstSendRequest)
-        walletData.wallet!!.completeTx(firstSendRequest)
+        wallet.completeTx(firstSendRequest)

86-86: Verify MAX_NO_CHANGE_FEE threshold value.

The constant MAX_NO_CHANGE_FEE is set to Coin.valueOf(10_0000).multiply(2) which equals 200,000 satoshis (0.002 DASH). The comment is correct. This threshold determines when fees are considered "too high" for CoinJoin transactions without change.

Consider extracting the magic numbers into named constants for clarity:

private val MAX_NO_CHANGE_FEE = Coin.MILLICOIN.multiply(2) // 0.002 DASH

422-473: Complex fee-checking logic may create unnecessary transactions.

This createSendRequest overload:

  1. Creates a request with useCoinJoinGreedy = true
  2. Signs and completes it
  3. Checks for dust → potentially creates another
  4. Checks for high fees → returns either greedy or non-greedy version

The issue is that at lines 465-472, if isFeeTooHigh returns false, it creates a new SendRequest with useCoinJoinGreedy = true instead of returning the already-completed secondSendRequest. This discards the work already done.

Consider returning secondSendRequest directly when fees are acceptable:

Suggested fix
         // check for high fees when using coinjoin/greedy
         return if (isFeeTooHigh(secondSendRequest.tx)) {
             log.info("fee was found to be too high: {}", secondSendRequest.tx.fee)
             createSendRequest(
                 mayEditAmount,
                 paymentIntent,
                 signInputs,
                 forceEnsureMinRequiredFee,
                 useCoinJoinGreedy = false
             )
         } else {
-            createSendRequest(
-                mayEditAmount,
-                paymentIntent,
-                signInputs,
-                forceEnsureMinRequiredFee,
-                useCoinJoinGreedy = true
-            )
+            // Return a fresh request with the determined parameters
+            // (secondSendRequest was signed for fee estimation, caller may need unsigned)
+            if (signInputs == secondSendRequest.signInputs) {
+                secondSendRequest
+            } else {
+                createSendRequest(mayEditAmount, paymentIntent, signInputs, forceEnsureMinRequiredFee, true)
+            }
         }

@HashEngineering
HashEngineering changed the base branch from build-11.6.1 to master February 11, 2026 23:34

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@wallet/src/de/schildbach/wallet/payments/SendCoinsTaskRunner.kt`:
- Around line 497-550: The trial paths in createAssetLockSendRequest call
walletData.wallet!!.completeTx(...) without first calling signSendRequest(...),
which can cause KeyCrypterException for encrypted wallets; update both places
where completeTx is invoked for the firstSendRequest and the retry sendRequest
(the branch that builds sendRequest when checkDust(...) is true) to call
signSendRequest(firstSendRequest) / signSendRequest(sendRequest) respectively
before calling walletData.wallet!!.completeTx(...), mirroring the 4-parameter
createSendRequest behavior so AES keys are set when signInputs is true.

In `@wallet/src/de/schildbach/wallet/ui/send/PaymentProtocolViewModel.kt`:
- Around line 126-143: The isExtendedBy check in PaymentProtocolViewModel is
redundant because sendCoinsTaskRunner.fetchPaymentRequest(basePaymentIntent)
already verifies extension and throws on failure; remove the if/else branch
around sendCoinsTaskRunner.fetchPaymentRequest — directly assign
finalPaymentIntent = paymentIntent and call createBaseSendRequest(paymentIntent)
after a successful fetch, keeping the existing try/catch and
_sendRequestLiveData error handling for exceptions; reference
sendCoinsTaskRunner.fetchPaymentRequest, basePaymentIntent, isExtendedBy,
finalPaymentIntent, and createBaseSendRequest to locate and update the code (or
alternatively remove the duplicate check from
SendCoinsTaskRunner.fetchPaymentRequest if you prefer the validation to live in
the ViewModel).
🧹 Nitpick comments (6)
wallet/test/de/schildbach/wallet/FakeAnalyticsService.kt (1)

22-30: Optionally silence detekt EmptyFunctionBlock warnings with expression-body syntax.

The empty bodies are intentional for a test fake, so the detekt warnings are false positives here. You can optionally use expression bodies to avoid the noise:

♻️ Suggested tweak
 class FakeAnalyticsService : AnalyticsService {
-    override fun logEvent(event: String, params: Map<AnalyticsConstants.Parameter, Any>) {
-
-    }
+    override fun logEvent(event: String, params: Map<AnalyticsConstants.Parameter, Any>) = Unit
 
-    override fun logError(error: Throwable, details: String?) {
-
-    }
+    override fun logError(error: Throwable, details: String?) = Unit
 }
common/src/main/java/org/dash/wallet/common/util/Constants.kt (1)

70-76: Commented-out debug logging left in place.

The BuildConfig.DEBUG block is fully commented out, leaving BASIC as the only effective level — no behavioral change. Consider either removing the commented-out code (and the now-unused BuildConfig import on line 25) or uncommenting it if debug-level body logging is intended during development.

Given your preference for keeping HTTP logging available in release builds, this is just a housekeeping note.

wallet/src/de/schildbach/wallet/payments/SendCoinsTaskRunner.kt (1)

433-433: Prefer safe null handling over !! for walletData.wallet.

These four lines use walletData.wallet!! while the rest of the file consistently uses walletData.wallet ?: throw RuntimeException(WALLET_EXCEPTION_MESSAGE). Using !! loses the descriptive error message on NPE.

♻️ Example fix (apply to all four occurrences)
-        walletData.wallet!!.completeTx(firstSendRequest)
+        val wallet = walletData.wallet ?: throw RuntimeException(WALLET_EXCEPTION_MESSAGE)
+        wallet.completeTx(firstSendRequest)

Also applies to: 445-445, 512-512, 524-524

wallet/src/de/schildbach/wallet/ui/send/SendCoinsViewModel.kt (1)

406-408: Remove commented-out parameter.

The //useGreedyAlgorithm: Boolean = true line is dead code. If needed later, it can be retrieved from version control.

♻️ Proposed fix
     private fun createSendRequest(
         mayEditAmount: Boolean,
         paymentIntent: PaymentIntent,
         signInputs: Boolean,
-        forceEnsureMinRequiredFee: Boolean
-        //useGreedyAlgorithm: Boolean = true
+        forceEnsureMinRequiredFee: Boolean
     ): SendRequest {
wallet/src/de/schildbach/wallet/ui/send/PaymentProtocolViewModel.kt (2)

73-73: directPaymentAckLiveData is publicly mutable — encapsulate it.

This field exposes MutableLiveData publicly, breaking the encapsulation pattern used by _sendRequestLiveData / sendRequestLiveData in this same class. As per coding guidelines, ViewModels should use a private mutable backing field with a public immutable getter (and prefer StateFlow).

♻️ Proposed fix (LiveData pattern)
-    val directPaymentAckLiveData = MutableLiveData<Resource<Transaction>>()
+    private val _directPaymentAckLiveData = MutableLiveData<Resource<Transaction>>()
+    val directPaymentAckLiveData: LiveData<Resource<Transaction>>
+        get() = _directPaymentAckLiveData

Then update internal usages to _directPaymentAckLiveData.postValue(...).

As per coding guidelines: "Use private mutable _uiState with public immutable uiState via asStateFlow() in ViewModels."


176-199: Force-unwrapping finalPaymentIntent!! and baseSendRequest!! without guards.

If sendPayment() is called before requestPaymentRequest completes successfully, lines 183 and 185 will throw NPE with no descriptive message. Consider an early-return with an error state, or use a descriptive requireNotNull.

♻️ Proposed fix
     fun sendPayment() {
         viewModelScope.launch(Dispatchers.IO) {
             try {
-                directPaymentAckLiveData.postValue(Resource.loading(null))
+                _directPaymentAckLiveData.postValue(Resource.loading(null))
+
+                val paymentIntent = requireNotNull(finalPaymentIntent) { "finalPaymentIntent is null — was the payment request fetched?" }
+                val baseRequest = requireNotNull(baseSendRequest) { "baseSendRequest is null — was createBaseSendRequest successful?" }
 
                 val sendRequest = sendCoinsTaskRunner.createSendRequest(
                     basePaymentIntent.mayEditAmount(),
-                    finalPaymentIntent!!,
+                    paymentIntent,
                     true,
-                    baseSendRequest!!.ensureMinRequiredFee
+                    baseRequest.ensureMinRequiredFee
                 )
 
                 val transaction = sendCoinsTaskRunner.sendDirectPayment(
                     sendRequest,
-                    finalPaymentIntent!!
+                    paymentIntent
                 )

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@build.gradle`:
- Line 6: The build currently pins dashjVersion = '21.2.0-SNAPSHOT', which
breaks reproducible builds; update build.gradle to remove the SNAPSHOT
dependency by either (preferred) switching dashjVersion to the upstream released
artifact '21.2.0' once dashj publishes it (replace the dashjVersion value in
build.gradle), or (alternative) build the required dashj commit locally and
publish it to mavenLocal() then set dashjVersion to that published
artifact/version, or (short-term) add a clear TODO comment in build.gradle and
the PR description marking this as blocked on dashj releasing 21.2.0 and
documenting why the SNAPSHOT is required until then.
🧹 Nitpick comments (1)
common/src/main/java/org/dash/wallet/common/util/Constants.kt (1)

25-25: Unused BuildConfig import.

BuildConfig is imported but not referenced anywhere in this file. If it's needed for an upcoming change, consider adding it in the same commit that uses it to keep the diff clean. Otherwise this will likely be flagged by lint tools.

Comment thread build.gradle
coroutinesVersion = '1.6.4'
ok_http_version = '4.12.0'
dashjVersion = '21.1.14'
dashjVersion = '21.2.0-SNAPSHOT'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check what versions of dashj are available on Maven Central and snapshot repos

echo "=== Checking Maven Central for stable dashj releases ==="
curl -s "https://search.maven.org/solrsearch/select?q=g:org.dashj+AND+a:dashj-core&rows=10&core=gav&wt=json" 2>/dev/null | jq -r '.response.docs[] | "\(.v)"' | sort -V | tail -15

echo ""
echo "=== Checking snapshot repo for 21.2.0-SNAPSHOT metadata ==="
curl -s "https://s01.oss.sonatype.org/content/repositories/snapshots/org/dashj/dashj-core/21.2.0-SNAPSHOT/maven-metadata.xml" 2>/dev/null | head -50

echo ""
echo "=== Checking if 21.2.0 stable exists on Maven Central ==="
curl -s "https://search.maven.org/artifact/org/dashj/dashj-core/21.2.0/jar" 2>/dev/null | head -20 || echo "Not found or error occurred"

echo ""
echo "=== Listing recent 21.x versions available ==="
curl -s "https://search.maven.org/solrsearch/select?q=g:org.dashj+AND+a:dashj-core+AND+v:21*&rows=20&core=gav&wt=json" 2>/dev/null | jq -r '.response.docs[] | "\(.v)"' | sort -V

Repository: dashpay/dash-wallet

Length of output: 1040


🏁 Script executed:

#!/bin/bash
# Check the actual build.gradle file to understand the full context
echo "=== Full build.gradle content ==="
cat build.gradle

echo ""
echo "=== Checking for any local dashj build or module ==="
find . -type f -name "*.gradle" | xargs grep -l "dashj" 2>/dev/null || echo "No local dashj gradle config found"

echo ""
echo "=== Checking if dashj is built from source in this repo ==="
fd -t d dashj . --max-depth 3 2>/dev/null || echo "No dashj directory found"

Repository: dashpay/dash-wallet

Length of output: 3195


🏁 Script executed:

#!/bin/bash
# Check if 21.2.0-SNAPSHOT can be resolved and understand the PR context
echo "=== Checking git log for dashj version change context ==="
git log --oneline -20 | head -20

echo ""
echo "=== Checking git diff for context on why 21.2.0-SNAPSHOT was needed ==="
git show --stat 2>/dev/null | head -50

echo ""
echo "=== Checking if there's any documentation or comment about dashj dependency ==="
rg "21.2.0|dashj" --type md --type txt 2>/dev/null | head -20

echo ""
echo "=== Checking gradle dependency declarations in wallet/build.gradle ==="
grep -A 5 -B 5 "dashj" wallet/build.gradle 2>/dev/null || echo "Not in wallet/build.gradle"

Repository: dashpay/dash-wallet

Length of output: 6271


SNAPSHOT dependency requires upstream dashj release or alternative pinning strategy.

While 21.2.0-SNAPSHOT is indeed mutable and breaks reproducible builds, the suggestion to pin to 21.2.0 stable is not currently viable—that release doesn't exist on Maven Central (latest stable is 21.1.7). Since the PR requires new features from 21.2.0, consider one of these approaches:

  • Preferred: Work with the dashj project to release 21.2.0 or an RC (release candidate), then pin to the stable version.
  • Alternative: Pin to a specific commit hash in dashj if this project can build it locally, then publish to mavenLocal() which is already configured.
  • Short-term only: Document why 21.2.0-SNAPSHOT is required and mark this as blocking on dashj's release schedule; gate the merge until a stable version is available.
🤖 Prompt for AI Agents
In `@build.gradle` at line 6, The build currently pins dashjVersion =
'21.2.0-SNAPSHOT', which breaks reproducible builds; update build.gradle to
remove the SNAPSHOT dependency by either (preferred) switching dashjVersion to
the upstream released artifact '21.2.0' once dashj publishes it (replace the
dashjVersion value in build.gradle), or (alternative) build the required dashj
commit locally and publish it to mavenLocal() then set dashjVersion to that
published artifact/version, or (short-term) add a clear TODO comment in
build.gradle and the PR description marking this as blocked on dashj releasing
21.2.0 and documenting why the SNAPSHOT is required until then.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@wallet/src/de/schildbach/wallet/payments/SendCoinsTaskRunner.kt`:
- Around line 193-222: The Response from Constants.HTTP_CLIENT.call in
fetchPaymentRequest is not closed; wrap the Response in a Kotlin use block
(e.g., response.use { ... }) so the response and its body are always closed even
if ensureSuccessful() or PaymentIntentParser.parse() throws; inside that block
read headers and obtain the body byteStream (or better: use response.body?.use {
stream -> PaymentIntentParser.parse(stream, contentType) }) and perform the
trust check against basePaymentIntent there, ensuring both the Response and
response.body are properly closed/releases to avoid connection pool leaks.
- Around line 744-750: The isFeeTooHigh override can NPE because Transaction.fee
is nullable; update SendCoinsTaskRunner.isFeeTooHigh to defensively handle null
by reading tx.fee into a local (e.g., fee) and returning false (or a safe
default) if fee is null, then perform the existing coinJoinSend && fee >
MAX_NO_CHANGE_FEE check; reference symbols: isFeeTooHigh, Transaction.fee,
coinJoinSend, MAX_NO_CHANGE_FEE, SendPaymentService.
🧹 Nitpick comments (2)
wallet/src/de/schildbach/wallet/payments/SendCoinsTaskRunner.kt (2)

86-86: Simplify MAX_NO_CHANGE_FEE initialization for readability.

Coin.valueOf(10_0000).multiply(2) uses non-standard underscore grouping and an unnecessary .multiply(2). Consider expressing the value directly:

Suggested change
-        private val MAX_NO_CHANGE_FEE = Coin.valueOf(10_0000).multiply(2) // 0.002 DASH
+        private val MAX_NO_CHANGE_FEE = Coin.valueOf(200_000) // 0.002 DASH

497-552: Significant duplication with createSendRequest(4-param) — consider extracting shared trial logic.

The trial-run → dust-check → fee-check → return-final pattern in this 5-param createAssetLockSendRequest (lines 497–552) is structurally identical to the 4-param createSendRequest (lines 419–470). Any future bug fix or behavioral change to one must be mirrored in the other.

Consider extracting the shared logic into a private helper that accepts a factory lambda for creating the underlying request:

private fun <T> createRequestWithGreedyFallback(
    mayEditAmount: Boolean,
    signInputs: Boolean,
    forceEnsureMinRequiredFee: Boolean,
    createReq: (Boolean, Boolean, Boolean, Boolean) -> SendRequest
): SendRequest { /* shared trial/dust/fee logic */ }

Comment on lines +193 to +222
suspend fun fetchPaymentRequest(basePaymentIntent: PaymentIntent): PaymentIntent = withContext(Dispatchers.IO) {
val requestUrl = basePaymentIntent.paymentRequestUrl
if (requestUrl != null) {
?: throw IllegalArgumentException("Payment intent must have a payment request URL")

log.info("requesting payment request from {}", requestUrl)
val timer = AnalyticsTimer(analyticsService, log, AnalyticsConstants.Process.PROCESS_BIP7O_GET_PAYMENT_REQUEST)
val request = buildOkHttpPaymentRequest(requestUrl)
val response = Constants.HTTP_CLIENT.call(request)
response.ensureSuccessful()
val request = buildOkHttpPaymentRequest(requestUrl)
val response = Constants.HTTP_CLIENT.call(request)
response.ensureSuccessful()
requestUrl.toUri().host?.let {
timer.logTiming(hashMapOf(AnalyticsConstants.Parameter.ARG1 to it))
}
log.info("payment request received")

val contentType = response.header("Content-Type")
val byteStream = response.body?.byteStream()
val contentType = response.header("Content-Type")
val byteStream = response.body?.byteStream()

if (byteStream == null || contentType.isNullOrEmpty()) {
throw IOException("Null response for the payment request: $requestUrl")
}
if (byteStream == null || contentType.isNullOrEmpty()) {
throw IOException("Null response for the payment request: $requestUrl")
}

val paymentIntent = PaymentIntentParser.parse(byteStream, contentType)
val paymentIntent = PaymentIntentParser.parse(byteStream, contentType)

if (!basePaymentIntent.isExtendedBy(paymentIntent, true)) {
log.info("BIP72 trust check failed")
throw IllegalStateException("BIP72 trust check failed: $requestUrl")
}
if (!basePaymentIntent.isExtendedBy(paymentIntent, true)) {
log.info("BIP72 trust check failed")
throw IllegalStateException("BIP72 trust check failed: $requestUrl")
}

paymentIntent
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

OkHttp Response body is never closed — potential connection pool leak.

The response returned from Constants.HTTP_CLIENT.call(request) is never closed. If ensureSuccessful() throws, or after PaymentIntentParser.parse consumes the stream, the underlying connection is not returned to the pool. Use response.use { } or response.body?.use { } to ensure cleanup.

Suggested fix
     suspend fun fetchPaymentRequest(basePaymentIntent: PaymentIntent): PaymentIntent = withContext(Dispatchers.IO) {
         val requestUrl = basePaymentIntent.paymentRequestUrl
             ?: throw IllegalArgumentException("Payment intent must have a payment request URL")
 
         log.info("requesting payment request from {}", requestUrl)
         val timer = AnalyticsTimer(analyticsService, log, AnalyticsConstants.Process.PROCESS_BIP7O_GET_PAYMENT_REQUEST)
         val request = buildOkHttpPaymentRequest(requestUrl)
-        val response = Constants.HTTP_CLIENT.call(request)
-        response.ensureSuccessful()
-        requestUrl.toUri().host?.let {
-            timer.logTiming(hashMapOf(AnalyticsConstants.Parameter.ARG1 to it))
-        }
-        log.info("payment request received")
-
-        val contentType = response.header("Content-Type")
-        val byteStream = response.body?.byteStream()
-
-        if (byteStream == null || contentType.isNullOrEmpty()) {
-            throw IOException("Null response for the payment request: $requestUrl")
-        }
-
-        val paymentIntent = PaymentIntentParser.parse(byteStream, contentType)
+        Constants.HTTP_CLIENT.call(request).use { response ->
+            response.ensureSuccessful()
+            requestUrl.toUri().host?.let {
+                timer.logTiming(hashMapOf(AnalyticsConstants.Parameter.ARG1 to it))
+            }
+            log.info("payment request received")
+
+            val contentType = response.header("Content-Type")
+            val byteStream = response.body?.byteStream()
+
+            if (byteStream == null || contentType.isNullOrEmpty()) {
+                throw IOException("Null response for the payment request: $requestUrl")
+            }
+
+            val paymentIntent = PaymentIntentParser.parse(byteStream, contentType)
 
-        if (!basePaymentIntent.isExtendedBy(paymentIntent, true)) {
-            log.info("BIP72 trust check failed")
-            throw IllegalStateException("BIP72 trust check failed: $requestUrl")
-        }
+            if (!basePaymentIntent.isExtendedBy(paymentIntent, true)) {
+                log.info("BIP72 trust check failed")
+                throw IllegalStateException("BIP72 trust check failed: $requestUrl")
+            }
 
-        paymentIntent
+            paymentIntent
+        }
     }
🤖 Prompt for AI Agents
In `@wallet/src/de/schildbach/wallet/payments/SendCoinsTaskRunner.kt` around lines
193 - 222, The Response from Constants.HTTP_CLIENT.call in fetchPaymentRequest
is not closed; wrap the Response in a Kotlin use block (e.g., response.use { ...
}) so the response and its body are always closed even if ensureSuccessful() or
PaymentIntentParser.parse() throws; inside that block read headers and obtain
the body byteStream (or better: use response.body?.use { stream ->
PaymentIntentParser.parse(stream, contentType) }) and perform the trust check
against basePaymentIntent there, ensuring both the Response and response.body
are properly closed/releases to avoid connection pool leaks.

@abaranouski abaranouski left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

was successfully tested

@HashEngineering
HashEngineering merged commit 90f6bc9 into master Feb 17, 2026
2 checks passed
@HashEngineering
HashEngineering deleted the feat/coinjoin-no-change branch June 26, 2026 06:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants