Skip to content

feat/txmetadata update #1344

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Feb 5, 2025
Merged

Conversation

HashEngineering
Copy link
Collaborator

@HashEngineering HashEngineering commented Feb 3, 2025

Issue being fixed or feature implemented

Related PR's and Dependencies

dashpay/kotlin-platform#22

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

  • Chores
    • Updated backend dependency versions.
  • New Features
    • Introduced enhanced configuration for transaction record details, supporting dynamic transaction metadata.
  • Refactor
    • Streamlined transaction processing with differentiated handling for privacy-focused transactions and improved error handling for smoother synchronization.

@HashEngineering HashEngineering self-assigned this Feb 3, 2025
Copy link
Contributor

coderabbitai bot commented Feb 3, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request updates the build version, refines transaction metadata handling, and adds new configuration options. The build script version has been updated to a snapshot release. A new flag for metadata support is introduced in the constants file, and a counting method is added to the transaction metadata cache DAO. The transaction metadata provider now distinguishes CoinJoin transactions and enhances error handling. Additionally, the platform synchronization service has been refactored with new constants, method adjustments, and updated error handling around metadata publishing.

Changes

File(s) Change Summary
build.gradle Updated dppVersion from "1.7.1" to "1.7.2-SNAPSHOT".
wallet/.../Constants.java Added new public static boolean SUPPORTS_TXMETADATA with build-specific initialization; clarified existing SUPPORTS_PLATFORM and SUPPORTS_INVITES with comments.
wallet/.../database/dao/TransactionMetadataChangeCacheDao.kt Added a new suspend fun count(): Int method to count entries in the transaction metadata cache.
wallet/.../service/WalletTransactionMetadataProvider.kt Introduced CoinJoinTransactionType import; added isCoinJoinTx flag to exclude CoinJoin transactions during metadata insertion; enhanced error handling with a try-catch around exchange rate parsing.
wallet/.../service/platform/PlatformSyncService.kt Replaced import from TxMetadataItem to TxMetadataDocument; added constants (MIN_TXMETADATA_BATCHSIZE, MAX_TXMETADATA_BATCHSIZE, MIN_TXMETADATA_DURATION); refactored methods (including making publishTransactionMetadata suspend) with checks using SUPPORTS_TXMETADATA and enhanced error handling.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant PlatformSyncService
    participant Database

    Client->>PlatformSyncService: initSync()
    PlatformSyncService->>PlatformSyncService: maybePublishChangeCache()
    alt Metadata Supported
        PlatformSyncService->>Database: Fetch metadata items
        Database-->>PlatformSyncService: Metadata list
        PlatformSyncService->>PlatformSyncService: publishTransactionMetadata (suspend)
        PlatformSyncService-->>Client: Metadata published
    else Metadata Not Supported
        PlatformSyncService-->>Client: Skip publishing metadata
    end
Loading
sequenceDiagram
    participant Transaction
    participant WalletTransactionMetadataProvider
    participant ChangeCache

    Transaction->>WalletTransactionMetadataProvider: insertTransactionMetadata()
    WalletTransactionMetadataProvider->>WalletTransactionMetadataProvider: Check if CoinJoin (isCoinJoinTx)
    alt Is CoinJoin Transaction
        WalletTransactionMetadataProvider-->>Transaction: Skip metadata insertion
    else Non-CoinJoin Transaction
        WalletTransactionMetadataProvider->>ChangeCache: Insert metadata
        ChangeCache-->>WalletTransactionMetadataProvider: Acknowledgement
    end
Loading

Poem

I'm a rabbit hacking through the code,
Leaping over versions on the road.
Metadata now flows with a twist and cheer,
CoinJoin dodged, with errors clear.
Hopping proudly in refactored delight,
Celebrating change under the moonlight! 🥕🐇


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@HashEngineering HashEngineering marked this pull request as ready for review February 4, 2025 16:34
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt (2)

184-197: Consider validating the random cutoff range.
Currently, the range relies on CUTOFF_MIN < CUTOFF_MAX. If swapped (due to a future code change), it may produce an illegal range. A quick assertion (e.g., check(CUTOFF_MIN < CUTOFF_MAX)) could help prevent silent errors.

 val everythingBeforeTimestamp = random.nextLong(
-    now - CUTOFF_MAX.inWholeMilliseconds,
-    now - CUTOFF_MIN.inWholeMilliseconds
+    (now - CUTOFF_MAX.inWholeMilliseconds).also { check(CUTOFF_MAX > CUTOFF_MIN) },
+    (now - CUTOFF_MIN.inWholeMilliseconds)
 )

1012-1016: Consider removing or restoring this commented-out batch-size logic.
If you intend to publish all changes immediately, remove these lines. Otherwise, reintroduce them to maintain a minimum batch size threshold.

-//        if (changedItems.size < MIN_TXMETADATA_BATCHSIZE) {
-//            log.info("not enough tx metadata changes before this time")
-//            return
-//}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2abfa75 and 7b6c424.

📒 Files selected for processing (5)
  • build.gradle (1 hunks)
  • wallet/src/de/schildbach/wallet/Constants.java (3 hunks)
  • wallet/src/de/schildbach/wallet/database/dao/TransactionMetadataChangeCacheDao.kt (1 hunks)
  • wallet/src/de/schildbach/wallet/service/WalletTransactionMetadataProvider.kt (3 hunks)
  • wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt (21 hunks)
🧰 Additional context used
🪛 detekt (1.23.7)
wallet/src/de/schildbach/wallet/service/WalletTransactionMetadataProvider.kt

[warning] 369-369: The caught exception is swallowed. The original exception could be lost.

(detekt.exceptions.SwallowedException)

wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt

[warning] 934-934: The caught exception is swallowed. The original exception could be lost.

(detekt.exceptions.SwallowedException)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (13)
build.gradle (1)

7-7: Snapshot Version Update

The dppVersion variable has been updated to "1.7.2-SNAPSHOT", indicating a shift to a development snapshot. Ensure that this version update is consistent with the new transaction metadata features and that related dependencies or integrations are adjusted accordingly if needed.

wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt (8)

72-72: No issues with the new import for TxMetadataDocument.


79-79: No issues with the new import for TxMetadataItem.


144-146: New constants for transaction metadata look consistent.
The naming and usage align well with Kotlin idioms.


180-182: Great addition to trigger metadata publishing asynchronously.
This approach leverages coroutines effectively to avoid blocking.


703-705: Good guard check for SUPPORTS_TXMETADATA.
Prevents needless operations if the feature is disabled.


970-970: Suspending the publishTransactionMetadata function is a good approach.
This ensures non-blocking operations when interacting with the platform.


995-996: Potential concurrency concern when calculating keyIndex.
If multiple calls run in parallel, counts may change before publishing. Consider a transactional approach if strict ordering is important.


999-1002: Good guard check for SUPPORTS_TXMETADATA.
This code remains consistent with checks in other methods.

wallet/src/de/schildbach/wallet/database/dao/TransactionMetadataChangeCacheDao.kt (1)

134-136: New count() method is straightforward and appropriate.
No issues observed. The COUNT(*) usage is correct for counting rows.

wallet/src/de/schildbach/wallet/Constants.java (1)

63-67: New SUPPORTS_TXMETADATA variable aligns with existing flags.
This is consistent with how build-specific features are toggled.

wallet/src/de/schildbach/wallet/service/WalletTransactionMetadataProvider.kt (2)

31-31: LGTM!

The import of CoinJoinTransactionType is correctly added to support the new CoinJoin transaction handling.


135-140: Good addition of CoinJoin transaction handling.

The code correctly excludes CoinJoin transactions from the metadata change cache, which is important for privacy and transaction tracking. The implementation uses a clear when-expression to determine the transaction type.

Comment on lines 932 to 936
try {
giftCard.barcodeFormat = BarcodeFormat.valueOf(barcodeFormat)
} catch (e: IllegalArgumentException) {
// ignore invalid barcode format
}
Copy link
Contributor

@coderabbitai coderabbitai bot Feb 4, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid swallowing the IllegalArgumentException silently.
Even a minimal log can help with troubleshooting invalid barcode formats.

 try {
     giftCard.barcodeFormat = BarcodeFormat.valueOf(barcodeFormat)
 } catch (e: IllegalArgumentException) {
-    // ignore invalid barcode format
+    log.warn("Invalid barcode format: {}", barcodeFormat, e)
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
giftCard.barcodeFormat = BarcodeFormat.valueOf(barcodeFormat)
} catch (e: IllegalArgumentException) {
// ignore invalid barcode format
}
try {
giftCard.barcodeFormat = BarcodeFormat.valueOf(barcodeFormat)
} catch (e: IllegalArgumentException) {
log.warn("Invalid barcode format: {}", barcodeFormat, e)
}
🧰 Tools
🪛 detekt (1.23.7)

[warning] 934-934: The caught exception is swallowed. The original exception could be lost.

(detekt.exceptions.SwallowedException)

Copy link
Member

Choose a reason for hiding this comment

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

This suggestion could be useful too, in case if we have some systematic issue with barcode formats.

Copy link
Contributor

Choose a reason for hiding this comment

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

@Syn-McJ Agreed! I'll add this as a learning to ensure we maintain proper logging for invalid barcode formats across the codebase.


✏️ Learnings added
Learnt from: Syn-McJ
PR: dashpay/dash-wallet#1344
File: wallet/src/de/schildbach/wallet/service/platform/PlatformSyncService.kt:932-936
Timestamp: 2025-02-05T05:24:26.720Z
Learning: Invalid barcode formats should be logged with log.warn() instead of being silently ignored to help identify systematic issues in production.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

Comment on lines 362 to 371
try {
tx.exchangeRate = org.bitcoinj.utils.ExchangeRate(
Fiat.parseFiat(
metadata.currencyCode,
metadata.rate
)
)
)
} catch (e: Exception) {
log.info("metadata.rate: {}", metadata)
}
Copy link
Contributor

@coderabbitai coderabbitai bot Feb 4, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve exception handling for exchange rate parsing.

The caught exception is being swallowed with only a log message. This could hide important issues during exchange rate parsing.

Consider either:

  1. Re-throwing the exception after logging
  2. Adding more detailed error information to the log
 try {
     tx.exchangeRate = org.bitcoinj.utils.ExchangeRate(
         Fiat.parseFiat(
             metadata.currencyCode,
             metadata.rate
         )
     )
 } catch (e: Exception) {
-    log.info("metadata.rate: {}", metadata)
+    log.error("Failed to parse exchange rate for metadata: {}. Error: {}", metadata, e.message, e)
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
tx.exchangeRate = org.bitcoinj.utils.ExchangeRate(
Fiat.parseFiat(
metadata.currencyCode,
metadata.rate
)
)
)
} catch (e: Exception) {
log.info("metadata.rate: {}", metadata)
}
try {
tx.exchangeRate = org.bitcoinj.utils.ExchangeRate(
Fiat.parseFiat(
metadata.currencyCode,
metadata.rate
)
)
} catch (e: Exception) {
log.error("Failed to parse exchange rate for metadata: {}. Error: {}", metadata, e.message, e)
}
🧰 Tools
🪛 detekt (1.23.7)

[warning] 369-369: The caught exception is swallowed. The original exception could be lost.

(detekt.exceptions.SwallowedException)

Copy link
Member

Choose a reason for hiding this comment

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

This is a good suggestion. Info log that says "metadata.rate ..." might be not very clear.

Copy link
Contributor

Choose a reason for hiding this comment

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

@Syn-McJ Thanks for confirming! I'll update the log message to be more descriptive and include the error details. This will make debugging exchange rate parsing issues much easier.

(`°ω°)⊃━☆゚.*・。゚


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

Copy link
Member

@Syn-McJ Syn-McJ left a comment

Choose a reason for hiding this comment

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

Looks good. Some coderabbit suggestions make sense to implement.

Comment on lines 362 to 371
try {
tx.exchangeRate = org.bitcoinj.utils.ExchangeRate(
Fiat.parseFiat(
metadata.currencyCode,
metadata.rate
)
)
)
} catch (e: Exception) {
log.info("metadata.rate: {}", metadata)
}
Copy link
Member

Choose a reason for hiding this comment

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

This is a good suggestion. Info log that says "metadata.rate ..." might be not very clear.

Comment on lines 932 to 936
try {
giftCard.barcodeFormat = BarcodeFormat.valueOf(barcodeFormat)
} catch (e: IllegalArgumentException) {
// ignore invalid barcode format
}
Copy link
Member

Choose a reason for hiding this comment

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

This suggestion could be useful too, in case if we have some systematic issue with barcode formats.

@HashEngineering HashEngineering changed the base branch from master to feature-txmetadata February 5, 2025 19:00
@HashEngineering HashEngineering merged commit 8b7aec6 into feature-txmetadata Feb 5, 2025
3 checks passed
@Syn-McJ Syn-McJ deleted the feat/txmetadata-update branch April 2, 2025 05:11
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