From aa613c407847bfe92b29114897cea0506a6b1c4d Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Sat, 8 Aug 2026 21:09:26 +0700 Subject: [PATCH 1/4] fix(wallet): restored internal transfers show their route and amount After a wipe & recover, PersistentAssetLock rows don't survive, so asset-lock funding txs rendered "Internal Transfer - 0 DASH"; shielded Sent rows showed no destination at all. ShieldedTxLookup now reconstructs missing locks from the persisted raw tx bytes (real locked amount; full Core->Platform treatment when the credit outputs pay own persisted Platform addresses; an explicit unknown-destination sentinel otherwise), and shielded Sent entries decode their 43-byte Orchard counterparty to the DIP-0018 bech32m form for the row pill and the detail sheet's From/To rows. Co-Authored-By: Claude Fable 5 --- .../PlatformAddressSyncCoordinator.swift | 85 +++++++++++++++++++ .../Model/RawTransactionInspector.swift | 55 +++++++++--- .../Transactions/Model/Transaction.swift | 14 ++- .../Sources/UI/Home/Views/HomeViewModel.swift | 25 ++++++ .../Home/Views/ShieldedActivityHistory.swift | 26 ++++-- 5 files changed, 184 insertions(+), 21 deletions(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/PlatformAddressSyncCoordinator.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/PlatformAddressSyncCoordinator.swift index c7142c9740..3fe118d42a 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/PlatformAddressSyncCoordinator.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/PlatformAddressSyncCoordinator.swift @@ -1461,6 +1461,19 @@ final class ShieldedTxLookup { /// 2 = IdentityTopUpNotBound, 3 = IdentityInvitation. private static let identityFundingTypes = 0...3 + /// App-side sentinel (never emitted by the SDK's funding-type enum) for a + /// lock reconstructed from raw transaction bytes whose destination can't + /// be proven: the amount is consensus-parsed truth, but whether it funded + /// an identity, a Platform address, or the shielded pool is unknown. + static let reconstructedUnknownFundingType = -1 + + /// App-side sentinel for `statusRaw` on reconstructed entries: the lock is + /// confirmed on-chain but its consumption state is unknown (the SDK's + /// `PersistentAssetLock` row didn't survive the wallet restore). Outside + /// both the pending window (1…3) and consumed (4), so reconstructed rows + /// never render "Pending" and never claim success. + static let reconstructedStatus = -1 + private static let logger = Logger( subsystem: "org.dashfoundation.dash", category: "swift-sdk-migration.shielded-tx-lookup") @@ -1508,6 +1521,14 @@ final class ShieldedTxLookup { entry(forTxidHex: txidHex, fundingType: Self.platformFundingType) } + /// Snapshot entry for an asset lock reconstructed from raw tx bytes after + /// a restore — real locked amount, unknown destination and consumption + /// (see `reconstructedUnknownFundingType`). Thread-safe; touches no + /// SwiftData. + func reconstructedLockInfo(forTxidHex txidHex: String) -> ShieldedLockInfo? { + entry(forTxidHex: txidHex, fundingType: Self.reconstructedUnknownFundingType) + } + /// Snapshot entry for an identity funding lock (types 0…3 — registration, /// top-up, invitation). `fundingTypeRaw` distinguishes the variants. /// Thread-safe; touches no SwiftData. @@ -1563,6 +1584,7 @@ final class ShieldedTxLookup { if let existing = map[txid], existing.statusRaw >= info.statusRaw { continue } map[txid] = info } + addReconstructedLocks(to: &map, context: container.mainContext) store(map) Self.logger.info("🛡️ SHIELD-TX :: snapshot \(map.count, privacy: .public) funding tx(s) (shielded + platform)") // Diagnostic: if asset locks exist but none matched the shielded @@ -1577,6 +1599,69 @@ final class ShieldedTxLookup { } } + /// Restore-time fallback: `PersistentAssetLock` rows are SDK-recorded at + /// execution and do NOT survive a wipe & recover, so a restored wallet's + /// asset-lock funding txs otherwise render "Internal Transfer — 0 DASH". + /// For every persisted AssetLock transaction with no store row, parse the + /// credit outputs from the raw bytes (consensus truth) and add: + /// - funding type 4 when every credit output pays one of the wallet's own + /// persisted Platform addresses — the full Core → Platform treatment; + /// - a `reconstructedUnknownFundingType` entry otherwise — real amount, + /// no destination claim (one-time identity/shield keys are not + /// distinguishable from the L1 tx alone). + /// Store-backed entries always win (`map` is checked first). + @MainActor + private func addReconstructedLocks(to map: inout [String: ShieldedLockInfo], context: ModelContext) { + let assetLockKind = TransactionTypeKind.assetLock.rawValue + let descriptor = FetchDescriptor( + predicate: #Predicate { $0.transactionTypeKind == assetLockKind }) + guard let rows = try? context.fetch(descriptor), !rows.isEmpty else { return } + + // Own DIP-17 Platform address key hashes, for the provable-route case. + let ownPlatformHashes: Set = { + let addresses = (try? context.fetch(FetchDescriptor())) ?? [] + return Set(addresses.map { $0.addressHash }) + }() + + var reconstructed = 0 + for row in rows { + let txid = Transaction.displayHex(row.txid).lowercased() + if map[txid] != nil { continue } + guard !row.transactionData.isEmpty, + let parsed = try? ParsedRawTransaction(data: row.transactionData), + let payload = parsed.extraPayload, + let creditOutputs = RawTransactionInspector.assetLockCreditOutputs(payload: payload) else { + continue + } + let amount = creditOutputs.reduce(UInt64(0)) { $0 + $1.valueDuffs } + guard amount > 0 else { continue } + // The lock outpoint's vout is the index of the OP_RETURN output + // that carries the locked value on L1. Skip on ambiguity — a + // reconstructed entry never feeds a recovery resume, but a wrong + // vout shouldn't exist even unused. + let opReturnIndexes = parsed.outputs.enumerated() + .filter { $0.element.scriptPubKey.first == 0x6a } + .map { $0.offset } + guard opReturnIndexes.count == 1, let voutIndex = opReturnIndexes.first else { continue } + + let keyHashes = creditOutputs.compactMap { RawTransactionInspector.p2pkhKeyHash(script: $0.script) } + let paysOnlyOwnPlatformAddresses = keyHashes.count == creditOutputs.count + && keyHashes.allSatisfy { ownPlatformHashes.contains($0) } + + map[txid] = ShieldedLockInfo( + amountDuffs: amount, + statusRaw: Self.reconstructedStatus, + vout: UInt32(voutIndex), + fundingTypeRaw: paysOnlyOwnPlatformAddresses + ? Self.platformFundingType + : Self.reconstructedUnknownFundingType) + reconstructed += 1 + } + if reconstructed > 0 { + Self.logger.info("🛡️ SHIELD-TX :: reconstructed \(reconstructed, privacy: .public) asset lock(s) from raw tx bytes (no store row)") + } + } + private func store(_ map: [String: ShieldedLockInfo]) { lock.lock() infoByTxid = map diff --git a/DashWallet/Sources/Models/Transactions/Model/RawTransactionInspector.swift b/DashWallet/Sources/Models/Transactions/Model/RawTransactionInspector.swift index 4434f4cb6d..ff190f818a 100644 --- a/DashWallet/Sources/Models/Transactions/Model/RawTransactionInspector.swift +++ b/DashWallet/Sources/Models/Transactions/Model/RawTransactionInspector.swift @@ -215,6 +215,42 @@ enum RawTransactionInspector { // MARK: - Special transaction payloads + /// One credit output of an asset-lock payload: the locked value and the + /// destination scriptPubKey it credits on Platform. + struct AssetLockCreditOutput { + let valueDuffs: UInt64 + let script: Data + } + + /// Consensus-decode the credit outputs of a DIP-2 asset-lock payload + /// (u8 version, varint count, TxOuts). Nil when the bytes don't parse as + /// that shape — callers must treat the lock as undecodable rather than + /// substitute a guess. Shared by the inspector's field list and + /// `ShieldedTxLookup`'s restore-time reconstruction. + static func assetLockCreditOutputs(payload: Data) -> [AssetLockCreditOutput]? { + var reader = ByteReader(payload) + guard (try? reader.readUInt8()) != nil, + let count = try? reader.readVarInt(), + count > 0, count <= 32 else { return nil } + var outputs: [AssetLockCreditOutput] = [] + for _ in 0 ..< count { + guard let value = try? reader.readUInt64(), + let scriptLength = try? reader.readVarInt(), + let script = try? reader.readBytes(Int(scriptLength)) else { return nil } + outputs.append(AssetLockCreditOutput(valueDuffs: value, script: script)) + } + return outputs + } + + /// The 20-byte pubkey hash of a P2PKH script, or nil for any other shape. + static func p2pkhKeyHash(script: Data) -> Data? { + let b = [UInt8](script) + guard b.count == 25, b[0] == 0x76, b[1] == 0xa9, b[2] == 0x14, b[23] == 0x88, b[24] == 0xac else { + return nil + } + return Data(b[3 ..< 23]) + } + /// DIP-2 special transaction names, keyed by the tx `type` field. static func specialTypeName(_ type: UInt16) -> String? { switch type { @@ -253,20 +289,15 @@ enum RawTransactionInspector { } } case 8: // Asset lock: u8 version, varint count, credit outputs (TxOuts). - var reader = ByteReader(payload) - if let version = try? reader.readUInt8(), - let count = try? reader.readVarInt() { - fields.append(.init(label: "Payload version", value: "\(version)")) - fields.append(.init(label: "Credit outputs", value: "\(count)")) - for i in 0 ..< min(count, 16) { - guard let value = try? reader.readUInt64(), - let scriptLength = try? reader.readVarInt(), - let script = try? reader.readBytes(Int(scriptLength)) else { break } - let destination = ScriptAddressCodec.address(forScript: script, network: network) - ?? script.map { String(format: "%02x", $0) }.joined() + if let creditOutputs = assetLockCreditOutputs(payload: payload) { + fields.append(.init(label: "Payload version", value: "\(payload[payload.startIndex])")) + fields.append(.init(label: "Credit outputs", value: "\(creditOutputs.count)")) + for (i, output) in creditOutputs.enumerated() { + let destination = ScriptAddressCodec.address(forScript: output.script, network: network) + ?? output.script.map { String(format: "%02x", $0) }.joined() fields.append(.init( label: String(format: "Credit output %d", i), - value: "\(value.formattedDashAmountWithoutCurrencySymbol) → \(destination)")) + value: "\(output.valueDuffs.formattedDashAmountWithoutCurrencySymbol) → \(destination)")) } } default: diff --git a/DashWallet/Sources/Models/Transactions/Model/Transaction.swift b/DashWallet/Sources/Models/Transactions/Model/Transaction.swift index cdee9ab057..6ef2f62a52 100644 --- a/DashWallet/Sources/Models/Transactions/Model/Transaction.swift +++ b/DashWallet/Sources/Models/Transactions/Model/Transaction.swift @@ -307,6 +307,15 @@ class Transaction: TransactionDataItem, Identifiable { private var identityFundingAmountDuffs: UInt64? { identityFundingLockInfo?.amountDuffs } + /// Locked amount for an asset lock reconstructed from raw tx bytes after + /// a restore (`ShieldedTxLookup.reconstructedLockInfo`): the destination + /// is unprovable, so the row keeps its generic "Internal Transfer" + /// presentation, but the amount is consensus-parsed truth instead of the + /// 0 the net-change view derives for a self-directed lock. + private var reconstructedLockAmountDuffs: UInt64? { + ShieldedTxLookup.shared.reconstructedLockInfo(forTxidHex: shieldedDisplayTxid)?.amountDuffs + } + /// True when this is the funding tx of an identity registration/top-up/ /// invitation. var isIdentityFundingTransfer: Bool { identityFundingLockInfo != nil } @@ -389,7 +398,7 @@ class Transaction: TransactionDataItem, Identifiable { // asset lock; surface the real locked amount the SDK recorded // instead of the 0 the generic logic below derives for a // self-directed move. - if let locked = shieldedTransferAmountDuffs ?? platformFundingAmountDuffs ?? identityFundingAmountDuffs { return locked } + if let locked = shieldedTransferAmountDuffs ?? platformFundingAmountDuffs ?? identityFundingAmountDuffs ?? reconstructedLockAmountDuffs { return locked } let fee = Int64(snapshot.fee ?? 0) switch direction { case .received: @@ -419,6 +428,7 @@ class Transaction: TransactionDataItem, Identifiable { ?? shieldedTransferAmountDuffs ?? platformFundingAmountDuffs ?? identityFundingAmountDuffs + ?? reconstructedLockAmountDuffs ?? _dashAmount } var signedDashAmount: Int64 { @@ -454,7 +464,7 @@ class Transaction: TransactionDataItem, Identifiable { // The shielded / DashPay-payment amount is read live (see // `dashAmount`), so compute its fiat live too; other rows keep the // lazily-cached value. - if dashPayPayment != nil || shieldedTransferAmountDuffs != nil || platformFundingAmountDuffs != nil || identityFundingAmountDuffs != nil { + if dashPayPayment != nil || shieldedTransferAmountDuffs != nil || platformFundingAmountDuffs != nil || identityFundingAmountDuffs != nil || reconstructedLockAmountDuffs != nil { return userInfo?.fiatAmountString(from: dashAmount) ?? NSLocalizedString("Not available", comment: "") } return storedFiatAmount diff --git a/DashWallet/Sources/UI/Home/Views/HomeViewModel.swift b/DashWallet/Sources/UI/Home/Views/HomeViewModel.swift index a939bc8246..16dd420cb0 100644 --- a/DashWallet/Sources/UI/Home/Views/HomeViewModel.swift +++ b/DashWallet/Sources/UI/Home/Views/HomeViewModel.swift @@ -1560,6 +1560,19 @@ class SwiftDashSDKWalletSource: TransactionSource { items.append(ShieldedActivityItem( row: row, amountCreditsOverride: reconstructedAmountCredits)) + case ShieldedActivityItem.Kind.sent.rawValue: + // A shielded → shielded send's counterparty is the recipient's + // 43-byte raw Orchard address (live-recorded, or OVK-recovered + // by the restore scan). Surface it so the row and detail sheet + // name where the money went instead of a bare "Sent / + // Shielded". Sent entries are outgoing to a non-own address by + // the recorder's classification, hence external. + let address = shieldedDestinationAddress(counterparty: row.counterparty) + items.append(ShieldedActivityItem( + row: row, + amountCreditsOverride: reconstructedAmountCredits, + destinationAddress: address, + isExternalDestination: address != nil)) default: items.append(ShieldedActivityItem( row: row, @@ -1726,6 +1739,18 @@ class SwiftDashSDKWalletSource: TransactionSource { isTestnet: WalletEnvironment.isTestnet) } + /// Decode a shielded send's counterparty (43-byte raw Orchard address) to + /// its DIP-0018 display form: HRP `dash`/`tdash`, payload = 0x10 type + /// byte + the raw address bytes (same encoding as + /// `PaymentsLandingViewModel.reloadShieldedAddress`). Nil for empty / + /// non-43-byte counterparties. + private static func shieldedDestinationAddress(counterparty: Data) -> String? { + guard counterparty.count == 43 else { return nil } + return Bech32m.encode( + hrp: Bech32m.platformHrp(mainnet: !WalletEnvironment.isTestnet), + data: Data([0x10]) + counterparty) + } + /// True when `address` is one of the ACTIVE wallet's own DIP-17 /// Platform Payment addresses (same active-wallet scoping rationale /// as `isActiveWalletCoreAddress`). diff --git a/DashWallet/Sources/UI/Home/Views/ShieldedActivityHistory.swift b/DashWallet/Sources/UI/Home/Views/ShieldedActivityHistory.swift index 174297de9e..ddc424a77d 100644 --- a/DashWallet/Sources/UI/Home/Views/ShieldedActivityHistory.swift +++ b/DashWallet/Sources/UI/Home/Views/ShieldedActivityHistory.swift @@ -162,7 +162,7 @@ struct ShieldedActivityItem: Identifiable { switch kind { case .shield, .shieldFromAssetLock: return NSLocalizedString("Platform → Shielded", comment: "Transfer of own funds from the Platform balance into the private shielded balance") - case .unshield, .withdrawal: + case .unshield, .withdrawal, .sent: if isExternalDestination { // External destination: show where the money went, // shortened to row-pill size (the detail sheet carries @@ -172,10 +172,16 @@ struct ShieldedActivityItem: Identifiable { } return NSLocalizedString("Shielded", comment: "Shielded activity: funds moved into the private shielded balance") } - return kind == .unshield - ? NSLocalizedString("Shielded → Platform", comment: "Transfer of own funds from the private shielded balance to the Platform balance") - : NSLocalizedString("Shielded → Transparent", comment: "Transfer of own funds from the private shielded balance back to the transparent wallet") - case .received, .sent, .identityCreate, .shieldedSpend: + switch kind { + case .unshield: + return NSLocalizedString("Shielded → Platform", comment: "Transfer of own funds from the private shielded balance to the Platform balance") + case .withdrawal: + return NSLocalizedString("Shielded → Transparent", comment: "Transfer of own funds from the private shielded balance back to the transparent wallet") + default: + // A Sent row whose recipient couldn't be decoded. + return NSLocalizedString("Shielded", comment: "Shielded activity: funds moved into the private shielded balance") + } + case .received, .identityCreate, .shieldedSpend: return NSLocalizedString("Shielded", comment: "Shielded activity: funds moved into the private shielded balance") } } @@ -221,7 +227,7 @@ struct ShieldedActivityItem: Identifiable { /// From/To wording for the detail sheet. Internal moves name the /// user's own balances on both sides (a guarantee — see the fetch - /// doc); an external unshield/withdrawal names the destination + /// doc); an external unshield/withdrawal/send names the destination /// address (or an honest "External address" when the counterparty /// script couldn't be decoded). var internalMoveRoute: (source: String, destination: String)? { @@ -237,7 +243,13 @@ struct ShieldedActivityItem: Identifiable { return (shielded, destinationAddress ?? fallback) } return kind == .unshield ? (shielded, platform) : (shielded, transparent) - case .received, .sent, .identityCreate, .shieldedSpend: return nil + case .sent: + // Only when the recipient address decoded — a bare Sent row + // (no counterparty recovered) keeps the sheet route-less + // rather than claiming a destination we don't know. + guard let destinationAddress else { return nil } + return (shielded, destinationAddress) + case .received, .identityCreate, .shieldedSpend: return nil } } From cbf806526032406963fac8c91fd104c63c96e3d1 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Sat, 8 Aug 2026 21:26:06 +0700 Subject: [PATCH 2/4] fix(wallet): classify reconstructed asset locks via funding-account pools Every asset-lock credit output pays a one-time address derived from a purpose-specific funding account (identity registration/top-up/ invitation, Platform address top-up, shielded top-up), and those address pools survive a restore as PersistentCoreAddress rows. Match the parsed credit outputs against them to recover the exact funding type, so a restored Transparent->Shielded transfer renders the full Core->Shielded treatment instead of a generic unknown-destination "Internal Transfer". Co-Authored-By: Claude Fable 5 --- .../PlatformAddressSyncCoordinator.swift | 74 ++++++++++++++----- 1 file changed, 56 insertions(+), 18 deletions(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/PlatformAddressSyncCoordinator.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/PlatformAddressSyncCoordinator.swift index 3fe118d42a..42c6b3a0d8 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/PlatformAddressSyncCoordinator.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/PlatformAddressSyncCoordinator.swift @@ -1603,25 +1603,26 @@ final class ShieldedTxLookup { /// execution and do NOT survive a wipe & recover, so a restored wallet's /// asset-lock funding txs otherwise render "Internal Transfer — 0 DASH". /// For every persisted AssetLock transaction with no store row, parse the - /// credit outputs from the raw bytes (consensus truth) and add: - /// - funding type 4 when every credit output pays one of the wallet's own - /// persisted Platform addresses — the full Core → Platform treatment; - /// - a `reconstructedUnknownFundingType` entry otherwise — real amount, - /// no destination claim (one-time identity/shield keys are not - /// distinguishable from the L1 tx alone). - /// Store-backed entries always win (`map` is checked first). + /// credit outputs from the raw bytes (consensus truth) and classify the + /// destination through the wallet's persisted funding-account address + /// pools: each credit output pays a one-time address the wallet derived + /// from a purpose-specific account (identity registration/top-up/ + /// invitation, Platform address top-up, shielded top-up — accountType + /// 2…7), and those pools DO survive a restore as `PersistentCoreAddress` + /// rows. A match yields the exact funding type and the full existing + /// route treatment; no match yields a `reconstructedUnknownFundingType` + /// entry — real amount, no destination claim. Store-backed entries + /// always win (`map` is checked first). @MainActor private func addReconstructedLocks(to map: inout [String: ShieldedLockInfo], context: ModelContext) { let assetLockKind = TransactionTypeKind.assetLock.rawValue let descriptor = FetchDescriptor( predicate: #Predicate { $0.transactionTypeKind == assetLockKind }) guard let rows = try? context.fetch(descriptor), !rows.isEmpty else { return } + guard let walletId = SwiftDashSDKHost.shared.wallet?.walletId else { return } - // Own DIP-17 Platform address key hashes, for the provable-route case. - let ownPlatformHashes: Set = { - let addresses = (try? context.fetch(FetchDescriptor())) ?? [] - return Set(addresses.map { $0.addressHash }) - }() + let fundingTypeByAddress = Self.fundingAccountTypeByAddress(walletId: walletId, in: context) + let network: PaymentNetwork = WalletEnvironment.isTestnet ? .testnet : .mainnet var reconstructed = 0 for row in rows { @@ -1644,17 +1645,24 @@ final class ShieldedTxLookup { .map { $0.offset } guard opReturnIndexes.count == 1, let voutIndex = opReturnIndexes.first else { continue } - let keyHashes = creditOutputs.compactMap { RawTransactionInspector.p2pkhKeyHash(script: $0.script) } - let paysOnlyOwnPlatformAddresses = keyHashes.count == creditOutputs.count - && keyHashes.allSatisfy { ownPlatformHashes.contains($0) } + // Funding type: every credit output must resolve to the SAME + // funding account — mixed or unmatched destinations stay unknown. + let matchedTypes = Set(creditOutputs.map { output -> Int in + guard let address = ScriptAddressCodec.address(forScript: output.script, network: network), + let fundingType = fundingTypeByAddress[address] else { + return Self.reconstructedUnknownFundingType + } + return fundingType + }) + let fundingType = matchedTypes.count == 1 + ? matchedTypes.first ?? Self.reconstructedUnknownFundingType + : Self.reconstructedUnknownFundingType map[txid] = ShieldedLockInfo( amountDuffs: amount, statusRaw: Self.reconstructedStatus, vout: UInt32(voutIndex), - fundingTypeRaw: paysOnlyOwnPlatformAddresses - ? Self.platformFundingType - : Self.reconstructedUnknownFundingType) + fundingTypeRaw: fundingType) reconstructed += 1 } if reconstructed > 0 { @@ -1662,6 +1670,36 @@ final class ShieldedTxLookup { } } + /// Credit-output address → `ManagedAssetLockManager.FundingType` raw + /// value, from the active wallet's persisted funding-account pools. + /// Account type tags (see `accountTypeName`): 2 Identity Registration, + /// 3 Identity Top-Up, 4 Identity Top-Up (Unbound), 5 Identity + /// Invitation, 6 Asset Lock Address Top-Up, 7 Asset Lock Shielded + /// Address Top-Up — mapped to funding types 0…5 in the same order. + @MainActor + private static func fundingAccountTypeByAddress(walletId: Data, in context: ModelContext) -> [String: Int] { + // Accounts are a tiny table; fetch all and filter in Swift rather + // than fighting `#Predicate` relationship-traversal rules. + let accounts = (try? context.fetch(FetchDescriptor())) ?? [] + var byAddress: [String: Int] = [:] + for account in accounts where account.wallet.walletId == walletId { + let fundingType: Int + switch account.accountType { + case 2: fundingType = 0 // IdentityRegistration + case 3: fundingType = 1 // IdentityTopUp + case 4: fundingType = 2 // IdentityTopUpNotBound + case 5: fundingType = 3 // IdentityInvitation + case 6: fundingType = 4 // AssetLockAddressTopUp + case 7: fundingType = 5 // AssetLockShieldedAddressTopUp + default: continue + } + for address in account.coreAddresses { + byAddress[address.address] = fundingType + } + } + return byAddress + } + private func store(_ map: [String: ShieldedLockInfo]) { lock.lock() infoByTxid = map From b42eb63313fa5c83dc00f95b6d2f53c3e15d788a Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Sat, 8 Aug 2026 21:55:19 +0700 Subject: [PATCH 3/4] fix(wallet): address PR #939 review findings - ByteReader gains a UInt64-length readBytes that rejects lengths above Int.max instead of trapping on the Int(_:) conversion; all CompactSize script/payload reads go through it. - A shielded Sent destination is marked external only when provably not the wallet's own: an intra-wallet transfer leaves a Received row under the same entry id, and the wallet's default Orchard address is checked directly. - internalMoveRoute doc: undecodable Sent counterparties stay route-less. Co-Authored-By: Claude Fable 5 --- .../Model/RawTransactionInspector.swift | 16 ++++++++--- .../Sources/UI/Home/Views/HomeViewModel.swift | 28 +++++++++++++++++-- .../Home/Views/ShieldedActivityHistory.swift | 5 ++-- 3 files changed, 40 insertions(+), 9 deletions(-) diff --git a/DashWallet/Sources/Models/Transactions/Model/RawTransactionInspector.swift b/DashWallet/Sources/Models/Transactions/Model/RawTransactionInspector.swift index ff190f818a..9debcc9d8d 100644 --- a/DashWallet/Sources/Models/Transactions/Model/RawTransactionInspector.swift +++ b/DashWallet/Sources/Models/Transactions/Model/RawTransactionInspector.swift @@ -236,7 +236,7 @@ enum RawTransactionInspector { for _ in 0 ..< count { guard let value = try? reader.readUInt64(), let scriptLength = try? reader.readVarInt(), - let script = try? reader.readBytes(Int(scriptLength)) else { return nil } + let script = try? reader.readBytes(length: scriptLength) else { return nil } outputs.append(AssetLockCreditOutput(valueDuffs: value, script: script)) } return outputs @@ -347,7 +347,7 @@ struct ParsedRawTransaction { let prevTxid = try reader.readBytes(32) let prevVout = try reader.readUInt32() let scriptLength = try reader.readVarInt() - let scriptSig = try reader.readBytes(Int(scriptLength)) + let scriptSig = try reader.readBytes(length: scriptLength) let sequence = try reader.readUInt32() return Input(prevTxid: prevTxid, prevVout: prevVout, scriptSig: scriptSig, sequence: sequence) } @@ -357,7 +357,7 @@ struct ParsedRawTransaction { outputs = try (0 ..< outputCount).map { _ in let value = try reader.readUInt64() let scriptLength = try reader.readVarInt() - let script = try reader.readBytes(Int(scriptLength)) + let script = try reader.readBytes(length: scriptLength) return Output(valueDuffs: value, scriptPubKey: script) } @@ -365,7 +365,7 @@ struct ParsedRawTransaction { if type > 0, reader.remaining > 0 { let payloadLength = try reader.readVarInt() - extraPayload = try reader.readBytes(Int(payloadLength)) + extraPayload = try reader.readBytes(length: payloadLength) } else { extraPayload = nil } @@ -439,4 +439,12 @@ private struct ByteReader { defer { offset += count } return Data(bytes[offset ..< offset + count]) } + + /// Consensus lengths arrive as CompactSize `UInt64`s; a plain `Int(_:)` + /// conversion traps on values above `Int.max`, which malformed bytes can + /// encode. Reject those as out-of-bounds instead of crashing. + mutating func readBytes(length: UInt64) throws -> Data { + guard let count = Int(exactly: length) else { throw ReadError.outOfBounds } + return try readBytes(count) + } } diff --git a/DashWallet/Sources/UI/Home/Views/HomeViewModel.swift b/DashWallet/Sources/UI/Home/Views/HomeViewModel.swift index 16dd420cb0..20e379dac4 100644 --- a/DashWallet/Sources/UI/Home/Views/HomeViewModel.swift +++ b/DashWallet/Sources/UI/Home/Views/HomeViewModel.swift @@ -1414,7 +1414,15 @@ class SwiftDashSDKWalletSource: TransactionSource { guard let rows = try? context.fetch(descriptor) else { return [] } var byEntry: [Data: PersistentShieldedActivity] = [:] + // Entry ids that also produced a Received projection: an + // intra-wallet transfer writes Sent + Received rows for the same + // operation (see the dedupe doc above), so a surviving Sent row + // whose entry id is in here paid one of the wallet's own accounts. + var receivedEntryIds: Set = [] for row in rows where row.kindTag != ShieldedActivityItem.Kind.shieldFromAssetLock.rawValue { + if row.kindTag == ShieldedActivityItem.Kind.received.rawValue { + receivedEntryIds.insert(row.entryId) + } if let existing = byEntry[row.entryId] { if shouldPreferShieldedProjection(row, over: existing) { byEntry[row.entryId] = row @@ -1427,6 +1435,16 @@ class SwiftDashSDKWalletSource: TransactionSource { let noteValueByCmx = shieldedNoteValueByCmx(in: context, walletId: walletId) let outgoingNoteValueByCmx = outgoingShieldedNoteValueByCmx(in: context, walletId: walletId) + // The wallet's own default Orchard address (raw 43 bytes), for the + // Sent-destination ownership check. Nil until the shielded + // sub-wallet is bound — then the Received-row evidence still covers + // live intra-wallet transfers. + let ownShieldedRaw43: Data? = onMain { + guard let manager = SwiftDashSDKHost.shared.manager, + let wallet = SwiftDashSDKHost.shared.wallet else { return nil } + return ((try? manager.shieldedDefaultAddress(walletId: wallet.walletId)) ?? nil) + } + var items: [ShieldedActivityItem] = [] for row in byEntry.values { let reconstructedAmountCredits = projectedShieldedAmountCredits( @@ -1565,14 +1583,18 @@ class SwiftDashSDKWalletSource: TransactionSource { // 43-byte raw Orchard address (live-recorded, or OVK-recovered // by the restore scan). Surface it so the row and detail sheet // name where the money went instead of a bare "Sent / - // Shielded". Sent entries are outgoing to a non-own address by - // the recorder's classification, hence external. + // Shielded". External only when the destination is provably + // not the wallet's own: an intra-wallet transfer leaves a + // Received row under the same entry id, and a send to the + // wallet's default Orchard address is its own funds either way. let address = shieldedDestinationAddress(counterparty: row.counterparty) + let isOwnDestination = receivedEntryIds.contains(row.entryId) + || (ownShieldedRaw43 != nil && row.counterparty == ownShieldedRaw43) items.append(ShieldedActivityItem( row: row, amountCreditsOverride: reconstructedAmountCredits, destinationAddress: address, - isExternalDestination: address != nil)) + isExternalDestination: address != nil && !isOwnDestination)) default: items.append(ShieldedActivityItem( row: row, diff --git a/DashWallet/Sources/UI/Home/Views/ShieldedActivityHistory.swift b/DashWallet/Sources/UI/Home/Views/ShieldedActivityHistory.swift index ddc424a77d..82b1c19934 100644 --- a/DashWallet/Sources/UI/Home/Views/ShieldedActivityHistory.swift +++ b/DashWallet/Sources/UI/Home/Views/ShieldedActivityHistory.swift @@ -227,9 +227,10 @@ struct ShieldedActivityItem: Identifiable { /// From/To wording for the detail sheet. Internal moves name the /// user's own balances on both sides (a guarantee — see the fetch - /// doc); an external unshield/withdrawal/send names the destination + /// doc); an external unshield/withdrawal names the destination /// address (or an honest "External address" when the counterparty - /// script couldn't be decoded). + /// script couldn't be decoded); a Sent entry names its decoded + /// recipient and stays route-less when the counterparty didn't decode. var internalMoveRoute: (source: String, destination: String)? { let platform = NSLocalizedString("Your Platform balance", comment: "Shielded activity: source/destination of an internal move") let shielded = NSLocalizedString("Your Shielded balance", comment: "Shielded activity: source/destination of an internal move") From f33bc3330a2d99ce64b31a54695a9b2b1300486e Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Sat, 8 Aug 2026 21:59:01 +0700 Subject: [PATCH 4/4] fix(wallet): key the Sent-ownership lookup by the fetched walletId The default-Orchard-address lookup re-read the host's active wallet on a later main hop; a wallet switch between the two reads could compare against the wrong wallet's address. Use the walletId the activity rows were fetched with. Co-Authored-By: Claude Fable 5 --- .../Sources/UI/Home/Views/HomeViewModel.swift | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/DashWallet/Sources/UI/Home/Views/HomeViewModel.swift b/DashWallet/Sources/UI/Home/Views/HomeViewModel.swift index 20e379dac4..ff1a658fe0 100644 --- a/DashWallet/Sources/UI/Home/Views/HomeViewModel.swift +++ b/DashWallet/Sources/UI/Home/Views/HomeViewModel.swift @@ -1436,13 +1436,14 @@ class SwiftDashSDKWalletSource: TransactionSource { let outgoingNoteValueByCmx = outgoingShieldedNoteValueByCmx(in: context, walletId: walletId) // The wallet's own default Orchard address (raw 43 bytes), for the - // Sent-destination ownership check. Nil until the shielded - // sub-wallet is bound — then the Received-row evidence still covers - // live intra-wallet transfers. + // Sent-destination ownership check. Keyed by the SAME walletId the + // rows were fetched with (not a re-read of the host's active wallet, + // which could have switched between the two main hops). Nil until + // the shielded sub-wallet is bound — then the Received-row evidence + // still covers live intra-wallet transfers. let ownShieldedRaw43: Data? = onMain { - guard let manager = SwiftDashSDKHost.shared.manager, - let wallet = SwiftDashSDKHost.shared.wallet else { return nil } - return ((try? manager.shieldedDefaultAddress(walletId: wallet.walletId)) ?? nil) + guard let manager = SwiftDashSDKHost.shared.manager else { return nil } + return ((try? manager.shieldedDefaultAddress(walletId: walletId)) ?? nil) } var items: [ShieldedActivityItem] = []