Repository navigation
feat: don't return change with CoinJoin Send unless there is a high fee - #1460
Conversation
📝 WalkthroughWalkthroughAdds 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
Sequence DiagramsequenceDiagram
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
Estimated Code Review Effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
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-unusedFirebaseAnalyticsServiceImplimport on line 57.🧹 Proposed cleanup
-import org.dash.wallet.common.services.analytics.FirebaseAnalyticsServiceImpl-// `@Binds` -// abstract fun bindAnalyticsService( -// analyticsService: FirebaseAnalyticsServiceImpl -// ): AnalyticsServicedocs/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.,
textorplaintext) 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.
FirebaseAppis 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)ande.printStackTrace()are debug artifacts. Consider using structured logging or removing them. Additionally, catching a broadExceptionand 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-
DirectPayExceptiondoes 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_FEEis set toCoin.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
createSendRequestoverload:
- Creates a request with
useCoinJoinGreedy = true- Signs and completes it
- Checks for dust → potentially creates another
- Checks for high fees → returns either greedy or non-greedy version
The issue is that at lines 465-472, if
isFeeTooHighreturns false, it creates a newSendRequestwithuseCoinJoinGreedy = trueinstead of returning the already-completedsecondSendRequest. This discards the work already done.Consider returning
secondSendRequestdirectly 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) + } }
There was a problem hiding this comment.
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 detektEmptyFunctionBlockwarnings 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.DEBUGblock is fully commented out, leavingBASICas the only effective level — no behavioral change. Consider either removing the commented-out code (and the now-unusedBuildConfigimport 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!!forwalletData.wallet.These four lines use
walletData.wallet!!while the rest of the file consistently useswalletData.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 = trueline 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:directPaymentAckLiveDatais publicly mutable — encapsulate it.This field exposes
MutableLiveDatapublicly, breaking the encapsulation pattern used by_sendRequestLiveData/sendRequestLiveDatain this same class. As per coding guidelines, ViewModels should use a private mutable backing field with a public immutable getter (and preferStateFlow).♻️ Proposed fix (LiveData pattern)
- val directPaymentAckLiveData = MutableLiveData<Resource<Transaction>>() + private val _directPaymentAckLiveData = MutableLiveData<Resource<Transaction>>() + val directPaymentAckLiveData: LiveData<Resource<Transaction>> + get() = _directPaymentAckLiveDataThen update internal usages to
_directPaymentAckLiveData.postValue(...).As per coding guidelines: "Use private mutable
_uiStatewith public immutableuiStateviaasStateFlow()in ViewModels."
176-199: Force-unwrappingfinalPaymentIntent!!andbaseSendRequest!!without guards.If
sendPayment()is called beforerequestPaymentRequestcompletes successfully, lines 183 and 185 will throw NPE with no descriptive message. Consider an early-return with an error state, or use a descriptiverequireNotNull.♻️ 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 )
There was a problem hiding this comment.
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: UnusedBuildConfigimport.
BuildConfigis 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.
| coroutinesVersion = '1.6.4' | ||
| ok_http_version = '4.12.0' | ||
| dashjVersion = '21.1.14' | ||
| dashjVersion = '21.2.0-SNAPSHOT' |
There was a problem hiding this comment.
🧩 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 -VRepository: 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.0or 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-SNAPSHOTis 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.
There was a problem hiding this comment.
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: SimplifyMAX_NO_CHANGE_FEEinitialization 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 withcreateSendRequest(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-paramcreateSendRequest(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 */ }
| 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 | ||
| } |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
was successfully tested
Issue being fixed or feature implemented
Related PR's and Dependencies
Screenshots / Videos
How Has This Been Tested?
Checklist:
Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Tests
Chores