@@ -189,9 +189,35 @@ enum WalletKeyHealthChecker {
189189 keyId : kid ,
190190 network : network
191191 )
192- derivedHex = preview . publicKeyHex
193192
194- if preview . publicKeyData == row . publicKeyData {
193+ // `row.publicKeyData` stores whatever shape was
194+ // registered on Platform — 33-byte compressed
195+ // pubkey for `.ecdsaSecp256k1`, 20-byte HASH160
196+ // for `.ecdsaHash160`. The Rust-derived preview
197+ // is always the raw 33-byte pubkey; hash it
198+ // ourselves before comparing for HASH160 rows.
199+ // (Other variants — BLS, BIP13 script-hash,
200+ // EdDSA — aren't produced by this preview path
201+ // today; treat them as `notSupported` so the
202+ // diagnostic surfaces them instead of silently
203+ // misclassifying them as orphans.)
204+ let derivedComparableHex : String ?
205+ switch row . keyTypeEnum ?? . ecdsaSecp256k1 {
206+ case . ecdsaSecp256k1 :
207+ derivedComparableHex = preview . publicKeyHex
208+ derivedHex = preview . publicKeyHex
209+ case . ecdsaHash160 :
210+ let hashHex = SwiftDashSDK . KeychainManager
211+ . computePublicKeyHashHex ( preview . publicKeyData )
212+ derivedComparableHex = hashHex . isEmpty ? nil : hashHex
213+ derivedHex = hashHex
214+ case . bls12_381 , . bip13ScriptHash , . eddsa25519Hash160 :
215+ derivedComparableHex = nil
216+ derivedHex = preview . publicKeyHex
217+ }
218+
219+ if let derivedComparableHex ,
220+ derivedComparableHex . caseInsensitiveCompare ( storedHex ) == . orderedSame {
195221 // pubkey matches the wallet's mnemonic →
196222 // look up the keychain bytes at the expected
197223 // walletId-namespaced account.
@@ -224,9 +250,20 @@ enum WalletKeyHealthChecker {
224250 reason : " No new-format Keychain entry (legacy-only entries don't count) "
225251 )
226252 }
253+ } else if derivedComparableHex == nil {
254+ // Key type isn't one the diagnostic knows
255+ // how to compare against a Rust-derived
256+ // pubkey today (BLS / BIP13 / EdDSA). Report
257+ // it as orphan with a clear reason so the
258+ // user knows we can't verify it, rather than
259+ // silently passing.
260+ let label = row . keyTypeEnum ? . name ?? " type \( row . keyType ) "
261+ status = . orphan (
262+ reason : " Key type \( label ) isn't supported by the diagnostic — can't verify against derived pubkey "
263+ )
227264 } else {
228265 status = . orphan (
229- reason : " Stored pubkey \( storedHex . prefix ( 12 ) ) … doesn't match wallet's derivation \( derivedHex . prefix ( 12 ) ) … "
266+ reason : " Stored \( storedHex . prefix ( 12 ) ) … doesn't match wallet's derivation \( derivedHex . prefix ( 12 ) ) … "
230267 )
231268 }
232269 } catch {
@@ -262,27 +299,53 @@ enum WalletKeyHealthChecker {
262299 return reports
263300 }
264301
302+ /// Per-key result of a rederive pass. `success` is the count of
303+ /// keys whose Keychain entry was rewritten; `failures` lists each
304+ /// key the pass tried and couldn't fix, with a reason — useful so
305+ /// the sheet can show the user *which* key is stuck (not just
306+ /// "Re-derived 0 keys").
307+ struct RederiveOutcome {
308+ let success : Int
309+ /// `(keyId, reason)` for each `.needsRederive` key the loop
310+ /// touched but did not fix.
311+ let failures : [ ( UInt32 , String ) ]
312+ }
313+
265314 /// Re-derive every key in `report` whose status is
266315 /// `.needsRederive`, write fresh Keychain entries (at the new
267316 /// walletId-namespaced account), and update each
268317 /// `PersistentPublicKey.privateKeyKeychainIdentifier` to point
269- /// at the new account. Returns the number of keys fixed.
318+ /// at the new account.
319+ ///
320+ /// Returns a `RederiveOutcome` with both the count fixed and a
321+ /// per-key list of failures. Individual key failures are
322+ /// collected rather than thrown so one bad key doesn't block
323+ /// repair of the rest of the identity's keys; throws only when
324+ /// the whole batch is unrecoverable (e.g. the SwiftData save at
325+ /// the end fails).
270326 @ MainActor
271327 static func rederive (
272328 report : WalletIdentityKeyHealthReport ,
273329 wallet : ManagedPlatformWallet ,
274330 walletId : Data ,
275331 network : Network ,
276332 modelContext : ModelContext
277- ) throws -> Int {
333+ ) throws -> RederiveOutcome {
278334 var fixed = 0
335+ var failures : [ ( UInt32 , String ) ] = [ ]
279336 for key in report . keys {
280337 guard case . needsRederive = key . status else { continue }
281- let preview = try wallet . deriveIdentityAuthKeyAtSlot (
282- identityIndex : report . identityIndex ,
283- keyId : key . keyId ,
284- network : network
285- )
338+ let preview : ManagedPlatformWallet . IdentityRegistrationKeyPreview
339+ do {
340+ preview = try wallet . deriveIdentityAuthKeyAtSlot (
341+ identityIndex : report . identityIndex ,
342+ keyId : key . keyId ,
343+ network : network
344+ )
345+ } catch {
346+ failures . append ( ( key . keyId , " derivation failed: \( error . localizedDescription ) " ) )
347+ continue
348+ }
286349 let pubkeyHashHex = SwiftDashSDK . KeychainManager . computePublicKeyHashHex ( preview . publicKeyData )
287350 let metadata = IdentityPrivateKeyMetadata (
288351 identityId : report . identityIdBase58 ,
@@ -302,6 +365,7 @@ enum WalletKeyHealthChecker {
302365 derivationPath : preview . derivationPath ,
303366 metadata : metadata
304367 ) else {
368+ failures . append ( ( key . keyId , " Keychain write at \( preview . derivationPath ) returned nil " ) )
305369 continue
306370 }
307371 key . row . privateKeyKeychainIdentifier = pkid
@@ -321,22 +385,36 @@ enum WalletKeyHealthChecker {
321385 if fixed > 0 {
322386 try modelContext . save ( )
323387 }
324- return fixed
388+ return RederiveOutcome ( success : fixed , failures : failures )
325389 }
326390
327- /// Cascade-delete an orphan identity from SwiftData. Safe to
328- /// call now that the relationship inverses
329- /// (`PersistentPublicKey.identity`, `PersistentDPNSName.identity` ,
330- /// `PersistentDashpayProfile.identity`, `PersistentDashpayContactRequest.owner`)
331- /// are all Optional — see the doc comments on those models for
332- /// the SwiftData cascade-on-non-optional crash this avoids .
391+ /// Cascade-delete an orphan identity from SwiftData AND wipe its
392+ /// associated Keychain entries. Order matters: clear the
393+ /// Keychain side first (purely additive to the SwiftData state) ,
394+ /// then drop the row. If Keychain wipe fails we still try the
395+ /// SwiftData delete so the user can finish the operation; the
396+ /// keychain error is surfaced to the caller .
333397 @ MainActor
334398 static func deleteOrphan (
335399 identity : PersistentIdentity ,
336400 modelContext : ModelContext
337401 ) throws {
402+ // Snapshot the base58 id BEFORE the delete — once the row
403+ // is removed its computed accessor is invalid.
404+ let identityIdBase58 = identity . identityIdBase58
405+ var keychainError : Error ?
406+ do {
407+ try KeychainManager . shared . deleteAllIdentityPrivateKeys (
408+ forIdentityIdBase58 : identityIdBase58
409+ )
410+ } catch {
411+ keychainError = error
412+ }
338413 modelContext . delete ( identity )
339414 try modelContext . save ( )
415+ if let keychainError {
416+ throw keychainError
417+ }
340418 }
341419}
342420
@@ -550,15 +628,23 @@ struct WalletKeyHealthSheet: View {
550628 private func rederive ( _ report : WalletIdentityKeyHealthReport ) {
551629 Task { @MainActor in
552630 do {
553- let fixed = try WalletKeyHealthChecker . rederive (
631+ let outcome = try WalletKeyHealthChecker . rederive (
554632 report : report ,
555633 wallet : wallet ,
556634 walletId : walletId ,
557635 network : network ,
558636 modelContext : modelContext
559637 )
560- actionMessage = " Re-derived \( fixed ) key \( fixed == 1 ? " " : " s " ) for identity \( report . identityIdBase58 . prefix ( 12 ) ) … "
561- errorMessage = nil
638+ let fixed = outcome . success
639+ var msg = " Re-derived \( fixed ) key \( fixed == 1 ? " " : " s " ) for identity \( report . identityIdBase58 . prefix ( 12 ) ) … "
640+ if ! outcome . failures . isEmpty {
641+ let detail = outcome . failures
642+ . map { " kid \( $0 . 0 ) : \( $0 . 1 ) " }
643+ . joined ( separator : " ; " )
644+ msg += " — \( outcome . failures . count ) failed: \( detail ) "
645+ }
646+ actionMessage = msg
647+ errorMessage = outcome . failures . isEmpty ? nil : msg
562648 // Re-run the check so the report reflects the new
563649 // state (formerly-orange rows should turn green).
564650 await runCheck ( )
0 commit comments