Update preactivity metadata and transfer activity handling - #476

Merged
ovitrif merged 7 commits into
masterfrom
use-preactivity-metadata
Nov 24, 2025
Merged

Update preactivity metadata and transfer activity handling#476
ovitrif merged 7 commits into
masterfrom
use-preactivity-metadata

Conversation

@ben-kaufman

@ben-kaufmanben-kaufman commented Nov 21, 2025

Copy link
Copy Markdown
Contributor

This PR migrates the tag metadata system from Room database to bitkit-core library's PreActivityMetadata system and improves transfer activity handling throughout the app.

Similar to: synonymdev/bitkit-ios#219synonymdev/bitkit-ios#226synonymdev/bitkit-ios#229

Description

Migration from Room TagMetadata to PreActivityMetadata:

  • Removed Room-based tag metadata storage (TagMetadataDao, TagMetadataEntity, and extensions)
  • Created new PreActivityMetadataRepo that interfaces with CoreService.activity for metadata management
  • PreActivityMetadata now stores more information including payment hash, txId, address, receive/transfer flags, fee rate, and channel ID
  • All metadata operations now go through the core library instead of direct database access
  • Database schema updated to version 5

Enhanced Transfer Activity Handling:

  • Improved tracking of transfer activities (channel opens/closes, LSP orders) using isTransfer flag in PreActivityMetadata
  • Updated ActivityRepo to properly handle transfer metadata when syncing activities
  • Enhanced WalletRepo with better pre-activity metadata integration for transfers
  • CoreService now provides activity service methods for metadata management
  • Added transfer-specific UI indicators and improved activity detail display for transfers

Testing Focus Areas:

  1. Tag Management:

    • Add/remove tags to transactions and payments
    • Verify tags persist across app restarts
    • Test tag backup/restore functionality
  2. Transfer Activities:

    • Create channel orders and verify they appear as "Transfer to Spending"
    • Open manual channels and check activity labeling
    • Close channels (cooperative/force) and verify "Transfer to Savings" display
    • Confirm transfer activities show correct metadata in detail view
  3. Activity Detail Screen:

    • View various activity types (onchain, lightning, transfers)
    • Check that all metadata displays correctly
    • Verify transfer-specific UI elements appear for transfer activities

Fixes#322

@ben-kaufman
ben-kaufmanforce-pushed the use-preactivity-metadata branch from f781983 to 9ee1001CompareNovember 21, 2025 19:03
@jvsena42

Copy link
Copy Markdown
Member

Starting review

@jvsena42

jvsena42 commented Nov 24, 2025

Copy link
Copy Markdown
Member

@ben-kaufman please add this issue to the description if the PR solves it
#322

Comment threadapp/src/main/java/to/bitkit/repositories/PreActivityMetadataRepo.kt Outdated

@jvsena42jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Tested:

  • Install over an old version ✅
  • reset and recover -> should recover tags ❌
tag-not-applyed.webm
  • Close channel -> should display transfer activity ✅
  • Open channel with external node -> should display transfer activity

onChain

onchain-receive.webm
  • Scan qr -> attach tag -> send -> Activity has tags ✅

Lighting

  • Create invoice -> attach tag -> receive payment -> Activity has tags ✅
  • Scan qr -> attach tag -> send -> Activity has tags ✅

@ben-kaufman

ben-kaufman commented Nov 24, 2025

Copy link
Copy Markdown
ContributorAuthor

reset and recover -> should recover tags ❌

This actually shouldn't be related to this PR, since changes here are only about pre-activity, but tags in existing activities are saved in the activity itself. I'll check the issue though but maybe better in another PR.

Create invoice -> attach tag -> receive payment ->#322

Hmm this seems to not happen consistently, checking.

@ben-kaufman

Copy link
Copy Markdown
ContributorAuthor

@jvsena42 issue with onchain invoice should be fixed now

@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@ben-kaufman

Copy link
Copy Markdown
ContributorAuthor

@jvsena42 I opened #479 which fixes the backup and restore issue.

@jvsena42jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Retested the two failing points

@ovitrifovitrif left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Awesome work!

Couldn't find any issue neither in code nor in my tests.

My Tests:

  • tag existing sent and received activity for onchain and for LN 🟢
  • tag LN and Onchain during send 🟢
  • add tags to LN and Onchain during receive, then scan with iOS & receive the payments 🟢
  • backup, wipe & restore 🟢
  • transfer to savings activity 🟢
  • check lightning connections list & detail 🟢
  • transfer to spending activity 🟢
  • re-check lightning connections list & detail 🟢
  • backup, wipe & restore: recheck connections, tags, activity 🟢
  • open manual channel ⚫ couldn't test, encountered issues connecting to my LND peer in bitkit-docker 🤷🏻

@claude

claudeBot commented Nov 24, 2025

Copy link
Copy Markdown
Contributor

Pull Request Review: Tag Metadata Migration to PreActivityMetadata

Overview

This PR successfully migrates tag metadata from Room database to the bitkit-core PreActivityMetadata system and enhances transfer activity handling. The code quality is generally good with comprehensive test coverage (+623 lines of new tests). However, I've identified several issues that should be addressed before merging.

⚠️ Critical Issues

1. Race Condition in Tag Migration (ActivityRepo.kt:327-365)

Location: replaceActivity method

Issue: Tags are migrated but if addTagsToActivity fails, the error is silently ignored:

val tags = coreService.activity.tags(activityIdToDelete)
addTagsToActivity(activityId = id, tags = tags) // Failure ignored!
markActivityAsRemovedFromMempool(activityIdToDelete).onFailure { e ->// ... error handling
}
Result.success(Unit) // Returns success even if tags failed

Impact: Tags can be silently lost during activity replacements.

Fix: Check the result and handle failures:

addTagsToActivity(activityId = id, tags = tags).onFailure { e ->Logger.error("Failed to migrate tags from $activityIdToDelete to $id", e, context =TAG)
// Consider whether this should fail the entire operation
}

2. N+1 Query Problem in Address Lookup (CoreService.kt:486-495)

Location: findAddressInPreActivityMetadata

Issue: Makes a database query for EACH output in a transaction:

for (output in txDetails.vout) {
val address = output.scriptpubkey_address ?:continueval metadata = coreService.activity.getPreActivityMetadata(
searchKey = address, searchByAddress =true
) // Query per output!
}

Impact: Significant performance degradation for transactions with many outputs.

Fix: Implement batch lookup:

privatesuspendfunfindAddressInPreActivityMetadata(txDetails:TxDetails): String? {
val addresses = txDetails.vout.mapNotNull { it.scriptpubkey_address }
if (addresses.isEmpty()) returnnull// Add batch query method to core serviceval allMetadata = coreService.activity.getPreActivityMetadataByAddresses(addresses)
return addresses.firstOrNull { address ->
allMetadata[address]?.isReceive ==true
}
}

3. Performance Issue in Replacement Transaction Marking (CoreService.kt:661-703)

Location: markReplacementTransactionsAsRemoved

Issue: Fetches ALL onchain activities and iterates through them:

val allActivities = getActivities(
filter =ActivityFilter.ONCHAIN,
limit =UInt.MAX_VALUE// All activities!
)

Impact: Very slow for wallets with many transactions; could cause ANR.

Fix: Add database index on boostTxIds or implement a direct query to find activities where boostTxIds contains the original transaction ID.

🐛 High Priority Bugs

4. Race Condition in Channel State Reads (ActivityRepo.kt:143-183)

Issue: Channel state is read multiple times without synchronization:

// Read 1:val channels = lightningRepo.lightningState.value.channels
// ... later in findOpenChannelForTransaction ...// Read 2:val orders = blocktankRepo.blocktankState.value.orders
// ... later in findClosedChannelForTransaction ...// Read 3:val closedChannels = getClosedChannels(SortDirection.DESC).getOrNull()

Impact: If channel state changes between reads, could match wrong channels or miss matches entirely.

Fix: Snapshot all state at the start of findChannelsForPayments.

5. Tag Migration Data Loss (WalletRepo.kt:98-121)

Issue: Tags are read from old payment ID, but old metadata is deleted before confirming new metadata is saved:

val tagsToMigrate =/* ... get from old payment ID ... */
clearBip21State() // Deletes old metadata here// ... operations that could fail ...
persistPreActivityMetadata(newPaymentId, tagsToMigrate, newBip21Url) // Could fail

Impact: Tags lost if any error occurs between clearing and persisting.

Fix: Only delete old metadata after confirming new metadata is successfully saved.

6. Timestamp Edge Case Handling (ActivityRepo.kt:391-394)

Issue: Null timestamp defaults to 0, which always triggers boost:

if ((newOnChainActivity.v1.updatedAt ?:0u) > pendingBoostActivity.updatedAt) {
cacheStore.removeActivityFromPendingBoost(pendingBoostActivity)
return@onSuccess
}

Impact: Activities with null updatedAt will always be boosted.

Fix: Handle null explicitly:

val activityUpdatedAt = newOnChainActivity.v1.updatedAt
if (activityUpdatedAt !=null&& activityUpdatedAt > pendingBoostActivity.updatedAt) {
cacheStore.removeActivityFromPendingBoost(pendingBoostActivity)
return@onSuccess
}

🔒 Security Concerns

7. Input Validation Missing (PreActivityMetadataRepo.kt, WalletRepo.kt)

Issue: Payment IDs and tags accepted without validation.

Risk: Data integrity issues; potential XSS if tags displayed in web views.

Fix: Add validation:

privatefunvalidatePaymentId(id:String): Boolean {
return id.isNotBlank() && id.length <=256&& id.matches(Regex("[a-zA-Z0-9]+"))
}
privatefunsanitizeTag(tag:String): String {
return tag.trim()
.take(50) // Max length
.replace(Regex("[^a-zA-Z0-9\\s-_]"), "")
}

8. Sensitive Data in Logs

Issue: Payment hashes, addresses, and amounts logged at INFO/DEBUG level throughout.

Example: CoreService.kt:389, PreActivityMetadataRepo.kt:146

Risk: Privacy exposure if logs are collected/shared.

Fix: Use VERBOSE level for sensitive data; truncate payment hashes: paymentHash.take(8)...

📝 Code Quality Issues

9. Complex Nested Logic (ActivityRepo.kt:143-166)

Issue: findOpenChannelForTransaction has three return paths with similar null returns but different meanings:

channels.firstOrNull { channel ->... }?.channelId
?:run {
val matchingOrder = orders.firstOrNull { ... } ?:returnnullval orderChannel = matchingOrder.channel ?:returnnull
channels.firstOrNull { ... }?.channelId
}

Recommendation: Extract to named functions and add logging for each path to improve debuggability.

10. Silent Error Swallowing (WalletRepo.kt:132-138)

Issue: Payment hash extraction failures silently return null:

val paymentHash = runCatching {
when (val decoded = decode(bip21Url)) {
isScanner.Lightning-> decoded.invoice.paymentHash.toHex()
isScanner.OnChain-> decoded.extractLightningHash()
else->null
}
}.getOrNull() // Error swallowed

Recommendation: Log failures to help diagnose BIP21 generation issues.

11. Inconsistent Concurrency Strategy (CoreService.kt:382-401)

Issue: Chunks processed sequentially, but payments within chunks processed in parallel:

payments.chunked(CHUNK_SIZE).forEach { chunk ->// Sequential
chunk.map { payment ->
async { ... } // Parallel
}.awaitAll()
}

Recommendation: Document why this hybrid approach is needed, or simplify by fully parallelizing if order doesn't matter.

✅ Test Coverage Gaps

Missing Tests:

  1. Concurrent operations: Multiple simultaneous tag additions/removals
  2. Channel matching: Tests with various channel states and edge cases
  3. Tag migration failures: Partial failures (old deleted, new creation fails)
  4. Performance: Large datasets (1000+ activities, 100+ channels)
  5. Integration: End-to-end flows across PreActivityMetadataRepo → ActivityRepo → WalletRepo
  6. Time edge cases: Extreme timestamp values (far future, null timestamps)

🎯 Recommendations

Before Merging:

  1. ✅ Fix tag migration race condition (Android - Project setup #1)
  2. ✅ Implement batch address lookup (POC wake2pay from notification #2)
  3. ✅ Optimize replacement transaction marking (Android - Migrate to ldk-node #3)
  4. ✅ Add input validation (Setup Keychain #7)
  5. ✅ Fix timestamp edge case handling (Migrate channels from LDK to ldk-node #6)

High Priority:

  1. Fix channel matching race conditions (Migrate to ldk-node #4)
  2. Fix tag migration data loss (Android - LDK state & Slashtags metadata #5)
  3. Add proper error logging for silent failures (chore: Merge BT notifications changes from deps/bdk-1.0 to master #10)
  4. Reduce sensitive data in logs (BDK 1.0.0-alpha.11 #8)

Medium Priority:

  1. Refactor complex nested logic (Blocktank Push Notifications #9)
  2. Document concurrency strategy (Business Logic Data Modeling #11)
  3. Add missing test coverage
  4. Consider adding database indexes for boostTxIds

📊 Overall Assessment

Code Quality: ⭐⭐⭐⭐ (4/5) - Well-structured with good separation of concerns

Test Coverage: ⭐⭐⭐⭐ (4/5) - Comprehensive unit tests, needs more integration tests

Performance: ⭐⭐⭐ (3/5) - Several potential bottlenecks identified

Security: ⭐⭐⭐ (3/5) - Needs input validation and privacy improvements

This is a solid architectural improvement that properly migrates to bitkit-core. The critical issues around race conditions and performance should be addressed before merging, but the overall direction is excellent. The test coverage is impressive (+623 lines) and shows careful attention to correctness.

Great work on this migration! Let me know if you'd like me to elaborate on any of these points or if you have questions about the recommended fixes.

@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@ovitrif
ovitrif merged commit c93b451 into masterNov 24, 2025
16 of 17 checks passed
@ovitrif
ovitrif deleted the use-preactivity-metadata branch November 24, 2025 17:46
Sign up for freeto 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.

Tag set upfront on the receive BTC invoice is not displayed on incoming transaction

3 participants

@ben-kaufman@jvsena42@ovitrif
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Update preactivity metadata and transfer activity handling - #476

Merged
ovitrif merged 7 commits into
masterfrom
use-preactivity-metadata
Nov 24, 2025
Merged

Update preactivity metadata and transfer activity handling#476
ovitrif merged 7 commits into
masterfrom
use-preactivity-metadata

Conversation

@ben-kaufman

@ben-kaufmanben-kaufman commented Nov 21, 2025

Copy link
Copy Markdown
Contributor

This PR migrates the tag metadata system from Room database to bitkit-core library's PreActivityMetadata system and improves transfer activity handling throughout the app.

Similar to: synonymdev/bitkit-ios#219synonymdev/bitkit-ios#226synonymdev/bitkit-ios#229

Description

Migration from Room TagMetadata to PreActivityMetadata:

  • Removed Room-based tag metadata storage (TagMetadataDao, TagMetadataEntity, and extensions)
  • Created new PreActivityMetadataRepo that interfaces with CoreService.activity for metadata management
  • PreActivityMetadata now stores more information including payment hash, txId, address, receive/transfer flags, fee rate, and channel ID
  • All metadata operations now go through the core library instead of direct database access
  • Database schema updated to version 5

Enhanced Transfer Activity Handling:

  • Improved tracking of transfer activities (channel opens/closes, LSP orders) using isTransfer flag in PreActivityMetadata
  • Updated ActivityRepo to properly handle transfer metadata when syncing activities
  • Enhanced WalletRepo with better pre-activity metadata integration for transfers
  • CoreService now provides activity service methods for metadata management
  • Added transfer-specific UI indicators and improved activity detail display for transfers

Testing Focus Areas:

  1. Tag Management:

    • Add/remove tags to transactions and payments
    • Verify tags persist across app restarts
    • Test tag backup/restore functionality
  2. Transfer Activities:

    • Create channel orders and verify they appear as "Transfer to Spending"
    • Open manual channels and check activity labeling
    • Close channels (cooperative/force) and verify "Transfer to Savings" display
    • Confirm transfer activities show correct metadata in detail view
  3. Activity Detail Screen:

    • View various activity types (onchain, lightning, transfers)
    • Check that all metadata displays correctly
    • Verify transfer-specific UI elements appear for transfer activities

Fixes#322

@ben-kaufman
ben-kaufmanforce-pushed the use-preactivity-metadata branch from f781983 to 9ee1001CompareNovember 21, 2025 19:03
@jvsena42

Copy link
Copy Markdown
Member

Starting review

@jvsena42

jvsena42 commented Nov 24, 2025

Copy link
Copy Markdown
Member

@ben-kaufman please add this issue to the description if the PR solves it
#322

Comment threadapp/src/main/java/to/bitkit/repositories/PreActivityMetadataRepo.kt Outdated

@jvsena42jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Tested:

  • Install over an old version ✅
  • reset and recover -> should recover tags ❌
tag-not-applyed.webm
  • Close channel -> should display transfer activity ✅
  • Open channel with external node -> should display transfer activity

onChain

onchain-receive.webm
  • Scan qr -> attach tag -> send -> Activity has tags ✅

Lighting

  • Create invoice -> attach tag -> receive payment -> Activity has tags ✅
  • Scan qr -> attach tag -> send -> Activity has tags ✅

@ben-kaufman

ben-kaufman commented Nov 24, 2025

Copy link
Copy Markdown
ContributorAuthor

reset and recover -> should recover tags ❌

This actually shouldn't be related to this PR, since changes here are only about pre-activity, but tags in existing activities are saved in the activity itself. I'll check the issue though but maybe better in another PR.

Create invoice -> attach tag -> receive payment ->#322

Hmm this seems to not happen consistently, checking.

@ben-kaufman

Copy link
Copy Markdown
ContributorAuthor

@jvsena42 issue with onchain invoice should be fixed now

@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@ben-kaufman

Copy link
Copy Markdown
ContributorAuthor

@jvsena42 I opened #479 which fixes the backup and restore issue.

@jvsena42jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Retested the two failing points

@ovitrifovitrif left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Awesome work!

Couldn't find any issue neither in code nor in my tests.

My Tests:

  • tag existing sent and received activity for onchain and for LN 🟢
  • tag LN and Onchain during send 🟢
  • add tags to LN and Onchain during receive, then scan with iOS & receive the payments 🟢
  • backup, wipe & restore 🟢
  • transfer to savings activity 🟢
  • check lightning connections list & detail 🟢
  • transfer to spending activity 🟢
  • re-check lightning connections list & detail 🟢
  • backup, wipe & restore: recheck connections, tags, activity 🟢
  • open manual channel ⚫ couldn't test, encountered issues connecting to my LND peer in bitkit-docker 🤷🏻

@claude

claudeBot commented Nov 24, 2025

Copy link
Copy Markdown
Contributor

Pull Request Review: Tag Metadata Migration to PreActivityMetadata

Overview

This PR successfully migrates tag metadata from Room database to the bitkit-core PreActivityMetadata system and enhances transfer activity handling. The code quality is generally good with comprehensive test coverage (+623 lines of new tests). However, I've identified several issues that should be addressed before merging.

⚠️ Critical Issues

1. Race Condition in Tag Migration (ActivityRepo.kt:327-365)

Location: replaceActivity method

Issue: Tags are migrated but if addTagsToActivity fails, the error is silently ignored:

val tags = coreService.activity.tags(activityIdToDelete)
addTagsToActivity(activityId = id, tags = tags) // Failure ignored!
markActivityAsRemovedFromMempool(activityIdToDelete).onFailure { e ->// ... error handling
}
Result.success(Unit) // Returns success even if tags failed

Impact: Tags can be silently lost during activity replacements.

Fix: Check the result and handle failures:

addTagsToActivity(activityId = id, tags = tags).onFailure { e ->Logger.error("Failed to migrate tags from $activityIdToDelete to $id", e, context =TAG)
// Consider whether this should fail the entire operation
}

2. N+1 Query Problem in Address Lookup (CoreService.kt:486-495)

Location: findAddressInPreActivityMetadata

Issue: Makes a database query for EACH output in a transaction:

for (output in txDetails.vout) {
val address = output.scriptpubkey_address ?:continueval metadata = coreService.activity.getPreActivityMetadata(
searchKey = address, searchByAddress =true
) // Query per output!
}

Impact: Significant performance degradation for transactions with many outputs.

Fix: Implement batch lookup:

privatesuspendfunfindAddressInPreActivityMetadata(txDetails:TxDetails): String? {
val addresses = txDetails.vout.mapNotNull { it.scriptpubkey_address }
if (addresses.isEmpty()) returnnull// Add batch query method to core serviceval allMetadata = coreService.activity.getPreActivityMetadataByAddresses(addresses)
return addresses.firstOrNull { address ->
allMetadata[address]?.isReceive ==true
}
}

3. Performance Issue in Replacement Transaction Marking (CoreService.kt:661-703)

Location: markReplacementTransactionsAsRemoved

Issue: Fetches ALL onchain activities and iterates through them:

val allActivities = getActivities(
filter =ActivityFilter.ONCHAIN,
limit =UInt.MAX_VALUE// All activities!
)

Impact: Very slow for wallets with many transactions; could cause ANR.

Fix: Add database index on boostTxIds or implement a direct query to find activities where boostTxIds contains the original transaction ID.

🐛 High Priority Bugs

4. Race Condition in Channel State Reads (ActivityRepo.kt:143-183)

Issue: Channel state is read multiple times without synchronization:

// Read 1:val channels = lightningRepo.lightningState.value.channels
// ... later in findOpenChannelForTransaction ...// Read 2:val orders = blocktankRepo.blocktankState.value.orders
// ... later in findClosedChannelForTransaction ...// Read 3:val closedChannels = getClosedChannels(SortDirection.DESC).getOrNull()

Impact: If channel state changes between reads, could match wrong channels or miss matches entirely.

Fix: Snapshot all state at the start of findChannelsForPayments.

5. Tag Migration Data Loss (WalletRepo.kt:98-121)

Issue: Tags are read from old payment ID, but old metadata is deleted before confirming new metadata is saved:

val tagsToMigrate =/* ... get from old payment ID ... */
clearBip21State() // Deletes old metadata here// ... operations that could fail ...
persistPreActivityMetadata(newPaymentId, tagsToMigrate, newBip21Url) // Could fail

Impact: Tags lost if any error occurs between clearing and persisting.

Fix: Only delete old metadata after confirming new metadata is successfully saved.

6. Timestamp Edge Case Handling (ActivityRepo.kt:391-394)

Issue: Null timestamp defaults to 0, which always triggers boost:

if ((newOnChainActivity.v1.updatedAt ?:0u) > pendingBoostActivity.updatedAt) {
cacheStore.removeActivityFromPendingBoost(pendingBoostActivity)
return@onSuccess
}

Impact: Activities with null updatedAt will always be boosted.

Fix: Handle null explicitly:

val activityUpdatedAt = newOnChainActivity.v1.updatedAt
if (activityUpdatedAt !=null&& activityUpdatedAt > pendingBoostActivity.updatedAt) {
cacheStore.removeActivityFromPendingBoost(pendingBoostActivity)
return@onSuccess
}

🔒 Security Concerns

7. Input Validation Missing (PreActivityMetadataRepo.kt, WalletRepo.kt)

Issue: Payment IDs and tags accepted without validation.

Risk: Data integrity issues; potential XSS if tags displayed in web views.

Fix: Add validation:

privatefunvalidatePaymentId(id:String): Boolean {
return id.isNotBlank() && id.length <=256&& id.matches(Regex("[a-zA-Z0-9]+"))
}
privatefunsanitizeTag(tag:String): String {
return tag.trim()
.take(50) // Max length
.replace(Regex("[^a-zA-Z0-9\\s-_]"), "")
}

8. Sensitive Data in Logs

Issue: Payment hashes, addresses, and amounts logged at INFO/DEBUG level throughout.

Example: CoreService.kt:389, PreActivityMetadataRepo.kt:146

Risk: Privacy exposure if logs are collected/shared.

Fix: Use VERBOSE level for sensitive data; truncate payment hashes: paymentHash.take(8)...

📝 Code Quality Issues

9. Complex Nested Logic (ActivityRepo.kt:143-166)

Issue: findOpenChannelForTransaction has three return paths with similar null returns but different meanings:

channels.firstOrNull { channel ->... }?.channelId
?:run {
val matchingOrder = orders.firstOrNull { ... } ?:returnnullval orderChannel = matchingOrder.channel ?:returnnull
channels.firstOrNull { ... }?.channelId
}

Recommendation: Extract to named functions and add logging for each path to improve debuggability.

10. Silent Error Swallowing (WalletRepo.kt:132-138)

Issue: Payment hash extraction failures silently return null:

val paymentHash = runCatching {
when (val decoded = decode(bip21Url)) {
isScanner.Lightning-> decoded.invoice.paymentHash.toHex()
isScanner.OnChain-> decoded.extractLightningHash()
else->null
}
}.getOrNull() // Error swallowed

Recommendation: Log failures to help diagnose BIP21 generation issues.

11. Inconsistent Concurrency Strategy (CoreService.kt:382-401)

Issue: Chunks processed sequentially, but payments within chunks processed in parallel:

payments.chunked(CHUNK_SIZE).forEach { chunk ->// Sequential
chunk.map { payment ->
async { ... } // Parallel
}.awaitAll()
}

Recommendation: Document why this hybrid approach is needed, or simplify by fully parallelizing if order doesn't matter.

✅ Test Coverage Gaps

Missing Tests:

  1. Concurrent operations: Multiple simultaneous tag additions/removals
  2. Channel matching: Tests with various channel states and edge cases
  3. Tag migration failures: Partial failures (old deleted, new creation fails)
  4. Performance: Large datasets (1000+ activities, 100+ channels)
  5. Integration: End-to-end flows across PreActivityMetadataRepo → ActivityRepo → WalletRepo
  6. Time edge cases: Extreme timestamp values (far future, null timestamps)

🎯 Recommendations

Before Merging:

  1. ✅ Fix tag migration race condition (Android - Project setup #1)
  2. ✅ Implement batch address lookup (POC wake2pay from notification #2)
  3. ✅ Optimize replacement transaction marking (Android - Migrate to ldk-node #3)
  4. ✅ Add input validation (Setup Keychain #7)
  5. ✅ Fix timestamp edge case handling (Migrate channels from LDK to ldk-node #6)

High Priority:

  1. Fix channel matching race conditions (Migrate to ldk-node #4)
  2. Fix tag migration data loss (Android - LDK state & Slashtags metadata #5)
  3. Add proper error logging for silent failures (chore: Merge BT notifications changes from deps/bdk-1.0 to master #10)
  4. Reduce sensitive data in logs (BDK 1.0.0-alpha.11 #8)

Medium Priority:

  1. Refactor complex nested logic (Blocktank Push Notifications #9)
  2. Document concurrency strategy (Business Logic Data Modeling #11)
  3. Add missing test coverage
  4. Consider adding database indexes for boostTxIds

📊 Overall Assessment

Code Quality: ⭐⭐⭐⭐ (4/5) - Well-structured with good separation of concerns

Test Coverage: ⭐⭐⭐⭐ (4/5) - Comprehensive unit tests, needs more integration tests

Performance: ⭐⭐⭐ (3/5) - Several potential bottlenecks identified

Security: ⭐⭐⭐ (3/5) - Needs input validation and privacy improvements

This is a solid architectural improvement that properly migrates to bitkit-core. The critical issues around race conditions and performance should be addressed before merging, but the overall direction is excellent. The test coverage is impressive (+623 lines) and shows careful attention to correctness.

Great work on this migration! Let me know if you'd like me to elaborate on any of these points or if you have questions about the recommended fixes.

@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@ovitrif
ovitrif merged commit c93b451 into masterNov 24, 2025
16 of 17 checks passed
@ovitrif
ovitrif deleted the use-preactivity-metadata branch November 24, 2025 17:46
Sign up for freeto 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.

Tag set upfront on the receive BTC invoice is not displayed on incoming transaction

3 participants

@ben-kaufman@jvsena42@ovitrif
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Update preactivity metadata and transfer activity handling - #476

Merged
ovitrif merged 7 commits into
masterfrom
use-preactivity-metadata
Nov 24, 2025
Merged

Update preactivity metadata and transfer activity handling#476
ovitrif merged 7 commits into
masterfrom
use-preactivity-metadata

Conversation

@ben-kaufman

@ben-kaufmanben-kaufman commented Nov 21, 2025

Copy link
Copy Markdown
Contributor

This PR migrates the tag metadata system from Room database to bitkit-core library's PreActivityMetadata system and improves transfer activity handling throughout the app.

Similar to: synonymdev/bitkit-ios#219synonymdev/bitkit-ios#226synonymdev/bitkit-ios#229

Description

Migration from Room TagMetadata to PreActivityMetadata:

  • Removed Room-based tag metadata storage (TagMetadataDao, TagMetadataEntity, and extensions)
  • Created new PreActivityMetadataRepo that interfaces with CoreService.activity for metadata management
  • PreActivityMetadata now stores more information including payment hash, txId, address, receive/transfer flags, fee rate, and channel ID
  • All metadata operations now go through the core library instead of direct database access
  • Database schema updated to version 5

Enhanced Transfer Activity Handling:

  • Improved tracking of transfer activities (channel opens/closes, LSP orders) using isTransfer flag in PreActivityMetadata
  • Updated ActivityRepo to properly handle transfer metadata when syncing activities
  • Enhanced WalletRepo with better pre-activity metadata integration for transfers
  • CoreService now provides activity service methods for metadata management
  • Added transfer-specific UI indicators and improved activity detail display for transfers

Testing Focus Areas:

  1. Tag Management:

    • Add/remove tags to transactions and payments
    • Verify tags persist across app restarts
    • Test tag backup/restore functionality
  2. Transfer Activities:

    • Create channel orders and verify they appear as "Transfer to Spending"
    • Open manual channels and check activity labeling
    • Close channels (cooperative/force) and verify "Transfer to Savings" display
    • Confirm transfer activities show correct metadata in detail view
  3. Activity Detail Screen:

    • View various activity types (onchain, lightning, transfers)
    • Check that all metadata displays correctly
    • Verify transfer-specific UI elements appear for transfer activities

Fixes#322

@ben-kaufman
ben-kaufmanforce-pushed the use-preactivity-metadata branch from f781983 to 9ee1001CompareNovember 21, 2025 19:03
@jvsena42

Copy link
Copy Markdown
Member

Starting review

@jvsena42

jvsena42 commented Nov 24, 2025

Copy link
Copy Markdown
Member

@ben-kaufman please add this issue to the description if the PR solves it
#322

Comment threadapp/src/main/java/to/bitkit/repositories/PreActivityMetadataRepo.kt Outdated

@jvsena42jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Tested:

  • Install over an old version ✅
  • reset and recover -> should recover tags ❌
tag-not-applyed.webm
  • Close channel -> should display transfer activity ✅
  • Open channel with external node -> should display transfer activity

onChain

onchain-receive.webm
  • Scan qr -> attach tag -> send -> Activity has tags ✅

Lighting

  • Create invoice -> attach tag -> receive payment -> Activity has tags ✅
  • Scan qr -> attach tag -> send -> Activity has tags ✅

@ben-kaufman

ben-kaufman commented Nov 24, 2025

Copy link
Copy Markdown
ContributorAuthor

reset and recover -> should recover tags ❌

This actually shouldn't be related to this PR, since changes here are only about pre-activity, but tags in existing activities are saved in the activity itself. I'll check the issue though but maybe better in another PR.

Create invoice -> attach tag -> receive payment ->#322

Hmm this seems to not happen consistently, checking.

@ben-kaufman

Copy link
Copy Markdown
ContributorAuthor

@jvsena42 issue with onchain invoice should be fixed now

@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@ben-kaufman

Copy link
Copy Markdown
ContributorAuthor

@jvsena42 I opened #479 which fixes the backup and restore issue.

@jvsena42jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Retested the two failing points

@ovitrifovitrif left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Awesome work!

Couldn't find any issue neither in code nor in my tests.

My Tests:

  • tag existing sent and received activity for onchain and for LN 🟢
  • tag LN and Onchain during send 🟢
  • add tags to LN and Onchain during receive, then scan with iOS & receive the payments 🟢
  • backup, wipe & restore 🟢
  • transfer to savings activity 🟢
  • check lightning connections list & detail 🟢
  • transfer to spending activity 🟢
  • re-check lightning connections list & detail 🟢
  • backup, wipe & restore: recheck connections, tags, activity 🟢
  • open manual channel ⚫ couldn't test, encountered issues connecting to my LND peer in bitkit-docker 🤷🏻

@claude

claudeBot commented Nov 24, 2025

Copy link
Copy Markdown
Contributor

Pull Request Review: Tag Metadata Migration to PreActivityMetadata

Overview

This PR successfully migrates tag metadata from Room database to the bitkit-core PreActivityMetadata system and enhances transfer activity handling. The code quality is generally good with comprehensive test coverage (+623 lines of new tests). However, I've identified several issues that should be addressed before merging.

⚠️ Critical Issues

1. Race Condition in Tag Migration (ActivityRepo.kt:327-365)

Location: replaceActivity method

Issue: Tags are migrated but if addTagsToActivity fails, the error is silently ignored:

val tags = coreService.activity.tags(activityIdToDelete)
addTagsToActivity(activityId = id, tags = tags) // Failure ignored!
markActivityAsRemovedFromMempool(activityIdToDelete).onFailure { e ->// ... error handling
}
Result.success(Unit) // Returns success even if tags failed

Impact: Tags can be silently lost during activity replacements.

Fix: Check the result and handle failures:

addTagsToActivity(activityId = id, tags = tags).onFailure { e ->Logger.error("Failed to migrate tags from $activityIdToDelete to $id", e, context =TAG)
// Consider whether this should fail the entire operation
}

2. N+1 Query Problem in Address Lookup (CoreService.kt:486-495)

Location: findAddressInPreActivityMetadata

Issue: Makes a database query for EACH output in a transaction:

for (output in txDetails.vout) {
val address = output.scriptpubkey_address ?:continueval metadata = coreService.activity.getPreActivityMetadata(
searchKey = address, searchByAddress =true
) // Query per output!
}

Impact: Significant performance degradation for transactions with many outputs.

Fix: Implement batch lookup:

privatesuspendfunfindAddressInPreActivityMetadata(txDetails:TxDetails): String? {
val addresses = txDetails.vout.mapNotNull { it.scriptpubkey_address }
if (addresses.isEmpty()) returnnull// Add batch query method to core serviceval allMetadata = coreService.activity.getPreActivityMetadataByAddresses(addresses)
return addresses.firstOrNull { address ->
allMetadata[address]?.isReceive ==true
}
}

3. Performance Issue in Replacement Transaction Marking (CoreService.kt:661-703)

Location: markReplacementTransactionsAsRemoved

Issue: Fetches ALL onchain activities and iterates through them:

val allActivities = getActivities(
filter =ActivityFilter.ONCHAIN,
limit =UInt.MAX_VALUE// All activities!
)

Impact: Very slow for wallets with many transactions; could cause ANR.

Fix: Add database index on boostTxIds or implement a direct query to find activities where boostTxIds contains the original transaction ID.

🐛 High Priority Bugs

4. Race Condition in Channel State Reads (ActivityRepo.kt:143-183)

Issue: Channel state is read multiple times without synchronization:

// Read 1:val channels = lightningRepo.lightningState.value.channels
// ... later in findOpenChannelForTransaction ...// Read 2:val orders = blocktankRepo.blocktankState.value.orders
// ... later in findClosedChannelForTransaction ...// Read 3:val closedChannels = getClosedChannels(SortDirection.DESC).getOrNull()

Impact: If channel state changes between reads, could match wrong channels or miss matches entirely.

Fix: Snapshot all state at the start of findChannelsForPayments.

5. Tag Migration Data Loss (WalletRepo.kt:98-121)

Issue: Tags are read from old payment ID, but old metadata is deleted before confirming new metadata is saved:

val tagsToMigrate =/* ... get from old payment ID ... */
clearBip21State() // Deletes old metadata here// ... operations that could fail ...
persistPreActivityMetadata(newPaymentId, tagsToMigrate, newBip21Url) // Could fail

Impact: Tags lost if any error occurs between clearing and persisting.

Fix: Only delete old metadata after confirming new metadata is successfully saved.

6. Timestamp Edge Case Handling (ActivityRepo.kt:391-394)

Issue: Null timestamp defaults to 0, which always triggers boost:

if ((newOnChainActivity.v1.updatedAt ?:0u) > pendingBoostActivity.updatedAt) {
cacheStore.removeActivityFromPendingBoost(pendingBoostActivity)
return@onSuccess
}

Impact: Activities with null updatedAt will always be boosted.

Fix: Handle null explicitly:

val activityUpdatedAt = newOnChainActivity.v1.updatedAt
if (activityUpdatedAt !=null&& activityUpdatedAt > pendingBoostActivity.updatedAt) {
cacheStore.removeActivityFromPendingBoost(pendingBoostActivity)
return@onSuccess
}

🔒 Security Concerns

7. Input Validation Missing (PreActivityMetadataRepo.kt, WalletRepo.kt)

Issue: Payment IDs and tags accepted without validation.

Risk: Data integrity issues; potential XSS if tags displayed in web views.

Fix: Add validation:

privatefunvalidatePaymentId(id:String): Boolean {
return id.isNotBlank() && id.length <=256&& id.matches(Regex("[a-zA-Z0-9]+"))
}
privatefunsanitizeTag(tag:String): String {
return tag.trim()
.take(50) // Max length
.replace(Regex("[^a-zA-Z0-9\\s-_]"), "")
}

8. Sensitive Data in Logs

Issue: Payment hashes, addresses, and amounts logged at INFO/DEBUG level throughout.

Example: CoreService.kt:389, PreActivityMetadataRepo.kt:146

Risk: Privacy exposure if logs are collected/shared.

Fix: Use VERBOSE level for sensitive data; truncate payment hashes: paymentHash.take(8)...

📝 Code Quality Issues

9. Complex Nested Logic (ActivityRepo.kt:143-166)

Issue: findOpenChannelForTransaction has three return paths with similar null returns but different meanings:

channels.firstOrNull { channel ->... }?.channelId
?:run {
val matchingOrder = orders.firstOrNull { ... } ?:returnnullval orderChannel = matchingOrder.channel ?:returnnull
channels.firstOrNull { ... }?.channelId
}

Recommendation: Extract to named functions and add logging for each path to improve debuggability.

10. Silent Error Swallowing (WalletRepo.kt:132-138)

Issue: Payment hash extraction failures silently return null:

val paymentHash = runCatching {
when (val decoded = decode(bip21Url)) {
isScanner.Lightning-> decoded.invoice.paymentHash.toHex()
isScanner.OnChain-> decoded.extractLightningHash()
else->null
}
}.getOrNull() // Error swallowed

Recommendation: Log failures to help diagnose BIP21 generation issues.

11. Inconsistent Concurrency Strategy (CoreService.kt:382-401)

Issue: Chunks processed sequentially, but payments within chunks processed in parallel:

payments.chunked(CHUNK_SIZE).forEach { chunk ->// Sequential
chunk.map { payment ->
async { ... } // Parallel
}.awaitAll()
}

Recommendation: Document why this hybrid approach is needed, or simplify by fully parallelizing if order doesn't matter.

✅ Test Coverage Gaps

Missing Tests:

  1. Concurrent operations: Multiple simultaneous tag additions/removals
  2. Channel matching: Tests with various channel states and edge cases
  3. Tag migration failures: Partial failures (old deleted, new creation fails)
  4. Performance: Large datasets (1000+ activities, 100+ channels)
  5. Integration: End-to-end flows across PreActivityMetadataRepo → ActivityRepo → WalletRepo
  6. Time edge cases: Extreme timestamp values (far future, null timestamps)

🎯 Recommendations

Before Merging:

  1. ✅ Fix tag migration race condition (Android - Project setup #1)
  2. ✅ Implement batch address lookup (POC wake2pay from notification #2)
  3. ✅ Optimize replacement transaction marking (Android - Migrate to ldk-node #3)
  4. ✅ Add input validation (Setup Keychain #7)
  5. ✅ Fix timestamp edge case handling (Migrate channels from LDK to ldk-node #6)

High Priority:

  1. Fix channel matching race conditions (Migrate to ldk-node #4)
  2. Fix tag migration data loss (Android - LDK state & Slashtags metadata #5)
  3. Add proper error logging for silent failures (chore: Merge BT notifications changes from deps/bdk-1.0 to master #10)
  4. Reduce sensitive data in logs (BDK 1.0.0-alpha.11 #8)

Medium Priority:

  1. Refactor complex nested logic (Blocktank Push Notifications #9)
  2. Document concurrency strategy (Business Logic Data Modeling #11)
  3. Add missing test coverage
  4. Consider adding database indexes for boostTxIds

📊 Overall Assessment

Code Quality: ⭐⭐⭐⭐ (4/5) - Well-structured with good separation of concerns

Test Coverage: ⭐⭐⭐⭐ (4/5) - Comprehensive unit tests, needs more integration tests

Performance: ⭐⭐⭐ (3/5) - Several potential bottlenecks identified

Security: ⭐⭐⭐ (3/5) - Needs input validation and privacy improvements

This is a solid architectural improvement that properly migrates to bitkit-core. The critical issues around race conditions and performance should be addressed before merging, but the overall direction is excellent. The test coverage is impressive (+623 lines) and shows careful attention to correctness.

Great work on this migration! Let me know if you'd like me to elaborate on any of these points or if you have questions about the recommended fixes.

@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@ovitrif
ovitrif merged commit c93b451 into masterNov 24, 2025
16 of 17 checks passed
@ovitrif
ovitrif deleted the use-preactivity-metadata branch November 24, 2025 17:46
Sign up for freeto 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.

Tag set upfront on the receive BTC invoice is not displayed on incoming transaction

3 participants

@ben-kaufman@jvsena42@ovitrif
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Update preactivity metadata and transfer activity handling - #476

Merged
ovitrif merged 7 commits into
masterfrom
use-preactivity-metadata
Nov 24, 2025
Merged

Update preactivity metadata and transfer activity handling#476
ovitrif merged 7 commits into
masterfrom
use-preactivity-metadata

Conversation

@ben-kaufman

@ben-kaufmanben-kaufman commented Nov 21, 2025

Copy link
Copy Markdown
Contributor

This PR migrates the tag metadata system from Room database to bitkit-core library's PreActivityMetadata system and improves transfer activity handling throughout the app.

Similar to: synonymdev/bitkit-ios#219synonymdev/bitkit-ios#226synonymdev/bitkit-ios#229

Description

Migration from Room TagMetadata to PreActivityMetadata:

  • Removed Room-based tag metadata storage (TagMetadataDao, TagMetadataEntity, and extensions)
  • Created new PreActivityMetadataRepo that interfaces with CoreService.activity for metadata management
  • PreActivityMetadata now stores more information including payment hash, txId, address, receive/transfer flags, fee rate, and channel ID
  • All metadata operations now go through the core library instead of direct database access
  • Database schema updated to version 5

Enhanced Transfer Activity Handling:

  • Improved tracking of transfer activities (channel opens/closes, LSP orders) using isTransfer flag in PreActivityMetadata
  • Updated ActivityRepo to properly handle transfer metadata when syncing activities
  • Enhanced WalletRepo with better pre-activity metadata integration for transfers
  • CoreService now provides activity service methods for metadata management
  • Added transfer-specific UI indicators and improved activity detail display for transfers

Testing Focus Areas:

  1. Tag Management:

    • Add/remove tags to transactions and payments
    • Verify tags persist across app restarts
    • Test tag backup/restore functionality
  2. Transfer Activities:

    • Create channel orders and verify they appear as "Transfer to Spending"
    • Open manual channels and check activity labeling
    • Close channels (cooperative/force) and verify "Transfer to Savings" display
    • Confirm transfer activities show correct metadata in detail view
  3. Activity Detail Screen:

    • View various activity types (onchain, lightning, transfers)
    • Check that all metadata displays correctly
    • Verify transfer-specific UI elements appear for transfer activities

Fixes#322

@ben-kaufman
ben-kaufmanforce-pushed the use-preactivity-metadata branch from f781983 to 9ee1001CompareNovember 21, 2025 19:03
@jvsena42

Copy link
Copy Markdown
Member

Starting review

@jvsena42

jvsena42 commented Nov 24, 2025

Copy link
Copy Markdown
Member

@ben-kaufman please add this issue to the description if the PR solves it
#322

Comment threadapp/src/main/java/to/bitkit/repositories/PreActivityMetadataRepo.kt Outdated

@jvsena42jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Tested:

  • Install over an old version ✅
  • reset and recover -> should recover tags ❌
tag-not-applyed.webm
  • Close channel -> should display transfer activity ✅
  • Open channel with external node -> should display transfer activity

onChain

onchain-receive.webm
  • Scan qr -> attach tag -> send -> Activity has tags ✅

Lighting

  • Create invoice -> attach tag -> receive payment -> Activity has tags ✅
  • Scan qr -> attach tag -> send -> Activity has tags ✅

@ben-kaufman

ben-kaufman commented Nov 24, 2025

Copy link
Copy Markdown
ContributorAuthor

reset and recover -> should recover tags ❌

This actually shouldn't be related to this PR, since changes here are only about pre-activity, but tags in existing activities are saved in the activity itself. I'll check the issue though but maybe better in another PR.

Create invoice -> attach tag -> receive payment ->#322

Hmm this seems to not happen consistently, checking.

@ben-kaufman

Copy link
Copy Markdown
ContributorAuthor

@jvsena42 issue with onchain invoice should be fixed now

@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@ben-kaufman

Copy link
Copy Markdown
ContributorAuthor

@jvsena42 I opened #479 which fixes the backup and restore issue.

@jvsena42jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Retested the two failing points

@ovitrifovitrif left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Awesome work!

Couldn't find any issue neither in code nor in my tests.

My Tests:

  • tag existing sent and received activity for onchain and for LN 🟢
  • tag LN and Onchain during send 🟢
  • add tags to LN and Onchain during receive, then scan with iOS & receive the payments 🟢
  • backup, wipe & restore 🟢
  • transfer to savings activity 🟢
  • check lightning connections list & detail 🟢
  • transfer to spending activity 🟢
  • re-check lightning connections list & detail 🟢
  • backup, wipe & restore: recheck connections, tags, activity 🟢
  • open manual channel ⚫ couldn't test, encountered issues connecting to my LND peer in bitkit-docker 🤷🏻

@claude

claudeBot commented Nov 24, 2025

Copy link
Copy Markdown
Contributor

Pull Request Review: Tag Metadata Migration to PreActivityMetadata

Overview

This PR successfully migrates tag metadata from Room database to the bitkit-core PreActivityMetadata system and enhances transfer activity handling. The code quality is generally good with comprehensive test coverage (+623 lines of new tests). However, I've identified several issues that should be addressed before merging.

⚠️ Critical Issues

1. Race Condition in Tag Migration (ActivityRepo.kt:327-365)

Location: replaceActivity method

Issue: Tags are migrated but if addTagsToActivity fails, the error is silently ignored:

val tags = coreService.activity.tags(activityIdToDelete)
addTagsToActivity(activityId = id, tags = tags) // Failure ignored!
markActivityAsRemovedFromMempool(activityIdToDelete).onFailure { e ->// ... error handling
}
Result.success(Unit) // Returns success even if tags failed

Impact: Tags can be silently lost during activity replacements.

Fix: Check the result and handle failures:

addTagsToActivity(activityId = id, tags = tags).onFailure { e ->Logger.error("Failed to migrate tags from $activityIdToDelete to $id", e, context =TAG)
// Consider whether this should fail the entire operation
}

2. N+1 Query Problem in Address Lookup (CoreService.kt:486-495)

Location: findAddressInPreActivityMetadata

Issue: Makes a database query for EACH output in a transaction:

for (output in txDetails.vout) {
val address = output.scriptpubkey_address ?:continueval metadata = coreService.activity.getPreActivityMetadata(
searchKey = address, searchByAddress =true
) // Query per output!
}

Impact: Significant performance degradation for transactions with many outputs.

Fix: Implement batch lookup:

privatesuspendfunfindAddressInPreActivityMetadata(txDetails:TxDetails): String? {
val addresses = txDetails.vout.mapNotNull { it.scriptpubkey_address }
if (addresses.isEmpty()) returnnull// Add batch query method to core serviceval allMetadata = coreService.activity.getPreActivityMetadataByAddresses(addresses)
return addresses.firstOrNull { address ->
allMetadata[address]?.isReceive ==true
}
}

3. Performance Issue in Replacement Transaction Marking (CoreService.kt:661-703)

Location: markReplacementTransactionsAsRemoved

Issue: Fetches ALL onchain activities and iterates through them:

val allActivities = getActivities(
filter =ActivityFilter.ONCHAIN,
limit =UInt.MAX_VALUE// All activities!
)

Impact: Very slow for wallets with many transactions; could cause ANR.

Fix: Add database index on boostTxIds or implement a direct query to find activities where boostTxIds contains the original transaction ID.

🐛 High Priority Bugs

4. Race Condition in Channel State Reads (ActivityRepo.kt:143-183)

Issue: Channel state is read multiple times without synchronization:

// Read 1:val channels = lightningRepo.lightningState.value.channels
// ... later in findOpenChannelForTransaction ...// Read 2:val orders = blocktankRepo.blocktankState.value.orders
// ... later in findClosedChannelForTransaction ...// Read 3:val closedChannels = getClosedChannels(SortDirection.DESC).getOrNull()

Impact: If channel state changes between reads, could match wrong channels or miss matches entirely.

Fix: Snapshot all state at the start of findChannelsForPayments.

5. Tag Migration Data Loss (WalletRepo.kt:98-121)

Issue: Tags are read from old payment ID, but old metadata is deleted before confirming new metadata is saved:

val tagsToMigrate =/* ... get from old payment ID ... */
clearBip21State() // Deletes old metadata here// ... operations that could fail ...
persistPreActivityMetadata(newPaymentId, tagsToMigrate, newBip21Url) // Could fail

Impact: Tags lost if any error occurs between clearing and persisting.

Fix: Only delete old metadata after confirming new metadata is successfully saved.

6. Timestamp Edge Case Handling (ActivityRepo.kt:391-394)

Issue: Null timestamp defaults to 0, which always triggers boost:

if ((newOnChainActivity.v1.updatedAt ?:0u) > pendingBoostActivity.updatedAt) {
cacheStore.removeActivityFromPendingBoost(pendingBoostActivity)
return@onSuccess
}

Impact: Activities with null updatedAt will always be boosted.

Fix: Handle null explicitly:

val activityUpdatedAt = newOnChainActivity.v1.updatedAt
if (activityUpdatedAt !=null&& activityUpdatedAt > pendingBoostActivity.updatedAt) {
cacheStore.removeActivityFromPendingBoost(pendingBoostActivity)
return@onSuccess
}

🔒 Security Concerns

7. Input Validation Missing (PreActivityMetadataRepo.kt, WalletRepo.kt)

Issue: Payment IDs and tags accepted without validation.

Risk: Data integrity issues; potential XSS if tags displayed in web views.

Fix: Add validation:

privatefunvalidatePaymentId(id:String): Boolean {
return id.isNotBlank() && id.length <=256&& id.matches(Regex("[a-zA-Z0-9]+"))
}
privatefunsanitizeTag(tag:String): String {
return tag.trim()
.take(50) // Max length
.replace(Regex("[^a-zA-Z0-9\\s-_]"), "")
}

8. Sensitive Data in Logs

Issue: Payment hashes, addresses, and amounts logged at INFO/DEBUG level throughout.

Example: CoreService.kt:389, PreActivityMetadataRepo.kt:146

Risk: Privacy exposure if logs are collected/shared.

Fix: Use VERBOSE level for sensitive data; truncate payment hashes: paymentHash.take(8)...

📝 Code Quality Issues

9. Complex Nested Logic (ActivityRepo.kt:143-166)

Issue: findOpenChannelForTransaction has three return paths with similar null returns but different meanings:

channels.firstOrNull { channel ->... }?.channelId
?:run {
val matchingOrder = orders.firstOrNull { ... } ?:returnnullval orderChannel = matchingOrder.channel ?:returnnull
channels.firstOrNull { ... }?.channelId
}

Recommendation: Extract to named functions and add logging for each path to improve debuggability.

10. Silent Error Swallowing (WalletRepo.kt:132-138)

Issue: Payment hash extraction failures silently return null:

val paymentHash = runCatching {
when (val decoded = decode(bip21Url)) {
isScanner.Lightning-> decoded.invoice.paymentHash.toHex()
isScanner.OnChain-> decoded.extractLightningHash()
else->null
}
}.getOrNull() // Error swallowed

Recommendation: Log failures to help diagnose BIP21 generation issues.

11. Inconsistent Concurrency Strategy (CoreService.kt:382-401)

Issue: Chunks processed sequentially, but payments within chunks processed in parallel:

payments.chunked(CHUNK_SIZE).forEach { chunk ->// Sequential
chunk.map { payment ->
async { ... } // Parallel
}.awaitAll()
}

Recommendation: Document why this hybrid approach is needed, or simplify by fully parallelizing if order doesn't matter.

✅ Test Coverage Gaps

Missing Tests:

  1. Concurrent operations: Multiple simultaneous tag additions/removals
  2. Channel matching: Tests with various channel states and edge cases
  3. Tag migration failures: Partial failures (old deleted, new creation fails)
  4. Performance: Large datasets (1000+ activities, 100+ channels)
  5. Integration: End-to-end flows across PreActivityMetadataRepo → ActivityRepo → WalletRepo
  6. Time edge cases: Extreme timestamp values (far future, null timestamps)

🎯 Recommendations

Before Merging:

  1. ✅ Fix tag migration race condition (Android - Project setup #1)
  2. ✅ Implement batch address lookup (POC wake2pay from notification #2)
  3. ✅ Optimize replacement transaction marking (Android - Migrate to ldk-node #3)
  4. ✅ Add input validation (Setup Keychain #7)
  5. ✅ Fix timestamp edge case handling (Migrate channels from LDK to ldk-node #6)

High Priority:

  1. Fix channel matching race conditions (Migrate to ldk-node #4)
  2. Fix tag migration data loss (Android - LDK state & Slashtags metadata #5)
  3. Add proper error logging for silent failures (chore: Merge BT notifications changes from deps/bdk-1.0 to master #10)
  4. Reduce sensitive data in logs (BDK 1.0.0-alpha.11 #8)

Medium Priority:

  1. Refactor complex nested logic (Blocktank Push Notifications #9)
  2. Document concurrency strategy (Business Logic Data Modeling #11)
  3. Add missing test coverage
  4. Consider adding database indexes for boostTxIds

📊 Overall Assessment

Code Quality: ⭐⭐⭐⭐ (4/5) - Well-structured with good separation of concerns

Test Coverage: ⭐⭐⭐⭐ (4/5) - Comprehensive unit tests, needs more integration tests

Performance: ⭐⭐⭐ (3/5) - Several potential bottlenecks identified

Security: ⭐⭐⭐ (3/5) - Needs input validation and privacy improvements

This is a solid architectural improvement that properly migrates to bitkit-core. The critical issues around race conditions and performance should be addressed before merging, but the overall direction is excellent. The test coverage is impressive (+623 lines) and shows careful attention to correctness.

Great work on this migration! Let me know if you'd like me to elaborate on any of these points or if you have questions about the recommended fixes.

@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@ovitrif
ovitrif merged commit c93b451 into masterNov 24, 2025
16 of 17 checks passed
@ovitrif
ovitrif deleted the use-preactivity-metadata branch November 24, 2025 17:46
Sign up for freeto 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.

Tag set upfront on the receive BTC invoice is not displayed on incoming transaction

3 participants

@ben-kaufman@jvsena42@ovitrif
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Update preactivity metadata and transfer activity handling - #476

Merged
ovitrif merged 7 commits into
masterfrom
use-preactivity-metadata
Nov 24, 2025
Merged

Update preactivity metadata and transfer activity handling#476
ovitrif merged 7 commits into
masterfrom
use-preactivity-metadata

Conversation

@ben-kaufman

@ben-kaufmanben-kaufman commented Nov 21, 2025

Copy link
Copy Markdown
Contributor

This PR migrates the tag metadata system from Room database to bitkit-core library's PreActivityMetadata system and improves transfer activity handling throughout the app.

Similar to: synonymdev/bitkit-ios#219synonymdev/bitkit-ios#226synonymdev/bitkit-ios#229

Description

Migration from Room TagMetadata to PreActivityMetadata:

  • Removed Room-based tag metadata storage (TagMetadataDao, TagMetadataEntity, and extensions)
  • Created new PreActivityMetadataRepo that interfaces with CoreService.activity for metadata management
  • PreActivityMetadata now stores more information including payment hash, txId, address, receive/transfer flags, fee rate, and channel ID
  • All metadata operations now go through the core library instead of direct database access
  • Database schema updated to version 5

Enhanced Transfer Activity Handling:

  • Improved tracking of transfer activities (channel opens/closes, LSP orders) using isTransfer flag in PreActivityMetadata
  • Updated ActivityRepo to properly handle transfer metadata when syncing activities
  • Enhanced WalletRepo with better pre-activity metadata integration for transfers
  • CoreService now provides activity service methods for metadata management
  • Added transfer-specific UI indicators and improved activity detail display for transfers

Testing Focus Areas:

  1. Tag Management:

    • Add/remove tags to transactions and payments
    • Verify tags persist across app restarts
    • Test tag backup/restore functionality
  2. Transfer Activities:

    • Create channel orders and verify they appear as "Transfer to Spending"
    • Open manual channels and check activity labeling
    • Close channels (cooperative/force) and verify "Transfer to Savings" display
    • Confirm transfer activities show correct metadata in detail view
  3. Activity Detail Screen:

    • View various activity types (onchain, lightning, transfers)
    • Check that all metadata displays correctly
    • Verify transfer-specific UI elements appear for transfer activities

Fixes#322

@ben-kaufman
ben-kaufmanforce-pushed the use-preactivity-metadata branch from f781983 to 9ee1001CompareNovember 21, 2025 19:03
@jvsena42

Copy link
Copy Markdown
Member

Starting review

@jvsena42

jvsena42 commented Nov 24, 2025

Copy link
Copy Markdown
Member

@ben-kaufman please add this issue to the description if the PR solves it
#322

Comment threadapp/src/main/java/to/bitkit/repositories/PreActivityMetadataRepo.kt Outdated

@jvsena42jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Tested:

  • Install over an old version ✅
  • reset and recover -> should recover tags ❌
tag-not-applyed.webm
  • Close channel -> should display transfer activity ✅
  • Open channel with external node -> should display transfer activity

onChain

onchain-receive.webm
  • Scan qr -> attach tag -> send -> Activity has tags ✅

Lighting

  • Create invoice -> attach tag -> receive payment -> Activity has tags ✅
  • Scan qr -> attach tag -> send -> Activity has tags ✅

@ben-kaufman

ben-kaufman commented Nov 24, 2025

Copy link
Copy Markdown
ContributorAuthor

reset and recover -> should recover tags ❌

This actually shouldn't be related to this PR, since changes here are only about pre-activity, but tags in existing activities are saved in the activity itself. I'll check the issue though but maybe better in another PR.

Create invoice -> attach tag -> receive payment ->#322

Hmm this seems to not happen consistently, checking.

@ben-kaufman

Copy link
Copy Markdown
ContributorAuthor

@jvsena42 issue with onchain invoice should be fixed now

@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@ben-kaufman

Copy link
Copy Markdown
ContributorAuthor

@jvsena42 I opened #479 which fixes the backup and restore issue.

@jvsena42jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Retested the two failing points

@ovitrifovitrif left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Awesome work!

Couldn't find any issue neither in code nor in my tests.

My Tests:

  • tag existing sent and received activity for onchain and for LN 🟢
  • tag LN and Onchain during send 🟢
  • add tags to LN and Onchain during receive, then scan with iOS & receive the payments 🟢
  • backup, wipe & restore 🟢
  • transfer to savings activity 🟢
  • check lightning connections list & detail 🟢
  • transfer to spending activity 🟢
  • re-check lightning connections list & detail 🟢
  • backup, wipe & restore: recheck connections, tags, activity 🟢
  • open manual channel ⚫ couldn't test, encountered issues connecting to my LND peer in bitkit-docker 🤷🏻

@claude

claudeBot commented Nov 24, 2025

Copy link
Copy Markdown
Contributor

Pull Request Review: Tag Metadata Migration to PreActivityMetadata

Overview

This PR successfully migrates tag metadata from Room database to the bitkit-core PreActivityMetadata system and enhances transfer activity handling. The code quality is generally good with comprehensive test coverage (+623 lines of new tests). However, I've identified several issues that should be addressed before merging.

⚠️ Critical Issues

1. Race Condition in Tag Migration (ActivityRepo.kt:327-365)

Location: replaceActivity method

Issue: Tags are migrated but if addTagsToActivity fails, the error is silently ignored:

val tags = coreService.activity.tags(activityIdToDelete)
addTagsToActivity(activityId = id, tags = tags) // Failure ignored!
markActivityAsRemovedFromMempool(activityIdToDelete).onFailure { e ->// ... error handling
}
Result.success(Unit) // Returns success even if tags failed

Impact: Tags can be silently lost during activity replacements.

Fix: Check the result and handle failures:

addTagsToActivity(activityId = id, tags = tags).onFailure { e ->Logger.error("Failed to migrate tags from $activityIdToDelete to $id", e, context =TAG)
// Consider whether this should fail the entire operation
}

2. N+1 Query Problem in Address Lookup (CoreService.kt:486-495)

Location: findAddressInPreActivityMetadata

Issue: Makes a database query for EACH output in a transaction:

for (output in txDetails.vout) {
val address = output.scriptpubkey_address ?:continueval metadata = coreService.activity.getPreActivityMetadata(
searchKey = address, searchByAddress =true
) // Query per output!
}

Impact: Significant performance degradation for transactions with many outputs.

Fix: Implement batch lookup:

privatesuspendfunfindAddressInPreActivityMetadata(txDetails:TxDetails): String? {
val addresses = txDetails.vout.mapNotNull { it.scriptpubkey_address }
if (addresses.isEmpty()) returnnull// Add batch query method to core serviceval allMetadata = coreService.activity.getPreActivityMetadataByAddresses(addresses)
return addresses.firstOrNull { address ->
allMetadata[address]?.isReceive ==true
}
}

3. Performance Issue in Replacement Transaction Marking (CoreService.kt:661-703)

Location: markReplacementTransactionsAsRemoved

Issue: Fetches ALL onchain activities and iterates through them:

val allActivities = getActivities(
filter =ActivityFilter.ONCHAIN,
limit =UInt.MAX_VALUE// All activities!
)

Impact: Very slow for wallets with many transactions; could cause ANR.

Fix: Add database index on boostTxIds or implement a direct query to find activities where boostTxIds contains the original transaction ID.

🐛 High Priority Bugs

4. Race Condition in Channel State Reads (ActivityRepo.kt:143-183)

Issue: Channel state is read multiple times without synchronization:

// Read 1:val channels = lightningRepo.lightningState.value.channels
// ... later in findOpenChannelForTransaction ...// Read 2:val orders = blocktankRepo.blocktankState.value.orders
// ... later in findClosedChannelForTransaction ...// Read 3:val closedChannels = getClosedChannels(SortDirection.DESC).getOrNull()

Impact: If channel state changes between reads, could match wrong channels or miss matches entirely.

Fix: Snapshot all state at the start of findChannelsForPayments.

5. Tag Migration Data Loss (WalletRepo.kt:98-121)

Issue: Tags are read from old payment ID, but old metadata is deleted before confirming new metadata is saved:

val tagsToMigrate =/* ... get from old payment ID ... */
clearBip21State() // Deletes old metadata here// ... operations that could fail ...
persistPreActivityMetadata(newPaymentId, tagsToMigrate, newBip21Url) // Could fail

Impact: Tags lost if any error occurs between clearing and persisting.

Fix: Only delete old metadata after confirming new metadata is successfully saved.

6. Timestamp Edge Case Handling (ActivityRepo.kt:391-394)

Issue: Null timestamp defaults to 0, which always triggers boost:

if ((newOnChainActivity.v1.updatedAt ?:0u) > pendingBoostActivity.updatedAt) {
cacheStore.removeActivityFromPendingBoost(pendingBoostActivity)
return@onSuccess
}

Impact: Activities with null updatedAt will always be boosted.

Fix: Handle null explicitly:

val activityUpdatedAt = newOnChainActivity.v1.updatedAt
if (activityUpdatedAt !=null&& activityUpdatedAt > pendingBoostActivity.updatedAt) {
cacheStore.removeActivityFromPendingBoost(pendingBoostActivity)
return@onSuccess
}

🔒 Security Concerns

7. Input Validation Missing (PreActivityMetadataRepo.kt, WalletRepo.kt)

Issue: Payment IDs and tags accepted without validation.

Risk: Data integrity issues; potential XSS if tags displayed in web views.

Fix: Add validation:

privatefunvalidatePaymentId(id:String): Boolean {
return id.isNotBlank() && id.length <=256&& id.matches(Regex("[a-zA-Z0-9]+"))
}
privatefunsanitizeTag(tag:String): String {
return tag.trim()
.take(50) // Max length
.replace(Regex("[^a-zA-Z0-9\\s-_]"), "")
}

8. Sensitive Data in Logs

Issue: Payment hashes, addresses, and amounts logged at INFO/DEBUG level throughout.

Example: CoreService.kt:389, PreActivityMetadataRepo.kt:146

Risk: Privacy exposure if logs are collected/shared.

Fix: Use VERBOSE level for sensitive data; truncate payment hashes: paymentHash.take(8)...

📝 Code Quality Issues

9. Complex Nested Logic (ActivityRepo.kt:143-166)

Issue: findOpenChannelForTransaction has three return paths with similar null returns but different meanings:

channels.firstOrNull { channel ->... }?.channelId
?:run {
val matchingOrder = orders.firstOrNull { ... } ?:returnnullval orderChannel = matchingOrder.channel ?:returnnull
channels.firstOrNull { ... }?.channelId
}

Recommendation: Extract to named functions and add logging for each path to improve debuggability.

10. Silent Error Swallowing (WalletRepo.kt:132-138)

Issue: Payment hash extraction failures silently return null:

val paymentHash = runCatching {
when (val decoded = decode(bip21Url)) {
isScanner.Lightning-> decoded.invoice.paymentHash.toHex()
isScanner.OnChain-> decoded.extractLightningHash()
else->null
}
}.getOrNull() // Error swallowed

Recommendation: Log failures to help diagnose BIP21 generation issues.

11. Inconsistent Concurrency Strategy (CoreService.kt:382-401)

Issue: Chunks processed sequentially, but payments within chunks processed in parallel:

payments.chunked(CHUNK_SIZE).forEach { chunk ->// Sequential
chunk.map { payment ->
async { ... } // Parallel
}.awaitAll()
}

Recommendation: Document why this hybrid approach is needed, or simplify by fully parallelizing if order doesn't matter.

✅ Test Coverage Gaps

Missing Tests:

  1. Concurrent operations: Multiple simultaneous tag additions/removals
  2. Channel matching: Tests with various channel states and edge cases
  3. Tag migration failures: Partial failures (old deleted, new creation fails)
  4. Performance: Large datasets (1000+ activities, 100+ channels)
  5. Integration: End-to-end flows across PreActivityMetadataRepo → ActivityRepo → WalletRepo
  6. Time edge cases: Extreme timestamp values (far future, null timestamps)

🎯 Recommendations

Before Merging:

  1. ✅ Fix tag migration race condition (Android - Project setup #1)
  2. ✅ Implement batch address lookup (POC wake2pay from notification #2)
  3. ✅ Optimize replacement transaction marking (Android - Migrate to ldk-node #3)
  4. ✅ Add input validation (Setup Keychain #7)
  5. ✅ Fix timestamp edge case handling (Migrate channels from LDK to ldk-node #6)

High Priority:

  1. Fix channel matching race conditions (Migrate to ldk-node #4)
  2. Fix tag migration data loss (Android - LDK state & Slashtags metadata #5)
  3. Add proper error logging for silent failures (chore: Merge BT notifications changes from deps/bdk-1.0 to master #10)
  4. Reduce sensitive data in logs (BDK 1.0.0-alpha.11 #8)

Medium Priority:

  1. Refactor complex nested logic (Blocktank Push Notifications #9)
  2. Document concurrency strategy (Business Logic Data Modeling #11)
  3. Add missing test coverage
  4. Consider adding database indexes for boostTxIds

📊 Overall Assessment

Code Quality: ⭐⭐⭐⭐ (4/5) - Well-structured with good separation of concerns

Test Coverage: ⭐⭐⭐⭐ (4/5) - Comprehensive unit tests, needs more integration tests

Performance: ⭐⭐⭐ (3/5) - Several potential bottlenecks identified

Security: ⭐⭐⭐ (3/5) - Needs input validation and privacy improvements

This is a solid architectural improvement that properly migrates to bitkit-core. The critical issues around race conditions and performance should be addressed before merging, but the overall direction is excellent. The test coverage is impressive (+623 lines) and shows careful attention to correctness.

Great work on this migration! Let me know if you'd like me to elaborate on any of these points or if you have questions about the recommended fixes.

@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@ovitrif
ovitrif merged commit c93b451 into masterNov 24, 2025
16 of 17 checks passed
@ovitrif
ovitrif deleted the use-preactivity-metadata branch November 24, 2025 17:46
Sign up for freeto 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.

Tag set upfront on the receive BTC invoice is not displayed on incoming transaction

3 participants

@ben-kaufman@jvsena42@ovitrif
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Update preactivity metadata and transfer activity handling - #476

Merged
ovitrif merged 7 commits into
masterfrom
use-preactivity-metadata
Nov 24, 2025
Merged

Update preactivity metadata and transfer activity handling#476
ovitrif merged 7 commits into
masterfrom
use-preactivity-metadata

Conversation

@ben-kaufman

@ben-kaufmanben-kaufman commented Nov 21, 2025

Copy link
Copy Markdown
Contributor

This PR migrates the tag metadata system from Room database to bitkit-core library's PreActivityMetadata system and improves transfer activity handling throughout the app.

Similar to: synonymdev/bitkit-ios#219synonymdev/bitkit-ios#226synonymdev/bitkit-ios#229

Description

Migration from Room TagMetadata to PreActivityMetadata:

  • Removed Room-based tag metadata storage (TagMetadataDao, TagMetadataEntity, and extensions)
  • Created new PreActivityMetadataRepo that interfaces with CoreService.activity for metadata management
  • PreActivityMetadata now stores more information including payment hash, txId, address, receive/transfer flags, fee rate, and channel ID
  • All metadata operations now go through the core library instead of direct database access
  • Database schema updated to version 5

Enhanced Transfer Activity Handling:

  • Improved tracking of transfer activities (channel opens/closes, LSP orders) using isTransfer flag in PreActivityMetadata
  • Updated ActivityRepo to properly handle transfer metadata when syncing activities
  • Enhanced WalletRepo with better pre-activity metadata integration for transfers
  • CoreService now provides activity service methods for metadata management
  • Added transfer-specific UI indicators and improved activity detail display for transfers

Testing Focus Areas:

  1. Tag Management:

    • Add/remove tags to transactions and payments
    • Verify tags persist across app restarts
    • Test tag backup/restore functionality
  2. Transfer Activities:

    • Create channel orders and verify they appear as "Transfer to Spending"
    • Open manual channels and check activity labeling
    • Close channels (cooperative/force) and verify "Transfer to Savings" display
    • Confirm transfer activities show correct metadata in detail view
  3. Activity Detail Screen:

    • View various activity types (onchain, lightning, transfers)
    • Check that all metadata displays correctly
    • Verify transfer-specific UI elements appear for transfer activities

Fixes#322

@ben-kaufman
ben-kaufmanforce-pushed the use-preactivity-metadata branch from f781983 to 9ee1001CompareNovember 21, 2025 19:03
@jvsena42

Copy link
Copy Markdown
Member

Starting review

@jvsena42

jvsena42 commented Nov 24, 2025

Copy link
Copy Markdown
Member

@ben-kaufman please add this issue to the description if the PR solves it
#322

Comment threadapp/src/main/java/to/bitkit/repositories/PreActivityMetadataRepo.kt Outdated

@jvsena42jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Tested:

  • Install over an old version ✅
  • reset and recover -> should recover tags ❌
tag-not-applyed.webm
  • Close channel -> should display transfer activity ✅
  • Open channel with external node -> should display transfer activity

onChain

onchain-receive.webm
  • Scan qr -> attach tag -> send -> Activity has tags ✅

Lighting

  • Create invoice -> attach tag -> receive payment -> Activity has tags ✅
  • Scan qr -> attach tag -> send -> Activity has tags ✅

@ben-kaufman

ben-kaufman commented Nov 24, 2025

Copy link
Copy Markdown
ContributorAuthor

reset and recover -> should recover tags ❌

This actually shouldn't be related to this PR, since changes here are only about pre-activity, but tags in existing activities are saved in the activity itself. I'll check the issue though but maybe better in another PR.

Create invoice -> attach tag -> receive payment ->#322

Hmm this seems to not happen consistently, checking.

@ben-kaufman

Copy link
Copy Markdown
ContributorAuthor

@jvsena42 issue with onchain invoice should be fixed now

@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@ben-kaufman

Copy link
Copy Markdown
ContributorAuthor

@jvsena42 I opened #479 which fixes the backup and restore issue.

@jvsena42jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Retested the two failing points

@ovitrifovitrif left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Awesome work!

Couldn't find any issue neither in code nor in my tests.

My Tests:

  • tag existing sent and received activity for onchain and for LN 🟢
  • tag LN and Onchain during send 🟢
  • add tags to LN and Onchain during receive, then scan with iOS & receive the payments 🟢
  • backup, wipe & restore 🟢
  • transfer to savings activity 🟢
  • check lightning connections list & detail 🟢
  • transfer to spending activity 🟢
  • re-check lightning connections list & detail 🟢
  • backup, wipe & restore: recheck connections, tags, activity 🟢
  • open manual channel ⚫ couldn't test, encountered issues connecting to my LND peer in bitkit-docker 🤷🏻

@claude

claudeBot commented Nov 24, 2025

Copy link
Copy Markdown
Contributor

Pull Request Review: Tag Metadata Migration to PreActivityMetadata

Overview

This PR successfully migrates tag metadata from Room database to the bitkit-core PreActivityMetadata system and enhances transfer activity handling. The code quality is generally good with comprehensive test coverage (+623 lines of new tests). However, I've identified several issues that should be addressed before merging.

⚠️ Critical Issues

1. Race Condition in Tag Migration (ActivityRepo.kt:327-365)

Location: replaceActivity method

Issue: Tags are migrated but if addTagsToActivity fails, the error is silently ignored:

val tags = coreService.activity.tags(activityIdToDelete)
addTagsToActivity(activityId = id, tags = tags) // Failure ignored!
markActivityAsRemovedFromMempool(activityIdToDelete).onFailure { e ->// ... error handling
}
Result.success(Unit) // Returns success even if tags failed

Impact: Tags can be silently lost during activity replacements.

Fix: Check the result and handle failures:

addTagsToActivity(activityId = id, tags = tags).onFailure { e ->Logger.error("Failed to migrate tags from $activityIdToDelete to $id", e, context =TAG)
// Consider whether this should fail the entire operation
}

2. N+1 Query Problem in Address Lookup (CoreService.kt:486-495)

Location: findAddressInPreActivityMetadata

Issue: Makes a database query for EACH output in a transaction:

for (output in txDetails.vout) {
val address = output.scriptpubkey_address ?:continueval metadata = coreService.activity.getPreActivityMetadata(
searchKey = address, searchByAddress =true
) // Query per output!
}

Impact: Significant performance degradation for transactions with many outputs.

Fix: Implement batch lookup:

privatesuspendfunfindAddressInPreActivityMetadata(txDetails:TxDetails): String? {
val addresses = txDetails.vout.mapNotNull { it.scriptpubkey_address }
if (addresses.isEmpty()) returnnull// Add batch query method to core serviceval allMetadata = coreService.activity.getPreActivityMetadataByAddresses(addresses)
return addresses.firstOrNull { address ->
allMetadata[address]?.isReceive ==true
}
}

3. Performance Issue in Replacement Transaction Marking (CoreService.kt:661-703)

Location: markReplacementTransactionsAsRemoved

Issue: Fetches ALL onchain activities and iterates through them:

val allActivities = getActivities(
filter =ActivityFilter.ONCHAIN,
limit =UInt.MAX_VALUE// All activities!
)

Impact: Very slow for wallets with many transactions; could cause ANR.

Fix: Add database index on boostTxIds or implement a direct query to find activities where boostTxIds contains the original transaction ID.

🐛 High Priority Bugs

4. Race Condition in Channel State Reads (ActivityRepo.kt:143-183)

Issue: Channel state is read multiple times without synchronization:

// Read 1:val channels = lightningRepo.lightningState.value.channels
// ... later in findOpenChannelForTransaction ...// Read 2:val orders = blocktankRepo.blocktankState.value.orders
// ... later in findClosedChannelForTransaction ...// Read 3:val closedChannels = getClosedChannels(SortDirection.DESC).getOrNull()

Impact: If channel state changes between reads, could match wrong channels or miss matches entirely.

Fix: Snapshot all state at the start of findChannelsForPayments.

5. Tag Migration Data Loss (WalletRepo.kt:98-121)

Issue: Tags are read from old payment ID, but old metadata is deleted before confirming new metadata is saved:

val tagsToMigrate =/* ... get from old payment ID ... */
clearBip21State() // Deletes old metadata here// ... operations that could fail ...
persistPreActivityMetadata(newPaymentId, tagsToMigrate, newBip21Url) // Could fail

Impact: Tags lost if any error occurs between clearing and persisting.

Fix: Only delete old metadata after confirming new metadata is successfully saved.

6. Timestamp Edge Case Handling (ActivityRepo.kt:391-394)

Issue: Null timestamp defaults to 0, which always triggers boost:

if ((newOnChainActivity.v1.updatedAt ?:0u) > pendingBoostActivity.updatedAt) {
cacheStore.removeActivityFromPendingBoost(pendingBoostActivity)
return@onSuccess
}

Impact: Activities with null updatedAt will always be boosted.

Fix: Handle null explicitly:

val activityUpdatedAt = newOnChainActivity.v1.updatedAt
if (activityUpdatedAt !=null&& activityUpdatedAt > pendingBoostActivity.updatedAt) {
cacheStore.removeActivityFromPendingBoost(pendingBoostActivity)
return@onSuccess
}

🔒 Security Concerns

7. Input Validation Missing (PreActivityMetadataRepo.kt, WalletRepo.kt)

Issue: Payment IDs and tags accepted without validation.

Risk: Data integrity issues; potential XSS if tags displayed in web views.

Fix: Add validation:

privatefunvalidatePaymentId(id:String): Boolean {
return id.isNotBlank() && id.length <=256&& id.matches(Regex("[a-zA-Z0-9]+"))
}
privatefunsanitizeTag(tag:String): String {
return tag.trim()
.take(50) // Max length
.replace(Regex("[^a-zA-Z0-9\\s-_]"), "")
}

8. Sensitive Data in Logs

Issue: Payment hashes, addresses, and amounts logged at INFO/DEBUG level throughout.

Example: CoreService.kt:389, PreActivityMetadataRepo.kt:146

Risk: Privacy exposure if logs are collected/shared.

Fix: Use VERBOSE level for sensitive data; truncate payment hashes: paymentHash.take(8)...

📝 Code Quality Issues

9. Complex Nested Logic (ActivityRepo.kt:143-166)

Issue: findOpenChannelForTransaction has three return paths with similar null returns but different meanings:

channels.firstOrNull { channel ->... }?.channelId
?:run {
val matchingOrder = orders.firstOrNull { ... } ?:returnnullval orderChannel = matchingOrder.channel ?:returnnull
channels.firstOrNull { ... }?.channelId
}

Recommendation: Extract to named functions and add logging for each path to improve debuggability.

10. Silent Error Swallowing (WalletRepo.kt:132-138)

Issue: Payment hash extraction failures silently return null:

val paymentHash = runCatching {
when (val decoded = decode(bip21Url)) {
isScanner.Lightning-> decoded.invoice.paymentHash.toHex()
isScanner.OnChain-> decoded.extractLightningHash()
else->null
}
}.getOrNull() // Error swallowed

Recommendation: Log failures to help diagnose BIP21 generation issues.

11. Inconsistent Concurrency Strategy (CoreService.kt:382-401)

Issue: Chunks processed sequentially, but payments within chunks processed in parallel:

payments.chunked(CHUNK_SIZE).forEach { chunk ->// Sequential
chunk.map { payment ->
async { ... } // Parallel
}.awaitAll()
}

Recommendation: Document why this hybrid approach is needed, or simplify by fully parallelizing if order doesn't matter.

✅ Test Coverage Gaps

Missing Tests:

  1. Concurrent operations: Multiple simultaneous tag additions/removals
  2. Channel matching: Tests with various channel states and edge cases
  3. Tag migration failures: Partial failures (old deleted, new creation fails)
  4. Performance: Large datasets (1000+ activities, 100+ channels)
  5. Integration: End-to-end flows across PreActivityMetadataRepo → ActivityRepo → WalletRepo
  6. Time edge cases: Extreme timestamp values (far future, null timestamps)

🎯 Recommendations

Before Merging:

  1. ✅ Fix tag migration race condition (Android - Project setup #1)
  2. ✅ Implement batch address lookup (POC wake2pay from notification #2)
  3. ✅ Optimize replacement transaction marking (Android - Migrate to ldk-node #3)
  4. ✅ Add input validation (Setup Keychain #7)
  5. ✅ Fix timestamp edge case handling (Migrate channels from LDK to ldk-node #6)

High Priority:

  1. Fix channel matching race conditions (Migrate to ldk-node #4)
  2. Fix tag migration data loss (Android - LDK state & Slashtags metadata #5)
  3. Add proper error logging for silent failures (chore: Merge BT notifications changes from deps/bdk-1.0 to master #10)
  4. Reduce sensitive data in logs (BDK 1.0.0-alpha.11 #8)

Medium Priority:

  1. Refactor complex nested logic (Blocktank Push Notifications #9)
  2. Document concurrency strategy (Business Logic Data Modeling #11)
  3. Add missing test coverage
  4. Consider adding database indexes for boostTxIds

📊 Overall Assessment

Code Quality: ⭐⭐⭐⭐ (4/5) - Well-structured with good separation of concerns

Test Coverage: ⭐⭐⭐⭐ (4/5) - Comprehensive unit tests, needs more integration tests

Performance: ⭐⭐⭐ (3/5) - Several potential bottlenecks identified

Security: ⭐⭐⭐ (3/5) - Needs input validation and privacy improvements

This is a solid architectural improvement that properly migrates to bitkit-core. The critical issues around race conditions and performance should be addressed before merging, but the overall direction is excellent. The test coverage is impressive (+623 lines) and shows careful attention to correctness.

Great work on this migration! Let me know if you'd like me to elaborate on any of these points or if you have questions about the recommended fixes.

@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@ovitrif
ovitrif merged commit c93b451 into masterNov 24, 2025
16 of 17 checks passed
@ovitrif
ovitrif deleted the use-preactivity-metadata branch November 24, 2025 17:46
Sign up for freeto 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.

Tag set upfront on the receive BTC invoice is not displayed on incoming transaction

3 participants

@ben-kaufman@jvsena42@ovitrif
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Update preactivity metadata and transfer activity handling - #476

Merged
ovitrif merged 7 commits into
masterfrom
use-preactivity-metadata
Nov 24, 2025
Merged

Update preactivity metadata and transfer activity handling#476
ovitrif merged 7 commits into
masterfrom
use-preactivity-metadata

Conversation

@ben-kaufman

@ben-kaufmanben-kaufman commented Nov 21, 2025

Copy link
Copy Markdown
Contributor

This PR migrates the tag metadata system from Room database to bitkit-core library's PreActivityMetadata system and improves transfer activity handling throughout the app.

Similar to: synonymdev/bitkit-ios#219synonymdev/bitkit-ios#226synonymdev/bitkit-ios#229

Description

Migration from Room TagMetadata to PreActivityMetadata:

  • Removed Room-based tag metadata storage (TagMetadataDao, TagMetadataEntity, and extensions)
  • Created new PreActivityMetadataRepo that interfaces with CoreService.activity for metadata management
  • PreActivityMetadata now stores more information including payment hash, txId, address, receive/transfer flags, fee rate, and channel ID
  • All metadata operations now go through the core library instead of direct database access
  • Database schema updated to version 5

Enhanced Transfer Activity Handling:

  • Improved tracking of transfer activities (channel opens/closes, LSP orders) using isTransfer flag in PreActivityMetadata
  • Updated ActivityRepo to properly handle transfer metadata when syncing activities
  • Enhanced WalletRepo with better pre-activity metadata integration for transfers
  • CoreService now provides activity service methods for metadata management
  • Added transfer-specific UI indicators and improved activity detail display for transfers

Testing Focus Areas:

  1. Tag Management:

    • Add/remove tags to transactions and payments
    • Verify tags persist across app restarts
    • Test tag backup/restore functionality
  2. Transfer Activities:

    • Create channel orders and verify they appear as "Transfer to Spending"
    • Open manual channels and check activity labeling
    • Close channels (cooperative/force) and verify "Transfer to Savings" display
    • Confirm transfer activities show correct metadata in detail view
  3. Activity Detail Screen:

    • View various activity types (onchain, lightning, transfers)
    • Check that all metadata displays correctly
    • Verify transfer-specific UI elements appear for transfer activities

Fixes#322

@ben-kaufman
ben-kaufmanforce-pushed the use-preactivity-metadata branch from f781983 to 9ee1001CompareNovember 21, 2025 19:03
@jvsena42

Copy link
Copy Markdown
Member

Starting review

@jvsena42

jvsena42 commented Nov 24, 2025

Copy link
Copy Markdown
Member

@ben-kaufman please add this issue to the description if the PR solves it
#322

Comment threadapp/src/main/java/to/bitkit/repositories/PreActivityMetadataRepo.kt Outdated

@jvsena42jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Tested:

  • Install over an old version ✅
  • reset and recover -> should recover tags ❌
tag-not-applyed.webm
  • Close channel -> should display transfer activity ✅
  • Open channel with external node -> should display transfer activity

onChain

onchain-receive.webm
  • Scan qr -> attach tag -> send -> Activity has tags ✅

Lighting

  • Create invoice -> attach tag -> receive payment -> Activity has tags ✅
  • Scan qr -> attach tag -> send -> Activity has tags ✅

@ben-kaufman

ben-kaufman commented Nov 24, 2025

Copy link
Copy Markdown
ContributorAuthor

reset and recover -> should recover tags ❌

This actually shouldn't be related to this PR, since changes here are only about pre-activity, but tags in existing activities are saved in the activity itself. I'll check the issue though but maybe better in another PR.

Create invoice -> attach tag -> receive payment ->#322

Hmm this seems to not happen consistently, checking.

@ben-kaufman

Copy link
Copy Markdown
ContributorAuthor

@jvsena42 issue with onchain invoice should be fixed now

@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@ben-kaufman

Copy link
Copy Markdown
ContributorAuthor

@jvsena42 I opened #479 which fixes the backup and restore issue.

@jvsena42jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Retested the two failing points

@ovitrifovitrif left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Awesome work!

Couldn't find any issue neither in code nor in my tests.

My Tests:

  • tag existing sent and received activity for onchain and for LN 🟢
  • tag LN and Onchain during send 🟢
  • add tags to LN and Onchain during receive, then scan with iOS & receive the payments 🟢
  • backup, wipe & restore 🟢
  • transfer to savings activity 🟢
  • check lightning connections list & detail 🟢
  • transfer to spending activity 🟢
  • re-check lightning connections list & detail 🟢
  • backup, wipe & restore: recheck connections, tags, activity 🟢
  • open manual channel ⚫ couldn't test, encountered issues connecting to my LND peer in bitkit-docker 🤷🏻

@claude

claudeBot commented Nov 24, 2025

Copy link
Copy Markdown
Contributor

Pull Request Review: Tag Metadata Migration to PreActivityMetadata

Overview

This PR successfully migrates tag metadata from Room database to the bitkit-core PreActivityMetadata system and enhances transfer activity handling. The code quality is generally good with comprehensive test coverage (+623 lines of new tests). However, I've identified several issues that should be addressed before merging.

⚠️ Critical Issues

1. Race Condition in Tag Migration (ActivityRepo.kt:327-365)

Location: replaceActivity method

Issue: Tags are migrated but if addTagsToActivity fails, the error is silently ignored:

val tags = coreService.activity.tags(activityIdToDelete)
addTagsToActivity(activityId = id, tags = tags) // Failure ignored!
markActivityAsRemovedFromMempool(activityIdToDelete).onFailure { e ->// ... error handling
}
Result.success(Unit) // Returns success even if tags failed

Impact: Tags can be silently lost during activity replacements.

Fix: Check the result and handle failures:

addTagsToActivity(activityId = id, tags = tags).onFailure { e ->Logger.error("Failed to migrate tags from $activityIdToDelete to $id", e, context =TAG)
// Consider whether this should fail the entire operation
}

2. N+1 Query Problem in Address Lookup (CoreService.kt:486-495)

Location: findAddressInPreActivityMetadata

Issue: Makes a database query for EACH output in a transaction:

for (output in txDetails.vout) {
val address = output.scriptpubkey_address ?:continueval metadata = coreService.activity.getPreActivityMetadata(
searchKey = address, searchByAddress =true
) // Query per output!
}

Impact: Significant performance degradation for transactions with many outputs.

Fix: Implement batch lookup:

privatesuspendfunfindAddressInPreActivityMetadata(txDetails:TxDetails): String? {
val addresses = txDetails.vout.mapNotNull { it.scriptpubkey_address }
if (addresses.isEmpty()) returnnull// Add batch query method to core serviceval allMetadata = coreService.activity.getPreActivityMetadataByAddresses(addresses)
return addresses.firstOrNull { address ->
allMetadata[address]?.isReceive ==true
}
}

3. Performance Issue in Replacement Transaction Marking (CoreService.kt:661-703)

Location: markReplacementTransactionsAsRemoved

Issue: Fetches ALL onchain activities and iterates through them:

val allActivities = getActivities(
filter =ActivityFilter.ONCHAIN,
limit =UInt.MAX_VALUE// All activities!
)

Impact: Very slow for wallets with many transactions; could cause ANR.

Fix: Add database index on boostTxIds or implement a direct query to find activities where boostTxIds contains the original transaction ID.

🐛 High Priority Bugs

4. Race Condition in Channel State Reads (ActivityRepo.kt:143-183)

Issue: Channel state is read multiple times without synchronization:

// Read 1:val channels = lightningRepo.lightningState.value.channels
// ... later in findOpenChannelForTransaction ...// Read 2:val orders = blocktankRepo.blocktankState.value.orders
// ... later in findClosedChannelForTransaction ...// Read 3:val closedChannels = getClosedChannels(SortDirection.DESC).getOrNull()

Impact: If channel state changes between reads, could match wrong channels or miss matches entirely.

Fix: Snapshot all state at the start of findChannelsForPayments.

5. Tag Migration Data Loss (WalletRepo.kt:98-121)

Issue: Tags are read from old payment ID, but old metadata is deleted before confirming new metadata is saved:

val tagsToMigrate =/* ... get from old payment ID ... */
clearBip21State() // Deletes old metadata here// ... operations that could fail ...
persistPreActivityMetadata(newPaymentId, tagsToMigrate, newBip21Url) // Could fail

Impact: Tags lost if any error occurs between clearing and persisting.

Fix: Only delete old metadata after confirming new metadata is successfully saved.

6. Timestamp Edge Case Handling (ActivityRepo.kt:391-394)

Issue: Null timestamp defaults to 0, which always triggers boost:

if ((newOnChainActivity.v1.updatedAt ?:0u) > pendingBoostActivity.updatedAt) {
cacheStore.removeActivityFromPendingBoost(pendingBoostActivity)
return@onSuccess
}

Impact: Activities with null updatedAt will always be boosted.

Fix: Handle null explicitly:

val activityUpdatedAt = newOnChainActivity.v1.updatedAt
if (activityUpdatedAt !=null&& activityUpdatedAt > pendingBoostActivity.updatedAt) {
cacheStore.removeActivityFromPendingBoost(pendingBoostActivity)
return@onSuccess
}

🔒 Security Concerns

7. Input Validation Missing (PreActivityMetadataRepo.kt, WalletRepo.kt)

Issue: Payment IDs and tags accepted without validation.

Risk: Data integrity issues; potential XSS if tags displayed in web views.

Fix: Add validation:

privatefunvalidatePaymentId(id:String): Boolean {
return id.isNotBlank() && id.length <=256&& id.matches(Regex("[a-zA-Z0-9]+"))
}
privatefunsanitizeTag(tag:String): String {
return tag.trim()
.take(50) // Max length
.replace(Regex("[^a-zA-Z0-9\\s-_]"), "")
}

8. Sensitive Data in Logs

Issue: Payment hashes, addresses, and amounts logged at INFO/DEBUG level throughout.

Example: CoreService.kt:389, PreActivityMetadataRepo.kt:146

Risk: Privacy exposure if logs are collected/shared.

Fix: Use VERBOSE level for sensitive data; truncate payment hashes: paymentHash.take(8)...

📝 Code Quality Issues

9. Complex Nested Logic (ActivityRepo.kt:143-166)

Issue: findOpenChannelForTransaction has three return paths with similar null returns but different meanings:

channels.firstOrNull { channel ->... }?.channelId
?:run {
val matchingOrder = orders.firstOrNull { ... } ?:returnnullval orderChannel = matchingOrder.channel ?:returnnull
channels.firstOrNull { ... }?.channelId
}

Recommendation: Extract to named functions and add logging for each path to improve debuggability.

10. Silent Error Swallowing (WalletRepo.kt:132-138)

Issue: Payment hash extraction failures silently return null:

val paymentHash = runCatching {
when (val decoded = decode(bip21Url)) {
isScanner.Lightning-> decoded.invoice.paymentHash.toHex()
isScanner.OnChain-> decoded.extractLightningHash()
else->null
}
}.getOrNull() // Error swallowed

Recommendation: Log failures to help diagnose BIP21 generation issues.

11. Inconsistent Concurrency Strategy (CoreService.kt:382-401)

Issue: Chunks processed sequentially, but payments within chunks processed in parallel:

payments.chunked(CHUNK_SIZE).forEach { chunk ->// Sequential
chunk.map { payment ->
async { ... } // Parallel
}.awaitAll()
}

Recommendation: Document why this hybrid approach is needed, or simplify by fully parallelizing if order doesn't matter.

✅ Test Coverage Gaps

Missing Tests:

  1. Concurrent operations: Multiple simultaneous tag additions/removals
  2. Channel matching: Tests with various channel states and edge cases
  3. Tag migration failures: Partial failures (old deleted, new creation fails)
  4. Performance: Large datasets (1000+ activities, 100+ channels)
  5. Integration: End-to-end flows across PreActivityMetadataRepo → ActivityRepo → WalletRepo
  6. Time edge cases: Extreme timestamp values (far future, null timestamps)

🎯 Recommendations

Before Merging:

  1. ✅ Fix tag migration race condition (Android - Project setup #1)
  2. ✅ Implement batch address lookup (POC wake2pay from notification #2)
  3. ✅ Optimize replacement transaction marking (Android - Migrate to ldk-node #3)
  4. ✅ Add input validation (Setup Keychain #7)
  5. ✅ Fix timestamp edge case handling (Migrate channels from LDK to ldk-node #6)

High Priority:

  1. Fix channel matching race conditions (Migrate to ldk-node #4)
  2. Fix tag migration data loss (Android - LDK state & Slashtags metadata #5)
  3. Add proper error logging for silent failures (chore: Merge BT notifications changes from deps/bdk-1.0 to master #10)
  4. Reduce sensitive data in logs (BDK 1.0.0-alpha.11 #8)

Medium Priority:

  1. Refactor complex nested logic (Blocktank Push Notifications #9)
  2. Document concurrency strategy (Business Logic Data Modeling #11)
  3. Add missing test coverage
  4. Consider adding database indexes for boostTxIds

📊 Overall Assessment

Code Quality: ⭐⭐⭐⭐ (4/5) - Well-structured with good separation of concerns

Test Coverage: ⭐⭐⭐⭐ (4/5) - Comprehensive unit tests, needs more integration tests

Performance: ⭐⭐⭐ (3/5) - Several potential bottlenecks identified

Security: ⭐⭐⭐ (3/5) - Needs input validation and privacy improvements

This is a solid architectural improvement that properly migrates to bitkit-core. The critical issues around race conditions and performance should be addressed before merging, but the overall direction is excellent. The test coverage is impressive (+623 lines) and shows careful attention to correctness.

Great work on this migration! Let me know if you'd like me to elaborate on any of these points or if you have questions about the recommended fixes.

@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@ovitrif
ovitrif merged commit c93b451 into masterNov 24, 2025
16 of 17 checks passed
@ovitrif
ovitrif deleted the use-preactivity-metadata branch November 24, 2025 17:46
Sign up for freeto 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.

Tag set upfront on the receive BTC invoice is not displayed on incoming transaction

3 participants

@ben-kaufman@jvsena42@ovitrif
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Update preactivity metadata and transfer activity handling - #476

Merged
ovitrif merged 7 commits into
masterfrom
use-preactivity-metadata
Nov 24, 2025
Merged

Update preactivity metadata and transfer activity handling#476
ovitrif merged 7 commits into
masterfrom
use-preactivity-metadata

Conversation

@ben-kaufman

@ben-kaufmanben-kaufman commented Nov 21, 2025

Copy link
Copy Markdown
Contributor

This PR migrates the tag metadata system from Room database to bitkit-core library's PreActivityMetadata system and improves transfer activity handling throughout the app.

Similar to: synonymdev/bitkit-ios#219synonymdev/bitkit-ios#226synonymdev/bitkit-ios#229

Description

Migration from Room TagMetadata to PreActivityMetadata:

  • Removed Room-based tag metadata storage (TagMetadataDao, TagMetadataEntity, and extensions)
  • Created new PreActivityMetadataRepo that interfaces with CoreService.activity for metadata management
  • PreActivityMetadata now stores more information including payment hash, txId, address, receive/transfer flags, fee rate, and channel ID
  • All metadata operations now go through the core library instead of direct database access
  • Database schema updated to version 5

Enhanced Transfer Activity Handling:

  • Improved tracking of transfer activities (channel opens/closes, LSP orders) using isTransfer flag in PreActivityMetadata
  • Updated ActivityRepo to properly handle transfer metadata when syncing activities
  • Enhanced WalletRepo with better pre-activity metadata integration for transfers
  • CoreService now provides activity service methods for metadata management
  • Added transfer-specific UI indicators and improved activity detail display for transfers

Testing Focus Areas:

  1. Tag Management:

    • Add/remove tags to transactions and payments
    • Verify tags persist across app restarts
    • Test tag backup/restore functionality
  2. Transfer Activities:

    • Create channel orders and verify they appear as "Transfer to Spending"
    • Open manual channels and check activity labeling
    • Close channels (cooperative/force) and verify "Transfer to Savings" display
    • Confirm transfer activities show correct metadata in detail view
  3. Activity Detail Screen:

    • View various activity types (onchain, lightning, transfers)
    • Check that all metadata displays correctly
    • Verify transfer-specific UI elements appear for transfer activities

Fixes#322

@ben-kaufman
ben-kaufmanforce-pushed the use-preactivity-metadata branch from f781983 to 9ee1001CompareNovember 21, 2025 19:03
@jvsena42

Copy link
Copy Markdown
Member

Starting review

@jvsena42

jvsena42 commented Nov 24, 2025

Copy link
Copy Markdown
Member

@ben-kaufman please add this issue to the description if the PR solves it
#322

Comment threadapp/src/main/java/to/bitkit/repositories/PreActivityMetadataRepo.kt Outdated

@jvsena42jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Tested:

  • Install over an old version ✅
  • reset and recover -> should recover tags ❌
tag-not-applyed.webm
  • Close channel -> should display transfer activity ✅
  • Open channel with external node -> should display transfer activity

onChain

onchain-receive.webm
  • Scan qr -> attach tag -> send -> Activity has tags ✅

Lighting

  • Create invoice -> attach tag -> receive payment -> Activity has tags ✅
  • Scan qr -> attach tag -> send -> Activity has tags ✅

@ben-kaufman

ben-kaufman commented Nov 24, 2025

Copy link
Copy Markdown
ContributorAuthor

reset and recover -> should recover tags ❌

This actually shouldn't be related to this PR, since changes here are only about pre-activity, but tags in existing activities are saved in the activity itself. I'll check the issue though but maybe better in another PR.

Create invoice -> attach tag -> receive payment ->#322

Hmm this seems to not happen consistently, checking.

@ben-kaufman

Copy link
Copy Markdown
ContributorAuthor

@jvsena42 issue with onchain invoice should be fixed now

@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@ben-kaufman

Copy link
Copy Markdown
ContributorAuthor

@jvsena42 I opened #479 which fixes the backup and restore issue.

@jvsena42jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Retested the two failing points

@ovitrifovitrif left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Awesome work!

Couldn't find any issue neither in code nor in my tests.

My Tests:

  • tag existing sent and received activity for onchain and for LN 🟢
  • tag LN and Onchain during send 🟢
  • add tags to LN and Onchain during receive, then scan with iOS & receive the payments 🟢
  • backup, wipe & restore 🟢
  • transfer to savings activity 🟢
  • check lightning connections list & detail 🟢
  • transfer to spending activity 🟢
  • re-check lightning connections list & detail 🟢
  • backup, wipe & restore: recheck connections, tags, activity 🟢
  • open manual channel ⚫ couldn't test, encountered issues connecting to my LND peer in bitkit-docker 🤷🏻

@claude

claudeBot commented Nov 24, 2025

Copy link
Copy Markdown
Contributor

Pull Request Review: Tag Metadata Migration to PreActivityMetadata

Overview

This PR successfully migrates tag metadata from Room database to the bitkit-core PreActivityMetadata system and enhances transfer activity handling. The code quality is generally good with comprehensive test coverage (+623 lines of new tests). However, I've identified several issues that should be addressed before merging.

⚠️ Critical Issues

1. Race Condition in Tag Migration (ActivityRepo.kt:327-365)

Location: replaceActivity method

Issue: Tags are migrated but if addTagsToActivity fails, the error is silently ignored:

val tags = coreService.activity.tags(activityIdToDelete)
addTagsToActivity(activityId = id, tags = tags) // Failure ignored!
markActivityAsRemovedFromMempool(activityIdToDelete).onFailure { e ->// ... error handling
}
Result.success(Unit) // Returns success even if tags failed

Impact: Tags can be silently lost during activity replacements.

Fix: Check the result and handle failures:

addTagsToActivity(activityId = id, tags = tags).onFailure { e ->Logger.error("Failed to migrate tags from $activityIdToDelete to $id", e, context =TAG)
// Consider whether this should fail the entire operation
}

2. N+1 Query Problem in Address Lookup (CoreService.kt:486-495)

Location: findAddressInPreActivityMetadata

Issue: Makes a database query for EACH output in a transaction:

for (output in txDetails.vout) {
val address = output.scriptpubkey_address ?:continueval metadata = coreService.activity.getPreActivityMetadata(
searchKey = address, searchByAddress =true
) // Query per output!
}

Impact: Significant performance degradation for transactions with many outputs.

Fix: Implement batch lookup:

privatesuspendfunfindAddressInPreActivityMetadata(txDetails:TxDetails): String? {
val addresses = txDetails.vout.mapNotNull { it.scriptpubkey_address }
if (addresses.isEmpty()) returnnull// Add batch query method to core serviceval allMetadata = coreService.activity.getPreActivityMetadataByAddresses(addresses)
return addresses.firstOrNull { address ->
allMetadata[address]?.isReceive ==true
}
}

3. Performance Issue in Replacement Transaction Marking (CoreService.kt:661-703)

Location: markReplacementTransactionsAsRemoved

Issue: Fetches ALL onchain activities and iterates through them:

val allActivities = getActivities(
filter =ActivityFilter.ONCHAIN,
limit =UInt.MAX_VALUE// All activities!
)

Impact: Very slow for wallets with many transactions; could cause ANR.

Fix: Add database index on boostTxIds or implement a direct query to find activities where boostTxIds contains the original transaction ID.

🐛 High Priority Bugs

4. Race Condition in Channel State Reads (ActivityRepo.kt:143-183)

Issue: Channel state is read multiple times without synchronization:

// Read 1:val channels = lightningRepo.lightningState.value.channels
// ... later in findOpenChannelForTransaction ...// Read 2:val orders = blocktankRepo.blocktankState.value.orders
// ... later in findClosedChannelForTransaction ...// Read 3:val closedChannels = getClosedChannels(SortDirection.DESC).getOrNull()

Impact: If channel state changes between reads, could match wrong channels or miss matches entirely.

Fix: Snapshot all state at the start of findChannelsForPayments.

5. Tag Migration Data Loss (WalletRepo.kt:98-121)

Issue: Tags are read from old payment ID, but old metadata is deleted before confirming new metadata is saved:

val tagsToMigrate =/* ... get from old payment ID ... */
clearBip21State() // Deletes old metadata here// ... operations that could fail ...
persistPreActivityMetadata(newPaymentId, tagsToMigrate, newBip21Url) // Could fail

Impact: Tags lost if any error occurs between clearing and persisting.

Fix: Only delete old metadata after confirming new metadata is successfully saved.

6. Timestamp Edge Case Handling (ActivityRepo.kt:391-394)

Issue: Null timestamp defaults to 0, which always triggers boost:

if ((newOnChainActivity.v1.updatedAt ?:0u) > pendingBoostActivity.updatedAt) {
cacheStore.removeActivityFromPendingBoost(pendingBoostActivity)
return@onSuccess
}

Impact: Activities with null updatedAt will always be boosted.

Fix: Handle null explicitly:

val activityUpdatedAt = newOnChainActivity.v1.updatedAt
if (activityUpdatedAt !=null&& activityUpdatedAt > pendingBoostActivity.updatedAt) {
cacheStore.removeActivityFromPendingBoost(pendingBoostActivity)
return@onSuccess
}

🔒 Security Concerns

7. Input Validation Missing (PreActivityMetadataRepo.kt, WalletRepo.kt)

Issue: Payment IDs and tags accepted without validation.

Risk: Data integrity issues; potential XSS if tags displayed in web views.

Fix: Add validation:

privatefunvalidatePaymentId(id:String): Boolean {
return id.isNotBlank() && id.length <=256&& id.matches(Regex("[a-zA-Z0-9]+"))
}
privatefunsanitizeTag(tag:String): String {
return tag.trim()
.take(50) // Max length
.replace(Regex("[^a-zA-Z0-9\\s-_]"), "")
}

8. Sensitive Data in Logs

Issue: Payment hashes, addresses, and amounts logged at INFO/DEBUG level throughout.

Example: CoreService.kt:389, PreActivityMetadataRepo.kt:146

Risk: Privacy exposure if logs are collected/shared.

Fix: Use VERBOSE level for sensitive data; truncate payment hashes: paymentHash.take(8)...

📝 Code Quality Issues

9. Complex Nested Logic (ActivityRepo.kt:143-166)

Issue: findOpenChannelForTransaction has three return paths with similar null returns but different meanings:

channels.firstOrNull { channel ->... }?.channelId
?:run {
val matchingOrder = orders.firstOrNull { ... } ?:returnnullval orderChannel = matchingOrder.channel ?:returnnull
channels.firstOrNull { ... }?.channelId
}

Recommendation: Extract to named functions and add logging for each path to improve debuggability.

10. Silent Error Swallowing (WalletRepo.kt:132-138)

Issue: Payment hash extraction failures silently return null:

val paymentHash = runCatching {
when (val decoded = decode(bip21Url)) {
isScanner.Lightning-> decoded.invoice.paymentHash.toHex()
isScanner.OnChain-> decoded.extractLightningHash()
else->null
}
}.getOrNull() // Error swallowed

Recommendation: Log failures to help diagnose BIP21 generation issues.

11. Inconsistent Concurrency Strategy (CoreService.kt:382-401)

Issue: Chunks processed sequentially, but payments within chunks processed in parallel:

payments.chunked(CHUNK_SIZE).forEach { chunk ->// Sequential
chunk.map { payment ->
async { ... } // Parallel
}.awaitAll()
}

Recommendation: Document why this hybrid approach is needed, or simplify by fully parallelizing if order doesn't matter.

✅ Test Coverage Gaps

Missing Tests:

  1. Concurrent operations: Multiple simultaneous tag additions/removals
  2. Channel matching: Tests with various channel states and edge cases
  3. Tag migration failures: Partial failures (old deleted, new creation fails)
  4. Performance: Large datasets (1000+ activities, 100+ channels)
  5. Integration: End-to-end flows across PreActivityMetadataRepo → ActivityRepo → WalletRepo
  6. Time edge cases: Extreme timestamp values (far future, null timestamps)

🎯 Recommendations

Before Merging:

  1. ✅ Fix tag migration race condition (Android - Project setup #1)
  2. ✅ Implement batch address lookup (POC wake2pay from notification #2)
  3. ✅ Optimize replacement transaction marking (Android - Migrate to ldk-node #3)
  4. ✅ Add input validation (Setup Keychain #7)
  5. ✅ Fix timestamp edge case handling (Migrate channels from LDK to ldk-node #6)

High Priority:

  1. Fix channel matching race conditions (Migrate to ldk-node #4)
  2. Fix tag migration data loss (Android - LDK state & Slashtags metadata #5)
  3. Add proper error logging for silent failures (chore: Merge BT notifications changes from deps/bdk-1.0 to master #10)
  4. Reduce sensitive data in logs (BDK 1.0.0-alpha.11 #8)

Medium Priority:

  1. Refactor complex nested logic (Blocktank Push Notifications #9)
  2. Document concurrency strategy (Business Logic Data Modeling #11)
  3. Add missing test coverage
  4. Consider adding database indexes for boostTxIds

📊 Overall Assessment

Code Quality: ⭐⭐⭐⭐ (4/5) - Well-structured with good separation of concerns

Test Coverage: ⭐⭐⭐⭐ (4/5) - Comprehensive unit tests, needs more integration tests

Performance: ⭐⭐⭐ (3/5) - Several potential bottlenecks identified

Security: ⭐⭐⭐ (3/5) - Needs input validation and privacy improvements

This is a solid architectural improvement that properly migrates to bitkit-core. The critical issues around race conditions and performance should be addressed before merging, but the overall direction is excellent. The test coverage is impressive (+623 lines) and shows careful attention to correctness.

Great work on this migration! Let me know if you'd like me to elaborate on any of these points or if you have questions about the recommended fixes.

@synonymdevsynonymdev deleted a comment from claudeBotNov 24, 2025
@ovitrif
ovitrif merged commit c93b451 into masterNov 24, 2025
16 of 17 checks passed
@ovitrif
ovitrif deleted the use-preactivity-metadata branch November 24, 2025 17:46
Sign up for freeto 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.

Tag set upfront on the receive BTC invoice is not displayed on incoming transaction

3 participants

@ben-kaufman@jvsena42@ovitrif