From 942de7d27ac29444b55ff0e4b96480fd000c70ea Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:10:40 +0000 Subject: [PATCH 01/73] perf(identity): clone the Profile tab's identity snapshot once per frame The Profile tab cloned the hub's identity into an owned value, then cloned it again to keep the refreshed snapshot when the identity had not changed. Reconciliation now borrows the incoming identity, compares IDs by reference, and clones once when it keeps the snapshot. A refresh of the same identity still replaces the snapshot and keeps unsaved edits; a switch to another identity still resets the editor. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012YneRVSNLhVnGiedWDr3fw --- src/ui/identity/settings.rs | 59 +++++++++++++++++++++++++++++-------- 1 file changed, 46 insertions(+), 13 deletions(-) diff --git a/src/ui/identity/settings.rs b/src/ui/identity/settings.rs index 73b918790..c15617716 100644 --- a/src/ui/identity/settings.rs +++ b/src/ui/identity/settings.rs @@ -698,12 +698,9 @@ impl SettingsTab { // `incoming` is the app-scoped active identity the hub resolved // (selected → first → none), not `.first()`, so the Settings tab agrees // with the breadcrumb/hub and does not flip-flop across frames (D4). - let incoming = incoming.cloned(); - - let changed = self.reconcile_selected_identity(&incoming); + let changed = self.reconcile_selected_identity(incoming); if changed { - self.selected_identity = incoming; self.profile_loaded = false; // Clear the editor to a clean slate; fields repopulate once the // async profile load lands (see `load_cached_profile`). @@ -724,17 +721,17 @@ impl SettingsTab { } } - fn reconcile_selected_identity(&mut self, incoming: &Option) -> bool { - let changed = match (&self.selected_identity, incoming) { - (Some(a), Some(b)) => a.identity.id() != b.identity.id(), + /// Retain the refreshed snapshot of `incoming` (cloned once) and report + /// whether it is a different identity than the one shown, so the caller + /// resets the editor only on a switch. A same-identity refresh still + /// replaces the snapshot, so key and balance changes reach the tab. + fn reconcile_selected_identity(&mut self, incoming: Option<&QualifiedIdentity>) -> bool { + let changed = match (self.selected_identity.as_ref(), incoming) { + (Some(shown), Some(incoming)) => shown.identity.id() != incoming.identity.id(), (None, Some(_)) | (Some(_), None) => true, (None, None) => false, }; - - if !changed { - self.selected_identity = incoming.clone(); - } - + self.selected_identity = incoming.cloned(); changed } @@ -1040,7 +1037,7 @@ mod tests { let mut tab = SettingsTab::new(); tab.selected_identity = Some(stale); - let changed_identity = tab.reconcile_selected_identity(&Some(refreshed)); + let changed_identity = tab.reconcile_selected_identity(Some(&refreshed)); assert!(!changed_identity, "the selected identity ID did not change"); assert_eq!( @@ -1055,6 +1052,42 @@ mod tests { ); } + /// A refresh of the shown identity replaces its snapshot but keeps the + /// user's unsaved edits; switching to another identity clears them. + #[test] + fn same_identity_refresh_keeps_edits_and_a_switch_resets_the_editor() { + use super::super::profile_cache::ProfileCache; + let shown = qualified_identity(); + let mut profiles = ProfileCache::default(); + let mut tab = SettingsTab::new(); + tab.ensure_selected(Some(&shown), &mut profiles); + tab.profile_loaded = true; + tab.edit_display_name = "Draft".into(); + + let mut refreshed = shown.clone(); + let key = IdentityPublicKey::random_key(7, Some(7), PlatformVersion::latest()); + refreshed.identity.public_keys_mut().insert(7, key); + tab.ensure_selected(Some(&refreshed), &mut profiles); + assert_eq!(tab.edit_display_name, "Draft", "a refresh keeps edits"); + assert!( + tab.selected_identity + .as_ref() + .is_some_and(|identity| identity.identity.public_keys().len() == 1), + "a refresh replaces the snapshot" + ); + + let other = qualified_identity_with_id(9); + tab.ensure_selected(Some(&other), &mut profiles); + assert!( + tab.edit_display_name.is_empty(), + "a switch resets the editor" + ); + assert_eq!( + tab.selected_identity.as_ref().map(|i| i.identity.id()), + Some(other.identity.id()) + ); + } + #[test] fn identity_profile_shows_display_name_without_device_name_controls() { use egui_kittest::Harness; From 1451e89d6d80c94701eb27970e8923e268ae8252 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:22:23 +0000 Subject: [PATCH 02/73] fix(identity): keep identity hub tabs to one content width The hub drew every tab inside a centred layout that spanned the whole window, so on a wide window Home's columns, the Profile form and the Contacts cards stretched across it. Tab content now starts at the tab bar's left edge and stops at one shared width taken from the identities wireframes; the rest of a wide window stays empty. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012YneRVSNLhVnGiedWDr3fw --- src/ui/identity/hub_screen.rs | 81 +++++++----- src/ui/identity/mod.rs | 6 + tests/kittest/identity_hub_layout.rs | 187 +++++++++++++++++++++++++++ tests/kittest/main.rs | 1 + 4 files changed, 240 insertions(+), 35 deletions(-) create mode 100644 tests/kittest/identity_hub_layout.rs diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index a0b7a480d..8fb1fba86 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -585,47 +585,58 @@ impl ScreenLike for IdentityHubScreen { } ui.add_space(16.0); rendered_tab = Some(self.selected_tab); - let mut tab_action = match self.selected_tab { - IdentityHubTab::Home => { - let (home_action, outcome) = match &selected { - Some(identity) => super::home::render( + // Tab content starts at the tab bar's left edge and + // stops at one shared width, so wide windows do not + // stretch forms and rows (wireframes A05/A06/A08). + let content = + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { + ui.set_max_width(super::HUB_CONTENT_MAX_WIDTH); + match self.selected_tab { + IdentityHubTab::Home => { + let (home_action, outcome) = match &selected { + Some(identity) => super::home::render( + ui, + &self.app_context, + identity, + &mut self.home_state, + &mut self.profile_cache, + &mut self.contacts_state, + ), + None => { + (AppAction::None, super::home::HomeOutcome::None) + } + }; + if let Some(next_tab) = super::home::apply_outcome( + &mut self.home_state, + outcome, + ) { + if next_tab != self.selected_tab { + self.contacts_state.reset(); + } + self.selected_tab = next_tab; + self.settings_tab.focus_section(outcome); + } + home_action + } + IdentityHubTab::Contacts => super::contacts::render( ui, &self.app_context, - identity, - &mut self.home_state, - &mut self.profile_cache, + selected.as_ref(), &mut self.contacts_state, + &mut self.profile_cache, ), - None => (AppAction::None, super::home::HomeOutcome::None), - }; - if let Some(next_tab) = - super::home::apply_outcome(&mut self.home_state, outcome) - { - if next_tab != self.selected_tab { - self.contacts_state.reset(); + IdentityHubTab::Activity => { + super::activity::render(ui, &self.app_context) } - self.selected_tab = next_tab; - self.settings_tab.focus_section(outcome); + IdentityHubTab::Settings => self.settings_tab.render( + ui, + &self.app_context, + selected.as_ref(), + &mut self.profile_cache, + ), } - home_action - } - IdentityHubTab::Contacts => super::contacts::render( - ui, - &self.app_context, - selected.as_ref(), - &mut self.contacts_state, - &mut self.profile_cache, - ), - IdentityHubTab::Activity => { - super::activity::render(ui, &self.app_context) - } - IdentityHubTab::Settings => self.settings_tab.render( - ui, - &self.app_context, - selected.as_ref(), - &mut self.profile_cache, - ), - }; + }); + let mut tab_action = content.inner; tab_action |= header_action; tab_action }); diff --git a/src/ui/identity/mod.rs b/src/ui/identity/mod.rs index c31274ebb..e8abccc28 100644 --- a/src/ui/identity/mod.rs +++ b/src/ui/identity/mod.rs @@ -65,6 +65,12 @@ pub mod withdraw_screen; pub use hub_screen::IdentityHubScreen; pub use tabs::IdentityHubTab; +/// Widest the content of an identity hub tab grows, in points. Matches the +/// content area of the identities wireframes (A05 Home, A06 Contacts, A08 +/// Profile); wider windows leave the space to the right empty instead of +/// stretching forms, columns and rows. +pub const HUB_CONTENT_MAX_WIDTH: f32 = 1040.0; + /// Confirmation shown once an identity is removed from this device. pub const IDENTITY_REMOVED: &str = "The identity was removed from this device."; diff --git a/tests/kittest/identity_hub_layout.rs b/tests/kittest/identity_hub_layout.rs new file mode 100644 index 000000000..f4859618e --- /dev/null +++ b/tests/kittest/identity_hub_layout.rs @@ -0,0 +1,187 @@ +//! Identity hub layout on ordinary and wide windows. +//! +//! The hub tabs follow the 2026-09-22 identities wireframes (A05 Home, A06 +//! Contacts, A08 Profile): content starts at the tab bar's left edge and never +//! grows past one shared content width, however wide the window is. + +use crate::identity_home::key; +use crate::support::{fresh_app_context, with_isolated_data_dir}; +use dash_evo_tool::app::AppAction; +use dash_evo_tool::backend_task::dashpay::{ContactData, DashPayTask}; +use dash_evo_tool::backend_task::{BackendTask, BackendTaskContext, BackendTaskSuccessResult}; +use dash_evo_tool::context::AppContext; +use dash_evo_tool::model::dashpay::ProfileSnapshot; +use dash_evo_tool::model::qualified_identity::encrypted_key_storage::KeyStorage; +use dash_evo_tool::model::qualified_identity::{ + DPNSNameInfo, IdentityStatus, IdentityType, QualifiedIdentity, +}; +use dash_evo_tool::ui::ScreenLike; +use dash_evo_tool::ui::identity::{HUB_CONTENT_MAX_WIDTH, IdentityHubScreen, IdentityHubTab}; +use dash_sdk::dpp::identity::accessors::IdentityGettersV0; +use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; +use dash_sdk::dpp::identity::{Identity, Purpose}; +use dash_sdk::dpp::version::PlatformVersion; +use dash_sdk::platform::Identifier; +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use std::collections::BTreeMap; +use std::sync::Arc; + +/// An ordinary laptop window and a wide desktop window. +const WIDTHS: [f32; 2] = [1280.0, 2000.0]; + +/// Slack for rounding and stroke widths when comparing edges. +const EPSILON: f32 = 2.0; + +type HubHarness = Harness<'static, (IdentityHubScreen, Vec)>; + +fn mount_hub(app_context: &Arc, width: f32) -> HubHarness { + Harness::builder() + .with_size(egui::vec2(width, 1100.0)) + .build_ui_state( + |ui, state: &mut (IdentityHubScreen, Vec)| { + let action = state.0.ui(ui); + if !matches!(action, AppAction::None) { + state.1.push(action); + } + }, + (IdentityHubScreen::new(app_context), Vec::new()), + ) +} + +/// Seeds and selects a user identity that owns two usernames. +fn seed_identity_with_usernames(app_context: &Arc) -> Identifier { + let auth = key(1, Purpose::AUTHENTICATION); + let identity = Identity::new_with_id_and_keys( + Identifier::from([0xA7; 32]), + BTreeMap::from([(auth.id(), auth)]), + PlatformVersion::latest(), + ) + .expect("identity"); + let identity_id = identity.id(); + let qualified_identity = QualifiedIdentity { + identity, + associated_voter_identity: None, + associated_operator_identity: None, + associated_owner_key_id: None, + identity_type: IdentityType::User, + alias: None, + private_keys: KeyStorage::default(), + dpns_names: vec![ + DPNSNameInfo { + name: "alex".into(), + acquired_at: 1_700_000_000_000, + }, + DPNSNameInfo { + name: "alexander".into(), + acquired_at: 1_700_000_000_000, + }, + ], + associated_wallets: BTreeMap::new(), + secret_access: None, + wallet_index: None, + top_ups: BTreeMap::new(), + status: IdentityStatus::Active, + network: app_context.network(), + }; + app_context + .insert_local_qualified_identity(&qualified_identity, &None) + .expect("seed identity"); + app_context.set_selected_identity(Some(identity_id)); + identity_id +} + +/// Renders frames until the hub asks for `owner`'s social profile, then answers +/// with a published one so every tab shows its populated state. +fn deliver_profile(hub: &mut HubHarness, owner: Identifier) { + for _ in 0..16 { + let request = hub.state().1.iter().find_map(|action| match action { + AppAction::BackendTaskWithContext { + task: BackendTask::DashPayTask(task), + context, + } if matches!(**task, DashPayTask::LoadProfile { .. }) => Some(context.clone()), + _ => None, + }); + if let Some(request) = request { + let app_context = hub.state().0.app_context.clone(); + hub.state_mut().0.display_backend_task_result( + &request, + BackendTaskSuccessResult::DashPayProfile(ProfileSnapshot { + network: app_context.network(), + owner, + revision: app_context.identity_profile_revision(owner), + profile: Some(("Alex".into(), String::new(), String::new())), + }), + ); + hub.state_mut().1.clear(); + return; + } + hub.step(); + } + panic!("the hub never asked for the social profile"); +} + +fn deliver_contact(hub: &mut HubHarness, owner: Identifier) { + let app_context = hub.state().0.app_context.clone(); + let task = BackendTask::DashPayTask(Box::new(DashPayTask::LoadContacts { + identity: app_context.resolve_selected_identity().expect("identity"), + })); + hub.state_mut().0.display_backend_task_result( + &BackendTaskContext::from(&task), + BackendTaskSuccessResult::DashPayContactsWithInfo { + identity: owner, + contacts: vec![ContactData { + identity_id: Identifier::from([0xD8; 32]), + nickname: Some("Bao".into()), + note: None, + is_hidden: false, + account_reference: 0, + username: None, + display_name: None, + avatar_url: None, + bio: None, + }], + }, + ); +} + +/// The hub on `tab` for an identity with a published profile and one contact. +fn hub_on(app_context: &Arc, width: f32, tab: IdentityHubTab) -> HubHarness { + let owner = seed_identity_with_usernames(app_context); + let mut hub = mount_hub(app_context, width); + deliver_profile(&mut hub, owner); + hub.state_mut().0.select_tab(tab); + hub.run_steps(4); + deliver_contact(&mut hub, owner); + hub.run_steps(4); + hub +} + +/// The tab bar's left edge, where every tab's content starts. +fn content_left(hub: &HubHarness) -> f32 { + hub.get_by_label("Home").rect().left() +} + +fn assert_within_content(hub: &HubHarness, what: &str, rect: egui::Rect, width: f32) { + let limit = content_left(hub) + HUB_CONTENT_MAX_WIDTH + EPSILON; + assert!( + rect.right() <= limit, + "at {width} px, {what} ends at {} but the content ends at {limit}", + rect.right() + ); +} + +#[test] +fn home_stays_within_the_content_width() { + for width in WIDTHS { + with_isolated_data_dir(|| { + let (_runtime, app_context) = fresh_app_context(); + let hub = hub_on(&app_context, width, IdentityHubTab::Home); + let add_contact = hub + .get_by_role_and_label(Role::Button, "Add contact") + .rect(); + assert_within_content(&hub, "Home's Add contact button", add_contact, width); + }); + } +} diff --git a/tests/kittest/main.rs b/tests/kittest/main.rs index 650f7296d..9c172c5a4 100644 --- a/tests/kittest/main.rs +++ b/tests/kittest/main.rs @@ -10,6 +10,7 @@ mod identity_home; mod identity_hub; mod identity_hub_activity; mod identity_hub_contacts; +mod identity_hub_layout; mod identity_hub_onboarding; mod identity_hub_settings; mod identity_hub_switcher; From fb50583cc8f8316f269f5a1753505641b28ba0dd Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:22:23 +0000 Subject: [PATCH 03/73] fix(identity): lay out the Profile tab like its wireframe The Profile tab split its width evenly with a justified layout, so on a wide window the form stretched, each username's menu floated right after the name, Get another username spanned the whole column and the identity type badge sat beside the usernames. The tab now follows the A08 wireframe: the social profile form beside a usernames card, split 560:380. Each username's menu sits at the card's right edge, Get another username is a secondary, card-wide button below a divider, and the identity type badge moves to Advanced next to the identity ID. Narrow windows still stack the two columns. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012YneRVSNLhVnGiedWDr3fw --- src/ui/identity/settings.rs | 90 ++++++++++++-------------- src/ui/identity/usernames_card.rs | 97 ++++++++++++++++++++-------- tests/kittest/identity_hub_layout.rs | 53 +++++++++++++++ 3 files changed, 163 insertions(+), 77 deletions(-) diff --git a/src/ui/identity/settings.rs b/src/ui/identity/settings.rs index c15617716..270f51a88 100644 --- a/src/ui/identity/settings.rs +++ b/src/ui/identity/settings.rs @@ -246,14 +246,33 @@ impl SettingsTab { egui::ScrollArea::vertical() .auto_shrink([false, false]) .show(ui, |ui| { - // Two-column layout. egui's `columns` takes care of splitting - // the available width evenly; on narrow panels the individual - // rows inside each column wrap gracefully because we use - // `set_max_width` on the text fields. + // Two columns as in the A08 wireframe: the social profile form + // beside the usernames card, split 560:380. Explicit + // left-aligned columns, not `ui.columns`, whose justified + // layout stretches every button to the column width. Narrow + // panels stack the two. if ui.available_width() >= 760.0 { - ui.columns(2, |cols| { - action |= self.render_social_profile(&mut cols[0], app_context, &identity); - action |= self.render_usernames(&mut cols[1], app_context, &identity); + let content_width = ui.available_width() - Spacing::LG; + let left_width = content_width * 560.0 / 940.0; + let right_width = content_width - left_width; + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = Spacing::LG; + ui.allocate_ui_with_layout( + egui::vec2(left_width, 0.0), + egui::Layout::top_down(egui::Align::Min), + |ui| { + ui.set_width(left_width); + action |= self.render_social_profile(ui, app_context, &identity); + }, + ); + ui.allocate_ui_with_layout( + egui::vec2(right_width, 0.0), + egui::Layout::top_down(egui::Align::Min), + |ui| { + ui.set_width(right_width); + action |= self.render_usernames(ui, app_context, &identity); + }, + ); }); } else { action |= self.render_social_profile(ui, app_context, &identity); @@ -457,9 +476,12 @@ impl SettingsTab { ui.scroll_to_cursor(Some(egui::Align::TOP)); self.focus_usernames = false; } - username_section_header(ui, identity.identity_type, dark_mode); - let action = self.usernames_card.show(ui, app_context, identity); - ui.add_space(12.0); + let action = super::home::card(ui, |ui| { + section_heading(ui, "Usernames", dark_mode); + ui.add_space(Spacing::XS); + self.usernames_card.show(ui, app_context, identity) + }); + ui.add_space(Spacing::MD); action } @@ -472,8 +494,16 @@ impl SettingsTab { let mut action = AppAction::None; let dark_mode = ui.ctx().global_style().visuals.dark_mode; - // 1. Identity type + raw ID + (optional) ProTxHash. + // 1. Identity type + raw ID + (optional) ProTxHash. The type badge + // lives here, not beside the usernames (A08; design-spec §B.8). sub_heading(ui, "Identity", dark_mode); + let kind = HeroIdentityKind::from(identity.identity_type); + pill::accent_pill( + ui, + kind.badge_label(), + kind.badge_accent(), + Some(kind.badge_tooltip()), + ); let id_base58 = identity.identity.id().to_string(Encoding::Base58); ui.horizontal(|ui| { ui.label(RichText::new("Identity ID").color(DashColors::text_secondary(dark_mode))); @@ -923,22 +953,6 @@ fn section_heading(ui: &mut Ui, text: &str, dark_mode: bool) { ui.add_space(4.0); } -fn username_section_header(ui: &mut Ui, identity_type: IdentityType, dark_mode: bool) { - let kind = HeroIdentityKind::from(identity_type); - ui.horizontal(|ui| { - section_heading(ui, "Usernames", dark_mode); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - pill::accent_pill( - ui, - kind.badge_label(), - kind.badge_accent(), - Some(kind.badge_tooltip()), - ); - }); - }); - ui.add_space(Spacing::XS); -} - fn sub_heading(ui: &mut Ui, text: &str, dark_mode: bool) { ui.label( RichText::new(text) @@ -1343,28 +1357,6 @@ mod tests { assert_eq!(string_if_set(" alex "), Some("alex".to_string())); } - #[test] - fn username_heading_and_identity_badge_share_a_row() { - use egui_kittest::Harness; - use egui_kittest::kittest::Queryable; - - let mut harness = Harness::builder() - .with_size(egui::vec2(400.0, 100.0)) - .build_ui(|ui| { - let dark_mode = ui.ctx().global_style().visuals.dark_mode; - username_section_header(ui, IdentityType::User, dark_mode); - }); - harness.run(); - - let heading = harness.get_by_label("Usernames").rect().center(); - let badge = harness.get_by_label("User identity").rect().center(); - assert!( - (heading.y - badge.y).abs() <= 1.0, - "the badge and heading must share a visual baseline", - ); - assert!(badge.x > heading.x, "the badge must sit to the right"); - } - /// IT-SETTINGS-01 (section-heading slice) — verifies the three required /// section headings are rendered as labels when the layout helpers are /// called directly. This covers the expected section-name assertions diff --git a/src/ui/identity/usernames_card.rs b/src/ui/identity/usernames_card.rs index b2edae5ac..769b525e1 100644 --- a/src/ui/identity/usernames_card.rs +++ b/src/ui/identity/usernames_card.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use dash_sdk::dpp::identity::TimestampMillis; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; -use egui::{RichText, Ui}; +use egui::{Align, Layout, RichText, Ui}; use crate::app::AppAction; use crate::backend_task::identity::IdentityTask; @@ -26,7 +26,7 @@ use crate::ui::identity::username_copy::{ }; use crate::ui::masternodes::KeyVocabulary; use crate::ui::state::legacy_recovery::LegacyRecoveryState; -use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt}; +use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt, Spacing}; use crate::ui::{RootScreenType, ScreenType}; /// One row of the card, in display order. @@ -219,6 +219,24 @@ pub struct UsernamesCard { recovery: Option<(dash_sdk::platform::Identifier, LegacyRecoveryState)>, } +/// Which register button the card offers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum GetUsername { + /// The identity has no username yet. + First, + /// The identity already has at least one username. + Another, +} + +impl GetUsername { + fn label(self) -> &'static str { + match self { + Self::First => "Get a username", + Self::Another => "Get another username", + } + } +} + impl UsernamesCard { /// Render the card for `identity`; returns any navigation the user asked for. pub fn show( @@ -240,7 +258,7 @@ impl UsernamesCard { "This identity has no username yet. A username lets people pay you as @name instead of a long address.", ); ui.add_space(6.0); - action |= self.get_username_button(ui, app_context, identity, hint, "Get a username"); + action |= self.get_username_button(ui, app_context, identity, hint, GetUsername::First); return action; } @@ -263,27 +281,31 @@ impl UsernamesCard { None, ); } - ui.menu_button("•••", |ui| { - if ui.button("Copy username").clicked() { - ui.ctx().copy_text(format!("@{name}")); - ui.close(); - } - if ui.button("Show QR code").clicked() { - self.open_qr(&name); - ui.close(); - } - if !is_main && ui.button("Show as main").clicked() { - action = AppAction::BackendTask(BackendTask::IdentityTask( - IdentityTask::SetMainUsername { - identity_id, - name: name.clone(), - }, - )); - ui.close(); - } - }) - .response - .clickable_tooltip(format!("More actions for @{name}")); + // The row's actions sit at the card's right edge, as in + // the A08 wireframe, not right after the name. + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + ui.menu_button("•••", |ui| { + if ui.button("Copy username").clicked() { + ui.ctx().copy_text(format!("@{name}")); + ui.close(); + } + if ui.button("Show QR code").clicked() { + self.open_qr(&name); + ui.close(); + } + if !is_main && ui.button("Show as main").clicked() { + action = AppAction::BackendTask(BackendTask::IdentityTask( + IdentityTask::SetMainUsername { + identity_id, + name: name.clone(), + }, + )); + ui.close(); + } + }) + .response + .clickable_tooltip(format!("More actions for @{name}")); + }); }); if acquired_at > 0 { ui.label( @@ -340,8 +362,10 @@ impl UsernamesCard { } } - ui.add_space(10.0); - action |= self.get_username_button(ui, app_context, identity, hint, "Get another username"); + ui.add_space(Spacing::SM); + ui.separator(); + ui.add_space(Spacing::SM); + action |= self.get_username_button(ui, app_context, identity, hint, GetUsername::Another); ui.label( RichText::new("Each username is a separate payment from this identity's balance.") .small() @@ -408,10 +432,27 @@ impl UsernamesCard { app_context: &Arc, identity: &QualifiedIdentity, hint: Option, - label: &str, + kind: GetUsername, ) -> AppAction { let mut action = AppAction::None; - let button = ComponentStyles::add_primary_button_enabled(ui, hint.is_none(), label); + let dark_mode = ui.style().visuals.dark_mode; + // The first username is the card's call to action; another one is a + // secondary, card-wide button below the list (A08). + let button = match kind { + GetUsername::First => { + ComponentStyles::add_primary_button_enabled(ui, hint.is_none(), kind.label()) + } + GetUsername::Another => { + ui.with_layout(Layout::top_down_justified(Align::Min), |ui| { + if hint.is_none() { + ComponentStyles::add_secondary_button(ui, kind.label(), dark_mode) + } else { + ComponentStyles::add_primary_button_enabled(ui, false, kind.label()) + } + }) + .inner + } + }; let Some(hint) = hint else { if button.clicked() { action = register_action(app_context, identity); diff --git a/tests/kittest/identity_hub_layout.rs b/tests/kittest/identity_hub_layout.rs index f4859618e..012eb6c86 100644 --- a/tests/kittest/identity_hub_layout.rs +++ b/tests/kittest/identity_hub_layout.rs @@ -185,3 +185,56 @@ fn home_stays_within_the_content_width() { }); } } + +#[test] +fn profile_keeps_the_form_and_the_usernames_card_side_by_side() { + for width in WIDTHS { + with_isolated_data_dir(|| { + let (_runtime, app_context) = fresh_app_context(); + let hub = hub_on(&app_context, width, IdentityHubTab::Settings); + let tab_bottom = hub.get_by_label("Home").rect().bottom(); + + let usernames = hub.get_by_label("Usernames").rect(); + let form_right = hub + .query_all_by_role(Role::TextInput) + .chain(hub.query_all_by_role(Role::MultilineTextInput)) + .map(|field| field.rect().right()) + .fold(f32::MIN, f32::max); + assert!( + form_right < usernames.left(), + "at {width} px, the profile form ({form_right}) must end before the \ + usernames card ({})", + usernames.left() + ); + + let another = hub + .get_by_role_and_label(Role::Button, "Get another username") + .rect(); + assert!( + another.width() <= 420.0, + "at {width} px, Get another username must stay card-sized, is {}", + another.width() + ); + assert_within_content(&hub, "the usernames card", another, width); + + let menu = hub + .query_all_by_label("•••") + .map(|node| node.rect()) + .find(|rect| rect.top() > tab_bottom) + .expect("a username has a menu"); + assert!( + (menu.right() - another.right()).abs() <= 24.0, + "at {width} px, a username's menu belongs at the card's right edge: \ + {menu:?} vs {another:?}" + ); + + if let Some(badge) = hub.query_by_label("User identity") { + let advanced = hub.get_by_label("Advanced").rect(); + assert!( + badge.rect().top() > advanced.bottom(), + "at {width} px, the identity type belongs under Advanced" + ); + } + }); + } +} From 6f90d46aa41e29862e4dad1e38c69ce99c00f8a9 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:22:23 +0000 Subject: [PATCH 04/73] fix(identity): tidy the Contacts tab's sections and rows The Contacts tab offered Add by username twice, once in the header and again inside Active contacts, its sections shrank to their content and did not scroll, and a contact row showed only one line. Add by username now appears in the header, and inside Active contacts only as the empty state's call to action. The sections share the content width and scroll below the header, and each contact row shows the contact's @username under its name when that adds something. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012YneRVSNLhVnGiedWDr3fw --- src/ui/identity/contacts.rs | 83 ++++++++++++++++++++++------ tests/kittest/identity_hub_layout.rs | 34 ++++++++++++ 2 files changed, 101 insertions(+), 16 deletions(-) diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index a6f914a1b..9696a6614 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -409,9 +409,15 @@ fn render_populated( action |= header_row(ui, app_context, dark_mode); - action |= received_section(ui, app_context, identity, state, dark_mode); - action |= active_section(ui, app_context, identity, state, dark_mode); - action |= sent_section(ui, app_context, identity, state, dark_mode); + // The sections scroll below the header, so a long contact list stays + // reachable in a short window. + eframe::egui::ScrollArea::vertical() + .auto_shrink([false, false]) + .show(ui, |ui| { + action |= received_section(ui, app_context, identity, state, dark_mode); + action |= active_section(ui, app_context, identity, state, dark_mode); + action |= sent_section(ui, app_context, identity, state, dark_mode); + }); action } @@ -493,11 +499,21 @@ fn active_section( } else { for contact in matches { ui.horizontal(|ui| { - ui.label( - RichText::new(contact_label(contact)) - .strong() - .color(DashColors::text_primary(dark_mode)), - ); + let label = contact_label(contact); + ui.vertical(|ui| { + ui.label( + RichText::new(&label) + .strong() + .color(DashColors::text_primary(dark_mode)), + ); + if let Some(handle) = contact_handle(contact, &label) { + ui.label( + RichText::new(handle) + .small() + .color(DashColors::text_secondary(dark_mode)), + ); + } + }); ui.with_layout( eframe::egui::Layout::right_to_left(eframe::egui::Align::Center), |ui| { @@ -538,14 +554,18 @@ fn active_section( } } - ui.add_space(8.0); - let add = ui - .add(ComponentStyles::primary_button(ADD_BY_USERNAME_LABEL)) - .clickable_tooltip( - "Find someone by their Dash username or identity ID and add them as a contact.", - ); - if add.clicked() { - action = resolve_contacts_button(ContactsButton::ActiveAddByUsername, app_context); + // The header already offers Add by username; the section repeats it + // only as the empty state's call to action (design-spec §B.4). + if !has_contacts { + ui.add_space(8.0); + let add = ui + .add(ComponentStyles::primary_button(ADD_BY_USERNAME_LABEL)) + .clickable_tooltip( + "Find someone by their Dash username or identity ID and add them as a contact.", + ); + if add.clicked() { + action = resolve_contacts_button(ContactsButton::ActiveAddByUsername, app_context); + } } action |= hidden_section(ui, identity, state, dark_mode); @@ -749,6 +769,8 @@ fn section_card(ui: &mut Ui, dark_mode: bool, heading: &str, body: impl FnOnce(& .corner_radius(CornerRadius::same(Shape::RADIUS_MD)) .inner_margin(Margin::symmetric(16, 12)); frame.show(ui, |ui| { + // Every section spans the content width, so the cards line up. + ui.set_width(ui.available_width()); ui.label( RichText::new(heading) .strong() @@ -770,6 +792,17 @@ fn has_social_profile( matches!(profiles.get_or_request(identity), Some(Some(_))) } +/// A contact's `@username`, shown under its label unless the label already +/// is that username. +fn contact_handle(contact: &ContactData, label: &str) -> Option { + let username = contact.username.as_deref()?.trim(); + if username.is_empty() { + return None; + } + let handle = format!("@{}", username.trim_start_matches('@')); + (handle != label && username != label).then_some(handle) +} + fn contact_profile_screen_type(identity: QualifiedIdentity, contact_id: Identifier) -> ScreenType { ScreenType::DashPayContactProfileViewer(identity, contact_id) } @@ -917,6 +950,24 @@ mod tests { } } + /// A contact row adds the `@username` under its label, unless the label + /// already is the username or there is none. + #[test] + fn contact_rows_show_the_username_once() { + let mut contact = contact_named("Bao"); + assert_eq!(contact_handle(&contact, "Bao"), None); + + contact.username = Some("bao".into()); + assert_eq!(contact_handle(&contact, "Bao"), Some("@bao".into())); + + contact.nickname = None; + let label = contact_label(&contact); + assert_eq!(contact_handle(&contact, &label), None, "label {label}"); + + contact.username = Some(" ".into()); + assert_eq!(contact_handle(&contact, "Bao"), None); + } + fn request_from( request_id: Identifier, sender: Identifier, diff --git a/tests/kittest/identity_hub_layout.rs b/tests/kittest/identity_hub_layout.rs index 012eb6c86..fdaa3dc15 100644 --- a/tests/kittest/identity_hub_layout.rs +++ b/tests/kittest/identity_hub_layout.rs @@ -238,3 +238,37 @@ fn profile_keeps_the_form_and_the_usernames_card_side_by_side() { }); } } + +#[test] +fn contacts_sections_start_at_the_content_edge_with_one_add_button() { + for width in WIDTHS { + with_isolated_data_dir(|| { + let (_runtime, app_context) = fresh_app_context(); + let hub = hub_on(&app_context, width, IdentityHubTab::Contacts); + let left = content_left(&hub); + + let heading = hub + .get_by_label(dash_evo_tool::ui::identity::contacts::RECEIVED_HEADING) + .rect(); + assert!( + heading.left() - left <= 24.0, + "at {width} px, section headings start at the content edge ({left}), \ + not at {}", + heading.left() + ); + + let add_buttons = hub + .query_all_by_label(dash_evo_tool::ui::identity::contacts::ADD_BY_USERNAME_LABEL) + .count(); + assert_eq!( + add_buttons, 1, + "at {width} px, Add by username is offered once when there are contacts" + ); + + let view_profile = hub + .get_by_label(dash_evo_tool::ui::identity::contacts::VIEW_PROFILE_LABEL) + .rect(); + assert_within_content(&hub, "a contact's View Profile button", view_profile, width); + }); + } +} From 4132340529c54ee1bd9d4fd0e9320beaa8385036 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 16 Oct 2026 07:23:44 +0000 Subject: [PATCH 05/73] fix(identity): keep the identity header in the hub's content column The identity header (avatar, name, balance and its actions) still spanned the whole window while the tab content below it stopped at one width, so on a wide window the balance and Move to wallet sat far to the right of everything else. The header, the tab bar and the tab content now share one left-aligned column of the same width on every tab. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012YneRVSNLhVnGiedWDr3fw --- src/ui/identity/hub_screen.rs | 92 +++++++++++++--------------- tests/kittest/identity_hub_layout.rs | 25 ++++++++ 2 files changed, 67 insertions(+), 50 deletions(-) diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index 8fb1fba86..74a23f67d 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -535,7 +535,7 @@ impl ScreenLike for IdentityHubScreen { let mut rendered_tab: Option = None; action |= island_central_panel(ui, |ui| { // Claim the island's full width so its bordered panel reaches the - // window edges; the content below stays centered. + // window edges; each view lays out its own content inside it. ui.set_min_width(ui.available_width()); match view { HubView::Onboarding => super::onboarding::render(ui, &self.app_context), @@ -551,9 +551,12 @@ impl ScreenLike for IdentityHubScreen { HubView::Home => { // One roster read per frame serves the header and every tab. let selected = self.app_context.resolve_selected_identity(); - // `ui.vertical_centered(...).inner` carries the tab's - // `AppAction` back out. - let inner = ui.vertical_centered(|ui| { + // The header, the tab bar and the tab content share one + // left-aligned column that stops at one width, so wide + // windows do not stretch them (wireframes A05/A06/A08). + // `.inner` carries the tab's `AppAction` back out. + let inner = ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { + ui.set_max_width(super::HUB_CONTENT_MAX_WIDTH); let (header_action, header_outcome) = match &selected { Some(identity) => super::home::render_header( ui, @@ -585,58 +588,47 @@ impl ScreenLike for IdentityHubScreen { } ui.add_space(16.0); rendered_tab = Some(self.selected_tab); - // Tab content starts at the tab bar's left edge and - // stops at one shared width, so wide windows do not - // stretch forms and rows (wireframes A05/A06/A08). - let content = - ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { - ui.set_max_width(super::HUB_CONTENT_MAX_WIDTH); - match self.selected_tab { - IdentityHubTab::Home => { - let (home_action, outcome) = match &selected { - Some(identity) => super::home::render( - ui, - &self.app_context, - identity, - &mut self.home_state, - &mut self.profile_cache, - &mut self.contacts_state, - ), - None => { - (AppAction::None, super::home::HomeOutcome::None) - } - }; - if let Some(next_tab) = super::home::apply_outcome( - &mut self.home_state, - outcome, - ) { - if next_tab != self.selected_tab { - self.contacts_state.reset(); - } - self.selected_tab = next_tab; - self.settings_tab.focus_section(outcome); - } - home_action - } - IdentityHubTab::Contacts => super::contacts::render( + let mut tab_action = match self.selected_tab { + IdentityHubTab::Home => { + let (home_action, outcome) = match &selected { + Some(identity) => super::home::render( ui, &self.app_context, - selected.as_ref(), - &mut self.contacts_state, + identity, + &mut self.home_state, &mut self.profile_cache, + &mut self.contacts_state, ), - IdentityHubTab::Activity => { - super::activity::render(ui, &self.app_context) + None => (AppAction::None, super::home::HomeOutcome::None), + }; + if let Some(next_tab) = + super::home::apply_outcome(&mut self.home_state, outcome) + { + if next_tab != self.selected_tab { + self.contacts_state.reset(); } - IdentityHubTab::Settings => self.settings_tab.render( - ui, - &self.app_context, - selected.as_ref(), - &mut self.profile_cache, - ), + self.selected_tab = next_tab; + self.settings_tab.focus_section(outcome); } - }); - let mut tab_action = content.inner; + home_action + } + IdentityHubTab::Contacts => super::contacts::render( + ui, + &self.app_context, + selected.as_ref(), + &mut self.contacts_state, + &mut self.profile_cache, + ), + IdentityHubTab::Activity => { + super::activity::render(ui, &self.app_context) + } + IdentityHubTab::Settings => self.settings_tab.render( + ui, + &self.app_context, + selected.as_ref(), + &mut self.profile_cache, + ), + }; tab_action |= header_action; tab_action }); diff --git a/tests/kittest/identity_hub_layout.rs b/tests/kittest/identity_hub_layout.rs index fdaa3dc15..e9aa4b874 100644 --- a/tests/kittest/identity_hub_layout.rs +++ b/tests/kittest/identity_hub_layout.rs @@ -272,3 +272,28 @@ fn contacts_sections_start_at_the_content_edge_with_one_add_button() { }); } } + +/// The identity header (avatar, name, balance and its actions) shares the tab +/// content's column on every tab, instead of spanning a wide window. +#[test] +fn header_stays_within_the_content_width_on_every_tab() { + for tab in [ + IdentityHubTab::Home, + IdentityHubTab::Contacts, + IdentityHubTab::Settings, + ] { + with_isolated_data_dir(|| { + let (_runtime, app_context) = fresh_app_context(); + let hub = hub_on(&app_context, 2000.0, tab); + let move_to_wallet = hub + .get_by_role_and_label(Role::Button, "Move to wallet") + .rect(); + assert_within_content( + &hub, + &format!("the header's Move to wallet on {tab:?}"), + move_to_wallet, + 2000.0, + ); + }); + } +} From f1a43f2a0b884382af8d247f29a0c380c6971c57 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 16 Oct 2026 08:17:26 +0000 Subject: [PATCH 06/73] fix(identity): shorten long usernames and contact names to fit their row MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A username can be 63 characters long. In the Profile tab's usernames card the name sat in a row that grows to fit its text, so a long name pushed the Main badge and the ••• menu out of the card and the whole tab past its content width. A hidden contact with a long name did the same to its Unhide button. These rows now lay out their actions first and shorten the name with "…" to the room that is left, keeping room for the Main badge; hovering shows the full name. Pending and finished username requests use the same layout. Active contact rows already wrap long names and are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012YneRVSNLhVnGiedWDr3fw --- src/ui/components/pill.rs | 26 +++- src/ui/identity/contacts.rs | 35 +++--- src/ui/identity/usernames_card.rs | 74 +++++++---- tests/kittest/identity_hub_layout.rs | 179 +++++++++++++++++++++++++-- 4 files changed, 255 insertions(+), 59 deletions(-) diff --git a/src/ui/components/pill.rs b/src/ui/components/pill.rs index 02f00ef2f..c0e237513 100644 --- a/src/ui/components/pill.rs +++ b/src/ui/components/pill.rs @@ -10,9 +10,29 @@ use crate::model::contested_name::approximate_time_until; use crate::model::dpns_usernames::UsernameRequest; use crate::ui::theme::{DashColors, ResponseExt, Shape}; use eframe::egui::{ - Color32, CornerRadius, Frame, Margin, Response, RichText, Sense, Stroke, StrokeKind, Ui, + Color32, CornerRadius, FontSelection, Frame, Margin, Response, RichText, Sense, Stroke, + StrokeKind, TextWrapMode, Ui, WidgetText, }; +/// Horizontal padding between a pill's edge and its label, in points. +const PILL_MARGIN_X: i8 = 10; + +fn pill_text(label: &str, accent: Color32) -> RichText { + RichText::new(label).color(accent).size(12.0).strong() +} + +/// Width [`accent_pill`] takes for `label`, so a row can keep room for it +/// before laying out text that has to shrink. +pub fn accent_pill_width(ui: &Ui, label: &str) -> f32 { + let galley = WidgetText::from(pill_text(label, Color32::WHITE)).into_galley( + ui, + Some(TextWrapMode::Extend), + f32::INFINITY, + FontSelection::Default, + ); + galley.size().x + 2.0 * f32::from(PILL_MARGIN_X) +} + /// Paint an inline pill: `label` in `accent`, on a 12%-accent fill with a 1px /// accent ring. `tooltip`, when present, is attached on hover. Returns the /// pill's [`Response`]. @@ -21,12 +41,12 @@ pub fn accent_pill(ui: &mut Ui, label: &str, accent: Color32, tooltip: Option<&s Color32::from_rgba_unmultiplied(accent.r(), accent.g(), accent.b(), (0.12 * 255.0) as u8); let stroke_color = Color32::from_rgba_unmultiplied(accent.r(), accent.g(), accent.b(), 180); - let text = RichText::new(label).color(accent).size(12.0).strong(); + let text = pill_text(label, accent); let inner = Frame::new() .fill(fill) .stroke(Stroke::NONE) .corner_radius(CornerRadius::same(Shape::RADIUS_FULL)) - .inner_margin(Margin::symmetric(10, 3)) + .inner_margin(Margin::symmetric(PILL_MARGIN_X, 3)) .show(ui, |ui| { ui.add(eframe::egui::Label::new(text).sense(Sense::hover())) }); diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index 9696a6614..1ea67b846 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -607,22 +607,25 @@ fn hidden_section( // `state` once the read borrow the row loop holds has ended. let mut clicked: Option = None; for contact in state.hidden_contacts() { - ui.horizontal(|ui| { - ui.label( - RichText::new(contact_label(contact)).color(DashColors::text_secondary(dark_mode)), - ); - ui.with_layout( - eframe::egui::Layout::right_to_left(eframe::egui::Align::Center), - |ui| { - let unhide = ui - .add(ComponentStyles::secondary_button(UNHIDE_LABEL, dark_mode)) - .clickable_tooltip(UNHIDE_TOOLTIP); - if unhide.clicked() { - clicked = Some(contact.clone()); - } - }, - ); - }); + // Unhide is laid out first so a long name is shortened to the room it + // leaves instead of pushing the button past the content column. + eframe::egui::Sides::new().shrink_left().truncate().show( + ui, + |ui| { + ui.label( + RichText::new(contact_label(contact)) + .color(DashColors::text_secondary(dark_mode)), + ); + }, + |ui| { + let unhide = ui + .add(ComponentStyles::secondary_button(UNHIDE_LABEL, dark_mode)) + .clickable_tooltip(UNHIDE_TOOLTIP); + if unhide.clicked() { + clicked = Some(contact.clone()); + } + }, + ); ui.add_space(4.0); } diff --git a/src/ui/identity/usernames_card.rs b/src/ui/identity/usernames_card.rs index 769b525e1..9c3c2d5d6 100644 --- a/src/ui/identity/usernames_card.rs +++ b/src/ui/identity/usernames_card.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use dash_sdk::dpp::identity::TimestampMillis; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; -use egui::{Align, Layout, RichText, Ui}; +use egui::{Align, Layout, RichText, Sides, Ui}; use crate::app::AppAction; use crate::backend_task::identity::IdentityTask; @@ -17,6 +17,7 @@ use crate::model::dpns_usernames::{ }; use crate::model::qualified_identity::QualifiedIdentity; use crate::ui::components::legacy_recovery_section::host_offer; +use crate::ui::components::pill; use crate::ui::components::qr_code_image::QrCodeImage; use crate::ui::identity::register_dpns_name_screen::{RegisterDpnsNameSource, status_line}; use crate::ui::identity::username_copy::{ @@ -47,6 +48,16 @@ pub enum UsernameRow { Outcome(UsernameRequest), } +/// A username in bold, shortened with "…" to the room left on its line less +/// `reserve` (points kept for what follows it). Hovering shows the full name. +fn name_label(ui: &mut Ui, text: &str, reserve: f32) { + let width = (ui.available_width() - reserve).max(0.0); + ui.scope(|ui| { + ui.set_max_width(width); + ui.add(egui::Label::new(RichText::new(text).strong()).truncate()); + }); +} + fn same_name(a: &str, b: &str) -> bool { normalize_dpns_label(a) == normalize_dpns_label(b) } @@ -271,19 +282,24 @@ impl UsernamesCard { show_main_badge, acquired_at, } => { - ui.horizontal(|ui| { - ui.label(RichText::new(format!("@{name}")).strong()); - if is_main && show_main_badge { - crate::ui::components::pill::accent_pill( - ui, - "Main", - DashColors::DASH_BLUE, - None, - ); - } - // The row's actions sit at the card's right edge, as in - // the A08 wireframe, not right after the name. - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let badge = is_main && show_main_badge; + // The row's actions sit at the card's right edge, as in + // the A08 wireframe; they are laid out first so a long name + // is shortened to the room they and the badge leave. + Sides::new().shrink_left().truncate().show( + ui, + |ui| { + let badge_room = if badge { + pill::accent_pill_width(ui, "Main") + ui.spacing().item_spacing.x + } else { + 0.0 + }; + name_label(ui, &format!("@{name}"), badge_room); + if badge { + pill::accent_pill(ui, "Main", DashColors::DASH_BLUE, None); + } + }, + |ui| { ui.menu_button("•••", |ui| { if ui.button("Copy username").clicked() { ui.ctx().copy_text(format!("@{name}")); @@ -305,8 +321,8 @@ impl UsernamesCard { }) .response .clickable_tooltip(format!("More actions for @{name}")); - }); - }); + }, + ); if acquired_at > 0 { ui.label( RichText::new(registered_on_line(acquired_at)) @@ -316,13 +332,16 @@ impl UsernamesCard { } } UsernameRow::Pending(request) => { - ui.horizontal(|ui| { - ui.label(RichText::new(format!("@{}", request.label)).strong()); - status_line(ui, Tone::Caution, phase_label(request.phase), dark_mode); - if ui.button("View status").clicked() { - action = request_status_action(app_context, identity, &request); - } - }); + Sides::new().shrink_left().truncate().show( + ui, + |ui| name_label(ui, &format!("@{}", request.label), 0.0), + |ui| { + if ui.button("View status").clicked() { + action = request_status_action(app_context, identity, &request); + } + status_line(ui, Tone::Caution, phase_label(request.phase), dark_mode); + }, + ); if let Some(detail) = pending_request_detail(request.phase, request.join_end, request.end) { @@ -334,10 +353,11 @@ impl UsernamesCard { } } UsernameRow::Outcome(request) => { - ui.horizontal(|ui| { - ui.label(RichText::new(format!("@{}", request.label)).strong()); - status_line(ui, Tone::Negative, phase_label(request.phase), dark_mode); - }); + Sides::new().shrink_left().truncate().show( + ui, + |ui| name_label(ui, &format!("@{}", request.label), 0.0), + |ui| status_line(ui, Tone::Negative, phase_label(request.phase), dark_mode), + ); ui.label( RichText::new(finished_request_detail(request.phase, request.decided_at)) .small() diff --git a/tests/kittest/identity_hub_layout.rs b/tests/kittest/identity_hub_layout.rs index e9aa4b874..307ed7cc6 100644 --- a/tests/kittest/identity_hub_layout.rs +++ b/tests/kittest/identity_hub_layout.rs @@ -52,6 +52,16 @@ fn mount_hub(app_context: &Arc, width: f32) -> HubHarness { /// Seeds and selects a user identity that owns two usernames. fn seed_identity_with_usernames(app_context: &Arc) -> Identifier { + seed_identity_named(app_context, &["alex", "alexander"]) +} + +/// The longest username Dash Platform accepts, in a wide letter. +fn longest_username() -> String { + "w".repeat(63) +} + +/// Seeds and selects a user identity that owns `names`. +fn seed_identity_named(app_context: &Arc, names: &[&str]) -> Identifier { let auth = key(1, Purpose::AUTHENTICATION); let identity = Identity::new_with_id_and_keys( Identifier::from([0xA7; 32]), @@ -68,16 +78,13 @@ fn seed_identity_with_usernames(app_context: &Arc) -> Identifier { identity_type: IdentityType::User, alias: None, private_keys: KeyStorage::default(), - dpns_names: vec![ - DPNSNameInfo { - name: "alex".into(), + dpns_names: names + .iter() + .map(|name| DPNSNameInfo { + name: (*name).into(), acquired_at: 1_700_000_000_000, - }, - DPNSNameInfo { - name: "alexander".into(), - acquired_at: 1_700_000_000_000, - }, - ], + }) + .collect(), associated_wallets: BTreeMap::new(), secret_access: None, wallet_index: None, @@ -123,6 +130,25 @@ fn deliver_profile(hub: &mut HubHarness, owner: Identifier) { } fn deliver_contact(hub: &mut HubHarness, owner: Identifier) { + deliver_contact_named(hub, owner, "Bao", None); +} + +fn deliver_contact_named( + hub: &mut HubHarness, + owner: Identifier, + nickname: &str, + username: Option, +) { + deliver_contact_with(hub, owner, nickname, username, false); +} + +fn deliver_contact_with( + hub: &mut HubHarness, + owner: Identifier, + nickname: &str, + username: Option, + is_hidden: bool, +) { let app_context = hub.state().0.app_context.clone(); let task = BackendTask::DashPayTask(Box::new(DashPayTask::LoadContacts { identity: app_context.resolve_selected_identity().expect("identity"), @@ -133,11 +159,11 @@ fn deliver_contact(hub: &mut HubHarness, owner: Identifier) { identity: owner, contacts: vec![ContactData { identity_id: Identifier::from([0xD8; 32]), - nickname: Some("Bao".into()), + nickname: Some(nickname.into()), note: None, - is_hidden: false, + is_hidden, account_reference: 0, - username: None, + username, display_name: None, avatar_url: None, bio: None, @@ -149,11 +175,23 @@ fn deliver_contact(hub: &mut HubHarness, owner: Identifier) { /// The hub on `tab` for an identity with a published profile and one contact. fn hub_on(app_context: &Arc, width: f32, tab: IdentityHubTab) -> HubHarness { let owner = seed_identity_with_usernames(app_context); + hub_for(app_context, owner, width, tab, |hub, owner| { + deliver_contact(hub, owner) + }) +} + +fn hub_for( + app_context: &Arc, + owner: Identifier, + width: f32, + tab: IdentityHubTab, + contacts: impl FnOnce(&mut HubHarness, Identifier), +) -> HubHarness { let mut hub = mount_hub(app_context, width); deliver_profile(&mut hub, owner); hub.state_mut().0.select_tab(tab); hub.run_steps(4); - deliver_contact(&mut hub, owner); + contacts(&mut hub, owner); hub.run_steps(4); hub } @@ -297,3 +335,118 @@ fn header_stays_within_the_content_width_on_every_tab() { }); } } + +/// The longest username Platform accepts never pushes a username's menu, the +/// card or the Profile tab past the content column: the name is shortened to +/// the room its badge and menu leave. +#[test] +fn the_longest_username_stays_within_the_usernames_card() { + for width in WIDTHS { + with_isolated_data_dir(|| { + let (_runtime, app_context) = fresh_app_context(); + let long = longest_username(); + let owner = seed_identity_named(&app_context, &[&long, "alex"]); + let hub = hub_for( + &app_context, + owner, + width, + IdentityHubTab::Settings, + |_, _| {}, + ); + let tab_bottom = hub.get_by_label("Home").rect().bottom(); + + let another = hub + .get_by_role_and_label(Role::Button, "Get another username") + .rect(); + assert_within_content(&hub, "the usernames card", another, width); + + // The shortened name, its Main badge and its menu sit side by side. + let name = hub + .query_all_by_label_contains("@www") + .map(|node| node.rect()) + .find(|rect| rect.top() > tab_bottom) + .expect("the long username is listed"); + let badge = hub.get_by_label("Main").rect(); + let menu = hub + .query_all_by_label("•••") + .map(|node| node.rect()) + .filter(|rect| rect.top() > tab_bottom) + .min_by(|a, b| a.top().total_cmp(&b.top())) + .expect("the long username has a menu"); + assert!( + name.right() <= badge.left() + EPSILON && badge.right() <= menu.left() + EPSILON, + "at {width} px, name {name:?}, badge {badge:?} and menu {menu:?} must not overlap" + ); + for menu in hub + .query_all_by_label("•••") + .map(|node| node.rect()) + .filter(|rect| rect.top() > tab_bottom) + { + assert!( + menu.right() <= another.right() + EPSILON, + "at {width} px, a username's menu ({menu:?}) must stay inside the card \ + ({another:?})" + ); + } + }); + } +} + +/// A long nickname and the longest username never push a contact's actions +/// past the content column. +#[test] +fn long_contact_names_stay_within_the_content_width() { + for width in WIDTHS { + with_isolated_data_dir(|| { + let (_runtime, app_context) = fresh_app_context(); + let owner = seed_identity_with_usernames(&app_context); + let nickname = "W".repeat(120); + let hub = hub_for( + &app_context, + owner, + width, + IdentityHubTab::Contacts, + |hub, owner| deliver_contact_named(hub, owner, &nickname, Some(longest_username())), + ); + let view_profile = hub + .get_by_label(dash_evo_tool::ui::identity::contacts::VIEW_PROFILE_LABEL) + .rect(); + assert_within_content(&hub, "a contact's View Profile button", view_profile, width); + assert!( + view_profile.left() >= content_left(&hub), + "at {width} px, View Profile stays on screen ({view_profile:?})" + ); + }); + } +} + +/// A hidden contact with a long nickname keeps its Unhide button inside the +/// content column. +#[test] +fn long_hidden_contact_names_stay_within_the_content_width() { + for width in WIDTHS { + with_isolated_data_dir(|| { + let (_runtime, app_context) = fresh_app_context(); + let owner = seed_identity_with_usernames(&app_context); + let nickname = "W".repeat(120); + let mut hub = hub_for( + &app_context, + owner, + width, + IdentityHubTab::Contacts, + |hub, owner| { + deliver_contact_with(hub, owner, &nickname, Some(longest_username()), true) + }, + ); + hub.get_by_role(Role::CheckBox).click(); + hub.run_steps(4); + let unhide = hub + .get_by_role_and_label( + Role::Button, + dash_evo_tool::ui::identity::contacts::UNHIDE_LABEL, + ) + .rect(); + assert_within_content(&hub, "a hidden contact's Unhide button", unhide, width); + }); + } +} From 5320dd5d729d36be53673c465c6ae76f537be8ee Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 16 Oct 2026 08:20:22 +0000 Subject: [PATCH 07/73] perf(identity): render the Profile tab from the borrowed identity The Profile tab cloned the selected identity twice per frame: once to keep its snapshot and again to render from it. It now renders from the identity the hub lends it and keeps the one owned snapshot only for attributing results, so steady-state frames clone it once. The profile-cache lookup borrows the snapshot as well. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012YneRVSNLhVnGiedWDr3fw --- src/ui/identity/settings.rs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/ui/identity/settings.rs b/src/ui/identity/settings.rs index 270f51a88..f0696b29d 100644 --- a/src/ui/identity/settings.rs +++ b/src/ui/identity/settings.rs @@ -236,7 +236,9 @@ impl SettingsTab { ) -> AppAction { self.ensure_selected(identity, profiles); - let Some(identity) = self.selected_identity.clone() else { + // Render from the borrowed identity; `selected_identity` keeps the one + // owned snapshot `ensure_selected` took, for attributing results. + let Some(identity) = identity else { return render_empty_state(ui); }; @@ -262,7 +264,7 @@ impl SettingsTab { egui::Layout::top_down(egui::Align::Min), |ui| { ui.set_width(left_width); - action |= self.render_social_profile(ui, app_context, &identity); + action |= self.render_social_profile(ui, app_context, identity); }, ); ui.allocate_ui_with_layout( @@ -270,13 +272,13 @@ impl SettingsTab { egui::Layout::top_down(egui::Align::Min), |ui| { ui.set_width(right_width); - action |= self.render_usernames(ui, app_context, &identity); + action |= self.render_usernames(ui, app_context, identity); }, ); }); } else { - action |= self.render_social_profile(ui, app_context, &identity); - action |= self.render_usernames(ui, app_context, &identity); + action |= self.render_social_profile(ui, app_context, identity); + action |= self.render_usernames(ui, app_context, identity); } ui.add_space(16.0); @@ -299,7 +301,7 @@ impl SettingsTab { .color(DashColors::text_secondary(dark_mode)), ); ui.add_space(8.0); - action |= self.render_advanced(ui, app_context, &identity); + action |= self.render_advanced(ui, app_context, identity); }); // Track open state so test helpers can read it if needed. self.advanced_open = resp.fully_open(); @@ -773,11 +775,11 @@ impl SettingsTab { if self.pending_save.is_some() { return; } - let Some(identity) = self.selected_identity.clone() else { + let Some(identity) = self.selected_identity.as_ref() else { self.profile_loaded = true; return; }; - let fields = match profiles.get_or_request(&identity) { + let fields = match profiles.get_or_request(identity) { Some(loaded) => loaded.clone(), // Not loaded yet — a load is queued; retry on the next frame. None => return, From 1b559f48f4f594bc28aa0cea75017828a410d252 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 16 Oct 2026 08:29:37 +0000 Subject: [PATCH 08/73] fix(identity): keep the identity hub inside narrow windows The hub's content column was given the content width as its width, but egui's set_max_width sets the width instead of capping it. In a window narrower than that the column grew past the window: the header's balance and actions were cut off, and the Profile tab never had little enough room to stack its usernames card under the form. The column now takes the smaller of the content width and the room the window has. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012YneRVSNLhVnGiedWDr3fw --- src/ui/identity/hub_screen.rs | 4 ++- tests/kittest/identity_hub_layout.rs | 40 ++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index 74a23f67d..b2b025246 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -556,7 +556,9 @@ impl ScreenLike for IdentityHubScreen { // windows do not stretch them (wireframes A05/A06/A08). // `.inner` carries the tab's `AppAction` back out. let inner = ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { - ui.set_max_width(super::HUB_CONTENT_MAX_WIDTH); + // `set_max_width` replaces the width rather than + // capping it, so cap at what the window has too. + ui.set_max_width(ui.available_width().min(super::HUB_CONTENT_MAX_WIDTH)); let (header_action, header_outcome) = match &selected { Some(identity) => super::home::render_header( ui, diff --git a/tests/kittest/identity_hub_layout.rs b/tests/kittest/identity_hub_layout.rs index 307ed7cc6..201c64394 100644 --- a/tests/kittest/identity_hub_layout.rs +++ b/tests/kittest/identity_hub_layout.rs @@ -450,3 +450,43 @@ fn long_hidden_contact_names_stay_within_the_content_width() { }); } } + +/// A window too narrow for the content width: the hub fits the window instead +/// of growing past it, and the Profile tab stacks its usernames card under the +/// form once the tab has less than 760 pt. +#[test] +fn a_narrow_window_keeps_the_hub_on_screen_and_stacks_the_profile() { + const NARROW: f32 = 900.0; + with_isolated_data_dir(|| { + let (_runtime, app_context) = fresh_app_context(); + let hub = hub_on(&app_context, NARROW, IdentityHubTab::Settings); + assert!( + NARROW - content_left(&hub) < 760.0, + "the tab must have less than 760 pt for this case" + ); + + for (what, label) in [ + ("the header's Move to wallet", "Move to wallet"), + ("Get another username", "Get another username"), + ] { + let rect = hub.get_by_role_and_label(Role::Button, label).rect(); + assert!( + rect.right() <= NARROW + EPSILON, + "at {NARROW} px, {what} ends at {} past the window", + rect.right() + ); + } + + let usernames = hub.get_by_label("Usernames").rect(); + let form_bottom = hub + .query_all_by_role(Role::TextInput) + .chain(hub.query_all_by_role(Role::MultilineTextInput)) + .map(|field| field.rect().bottom()) + .fold(f32::MIN, f32::max); + assert!( + usernames.top() > form_bottom, + "at {NARROW} px, the usernames card ({usernames:?}) stacks under the form \ + (ends at {form_bottom})" + ); + }); +} From 4b980d8f3891a980f01b432b6a337c4e96df8804 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 16 Oct 2026 08:34:53 +0000 Subject: [PATCH 09/73] fix(identity): keep long contact names clear of the row's buttons MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An active contact's name and username were laid out across the whole row before View Profile and Pay, so a long nickname wrapped under the buttons. The buttons are now laid out first and the name and username are shortened with "…" to the room they leave; hovering shows the full text, the same as hidden contacts and usernames. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012YneRVSNLhVnGiedWDr3fw --- src/ui/identity/contacts.rs | 84 ++++++++++++++-------------- tests/kittest/identity_hub_layout.rs | 35 ++++++++++++ 2 files changed, 77 insertions(+), 42 deletions(-) diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index 1ea67b846..ee5076868 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -498,58 +498,58 @@ fn active_section( ui.label(RichText::new(NO_SEARCH_MATCH).color(DashColors::text_secondary(dark_mode))); } else { for contact in matches { - ui.horizontal(|ui| { - let label = contact_label(contact); - ui.vertical(|ui| { - ui.label( - RichText::new(&label) - .strong() - .color(DashColors::text_primary(dark_mode)), - ); - if let Some(handle) = contact_handle(contact, &label) { + let label = contact_label(contact); + // The actions are laid out first so a long name or handle is + // shortened to the room they leave instead of running under + // them; hovering shows the full text. + eframe::egui::Sides::new().shrink_left().truncate().show( + ui, + |ui| { + ui.vertical(|ui| { ui.label( - RichText::new(handle) - .small() - .color(DashColors::text_secondary(dark_mode)), + RichText::new(&label) + .strong() + .color(DashColors::text_primary(dark_mode)), ); - } - }); - ui.with_layout( - eframe::egui::Layout::right_to_left(eframe::egui::Align::Center), - |ui| { - if pay_available { - let pay = ui - .add(ComponentStyles::secondary_button(PAY_LABEL, dark_mode)) - .clickable_tooltip("Send Dash to this contact."); - if pay.clicked() { - action = AppAction::AddScreen( - ScreenType::DashPaySendPayment( - identity.clone(), - contact.identity_id, - ) - .create_screen(app_context), - ); - } + if let Some(handle) = contact_handle(contact, &label) { + ui.label( + RichText::new(handle) + .small() + .color(DashColors::text_secondary(dark_mode)), + ); } - - let view_profile = ui - .add(ComponentStyles::secondary_button( - VIEW_PROFILE_LABEL, - dark_mode, - )) - .clickable_tooltip("View this contact's public profile."); - if view_profile.clicked() { + }); + }, + |ui| { + if pay_available { + let pay = ui + .add(ComponentStyles::secondary_button(PAY_LABEL, dark_mode)) + .clickable_tooltip("Send Dash to this contact."); + if pay.clicked() { action = AppAction::AddScreen( - contact_profile_screen_type( + ScreenType::DashPaySendPayment( identity.clone(), contact.identity_id, ) .create_screen(app_context), ); } - }, - ); - }); + } + + let view_profile = ui + .add(ComponentStyles::secondary_button( + VIEW_PROFILE_LABEL, + dark_mode, + )) + .clickable_tooltip("View this contact's public profile."); + if view_profile.clicked() { + action = AppAction::AddScreen( + contact_profile_screen_type(identity.clone(), contact.identity_id) + .create_screen(app_context), + ); + } + }, + ); ui.add_space(4.0); } } diff --git a/tests/kittest/identity_hub_layout.rs b/tests/kittest/identity_hub_layout.rs index 201c64394..255c283b4 100644 --- a/tests/kittest/identity_hub_layout.rs +++ b/tests/kittest/identity_hub_layout.rs @@ -416,6 +416,31 @@ fn long_contact_names_stay_within_the_content_width() { view_profile.left() >= content_left(&hub), "at {width} px, View Profile stays on screen ({view_profile:?})" ); + + // The name and the handle are shortened to the room the actions + // leave, so neither runs under a button. + let actions: Vec = hub + .query_all_by_role(Role::Button) + .map(|node| node.rect()) + .filter(|rect| { + rect.top() >= view_profile.top() - 30.0 + && rect.bottom() <= view_profile.bottom() + 30.0 + }) + .collect(); + for text in ["WWWW", "@www"] { + let text_rect = hub + .query_all_by_label_contains(text) + .map(|node| node.rect()) + .find(|rect| rect.top() >= view_profile.top() - 30.0) + .unwrap_or_else(|| panic!("the contact row shows {text}")); + for action in &actions { + assert!( + !text_rect.intersects(*action), + "at {width} px, {text}… ({text_rect:?}) runs under an action \ + ({action:?})" + ); + } + } }); } } @@ -447,6 +472,16 @@ fn long_hidden_contact_names_stay_within_the_content_width() { ) .rect(); assert_within_content(&hub, "a hidden contact's Unhide button", unhide, width); + let name = hub + .query_all_by_label_contains("WWWW") + .map(|node| node.rect()) + .find(|rect| rect.top() >= unhide.top() - 30.0) + .expect("the hidden contact is listed"); + assert!( + !name.intersects(unhide), + "at {width} px, the hidden contact's name ({name:?}) runs under Unhide \ + ({unhide:?})" + ); }); } } From ba828356c71aff7e1b62e848a6fa09368e977445 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 16 Oct 2026 18:39:03 +0000 Subject: [PATCH 10/73] feat(identity): show contact details and a private note in the hub's Contacts tab Clicking a contact on the Identity Hub Contacts tab now opens a detail pane next to the list instead of the legacy DashPay profile screen. On narrow windows the pane sits under the list. It shows the contact's picture, name, @username and bio, plus Pay when DashPay payments are enabled. The pane also edits the contact's private note. The note is saved encrypted on Dash Platform through the existing contactInfo write (DashPayTask::UpdateContactInfo), which keeps the nickname, the accepted accounts and the hidden state. The estimated fee is shown before saving. A save cannot be sent twice while one is still running, and a reload never overwrites an edit in progress. When the stored details cannot be read, the hub's existing overwrite confirmation now uses wording for a note save. The 255-byte note limit now lives in model::dashpay (MAX_CONTACT_NOTE_BYTES and validate_contact_note), and the backend serializer uses the same constant. The fee estimate is in PlatformFeeEstimator::estimate_contact_info_write. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012YneRVSNLhVnGiedWDr3fw --- docs/user-stories.md | 4 + src/backend_task/dashpay/contact_info.rs | 9 +- src/model/dashpay.rs | 76 +++ src/model/fee_estimation.rs | 46 ++ src/ui/identity/README.md | 2 +- src/ui/identity/contacts.rs | 518 +++++++++++++++++-- src/ui/identity/hub_screen.rs | 194 ++++++- src/ui/identity/settings.rs | 2 +- src/ui/state/contact_detail_view.rs | 336 ++++++++++++ src/ui/state/contacts_view.rs | 154 +++++- src/ui/state/mod.rs | 1 + tests/kittest/identity_hub_contact_detail.rs | 238 +++++++++ tests/kittest/identity_hub_contacts.rs | 2 + tests/kittest/identity_hub_layout.rs | 62 +-- tests/kittest/main.rs | 1 + 15 files changed, 1539 insertions(+), 106 deletions(-) create mode 100644 src/ui/state/contact_detail_view.rs create mode 100644 tests/kittest/identity_hub_contact_detail.rs diff --git a/docs/user-stories.md b/docs/user-stories.md index ddeba35f3..6791ada65 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -1042,6 +1042,8 @@ As a user, I want to see my contacts and their profiles so that I can manage my - Lists all accepted contacts. - View individual contact details and profile. +- In the Identity Hub Contacts tab, selecting a contact shows its picture, name, username, and + bio beside the list, or under it on a narrow window. ### DPY-006: Send payment to contact [Implemented] **Persona:** Alex, Priya @@ -1076,6 +1078,8 @@ As a user, I want to edit contact details (nickname, note, hidden status) so tha Contacts tab, and can be unhidden from there — including contacts hidden as a side effect of declining or cancelling a request. If another client saved details this app cannot read, the app warns that continuing will replace those details and asks for confirmation before unhiding. +- The Identity Hub contact details edit the private note, which is saved encrypted on Dash + Platform; the estimated fee is shown before saving, and the saved note loads with the contact. - Changes persist locally. ### DPY-010: Remove a contact [Gap] diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 3e191237f..9a5adff56 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -3,7 +3,8 @@ use crate::backend_task::dashpay::errors::DashPayError; use crate::backend_task::error::{ContactInfoReadError, TaskError}; use crate::context::AppContext; use crate::model::dashpay::{ - AcceptedAccounts, ContactInfoField, ContactInfoUpdate, UnreadableContactInfoPolicy, + AcceptedAccounts, ContactInfoField, ContactInfoUpdate, MAX_CONTACT_NOTE_BYTES, + UnreadableContactInfoPolicy, }; use crate::model::qualified_identity::QualifiedIdentity; use aes_gcm::aes::Aes256; @@ -76,9 +77,11 @@ impl ContactInfoPrivateData { if let Some(note) = &self.note { let note_bytes = note.as_bytes(); let note_len = note_bytes.len(); - if note_len > u8::MAX as usize { + if note_len > MAX_CONTACT_NOTE_BYTES { return Err(DashPayError::ContactInfoValidationFailed { - errors: vec![format!("Note too long ({note_len} bytes, max 255)")], + errors: vec![format!( + "Note too long ({note_len} bytes, max {MAX_CONTACT_NOTE_BYTES})" + )], }); } bytes.push(note_len as u8); diff --git a/src/model/dashpay.rs b/src/model/dashpay.rs index 6ca8fa253..fff9bf87d 100644 --- a/src/model/dashpay.rs +++ b/src/model/dashpay.rs @@ -22,6 +22,33 @@ pub fn validate_account_label(label: &str) -> Result<(), TextLengthError> { validate_char_count(label, 0, MAX_ACCOUNT_LABEL_CHARS) } +/// Most bytes a contact's private note can hold. Its encrypted `contactInfo` +/// payload stores the note's length in a single byte. +pub const MAX_CONTACT_NOTE_BYTES: usize = u8::MAX as usize; + +/// A private contact note is longer than its encrypted payload can store. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +#[error("This note is too long. Shorten it to save it.")] +pub struct ContactNoteTooLong { + /// Size of the note in UTF-8 bytes. + pub bytes: usize, + /// Largest size the payload accepts. + pub max: usize, +} + +/// Validate a contact's private note. The limit counts UTF-8 bytes, not +/// characters, because that is what the payload stores. +pub fn validate_contact_note(note: &str) -> Result<(), ContactNoteTooLong> { + let bytes = note.len(); + if bytes > MAX_CONTACT_NOTE_BYTES { + return Err(ContactNoteTooLong { + bytes, + max: MAX_CONTACT_NOTE_BYTES, + }); + } + Ok(()) +} + /// The recipient (`toUserId`) of a DashPay `contactRequest` document. /// /// Returns `None` when the field is absent or does not hold a readable @@ -125,6 +152,16 @@ impl ContactInfoUpdate { } } + /// Replace the private note, preserving the nickname and accepted accounts. + /// `display_hidden` must carry the contact's current hidden state, since the + /// whole document is rewritten. + pub fn note(note: Option, display_hidden: bool) -> Self { + Self { + note: ContactInfoField::Replace(note), + ..Self::visibility(display_hidden) + } + } + /// Replace every editable field with caller-owned values. pub fn replace_all( nickname: Option, @@ -454,6 +491,45 @@ mod tests { }) } + #[test] + fn a_contact_note_fits_up_to_the_payload_limit_in_bytes() { + assert_eq!(MAX_CONTACT_NOTE_BYTES, 255); + assert_eq!(validate_contact_note(""), Ok(())); + assert_eq!(validate_contact_note(&"a".repeat(255)), Ok(())); + assert_eq!( + validate_contact_note(&"a".repeat(256)), + Err(ContactNoteTooLong { + bytes: 256, + max: 255 + }) + ); + // 128 two-byte letters are 128 characters but 256 bytes. + assert_eq!( + validate_contact_note(&"é".repeat(128)), + Err(ContactNoteTooLong { + bytes: 256, + max: 255 + }) + ); + } + + #[test] + fn a_note_update_replaces_only_the_note() { + let update = ContactInfoUpdate::note(Some("Met at the meetup".into()), true); + assert_eq!( + update.note, + ContactInfoField::Replace(Some("Met at the meetup".into())) + ); + assert_eq!(update.nickname, ContactInfoField::Preserve); + assert_eq!(update.accepted_accounts, AcceptedAccounts::Preserve); + assert!(update.display_hidden, "the contact's hidden state is kept"); + assert_eq!(update.unreadable, UnreadableContactInfoPolicy::Abort); + + let cleared = ContactInfoUpdate::note(None, false); + assert_eq!(cleared.note, ContactInfoField::Replace(None)); + assert!(!cleared.display_hidden); + } + #[test] fn contact_request_recipient_reads_the_to_user_id() { assert_eq!( diff --git a/src/model/fee_estimation.rs b/src/model/fee_estimation.rs index 9919d97d6..c26636bec 100644 --- a/src/model/fee_estimation.rs +++ b/src/model/fee_estimation.rs @@ -707,6 +707,29 @@ impl PlatformFeeEstimator { self.estimate_document_replace_with_size(200) } + /// Estimate the fee for writing a contact's encrypted DashPay `contactInfo` + /// document holding a nickname and a private note of the given UTF-8 sizes. + /// Creating and replacing the document cost the same here. + pub fn estimate_contact_info_write(&self, nickname_bytes: usize, note_bytes: usize) -> u64 { + // Document fields: encToUserId (32), the two key indexes (8), and the + // id, owner and revision every document carries (72). + const FIXED_DOCUMENT_BYTES: usize = 112; + // privateData plaintext: version (4), nickname and note length + // prefixes (2), hidden flag (1), one accepted account (5). + const FIXED_PAYLOAD_BYTES: usize = 12; + const AES_BLOCK: usize = 16; + let plaintext = FIXED_PAYLOAD_BYTES + .saturating_add(nickname_bytes) + .saturating_add(note_bytes); + // A random IV, then the plaintext PKCS#7-padded to whole blocks. + let private_data = AES_BLOCK.saturating_add( + (plaintext / AES_BLOCK) + .saturating_add(1) + .saturating_mul(AES_BLOCK), + ); + self.estimate_document_create_with_size(FIXED_DOCUMENT_BYTES.saturating_add(private_data)) + } + /// Estimate fee for document transfer. /// Transfer updates ownership, minimal storage change. pub fn estimate_document_transfer(&self) -> u64 { @@ -1337,6 +1360,29 @@ pub fn shield_from_balance_fee_headroom( mod tests { use super::*; + #[test] + fn contact_info_write_fee_covers_a_document_and_grows_with_the_note() { + let estimator = PlatformFeeEstimator::new(); + let empty = estimator.estimate_contact_info_write(0, 0); + assert!( + empty >= estimator.estimate_document_create_with_size(0), + "a contactInfo write is at least a document write" + ); + let full = estimator.estimate_contact_info_write(0, 255); + assert!(full > empty, "a longer note stores more bytes"); + assert!( + estimator.estimate_contact_info_write(10, 255) >= full, + "the nickname is stored too" + ); + assert_eq!( + PlatformFeeEstimator::with_fee_multiplier(2000).estimate_contact_info_write(0, 255), + estimator + .estimate_contact_info_write(0, 255) + .saturating_mul(2), + "the network's fee multiplier applies" + ); + } + #[test] fn contest_fee_follows_protocol_version() { // USR-TC-005 diff --git a/src/ui/identity/README.md b/src/ui/identity/README.md index 3fabb22c7..9abf2672b 100644 --- a/src/ui/identity/README.md +++ b/src/ui/identity/README.md @@ -10,7 +10,7 @@ Promote a widget to `src/ui/components/` only if a second, non-hub consumer appe |---|---| | `hub_screen.rs` | Root screen, tab selection, landing resolution | | `home.rs` | Shared summary and Home (send · receive · top up · setup · payments · contacts) | -| `contacts.rs` | Contacts tab (gated / populated shell) | +| `contacts.rs` | Contacts tab (gated / populated shell, contact detail pane with private note) | | `activity.rs` | Hidden activity shell (retained for internal links) | | `settings.rs` | Profile tab (social profile · usernames · advanced) | | `onboarding.rs` | Onboarding empty state | diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index ee5076868..91d795a6d 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -12,8 +12,10 @@ //! //! Row actions dispatch the DashPay backend tasks directly: Accept and Decline //! on a received request, Cancel on a sent one, and Pay on an established -//! contact (which opens the existing send-payment screen), and View Profile -//! (which opens the existing contact-profile viewer). +//! contact (which opens the existing send-payment screen). Clicking an +//! established contact shows it in the detail pane beside the list (under it on +//! a narrow window), with its profile and a private note saved encrypted on +//! Dash Platform. use super::request_card::{RequestAction, RequestCard}; use super::social_profile_gate_card::SocialProfileGateCard; @@ -22,15 +24,22 @@ use crate::backend_task::BackendTask; use crate::backend_task::dashpay::{ContactData, DashPayTask}; use crate::context::AppContext; use crate::context::feature_gate::FeatureGate; -use crate::model::dashpay::{ContactInfoUpdate, UnreadableContactInfoPolicy}; +use crate::model::dashpay::{ + ContactInfoUpdate, MAX_CONTACT_NOTE_BYTES, UnreadableContactInfoPolicy, validate_contact_note, +}; +use crate::model::fee_estimation::format_credits_as_dash; use crate::model::qualified_identity::QualifiedIdentity; use crate::ui::ScreenType; +use crate::ui::components::avatar::Avatar; +use crate::ui::identity::identity_hero_card::HeroIdentityKind; use crate::ui::identity::identity_pill::shorten_id; +use crate::ui::state::AvatarCache; use crate::ui::state::contacts_view::contact_label; -use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt, Shape}; +use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt, Shape, Spacing}; +use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::platform_value::string_encoding::Encoding; use dash_sdk::platform::Identifier; -use eframe::egui::{CornerRadius, Frame, Margin, RichText, Stroke, Ui}; +use eframe::egui::{CornerRadius, Frame, Label, Margin, RichText, Stroke, TextEdit, Ui}; use std::sync::Arc; pub use crate::ui::state::contacts_view::{ContactRequestEntry, ContactsState}; @@ -42,7 +51,18 @@ pub const ADD_BY_USERNAME_LABEL: &str = "Add by username"; pub const SCAN_QR_LABEL: &str = "Scan QR"; pub const SHOW_MY_QR_LABEL: &str = "Show my QR"; pub const PAY_LABEL: &str = "Pay"; -pub const VIEW_PROFILE_LABEL: &str = "View Profile"; +pub const SELECT_CONTACT_TOOLTIP: &str = "Show this contact's details."; +pub const DETAIL_HEADING: &str = "Contact details"; +pub const NO_SELECTION: &str = "Select a contact to see their details."; +pub const NOTE_HEADING: &str = "Private note"; +pub const NOTE_HINT: &str = "Only you can see this note. It is stored encrypted on Dash Platform."; +pub const NOTE_PLACEHOLDER: &str = "Add a note that only you can see"; +pub const SAVE_NOTE_LABEL: &str = "Save note"; +pub const SAVING_NOTE_LABEL: &str = "Saving…"; +pub const NOTE_UNCHANGED_TOOLTIP: &str = "There are no changes to save."; +pub const NOTE_SAVE_TOOLTIP: &str = "Save this note on Dash Platform. Saving costs a small fee."; +pub const NOTE_SAVED: &str = "Your note is saved."; +const NOTE_SAVING_TOOLTIP: &str = "Your note is being saved."; pub const RECEIVED_HEADING: &str = "Received requests"; pub const ACTIVE_HEADING_PREFIX: &str = "Active contacts"; pub const SENT_HEADING: &str = "Sent requests"; @@ -70,6 +90,13 @@ pub const HIDDEN_EXPLAINER: &str = "Hidden contacts are kept out of your list. D pub const CANCEL_EXPLAINER: &str = "Cancelling a request hides it and tells the other person you are no longer waiting. The \ original request stays on the network."; +/// Below this tab width the detail pane stacks under the contact list. Home +/// and Profile switch to one column at the same width. +const TWO_COLUMN_MIN_WIDTH: f32 = 760.0; +/// Share of the two-column width the contact list takes. +const LIST_SHARE: f32 = 0.55; +const DETAIL_AVATAR_SIZE: f32 = 64.0; + /// Every clickable affordance on the Contacts tab header + populated shell. /// Mirrors the home-tab `HomeButton` dispatcher pattern so the dead-button /// unit test can enumerate every variant and assert each one maps to a real @@ -264,6 +291,49 @@ pub fn unhide_task(identity: QualifiedIdentity, contact: &ContactData) -> DashPa } } +/// Backend task that stores `note` as the private note on `contact`, keeping +/// its nickname, accepted accounts and hidden state. +pub fn save_note_task( + identity: QualifiedIdentity, + contact: &ContactData, + note: Option, +) -> DashPayTask { + DashPayTask::UpdateContactInfo { + identity, + contact_id: contact.identity_id, + update: ContactInfoUpdate::note(note, contact.is_hidden), + } +} + +/// The fee line shown beside Save note. +pub fn note_fee_text(fee: &str) -> String { + format!("Saving this note costs about {fee}.") +} + +/// Dispatch the save of the selected contact's note draft, if it has a valid +/// change. A save already running for that contact dispatches nothing: each +/// save is a paid write. +fn dispatch_note_save(state: &mut ContactsState, identity: &QualifiedIdentity) -> AppAction { + let Some(contact) = state.selected_contact().cloned() else { + return AppAction::None; + }; + let detail = state.detail_mut(); + let valid = detail + .note_to_save(&contact.identity_id) + .is_none_or(|note| validate_contact_note(¬e).is_ok()); + if !valid || !detail.is_dirty(&contact.identity_id) { + return AppAction::None; + } + let Some(note) = detail.begin_save(identity.identity.id(), contact.identity_id) else { + return AppAction::None; + }; + AppAction::BackendTask(BackendTask::DashPayTask(Box::new(save_note_task( + identity.clone(), + &contact, + note, + )))) +} + /// Public entry point invoked by `hub_screen` when the Contacts tab is active. /// /// Resolves the "current" identity as the app-scoped active identity. When no @@ -278,9 +348,21 @@ pub fn render( identity: Option<&QualifiedIdentity>, state: &mut ContactsState, profiles: &mut super::profile_cache::ProfileCache, + avatars: &mut AvatarCache, + pending_avatars: &mut Vec, ) -> AppAction { let tab_state = ContactsTabState::resolve(app_context, identity, profiles); - render_state(ui, app_context, &tab_state, state) + let mut avatars = DetailAvatars { + cache: avatars, + pending: pending_avatars, + }; + render_state(ui, app_context, &tab_state, state, &mut avatars) +} + +/// The hub's avatar cache and the fetches the detail pane asks it for. +struct DetailAvatars<'a> { + cache: &'a mut AvatarCache, + pending: &'a mut Vec, } /// The populated Contacts tab's load, when it is due: the contact list and the @@ -359,11 +441,12 @@ fn render_state( app_context: &Arc, tab_state: &ContactsTabState, state: &mut ContactsState, + avatars: &mut DetailAvatars<'_>, ) -> AppAction { match tab_state { ContactsTabState::Gated { handle } => render_gated(ui, handle.as_deref()), ContactsTabState::Populated { identity } => { - render_populated(ui, app_context, identity, state) + render_populated(ui, app_context, identity, state, avatars) } } } @@ -394,14 +477,15 @@ pub fn render_gated(ui: &mut Ui, handle: Option<&str>) -> AppAction { AppAction::None } -/// Populated-state shell — three sections, each rendering live rows, plus a -/// one-shot dispatch of [`DashPayTask::LoadContacts`] + -/// [`DashPayTask::LoadContactRequests`]. +/// Populated-state shell — the three sections and the selected contact's +/// detail pane: beside them on a wide tab, under the active contacts on a +/// narrow one. fn render_populated( ui: &mut Ui, app_context: &Arc, identity: &QualifiedIdentity, state: &mut ContactsState, + avatars: &mut DetailAvatars<'_>, ) -> AppAction { state.reconcile_owner(identity); let dark_mode = ui.ctx().global_style().visuals.dark_mode; @@ -409,18 +493,250 @@ fn render_populated( action |= header_row(ui, app_context, dark_mode); - // The sections scroll below the header, so a long contact list stays - // reachable in a short window. - eframe::egui::ScrollArea::vertical() - .auto_shrink([false, false]) - .show(ui, |ui| { - action |= received_section(ui, app_context, identity, state, dark_mode); - action |= active_section(ui, app_context, identity, state, dark_mode); - action |= sent_section(ui, app_context, identity, state, dark_mode); + // Everything scrolls below the header, so a long contact list stays + // reachable in a short window. The two columns scroll on their own, so the + // details stay in view while the list is scrolled. + if ui.available_width() >= TWO_COLUMN_MIN_WIDTH { + let content_width = ui.available_width() - Spacing::LG; + let list_width = content_width * LIST_SHARE; + let detail_width = content_width - list_width; + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = Spacing::LG; + let height = ui.available_height(); + ui.allocate_ui_with_layout( + eframe::egui::vec2(list_width, height), + eframe::egui::Layout::top_down(eframe::egui::Align::Min), + |ui| { + ui.set_width(list_width); + eframe::egui::ScrollArea::vertical() + .id_salt("identity_hub_contacts_list") + .auto_shrink([false, false]) + .show(ui, |ui| { + action |= received_section(ui, app_context, identity, state, dark_mode); + action |= active_section(ui, app_context, identity, state, dark_mode); + action |= sent_section(ui, app_context, identity, state, dark_mode); + }); + }, + ); + ui.allocate_ui_with_layout( + eframe::egui::vec2(detail_width, height), + eframe::egui::Layout::top_down(eframe::egui::Align::Min), + |ui| { + ui.set_width(detail_width); + eframe::egui::ScrollArea::vertical() + .id_salt("identity_hub_contact_detail") + .auto_shrink([false, false]) + .show(ui, |ui| { + action |= + detail_pane(ui, app_context, identity, state, avatars, dark_mode); + }); + }, + ); + }); + } else { + eframe::egui::ScrollArea::vertical() + .auto_shrink([false, false]) + .show(ui, |ui| { + action |= received_section(ui, app_context, identity, state, dark_mode); + action |= active_section(ui, app_context, identity, state, dark_mode); + // Stacked, the empty pane would only push the sent requests down. + if state.selected_contact().is_some() { + action |= detail_pane(ui, app_context, identity, state, avatars, dark_mode); + } + action |= sent_section(ui, app_context, identity, state, dark_mode); + }); + } + action +} + +/// Open the send-payment screen for `contact_id`. +fn pay_action( + app_context: &Arc, + identity: &QualifiedIdentity, + contact_id: Identifier, +) -> AppAction { + AppAction::AddScreen( + ScreenType::DashPaySendPayment(identity.clone(), contact_id).create_screen(app_context), + ) +} + +/// The selected contact's profile, its Pay action, and its private note. +fn detail_pane( + ui: &mut Ui, + app_context: &Arc, + identity: &QualifiedIdentity, + state: &mut ContactsState, + avatars: &mut DetailAvatars<'_>, + dark_mode: bool, +) -> AppAction { + let mut action = AppAction::None; + let mut save_clicked = false; + ui.add_space(12.0); + + section_card(ui, dark_mode, DETAIL_HEADING, |ui| { + let Some(contact) = state.selected_contact().cloned() else { + ui.label(RichText::new(NO_SELECTION).color(DashColors::text_secondary(dark_mode))); + return; + }; + let label = contact_label(&contact); + + ui.horizontal(|ui| { + match contact + .avatar_url + .as_deref() + .filter(|url| !url.is_empty() && !avatars.cache.is_failed(url)) + { + Some(url) => { + if let Some(task) = Avatar::new(Some(url), DETAIL_AVATAR_SIZE) + .show(ui, avatars.cache) + .fetch + { + avatars.pending.push(task); + } + } + None => { + super::avatar::paint_identity_monogram( + ui, + DETAIL_AVATAR_SIZE, + HeroIdentityKind::User, + label.chars().next(), + DashColors::DASH_BLUE, + ); + } + } + ui.add_space(12.0); + ui.vertical(|ui| { + ui.add( + Label::new( + RichText::new(&label) + .strong() + .size(18.0) + .color(DashColors::text_primary(dark_mode)), + ) + .truncate(), + ); + if let Some(handle) = contact_handle(&contact, &label) { + ui.add( + Label::new( + RichText::new(handle).color(DashColors::text_secondary(dark_mode)), + ) + .truncate(), + ); + } + }); }); + + if let Some(bio) = contact + .bio + .as_deref() + .map(str::trim) + .filter(|bio| !bio.is_empty()) + { + ui.add_space(8.0); + ui.label(RichText::new(bio).color(DashColors::text_primary(dark_mode))); + } + + if FeatureGate::DashPayOperations.is_available(app_context) { + ui.add_space(8.0); + let pay = ui + .add(ComponentStyles::secondary_button(PAY_LABEL, dark_mode)) + .clickable_tooltip("Send Dash to this contact."); + if pay.clicked() { + action = pay_action(app_context, identity, contact.identity_id); + } + } + + ui.add_space(12.0); + ui.separator(); + ui.add_space(8.0); + save_clicked = note_editor(ui, app_context, identity, state, &contact, dark_mode); + }); + + if save_clicked { + action = dispatch_note_save(state, identity); + } action } +/// The private-note editor, its size and fee, and Save note. Returns whether +/// Save note was clicked while it could save. +fn note_editor( + ui: &mut Ui, + app_context: &Arc, + identity: &QualifiedIdentity, + state: &mut ContactsState, + contact: &ContactData, + dark_mode: bool, +) -> bool { + let contact_id = contact.identity_id; + let saving = state + .detail() + .is_saving(&identity.identity.id(), &contact_id); + let detail = state.detail_mut(); + let Some(note) = detail.note_mut(&contact_id) else { + return false; + }; + + ui.label( + RichText::new(NOTE_HEADING) + .strong() + .color(DashColors::text_primary(dark_mode)), + ); + ui.label( + RichText::new(NOTE_HINT) + .small() + .color(DashColors::text_secondary(dark_mode)), + ); + ui.add_space(6.0); + ui.add_enabled( + !saving, + TextEdit::multiline(note) + .hint_text(NOTE_PLACEHOLDER) + .desired_rows(4) + .desired_width(f32::INFINITY), + ); + + let to_save = detail.note_to_save(&contact_id); + let note_bytes = to_save.as_deref().map_or(0, str::len); + super::settings::counter(ui, note_bytes, MAX_CONTACT_NOTE_BYTES, dark_mode); + let invalid = to_save + .as_deref() + .and_then(|note| validate_contact_note(note).err()); + if let Some(error) = invalid { + ui.label(RichText::new(error.to_string()).color(DashColors::ERROR)); + } + + ui.add_space(8.0); + let fee = app_context + .fee_estimator() + .estimate_contact_info_write(contact.nickname.as_deref().map_or(0, str::len), note_bytes); + ui.label( + RichText::new(note_fee_text(&format_credits_as_dash(fee))) + .small() + .color(DashColors::text_secondary(dark_mode)), + ); + ui.add_space(6.0); + + let dirty = detail.is_dirty(&contact_id); + let can_save = dirty && invalid.is_none() && !saving; + let label = if saving { + SAVING_NOTE_LABEL + } else { + SAVE_NOTE_LABEL + }; + let save = ComponentStyles::add_primary_button_enabled(ui, can_save, label); + let save = if can_save { + save.clickable_tooltip(NOTE_SAVE_TOOLTIP) + } else if saving { + save.disabled_tooltip(NOTE_SAVING_TOOLTIP) + } else if let Some(error) = invalid { + save.disabled_tooltip(error.to_string()) + } else { + save.disabled_tooltip(NOTE_UNCHANGED_TOOLTIP) + }; + save.clicked() && can_save +} + /// Received requests — one [`RequestCard`] per incoming request, with Accept /// and Decline wired to their backend tasks. fn received_section( @@ -462,10 +778,10 @@ fn received_section( dispatch_request_shared(app_context, state, identity, clicked) } -/// Active contacts — searchable list of established contacts, each row offering -/// the existing contact-profile viewer and, when enabled, the send-payment -/// screen. Pay is an experimental DashPay feature, classified identically at all -/// four entry points into [`ScreenType::DashPaySendPayment`]. +/// Active contacts — searchable list of established contacts. Clicking a contact +/// shows it in the detail pane; each row also offers, when enabled, the +/// send-payment screen. Pay is an experimental DashPay feature, classified +/// identically at every entry point into [`ScreenType::DashPaySendPayment`]. fn active_section( ui: &mut Ui, app_context: &Arc, @@ -479,6 +795,8 @@ fn active_section( let heading = format!("{ACTIVE_HEADING_PREFIX} · {}", state.contacts_len()); let has_contacts = state.contacts_len() > 0; + let selected = state.detail().selected(); + let mut clicked_contact = None; section_card(ui, dark_mode, &heading, |ui| { // The search box only earns its place once there is something to search. @@ -506,11 +824,17 @@ fn active_section( ui, |ui| { ui.vertical(|ui| { - ui.label( - RichText::new(&label) - .strong() - .color(DashColors::text_primary(dark_mode)), - ); + let row = ui + .add(eframe::egui::Button::selectable( + selected == Some(contact.identity_id), + RichText::new(&label) + .strong() + .color(DashColors::text_primary(dark_mode)), + )) + .clickable_tooltip(SELECT_CONTACT_TOOLTIP); + if row.clicked() { + clicked_contact = Some(contact.identity_id); + } if let Some(handle) = contact_handle(contact, &label) { ui.label( RichText::new(handle) @@ -526,28 +850,9 @@ fn active_section( .add(ComponentStyles::secondary_button(PAY_LABEL, dark_mode)) .clickable_tooltip("Send Dash to this contact."); if pay.clicked() { - action = AppAction::AddScreen( - ScreenType::DashPaySendPayment( - identity.clone(), - contact.identity_id, - ) - .create_screen(app_context), - ); + action = pay_action(app_context, identity, contact.identity_id); } } - - let view_profile = ui - .add(ComponentStyles::secondary_button( - VIEW_PROFILE_LABEL, - dark_mode, - )) - .clickable_tooltip("View this contact's public profile."); - if view_profile.clicked() { - action = AppAction::AddScreen( - contact_profile_screen_type(identity.clone(), contact.identity_id) - .create_screen(app_context), - ); - } }, ); ui.add_space(4.0); @@ -571,6 +876,9 @@ fn active_section( action |= hidden_section(ui, identity, state, dark_mode); }); + if let Some(contact_id) = clicked_contact { + state.select_contact(&contact_id); + } action } @@ -1047,9 +1355,123 @@ mod tests { ); } + // --------------------------------------------------------------- + // Private note — a paid, encrypted contactInfo write. + // --------------------------------------------------------------- + + fn contact_with_note(note: Option<&str>) -> ContactData { + ContactData { + note: note.map(str::to_string), + ..contact_named("Bao") + } + } + + /// A state bound to `identity` with Bao listed and selected. + fn state_with_selected_contact( + identity: &QualifiedIdentity, + note: Option<&str>, + ) -> ContactsState { + let mut state = ContactsState::default(); + state.reconcile_owner(identity); + state.record_contacts(vec![contact_with_note(note)]); + state.select_contact(&id(5)); + state + } + + fn saved_note(action: AppAction) -> (Identifier, Identifier, ContactInfoUpdate) { + let AppAction::BackendTask(BackendTask::DashPayTask(task)) = action else { + panic!("expected a contactInfo write, got {action:?}"); + }; + match *task { + DashPayTask::UpdateContactInfo { + identity, + contact_id, + update, + } => (identity.identity.id(), contact_id, update), + other => panic!("expected UpdateContactInfo, got {other:?}"), + } + } + + #[test] + fn saving_a_note_replaces_only_the_note_of_that_contact() { + let mut contact = contact_with_note(None); + contact.is_hidden = true; + let task = save_note_task(qualified_identity(id(1)), &contact, Some("Bao".into())); + let (owner, contact_id, update) = saved_note(AppAction::BackendTask( + BackendTask::DashPayTask(Box::new(task)), + )); + assert_eq!((owner, contact_id), (id(1), id(5))); + assert_eq!(update, ContactInfoUpdate::note(Some("Bao".into()), true)); + } + + #[test] + fn save_note_sends_the_edited_note_once() { + let identity = qualified_identity(id(1)); + let mut state = state_with_selected_contact(&identity, Some("Old")); + *state.detail_mut().note_mut(&id(5)).expect("draft") = " Met at the meetup\n".into(); + + let (owner, contact_id, update) = saved_note(dispatch_note_save(&mut state, &identity)); + assert_eq!((owner, contact_id), (id(1), id(5))); + assert_eq!( + update.note, + crate::model::dashpay::ContactInfoField::Replace(Some("Met at the meetup".into())) + ); + assert!(state.detail().is_saving(&id(1), &id(5))); + assert_eq!( + dispatch_note_save(&mut state, &identity), + AppAction::None, + "a second click must not pay for a second write" + ); + } + + #[test] + fn clearing_a_note_saves_no_note() { + let identity = qualified_identity(id(1)); + let mut state = state_with_selected_contact(&identity, Some("Old")); + state.detail_mut().note_mut(&id(5)).expect("draft").clear(); + + let (_, _, update) = saved_note(dispatch_note_save(&mut state, &identity)); + assert_eq!( + update.note, + crate::model::dashpay::ContactInfoField::Replace(None) + ); + } + + #[test] + fn an_unchanged_or_too_long_note_is_not_saved() { + let identity = qualified_identity(id(1)); + let mut state = state_with_selected_contact(&identity, Some("Old")); + assert_eq!(dispatch_note_save(&mut state, &identity), AppAction::None); + + *state.detail_mut().note_mut(&id(5)).expect("draft") = "a".repeat(256); + assert_eq!(dispatch_note_save(&mut state, &identity), AppAction::None); + assert!(!state.detail().is_saving(&id(1), &id(5))); + + let mut unselected = ContactsState::default(); + unselected.reconcile_owner(&identity); + assert_eq!( + dispatch_note_save(&mut unselected, &identity), + AppAction::None + ); + } + + #[test] + fn the_fee_line_is_one_sentence_with_the_amount() { + assert_eq!( + note_fee_text("0.0001 DASH"), + "Saving this note costs about 0.0001 DASH." + ); + } + #[test] fn copy_constants_are_complete_sentences() { for line in [ + NO_SELECTION, + NOTE_HINT, + NOTE_UNCHANGED_TOOLTIP, + NOTE_SAVE_TOOLTIP, + NOTE_SAVED, + SELECT_CONTACT_TOOLTIP, NO_RECEIVED_EMPTY, NO_ACTIVE_EMPTY, NO_SENT_EMPTY, diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index b2b025246..b46043ce7 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -14,7 +14,7 @@ use crate::backend_task::error::TaskError; use crate::backend_task::identity::IdentityTask; use crate::backend_task::{BackendTask, BackendTaskContext, BackendTaskSuccessResult}; use crate::context::AppContext; -use crate::model::dashpay::UnreadableContactInfoPolicy; +use crate::model::dashpay::{ContactInfoField, UnreadableContactInfoPolicy}; use crate::ui::components::component_trait::Component; use crate::ui::components::confirmation_dialog::{ConfirmationDialog, ConfirmationStatus}; use crate::ui::components::left_panel::add_left_panel; @@ -200,7 +200,7 @@ impl IdentityHubScreen { } fn reset_contacts_for_identity_change(&mut self) { - release_request_guards_for_abandoned_confirmations( + release_guards_for_abandoned_confirmations( &mut self.contacts_state, self.pending_contact_info_confirmations.iter().chain( self.contact_info_overwrite_dialog @@ -620,6 +620,8 @@ impl ScreenLike for IdentityHubScreen { selected.as_ref(), &mut self.contacts_state, &mut self.profile_cache, + &mut self.avatar_cache, + &mut self.pending_avatars, ), IdentityHubTab::Activity => { super::activity::render(ui, &self.app_context) @@ -676,9 +678,7 @@ impl ScreenLike for IdentityHubScreen { self.contact_info_overwrite_dialog = None; } Some(ConfirmationStatus::Canceled) => { - if let ContactInfoTaskKey::Request(request_id) = key { - self.contacts_state.release_request(&request_id); - } + release_guards_for_abandoned_confirmations(&mut self.contacts_state, [&key]); self.pending_contact_info_tasks.remove(&key); self.contacts_state.invalidate(); self.contact_info_overwrite_dialog = None; @@ -812,9 +812,9 @@ impl ScreenLike for IdentityHubScreen { self.contacts_state.record_contacts(contacts.clone()); } } - // A confirmed contactInfo write — on this tab that is an unhide. - // Re-arm the load so the restored contact comes back from the - // authoritative list, not just the optimistic local move. + // A confirmed contactInfo write — an unhide or a private-note + // save. Re-arm the load so the authoritative list replaces the + // optimistic local edit. BackendTaskSuccessResult::DashPayContactInfoUpdated { identity, contact_id, @@ -823,11 +823,12 @@ impl ScreenLike for IdentityHubScreen { identity_id: *identity, contact_id: *contact_id, }; - if self.pending_contact_info_tasks.remove(&key).is_some() { + self.contacts_state.finish_note_save(identity, contact_id); + if let Some(task) = self.pending_contact_info_tasks.remove(&key) { self.contacts_state.invalidate(); MessageBanner::set_global( self.app_context.egui_ctx(), - "This contact is back in your list.", + contact_info_saved_message(&task), MessageType::Success, ); } @@ -908,6 +909,7 @@ impl ScreenLike for IdentityHubScreen { self.pending_contact_info_tasks.remove(&key); } release_request_guard_for_error(&mut self.contacts_state, error); + release_note_save_for_error(&mut self.contacts_state, error); // Let AppState render the default error banner — the hub has no // other special-case error handling of its own yet. @@ -927,17 +929,54 @@ fn release_request_guard_for_error(state: &mut super::contacts::ContactsState, e } } -fn release_request_guards_for_abandoned_confirmations<'a>( +/// Release the note-save guard a failed direct contactInfo write names. +fn release_note_save_for_error(state: &mut super::contacts::ContactsState, error: &TaskError) { + if let TaskError::DashPayContactInfoActionFailed { + identity_id, + contact_id, + .. + } = error + { + state.release_note_save(identity_id, contact_id); + } +} + +/// Release the request and note-save guards of confirmations that will never +/// be answered: no task is left running for them. +fn release_guards_for_abandoned_confirmations<'a>( state: &mut super::contacts::ContactsState, keys: impl IntoIterator, ) { for key in keys { - if let ContactInfoTaskKey::Request(request_id) = key { - state.release_request(request_id); + match key { + ContactInfoTaskKey::Request(request_id) => state.release_request(request_id), + ContactInfoTaskKey::Direct { + identity_id, + contact_id, + } => state.release_note_save(identity_id, contact_id), } } } +/// Whether a captured contactInfo write is a private-note save rather than an +/// unhide. +fn is_note_save(task: &DashPayTask) -> bool { + matches!( + task, + DashPayTask::UpdateContactInfo { update, .. } + if matches!(update.note, ContactInfoField::Replace(_)) + ) +} + +/// Success banner for a confirmed direct contactInfo write. +fn contact_info_saved_message(task: &DashPayTask) -> &'static str { + if is_note_save(task) { + super::contacts::NOTE_SAVED + } else { + "This contact is back in your list." + } +} + fn can_confirm_contact_info_overwrite(task: &DashPayTask) -> bool { match task { DashPayTask::UpdateContactInfo { update, .. } => { @@ -960,6 +999,15 @@ fn contact_info_confirmation_copy(task: &DashPayTask) -> (&'static str, String) use dash_sdk::dpp::platform_value::string_encoding::Encoding; match task { + DashPayTask::UpdateContactInfo { contact_id, .. } if is_note_save(task) => { + let contact = shorten_id(&contact_id.to_string(Encoding::Base58)); + ( + "Save note and replace saved details?", + format!( + "The saved details for contact {contact} cannot be read. Saving this note will clear the contact's saved nickname and accepted-account settings. You cannot undo this change." + ), + ) + } DashPayTask::UpdateContactInfo { contact_id, .. } => { let contact = shorten_id(&contact_id.to_string(Encoding::Base58)); ( @@ -2057,7 +2105,7 @@ mod tests { }, ]; - release_request_guards_for_abandoned_confirmations(&mut state, &keys); + release_guards_for_abandoned_confirmations(&mut state, &keys); assert!(state.is_in_flight(&id(1))); assert!( @@ -2066,6 +2114,124 @@ mod tests { ); } + fn contact_info_task(update: crate::model::dashpay::ContactInfoUpdate) -> DashPayTask { + DashPayTask::UpdateContactInfo { + identity: hub_identity(id(1)), + contact_id: id(5), + update, + } + } + + fn hub_identity(identifier: Identifier) -> QualifiedIdentity { + QualifiedIdentity { + identity: Identity::create_basic_identity(identifier, PlatformVersion::latest()) + .expect("basic identity"), + associated_voter_identity: None, + associated_operator_identity: None, + associated_owner_key_id: None, + identity_type: IdentityType::User, + alias: None, + private_keys: KeyStorage::default(), + dpns_names: vec![], + associated_wallets: BTreeMap::new(), + secret_access: None, + wallet_index: None, + top_ups: BTreeMap::new(), + status: IdentityStatus::Active, + network: Network::Testnet, + } + } + + #[test] + fn a_saved_note_and_an_unhide_confirm_differently() { + use crate::model::dashpay::ContactInfoUpdate; + + let note = contact_info_task(ContactInfoUpdate::note(Some("Bao".into()), false)); + let unhide = contact_info_task(ContactInfoUpdate::visibility(false)); + assert!(is_note_save(¬e)); + assert!(!is_note_save(&unhide)); + assert_eq!( + contact_info_saved_message(¬e), + crate::ui::identity::contacts::NOTE_SAVED + ); + assert_eq!( + contact_info_saved_message(&unhide), + "This contact is back in your list." + ); + + let (title, message) = contact_info_confirmation_copy(¬e); + assert_eq!(title, "Save note and replace saved details?"); + assert!( + message.contains("nickname") && !message.contains("Unhiding"), + "the overwrite warning names what a note save clears: {message}" + ); + let (title, _) = contact_info_confirmation_copy(&unhide); + assert_eq!(title, "Unhide contact and replace saved details?"); + } + + #[test] + fn abandoning_a_note_save_confirmation_releases_its_guard() { + let mut state = ContactsState::default(); + assert!(state.begin_request(id(2))); + state.record_contacts(vec![crate::backend_task::dashpay::ContactData { + identity_id: id(4), + nickname: None, + note: None, + is_hidden: false, + account_reference: 0, + username: None, + display_name: None, + avatar_url: None, + bio: None, + }]); + state.select_contact(&id(4)); + *state.detail_mut().note_mut(&id(4)).expect("draft") = "Bao".into(); + assert!(state.detail_mut().begin_save(id(3), id(4)).is_some()); + + release_guards_for_abandoned_confirmations( + &mut state, + &[ContactInfoTaskKey::Direct { + identity_id: id(3), + contact_id: id(4), + }], + ); + + assert!(!state.detail().is_saving(&id(3), &id(4))); + assert!(state.is_in_flight(&id(2)), "unrelated request guards stay"); + } + + #[test] + fn a_failed_note_save_releases_only_its_own_guard() { + let mut state = ContactsState::default(); + state.record_contacts(vec![crate::backend_task::dashpay::ContactData { + identity_id: id(4), + nickname: None, + note: None, + is_hidden: false, + account_reference: 0, + username: None, + display_name: None, + avatar_url: None, + bio: None, + }]); + state.select_contact(&id(4)); + *state.detail_mut().note_mut(&id(4)).expect("draft") = "Bao".into(); + assert!(state.detail_mut().begin_save(id(3), id(4)).is_some()); + + release_note_save_for_error(&mut state, &TaskError::WalletLocked); + assert!(state.detail().is_saving(&id(3), &id(4))); + + release_note_save_for_error( + &mut state, + &TaskError::DashPayContactInfoActionFailed { + identity_id: id(3), + contact_id: id(4), + source: Box::new(TaskError::WalletLocked), + }, + ); + assert!(!state.detail().is_saving(&id(3), &id(4))); + } + #[test] fn concurrent_contact_info_errors_keep_distinct_retry_keys() { use crate::backend_task::error::ContactInfoReadError; diff --git a/src/ui/identity/settings.rs b/src/ui/identity/settings.rs index f0696b29d..1bc5f2556 100644 --- a/src/ui/identity/settings.rs +++ b/src/ui/identity/settings.rs @@ -964,7 +964,7 @@ fn sub_heading(ui: &mut Ui, text: &str, dark_mode: bool) { ); } -fn counter(ui: &mut Ui, count: usize, max: usize, dark_mode: bool) { +pub(super) fn counter(ui: &mut Ui, count: usize, max: usize, dark_mode: bool) { let color = if count > max { DashColors::ERROR } else { diff --git a/src/ui/state/contact_detail_view.rs b/src/ui/state/contact_detail_view.rs new file mode 100644 index 000000000..f3467ac62 --- /dev/null +++ b/src/ui/state/contact_detail_view.rs @@ -0,0 +1,336 @@ +//! Detail-pane state for the Identities hub's Contacts tab: which contact is +//! selected, the private note being edited for it, and the note saves still +//! running. Renders nothing — [`crate::ui::identity::contacts`] paints it. + +use crate::backend_task::dashpay::ContactData; +use dash_sdk::platform::Identifier; +use std::collections::HashMap; +use std::time::{Duration, Instant}; + +/// Age after which a note save that never reported back stops blocking the +/// Save button, pruned on the next view reset. +const NOTE_SAVE_TIMEOUT: Duration = Duration::from_secs(5 * 60); + +/// The note being edited for one contact, and the stored note it started from. +#[derive(Debug, Clone)] +struct NoteDraft { + contact_id: Identifier, + baseline: Option, + text: String, +} + +/// Selection and private-note editing for the contact detail pane. +#[derive(Debug, Default, Clone)] +pub struct ContactDetailState { + selected: Option, + draft: Option, + /// Note saves still running, keyed by owner identity and contact, with the + /// note that was sent. Each save is a paid write, so the Save button stays + /// disabled until its result lands. + saving: HashMap<(Identifier, Identifier), (Option, Instant)>, +} + +/// The note as it is stored: surrounding whitespace dropped, and an empty note +/// stored as no note. +pub fn normalized_note(text: &str) -> Option { + let trimmed = text.trim(); + (!trimmed.is_empty()).then(|| trimmed.to_string()) +} + +impl NoteDraft { + fn new(contact: &ContactData) -> Self { + let baseline = contact.note.as_deref().and_then(normalized_note); + Self { + contact_id: contact.identity_id, + text: baseline.clone().unwrap_or_default(), + baseline, + } + } + + fn is_dirty(&self) -> bool { + normalized_note(&self.text) != self.baseline + } +} + +impl ContactDetailState { + /// Select `contact` and start its note draft from the stored note. + /// Selecting the contact already selected keeps its draft. + pub fn select(&mut self, contact: &ContactData) { + if self.draft_for(&contact.identity_id).is_some() { + return; + } + self.selected = Some(contact.identity_id); + self.draft = Some(NoteDraft::new(contact)); + } + + /// The selected contact, if any. + pub fn selected(&self) -> Option { + self.selected + } + + /// Drop the selection and the draft, keeping the guards of saves still + /// running and pruning those that never reported back. + pub fn reset(&mut self) { + self.selected = None; + self.draft = None; + let now = Instant::now(); + self.saving + .retain(|_, (_, started)| now.saturating_duration_since(*started) < NOTE_SAVE_TIMEOUT); + } + + /// Follow a fresh copy of the selected contact. The draft restarts from the + /// stored note when the user has not changed it, and an edit the stored + /// note now matches is no longer unsaved; any other edit is kept. + pub fn sync(&mut self, contact: &ContactData) { + if self.selected != Some(contact.identity_id) { + return; + } + let stored = contact.note.as_deref().and_then(normalized_note); + match &mut self.draft { + Some(draft) if draft.contact_id == contact.identity_id => { + if !draft.is_dirty() { + draft.text = stored.clone().unwrap_or_default(); + draft.baseline = stored; + } else if normalized_note(&draft.text) == stored { + draft.baseline = stored; + } + } + _ => self.draft = Some(NoteDraft::new(contact)), + } + } + + fn draft_for(&self, contact_id: &Identifier) -> Option<&NoteDraft> { + self.draft + .as_ref() + .filter(|draft| draft.contact_id == *contact_id) + } + + /// The draft text for `contact_id`, for binding to the note editor. + pub fn note_mut(&mut self, contact_id: &Identifier) -> Option<&mut String> { + self.draft + .as_mut() + .filter(|draft| draft.contact_id == *contact_id) + .map(|draft| &mut draft.text) + } + + /// The note the draft would store for `contact_id`. + pub fn note_to_save(&self, contact_id: &Identifier) -> Option { + self.draft_for(contact_id) + .and_then(|draft| normalized_note(&draft.text)) + } + + /// Whether the draft for `contact_id` differs from the stored note. + pub fn is_dirty(&self, contact_id: &Identifier) -> bool { + self.draft_for(contact_id).is_some_and(NoteDraft::is_dirty) + } + + /// Claim the save slot for `owner`'s note on `contact_id`. Returns the note + /// to send, or `None` when there is no draft for that contact or a save for + /// it is already running. + pub fn begin_save( + &mut self, + owner: Identifier, + contact_id: Identifier, + ) -> Option> { + let draft = self.draft_for(&contact_id)?; + let key = (owner, contact_id); + if self.saving.contains_key(&key) { + return None; + } + let note = normalized_note(&draft.text); + self.saving.insert(key, (note.clone(), Instant::now())); + Some(note) + } + + /// Whether a note save for `owner` and `contact_id` is running. + pub fn is_saving(&self, owner: &Identifier, contact_id: &Identifier) -> bool { + self.saving.contains_key(&(*owner, *contact_id)) + } + + /// Release a confirmed save and return the note it stored. + pub fn finish_save( + &mut self, + owner: &Identifier, + contact_id: &Identifier, + ) -> Option> { + self.saving + .remove(&(*owner, *contact_id)) + .map(|(note, _)| note) + } + + /// Release a save that failed or was abandoned; the draft is kept. + pub fn release_save(&mut self, owner: &Identifier, contact_id: &Identifier) { + self.saving.remove(&(*owner, *contact_id)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn id(byte: u8) -> Identifier { + Identifier::from_bytes(&[byte; 32]).expect("32-byte identifier") + } + + fn contact(byte: u8, note: Option<&str>) -> ContactData { + ContactData { + identity_id: id(byte), + nickname: None, + note: note.map(str::to_string), + is_hidden: false, + account_reference: 0, + username: None, + display_name: None, + avatar_url: None, + bio: None, + } + } + + #[test] + fn whitespace_only_notes_are_stored_as_no_note() { + assert_eq!(normalized_note(""), None); + assert_eq!(normalized_note(" \n"), None); + assert_eq!(normalized_note(" Bao\n"), Some("Bao".into())); + } + + #[test] + fn selecting_a_contact_starts_from_its_stored_note() { + let mut state = ContactDetailState::default(); + state.select(&contact(5, Some("Met at the meetup"))); + + assert_eq!(state.selected(), Some(id(5))); + assert_eq!( + state.note_mut(&id(5)).map(|note| note.as_str()), + Some("Met at the meetup") + ); + assert!( + !state.is_dirty(&id(5)), + "an untouched note has nothing to save" + ); + assert_eq!( + state.note_mut(&id(6)), + None, + "the draft is only for the selection" + ); + } + + #[test] + fn editing_the_note_makes_it_dirty_until_it_matches_again() { + let mut state = ContactDetailState::default(); + state.select(&contact(5, Some("Bao"))); + *state.note_mut(&id(5)).expect("draft") = "Bao from work".into(); + assert!(state.is_dirty(&id(5))); + assert_eq!(state.note_to_save(&id(5)), Some("Bao from work".into())); + + *state.note_mut(&id(5)).expect("draft") = " Bao ".into(); + assert!( + !state.is_dirty(&id(5)), + "surrounding whitespace does not change what is stored" + ); + } + + #[test] + fn a_reloaded_note_replaces_an_untouched_draft_but_not_an_edit() { + let mut state = ContactDetailState::default(); + state.select(&contact(5, None)); + state.sync(&contact(5, Some("Saved elsewhere"))); + assert_eq!( + state.note_mut(&id(5)).map(|note| note.clone()), + Some("Saved elsewhere".into()) + ); + + *state.note_mut(&id(5)).expect("draft") = "My edit".into(); + state.sync(&contact(5, Some("Saved again"))); + assert_eq!( + state.note_mut(&id(5)).map(|note| note.clone()), + Some("My edit".into()), + "an edit in progress is never overwritten" + ); + } + + #[test] + fn only_the_selected_contact_moves_the_draft() { + let mut state = ContactDetailState::default(); + state.select(&contact(5, None)); + *state.note_mut(&id(5)).expect("draft") = "My edit".into(); + + state.select(&contact(5, None)); + state.sync(&contact(6, Some("Someone else"))); + assert_eq!( + state.note_mut(&id(5)).map(|note| note.clone()), + Some("My edit".into()), + "re-selecting the contact or another contact's reload keeps the edit" + ); + + state.select(&contact(6, Some("Theirs"))); + assert_eq!(state.selected(), Some(id(6))); + assert_eq!( + state.note_mut(&id(6)).map(|note| note.clone()), + Some("Theirs".into()) + ); + } + + #[test] + fn a_save_runs_once_until_its_result_lands() { + let mut state = ContactDetailState::default(); + state.select(&contact(5, None)); + *state.note_mut(&id(5)).expect("draft") = "Bao".into(); + + assert_eq!(state.begin_save(id(1), id(5)), Some(Some("Bao".into()))); + assert!(state.is_saving(&id(1), &id(5))); + assert_eq!( + state.begin_save(id(1), id(5)), + None, + "a second click must not pay for a second write" + ); + assert!(!state.is_saving(&id(2), &id(5)), "guards are per owner"); + + assert_eq!(state.finish_save(&id(1), &id(5)), Some(Some("Bao".into()))); + assert!(!state.is_saving(&id(1), &id(5))); + state.sync(&contact(5, Some("Bao"))); + assert!( + !state.is_dirty(&id(5)), + "the stored note is the draft's new starting point" + ); + } + + #[test] + fn a_failed_save_keeps_the_draft_and_can_be_retried() { + let mut state = ContactDetailState::default(); + state.select(&contact(5, None)); + *state.note_mut(&id(5)).expect("draft") = "Bao".into(); + assert!(state.begin_save(id(1), id(5)).is_some()); + + state.release_save(&id(1), &id(5)); + + assert!(!state.is_saving(&id(1), &id(5))); + assert!(state.is_dirty(&id(5)), "the unsaved edit stays"); + assert!(state.begin_save(id(1), id(5)).is_some()); + } + + #[test] + fn there_is_nothing_to_save_without_a_draft_for_that_contact() { + let mut state = ContactDetailState::default(); + assert_eq!(state.begin_save(id(1), id(5)), None); + state.select(&contact(6, None)); + assert_eq!(state.begin_save(id(1), id(5)), None); + } + + #[test] + fn reset_drops_the_selection_but_keeps_a_running_save() { + let mut state = ContactDetailState::default(); + state.select(&contact(5, None)); + *state.note_mut(&id(5)).expect("draft") = "Bao".into(); + assert!(state.begin_save(id(1), id(5)).is_some()); + + state.reset(); + + assert_eq!(state.selected(), None); + assert_eq!(state.note_mut(&id(5)), None); + assert!( + state.is_saving(&id(1), &id(5)), + "a paid write still running keeps its guard" + ); + assert_eq!(state.finish_save(&id(1), &id(5)), Some(Some("Bao".into()))); + } +} diff --git a/src/ui/state/contacts_view.rs b/src/ui/state/contacts_view.rs index 866e09650..13797bbfc 100644 --- a/src/ui/state/contacts_view.rs +++ b/src/ui/state/contacts_view.rs @@ -6,6 +6,7 @@ //! and paints it. Placement follows the DET module policy: non-widget UI state //! belongs in `ui/state/`. +use super::contact_detail_view::ContactDetailState; use crate::backend_task::dashpay::ContactData; use crate::model::dashpay::contact_request_recipient; use crate::model::identity_name::display_label as profile_display_label; @@ -73,6 +74,8 @@ pub struct ContactsState { in_flight: HashMap, /// The identity the lists belong to, once a renderer has bound them. owner: Option<(Network, Identifier)>, + /// The selected contact and its private-note editor. + detail: ContactDetailState, } impl ContactsState { @@ -96,6 +99,7 @@ impl ContactsState { self.hidden.clear(); self.show_hidden = false; self.search.clear(); + self.detail.reset(); let now = Instant::now(); self.in_flight.retain(|_, started| { now.saturating_duration_since(*started) < REQUEST_IN_FLIGHT_TIMEOUT @@ -184,12 +188,18 @@ impl ContactsState { /// Store the established-contact list from `DashPayTask::LoadContacts`, /// split into the visible contacts and the hidden ones. Hidden contacts stay /// out of the active list — that is what "hidden" promises — but remain - /// reachable through [`ContactsState::hidden_contacts`]. + /// reachable through [`ContactsState::hidden_contacts`]. The selected + /// contact's note draft follows the reloaded note. pub fn record_contacts(&mut self, contacts: Vec) { let (hidden, visible) = contacts.into_iter().partition(|c| c.is_hidden); self.contacts = visible; self.hidden = hidden; self.contacts_known = true; + if let Some(selected) = self.detail.selected() + && let Some(contact) = self.contacts.iter().find(|c| c.identity_id == selected) + { + self.detail.sync(contact); + } } /// Whether the established-contact list has been loaded for this identity. @@ -287,6 +297,60 @@ impl ContactsState { pub fn release_request(&mut self, request_id: &Identifier) { self.in_flight.remove(request_id); } + + /// The identity the lists belong to, once bound. + pub fn owner_id(&self) -> Option { + self.owner.map(|(_, id)| id) + } + + /// Select an active contact for the detail pane. A no-op for a contact + /// that is not listed. + pub fn select_contact(&mut self, contact_id: &Identifier) { + if let Some(contact) = self.contacts.iter().find(|c| c.identity_id == *contact_id) { + self.detail.select(contact); + } + } + + /// The selected contact, while it is still among the active contacts. + pub fn selected_contact(&self) -> Option<&ContactData> { + let selected = self.detail.selected()?; + self.contacts.iter().find(|c| c.identity_id == selected) + } + + /// The detail pane's state. + pub fn detail(&self) -> &ContactDetailState { + &self.detail + } + + /// Mutable detail-pane state, for the note editor. + pub fn detail_mut(&mut self) -> &mut ContactDetailState { + &mut self.detail + } + + /// Settle a confirmed note save. Returns whether one was running. The + /// listed contact shows the stored note right away when the lists belong to + /// `owner`, without waiting for the reload. + pub fn finish_note_save(&mut self, owner: &Identifier, contact_id: &Identifier) -> bool { + let Some(note) = self.detail.finish_save(owner, contact_id) else { + return false; + }; + if self.owner_id() == Some(*owner) + && let Some(contact) = self + .contacts + .iter_mut() + .chain(self.hidden.iter_mut()) + .find(|c| c.identity_id == *contact_id) + { + contact.note = note; + self.detail.sync(contact); + } + true + } + + /// Release a note save that failed or was abandoned. + pub fn release_note_save(&mut self, owner: &Identifier, contact_id: &Identifier) { + self.detail.release_save(owner, contact_id); + } } /// The handles a contact search matches against, borrowed from whichever contact @@ -403,6 +467,94 @@ mod tests { assert!(state.claim_load(), "reset must re-arm the load"); } + fn owned_state(owner: u8) -> ContactsState { + let identity = dash_sdk::dpp::identity::Identity::create_basic_identity( + id(owner), + dash_sdk::dpp::version::PlatformVersion::latest(), + ) + .expect("basic identity"); + ContactsState { + owner: Some((Network::Testnet, identity.id())), + ..Default::default() + } + } + + #[test] + fn the_selected_contact_follows_the_active_list() { + let mut state = ContactsState::default(); + state.record_contacts(vec![ContactData { + note: Some("Met at the meetup".into()), + ..contact(Some("Bao"), None, None) + }]); + assert!(state.selected_contact().is_none()); + + state.select_contact(&id(9)); + assert!( + state.selected_contact().is_none(), + "an unlisted contact is not selected" + ); + + state.select_contact(&id(7)); + assert_eq!( + state.selected_contact().and_then(|c| c.nickname.as_deref()), + Some("Bao") + ); + assert!(!state.detail().is_dirty(&id(7))); + + state.record_contacts(vec![ContactData { + is_hidden: true, + ..contact(Some("Bao"), None, None) + }]); + assert!( + state.selected_contact().is_none(), + "a contact that left the active list is no longer shown" + ); + + state.reset(); + state.record_contacts(vec![contact(Some("Bao"), None, None)]); + assert!( + state.selected_contact().is_none(), + "a tab entry starts unselected" + ); + } + + #[test] + fn a_confirmed_note_save_shows_the_stored_note_right_away() { + let mut state = owned_state(1); + state.record_contacts(vec![contact(Some("Bao"), None, None)]); + state.select_contact(&id(7)); + *state.detail_mut().note_mut(&id(7)).expect("draft") = "Met at the meetup".into(); + assert!(state.detail_mut().begin_save(id(1), id(7)).is_some()); + + assert!(state.finish_note_save(&id(1), &id(7))); + + assert_eq!( + state.selected_contact().and_then(|c| c.note.as_deref()), + Some("Met at the meetup") + ); + assert!(!state.detail().is_dirty(&id(7))); + assert!( + !state.finish_note_save(&id(1), &id(7)), + "a save settles only once" + ); + } + + #[test] + fn a_note_saved_for_another_identity_leaves_these_lists_alone() { + let mut state = owned_state(1); + state.record_contacts(vec![contact(Some("Bao"), None, None)]); + state.select_contact(&id(7)); + *state.detail_mut().note_mut(&id(7)).expect("draft") = "Theirs".into(); + assert!(state.detail_mut().begin_save(id(2), id(7)).is_some()); + + assert!(state.finish_note_save(&id(2), &id(7))); + + assert_eq!( + state.selected_contact().and_then(|c| c.note.as_deref()), + None + ); + } + #[test] fn reset_clears_guard_lists_and_search() { let mut state = ContactsState::default(); diff --git a/src/ui/state/mod.rs b/src/ui/state/mod.rs index 5486d2d57..3f1cd8ce5 100644 --- a/src/ui/state/mod.rs +++ b/src/ui/state/mod.rs @@ -8,6 +8,7 @@ pub mod account_summary; pub mod asset_lock_balance; pub mod avatar_cache; +pub mod contact_detail_view; pub mod contacts_view; pub mod derived_key_chooser; pub mod dpns_contests; diff --git a/tests/kittest/identity_hub_contact_detail.rs b/tests/kittest/identity_hub_contact_detail.rs new file mode 100644 index 000000000..bb57a12bc --- /dev/null +++ b/tests/kittest/identity_hub_contact_detail.rs @@ -0,0 +1,238 @@ +//! Contacts tab master–detail: selecting a contact shows its details and its +//! private note beside the list (under it on a narrow window), and Save note +//! dispatches one encrypted `contactInfo` write with the fee shown beforehand. +//! Nothing is signed or broadcast — dispatched tasks are only captured. + +use crate::identity_hub_layout::{ + EPSILON, HubHarness, assert_within_content, content_left, hub_for, seed_identity_with_usernames, +}; +use crate::support::{fresh_app_context, with_isolated_data_dir}; +use dash_evo_tool::app::AppAction; +use dash_evo_tool::backend_task::dashpay::{ContactData, DashPayTask}; +use dash_evo_tool::backend_task::{BackendTask, BackendTaskContext, BackendTaskSuccessResult}; +use dash_evo_tool::model::dashpay::ContactInfoField; +use dash_evo_tool::ui::ScreenLike; +use dash_evo_tool::ui::identity::IdentityHubTab; +use dash_evo_tool::ui::identity::contacts::{ + DETAIL_HEADING, NO_SELECTION, NOTE_HEADING, SAVE_NOTE_LABEL, SAVING_NOTE_LABEL, +}; +use dash_sdk::platform::Identifier; +use egui::accesskit::Role; +use egui_kittest::kittest::Queryable; + +const WIDE: f32 = 1280.0; +const NARROW: f32 = 900.0; +const CONTACT: [u8; 32] = [0xD8; 32]; + +fn bao(note: Option<&str>) -> ContactData { + ContactData { + identity_id: Identifier::from(CONTACT), + nickname: None, + note: note.map(str::to_string), + is_hidden: false, + account_reference: 0, + username: Some("bao".into()), + display_name: Some("Bao Nguyen".into()), + avatar_url: None, + bio: Some("Coffee and code.".into()), + } +} + +fn deliver(hub: &mut HubHarness, owner: Identifier, contact: ContactData) { + let app_context = hub.state().0.app_context.clone(); + let task = BackendTask::DashPayTask(Box::new(DashPayTask::LoadContacts { + identity: app_context.resolve_selected_identity().expect("identity"), + })); + hub.state_mut().0.display_backend_task_result( + &BackendTaskContext::from(&task), + BackendTaskSuccessResult::DashPayContactsWithInfo { + identity: owner, + contacts: vec![contact], + }, + ); +} + +/// The Contacts tab with Bao listed, then Bao selected. +fn hub_with_bao_selected( + app_context: &std::sync::Arc, + width: f32, + note: Option<&'static str>, +) -> (HubHarness, Identifier) { + let owner = seed_identity_with_usernames(app_context); + let mut hub = hub_for( + app_context, + owner, + width, + IdentityHubTab::Contacts, + move |hub, owner| deliver(hub, owner, bao(note)), + ); + hub.get_by_role_and_label(Role::Button, "Bao Nguyen") + .click(); + hub.run_steps(4); + (hub, owner) +} + +fn note_editor(hub: &HubHarness) -> egui_kittest::Node<'_> { + hub.get_by_role(Role::MultilineTextInput) +} + +/// The note writes the Save note click dispatched. +fn saved_notes(hub: &HubHarness) -> Vec<(Identifier, ContactInfoField>)> { + hub.state() + .1 + .iter() + .filter_map(|action| match action { + AppAction::BackendTask(BackendTask::DashPayTask(task)) => match task.as_ref() { + DashPayTask::UpdateContactInfo { + contact_id, update, .. + } => Some((*contact_id, update.note.clone())), + _ => None, + }, + _ => None, + }) + .collect() +} + +#[test] +fn selecting_a_contact_shows_its_details_beside_the_list() { + with_isolated_data_dir(|| { + let (_runtime, app_context) = fresh_app_context(); + let owner = seed_identity_with_usernames(&app_context); + let mut hub = hub_for( + &app_context, + owner, + WIDE, + IdentityHubTab::Contacts, + |hub, owner| deliver(hub, owner, bao(Some("Met at the meetup"))), + ); + assert!( + hub.query_by_label(NO_SELECTION).is_some(), + "the pane says how to fill it before a contact is chosen" + ); + assert!(hub.query_by_role(Role::MultilineTextInput).is_none()); + + hub.get_by_role_and_label(Role::Button, "Bao Nguyen") + .click(); + hub.run_steps(4); + + assert!(hub.query_by_label(NO_SELECTION).is_none()); + let heading = hub.get_by_label(DETAIL_HEADING).rect(); + let row = hub.get_by_role_and_label(Role::Button, "Bao Nguyen").rect(); + assert!( + heading.left() > row.right(), + "on a wide window the details sit beside the list: {heading:?} vs {row:?}" + ); + assert_within_content(&hub, "the contact detail pane", heading, WIDE); + + let in_pane = |label: &str| { + hub.query_all_by_label(label) + .any(|node| node.rect().left() >= heading.left() - EPSILON) + }; + for label in ["Bao Nguyen", "@bao", "Coffee and code.", NOTE_HEADING] { + assert!(in_pane(label), "the detail pane shows {label}"); + } + assert_eq!( + note_editor(&hub).value().as_deref(), + Some("Met at the meetup"), + "the stored note is loaded into the editor" + ); + let editor = note_editor(&hub).rect(); + assert_within_content(&hub, "the note editor", editor, WIDE); + assert!( + editor.left() >= heading.left() - 24.0, + "the note editor belongs to the pane, not the list" + ); + }); +} + +#[test] +fn save_note_shows_the_fee_first_and_sends_the_note_once() { + with_isolated_data_dir(|| { + let (_runtime, app_context) = fresh_app_context(); + let (mut hub, owner) = hub_with_bao_selected(&app_context, WIDE, None); + + assert!( + hub.query_by_label_contains("Saving this note costs about") + .is_some(), + "the fee is shown before the user saves" + ); + hub.get_by_role_and_label(Role::Button, SAVE_NOTE_LABEL) + .click(); + hub.run_steps(2); + assert!( + saved_notes(&hub).is_empty(), + "an unchanged note has nothing to save" + ); + + note_editor(&hub).focus(); + hub.run(); + note_editor(&hub).type_text("Met at the meetup"); + hub.run(); + hub.get_by_role_and_label(Role::Button, SAVE_NOTE_LABEL) + .click(); + hub.run_steps(2); + + assert_eq!( + saved_notes(&hub), + [( + Identifier::from(CONTACT), + ContactInfoField::Replace(Some("Met at the meetup".into())) + )], + "Save note dispatches one write of the typed note for that contact" + ); + hub.get_by_role_and_label(Role::Button, SAVING_NOTE_LABEL) + .click(); + hub.run_steps(2); + assert_eq!( + saved_notes(&hub).len(), + 1, + "a click while the paid write runs buys nothing" + ); + + hub.state_mut().0.display_task_result( + BackendTaskSuccessResult::DashPayContactInfoUpdated { + identity: owner, + contact_id: Identifier::from(CONTACT), + }, + ); + hub.run_steps(4); + + hub.get_by_role_and_label(Role::Button, SAVE_NOTE_LABEL) + .click(); + hub.run_steps(2); + assert_eq!( + saved_notes(&hub).len(), + 1, + "the saved note is not offered for saving again" + ); + assert_eq!( + note_editor(&hub).value().as_deref(), + Some("Met at the meetup") + ); + }); +} + +#[test] +fn a_narrow_window_stacks_the_details_under_the_contact() { + with_isolated_data_dir(|| { + let (_runtime, app_context) = fresh_app_context(); + let (hub, _) = hub_with_bao_selected(&app_context, NARROW, Some("Met at the meetup")); + assert!( + NARROW - content_left(&hub) < 760.0, + "the tab must have less than 760 pt for this case" + ); + + let row = hub.get_by_role_and_label(Role::Button, "Bao Nguyen").rect(); + let heading = hub.get_by_label(DETAIL_HEADING).rect(); + assert!( + heading.top() > row.bottom(), + "on a narrow window the details stack under the contact: {heading:?} vs {row:?}" + ); + for rect in [heading, note_editor(&hub).rect()] { + assert!( + rect.right() <= NARROW + EPSILON, + "the pane stays inside the window: {rect:?}" + ); + } + }); +} diff --git a/tests/kittest/identity_hub_contacts.rs b/tests/kittest/identity_hub_contacts.rs index 37f0a0d43..dacd40c7b 100644 --- a/tests/kittest/identity_hub_contacts.rs +++ b/tests/kittest/identity_hub_contacts.rs @@ -139,6 +139,8 @@ fn contacts_tab_follows_an_identity_selected_outside_the_hub() { render_context.resolve_selected_identity().as_ref(), &mut state.0, &mut state.1, + &mut Default::default(), + &mut Vec::new(), ); }, (ContactsState::default(), profiles), diff --git a/tests/kittest/identity_hub_layout.rs b/tests/kittest/identity_hub_layout.rs index 255c283b4..7d490b51c 100644 --- a/tests/kittest/identity_hub_layout.rs +++ b/tests/kittest/identity_hub_layout.rs @@ -32,9 +32,9 @@ use std::sync::Arc; const WIDTHS: [f32; 2] = [1280.0, 2000.0]; /// Slack for rounding and stroke widths when comparing edges. -const EPSILON: f32 = 2.0; +pub(crate) const EPSILON: f32 = 2.0; -type HubHarness = Harness<'static, (IdentityHubScreen, Vec)>; +pub(crate) type HubHarness = Harness<'static, (IdentityHubScreen, Vec)>; fn mount_hub(app_context: &Arc, width: f32) -> HubHarness { Harness::builder() @@ -51,7 +51,7 @@ fn mount_hub(app_context: &Arc, width: f32) -> HubHarness { } /// Seeds and selects a user identity that owns two usernames. -fn seed_identity_with_usernames(app_context: &Arc) -> Identifier { +pub(crate) fn seed_identity_with_usernames(app_context: &Arc) -> Identifier { seed_identity_named(app_context, &["alex", "alexander"]) } @@ -180,7 +180,7 @@ fn hub_on(app_context: &Arc, width: f32, tab: IdentityHubTab) -> Hub }) } -fn hub_for( +pub(crate) fn hub_for( app_context: &Arc, owner: Identifier, width: f32, @@ -197,11 +197,11 @@ fn hub_for( } /// The tab bar's left edge, where every tab's content starts. -fn content_left(hub: &HubHarness) -> f32 { +pub(crate) fn content_left(hub: &HubHarness) -> f32 { hub.get_by_label("Home").rect().left() } -fn assert_within_content(hub: &HubHarness, what: &str, rect: egui::Rect, width: f32) { +pub(crate) fn assert_within_content(hub: &HubHarness, what: &str, rect: egui::Rect, width: f32) { let limit = content_left(hub) + HUB_CONTENT_MAX_WIDTH + EPSILON; assert!( rect.right() <= limit, @@ -303,10 +303,8 @@ fn contacts_sections_start_at_the_content_edge_with_one_add_button() { "at {width} px, Add by username is offered once when there are contacts" ); - let view_profile = hub - .get_by_label(dash_evo_tool::ui::identity::contacts::VIEW_PROFILE_LABEL) - .rect(); - assert_within_content(&hub, "a contact's View Profile button", view_profile, width); + let contact = hub.get_by_role_and_label(Role::Button, "Bao").rect(); + assert_within_content(&hub, "a contact's row", contact, width); }); } } @@ -392,10 +390,10 @@ fn the_longest_username_stays_within_the_usernames_card() { } } -/// A long nickname and the longest username never push a contact's actions -/// past the content column. +/// A long nickname and the longest username are shortened to the contact +/// list's column instead of running under the detail pane beside it. #[test] -fn long_contact_names_stay_within_the_content_width() { +fn long_contact_names_stay_within_the_contact_list() { for width in WIDTHS { with_isolated_data_dir(|| { let (_runtime, app_context) = fresh_app_context(); @@ -408,38 +406,26 @@ fn long_contact_names_stay_within_the_content_width() { IdentityHubTab::Contacts, |hub, owner| deliver_contact_named(hub, owner, &nickname, Some(longest_username())), ); - let view_profile = hub - .get_by_label(dash_evo_tool::ui::identity::contacts::VIEW_PROFILE_LABEL) + let pane = hub + .get_by_label(dash_evo_tool::ui::identity::contacts::DETAIL_HEADING) .rect(); - assert_within_content(&hub, "a contact's View Profile button", view_profile, width); - assert!( - view_profile.left() >= content_left(&hub), - "at {width} px, View Profile stays on screen ({view_profile:?})" - ); + assert_within_content(&hub, "the contact detail pane", pane, width); - // The name and the handle are shortened to the room the actions - // leave, so neither runs under a button. - let actions: Vec = hub - .query_all_by_role(Role::Button) - .map(|node| node.rect()) - .filter(|rect| { - rect.top() >= view_profile.top() - 30.0 - && rect.bottom() <= view_profile.bottom() + 30.0 - }) - .collect(); for text in ["WWWW", "@www"] { let text_rect = hub .query_all_by_label_contains(text) .map(|node| node.rect()) - .find(|rect| rect.top() >= view_profile.top() - 30.0) + .find(|rect| rect.top() > hub.get_by_label("Home").rect().bottom()) .unwrap_or_else(|| panic!("the contact row shows {text}")); - for action in &actions { - assert!( - !text_rect.intersects(*action), - "at {width} px, {text}… ({text_rect:?}) runs under an action \ - ({action:?})" - ); - } + assert!( + text_rect.left() >= content_left(&hub), + "at {width} px, {text}… stays on screen ({text_rect:?})" + ); + assert!( + text_rect.right() <= pane.left(), + "at {width} px, {text}… ({text_rect:?}) runs under the detail pane \ + ({pane:?})" + ); } }); } diff --git a/tests/kittest/main.rs b/tests/kittest/main.rs index 9c172c5a4..42b6b6986 100644 --- a/tests/kittest/main.rs +++ b/tests/kittest/main.rs @@ -9,6 +9,7 @@ mod global_nav_switcher; mod identity_home; mod identity_hub; mod identity_hub_activity; +mod identity_hub_contact_detail; mod identity_hub_contacts; mod identity_hub_layout; mod identity_hub_onboarding; From 861c047fea0369b32ba1dd7297a15f44f7d1796a Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 16 Oct 2026 19:02:28 +0000 Subject: [PATCH 11/73] fix(identity): keep the contact pane's spacing and align usernames in the list In the two-column Contacts layout, the 24 pt gap between the columns was also applied to every row inside them. This pushed the contact's name in the detail pane 16 pt further from its picture than it sits in the narrow layout, and widened the gaps between the buttons in the sections. Each column now goes back to the normal spacing. In the contact list, the @username under a name started at the button's edge, not at the name text inside the button, so the two lines did not line up. The username now lines up with the name. Found in a visual check on testnet. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_012YneRVSNLhVnGiedWDr3fw --- src/ui/identity/contacts.rs | 20 ++++++--- tests/kittest/identity_hub_contact_detail.rs | 47 ++++++++++++++++++++ 2 files changed, 62 insertions(+), 5 deletions(-) diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index 91d795a6d..fc23b48d2 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -500,6 +500,8 @@ fn render_populated( let content_width = ui.available_width() - Spacing::LG; let list_width = content_width * LIST_SHARE; let detail_width = content_width - list_width; + // The column gap applies between the columns only, not inside them. + let item_spacing = ui.spacing().item_spacing; ui.horizontal_top(|ui| { ui.spacing_mut().item_spacing.x = Spacing::LG; let height = ui.available_height(); @@ -507,6 +509,7 @@ fn render_populated( eframe::egui::vec2(list_width, height), eframe::egui::Layout::top_down(eframe::egui::Align::Min), |ui| { + ui.spacing_mut().item_spacing = item_spacing; ui.set_width(list_width); eframe::egui::ScrollArea::vertical() .id_salt("identity_hub_contacts_list") @@ -522,6 +525,7 @@ fn render_populated( eframe::egui::vec2(detail_width, height), eframe::egui::Layout::top_down(eframe::egui::Align::Min), |ui| { + ui.spacing_mut().item_spacing = item_spacing; ui.set_width(detail_width); eframe::egui::ScrollArea::vertical() .id_salt("identity_hub_contact_detail") @@ -836,11 +840,17 @@ fn active_section( clicked_contact = Some(contact.identity_id); } if let Some(handle) = contact_handle(contact, &label) { - ui.label( - RichText::new(handle) - .small() - .color(DashColors::text_secondary(dark_mode)), - ); + // Line the handle up with the name, which the + // row button insets by its padding. + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + ui.add_space(ui.spacing().button_padding.x); + ui.label( + RichText::new(handle) + .small() + .color(DashColors::text_secondary(dark_mode)), + ); + }); } }); }, diff --git a/tests/kittest/identity_hub_contact_detail.rs b/tests/kittest/identity_hub_contact_detail.rs index bb57a12bc..f9d45cee7 100644 --- a/tests/kittest/identity_hub_contact_detail.rs +++ b/tests/kittest/identity_hub_contact_detail.rs @@ -236,3 +236,50 @@ fn a_narrow_window_stacks_the_details_under_the_contact() { } }); } + +/// The pane is laid out the same in both layouts: the two-column split must not +/// leak its column gap into the spacing inside the columns. +#[test] +fn the_detail_pane_keeps_its_spacing_in_both_layouts() { + let name_offset = |width: f32| { + with_isolated_data_dir(|| { + let (_runtime, app_context) = fresh_app_context(); + let (hub, _) = hub_with_bao_selected(&app_context, width, None); + let heading = hub.get_by_label(DETAIL_HEADING).rect(); + let name = hub + .query_all_by_label("Bao Nguyen") + .map(|node| node.rect()) + .find(|rect| rect.top() > heading.bottom() && rect.left() > heading.left()) + .expect("the pane shows the contact's name"); + name.left() - heading.left() + }) + }; + let (wide, narrow) = (name_offset(WIDE), name_offset(NARROW)); + assert!( + (wide - narrow).abs() <= EPSILON, + "the name sits {wide} pt into the pane on a wide window but {narrow} pt on a narrow one" + ); +} + +/// A contact's @username lines up with its name, which starts after the +/// selectable row's padding. +#[test] +fn a_contacts_username_lines_up_with_its_name() { + with_isolated_data_dir(|| { + let (_runtime, app_context) = fresh_app_context(); + let (hub, _) = hub_with_bao_selected(&app_context, WIDE, None); + let row = hub.get_by_role_and_label(Role::Button, "Bao Nguyen").rect(); + let handle = hub + .query_all_by_label("@bao") + .map(|node| node.rect()) + .find(|rect| rect.left() < row.right()) + .expect("the row shows the username"); + let padding = hub.ctx.global_style().spacing.button_padding.x; + assert!( + (handle.left() - (row.left() + padding)).abs() <= EPSILON, + "the username starts at {} but the name text at {}", + handle.left(), + row.left() + padding + ); + }); +} From c699370883706667774968d68c84d370a9378f5c Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 16 Oct 2026 20:00:24 +0000 Subject: [PATCH 12/73] fix(identity): settle contact details writes the hub cannot see - Route DashPayContactInfoUpdated and DashPayContactInfoActionFailed to the hidden Identity Hub, so a note save or unhide that finishes behind another screen releases its guard and still asks before overwriting unreadable details. - Run one contactInfo write per owner and contact: a note save waits for a running unhide and vice versa, so a result can no longer settle the wrong write. - The migration gate names the owner and contact of a refused UpdateContactInfo, so the hub releases exactly that write's guard. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012YneRVSNLhVnGiedWDr3fw --- src/app.rs | 4 + src/backend_task/mod.rs | 67 ++++++++- src/ui/identity/contacts.rs | 108 ++++++++++++-- src/ui/identity/hub_screen.rs | 56 ++++--- src/ui/state/contact_detail_view.rs | 108 +++++++++----- src/ui/state/contacts_view.rs | 32 ++-- tests/kittest/identity_hub.rs | 27 +++- tests/kittest/identity_hub_contact_detail.rs | 149 +++++++++++++++++++ 8 files changed, 456 insertions(+), 95 deletions(-) diff --git a/src/app.rs b/src/app.rs index 37271d99e..7a38cef56 100644 --- a/src/app.rs +++ b/src/app.rs @@ -2805,6 +2805,9 @@ impl AppState { BackendTaskSuccessResult::DashPayPaymentHistory(_) | BackendTaskSuccessResult::DashPayContactsWithInfo { .. } | BackendTaskSuccessResult::DashPayContactRequests { .. } => true, + // A contact details write the hub dispatched holds a guard and + // a pending task there until its outcome arrives. + BackendTaskSuccessResult::DashPayContactInfoUpdated { .. } => true, BackendTaskSuccessResult::DashPayAvatar { url, .. } => { hub.is_waiting_for_avatar(url) } @@ -2832,6 +2835,7 @@ impl AppState { { hub.display_backend_task_error(context, error); hub.handle_contact_request_error(error); + hub.handle_contact_info_error(error); } } diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index e4eb9b11f..82284a873 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -217,6 +217,23 @@ pub(crate) fn dashpay_request_id(task: &BackendTask) -> Option { } } +/// The owner and contact a direct contact details write acts on. The migration +/// gate names them in its refusal so the Identity Hub releases only that +/// write's guard. +fn dashpay_contact_info_target(task: &BackendTask) -> Option<(Identifier, Identifier)> { + match task { + BackendTask::DashPayTask(task) => match task.as_ref() { + DashPayTask::UpdateContactInfo { + identity, + contact_id, + .. + } => Some((identity.identity.id(), *contact_id)), + _ => None, + }, + _ => None, + } +} + /// The identity-load record `task` was dispatched under, when its caller marked /// the load `Submitted` and is gating on it. `None` for every other task, and for /// a load whose caller gates on nothing. @@ -1330,11 +1347,19 @@ impl AppContext { task = ?task, "Short-circuiting wallet-touching task — migration in progress", ); - // A guarded DashPay contact action carries its request ID so the - // Identity Hub releases only that request's in-flight guard, not every - // contact action's. Every other wallet-touching task names none and - // keeps the bare variant. Both surface the same user-facing banner — - // `DashPayContactRequestActionFailed` forwards its source's `Display`. + // A guarded DashPay contact action carries its request ID, and a + // contact details write its owner and contact, so the Identity Hub + // releases only that action's in-flight guard. Every other + // wallet-touching task names none and keeps the bare variant. All + // surface the same user-facing banner — both envelopes forward their + // source's `Display`. + if let Some((identity_id, contact_id)) = dashpay_contact_info_target(&task) { + return Err(TaskError::DashPayContactInfoActionFailed { + identity_id, + contact_id, + source: Box::new(TaskError::WalletStorageNotReady), + }); + } return match dashpay_request_id(&task) { Some(request_id) => Err(TaskError::DashPayContactRequestActionFailed { request_id, @@ -2447,8 +2472,9 @@ mod tests { /// End-to-end: the migration gate wraps a rejected DashPay contact action in /// `DashPayContactRequestActionFailed` carrying its request ID (so the Hub - /// un-sticks only that row), while a non-contact wallet-touching task keeps - /// the bare `WalletStorageNotReady`. + /// un-sticks only that row), and a rejected contact details write in + /// `DashPayContactInfoActionFailed` naming its owner and contact, while a + /// non-contact wallet-touching task keeps the bare `WalletStorageNotReady`. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn gate_rejection_wraps_a_contact_action_but_not_other_tasks() { use crate::backend_task::dashpay::DashPayTask; @@ -2483,6 +2509,33 @@ mod tests { "a gate-rejected contact action must name its request: {contact_result:?}" ); + // A contact's details write names its owner and contact, so the hub + // releases only that write's guard. + let contact_id = Identifier::from([0x33; 32]); + let owner = qualified_identity(9); + let owner_id = owner.identity.id(); + let (tx, _rx) = tokio::sync::mpsc::channel::(32); + let note_result = ctx + .run_backend_task( + BackendTask::DashPayTask(Box::new(DashPayTask::UpdateContactInfo { + identity: owner, + contact_id, + update: crate::model::dashpay::ContactInfoUpdate::note(None, false), + })), + SenderAsync::new(tx, ctx.egui_ctx().clone()), + ) + .await; + assert!( + matches!( + ¬e_result, + Err(TaskError::DashPayContactInfoActionFailed { identity_id, contact_id: c, source }) + if *identity_id == owner_id + && *c == contact_id + && matches!(source.as_ref(), TaskError::WalletStorageNotReady) + ), + "a gate-rejected contact details write must name its owner and contact: {note_result:?}" + ); + let (tx, _rx) = tokio::sync::mpsc::channel::(32); let search_result = ctx .run_backend_task( diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index fc23b48d2..3adca6961 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -62,7 +62,7 @@ pub const SAVING_NOTE_LABEL: &str = "Saving…"; pub const NOTE_UNCHANGED_TOOLTIP: &str = "There are no changes to save."; pub const NOTE_SAVE_TOOLTIP: &str = "Save this note on Dash Platform. Saving costs a small fee."; pub const NOTE_SAVED: &str = "Your note is saved."; -const NOTE_SAVING_TOOLTIP: &str = "Your note is being saved."; +const NOTE_SAVING_TOOLTIP: &str = "This contact's details are being saved."; pub const RECEIVED_HEADING: &str = "Received requests"; pub const ACTIVE_HEADING_PREFIX: &str = "Active contacts"; pub const SENT_HEADING: &str = "Sent requests"; @@ -334,6 +334,28 @@ fn dispatch_note_save(state: &mut ContactsState, identity: &QualifiedIdentity) - )))) } +/// Dispatch the unhide of `contact`. Unhiding rewrites the contact's whole +/// `contactInfo`, so it waits for any other write to that contact to finish. +fn dispatch_unhide( + state: &mut ContactsState, + identity: &QualifiedIdentity, + contact: &ContactData, +) -> AppAction { + if !state + .detail_mut() + .begin_visibility_write(identity.identity.id(), contact.identity_id) + { + return AppAction::None; + } + // Move the row now; the authoritative reload lands when the broadcast + // confirms. + state.unhide_contact(&contact.identity_id); + AppAction::BackendTask(BackendTask::DashPayTask(Box::new(unhide_task( + identity.clone(), + contact, + )))) +} + /// Public entry point invoked by `hub_screen` when the Contacts tab is active. /// /// Resolves the "current" identity as the app-scoped active identity. When no @@ -675,7 +697,7 @@ fn note_editor( let contact_id = contact.identity_id; let saving = state .detail() - .is_saving(&identity.identity.id(), &contact_id); + .is_writing(&identity.identity.id(), &contact_id); let detail = state.detail_mut(); let Some(note) = detail.note_mut(&contact_id) else { return false; @@ -924,7 +946,10 @@ fn hidden_section( // The clicked contact is cloned out of the list so the unhide can mutate // `state` once the read borrow the row loop holds has ended. let mut clicked: Option = None; + let owner = identity.identity.id(); for contact in state.hidden_contacts() { + // A write to this contact is still running; the unhide waits for it. + let busy = state.detail().is_writing(&owner, &contact.identity_id); // Unhide is laid out first so a long name is shortened to the room it // leaves instead of pushing the button past the content column. eframe::egui::Sides::new().shrink_left().truncate().show( @@ -937,7 +962,10 @@ fn hidden_section( }, |ui| { let unhide = ui - .add(ComponentStyles::secondary_button(UNHIDE_LABEL, dark_mode)) + .add_enabled( + !busy, + ComponentStyles::secondary_button(UNHIDE_LABEL, dark_mode), + ) .clickable_tooltip(UNHIDE_TOOLTIP); if unhide.clicked() { clicked = Some(contact.clone()); @@ -948,13 +976,7 @@ fn hidden_section( } if let Some(contact) = clicked { - // Move the row now; the authoritative reload lands when the broadcast - // confirms. - state.unhide_contact(&contact.identity_id); - action = AppAction::BackendTask(BackendTask::DashPayTask(Box::new(unhide_task( - identity.clone(), - &contact, - )))); + action = dispatch_unhide(state, identity, &contact); } action @@ -1426,7 +1448,7 @@ mod tests { update.note, crate::model::dashpay::ContactInfoField::Replace(Some("Met at the meetup".into())) ); - assert!(state.detail().is_saving(&id(1), &id(5))); + assert!(state.detail().is_writing(&id(1), &id(5))); assert_eq!( dispatch_note_save(&mut state, &identity), AppAction::None, @@ -1455,7 +1477,7 @@ mod tests { *state.detail_mut().note_mut(&id(5)).expect("draft") = "a".repeat(256); assert_eq!(dispatch_note_save(&mut state, &identity), AppAction::None); - assert!(!state.detail().is_saving(&id(1), &id(5))); + assert!(!state.detail().is_writing(&id(1), &id(5))); let mut unselected = ContactsState::default(); unselected.reconcile_owner(&identity); @@ -1465,6 +1487,68 @@ mod tests { ); } + fn hidden_bao() -> ContactData { + ContactData { + is_hidden: true, + ..contact_with_note(None) + } + } + + /// An unhide and a note save both rewrite the same contactInfo document, + /// so they run one at a time: the second would otherwise race the first + /// and the hub could not tell which write a result settles. + #[test] + fn a_note_save_waits_for_a_running_unhide_of_that_contact() { + let identity = qualified_identity(id(1)); + let mut state = ContactsState::default(); + state.reconcile_owner(&identity); + state.record_contacts(vec![hidden_bao()]); + + let (_, contact_id, update) = + saved_note(dispatch_unhide(&mut state, &identity, &hidden_bao())); + assert_eq!(contact_id, id(5)); + assert!(!update.display_hidden); + assert_eq!( + dispatch_unhide(&mut state, &identity, &hidden_bao()), + AppAction::None, + "a second unhide must not pay for a second write" + ); + + state.select_contact(&id(5)); + *state.detail_mut().note_mut(&id(5)).expect("draft") = "Bao".into(); + assert_eq!( + dispatch_note_save(&mut state, &identity), + AppAction::None, + "the note save must wait for the unhide" + ); + + assert!(state.finish_contact_info_write(&id(1), &id(5))); + assert_eq!( + state.selected_contact().and_then(|c| c.note.as_deref()), + None, + "an unhide stores no note" + ); + assert_ne!(dispatch_note_save(&mut state, &identity), AppAction::None); + } + + #[test] + fn an_unhide_waits_for_a_running_note_save_of_that_contact() { + let identity = qualified_identity(id(1)); + let mut state = state_with_selected_contact(&identity, None); + *state.detail_mut().note_mut(&id(5)).expect("draft") = "Bao".into(); + assert_ne!(dispatch_note_save(&mut state, &identity), AppAction::None); + + assert_eq!( + dispatch_unhide(&mut state, &identity, &hidden_bao()), + AppAction::None + ); + state.release_contact_info_write(&id(1), &id(5)); + assert_ne!( + dispatch_unhide(&mut state, &identity, &hidden_bao()), + AppAction::None + ); + } + #[test] fn the_fee_line_is_one_sentence_with_the_amount() { assert_eq!( diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index b46043ce7..506ecf7c9 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -394,6 +394,27 @@ impl IdentityHubScreen { true } + /// Settle a failed direct contact details write: ask before overwriting + /// unreadable details, otherwise drop the pending write and release its + /// guard. Returns whether the hub took over telling the user. + pub(crate) fn handle_contact_info_error(&mut self, error: &TaskError) -> bool { + if !matches!(error, TaskError::DashPayContactInfoActionFailed { .. }) { + return false; + } + if let Some(key) = contact_info_read_error_key(error) + && self.pending_contact_info_tasks.contains_key(&key) + { + self.contacts_state.invalidate(); + self.queue_contact_info_confirmation(key); + return true; + } + if let Some(key) = contact_info_error_key(error) { + self.pending_contact_info_tasks.remove(&key); + } + release_contact_info_write_for_error(&mut self.contacts_state, error); + false + } + /// Show all User identities, clearing the selected wallet filter. pub(crate) fn open_picker(&mut self) { self.app_context.set_selected_hd_wallet(None); @@ -823,7 +844,8 @@ impl ScreenLike for IdentityHubScreen { identity_id: *identity, contact_id: *contact_id, }; - self.contacts_state.finish_note_save(identity, contact_id); + self.contacts_state + .finish_contact_info_write(identity, contact_id); if let Some(task) = self.pending_contact_info_tasks.remove(&key) { self.contacts_state.invalidate(); MessageBanner::set_global( @@ -897,19 +919,10 @@ impl ScreenLike for IdentityHubScreen { Some(key) if self.pending_contact_info_tasks.contains_key(&key) ); } - if let Some(key) = contact_info_read_error_key(error) - && self.pending_contact_info_tasks.contains_key(&key) - { - self.contacts_state.invalidate(); - self.queue_contact_info_confirmation(key); + if self.handle_contact_info_error(error) { return true; } - - if let Some(key) = contact_info_error_key(error) { - self.pending_contact_info_tasks.remove(&key); - } release_request_guard_for_error(&mut self.contacts_state, error); - release_note_save_for_error(&mut self.contacts_state, error); // Let AppState render the default error banner — the hub has no // other special-case error handling of its own yet. @@ -929,15 +942,18 @@ fn release_request_guard_for_error(state: &mut super::contacts::ContactsState, e } } -/// Release the note-save guard a failed direct contactInfo write names. -fn release_note_save_for_error(state: &mut super::contacts::ContactsState, error: &TaskError) { +/// Release the write guard a failed direct contactInfo write names. +fn release_contact_info_write_for_error( + state: &mut super::contacts::ContactsState, + error: &TaskError, +) { if let TaskError::DashPayContactInfoActionFailed { identity_id, contact_id, .. } = error { - state.release_note_save(identity_id, contact_id); + state.release_contact_info_write(identity_id, contact_id); } } @@ -953,7 +969,7 @@ fn release_guards_for_abandoned_confirmations<'a>( ContactInfoTaskKey::Direct { identity_id, contact_id, - } => state.release_note_save(identity_id, contact_id), + } => state.release_contact_info_write(identity_id, contact_id), } } } @@ -2196,7 +2212,7 @@ mod tests { }], ); - assert!(!state.detail().is_saving(&id(3), &id(4))); + assert!(!state.detail().is_writing(&id(3), &id(4))); assert!(state.is_in_flight(&id(2)), "unrelated request guards stay"); } @@ -2218,10 +2234,10 @@ mod tests { *state.detail_mut().note_mut(&id(4)).expect("draft") = "Bao".into(); assert!(state.detail_mut().begin_save(id(3), id(4)).is_some()); - release_note_save_for_error(&mut state, &TaskError::WalletLocked); - assert!(state.detail().is_saving(&id(3), &id(4))); + release_contact_info_write_for_error(&mut state, &TaskError::WalletLocked); + assert!(state.detail().is_writing(&id(3), &id(4))); - release_note_save_for_error( + release_contact_info_write_for_error( &mut state, &TaskError::DashPayContactInfoActionFailed { identity_id: id(3), @@ -2229,7 +2245,7 @@ mod tests { source: Box::new(TaskError::WalletLocked), }, ); - assert!(!state.detail().is_saving(&id(3), &id(4))); + assert!(!state.detail().is_writing(&id(3), &id(4))); } #[test] diff --git a/src/ui/state/contact_detail_view.rs b/src/ui/state/contact_detail_view.rs index f3467ac62..73f03fdc2 100644 --- a/src/ui/state/contact_detail_view.rs +++ b/src/ui/state/contact_detail_view.rs @@ -1,15 +1,26 @@ //! Detail-pane state for the Identities hub's Contacts tab: which contact is -//! selected, the private note being edited for it, and the note saves still -//! running. Renders nothing — [`crate::ui::identity::contacts`] paints it. +//! selected, the private note being edited for it, and the contact details +//! writes still running. Renders nothing — [`crate::ui::identity::contacts`] +//! paints it. use crate::backend_task::dashpay::ContactData; use dash_sdk::platform::Identifier; use std::collections::HashMap; use std::time::{Duration, Instant}; -/// Age after which a note save that never reported back stops blocking the -/// Save button, pruned on the next view reset. -const NOTE_SAVE_TIMEOUT: Duration = Duration::from_secs(5 * 60); +/// Age after which a contact details write that never reported back stops +/// blocking the next one, pruned on the next view reset. +const WRITE_TIMEOUT: Duration = Duration::from_secs(5 * 60); + +/// A contact details write still running. Each rewrites the contact's whole +/// `contactInfo` document, so a contact has at most one at a time. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PendingWrite { + /// A private-note save, with the note that was sent. + Note(Option), + /// An unhide. + Visibility, +} /// The note being edited for one contact, and the stored note it started from. #[derive(Debug, Clone)] @@ -24,10 +35,10 @@ struct NoteDraft { pub struct ContactDetailState { selected: Option, draft: Option, - /// Note saves still running, keyed by owner identity and contact, with the - /// note that was sent. Each save is a paid write, so the Save button stays - /// disabled until its result lands. - saving: HashMap<(Identifier, Identifier), (Option, Instant)>, + /// Contact details writes still running, keyed by owner identity and + /// contact. Each is paid for, so the next write to that contact waits until + /// its result lands. + writes: HashMap<(Identifier, Identifier), (PendingWrite, Instant)>, } /// The note as it is stored: surrounding whitespace dropped, and an empty note @@ -74,8 +85,8 @@ impl ContactDetailState { self.selected = None; self.draft = None; let now = Instant::now(); - self.saving - .retain(|_, (_, started)| now.saturating_duration_since(*started) < NOTE_SAVE_TIMEOUT); + self.writes + .retain(|_, (_, started)| now.saturating_duration_since(*started) < WRITE_TIMEOUT); } /// Follow a fresh copy of the selected contact. The draft restarts from the @@ -124,8 +135,8 @@ impl ContactDetailState { self.draft_for(contact_id).is_some_and(NoteDraft::is_dirty) } - /// Claim the save slot for `owner`'s note on `contact_id`. Returns the note - /// to send, or `None` when there is no draft for that contact or a save for + /// Claim the write slot for `owner`'s note on `contact_id`. Returns the note + /// to send, or `None` when there is no draft for that contact or a write to /// it is already running. pub fn begin_save( &mut self, @@ -133,34 +144,51 @@ impl ContactDetailState { contact_id: Identifier, ) -> Option> { let draft = self.draft_for(&contact_id)?; + let note = normalized_note(&draft.text); + self.begin_write(owner, contact_id, PendingWrite::Note(note.clone())) + .then_some(note) + } + + /// Claim the write slot for unhiding `contact_id`. `false` when a write to + /// that contact is already running. + #[must_use] + pub fn begin_visibility_write(&mut self, owner: Identifier, contact_id: Identifier) -> bool { + self.begin_write(owner, contact_id, PendingWrite::Visibility) + } + + fn begin_write( + &mut self, + owner: Identifier, + contact_id: Identifier, + write: PendingWrite, + ) -> bool { let key = (owner, contact_id); - if self.saving.contains_key(&key) { - return None; + if self.writes.contains_key(&key) { + return false; } - let note = normalized_note(&draft.text); - self.saving.insert(key, (note.clone(), Instant::now())); - Some(note) + self.writes.insert(key, (write, Instant::now())); + true } - /// Whether a note save for `owner` and `contact_id` is running. - pub fn is_saving(&self, owner: &Identifier, contact_id: &Identifier) -> bool { - self.saving.contains_key(&(*owner, *contact_id)) + /// Whether a contact details write for `owner` and `contact_id` is running. + pub fn is_writing(&self, owner: &Identifier, contact_id: &Identifier) -> bool { + self.writes.contains_key(&(*owner, *contact_id)) } - /// Release a confirmed save and return the note it stored. - pub fn finish_save( + /// Release a confirmed write and return what it was. + pub fn finish_write( &mut self, owner: &Identifier, contact_id: &Identifier, - ) -> Option> { - self.saving + ) -> Option { + self.writes .remove(&(*owner, *contact_id)) - .map(|(note, _)| note) + .map(|(write, _)| write) } - /// Release a save that failed or was abandoned; the draft is kept. - pub fn release_save(&mut self, owner: &Identifier, contact_id: &Identifier) { - self.saving.remove(&(*owner, *contact_id)); + /// Release a write that failed or was abandoned; the draft is kept. + pub fn release_write(&mut self, owner: &Identifier, contact_id: &Identifier) { + self.writes.remove(&(*owner, *contact_id)); } } @@ -277,16 +305,19 @@ mod tests { *state.note_mut(&id(5)).expect("draft") = "Bao".into(); assert_eq!(state.begin_save(id(1), id(5)), Some(Some("Bao".into()))); - assert!(state.is_saving(&id(1), &id(5))); + assert!(state.is_writing(&id(1), &id(5))); assert_eq!( state.begin_save(id(1), id(5)), None, "a second click must not pay for a second write" ); - assert!(!state.is_saving(&id(2), &id(5)), "guards are per owner"); + assert!(!state.is_writing(&id(2), &id(5)), "guards are per owner"); - assert_eq!(state.finish_save(&id(1), &id(5)), Some(Some("Bao".into()))); - assert!(!state.is_saving(&id(1), &id(5))); + assert_eq!( + state.finish_write(&id(1), &id(5)), + Some(PendingWrite::Note(Some("Bao".into()))) + ); + assert!(!state.is_writing(&id(1), &id(5))); state.sync(&contact(5, Some("Bao"))); assert!( !state.is_dirty(&id(5)), @@ -301,9 +332,9 @@ mod tests { *state.note_mut(&id(5)).expect("draft") = "Bao".into(); assert!(state.begin_save(id(1), id(5)).is_some()); - state.release_save(&id(1), &id(5)); + state.release_write(&id(1), &id(5)); - assert!(!state.is_saving(&id(1), &id(5))); + assert!(!state.is_writing(&id(1), &id(5))); assert!(state.is_dirty(&id(5)), "the unsaved edit stays"); assert!(state.begin_save(id(1), id(5)).is_some()); } @@ -328,9 +359,12 @@ mod tests { assert_eq!(state.selected(), None); assert_eq!(state.note_mut(&id(5)), None); assert!( - state.is_saving(&id(1), &id(5)), + state.is_writing(&id(1), &id(5)), "a paid write still running keeps its guard" ); - assert_eq!(state.finish_save(&id(1), &id(5)), Some(Some("Bao".into()))); + assert_eq!( + state.finish_write(&id(1), &id(5)), + Some(PendingWrite::Note(Some("Bao".into()))) + ); } } diff --git a/src/ui/state/contacts_view.rs b/src/ui/state/contacts_view.rs index 13797bbfc..63cb979b9 100644 --- a/src/ui/state/contacts_view.rs +++ b/src/ui/state/contacts_view.rs @@ -6,7 +6,7 @@ //! and paints it. Placement follows the DET module policy: non-widget UI state //! belongs in `ui/state/`. -use super::contact_detail_view::ContactDetailState; +use super::contact_detail_view::{ContactDetailState, PendingWrite}; use crate::backend_task::dashpay::ContactData; use crate::model::dashpay::contact_request_recipient; use crate::model::identity_name::display_label as profile_display_label; @@ -327,14 +327,20 @@ impl ContactsState { &mut self.detail } - /// Settle a confirmed note save. Returns whether one was running. The - /// listed contact shows the stored note right away when the lists belong to - /// `owner`, without waiting for the reload. - pub fn finish_note_save(&mut self, owner: &Identifier, contact_id: &Identifier) -> bool { - let Some(note) = self.detail.finish_save(owner, contact_id) else { + /// Settle a confirmed contact details write. Returns whether one was + /// running. After a note save the listed contact shows the stored note + /// right away when the lists belong to `owner`, without waiting for the + /// reload. + pub fn finish_contact_info_write( + &mut self, + owner: &Identifier, + contact_id: &Identifier, + ) -> bool { + let Some(write) = self.detail.finish_write(owner, contact_id) else { return false; }; - if self.owner_id() == Some(*owner) + if let PendingWrite::Note(note) = write + && self.owner_id() == Some(*owner) && let Some(contact) = self .contacts .iter_mut() @@ -347,9 +353,9 @@ impl ContactsState { true } - /// Release a note save that failed or was abandoned. - pub fn release_note_save(&mut self, owner: &Identifier, contact_id: &Identifier) { - self.detail.release_save(owner, contact_id); + /// Release a contact details write that failed or was abandoned. + pub fn release_contact_info_write(&mut self, owner: &Identifier, contact_id: &Identifier) { + self.detail.release_write(owner, contact_id); } } @@ -526,7 +532,7 @@ mod tests { *state.detail_mut().note_mut(&id(7)).expect("draft") = "Met at the meetup".into(); assert!(state.detail_mut().begin_save(id(1), id(7)).is_some()); - assert!(state.finish_note_save(&id(1), &id(7))); + assert!(state.finish_contact_info_write(&id(1), &id(7))); assert_eq!( state.selected_contact().and_then(|c| c.note.as_deref()), @@ -534,7 +540,7 @@ mod tests { ); assert!(!state.detail().is_dirty(&id(7))); assert!( - !state.finish_note_save(&id(1), &id(7)), + !state.finish_contact_info_write(&id(1), &id(7)), "a save settles only once" ); } @@ -547,7 +553,7 @@ mod tests { *state.detail_mut().note_mut(&id(7)).expect("draft") = "Theirs".into(); assert!(state.detail_mut().begin_save(id(2), id(7)).is_some()); - assert!(state.finish_note_save(&id(2), &id(7))); + assert!(state.finish_contact_info_write(&id(2), &id(7))); assert_eq!( state.selected_contact().and_then(|c| c.note.as_deref()), diff --git a/tests/kittest/identity_hub.rs b/tests/kittest/identity_hub.rs index 7409ed733..065c111c1 100644 --- a/tests/kittest/identity_hub.rs +++ b/tests/kittest/identity_hub.rs @@ -54,7 +54,7 @@ fn identity_hub_screen_type_creates_hub_screen() { let _ = screen_type; } -mod loads { +pub(crate) mod loads { //! The hub's own data loads: each is dispatched once per arrival, so one //! that is lost on the way out or on the way back never comes again. @@ -594,6 +594,24 @@ mod loads { results: Vec<(BackendTaskContext, BackendTaskSuccessResult)>, ) { use dash_evo_tool::app::TaskResult; + let results = results + .into_iter() + .map(|(context, result)| TaskResult::Success { + context, + result: Box::new(result), + }) + .collect(); + receive_task_results_behind_the_send_screen(runtime, app, hub, results); + } + + /// Moves the hub into `app`, delivers `results` while the Send screen + /// covers it, then cancels Send and hands the hub back. + pub(crate) fn receive_task_results_behind_the_send_screen( + runtime: &tokio::runtime::Runtime, + app: &mut Harness<'static, dash_evo_tool::app::AppState>, + hub: &mut Harness<'static, (IdentityHubScreen, Vec)>, + results: Vec, + ) { use dash_evo_tool::ui::wallets::send_screen::IdentitySendMode; use dash_evo_tool::ui::{RootScreenType, Screen, ScreenType}; @@ -612,12 +630,9 @@ mod loads { .create_screen(&app_context), ); - for (context, result) in results { + for result in results { runtime - .block_on(app.state().task_result_sender.send(TaskResult::Success { - context, - result: Box::new(result), - })) + .block_on(app.state().task_result_sender.send(result)) .expect("deliver the result"); } // One frame drains the result queue before it renders. diff --git a/tests/kittest/identity_hub_contact_detail.rs b/tests/kittest/identity_hub_contact_detail.rs index f9d45cee7..c472c6754 100644 --- a/tests/kittest/identity_hub_contact_detail.rs +++ b/tests/kittest/identity_hub_contact_detail.rs @@ -283,3 +283,152 @@ fn a_contacts_username_lines_up_with_its_name() { ); }); } + +// ------------------------------------------------------------------- +// A save's outcome reaches the hub even while another screen covers it. +// ------------------------------------------------------------------- + +/// Bao selected with a typed note and Save note clicked, with the hub mounted +/// on `app`'s context so it can be moved behind another screen. +fn hub_saving_a_note( + app: &egui_kittest::Harness<'static, dash_evo_tool::app::AppState>, +) -> (HubHarness, Identifier, BackendTaskContext) { + let app_context = app.state().current_app_context().clone(); + let (mut hub, owner) = hub_with_bao_selected(&app_context, WIDE, None); + note_editor(&hub).focus(); + hub.run(); + note_editor(&hub).type_text("Met at the meetup"); + hub.run(); + hub.get_by_role_and_label(Role::Button, SAVE_NOTE_LABEL) + .click(); + hub.run_steps(2); + let context = hub + .state() + .1 + .iter() + .find_map(|action| match action { + AppAction::BackendTask(task @ BackendTask::DashPayTask(inner)) + if matches!(**inner, DashPayTask::UpdateContactInfo { .. }) => + { + Some(BackendTaskContext::from(task)) + } + _ => None, + }) + .expect("Save note dispatched the write"); + assert!(hub.query_by_label(SAVING_NOTE_LABEL).is_some()); + hub.state_mut().1.clear(); + (hub, owner, context) +} + +fn contact_info_failure( + owner: Identifier, + source: dash_evo_tool::backend_task::error::TaskError, +) -> dash_evo_tool::backend_task::error::TaskError { + dash_evo_tool::backend_task::error::TaskError::DashPayContactInfoActionFailed { + identity_id: owner, + contact_id: Identifier::from(CONTACT), + source: Box::new(source), + } +} + +#[test] +fn a_note_saved_behind_another_screen_is_settled_on_return() { + with_isolated_data_dir(|| { + let runtime = tokio::runtime::Runtime::new().expect("runtime"); + let _guard = runtime.enter(); + let mut app = + crate::support::mount_app(dash_evo_tool::ui::RootScreenType::RootScreenWalletsBalances); + let (mut hub, owner, context) = hub_saving_a_note(&app); + + crate::identity_hub::loads::receive_task_results_behind_the_send_screen( + &runtime, + &mut app, + &mut hub, + vec![dash_evo_tool::app::TaskResult::Success { + context, + result: Box::new(BackendTaskSuccessResult::DashPayContactInfoUpdated { + identity: owner, + contact_id: Identifier::from(CONTACT), + }), + }], + ); + hub.run_steps(2); + + assert!( + hub.query_by_label(SAVING_NOTE_LABEL).is_none(), + "a save that finished behind another screen must not stay Saving…" + ); + hub.get_by_role_and_label(Role::Button, SAVE_NOTE_LABEL) + .click(); + hub.run_steps(2); + assert!(saved_notes(&hub).is_empty(), "the saved note is not dirty"); + }); +} + +#[test] +fn a_note_save_that_failed_behind_another_screen_can_be_retried() { + with_isolated_data_dir(|| { + let runtime = tokio::runtime::Runtime::new().expect("runtime"); + let _guard = runtime.enter(); + let mut app = + crate::support::mount_app(dash_evo_tool::ui::RootScreenType::RootScreenWalletsBalances); + let (mut hub, owner, context) = hub_saving_a_note(&app); + + crate::identity_hub::loads::receive_task_results_behind_the_send_screen( + &runtime, + &mut app, + &mut hub, + vec![dash_evo_tool::app::TaskResult::Error { + context, + error: contact_info_failure( + owner, + dash_evo_tool::backend_task::error::TaskError::WalletLocked, + ), + }], + ); + hub.run_steps(2); + + hub.get_by_role_and_label(Role::Button, SAVE_NOTE_LABEL) + .click(); + hub.run_steps(2); + assert_eq!( + saved_notes(&hub).len(), + 1, + "a failed save releases its guard, so the kept note can be saved again" + ); + }); +} + +#[test] +fn unreadable_details_found_behind_another_screen_still_ask_first() { + use dash_evo_tool::backend_task::error::{ContactInfoReadError, TaskError}; + with_isolated_data_dir(|| { + let runtime = tokio::runtime::Runtime::new().expect("runtime"); + let _guard = runtime.enter(); + let mut app = + crate::support::mount_app(dash_evo_tool::ui::RootScreenType::RootScreenWalletsBalances); + let (mut hub, owner, context) = hub_saving_a_note(&app); + + crate::identity_hub::loads::receive_task_results_behind_the_send_screen( + &runtime, + &mut app, + &mut hub, + vec![dash_evo_tool::app::TaskResult::Error { + context, + error: contact_info_failure( + owner, + TaskError::DashPayContactInfoRead { + source: ContactInfoReadError::DeserializeFailed, + }, + ), + }], + ); + hub.run_steps(2); + + assert!( + hub.query_by_label("Save note and replace saved details?") + .is_some(), + "the overwrite question must be asked once the hub is back in view" + ); + }); +} From ed3d486ee7cfef8e764f3e71d4ea1fc6b7bafca2 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Sat, 17 Oct 2026 15:41:09 +0000 Subject: [PATCH 13/73] fix(dashpay): read and write contact details the way platform-wallet does - Encode contactInfo private data with platform-wallet's DIP-15 codec, so 253-255-byte notes and nicknames get CompactSize length prefixes that other clients can read. - Read CompactSize lengths, and accept platform-wallet's zero padding, in the strict reader that guards writes against dropping fields. - Load contact details from every page of contactInfo documents, in the order the write lookup uses, decoded with platform-wallet's reader; the first document for a contact wins, matching the one a save rewrites. - Size the note fee from the encoded payload, including longer prefixes and the minimum padding. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012YneRVSNLhVnGiedWDr3fw --- src/backend_task/dashpay/contact_info.rs | 286 ++++++++++++++++------- src/backend_task/dashpay/contacts.rs | 210 ++++++++--------- src/model/fee_estimation.rs | 23 +- 3 files changed, 318 insertions(+), 201 deletions(-) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 9a5adff56..87f5ef0bc 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -25,6 +25,8 @@ use dash_sdk::platform::documents::transitions::DocumentCreateTransitionBuilder; use dash_sdk::platform::proto::get_documents_request::get_documents_request_v0::Start; use dash_sdk::platform::{Document, DocumentQuery, FetchMany, Identifier}; use dash_sdk::query_types::Documents; +use platform_wallet::wallet::identity::crypto::ContactInfoPrivateData as UpstreamPrivateData; +use platform_wallet::wallet::identity::crypto::contact_info::encode_private_data_bounded; use std::collections::{BTreeMap, HashSet}; use std::future::Future; use std::sync::Arc; @@ -45,91 +47,46 @@ impl ContactInfoPrivateData { Self::default() } - /// Minimum plaintext size so that IV (16) + AES-CBC ciphertext ≥ 48 bytes - /// (the `privateData` field's `minItems` in the DashPay contract). - /// PKCS7 pads 16 bytes to 32 (adds a full padding block when input is - /// block-aligned), so 16 plaintext → 32 ciphertext → 48 with IV. - const MIN_PLAINTEXT_SIZE: usize = 16; + /// The plaintext floor platform-wallet pads to with zero bytes, so that + /// IV (16) + AES-CBC ciphertext reaches the contract's 48-byte minimum. + /// Older versions of this client padded to 16 bytes, starting with a zero. + const MIN_PLAINTEXT_SIZE: usize = 17; - // Serialize to bytes for encryption + /// Encode for encryption with platform-wallet's DIP-15 codec, so every + /// client that uses it reads what this one writes. pub fn serialize(&self) -> Result, DashPayError> { - let mut bytes = Vec::new(); - - // Version (4 bytes) - bytes.extend_from_slice(&self.version.to_le_bytes()); - - // Alias name (length + string) - if let Some(alias) = &self.alias_name { - let alias_bytes = alias.as_bytes(); - let alias_len = alias_bytes.len(); - if alias_len > u8::MAX as usize { - return Err(DashPayError::ContactInfoValidationFailed { - errors: vec![format!("Nickname too long ({alias_len} bytes, max 255)")], - }); - } - bytes.push(alias_len as u8); - bytes.extend_from_slice(alias_bytes); - } else { - bytes.push(0u8); - } - - // Note (length + string) - if let Some(note) = &self.note { - let note_bytes = note.as_bytes(); - let note_len = note_bytes.len(); - if note_len > MAX_CONTACT_NOTE_BYTES { - return Err(DashPayError::ContactInfoValidationFailed { - errors: vec![format!( - "Note too long ({note_len} bytes, max {MAX_CONTACT_NOTE_BYTES})" - )], - }); - } - bytes.push(note_len as u8); - bytes.extend_from_slice(note_bytes); - } else { - bytes.push(0u8); + let alias_len = self.alias_name.as_deref().map_or(0, str::len); + if alias_len > u8::MAX as usize { + return Err(DashPayError::ContactInfoValidationFailed { + errors: vec![format!("Nickname too long ({alias_len} bytes, max 255)")], + }); } - - // Display hidden (1 byte) - bytes.push(if self.display_hidden { 1 } else { 0 }); - - // Accepted accounts (length + array) - let accounts_len = self.accepted_accounts.len(); - if accounts_len > u8::MAX as usize { + let note_len = self.note.as_deref().map_or(0, str::len); + if note_len > MAX_CONTACT_NOTE_BYTES { return Err(DashPayError::ContactInfoValidationFailed { errors: vec![format!( - "Too many accepted accounts ({accounts_len}, max 255)" + "Note too long ({note_len} bytes, max {MAX_CONTACT_NOTE_BYTES})" )], }); } - bytes.push(accounts_len as u8); - for account in &self.accepted_accounts { - bytes.extend_from_slice(&account.to_le_bytes()); - } - - // Pad to minimum plaintext size so the encrypted output (IV + ciphertext) - // meets the DashPay contract's privateData minItems (48 bytes). - // First padding byte is 0x00 as a sentinel so deserializers can - // distinguish real data from padding. Remaining bytes are random. - if bytes.len() < Self::MIN_PLAINTEXT_SIZE { - use bip39::rand::RngCore; - bytes.push(0x00); // sentinel: marks start of padding - let remaining = Self::MIN_PLAINTEXT_SIZE - bytes.len(); - if remaining > 0 { - let mut pad = vec![0u8; remaining]; - StdRng::from_entropy().fill_bytes(&mut pad); - bytes.extend_from_slice(&pad); - } - } - - Ok(bytes) + encode_private_data_bounded(&UpstreamPrivateData { + alias_name: self.alias_name.clone(), + note: self.note.clone(), + display_hidden: self.display_hidden, + accepted_accounts: self.accepted_accounts.clone(), + }) + .map_err(|e| DashPayError::ContactInfoValidationFailed { + errors: vec![e.to_string()], + }) } /// Parse the plaintext produced by [`serialize`](Self::serialize). /// /// Returns `None` for a truncated or non-canonical v0 payload, invalid /// UTF-8, or an unsupported version. The only accepted trailing bytes are - /// this client's sentinel padding up to [`Self::MIN_PLAINTEXT_SIZE`]. + /// padding up to [`Self::MIN_PLAINTEXT_SIZE`] that starts with a zero. + /// Stricter than platform-wallet's reader: a write must never drop fields + /// it cannot read. pub fn deserialize(bytes: &[u8]) -> Option { let version = u32::from_le_bytes(bytes.get(..4)?.try_into().ok()?); if version != 0 { @@ -137,10 +94,30 @@ impl ContactInfoPrivateData { } let mut pos = 4; + // A Bitcoin CompactSize length, in its shortest encoding only. + let take_compact_size = |pos: &mut usize| -> Option { + let field = |width: usize| bytes.get(*pos + 1..*pos + 1 + width); + let (value, width): (u64, usize) = match *bytes.get(*pos)? { + 0xFD => (u16::from_le_bytes(field(2)?.try_into().ok()?).into(), 3), + 0xFE => (u32::from_le_bytes(field(4)?.try_into().ok()?).into(), 5), + 0xFF => (u64::from_le_bytes(field(8)?.try_into().ok()?), 9), + n => (n.into(), 1), + }; + let shortest = match width { + 3 => 0xFD, + 5 => 0x1_0000, + 9 => 0x1_0000_0000, + _ => 0, + }; + if value < shortest { + return None; + } + *pos += width; + usize::try_from(value).ok() + }; let take_string = |pos: &mut usize| -> Option> { - let len = *bytes.get(*pos)? as usize; - *pos += 1; - let raw = bytes.get(*pos..*pos + len)?; + let len = take_compact_size(pos)?; + let raw = bytes.get(*pos..pos.checked_add(len)?)?; *pos += len; if len == 0 { Some(None) @@ -158,8 +135,7 @@ impl ContactInfoPrivateData { }; pos += 1; - let count = *bytes.get(pos)? as usize; - pos += 1; + let count = take_compact_size(&mut pos)?; let accepted_accounts = (0..count) .map(|_| { let raw = bytes.get(pos..pos + 4)?; @@ -169,7 +145,7 @@ impl ContactInfoPrivateData { .collect::>>()?; if pos < bytes.len() - && (bytes.len() != Self::MIN_PLAINTEXT_SIZE || bytes.get(pos) != Some(&0)) + && (bytes.len() > Self::MIN_PLAINTEXT_SIZE || bytes.get(pos) != Some(&0)) { return None; } @@ -380,7 +356,7 @@ fn next_contact_info_page(docs: &Documents) -> Option { .map(|last_id| Start::StartAfter(last_id.to_buffer().to_vec())) } -async fn fetch_all_contact_info_documents( +pub(super) async fn fetch_all_contact_info_documents( mut query: DocumentQuery, mut fetch_page: F, ) -> Result @@ -1034,6 +1010,158 @@ mod tests { assert_eq!(documents.keys().last().copied(), Some(id(101))); } + /// DIP-15 writes string lengths as CompactSize, where 253 and longer take a + /// three-byte prefix. Other platform-wallet clients must read what this + /// client writes, and this client what they write. + #[test] + fn contact_details_round_trip_with_the_platform_wallet_codec() { + use platform_wallet::wallet::identity::crypto as upstream; + for len in [0, 252, 253, 255] { + let text = (len > 0).then(|| "x".repeat(len)); + let ours = ContactInfoPrivateData { + version: 0, + alias_name: text.clone(), + note: text.clone(), + display_hidden: true, + accepted_accounts: vec![0, 3], + }; + let theirs = upstream::ContactInfoPrivateData { + alias_name: text.clone(), + note: text.clone(), + display_hidden: true, + accepted_accounts: vec![0, 3], + }; + + let decoded = upstream::decode_private_data(&ours.serialize().expect("serialize")); + assert_eq!( + decoded.ok(), + Some(theirs.clone()), + "platform-wallet reads {len} bytes" + ); + + let parsed = + ContactInfoPrivateData::deserialize(&upstream::encode_private_data(&theirs)) + .unwrap_or_else(|| { + panic!("this client reads {len} bytes from platform-wallet") + }); + assert_eq!(parsed.alias_name, text); + assert_eq!(parsed.note, text); + assert!(parsed.display_hidden); + assert_eq!(parsed.accepted_accounts, vec![0, 3]); + } + } + + /// The fee shown before a save is sized from the bytes the write sends. + #[test] + fn the_fee_is_sized_from_the_encoded_contact_details() { + use crate::model::fee_estimation::PlatformFeeEstimator; + use platform_wallet::wallet::identity::crypto as upstream; + for len in [0, 252, 253, 255] { + let text = (len > 0).then(|| "x".repeat(len)); + let encoded = upstream::encode_private_data(&upstream::ContactInfoPrivateData { + alias_name: text.clone(), + note: text, + display_hidden: false, + accepted_accounts: vec![0], + }); + assert_eq!( + PlatformFeeEstimator::contact_info_plaintext_bytes(len, len), + encoded.len(), + "{len}-byte nickname and note" + ); + } + } + + fn contact_details_page(documents: impl IntoIterator) -> Documents { + documents + .into_iter() + .map(|document| (document.id(), Some(document))) + .collect() + } + + /// A stored contactInfo for `contact` whose note platform-wallet wrote. + fn saved_note_document(document_id: u8, contact: Identifier, note: &str) -> Document { + use platform_wallet::wallet::identity::crypto as upstream; + let user_id = encrypt_to_user_id(&contact.to_buffer(), &KEY).expect("encrypt"); + let mut document = lookup_contact_info_document(document_id, document_id.into(), user_id); + let plaintext = upstream::encode_private_data(&upstream::ContactInfoPrivateData { + note: Some(note.to_string()), + ..Default::default() + }); + let private_data = encrypt_private_data(&plaintext, &KEY).expect("encrypt"); + document.set("privateData", Value::Bytes(private_data)); + document + } + + /// The details loaded from `pages`, and whether every page was asked for + /// in the order the write lookup uses. + async fn load_details( + pages: Vec, + ) -> ( + std::collections::HashMap, + bool, + ) { + let contract = + load_system_data_contract(SystemDataContract::Dashpay, PlatformVersion::latest()) + .expect("DashPay contract fixture"); + let query = DocumentQuery::new(contract, "contactInfo").expect("contactInfo query"); + let mut pages = VecDeque::from(pages); + let mut ordered = true; + let details = super::super::contacts::load_contact_details( + query, + |query| { + ordered &= query + .order_by_clauses + .iter() + .any(|clause| clause.field == "$updatedAt" && clause.ascending); + ready(Ok::<_, TaskError>(pages.pop_front().unwrap_or_default())) + }, + |_| ready(Ok((Zeroizing::new(KEY), Zeroizing::new(KEY)))), + ) + .await + .expect("contact details load"); + (details, ordered) + } + + /// A saved note can sit beyond the first page of the owner's contactInfo + /// documents; it must not be read as "no note". + #[tokio::test] + async fn the_contact_details_load_reads_every_page() { + let contact = id(201); + let other = encrypt_to_user_id(&id(202).to_buffer(), &KEY).expect("encrypt"); + let first_page = contact_details_page( + (1..=100).map(|byte| lookup_contact_info_document(byte, byte.into(), other)), + ); + let note = "n".repeat(253); + let second_page = contact_details_page([saved_note_document(101, contact, ¬e)]); + + let (details, ordered) = load_details(vec![first_page, second_page]).await; + + assert_eq!( + details.get(&contact).and_then(|c| c.note.clone()), + Some(note) + ); + assert!(ordered, "pages follow the order the write lookup uses"); + } + + /// With two documents for one contact, the load shows the one a save + /// rewrites: the first in that order. + #[tokio::test] + async fn the_contact_details_load_shows_the_document_a_save_rewrites() { + let contact = id(201); + let page = contact_details_page([ + saved_note_document(1, contact, "kept"), + saved_note_document(2, contact, "stale"), + ]); + + let (details, _) = load_details(vec![page]).await; + + assert_eq!( + details.get(&contact).and_then(|c| c.note.as_deref()), + Some("kept") + ); + } + #[test] fn private_data_round_trips_every_accepted_account() { let original = ContactInfoPrivateData { @@ -1132,7 +1260,7 @@ mod tests { fn trailing_extension_bytes_require_confirmation() { let mut bytes = ContactInfoPrivateData { version: 0, - alias_name: Some("12345678".to_string()), + alias_name: Some("123456789".to_string()), note: None, display_hidden: false, accepted_accounts: Vec::new(), diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index 6de7aa6d1..e5ed3a6de 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -12,8 +12,11 @@ use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::platform_value::Value; use dash_sdk::drive::query::{OrderClause, WhereClause, WhereOperator}; use dash_sdk::platform::{Document, DocumentQuery, Fetch, FetchMany, Identifier}; +use dash_sdk::query_types::Documents; use futures::future::join_all; +use platform_wallet::wallet::identity::crypto::decode_private_data; use std::collections::{HashMap, HashSet}; +use std::future::Future; use std::sync::Arc; use zeroize::Zeroizing; @@ -125,6 +128,87 @@ pub(super) fn decrypt_private_data( Ok(decrypted.to_vec()) } +/// The nickname, note and visibility the owner stored for each contact, read +/// from every page of the owner's `contactInfo` documents. +/// +/// Pages follow the order the write lookup scans, and the first document for +/// a contact wins, so the load shows the document a save rewrites. +pub(super) async fn load_contact_details( + query: DocumentQuery, + fetch_page: P, + mut derive_keys: D, +) -> Result, TaskError> +where + P: FnMut(DocumentQuery) -> PF, + PF: Future>, + D: FnMut(u32) -> DF, + DF: Future, Zeroizing<[u8; 32]>), TaskError>>, +{ + let query = query.with_order_by(OrderClause { + field: "$updatedAt".to_string(), + ascending: true, + }); + let documents = + super::contact_info::fetch_all_contact_info_documents(query, fetch_page).await?; + + let mut contact_info_map: HashMap = HashMap::new(); + for doc in documents.into_values().flatten() { + let props = doc.properties(); + let Some(deriv_idx) = props + .get("derivationEncryptionKeyIndex") + .and_then(|value| value.to_integer::().ok()) + else { + continue; + }; + let Ok((enc_user_id_key, private_data_key)) = derive_keys(deriv_idx).await else { + continue; + }; + let Some(Value::Bytes(enc_user_id)) = props.get("encToUserId") else { + continue; + }; + let Ok(decrypted_id) = decrypt_to_user_id(enc_user_id, &enc_user_id_key) else { + continue; + }; + let Ok(contact_id) = Identifier::from_bytes(&decrypted_id) else { + tracing::warn!( + "Failed to parse decrypted contact ID (length {}), skipping contact info entry", + decrypted_id.len() + ); + continue; + }; + if contact_info_map.contains_key(&contact_id) { + continue; + } + + // The DIP-15 codec platform-wallet writes with; an unreadable payload + // shows as no stored details. + let private_data = match props.get("privateData") { + Some(Value::Bytes(encrypted)) => decrypt_private_data(encrypted, &private_data_key) + .ok() + .and_then(|plaintext| decode_private_data(&plaintext).ok()), + _ => None, + } + .unwrap_or_default(); + + contact_info_map.insert( + contact_id, + ContactData { + identity_id: contact_id, + account_reference: private_data.accepted_accounts.first().copied().unwrap_or(0), + nickname: private_data.alias_name, + note: private_data.note, + is_hidden: private_data.display_hidden, + username: None, + display_name: None, + avatar_url: None, + bio: None, + }, + ); + } + + Ok(contact_info_map) +} + #[derive(Debug, Clone, PartialEq)] pub struct ContactData { pub identity_id: Identifier, @@ -212,122 +296,16 @@ pub async fn load_contacts( operator: WhereOperator::Equal, value: Value::Identifier(identity_id.to_buffer()), }); - contact_info_query.limit = 100; - - let contact_info_docs = Document::fetch_many(sdk, contact_info_query).await?; - - // Build a map of contact ID to contact info - let mut contact_info_map: HashMap = HashMap::new(); - - for (_doc_id, doc) in contact_info_docs.iter() { - if let Some(doc) = doc { - let props = doc.properties(); - - // Get the derivation index used for this document - if let Some(deriv_idx) = props - .get("derivationEncryptionKeyIndex") - .and_then(|value| value.to_integer::().ok()) - { - // Derive keys for this document - let (enc_user_id_key, private_data_key) = - match derive_contact_info_keys(app_context, &identity, deriv_idx).await { - Ok(keys) => keys, - Err(_) => continue, - }; - - // Decrypt encToUserId to find which contact this is for - if let Some(Value::Bytes(enc_user_id)) = props.get("encToUserId") - && let Ok(decrypted_id) = decrypt_to_user_id(enc_user_id, &enc_user_id_key) - { - let Ok(contact_id) = Identifier::from_bytes(&decrypted_id) else { - tracing::warn!( - "Failed to parse decrypted contact ID (length {}), skipping contact info entry", - decrypted_id.len() - ); - continue; - }; - - // Decrypt private data if available - let mut nickname = None; - let mut note = None; - let mut is_hidden = false; - let mut account_reference = 0u32; - - if let Some(Value::Bytes(encrypted_private)) = props.get("privateData") - && let Ok(decrypted_data) = - decrypt_private_data(encrypted_private, &private_data_key) - { - // Parse the decrypted data - // Simple format: version(4) + alias_len(1) + alias + note_len(1) + note + hidden(1) + accounts_len(1) + accounts - if decrypted_data.len() >= 8 { - let mut pos = 4; // Skip version - - // Read alias - if pos < decrypted_data.len() { - let alias_len = decrypted_data[pos] as usize; - pos += 1; - if pos + alias_len <= decrypted_data.len() && alias_len > 0 { - nickname = String::from_utf8( - decrypted_data[pos..pos + alias_len].to_vec(), - ) - .ok(); - pos += alias_len; - } - } - - // Read note - if pos < decrypted_data.len() { - let note_len = decrypted_data[pos] as usize; - pos += 1; - if pos + note_len <= decrypted_data.len() && note_len > 0 { - note = String::from_utf8( - decrypted_data[pos..pos + note_len].to_vec(), - ) - .ok(); - pos += note_len; - } - } - - // Read hidden flag - if pos < decrypted_data.len() { - is_hidden = decrypted_data[pos] != 0; - pos += 1; - } - - // Read accounts (simplified - just take first if available) - if pos < decrypted_data.len() { - let accounts_len = decrypted_data[pos] as usize; - pos += 1; - if accounts_len > 0 && pos + 4 <= decrypted_data.len() { - account_reference = u32::from_le_bytes([ - decrypted_data[pos], - decrypted_data[pos + 1], - decrypted_data[pos + 2], - decrypted_data[pos + 3], - ]); - } - } - } - } - - contact_info_map.insert( - contact_id, - ContactData { - identity_id: contact_id, - nickname, - note, - is_hidden, - account_reference, - username: None, - display_name: None, - avatar_url: None, - bio: None, - }, - ); - } - } - } - } + let contact_info_map = load_contact_details( + contact_info_query, + |query| async move { + Document::fetch_many(sdk, query) + .await + .map_err(TaskError::from) + }, + |derivation_index| derive_contact_info_keys(app_context, &identity, derivation_index), + ) + .await?; // Build enriched contact list with basic data let mut contact_list: Vec = contacts diff --git a/src/model/fee_estimation.rs b/src/model/fee_estimation.rs index c26636bec..8e8100419 100644 --- a/src/model/fee_estimation.rs +++ b/src/model/fee_estimation.rs @@ -714,13 +714,8 @@ impl PlatformFeeEstimator { // Document fields: encToUserId (32), the two key indexes (8), and the // id, owner and revision every document carries (72). const FIXED_DOCUMENT_BYTES: usize = 112; - // privateData plaintext: version (4), nickname and note length - // prefixes (2), hidden flag (1), one accepted account (5). - const FIXED_PAYLOAD_BYTES: usize = 12; const AES_BLOCK: usize = 16; - let plaintext = FIXED_PAYLOAD_BYTES - .saturating_add(nickname_bytes) - .saturating_add(note_bytes); + let plaintext = Self::contact_info_plaintext_bytes(nickname_bytes, note_bytes); // A random IV, then the plaintext PKCS#7-padded to whole blocks. let private_data = AES_BLOCK.saturating_add( (plaintext / AES_BLOCK) @@ -730,6 +725,22 @@ impl PlatformFeeEstimator { self.estimate_document_create_with_size(FIXED_DOCUMENT_BYTES.saturating_add(private_data)) } + /// Size of a contact's DIP-15 `contactInfo` private data before + /// encryption, with one accepted account. + pub fn contact_info_plaintext_bytes(nickname_bytes: usize, note_bytes: usize) -> usize { + // Version (4), hidden flag (1), one accepted account with its count (5). + const FIXED_PAYLOAD_BYTES: usize = 10; + // Short payloads are zero-padded so the encrypted field meets the + // contract's 48-byte minimum. + const MIN_PLAINTEXT_BYTES: usize = 17; + // A CompactSize length prefix: one byte below 253, three up to 65535. + let prefixed = |len: usize| len.saturating_add(if len < 0xFD { 1 } else { 3 }); + FIXED_PAYLOAD_BYTES + .saturating_add(prefixed(nickname_bytes)) + .saturating_add(prefixed(note_bytes)) + .max(MIN_PLAINTEXT_BYTES) + } + /// Estimate fee for document transfer. /// Transfer updates ownership, minimal storage change. pub fn estimate_document_transfer(&self) -> u64 { From 67d3fc38d5508f482da2507d6743cdea796c5d8f Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 19 Oct 2026 12:28:33 +0000 Subject: [PATCH 14/73] fix(identity): expand the hub to the available window width MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove the shared width cap and verify that the header and each tab grow with the window while narrow layouts and long labels remain contained. Co-Authored-By: Codex 🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent --- src/ui/identity/hub_screen.rs | 9 +--- src/ui/identity/mod.rs | 6 --- tests/kittest/identity_hub_layout.rs | 67 +++++++++++++++++----------- 3 files changed, 43 insertions(+), 39 deletions(-) diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index b2b025246..f04c2b984 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -551,14 +551,9 @@ impl ScreenLike for IdentityHubScreen { HubView::Home => { // One roster read per frame serves the header and every tab. let selected = self.app_context.resolve_selected_identity(); - // The header, the tab bar and the tab content share one - // left-aligned column that stops at one width, so wide - // windows do not stretch them (wireframes A05/A06/A08). - // `.inner` carries the tab's `AppAction` back out. + // Share the island's available width across the header and + // tabs; each tab handles its own responsive columns. let inner = ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { - // `set_max_width` replaces the width rather than - // capping it, so cap at what the window has too. - ui.set_max_width(ui.available_width().min(super::HUB_CONTENT_MAX_WIDTH)); let (header_action, header_outcome) = match &selected { Some(identity) => super::home::render_header( ui, diff --git a/src/ui/identity/mod.rs b/src/ui/identity/mod.rs index e8abccc28..c31274ebb 100644 --- a/src/ui/identity/mod.rs +++ b/src/ui/identity/mod.rs @@ -65,12 +65,6 @@ pub mod withdraw_screen; pub use hub_screen::IdentityHubScreen; pub use tabs::IdentityHubTab; -/// Widest the content of an identity hub tab grows, in points. Matches the -/// content area of the identities wireframes (A05 Home, A06 Contacts, A08 -/// Profile); wider windows leave the space to the right empty instead of -/// stretching forms, columns and rows. -pub const HUB_CONTENT_MAX_WIDTH: f32 = 1040.0; - /// Confirmation shown once an identity is removed from this device. pub const IDENTITY_REMOVED: &str = "The identity was removed from this device."; diff --git a/tests/kittest/identity_hub_layout.rs b/tests/kittest/identity_hub_layout.rs index 255c283b4..106b336b5 100644 --- a/tests/kittest/identity_hub_layout.rs +++ b/tests/kittest/identity_hub_layout.rs @@ -1,8 +1,8 @@ //! Identity hub layout on ordinary and wide windows. //! //! The hub tabs follow the 2026-09-22 identities wireframes (A05 Home, A06 -//! Contacts, A08 Profile): content starts at the tab bar's left edge and never -//! grows past one shared content width, however wide the window is. +//! Contacts, A08 Profile): content starts at the tab bar's left edge and grows +//! with the available window width, while narrow layouts stay on screen. use crate::identity_home::key; use crate::support::{fresh_app_context, with_isolated_data_dir}; @@ -16,7 +16,7 @@ use dash_evo_tool::model::qualified_identity::{ DPNSNameInfo, IdentityStatus, IdentityType, QualifiedIdentity, }; use dash_evo_tool::ui::ScreenLike; -use dash_evo_tool::ui::identity::{HUB_CONTENT_MAX_WIDTH, IdentityHubScreen, IdentityHubTab}; +use dash_evo_tool::ui::identity::{IdentityHubScreen, IdentityHubTab}; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dash_sdk::dpp::identity::{Identity, Purpose}; @@ -202,7 +202,8 @@ fn content_left(hub: &HubHarness) -> f32 { } fn assert_within_content(hub: &HubHarness, what: &str, rect: egui::Rect, width: f32) { - let limit = content_left(hub) + HUB_CONTENT_MAX_WIDTH + EPSILON; + assert!(rect.left() >= content_left(hub) - EPSILON); + let limit = width + EPSILON; assert!( rect.right() <= limit, "at {width} px, {what} ends at {} but the content ends at {limit}", @@ -249,8 +250,8 @@ fn profile_keeps_the_form_and_the_usernames_card_side_by_side() { .get_by_role_and_label(Role::Button, "Get another username") .rect(); assert!( - another.width() <= 420.0, - "at {width} px, Get another username must stay card-sized, is {}", + another.width() < (width - content_left(&hub)) / 2.0, + "at {width} px, Get another username must fit the right column, is {}", another.width() ); assert_within_content(&hub, "the usernames card", another, width); @@ -311,28 +312,42 @@ fn contacts_sections_start_at_the_content_edge_with_one_add_button() { } } -/// The identity header (avatar, name, balance and its actions) shares the tab -/// content's column on every tab, instead of spanning a wide window. +/// Both the header and tab content expand when the user widens the window. #[test] -fn header_stays_within_the_content_width_on_every_tab() { - for tab in [ - IdentityHubTab::Home, - IdentityHubTab::Contacts, - IdentityHubTab::Settings, +fn header_and_tabs_expand_with_the_window() { + for (tab, content_label) in [ + (IdentityHubTab::Home, "Add contact"), + ( + IdentityHubTab::Contacts, + dash_evo_tool::ui::identity::contacts::VIEW_PROFILE_LABEL, + ), + (IdentityHubTab::Settings, "Get another username"), ] { - with_isolated_data_dir(|| { - let (_runtime, app_context) = fresh_app_context(); - let hub = hub_on(&app_context, 2000.0, tab); - let move_to_wallet = hub - .get_by_role_and_label(Role::Button, "Move to wallet") - .rect(); - assert_within_content( - &hub, - &format!("the header's Move to wallet on {tab:?}"), - move_to_wallet, - 2000.0, - ); - }); + let mut edges = Vec::new(); + for width in WIDTHS { + with_isolated_data_dir(|| { + let (_runtime, app_context) = fresh_app_context(); + let hub = hub_on(&app_context, width, tab); + let header = hub + .get_by_role_and_label(Role::Button, "Move to wallet") + .rect(); + let content = hub + .get_by_role_and_label(Role::Button, content_label) + .rect(); + assert_within_content(&hub, "Move to wallet", header, width); + assert_within_content(&hub, content_label, content, width); + edges.push((header.right(), content.right())); + }); + } + let growth = WIDTHS[1] - WIDTHS[0]; + assert!( + edges[1].0 - edges[0].0 > growth * 0.9, + "{tab:?}'s header must use the added window width: {edges:?}" + ); + assert!( + edges[1].1 - edges[0].1 > growth * 0.5, + "{tab:?}'s content must expand with the window: {edges:?}" + ); } } From b977e316e22a0226a66e12d16298f95a4d46437c Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 19 Oct 2026 12:53:53 +0000 Subject: [PATCH 15/73] fix(dashpay): preserve typed contact encoding errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Validate note lengths through the shared model validator and preserve the upstream codec error as a typed source. Document CompactSize encoding and distinguish the application's note limit from the wire format. Validation: 222 targeted unit tests, 65 identity hub UI tests, scoped clippy, and cargo fmt --all passed. 🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent Co-Authored-By: Codex --- src/backend_task/dashpay/contact_info.rs | 26 +++++++++--------------- src/backend_task/error.rs | 14 +++++++++++++ src/model/dashpay.rs | 8 ++++---- 3 files changed, 28 insertions(+), 20 deletions(-) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 87f5ef0bc..6d5b2ca80 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -3,8 +3,8 @@ use crate::backend_task::dashpay::errors::DashPayError; use crate::backend_task::error::{ContactInfoReadError, TaskError}; use crate::context::AppContext; use crate::model::dashpay::{ - AcceptedAccounts, ContactInfoField, ContactInfoUpdate, MAX_CONTACT_NOTE_BYTES, - UnreadableContactInfoPolicy, + AcceptedAccounts, ContactInfoField, ContactInfoUpdate, UnreadableContactInfoPolicy, + validate_contact_note, }; use crate::model::qualified_identity::QualifiedIdentity; use aes_gcm::aes::Aes256; @@ -54,29 +54,23 @@ impl ContactInfoPrivateData { /// Encode for encryption with platform-wallet's DIP-15 codec, so every /// client that uses it reads what this one writes. - pub fn serialize(&self) -> Result, DashPayError> { + pub fn serialize(&self) -> Result, TaskError> { let alias_len = self.alias_name.as_deref().map_or(0, str::len); if alias_len > u8::MAX as usize { return Err(DashPayError::ContactInfoValidationFailed { errors: vec![format!("Nickname too long ({alias_len} bytes, max 255)")], - }); - } - let note_len = self.note.as_deref().map_or(0, str::len); - if note_len > MAX_CONTACT_NOTE_BYTES { - return Err(DashPayError::ContactInfoValidationFailed { - errors: vec![format!( - "Note too long ({note_len} bytes, max {MAX_CONTACT_NOTE_BYTES})" - )], - }); + } + .into()); } + validate_contact_note(self.note.as_deref().unwrap_or_default())?; encode_private_data_bounded(&UpstreamPrivateData { alias_name: self.alias_name.clone(), note: self.note.clone(), display_hidden: self.display_hidden, accepted_accounts: self.accepted_accounts.clone(), }) - .map_err(|e| DashPayError::ContactInfoValidationFailed { - errors: vec![e.to_string()], + .map_err(|source| TaskError::DashPayContactInfoEncoding { + source: Box::new(source), }) } @@ -554,8 +548,8 @@ pub(super) async fn contact_info_is_hidden( /// identity has none yet and replacing it otherwise. /// /// The document is written whole, so `update` explicitly chooses which fields -/// are preserved and which fields are replaced. Nicknames, notes, and account -/// lists are each limited to 255 bytes/items by the v0 encoding. +/// are preserved and which fields are replaced. Nicknames and notes are limited +/// to 255 UTF-8 bytes; the encoded payload must also fit the contract size limit. /// /// # Errors /// diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 8f8759534..8f6091040 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -1366,6 +1366,20 @@ pub enum TaskError { source: crate::wallet_backend::KvAdapterError, }, + /// A private contact note exceeds the application's byte limit. + #[error("This note is too long. Shorten it to save it.")] + DashPayContactNoteTooLong { + #[from] + source: crate::model::dashpay::ContactNoteTooLong, + }, + + /// Contact details could not be encoded within the document size limit. + #[error("Contact info is too large to save. Try shortening your nickname or note.")] + DashPayContactInfoEncoding { + #[source] + source: Box, + }, + /// An existing contact's encrypted details could not be read safely. #[error( "Your saved contact details could not be read, so no changes were made. Use a compatible DashPay client, or try again and confirm replacing the saved details when asked." diff --git a/src/model/dashpay.rs b/src/model/dashpay.rs index fff9bf87d..55ea411a0 100644 --- a/src/model/dashpay.rs +++ b/src/model/dashpay.rs @@ -22,17 +22,17 @@ pub fn validate_account_label(label: &str) -> Result<(), TextLengthError> { validate_char_count(label, 0, MAX_ACCOUNT_LABEL_CHARS) } -/// Most bytes a contact's private note can hold. Its encrypted `contactInfo` -/// payload stores the note's length in a single byte. +/// Application limit for a contact's private note, in UTF-8 bytes. +/// The encrypted `contactInfo` payload encodes its length with CompactSize. pub const MAX_CONTACT_NOTE_BYTES: usize = u8::MAX as usize; -/// A private contact note is longer than its encrypted payload can store. +/// A private contact note exceeds the application's size limit. #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] #[error("This note is too long. Shorten it to save it.")] pub struct ContactNoteTooLong { /// Size of the note in UTF-8 bytes. pub bytes: usize, - /// Largest size the payload accepts. + /// Largest note size the application accepts. pub max: usize, } From 3b0e080e01a7e45abf4facc82d96e226e187a713 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 19 Oct 2026 14:05:55 +0000 Subject: [PATCH 16/73] fix(identity): open Home contacts in the hub detail pane MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Route Home contact selections to Contacts while retaining the selected profile and note during refresh. Center the detail pane's Pay label with the shared button helper. 🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent Co-Authored-By: Codex GPT-6 --- docs/user-stories.md | 1 + src/ui/identity/contacts.rs | 23 +----- src/ui/identity/home.rs | 4 +- src/ui/identity/hub_screen.rs | 8 ++- tests/kittest/identity_hub_contact_detail.rs | 75 ++++++++++++++++++++ 5 files changed, 88 insertions(+), 23 deletions(-) diff --git a/docs/user-stories.md b/docs/user-stories.md index 6791ada65..922021aa3 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -1737,6 +1737,7 @@ As Alex, when I have one identity, opening Identities shows me my balance, usern - Move to wallet uses the same form, restricted to receiving addresses of loaded wallets. Arbitrary destinations remain available through Send. - Receive shares the username or identity ID and its QR code; it does not create or send a payment. - Setup and actual recent contact payments appear beside a contacts/request preview, stacking on narrow windows. Empty payment history and the unfinished Activity tab are hidden. Pending username requests and their outcomes remain visible. +- Selecting a contact in Home's preview opens Contacts with that person's profile and private note selected in Contact details. The selection stays visible while the list refreshes. - Technical identity details and keys are available from Profile → Advanced or the summary's menu. ### IDH-003: Multi-identity switching [Implemented] diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index 3adca6961..e525dbcba 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -664,8 +664,7 @@ fn detail_pane( if FeatureGate::DashPayOperations.is_available(app_context) { ui.add_space(8.0); - let pay = ui - .add(ComponentStyles::secondary_button(PAY_LABEL, dark_mode)) + let pay = ComponentStyles::add_secondary_button(ui, PAY_LABEL, dark_mode) .clickable_tooltip("Send Dash to this contact."); if pay.clicked() { action = pay_action(app_context, identity, contact.identity_id); @@ -1146,10 +1145,6 @@ fn contact_handle(contact: &ContactData, label: &str) -> Option { (handle != label && username != label).then_some(handle) } -fn contact_profile_screen_type(identity: QualifiedIdentity, contact_id: Identifier) -> ScreenType { - ScreenType::DashPayContactProfileViewer(identity, contact_id) -} - /// Compact Home preview; request actions share the Contacts tab's paid-action guards. pub(super) fn render_preview( ui: &mut Ui, @@ -1183,10 +1178,7 @@ pub(super) fn render_preview( } for contact in state.matching_contacts().take(6) { if ui.button(contact_label(contact)).clicked() { - action = AppAction::AddScreen( - contact_profile_screen_type(identity.clone(), contact.identity_id) - .create_screen(app_context), - ); + *outcome = super::home::HomeOutcome::GoToContact(contact.identity_id); } } if state.contacts_len() == 0 && state.incoming().is_empty() { @@ -1643,17 +1635,6 @@ mod tests { ); } - #[test] - fn contact_profile_action_targets_the_working_viewer_and_selected_contact() { - let identity = qualified_identity(id(1)); - - assert!(matches!( - contact_profile_screen_type(identity, id(2)), - ScreenType::DashPayContactProfileViewer(owner, contact_id) - if owner.identity.id() == id(1) && contact_id == id(2) - )); - } - // --------------------------------------------------------------- // Request-row actions — the dead-button regression these rows had: // Accept/Decline were TODO stubs and Cancel had no task at all. diff --git a/src/ui/identity/home.rs b/src/ui/identity/home.rs index 7212b931d..58fba5915 100644 --- a/src/ui/identity/home.rs +++ b/src/ui/identity/home.rs @@ -18,6 +18,7 @@ use crate::ui::theme::{ComponentStyles, DashColors, ResponseExt, Shape, Spacing} use crate::ui::wallets::send_screen::IdentitySendMode; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::platform_value::string_encoding::Encoding; +use dash_sdk::platform::Identifier; use egui::{self, Frame, Margin, RichText, Ui}; use std::sync::Arc; @@ -25,6 +26,7 @@ use std::sync::Arc; pub enum HomeOutcome { None, GoToContacts, + GoToContact(Identifier), GoToSettings, GoToUsernames, GoToAdvanced, @@ -495,7 +497,7 @@ pub(super) fn card(ui: &mut Ui, content: impl FnOnce(&mut Ui) -> R) -> R { pub fn apply_outcome(state: &mut HomeState, outcome: HomeOutcome) -> Option { match outcome { HomeOutcome::None => None, - HomeOutcome::GoToContacts => Some(IdentityHubTab::Contacts), + HomeOutcome::GoToContacts | HomeOutcome::GoToContact(_) => Some(IdentityHubTab::Contacts), HomeOutcome::GoToSettings | HomeOutcome::GoToUsernames | HomeOutcome::GoToAdvanced => { Some(IdentityHubTab::Settings) } diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index aead250e7..4f9560184 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -627,7 +627,13 @@ impl ScreenLike for IdentityHubScreen { if let Some(next_tab) = super::home::apply_outcome(&mut self.home_state, outcome) { - if next_tab != self.selected_tab { + if let super::home::HomeOutcome::GoToContact(contact_id) = + outcome + { + self.contacts_state.search_mut().clear(); + self.contacts_state.select_contact(&contact_id); + self.contacts_state.invalidate(); + } else if next_tab != self.selected_tab { self.contacts_state.reset(); } self.selected_tab = next_tab; diff --git a/tests/kittest/identity_hub_contact_detail.rs b/tests/kittest/identity_hub_contact_detail.rs index c472c6754..85c48f117 100644 --- a/tests/kittest/identity_hub_contact_detail.rs +++ b/tests/kittest/identity_hub_contact_detail.rs @@ -76,6 +76,81 @@ fn note_editor(hub: &HubHarness) -> egui_kittest::Node<'_> { hub.get_by_role(Role::MultilineTextInput) } +#[test] +fn home_contact_opens_contacts_with_selected_details() { + for width in [WIDE, NARROW] { + with_isolated_data_dir(|| { + let (_runtime, app_context) = fresh_app_context(); + let owner = seed_identity_with_usernames(&app_context); + let mut hub = hub_for( + &app_context, + owner, + width, + IdentityHubTab::Home, + |hub, owner| deliver(hub, owner, bao(Some("Met at the meetup"))), + ); + hub.state_mut().1.clear(); + hub.get_by_role_and_label(Role::Button, "Bao Nguyen") + .click(); + hub.run_steps(4); + + assert_eq!(hub.state().0.selected_tab(), IdentityHubTab::Contacts); + assert!(hub.query_by_label(DETAIL_HEADING).is_some()); + assert!(hub.query_by_label("Coffee and code.").is_some()); + assert_eq!( + note_editor(&hub).value().as_deref(), + Some("Met at the meetup") + ); + assert!( + hub.state() + .1 + .iter() + .all(|action| !matches!(action, AppAction::AddScreen(_))) + ); + + deliver(&mut hub, owner, bao(Some("Updated note"))); + hub.run_steps(4); + assert_eq!(note_editor(&hub).value().as_deref(), Some("Updated note")); + }); + } +} + +#[test] +fn contact_details_pay_label_is_centered() { + fn pay_text(shape: &egui::Shape, button: egui::Rect) -> Option { + match shape { + egui::Shape::Text(text) if text.galley.text() == "Pay" => { + let rect = text.visual_bounding_rect(); + button.contains(rect.center()).then_some(rect) + } + egui::Shape::Vec(shapes) => shapes.iter().find_map(|shape| pay_text(shape, button)), + _ => None, + } + } + + with_isolated_data_dir(|| { + let (_runtime, app_context) = fresh_app_context(); + app_context.set_user_role(dash_evo_tool::model::user_role::UserRole::Power); + let (hub, _) = hub_with_bao_selected(&app_context, WIDE, None); + let heading = hub.get_by_label(DETAIL_HEADING).rect(); + let button = hub + .query_all_by_role_and_label(Role::Button, "Pay") + .map(|node| node.rect()) + .find(|rect| rect.left() >= heading.left() - EPSILON && rect.top() > heading.bottom()) + .expect("Pay in the contact detail pane"); + let text = hub + .output() + .shapes + .iter() + .find_map(|shape| pay_text(&shape.shape, button)) + .expect("painted Pay label"); + assert!( + (text.center().x - button.center().x).abs() <= 1.5, + "Pay must be centered: text {text:?}, button {button:?}" + ); + }); +} + /// The note writes the Save note click dispatched. fn saved_notes(hub: &HubHarness) -> Vec<(Identifier, ContactInfoField>)> { hub.state() From a72db921d96aaefcc029f06996e5aec2e16c68bc Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 20 Oct 2026 08:57:00 +0000 Subject: [PATCH 17/73] fix(identity): address contact note review findings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Serialize contact-info writes across UI surfaces and preserve visibility in note-only updates. Carry owner/contact correlation through initialization, join and bare task failures. Keep confirmed notes across stale reloads until observed, and estimate fees using the encrypted payload limit. Clarify offline memo behavior and cover long usernames in narrow Home layouts. Validation: 164 targeted tests passed; scoped Clippy, formatter and four CLI smoke checks passed. Native desktop checks covered long usernames in light and dark themes with isolated synthetic data. No transactions submitted. 🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent Co-Authored-By: Codex GPT-6 --- docs/user-stories.md | 6 +- src/app.rs | 51 ++++++++++++++- src/backend_task/dashpay/contact_info.rs | 62 +++++++++++++----- src/backend_task/dashpay/contact_requests.rs | 14 +++-- src/backend_task/dashpay/validation.rs | 4 +- src/backend_task/mod.rs | 35 ++++++++++- src/context/contact_info_writes.rs | 66 ++++++++++++++++++++ src/context/mod.rs | 4 ++ src/model/dashpay.rs | 27 ++++---- src/model/fee_estimation.rs | 60 ++++-------------- src/ui/dashpay/contact_details.rs | 13 +++- src/ui/identity/contacts.rs | 17 +++-- src/ui/identity/hub_screen.rs | 14 ++++- src/ui/state/contacts_view.rs | 53 +++++++++++++++- tests/kittest/identity_home.rs | 38 +++++++++++ tests/kittest/identity_hub_contact_detail.rs | 37 ++++++++++- 16 files changed, 397 insertions(+), 104 deletions(-) create mode 100644 src/context/contact_info_writes.rs diff --git a/docs/user-stories.md b/docs/user-stories.md index 922021aa3..b76c76fad 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -1079,8 +1079,10 @@ As a user, I want to edit contact details (nickname, note, hidden status) so tha declining or cancelling a request. If another client saved details this app cannot read, the app warns that continuing will replace those details and asks for confirmation before unhiding. - The Identity Hub contact details edit the private note, which is saved encrypted on Dash - Platform; the estimated fee is shown before saving, and the saved note loads with the contact. -- Changes persist locally. + Platform; a conservative fee estimate is shown before saving, and the saved note loads with + the contact from the network. Hub notes are not copied to the local memo: offline views and + legacy DashPay screens can continue to show an older local note. +- Edits made through the legacy contact-details screen persist in its local memo. ### DPY-010: Remove a contact [Gap] **Persona:** Alex, Priya diff --git a/src/app.rs b/src/app.rs index 7a38cef56..e5b6a43a0 100644 --- a/src/app.rs +++ b/src/app.rs @@ -801,6 +801,46 @@ mod backend_task_join_tests { ); } + #[tokio::test] + async fn contact_info_join_failures_keep_the_dispatched_owner_and_contact() { + use crate::backend_task::dashpay::DashPayTask; + use crate::context::test_support::bare_user_identity; + use crate::model::dashpay::ContactInfoUpdate; + let owner = Identifier::from([0x42; 32]); + let contact = Identifier::from([0x43; 32]); + let task = BackendTask::DashPayTask(Box::new(DashPayTask::UpdateContactInfo { + identity: bare_user_identity(owner, Network::Testnet), + contact_id: contact, + update: ContactInfoUpdate::note(Some("Saved".into())), + })); + for cancel in [false, true] { + let context = BackendTaskContext::for_dispatch_on(&task, Network::Testnet); + let (tx, mut rx) = tokio::sync::mpsc::channel(1); + let handle = tokio::spawn(async move { + if cancel { + std::future::pending::<()>().await; + } + panic!("contact-info task panic"); + }); + if cancel { + handle.abort(); + } + forward_backend_task_join_error( + handle.await, + SenderAsync::new(tx, egui::Context::default()), + None, + context.clone(), + ) + .await; + let result = rx.recv().await.expect("forwarded error"); + assert!(matches!(result, TaskResult::Error { + context: received, + error: TaskError::DashPayContactInfoActionFailed { identity_id, contact_id, source }, + } if received == context && identity_id == owner && contact_id == contact + && matches!(*source, TaskError::BackendTaskFailed { .. }))); + } + } + #[tokio::test] async fn panicking_paid_contact_action_keeps_its_request_correlation() { let (tx, mut rx) = tokio::sync::mpsc::channel(1); @@ -1201,12 +1241,17 @@ async fn forward_backend_task_join_error( let stopped = TaskError::BackendTaskFailed { source: source.into(), }; - let error = match request_id { - Some(request_id) => TaskError::DashPayContactRequestActionFailed { + let error = match (context.dashpay_contact_info_target(), request_id) { + (Some((identity_id, contact_id)), _) => TaskError::DashPayContactInfoActionFailed { + identity_id, + contact_id, + source: Box::new(stopped), + }, + (None, Some(request_id)) => TaskError::DashPayContactRequestActionFailed { request_id, source: Box::new(stopped), }, - None => stopped, + (None, None) => stopped, }; if let Err(error) = sender.send(TaskResult::Error { context, error }).await { tracing::error!(%error, "Failed to report a stopped backend task"); diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 6d5b2ca80..0245210a1 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -160,7 +160,8 @@ fn apply_contact_info_update( existing: Option<&Document>, private_data_key: &[u8; 32], ) -> Result { - let preserves_existing = matches!(update.nickname, ContactInfoField::Preserve) + let preserves_existing = matches!(update.display_hidden, ContactInfoField::Preserve) + || matches!(update.nickname, ContactInfoField::Preserve) || matches!(update.note, ContactInfoField::Preserve) || matches!(update.accepted_accounts, AcceptedAccounts::Preserve); @@ -176,7 +177,9 @@ fn apply_contact_info_update( if let ContactInfoField::Replace(note) = update.note { data.note = note; } - data.display_hidden = update.display_hidden; + if let ContactInfoField::Replace(hidden) = update.display_hidden { + data.display_hidden = hidden; + } if let AcceptedAccounts::Replace(accounts) = update.accepted_accounts { data.accepted_accounts = accounts; } @@ -566,6 +569,8 @@ pub async fn create_or_update_contact_info( ) -> Result { let dashpay_contract = app_context.dashpay_contract.clone(); let identity_id = identity.identity.id(); + // Every direct, legacy, decline and cancel writer enters through this seam. + let _write = app_context.contact_info_writes.acquire(identity_id).await; let lookup = lookup_contact_info(app_context, sdk, &identity, contact_user_id).await?; let (found_existing_doc, derivation_index, enc_user_id_key, private_data_key) = match lookup.existing { @@ -1045,24 +1050,29 @@ mod tests { } } - /// The fee shown before a save is sized from the bytes the write sends. #[test] - fn the_fee_is_sized_from_the_encoded_contact_details() { + fn contact_info_fee_estimate_covers_preserved_accounts() { use crate::model::fee_estimation::PlatformFeeEstimator; - use platform_wallet::wallet::identity::crypto as upstream; + let estimator = PlatformFeeEstimator::new(); for len in [0, 252, 253, 255] { - let text = (len > 0).then(|| "x".repeat(len)); - let encoded = upstream::encode_private_data(&upstream::ContactInfoPrivateData { - alias_name: text.clone(), - note: text, - display_hidden: false, - accepted_accounts: vec![0], - }); - assert_eq!( - PlatformFeeEstimator::contact_info_plaintext_bytes(len, len), - encoded.len(), - "{len}-byte nickname and note" - ); + for accounts in [0, 1, 16, 252, 253, 400, 500] { + let text = (len > 0).then(|| "x".repeat(len)); + let data = ContactInfoPrivateData { + alias_name: text.clone(), + note: text, + accepted_accounts: (0..accounts).collect(), + ..Default::default() + }; + let Ok(encoded) = data.serialize() else { + continue; + }; + let encrypted = encrypt_private_data(&encoded, &KEY).unwrap(); + assert!( + estimator.estimate_contact_info_write() + >= estimator.estimate_document_create_with_size(112 + encrypted.len()), + "{len}-byte fields and {accounts} accounts" + ); + } } } @@ -1277,6 +1287,24 @@ mod tests { assert!(ContactInfoPrivateData::deserialize(&bytes).is_none()); } + #[test] + fn contact_info_note_preserves_a_concurrent_visibility_change() { + let existing = stored_contact_info(vec![0, 4, 9], &KEY); + let data = apply_contact_info_update( + ContactInfoUpdate::note(Some("New note".into())), + Some(&existing), + &KEY, + ) + .unwrap(); + assert!( + data.display_hidden, + "note edits must keep the latest stored visibility" + ); + assert_eq!(data.note.as_deref(), Some("New note")); + assert_eq!(data.alias_name.as_deref(), Some("Bao")); + assert_eq!(data.accepted_accounts, vec![0, 4, 9]); + } + #[test] fn visibility_update_preserves_every_unrelated_stored_field() { let existing = stored_contact_info(vec![0, 4, 9], &KEY); diff --git a/src/backend_task/dashpay/contact_requests.rs b/src/backend_task/dashpay/contact_requests.rs index 50873710e..33d91e4d1 100644 --- a/src/backend_task/dashpay/contact_requests.rs +++ b/src/backend_task/dashpay/contact_requests.rs @@ -1275,6 +1275,7 @@ pub async fn cancel_contact_request( #[cfg(test)] mod tests { use super::*; + use crate::model::dashpay::ContactInfoField; use dash_sdk::dpp::document::DocumentV0; fn id(byte: u8) -> Identifier { @@ -1574,7 +1575,10 @@ mod tests { .lock() .expect("not poisoned") .iter() - .map(|update| update.display_hidden) + .map(|update| match update.display_hidden { + ContactInfoField::Replace(hidden) => hidden, + ContactInfoField::Preserve => panic!("expected an explicit visibility change"), + }) .collect() } @@ -1631,7 +1635,9 @@ mod tests { .lock() .expect("not poisoned") .push(update.clone()); - *self.contact_hidden.lock().expect("not poisoned") = update.display_hidden; + if let ContactInfoField::Replace(hidden) = update.display_hidden { + *self.contact_hidden.lock().expect("not poisoned") = hidden; + } Ok(()) } @@ -1652,7 +1658,7 @@ mod tests { assert_eq!(update.nickname, ContactInfoField::Preserve); assert_eq!(update.note, ContactInfoField::Preserve); assert_eq!(update.accepted_accounts, AcceptedAccounts::Preserve); - assert_eq!(update.display_hidden, hidden); + assert_eq!(update.display_hidden, ContactInfoField::Replace(hidden)); } #[tokio::test] @@ -1810,7 +1816,7 @@ mod tests { } async fn update_contact_info(&self, update: ContactInfoUpdate) -> Result<(), TaskError> { - assert!(update.display_hidden); + assert_eq!(update.display_hidden, ContactInfoField::Replace(true)); *self.hidden.lock().expect("not poisoned") = true; *self.hidden_writes.lock().expect("not poisoned") += 1; Ok(()) diff --git a/src/backend_task/dashpay/validation.rs b/src/backend_task/dashpay/validation.rs index 3844ce929..7942664a6 100644 --- a/src/backend_task/dashpay/validation.rs +++ b/src/backend_task/dashpay/validation.rs @@ -321,7 +321,9 @@ pub fn validate_contact_info_field_sizes( } // Validate privateData (48-2048 bytes) - if private_data.len() < 48 || private_data.len() > 2048 { + if private_data.len() < 48 + || private_data.len() > crate::model::dashpay::MAX_CONTACT_INFO_ENCRYPTED_BYTES + { validation.add_error(format!( "privateData must be 48-2048 bytes, got {}", private_data.len() diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index 82284a873..b107c32b2 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -349,6 +349,11 @@ pub enum BackendTaskContext { TokenBalanceRefresh, /// A DashPay social-profile update for one identity. DashPayProfileUpdate(Identifier), + /// A direct contact-details write, including failures before its handler runs. + DashPayContactInfoUpdate { + identity_id: Identifier, + contact_id: Identifier, + }, /// A top-up of one identity's balance. IdentityTopUp(Identifier), /// A perpetual-reward estimate for one identity-token pair. @@ -513,6 +518,17 @@ impl BackendTaskContext { matches!(self.operation(), Self::FetchDocumentsPage(_)) } + /// Identify the direct contact write through dispatch wrappers. + pub(crate) fn dashpay_contact_info_target(&self) -> Option<(Identifier, Identifier)> { + match self.operation() { + Self::DashPayContactInfoUpdate { + identity_id, + contact_id, + } => Some((*identity_id, *contact_id)), + _ => None, + } + } + pub(crate) fn dashpay_profile_update_identity(&self) -> Option { match self.operation() { Self::DashPayProfileUpdate(identity_id) => Some(*identity_id), @@ -638,6 +654,14 @@ impl From<&BackendTask> for BackendTaskContext { DashPayTask::UpdateProfile { identity, .. } => { Self::DashPayProfileUpdate(identity.identity.id()) } + DashPayTask::UpdateContactInfo { + identity, + contact_id, + .. + } => Self::DashPayContactInfoUpdate { + identity_id: identity.identity.id(), + contact_id: *contact_id, + }, _ => Self::Other, }, BackendTask::IdentityTask(IdentityTask::CheckLegacyRecovery { identity_id }) => { @@ -1330,7 +1354,14 @@ impl AppContext { // other init error is a transient deferral the cold-boot bridge // retries. if is_terminal_storage_open_error(&e) { - return Err(e); + return Err(match dashpay_contact_info_target(&task) { + Some((identity_id, contact_id)) => TaskError::DashPayContactInfoActionFailed { + identity_id, + contact_id, + source: Box::new(e), + }, + None => e, + }); } tracing::warn!(error = %e, "Wallet backend initialization deferred"); } @@ -2520,7 +2551,7 @@ mod tests { BackendTask::DashPayTask(Box::new(DashPayTask::UpdateContactInfo { identity: owner, contact_id, - update: crate::model::dashpay::ContactInfoUpdate::note(None, false), + update: crate::model::dashpay::ContactInfoUpdate::note(None), })), SenderAsync::new(tx, ctx.egui_ctx().clone()), ) diff --git a/src/context/contact_info_writes.rs b/src/context/contact_info_writes.rs new file mode 100644 index 000000000..8d6e17c99 --- /dev/null +++ b/src/context/contact_info_writes.rs @@ -0,0 +1,66 @@ +//! Serializes contact-info read/modify/write operations across UI surfaces. + +use dash_sdk::platform::Identifier; +use std::collections::HashMap; +use std::sync::{Arc, Mutex, Weak}; +use tokio::sync::{Mutex as AsyncMutex, OwnedMutexGuard}; + +/// Owner-wide locking also protects allocation of new contact derivation indexes. +#[derive(Debug, Default)] +pub(crate) struct ContactInfoWrites { + owners: Mutex>>>, +} + +impl ContactInfoWrites { + /// Hold through the network read, merge and confirmed document write. + pub(crate) async fn acquire(&self, owner: Identifier) -> OwnedMutexGuard<()> { + let gate = { + let mut owners = self + .owners + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + owners.retain(|_, gate| gate.strong_count() > 0); + match owners.get(&owner).and_then(Weak::upgrade) { + Some(gate) => gate, + None => { + let gate = Arc::new(AsyncMutex::new(())); + owners.insert(owner, Arc::downgrade(&gate)); + gate + } + } + }; + gate.lock_owned().await + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::task::Poll; + + #[tokio::test] + async fn contact_info_writes_serialize_each_owner_and_release_after_cancellation() { + let writes = ContactInfoWrites::default(); + let owner = Identifier::from([1; 32]); + let first = writes.acquire(owner).await; + let mut queued = Box::pin(writes.acquire(owner)); + assert!(matches!(futures::poll!(&mut queued), Poll::Pending)); + let other_owner = writes.acquire(Identifier::from([2; 32])).await; + drop(queued); + let mut next = Box::pin(writes.acquire(owner)); + assert!(matches!(futures::poll!(&mut next), Poll::Pending)); + drop(first); + let next = next.await; + let mut last = Box::pin(writes.acquire(owner)); + assert!(matches!(futures::poll!(&mut last), Poll::Pending)); + drop(next); + drop(last.await); + drop(other_owner); + drop(writes.acquire(owner).await); + assert_eq!( + writes.owners.lock().unwrap().len(), + 1, + "unused gates are pruned" + ); + } +} diff --git a/src/context/mod.rs b/src/context/mod.rs index d5a2a5139..980eac55c 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -1,4 +1,5 @@ pub mod connection_status; +mod contact_info_writes; mod contested_names_db; mod contract_token_db; mod dpns_vote_attention; @@ -277,6 +278,8 @@ pub struct AppContext { /// Process-local claim shared by every UI surface before a paid DashPay /// request action enters its backend flow. contact_request_actions_in_flight: Mutex>, + /// Shared across all contact-info writers on this network. + pub(crate) contact_info_writes: contact_info_writes::ContactInfoWrites, /// Serializes operation journal writes and target-lock acquisition. dpns_vote_operation_guard: Mutex<()>, /// Bumped under `dpns_vote_operation_guard` when a removed voter is loaded @@ -636,6 +639,7 @@ impl AppContext { #[cfg(feature = "testing")] test_network_switch_gate: tokio::sync::Mutex::new(()), contact_request_actions_in_flight: Mutex::new(HashSet::new()), + contact_info_writes: Default::default(), dpns_vote_operation_guard: Mutex::new(()), dpns_voter_lifecycles: Mutex::default(), dpns_vote_dispatch: DpnsVoteDispatchCoordinator::default(), diff --git a/src/model/dashpay.rs b/src/model/dashpay.rs index 55ea411a0..a61e52098 100644 --- a/src/model/dashpay.rs +++ b/src/model/dashpay.rs @@ -25,6 +25,8 @@ pub fn validate_account_label(label: &str) -> Result<(), TextLengthError> { /// Application limit for a contact's private note, in UTF-8 bytes. /// The encrypted `contactInfo` payload encodes its length with CompactSize. pub const MAX_CONTACT_NOTE_BYTES: usize = u8::MAX as usize; +/// DashPay contract limit for the encrypted contact-info payload, including its IV. +pub const MAX_CONTACT_INFO_ENCRYPTED_BYTES: usize = 2048; /// A private contact note exceeds the application's size limit. #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] @@ -132,8 +134,8 @@ pub struct ContactInfoUpdate { pub nickname: ContactInfoField>, /// Note update intent. pub note: ContactInfoField>, - /// New hidden state. - pub display_hidden: bool, + /// Visibility update intent. + pub display_hidden: ContactInfoField, /// Accepted-account update intent. pub accepted_accounts: AcceptedAccounts, /// Policy for a present payload that cannot be read. @@ -146,19 +148,18 @@ impl ContactInfoUpdate { Self { nickname: ContactInfoField::Preserve, note: ContactInfoField::Preserve, - display_hidden, + display_hidden: ContactInfoField::Replace(display_hidden), accepted_accounts: AcceptedAccounts::Preserve, unreadable: UnreadableContactInfoPolicy::Abort, } } - /// Replace the private note, preserving the nickname and accepted accounts. - /// `display_hidden` must carry the contact's current hidden state, since the - /// whole document is rewritten. - pub fn note(note: Option, display_hidden: bool) -> Self { + /// Replace only the private note, preserving the latest stored contact details. + pub fn note(note: Option) -> Self { Self { note: ContactInfoField::Replace(note), - ..Self::visibility(display_hidden) + display_hidden: ContactInfoField::Preserve, + ..Self::visibility(false) } } @@ -172,7 +173,7 @@ impl ContactInfoUpdate { Self { nickname: ContactInfoField::Replace(nickname), note: ContactInfoField::Replace(note), - display_hidden, + display_hidden: ContactInfoField::Replace(display_hidden), accepted_accounts: AcceptedAccounts::Replace(accepted_accounts), unreadable: UnreadableContactInfoPolicy::Abort, } @@ -515,19 +516,19 @@ mod tests { #[test] fn a_note_update_replaces_only_the_note() { - let update = ContactInfoUpdate::note(Some("Met at the meetup".into()), true); + let update = ContactInfoUpdate::note(Some("Met at the meetup".into())); assert_eq!( update.note, ContactInfoField::Replace(Some("Met at the meetup".into())) ); assert_eq!(update.nickname, ContactInfoField::Preserve); assert_eq!(update.accepted_accounts, AcceptedAccounts::Preserve); - assert!(update.display_hidden, "the contact's hidden state is kept"); + assert_eq!(update.display_hidden, ContactInfoField::Preserve); assert_eq!(update.unreadable, UnreadableContactInfoPolicy::Abort); - let cleared = ContactInfoUpdate::note(None, false); + let cleared = ContactInfoUpdate::note(None); assert_eq!(cleared.note, ContactInfoField::Replace(None)); - assert!(!cleared.display_hidden); + assert_eq!(cleared.display_hidden, ContactInfoField::Preserve); } #[test] diff --git a/src/model/fee_estimation.rs b/src/model/fee_estimation.rs index 8e8100419..e5a697c23 100644 --- a/src/model/fee_estimation.rs +++ b/src/model/fee_estimation.rs @@ -707,38 +707,14 @@ impl PlatformFeeEstimator { self.estimate_document_replace_with_size(200) } - /// Estimate the fee for writing a contact's encrypted DashPay `contactInfo` - /// document holding a nickname and a private note of the given UTF-8 sizes. - /// Creating and replacing the document cost the same here. - pub fn estimate_contact_info_write(&self, nickname_bytes: usize, note_bytes: usize) -> u64 { - // Document fields: encToUserId (32), the two key indexes (8), and the - // id, owner and revision every document carries (72). + /// Conservative fee estimate for a contact-info write, including all preserved + /// accounts. The UI does not have their count, so use the contract payload limit. + pub fn estimate_contact_info_write(&self) -> u64 { + // encToUserId (32), key indexes (8), document ID, owner and revision (72). const FIXED_DOCUMENT_BYTES: usize = 112; - const AES_BLOCK: usize = 16; - let plaintext = Self::contact_info_plaintext_bytes(nickname_bytes, note_bytes); - // A random IV, then the plaintext PKCS#7-padded to whole blocks. - let private_data = AES_BLOCK.saturating_add( - (plaintext / AES_BLOCK) - .saturating_add(1) - .saturating_mul(AES_BLOCK), - ); - self.estimate_document_create_with_size(FIXED_DOCUMENT_BYTES.saturating_add(private_data)) - } - - /// Size of a contact's DIP-15 `contactInfo` private data before - /// encryption, with one accepted account. - pub fn contact_info_plaintext_bytes(nickname_bytes: usize, note_bytes: usize) -> usize { - // Version (4), hidden flag (1), one accepted account with its count (5). - const FIXED_PAYLOAD_BYTES: usize = 10; - // Short payloads are zero-padded so the encrypted field meets the - // contract's 48-byte minimum. - const MIN_PLAINTEXT_BYTES: usize = 17; - // A CompactSize length prefix: one byte below 253, three up to 65535. - let prefixed = |len: usize| len.saturating_add(if len < 0xFD { 1 } else { 3 }); - FIXED_PAYLOAD_BYTES - .saturating_add(prefixed(nickname_bytes)) - .saturating_add(prefixed(note_bytes)) - .max(MIN_PLAINTEXT_BYTES) + self.estimate_document_create_with_size( + FIXED_DOCUMENT_BYTES + crate::model::dashpay::MAX_CONTACT_INFO_ENCRYPTED_BYTES, + ) } /// Estimate fee for document transfer. @@ -1372,25 +1348,15 @@ mod tests { use super::*; #[test] - fn contact_info_write_fee_covers_a_document_and_grows_with_the_note() { + fn contact_info_write_fee_covers_the_contract_limit_and_fee_multiplier() { let estimator = PlatformFeeEstimator::new(); - let empty = estimator.estimate_contact_info_write(0, 0); - assert!( - empty >= estimator.estimate_document_create_with_size(0), - "a contactInfo write is at least a document write" - ); - let full = estimator.estimate_contact_info_write(0, 255); - assert!(full > empty, "a longer note stores more bytes"); - assert!( - estimator.estimate_contact_info_write(10, 255) >= full, - "the nickname is stored too" + assert_eq!( + estimator.estimate_contact_info_write(), + estimator.estimate_document_create_with_size(112 + 2048), ); assert_eq!( - PlatformFeeEstimator::with_fee_multiplier(2000).estimate_contact_info_write(0, 255), - estimator - .estimate_contact_info_write(0, 255) - .saturating_mul(2), - "the network's fee multiplier applies" + PlatformFeeEstimator::with_fee_multiplier(2000).estimate_contact_info_write(), + estimator.estimate_contact_info_write().saturating_mul(2), ); } diff --git a/src/ui/dashpay/contact_details.rs b/src/ui/dashpay/contact_details.rs index fca29a1de..8289eb575 100644 --- a/src/ui/dashpay/contact_details.rs +++ b/src/ui/dashpay/contact_details.rs @@ -187,7 +187,7 @@ impl ContactDetailsScreen { } else { Some(self.edit_note.clone()) }), - display_hidden: self.edit_hidden, + display_hidden: ContactInfoField::Replace(self.edit_hidden), accepted_accounts: AcceptedAccounts::Preserve, unreadable: Default::default(), }; @@ -226,10 +226,17 @@ impl ContactDetailsScreen { ContactInfoField::Replace(value) => value, }; + let hidden = match update.display_hidden { + ContactInfoField::Preserve => self + .contact_info + .as_ref() + .is_some_and(|info| info.is_hidden), + ContactInfoField::Replace(hidden) => hidden, + }; if let Some(info) = &mut self.contact_info { info.nickname = nickname.clone(); info.note = note.clone(); - info.is_hidden = update.display_hidden; + info.is_hidden = hidden; } let identity_id = self.identity.identity.id(); @@ -239,7 +246,7 @@ impl ContactDetailsScreen { &self.contact_id, nickname.unwrap_or_default(), note.unwrap_or_default(), - update.display_hidden, + hidden, ) { tracing::warn!("DashPay private-info sidecar write failed after Platform save: {e:?}"); } diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index e525dbcba..b8990febb 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -301,13 +301,13 @@ pub fn save_note_task( DashPayTask::UpdateContactInfo { identity, contact_id: contact.identity_id, - update: ContactInfoUpdate::note(note, contact.is_hidden), + update: ContactInfoUpdate::note(note), } } /// The fee line shown beside Save note. pub fn note_fee_text(fee: &str) -> String { - format!("Saving this note costs about {fee}.") + format!("Estimated fee for saving this note: up to {fee}.") } /// Dispatch the save of the selected contact's note draft, if it has a valid @@ -732,9 +732,7 @@ fn note_editor( } ui.add_space(8.0); - let fee = app_context - .fee_estimator() - .estimate_contact_info_write(contact.nickname.as_deref().map_or(0, str::len), note_bytes); + let fee = app_context.fee_estimator().estimate_contact_info_write(); ui.label( RichText::new(note_fee_text(&format_credits_as_dash(fee))) .small() @@ -1200,6 +1198,7 @@ pub(super) fn render_preview( #[cfg(test)] mod tests { use super::*; + use crate::model::dashpay::ContactInfoField; use crate::model::qualified_identity::{IdentityStatus, IdentityType}; use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::identity::Identity; @@ -1425,7 +1424,7 @@ mod tests { BackendTask::DashPayTask(Box::new(task)), )); assert_eq!((owner, contact_id), (id(1), id(5))); - assert_eq!(update, ContactInfoUpdate::note(Some("Bao".into()), true)); + assert_eq!(update, ContactInfoUpdate::note(Some("Bao".into()))); } #[test] @@ -1499,7 +1498,7 @@ mod tests { let (_, contact_id, update) = saved_note(dispatch_unhide(&mut state, &identity, &hidden_bao())); assert_eq!(contact_id, id(5)); - assert!(!update.display_hidden); + assert_eq!(update.display_hidden, ContactInfoField::Replace(false)); assert_eq!( dispatch_unhide(&mut state, &identity, &hidden_bao()), AppAction::None, @@ -1545,7 +1544,7 @@ mod tests { fn the_fee_line_is_one_sentence_with_the_amount() { assert_eq!( note_fee_text("0.0001 DASH"), - "Saving this note costs about 0.0001 DASH." + "Estimated fee for saving this note: up to 0.0001 DASH." ); } @@ -1710,7 +1709,7 @@ mod tests { assert_eq!(identity.identity.id(), id(1)); assert_eq!(contact_id, id(5), "the clicked contact must be unhidden"); assert!( - !update.display_hidden, + update.display_hidden == ContactInfoField::Replace(false), "unhiding must broadcast contactInfo with the hidden flag cleared" ); } diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index 4f9560184..582b589eb 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -906,6 +906,18 @@ impl ScreenLike for IdentityHubScreen { } fn display_backend_task_error(&mut self, context: &BackendTaskContext, error: &TaskError) { + // Wrapped errors retain the unreadable-details confirmation flow. + if !matches!(error, TaskError::DashPayContactInfoActionFailed { .. }) + && let Some((identity_id, contact_id)) = context.dashpay_contact_info_target() + { + self.pending_contact_info_tasks + .remove(&ContactInfoTaskKey::Direct { + identity_id, + contact_id, + }); + self.contacts_state + .release_contact_info_write(&identity_id, &contact_id); + } if matches!(error, TaskError::MasternodeListNotReady { .. }) { self.profile_cache.record_error_while_syncing(context); } else { @@ -2231,7 +2243,7 @@ mod tests { fn a_saved_note_and_an_unhide_confirm_differently() { use crate::model::dashpay::ContactInfoUpdate; - let note = contact_info_task(ContactInfoUpdate::note(Some("Bao".into()), false)); + let note = contact_info_task(ContactInfoUpdate::note(Some("Bao".into()))); let unhide = contact_info_task(ContactInfoUpdate::visibility(false)); assert!(is_note_save(¬e)); assert!(!is_note_save(&unhide)); diff --git a/src/ui/state/contacts_view.rs b/src/ui/state/contacts_view.rs index 63cb979b9..68edd62d0 100644 --- a/src/ui/state/contacts_view.rs +++ b/src/ui/state/contacts_view.rs @@ -56,6 +56,8 @@ pub struct ContactsState { /// Whether `contacts` holds a loaded list, not the empty one before the /// first load lands. contacts_known: bool, + /// Confirmed notes override lagging reads until the network returns them. + confirmed_notes: HashMap<(Identifier, Identifier), Option>, /// Established contacts flagged `display_hidden`, kept aside so the tab can /// offer a way back. Declining or cancelling a request hides that person, /// so without this list a contact could only be recovered from the legacy @@ -190,7 +192,19 @@ impl ContactsState { /// out of the active list — that is what "hidden" promises — but remain /// reachable through [`ContactsState::hidden_contacts`]. The selected /// contact's note draft follows the reloaded note. - pub fn record_contacts(&mut self, contacts: Vec) { + pub fn record_contacts(&mut self, mut contacts: Vec) { + if let Some(owner) = self.owner_id() { + for contact in &mut contacts { + let key = (owner, contact.identity_id); + if let Some(confirmed) = self.confirmed_notes.get(&key) { + if &contact.note == confirmed { + self.confirmed_notes.remove(&key); + } else { + contact.note.clone_from(confirmed); + } + } + } + } let (hidden, visible) = contacts.into_iter().partition(|c| c.is_hidden); self.contacts = visible; self.hidden = hidden; @@ -339,6 +353,10 @@ impl ContactsState { let Some(write) = self.detail.finish_write(owner, contact_id) else { return false; }; + if let PendingWrite::Note(note) = &write { + self.confirmed_notes + .insert((*owner, *contact_id), note.clone()); + } if let PendingWrite::Note(note) = write && self.owner_id() == Some(*owner) && let Some(contact) = self @@ -545,6 +563,39 @@ mod tests { ); } + #[test] + fn confirmed_note_survives_stale_reload_and_tab_reset_until_observed() { + for note in [Some("Confirmed"), None] { + let mut state = owned_state(1); + let stale = ContactData { + note: Some("Old note".into()), + ..contact(Some("Bao"), None, None) + }; + state.record_contacts(vec![stale.clone()]); + state.select_contact(&id(7)); + *state.detail_mut().note_mut(&id(7)).unwrap() = note.unwrap_or_default().into(); + assert!(state.detail_mut().begin_save(id(1), id(7)).is_some()); + assert!(state.finish_contact_info_write(&id(1), &id(7))); + state.reset(); + state.record_contacts(vec![stale.clone()]); + state.select_contact(&id(7)); + assert_eq!(state.selected_contact().unwrap().note.as_deref(), note); + assert!(!state.detail().is_dirty(&id(7))); + state.record_contacts(vec![ContactData { + note: note.map(str::to_string), + ..stale.clone() + }]); + state.record_contacts(vec![ContactData { + note: Some("Later remote edit".into()), + ..stale + }]); + assert_eq!( + state.selected_contact().unwrap().note.as_deref(), + Some("Later remote edit") + ); + } + } + #[test] fn a_note_saved_for_another_identity_leaves_these_lists_alone() { let mut state = owned_state(1); diff --git a/tests/kittest/identity_home.rs b/tests/kittest/identity_home.rs index da25cd330..d4db06758 100644 --- a/tests/kittest/identity_home.rs +++ b/tests/kittest/identity_home.rs @@ -432,6 +432,44 @@ fn home_profile_avatar_requests_its_image() { }); } +#[test] +fn home_header_long_usernames_stay_above_balance_at_narrow_widths() { + with_isolated_data_dir(|| { + let (_runtime, ctx) = fresh_app_context(); + let name = "a".repeat(63); + super::identity_usernames::seed_username_identity( + &ctx, + 0xB4, + "Alex", + &[&name, &"b".repeat(63), &"c".repeat(63)], + 0, + true, + ); + let mut harness = mount_home(ctx); + for width in [360.0, 520.0, 800.0] { + harness.set_size(egui::vec2(width, 900.0)); + harness.run(); + let names = harness.get_by_label_contains(&format!("@{name}")).rect(); + let add = harness.get_by_label("Add username").rect(); + let balance = harness.get_by_label("Identity balance").rect(); + if width < 640.0 { + assert!( + names.bottom() <= balance.top(), + "names {names:?} overlap balance {balance:?}" + ); + assert!( + add.bottom() <= balance.top(), + "add {add:?} overlaps balance {balance:?}" + ); + } else { + assert!(!names.intersects(balance), "names overlap balance"); + assert!(!add.intersects(balance), "add overlaps balance"); + } + assert!(names.right() <= width, "names exceed viewport: {names:?}"); + } + }); +} + #[test] fn home_username_summary_limits_to_three_and_routes_add_and_overflow() { with_isolated_data_dir(|| { diff --git a/tests/kittest/identity_hub_contact_detail.rs b/tests/kittest/identity_hub_contact_detail.rs index 85c48f117..a4d0027fa 100644 --- a/tests/kittest/identity_hub_contact_detail.rs +++ b/tests/kittest/identity_hub_contact_detail.rs @@ -227,7 +227,7 @@ fn save_note_shows_the_fee_first_and_sends_the_note_once() { let (mut hub, owner) = hub_with_bao_selected(&app_context, WIDE, None); assert!( - hub.query_by_label_contains("Saving this note costs about") + hub.query_by_label_contains("Estimated fee for saving this note: up to") .is_some(), "the fee is shown before the user saves" ); @@ -474,6 +474,41 @@ fn a_note_save_that_failed_behind_another_screen_can_be_retried() { }); } +#[test] +fn bare_contact_info_failure_behind_another_screen_releases_only_its_save() { + use dash_evo_tool::backend_task::error::TaskError; + with_isolated_data_dir(|| { + let runtime = tokio::runtime::Runtime::new().expect("runtime"); + let _guard = runtime.enter(); + let mut app = + crate::support::mount_app(dash_evo_tool::ui::RootScreenType::RootScreenWalletsBalances); + let (mut hub, _, context) = hub_saving_a_note(&app); + hub.state_mut() + .0 + .display_backend_task_error(&BackendTaskContext::Other, &TaskError::WalletLocked); + hub.run_steps(2); + assert!( + hub.query_by_label(SAVING_NOTE_LABEL).is_some(), + "unrelated errors keep the guard" + ); + crate::identity_hub::loads::receive_task_results_behind_the_send_screen( + &runtime, + &mut app, + &mut hub, + vec![dash_evo_tool::app::TaskResult::Error { + context, + error: TaskError::WalletLocked, + }], + ); + hub.run_steps(2); + assert!(hub.query_by_label(SAVING_NOTE_LABEL).is_none()); + hub.get_by_role_and_label(Role::Button, SAVE_NOTE_LABEL) + .click(); + hub.run_steps(2); + assert_eq!(saved_notes(&hub).len(), 1); + }); +} + #[test] fn unreadable_details_found_behind_another_screen_still_ask_first() { use dash_evo_tool::backend_task::error::{ContactInfoReadError, TaskError}; From 863d1efb594fe981c242f59070677d814974b1b7 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 20 Oct 2026 13:38:44 +0000 Subject: [PATCH 18/73] fix(identity): preserve contact write lifecycle and visibility MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep contact-info guards until task completion, serialize request-action reads and decisions with writes, reject nonzero padding, and restore hidden contacts after failed unhide operations. Validated with 116 targeted unit/UI tests, scoped Clippy and formatting. 🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent Co-Authored-By: Codex GPT-6 --- src/backend_task/dashpay/contact_info.rs | 50 +++++++- src/backend_task/dashpay/contact_requests.rs | 127 +++++++++++++++++-- src/ui/state/contact_detail_view.rs | 41 +++--- src/ui/state/contacts_view.rs | 39 +++++- tests/kittest/identity_hub_contact_detail.rs | 80 ++++++++++++ 5 files changed, 306 insertions(+), 31 deletions(-) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 0245210a1..aa03755d2 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -78,7 +78,7 @@ impl ContactInfoPrivateData { /// /// Returns `None` for a truncated or non-canonical v0 payload, invalid /// UTF-8, or an unsupported version. The only accepted trailing bytes are - /// padding up to [`Self::MIN_PLAINTEXT_SIZE`] that starts with a zero. + /// zero padding up to [`Self::MIN_PLAINTEXT_SIZE`]. /// Stricter than platform-wallet's reader: a write must never drop fields /// it cannot read. pub fn deserialize(bytes: &[u8]) -> Option { @@ -139,7 +139,8 @@ impl ContactInfoPrivateData { .collect::>>()?; if pos < bytes.len() - && (bytes.len() > Self::MIN_PLAINTEXT_SIZE || bytes.get(pos) != Some(&0)) + && (bytes.len() > Self::MIN_PLAINTEXT_SIZE + || bytes[pos..].iter().any(|byte| *byte != 0)) { return None; } @@ -566,11 +567,34 @@ pub async fn create_or_update_contact_info( identity: QualifiedIdentity, contact_user_id: Identifier, update: ContactInfoUpdate, +) -> Result { + let write_guard = app_context + .contact_info_writes + .acquire(identity.identity.id()) + .await; + create_or_update_contact_info_locked( + app_context, + sdk, + identity, + contact_user_id, + update, + &write_guard, + ) + .await +} + +/// Write while the caller holds the owner's lock across its reads and decisions. +/// Request actions acquire their request lock before this owner lock. +pub(super) async fn create_or_update_contact_info_locked( + app_context: &Arc, + sdk: &Sdk, + identity: QualifiedIdentity, + contact_user_id: Identifier, + update: ContactInfoUpdate, + _write_guard: &tokio::sync::OwnedMutexGuard<()>, ) -> Result { let dashpay_contract = app_context.dashpay_contract.clone(); let identity_id = identity.identity.id(); - // Every direct, legacy, decline and cancel writer enters through this seam. - let _write = app_context.contact_info_writes.acquire(identity_id).await; let lookup = lookup_contact_info(app_context, sdk, &identity, contact_user_id).await?; let (found_existing_doc, derivation_index, enc_user_id_key, private_data_key) = match lookup.existing { @@ -1277,6 +1301,24 @@ mod tests { assert!(ContactInfoPrivateData::deserialize(&bytes).is_none()); } + #[test] + fn contact_info_padding_rejects_nonzero_bytes_after_the_sentinel() { + let canonical = ContactInfoPrivateData::new() + .serialize() + .expect("serialize"); + for length in [16, ContactInfoPrivateData::MIN_PLAINTEXT_SIZE] { + assert!(ContactInfoPrivateData::deserialize(&canonical[..length]).is_some()); + for offset in 9..length { + let mut malformed = canonical[..length].to_vec(); + malformed[offset] = 42; + assert!( + ContactInfoPrivateData::deserialize(&malformed).is_none(), + "nonzero padding at {offset} in {length} bytes must require confirmation" + ); + } + } + } + #[test] fn minimum_size_padding_requires_the_sentinel() { let mut bytes = ContactInfoPrivateData::new() diff --git a/src/backend_task/dashpay/contact_requests.rs b/src/backend_task/dashpay/contact_requests.rs index 33d91e4d1..dc6c74fd3 100644 --- a/src/backend_task/dashpay/contact_requests.rs +++ b/src/backend_task/dashpay/contact_requests.rs @@ -837,6 +837,7 @@ trait RejectOps { fn lock_action( &self, ) -> impl Future, TaskError>> + Send; + fn lock_contact_info(&self) -> impl Future> + Send; fn phase(&self) -> Result, TaskError>; fn set_phase(&self, phase: ContactRequestActionPhase) -> Result<(), TaskError>; fn clear_phase(&self) -> Result<(), TaskError>; @@ -847,6 +848,7 @@ trait RejectOps { fn update_contact_info( &self, update: ContactInfoUpdate, + write_guard: &tokio::sync::OwnedMutexGuard<()>, ) -> impl Future> + Send; fn mark_declined(&self) -> Result<(), TaskError>; fn request_id(&self) -> Identifier; @@ -857,6 +859,7 @@ async fn reject_flow( unreadable: UnreadableContactInfoPolicy, ) -> Result { let _action_guard = ops.lock_action().await?; + let contact_info_guard = ops.lock_contact_info().await; let phase = match ops.phase()? { Some(phase) => phase, None => { @@ -867,7 +870,7 @@ async fn reject_flow( if phase == ContactRequestActionPhase::HideIntent { if !ops.contact_is_hidden(unreadable).await? { - ops.update_contact_info(hidden_contact_update(true, unreadable)) + ops.update_contact_info(hidden_contact_update(true, unreadable), &contact_info_guard) .await?; } ops.set_phase(ContactRequestActionPhase::MarkerPending)?; @@ -896,6 +899,13 @@ impl RejectOps for PlatformRejectOps<'_> { .await) } + async fn lock_contact_info(&self) -> tokio::sync::OwnedMutexGuard<()> { + self.app_context + .contact_info_writes + .acquire(self.owner_id) + .await + } + fn phase(&self) -> Result, TaskError> { self.app_context .wallet_backend()? @@ -941,13 +951,18 @@ impl RejectOps for PlatformRejectOps<'_> { .await } - async fn update_contact_info(&self, update: ContactInfoUpdate) -> Result<(), TaskError> { - super::contact_info::create_or_update_contact_info( + async fn update_contact_info( + &self, + update: ContactInfoUpdate, + write_guard: &tokio::sync::OwnedMutexGuard<()>, + ) -> Result<(), TaskError> { + super::contact_info::create_or_update_contact_info_locked( self.app_context, self.sdk, self.identity.clone(), self.from_identity_id, update, + write_guard, ) .await .map(|_| ()) @@ -1011,6 +1026,7 @@ trait CancelOps { fn lock_action( &self, ) -> impl Future, TaskError>> + Send; + fn lock_contact_info(&self) -> impl Future> + Send; fn phase(&self) -> Result, TaskError>; fn set_phase(&self, phase: ContactRequestActionPhase) -> Result<(), TaskError>; fn clear_phase(&self) -> Result<(), TaskError>; @@ -1028,6 +1044,7 @@ trait CancelOps { fn update_contact_info( &self, update: ContactInfoUpdate, + write_guard: &tokio::sync::OwnedMutexGuard<()>, ) -> impl Future> + Send; /// Record the withdrawal in the DET sidecar so the request stops being @@ -1062,6 +1079,7 @@ async fn cancel_flow( unreadable: UnreadableContactInfoPolicy, ) -> Result { let _action_guard = ops.lock_action().await?; + let contact_info_guard = ops.lock_contact_info().await; let mut phase = match ops.phase()? { Some(phase) => phase, None => { @@ -1075,7 +1093,7 @@ async fn cancel_flow( if phase == ContactRequestActionPhase::HideIntent { if !ops.contact_is_hidden(unreadable).await? { - ops.update_contact_info(hidden_contact_update(true, unreadable)) + ops.update_contact_info(hidden_contact_update(true, unreadable), &contact_info_guard) .await?; } ops.set_phase(ContactRequestActionPhase::HideCommitted)?; @@ -1094,8 +1112,11 @@ async fn cancel_flow( if phase == ContactRequestActionPhase::CorrectiveUnhideIntent { if ops.contact_is_hidden(unreadable).await? { - ops.update_contact_info(hidden_contact_update(false, unreadable)) - .await?; + ops.update_contact_info( + hidden_contact_update(false, unreadable), + &contact_info_guard, + ) + .await?; } ops.set_phase(ContactRequestActionPhase::CorrectiveUnhideComplete)?; phase = ContactRequestActionPhase::CorrectiveUnhideComplete; @@ -1132,6 +1153,13 @@ impl CancelOps for PlatformCancelOps<'_> { .await) } + async fn lock_contact_info(&self) -> tokio::sync::OwnedMutexGuard<()> { + self.app_context + .contact_info_writes + .acquire(self.owner_id) + .await + } + fn phase(&self) -> Result, TaskError> { self.app_context .wallet_backend()? @@ -1181,13 +1209,18 @@ impl CancelOps for PlatformCancelOps<'_> { Ok(!Document::fetch_many(self.sdk, query).await?.is_empty()) } - async fn update_contact_info(&self, update: ContactInfoUpdate) -> Result<(), TaskError> { - super::contact_info::create_or_update_contact_info( + async fn update_contact_info( + &self, + update: ContactInfoUpdate, + write_guard: &tokio::sync::OwnedMutexGuard<()>, + ) -> Result<(), TaskError> { + super::contact_info::create_or_update_contact_info_locked( self.app_context, self.sdk, self.identity.clone(), self.to_identity_id, update, + write_guard, ) .await .map(|_| ()) @@ -1541,6 +1574,7 @@ mod tests { #[derive(Default)] struct ScriptedOps { action_lock: Arc>, + contact_info_lock: Arc>, reciprocal: Mutex>>, /// Every contact-info update, in call order. contact_updates: Mutex>, @@ -1596,6 +1630,10 @@ mod tests { Ok(self.action_lock.clone().lock_owned().await) } + async fn lock_contact_info(&self) -> tokio::sync::OwnedMutexGuard<()> { + self.contact_info_lock.clone().lock_owned().await + } + fn phase(&self) -> Result, TaskError> { Ok(*self.phase.lock().expect("not poisoned")) } @@ -1627,7 +1665,11 @@ mod tests { Ok(hidden) } - async fn update_contact_info(&self, update: ContactInfoUpdate) -> Result<(), TaskError> { + async fn update_contact_info( + &self, + update: ContactInfoUpdate, + _write_guard: &tokio::sync::OwnedMutexGuard<()>, + ) -> Result<(), TaskError> { if self.hide_fails { return Err(TaskError::DocumentNotFound); } @@ -1780,6 +1822,7 @@ mod tests { #[derive(Default)] struct ScriptedRejectOps { action_lock: Arc>, + contact_info_lock: Arc>, phase: Mutex>, hidden: Mutex, hidden_writes: Mutex, @@ -1792,6 +1835,10 @@ mod tests { Ok(self.action_lock.clone().lock_owned().await) } + async fn lock_contact_info(&self) -> tokio::sync::OwnedMutexGuard<()> { + self.contact_info_lock.clone().lock_owned().await + } + fn phase(&self) -> Result, TaskError> { Ok(*self.phase.lock().expect("not poisoned")) } @@ -1815,7 +1862,11 @@ mod tests { Ok(hidden) } - async fn update_contact_info(&self, update: ContactInfoUpdate) -> Result<(), TaskError> { + async fn update_contact_info( + &self, + update: ContactInfoUpdate, + _write_guard: &tokio::sync::OwnedMutexGuard<()>, + ) -> Result<(), TaskError> { assert_eq!(update.display_hidden, ContactInfoField::Replace(true)); *self.hidden.lock().expect("not poisoned") = true; *self.hidden_writes.lock().expect("not poisoned") += 1; @@ -1837,6 +1888,62 @@ mod tests { } } + #[tokio::test] + async fn contact_info_decline_waits_for_unhide_before_reading_visibility() { + let ops = ScriptedRejectOps { + hidden: Mutex::new(true), + ..Default::default() + }; + let unhide = ops.contact_info_lock.clone().lock_owned().await; + let mut decline = Box::pin(reject_flow(&ops, UnreadableContactInfoPolicy::Abort)); + assert!(futures::poll!(&mut decline).is_pending()); + assert_eq!( + *ops.phase.lock().unwrap(), + None, + "wait before reading or deciding" + ); + *ops.hidden.lock().unwrap() = false; + drop(unhide); + assert!(futures::poll!(&mut decline).is_pending()); + let mut competing_write = Box::pin(ops.contact_info_lock.clone().lock_owned()); + assert!( + futures::poll!(&mut competing_write).is_pending(), + "hold through the hide decision" + ); + decline.await.expect("decline completes"); + assert!(*ops.hidden.lock().unwrap()); + assert_eq!(*ops.hidden_writes.lock().unwrap(), 1); + drop(competing_write.await); + } + + #[tokio::test] + async fn contact_info_cancel_waits_for_unhide_before_reading_visibility() { + let ops = ScriptedOps { + contact_hidden: Mutex::new(true), + ..Default::default() + }; + let unhide = ops.contact_info_lock.clone().lock_owned().await; + let mut cancel = Box::pin(cancel_flow(&ops, UnreadableContactInfoPolicy::Abort)); + assert!(futures::poll!(&mut cancel).is_pending()); + assert_eq!( + *ops.phase.lock().unwrap(), + None, + "wait before reading or deciding" + ); + *ops.contact_hidden.lock().unwrap() = false; + drop(unhide); + assert!(futures::poll!(&mut cancel).is_pending()); + let mut competing_write = Box::pin(ops.contact_info_lock.clone().lock_owned()); + assert!( + futures::poll!(&mut competing_write).is_pending(), + "hold through the hide decision" + ); + assert_eq!(cancel.await.unwrap(), CancelOutcome::Withdrawn); + assert!(*ops.contact_hidden.lock().unwrap()); + assert_eq!(ops.hidden_writes(), vec![true]); + drop(competing_write.await); + } + #[tokio::test] async fn decline_retry_after_marker_failure_does_not_rebroadcast_hide() { let ops = ScriptedRejectOps { diff --git a/src/ui/state/contact_detail_view.rs b/src/ui/state/contact_detail_view.rs index 73f03fdc2..6d94fd1ce 100644 --- a/src/ui/state/contact_detail_view.rs +++ b/src/ui/state/contact_detail_view.rs @@ -6,11 +6,6 @@ use crate::backend_task::dashpay::ContactData; use dash_sdk::platform::Identifier; use std::collections::HashMap; -use std::time::{Duration, Instant}; - -/// Age after which a contact details write that never reported back stops -/// blocking the next one, pruned on the next view reset. -const WRITE_TIMEOUT: Duration = Duration::from_secs(5 * 60); /// A contact details write still running. Each rewrites the contact's whole /// `contactInfo` document, so a contact has at most one at a time. @@ -38,7 +33,7 @@ pub struct ContactDetailState { /// Contact details writes still running, keyed by owner identity and /// contact. Each is paid for, so the next write to that contact waits until /// its result lands. - writes: HashMap<(Identifier, Identifier), (PendingWrite, Instant)>, + writes: HashMap<(Identifier, Identifier), PendingWrite>, } /// The note as it is stored: surrounding whitespace dropped, and an empty note @@ -79,14 +74,10 @@ impl ContactDetailState { self.selected } - /// Drop the selection and the draft, keeping the guards of saves still - /// running and pruning those that never reported back. + /// Drop the selection and draft, retaining write guards until their tasks finish. pub fn reset(&mut self) { self.selected = None; self.draft = None; - let now = Instant::now(); - self.writes - .retain(|_, (_, started)| now.saturating_duration_since(*started) < WRITE_TIMEOUT); } /// Follow a fresh copy of the selected contact. The draft restarts from the @@ -166,7 +157,7 @@ impl ContactDetailState { if self.writes.contains_key(&key) { return false; } - self.writes.insert(key, (write, Instant::now())); + self.writes.insert(key, write); true } @@ -181,9 +172,7 @@ impl ContactDetailState { owner: &Identifier, contact_id: &Identifier, ) -> Option { - self.writes - .remove(&(*owner, *contact_id)) - .map(|(write, _)| write) + self.writes.remove(&(*owner, *contact_id)) } /// Release a write that failed or was abandoned; the draft is kept. @@ -347,6 +336,28 @@ mod tests { assert_eq!(state.begin_save(id(1), id(5)), None); } + #[test] + fn contact_info_running_write_survives_resets_until_its_own_result() { + let mut state = ContactDetailState::default(); + state.select(&contact(5, None)); + *state.note_mut(&id(5)).expect("draft") = "First note".into(); + assert!(state.begin_save(id(1), id(5)).is_some()); + + state.reset(); + state.select(&contact(5, None)); + *state.note_mut(&id(5)).expect("draft") = "Second note".into(); + assert_eq!(state.begin_save(id(1), id(5)), None); + assert!(!state.begin_visibility_write(id(1), id(5))); + assert_eq!( + state.finish_write(&id(1), &id(5)), + Some(PendingWrite::Note(Some("First note".into()))) + ); + assert_eq!( + state.begin_save(id(1), id(5)), + Some(Some("Second note".into())) + ); + } + #[test] fn reset_drops_the_selection_but_keeps_a_running_save() { let mut state = ContactDetailState::default(); diff --git a/src/ui/state/contacts_view.rs b/src/ui/state/contacts_view.rs index 68edd62d0..bb1584d1b 100644 --- a/src/ui/state/contacts_view.rs +++ b/src/ui/state/contacts_view.rs @@ -371,9 +371,22 @@ impl ContactsState { true } - /// Release a contact details write that failed or was abandoned. + /// Release a failed or abandoned write, rolling back an optimistic unhide. pub fn release_contact_info_write(&mut self, owner: &Identifier, contact_id: &Identifier) { - self.detail.release_write(owner, contact_id); + if self.detail.finish_write(owner, contact_id) == Some(PendingWrite::Visibility) + && self.owner_id() == Some(*owner) + { + if let Some(pos) = self + .contacts + .iter() + .position(|c| c.identity_id == *contact_id) + { + let mut contact = self.contacts.remove(pos); + contact.is_hidden = true; + self.hidden.push(contact); + } + self.invalidate(); + } } } @@ -727,6 +740,28 @@ mod tests { ); } + #[test] + fn contact_info_failed_unhide_restores_only_the_owning_contacts() { + let mut state = owned_state(1); + state.record_contacts(vec![hidden_contact("Ghost", id(8))]); + assert!(state.detail_mut().begin_visibility_write(id(1), id(8))); + state.unhide_contact(&id(8)); + state.select_contact(&id(8)); + state.release_contact_info_write(&id(2), &id(8)); + assert_eq!( + state.contacts_len(), + 1, + "another owner's failure cannot move this row" + ); + state.release_contact_info_write(&id(1), &id(8)); + assert_eq!(state.contacts_len(), 0); + assert_eq!(state.hidden_contacts().len(), 1); + assert!(state.hidden_contacts()[0].is_hidden); + assert!(state.selected_contact().is_none()); + assert!(!state.detail().is_writing(&id(1), &id(8))); + assert!(state.detail_mut().begin_visibility_write(id(1), id(8))); + } + #[test] fn unhiding_an_unknown_contact_changes_nothing() { let mut state = ContactsState::default(); diff --git a/tests/kittest/identity_hub_contact_detail.rs b/tests/kittest/identity_hub_contact_detail.rs index a4d0027fa..8b9b7352f 100644 --- a/tests/kittest/identity_hub_contact_detail.rs +++ b/tests/kittest/identity_hub_contact_detail.rs @@ -542,3 +542,83 @@ fn unreadable_details_found_behind_another_screen_still_ask_first() { ); }); } + +#[test] +fn failed_unhide_behind_another_screen_restores_the_hidden_row() { + use dash_evo_tool::backend_task::error::TaskError; + use dash_evo_tool::ui::identity::contacts::{SHOW_HIDDEN_LABEL, UNHIDE_LABEL}; + for bare_error in [false, true] { + with_isolated_data_dir(|| { + let runtime = tokio::runtime::Runtime::new().expect("runtime"); + let _guard = runtime.enter(); + let mut app = crate::support::mount_app( + dash_evo_tool::ui::RootScreenType::RootScreenWalletsBalances, + ); + let app_context = app.state().current_app_context().clone(); + let owner = seed_identity_with_usernames(&app_context); + let mut hub = hub_for( + &app_context, + owner, + WIDE, + IdentityHubTab::Contacts, + |hub, owner| { + let mut contact = bao(None); + contact.is_hidden = true; + deliver(hub, owner, contact); + }, + ); + hub.get_by_label(&format!("{SHOW_HIDDEN_LABEL} · 1")) + .click(); + hub.run_steps(2); + hub.get_by_role_and_label(Role::Button, UNHIDE_LABEL) + .click(); + hub.run_steps(2); + let context = hub + .state() + .1 + .iter() + .find_map(|action| match action { + AppAction::BackendTask(task @ BackendTask::DashPayTask(inner)) + if matches!(**inner, DashPayTask::UpdateContactInfo { .. }) => + { + Some(BackendTaskContext::from(task)) + } + _ => None, + }) + .expect("Unhide dispatched a write"); + assert!( + hub.query_by_role_and_label(Role::Button, "Bao Nguyen") + .is_some() + ); + crate::identity_hub::loads::receive_task_results_behind_the_send_screen( + &runtime, + &mut app, + &mut hub, + vec![dash_evo_tool::app::TaskResult::Error { + context, + error: if bare_error { + TaskError::WalletLocked + } else { + contact_info_failure(owner, TaskError::WalletLocked) + }, + }], + ); + hub.run_steps(2); + assert!( + hub.query_by_role_and_label(Role::Button, "Bao Nguyen") + .is_none(), + "a failed unhide must not leave an active contact" + ); + hub.state_mut().1.clear(); + hub.get_by_role_and_label(Role::Button, UNHIDE_LABEL) + .click(); + hub.run_steps(2); + assert!( + hub.state().1.iter().any(|action| matches!(action, + AppAction::BackendTask(BackendTask::DashPayTask(task)) + if matches!(**task, DashPayTask::UpdateContactInfo { .. }))), + "the restored hidden row permits a retry" + ); + }); + } +} From 69f1a513175f8e62b88dd20247bd874f9a7a142c Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 22 Oct 2026 15:30:57 +0000 Subject: [PATCH 19/73] fix(identity): release hidden hub contact details writes on bare errors The base merge kept the hidden-hub error route's new owner-aware shape but dropped the hub's context-keyed release, so a bare error on a contact details write sent while another screen covered the hub left its saving guard stuck. Pass the context through again and release the write it names. Also adapt the kittest helper to the base's `TaskResult` delivery API. Co-Authored-By: Claude Opus 5.5 --- src/app.rs | 14 ++++++++++---- tests/kittest/identity_hub.rs | 8 ++++++-- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/src/app.rs b/src/app.rs index 2264bf486..cb32ed1d8 100644 --- a/src/app.rs +++ b/src/app.rs @@ -2990,12 +2990,13 @@ impl AppState { } } - /// Release the hub's contact-request guards on a failed request action, - /// which it dispatches without a dispatch context, when the error goes to - /// another screen. + /// Release the hub's contact-request and contact details guards on a + /// failed action, which it dispatches without a dispatch context, when the + /// error goes to another screen. fn route_identity_error_to_hidden_hub( &mut self, owner: Option, + context: &BackendTaskContext, error: &TaskError, ) { if self.hub_takes_result(owner) { @@ -3005,6 +3006,11 @@ impl AppState { .main_screens .get_mut(&RootScreenType::RootScreenIdentityHub) { + // A bare error names its contact details write only through the + // context; the hub releases that write's guard from it. + if context.dashpay_contact_info_target().is_some() { + hub.display_backend_task_error(context, error); + } hub.handle_contact_request_error(error); hub.handle_contact_info_error(error); } @@ -3908,7 +3914,7 @@ impl App for AppState { &context, &err, ); - self.route_identity_error_to_hidden_hub(owner, &err); + self.route_identity_error_to_hidden_hub(owner, &context, &err); self.route_dpns_vote_error_to_hidden_screens(owner, &context, &err); let chooser_owned = network_chooser_owns_task(&context); // A top-up nobody open sent, or any task whose screen is diff --git a/tests/kittest/identity_hub.rs b/tests/kittest/identity_hub.rs index 65652e1ce..556732118 100644 --- a/tests/kittest/identity_hub.rs +++ b/tests/kittest/identity_hub.rs @@ -626,8 +626,12 @@ pub(crate) mod loads { ); state.selected_main_screen = RootScreenType::RootScreenIdentityHub; // The hub sent its own requests while it was the screen in view. - for (context, _) in &results { - state.test_record_visible_dispatch(context); + for result in &results { + if let dash_evo_tool::app::TaskResult::Success { context, .. } + | dash_evo_tool::app::TaskResult::Error { context, .. } = result + { + state.test_record_visible_dispatch(context); + } } state.screen_stack.push( ScreenType::IdentitySendScreen(identity, IdentitySendMode::Send) From c02b866cb3dabc461992e4d235881968c9f5153c Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 22 Oct 2026 16:50:36 +0000 Subject: [PATCH 20/73] fix(dashpay): save contact details through platform-wallet (DIP-15) Contact details (nickname, note, hidden) are now written and read through platform-wallet's DIP-15 contactInfo support, so other DashPay clients can read them. DET supplies only the seal/open step via a ContactCryptoProvider that borrows the seed from the secret seam for one operation; the child keys come from platform-wallet's derive_contact_info_keys. - Writes go through set_contact_info_with_external_signer; DET checks the wallet identity index and the established contact first. Until the identity has two contacts the details stay on this device and the UI says so. - Reads prefer platform-wallet's synced details; documents written by older DET versions show only as a fallback, newest document wins. - Declining a request ignores the sender in platform-wallet and records the decline; withdrawing records the withdrawal. Neither writes contactInfo. - Removed the unreadable-details overwrite prompts, per-request hide journal, and preserved accepted accounts, which no longer apply. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + Cargo.toml | 3 + docs/user-stories.md | 12 +- src/backend_task/dashpay.rs | 40 +- src/backend_task/dashpay/contact_info.rs | 1306 ++---------------- src/backend_task/dashpay/contact_requests.rs | 800 ++--------- src/backend_task/dashpay/contacts.rs | 173 ++- src/backend_task/error.rs | 45 +- src/backend_task/mod.rs | 6 +- src/model/dashpay.rs | 102 +- src/ui/dashpay/contact_details.rs | 67 +- src/ui/dashpay/contact_requests.rs | 61 +- src/ui/identity/contacts.rs | 25 +- src/ui/identity/hub_screen.rs | 337 +---- src/wallet_backend/contact_info.rs | 451 ++++++ src/wallet_backend/dashpay.rs | 86 +- src/wallet_backend/mod.rs | 4 +- tests/backend-e2e/dashpay_tasks.rs | 7 +- tests/kittest/identity_hub_contact_detail.rs | 82 +- 19 files changed, 1009 insertions(+), 2599 deletions(-) create mode 100644 src/wallet_backend/contact_info.rs diff --git a/Cargo.lock b/Cargo.lock index 00d31d4ed..4c1c50d57 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2120,6 +2120,7 @@ dependencies = [ "native-dialog", "nix", "objc2 0.6.4", + "platform-encryption", "platform-wallet", "platform-wallet-storage", "qrcode", diff --git a/Cargo.toml b/Cargo.toml index bd1648d5e..154c4819b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,6 +46,9 @@ platform-wallet-storage = { git = "https://github.com/dashpay/platform", rev = " "shielded", "serde", ] } +# DIP-15 contactInfo AES primitives for the host-side `ContactCryptoProvider`; +# the same crate platform-wallet seals and opens with. +platform-encryption = { git = "https://github.com/dashpay/platform", rev = "9f7ed16935bd540e4c2a542688800d2953f9f67a" } zip32 = "0.2.0" grovestark = { git = "https://www.github.com/dashpay/grovestark", rev = "5b9e289cca54c79b1305d5f4f40bf1148f1eb0e3" } rayon = "1.8" diff --git a/docs/user-stories.md b/docs/user-stories.md index b76c76fad..268504a9d 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -1075,12 +1075,14 @@ As a user, I want to edit contact details (nickname, note, hidden status) so tha - Set custom nickname and personal notes per contact. - Toggle contact visibility (hidden/visible). - Hidden contacts stay listed in a collapsed "Show hidden contacts" section of the Identity Hub - Contacts tab, and can be unhidden from there — including contacts hidden as a side effect of - declining or cancelling a request. If another client saved details this app cannot read, the app - warns that continuing will replace those details and asks for confirmation before unhiding. + Contacts tab, and can be unhidden from there. +- Declining a received request or withdrawing a sent one is recorded on this device only and + publishes nothing. - The Identity Hub contact details edit the private note, which is saved encrypted on Dash - Platform; a conservative fee estimate is shown before saving, and the saved note loads with - the contact from the network. Hub notes are not copied to the local memo: offline views and + Platform in the DashPay (DIP-0015) format other DashPay clients read; a conservative fee + estimate is shown before saving, and the saved note loads with the contact from the network. + Until the identity has two contacts, details are kept on this device and published later, and + the app says so. Details saved by older versions of this app still show until replaced. Hub notes are not copied to the local memo: offline views and legacy DashPay screens can continue to show an older local note. - Edits made through the legacy contact-details screen persist in its local memo. diff --git a/src/backend_task/dashpay.rs b/src/backend_task/dashpay.rs index ae474f2fe..27c3f7e3c 100644 --- a/src/backend_task/dashpay.rs +++ b/src/backend_task/dashpay.rs @@ -19,7 +19,7 @@ pub mod validation; pub use contacts::ContactData; -use crate::model::dashpay::{ContactInfoUpdate, UnreadableContactInfoPolicy}; +use crate::model::dashpay::ContactInfoUpdate; use crate::model::qualified_identity::QualifiedIdentity; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::platform_value::string_encoding::Encoding; @@ -93,20 +93,20 @@ pub enum DashPayTask { identity: QualifiedIdentity, request_id: Identifier, }, + /// Decline a contact request this identity received. Local only: the + /// sender is ignored on this device and nothing is published. RejectContactRequest { identity: QualifiedIdentity, request_id: Identifier, - unreadable: UnreadableContactInfoPolicy, }, /// Withdraw a still-pending contact request this identity sent. /// /// Platform cannot delete a `contactRequest` document, so the handler - /// broadcasts a hidden `contactInfo` and records the withdrawal locally — - /// see [`contact_requests::cancel_contact_request`]. + /// records the withdrawal on this device only — see + /// [`contact_requests::cancel_contact_request`]. CancelContactRequest { identity: QualifiedIdentity, request_id: Identifier, - unreadable: UnreadableContactInfoPolicy, }, LoadPaymentHistory { identity: QualifiedIdentity, @@ -229,27 +229,21 @@ impl AppContext { DashPayTask::RejectContactRequest { identity, request_id, - unreadable, - } => contact_requests::reject_contact_request( - self, sdk, identity, request_id, unreadable, - ) - .await - .map_err(|source| TaskError::DashPayContactRequestActionFailed { - request_id, - source: Box::new(source), - }), + } => contact_requests::reject_contact_request(self, sdk, identity, request_id) + .await + .map_err(|source| TaskError::DashPayContactRequestActionFailed { + request_id, + source: Box::new(source), + }), DashPayTask::CancelContactRequest { identity, request_id, - unreadable, - } => contact_requests::cancel_contact_request( - self, sdk, identity, request_id, unreadable, - ) - .await - .map_err(|source| TaskError::DashPayContactRequestActionFailed { - request_id, - source: Box::new(source), - }), + } => contact_requests::cancel_contact_request(self, sdk, identity, request_id) + .await + .map_err(|source| TaskError::DashPayContactRequestActionFailed { + request_id, + source: Box::new(source), + }), DashPayTask::LoadPaymentHistory { identity } => { let identity_id = identity.identity.id(); // Refresh-style action: kick upstream before reading so the diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index aa03755d2..90286a92c 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -1,349 +1,25 @@ +//! Contact details (DIP-0015 `contactInfo`). +//! +//! platform-wallet writes and syncs the identity's `contactInfo` documents. +//! This module keeps the paginated document fetch the read of older, +//! legacy-key documents uses, and turns a field-level update into the full +//! set of details platform-wallet publishes. + use crate::backend_task::BackendTaskSuccessResult; -use crate::backend_task::dashpay::errors::DashPayError; -use crate::backend_task::error::{ContactInfoReadError, TaskError}; +use crate::backend_task::error::TaskError; use crate::context::AppContext; -use crate::model::dashpay::{ - AcceptedAccounts, ContactInfoField, ContactInfoUpdate, UnreadableContactInfoPolicy, - validate_contact_note, -}; +use crate::model::dashpay::{ContactInfoUpdate, validate_contact_note}; use crate::model::qualified_identity::QualifiedIdentity; -use aes_gcm::aes::Aes256; -use aes_gcm::aes::cipher::{BlockCipherEncrypt, KeyInit}; -use bip39::rand::{SeedableRng, rngs::StdRng}; -use cbc::cipher::{BlockModeEncrypt, KeyIvInit}; use dash_sdk::Sdk; -use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; -use dash_sdk::dpp::document::{ - Document as DppDocument, DocumentV0, DocumentV0Getters, DocumentV0Setters, -}; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; -use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; -use dash_sdk::dpp::identity::{KeyType, Purpose, SecurityLevel}; -use dash_sdk::dpp::platform_value::{Bytes32, Value}; -use dash_sdk::drive::query::{OrderClause, WhereClause, WhereOperator}; -use dash_sdk::platform::documents::transitions::DocumentCreateTransitionBuilder; use dash_sdk::platform::proto::get_documents_request::get_documents_request_v0::Start; -use dash_sdk::platform::{Document, DocumentQuery, FetchMany, Identifier}; +use dash_sdk::platform::{DocumentQuery, Identifier}; use dash_sdk::query_types::Documents; -use platform_wallet::wallet::identity::crypto::ContactInfoPrivateData as UpstreamPrivateData; +use platform_wallet::wallet::identity::crypto::ContactInfoPrivateData; use platform_wallet::wallet::identity::crypto::contact_info::encode_private_data_bounded; -use std::collections::{BTreeMap, HashSet}; +use platform_wallet::wallet::identity::network::ContactInfoPublishOutcome; use std::future::Future; use std::sync::Arc; -use zeroize::Zeroizing; - -// ContactInfo private data structure -#[derive(Debug, Clone, Default)] -pub struct ContactInfoPrivateData { - pub version: u32, - pub alias_name: Option, - pub note: Option, - pub display_hidden: bool, - pub accepted_accounts: Vec, -} - -impl ContactInfoPrivateData { - pub fn new() -> Self { - Self::default() - } - - /// The plaintext floor platform-wallet pads to with zero bytes, so that - /// IV (16) + AES-CBC ciphertext reaches the contract's 48-byte minimum. - /// Older versions of this client padded to 16 bytes, starting with a zero. - const MIN_PLAINTEXT_SIZE: usize = 17; - - /// Encode for encryption with platform-wallet's DIP-15 codec, so every - /// client that uses it reads what this one writes. - pub fn serialize(&self) -> Result, TaskError> { - let alias_len = self.alias_name.as_deref().map_or(0, str::len); - if alias_len > u8::MAX as usize { - return Err(DashPayError::ContactInfoValidationFailed { - errors: vec![format!("Nickname too long ({alias_len} bytes, max 255)")], - } - .into()); - } - validate_contact_note(self.note.as_deref().unwrap_or_default())?; - encode_private_data_bounded(&UpstreamPrivateData { - alias_name: self.alias_name.clone(), - note: self.note.clone(), - display_hidden: self.display_hidden, - accepted_accounts: self.accepted_accounts.clone(), - }) - .map_err(|source| TaskError::DashPayContactInfoEncoding { - source: Box::new(source), - }) - } - - /// Parse the plaintext produced by [`serialize`](Self::serialize). - /// - /// Returns `None` for a truncated or non-canonical v0 payload, invalid - /// UTF-8, or an unsupported version. The only accepted trailing bytes are - /// zero padding up to [`Self::MIN_PLAINTEXT_SIZE`]. - /// Stricter than platform-wallet's reader: a write must never drop fields - /// it cannot read. - pub fn deserialize(bytes: &[u8]) -> Option { - let version = u32::from_le_bytes(bytes.get(..4)?.try_into().ok()?); - if version != 0 { - return None; - } - let mut pos = 4; - - // A Bitcoin CompactSize length, in its shortest encoding only. - let take_compact_size = |pos: &mut usize| -> Option { - let field = |width: usize| bytes.get(*pos + 1..*pos + 1 + width); - let (value, width): (u64, usize) = match *bytes.get(*pos)? { - 0xFD => (u16::from_le_bytes(field(2)?.try_into().ok()?).into(), 3), - 0xFE => (u32::from_le_bytes(field(4)?.try_into().ok()?).into(), 5), - 0xFF => (u64::from_le_bytes(field(8)?.try_into().ok()?), 9), - n => (n.into(), 1), - }; - let shortest = match width { - 3 => 0xFD, - 5 => 0x1_0000, - 9 => 0x1_0000_0000, - _ => 0, - }; - if value < shortest { - return None; - } - *pos += width; - usize::try_from(value).ok() - }; - let take_string = |pos: &mut usize| -> Option> { - let len = take_compact_size(pos)?; - let raw = bytes.get(*pos..pos.checked_add(len)?)?; - *pos += len; - if len == 0 { - Some(None) - } else { - Some(Some(std::str::from_utf8(raw).ok()?.to_owned())) - } - }; - let alias_name = take_string(&mut pos)?; - let note = take_string(&mut pos)?; - - let display_hidden = match *bytes.get(pos)? { - 0 => false, - 1 => true, - _ => return None, - }; - pos += 1; - - let count = take_compact_size(&mut pos)?; - let accepted_accounts = (0..count) - .map(|_| { - let raw = bytes.get(pos..pos + 4)?; - pos += 4; - Some(u32::from_le_bytes(raw.try_into().ok()?)) - }) - .collect::>>()?; - - if pos < bytes.len() - && (bytes.len() > Self::MIN_PLAINTEXT_SIZE - || bytes[pos..].iter().any(|byte| *byte != 0)) - { - return None; - } - - Some(Self { - version, - alias_name, - note, - display_hidden, - accepted_accounts, - }) - } -} - -/// Apply an explicit whole-document update to the payload already on Platform. -fn apply_contact_info_update( - update: ContactInfoUpdate, - existing: Option<&Document>, - private_data_key: &[u8; 32], -) -> Result { - let preserves_existing = matches!(update.display_hidden, ContactInfoField::Preserve) - || matches!(update.nickname, ContactInfoField::Preserve) - || matches!(update.note, ContactInfoField::Preserve) - || matches!(update.accepted_accounts, AcceptedAccounts::Preserve); - - let mut data = if preserves_existing { - read_contact_info_private_data(existing, private_data_key, update.unreadable)? - } else { - ContactInfoPrivateData::new() - }; - - if let ContactInfoField::Replace(nickname) = update.nickname { - data.alias_name = nickname; - } - if let ContactInfoField::Replace(note) = update.note { - data.note = note; - } - if let ContactInfoField::Replace(hidden) = update.display_hidden { - data.display_hidden = hidden; - } - if let AcceptedAccounts::Replace(accounts) = update.accepted_accounts { - data.accepted_accounts = accounts; - } - Ok(data) -} - -fn read_contact_info_private_data( - existing: Option<&Document>, - private_data_key: &[u8; 32], - unreadable: UnreadableContactInfoPolicy, -) -> Result { - let Some(existing) = existing else { - return Ok(ContactInfoPrivateData::new()); - }; - let Some(value) = existing.properties().get("privateData") else { - return Ok(ContactInfoPrivateData::new()); - }; - let result = match value { - Value::Bytes(encrypted) => { - super::contacts::decrypt_private_data(encrypted, private_data_key) - .map_err(|_| ContactInfoReadError::DecryptFailed) - .and_then(|plaintext| { - ContactInfoPrivateData::deserialize(&plaintext) - .ok_or(ContactInfoReadError::DeserializeFailed) - }) - } - _ => Err(ContactInfoReadError::UnexpectedPrivateDataType), - }; - - match (result, unreadable) { - (Ok(data), _) => Ok(data), - (Err(_), UnreadableContactInfoPolicy::Overwrite) => Ok(ContactInfoPrivateData::new()), - (Err(source), UnreadableContactInfoPolicy::Abort) => { - Err(TaskError::DashPayContactInfoRead { source }) - } - } -} - -/// Derive the DIP-0015 contactInfo encryption keys for `identity`, fetching -/// the wallet's HD seed just-in-time through the [`SecretAccess`] chokepoint. -/// -/// The seed is obtained per-operation via -/// [`SecretAccess::with_secret`](crate::wallet_backend::SecretAccess::with_secret) -/// keyed by the identity's DashPay wallet seed hash, and the BIP-32 -/// derivation runs inside the closure through the shared -/// [`derive_contact_info_encryption_keys`](crate::wallet_backend::derive_contact_info_encryption_keys) -/// helper — the raw seed never enters this layer. -#[allow(clippy::type_complexity)] -async fn derive_contact_info_keys( - app_context: &Arc, - identity: &QualifiedIdentity, - derivation_index: u32, -) -> Result<(Zeroizing<[u8; 32]>, Zeroizing<[u8; 32]>), TaskError> { - let seed_hash = identity - .dashpay_wallet_seed_hash() - .ok_or(TaskError::ContactWalletSeedUnavailable)?; - let network = identity.network; - - app_context - .wallet_backend()? - .secret_access() - .with_secret( - &crate::wallet_backend::SecretScope::HdSeed { seed_hash }, - |plaintext| { - let seed = plaintext - .expose_hd_seed() - .ok_or(TaskError::ContactWalletSeedUnavailable)?; - crate::wallet_backend::derive_contact_info_encryption_keys( - seed, - network, - derivation_index, - ) - }, - ) - .await -} - -/// Encrypt toUserId using AES-256-ECB as specified by DIP-0015. -/// -/// DIP-0015 mandates ECB mode for encToUserId encryption because: -/// 1. The toUserId is derived from SHA256, making it appear random (no patterns) -/// 2. Keys are never reused (unique per contact via hardened BIP32 derivation) -/// 3. The data is fixed-size (32 bytes = exactly 2 AES blocks) -/// -/// These properties eliminate typical ECB vulnerabilities (pattern leakage). -/// See: https://github.com/dashpay/dips/blob/master/dip-0015.md -fn encrypt_to_user_id(user_id: &[u8; 32], key: &[u8; 32]) -> Result<[u8; 32], String> { - let cipher = Aes256::new(key.into()); - - // The 32-byte ID is exactly two 16-byte AES blocks; encrypt each in place (ECB). - let mut encrypted = *user_id; - let (blocks, _) = encrypted.as_chunks_mut::<16>(); - for block in blocks { - cipher.encrypt_block(block.into()); - } - - Ok(encrypted) -} - -/// Decrypt toUserId using AES-256-ECB as specified by DIP-0015. -/// -/// See `encrypt_to_user_id` for the rationale behind ECB mode usage per DIP-0015. -fn decrypt_to_user_id(encrypted: &[u8], key: &[u8; 32]) -> Result<[u8; 32], String> { - use aes_gcm::aes::cipher::BlockCipherDecrypt; - - let mut decrypted: [u8; 32] = encrypted - .try_into() - .map_err(|_| "Invalid encrypted user ID length".to_string())?; - - let cipher = Aes256::new(key.into()); - - // The 32-byte ciphertext is exactly two 16-byte AES blocks; decrypt each in place (ECB). - let (blocks, _) = decrypted.as_chunks_mut::<16>(); - for block in blocks { - cipher.decrypt_block(block.into()); - } - - Ok(decrypted) -} - -// Encrypt private data using AES-256-CBC -fn encrypt_private_data(data: &[u8], key: &[u8; 32]) -> Result, String> { - use cbc::cipher::block_padding::Pkcs7; - type Aes256CbcEnc = cbc::Encryptor; - - // Generate random IV (16 bytes) - let mut rng = StdRng::from_entropy(); - let mut iv = [0u8; 16]; - use bip39::rand::RngCore; - rng.fill_bytes(&mut iv); - - // Pad data to multiple of 16 bytes and encrypt - let cipher = Aes256CbcEnc::new(key.into(), &iv.into()); - - // Allocate buffer with padding - let mut buffer = vec![0u8; data.len() + 16]; // Extra space for padding - buffer[..data.len()].copy_from_slice(data); - - let encrypted = cipher - .encrypt_padded::(&mut buffer, data.len()) - .map_err(|e| format!("Encryption failed: {:?}", e))?; - - // Combine IV and encrypted data - let mut result = Vec::with_capacity(16 + encrypted.len()); - result.extend_from_slice(&iv); - result.extend_from_slice(encrypted); - - Ok(result) -} - -struct ExistingContactInfo { - document: Document, - derivation_index: u32, - enc_user_id_key: Zeroizing<[u8; 32]>, - private_data_key: Zeroizing<[u8; 32]>, -} - -struct ContactInfoLookup { - existing: Option, - next_derivation_index: u32, -} - -type ContactInfoKeys = (Zeroizing<[u8; 32]>, Zeroizing<[u8; 32]>); const CONTACT_INFO_PAGE_SIZE: usize = 100; @@ -379,188 +55,18 @@ where Ok(documents) } -fn contact_info_derivation_index(document: &Document) -> Option { - document - .properties() - .get("derivationEncryptionKeyIndex") - .and_then(|value| value.to_integer::().ok()) -} - -fn has_contact_info_key_material(document: &Document) -> bool { - contact_info_derivation_index(document).is_some() - && document - .properties() - .get("rootEncryptionKeyIndex") - .and_then(|value| value.to_integer::().ok()) - .is_some() - && matches!( - document.properties().get("encToUserId"), - Some(Value::Bytes(_)) - ) -} - -fn find_existing_contact_info( - documents: Vec, - contact_user_id: Identifier, - mut derive_keys: F, -) -> Option -where - F: FnMut(u32) -> Result, -{ - for document in documents { - let Some(derivation_index) = contact_info_derivation_index(&document) else { - continue; - }; - if !has_contact_info_key_material(&document) { - continue; - } - - let Ok((enc_user_id_key, private_data_key)) = derive_keys(derivation_index) else { - continue; - }; - let Some(Value::Bytes(enc_user_id)) = document.properties().get("encToUserId") else { - continue; - }; - if decrypt_to_user_id(enc_user_id, &enc_user_id_key).ok() - == Some(contact_user_id.to_buffer()) - { - return Some(ExistingContactInfo { - document, - derivation_index, - enc_user_id_key, - private_data_key, - }); - } - } - - None -} - -async fn scan_contact_info_documents( - documents: Vec, - contact_user_id: Identifier, - with_key_session: F, -) -> Result -where - F: FnOnce(Vec, Identifier) -> Fut, - Fut: Future, TaskError>>, -{ - let next_derivation_index = documents - .iter() - .filter_map(contact_info_derivation_index) - .fold(0u32, |next, index| next.max(index.saturating_add(1))); - let existing = if documents.iter().any(has_contact_info_key_material) { - with_key_session(documents, contact_user_id).await? - } else { - None - }; - - Ok(ContactInfoLookup { - existing, - next_derivation_index, - }) -} - -async fn lookup_contact_info( - app_context: &Arc, - sdk: &Sdk, - identity: &QualifiedIdentity, - contact_user_id: Identifier, -) -> Result { - let dashpay_contract = app_context.dashpay_contract.clone(); - let identity_id = identity.identity.id(); - let mut query = DocumentQuery::new(dashpay_contract, "contactInfo").map_err(|e| { - DashPayError::QueryCreation { - query_target: "DashPay contactInfo", - source: Box::new(e.into()), - } - })?; - query = query.with_where(WhereClause { - field: "$ownerId".to_string(), - operator: WhereOperator::Equal, - value: Value::Identifier(identity_id.to_buffer()), - }); - query = query.with_order_by(OrderClause { - field: "$updatedAt".to_string(), - ascending: true, - }); - let existing_docs = fetch_all_contact_info_documents(query, |page_query| async move { - Document::fetch_many(sdk, page_query) - .await - .map_err(TaskError::from) - }) - .await?; - let documents = existing_docs.into_values().flatten().collect(); - scan_contact_info_documents( - documents, - contact_user_id, - |documents, contact_user_id| async move { - let seed_hash = identity - .dashpay_wallet_seed_hash() - .ok_or(TaskError::ContactWalletSeedUnavailable)?; - let network = identity.network; - - app_context - .wallet_backend()? - .secret_access() - .with_secret_session( - &crate::wallet_backend::SecretScope::HdSeed { seed_hash }, - async |session| { - let plaintext = session.plaintext(); - let seed = plaintext - .expose_hd_seed() - .ok_or(TaskError::ContactWalletSeedUnavailable)?; - Ok(find_existing_contact_info( - documents, - contact_user_id, - |derivation_index| { - crate::wallet_backend::derive_contact_info_encryption_keys( - seed, - network, - derivation_index, - ) - }, - )) - }, - ) - .await - }, - ) - .await -} - -pub(super) async fn contact_info_is_hidden( - app_context: &Arc, - sdk: &Sdk, - identity: &QualifiedIdentity, - contact_user_id: Identifier, - unreadable: UnreadableContactInfoPolicy, -) -> Result { - let lookup = lookup_contact_info(app_context, sdk, identity, contact_user_id).await?; - let Some(existing) = lookup.existing else { - return Ok(false); - }; - Ok(read_contact_info_private_data( - Some(&existing.document), - &existing.private_data_key, - unreadable, - )? - .display_hidden) -} - -/// Write the `contactInfo` document for `contact_user_id`, creating it when the -/// identity has none yet and replacing it otherwise. +/// Save `update` for `contact_user_id` through platform-wallet. /// -/// The document is written whole, so `update` explicitly chooses which fields -/// are preserved and which fields are replaced. Nicknames and notes are limited -/// to 255 UTF-8 bytes; the encoded payload must also fit the contract size limit. +/// Every field the update preserves keeps the value the contacts list shows: +/// platform-wallet's synced details, or a legacy-key document's when +/// platform-wallet has none for the contact. Notes are limited to 255 UTF-8 +/// bytes, and the details must fit the document size limit. /// /// # Errors /// -/// Fails when a preserved payload is present but unreadable, when the contact's -/// encryption keys cannot be derived, when an encoded field exceeds its v0 or -/// contract limit, when the identity has no usable authentication key, or when -/// the state transition is rejected. +/// Fails when the details are too large, when the identity was not loaded +/// from its wallet, when the contact is not established, or when the sync or +/// the publish fails. pub async fn create_or_update_contact_info( app_context: &Arc, sdk: &Sdk, @@ -568,240 +74,78 @@ pub async fn create_or_update_contact_info( contact_user_id: Identifier, update: ContactInfoUpdate, ) -> Result { - let write_guard = app_context + let _write_guard = app_context .contact_info_writes .acquire(identity.identity.id()) .await; - create_or_update_contact_info_locked( - app_context, - sdk, - identity, - contact_user_id, - update, - &write_guard, - ) - .await -} - -/// Write while the caller holds the owner's lock across its reads and decisions. -/// Request actions acquire their request lock before this owner lock. -pub(super) async fn create_or_update_contact_info_locked( - app_context: &Arc, - sdk: &Sdk, - identity: QualifiedIdentity, - contact_user_id: Identifier, - update: ContactInfoUpdate, - _write_guard: &tokio::sync::OwnedMutexGuard<()>, -) -> Result { - let dashpay_contract = app_context.dashpay_contract.clone(); - let identity_id = identity.identity.id(); - let lookup = lookup_contact_info(app_context, sdk, &identity, contact_user_id).await?; - let (found_existing_doc, derivation_index, enc_user_id_key, private_data_key) = - match lookup.existing { - Some(existing) => ( - Some(existing.document), - existing.derivation_index, - existing.enc_user_id_key, - existing.private_data_key, - ), - None => { - let derivation_index = lookup.next_derivation_index; - let (enc_user_id_key, private_data_key) = - derive_contact_info_keys(app_context, &identity, derivation_index).await?; - (None, derivation_index, enc_user_id_key, private_data_key) - } - }; - - // Encrypt toUserId - let encrypted_user_id = encrypt_to_user_id(&contact_user_id.to_buffer(), &enc_user_id_key) - .map_err(|e| TaskError::EncryptionError { detail: e })?; - - let private_data = - apply_contact_info_update(update, found_existing_doc.as_ref(), &private_data_key)?; - - // Encrypt private data - let encrypted_private_data = - encrypt_private_data(&private_data.serialize()?, &private_data_key) - .map_err(|e| TaskError::EncryptionError { detail: e })?; - - let validation = crate::backend_task::dashpay::validation::validate_contact_info_field_sizes( - &encrypted_user_id, - &encrypted_private_data, - ); - if !validation.is_valid { - return Err(TaskError::DashPay( - DashPayError::ContactInfoValidationFailed { - errors: validation.errors, - }, - )); - } - - // Get signing key — accept any key type (BLS, ECDSA, EDDSA) since - // Platform accepts all for document state transitions. - let signing_key = identity - .identity - .get_first_public_key_matching( - Purpose::AUTHENTICATION, - HashSet::from([ - SecurityLevel::CRITICAL, - SecurityLevel::HIGH, - SecurityLevel::MEDIUM, - ]), - KeyType::all_key_types().into(), - false, - ) - .ok_or_else(|| TaskError::DashPay(DashPayError::MissingAuthenticationKey))?; - - // Create document properties - let mut properties = BTreeMap::new(); - properties.insert( - "encToUserId".to_string(), - Value::Bytes(encrypted_user_id.to_vec()), - ); - properties.insert( - "rootEncryptionKeyIndex".to_string(), - Value::U32(signing_key.id()), - ); - properties.insert( - "derivationEncryptionKeyIndex".to_string(), - Value::U32(derivation_index), - ); - properties.insert( - "privateData".to_string(), - Value::Bytes(encrypted_private_data), - ); - - if let Some(existing_doc) = found_existing_doc { - // Update existing document - let mut updated_doc = existing_doc.clone(); - - // Update properties - for (key, value) in properties { - updated_doc.set(&key, value); - } - - // Bump revision - updated_doc.bump_revision(); - - // Create replacement transition - use dash_sdk::platform::documents::transitions::DocumentReplaceTransitionBuilder; - let mut builder = DocumentReplaceTransitionBuilder::new( - dashpay_contract, - "contactInfo".to_string(), - updated_doc, - ); - - // Add state transition options if available - let maybe_options = app_context.state_transition_options(); - if let Some(options) = maybe_options { - builder = builder.with_state_transition_creation_options(options); - } - - let result = sdk - .document_replace(builder, signing_key, &identity) - .await?; + let backend = app_context.wallet_backend()?; + let owner = identity.identity.id(); - // Log the proof-verified document for audit trail - match result { - dash_sdk::platform::documents::transitions::DocumentReplaceResult::Document(doc) => { - tracing::info!( - "Contact info updated: doc_id={}, revision={:?}", - doc.id(), - doc.revision() - ); - } - } - } else { - // Create new contactInfo document - let mut rng = StdRng::from_entropy(); - let entropy = Bytes32::random_with_rng(&mut rng); - - let document_id = Document::generate_document_id_v0( - &dashpay_contract.id(), - &identity_id, - "contactInfo", - entropy.as_slice(), - ); - - let document = DppDocument::V0(DocumentV0 { - id: document_id, - owner_id: identity_id, - creator_id: None, - properties, - revision: Some(1), - created_at: None, - updated_at: None, - transferred_at: None, - created_at_block_height: None, - updated_at_block_height: None, - transferred_at_block_height: None, - created_at_core_block_height: None, - updated_at_core_block_height: None, - transferred_at_core_block_height: None, - contract_version: None, - }); - - let mut builder = DocumentCreateTransitionBuilder::new( - dashpay_contract, - "contactInfo".to_string(), - document, - entropy - .as_slice() - .try_into() - .expect("entropy should be 32 bytes"), - ); - - // Add state transition options if available - let maybe_options = app_context.state_transition_options(); - if let Some(options) = maybe_options { - builder = builder.with_state_transition_creation_options(options); - } - - let result = sdk.document_create(builder, signing_key, &identity).await?; + backend.dashpay_sync_contact_infos(&owner).await?; + let synced = backend + .dashpay_contact_details(&owner) + .await + .remove(&contact_user_id) + .filter(|details| !details.is_empty()); + let current = match synced { + Some(details) => details, + None => super::contacts::legacy_contact_details(app_context, sdk, &identity) + .await? + .get(&contact_user_id) + .map(super::contacts::ContactData::details) + .unwrap_or_default(), + }; + let details = update.apply_to(current); + + validate_contact_note(details.note.as_deref().unwrap_or_default())?; + // The bound platform-wallet enforces, checked before it saves anything. + encode_private_data_bounded(&ContactInfoPrivateData { + alias_name: details.nickname.clone(), + note: details.note.clone(), + display_hidden: details.hidden, + accepted_accounts: Vec::new(), + }) + .map_err(|source| TaskError::DashPayContactInfoEncoding { + source: Box::new(source), + })?; - // Log the proof-verified document for audit trail - match result { - dash_sdk::platform::documents::transitions::DocumentCreateResult::Document(doc) => { - tracing::info!( - "Contact info created: doc_id={}, revision={:?}", - doc.id(), - doc.revision() - ); - } + let published = match backend + .dashpay_set_contact_info(&identity, &contact_user_id, details) + .await? + { + ContactInfoPublishOutcome::Published => true, + ContactInfoPublishOutcome::DeferredUntilTwoContacts => false, + // The write checks for a wallet identity index before platform-wallet + // runs, so this is reached only if the two disagree. + ContactInfoPublishOutcome::SkippedWatchOnly => { + return Err(TaskError::ContactInfoIdentityNotFromWallet); } - } - + }; Ok(BackendTaskSuccessResult::DashPayContactInfoUpdated { - identity: identity_id, + identity: owner, contact_id: contact_user_id, + published, }) } #[cfg(test)] mod tests { use super::*; + use dash_sdk::dpp::document::{ + Document as DppDocument, DocumentV0, DocumentV0Getters, DocumentV0Setters, + }; + use dash_sdk::dpp::platform_value::Value; use dash_sdk::dpp::system_data_contracts::{SystemDataContract, load_system_data_contract}; use dash_sdk::dpp::version::PlatformVersion; - use std::cell::Cell; - use std::collections::VecDeque; + use dash_sdk::platform::Document; + use std::collections::{BTreeMap, VecDeque}; use std::future::ready; + use zeroize::Zeroizing; const KEY: [u8; 32] = [7u8; 32]; - const OTHER_KEY: [u8; 32] = [9u8; 32]; - - /// DIP-15 `encToUserId` known-answer vector: AES-256-ECB(key = 00..1f, - /// pt = 40..5f), generated independently with Python `cryptography` 46 - /// (OpenSSL). Pins interoperability across `aes` / `aes-gcm` bumps. - #[test] - fn to_user_id_ecb_matches_golden_vector() { - let key: [u8; 32] = std::array::from_fn(|i| i as u8); - let user_id: [u8; 32] = std::array::from_fn(|i| 0x40 + i as u8); - let expected = "a37edf3f975abaef937b62c78d5bb157974b412738e50f45c7f9db25413f274b"; - let encrypted = encrypt_to_user_id(&user_id, &key).expect("encrypt"); - assert_eq!(hex::encode(encrypted), expected); - let decrypted = decrypt_to_user_id(&encrypted, &key).expect("decrypt"); - assert_eq!(decrypted, user_id); + fn encrypt_to_user_id(user_id: &[u8; 32], key: &[u8; 32]) -> [u8; 32] { + platform_encryption::encrypt_enc_to_user_id(key, user_id) } fn id(byte: u8) -> Identifier { @@ -823,46 +167,6 @@ mod tests { assert_eq!(next_contact_info_page(&docs), None); } - /// A stored `contactInfo` document whose `privateData` holds `accounts`, - /// encrypted exactly the way [`create_or_update_contact_info`] writes it. - fn stored_contact_info(accounts: Vec, key: &[u8; 32]) -> Document { - let private_data = ContactInfoPrivateData { - version: 0, - alias_name: Some("Bao".to_string()), - note: None, - display_hidden: true, - accepted_accounts: accounts, - }; - let encrypted = encrypt_private_data(&private_data.serialize().expect("serialize"), key) - .expect("encrypt"); - - contact_info_document(Some(Value::Bytes(encrypted))) - } - - fn contact_info_document(private_data: Option) -> Document { - let mut properties = BTreeMap::new(); - if let Some(private_data) = private_data { - properties.insert("privateData".to_string(), private_data); - } - DppDocument::V0(DocumentV0 { - id: id(1), - owner_id: id(2), - creator_id: None, - properties, - revision: Some(1), - created_at: None, - updated_at: None, - transferred_at: None, - created_at_block_height: None, - updated_at_block_height: None, - transferred_at_block_height: None, - created_at_core_block_height: None, - updated_at_core_block_height: None, - transferred_at_core_block_height: None, - contract_version: None, - }) - } - fn lookup_contact_info_document( document_id: u8, derivation_index: u32, @@ -898,104 +202,6 @@ mod tests { }) } - #[tokio::test] - async fn contact_info_scan_uses_one_secret_session_for_many_documents() { - let contact_user_id = id(200); - let encrypted_other_id = encrypt_to_user_id(&id(201).to_buffer(), &KEY).expect("encrypt"); - let documents = (0..=CONTACT_INFO_PAGE_SIZE) - .map(|index| { - lookup_contact_info_document(index as u8, index as u32, encrypted_other_id) - }) - .collect(); - let sessions = Cell::new(0); - let derivations = Cell::new(0); - - let lookup = - scan_contact_info_documents(documents, contact_user_id, |documents, target| { - sessions.set(sessions.get() + 1); - ready(Ok(find_existing_contact_info(documents, target, |_| { - derivations.set(derivations.get() + 1); - Ok((Zeroizing::new(KEY), Zeroizing::new(OTHER_KEY))) - }))) - }) - .await - .expect("scan"); - - assert!(lookup.existing.is_none()); - assert_eq!(lookup.next_derivation_index, 101); - assert_eq!(derivations.get(), 101); - assert_eq!(sessions.get(), 1, "the entire scan uses one unlock session"); - } - - #[test] - fn contact_info_scan_stops_deriving_after_target_match() { - let contact_user_id = id(210); - let encrypted_target = - encrypt_to_user_id(&contact_user_id.to_buffer(), &KEY).expect("encrypt target"); - let encrypted_other = - encrypt_to_user_id(&id(211).to_buffer(), &KEY).expect("encrypt other"); - let documents = vec![ - lookup_contact_info_document(1, 3, encrypted_target), - lookup_contact_info_document(2, 4, encrypted_other), - ]; - let mut derived_indices = Vec::new(); - - let existing = find_existing_contact_info(documents, contact_user_id, |index| { - derived_indices.push(index); - Ok((Zeroizing::new(KEY), Zeroizing::new(OTHER_KEY))) - }); - - assert!(existing.is_some()); - assert_eq!(derived_indices, vec![3]); - } - - #[tokio::test] - async fn contact_info_scan_skips_late_hardened_index_and_keeps_high_water_mark() { - const SEED: [u8; 64] = [42; 64]; - const MATCH_INDEX: u32 = 7; - const UNDERIVABLE_INDEX: u32 = 1 << 31; - - let contact_user_id = id(220); - let (target_key, _) = crate::wallet_backend::derive_contact_info_encryption_keys( - &SEED, - dash_sdk::dpp::dashcore::Network::Testnet, - MATCH_INDEX, - ) - .expect("derive target key"); - let encrypted_target = - encrypt_to_user_id(&contact_user_id.to_buffer(), &target_key).expect("encrypt target"); - let documents = vec![ - lookup_contact_info_document(1, MATCH_INDEX, encrypted_target), - lookup_contact_info_document(2, UNDERIVABLE_INDEX, [0; 32]), - ]; - let sessions = Cell::new(0); - - let lookup = - scan_contact_info_documents(documents, contact_user_id, |documents, target| { - sessions.set(sessions.get() + 1); - ready(Ok(find_existing_contact_info(documents, target, |index| { - crate::wallet_backend::derive_contact_info_encryption_keys( - &SEED, - dash_sdk::dpp::dashcore::Network::Testnet, - index, - ) - }))) - }) - .await - .expect("the late underivable document must not abort the matched lookup"); - - assert_eq!( - lookup.existing.map(|existing| existing.derivation_index), - Some(MATCH_INDEX) - ); - assert_eq!( - lookup.next_derivation_index, - UNDERIVABLE_INDEX + 1, - "the on-chain coordinate still advances the public high-water mark" - ); - assert_eq!(sessions.get(), 1); - } - #[tokio::test] async fn contact_info_fetch_walks_every_page() { let contract = @@ -1033,70 +239,26 @@ mod tests { assert_eq!(documents.keys().last().copied(), Some(id(101))); } - /// DIP-15 writes string lengths as CompactSize, where 253 and longer take a - /// three-byte prefix. Other platform-wallet clients must read what this - /// client writes, and this client what they write. + /// The fee estimate covers the largest details platform-wallet accepts. #[test] - fn contact_details_round_trip_with_the_platform_wallet_codec() { - use platform_wallet::wallet::identity::crypto as upstream; + fn contact_info_fee_estimate_covers_the_largest_details() { + use crate::model::fee_estimation::PlatformFeeEstimator; + let estimator = PlatformFeeEstimator::new(); for len in [0, 252, 253, 255] { let text = (len > 0).then(|| "x".repeat(len)); - let ours = ContactInfoPrivateData { - version: 0, + let encoded = encode_private_data_bounded(&ContactInfoPrivateData { alias_name: text.clone(), - note: text.clone(), + note: text, display_hidden: true, - accepted_accounts: vec![0, 3], - }; - let theirs = upstream::ContactInfoPrivateData { - alias_name: text.clone(), - note: text.clone(), - display_hidden: true, - accepted_accounts: vec![0, 3], - }; - - let decoded = upstream::decode_private_data(&ours.serialize().expect("serialize")); - assert_eq!( - decoded.ok(), - Some(theirs.clone()), - "platform-wallet reads {len} bytes" + accepted_accounts: Vec::new(), + }) + .expect("within the bound"); + let encrypted = platform_encryption::encrypt_private_data(&KEY, &[0; 16], &encoded); + assert!( + estimator.estimate_contact_info_write() + >= estimator.estimate_document_create_with_size(112 + encrypted.len()), + "{len}-byte fields" ); - - let parsed = - ContactInfoPrivateData::deserialize(&upstream::encode_private_data(&theirs)) - .unwrap_or_else(|| { - panic!("this client reads {len} bytes from platform-wallet") - }); - assert_eq!(parsed.alias_name, text); - assert_eq!(parsed.note, text); - assert!(parsed.display_hidden); - assert_eq!(parsed.accepted_accounts, vec![0, 3]); - } - } - - #[test] - fn contact_info_fee_estimate_covers_preserved_accounts() { - use crate::model::fee_estimation::PlatformFeeEstimator; - let estimator = PlatformFeeEstimator::new(); - for len in [0, 252, 253, 255] { - for accounts in [0, 1, 16, 252, 253, 400, 500] { - let text = (len > 0).then(|| "x".repeat(len)); - let data = ContactInfoPrivateData { - alias_name: text.clone(), - note: text, - accepted_accounts: (0..accounts).collect(), - ..Default::default() - }; - let Ok(encoded) = data.serialize() else { - continue; - }; - let encrypted = encrypt_private_data(&encoded, &KEY).unwrap(); - assert!( - estimator.estimate_contact_info_write() - >= estimator.estimate_document_create_with_size(112 + encrypted.len()), - "{len}-byte fields and {accounts} accounts" - ); - } } } @@ -1110,13 +272,13 @@ mod tests { /// A stored contactInfo for `contact` whose note platform-wallet wrote. fn saved_note_document(document_id: u8, contact: Identifier, note: &str) -> Document { use platform_wallet::wallet::identity::crypto as upstream; - let user_id = encrypt_to_user_id(&contact.to_buffer(), &KEY).expect("encrypt"); + let user_id = encrypt_to_user_id(&contact.to_buffer(), &KEY); let mut document = lookup_contact_info_document(document_id, document_id.into(), user_id); let plaintext = upstream::encode_private_data(&upstream::ContactInfoPrivateData { note: Some(note.to_string()), ..Default::default() }); - let private_data = encrypt_private_data(&plaintext, &KEY).expect("encrypt"); + let private_data = platform_encryption::encrypt_private_data(&KEY, &[5; 16], &plaintext); document.set("privateData", Value::Bytes(private_data)); document } @@ -1156,7 +318,7 @@ mod tests { #[tokio::test] async fn the_contact_details_load_reads_every_page() { let contact = id(201); - let other = encrypt_to_user_id(&id(202).to_buffer(), &KEY).expect("encrypt"); + let other = encrypt_to_user_id(&id(202).to_buffer(), &KEY); let first_page = contact_details_page( (1..=100).map(|byte| lookup_contact_info_document(byte, byte.into(), other)), ); @@ -1172,299 +334,21 @@ mod tests { assert!(ordered, "pages follow the order the write lookup uses"); } - /// With two documents for one contact, the load shows the one a save - /// rewrites: the first in that order. + /// With two readable documents for one contact, the newer one is shown: + /// pages are ordered by `$updatedAt`, oldest first. #[tokio::test] - async fn the_contact_details_load_shows_the_document_a_save_rewrites() { + async fn the_contact_details_load_shows_the_newest_document() { let contact = id(201); let page = contact_details_page([ - saved_note_document(1, contact, "kept"), - saved_note_document(2, contact, "stale"), + saved_note_document(1, contact, "older"), + saved_note_document(2, contact, "newer"), ]); let (details, _) = load_details(vec![page]).await; assert_eq!( details.get(&contact).and_then(|c| c.note.as_deref()), - Some("kept") - ); - } - - #[test] - fn private_data_round_trips_every_accepted_account() { - let original = ContactInfoPrivateData { - version: 0, - alias_name: Some("Bao".to_string()), - note: Some("Met at the meetup".to_string()), - display_hidden: true, - accepted_accounts: vec![0, 3, 17], - }; - - let parsed = ContactInfoPrivateData::deserialize(&original.serialize().expect("serialize")) - .expect("a document this client wrote must parse back"); - - assert_eq!(parsed.alias_name.as_deref(), Some("Bao")); - assert_eq!(parsed.note.as_deref(), Some("Met at the meetup")); - assert!(parsed.display_hidden); - assert_eq!( - parsed.accepted_accounts, - vec![0, 3, 17], - "every accepted account must survive the round trip, not just the first" + Some("newer") ); } - - #[test] - fn private_data_round_trips_through_the_minimum_size_padding() { - // An empty private data is padded up to the contract's minimum size — - // the padding must not be mistaken for a field. - let original = ContactInfoPrivateData::new(); - let parsed = ContactInfoPrivateData::deserialize(&original.serialize().expect("serialize")) - .expect("padded plaintext must parse"); - - assert_eq!(parsed.alias_name, None); - assert_eq!(parsed.note, None); - assert!(!parsed.display_hidden); - assert!(parsed.accepted_accounts.is_empty()); - } - - #[test] - fn truncated_private_data_is_not_parsed_as_a_shorter_list() { - let bytes = ContactInfoPrivateData { - version: 0, - alias_name: None, - note: None, - display_hidden: false, - accepted_accounts: vec![1, 2, 3], - } - .serialize() - .expect("serialize"); - - // Chop the final account in half: the list declares three, so a parser - // that returned the two it could read would silently drop an account. - assert!( - ContactInfoPrivateData::deserialize(&bytes[..bytes.len() - 2]).is_none(), - "a truncated account list must not parse as a shorter one" - ); - } - - #[test] - fn unsupported_private_data_version_requires_confirmation() { - let mut bytes = ContactInfoPrivateData::new() - .serialize() - .expect("serialize"); - bytes[..4].copy_from_slice(&1_u32.to_le_bytes()); - - assert!( - ContactInfoPrivateData::deserialize(&bytes).is_none(), - "a future payload version must not be rewritten as though it were version zero" - ); - } - - #[test] - fn invalid_utf8_is_not_treated_as_an_absent_contact_detail() { - let mut bytes = ContactInfoPrivateData::new() - .serialize() - .expect("serialize"); - bytes[4] = 1; - bytes[5] = 0xff; - - assert!( - ContactInfoPrivateData::deserialize(&bytes).is_none(), - "an unreadable nickname must not silently become an empty nickname" - ); - } - - #[test] - fn unknown_visibility_encoding_requires_confirmation() { - let mut bytes = ContactInfoPrivateData::new() - .serialize() - .expect("serialize"); - bytes[6] = 2; - - assert!(ContactInfoPrivateData::deserialize(&bytes).is_none()); - } - - #[test] - fn trailing_extension_bytes_require_confirmation() { - let mut bytes = ContactInfoPrivateData { - version: 0, - alias_name: Some("123456789".to_string()), - note: None, - display_hidden: false, - accepted_accounts: Vec::new(), - } - .serialize() - .expect("serialize without minimum-size padding"); - assert_eq!(bytes.len(), ContactInfoPrivateData::MIN_PLAINTEXT_SIZE); - bytes.push(42); - - assert!(ContactInfoPrivateData::deserialize(&bytes).is_none()); - } - - #[test] - fn contact_info_padding_rejects_nonzero_bytes_after_the_sentinel() { - let canonical = ContactInfoPrivateData::new() - .serialize() - .expect("serialize"); - for length in [16, ContactInfoPrivateData::MIN_PLAINTEXT_SIZE] { - assert!(ContactInfoPrivateData::deserialize(&canonical[..length]).is_some()); - for offset in 9..length { - let mut malformed = canonical[..length].to_vec(); - malformed[offset] = 42; - assert!( - ContactInfoPrivateData::deserialize(&malformed).is_none(), - "nonzero padding at {offset} in {length} bytes must require confirmation" - ); - } - } - } - - #[test] - fn minimum_size_padding_requires_the_sentinel() { - let mut bytes = ContactInfoPrivateData::new() - .serialize() - .expect("serialize"); - bytes[8] = 1; - - assert!(ContactInfoPrivateData::deserialize(&bytes).is_none()); - } - - #[test] - fn contact_info_note_preserves_a_concurrent_visibility_change() { - let existing = stored_contact_info(vec![0, 4, 9], &KEY); - let data = apply_contact_info_update( - ContactInfoUpdate::note(Some("New note".into())), - Some(&existing), - &KEY, - ) - .unwrap(); - assert!( - data.display_hidden, - "note edits must keep the latest stored visibility" - ); - assert_eq!(data.note.as_deref(), Some("New note")); - assert_eq!(data.alias_name.as_deref(), Some("Bao")); - assert_eq!(data.accepted_accounts, vec![0, 4, 9]); - } - - #[test] - fn visibility_update_preserves_every_unrelated_stored_field() { - let existing = stored_contact_info(vec![0, 4, 9], &KEY); - let data = - apply_contact_info_update(ContactInfoUpdate::visibility(false), Some(&existing), &KEY) - .expect("stored details must be readable"); - - assert_eq!(data.alias_name.as_deref(), Some("Bao")); - assert_eq!(data.note, None); - assert!(!data.display_hidden); - assert_eq!(data.accepted_accounts, vec![0, 4, 9]); - } - - #[test] - fn replace_overwrites_whatever_the_document_stored() { - let existing = stored_contact_info(vec![0, 4, 9], &KEY); - - let data = apply_contact_info_update( - ContactInfoUpdate::replace_all(None, None, false, vec![2]), - Some(&existing), - &OTHER_KEY, - ) - .expect("an explicit full replacement does not read stored data"); - - assert_eq!(data.accepted_accounts, vec![2]); - assert_eq!(data.alias_name, None); - } - - #[test] - fn preserving_a_contact_with_no_stored_document_yields_no_accounts() { - let data = apply_contact_info_update(ContactInfoUpdate::visibility(false), None, &KEY) - .expect("a first-ever contactInfo has nothing to preserve"); - - assert!(data.accepted_accounts.is_empty()); - } - - #[test] - fn unreadable_private_data_aborts_the_write() { - let existing = stored_contact_info(vec![0, 4, 9], &OTHER_KEY); - - // A wrong-key AES-CBC decrypt is unauthenticated: PKCS7 unpadding usually - // rejects it (DecryptFailed), but ~1/256 the random IV yields valid - // padding and the garbage plaintext fails to parse (DeserializeFailed). - // Both are the "present but unreadable" abort this test asserts. - assert!( - matches!( - apply_contact_info_update( - ContactInfoUpdate::visibility(false), - Some(&existing), - &KEY, - ), - Err(TaskError::DashPayContactInfoRead { - source: ContactInfoReadError::DecryptFailed - | ContactInfoReadError::DeserializeFailed, - }) - ), - "an undecryptable present payload must abort before it can be overwritten" - ); - } - - #[test] - fn confirmed_overwrite_is_the_only_escape_hatch_for_unreadable_private_data() { - use crate::model::dashpay::ContactInfoUpdate; - - let existing = stored_contact_info(vec![0, 4, 9], &OTHER_KEY); - let update = ContactInfoUpdate::visibility(false); - - // Wrong-key decrypt aborts as either DecryptFailed or (≈1/256, on a - // random IV that passes PKCS7 unpadding) DeserializeFailed. - assert!(matches!( - apply_contact_info_update(update.clone(), Some(&existing), &KEY), - Err(TaskError::DashPayContactInfoRead { - source: ContactInfoReadError::DecryptFailed - | ContactInfoReadError::DeserializeFailed, - }) - )); - - let replaced = - apply_contact_info_update(update.overwrite_unreadable(), Some(&existing), &KEY) - .expect("a confirmed overwrite must let the contact be unhidden"); - assert_eq!(replaced.alias_name, None); - assert_eq!(replaced.note, None); - assert!(!replaced.display_hidden); - assert!(replaced.accepted_accounts.is_empty()); - } - - #[test] - fn missing_private_data_is_safe_to_treat_as_empty() { - let existing = contact_info_document(None); - let data = - apply_contact_info_update(ContactInfoUpdate::visibility(false), Some(&existing), &KEY) - .expect("an absent payload contains no details to lose"); - - assert!(data.accepted_accounts.is_empty()); - } - - #[test] - fn unexpected_private_data_type_requires_confirmation() { - let existing = contact_info_document(Some(Value::Text("unknown".to_string()))); - - assert!(matches!( - apply_contact_info_update(ContactInfoUpdate::visibility(false), Some(&existing), &KEY,), - Err(TaskError::DashPayContactInfoRead { - source: ContactInfoReadError::UnexpectedPrivateDataType, - }) - )); - } - - #[test] - fn undecodable_private_data_aborts_the_write() { - let encrypted = encrypt_private_data(&[0, 0, 0, 0], &KEY).expect("encrypt malformed data"); - let existing = contact_info_document(Some(Value::Bytes(encrypted))); - - assert!(matches!( - apply_contact_info_update(ContactInfoUpdate::visibility(false), Some(&existing), &KEY,), - Err(TaskError::DashPayContactInfoRead { - source: ContactInfoReadError::DeserializeFailed, - }) - )); - } } diff --git a/src/backend_task/dashpay/contact_requests.rs b/src/backend_task/dashpay/contact_requests.rs index dc6c74fd3..22b6a2447 100644 --- a/src/backend_task/dashpay/contact_requests.rs +++ b/src/backend_task/dashpay/contact_requests.rs @@ -10,11 +10,9 @@ use crate::backend_task::dashpay::auto_accept_proof::{ }; use crate::backend_task::error::TaskError; use crate::context::AppContext; -use crate::model::dashpay::{ - ContactInfoUpdate, UnreadableContactInfoPolicy, contact_request_recipient, -}; +use crate::model::dashpay::contact_request_recipient; use crate::model::qualified_identity::QualifiedIdentity; -use crate::wallet_backend::{ContactRequestActionKind, ContactRequestActionPhase}; +use crate::wallet_backend::ContactRequestActionKind; // Upstream contact-request type: used to record the sent request in the // local wallet-manager so dashpay_sync can auto-establish the contact. use bip39::rand::{SeedableRng, rngs::StdRng}; @@ -626,7 +624,10 @@ pub async fn send_contact_request_with_proof( // leave the other standing. let declined = backend.dashpay_unmark_declined(&owner_id, &to_identity_id); let withdrawn = backend.dashpay_unmark_withdrawn(&owner_id, &to_identity_id); - if let Err(err) = declined.and(withdrawn) { + let ignored = backend + .dashpay_unignore_contact_sender(&owner_id, &to_identity_id) + .await; + if let Err(err) = declined.and(withdrawn).and(ignored) { tracing::debug!( %err, "Clearing the stale resolution markers failed; an earlier declined or \ @@ -802,12 +803,11 @@ pub async fn reject_contact_request( sdk: &Sdk, identity: QualifiedIdentity, request_id: Identifier, - unreadable: UnreadableContactInfoPolicy, ) -> Result { - // According to DashPay DIP, rejecting doesn't delete the request (they're immutable) - // Instead, we should update our contactInfo document to mark this contact as hidden - - // First, fetch the contact request to get the sender's identity + // A contactRequest document is immutable, and a contactInfo about someone + // who is not a contact would publish whom this identity turned down, so + // declining is local only: platform-wallet ignores the sender and the DET + // marker retires the request. let query_with_id = DocumentQuery::with_document_id(contact_request_query(app_context)?, &request_id); @@ -815,8 +815,6 @@ pub async fn reject_contact_request( .await? .ok_or(TaskError::DocumentNotFound)?; - // Captured before `identity` is moved into `create_or_update_contact_info`; - // the decline marker is scoped to this acting identity. let owner_id = identity.identity.id(); // Verify the request was addressed to us before declining it. @@ -824,58 +822,30 @@ pub async fn reject_contact_request( let ops = PlatformRejectOps { app_context, - sdk, - identity, owner_id, from_identity_id, request_id, }; - reject_flow(&ops, unreadable).await + reject_flow(&ops).await } +/// The local writes a decline performs, behind a trait so their order can be +/// driven in tests. trait RejectOps { fn lock_action( &self, ) -> impl Future, TaskError>> + Send; - fn lock_contact_info(&self) -> impl Future> + Send; - fn phase(&self) -> Result, TaskError>; - fn set_phase(&self, phase: ContactRequestActionPhase) -> Result<(), TaskError>; + /// Forget the progress record an older version kept for this action. fn clear_phase(&self) -> Result<(), TaskError>; - fn contact_is_hidden( - &self, - unreadable: UnreadableContactInfoPolicy, - ) -> impl Future> + Send; - fn update_contact_info( - &self, - update: ContactInfoUpdate, - write_guard: &tokio::sync::OwnedMutexGuard<()>, - ) -> impl Future> + Send; + /// Ignore the sender in platform-wallet (local only). + fn ignore_sender(&self) -> impl Future> + Send; fn mark_declined(&self) -> Result<(), TaskError>; fn request_id(&self) -> Identifier; } -async fn reject_flow( - ops: &O, - unreadable: UnreadableContactInfoPolicy, -) -> Result { +async fn reject_flow(ops: &O) -> Result { let _action_guard = ops.lock_action().await?; - let contact_info_guard = ops.lock_contact_info().await; - let phase = match ops.phase()? { - Some(phase) => phase, - None => { - ops.set_phase(ContactRequestActionPhase::HideIntent)?; - ContactRequestActionPhase::HideIntent - } - }; - - if phase == ContactRequestActionPhase::HideIntent { - if !ops.contact_is_hidden(unreadable).await? { - ops.update_contact_info(hidden_contact_update(true, unreadable), &contact_info_guard) - .await?; - } - ops.set_phase(ContactRequestActionPhase::MarkerPending)?; - } - + ops.ignore_sender().await?; let result = complete_rejection(ops.request_id(), || ops.mark_declined())?; ops.clear_phase()?; Ok(result) @@ -883,8 +853,6 @@ async fn reject_flow( struct PlatformRejectOps<'a> { app_context: &'a Arc, - sdk: &'a Sdk, - identity: QualifiedIdentity, owner_id: Identifier, from_identity_id: Identifier, request_id: Identifier, @@ -899,34 +867,6 @@ impl RejectOps for PlatformRejectOps<'_> { .await) } - async fn lock_contact_info(&self) -> tokio::sync::OwnedMutexGuard<()> { - self.app_context - .contact_info_writes - .acquire(self.owner_id) - .await - } - - fn phase(&self) -> Result, TaskError> { - self.app_context - .wallet_backend()? - .dashpay_contact_request_action_phase( - &self.owner_id, - &self.request_id, - ContactRequestActionKind::Decline, - ) - } - - fn set_phase(&self, phase: ContactRequestActionPhase) -> Result<(), TaskError> { - self.app_context - .wallet_backend()? - .dashpay_set_contact_request_action_phase( - &self.owner_id, - &self.request_id, - ContactRequestActionKind::Decline, - phase, - ) - } - fn clear_phase(&self) -> Result<(), TaskError> { self.app_context .wallet_backend()? @@ -937,35 +877,11 @@ impl RejectOps for PlatformRejectOps<'_> { ) } - async fn contact_is_hidden( - &self, - unreadable: UnreadableContactInfoPolicy, - ) -> Result { - super::contact_info::contact_info_is_hidden( - self.app_context, - self.sdk, - &self.identity, - self.from_identity_id, - unreadable, - ) - .await - } - - async fn update_contact_info( - &self, - update: ContactInfoUpdate, - write_guard: &tokio::sync::OwnedMutexGuard<()>, - ) -> Result<(), TaskError> { - super::contact_info::create_or_update_contact_info_locked( - self.app_context, - self.sdk, - self.identity.clone(), - self.from_identity_id, - update, - write_guard, - ) - .await - .map(|_| ()) + async fn ignore_sender(&self) -> Result<(), TaskError> { + self.app_context + .wallet_backend()? + .dashpay_ignore_contact_sender(&self.owner_id, &self.from_identity_id) + .await } fn mark_declined(&self) -> Result<(), TaskError> { @@ -979,17 +895,6 @@ impl RejectOps for PlatformRejectOps<'_> { } } -/// The visibility flip that declining and withdrawing both write. Every other -/// stored detail is preserved: these actions hide a contact, they do not edit it. -fn hidden_contact_update( - hidden: bool, - unreadable: UnreadableContactInfoPolicy, -) -> ContactInfoUpdate { - let mut update = ContactInfoUpdate::visibility(hidden); - update.unreadable = unreadable; - update -} - /// Return rejection success only after storing the local marker that retires the row. /// The closure seam keeps the failure path deterministic in tests. /// @@ -1011,42 +916,25 @@ fn complete_rejection( /// What a cancellation attempt resolved to. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum CancelOutcome { - /// The request was pending throughout; it is now withdrawn. + /// The request was pending; it is now withdrawn. Withdrawn, /// The recipient had answered — there was nothing left to cancel. AlreadyEstablished, } -/// The Platform reads and writes a cancellation performs. -/// -/// Behind a trait so [`cancel_flow`]'s ordering — and the race window between -/// the reciprocal check and the hide broadcast — can be driven deterministically -/// in tests, which is impossible against a live Platform. +/// The reads and local writes a cancellation performs, behind a trait so +/// their order can be driven in tests. trait CancelOps { fn lock_action( &self, ) -> impl Future, TaskError>> + Send; - fn lock_contact_info(&self) -> impl Future> + Send; - fn phase(&self) -> Result, TaskError>; - fn set_phase(&self, phase: ContactRequestActionPhase) -> Result<(), TaskError>; + /// Forget the progress record an older version kept for this action. fn clear_phase(&self) -> Result<(), TaskError>; /// `true` when the recipient has already sent a contact request back, which /// makes the pending request an established contact instead. fn reciprocal_request_exists(&self) -> impl Future> + Send; - fn contact_is_hidden( - &self, - unreadable: UnreadableContactInfoPolicy, - ) -> impl Future> + Send; - - /// Broadcast the complete visibility update for the recipient. - fn update_contact_info( - &self, - update: ContactInfoUpdate, - write_guard: &tokio::sync::OwnedMutexGuard<()>, - ) -> impl Future> + Send; - /// Record the withdrawal in the DET sidecar so the request stops being /// listed as pending. /// @@ -1058,85 +946,24 @@ trait CancelOps { fn mark_withdrawn(&self) -> Result<(), TaskError>; } -/// Check, hide, then re-check and undo the hide if the recipient answered inside -/// the window. -/// -/// Platform has no conditional write, so the reciprocal check and the hide -/// broadcast cannot be one atomic step: they are two round-trips against two -/// different documents. The check is therefore the last read before the write, -/// and a second read straight after the write closes the gap retroactively — a -/// reciprocal request that lands mid-flight is detected and the hide is -/// reverted, leaving the freshly-established contact visible. That is the same -/// end state the caller would have reached had the reciprocal arrived a moment -/// earlier. -/// -/// Residual risk: a reciprocal request landing *after* the second read still -/// leaves the contact hidden. It is not detectable from here at any window -/// width; recovery is the Contacts tab's hidden-contacts section, which can -/// unhide the contact. -async fn cancel_flow( - ops: &O, - unreadable: UnreadableContactInfoPolicy, -) -> Result { +/// Withdraw the request unless the recipient has answered it. Local only: +/// nothing is published. +async fn cancel_flow(ops: &O) -> Result { let _action_guard = ops.lock_action().await?; - let contact_info_guard = ops.lock_contact_info().await; - let mut phase = match ops.phase()? { - Some(phase) => phase, - None => { - if ops.reciprocal_request_exists().await? { - return Ok(CancelOutcome::AlreadyEstablished); - } - ops.set_phase(ContactRequestActionPhase::HideIntent)?; - ContactRequestActionPhase::HideIntent - } + let outcome = if ops.reciprocal_request_exists().await? { + CancelOutcome::AlreadyEstablished + } else { + ops.mark_withdrawn()?; + CancelOutcome::Withdrawn }; - - if phase == ContactRequestActionPhase::HideIntent { - if !ops.contact_is_hidden(unreadable).await? { - ops.update_contact_info(hidden_contact_update(true, unreadable), &contact_info_guard) - .await?; - } - ops.set_phase(ContactRequestActionPhase::HideCommitted)?; - phase = ContactRequestActionPhase::HideCommitted; - } - - if phase == ContactRequestActionPhase::HideCommitted { - if ops.reciprocal_request_exists().await? { - ops.set_phase(ContactRequestActionPhase::CorrectiveUnhideIntent)?; - phase = ContactRequestActionPhase::CorrectiveUnhideIntent; - } else { - ops.set_phase(ContactRequestActionPhase::MarkerPending)?; - phase = ContactRequestActionPhase::MarkerPending; - } - } - - if phase == ContactRequestActionPhase::CorrectiveUnhideIntent { - if ops.contact_is_hidden(unreadable).await? { - ops.update_contact_info( - hidden_contact_update(false, unreadable), - &contact_info_guard, - ) - .await?; - } - ops.set_phase(ContactRequestActionPhase::CorrectiveUnhideComplete)?; - phase = ContactRequestActionPhase::CorrectiveUnhideComplete; - } - - if phase == ContactRequestActionPhase::CorrectiveUnhideComplete { - ops.clear_phase()?; - return Ok(CancelOutcome::AlreadyEstablished); - } - - ops.mark_withdrawn()?; ops.clear_phase()?; - Ok(CancelOutcome::Withdrawn) + Ok(outcome) } /// [`CancelOps`] against the live Platform, for one sender/recipient pair. struct PlatformCancelOps<'a> { app_context: &'a Arc, sdk: &'a Sdk, - identity: QualifiedIdentity, /// The cancelling identity — the sender of the request being withdrawn. owner_id: Identifier, /// The recipient of the request being withdrawn. @@ -1153,34 +980,6 @@ impl CancelOps for PlatformCancelOps<'_> { .await) } - async fn lock_contact_info(&self) -> tokio::sync::OwnedMutexGuard<()> { - self.app_context - .contact_info_writes - .acquire(self.owner_id) - .await - } - - fn phase(&self) -> Result, TaskError> { - self.app_context - .wallet_backend()? - .dashpay_contact_request_action_phase( - &self.owner_id, - &self.request_id, - ContactRequestActionKind::Cancel, - ) - } - - fn set_phase(&self, phase: ContactRequestActionPhase) -> Result<(), TaskError> { - self.app_context - .wallet_backend()? - .dashpay_set_contact_request_action_phase( - &self.owner_id, - &self.request_id, - ContactRequestActionKind::Cancel, - phase, - ) - } - fn clear_phase(&self) -> Result<(), TaskError> { self.app_context .wallet_backend()? @@ -1209,37 +1008,6 @@ impl CancelOps for PlatformCancelOps<'_> { Ok(!Document::fetch_many(self.sdk, query).await?.is_empty()) } - async fn update_contact_info( - &self, - update: ContactInfoUpdate, - write_guard: &tokio::sync::OwnedMutexGuard<()>, - ) -> Result<(), TaskError> { - super::contact_info::create_or_update_contact_info_locked( - self.app_context, - self.sdk, - self.identity.clone(), - self.to_identity_id, - update, - write_guard, - ) - .await - .map(|_| ()) - } - - async fn contact_is_hidden( - &self, - unreadable: UnreadableContactInfoPolicy, - ) -> Result { - super::contact_info::contact_info_is_hidden( - self.app_context, - self.sdk, - &self.identity, - self.to_identity_id, - unreadable, - ) - .await - } - fn mark_withdrawn(&self) -> Result<(), TaskError> { self.app_context .wallet_backend()? @@ -1251,21 +1019,18 @@ impl CancelOps for PlatformCancelOps<'_> { /// /// DashPay `contactRequest` documents are immutable and cannot be deleted /// (`documentsMutable: false`, `canBeDeleted: false` in the DashPay contract), -/// so the request cannot be un-sent from Platform. Cancelling therefore does -/// what `reject_contact_request` does for the incoming direction: it broadcasts -/// a `contactInfo` document marking the recipient hidden — a real, persisted -/// state transition — and records the withdrawal in the DET sidecar so the -/// request stops being listed as pending. +/// so the request cannot be un-sent from Platform. Cancelling records the +/// withdrawal on this device only, so the request stops being listed as +/// pending; nothing is published. /// /// State is re-verified against Platform before acting: the request must still /// exist, must have been sent by `identity`, and must not have been answered in -/// the meantime. See [`cancel_flow`] for how the answer race is handled. +/// the meantime. pub async fn cancel_contact_request( app_context: &Arc, sdk: &Sdk, identity: QualifiedIdentity, request_id: Identifier, - unreadable: UnreadableContactInfoPolicy, ) -> Result { let owner_id = identity.identity.id(); @@ -1284,13 +1049,12 @@ pub async fn cancel_contact_request( let ops = PlatformCancelOps { app_context, sdk, - identity, owner_id, to_identity_id, request_id, }; - match cancel_flow(&ops, unreadable).await? { + match cancel_flow(&ops).await? { CancelOutcome::Withdrawn => Ok(BackendTaskSuccessResult::DashPayContactRequestCancelled( request_id, )), @@ -1308,7 +1072,6 @@ pub async fn cancel_contact_request( #[cfg(test)] mod tests { use super::*; - use crate::model::dashpay::ContactInfoField; use dash_sdk::dpp::document::DocumentV0; fn id(byte: u8) -> Identifier { @@ -1559,70 +1322,19 @@ mod tests { } // ----------------------------------------------------------------- - // Cancellation flow — the reciprocal check and the hide broadcast are - // separate Platform round-trips, so the window between them is where a - // reciprocal request can slip in and get a fresh contact hidden. + // Decline and withdraw — both are local only: no contact details are + // written for someone who is not a contact. // ----------------------------------------------------------------- - use std::collections::VecDeque; use std::sync::Mutex; - /// Scriptable [`CancelOps`]. `reciprocal` is consumed one answer per probe, - /// which is how a reciprocal request is injected *inside* the window: - /// `[false, true]` means "pending when we checked, established by the time - /// the hide landed". #[derive(Default)] struct ScriptedOps { action_lock: Arc>, - contact_info_lock: Arc>, - reciprocal: Mutex>>, - /// Every contact-info update, in call order. - contact_updates: Mutex>, - contact_hidden: Mutex, - phase: Mutex>, + reciprocal: bool, withdrawn: Mutex, - /// When set, the first hide broadcast fails. - hide_fails: bool, - /// When set, recording the withdrawal in the sidecar fails. - withdraw_failures: Mutex, - } - - impl ScriptedOps { - fn with_reciprocal(answers: [bool; 2]) -> Self { - Self { - reciprocal: Mutex::new(answers.map(Ok).into()), - ..Default::default() - } - } - - fn with_reciprocal_results( - answers: impl IntoIterator>, - ) -> Self { - Self { - reciprocal: Mutex::new(answers.into_iter().collect()), - ..Default::default() - } - } - - fn hidden_writes(&self) -> Vec { - self.contact_updates - .lock() - .expect("not poisoned") - .iter() - .map(|update| match update.display_hidden { - ContactInfoField::Replace(hidden) => hidden, - ContactInfoField::Preserve => panic!("expected an explicit visibility change"), - }) - .collect() - } - - fn contact_updates(&self) -> Vec { - self.contact_updates.lock().expect("not poisoned").clone() - } - - fn was_withdrawn(&self) -> bool { - *self.withdrawn.lock().expect("not poisoned") - } + withdraw_fails: bool, + phase_cleared: Mutex, } impl CancelOps for ScriptedOps { @@ -1630,161 +1342,53 @@ mod tests { Ok(self.action_lock.clone().lock_owned().await) } - async fn lock_contact_info(&self) -> tokio::sync::OwnedMutexGuard<()> { - self.contact_info_lock.clone().lock_owned().await - } - - fn phase(&self) -> Result, TaskError> { - Ok(*self.phase.lock().expect("not poisoned")) - } - - fn set_phase(&self, phase: ContactRequestActionPhase) -> Result<(), TaskError> { - *self.phase.lock().expect("not poisoned") = Some(phase); - Ok(()) - } - fn clear_phase(&self) -> Result<(), TaskError> { - *self.phase.lock().expect("not poisoned") = None; + *self.phase_cleared.lock().unwrap() = true; Ok(()) } async fn reciprocal_request_exists(&self) -> Result { - self.reciprocal - .lock() - .expect("not poisoned") - .pop_front() - .unwrap_or(Ok(false)) - } - - async fn contact_is_hidden( - &self, - _unreadable: UnreadableContactInfoPolicy, - ) -> Result { - let hidden = *self.contact_hidden.lock().expect("not poisoned"); - tokio::task::yield_now().await; - Ok(hidden) - } - - async fn update_contact_info( - &self, - update: ContactInfoUpdate, - _write_guard: &tokio::sync::OwnedMutexGuard<()>, - ) -> Result<(), TaskError> { - if self.hide_fails { - return Err(TaskError::DocumentNotFound); - } - self.contact_updates - .lock() - .expect("not poisoned") - .push(update.clone()); - if let ContactInfoField::Replace(hidden) = update.display_hidden { - *self.contact_hidden.lock().expect("not poisoned") = hidden; - } - Ok(()) + Ok(self.reciprocal) } fn mark_withdrawn(&self) -> Result<(), TaskError> { - let mut failures = self.withdraw_failures.lock().expect("not poisoned"); - if *failures > 0 { - *failures -= 1; - return Err(TaskError::WalletBackendNotYetWired); + if self.withdraw_fails { + return Err(TaskError::DashpaySidecarStorage { + source: crate::wallet_backend::KvAdapterError::Truncated, + }); } - *self.withdrawn.lock().expect("not poisoned") = true; + *self.withdrawn.lock().unwrap() = true; Ok(()) } } - fn assert_preserving_visibility_update(update: &ContactInfoUpdate, hidden: bool) { - use crate::model::dashpay::{AcceptedAccounts, ContactInfoField}; - - assert_eq!(update.nickname, ContactInfoField::Preserve); - assert_eq!(update.note, ContactInfoField::Preserve); - assert_eq!(update.accepted_accounts, AcceptedAccounts::Preserve); - assert_eq!(update.display_hidden, ContactInfoField::Replace(hidden)); - } - - #[tokio::test] - async fn cancelling_a_pending_request_preserves_unrelated_contact_details() { - let ops = ScriptedOps::with_reciprocal([false, false]); - - let outcome = cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .expect("cancellation succeeds"); - - assert_eq!(outcome, CancelOutcome::Withdrawn); - assert_eq!( - ops.hidden_writes(), - vec![true], - "a pending request must be hidden exactly once" - ); - assert_preserving_visibility_update(&ops.contact_updates()[0], true); - assert!( - ops.was_withdrawn(), - "the withdrawal must be recorded so the row stops being listed" - ); - } - - #[tokio::test] - async fn cancelling_an_answered_request_hides_nothing() { - // The recipient answered before the user clicked Cancel. - let ops = ScriptedOps::with_reciprocal([true, true]); - - let outcome = cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .expect("cancellation succeeds"); - - assert_eq!(outcome, CancelOutcome::AlreadyEstablished); - assert!( - ops.hidden_writes().is_empty(), - "an established contact must never be hidden by a cancellation" - ); - assert!(!ops.was_withdrawn()); - } - #[tokio::test] - async fn a_reciprocal_request_landing_inside_the_window_leaves_the_contact_visible() { - // Pending when checked, established by the time the hide broadcast - // landed — the exact race the check-then-write ordering cannot prevent. - let ops = ScriptedOps::with_reciprocal([false, true]); - - let outcome = cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .expect("cancellation succeeds"); + async fn withdrawing_a_pending_request_records_it_on_this_device() { + let ops = ScriptedOps::default(); assert_eq!( - outcome, - CancelOutcome::AlreadyEstablished, - "the caller must be told the pair is a contact, not that a request was cancelled" - ); - assert_eq!( - ops.hidden_writes(), - vec![true, false], - "the hide must be undone once the reciprocal request is detected, so the \ - freshly-established contact does not vanish" + cancel_flow(&ops).await.expect("cancel"), + CancelOutcome::Withdrawn ); + assert!(*ops.withdrawn.lock().unwrap()); assert!( - !ops.was_withdrawn(), - "an established contact must not be marked as a withdrawn request" + *ops.phase_cleared.lock().unwrap(), + "an older version's record is retired" ); } #[tokio::test] - async fn a_failed_hide_broadcast_records_no_withdrawal() { + async fn withdrawing_an_answered_request_changes_nothing() { let ops = ScriptedOps { - hide_fails: true, - ..ScriptedOps::with_reciprocal([false, false]) + reciprocal: true, + ..Default::default() }; - assert!( - cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .is_err(), - "a failed broadcast must surface, not be swallowed" - ); - assert!( - !ops.was_withdrawn(), - "the request is still pending on Platform, so it must keep being listed" + assert_eq!( + cancel_flow(&ops).await.expect("cancel"), + CancelOutcome::AlreadyEstablished ); + assert!(!*ops.withdrawn.lock().unwrap()); } #[tokio::test] @@ -1793,16 +1397,11 @@ mod tests { // request comes back as pending on the next reload, so announcing a // successful cancellation would be a lie. let ops = ScriptedOps { - withdraw_failures: Mutex::new(1), - ..ScriptedOps::with_reciprocal([false, false]) + withdraw_fails: true, + ..Default::default() }; - assert!( - cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .is_err(), - "a withdrawal the sidecar refused must surface as an error, not as success" - ); + assert!(cancel_flow(&ops).await.is_err()); } #[test] @@ -1822,12 +1421,9 @@ mod tests { #[derive(Default)] struct ScriptedRejectOps { action_lock: Arc>, - contact_info_lock: Arc>, - phase: Mutex>, - hidden: Mutex, - hidden_writes: Mutex, - mark_attempts: Mutex, - mark_failures: Mutex, + ignore_fails: bool, + ignored: Mutex, + declined: Mutex, } impl RejectOps for ScriptedRejectOps { @@ -1835,51 +1431,20 @@ mod tests { Ok(self.action_lock.clone().lock_owned().await) } - async fn lock_contact_info(&self) -> tokio::sync::OwnedMutexGuard<()> { - self.contact_info_lock.clone().lock_owned().await - } - - fn phase(&self) -> Result, TaskError> { - Ok(*self.phase.lock().expect("not poisoned")) - } - - fn set_phase(&self, phase: ContactRequestActionPhase) -> Result<(), TaskError> { - *self.phase.lock().expect("not poisoned") = Some(phase); - Ok(()) - } - fn clear_phase(&self) -> Result<(), TaskError> { - *self.phase.lock().expect("not poisoned") = None; Ok(()) } - async fn contact_is_hidden( - &self, - _unreadable: UnreadableContactInfoPolicy, - ) -> Result { - let hidden = *self.hidden.lock().expect("not poisoned"); - tokio::task::yield_now().await; - Ok(hidden) - } - - async fn update_contact_info( - &self, - update: ContactInfoUpdate, - _write_guard: &tokio::sync::OwnedMutexGuard<()>, - ) -> Result<(), TaskError> { - assert_eq!(update.display_hidden, ContactInfoField::Replace(true)); - *self.hidden.lock().expect("not poisoned") = true; - *self.hidden_writes.lock().expect("not poisoned") += 1; + async fn ignore_sender(&self) -> Result<(), TaskError> { + if self.ignore_fails { + return Err(TaskError::WalletStateInconsistent); + } + *self.ignored.lock().unwrap() += 1; Ok(()) } fn mark_declined(&self) -> Result<(), TaskError> { - *self.mark_attempts.lock().expect("not poisoned") += 1; - let mut failures = self.mark_failures.lock().expect("not poisoned"); - if *failures > 0 { - *failures -= 1; - return Err(TaskError::WalletBackendNotYetWired); - } + *self.declined.lock().unwrap() = true; Ok(()) } @@ -1889,208 +1454,25 @@ mod tests { } #[tokio::test] - async fn contact_info_decline_waits_for_unhide_before_reading_visibility() { - let ops = ScriptedRejectOps { - hidden: Mutex::new(true), - ..Default::default() - }; - let unhide = ops.contact_info_lock.clone().lock_owned().await; - let mut decline = Box::pin(reject_flow(&ops, UnreadableContactInfoPolicy::Abort)); - assert!(futures::poll!(&mut decline).is_pending()); - assert_eq!( - *ops.phase.lock().unwrap(), - None, - "wait before reading or deciding" - ); - *ops.hidden.lock().unwrap() = false; - drop(unhide); - assert!(futures::poll!(&mut decline).is_pending()); - let mut competing_write = Box::pin(ops.contact_info_lock.clone().lock_owned()); - assert!( - futures::poll!(&mut competing_write).is_pending(), - "hold through the hide decision" - ); - decline.await.expect("decline completes"); - assert!(*ops.hidden.lock().unwrap()); - assert_eq!(*ops.hidden_writes.lock().unwrap(), 1); - drop(competing_write.await); - } + async fn declining_ignores_the_sender_and_records_the_decline() { + let ops = ScriptedRejectOps::default(); - #[tokio::test] - async fn contact_info_cancel_waits_for_unhide_before_reading_visibility() { - let ops = ScriptedOps { - contact_hidden: Mutex::new(true), - ..Default::default() - }; - let unhide = ops.contact_info_lock.clone().lock_owned().await; - let mut cancel = Box::pin(cancel_flow(&ops, UnreadableContactInfoPolicy::Abort)); - assert!(futures::poll!(&mut cancel).is_pending()); - assert_eq!( - *ops.phase.lock().unwrap(), - None, - "wait before reading or deciding" - ); - *ops.contact_hidden.lock().unwrap() = false; - drop(unhide); - assert!(futures::poll!(&mut cancel).is_pending()); - let mut competing_write = Box::pin(ops.contact_info_lock.clone().lock_owned()); - assert!( - futures::poll!(&mut competing_write).is_pending(), - "hold through the hide decision" - ); - assert_eq!(cancel.await.unwrap(), CancelOutcome::Withdrawn); - assert!(*ops.contact_hidden.lock().unwrap()); - assert_eq!(ops.hidden_writes(), vec![true]); - drop(competing_write.await); + assert!(matches!( + reject_flow(&ops).await, + Ok(BackendTaskSuccessResult::DashPayContactRequestRejected(request)) if request == id(7) + )); + assert_eq!(*ops.ignored.lock().unwrap(), 1); + assert!(*ops.declined.lock().unwrap()); } #[tokio::test] - async fn decline_retry_after_marker_failure_does_not_rebroadcast_hide() { + async fn a_failed_ignore_records_no_decline() { let ops = ScriptedRejectOps { - mark_failures: Mutex::new(1), + ignore_fails: true, ..Default::default() }; - assert!( - reject_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .is_err() - ); - assert!( - reject_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .is_ok() - ); - assert_eq!(*ops.hidden_writes.lock().expect("not poisoned"), 1); - assert_eq!(*ops.mark_attempts.lock().expect("not poisoned"), 2); - } - - #[tokio::test] - async fn concurrent_declines_share_one_paid_hide() { - let ops = ScriptedRejectOps::default(); - - let (first, second) = tokio::join!( - reject_flow(&ops, UnreadableContactInfoPolicy::Abort), - reject_flow(&ops, UnreadableContactInfoPolicy::Abort), - ); - - assert!(first.is_ok()); - assert!(second.is_ok()); - assert_eq!( - *ops.hidden_writes.lock().expect("not poisoned"), - 1, - "backend serialization must permit only one paid hide" - ); - } - - #[tokio::test] - async fn cancel_retry_after_marker_failure_does_not_rebroadcast_hide() { - let ops = ScriptedOps { - withdraw_failures: Mutex::new(1), - ..ScriptedOps::with_reciprocal([false, false]) - }; - - assert!( - cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .is_err() - ); - assert_eq!( - cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .expect("marker repair succeeds"), - CancelOutcome::Withdrawn - ); - assert_eq!(ops.hidden_writes(), vec![true]); - assert!(ops.reciprocal.lock().expect("not poisoned").is_empty()); - } - - #[tokio::test] - async fn concurrent_cancellations_share_one_paid_hide() { - let ops = ScriptedOps::with_reciprocal([false, false]); - - let (first, second) = tokio::join!( - cancel_flow(&ops, UnreadableContactInfoPolicy::Abort), - cancel_flow(&ops, UnreadableContactInfoPolicy::Abort), - ); - - assert_eq!(first.expect("first cancellation"), CancelOutcome::Withdrawn); - assert_eq!( - second.expect("second cancellation"), - CancelOutcome::Withdrawn - ); - assert_eq!( - ops.hidden_writes(), - vec![true], - "backend serialization must permit only one paid hide" - ); - } - - #[tokio::test] - async fn cancel_retry_after_post_hide_probe_failure_does_not_rehide() { - let ops = ScriptedOps::with_reciprocal_results([ - Ok(false), - Err(TaskError::DocumentNotFound), - Ok(false), - ]); - - assert!( - cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .is_err() - ); - assert_eq!( - cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .expect("post-hide probe resumes"), - CancelOutcome::Withdrawn - ); - assert_eq!(ops.hidden_writes(), vec![true]); - } - - #[tokio::test] - async fn cancel_retry_that_discovers_reciprocal_unhides_once() { - let ops = ScriptedOps::with_reciprocal_results([ - Ok(false), - Err(TaskError::DocumentNotFound), - Ok(true), - ]); - - assert!( - cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .is_err() - ); - assert_eq!( - cancel_flow(&ops, UnreadableContactInfoPolicy::Abort) - .await - .expect("reciprocal retry succeeds"), - CancelOutcome::AlreadyEstablished - ); - assert_eq!(ops.hidden_writes(), vec![true, false]); - assert!(!ops.was_withdrawn()); - } - - #[test] - fn declining_preserves_unrelated_contact_details() { - // The write `reject_contact_request` broadcasts. Declining hides the - // sender; it must not volunteer empty details over what they stored. - let update = hidden_contact_update(true, UnreadableContactInfoPolicy::Abort); - - assert_preserving_visibility_update(&update, true); - } - - #[test] - fn a_confirmed_overwrite_carries_the_users_choice_into_the_write() { - use crate::model::dashpay::AcceptedAccounts; - - let update = hidden_contact_update(true, UnreadableContactInfoPolicy::Overwrite); - - assert_eq!(update.unreadable, UnreadableContactInfoPolicy::Overwrite); - assert_eq!( - update.accepted_accounts, - AcceptedAccounts::Preserve, - "confirming an overwrite of unreadable data must not also volunteer an empty account list" - ); + assert!(reject_flow(&ops).await.is_err()); + assert!(!*ops.declined.lock().unwrap(), "a retry starts over"); } } diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index e5ed3a6de..c5f2071e3 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -3,7 +3,7 @@ use crate::backend_task::dashpay::contact_request_query; use crate::backend_task::dashpay::errors::DashPayError; use crate::backend_task::error::TaskError; use crate::context::AppContext; -use crate::model::dashpay::contact_request_recipient; +use crate::model::dashpay::{ContactDetails, contact_request_recipient}; use crate::model::qualified_identity::QualifiedIdentity; use dash_sdk::Sdk; use dash_sdk::dpp::data_contract::DataContract; @@ -128,11 +128,12 @@ pub(super) fn decrypt_private_data( Ok(decrypted.to_vec()) } -/// The nickname, note and visibility the owner stored for each contact, read -/// from every page of the owner's `contactInfo` documents. +/// The nickname, note and visibility the owner stored for each contact in +/// `contactInfo` documents sealed under the legacy key root, read from every +/// page of the owner's documents. /// -/// Pages follow the order the write lookup scans, and the first document for -/// a contact wins, so the load shows the document a save rewrites. +/// Pages are ordered by `$updatedAt`, oldest first, and a later document for +/// a contact replaces an earlier one, so the newest document wins. pub(super) async fn load_contact_details( query: DocumentQuery, fetch_page: P, @@ -176,10 +177,6 @@ where ); continue; }; - if contact_info_map.contains_key(&contact_id) { - continue; - } - // The DIP-15 codec platform-wallet writes with; an unreadable payload // shows as no stored details. let private_data = match props.get("privateData") { @@ -209,6 +206,57 @@ where Ok(contact_info_map) } +/// The details legacy-key `contactInfo` documents hold for each contact. +pub(super) async fn legacy_contact_details( + app_context: &Arc, + sdk: &Sdk, + identity: &QualifiedIdentity, +) -> Result, TaskError> { + let query = DocumentQuery::new(app_context.dashpay_contract.clone(), "contactInfo") + .map_err(|e| DashPayError::QueryCreation { + query_target: "DashPay contactInfo", + source: Box::new(e.into()), + })? + .with_where(WhereClause { + field: "$ownerId".to_string(), + operator: WhereOperator::Equal, + value: Value::Identifier(identity.identity.id().to_buffer()), + }); + load_contact_details( + query, + |query| async move { + Document::fetch_many(sdk, query) + .await + .map_err(TaskError::from) + }, + |derivation_index| derive_contact_info_keys(app_context, identity, derivation_index), + ) + .await +} + +/// The details the contacts list shows for one contact: platform-wallet's +/// synced details, or a legacy-key document's when platform-wallet holds +/// none for the contact. +pub(super) fn shown_contact_details( + synced: Option, + legacy: Option, +) -> ContactDetails { + synced + .filter(|details| !details.is_empty()) + .or(legacy) + .unwrap_or_default() +} + +impl ContactData { + pub(super) fn details(&self) -> ContactDetails { + ContactDetails { + nickname: self.nickname.clone(), + note: self.note.clone(), + hidden: self.is_hidden, + } + } +} + #[derive(Debug, Clone, PartialEq)] pub struct ContactData { pub identity_id: Identifier, @@ -284,47 +332,52 @@ pub async fn load_contacts( }) .collect(); - // Now query for contact info documents - let mut contact_info_query = DocumentQuery::new(dashpay_contract.clone(), "contactInfo") - .map_err(|e| DashPayError::QueryCreation { - query_target: "DashPay contactInfo", - source: Box::new(e.into()), - })?; - - contact_info_query = contact_info_query.with_where(WhereClause { - field: "$ownerId".to_string(), - operator: WhereOperator::Equal, - value: Value::Identifier(identity_id.to_buffer()), - }); - let contact_info_map = load_contact_details( - contact_info_query, - |query| async move { - Document::fetch_many(sdk, query) - .await - .map_err(TaskError::from) - }, - |derivation_index| derive_contact_info_keys(app_context, &identity, derivation_index), - ) - .await?; + // platform-wallet's synced details first; a refresh failure leaves the + // last synced details in place. + let mut synced = match app_context.wallet_backend() { + Ok(backend) => { + if let Err(error) = backend.dashpay_sync(&identity_id).await { + tracing::debug!( + ?error, + "LoadContacts: DashPay sync degraded; using cached state" + ); + } + if let Err(error) = backend.dashpay_sync_contact_infos(&identity_id).await { + tracing::debug!( + ?error, + "LoadContacts: contact details sync degraded; using cached state" + ); + } + backend.dashpay_contact_details(&identity_id).await + } + Err(error) => { + tracing::debug!( + ?error, + "LoadContacts: no wallet backend; showing legacy details" + ); + Default::default() + } + }; + let legacy = legacy_contact_details(app_context, sdk, &identity).await?; // Build enriched contact list with basic data let mut contact_list: Vec = contacts .into_iter() .map(|contact_id| { - contact_info_map - .get(&contact_id) - .cloned() - .unwrap_or(ContactData { - identity_id: contact_id, - nickname: None, - note: None, - is_hidden: false, - account_reference: 0, - username: None, - display_name: None, - avatar_url: None, - bio: None, - }) + let legacy = legacy.get(&contact_id); + let details = + shown_contact_details(synced.remove(&contact_id), legacy.map(ContactData::details)); + ContactData { + identity_id: contact_id, + nickname: details.nickname, + note: details.note, + is_hidden: details.hidden, + account_reference: legacy.map_or(0, |legacy| legacy.account_reference), + username: None, + display_name: None, + avatar_url: None, + bio: None, + } }) .collect(); @@ -518,6 +571,36 @@ fn cache_contact_profiles(app_context: &Arc, contacts: &[ContactData mod tests { use super::*; + fn details(note: &str) -> ContactDetails { + ContactDetails { + nickname: None, + note: Some(note.to_string()), + hidden: false, + } + } + + #[test] + fn synced_contact_details_win_over_legacy_ones() { + assert_eq!( + shown_contact_details(Some(details("synced")), Some(details("legacy"))), + details("synced") + ); + } + + #[test] + fn legacy_contact_details_show_when_none_are_synced() { + assert_eq!( + shown_contact_details(None, Some(details("legacy"))), + details("legacy") + ); + assert_eq!( + shown_contact_details(Some(ContactDetails::default()), Some(details("legacy"))), + details("legacy"), + "a contact platform-wallet holds no details for shows the legacy ones" + ); + assert_eq!(shown_contact_details(None, None), ContactDetails::default()); + } + /// Known-answer vectors generated independently with Python /// `cryptography` 46 (OpenSSL). They pin DIP-15 interoperability with other /// DashPay clients across `cbc` / `aes` / `aes-gcm` bumps. diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 8f6091040..70b888a26 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -43,20 +43,6 @@ impl DapiAddressAvailability { } } -/// Why an existing DashPay `contactInfo` payload could not be preserved. -#[derive(Debug, Error)] -pub enum ContactInfoReadError { - /// The private payload was present with a shape this client does not understand. - #[error("contactInfo privateData has an unexpected type")] - UnexpectedPrivateDataType, - /// The private payload was present but could not be decrypted with its derived key. - #[error("contactInfo privateData decryption failed")] - DecryptFailed, - /// Decryption succeeded, but the plaintext is not a format this client understands. - #[error("contactInfo privateData deserialization failed")] - DeserializeFailed, -} - /// Typed failures while restoring persisted Core transaction history. #[derive(Debug, Error)] pub enum WalletTransactionHistoryError { @@ -1380,15 +1366,26 @@ pub enum TaskError { source: Box, }, - /// An existing contact's encrypted details could not be read safely. - #[error( - "Your saved contact details could not be read, so no changes were made. Use a compatible DashPay client, or try again and confirm replacing the saved details when asked." - )] - DashPayContactInfoRead { + /// Publishing contact details through platform-wallet failed. + #[error("Your contact details could not be saved. Check your connection, then try again.")] + DashPayContactInfoWriteFailed { #[source] - source: ContactInfoReadError, + source: std::sync::Arc, }, + /// Saving contact details needs the identity's index in its wallet, which + /// an identity added without its wallet does not have. + #[error( + "Contact details can be saved only for an identity loaded from its wallet. Load this identity from the wallet that created it, then try again." + )] + ContactInfoIdentityNotFromWallet, + + /// Contact details are kept only for established contacts. + #[error( + "You can save details only for people in your contacts. Wait until they accept your contact request, then try again." + )] + ContactInfoContactNotEstablished, + /// A direct contact-details update failed. The identity/contact envelope /// lets screens correlate a delayed failure with the exact pending write. #[error("{source}")] @@ -4823,15 +4820,11 @@ mod tests { #[test] fn a_contact_info_action_failure_shows_the_underlying_reason_to_the_user() { - let cause = TaskError::DashPayContactInfoRead { - source: ContactInfoReadError::DeserializeFailed, - }; + let cause = TaskError::ContactInfoContactNotEstablished; let wrapped = TaskError::DashPayContactInfoActionFailed { identity_id: Identifier::from([6; 32]), contact_id: Identifier::from([7; 32]), - source: Box::new(TaskError::DashPayContactInfoRead { - source: ContactInfoReadError::DeserializeFailed, - }), + source: Box::new(TaskError::ContactInfoContactNotEstablished), }; assert_eq!(wrapped.to_string(), cause.to_string()); diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index 406076e75..4ba25c5a6 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -879,6 +879,9 @@ pub enum BackendTaskSuccessResult { identity: Identifier, /// Contact whose private details were updated. contact_id: Identifier, + /// Whether the details reached Platform. `false` when they are saved on + /// this device only, until the identity has two contacts (DIP-0015). + published: bool, }, DashPayPaymentSent(String, String, u64), // (recipient, address, amount in duffs) /// Result of a [`FetchAvatar`](crate::backend_task::dashpay::DashPayTask::FetchAvatar): @@ -2480,7 +2483,6 @@ mod tests { #[test] fn dashpay_request_id_extracts_only_the_three_contact_actions() { use crate::backend_task::dashpay::DashPayTask; - use crate::model::dashpay::UnreadableContactInfoPolicy; let request_id = Identifier::from([0x11; 32]); let dashpay = |t: DashPayTask| BackendTask::DashPayTask(Box::new(t)); @@ -2496,7 +2498,6 @@ mod tests { dashpay_request_id(&dashpay(DashPayTask::RejectContactRequest { identity: qualified_identity(1), request_id, - unreadable: UnreadableContactInfoPolicy::Abort, })), Some(request_id) ); @@ -2504,7 +2505,6 @@ mod tests { dashpay_request_id(&dashpay(DashPayTask::CancelContactRequest { identity: qualified_identity(1), request_id, - unreadable: UnreadableContactInfoPolicy::Abort, })), Some(request_id) ); diff --git a/src/model/dashpay.rs b/src/model/dashpay.rs index a61e52098..c1b238a84 100644 --- a/src/model/dashpay.rs +++ b/src/model/dashpay.rs @@ -89,45 +89,33 @@ pub struct StoredProfile { pub updated_at: i64, } -/// What a `contactInfo` write does to the contact's accepted-accounts list. -/// -/// A `contactInfo` document is always written whole, so every write decides the -/// fate of the accounts the user has already accepted. A caller with no opinion -/// on them — unhiding a contact, renaming one — says [`Preserve`] and keeps the -/// stored list; only a caller that owns the list says [`Replace`]. -/// -/// [`Preserve`]: AcceptedAccounts::Preserve -/// [`Replace`]: AcceptedAccounts::Replace -#[derive(Debug, Clone, PartialEq, Eq, Default)] -pub enum AcceptedAccounts { - /// Keep the accounts already stored in the contact's `contactInfo`. - #[default] - Preserve, - /// Overwrite the stored accounts with exactly these. - Replace(Vec), -} - -/// What a whole-document write does to one optional contact detail. +/// What a contact details write does to one optional detail. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub enum ContactInfoField { - /// Keep the value already stored in the encrypted payload. + /// Keep the value currently saved for the contact. #[default] Preserve, /// Store this value, including `None` when clearing an optional field. Replace(T), } -/// How a write handles a present encrypted payload this client cannot read. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum UnreadableContactInfoPolicy { - /// Abort before overwriting data this client cannot preserve. - #[default] - Abort, - /// Replace the unreadable payload after the user explicitly confirms. - Overwrite, +/// The private details an identity keeps about one contact: its nickname, +/// note, and whether it is hidden. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct ContactDetails { + pub nickname: Option, + pub note: Option, + pub hidden: bool, +} + +impl ContactDetails { + /// Whether nothing is saved for the contact. + pub fn is_empty(&self) -> bool { + self.nickname.is_none() && self.note.is_none() && !self.hidden + } } -/// Explicit field-by-field intent for a whole encrypted `contactInfo` write. +/// Explicit field-by-field intent for a contact details write. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ContactInfoUpdate { /// Nickname update intent. @@ -136,10 +124,6 @@ pub struct ContactInfoUpdate { pub note: ContactInfoField>, /// Visibility update intent. pub display_hidden: ContactInfoField, - /// Accepted-account update intent. - pub accepted_accounts: AcceptedAccounts, - /// Policy for a present payload that cannot be read. - pub unreadable: UnreadableContactInfoPolicy, } impl ContactInfoUpdate { @@ -149,8 +133,6 @@ impl ContactInfoUpdate { nickname: ContactInfoField::Preserve, note: ContactInfoField::Preserve, display_hidden: ContactInfoField::Replace(display_hidden), - accepted_accounts: AcceptedAccounts::Preserve, - unreadable: UnreadableContactInfoPolicy::Abort, } } @@ -168,21 +150,27 @@ impl ContactInfoUpdate { nickname: Option, note: Option, display_hidden: bool, - accepted_accounts: Vec, ) -> Self { Self { nickname: ContactInfoField::Replace(nickname), note: ContactInfoField::Replace(note), display_hidden: ContactInfoField::Replace(display_hidden), - accepted_accounts: AcceptedAccounts::Replace(accepted_accounts), - unreadable: UnreadableContactInfoPolicy::Abort, } } - /// Allow replacement of unreadable stored data after explicit confirmation. - pub fn overwrite_unreadable(mut self) -> Self { - self.unreadable = UnreadableContactInfoPolicy::Overwrite; - self + /// The details to save: `current` with this update's replacements. + pub fn apply_to(&self, current: ContactDetails) -> ContactDetails { + fn pick(field: &ContactInfoField, current: T) -> T { + match field { + ContactInfoField::Preserve => current, + ContactInfoField::Replace(value) => value.clone(), + } + } + ContactDetails { + nickname: pick(&self.nickname, current.nickname), + note: pick(&self.note, current.note), + hidden: pick(&self.display_hidden, current.hidden), + } } } @@ -522,15 +510,41 @@ mod tests { ContactInfoField::Replace(Some("Met at the meetup".into())) ); assert_eq!(update.nickname, ContactInfoField::Preserve); - assert_eq!(update.accepted_accounts, AcceptedAccounts::Preserve); assert_eq!(update.display_hidden, ContactInfoField::Preserve); - assert_eq!(update.unreadable, UnreadableContactInfoPolicy::Abort); let cleared = ContactInfoUpdate::note(None); assert_eq!(cleared.note, ContactInfoField::Replace(None)); assert_eq!(cleared.display_hidden, ContactInfoField::Preserve); } + /// A write keeps every detail it does not replace. + #[test] + fn an_update_keeps_the_details_it_does_not_replace() { + let current = ContactDetails { + nickname: Some("Bao".into()), + note: Some("old".into()), + hidden: true, + }; + assert_eq!( + ContactInfoUpdate::note(Some("new".into())).apply_to(current.clone()), + ContactDetails { + note: Some("new".into()), + ..current.clone() + } + ); + assert_eq!( + ContactInfoUpdate::visibility(false).apply_to(current.clone()), + ContactDetails { + hidden: false, + ..current.clone() + } + ); + assert_eq!( + ContactInfoUpdate::replace_all(None, None, false).apply_to(current), + ContactDetails::default() + ); + } + #[test] fn contact_request_recipient_reads_the_to_user_id() { assert_eq!( diff --git a/src/ui/dashpay/contact_details.rs b/src/ui/dashpay/contact_details.rs index 8289eb575..4a9e3cfdc 100644 --- a/src/ui/dashpay/contact_details.rs +++ b/src/ui/dashpay/contact_details.rs @@ -4,12 +4,10 @@ use crate::backend_task::error::TaskError; use crate::backend_task::{BackendTask, BackendTaskSuccessResult}; use crate::context::AppContext; use crate::context::feature_gate::FeatureGate; -use crate::model::dashpay::{AcceptedAccounts, ContactInfoField, ContactInfoUpdate}; +use crate::model::dashpay::{ContactInfoField, ContactInfoUpdate}; use crate::model::fee_estimation::format_duffs_as_dash; use crate::model::qualified_identity::QualifiedIdentity; use crate::ui::components::MessageBanner; -use crate::ui::components::component_trait::Component; -use crate::ui::components::confirmation_dialog::{ConfirmationDialog, ConfirmationStatus}; use crate::ui::components::dashpay_subscreen_chooser_panel::add_dashpay_subscreen_chooser_panel; use crate::ui::components::info_popup::InfoPopup; use crate::ui::components::left_panel::add_left_panel; @@ -68,7 +66,6 @@ pub struct ContactDetailsScreen { loading: bool, show_info_popup: bool, needs_backend_fetch: bool, - overwrite_dialog: Option, pending_update: Option, } @@ -91,7 +88,6 @@ impl ContactDetailsScreen { loading: false, show_info_popup: false, needs_backend_fetch: true, - overwrite_dialog: None, pending_update: None, }; screen.load_from_database(); @@ -188,8 +184,6 @@ impl ContactDetailsScreen { Some(self.edit_note.clone()) }), display_hidden: ContactInfoField::Replace(self.edit_hidden), - accepted_accounts: AcceptedAccounts::Preserve, - unreadable: Default::default(), }; self.pending_update = Some(update.clone()); @@ -575,29 +569,6 @@ impl ScreenLike for ContactDetailsScreen { action |= island_central_panel(ui, |ui| self.render(ui)); - if let Some(dialog) = &mut self.overwrite_dialog { - match dialog.show(ui).inner.dialog_response { - Some(ConfirmationStatus::Confirmed) => { - if let Some(update) = self.pending_update.clone() { - self.loading = true; - action |= AppAction::BackendTask(BackendTask::DashPayTask(Box::new( - DashPayTask::UpdateContactInfo { - identity: self.identity.clone(), - contact_id: self.contact_id, - update: update.overwrite_unreadable(), - }, - ))); - } - self.overwrite_dialog = None; - } - Some(ConfirmationStatus::Canceled) => { - self.pending_update = None; - self.overwrite_dialog = None; - } - None => {} - } - } - // Show info popup if requested if self.show_info_popup { egui::CentralPanel::default() @@ -680,14 +651,19 @@ impl ScreenLike for ContactDetailsScreen { BackendTaskSuccessResult::DashPayContactInfoUpdated { identity, contact_id, + published, } => { if identity == self.identity.identity.id() && contact_id == self.contact_id { self.commit_pending_update(); - MessageBanner::set_global( - self.app_context.egui_ctx(), - "Contact information saved.", - MessageType::Success, - ); + let (message, kind) = if published { + ("Contact information saved.", MessageType::Success) + } else { + ( + crate::ui::identity::contacts::DETAILS_SAVED_ON_THIS_DEVICE, + MessageType::Info, + ) + }; + MessageBanner::set_global(self.app_context.egui_ctx(), message, kind); } } BackendTaskSuccessResult::DashPayContactsWithInfo { @@ -732,27 +708,6 @@ impl ScreenLike for ContactDetailsScreen { fn display_task_error(&mut self, error: &TaskError) -> bool { self.loading = false; - let is_matching_read_error = matches!( - error, - TaskError::DashPayContactInfoActionFailed { - identity_id, - contact_id, - source, - } if *identity_id == self.identity.identity.id() - && *contact_id == self.contact_id - && matches!(source.as_ref(), TaskError::DashPayContactInfoRead { .. }) - ); - if is_matching_read_error && self.pending_update.is_some() { - self.overwrite_dialog = Some( - ConfirmationDialog::new( - "Replace saved contact details?", - "This contact's saved details cannot be read. Continuing will save the nickname and note shown here and clear the accepted-account settings. You cannot undo this change.", - ) - .confirm_text(Some("Replace saved details")) - .danger_mode(true), - ); - return true; - } if matches!( error, TaskError::DashPayContactInfoActionFailed { diff --git a/src/ui/dashpay/contact_requests.rs b/src/ui/dashpay/contact_requests.rs index eaeb72e54..772268f12 100644 --- a/src/ui/dashpay/contact_requests.rs +++ b/src/ui/dashpay/contact_requests.rs @@ -4,7 +4,7 @@ use crate::backend_task::dashpay::errors::DashPayError; use crate::backend_task::error::TaskError; use crate::backend_task::{BackendTask, BackendTaskSuccessResult}; use crate::context::AppContext; -use crate::model::dashpay::{UnreadableContactInfoPolicy, contact_request_recipient}; +use crate::model::dashpay::contact_request_recipient; use crate::model::qualified_identity::QualifiedIdentity; use crate::model::wallet::Wallet; use crate::ui::components::component_trait::Component; @@ -65,7 +65,6 @@ pub struct ContactRequests { has_fetched_requests: bool, accept_confirmation_dialog: Option<(ConfirmationDialog, ContactRequest)>, reject_confirmation_dialog: Option<(ConfirmationDialog, ContactRequest)>, - overwrite_confirmation_dialog: Option, pub selected_wallet: Option>>, pub wallet_unlock_popup: WalletUnlockPopup, wallet_open_attempted: bool, @@ -92,7 +91,6 @@ impl ContactRequests { has_fetched_requests: false, accept_confirmation_dialog: None, reject_confirmation_dialog: None, - overwrite_confirmation_dialog: None, selected_wallet: None, wallet_unlock_popup: WalletUnlockPopup::new(), wallet_open_attempted: false, @@ -159,7 +157,6 @@ impl ContactRequests { self.pending_profile_fetches.clear(); self.request_in_flight = None; self.request_task_in_flight = None; - self.overwrite_confirmation_dialog = None; self.loading = false; } } @@ -382,7 +379,6 @@ impl ContactRequests { let request_task = DashPayTask::RejectContactRequest { identity: identity.clone(), request_id: request.request_id, - unreadable: UnreadableContactInfoPolicy::Abort, }; self.request_task_in_flight = Some(request_task.clone()); let task = BackendTask::DashPayTask(Box::new(request_task)); @@ -395,36 +391,6 @@ impl ContactRequests { } } - if let Some(dialog) = &mut self.overwrite_confirmation_dialog { - match dialog.show(ui).inner.dialog_response { - Some(ConfirmationStatus::Confirmed) => { - if let Some(DashPayTask::RejectContactRequest { - identity, - request_id, - .. - }) = self.request_task_in_flight.take() - { - let retry = DashPayTask::RejectContactRequest { - identity, - request_id, - unreadable: UnreadableContactInfoPolicy::Overwrite, - }; - self.request_task_in_flight = Some(retry.clone()); - self.loading = true; - action |= AppAction::BackendTask(BackendTask::DashPayTask(Box::new(retry))); - } - self.overwrite_confirmation_dialog = None; - } - Some(ConfirmationStatus::Canceled) => { - self.request_in_flight = None; - self.request_task_in_flight = None; - self.loading = false; - self.overwrite_confirmation_dialog = None; - } - None => {} - } - } - // Identity selector or no identities message let identities = self .app_context @@ -907,23 +873,6 @@ impl ScreenLike for ContactRequests { fn display_task_error(&mut self, error: &TaskError) -> bool { let matches_request = request_error_id(error).is_some_and(|id| self.request_in_flight.as_ref() == Some(id)); - if matches_request - && is_contact_info_read_error(error) - && matches!( - self.request_task_in_flight, - Some(DashPayTask::RejectContactRequest { .. }) - ) - { - self.overwrite_confirmation_dialog = Some( - ConfirmationDialog::new( - "Replace saved contact details?", - "This contact's saved details cannot be read. Continuing will decline the request and clear the saved nickname, note, and accepted-account settings. You cannot undo this change.", - ) - .confirm_text(Some("Replace saved details")) - .danger_mode(true), - ); - return true; - } if matches_request { self.request_in_flight = None; self.request_task_in_flight = None; @@ -1114,14 +1063,6 @@ fn request_error_id(error: &TaskError) -> Option<&Identifier> { } } -fn is_contact_info_read_error(error: &TaskError) -> bool { - matches!( - error, - TaskError::DashPayContactRequestActionFailed { source, .. } - if matches!(source.as_ref(), TaskError::DashPayContactInfoRead { .. }) - ) -} - /// Map a typed accept/reject error onto the screen-local error category that /// drives a dedicated affordance (the "Add Encryption Key" button). Returns /// `None` when no request-specific UI applies, leaving the global banner to diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index b8990febb..847478f3a 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -24,9 +24,7 @@ use crate::backend_task::BackendTask; use crate::backend_task::dashpay::{ContactData, DashPayTask}; use crate::context::AppContext; use crate::context::feature_gate::FeatureGate; -use crate::model::dashpay::{ - ContactInfoUpdate, MAX_CONTACT_NOTE_BYTES, UnreadableContactInfoPolicy, validate_contact_note, -}; +use crate::model::dashpay::{ContactInfoUpdate, MAX_CONTACT_NOTE_BYTES, validate_contact_note}; use crate::model::fee_estimation::format_credits_as_dash; use crate::model::qualified_identity::QualifiedIdentity; use crate::ui::ScreenType; @@ -62,6 +60,9 @@ pub const SAVING_NOTE_LABEL: &str = "Saving…"; pub const NOTE_UNCHANGED_TOOLTIP: &str = "There are no changes to save."; pub const NOTE_SAVE_TOOLTIP: &str = "Save this note on Dash Platform. Saving costs a small fee."; pub const NOTE_SAVED: &str = "Your note is saved."; +/// Shown when contact details are kept on this device only: DIP-0015 holds +/// them back until the identity has two contacts. +pub const DETAILS_SAVED_ON_THIS_DEVICE: &str = "Your contact details are saved on this device. They will sync to your other devices once this identity has two contacts."; const NOTE_SAVING_TOOLTIP: &str = "This contact's details are being saved."; pub const RECEIVED_HEADING: &str = "Received requests"; pub const ACTIVE_HEADING_PREFIX: &str = "Active contacts"; @@ -266,12 +267,10 @@ pub fn request_task( RequestAction::Declined => DashPayTask::RejectContactRequest { identity, request_id, - unreadable: UnreadableContactInfoPolicy::Abort, }, RequestAction::Cancelled => DashPayTask::CancelContactRequest { identity, request_id, - unreadable: UnreadableContactInfoPolicy::Abort, }, } } @@ -1738,22 +1737,6 @@ mod tests { } } - #[test] - fn unhide_leaves_the_accepted_accounts_alone() { - // The write replaces the whole contactInfo document. Unhiding says - // nothing about which accounts the user accepted, so it must not - // volunteer an empty list — that would erase every one of them. - let task = unhide_task(qualified_identity(id(1)), &hidden_contact(None, None)); - match task { - DashPayTask::UpdateContactInfo { update, .. } => assert_eq!( - update.accepted_accounts, - crate::model::dashpay::AcceptedAccounts::Preserve, - "unhiding must preserve the contact's accepted accounts, not overwrite them" - ), - other => panic!("expected UpdateContactInfo, got {other:?}"), - } - } - // --------------------------------------------------------------- // Hydration — both loads must survive the trip to `AppState`. // `AppAction`'s `|=` is last-writer-wins, so two separate diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index 582b589eb..550babaa1 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -14,9 +14,7 @@ use crate::backend_task::error::TaskError; use crate::backend_task::identity::IdentityTask; use crate::backend_task::{BackendTask, BackendTaskContext, BackendTaskSuccessResult}; use crate::context::AppContext; -use crate::model::dashpay::{ContactInfoField, UnreadableContactInfoPolicy}; -use crate::ui::components::component_trait::Component; -use crate::ui::components::confirmation_dialog::{ConfirmationDialog, ConfirmationStatus}; +use crate::model::dashpay::ContactInfoField; use crate::ui::components::left_panel::add_left_panel; use crate::ui::components::message_banner::{BannerHandle, MessageBanner, OptionBannerExt}; use crate::ui::components::styled::island_central_panel; @@ -26,7 +24,7 @@ use crate::ui::{MessageType, RootScreenType, ScreenLike, ScreenType}; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::platform::Identifier; use eframe::egui::{self, Context}; -use std::collections::{BTreeSet, HashMap, VecDeque}; +use std::collections::{BTreeSet, HashMap}; use std::sync::Arc; use super::home::HomeState; @@ -99,9 +97,7 @@ pub struct IdentityHubScreen { /// Breadcrumb-switcher view state (picker override + dropdown search /// buffers). The active identity itself is app-scoped on `AppContext`. selection: HubSelection, - contact_info_overwrite_dialog: Option<(ConfirmationDialog, ContactInfoTaskKey)>, pending_contact_info_tasks: HashMap, - pending_contact_info_confirmations: VecDeque, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] @@ -164,9 +160,7 @@ impl IdentityHubScreen { avatar_cache: crate::ui::state::AvatarCache::default(), pending_avatars: Vec::new(), selection: HubSelection::default(), - contact_info_overwrite_dialog: None, pending_contact_info_tasks: HashMap::new(), - pending_contact_info_confirmations: VecDeque::new(), } } @@ -174,9 +168,7 @@ impl IdentityHubScreen { let AppAction::BackendTask(BackendTask::DashPayTask(task)) = action else { return; }; - if can_confirm_contact_info_overwrite(task) - && let Some(key) = contact_info_task_key(task) - { + if let Some(key) = contact_info_task_key(task) { self.pending_contact_info_tasks .insert(key, task.as_ref().clone()); } @@ -200,49 +192,9 @@ impl IdentityHubScreen { } fn reset_contacts_for_identity_change(&mut self) { - release_guards_for_abandoned_confirmations( - &mut self.contacts_state, - self.pending_contact_info_confirmations.iter().chain( - self.contact_info_overwrite_dialog - .iter() - .map(|(_, key)| key), - ), - ); self.home_state = HomeState::default(); self.contacts_state.reset_for_identity_change(); self.pending_contact_info_tasks.clear(); - self.pending_contact_info_confirmations.clear(); - self.contact_info_overwrite_dialog = None; - } - - fn queue_contact_info_confirmation(&mut self, key: ContactInfoTaskKey) { - let already_showing = self - .contact_info_overwrite_dialog - .as_ref() - .is_some_and(|(_, shown_key)| *shown_key == key); - if already_showing || self.pending_contact_info_confirmations.contains(&key) { - return; - } - - self.pending_contact_info_confirmations.push_back(key); - } - - fn prepare_contact_info_dialog(&mut self) { - if self.contact_info_overwrite_dialog.is_some() { - return; - } - while let Some(key) = self.pending_contact_info_confirmations.pop_front() { - if let Some(task) = self.pending_contact_info_tasks.get(&key) { - let (title, message) = contact_info_confirmation_copy(task); - self.contact_info_overwrite_dialog = Some(( - ConfirmationDialog::new(title, message) - .confirm_text(Some("Replace saved details")) - .danger_mode(true), - key, - )); - break; - } - } } /// Clear the stale load-error banner so the next `landing()` call can try @@ -266,8 +218,8 @@ impl IdentityHubScreen { } /// Reset all identity-scoped state after the owning application context - /// changes. Abandoned confirmations release their guards; live paid actions - /// remain guarded, and stale guards are pruned during the contacts reset. + /// changes. Live paid actions remain guarded, and stale guards are pruned + /// during the contacts reset. pub(crate) fn reset_for_context_change(&mut self) { self.reset_contacts_for_identity_change(); self.settings_tab = SettingsTab::new(); @@ -380,13 +332,6 @@ impl IdentityHubScreen { if !matches!(error, TaskError::DashPayContactRequestActionFailed { .. }) { return false; } - if let Some(key) = contact_info_read_error_key(error) - && self.pending_contact_info_tasks.contains_key(&key) - { - self.contacts_state.invalidate(); - self.queue_contact_info_confirmation(key); - return true; - } if let Some(key) = contact_info_error_key(error) { self.pending_contact_info_tasks.remove(&key); } @@ -394,20 +339,12 @@ impl IdentityHubScreen { true } - /// Settle a failed direct contact details write: ask before overwriting - /// unreadable details, otherwise drop the pending write and release its - /// guard. Returns whether the hub took over telling the user. + /// Settle a failed direct contact details write: drop the pending write + /// and release its guard. The error banner tells the user. pub(crate) fn handle_contact_info_error(&mut self, error: &TaskError) -> bool { if !matches!(error, TaskError::DashPayContactInfoActionFailed { .. }) { return false; } - if let Some(key) = contact_info_read_error_key(error) - && self.pending_contact_info_tasks.contains_key(&key) - { - self.contacts_state.invalidate(); - self.queue_contact_info_confirmation(key); - return true; - } if let Some(key) = contact_info_error_key(error) { self.pending_contact_info_tasks.remove(&key); } @@ -688,32 +625,6 @@ impl ScreenLike for IdentityHubScreen { action = self.apply_breadcrumb_effect(effect); } - self.prepare_contact_info_dialog(); - if let Some((dialog, key)) = &mut self.contact_info_overwrite_dialog { - let key = *key; - match dialog.show(ui).inner.dialog_response { - Some(ConfirmationStatus::Confirmed) => { - if let Some(task) = self - .pending_contact_info_tasks - .get(&key) - .cloned() - .and_then(overwrite_unreadable_task) - { - self.pending_contact_info_tasks.insert(key, task.clone()); - action = AppAction::BackendTask(BackendTask::DashPayTask(Box::new(task))); - } - self.contact_info_overwrite_dialog = None; - } - Some(ConfirmationStatus::Canceled) => { - release_guards_for_abandoned_confirmations(&mut self.contacts_state, [&key]); - self.pending_contact_info_tasks.remove(&key); - self.contacts_state.invalidate(); - self.contact_info_overwrite_dialog = None; - } - None => {} - } - } - // Every part of the frame above has had its say; this is where the // action that leaves the frame is settled. A data load claims its one // dispatch slot when it is asked for, so it is asked for only here and @@ -845,6 +756,7 @@ impl ScreenLike for IdentityHubScreen { BackendTaskSuccessResult::DashPayContactInfoUpdated { identity, contact_id, + published, } => { let key = ContactInfoTaskKey::Direct { identity_id: *identity, @@ -854,11 +766,15 @@ impl ScreenLike for IdentityHubScreen { .finish_contact_info_write(identity, contact_id); if let Some(task) = self.pending_contact_info_tasks.remove(&key) { self.contacts_state.invalidate(); - MessageBanner::set_global( - self.app_context.egui_ctx(), - contact_info_saved_message(&task), - MessageType::Success, - ); + let (message, kind) = if *published { + (contact_info_saved_message(&task), MessageType::Success) + } else { + ( + super::contacts::DETAILS_SAVED_ON_THIS_DEVICE, + MessageType::Info, + ) + }; + MessageBanner::set_global(self.app_context.egui_ctx(), message, kind); } } // AppState delivers removals even while this root is hidden and owns the banner. @@ -906,7 +822,7 @@ impl ScreenLike for IdentityHubScreen { } fn display_backend_task_error(&mut self, context: &BackendTaskContext, error: &TaskError) { - // Wrapped errors retain the unreadable-details confirmation flow. + // Wrapped errors are settled by `handle_contact_info_error`. if !matches!(error, TaskError::DashPayContactInfoActionFailed { .. }) && let Some((identity_id, contact_id)) = context.dashpay_contact_info_target() { @@ -936,10 +852,7 @@ impl ScreenLike for IdentityHubScreen { return true; } if self.handle_contact_request_error(error) { - return matches!( - contact_info_read_error_key(error), - Some(key) if self.pending_contact_info_tasks.contains_key(&key) - ); + return false; } if self.handle_contact_info_error(error) { return true; @@ -979,23 +892,6 @@ fn release_contact_info_write_for_error( } } -/// Release the request and note-save guards of confirmations that will never -/// be answered: no task is left running for them. -fn release_guards_for_abandoned_confirmations<'a>( - state: &mut super::contacts::ContactsState, - keys: impl IntoIterator, -) { - for key in keys { - match key { - ContactInfoTaskKey::Request(request_id) => state.release_request(request_id), - ContactInfoTaskKey::Direct { - identity_id, - contact_id, - } => state.release_contact_info_write(identity_id, contact_id), - } - } -} - /// Whether a captured contactInfo write is a private-note save rather than an /// unhide. fn is_note_save(task: &DashPayTask) -> bool { @@ -1015,61 +911,6 @@ fn contact_info_saved_message(task: &DashPayTask) -> &'static str { } } -fn can_confirm_contact_info_overwrite(task: &DashPayTask) -> bool { - match task { - DashPayTask::UpdateContactInfo { update, .. } => { - update.unreadable == UnreadableContactInfoPolicy::Abort - } - DashPayTask::RejectContactRequest { unreadable, .. } - | DashPayTask::CancelContactRequest { unreadable, .. } => { - *unreadable == UnreadableContactInfoPolicy::Abort - } - _ => false, - } -} - -/// Title and body for the overwrite confirmation, one complete message per -/// action so each stays a single translatable sentence group. Only the contact -/// case names an identifier: a request ID is not something the user has seen, -/// and the details at risk belong to the contact, not to the request. -fn contact_info_confirmation_copy(task: &DashPayTask) -> (&'static str, String) { - use crate::ui::identity::identity_pill::shorten_id; - use dash_sdk::dpp::platform_value::string_encoding::Encoding; - - match task { - DashPayTask::UpdateContactInfo { contact_id, .. } if is_note_save(task) => { - let contact = shorten_id(&contact_id.to_string(Encoding::Base58)); - ( - "Save note and replace saved details?", - format!( - "The saved details for contact {contact} cannot be read. Saving this note will clear the contact's saved nickname and accepted-account settings. You cannot undo this change." - ), - ) - } - DashPayTask::UpdateContactInfo { contact_id, .. } => { - let contact = shorten_id(&contact_id.to_string(Encoding::Base58)); - ( - "Unhide contact and replace saved details?", - format!( - "The saved details for contact {contact} cannot be read. Unhiding this contact will clear its saved nickname, note, and accepted-account settings. You cannot undo this change." - ), - ) - } - DashPayTask::RejectContactRequest { .. } => ( - "Decline request and replace saved details?", - "The saved details for this contact cannot be read. Declining the request will clear the contact's saved nickname, note, and accepted-account settings. You cannot undo this change.".to_string(), - ), - DashPayTask::CancelContactRequest { .. } => ( - "Cancel request and replace saved details?", - "The saved details for this contact cannot be read. Withdrawing the request will clear the contact's saved nickname, note, and accepted-account settings. You cannot undo this change.".to_string(), - ), - _ => ( - "Replace saved contact details?", - "The saved details for this contact cannot be read. Continuing will clear the contact's saved nickname, note, and accepted-account settings. You cannot undo this change.".to_string(), - ), - } -} - fn contact_info_task_key(task: &DashPayTask) -> Option { match task { DashPayTask::UpdateContactInfo { @@ -1088,39 +929,6 @@ fn contact_info_task_key(task: &DashPayTask) -> Option { } } -fn overwrite_unreadable_task(task: DashPayTask) -> Option { - match task { - DashPayTask::UpdateContactInfo { - identity, - contact_id, - update, - } => Some(DashPayTask::UpdateContactInfo { - identity, - contact_id, - update: update.overwrite_unreadable(), - }), - DashPayTask::RejectContactRequest { - identity, - request_id, - .. - } => Some(DashPayTask::RejectContactRequest { - identity, - request_id, - unreadable: UnreadableContactInfoPolicy::Overwrite, - }), - DashPayTask::CancelContactRequest { - identity, - request_id, - .. - } => Some(DashPayTask::CancelContactRequest { - identity, - request_id, - unreadable: UnreadableContactInfoPolicy::Overwrite, - }), - _ => None, - } -} - fn contact_info_error_key(error: &TaskError) -> Option { match error { TaskError::DashPayContactInfoActionFailed { @@ -1138,18 +946,6 @@ fn contact_info_error_key(error: &TaskError) -> Option { } } -fn contact_info_read_error_key(error: &TaskError) -> Option { - match error { - TaskError::DashPayContactInfoActionFailed { source, .. } - | TaskError::DashPayContactRequestActionFailed { source, .. } - if matches!(source.as_ref(), TaskError::DashPayContactInfoRead { .. }) => - { - contact_info_error_key(error) - } - _ => None, - } -} - /// Whether a backend result loaded for `result_identity` may still be applied /// while `selected` is the identity on screen. /// @@ -2189,28 +1985,6 @@ mod tests { assert!(state.is_in_flight(&id(3))); } - #[test] - fn abandoning_confirmations_releases_only_their_request_guards() { - let mut state = ContactsState::default(); - assert!(state.begin_request(id(1))); - assert!(state.begin_request(id(2))); - let keys = [ - ContactInfoTaskKey::Request(id(2)), - ContactInfoTaskKey::Direct { - identity_id: id(3), - contact_id: id(4), - }, - ]; - - release_guards_for_abandoned_confirmations(&mut state, &keys); - - assert!(state.is_in_flight(&id(1))); - assert!( - !state.is_in_flight(&id(2)), - "a discarded confirmation has no running task left to protect" - ); - } - fn contact_info_task(update: crate::model::dashpay::ContactInfoUpdate) -> DashPayTask { DashPayTask::UpdateContactInfo { identity: hub_identity(id(1)), @@ -2240,7 +2014,7 @@ mod tests { } #[test] - fn a_saved_note_and_an_unhide_confirm_differently() { + fn a_saved_note_and_an_unhide_report_differently() { use crate::model::dashpay::ContactInfoUpdate; let note = contact_info_task(ContactInfoUpdate::note(Some("Bao".into()))); @@ -2255,46 +2029,6 @@ mod tests { contact_info_saved_message(&unhide), "This contact is back in your list." ); - - let (title, message) = contact_info_confirmation_copy(¬e); - assert_eq!(title, "Save note and replace saved details?"); - assert!( - message.contains("nickname") && !message.contains("Unhiding"), - "the overwrite warning names what a note save clears: {message}" - ); - let (title, _) = contact_info_confirmation_copy(&unhide); - assert_eq!(title, "Unhide contact and replace saved details?"); - } - - #[test] - fn abandoning_a_note_save_confirmation_releases_its_guard() { - let mut state = ContactsState::default(); - assert!(state.begin_request(id(2))); - state.record_contacts(vec![crate::backend_task::dashpay::ContactData { - identity_id: id(4), - nickname: None, - note: None, - is_hidden: false, - account_reference: 0, - username: None, - display_name: None, - avatar_url: None, - bio: None, - }]); - state.select_contact(&id(4)); - *state.detail_mut().note_mut(&id(4)).expect("draft") = "Bao".into(); - assert!(state.detail_mut().begin_save(id(3), id(4)).is_some()); - - release_guards_for_abandoned_confirmations( - &mut state, - &[ContactInfoTaskKey::Direct { - identity_id: id(3), - contact_id: id(4), - }], - ); - - assert!(!state.detail().is_writing(&id(3), &id(4))); - assert!(state.is_in_flight(&id(2)), "unrelated request guards stay"); } #[test] @@ -2328,35 +2062,4 @@ mod tests { ); assert!(!state.detail().is_writing(&id(3), &id(4))); } - - #[test] - fn concurrent_contact_info_errors_keep_distinct_retry_keys() { - use crate::backend_task::error::ContactInfoReadError; - - let request_error = TaskError::DashPayContactRequestActionFailed { - request_id: id(2), - source: Box::new(TaskError::DashPayContactInfoRead { - source: ContactInfoReadError::DeserializeFailed, - }), - }; - let direct_error = TaskError::DashPayContactInfoActionFailed { - identity_id: id(3), - contact_id: id(4), - source: Box::new(TaskError::DashPayContactInfoRead { - source: ContactInfoReadError::DeserializeFailed, - }), - }; - - assert_eq!( - contact_info_read_error_key(&request_error), - Some(ContactInfoTaskKey::Request(id(2))) - ); - assert_eq!( - contact_info_read_error_key(&direct_error), - Some(ContactInfoTaskKey::Direct { - identity_id: id(3), - contact_id: id(4), - }) - ); - } } diff --git a/src/wallet_backend/contact_info.rs b/src/wallet_backend/contact_info.rs new file mode 100644 index 000000000..9f900c80a --- /dev/null +++ b/src/wallet_backend/contact_info.rs @@ -0,0 +1,451 @@ +//! DashPay `contactInfo` (DIP-0015) through platform-wallet. +//! +//! platform-wallet fetches, matches, encodes and publishes `contactInfo` +//! documents itself; it asks the host only to seal and open their two +//! ciphertexts. [`ContactInfoCrypto`] answers those two calls from the wallet +//! seed the secret seam lends for one operation. The child keys come from +//! platform-wallet's own `derive_contact_info_keys`, the AES steps from the +//! `platform-encryption` crate it uses, so both sides always agree. + +use std::collections::BTreeMap; +use std::sync::Arc; + +use dash_sdk::dpp::dashcore::Network; +use dash_sdk::dpp::dashcore::secp256k1::{PublicKey, SecretKey}; +use dash_sdk::dpp::identity::accessors::IdentityGettersV0; +use dash_sdk::dpp::key_wallet::bip32::{ + ChildNumber, DerivationPath, ExtendedPubKey, KeyDerivationType, +}; +use dash_sdk::dpp::key_wallet::wallet::Wallet; +use dash_sdk::dpp::key_wallet::wallet::initialization::WalletAccountCreationOptions; +use dash_sdk::platform::Identifier; +use platform_wallet::error::PlatformWalletError; +use platform_wallet::wallet::identity::crypto::contact_info::{ + ContactInfoKeys, derive_contact_info_keys, +}; +use platform_wallet::wallet::identity::network::{ + ContactCryptoProvider, ContactInfoOpened, ContactInfoPublishOutcome, ContactInfoSealed, + identity_auth_derivation_path_for_type, +}; +use zeroize::Zeroizing; + +use crate::backend_task::error::TaskError; +use crate::model::dashpay::ContactDetails; +use crate::model::qualified_identity::QualifiedIdentity; +use crate::wallet_backend::{SecretScope, WalletBackend}; + +impl WalletBackend { + /// Refresh the contact details platform-wallet holds for the identities + /// of the wallet that manages `owner`. Does nothing when no wallet does. + pub(crate) async fn dashpay_sync_contact_infos( + &self, + owner: &Identifier, + ) -> Result<(), TaskError> { + let Some(wallet) = self.find_wallet_for_identity(owner).await else { + return Ok(()); + }; + wallet + .identity() + .dashpay() + .sync_contact_infos() + .await + .map(|_| ()) + .map_err(|source| TaskError::WalletBackend { + source: Arc::new(source), + }) + } + + /// The details platform-wallet holds for each of `owner`'s established + /// contacts. Empty when no wallet manages `owner`. + pub(crate) async fn dashpay_contact_details( + &self, + owner: &Identifier, + ) -> BTreeMap { + let Some(wallet) = self.find_wallet_for_identity(owner).await else { + return BTreeMap::new(); + }; + let state = wallet.state().await; + let Some(managed) = state.identity_manager.managed_identity(owner) else { + return BTreeMap::new(); + }; + managed + .dashpay() + .established_contacts() + .values() + .map(|contact| { + ( + contact.contact_identity_id, + ContactDetails { + nickname: contact.alias.clone(), + note: contact.note.clone(), + hidden: contact.is_hidden, + }, + ) + }) + .collect() + } + + /// Save `details` for `contact_id` and publish them through + /// platform-wallet, which writes the identity's `contactInfo` document. + /// + /// # Errors + /// + /// Before platform-wallet changes anything: the identity is not managed + /// by its DashPay wallet or has no wallet identity index + /// ([`TaskError::ContactInfoIdentityNotFromWallet`]), or `contact_id` is + /// not an established contact + /// ([`TaskError::ContactInfoContactNotEstablished`]). A failed publish is + /// [`TaskError::DashPayContactInfoWriteFailed`]. + pub(crate) async fn dashpay_set_contact_info( + &self, + identity: &QualifiedIdentity, + contact_id: &Identifier, + details: ContactDetails, + ) -> Result { + let owner = identity.identity.id(); + let seed_hash = identity + .dashpay_wallet_seed_hash() + .ok_or(TaskError::ContactInfoIdentityNotFromWallet)?; + let wallet = self.resolve_wallet(&seed_hash).await?; + let identity_index = { + let state = wallet.state().await; + let managed = state.identity_manager.managed_identity(&owner); + contact_info_write_index( + managed.and_then(|managed| managed.identity_index), + managed.is_some_and(|managed| { + managed + .dashpay() + .established_contacts() + .contains_key(contact_id) + }), + )? + }; + let network = identity.network; + let identity_wallet = wallet.identity(); + let dashpay = identity_wallet.dashpay(); + + self.secret_access() + .with_secret_session(&SecretScope::HdSeed { seed_hash }, async |session| { + let plaintext = session.plaintext(); + let seed = plaintext + .expose_hd_seed() + .ok_or(TaskError::ContactWalletSeedUnavailable)?; + let crypto = ContactInfoCrypto::new(seed, network, identity_index); + dashpay + .set_contact_info_with_external_signer( + &owner, + contact_id, + details.nickname, + details.note, + details.hidden, + identity, + &crypto, + ) + .await + .map_err(|source| TaskError::DashPayContactInfoWriteFailed { + source: Arc::new(source), + }) + }) + .await + } +} + +/// The wallet identity index a contact details write derives beneath, +/// checked before platform-wallet changes any local state. +fn contact_info_write_index( + identity_index: Option, + contact_is_established: bool, +) -> Result { + let identity_index = identity_index.ok_or(TaskError::ContactInfoIdentityNotFromWallet)?; + if !contact_is_established { + return Err(TaskError::ContactInfoContactNotEstablished); + } + Ok(identity_index) +} + +/// Seals and opens `contactInfo` ciphertexts for one wallet identity. +/// +/// Holds a borrow of the seed for one operation only; it never copies the +/// seed out of that operation. +pub(crate) struct ContactInfoCrypto<'a> { + seed: &'a [u8; 64], + network: Network, + identity_index: u32, +} + +impl<'a> ContactInfoCrypto<'a> { + pub(crate) fn new(seed: &'a [u8; 64], network: Network, identity_index: u32) -> Self { + Self { + seed, + network, + identity_index, + } + } + + /// The two AES keys beneath `root_path`, derived by platform-wallet. + /// + /// `root_path` must be one of this identity's key paths: any other root is + /// refused, so a request can never select another identity's keys. + #[expect( + clippy::result_large_err, + reason = "ContactCryptoProvider fixes PlatformWalletError as the error type" + )] + fn keys( + &self, + root_path: &DerivationPath, + derivation_index: u32, + ) -> Result { + let key_id = match root_path.len().checked_sub(1).map(|last| root_path[last]) { + Some(ChildNumber::Hardened { index }) => index, + _ => return Err(foreign_root()), + }; + let own_root = identity_auth_derivation_path_for_type( + self.network, + KeyDerivationType::ECDSA, + self.identity_index, + key_id, + )?; + if own_root != *root_path { + return Err(foreign_root()); + } + let wallet = + Wallet::from_seed_bytes(*self.seed, self.network, WalletAccountCreationOptions::None) + .map_err(|error| PlatformWalletError::KeyDerivation(error.to_string()))?; + derive_contact_info_keys( + &wallet, + self.network, + self.identity_index, + key_id, + derivation_index, + ) + } +} + +fn foreign_root() -> PlatformWalletError { + PlatformWalletError::InvalidParameter( + "contactInfo root is not a key path of this identity".to_string(), + ) +} + +/// The provider serves `contactInfo` only; contact requests, invitations and +/// auto-accept keys go through their own paths. +fn not_contact_info() -> PlatformWalletError { + PlatformWalletError::InvalidParameter( + "this crypto provider serves contactInfo only".to_string(), + ) +} + +#[async_trait::async_trait] +impl ContactCryptoProvider for ContactInfoCrypto<'_> { + async fn receiving_xpub( + &self, + _path: &DerivationPath, + ) -> Result { + Err(not_contact_info()) + } + + async fn ecdh_shared_secret( + &self, + _path: &DerivationPath, + _peer: &PublicKey, + ) -> Result, PlatformWalletError> { + Err(not_contact_info()) + } + + async fn export_auto_accept_private_key( + &self, + _path: &DerivationPath, + ) -> Result { + Err(not_contact_info()) + } + + async fn export_invitation_private_key( + &self, + _path: &DerivationPath, + ) -> Result { + Err(not_contact_info()) + } + + async fn account_reference( + &self, + _path: &DerivationPath, + _compact_xpub: &[u8], + _account_index: u32, + _version: u32, + ) -> Result { + Err(not_contact_info()) + } + + async fn unmask_account_reference( + &self, + _path: &DerivationPath, + _compact_xpub: &[u8], + _account_reference: u32, + ) -> Result<(u32, u32), PlatformWalletError> { + Err(not_contact_info()) + } + + async fn contact_info_seal( + &self, + root_path: &DerivationPath, + derivation_index: u32, + contact_id: &[u8; 32], + private_data_plaintext: &[u8], + private_data_iv: &[u8; 16], + ) -> Result { + let keys = self.keys(root_path, derivation_index)?; + Ok(ContactInfoSealed { + enc_to_user_id: platform_encryption::encrypt_enc_to_user_id( + &keys.enc_to_user_id_key, + contact_id, + ), + private_data: platform_encryption::encrypt_private_data( + &keys.private_data_key, + private_data_iv, + private_data_plaintext, + ), + }) + } + + async fn contact_info_open( + &self, + root_path: &DerivationPath, + derivation_index: u32, + enc_to_user_id: &[u8; 32], + private_data_blob: &[u8], + ) -> Result { + let keys = self.keys(root_path, derivation_index)?; + let private_data = + platform_encryption::decrypt_private_data(&keys.private_data_key, private_data_blob) + .map_err(|error| { + PlatformWalletError::InvalidIdentityData(format!( + "contactInfo privateData could not be decrypted: {error}" + )) + })?; + Ok(ContactInfoOpened { + contact_id: platform_encryption::decrypt_enc_to_user_id( + &keys.enc_to_user_id_key, + enc_to_user_id, + ), + private_data, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const SEED: [u8; 64] = [0x42; 64]; + const NETWORK: Network = Network::Testnet; + const IDENTITY_INDEX: u32 = 1; + + fn root(identity_index: u32, key_id: u32) -> DerivationPath { + identity_auth_derivation_path_for_type( + NETWORK, + KeyDerivationType::ECDSA, + identity_index, + key_id, + ) + .expect("root path") + } + + fn upstream_keys(key_id: u32, derivation_index: u32) -> ContactInfoKeys { + let wallet = Wallet::from_seed_bytes(SEED, NETWORK, WalletAccountCreationOptions::None) + .expect("wallet"); + derive_contact_info_keys(&wallet, NETWORK, IDENTITY_INDEX, key_id, derivation_index) + .expect("upstream keys") + } + + /// What this provider seals, platform-wallet's own keys open: the + /// documents are readable by every client that uses platform-wallet. + #[tokio::test] + async fn sealed_details_open_with_platform_wallet_keys() { + let crypto = ContactInfoCrypto::new(&SEED, NETWORK, IDENTITY_INDEX); + let contact = [7u8; 32]; + let iv = [3u8; 16]; + + let sealed = crypto + .contact_info_seal(&root(IDENTITY_INDEX, 2), 5, &contact, b"note", &iv) + .await + .expect("seal"); + + let keys = upstream_keys(2, 5); + assert_eq!( + platform_encryption::decrypt_enc_to_user_id( + &keys.enc_to_user_id_key, + &sealed.enc_to_user_id + ), + contact + ); + assert_eq!( + platform_encryption::decrypt_private_data(&keys.private_data_key, &sealed.private_data) + .expect("decrypt"), + b"note" + ); + } + + /// A document platform-wallet sealed opens here. + #[tokio::test] + async fn opens_what_platform_wallet_sealed() { + let crypto = ContactInfoCrypto::new(&SEED, NETWORK, IDENTITY_INDEX); + let keys = upstream_keys(2, 0); + let contact = [9u8; 32]; + let enc = platform_encryption::encrypt_enc_to_user_id(&keys.enc_to_user_id_key, &contact); + let blob = + platform_encryption::encrypt_private_data(&keys.private_data_key, &[1; 16], b"alias"); + + let opened = crypto + .contact_info_open(&root(IDENTITY_INDEX, 2), 0, &enc, &blob) + .await + .expect("open"); + + assert_eq!(opened.contact_id, contact); + assert_eq!(opened.private_data, b"alias"); + } + + /// A root that belongs to another wallet identity is refused. + #[tokio::test] + async fn another_identitys_root_is_refused() { + let crypto = ContactInfoCrypto::new(&SEED, NETWORK, IDENTITY_INDEX); + let result = crypto + .contact_info_seal(&root(IDENTITY_INDEX + 1, 2), 0, &[0; 32], b"", &[0; 16]) + .await; + assert!(matches!( + result, + Err(PlatformWalletError::InvalidParameter(_)) + )); + } + + /// A write is refused before platform-wallet runs when the identity has no + /// wallet index or the contact is not established. + #[test] + fn a_write_needs_a_wallet_identity_and_an_established_contact() { + assert!(matches!( + contact_info_write_index(None, true), + Err(TaskError::ContactInfoIdentityNotFromWallet) + )); + assert!(matches!( + contact_info_write_index(Some(3), false), + Err(TaskError::ContactInfoContactNotEstablished) + )); + assert_eq!(contact_info_write_index(Some(3), true).expect("index"), 3); + } + + /// Everything other than contactInfo is refused rather than served. + #[tokio::test] + async fn other_crypto_requests_are_refused() { + let crypto = ContactInfoCrypto::new(&SEED, NETWORK, IDENTITY_INDEX); + let path = root(IDENTITY_INDEX, 0); + assert!(crypto.receiving_xpub(&path).await.is_err()); + assert!(crypto.export_auto_accept_private_key(&path).await.is_err()); + assert!(crypto.export_invitation_private_key(&path).await.is_err()); + assert!(crypto.account_reference(&path, &[], 0, 0).await.is_err()); + assert!( + crypto + .unmask_account_reference(&path, &[], 0) + .await + .is_err() + ); + } +} diff --git a/src/wallet_backend/dashpay.rs b/src/wallet_backend/dashpay.rs index 20bc155ab..53194abed 100644 --- a/src/wallet_backend/dashpay.rs +++ b/src/wallet_backend/dashpay.rs @@ -36,7 +36,6 @@ use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::key_wallet::wallet::Wallet; use dash_sdk::dpp::key_wallet::wallet::initialization::WalletAccountCreationOptions; use dash_sdk::platform::Identifier; -use serde::{Deserialize, Serialize}; use zeroize::Zeroizing; use platform_wallet::wallet::identity::types::dashpay::contact_request::ContactRequest; @@ -240,8 +239,9 @@ const KV_PREFIX_DECLINED: &str = "det:dashpay:declined:"; /// opposite directions: withdrawing our request to Bob says nothing about a /// request Bob later sends us, and a single marker would silently hide it. const KV_PREFIX_WITHDRAWN: &str = "det:dashpay:withdrawn:"; -/// Durable recovery journal for paid decline/cancel visibility transitions. -/// Value: [`ContactRequestActionPhase`]. Scope: the acting identity. +/// Recovery journal older versions kept while a decline or withdrawal wrote +/// contact details. Declines and withdrawals only clear it. Scope: the +/// acting identity. const KV_PREFIX_REQUEST_ACTION: &str = "det:dashpay:request_action:"; /// DET-local `(created_at, updated_at)` timestamps for an entity (contact, request). /// Value: `(i64, i64)` encoded by the [`DetKv`] schema. Scope: [`DetScope::Global`]. @@ -342,7 +342,9 @@ impl ContactRequestActionKind { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +/// The journal value older versions stored; tests seed such records. +#[cfg(test)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub(crate) enum ContactRequestActionPhase { HideIntent, HideCommitted, @@ -1192,6 +1194,48 @@ impl WalletBackend { self.put_marker(owner, KV_PREFIX_DECLINED, counterparty_id) } + /// Ignore `sender`'s contact requests in platform-wallet, as declining + /// does. Local only: nothing is published, so the decline stays on this + /// device. Does nothing when no wallet manages `owner`. + pub(crate) async fn dashpay_ignore_contact_sender( + &self, + owner: &Identifier, + sender: &Identifier, + ) -> Result<(), TaskError> { + let Some(wallet) = self.find_wallet_for_identity(owner).await else { + return Ok(()); + }; + wallet + .identity() + .dashpay() + .ignore_contact_sender(owner, sender) + .await + .map_err(|source| TaskError::WalletBackend { + source: Arc::new(source), + }) + } + + /// Undo [`Self::dashpay_ignore_contact_sender`]: platform-wallet skips an + /// ignored sender's requests entirely, so re-engaging with them must + /// lift the ignore or their reply never establishes the contact. + pub(crate) async fn dashpay_unignore_contact_sender( + &self, + owner: &Identifier, + sender: &Identifier, + ) -> Result<(), TaskError> { + let Some(wallet) = self.find_wallet_for_identity(owner).await else { + return Ok(()); + }; + wallet + .identity() + .dashpay() + .unignore_contact_sender(owner, sender) + .await + .map_err(|source| TaskError::WalletBackend { + source: Arc::new(source), + }) + } + /// Whether `owner` declined the incoming contact request from /// `counterparty_id`. Reads the same owner-scoped marker /// [`dashpay_mark_declined`](Self::dashpay_mark_declined) writes. @@ -1251,21 +1295,6 @@ impl WalletBackend { self.delete_marker(owner, KV_PREFIX_WITHDRAWN, counterparty_id) } - pub(crate) fn dashpay_contact_request_action_phase( - &self, - owner: &Identifier, - request_id: &Identifier, - kind: ContactRequestActionKind, - ) -> Result, TaskError> { - let owner_buf = owner.to_buffer(); - self.kv() - .get( - DetScope::Identity(&owner_buf), - &request_action_key(kind, request_id), - ) - .map_err(|source| TaskError::DashpaySidecarStorage { source }) - } - pub(crate) async fn dashpay_lock_contact_request_action( &self, owner: &Identifier, @@ -1277,23 +1306,6 @@ impl WalletBackend { .await } - pub(crate) fn dashpay_set_contact_request_action_phase( - &self, - owner: &Identifier, - request_id: &Identifier, - kind: ContactRequestActionKind, - phase: ContactRequestActionPhase, - ) -> Result<(), TaskError> { - let owner_buf = owner.to_buffer(); - self.kv() - .put( - DetScope::Identity(&owner_buf), - &request_action_key(kind, request_id), - &phase, - ) - .map_err(|source| TaskError::DashpaySidecarStorage { source }) - } - pub(crate) fn dashpay_clear_contact_request_action( &self, owner: &Identifier, @@ -1544,7 +1556,7 @@ impl WalletBackend { /// `identity_manager` for the id. `None` if no registered wallet /// knows about it (e.g. pre-registration, wrong network, observed- /// only identities that were never indexed). - async fn find_wallet_for_identity( + pub(super) async fn find_wallet_for_identity( &self, identity_id: &Identifier, ) -> Option> { diff --git a/src/wallet_backend/mod.rs b/src/wallet_backend/mod.rs index f1aeb5fc8..79275e506 100644 --- a/src/wallet_backend/mod.rs +++ b/src/wallet_backend/mod.rs @@ -24,6 +24,7 @@ pub mod auth_pubkey_cache; #[cfg(not(any(test, feature = "bench")))] pub(crate) mod auth_pubkey_cache; mod avatar_cache; +mod contact_info; mod contact_profile_cache; mod coordinator_gate; mod dashpay; @@ -79,8 +80,7 @@ pub(crate) mod wallet_seed_store; pub use dashpay::DashpayView; pub(crate) use dashpay::{ - ContactRequestActionKind, ContactRequestActionPhase, derive_contact_info_encryption_keys, - derive_contact_xpub_material, + ContactRequestActionKind, derive_contact_info_encryption_keys, derive_contact_xpub_material, }; pub(crate) use det_platform_signer::{DetPlatformSigner, PlatformPathIndex}; diff --git a/tests/backend-e2e/dashpay_tasks.rs b/tests/backend-e2e/dashpay_tasks.rs index c1ae089f8..7f6dcae8e 100644 --- a/tests/backend-e2e/dashpay_tasks.rs +++ b/tests/backend-e2e/dashpay_tasks.rs @@ -19,9 +19,7 @@ use crate::framework::task_runner::{run_task, run_task_with_nonce_retry}; use dash_evo_tool::backend_task::dashpay::DashPayTask; use dash_evo_tool::backend_task::identity::IdentityTask; use dash_evo_tool::backend_task::{BackendTask, BackendTaskSuccessResult}; -use dash_evo_tool::model::dashpay::{ - ContactInfoUpdate, ProfileSnapshot, UnreadableContactInfoPolicy, -}; +use dash_evo_tool::model::dashpay::{ContactInfoUpdate, ProfileSnapshot}; use dash_evo_tool::model::qualified_identity::qualified_identity_public_key::QualifiedIdentityPublicKey; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; @@ -701,7 +699,6 @@ async fn step_update_contact_info( Some("Test Nickname".into()), Some("E2E note".into()), false, - vec![0], ), })); @@ -713,6 +710,7 @@ async fn step_update_contact_info( BackendTaskSuccessResult::DashPayContactInfoUpdated { identity, contact_id: id, + .. } => { assert_eq!(identity, identity_b_id, "update should belong to B"); assert_eq!( @@ -1115,7 +1113,6 @@ async fn tc_043_reject_contact_request() { let reject_task = BackendTask::DashPayTask(Box::new(DashPayTask::RejectContactRequest { identity: qi_c, request_id, - unreadable: UnreadableContactInfoPolicy::Abort, })); let reject_result = run_task(&ctx.app_context, reject_task) .await diff --git a/tests/kittest/identity_hub_contact_detail.rs b/tests/kittest/identity_hub_contact_detail.rs index 8b9b7352f..849695673 100644 --- a/tests/kittest/identity_hub_contact_detail.rs +++ b/tests/kittest/identity_hub_contact_detail.rs @@ -12,9 +12,11 @@ use dash_evo_tool::backend_task::dashpay::{ContactData, DashPayTask}; use dash_evo_tool::backend_task::{BackendTask, BackendTaskContext, BackendTaskSuccessResult}; use dash_evo_tool::model::dashpay::ContactInfoField; use dash_evo_tool::ui::ScreenLike; +use dash_evo_tool::ui::components::MessageBanner; use dash_evo_tool::ui::identity::IdentityHubTab; use dash_evo_tool::ui::identity::contacts::{ - DETAIL_HEADING, NO_SELECTION, NOTE_HEADING, SAVE_NOTE_LABEL, SAVING_NOTE_LABEL, + DETAIL_HEADING, DETAILS_SAVED_ON_THIS_DEVICE, NO_SELECTION, NOTE_HEADING, NOTE_SAVED, + SAVE_NOTE_LABEL, SAVING_NOTE_LABEL, }; use dash_sdk::platform::Identifier; use egui::accesskit::Role; @@ -268,6 +270,7 @@ fn save_note_shows_the_fee_first_and_sends_the_note_once() { BackendTaskSuccessResult::DashPayContactInfoUpdated { identity: owner, contact_id: Identifier::from(CONTACT), + published: true, }, ); hub.run_steps(4); @@ -287,6 +290,48 @@ fn save_note_shows_the_fee_first_and_sends_the_note_once() { }); } +/// DIP-0015 holds contact details back until the identity has two contacts; +/// the user is told the note is kept on this device instead of "saved". +#[test] +fn a_note_kept_on_this_device_says_so() { + with_isolated_data_dir(|| { + let (_runtime, app_context) = fresh_app_context(); + let (mut hub, owner) = hub_with_bao_selected(&app_context, WIDE, None); + note_editor(&hub).focus(); + hub.run(); + note_editor(&hub).type_text("Met at the meetup"); + hub.run(); + hub.get_by_role_and_label(Role::Button, SAVE_NOTE_LABEL) + .click(); + hub.run_steps(2); + assert_eq!(saved_notes(&hub).len(), 1); + + // The hub harness does not draw global banners; read them instead. + let ctx = app_context.egui_ctx(); + MessageBanner::clear_all_global(ctx); + hub.state_mut().0.display_task_result( + BackendTaskSuccessResult::DashPayContactInfoUpdated { + identity: owner, + contact_id: Identifier::from(CONTACT), + published: false, + }, + ); + hub.run_steps(4); + assert!(hub.query_by_label(SAVING_NOTE_LABEL).is_none()); + + MessageBanner::clear_global_message(ctx, NOTE_SAVED); + assert!( + MessageBanner::has_global(ctx), + "the user is told the note is kept on this device" + ); + MessageBanner::clear_global_message(ctx, DETAILS_SAVED_ON_THIS_DEVICE); + assert!( + !MessageBanner::has_global(ctx), + "the only banner is the on-this-device one" + ); + }); +} + #[test] fn a_narrow_window_stacks_the_details_under_the_contact() { with_isolated_data_dir(|| { @@ -424,6 +469,7 @@ fn a_note_saved_behind_another_screen_is_settled_on_return() { result: Box::new(BackendTaskSuccessResult::DashPayContactInfoUpdated { identity: owner, contact_id: Identifier::from(CONTACT), + published: true, }), }], ); @@ -509,40 +555,6 @@ fn bare_contact_info_failure_behind_another_screen_releases_only_its_save() { }); } -#[test] -fn unreadable_details_found_behind_another_screen_still_ask_first() { - use dash_evo_tool::backend_task::error::{ContactInfoReadError, TaskError}; - with_isolated_data_dir(|| { - let runtime = tokio::runtime::Runtime::new().expect("runtime"); - let _guard = runtime.enter(); - let mut app = - crate::support::mount_app(dash_evo_tool::ui::RootScreenType::RootScreenWalletsBalances); - let (mut hub, owner, context) = hub_saving_a_note(&app); - - crate::identity_hub::loads::receive_task_results_behind_the_send_screen( - &runtime, - &mut app, - &mut hub, - vec![dash_evo_tool::app::TaskResult::Error { - context, - error: contact_info_failure( - owner, - TaskError::DashPayContactInfoRead { - source: ContactInfoReadError::DeserializeFailed, - }, - ), - }], - ); - hub.run_steps(2); - - assert!( - hub.query_by_label("Save note and replace saved details?") - .is_some(), - "the overwrite question must be asked once the hub is back in view" - ); - }); -} - #[test] fn failed_unhide_behind_another_screen_restores_the_hidden_row() { use dash_evo_tool::backend_task::error::TaskError; From 52fcddf8d4dca2924ff744adeb2eff739834bf56 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:15:21 +0000 Subject: [PATCH 21/73] fix(dashpay): keep withdrawals and cleared contact details in force - Withdrawing a contact request also ignores the recipient in platform-wallet, and the contacts list leaves out anyone whose request was withdrawn. A later reply shows as a new request to answer instead of turning into a contact on its own. - Once platform-wallet has held a contact's details, a legacy-key contactInfo document no longer stands in for them, even when they are empty. A cleared note or an unhide is not undone by the old document, and the next save does not publish it again. Co-Authored-By: Claude Opus 5.5 --- src/backend_task/dashpay/contact_info.rs | 27 ++-- src/backend_task/dashpay/contact_requests.rs | 26 +++ src/backend_task/dashpay/contacts.rs | 157 ++++++++++++++++--- src/wallet_backend/dashpay.rs | 26 +++ 4 files changed, 201 insertions(+), 35 deletions(-) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 90286a92c..40c6bf8d5 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -85,16 +85,18 @@ pub async fn create_or_update_contact_info( let synced = backend .dashpay_contact_details(&owner) .await - .remove(&contact_user_id) - .filter(|details| !details.is_empty()); - let current = match synced { - Some(details) => details, - None => super::contacts::legacy_contact_details(app_context, sdk, &identity) + .remove(&contact_user_id); + let synced_before = backend.dashpay_details_synced(&owner, &contact_user_id) + || super::contacts::holds_details(synced.as_ref()); + let legacy = if synced_before { + None + } else { + super::contacts::legacy_contact_details(app_context, sdk, &identity) .await? .get(&contact_user_id) .map(super::contacts::ContactData::details) - .unwrap_or_default(), }; + let current = super::contacts::shown_contact_details(synced, synced_before, legacy); let details = update.apply_to(current); validate_contact_note(details.note.as_deref().unwrap_or_default())?; @@ -109,10 +111,17 @@ pub async fn create_or_update_contact_info( source: Box::new(source), })?; - let published = match backend + let outcome = backend .dashpay_set_contact_info(&identity, &contact_user_id, details) - .await? - { + .await?; + // platform-wallet holds these details now, published or not. + if let Err(error) = backend.dashpay_mark_details_synced(&owner, &contact_user_id) { + tracing::debug!( + ?error, + "could not record that the contact details are synced" + ); + } + let published = match outcome { ContactInfoPublishOutcome::Published => true, ContactInfoPublishOutcome::DeferredUntilTwoContacts => false, // The write checks for a wallet identity index before platform-wallet diff --git a/src/backend_task/dashpay/contact_requests.rs b/src/backend_task/dashpay/contact_requests.rs index 22b6a2447..50809de2f 100644 --- a/src/backend_task/dashpay/contact_requests.rs +++ b/src/backend_task/dashpay/contact_requests.rs @@ -935,6 +935,10 @@ trait CancelOps { /// makes the pending request an established contact instead. fn reciprocal_request_exists(&self) -> impl Future> + Send; + /// Ignore the recipient in platform-wallet (local only), so a reply to + /// the withdrawn request cannot establish the contact on its own. + fn ignore_recipient(&self) -> impl Future> + Send; + /// Record the withdrawal in the DET sidecar so the request stops being /// listed as pending. /// @@ -953,6 +957,7 @@ async fn cancel_flow(ops: &O) -> Result let outcome = if ops.reciprocal_request_exists().await? { CancelOutcome::AlreadyEstablished } else { + ops.ignore_recipient().await?; ops.mark_withdrawn()?; CancelOutcome::Withdrawn }; @@ -1013,6 +1018,13 @@ impl CancelOps for PlatformCancelOps<'_> { .wallet_backend()? .dashpay_mark_withdrawn(&self.owner_id, &self.to_identity_id) } + + async fn ignore_recipient(&self) -> Result<(), TaskError> { + self.app_context + .wallet_backend()? + .dashpay_ignore_contact_sender(&self.owner_id, &self.to_identity_id) + .await + } } /// Cancel a contact request this identity sent and that is still pending. @@ -1335,6 +1347,7 @@ mod tests { withdrawn: Mutex, withdraw_fails: bool, phase_cleared: Mutex, + ignored: Mutex, } impl CancelOps for ScriptedOps { @@ -1351,6 +1364,11 @@ mod tests { Ok(self.reciprocal) } + async fn ignore_recipient(&self) -> Result<(), TaskError> { + *self.ignored.lock().unwrap() = true; + Ok(()) + } + fn mark_withdrawn(&self) -> Result<(), TaskError> { if self.withdraw_fails { return Err(TaskError::DashpaySidecarStorage { @@ -1371,6 +1389,10 @@ mod tests { CancelOutcome::Withdrawn ); assert!(*ops.withdrawn.lock().unwrap()); + assert!( + *ops.ignored.lock().unwrap(), + "SEC-001: a later reply must not establish the contact on its own" + ); assert!( *ops.phase_cleared.lock().unwrap(), "an older version's record is retired" @@ -1389,6 +1411,10 @@ mod tests { CancelOutcome::AlreadyEstablished ); assert!(!*ops.withdrawn.lock().unwrap()); + assert!( + !*ops.ignored.lock().unwrap(), + "an established contact is not ignored" + ); } #[tokio::test] diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index c5f2071e3..997199e46 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -234,19 +234,54 @@ pub(super) async fn legacy_contact_details( .await } -/// The details the contacts list shows for one contact: platform-wallet's -/// synced details, or a legacy-key document's when platform-wallet holds -/// none for the contact. +/// The details the contacts list shows for one contact, and that a save +/// keeps for every field it does not replace: platform-wallet's synced +/// details, or a legacy-key document's while platform-wallet has never held +/// any for the contact (`synced_before` false and nothing synced now). +/// +/// Once platform-wallet has held details, they win even when empty, so a +/// cleared note or an unhide is never undone by an old legacy document. pub(super) fn shown_contact_details( synced: Option, + synced_before: bool, legacy: Option, ) -> ContactDetails { + if synced_before { + return synced.unwrap_or_default(); + } synced .filter(|details| !details.is_empty()) .or(legacy) .unwrap_or_default() } +/// Whether platform-wallet holds details worth recording as its own: any +/// non-empty synced details mean a `contactInfo` document or a local save +/// set them. +pub(super) fn holds_details(synced: Option<&ContactDetails>) -> bool { + synced.is_some_and(|details| !details.is_empty()) +} + +/// The people both sides have sent a contact request to, minus anyone the +/// owner withdrew their request from: a reply to a withdrawn request is a new +/// request for the owner to answer, not an established contact. +pub(super) fn mutual_contacts( + incoming: &[(Identifier, Document)], + outgoing: &[(Identifier, Document)], + is_withdrawn: impl Fn(&Identifier) -> bool, +) -> HashSet { + incoming + .iter() + .map(|(_, doc)| doc.owner_id()) + .filter(|from_id| !is_withdrawn(from_id)) + .filter(|from_id| { + outgoing + .iter() + .any(|(_, doc)| contact_request_recipient(doc).as_ref() == Some(from_id)) + }) + .collect() +} + impl ContactData { pub(super) fn details(&self) -> ContactDetails { ContactDetails { @@ -322,20 +357,17 @@ pub async fn load_contacts( .collect(); // Find mutual contacts (where both parties have sent requests to each other) - let contacts: HashSet = incoming - .iter() - .map(|(_, doc)| doc.owner_id()) - .filter(|from_id| { - outgoing - .iter() - .any(|(_, doc)| contact_request_recipient(doc).as_ref() == Some(from_id)) - }) - .collect(); + let backend = app_context.wallet_backend().ok(); + let contacts = mutual_contacts(&incoming, &outgoing, |peer| { + backend + .as_ref() + .is_some_and(|backend| backend.dashpay_is_withdrawn(&identity_id, peer)) + }); // platform-wallet's synced details first; a refresh failure leaves the // last synced details in place. - let mut synced = match app_context.wallet_backend() { - Ok(backend) => { + let mut synced = match &backend { + Some(backend) => { if let Err(error) = backend.dashpay_sync(&identity_id).await { tracing::debug!( ?error, @@ -350,11 +382,8 @@ pub async fn load_contacts( } backend.dashpay_contact_details(&identity_id).await } - Err(error) => { - tracing::debug!( - ?error, - "LoadContacts: no wallet backend; showing legacy details" - ); + None => { + tracing::debug!("LoadContacts: no wallet backend; showing legacy details"); Default::default() } }; @@ -365,8 +394,20 @@ pub async fn load_contacts( .into_iter() .map(|contact_id| { let legacy = legacy.get(&contact_id); + let synced = synced.remove(&contact_id); + let synced_before = backend.as_ref().is_some_and(|backend| { + let synced_before = backend.dashpay_details_synced(&identity_id, &contact_id); + if !synced_before + && holds_details(synced.as_ref()) + && let Err(error) = + backend.dashpay_mark_details_synced(&identity_id, &contact_id) + { + tracing::debug!(?error, "LoadContacts: could not record synced details"); + } + synced_before + }); let details = - shown_contact_details(synced.remove(&contact_id), legacy.map(ContactData::details)); + shown_contact_details(synced, synced_before, legacy.map(ContactData::details)); ContactData { identity_id: contact_id, nickname: details.nickname, @@ -582,23 +623,87 @@ mod tests { #[test] fn synced_contact_details_win_over_legacy_ones() { assert_eq!( - shown_contact_details(Some(details("synced")), Some(details("legacy"))), + shown_contact_details(Some(details("synced")), false, Some(details("legacy"))), details("synced") ); } #[test] - fn legacy_contact_details_show_when_none_are_synced() { + fn legacy_contact_details_show_when_none_were_ever_synced() { assert_eq!( - shown_contact_details(None, Some(details("legacy"))), + shown_contact_details(None, false, Some(details("legacy"))), details("legacy") ); assert_eq!( - shown_contact_details(Some(ContactDetails::default()), Some(details("legacy"))), + shown_contact_details( + Some(ContactDetails::default()), + false, + Some(details("legacy")) + ), details("legacy"), - "a contact platform-wallet holds no details for shows the legacy ones" + "a contact platform-wallet never held details for shows the legacy ones" + ); + assert_eq!( + shown_contact_details(None, false, None), + ContactDetails::default() + ); + } + + /// SEC-002: a note the user cleared, or a contact they unhid, must not + /// come back from an old legacy document — nor be saved again by the + /// next edit, which keeps these details for every field it leaves alone. + #[test] + fn cleared_details_do_not_come_back_from_a_legacy_document() { + let legacy = ContactDetails { + nickname: None, + note: Some("old".into()), + hidden: true, + }; + assert_eq!( + shown_contact_details(Some(ContactDetails::default()), true, Some(legacy.clone())), + ContactDetails::default() + ); + assert_eq!( + shown_contact_details(None, true, Some(legacy)), + ContactDetails::default() ); - assert_eq!(shown_contact_details(None, None), ContactDetails::default()); + } + + #[test] + fn only_non_empty_synced_details_are_recorded_as_synced() { + assert!(holds_details(Some(&details("note")))); + assert!(!holds_details(Some(&ContactDetails::default()))); + assert!(!holds_details(None)); + } + + fn request(document_id: u8, owner: Identifier, to: Identifier) -> (Identifier, Document) { + use dash_sdk::dpp::document::DocumentV0; + let id = Identifier::from([document_id; 32]); + let document = Document::V0(DocumentV0 { + id, + owner_id: owner, + properties: std::collections::BTreeMap::from([( + "toUserId".to_string(), + Value::Identifier(to.to_buffer()), + )]), + ..Default::default() + }); + (id, document) + } + + /// SEC-001: after the owner withdraws their request, a reply from the + /// other person does not make them a contact. + #[test] + fn a_reply_to_a_withdrawn_request_is_not_a_contact() { + let owner = Identifier::from([1; 32]); + let bob = Identifier::from([2; 32]); + let carol = Identifier::from([3; 32]); + let incoming = [request(10, bob, owner), request(11, carol, owner)]; + let outgoing = [request(20, owner, bob), request(21, owner, carol)]; + + let contacts = mutual_contacts(&incoming, &outgoing, |peer| *peer == bob); + + assert_eq!(contacts, HashSet::from([carol])); } /// Known-answer vectors generated independently with Python diff --git a/src/wallet_backend/dashpay.rs b/src/wallet_backend/dashpay.rs index 53194abed..5ca6797cc 100644 --- a/src/wallet_backend/dashpay.rs +++ b/src/wallet_backend/dashpay.rs @@ -239,6 +239,11 @@ const KV_PREFIX_DECLINED: &str = "det:dashpay:declined:"; /// opposite directions: withdrawing our request to Bob says nothing about a /// request Bob later sends us, and a single marker would silently hide it. const KV_PREFIX_WITHDRAWN: &str = "det:dashpay:withdrawn:"; +/// Presence marker: platform-wallet holds `owner`'s details for this contact, +/// so a legacy-key `contactInfo` document no longer stands in for them — not +/// even when those details are empty because the user cleared them. +/// Scope: the owner identity. +const KV_PREFIX_DETAILS_SYNCED: &str = "det:dashpay:details_synced:"; /// Recovery journal older versions kept while a decline or withdrawal wrote /// contact details. Declines and withdrawals only clear it. Scope: the /// acting identity. @@ -1295,6 +1300,25 @@ impl WalletBackend { self.delete_marker(owner, KV_PREFIX_WITHDRAWN, counterparty_id) } + /// Record that platform-wallet holds `owner`'s details for `contact_id`; + /// see [`KV_PREFIX_DETAILS_SYNCED`]. Idempotent. + pub(crate) fn dashpay_mark_details_synced( + &self, + owner: &Identifier, + contact_id: &Identifier, + ) -> Result<(), TaskError> { + self.put_marker(owner, KV_PREFIX_DETAILS_SYNCED, contact_id) + } + + /// Whether platform-wallet holds `owner`'s details for `contact_id`. + pub(crate) fn dashpay_details_synced( + &self, + owner: &Identifier, + contact_id: &Identifier, + ) -> bool { + kv_contains(&self.kv(), owner, KV_PREFIX_DETAILS_SYNCED, contact_id) + } + pub(crate) async fn dashpay_lock_contact_request_action( &self, owner: &Identifier, @@ -1534,6 +1558,7 @@ impl WalletBackend { KV_PREFIX_DECLINED, KV_PREFIX_WITHDRAWN, KV_PREFIX_REQUEST_ACTION, + KV_PREFIX_DETAILS_SYNCED, ] { let keys = kv.list(scope, Some(prefix)).map_err(sidecar_err)?; for key in keys { @@ -3083,6 +3108,7 @@ mod tests { KV_PREFIX_DECLINED, KV_PREFIX_WITHDRAWN, KV_PREFIX_REQUEST_ACTION, + KV_PREFIX_DETAILS_SYNCED, ] { for k in kv.list(DetScope::Identity(&owner), Some(prefix)).unwrap() { kv.delete(DetScope::Identity(&owner), &k).unwrap(); From 8442489b39ba13f68fd76033f08c24e6fee8002a Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:25:25 +0000 Subject: [PATCH 22/73] fix(dashpay): read published contact details back after a restart Wallets load without their seed after a restart, and platform-wallet then only queues the contactInfo decrypt for a host drain that also runs unrelated contact-account jobs. DET now opens the owner's DIP-15 contactInfo documents itself with platform-wallet's keys and codec, in one secret session, through the same ContactCryptoProvider. Documents that do not open are skipped. A published document is the latest state from any device, so it wins over this device's details and over legacy ones, both in the list and as the base a save keeps. Saving on one device no longer reverts a hidden flag or note set on another. A published document, even an empty one, also counts as synced, so details cleared on another device stay cleared. Co-Authored-By: Claude Opus 5.5 --- src/backend_task/dashpay/contact_info.rs | 25 ++- src/backend_task/dashpay/contacts.rs | 194 ++++++++++++++----- src/wallet_backend/contact_info.rs | 231 ++++++++++++++++++++++- 3 files changed, 393 insertions(+), 57 deletions(-) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 40c6bf8d5..19db13914 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -57,9 +57,8 @@ where /// Save `update` for `contact_user_id` through platform-wallet. /// -/// Every field the update preserves keeps the value the contacts list shows: -/// platform-wallet's synced details, or a legacy-key document's when -/// platform-wallet has none for the contact. Notes are limited to 255 UTF-8 +/// Every field the update preserves keeps the value the contacts list shows; +/// see [`super::contacts::shown_contact_details`]. Notes are limited to 255 UTF-8 /// bytes, and the details must fit the document size limit. /// /// # Errors @@ -82,21 +81,19 @@ pub async fn create_or_update_contact_info( let owner = identity.identity.id(); backend.dashpay_sync_contact_infos(&owner).await?; - let synced = backend + let local = backend .dashpay_contact_details(&owner) .await .remove(&contact_user_id); + let mut stored = super::contacts::stored_contact_details(app_context, sdk, &identity).await?; + let published = stored.published.remove(&contact_user_id); let synced_before = backend.dashpay_details_synced(&owner, &contact_user_id) - || super::contacts::holds_details(synced.as_ref()); - let legacy = if synced_before { - None - } else { - super::contacts::legacy_contact_details(app_context, sdk, &identity) - .await? - .get(&contact_user_id) - .map(super::contacts::ContactData::details) - }; - let current = super::contacts::shown_contact_details(synced, synced_before, legacy); + || super::contacts::holds_details(published.as_ref(), local.as_ref()); + let legacy = stored + .legacy + .get(&contact_user_id) + .map(super::contacts::ContactData::details); + let current = super::contacts::shown_contact_details(published, local, synced_before, legacy); let details = update.apply_to(current); validate_contact_note(details.note.as_deref().unwrap_or_default())?; diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index 997199e46..4fb74bf1e 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -15,7 +15,7 @@ use dash_sdk::platform::{Document, DocumentQuery, Fetch, FetchMany, Identifier}; use dash_sdk::query_types::Documents; use futures::future::join_all; use platform_wallet::wallet::identity::crypto::decode_private_data; -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::future::Future; use std::sync::Arc; use zeroize::Zeroizing; @@ -133,17 +133,33 @@ pub(super) fn decrypt_private_data( /// page of the owner's documents. /// /// Pages are ordered by `$updatedAt`, oldest first, and a later document for -/// a contact replaces an earlier one, so the newest document wins. +/// a contact replaces an earlier one, so the newest document wins. The test +/// seam over [`stored_contact_details`]'s legacy half. +#[cfg(test)] pub(super) async fn load_contact_details( query: DocumentQuery, fetch_page: P, - mut derive_keys: D, + derive_keys: D, ) -> Result, TaskError> where P: FnMut(DocumentQuery) -> PF, PF: Future>, D: FnMut(u32) -> DF, DF: Future, Zeroizing<[u8; 32]>), TaskError>>, +{ + let documents = fetch_contact_info_documents(query, fetch_page).await?; + Ok(legacy_details_from(&documents, derive_keys).await) +} + +/// Every page of the owner's `contactInfo` documents, oldest first by +/// `$updatedAt`. +async fn fetch_contact_info_documents( + query: DocumentQuery, + fetch_page: P, +) -> Result, TaskError> +where + P: FnMut(DocumentQuery) -> PF, + PF: Future>, { let query = query.with_order_by(OrderClause { field: "$updatedAt".to_string(), @@ -151,9 +167,21 @@ where }); let documents = super::contact_info::fetch_all_contact_info_documents(query, fetch_page).await?; + Ok(documents.into_values().flatten().collect()) +} +/// The details `documents` (oldest first) hold under the legacy key root; +/// a later document for a contact replaces an earlier one. +async fn legacy_details_from( + documents: &[Document], + mut derive_keys: D, +) -> HashMap +where + D: FnMut(u32) -> DF, + DF: Future, Zeroizing<[u8; 32]>), TaskError>>, +{ let mut contact_info_map: HashMap = HashMap::new(); - for doc in documents.into_values().flatten() { + for doc in documents { let props = doc.properties(); let Some(deriv_idx) = props .get("derivationEncryptionKeyIndex") @@ -203,15 +231,29 @@ where ); } - Ok(contact_info_map) + contact_info_map } -/// The details legacy-key `contactInfo` documents hold for each contact. -pub(super) async fn legacy_contact_details( +/// The details the owner's stored `contactInfo` documents hold. +pub(super) struct StoredContactDetails { + /// From DIP-0015 documents platform-wallet can read, newest per contact. + pub(super) published: BTreeMap, + /// From documents older versions of this app wrote under the legacy + /// key root, newest per contact. + pub(super) legacy: HashMap, +} + +/// Read every `contactInfo` document the owner stored, both as DIP-0015 +/// documents and as legacy-key ones. +/// +/// platform-wallet does not read DIP-0015 documents back for a wallet loaded +/// without its seed, which is how wallets load after a restart, so they are +/// opened here with platform-wallet's keys and codec. +pub(super) async fn stored_contact_details( app_context: &Arc, sdk: &Sdk, identity: &QualifiedIdentity, -) -> Result, TaskError> { +) -> Result { let query = DocumentQuery::new(app_context.dashpay_contract.clone(), "contactInfo") .map_err(|e| DashPayError::QueryCreation { query_target: "DashPay contactInfo", @@ -222,44 +264,62 @@ pub(super) async fn legacy_contact_details( operator: WhereOperator::Equal, value: Value::Identifier(identity.identity.id().to_buffer()), }); - load_contact_details( - query, - |query| async move { - Document::fetch_many(sdk, query) + let documents = fetch_contact_info_documents(query, |query| async move { + Document::fetch_many(sdk, query) + .await + .map_err(TaskError::from) + }) + .await?; + let published = match app_context.wallet_backend() { + Ok(backend) => { + backend + .dashpay_open_contact_infos(identity, &documents) .await - .map_err(TaskError::from) - }, - |derivation_index| derive_contact_info_keys(app_context, identity, derivation_index), - ) - .await + } + Err(_) => BTreeMap::new(), + }; + let legacy = legacy_details_from(&documents, |derivation_index| { + derive_contact_info_keys(app_context, identity, derivation_index) + }) + .await; + Ok(StoredContactDetails { published, legacy }) } /// The details the contacts list shows for one contact, and that a save -/// keeps for every field it does not replace: platform-wallet's synced -/// details, or a legacy-key document's while platform-wallet has never held -/// any for the contact (`synced_before` false and nothing synced now). +/// keeps for every field it does not replace. /// -/// Once platform-wallet has held details, they win even when empty, so a -/// cleared note or an unhide is never undone by an old legacy document. +/// A published DIP-0015 document wins: Platform holds the latest saved state +/// from any device. Without one, platform-wallet's details on this device +/// win; a legacy-key document stands in only while platform-wallet has never +/// held details for the contact (`synced_before` false). Once it has, its +/// details win even when empty, so a cleared note or an unhide is never +/// undone by an old legacy document. pub(super) fn shown_contact_details( - synced: Option, + published: Option, + local: Option, synced_before: bool, legacy: Option, ) -> ContactDetails { + if let Some(published) = published { + return published; + } if synced_before { - return synced.unwrap_or_default(); + return local.unwrap_or_default(); } - synced + local .filter(|details| !details.is_empty()) .or(legacy) .unwrap_or_default() } -/// Whether platform-wallet holds details worth recording as its own: any -/// non-empty synced details mean a `contactInfo` document or a local save -/// set them. -pub(super) fn holds_details(synced: Option<&ContactDetails>) -> bool { - synced.is_some_and(|details| !details.is_empty()) +/// Whether platform-wallet's side holds details worth recording as its own: +/// a published DIP-0015 document (even an empty one), or non-empty details on +/// this device. +pub(super) fn holds_details( + published: Option<&ContactDetails>, + local: Option<&ContactDetails>, +) -> bool { + published.is_some() || local.is_some_and(|details| !details.is_empty()) } /// The people both sides have sent a contact request to, minus anyone the @@ -387,7 +447,10 @@ pub async fn load_contacts( Default::default() } }; - let legacy = legacy_contact_details(app_context, sdk, &identity).await?; + let StoredContactDetails { + mut published, + legacy, + } = stored_contact_details(app_context, sdk, &identity).await?; // Build enriched contact list with basic data let mut contact_list: Vec = contacts @@ -395,10 +458,11 @@ pub async fn load_contacts( .map(|contact_id| { let legacy = legacy.get(&contact_id); let synced = synced.remove(&contact_id); + let published = published.remove(&contact_id); let synced_before = backend.as_ref().is_some_and(|backend| { let synced_before = backend.dashpay_details_synced(&identity_id, &contact_id); if !synced_before - && holds_details(synced.as_ref()) + && holds_details(published.as_ref(), synced.as_ref()) && let Err(error) = backend.dashpay_mark_details_synced(&identity_id, &contact_id) { @@ -406,8 +470,12 @@ pub async fn load_contacts( } synced_before }); - let details = - shown_contact_details(synced, synced_before, legacy.map(ContactData::details)); + let details = shown_contact_details( + published, + synced, + synced_before, + legacy.map(ContactData::details), + ); ContactData { identity_id: contact_id, nickname: details.nickname, @@ -623,7 +691,12 @@ mod tests { #[test] fn synced_contact_details_win_over_legacy_ones() { assert_eq!( - shown_contact_details(Some(details("synced")), false, Some(details("legacy"))), + shown_contact_details( + None, + Some(details("synced")), + false, + Some(details("legacy")) + ), details("synced") ); } @@ -631,11 +704,12 @@ mod tests { #[test] fn legacy_contact_details_show_when_none_were_ever_synced() { assert_eq!( - shown_contact_details(None, false, Some(details("legacy"))), + shown_contact_details(None, None, false, Some(details("legacy"))), details("legacy") ); assert_eq!( shown_contact_details( + None, Some(ContactDetails::default()), false, Some(details("legacy")) @@ -644,7 +718,7 @@ mod tests { "a contact platform-wallet never held details for shows the legacy ones" ); assert_eq!( - shown_contact_details(None, false, None), + shown_contact_details(None, None, false, None), ContactDetails::default() ); } @@ -660,20 +734,56 @@ mod tests { hidden: true, }; assert_eq!( - shown_contact_details(Some(ContactDetails::default()), true, Some(legacy.clone())), + shown_contact_details( + None, + Some(ContactDetails::default()), + true, + Some(legacy.clone()) + ), ContactDetails::default() ); assert_eq!( - shown_contact_details(None, true, Some(legacy)), + shown_contact_details(None, None, true, Some(legacy)), ContactDetails::default() ); } #[test] fn only_non_empty_synced_details_are_recorded_as_synced() { - assert!(holds_details(Some(&details("note")))); - assert!(!holds_details(Some(&ContactDetails::default()))); - assert!(!holds_details(None)); + assert!(holds_details(None, Some(&details("note")))); + assert!(!holds_details(None, Some(&ContactDetails::default()))); + assert!(!holds_details(None, None)); + } + + /// SEC-003: Platform's DIP-0015 document is the latest saved state from + /// any device, so it wins over this device's details and legacy ones — + /// and a save keeps it for the fields it does not replace. + #[test] + fn a_published_document_wins_over_local_and_legacy_details() { + assert_eq!( + shown_contact_details( + Some(details("published")), + Some(details("local")), + true, + Some(details("legacy")) + ), + details("published") + ); + assert_eq!( + shown_contact_details( + Some(ContactDetails::default()), + None, + false, + Some(details("legacy")) + ), + ContactDetails::default(), + "details cleared on another device stay cleared" + ); + } + + #[test] + fn an_empty_published_document_counts_as_held_details() { + assert!(holds_details(Some(&ContactDetails::default()), None)); } fn request(document_id: u8, owner: Identifier, to: Identifier) -> (Identifier, Document) { diff --git a/src/wallet_backend/contact_info.rs b/src/wallet_backend/contact_info.rs index 9f900c80a..3b6b88077 100644 --- a/src/wallet_backend/contact_info.rs +++ b/src/wallet_backend/contact_info.rs @@ -18,11 +18,12 @@ use dash_sdk::dpp::key_wallet::bip32::{ }; use dash_sdk::dpp::key_wallet::wallet::Wallet; use dash_sdk::dpp::key_wallet::wallet::initialization::WalletAccountCreationOptions; -use dash_sdk::platform::Identifier; +use dash_sdk::platform::{Document, Identifier}; use platform_wallet::error::PlatformWalletError; use platform_wallet::wallet::identity::crypto::contact_info::{ ContactInfoKeys, derive_contact_info_keys, }; +use platform_wallet::wallet::identity::crypto::decode_private_data; use platform_wallet::wallet::identity::network::{ ContactCryptoProvider, ContactInfoOpened, ContactInfoPublishOutcome, ContactInfoSealed, identity_auth_derivation_path_for_type, @@ -150,6 +151,128 @@ impl WalletBackend { } } +impl WalletBackend { + /// The details `identity`'s DIP-0015 `contactInfo` documents hold, read + /// with platform-wallet's keys and codec; `documents` are oldest first and + /// the newest per contact wins. Documents that do not open — legacy-key + /// ones, or another client's — are skipped. Empty when the identity has + /// no wallet identity index or the seed is unavailable. + pub(crate) async fn dashpay_open_contact_infos( + &self, + identity: &QualifiedIdentity, + documents: &[Document], + ) -> BTreeMap { + if documents.is_empty() { + return BTreeMap::new(); + } + let Some(seed_hash) = identity.dashpay_wallet_seed_hash() else { + return BTreeMap::new(); + }; + let Ok(wallet) = self.resolve_wallet(&seed_hash).await else { + return BTreeMap::new(); + }; + let owner = identity.identity.id(); + let identity_index = { + let state = wallet.state().await; + state + .identity_manager + .managed_identity(&owner) + .and_then(|managed| managed.identity_index) + }; + let Some(identity_index) = identity_index else { + return BTreeMap::new(); + }; + let network = identity.network; + self.secret_access() + .with_secret_session(&SecretScope::HdSeed { seed_hash }, async |session| { + let plaintext = session.plaintext(); + let seed = plaintext + .expose_hd_seed() + .ok_or(TaskError::ContactWalletSeedUnavailable)?; + let crypto = ContactInfoCrypto::new(seed, network, identity_index); + Ok::<_, TaskError>(open_contact_info_documents(&crypto, documents).await) + }) + .await + .unwrap_or_else(|error| { + tracing::debug!(?error, "contactInfo documents could not be opened"); + BTreeMap::new() + }) + } +} + +/// Open `documents` (oldest first) through `crypto`; the newest readable +/// document per contact wins. +async fn open_contact_info_documents( + crypto: &ContactInfoCrypto<'_>, + documents: &[Document], +) -> BTreeMap { + let mut opened = BTreeMap::new(); + for document in documents { + let Some(stored) = StoredContactInfo::of(document) else { + continue; + }; + let Ok(root_path) = identity_auth_derivation_path_for_type( + crypto.network, + KeyDerivationType::ECDSA, + crypto.identity_index, + stored.root_index, + ) else { + continue; + }; + let Ok(contact) = crypto + .contact_info_open( + &root_path, + stored.derivation_index, + &stored.enc_to_user_id, + stored.private_data, + ) + .await + else { + continue; + }; + let Ok(data) = decode_private_data(&contact.private_data) else { + continue; + }; + opened.insert( + Identifier::from(contact.contact_id), + ContactDetails { + nickname: data.alias_name, + note: data.note, + hidden: data.display_hidden, + }, + ); + } + opened +} + +/// The `contactInfo` fields a read needs. +struct StoredContactInfo<'a> { + root_index: u32, + derivation_index: u32, + enc_to_user_id: [u8; 32], + private_data: &'a [u8], +} + +impl<'a> StoredContactInfo<'a> { + fn of(document: &'a Document) -> Option { + use dash_sdk::dpp::document::DocumentV0Getters; + use dash_sdk::dpp::platform_value::Value; + let properties = document.properties(); + let index = |name: &str| properties.get(name)?.to_integer::().ok(); + let bytes = |name: &str| match properties.get(name)? { + Value::Bytes(bytes) => Some(bytes.as_slice()), + Value::Bytes32(bytes) => Some(bytes.as_slice()), + _ => None, + }; + Some(Self { + root_index: index("rootEncryptionKeyIndex")?, + derivation_index: index("derivationEncryptionKeyIndex")?, + enc_to_user_id: bytes("encToUserId")?.try_into().ok()?, + private_data: bytes("privateData")?, + }) + } +} + /// The wallet identity index a contact details write derives beneath, /// checked before platform-wallet changes any local state. fn contact_info_write_index( @@ -404,6 +527,112 @@ mod tests { assert_eq!(opened.private_data, b"alias"); } + fn stored_document( + id: u8, + key_id: u32, + derivation_index: u32, + sealed: &ContactInfoSealed, + ) -> Document { + use dash_sdk::dpp::document::DocumentV0; + use dash_sdk::dpp::platform_value::Value; + Document::V0(DocumentV0 { + id: Identifier::from([id; 32]), + properties: BTreeMap::from([ + ("rootEncryptionKeyIndex".to_string(), Value::U32(key_id)), + ( + "derivationEncryptionKeyIndex".to_string(), + Value::U32(derivation_index), + ), + ( + "encToUserId".to_string(), + Value::Bytes(sealed.enc_to_user_id.to_vec()), + ), + ( + "privateData".to_string(), + Value::Bytes(sealed.private_data.clone()), + ), + ]), + ..Default::default() + }) + } + + async fn sealed( + crypto: &ContactInfoCrypto<'_>, + derivation_index: u32, + contact: [u8; 32], + details: ContactDetails, + ) -> ContactInfoSealed { + use platform_wallet::wallet::identity::crypto::{ + ContactInfoPrivateData, encode_private_data, + }; + let plaintext = encode_private_data(&ContactInfoPrivateData { + alias_name: details.nickname, + note: details.note, + display_hidden: details.hidden, + accepted_accounts: Vec::new(), + }); + crypto + .contact_info_seal( + &root(IDENTITY_INDEX, 2), + derivation_index, + &contact, + &plaintext, + &[4; 16], + ) + .await + .expect("seal") + } + + /// SEC-003: DIP-0015 documents are read back without platform-wallet + /// holding the seed; the newest per contact wins, and documents that do + /// not open (another key root, or garbage) are skipped, not fatal. + #[tokio::test] + async fn dip15_documents_are_read_back_newest_first() { + let crypto = ContactInfoCrypto::new(&SEED, NETWORK, IDENTITY_INDEX); + let note = |text: &str| ContactDetails { + note: Some(text.into()), + ..Default::default() + }; + let older = sealed(&crypto, 0, [7; 32], note("older")).await; + let newer = sealed(&crypto, 1, [7; 32], note("newer")).await; + let hidden = sealed( + &crypto, + 2, + [8; 32], + ContactDetails { + hidden: true, + ..Default::default() + }, + ) + .await; + let unreadable = ContactInfoSealed { + enc_to_user_id: [1; 32], + private_data: vec![9; 48], + }; + let documents = [ + stored_document(1, 2, 0, &older), + stored_document(2, 2, 9, &unreadable), + stored_document(3, 2, 1, &newer), + stored_document(4, 2, 2, &hidden), + ]; + + let opened = open_contact_info_documents(&crypto, &documents).await; + + assert_eq!( + opened, + BTreeMap::from([ + (Identifier::from([7; 32]), note("newer")), + ( + Identifier::from([8; 32]), + ContactDetails { + hidden: true, + ..Default::default() + } + ), + ]) + ); + } + /// A root that belongs to another wallet identity is refused. #[tokio::test] async fn another_identitys_root_is_refused() { From ef7ebb953c87d8aeb1cbb6407afff7306eef27f5 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 22 Oct 2026 17:36:20 +0000 Subject: [PATCH 23/73] fix(identity): settle hub contact details writes only for their dispatch Another screen can write the same contact while the hub's note save or unhide waits behind it on the per-identity lock. Its outcome reached the hub by owner and contact alone, which finished the hub's write, showed it as saved, and announced it before it ran. The hub now sends each direct contact details write under its own dispatch context and settles success, failure and the overwrite prompt only for that dispatch. Another screen's success just refreshes the list. Co-Authored-By: Claude Opus 5.5 --- src/ui/identity/hub_screen.rs | 68 ++++++++++- tests/kittest/identity_hub_contact_detail.rs | 112 +++++++++++++++++-- 2 files changed, 167 insertions(+), 13 deletions(-) diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index 582b589eb..cf2965203 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -101,6 +101,13 @@ pub struct IdentityHubScreen { selection: HubSelection, contact_info_overwrite_dialog: Option<(ConfirmationDialog, ContactInfoTaskKey)>, pending_contact_info_tasks: HashMap, + /// The dispatch each direct contact details write was sent under. Another + /// screen can write the same contact while the hub's write waits behind + /// it, so only an outcome for this dispatch settles the hub's write. + contact_info_dispatches: HashMap, + /// Set by `display_backend_task_error` when the error belongs to another + /// screen's write, so the context-free handler that follows it ignores it. + foreign_contact_info_error: bool, pending_contact_info_confirmations: VecDeque, } @@ -166,6 +173,8 @@ impl IdentityHubScreen { selection: HubSelection::default(), contact_info_overwrite_dialog: None, pending_contact_info_tasks: HashMap::new(), + contact_info_dispatches: HashMap::new(), + foreign_contact_info_error: false, pending_contact_info_confirmations: VecDeque::new(), } } @@ -182,6 +191,40 @@ impl IdentityHubScreen { } } + /// Send a direct contact details write under its own dispatch context and + /// remember it; see [`Self::contact_info_dispatches`]. + fn bind_contact_info_dispatch(&mut self, action: AppAction) -> AppAction { + let AppAction::BackendTask(task) = action else { + return action; + }; + let context = BackendTaskContext::for_dispatch(&task); + let (Some((identity_id, contact_id)), Some(dispatch_id)) = + (context.dashpay_contact_info_target(), context.dispatch_id()) + else { + return AppAction::BackendTask(task); + }; + let key = ContactInfoTaskKey::Direct { + identity_id, + contact_id, + }; + self.contact_info_dispatches.insert(key, dispatch_id); + AppAction::BackendTaskWithContext { task, context } + } + + /// Whether `context` is the dispatch of the hub's own write for its contact. + fn is_own_contact_info_dispatch(&self, context: &BackendTaskContext) -> bool { + context + .dashpay_contact_info_target() + .and_then(|(identity_id, contact_id)| { + self.contact_info_dispatches + .get(&ContactInfoTaskKey::Direct { + identity_id, + contact_id, + }) + }) + .is_some_and(|dispatch_id| context.dispatch_id() == Some(*dispatch_id)) + } + /// Remember the identity an unload was dispatched for. /// /// The removal is answered frames later, and `SettingsTab::ensure_selected` @@ -211,6 +254,7 @@ impl IdentityHubScreen { self.home_state = HomeState::default(); self.contacts_state.reset_for_identity_change(); self.pending_contact_info_tasks.clear(); + self.contact_info_dispatches.clear(); self.pending_contact_info_confirmations.clear(); self.contact_info_overwrite_dialog = None; } @@ -398,7 +442,10 @@ impl IdentityHubScreen { /// unreadable details, otherwise drop the pending write and release its /// guard. Returns whether the hub took over telling the user. pub(crate) fn handle_contact_info_error(&mut self, error: &TaskError) -> bool { - if !matches!(error, TaskError::DashPayContactInfoActionFailed { .. }) { + // Another screen's write failed; the hub's own write is still running. + if std::mem::take(&mut self.foreign_contact_info_error) + || !matches!(error, TaskError::DashPayContactInfoActionFailed { .. }) + { return false; } if let Some(key) = contact_info_read_error_key(error) @@ -668,6 +715,7 @@ impl ScreenLike for IdentityHubScreen { } }); self.capture_contact_info_update(&action); + action = self.bind_contact_info_dispatch(action); self.capture_unload_dispatch(&action); // A picker card click sets the active identity and routes to Home. @@ -700,7 +748,9 @@ impl ScreenLike for IdentityHubScreen { .and_then(overwrite_unreadable_task) { self.pending_contact_info_tasks.insert(key, task.clone()); - action = AppAction::BackendTask(BackendTask::DashPayTask(Box::new(task))); + action = self.bind_contact_info_dispatch(AppAction::BackendTask( + BackendTask::DashPayTask(Box::new(task)), + )); } self.contact_info_overwrite_dialog = None; } @@ -785,6 +835,15 @@ impl ScreenLike for IdentityHubScreen { ); return; } + if matches!( + result, + BackendTaskSuccessResult::DashPayContactInfoUpdated { .. } + ) && !self.is_own_contact_info_dispatch(context) + { + // Another screen's write: it changed the details shown, nothing more. + self.contacts_state.invalidate(); + return; + } self.display_task_result(result); } @@ -906,8 +965,11 @@ impl ScreenLike for IdentityHubScreen { } fn display_backend_task_error(&mut self, context: &BackendTaskContext, error: &TaskError) { + self.foreign_contact_info_error = context.dashpay_contact_info_target().is_some() + && !self.is_own_contact_info_dispatch(context); // Wrapped errors retain the unreadable-details confirmation flow. - if !matches!(error, TaskError::DashPayContactInfoActionFailed { .. }) + if !self.foreign_contact_info_error + && !matches!(error, TaskError::DashPayContactInfoActionFailed { .. }) && let Some((identity_id, contact_id)) = context.dashpay_contact_info_target() { self.pending_contact_info_tasks diff --git a/tests/kittest/identity_hub_contact_detail.rs b/tests/kittest/identity_hub_contact_detail.rs index 8b9b7352f..c3afae6c6 100644 --- a/tests/kittest/identity_hub_contact_detail.rs +++ b/tests/kittest/identity_hub_contact_detail.rs @@ -156,8 +156,8 @@ fn saved_notes(hub: &HubHarness) -> Vec<(Identifier, ContactInfoField match task.as_ref() { + .filter_map(|action| match dispatched_task(action)?.0 { + BackendTask::DashPayTask(task) => match task.as_ref() { DashPayTask::UpdateContactInfo { contact_id, update, .. } => Some((*contact_id, update.note.clone())), @@ -168,6 +168,15 @@ fn saved_notes(hub: &HubHarness) -> Vec<(Identifier, ContactInfoField Option<(&BackendTask, BackendTaskContext)> { + match action { + AppAction::BackendTask(task) => Some((task, BackendTaskContext::from(task))), + AppAction::BackendTaskWithContext { task, context } => Some((task, context.clone())), + _ => None, + } +} + #[test] fn selecting_a_contact_shows_its_details_beside_the_list() { with_isolated_data_dir(|| { @@ -381,11 +390,11 @@ fn hub_saving_a_note( .state() .1 .iter() - .find_map(|action| match action { - AppAction::BackendTask(task @ BackendTask::DashPayTask(inner)) + .find_map(|action| match dispatched_task(action)? { + (BackendTask::DashPayTask(inner), context) if matches!(**inner, DashPayTask::UpdateContactInfo { .. }) => { - Some(BackendTaskContext::from(task)) + Some(context) } _ => None, }) @@ -543,6 +552,86 @@ fn unreadable_details_found_behind_another_screen_still_ask_first() { }); } +/// The outcome of a same-contact write another screen dispatched: the +/// legacy Contact Details screen sends plain tasks, so its context names the +/// contact but no dispatch. +fn foreign_write_context(hub: &HubHarness) -> BackendTaskContext { + let app_context = hub.state().0.app_context.clone(); + BackendTaskContext::from(&BackendTask::DashPayTask(Box::new( + DashPayTask::UpdateContactInfo { + identity: app_context.resolve_selected_identity().expect("identity"), + contact_id: Identifier::from(CONTACT), + update: dash_evo_tool::model::dashpay::ContactInfoUpdate::note(Some( + "from the other screen".into(), + )), + }, + ))) +} + +/// Another screen's write for the same contact finishes while the hub's own +/// note save is still queued behind it. Its success must not settle, show as +/// saved, or announce the hub's write; only the hub's own outcome does. +#[test] +fn a_foreign_same_contact_save_does_not_settle_the_hubs_note() { + with_isolated_data_dir(|| { + let runtime = tokio::runtime::Runtime::new().expect("runtime"); + let _guard = runtime.enter(); + let app = + crate::support::mount_app(dash_evo_tool::ui::RootScreenType::RootScreenWalletsBalances); + let (mut hub, owner, own_context) = hub_saving_a_note(&app); + let foreign = foreign_write_context(&hub); + let updated = || BackendTaskSuccessResult::DashPayContactInfoUpdated { + identity: owner, + contact_id: Identifier::from(CONTACT), + }; + + hub.state_mut() + .0 + .display_backend_task_result(&foreign, updated()); + hub.run_steps(2); + assert!( + hub.query_by_label(SAVING_NOTE_LABEL).is_some(), + "another screen's save must not settle the hub's queued note" + ); + + hub.state_mut() + .0 + .display_backend_task_result(&own_context, updated()); + hub.run_steps(2); + assert!(hub.query_by_label(SAVING_NOTE_LABEL).is_none()); + }); +} + +/// Likewise, another screen's failure for the same contact leaves the hub's +/// queued note save running. +#[test] +fn a_foreign_same_contact_failure_does_not_release_the_hubs_note() { + use dash_evo_tool::backend_task::error::TaskError; + with_isolated_data_dir(|| { + let runtime = tokio::runtime::Runtime::new().expect("runtime"); + let _guard = runtime.enter(); + let app = + crate::support::mount_app(dash_evo_tool::ui::RootScreenType::RootScreenWalletsBalances); + let (mut hub, owner, _) = hub_saving_a_note(&app); + let foreign = foreign_write_context(&hub); + + for error in [ + contact_info_failure(owner, TaskError::WalletLocked), + TaskError::WalletLocked, + ] { + hub.state_mut() + .0 + .display_backend_task_error(&foreign, &error); + hub.state_mut().0.display_task_error(&error); + hub.run_steps(2); + assert!( + hub.query_by_label(SAVING_NOTE_LABEL).is_some(), + "another screen's failure must not release the hub's queued note: {error:?}" + ); + } + }); +} + #[test] fn failed_unhide_behind_another_screen_restores_the_hidden_row() { use dash_evo_tool::backend_task::error::TaskError; @@ -577,11 +666,11 @@ fn failed_unhide_behind_another_screen_restores_the_hidden_row() { .state() .1 .iter() - .find_map(|action| match action { - AppAction::BackendTask(task @ BackendTask::DashPayTask(inner)) + .find_map(|action| match dispatched_task(action)? { + (BackendTask::DashPayTask(inner), context) if matches!(**inner, DashPayTask::UpdateContactInfo { .. }) => { - Some(BackendTaskContext::from(task)) + Some(context) } _ => None, }) @@ -614,8 +703,11 @@ fn failed_unhide_behind_another_screen_restores_the_hidden_row() { .click(); hub.run_steps(2); assert!( - hub.state().1.iter().any(|action| matches!(action, - AppAction::BackendTask(BackendTask::DashPayTask(task)) + hub.state() + .1 + .iter() + .any(|action| matches!(dispatched_task(action), + Some((BackendTask::DashPayTask(task), _)) if matches!(**task, DashPayTask::UpdateContactInfo { .. }))), "the restored hidden row permits a retry" ); From a68370cd87966644dfd4f1cad56f9d127088905a Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 22 Oct 2026 19:10:56 +0000 Subject: [PATCH 24/73] fix(identity): keep a running contact details write correlated across identity switches MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Switching identity kept a running note save's or unhide's write guard but dropped its pending task and dispatch record. Its later outcome then read as another screen's, so success never settled it, failure never released it, and the contact stayed on Saving… on return. The identity reset now keeps the records of every write whose guard is still live, and each outcome retires the pending task and the dispatch record together. Co-Authored-By: Claude Opus 5.5 --- src/ui/identity/hub_screen.rs | 139 +++++++++++++++++++++++++++++++--- 1 file changed, 128 insertions(+), 11 deletions(-) diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index cf2965203..e6866ec2e 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -211,6 +211,12 @@ impl IdentityHubScreen { AppAction::BackendTaskWithContext { task, context } } + /// Retire a settled or abandoned write's records together. + fn forget_contact_info_task(&mut self, key: &ContactInfoTaskKey) -> Option { + self.contact_info_dispatches.remove(key); + self.pending_contact_info_tasks.remove(key) + } + /// Whether `context` is the dispatch of the hub's own write for its contact. fn is_own_contact_info_dispatch(&self, context: &BackendTaskContext) -> bool { context @@ -253,8 +259,15 @@ impl IdentityHubScreen { ); self.home_state = HomeState::default(); self.contacts_state.reset_for_identity_change(); - self.pending_contact_info_tasks.clear(); - self.contact_info_dispatches.clear(); + // A write still running keeps its guard across the change, so it keeps + // the records its outcome is matched against too. + let detail = self.contacts_state.detail(); + let live = |key: &ContactInfoTaskKey| { + matches!(key, ContactInfoTaskKey::Direct { identity_id, contact_id } + if detail.is_writing(identity_id, contact_id)) + }; + self.pending_contact_info_tasks.retain(|key, _| live(key)); + self.contact_info_dispatches.retain(|key, _| live(key)); self.pending_contact_info_confirmations.clear(); self.contact_info_overwrite_dialog = None; } @@ -432,7 +445,7 @@ impl IdentityHubScreen { return true; } if let Some(key) = contact_info_error_key(error) { - self.pending_contact_info_tasks.remove(&key); + self.forget_contact_info_task(&key); } release_request_guard_for_error(&mut self.contacts_state, error); true @@ -456,7 +469,7 @@ impl IdentityHubScreen { return true; } if let Some(key) = contact_info_error_key(error) { - self.pending_contact_info_tasks.remove(&key); + self.forget_contact_info_task(&key); } release_contact_info_write_for_error(&mut self.contacts_state, error); false @@ -756,7 +769,7 @@ impl ScreenLike for IdentityHubScreen { } Some(ConfirmationStatus::Canceled) => { release_guards_for_abandoned_confirmations(&mut self.contacts_state, [&key]); - self.pending_contact_info_tasks.remove(&key); + self.forget_contact_info_task(&key); self.contacts_state.invalidate(); self.contact_info_overwrite_dialog = None; } @@ -911,7 +924,7 @@ impl ScreenLike for IdentityHubScreen { }; self.contacts_state .finish_contact_info_write(identity, contact_id); - if let Some(task) = self.pending_contact_info_tasks.remove(&key) { + if let Some(task) = self.forget_contact_info_task(&key) { self.contacts_state.invalidate(); MessageBanner::set_global( self.app_context.egui_ctx(), @@ -972,11 +985,10 @@ impl ScreenLike for IdentityHubScreen { && !matches!(error, TaskError::DashPayContactInfoActionFailed { .. }) && let Some((identity_id, contact_id)) = context.dashpay_contact_info_target() { - self.pending_contact_info_tasks - .remove(&ContactInfoTaskKey::Direct { - identity_id, - contact_id, - }); + self.forget_contact_info_task(&ContactInfoTaskKey::Direct { + identity_id, + contact_id, + }); self.contacts_state .release_contact_info_write(&identity_id, &contact_id); } @@ -2391,6 +2403,111 @@ mod tests { assert!(!state.detail().is_writing(&id(3), &id(4))); } + /// A note save for identity A that is still running when the user switches + /// to B and back keeps its dispatch: its success settles it, and either + /// kind of failure releases it, instead of leaving A's contact on Saving…. + async fn settle_after_an_identity_switch(outcome: &str) { + use crate::model::dashpay::ContactInfoUpdate; + let (owner, contact) = (id(3), id(4)); + let wrapped = TaskError::DashPayContactInfoActionFailed { + identity_id: owner, + contact_id: contact, + source: Box::new(TaskError::WalletLocked), + }; + { + let (_temp_dir, app_context) = wired_test_context().await; + let mut screen = IdentityHubScreen::new(&app_context); + screen.contacts_state.record_contacts(vec![ + crate::backend_task::dashpay::ContactData { + identity_id: contact, + nickname: None, + note: None, + is_hidden: false, + account_reference: 0, + username: None, + display_name: None, + avatar_url: None, + bio: None, + }, + ]); + screen.contacts_state.select_contact(&contact); + *screen + .contacts_state + .detail_mut() + .note_mut(&contact) + .expect("draft") = "Bao".into(); + assert!( + screen + .contacts_state + .detail_mut() + .begin_save(owner, contact) + .is_some() + ); + let action = AppAction::BackendTask(BackendTask::DashPayTask(Box::new( + DashPayTask::UpdateContactInfo { + identity: hub_identity(owner), + contact_id: contact, + update: ContactInfoUpdate::note(Some("Bao".into())), + }, + ))); + screen.capture_contact_info_update(&action); + let AppAction::BackendTaskWithContext { + context: dispatched, + .. + } = screen.bind_contact_info_dispatch(action) + else { + panic!("the write is sent under its own dispatch"); + }; + + // A → B → A while the write runs. + screen.reset_contacts_for_identity_change(); + screen.reset_contacts_for_identity_change(); + + match outcome { + "success" => screen.display_backend_task_result( + &dispatched, + BackendTaskSuccessResult::DashPayContactInfoUpdated { + identity: owner, + contact_id: contact, + }, + ), + "wrapped failure" => { + screen.display_backend_task_error(&dispatched, &wrapped); + screen.display_task_error(&wrapped); + } + _ => { + screen.display_backend_task_error(&dispatched, &TaskError::WalletLocked); + screen.display_task_error(&TaskError::WalletLocked); + } + } + + assert!( + !screen.contacts_state.detail().is_writing(&owner, &contact), + "{outcome} after A → B → A must settle the write" + ); + assert!( + screen.contact_info_dispatches.is_empty() + && screen.pending_contact_info_tasks.is_empty(), + "{outcome}: the dispatch record retires with its guard" + ); + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_write_succeeding_after_an_identity_switch_settles() { + settle_after_an_identity_switch("success").await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_write_failing_after_an_identity_switch_is_released() { + settle_after_an_identity_switch("wrapped failure").await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_write_failing_bare_after_an_identity_switch_is_released() { + settle_after_an_identity_switch("bare failure").await; + } + #[test] fn concurrent_contact_info_errors_keep_distinct_retry_keys() { use crate::backend_task::error::ContactInfoReadError; From a31aef07352d8769ecaa4ad30e8ca349ab351a96 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 22 Oct 2026 19:49:51 +0000 Subject: [PATCH 25/73] fix(dashpay): finish the withdraw lifecycle and fail unsafe contact details saves - The request list uses the same withdrawal-aware contact check as the contacts list, so a reply to a withdrawn request is listed to answer instead of being dropped with it. - Accepting that reply, or sending a request again, restores the owner's withdrawn request that still stands on Platform: the ignore is lifted and the markers cleared, with no second publish. Accepting reports the request as accepted. - A save stops when the current details cannot be read (a cancelled password prompt included), instead of saving the fields it keeps from empty values, and fails when its synced record cannot be written. - The on-this-device banner says the details must be saved again once the identity has two contacts. Co-Authored-By: Claude Opus 5.5 --- docs/user-stories.md | 4 +- src/backend_task/dashpay/contact_info.rs | 234 +++++++++++++++---- src/backend_task/dashpay/contact_requests.rs | 191 ++++++++++++--- src/backend_task/dashpay/contacts.rs | 18 +- src/ui/identity/contacts.rs | 5 +- src/wallet_backend/contact_info.rs | 25 +- 6 files changed, 385 insertions(+), 92 deletions(-) diff --git a/docs/user-stories.md b/docs/user-stories.md index 268504a9d..dee58dae1 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -1081,8 +1081,8 @@ As a user, I want to edit contact details (nickname, note, hidden status) so tha - The Identity Hub contact details edit the private note, which is saved encrypted on Dash Platform in the DashPay (DIP-0015) format other DashPay clients read; a conservative fee estimate is shown before saving, and the saved note loads with the contact from the network. - Until the identity has two contacts, details are kept on this device and published later, and - the app says so. Details saved by older versions of this app still show until replaced. Hub notes are not copied to the local memo: offline views and + Until the identity has two contacts, details are kept on this device only, and the app says so; + saving them again after that publishes them. Details saved by older versions of this app still show until replaced. Hub notes are not copied to the local memo: offline views and legacy DashPay screens can continue to show an older local note. - Edits made through the legacy contact-details screen persist in its local memo. diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 19db13914..55a005c08 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -8,8 +8,9 @@ use crate::backend_task::BackendTaskSuccessResult; use crate::backend_task::error::TaskError; use crate::context::AppContext; -use crate::model::dashpay::{ContactInfoUpdate, validate_contact_note}; +use crate::model::dashpay::{ContactDetails, ContactInfoUpdate, validate_contact_note}; use crate::model::qualified_identity::QualifiedIdentity; +use crate::wallet_backend::WalletBackend; use dash_sdk::Sdk; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::platform::proto::get_documents_request::get_documents_request_v0::Start; @@ -73,28 +74,50 @@ pub async fn create_or_update_contact_info( contact_user_id: Identifier, update: ContactInfoUpdate, ) -> Result { - let _write_guard = app_context - .contact_info_writes - .acquire(identity.identity.id()) - .await; - let backend = app_context.wallet_backend()?; let owner = identity.identity.id(); + let _write_guard = app_context.contact_info_writes.acquire(owner).await; + let ops = PlatformSaveOps { + app_context, + sdk, + backend: app_context.wallet_backend()?, + identity: &identity, + contact_id: contact_user_id, + }; + let published = save_contact_details(&ops, &update).await?; + Ok(BackendTaskSuccessResult::DashPayContactInfoUpdated { + identity: owner, + contact_id: contact_user_id, + published, + }) +} - backend.dashpay_sync_contact_infos(&owner).await?; - let local = backend - .dashpay_contact_details(&owner) - .await - .remove(&contact_user_id); - let mut stored = super::contacts::stored_contact_details(app_context, sdk, &identity).await?; - let published = stored.published.remove(&contact_user_id); - let synced_before = backend.dashpay_details_synced(&owner, &contact_user_id) - || super::contacts::holds_details(published.as_ref(), local.as_ref()); - let legacy = stored - .legacy - .get(&contact_user_id) - .map(super::contacts::ContactData::details); - let current = super::contacts::shown_contact_details(published, local, synced_before, legacy); - let details = update.apply_to(current); +/// The reads and writes one contact details save performs, behind a trait so +/// their order and failures can be driven in tests. +trait SaveOps { + /// The details shown for the contact now; the fields an update keeps. + fn current(&self) -> impl Future> + Send; + fn publish( + &self, + details: ContactDetails, + ) -> impl Future> + Send; + /// Record that platform-wallet holds the contact's details, so a legacy + /// document no longer stands in for them. + fn mark_synced(&self) -> Result<(), TaskError>; +} + +/// Save `update` and return whether the details reached Platform. +/// +/// # Errors +/// +/// Nothing is written when the current details cannot be read (a cancelled +/// password prompt included): a field the update keeps would otherwise be +/// saved from a guess. A save whose synced record fails is reported as +/// failed, since the old legacy details would show again on reload. +async fn save_contact_details( + ops: &O, + update: &ContactInfoUpdate, +) -> Result { + let details = update.apply_to(ops.current().await?); validate_contact_note(details.note.as_deref().unwrap_or_default())?; // The bound platform-wallet enforces, checked before it saves anything. @@ -108,30 +131,69 @@ pub async fn create_or_update_contact_info( source: Box::new(source), })?; - let outcome = backend - .dashpay_set_contact_info(&identity, &contact_user_id, details) - .await?; - // platform-wallet holds these details now, published or not. - if let Err(error) = backend.dashpay_mark_details_synced(&owner, &contact_user_id) { - tracing::debug!( - ?error, - "could not record that the contact details are synced" - ); - } - let published = match outcome { - ContactInfoPublishOutcome::Published => true, - ContactInfoPublishOutcome::DeferredUntilTwoContacts => false, + let outcome = ops.publish(details).await?; + ops.mark_synced()?; + match outcome { + ContactInfoPublishOutcome::Published => Ok(true), + ContactInfoPublishOutcome::DeferredUntilTwoContacts => Ok(false), // The write checks for a wallet identity index before platform-wallet // runs, so this is reached only if the two disagree. ContactInfoPublishOutcome::SkippedWatchOnly => { - return Err(TaskError::ContactInfoIdentityNotFromWallet); + Err(TaskError::ContactInfoIdentityNotFromWallet) } - }; - Ok(BackendTaskSuccessResult::DashPayContactInfoUpdated { - identity: owner, - contact_id: contact_user_id, - published, - }) + } +} + +struct PlatformSaveOps<'a> { + app_context: &'a Arc, + sdk: &'a Sdk, + backend: Arc, + identity: &'a QualifiedIdentity, + contact_id: Identifier, +} + +impl SaveOps for PlatformSaveOps<'_> { + async fn current(&self) -> Result { + let owner = self.identity.identity.id(); + self.backend.dashpay_sync_contact_infos(&owner).await?; + let local = self + .backend + .dashpay_contact_details(&owner) + .await + .remove(&self.contact_id); + let stored = + super::contacts::stored_contact_details(self.app_context, self.sdk, self.identity) + .await?; + let published = stored.published?.remove(&self.contact_id); + let synced_before = self + .backend + .dashpay_details_synced(&owner, &self.contact_id) + || super::contacts::holds_details(published.as_ref(), local.as_ref()); + let legacy = stored + .legacy + .get(&self.contact_id) + .map(super::contacts::ContactData::details); + Ok(super::contacts::shown_contact_details( + published, + local, + synced_before, + legacy, + )) + } + + async fn publish( + &self, + details: ContactDetails, + ) -> Result { + self.backend + .dashpay_set_contact_info(self.identity, &self.contact_id, details) + .await + } + + fn mark_synced(&self) -> Result<(), TaskError> { + self.backend + .dashpay_mark_details_synced(&self.identity.identity.id(), &self.contact_id) + } } #[cfg(test)] @@ -268,6 +330,96 @@ mod tests { } } + struct ScriptedSave { + current: std::sync::Mutex>>, + mark_fails: bool, + published: std::sync::Mutex>, + } + + impl ScriptedSave { + fn new(current: Result, mark_fails: bool) -> Self { + Self { + current: std::sync::Mutex::new(Some(current)), + mark_fails, + published: std::sync::Mutex::new(Vec::new()), + } + } + } + + impl SaveOps for ScriptedSave { + async fn current(&self) -> Result { + self.current.lock().unwrap().take().expect("read once") + } + + async fn publish( + &self, + details: ContactDetails, + ) -> Result { + self.published.lock().unwrap().push(details); + Ok(ContactInfoPublishOutcome::DeferredUntilTwoContacts) + } + + fn mark_synced(&self) -> Result<(), TaskError> { + if self.mark_fails { + return Err(TaskError::DashpaySidecarStorage { + source: crate::wallet_backend::KvAdapterError::Truncated, + }); + } + Ok(()) + } + } + + /// A cancelled password prompt while reading the current details stops + /// the save: a note-only save must not overwrite the nickname or the + /// hidden flag with empty values it never read. + #[tokio::test] + async fn an_unreadable_baseline_writes_nothing() { + let ops = ScriptedSave::new(Err(TaskError::SecretPromptCancelled), false); + + let result = save_contact_details(&ops, &ContactInfoUpdate::note(Some("n".into()))).await; + + assert!(matches!(result, Err(TaskError::SecretPromptCancelled))); + assert!(ops.published.lock().unwrap().is_empty()); + } + + /// A save whose synced record fails is not reported as saved: on reload + /// the old legacy details would show again. + #[tokio::test] + async fn a_failed_synced_record_fails_the_save() { + let ops = ScriptedSave::new(Ok(ContactDetails::default()), true); + + let result = + save_contact_details(&ops, &ContactInfoUpdate::replace_all(None, None, false)).await; + + assert!(matches!( + result, + Err(TaskError::DashpaySidecarStorage { .. }) + )); + } + + #[tokio::test] + async fn a_save_keeps_the_fields_it_does_not_replace() { + let current = ContactDetails { + nickname: Some("Bao".into()), + note: None, + hidden: true, + }; + let ops = ScriptedSave::new(Ok(current.clone()), false); + + let published = save_contact_details(&ops, &ContactInfoUpdate::note(Some("n".into()))) + .await + .expect("saved"); + + assert!(!published, "deferred until two contacts"); + assert_eq!( + *ops.published.lock().unwrap(), + vec![ContactDetails { + note: Some("n".into()), + ..current + }] + ); + } + fn contact_details_page(documents: impl IntoIterator) -> Documents { documents .into_iter() diff --git a/src/backend_task/dashpay/contact_requests.rs b/src/backend_task/dashpay/contact_requests.rs index 50809de2f..e082d2787 100644 --- a/src/backend_task/dashpay/contact_requests.rs +++ b/src/backend_task/dashpay/contact_requests.rs @@ -99,33 +99,8 @@ pub async fn load_contact_requests( .filter_map(|(id, doc)| doc.map(|d| (id, d))) .collect(); - // Filter out mutual requests (where both parties have sent requests to each other) - // These are now contacts, not pending requests - let contacts_established: HashSet = incoming - .iter() - .map(|(_, doc)| doc.owner_id()) - .filter(|from_id| { - outgoing - .iter() - .any(|(_, doc)| contact_request_recipient(doc).as_ref() == Some(from_id)) - }) - .collect(); - - // Filter out established contacts from both lists. An outgoing document - // with an unreadable recipient is kept: it cannot be attributed, and hiding - // a request the user may still be waiting on is the worse failure. - incoming.retain(|(_, doc)| !contacts_established.contains(&doc.owner_id())); - - outgoing.retain(|(_, doc)| match contact_request_recipient(doc) { - Some(to_id) => !contacts_established.contains(&to_id), - None => true, - }); - - // Drop requests the user has already resolved locally (declined an incoming - // one, or withdrawn a sent one). Platform keeps contactRequest documents - // forever, so without this the resolved row reappears on every reload. let backend = app_context.wallet_backend().ok(); - retain_unresolved( + pending_requests( &mut incoming, &mut outgoing, |sender| match &backend { @@ -151,6 +126,28 @@ pub async fn load_contact_requests( }) } +/// Keep only the requests still waiting for an answer: drop the pairs that +/// are contacts (both sides sent a request, unless the owner withdrew theirs — +/// a reply to a withdrawn request is a new request to answer), then every +/// request the user resolved on this device; see [`retain_unresolved`]. +fn pending_requests( + incoming: &mut Vec<(Identifier, Document)>, + outgoing: &mut Vec<(Identifier, Document)>, + is_declined: impl Fn(&Identifier) -> bool, + is_withdrawn: impl Fn(&Identifier) -> bool, +) { + let contacts_established = super::contacts::mutual_contacts(incoming, outgoing, &is_withdrawn); + // An outgoing document with an unreadable recipient is kept: it cannot be + // attributed, and hiding a request the user may still be waiting on is + // the worse failure. + incoming.retain(|(_, doc)| !contacts_established.contains(&doc.owner_id())); + outgoing.retain(|(_, doc)| match contact_request_recipient(doc) { + Some(to_id) => !contacts_established.contains(&to_id), + None => true, + }); + retain_unresolved(incoming, outgoing, is_declined, is_withdrawn); +} + /// Drop every request the user has already resolved: an incoming one they /// declined (per `is_declined`, keyed on the sender) or a sent one they withdrew /// (per `is_withdrawn`, keyed on the recipient). @@ -306,6 +303,20 @@ pub async fn send_contact_request_with_proof( let existing = Document::fetch_many(sdk, existing_query).await?; if !existing.is_empty() { + // A withdrawn request still stands on Platform: sending again restores + // it instead of publishing a duplicate. + if let Ok(backend) = app_context.wallet_backend() + && restore_withdrawn_request(&PlatformReEngage { + backend: &backend, + owner: identity.identity.id(), + peer: to_identity_id, + }) + .await? + { + return Ok(BackendTaskSuccessResult::DashPayContactRequestSent( + to_username_or_id.to_string(), + )); + } return Err(DashPayError::ContactRequestAlreadySent { to: to_username_or_id.to_string(), } @@ -704,9 +715,22 @@ pub async fn accept_contact_request( let existing = Document::fetch_many(sdk, existing_query).await?; if !existing.is_empty() { - return Ok(BackendTaskSuccessResult::DashPayContactAlreadyEstablished { - request_id, - contact_id: from_identity_id, + // Our earlier request still stands on Platform. If it was withdrawn, + // accepting restores it, and with it the contact. + let backend = app_context.wallet_backend()?; + let restored = restore_withdrawn_request(&PlatformReEngage { + backend: &backend, + owner: identity.identity.id(), + peer: from_identity_id, + }) + .await?; + return Ok(if restored { + BackendTaskSuccessResult::DashPayContactRequestAccepted(request_id) + } else { + BackendTaskSuccessResult::DashPayContactAlreadyEstablished { + request_id, + contact_id: from_identity_id, + } }); } @@ -798,6 +822,48 @@ pub async fn accept_contact_request( } } +/// The local state that re-engages someone the owner withdrew a request +/// from, behind a trait so the decision can be driven in tests. +trait ReEngageOps { + fn is_withdrawn(&self) -> bool; + /// Lift the ignore and clear the withdrawal and decline markers. + fn re_engage(&self) -> impl Future> + Send; +} + +/// Restore a withdrawn request the owner sent earlier, which still stands on +/// Platform; returns whether there was one. Nothing is published. +async fn restore_withdrawn_request(ops: &O) -> Result { + if !ops.is_withdrawn() { + return Ok(false); + } + ops.re_engage().await?; + Ok(true) +} + +struct PlatformReEngage<'a> { + backend: &'a crate::wallet_backend::WalletBackend, + owner: Identifier, + peer: Identifier, +} + +impl ReEngageOps for PlatformReEngage<'_> { + fn is_withdrawn(&self) -> bool { + self.backend.dashpay_is_withdrawn(&self.owner, &self.peer) + } + + async fn re_engage(&self) -> Result<(), TaskError> { + // The ignore first: the withdrawal keeps the person out of the lists + // until it is lifted, so a failure here leaves a retry possible. + self.backend + .dashpay_unignore_contact_sender(&self.owner, &self.peer) + .await?; + self.backend + .dashpay_unmark_declined(&self.owner, &self.peer)?; + self.backend + .dashpay_unmark_withdrawn(&self.owner, &self.peer) + } +} + pub async fn reject_contact_request( app_context: &Arc, sdk: &Sdk, @@ -1246,6 +1312,73 @@ mod tests { )); } + /// PRRT_kwDOM8GK3c6vWRKJ: after the owner withdraws their request to + /// id(3), id(3)'s later request is listed for the owner to answer; the + /// pair is not taken for a contact and both rows dropped. + #[test] + fn a_reply_to_a_withdrawn_request_is_listed_to_answer() { + let owner = id(9); + let mut incoming = vec![ + (id(10), request_doc(id(3), Some(owner))), + (id(11), request_doc(id(4), Some(owner))), + ]; + let mut outgoing = vec![ + (id(12), request_doc(owner, Some(id(3)))), + (id(13), request_doc(owner, Some(id(4)))), + ]; + + pending_requests( + &mut incoming, + &mut outgoing, + |_| false, + |peer| *peer == id(3), + ); + + assert_eq!( + incoming.iter().map(|(id, _)| *id).collect::>(), + vec![id(10)], + "id(3)'s reply waits for an answer; id(4) is a contact" + ); + assert!(outgoing.is_empty(), "the withdrawn request is not listed"); + } + + #[derive(Default)] + struct ScriptedReEngage { + withdrawn: bool, + re_engaged: std::sync::Mutex, + } + + impl ReEngageOps for ScriptedReEngage { + fn is_withdrawn(&self) -> bool { + self.withdrawn + } + + async fn re_engage(&self) -> Result<(), TaskError> { + *self.re_engaged.lock().unwrap() = true; + Ok(()) + } + } + + /// PRRT_kwDOM8GK3c6vWRKe: accepting (or sending again) where the owner's + /// withdrawn request still stands restores it without a new publish. + #[tokio::test] + async fn an_existing_withdrawn_request_is_restored() { + let ops = ScriptedReEngage { + withdrawn: true, + ..Default::default() + }; + assert!(restore_withdrawn_request(&ops).await.expect("restored")); + assert!(*ops.re_engaged.lock().unwrap()); + + let pending = ScriptedReEngage::default(); + assert!( + !restore_withdrawn_request(&pending) + .await + .expect("nothing to restore") + ); + assert!(!*pending.re_engaged.lock().unwrap()); + } + #[test] fn retain_unresolved_drops_declined_and_withdrawn_rows() { // Incoming from id(1) — declined. Incoming from id(2) — still pending. diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index 4fb74bf1e..69e86ba9d 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -236,8 +236,10 @@ where /// The details the owner's stored `contactInfo` documents hold. pub(super) struct StoredContactDetails { - /// From DIP-0015 documents platform-wallet can read, newest per contact. - pub(super) published: BTreeMap, + /// From DIP-0015 documents platform-wallet can read, newest per contact; + /// an error when the seed could not be used to read them. A save must not + /// guess past that error; the contacts list may. + pub(super) published: Result, TaskError>, /// From documents older versions of this app wrote under the legacy /// key root, newest per contact. pub(super) legacy: HashMap, @@ -276,7 +278,7 @@ pub(super) async fn stored_contact_details( .dashpay_open_contact_infos(identity, &documents) .await } - Err(_) => BTreeMap::new(), + Err(_) => Ok(BTreeMap::new()), }; let legacy = legacy_details_from(&documents, |derivation_index| { derive_contact_info_keys(app_context, identity, derivation_index) @@ -447,10 +449,12 @@ pub async fn load_contacts( Default::default() } }; - let StoredContactDetails { - mut published, - legacy, - } = stored_contact_details(app_context, sdk, &identity).await?; + let StoredContactDetails { published, legacy } = + stored_contact_details(app_context, sdk, &identity).await?; + let mut published = published.unwrap_or_else(|error| { + tracing::debug!(?error, "LoadContacts: published contact details not read"); + BTreeMap::new() + }); // Build enriched contact list with basic data let mut contact_list: Vec = contacts diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index 847478f3a..50efcb35b 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -61,8 +61,9 @@ pub const NOTE_UNCHANGED_TOOLTIP: &str = "There are no changes to save."; pub const NOTE_SAVE_TOOLTIP: &str = "Save this note on Dash Platform. Saving costs a small fee."; pub const NOTE_SAVED: &str = "Your note is saved."; /// Shown when contact details are kept on this device only: DIP-0015 holds -/// them back until the identity has two contacts. -pub const DETAILS_SAVED_ON_THIS_DEVICE: &str = "Your contact details are saved on this device. They will sync to your other devices once this identity has two contacts."; +/// them back until the identity has two contacts, and nothing publishes them +/// later on its own. +pub const DETAILS_SAVED_ON_THIS_DEVICE: &str = "Your contact details are saved on this device only. After this identity has two contacts, edit and save these details again to sync them to your other devices."; const NOTE_SAVING_TOOLTIP: &str = "This contact's details are being saved."; pub const RECEIVED_HEADING: &str = "Received requests"; pub const ACTIVE_HEADING_PREFIX: &str = "Active contacts"; diff --git a/src/wallet_backend/contact_info.rs b/src/wallet_backend/contact_info.rs index 3b6b88077..35776b1e1 100644 --- a/src/wallet_backend/contact_info.rs +++ b/src/wallet_backend/contact_info.rs @@ -156,20 +156,25 @@ impl WalletBackend { /// with platform-wallet's keys and codec; `documents` are oldest first and /// the newest per contact wins. Documents that do not open — legacy-key /// ones, or another client's — are skipped. Empty when the identity has - /// no wallet identity index or the seed is unavailable. + /// no wallet or wallet identity index, so none can be DIP-0015 ones. + /// + /// # Errors + /// + /// The seed could not be used, for example because the password prompt + /// was cancelled. pub(crate) async fn dashpay_open_contact_infos( &self, identity: &QualifiedIdentity, documents: &[Document], - ) -> BTreeMap { + ) -> Result, TaskError> { if documents.is_empty() { - return BTreeMap::new(); + return Ok(BTreeMap::new()); } let Some(seed_hash) = identity.dashpay_wallet_seed_hash() else { - return BTreeMap::new(); + return Ok(BTreeMap::new()); }; let Ok(wallet) = self.resolve_wallet(&seed_hash).await else { - return BTreeMap::new(); + return Ok(BTreeMap::new()); }; let owner = identity.identity.id(); let identity_index = { @@ -180,7 +185,7 @@ impl WalletBackend { .and_then(|managed| managed.identity_index) }; let Some(identity_index) = identity_index else { - return BTreeMap::new(); + return Ok(BTreeMap::new()); }; let network = identity.network; self.secret_access() @@ -190,18 +195,16 @@ impl WalletBackend { .expose_hd_seed() .ok_or(TaskError::ContactWalletSeedUnavailable)?; let crypto = ContactInfoCrypto::new(seed, network, identity_index); - Ok::<_, TaskError>(open_contact_info_documents(&crypto, documents).await) + Ok(open_contact_info_documents(&crypto, documents).await) }) .await - .unwrap_or_else(|error| { - tracing::debug!(?error, "contactInfo documents could not be opened"); - BTreeMap::new() - }) } } /// Open `documents` (oldest first) through `crypto`; the newest readable /// document per contact wins. +// TODO: replace with a platform-wallet contactInfo-only read for seedless +// wallets once one exists (upstream issue drafted, not yet filed). async fn open_contact_info_documents( crypto: &ContactInfoCrypto<'_>, documents: &[Document], From 15ec29215d6ec924d7a3d43c8645c31c54aa24f3 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:38:15 +0000 Subject: [PATCH 26/73] fix(identity): drop contact lists from loads older than the latest one A reload re-arms without cancelling the load before it, so two contact loads can answer out of order. When the newer one returned the saved note first, the confirmed-note overlay was released, and the older one then put the old note and a clean draft back. The contact list load now goes out under its own dispatch (a new `AppAction::BackendTasksWithContexts` batch keeps both loads in one action), and the hub drops a list from any load older than the newest it dispatched. Co-Authored-By: Claude Opus 5.5 --- src/app.rs | 28 +++++- src/ui/identity/contacts.rs | 36 ++++--- src/ui/identity/hub_screen.rs | 124 +++++++++++++++++++++++++ src/ui/state/contacts_view.rs | 19 ++++ tests/kittest/identity_home.rs | 4 +- tests/kittest/identity_hub.rs | 22 +++-- tests/kittest/identity_hub_contacts.rs | 2 +- 7 files changed, 203 insertions(+), 32 deletions(-) diff --git a/src/app.rs b/src/app.rs index cb32ed1d8..bce86a637 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1506,6 +1506,12 @@ pub enum AppAction { context: BackendTaskContext, }, BackendTasks(Vec, BackendTasksExecutionMode), + /// [`Self::BackendTasks`] with the context each task's result comes back + /// under, so a screen can tell one dispatch of a task from another. + BackendTasksWithContexts( + Vec<(BackendTask, BackendTaskContext)>, + BackendTasksExecutionMode, + ), /// Wire the wallet backend (if needed) and start chain sync for the active /// context. Handled by the update loop, which owns the `TaskResult` sender /// the wiring step requires. Used by the manual Connect button so a click @@ -2406,13 +2412,23 @@ impl AppState { /// Handle the backend tasks and send the results through the channel fn handle_backend_tasks(&self, tasks: Vec, mode: BackendTasksExecutionMode) { + let network = self.current_app_context().network; + let contexts = tasks + .iter() + .map(|task| BackendTaskContext::for_task_on(task, network)) + .collect(); + self.run_backend_tasks(tasks, contexts, mode); + } + + fn run_backend_tasks( + &self, + tasks: Vec, + contexts: Vec, + mode: BackendTasksExecutionMode, + ) { let sender = self.task_result_sender.clone(); let watcher_sender = sender.clone(); let app_context = self.current_app_context().clone(); - let contexts = tasks - .iter() - .map(|task| BackendTaskContext::for_task_on(task, app_context.network)) - .collect::>(); let handle = tokio::runtime::Handle::current(); let _ = self.subtasks.spawn_blocking_sync( @@ -4332,6 +4348,10 @@ impl App for AppState { AppAction::BackendTasks(tasks, mode) => { self.handle_backend_tasks(tasks, mode); } + AppAction::BackendTasksWithContexts(tasks, mode) => { + let (tasks, contexts) = tasks.into_iter().unzip(); + self.run_backend_tasks(tasks, contexts, mode); + } AppAction::SetMainScreen(root_screen_type) => { self.set_main_screen(root_screen_type); } diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index b8990febb..e3c2ab915 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -20,8 +20,8 @@ use super::request_card::{RequestAction, RequestCard}; use super::social_profile_gate_card::SocialProfileGateCard; use crate::app::{AppAction, BackendTasksExecutionMode}; -use crate::backend_task::BackendTask; use crate::backend_task::dashpay::{ContactData, DashPayTask}; +use crate::backend_task::{BackendTask, BackendTaskContext}; use crate::context::AppContext; use crate::context::feature_gate::FeatureGate; use crate::model::dashpay::{ @@ -238,15 +238,20 @@ pub(super) fn load_action(identity: &QualifiedIdentity, state: &mut ContactsStat if !state.claim_load() { return AppAction::None; } - AppAction::BackendTasks( - vec![ - BackendTask::DashPayTask(Box::new(DashPayTask::LoadContacts { - identity: identity.clone(), - })), - BackendTask::DashPayTask(Box::new(DashPayTask::LoadContactRequests { - identity: identity.clone(), - })), - ], + let contacts = BackendTask::DashPayTask(Box::new(DashPayTask::LoadContacts { + identity: identity.clone(), + })); + // Its own dispatch, so an older load answering late is recognised as stale. + let contacts_context = BackendTaskContext::for_dispatch_on(&contacts, identity.network); + if let Some(dispatch_id) = contacts_context.dispatch_id() { + state.record_contacts_load(dispatch_id); + } + let requests = BackendTask::DashPayTask(Box::new(DashPayTask::LoadContactRequests { + identity: identity.clone(), + })); + let requests_context = BackendTaskContext::for_task_on(&requests, identity.network); + AppAction::BackendTasksWithContexts( + vec![(contacts, contacts_context), (requests, requests_context)], BackendTasksExecutionMode::Concurrent, ) } @@ -1318,12 +1323,12 @@ mod tests { } fn load_owner_ids(action: AppAction) -> Vec { - let AppAction::BackendTasks(tasks, _) = action else { + let AppAction::BackendTasksWithContexts(tasks, _) = action else { panic!("expected the contact loads, got {action:?}"); }; tasks .into_iter() - .map(|task| match task { + .map(|(task, _)| match task { BackendTask::DashPayTask(task) => match *task { DashPayTask::LoadContacts { identity } | DashPayTask::LoadContactRequests { identity } => identity.identity.id(), @@ -1765,20 +1770,21 @@ mod tests { let identity = qualified_identity(id(1)); let mut state = ContactsState::default(); - let AppAction::BackendTasks(tasks, mode) = load_action(&identity, &mut state) else { + let AppAction::BackendTasksWithContexts(tasks, mode) = load_action(&identity, &mut state) + else { panic!("hydration must dispatch its loads as one multi-task action"); }; assert_eq!(mode, BackendTasksExecutionMode::Concurrent); assert!( - tasks.iter().any(|t| matches!( + tasks.iter().any(|(t, _)| matches!( t, BackendTask::DashPayTask(task) if matches!(**task, DashPayTask::LoadContacts { .. }) )), "the contact list must be loaded — without it the active section stays empty" ); assert!( - tasks.iter().any(|t| matches!( + tasks.iter().any(|(t, _)| matches!( t, BackendTask::DashPayTask(task) if matches!(**task, DashPayTask::LoadContactRequests { .. }) diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index e6866ec2e..bd98db733 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -848,6 +848,17 @@ impl ScreenLike for IdentityHubScreen { ); return; } + // A reload re-arms without cancelling the load before it, so lists + // can answer out of order; an older one would undo a confirmed note. + if matches!( + result, + BackendTaskSuccessResult::DashPayContactsWithInfo { .. } + ) && !self + .contacts_state + .accepts_contacts_from(context.dispatch_id()) + { + return; + } if matches!( result, BackendTaskSuccessResult::DashPayContactInfoUpdated { .. } @@ -2493,6 +2504,119 @@ mod tests { } } + /// r4316990948: load A reads the old note and is still running when the + /// save lands and load B starts. B answers first with the saved note; A + /// answering afterwards must not put the old note back. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_stale_contacts_load_does_not_undo_a_confirmed_note() { + use crate::backend_task::dashpay::ContactData; + use crate::model::dashpay::ContactInfoUpdate; + + let (_temp_dir, app_context) = wired_test_context().await; + let identity = crate::context::test_support::user_identity_with_signing_key( + id(0x31), + Network::Testnet, + false, + ); + app_context + .insert_local_qualified_identity(&identity, &None) + .expect("seed identity"); + app_context.set_selected_identity(Some(identity.identity.id())); + let (owner, contact) = (identity.identity.id(), id(4)); + let listed = |note: Option<&str>| { + vec![ContactData { + identity_id: contact, + nickname: None, + note: note.map(Into::into), + is_hidden: false, + account_reference: 0, + username: None, + display_name: None, + avatar_url: None, + bio: None, + }] + }; + let contacts_load = |screen: &mut IdentityHubScreen| { + let AppAction::BackendTasksWithContexts(tasks, _) = + super::super::contacts::load_action(&identity, &mut screen.contacts_state) + else { + panic!("the contact loads are dispatched"); + }; + tasks + .into_iter() + .find_map(|(task, context)| { + matches!(&task, BackendTask::DashPayTask(t) + if matches!(**t, DashPayTask::LoadContacts { .. })) + .then_some(context) + }) + .expect("a contact list load") + }; + + let mut screen = IdentityHubScreen::new(&app_context); + screen.contacts_state.reconcile_owner(&identity); + screen.contacts_state.record_contacts(listed(None)); + screen.contacts_state.select_contact(&contact); + let load_a = contacts_load(&mut screen); + + *screen + .contacts_state + .detail_mut() + .note_mut(&contact) + .expect("draft") = "Bao".into(); + assert!( + screen + .contacts_state + .detail_mut() + .begin_save(owner, contact) + .is_some() + ); + let action = AppAction::BackendTask(BackendTask::DashPayTask(Box::new( + DashPayTask::UpdateContactInfo { + identity: identity.clone(), + contact_id: contact, + update: ContactInfoUpdate::note(Some("Bao".into())), + }, + ))); + screen.capture_contact_info_update(&action); + let AppAction::BackendTaskWithContext { context: write, .. } = + screen.bind_contact_info_dispatch(action) + else { + panic!("the write is sent under its own dispatch"); + }; + screen.display_backend_task_result( + &write, + BackendTaskSuccessResult::DashPayContactInfoUpdated { + identity: owner, + contact_id: contact, + }, + ); + let load_b = contacts_load(&mut screen); + + let contacts_result = |note| BackendTaskSuccessResult::DashPayContactsWithInfo { + identity: owner, + contacts: listed(note), + }; + screen.display_backend_task_result(&load_b, contacts_result(Some("Bao"))); + screen.display_backend_task_result(&load_a, contacts_result(None)); + + assert_eq!( + screen + .contacts_state + .selected_contact() + .and_then(|c| c.note.as_deref()), + Some("Bao"), + "the older load must not put the old note back" + ); + assert_eq!( + screen + .contacts_state + .detail_mut() + .note_mut(&contact) + .map(|draft| draft.clone()), + Some("Bao".into()) + ); + } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_write_succeeding_after_an_identity_switch_settles() { settle_after_an_identity_switch("success").await; diff --git a/src/ui/state/contacts_view.rs b/src/ui/state/contacts_view.rs index bb1584d1b..fcb49bb3d 100644 --- a/src/ui/state/contacts_view.rs +++ b/src/ui/state/contacts_view.rs @@ -78,6 +78,10 @@ pub struct ContactsState { owner: Option<(Network, Identifier)>, /// The selected contact and its private-note editor. detail: ContactDetailState, + /// The dispatch of the newest contact-list load. A reload re-arms without + /// cancelling, so an older load can answer after a newer one; its list is + /// stale and would undo a confirmed note. + latest_contacts_load: Option, } impl ContactsState { @@ -91,6 +95,21 @@ impl ContactsState { true } + /// Record `dispatch_id` as the newest contact-list load. + pub fn record_contacts_load(&mut self, dispatch_id: u64) { + self.latest_contacts_load = Some(dispatch_id); + } + + /// Whether a contact list from load `dispatch_id` may be shown: not when a + /// newer load was dispatched since. A list no load of this state asked for + /// carries no dispatch and is judged as before. + pub fn accepts_contacts_from(&self, dispatch_id: Option) -> bool { + match (self.latest_contacts_load, dispatch_id) { + (Some(latest), Some(dispatch_id)) => dispatch_id >= latest, + _ => true, + } + } + /// Clear cached view data while retaining guards for backend work still running. pub fn reset(&mut self) { self.load_requested = false; diff --git a/tests/kittest/identity_home.rs b/tests/kittest/identity_home.rs index d4db06758..2d720698a 100644 --- a/tests/kittest/identity_home.rs +++ b/tests/kittest/identity_home.rs @@ -808,10 +808,10 @@ fn home_contacts_follow_an_identity_selected_outside_the_hub() { &mut harness, "the newly selected identity's contact load", |action| match action { - AppAction::BackendTasks(tasks, _) => Some( + AppAction::BackendTasksWithContexts(tasks, _) => Some( tasks .iter() - .filter_map(|task| match task { + .filter_map(|(task, _)| match task { BackendTask::DashPayTask(task) => match &**task { DashPayTask::LoadContacts { identity } | DashPayTask::LoadContactRequests { identity } => { diff --git a/tests/kittest/identity_hub.rs b/tests/kittest/identity_hub.rs index 556732118..bb907c2d5 100644 --- a/tests/kittest/identity_hub.rs +++ b/tests/kittest/identity_hub.rs @@ -115,12 +115,12 @@ pub(crate) mod loads { } fn contacts_load(action: &AppAction) -> Option<()> { - let AppAction::BackendTasks(tasks, _) = action else { + let AppAction::BackendTasksWithContexts(tasks, _) = action else { return None; }; tasks .iter() - .any(|task| { + .any(|(task, _)| { matches!(task, BackendTask::DashPayTask(task) if matches!(**task, DashPayTask::LoadContacts { .. })) }) @@ -275,15 +275,17 @@ pub(crate) mod loads { step_until(&mut hub, "the first payment history load", payments_load); let load = |action: &AppAction| match action { - AppAction::BackendTasks(tasks, _) => tasks.iter().find_map(|task| match task { - BackendTask::DashPayTask(task) => match &**task { - DashPayTask::LoadContacts { identity } => { - Some(("contacts", identity.identity.id())) - } + AppAction::BackendTasksWithContexts(tasks, _) => { + tasks.iter().find_map(|(task, _)| match task { + BackendTask::DashPayTask(task) => match &**task { + DashPayTask::LoadContacts { identity } => { + Some(("contacts", identity.identity.id())) + } + _ => None, + }, _ => None, - }, - _ => None, - }), + }) + } AppAction::BackendTaskWithContext { task: BackendTask::DashPayTask(task), .. diff --git a/tests/kittest/identity_hub_contacts.rs b/tests/kittest/identity_hub_contacts.rs index dacd40c7b..978b55749 100644 --- a/tests/kittest/identity_hub_contacts.rs +++ b/tests/kittest/identity_hub_contacts.rs @@ -202,7 +202,7 @@ fn contacts_tab_load_is_for_a_populated_tab_and_goes_out_once() { ); let load = contacts::tab_load_action(&app_context, &mut state, &mut profiles); assert!( - matches!(&load, AppAction::BackendTasks(tasks, _) if tasks.len() == 2), + matches!(&load, AppAction::BackendTasksWithContexts(tasks, _) if tasks.len() == 2), "the populated tab loads its contacts and its requests, got {load:?}" ); assert!( From a2bd48827e9887f12e5495eb7220ed7a887469b7 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:40:46 +0000 Subject: [PATCH 27/73] test(identity): pass the publish outcome in the merged stale-load test Co-Authored-By: Claude Opus 5.5 --- src/ui/identity/hub_screen.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index 25f079b64..28dfb08e5 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -2321,6 +2321,7 @@ mod tests { BackendTaskSuccessResult::DashPayContactInfoUpdated { identity: owner, contact_id: contact, + published: true, }, ); let load_b = contacts_load(&mut screen); From 2839d067e839c9d0a43bdd22ff056d5e8ba7fe8e Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:47:23 +0000 Subject: [PATCH 28/73] fix(dashpay): fail a contact details save when the legacy keys cannot be read The legacy contactInfo reader treated every key failure as a missing document, so a cancelled password prompt for the legacy keys let a save replace a legacy-only nickname or hidden flag with empty values, then record the details as synced. The reader now skips only a document whose own key index cannot be derived and returns any other failure. The save stops on it; the contacts list falls back to no legacy details. The Sent and Hidden captions no longer claim that cancelling notifies the other person or that declining and cancelling hide anyone. Co-Authored-By: Claude Opus 5.5 --- src/backend_task/dashpay/contact_info.rs | 67 +++++++++++++++++++++++- src/backend_task/dashpay/contacts.rs | 42 ++++++++++----- src/ui/identity/contacts.rs | 16 +++--- src/ui/state/contacts_view.rs | 5 +- 4 files changed, 104 insertions(+), 26 deletions(-) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 55a005c08..5be10fc55 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -165,12 +165,12 @@ impl SaveOps for PlatformSaveOps<'_> { super::contacts::stored_contact_details(self.app_context, self.sdk, self.identity) .await?; let published = stored.published?.remove(&self.contact_id); + let legacy = stored.legacy?; let synced_before = self .backend .dashpay_details_synced(&owner, &self.contact_id) || super::contacts::holds_details(published.as_ref(), local.as_ref()); - let legacy = stored - .legacy + let legacy = legacy .get(&self.contact_id) .map(super::contacts::ContactData::details); Ok(super::contacts::shown_contact_details( @@ -441,6 +441,69 @@ mod tests { document } + /// The legacy details read from `documents` with keys from `derive_keys`. + async fn legacy_load( + documents: Vec, + derive_keys: D, + ) -> Result, TaskError> + where + D: FnMut(u32) -> DF, + DF: Future, Zeroizing<[u8; 32]>), TaskError>>, + { + let contract = + load_system_data_contract(SystemDataContract::Dashpay, PlatformVersion::latest()) + .expect("DashPay contract fixture"); + let query = DocumentQuery::new(contract, "contactInfo").expect("contactInfo query"); + let mut page = Some(contact_details_page(documents)); + super::super::contacts::load_contact_details( + query, + |_| ready(Ok::<_, TaskError>(page.take().unwrap_or_default())), + derive_keys, + ) + .await + } + + /// A cancelled password prompt for the legacy keys fails the read, so a + /// save does not keep a legacy-only nickname or hidden flag as empty. + #[tokio::test] + async fn a_cancelled_legacy_key_prompt_fails_the_read() { + let result = legacy_load(vec![saved_note_document(1, id(201), "n")], |_| { + ready(Err(TaskError::SecretPromptCancelled)) + }) + .await; + + assert!(matches!(result, Err(TaskError::SecretPromptCancelled))); + } + + /// A document whose own key index cannot be derived is skipped; the rest + /// still load. + #[tokio::test] + async fn an_underivable_legacy_document_is_skipped() { + let (readable, unreadable) = (id(201), id(202)); + let mut bad = saved_note_document(2, unreadable, "x"); + bad.set("derivationEncryptionKeyIndex", Value::U32(u32::MAX)); + let details = legacy_load(vec![saved_note_document(1, readable, "n"), bad], |index| { + ready(if index == u32::MAX { + Err(TaskError::ContactKeyDerivationFailed { + source: Box::new( + dash_sdk::dpp::key_wallet::bip32::ChildNumber::from_hardened_idx(index) + .expect_err("out of range"), + ), + }) + } else { + Ok((Zeroizing::new(KEY), Zeroizing::new(KEY))) + }) + }) + .await + .expect("loaded"); + + assert_eq!( + details.get(&readable).and_then(|c| c.note.as_deref()), + Some("n") + ); + assert!(!details.contains_key(&unreadable)); + } + /// The details loaded from `pages`, and whether every page was asked for /// in the order the write lookup uses. async fn load_details( diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index 69e86ba9d..fd5065bd2 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -148,7 +148,7 @@ where DF: Future, Zeroizing<[u8; 32]>), TaskError>>, { let documents = fetch_contact_info_documents(query, fetch_page).await?; - Ok(legacy_details_from(&documents, derive_keys).await) + legacy_details_from(&documents, derive_keys).await } /// Every page of the owner's `contactInfo` documents, oldest first by @@ -171,11 +171,17 @@ where } /// The details `documents` (oldest first) hold under the legacy key root; -/// a later document for a contact replaces an earlier one. +/// a later document for a contact replaces an earlier one. A document that +/// does not open is skipped. +/// +/// # Errors +/// +/// The keys could not be derived for a reason that holds for every +/// document, such as a cancelled password prompt. async fn legacy_details_from( documents: &[Document], mut derive_keys: D, -) -> HashMap +) -> Result, TaskError> where D: FnMut(u32) -> DF, DF: Future, Zeroizing<[u8; 32]>), TaskError>>, @@ -189,8 +195,11 @@ where else { continue; }; - let Ok((enc_user_id_key, private_data_key)) = derive_keys(deriv_idx).await else { - continue; + let (enc_user_id_key, private_data_key) = match derive_keys(deriv_idx).await { + Ok(keys) => keys, + // The document's own index cannot be derived. + Err(TaskError::ContactKeyDerivationFailed { .. }) => continue, + Err(error) => return Err(error), }; let Some(Value::Bytes(enc_user_id)) = props.get("encToUserId") else { continue; @@ -231,7 +240,7 @@ where ); } - contact_info_map + Ok(contact_info_map) } /// The details the owner's stored `contactInfo` documents hold. @@ -241,8 +250,8 @@ pub(super) struct StoredContactDetails { /// guess past that error; the contacts list may. pub(super) published: Result, TaskError>, /// From documents older versions of this app wrote under the legacy - /// key root, newest per contact. - pub(super) legacy: HashMap, + /// key root, newest per contact; an error as for `published`. + pub(super) legacy: Result, TaskError>, } /// Read every `contactInfo` document the owner stored, both as DIP-0015 @@ -280,10 +289,15 @@ pub(super) async fn stored_contact_details( } Err(_) => Ok(BTreeMap::new()), }; - let legacy = legacy_details_from(&documents, |derivation_index| { - derive_contact_info_keys(app_context, identity, derivation_index) - }) - .await; + // Without a wallet seed no legacy key exists, so no document opens. + let legacy = if identity.dashpay_wallet_seed_hash().is_some() { + legacy_details_from(&documents, |derivation_index| { + derive_contact_info_keys(app_context, identity, derivation_index) + }) + .await + } else { + Ok(HashMap::new()) + }; Ok(StoredContactDetails { published, legacy }) } @@ -455,6 +469,10 @@ pub async fn load_contacts( tracing::debug!(?error, "LoadContacts: published contact details not read"); BTreeMap::new() }); + let legacy = legacy.unwrap_or_else(|error| { + tracing::debug!(?error, "LoadContacts: legacy contact details not read"); + HashMap::new() + }); // Build enriched contact list with basic data let mut contact_list: Vec = contacts diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index 0aa772419..9242618b0 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -80,17 +80,15 @@ pub const UNHIDE_TOOLTIP: &str = "Show this contact in your contact list again." /// count tells the user there is something to recover. pub const SHOW_HIDDEN_LABEL: &str = "Show hidden contacts"; -/// Why a contact the user never hid by hand can still be in this section: -/// declining or cancelling a request hides that person, and a contact that is -/// later established with them stays hidden until it is unhidden here. -pub const HIDDEN_EXPLAINER: &str = "Hidden contacts are kept out of your list. Declining or cancelling a request also hides that \ - person. Unhide anyone you want back."; +/// Hidden-section caption. Only an explicit hide puts a contact here; +/// declining or cancelling a request writes no contact details. +pub const HIDDEN_EXPLAINER: &str = + "Hidden contacts are kept out of your list. Unhide anyone you want back."; /// Sent-section caption. A DashPay contact request cannot be deleted from the -/// network once sent, so the copy states plainly what Cancel really does -/// instead of promising a withdrawal the protocol cannot deliver. -pub const CANCEL_EXPLAINER: &str = "Cancelling a request hides it and tells the other person you are no longer waiting. The \ - original request stays on the network."; +/// network once sent, and Cancel publishes nothing, so the copy states plainly +/// that it only hides the request on this device. +pub const CANCEL_EXPLAINER: &str = "Cancelling a request hides it on this device only. The other person is not notified, and the original request stays on the network."; /// Below this tab width the detail pane stacks under the contact list. Home /// and Profile switch to one column at the same width. diff --git a/src/ui/state/contacts_view.rs b/src/ui/state/contacts_view.rs index fcb49bb3d..25896eedf 100644 --- a/src/ui/state/contacts_view.rs +++ b/src/ui/state/contacts_view.rs @@ -59,9 +59,8 @@ pub struct ContactsState { /// Confirmed notes override lagging reads until the network returns them. confirmed_notes: HashMap<(Identifier, Identifier), Option>, /// Established contacts flagged `display_hidden`, kept aside so the tab can - /// offer a way back. Declining or cancelling a request hides that person, - /// so without this list a contact could only be recovered from the legacy - /// DashPay screen. + /// offer a way back; without this list a hidden contact could only be + /// recovered from the legacy DashPay screen. hidden: Vec, /// Whether the hidden-contacts section is expanded. show_hidden: bool, From 964072b90f31a7ad741be9916c1530587ce09c19 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:14:32 +0000 Subject: [PATCH 29/73] fix(identity): give the hub's confirmed notes an explicit lifecycle A confirmed note overrode every reload that differed from it until one returned it, so a newer note saved on another device or by the legacy Contact Details screen could stay hidden indefinitely, and a write that finished after a network switch could change the new network's lists. `ConfirmedNote` documents the invariant the code now follows: - it is keyed by the network the write ran on, the owner and the contact; - a list from a load dispatched before the save always shows the note; - a later list shows it only while it still holds the note a lagging read can return, so any other note retires it; - another screen's successful write to the contact retires it. The hub records each write's network at dispatch, and an outcome from the network it left settles only that write's guard. Co-Authored-By: Claude Opus 5.5 --- src/ui/identity/contacts.rs | 4 +- src/ui/identity/hub_screen.rs | 356 ++++++++++++++++++++++++++++------ src/ui/state/contacts_view.rs | 130 +++++++++---- 3 files changed, 394 insertions(+), 96 deletions(-) diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index e3c2ab915..2614597f5 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -1518,7 +1518,7 @@ mod tests { "the note save must wait for the unhide" ); - assert!(state.finish_contact_info_write(&id(1), &id(5))); + assert!(state.finish_contact_info_write(Network::Testnet, &id(1), &id(5))); assert_eq!( state.selected_contact().and_then(|c| c.note.as_deref()), None, @@ -1538,7 +1538,7 @@ mod tests { dispatch_unhide(&mut state, &identity, &hidden_bao()), AppAction::None ); - state.release_contact_info_write(&id(1), &id(5)); + state.release_contact_info_write(Network::Testnet, &id(1), &id(5)); assert_ne!( dispatch_unhide(&mut state, &identity, &hidden_bao()), AppAction::None diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index bd98db733..d7f7fd383 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -23,6 +23,7 @@ use crate::ui::components::styled::island_central_panel; use crate::ui::components::top_panel::add_top_panel_with_breadcrumb; use crate::ui::state::hub_selection::{HubSelection, HubView, effective_view}; use crate::ui::{MessageType, RootScreenType, ScreenLike, ScreenType}; +use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::platform::Identifier; use eframe::egui::{self, Context}; @@ -101,10 +102,12 @@ pub struct IdentityHubScreen { selection: HubSelection, contact_info_overwrite_dialog: Option<(ConfirmationDialog, ContactInfoTaskKey)>, pending_contact_info_tasks: HashMap, - /// The dispatch each direct contact details write was sent under. Another - /// screen can write the same contact while the hub's write waits behind - /// it, so only an outcome for this dispatch settles the hub's write. - contact_info_dispatches: HashMap, + /// The dispatch each direct contact details write was sent under, and the + /// network it runs on. Another screen can write the same contact while the + /// hub's write waits behind it, so only an outcome for this dispatch + /// settles the hub's write; one arriving after a network switch changes + /// nothing the new network shows. + contact_info_dispatches: HashMap, /// Set by `display_backend_task_error` when the error belongs to another /// screen's write, so the context-free handler that follows it ignores it. foreign_contact_info_error: bool, @@ -207,10 +210,26 @@ impl IdentityHubScreen { identity_id, contact_id, }; - self.contact_info_dispatches.insert(key, dispatch_id); + self.contact_info_dispatches + .insert(key, (dispatch_id, self.app_context.network)); AppAction::BackendTaskWithContext { task, context } } + /// The network the hub's write to `contact_id` runs on: the one recorded + /// at dispatch, else the network on screen. + fn contact_info_write_network( + &self, + identity_id: &Identifier, + contact_id: &Identifier, + ) -> Network { + self.contact_info_dispatches + .get(&ContactInfoTaskKey::Direct { + identity_id: *identity_id, + contact_id: *contact_id, + }) + .map_or(self.app_context.network, |(_, network)| *network) + } + /// Retire a settled or abandoned write's records together. fn forget_contact_info_task(&mut self, key: &ContactInfoTaskKey) -> Option { self.contact_info_dispatches.remove(key); @@ -228,7 +247,7 @@ impl IdentityHubScreen { contact_id, }) }) - .is_some_and(|dispatch_id| context.dispatch_id() == Some(*dispatch_id)) + .is_some_and(|(dispatch_id, _)| context.dispatch_id() == Some(*dispatch_id)) } /// Remember the identity an unload was dispatched for. @@ -251,6 +270,7 @@ impl IdentityHubScreen { fn reset_contacts_for_identity_change(&mut self) { release_guards_for_abandoned_confirmations( &mut self.contacts_state, + self.app_context.network, self.pending_contact_info_confirmations.iter().chain( self.contact_info_overwrite_dialog .iter() @@ -468,10 +488,19 @@ impl IdentityHubScreen { self.queue_contact_info_confirmation(key); return true; } + if let TaskError::DashPayContactInfoActionFailed { + identity_id, + contact_id, + .. + } = error + { + let network = self.contact_info_write_network(identity_id, contact_id); + self.contacts_state + .release_contact_info_write(network, identity_id, contact_id); + } if let Some(key) = contact_info_error_key(error) { self.forget_contact_info_task(&key); } - release_contact_info_write_for_error(&mut self.contacts_state, error); false } @@ -768,7 +797,11 @@ impl ScreenLike for IdentityHubScreen { self.contact_info_overwrite_dialog = None; } Some(ConfirmationStatus::Canceled) => { - release_guards_for_abandoned_confirmations(&mut self.contacts_state, [&key]); + release_guards_for_abandoned_confirmations( + &mut self.contacts_state, + self.app_context.network, + [&key], + ); self.forget_contact_info_task(&key); self.contacts_state.invalidate(); self.contact_info_overwrite_dialog = None; @@ -850,21 +883,29 @@ impl ScreenLike for IdentityHubScreen { } // A reload re-arms without cancelling the load before it, so lists // can answer out of order; an older one would undo a confirmed note. - if matches!( - result, - BackendTaskSuccessResult::DashPayContactsWithInfo { .. } - ) && !self - .contacts_state - .accepts_contacts_from(context.dispatch_id()) - { + if let BackendTaskSuccessResult::DashPayContactsWithInfo { identity, contacts } = &result { + if self + .contacts_state + .accepts_contacts_from(context.dispatch_id()) + && self.result_is_for_selected_identity(identity) + { + self.contacts_state + .record_loaded_contacts(contacts.clone(), context.dispatch_id()); + } return; } - if matches!( - result, - BackendTaskSuccessResult::DashPayContactInfoUpdated { .. } - ) && !self.is_own_contact_info_dispatch(context) + if let BackendTaskSuccessResult::DashPayContactInfoUpdated { + identity, + contact_id, + } = &result + && !self.is_own_contact_info_dispatch(context) { - // Another screen's write: it changed the details shown, nothing more. + // Another screen's write: newer than any note the hub saved. + self.contacts_state.forget_confirmed_note( + self.app_context.network, + identity, + contact_id, + ); self.contacts_state.invalidate(); return; } @@ -915,13 +956,6 @@ impl ScreenLike for IdentityHubScreen { .record_requests(incoming.clone(), outgoing.clone()); } } - // The established-contact list behind the Contacts tab's active - // section and its search box. - BackendTaskSuccessResult::DashPayContactsWithInfo { identity, contacts } => { - if self.result_is_for_selected_identity(identity) { - self.contacts_state.record_contacts(contacts.clone()); - } - } // A confirmed contactInfo write — an unhide or a private-note // save. Re-arm the load so the authoritative list replaces the // optimistic local edit. @@ -933,8 +967,9 @@ impl ScreenLike for IdentityHubScreen { identity_id: *identity, contact_id: *contact_id, }; + let network = self.contact_info_write_network(identity, contact_id); self.contacts_state - .finish_contact_info_write(identity, contact_id); + .finish_contact_info_write(network, identity, contact_id); if let Some(task) = self.forget_contact_info_task(&key) { self.contacts_state.invalidate(); MessageBanner::set_global( @@ -996,12 +1031,13 @@ impl ScreenLike for IdentityHubScreen { && !matches!(error, TaskError::DashPayContactInfoActionFailed { .. }) && let Some((identity_id, contact_id)) = context.dashpay_contact_info_target() { + let network = self.contact_info_write_network(&identity_id, &contact_id); self.forget_contact_info_task(&ContactInfoTaskKey::Direct { identity_id, contact_id, }); self.contacts_state - .release_contact_info_write(&identity_id, &contact_id); + .release_contact_info_write(network, &identity_id, &contact_id); } if matches!(error, TaskError::MasternodeListNotReady { .. }) { self.profile_cache.record_error_while_syncing(context); @@ -1049,25 +1085,11 @@ fn release_request_guard_for_error(state: &mut super::contacts::ContactsState, e } } -/// Release the write guard a failed direct contactInfo write names. -fn release_contact_info_write_for_error( - state: &mut super::contacts::ContactsState, - error: &TaskError, -) { - if let TaskError::DashPayContactInfoActionFailed { - identity_id, - contact_id, - .. - } = error - { - state.release_contact_info_write(identity_id, contact_id); - } -} - /// Release the request and note-save guards of confirmations that will never /// be answered: no task is left running for them. fn release_guards_for_abandoned_confirmations<'a>( state: &mut super::contacts::ContactsState, + network: Network, keys: impl IntoIterator, ) { for key in keys { @@ -1076,7 +1098,7 @@ fn release_guards_for_abandoned_confirmations<'a>( ContactInfoTaskKey::Direct { identity_id, contact_id, - } => state.release_contact_info_write(identity_id, contact_id), + } => state.release_contact_info_write(network, identity_id, contact_id), } } } @@ -1325,7 +1347,6 @@ mod tests { use crate::model::qualified_identity::{IdentityStatus, IdentityType, QualifiedIdentity}; use crate::ui::state::contacts_view::ContactsState; use crate::utils::egui_mpsc::SenderAsync; - use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::identity::Identity; use dash_sdk::dpp::version::PlatformVersion; use std::collections::BTreeMap; @@ -2287,7 +2308,7 @@ mod tests { }, ]; - release_guards_for_abandoned_confirmations(&mut state, &keys); + release_guards_for_abandoned_confirmations(&mut state, Network::Testnet, &keys); assert!(state.is_in_flight(&id(1))); assert!( @@ -2372,6 +2393,7 @@ mod tests { release_guards_for_abandoned_confirmations( &mut state, + Network::Testnet, &[ContactInfoTaskKey::Direct { identity_id: id(3), contact_id: id(4), @@ -2382,9 +2404,11 @@ mod tests { assert!(state.is_in_flight(&id(2)), "unrelated request guards stay"); } - #[test] - fn a_failed_note_save_releases_only_its_own_guard() { - let mut state = ContactsState::default(); + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_failed_note_save_releases_only_its_own_guard() { + let (_temp_dir, app_context) = wired_test_context().await; + let mut screen = IdentityHubScreen::new(&app_context); + let state = &mut screen.contacts_state; state.record_contacts(vec![crate::backend_task::dashpay::ContactData { identity_id: id(4), nickname: None, @@ -2400,18 +2424,15 @@ mod tests { *state.detail_mut().note_mut(&id(4)).expect("draft") = "Bao".into(); assert!(state.detail_mut().begin_save(id(3), id(4)).is_some()); - release_contact_info_write_for_error(&mut state, &TaskError::WalletLocked); - assert!(state.detail().is_writing(&id(3), &id(4))); + screen.handle_contact_info_error(&TaskError::WalletLocked); + assert!(screen.contacts_state.detail().is_writing(&id(3), &id(4))); - release_contact_info_write_for_error( - &mut state, - &TaskError::DashPayContactInfoActionFailed { - identity_id: id(3), - contact_id: id(4), - source: Box::new(TaskError::WalletLocked), - }, - ); - assert!(!state.detail().is_writing(&id(3), &id(4))); + screen.handle_contact_info_error(&TaskError::DashPayContactInfoActionFailed { + identity_id: id(3), + contact_id: id(4), + source: Box::new(TaskError::WalletLocked), + }); + assert!(!screen.contacts_state.detail().is_writing(&id(3), &id(4))); } /// A note save for identity A that is still running when the user switches @@ -2617,6 +2638,219 @@ mod tests { ); } + /// One event in the life of a confirmed note; see `ConfirmedNote`. + #[derive(Debug, Clone, Copy)] + enum NoteEvent { + /// The hub's write succeeds. + Saved, + /// The hub's write fails. + Failed, + /// The hub's write succeeds after the hub moved to another network. + SavedOnTheNetworkLeft, + /// The legacy Contact Details screen saves the same contact. + SavedElsewhere, + /// A list from the load dispatched before the save. + ListFromBefore(&'static str), + /// A list from a load dispatched after the save. + ListFromAfter(&'static str), + IdentitySwitch, + /// The lists now belong to the same owner on another network. + NetworkSwitch, + } + + /// Every event that creates, keeps or retires a confirmed note, with the + /// note the hub shows after it. The contact's note was "Old"; the hub + /// saves "Mine". + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn the_confirmed_note_lifecycle() { + use NoteEvent::*; + let cases: &[(&str, &[NoteEvent], &str)] = &[ + ( + "a list from before the save", + &[Saved, ListFromBefore("Old")], + "Mine", + ), + ( + "a read lagging behind the save", + &[Saved, ListFromAfter("Old")], + "Mine", + ), + ( + "the saved note read back retires it", + &[Saved, ListFromAfter("Mine"), ListFromAfter("Old")], + "Old", + ), + ( + "a newer note saved elsewhere", + &[Saved, ListFromAfter("Theirs")], + "Theirs", + ), + ( + "another screen's save retires it", + &[Saved, SavedElsewhere, ListFromAfter("Old")], + "Old", + ), + ( + "a failed save confirms nothing", + &[Failed, ListFromAfter("Old")], + "Old", + ), + ( + "an identity switch keeps it", + &[Saved, IdentitySwitch, ListFromBefore("Old")], + "Mine", + ), + ( + "another network's lists are not overridden", + &[Saved, NetworkSwitch, ListFromBefore("Old")], + "Old", + ), + ( + "a save from the network left changes nothing here", + &[SavedOnTheNetworkLeft], + "Old", + ), + ]; + let mut wrong = Vec::new(); + for (name, events, shown) in cases { + let got = confirmed_note_after(events).await; + if got.as_deref() != Some(*shown) { + wrong.push(format!("{name}: shows {got:?}, expected {shown:?}")); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); + } + + /// The note the hub shows for the contact after `events`, asserting that + /// the hub's write was settled. + async fn confirmed_note_after(events: &[NoteEvent]) -> Option { + use crate::backend_task::dashpay::ContactData; + use crate::model::dashpay::ContactInfoUpdate; + + let (_temp_dir, app_context) = wired_test_context().await; + let identity = crate::context::test_support::user_identity_with_signing_key( + id(0x31), + Network::Testnet, + false, + ); + app_context + .insert_local_qualified_identity(&identity, &None) + .expect("seed identity"); + app_context.set_selected_identity(Some(identity.identity.id())); + let (owner, contact) = (identity.identity.id(), id(4)); + let list = |note: &str| BackendTaskSuccessResult::DashPayContactsWithInfo { + identity: owner, + contacts: vec![ContactData { + identity_id: contact, + nickname: None, + note: Some(note.into()), + is_hidden: false, + account_reference: 0, + username: None, + display_name: None, + avatar_url: None, + bio: None, + }], + }; + let contacts_load = |screen: &mut IdentityHubScreen| { + screen.contacts_state.invalidate(); + let AppAction::BackendTasksWithContexts(tasks, _) = + super::super::contacts::load_action(&identity, &mut screen.contacts_state) + else { + panic!("the contact loads are dispatched"); + }; + tasks + .into_iter() + .find_map(|(task, context)| { + matches!(&task, BackendTask::DashPayTask(t) + if matches!(**t, DashPayTask::LoadContacts { .. })) + .then_some(context) + }) + .expect("a contact list load") + }; + + let mut screen = IdentityHubScreen::new(&app_context); + screen.contacts_state.reconcile_owner(&identity); + let before = contacts_load(&mut screen); + screen.display_backend_task_result(&before, list("Old")); + screen.contacts_state.select_contact(&contact); + *screen + .contacts_state + .detail_mut() + .note_mut(&contact) + .expect("draft") = "Mine".into(); + assert!( + screen + .contacts_state + .detail_mut() + .begin_save(owner, contact) + .is_some() + ); + let task = BackendTask::DashPayTask(Box::new(DashPayTask::UpdateContactInfo { + identity: identity.clone(), + contact_id: contact, + update: ContactInfoUpdate::note(Some("Mine".into())), + })); + let action = AppAction::BackendTask(task.clone()); + screen.capture_contact_info_update(&action); + let AppAction::BackendTaskWithContext { context: write, .. } = + screen.bind_contact_info_dispatch(action) + else { + panic!("the write is sent under its own dispatch"); + }; + let saved = BackendTaskSuccessResult::DashPayContactInfoUpdated { + identity: owner, + contact_id: contact, + }; + + for event in events { + match *event { + NoteEvent::Saved => screen.display_backend_task_result(&write, saved.clone()), + NoteEvent::Failed => { + let error = TaskError::DashPayContactInfoActionFailed { + identity_id: owner, + contact_id: contact, + source: Box::new(TaskError::WalletLocked), + }; + screen.display_backend_task_error(&write, &error); + screen.display_task_error(&error); + } + NoteEvent::SavedOnTheNetworkLeft => { + for record in screen.contact_info_dispatches.values_mut() { + record.1 = Network::Mainnet; + } + screen.display_backend_task_result(&write, saved.clone()); + } + NoteEvent::SavedElsewhere => screen.display_backend_task_result( + &BackendTaskContext::for_dispatch(&task), + saved.clone(), + ), + NoteEvent::ListFromBefore(note) => { + screen.display_backend_task_result(&before, list(note)) + } + NoteEvent::ListFromAfter(note) => { + let after = contacts_load(&mut screen); + screen.display_backend_task_result(&after, list(note)); + } + NoteEvent::IdentitySwitch => screen.reset_contacts_for_identity_change(), + NoteEvent::NetworkSwitch => { + let mut elsewhere = identity.clone(); + elsewhere.network = Network::Mainnet; + screen.contacts_state.reconcile_owner(&elsewhere); + } + } + } + assert!( + !screen.contacts_state.detail().is_writing(&owner, &contact), + "the write is settled" + ); + screen + .contacts_state + .matching_contacts() + .find(|c| c.identity_id == contact) + .and_then(|c| c.note.clone()) + } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_write_succeeding_after_an_identity_switch_settles() { settle_after_an_identity_switch("success").await; diff --git a/src/ui/state/contacts_view.rs b/src/ui/state/contacts_view.rs index fcb49bb3d..84230e83f 100644 --- a/src/ui/state/contacts_view.rs +++ b/src/ui/state/contacts_view.rs @@ -56,8 +56,8 @@ pub struct ContactsState { /// Whether `contacts` holds a loaded list, not the empty one before the /// first load lands. contacts_known: bool, - /// Confirmed notes override lagging reads until the network returns them. - confirmed_notes: HashMap<(Identifier, Identifier), Option>, + /// Notes the hub saved, shown over lists that may not hold them yet. + confirmed_notes: HashMap<(Network, Identifier, Identifier), ConfirmedNote>, /// Established contacts flagged `display_hidden`, kept aside so the tab can /// offer a way back. Declining or cancelling a request hides that person, /// so without this list a contact could only be recovered from the legacy @@ -84,6 +84,29 @@ pub struct ContactsState { latest_contacts_load: Option, } +/// A note the hub saved, shown over contact lists that may not hold it yet. +/// +/// Invariant: +/// - Created only by a successful note write the hub itself dispatched, keyed +/// by the network the write ran on, the owner, and the contact. It applies +/// only to lists of that owner on that network. +/// - `after_load` is the newest contact-list load dispatched before the save +/// was confirmed. A list from that load or an earlier one, or from no load, +/// predates the save: it shows `note` whatever it holds. +/// - A list from a later load shows `note` only while it still holds +/// `lagging`, the note a read behind the save can return. +/// - Retired by: a list holding `note`; a later list holding anything other +/// than `lagging`; another screen's successful write to the contact; the +/// hub's next confirmed save of it (replaced). +/// - Untouched by: the hub's failed writes, identity switches, and network +/// switches (another network's lists never match the key). +#[derive(Debug, Clone)] +struct ConfirmedNote { + note: Option, + lagging: Option>, + after_load: u64, +} + impl ContactsState { /// Claim the one-shot load slot. Returns `true` exactly once per tab entry /// — the caller dispatches the backend loads on `true` and skips otherwise. @@ -211,16 +234,30 @@ impl ContactsState { /// out of the active list — that is what "hidden" promises — but remain /// reachable through [`ContactsState::hidden_contacts`]. The selected /// contact's note draft follows the reloaded note. - pub fn record_contacts(&mut self, mut contacts: Vec) { - if let Some(owner) = self.owner_id() { + pub fn record_contacts(&mut self, contacts: Vec) { + self.record_loaded_contacts(contacts, None); + } + + /// [`Self::record_contacts`] for the list load `dispatch_id` returned; see + /// [`ConfirmedNote`] for how it meets the notes the hub saved. + pub fn record_loaded_contacts( + &mut self, + mut contacts: Vec, + dispatch_id: Option, + ) { + if let Some((network, owner)) = self.owner { for contact in &mut contacts { - let key = (owner, contact.identity_id); - if let Some(confirmed) = self.confirmed_notes.get(&key) { - if &contact.note == confirmed { - self.confirmed_notes.remove(&key); - } else { - contact.note.clone_from(confirmed); - } + let key = (network, owner, contact.identity_id); + let Some(confirmed) = self.confirmed_notes.get(&key) else { + continue; + }; + let from_before = dispatch_id.is_none_or(|id| id <= confirmed.after_load); + if contact.note != confirmed.note + && (from_before || confirmed.lagging.as_ref() == Some(&contact.note)) + { + contact.note.clone_from(&confirmed.note); + } else { + self.confirmed_notes.remove(&key); } } } @@ -360,40 +397,67 @@ impl ContactsState { &mut self.detail } - /// Settle a confirmed contact details write. Returns whether one was - /// running. After a note save the listed contact shows the stored note - /// right away when the lists belong to `owner`, without waiting for the - /// reload. + /// Settle a confirmed contact details write `owner` ran on `network`. + /// Returns whether one was running. After a note save the listed contact + /// shows the stored note right away when the lists belong to that owner on + /// that network, without waiting for the reload; see [`ConfirmedNote`]. pub fn finish_contact_info_write( &mut self, + network: Network, owner: &Identifier, contact_id: &Identifier, ) -> bool { let Some(write) = self.detail.finish_write(owner, contact_id) else { return false; }; - if let PendingWrite::Note(note) = &write { - self.confirmed_notes - .insert((*owner, *contact_id), note.clone()); - } - if let PendingWrite::Note(note) = write - && self.owner_id() == Some(*owner) - && let Some(contact) = self - .contacts + let PendingWrite::Note(note) = write else { + return true; + }; + let listed = if self.owner == Some((network, *owner)) { + self.contacts .iter_mut() .chain(self.hidden.iter_mut()) .find(|c| c.identity_id == *contact_id) - { + } else { + None + }; + let lagging = listed.as_ref().map(|contact| contact.note.clone()); + self.confirmed_notes.insert( + (network, *owner, *contact_id), + ConfirmedNote { + note: note.clone(), + lagging, + after_load: self.latest_contacts_load.unwrap_or_default(), + }, + ); + if let Some(contact) = listed { contact.note = note; self.detail.sync(contact); } true } - /// Release a failed or abandoned write, rolling back an optimistic unhide. - pub fn release_contact_info_write(&mut self, owner: &Identifier, contact_id: &Identifier) { + /// Another screen saved the contact's details after the hub did, so the + /// hub's confirmed note is no longer the newest. + pub fn forget_confirmed_note( + &mut self, + network: Network, + owner: &Identifier, + contact_id: &Identifier, + ) { + self.confirmed_notes.remove(&(network, *owner, *contact_id)); + } + + /// Release a failed or abandoned write `owner` ran on `network`, rolling + /// back an optimistic unhide in that owner's lists on that network. + pub fn release_contact_info_write( + &mut self, + network: Network, + owner: &Identifier, + contact_id: &Identifier, + ) { if self.detail.finish_write(owner, contact_id) == Some(PendingWrite::Visibility) - && self.owner_id() == Some(*owner) + && self.owner == Some((network, *owner)) { if let Some(pos) = self .contacts @@ -582,7 +646,7 @@ mod tests { *state.detail_mut().note_mut(&id(7)).expect("draft") = "Met at the meetup".into(); assert!(state.detail_mut().begin_save(id(1), id(7)).is_some()); - assert!(state.finish_contact_info_write(&id(1), &id(7))); + assert!(state.finish_contact_info_write(Network::Testnet, &id(1), &id(7))); assert_eq!( state.selected_contact().and_then(|c| c.note.as_deref()), @@ -590,7 +654,7 @@ mod tests { ); assert!(!state.detail().is_dirty(&id(7))); assert!( - !state.finish_contact_info_write(&id(1), &id(7)), + !state.finish_contact_info_write(Network::Testnet, &id(1), &id(7)), "a save settles only once" ); } @@ -607,7 +671,7 @@ mod tests { state.select_contact(&id(7)); *state.detail_mut().note_mut(&id(7)).unwrap() = note.unwrap_or_default().into(); assert!(state.detail_mut().begin_save(id(1), id(7)).is_some()); - assert!(state.finish_contact_info_write(&id(1), &id(7))); + assert!(state.finish_contact_info_write(Network::Testnet, &id(1), &id(7))); state.reset(); state.record_contacts(vec![stale.clone()]); state.select_contact(&id(7)); @@ -636,7 +700,7 @@ mod tests { *state.detail_mut().note_mut(&id(7)).expect("draft") = "Theirs".into(); assert!(state.detail_mut().begin_save(id(2), id(7)).is_some()); - assert!(state.finish_contact_info_write(&id(2), &id(7))); + assert!(state.finish_contact_info_write(Network::Testnet, &id(2), &id(7))); assert_eq!( state.selected_contact().and_then(|c| c.note.as_deref()), @@ -766,13 +830,13 @@ mod tests { assert!(state.detail_mut().begin_visibility_write(id(1), id(8))); state.unhide_contact(&id(8)); state.select_contact(&id(8)); - state.release_contact_info_write(&id(2), &id(8)); + state.release_contact_info_write(Network::Testnet, &id(2), &id(8)); assert_eq!( state.contacts_len(), 1, "another owner's failure cannot move this row" ); - state.release_contact_info_write(&id(1), &id(8)); + state.release_contact_info_write(Network::Testnet, &id(1), &id(8)); assert_eq!(state.contacts_len(), 0); assert_eq!(state.hidden_contacts().len(), 1); assert!(state.hidden_contacts()[0].is_hidden); From 00f56391eabebdd29bccb1d52cb41700fbbb1a0b Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:28:25 +0000 Subject: [PATCH 30/73] fix(dashpay): let published notes win over saves kept on this device A save kept on this device (deferred until two contacts) became a confirmed note that overrode every later list until one returned it. Platform never echoes a deferred note, so a newer note published from another device stayed hidden. No read lags behind a save kept on this device, so a list loaded after it now shows whatever it holds, while lists loaded before it still show the saved note. The details-synced marker is now read for presence only, and a failed read is an error rather than absence. The save stops on it instead of letting legacy details stand in for ones the user cleared; the contacts list falls back on its own. Co-Authored-By: Claude Opus 5.5 --- src/backend_task/dashpay/contact_info.rs | 2 +- src/backend_task/dashpay/contacts.rs | 7 ++- src/backend_task/error.rs | 8 +++ src/ui/identity/contacts.rs | 2 +- src/ui/identity/hub_screen.rs | 22 +++++++- src/ui/state/contacts_view.rs | 23 +++++--- src/wallet_backend/dashpay.rs | 69 +++++++++++++++++++++++- 7 files changed, 119 insertions(+), 14 deletions(-) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 5be10fc55..508bbd3de 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -168,7 +168,7 @@ impl SaveOps for PlatformSaveOps<'_> { let legacy = stored.legacy?; let synced_before = self .backend - .dashpay_details_synced(&owner, &self.contact_id) + .dashpay_details_synced(&owner, &self.contact_id)? || super::contacts::holds_details(published.as_ref(), local.as_ref()); let legacy = legacy .get(&self.contact_id) diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index fd5065bd2..bf8e77ad1 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -482,7 +482,12 @@ pub async fn load_contacts( let synced = synced.remove(&contact_id); let published = published.remove(&contact_id); let synced_before = backend.as_ref().is_some_and(|backend| { - let synced_before = backend.dashpay_details_synced(&identity_id, &contact_id); + let synced_before = backend + .dashpay_details_synced(&identity_id, &contact_id) + .unwrap_or_else(|error| { + tracing::debug!(?error, "LoadContacts: synced record not read"); + false + }); if !synced_before && holds_details(published.as_ref(), synced.as_ref()) && let Err(error) = diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 70b888a26..22213c7da 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -1352,6 +1352,14 @@ pub enum TaskError { source: crate::wallet_backend::KvAdapterError, }, + /// The record of which contact details this device already holds could + /// not be read, so a save cannot tell which stored details to keep. + #[error("Could not read your contact details saved on this device. Try saving again in a moment.")] + ContactDetailsStateRead { + #[source] + source: crate::wallet_backend::KvAdapterError, + }, + /// A private contact note exceeds the application's byte limit. #[error("This note is too long. Shorten it to save it.")] DashPayContactNoteTooLong { diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index dd436972b..9b904137e 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -1516,7 +1516,7 @@ mod tests { "the note save must wait for the unhide" ); - assert!(state.finish_contact_info_write(Network::Testnet, &id(1), &id(5))); + assert!(state.finish_contact_info_write(Network::Testnet, &id(1), &id(5), true)); assert_eq!( state.selected_contact().and_then(|c| c.note.as_deref()), None, diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index 80a000a0c..6eb7a01f0 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -875,7 +875,7 @@ impl ScreenLike for IdentityHubScreen { }; let network = self.contact_info_write_network(identity, contact_id); self.contacts_state - .finish_contact_info_write(network, identity, contact_id); + .finish_contact_info_write(network, identity, contact_id, *published); if let Some(task) = self.forget_contact_info_task(&key) { self.contacts_state.invalidate(); let (message, kind) = if *published { @@ -2371,6 +2371,8 @@ mod tests { enum NoteEvent { /// The hub's write succeeds. Saved, + /// The hub's write succeeds and is kept on this device only. + SavedOnThisDevice, /// The hub's write fails. Failed, /// The hub's write succeeds after the hub moved to another network. @@ -2398,6 +2400,16 @@ mod tests { &[Saved, ListFromBefore("Old")], "Mine", ), + ( + "a list from before a save kept on this device", + &[SavedOnThisDevice, ListFromBefore("Old")], + "Mine", + ), + ( + "a published note wins over a save kept on this device", + &[SavedOnThisDevice, ListFromAfter("Old")], + "Old", + ), ( "a read lagging behind the save", &[Saved, ListFromAfter("Old")], @@ -2535,6 +2547,14 @@ mod tests { for event in events { match *event { NoteEvent::Saved => screen.display_backend_task_result(&write, saved.clone()), + NoteEvent::SavedOnThisDevice => screen.display_backend_task_result( + &write, + BackendTaskSuccessResult::DashPayContactInfoUpdated { + identity: owner, + contact_id: contact, + published: false, + }, + ), NoteEvent::Failed => { let error = TaskError::DashPayContactInfoActionFailed { identity_id: owner, diff --git a/src/ui/state/contacts_view.rs b/src/ui/state/contacts_view.rs index ce9e89706..ab3ab1760 100644 --- a/src/ui/state/contacts_view.rs +++ b/src/ui/state/contacts_view.rs @@ -93,7 +93,9 @@ pub struct ContactsState { /// was confirmed. A list from that load or an earlier one, or from no load, /// predates the save: it shows `note` whatever it holds. /// - A list from a later load shows `note` only while it still holds -/// `lagging`, the note a read behind the save can return. +/// `lagging`, the note a read behind the save can return. A save kept on +/// this device has none: a later list already reflects it, so a different +/// note there is a published one, which wins. /// - Retired by: a list holding `note`; a later list holding anything other /// than `lagging`; another screen's successful write to the contact; the /// hub's next confirmed save of it (replaced). @@ -396,8 +398,9 @@ impl ContactsState { &mut self.detail } - /// Settle a confirmed contact details write `owner` ran on `network`. - /// Returns whether one was running. After a note save the listed contact + /// Settle a confirmed contact details write `owner` ran on `network`; + /// `published` when it reached Platform rather than staying on this + /// device. Returns whether one was running. After a note save the listed contact /// shows the stored note right away when the lists belong to that owner on /// that network, without waiting for the reload; see [`ConfirmedNote`]. pub fn finish_contact_info_write( @@ -405,6 +408,7 @@ impl ContactsState { network: Network, owner: &Identifier, contact_id: &Identifier, + published: bool, ) -> bool { let Some(write) = self.detail.finish_write(owner, contact_id) else { return false; @@ -420,7 +424,10 @@ impl ContactsState { } else { None }; - let lagging = listed.as_ref().map(|contact| contact.note.clone()); + let lagging = listed + .as_ref() + .filter(|_| published) + .map(|contact| contact.note.clone()); self.confirmed_notes.insert( (network, *owner, *contact_id), ConfirmedNote { @@ -645,7 +652,7 @@ mod tests { *state.detail_mut().note_mut(&id(7)).expect("draft") = "Met at the meetup".into(); assert!(state.detail_mut().begin_save(id(1), id(7)).is_some()); - assert!(state.finish_contact_info_write(Network::Testnet, &id(1), &id(7))); + assert!(state.finish_contact_info_write(Network::Testnet, &id(1), &id(7), true)); assert_eq!( state.selected_contact().and_then(|c| c.note.as_deref()), @@ -653,7 +660,7 @@ mod tests { ); assert!(!state.detail().is_dirty(&id(7))); assert!( - !state.finish_contact_info_write(Network::Testnet, &id(1), &id(7)), + !state.finish_contact_info_write(Network::Testnet, &id(1), &id(7), true), "a save settles only once" ); } @@ -670,7 +677,7 @@ mod tests { state.select_contact(&id(7)); *state.detail_mut().note_mut(&id(7)).unwrap() = note.unwrap_or_default().into(); assert!(state.detail_mut().begin_save(id(1), id(7)).is_some()); - assert!(state.finish_contact_info_write(Network::Testnet, &id(1), &id(7))); + assert!(state.finish_contact_info_write(Network::Testnet, &id(1), &id(7), true)); state.reset(); state.record_contacts(vec![stale.clone()]); state.select_contact(&id(7)); @@ -699,7 +706,7 @@ mod tests { *state.detail_mut().note_mut(&id(7)).expect("draft") = "Theirs".into(); assert!(state.detail_mut().begin_save(id(2), id(7)).is_some()); - assert!(state.finish_contact_info_write(Network::Testnet, &id(2), &id(7))); + assert!(state.finish_contact_info_write(Network::Testnet, &id(2), &id(7), true)); assert_eq!( state.selected_contact().and_then(|c| c.note.as_deref()), diff --git a/src/wallet_backend/dashpay.rs b/src/wallet_backend/dashpay.rs index 5ca6797cc..7c0dd5797 100644 --- a/src/wallet_backend/dashpay.rs +++ b/src/wallet_backend/dashpay.rs @@ -924,6 +924,21 @@ fn kv_contains(kv: &DetKv, owner: &Identifier, prefix: &str, counterparty: &Iden ) } +/// Whether `owner`'s marker for `counterparty` exists, whatever its value +/// encodes. Unlike [`kv_contains`], a failed read is an error, not absence. +fn kv_marker_present( + kv: &DetKv, + owner: &Identifier, + prefix: &str, + counterparty: &Identifier, +) -> Result { + let owner_buf = owner.to_buffer(); + kv.contains( + DetScope::Identity(&owner_buf), + &sidecar_key(prefix, counterparty), + ) +} + fn kv_timestamps(kv: &DetKv, id: &Identifier) -> (i64, i64) { let key = sidecar_key(KV_PREFIX_TIMESTAMPS, id); kv_get_or_default(kv, DetScope::Global, &key, "dashpay_contact_timestamps") @@ -1311,12 +1326,18 @@ impl WalletBackend { } /// Whether platform-wallet holds `owner`'s details for `contact_id`. + /// + /// # Errors + /// + /// The marker could not be read; a save must not take that for absence, + /// or legacy details would stand in for ones the user cleared. pub(crate) fn dashpay_details_synced( &self, owner: &Identifier, contact_id: &Identifier, - ) -> bool { - kv_contains(&self.kv(), owner, KV_PREFIX_DETAILS_SYNCED, contact_id) + ) -> Result { + kv_marker_present(&self.kv(), owner, KV_PREFIX_DETAILS_SYNCED, contact_id) + .map_err(|source| TaskError::ContactDetailsStateRead { source }) } pub(crate) async fn dashpay_lock_contact_request_action( @@ -2640,6 +2661,50 @@ mod tests { ); } + /// PRRT_kwDOM8GK3c6vZ6qO: the synced marker is read for presence only, so + /// a value in an unknown encoding still counts; a failed read is an error. + #[test] + fn a_marker_read_tells_failure_from_absence() { + use platform_wallet_storage::{KvError, KvStore, ObjectId}; + + let store = Arc::new(crate::wallet_backend::kv_test_support::InMemoryKv::default()); + let kv = DetKv::from_store(store.clone()); + let (owner, contact) = (id_from_byte(1), id_from_byte(2)); + assert!(!kv_marker_present(&kv, &owner, KV_PREFIX_DETAILS_SYNCED, &contact).unwrap()); + store + .put( + &ObjectId::Identity(owner.to_buffer()), + &sidecar_key(KV_PREFIX_DETAILS_SYNCED, &contact), + &[crate::wallet_backend::kv::SCHEMA_VERSION.wrapping_add(1), 0], + ) + .unwrap(); + assert!( + kv_marker_present(&kv, &owner, KV_PREFIX_DETAILS_SYNCED, &contact).unwrap(), + "a marker in an unknown encoding is still present" + ); + + struct UnreadableKv; + impl KvStore for UnreadableKv { + fn get(&self, _: &ObjectId, _: &str) -> Result>, KvError> { + Err(KvError::LockPoisoned) + } + fn put(&self, _: &ObjectId, _: &str, _: &[u8]) -> Result<(), KvError> { + Ok(()) + } + fn delete(&self, _: &ObjectId, _: &str) -> Result<(), KvError> { + Ok(()) + } + fn list_keys(&self, _: &ObjectId, _: Option<&str>) -> Result, KvError> { + Ok(Vec::new()) + } + } + let unreadable = DetKv::from_store(Arc::new(UnreadableKv)); + assert!( + kv_marker_present(&unreadable, &owner, KV_PREFIX_DETAILS_SYNCED, &contact).is_err(), + "a failed read is not absence" + ); + } + /// F40: two identities that share a wallet must not see each other's /// blocked / declined markers. Identity A blocks/declines a counterparty; /// identity B's view of that same counterparty stays clean. From a247264f501f603da94621a7593a192c3c9012e4 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 23 Oct 2026 00:06:15 +0000 Subject: [PATCH 31/73] fix(dashpay): keep saves and withdrawals from racing other writers A contact details save read its baseline, then platform-wallet fetched the documents again and replaced whatever revision it found. A nickname another device saved in between was undone by a note-only save. The save now carries the sealed payloads of the documents it read, and the crypto provider platform-wallet opens every candidate through refuses to seal once the contact's document is one the save did not read. Every publish seals under a fresh IV, so the payload names the revision. The save then fails with a message to check the details and save again. A cancel or decline could ignore someone whose reply platform-wallet had just taken in, and record a withdrawal or decline for an established contact. Both now check for the contact after the ignore. An ignored sender's requests are not ingested, so a contact found then was established first; the ignore is lifted and the contact reported. Restoring a withdrawn request reads the withdrawal for presence only, and a failed read fails the accept or send instead of reporting success with the withdrawal still in force. Co-Authored-By: Claude Opus 5.5 --- src/backend_task/dashpay/contact_info.rs | 38 ++-- src/backend_task/dashpay/contact_requests.rs | 136 ++++++++++++--- src/backend_task/dashpay/contacts.rs | 13 +- src/backend_task/error.rs | 16 +- src/wallet_backend/contact_info.rs | 174 +++++++++++++++++-- src/wallet_backend/dashpay.rs | 117 +++++++++---- src/wallet_backend/mod.rs | 1 + 7 files changed, 403 insertions(+), 92 deletions(-) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 508bbd3de..f0649f41a 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -94,11 +94,17 @@ pub async fn create_or_update_contact_info( /// The reads and writes one contact details save performs, behind a trait so /// their order and failures can be driven in tests. trait SaveOps { - /// The details shown for the contact now; the fields an update keeps. - fn current(&self) -> impl Future> + Send; + /// What the current details were read from; the publish replaces only that. + type Baseline: Send + Sync; + /// The details shown for the contact now, the fields an update keeps, and + /// what they were read from. + fn current( + &self, + ) -> impl Future> + Send; fn publish( &self, details: ContactDetails, + baseline: &Self::Baseline, ) -> impl Future> + Send; /// Record that platform-wallet holds the contact's details, so a legacy /// document no longer stands in for them. @@ -117,7 +123,8 @@ async fn save_contact_details( ops: &O, update: &ContactInfoUpdate, ) -> Result { - let details = update.apply_to(ops.current().await?); + let (current, baseline) = ops.current().await?; + let details = update.apply_to(current); validate_contact_note(details.note.as_deref().unwrap_or_default())?; // The bound platform-wallet enforces, checked before it saves anything. @@ -131,7 +138,7 @@ async fn save_contact_details( source: Box::new(source), })?; - let outcome = ops.publish(details).await?; + let outcome = ops.publish(details, &baseline).await?; ops.mark_synced()?; match outcome { ContactInfoPublishOutcome::Published => Ok(true), @@ -153,7 +160,9 @@ struct PlatformSaveOps<'a> { } impl SaveOps for PlatformSaveOps<'_> { - async fn current(&self) -> Result { + type Baseline = crate::wallet_backend::ContactInfoBaseline; + + async fn current(&self) -> Result<(ContactDetails, Self::Baseline), TaskError> { let owner = self.identity.identity.id(); self.backend.dashpay_sync_contact_infos(&owner).await?; let local = self @@ -173,20 +182,18 @@ impl SaveOps for PlatformSaveOps<'_> { let legacy = legacy .get(&self.contact_id) .map(super::contacts::ContactData::details); - Ok(super::contacts::shown_contact_details( - published, - local, - synced_before, - legacy, - )) + let current = + super::contacts::shown_contact_details(published, local, synced_before, legacy); + Ok((current, stored.baseline)) } async fn publish( &self, details: ContactDetails, + baseline: &Self::Baseline, ) -> Result { self.backend - .dashpay_set_contact_info(self.identity, &self.contact_id, details) + .dashpay_set_contact_info(self.identity, &self.contact_id, details, baseline) .await } @@ -347,13 +354,16 @@ mod tests { } impl SaveOps for ScriptedSave { - async fn current(&self) -> Result { - self.current.lock().unwrap().take().expect("read once") + type Baseline = (); + + async fn current(&self) -> Result<(ContactDetails, ()), TaskError> { + Ok((self.current.lock().unwrap().take().expect("read once")?, ())) } async fn publish( &self, details: ContactDetails, + _baseline: &(), ) -> Result { self.published.lock().unwrap().push(details); Ok(ContactInfoPublishOutcome::DeferredUntilTwoContacts) diff --git a/src/backend_task/dashpay/contact_requests.rs b/src/backend_task/dashpay/contact_requests.rs index e082d2787..a07a74bee 100644 --- a/src/backend_task/dashpay/contact_requests.rs +++ b/src/backend_task/dashpay/contact_requests.rs @@ -825,7 +825,10 @@ pub async fn accept_contact_request( /// The local state that re-engages someone the owner withdrew a request /// from, behind a trait so the decision can be driven in tests. trait ReEngageOps { - fn is_withdrawn(&self) -> bool; + /// # Errors + /// + /// The withdrawal record could not be read. + fn is_withdrawn(&self) -> Result; /// Lift the ignore and clear the withdrawal and decline markers. fn re_engage(&self) -> impl Future> + Send; } @@ -833,7 +836,7 @@ trait ReEngageOps { /// Restore a withdrawn request the owner sent earlier, which still stands on /// Platform; returns whether there was one. Nothing is published. async fn restore_withdrawn_request(ops: &O) -> Result { - if !ops.is_withdrawn() { + if !ops.is_withdrawn()? { return Ok(false); } ops.re_engage().await?; @@ -847,8 +850,9 @@ struct PlatformReEngage<'a> { } impl ReEngageOps for PlatformReEngage<'_> { - fn is_withdrawn(&self) -> bool { - self.backend.dashpay_is_withdrawn(&self.owner, &self.peer) + fn is_withdrawn(&self) -> Result { + self.backend + .dashpay_withdrawal_recorded(&self.owner, &self.peer) } async fn re_engage(&self) -> Result<(), TaskError> { @@ -903,16 +907,25 @@ trait RejectOps { ) -> impl Future, TaskError>> + Send; /// Forget the progress record an older version kept for this action. fn clear_phase(&self) -> Result<(), TaskError>; - /// Ignore the sender in platform-wallet (local only). - fn ignore_sender(&self) -> impl Future> + Send; + /// Ignore the sender in platform-wallet (local only), unless the contact + /// is already established there; returns whether the ignore stands. + fn ignore_sender(&self) -> impl Future> + Send; fn mark_declined(&self) -> Result<(), TaskError>; fn request_id(&self) -> Identifier; + fn sender_id(&self) -> Identifier; } async fn reject_flow(ops: &O) -> Result { let _action_guard = ops.lock_action().await?; - ops.ignore_sender().await?; - let result = complete_rejection(ops.request_id(), || ops.mark_declined())?; + let result = if ops.ignore_sender().await? { + complete_rejection(ops.request_id(), || ops.mark_declined())? + } else { + // The contact was established before the ignore took effect. + BackendTaskSuccessResult::DashPayContactAlreadyEstablished { + request_id: ops.request_id(), + contact_id: ops.sender_id(), + } + }; ops.clear_phase()?; Ok(result) } @@ -943,10 +956,10 @@ impl RejectOps for PlatformRejectOps<'_> { ) } - async fn ignore_sender(&self) -> Result<(), TaskError> { + async fn ignore_sender(&self) -> Result { self.app_context .wallet_backend()? - .dashpay_ignore_contact_sender(&self.owner_id, &self.from_identity_id) + .dashpay_ignore_unless_established(&self.owner_id, &self.from_identity_id) .await } @@ -959,6 +972,10 @@ impl RejectOps for PlatformRejectOps<'_> { fn request_id(&self) -> Identifier { self.request_id } + + fn sender_id(&self) -> Identifier { + self.from_identity_id + } } /// Return rejection success only after storing the local marker that retires the row. @@ -1002,8 +1019,10 @@ trait CancelOps { fn reciprocal_request_exists(&self) -> impl Future> + Send; /// Ignore the recipient in platform-wallet (local only), so a reply to - /// the withdrawn request cannot establish the contact on its own. - fn ignore_recipient(&self) -> impl Future> + Send; + /// the withdrawn request cannot establish the contact on its own; returns + /// whether the ignore stands, which it does not when the reply was taken + /// in first and the contact is already established. + fn ignore_recipient(&self) -> impl Future> + Send; /// Record the withdrawal in the DET sidecar so the request stops being /// listed as pending. @@ -1022,10 +1041,12 @@ async fn cancel_flow(ops: &O) -> Result let _action_guard = ops.lock_action().await?; let outcome = if ops.reciprocal_request_exists().await? { CancelOutcome::AlreadyEstablished - } else { - ops.ignore_recipient().await?; + } else if ops.ignore_recipient().await? { ops.mark_withdrawn()?; CancelOutcome::Withdrawn + } else { + // The reply was taken in after the query, before the ignore. + CancelOutcome::AlreadyEstablished }; ops.clear_phase()?; Ok(outcome) @@ -1085,10 +1106,10 @@ impl CancelOps for PlatformCancelOps<'_> { .dashpay_mark_withdrawn(&self.owner_id, &self.to_identity_id) } - async fn ignore_recipient(&self) -> Result<(), TaskError> { + async fn ignore_recipient(&self) -> Result { self.app_context .wallet_backend()? - .dashpay_ignore_contact_sender(&self.owner_id, &self.to_identity_id) + .dashpay_ignore_unless_established(&self.owner_id, &self.to_identity_id) .await } } @@ -1345,12 +1366,18 @@ mod tests { #[derive(Default)] struct ScriptedReEngage { withdrawn: bool, + unreadable: bool, re_engaged: std::sync::Mutex, } impl ReEngageOps for ScriptedReEngage { - fn is_withdrawn(&self) -> bool { - self.withdrawn + fn is_withdrawn(&self) -> Result { + if self.unreadable { + return Err(TaskError::DashPayLocalStateRead { + source: crate::wallet_backend::KvAdapterError::Truncated, + }); + } + Ok(self.withdrawn) } async fn re_engage(&self) -> Result<(), TaskError> { @@ -1379,6 +1406,23 @@ mod tests { assert!(!*pending.re_engaged.lock().unwrap()); } + /// PRRT_kwDOM8GK3c6vbDgP: an unreadable withdrawal record fails the + /// accept or send instead of reporting success with the withdrawal still + /// in force. + #[tokio::test] + async fn an_unreadable_withdrawal_record_fails_the_restore() { + let ops = ScriptedReEngage { + unreadable: true, + ..Default::default() + }; + + assert!(matches!( + restore_withdrawn_request(&ops).await, + Err(TaskError::DashPayLocalStateRead { .. }) + )); + assert!(!*ops.re_engaged.lock().unwrap()); + } + #[test] fn retain_unresolved_drops_declined_and_withdrawn_rows() { // Incoming from id(1) — declined. Incoming from id(2) — still pending. @@ -1481,6 +1525,8 @@ mod tests { withdraw_fails: bool, phase_cleared: Mutex, ignored: Mutex, + /// The reply is taken in between the reciprocal query and the ignore. + established_meanwhile: bool, } impl CancelOps for ScriptedOps { @@ -1497,9 +1543,9 @@ mod tests { Ok(self.reciprocal) } - async fn ignore_recipient(&self) -> Result<(), TaskError> { - *self.ignored.lock().unwrap() = true; - Ok(()) + async fn ignore_recipient(&self) -> Result { + *self.ignored.lock().unwrap() = !self.established_meanwhile; + Ok(!self.established_meanwhile) } fn mark_withdrawn(&self) -> Result<(), TaskError> { @@ -1513,6 +1559,24 @@ mod tests { } } + /// PRRT_kwDOM8GK3c6vbDgL: the reply is taken in and the contact + /// established after the reciprocal query; the cancellation then reports + /// the contact and records no withdrawal. + #[tokio::test] + async fn a_reply_taken_in_during_the_cancel_wins() { + let ops = ScriptedOps { + established_meanwhile: true, + ..Default::default() + }; + + assert_eq!( + cancel_flow(&ops).await.expect("cancel"), + CancelOutcome::AlreadyEstablished + ); + assert!(!*ops.withdrawn.lock().unwrap()); + assert!(!*ops.ignored.lock().unwrap(), "the ignore is lifted again"); + } + #[tokio::test] async fn withdrawing_a_pending_request_records_it_on_this_device() { let ops = ScriptedOps::default(); @@ -1581,6 +1645,7 @@ mod tests { struct ScriptedRejectOps { action_lock: Arc>, ignore_fails: bool, + established_meanwhile: bool, ignored: Mutex, declined: Mutex, } @@ -1594,12 +1659,15 @@ mod tests { Ok(()) } - async fn ignore_sender(&self) -> Result<(), TaskError> { + async fn ignore_sender(&self) -> Result { if self.ignore_fails { return Err(TaskError::WalletStateInconsistent); } + if self.established_meanwhile { + return Ok(false); + } *self.ignored.lock().unwrap() += 1; - Ok(()) + Ok(true) } fn mark_declined(&self) -> Result<(), TaskError> { @@ -1610,6 +1678,28 @@ mod tests { fn request_id(&self) -> Identifier { id(7) } + + fn sender_id(&self) -> Identifier { + id(8) + } + } + + /// The decline twin of `a_reply_taken_in_during_the_cancel_wins`: the + /// owner's own request (sent from another device) is taken in first, so + /// the contact is established and nothing is declined. + #[tokio::test] + async fn a_contact_established_during_the_decline_wins() { + let ops = ScriptedRejectOps { + established_meanwhile: true, + ..Default::default() + }; + + assert!(matches!( + reject_flow(&ops).await, + Ok(BackendTaskSuccessResult::DashPayContactAlreadyEstablished { request_id, contact_id }) + if request_id == id(7) && contact_id == id(8) + )); + assert!(!*ops.declined.lock().unwrap()); } #[tokio::test] diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index bf8e77ad1..b5e5d35f9 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -252,6 +252,8 @@ pub(super) struct StoredContactDetails { /// From documents older versions of this app wrote under the legacy /// key root, newest per contact; an error as for `published`. pub(super) legacy: Result, TaskError>, + /// The documents these details were read from, which a save may replace. + pub(super) baseline: crate::wallet_backend::ContactInfoBaseline, } /// Read every `contactInfo` document the owner stored, both as DIP-0015 @@ -298,7 +300,11 @@ pub(super) async fn stored_contact_details( } else { Ok(HashMap::new()) }; - Ok(StoredContactDetails { published, legacy }) + Ok(StoredContactDetails { + published, + legacy, + baseline: crate::wallet_backend::ContactInfoBaseline::of(&documents), + }) } /// The details the contacts list shows for one contact, and that a save @@ -463,8 +469,9 @@ pub async fn load_contacts( Default::default() } }; - let StoredContactDetails { published, legacy } = - stored_contact_details(app_context, sdk, &identity).await?; + let StoredContactDetails { + published, legacy, .. + } = stored_contact_details(app_context, sdk, &identity).await?; let mut published = published.unwrap_or_else(|error| { tracing::debug!(?error, "LoadContacts: published contact details not read"); BTreeMap::new() diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 22213c7da..40126fb13 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -1352,10 +1352,18 @@ pub enum TaskError { source: crate::wallet_backend::KvAdapterError, }, - /// The record of which contact details this device already holds could - /// not be read, so a save cannot tell which stored details to keep. - #[error("Could not read your contact details saved on this device. Try saving again in a moment.")] - ContactDetailsStateRead { + /// The contact's details were saved from another device after this save + /// read them; publishing would undo that change with older values. + #[error( + "Your contact details were changed on another device while you were saving. Check them and save your change again." + )] + ContactInfoChangedElsewhere, + + /// A DashPay record this device keeps (which contact details it holds, + /// which requests were withdrawn) could not be read, so an action that + /// depends on it cannot tell what to do. + #[error("Could not read your DashPay records on this device. Try again in a moment.")] + DashPayLocalStateRead { #[source] source: crate::wallet_backend::KvAdapterError, }, diff --git a/src/wallet_backend/contact_info.rs b/src/wallet_backend/contact_info.rs index 35776b1e1..30e03b9ef 100644 --- a/src/wallet_backend/contact_info.rs +++ b/src/wallet_backend/contact_info.rs @@ -7,8 +7,9 @@ //! platform-wallet's own `derive_contact_info_keys`, the AES steps from the //! `platform-encryption` crate it uses, so both sides always agree. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::dashcore::secp256k1::{PublicKey, SecretKey}; @@ -97,11 +98,16 @@ impl WalletBackend { /// not an established contact /// ([`TaskError::ContactInfoContactNotEstablished`]). A failed publish is /// [`TaskError::DashPayContactInfoWriteFailed`]. + /// + /// The details are published only over the documents `baseline` was read + /// from: when the contact's document changed since, nothing is published + /// ([`TaskError::ContactInfoChangedElsewhere`]). pub(crate) async fn dashpay_set_contact_info( &self, identity: &QualifiedIdentity, contact_id: &Identifier, details: ContactDetails, + baseline: &ContactInfoBaseline, ) -> Result { let owner = identity.identity.id(); let seed_hash = identity @@ -131,8 +137,9 @@ impl WalletBackend { let seed = plaintext .expose_hd_seed() .ok_or(TaskError::ContactWalletSeedUnavailable)?; - let crypto = ContactInfoCrypto::new(seed, network, identity_index); - dashpay + let crypto = ContactInfoCrypto::new(seed, network, identity_index) + .replacing_only(contact_id, baseline); + let published = dashpay .set_contact_info_with_external_signer( &owner, contact_id, @@ -142,10 +149,13 @@ impl WalletBackend { identity, &crypto, ) - .await - .map_err(|source| TaskError::DashPayContactInfoWriteFailed { - source: Arc::new(source), - }) + .await; + if crypto.found_changed_document() { + return Err(TaskError::ContactInfoChangedElsewhere); + } + published.map_err(|source| TaskError::DashPayContactInfoWriteFailed { + source: Arc::new(source), + }) }) .await } @@ -289,6 +299,27 @@ fn contact_info_write_index( Ok(identity_index) } +/// The sealed `privateData` of the `contactInfo` documents a save read its +/// baseline from. +/// +/// Every publish seals `privateData` under a fresh random IV, so these bytes +/// name one revision of a document: a document whose sealed payload is not +/// here was written after the baseline was read. +#[derive(Debug, Default)] +pub(crate) struct ContactInfoBaseline(BTreeSet>); + +impl ContactInfoBaseline { + pub(crate) fn of(documents: &[Document]) -> Self { + Self( + documents + .iter() + .filter_map(StoredContactInfo::of) + .map(|stored| stored.private_data.to_vec()) + .collect(), + ) + } +} + /// Seals and opens `contactInfo` ciphertexts for one wallet identity. /// /// Holds a borrow of the seed for one operation only; it never copies the @@ -297,6 +328,15 @@ pub(crate) struct ContactInfoCrypto<'a> { seed: &'a [u8; 64], network: Network, identity_index: u32, + replacing: Option>, +} + +/// Keeps a write from replacing a document it did not read; see +/// [`ContactInfoCrypto::replacing_only`]. +struct ReplaceGuard<'a> { + contact_id: [u8; 32], + baseline: &'a ContactInfoBaseline, + found_changed: AtomicBool, } impl<'a> ContactInfoCrypto<'a> { @@ -305,9 +345,39 @@ impl<'a> ContactInfoCrypto<'a> { seed, network, identity_index, + replacing: None, } } + /// Refuse to seal once a document for `contact_id` that is not in + /// `baseline` was opened. + /// + /// platform-wallet's write fetches the owner's documents again, opens each + /// through this provider, and replaces the first that opens to the contact + /// under its current revision. A document written by another device since + /// the baseline was read would be replaced with fields kept from the older + /// read; refusing to seal stops the write before anything is published. + pub(crate) fn replacing_only( + mut self, + contact_id: &Identifier, + baseline: &'a ContactInfoBaseline, + ) -> Self { + self.replacing = Some(ReplaceGuard { + contact_id: contact_id.to_buffer(), + baseline, + found_changed: AtomicBool::new(false), + }); + self + } + + /// Whether the write opened a document for its contact written after its + /// baseline was read. + pub(crate) fn found_changed_document(&self) -> bool { + self.replacing + .as_ref() + .is_some_and(|guard| guard.found_changed.load(Ordering::Relaxed)) + } + /// The two AES keys beneath `root_path`, derived by platform-wallet. /// /// `root_path` must be one of this identity's key paths: any other root is @@ -419,6 +489,11 @@ impl ContactCryptoProvider for ContactInfoCrypto<'_> { private_data_plaintext: &[u8], private_data_iv: &[u8; 16], ) -> Result { + if self.found_changed_document() { + return Err(PlatformWalletError::InvalidParameter( + "contactInfo changed after it was read".to_string(), + )); + } let keys = self.keys(root_path, derivation_index)?; Ok(ContactInfoSealed { enc_to_user_id: platform_encryption::encrypt_enc_to_user_id( @@ -448,11 +523,16 @@ impl ContactCryptoProvider for ContactInfoCrypto<'_> { "contactInfo privateData could not be decrypted: {error}" )) })?; + let contact_id = + platform_encryption::decrypt_enc_to_user_id(&keys.enc_to_user_id_key, enc_to_user_id); + if let Some(guard) = &self.replacing + && guard.contact_id == contact_id + && !guard.baseline.0.contains(private_data_blob) + { + guard.found_changed.store(true, Ordering::Relaxed); + } Ok(ContactInfoOpened { - contact_id: platform_encryption::decrypt_enc_to_user_id( - &keys.enc_to_user_id_key, - enc_to_user_id, - ), + contact_id, private_data, }) } @@ -511,6 +591,78 @@ mod tests { ); } + /// PRRT_kwDOM8GK3c6vbDgJ: a save read its baseline while the contact's + /// document held one nickname; another device then rewrote it. The write + /// opens that newer document first, as platform-wallet does, and must + /// not seal: its kept fields come from the older read. + #[tokio::test] + async fn a_write_does_not_replace_a_document_changed_since_its_read() { + let contact = Identifier::from([9u8; 32]); + let other = Identifier::from([8u8; 32]); + let keys = upstream_keys(2, 0); + let seal = |id: &Identifier, nickname: &[u8], iv: u8| ContactInfoSealed { + enc_to_user_id: platform_encryption::encrypt_enc_to_user_id( + &keys.enc_to_user_id_key, + &id.to_buffer(), + ), + private_data: platform_encryption::encrypt_private_data( + &keys.private_data_key, + &[iv; 16], + nickname, + ), + }; + let read = seal(&contact, b"Bao", 1); + let theirs = seal(&other, b"Lan", 2); + let baseline = ContactInfoBaseline::of(&[ + stored_document(1, 2, 0, &read), + stored_document(2, 2, 0, &theirs), + ]); + let write = |documents: Vec| { + let baseline = &baseline; + async move { + let crypto = ContactInfoCrypto::new(&SEED, NETWORK, IDENTITY_INDEX) + .replacing_only(&contact, baseline); + for document in &documents { + crypto + .contact_info_open( + &root(IDENTITY_INDEX, 2), + 0, + &document.enc_to_user_id, + &document.private_data, + ) + .await + .expect("open"); + } + let sealed = crypto + .contact_info_seal( + &root(IDENTITY_INDEX, 2), + 0, + &contact.to_buffer(), + b"n", + &[3; 16], + ) + .await; + (sealed.is_ok(), crypto.found_changed_document()) + } + }; + + assert_eq!( + write(vec![seal(&contact, b"Bao", 1), seal(&other, b"Lan", 2)]).await, + (true, false), + "the documents read can be replaced" + ); + assert_eq!( + write(vec![seal(&other, b"Rewritten", 4)]).await, + (true, false), + "another contact's document is not this write's concern" + ); + assert_eq!( + write(vec![seal(&contact, b"Newer", 5)]).await, + (false, true), + "a document rewritten since the read is not replaced" + ); + } + /// A document platform-wallet sealed opens here. #[tokio::test] async fn opens_what_platform_wallet_sealed() { diff --git a/src/wallet_backend/dashpay.rs b/src/wallet_backend/dashpay.rs index 7c0dd5797..2969123d2 100644 --- a/src/wallet_backend/dashpay.rs +++ b/src/wallet_backend/dashpay.rs @@ -1304,6 +1304,46 @@ impl WalletBackend { kv_contains(&self.kv(), owner, KV_PREFIX_WITHDRAWN, counterparty_id) } + /// [`Self::dashpay_is_withdrawn`] for a decision that changes state: a + /// failed read is an error, not "not withdrawn". + pub(crate) fn dashpay_withdrawal_recorded( + &self, + owner: &Identifier, + counterparty_id: &Identifier, + ) -> Result { + kv_marker_present(&self.kv(), owner, KV_PREFIX_WITHDRAWN, counterparty_id) + .map_err(|source| TaskError::DashPayLocalStateRead { source }) + } + + /// Ignore `peer` for `owner` unless platform-wallet has established the + /// contact; returns whether the ignore stands. + /// + /// Establishing a contact and ignoring a sender each take platform-wallet's + /// wallet lock, and once `peer` is ignored their requests are no longer + /// ingested and their pending one is dropped. So a contact found + /// established after the ignore was established before it: the ignore lost + /// the race, and is lifted again. + pub(crate) async fn dashpay_ignore_unless_established( + &self, + owner: &Identifier, + peer: &Identifier, + ) -> Result { + self.dashpay_ignore_contact_sender(owner, peer).await?; + let Some(wallet) = self.find_wallet_for_identity(owner).await else { + return Ok(true); + }; + let established = wallet + .state() + .await + .identity_manager + .managed_identity(owner) + .is_some_and(|managed| managed.dashpay().established_contacts().contains_key(peer)); + if established { + self.dashpay_unignore_contact_sender(owner, peer).await?; + } + Ok(!established) + } + /// Clear `owner`'s withdrawal marker for `counterparty_id`. Idempotent — /// clearing an absent marker is `Ok(())`. Re-sending a request to the same /// person retires the earlier withdrawal, so the fresh request lists. @@ -1337,7 +1377,7 @@ impl WalletBackend { contact_id: &Identifier, ) -> Result { kv_marker_present(&self.kv(), owner, KV_PREFIX_DETAILS_SYNCED, contact_id) - .map_err(|source| TaskError::ContactDetailsStateRead { source }) + .map_err(|source| TaskError::DashPayLocalStateRead { source }) } pub(crate) async fn dashpay_lock_contact_request_action( @@ -2661,48 +2701,51 @@ mod tests { ); } - /// PRRT_kwDOM8GK3c6vZ6qO: the synced marker is read for presence only, so + /// PRRT_kwDOM8GK3c6vZ6qO / vbDgP: the synced and withdrawn markers are + /// read for presence only, so /// a value in an unknown encoding still counts; a failed read is an error. #[test] fn a_marker_read_tells_failure_from_absence() { - use platform_wallet_storage::{KvError, KvStore, ObjectId}; - - let store = Arc::new(crate::wallet_backend::kv_test_support::InMemoryKv::default()); - let kv = DetKv::from_store(store.clone()); - let (owner, contact) = (id_from_byte(1), id_from_byte(2)); - assert!(!kv_marker_present(&kv, &owner, KV_PREFIX_DETAILS_SYNCED, &contact).unwrap()); - store - .put( - &ObjectId::Identity(owner.to_buffer()), - &sidecar_key(KV_PREFIX_DETAILS_SYNCED, &contact), - &[crate::wallet_backend::kv::SCHEMA_VERSION.wrapping_add(1), 0], - ) - .unwrap(); - assert!( - kv_marker_present(&kv, &owner, KV_PREFIX_DETAILS_SYNCED, &contact).unwrap(), - "a marker in an unknown encoding is still present" - ); + for prefix in [KV_PREFIX_DETAILS_SYNCED, KV_PREFIX_WITHDRAWN] { + use platform_wallet_storage::{KvError, KvStore, ObjectId}; + + let store = Arc::new(crate::wallet_backend::kv_test_support::InMemoryKv::default()); + let kv = DetKv::from_store(store.clone()); + let (owner, contact) = (id_from_byte(1), id_from_byte(2)); + assert!(!kv_marker_present(&kv, &owner, prefix, &contact).unwrap()); + store + .put( + &ObjectId::Identity(owner.to_buffer()), + &sidecar_key(prefix, &contact), + &[crate::wallet_backend::kv::SCHEMA_VERSION.wrapping_add(1), 0], + ) + .unwrap(); + assert!( + kv_marker_present(&kv, &owner, prefix, &contact).unwrap(), + "a marker in an unknown encoding is still present" + ); - struct UnreadableKv; - impl KvStore for UnreadableKv { - fn get(&self, _: &ObjectId, _: &str) -> Result>, KvError> { - Err(KvError::LockPoisoned) - } - fn put(&self, _: &ObjectId, _: &str, _: &[u8]) -> Result<(), KvError> { - Ok(()) - } - fn delete(&self, _: &ObjectId, _: &str) -> Result<(), KvError> { - Ok(()) - } - fn list_keys(&self, _: &ObjectId, _: Option<&str>) -> Result, KvError> { - Ok(Vec::new()) + struct UnreadableKv; + impl KvStore for UnreadableKv { + fn get(&self, _: &ObjectId, _: &str) -> Result>, KvError> { + Err(KvError::LockPoisoned) + } + fn put(&self, _: &ObjectId, _: &str, _: &[u8]) -> Result<(), KvError> { + Ok(()) + } + fn delete(&self, _: &ObjectId, _: &str) -> Result<(), KvError> { + Ok(()) + } + fn list_keys(&self, _: &ObjectId, _: Option<&str>) -> Result, KvError> { + Ok(Vec::new()) + } } + let unreadable = DetKv::from_store(Arc::new(UnreadableKv)); + assert!( + kv_marker_present(&unreadable, &owner, prefix, &contact).is_err(), + "a failed read is not absence" + ); } - let unreadable = DetKv::from_store(Arc::new(UnreadableKv)); - assert!( - kv_marker_present(&unreadable, &owner, KV_PREFIX_DETAILS_SYNCED, &contact).is_err(), - "a failed read is not absence" - ); } /// F40: two identities that share a wallet must not see each other's diff --git a/src/wallet_backend/mod.rs b/src/wallet_backend/mod.rs index 79275e506..bd76cdd13 100644 --- a/src/wallet_backend/mod.rs +++ b/src/wallet_backend/mod.rs @@ -25,6 +25,7 @@ pub mod auth_pubkey_cache; pub(crate) mod auth_pubkey_cache; mod avatar_cache; mod contact_info; +pub(crate) use contact_info::ContactInfoBaseline; mod contact_profile_cache; mod coordinator_gate; mod dashpay; From 567c4c828dfdf3902d1640cb499ddb05e77bd444 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 23 Oct 2026 00:38:07 +0000 Subject: [PATCH 32/73] revert(dashpay): drop the stale-baseline guard on contact details saves The guard that refused to replace a contactInfo document the save had not read is removed: the save no longer carries a baseline, and `ContactInfoChangedElsewhere` is gone. Preserved fields still come from the save's read while platform-wallet replaces the revision it fetches itself. This is a known limitation until upstream `set_contact_info` takes an expected revision; a TODO at the write call names it. The withdraw/decline race fix and the fallible marker reads stay. Co-Authored-By: Claude Opus 5.5 --- src/backend_task/dashpay/contact_info.rs | 39 ++--- src/backend_task/dashpay/contacts.rs | 13 +- src/backend_task/error.rs | 7 - src/wallet_backend/contact_info.rs | 174 ++--------------------- src/wallet_backend/mod.rs | 1 - 5 files changed, 29 insertions(+), 205 deletions(-) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index f0649f41a..d64f59e62 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -94,17 +94,11 @@ pub async fn create_or_update_contact_info( /// The reads and writes one contact details save performs, behind a trait so /// their order and failures can be driven in tests. trait SaveOps { - /// What the current details were read from; the publish replaces only that. - type Baseline: Send + Sync; - /// The details shown for the contact now, the fields an update keeps, and - /// what they were read from. - fn current( - &self, - ) -> impl Future> + Send; + /// The details shown for the contact now; the fields an update keeps. + fn current(&self) -> impl Future> + Send; fn publish( &self, details: ContactDetails, - baseline: &Self::Baseline, ) -> impl Future> + Send; /// Record that platform-wallet holds the contact's details, so a legacy /// document no longer stands in for them. @@ -123,8 +117,7 @@ async fn save_contact_details( ops: &O, update: &ContactInfoUpdate, ) -> Result { - let (current, baseline) = ops.current().await?; - let details = update.apply_to(current); + let details = update.apply_to(ops.current().await?); validate_contact_note(details.note.as_deref().unwrap_or_default())?; // The bound platform-wallet enforces, checked before it saves anything. @@ -138,7 +131,7 @@ async fn save_contact_details( source: Box::new(source), })?; - let outcome = ops.publish(details, &baseline).await?; + let outcome = ops.publish(details).await?; ops.mark_synced()?; match outcome { ContactInfoPublishOutcome::Published => Ok(true), @@ -160,9 +153,7 @@ struct PlatformSaveOps<'a> { } impl SaveOps for PlatformSaveOps<'_> { - type Baseline = crate::wallet_backend::ContactInfoBaseline; - - async fn current(&self) -> Result<(ContactDetails, Self::Baseline), TaskError> { + async fn current(&self) -> Result { let owner = self.identity.identity.id(); self.backend.dashpay_sync_contact_infos(&owner).await?; let local = self @@ -182,18 +173,21 @@ impl SaveOps for PlatformSaveOps<'_> { let legacy = legacy .get(&self.contact_id) .map(super::contacts::ContactData::details); - let current = - super::contacts::shown_contact_details(published, local, synced_before, legacy); - Ok((current, stored.baseline)) + Ok(super::contacts::shown_contact_details( + published, + local, + synced_before, + legacy, + )) } async fn publish( &self, details: ContactDetails, - baseline: &Self::Baseline, ) -> Result { + // TODO: preserved fields come from `current()`'s read; upstream set_contact_info has no expected-revision check, so a newer edit from another device in between is overwritten. self.backend - .dashpay_set_contact_info(self.identity, &self.contact_id, details, baseline) + .dashpay_set_contact_info(self.identity, &self.contact_id, details) .await } @@ -354,16 +348,13 @@ mod tests { } impl SaveOps for ScriptedSave { - type Baseline = (); - - async fn current(&self) -> Result<(ContactDetails, ()), TaskError> { - Ok((self.current.lock().unwrap().take().expect("read once")?, ())) + async fn current(&self) -> Result { + self.current.lock().unwrap().take().expect("read once") } async fn publish( &self, details: ContactDetails, - _baseline: &(), ) -> Result { self.published.lock().unwrap().push(details); Ok(ContactInfoPublishOutcome::DeferredUntilTwoContacts) diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index b5e5d35f9..bf8e77ad1 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -252,8 +252,6 @@ pub(super) struct StoredContactDetails { /// From documents older versions of this app wrote under the legacy /// key root, newest per contact; an error as for `published`. pub(super) legacy: Result, TaskError>, - /// The documents these details were read from, which a save may replace. - pub(super) baseline: crate::wallet_backend::ContactInfoBaseline, } /// Read every `contactInfo` document the owner stored, both as DIP-0015 @@ -300,11 +298,7 @@ pub(super) async fn stored_contact_details( } else { Ok(HashMap::new()) }; - Ok(StoredContactDetails { - published, - legacy, - baseline: crate::wallet_backend::ContactInfoBaseline::of(&documents), - }) + Ok(StoredContactDetails { published, legacy }) } /// The details the contacts list shows for one contact, and that a save @@ -469,9 +463,8 @@ pub async fn load_contacts( Default::default() } }; - let StoredContactDetails { - published, legacy, .. - } = stored_contact_details(app_context, sdk, &identity).await?; + let StoredContactDetails { published, legacy } = + stored_contact_details(app_context, sdk, &identity).await?; let mut published = published.unwrap_or_else(|error| { tracing::debug!(?error, "LoadContacts: published contact details not read"); BTreeMap::new() diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 40126fb13..68feac635 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -1352,13 +1352,6 @@ pub enum TaskError { source: crate::wallet_backend::KvAdapterError, }, - /// The contact's details were saved from another device after this save - /// read them; publishing would undo that change with older values. - #[error( - "Your contact details were changed on another device while you were saving. Check them and save your change again." - )] - ContactInfoChangedElsewhere, - /// A DashPay record this device keeps (which contact details it holds, /// which requests were withdrawn) could not be read, so an action that /// depends on it cannot tell what to do. diff --git a/src/wallet_backend/contact_info.rs b/src/wallet_backend/contact_info.rs index 30e03b9ef..35776b1e1 100644 --- a/src/wallet_backend/contact_info.rs +++ b/src/wallet_backend/contact_info.rs @@ -7,9 +7,8 @@ //! platform-wallet's own `derive_contact_info_keys`, the AES steps from the //! `platform-encryption` crate it uses, so both sides always agree. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeMap; use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::dashcore::secp256k1::{PublicKey, SecretKey}; @@ -98,16 +97,11 @@ impl WalletBackend { /// not an established contact /// ([`TaskError::ContactInfoContactNotEstablished`]). A failed publish is /// [`TaskError::DashPayContactInfoWriteFailed`]. - /// - /// The details are published only over the documents `baseline` was read - /// from: when the contact's document changed since, nothing is published - /// ([`TaskError::ContactInfoChangedElsewhere`]). pub(crate) async fn dashpay_set_contact_info( &self, identity: &QualifiedIdentity, contact_id: &Identifier, details: ContactDetails, - baseline: &ContactInfoBaseline, ) -> Result { let owner = identity.identity.id(); let seed_hash = identity @@ -137,9 +131,8 @@ impl WalletBackend { let seed = plaintext .expose_hd_seed() .ok_or(TaskError::ContactWalletSeedUnavailable)?; - let crypto = ContactInfoCrypto::new(seed, network, identity_index) - .replacing_only(contact_id, baseline); - let published = dashpay + let crypto = ContactInfoCrypto::new(seed, network, identity_index); + dashpay .set_contact_info_with_external_signer( &owner, contact_id, @@ -149,13 +142,10 @@ impl WalletBackend { identity, &crypto, ) - .await; - if crypto.found_changed_document() { - return Err(TaskError::ContactInfoChangedElsewhere); - } - published.map_err(|source| TaskError::DashPayContactInfoWriteFailed { - source: Arc::new(source), - }) + .await + .map_err(|source| TaskError::DashPayContactInfoWriteFailed { + source: Arc::new(source), + }) }) .await } @@ -299,27 +289,6 @@ fn contact_info_write_index( Ok(identity_index) } -/// The sealed `privateData` of the `contactInfo` documents a save read its -/// baseline from. -/// -/// Every publish seals `privateData` under a fresh random IV, so these bytes -/// name one revision of a document: a document whose sealed payload is not -/// here was written after the baseline was read. -#[derive(Debug, Default)] -pub(crate) struct ContactInfoBaseline(BTreeSet>); - -impl ContactInfoBaseline { - pub(crate) fn of(documents: &[Document]) -> Self { - Self( - documents - .iter() - .filter_map(StoredContactInfo::of) - .map(|stored| stored.private_data.to_vec()) - .collect(), - ) - } -} - /// Seals and opens `contactInfo` ciphertexts for one wallet identity. /// /// Holds a borrow of the seed for one operation only; it never copies the @@ -328,15 +297,6 @@ pub(crate) struct ContactInfoCrypto<'a> { seed: &'a [u8; 64], network: Network, identity_index: u32, - replacing: Option>, -} - -/// Keeps a write from replacing a document it did not read; see -/// [`ContactInfoCrypto::replacing_only`]. -struct ReplaceGuard<'a> { - contact_id: [u8; 32], - baseline: &'a ContactInfoBaseline, - found_changed: AtomicBool, } impl<'a> ContactInfoCrypto<'a> { @@ -345,39 +305,9 @@ impl<'a> ContactInfoCrypto<'a> { seed, network, identity_index, - replacing: None, } } - /// Refuse to seal once a document for `contact_id` that is not in - /// `baseline` was opened. - /// - /// platform-wallet's write fetches the owner's documents again, opens each - /// through this provider, and replaces the first that opens to the contact - /// under its current revision. A document written by another device since - /// the baseline was read would be replaced with fields kept from the older - /// read; refusing to seal stops the write before anything is published. - pub(crate) fn replacing_only( - mut self, - contact_id: &Identifier, - baseline: &'a ContactInfoBaseline, - ) -> Self { - self.replacing = Some(ReplaceGuard { - contact_id: contact_id.to_buffer(), - baseline, - found_changed: AtomicBool::new(false), - }); - self - } - - /// Whether the write opened a document for its contact written after its - /// baseline was read. - pub(crate) fn found_changed_document(&self) -> bool { - self.replacing - .as_ref() - .is_some_and(|guard| guard.found_changed.load(Ordering::Relaxed)) - } - /// The two AES keys beneath `root_path`, derived by platform-wallet. /// /// `root_path` must be one of this identity's key paths: any other root is @@ -489,11 +419,6 @@ impl ContactCryptoProvider for ContactInfoCrypto<'_> { private_data_plaintext: &[u8], private_data_iv: &[u8; 16], ) -> Result { - if self.found_changed_document() { - return Err(PlatformWalletError::InvalidParameter( - "contactInfo changed after it was read".to_string(), - )); - } let keys = self.keys(root_path, derivation_index)?; Ok(ContactInfoSealed { enc_to_user_id: platform_encryption::encrypt_enc_to_user_id( @@ -523,16 +448,11 @@ impl ContactCryptoProvider for ContactInfoCrypto<'_> { "contactInfo privateData could not be decrypted: {error}" )) })?; - let contact_id = - platform_encryption::decrypt_enc_to_user_id(&keys.enc_to_user_id_key, enc_to_user_id); - if let Some(guard) = &self.replacing - && guard.contact_id == contact_id - && !guard.baseline.0.contains(private_data_blob) - { - guard.found_changed.store(true, Ordering::Relaxed); - } Ok(ContactInfoOpened { - contact_id, + contact_id: platform_encryption::decrypt_enc_to_user_id( + &keys.enc_to_user_id_key, + enc_to_user_id, + ), private_data, }) } @@ -591,78 +511,6 @@ mod tests { ); } - /// PRRT_kwDOM8GK3c6vbDgJ: a save read its baseline while the contact's - /// document held one nickname; another device then rewrote it. The write - /// opens that newer document first, as platform-wallet does, and must - /// not seal: its kept fields come from the older read. - #[tokio::test] - async fn a_write_does_not_replace_a_document_changed_since_its_read() { - let contact = Identifier::from([9u8; 32]); - let other = Identifier::from([8u8; 32]); - let keys = upstream_keys(2, 0); - let seal = |id: &Identifier, nickname: &[u8], iv: u8| ContactInfoSealed { - enc_to_user_id: platform_encryption::encrypt_enc_to_user_id( - &keys.enc_to_user_id_key, - &id.to_buffer(), - ), - private_data: platform_encryption::encrypt_private_data( - &keys.private_data_key, - &[iv; 16], - nickname, - ), - }; - let read = seal(&contact, b"Bao", 1); - let theirs = seal(&other, b"Lan", 2); - let baseline = ContactInfoBaseline::of(&[ - stored_document(1, 2, 0, &read), - stored_document(2, 2, 0, &theirs), - ]); - let write = |documents: Vec| { - let baseline = &baseline; - async move { - let crypto = ContactInfoCrypto::new(&SEED, NETWORK, IDENTITY_INDEX) - .replacing_only(&contact, baseline); - for document in &documents { - crypto - .contact_info_open( - &root(IDENTITY_INDEX, 2), - 0, - &document.enc_to_user_id, - &document.private_data, - ) - .await - .expect("open"); - } - let sealed = crypto - .contact_info_seal( - &root(IDENTITY_INDEX, 2), - 0, - &contact.to_buffer(), - b"n", - &[3; 16], - ) - .await; - (sealed.is_ok(), crypto.found_changed_document()) - } - }; - - assert_eq!( - write(vec![seal(&contact, b"Bao", 1), seal(&other, b"Lan", 2)]).await, - (true, false), - "the documents read can be replaced" - ); - assert_eq!( - write(vec![seal(&other, b"Rewritten", 4)]).await, - (true, false), - "another contact's document is not this write's concern" - ); - assert_eq!( - write(vec![seal(&contact, b"Newer", 5)]).await, - (false, true), - "a document rewritten since the read is not replaced" - ); - } - /// A document platform-wallet sealed opens here. #[tokio::test] async fn opens_what_platform_wallet_sealed() { diff --git a/src/wallet_backend/mod.rs b/src/wallet_backend/mod.rs index bd76cdd13..79275e506 100644 --- a/src/wallet_backend/mod.rs +++ b/src/wallet_backend/mod.rs @@ -25,7 +25,6 @@ pub mod auth_pubkey_cache; pub(crate) mod auth_pubkey_cache; mod avatar_cache; mod contact_info; -pub(crate) use contact_info::ContactInfoBaseline; mod contact_profile_cache; mod coordinator_gate; mod dashpay; From 8aceb4600f2cca0209db49f7a0dffd8765fc7332 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 23 Oct 2026 12:08:43 +0000 Subject: [PATCH 33/73] fix(identity): keep a confirmed note through a lagging read after an identity switch A confirmed note takes its "lagging" value, the note a read behind the save can still return, from the contact list on screen. When the save landed while another identity's lists were shown, there was none, so the first later read retired the note even if it still held the old one. A note write now carries the stored note its edit started from, and that note stands in when the contact is not listed. Co-Authored-By: Claude Opus 5.5 --- src/ui/identity/hub_screen.rs | 5 +++++ src/ui/state/contact_detail_view.rs | 30 ++++++++++++++++++++++------- src/ui/state/contacts_view.rs | 10 ++++++++-- 3 files changed, 36 insertions(+), 9 deletions(-) diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index d7f7fd383..148de3e2c 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -2700,6 +2700,11 @@ mod tests { &[Saved, IdentitySwitch, ListFromBefore("Old")], "Mine", ), + ( + "a save landing after an identity switch waits out a lagging read", + &[IdentitySwitch, Saved, ListFromAfter("Old")], + "Mine", + ), ( "another network's lists are not overridden", &[Saved, NetworkSwitch, ListFromBefore("Old")], diff --git a/src/ui/state/contact_detail_view.rs b/src/ui/state/contact_detail_view.rs index 6d94fd1ce..5dada5037 100644 --- a/src/ui/state/contact_detail_view.rs +++ b/src/ui/state/contact_detail_view.rs @@ -11,8 +11,12 @@ use std::collections::HashMap; /// `contactInfo` document, so a contact has at most one at a time. #[derive(Debug, Clone, PartialEq, Eq)] pub enum PendingWrite { - /// A private-note save, with the note that was sent. - Note(Option), + /// A private-note save: the note that was sent, and the stored note the + /// edit started from, which a read lagging behind the save still returns. + Note { + note: Option, + before: Option, + }, /// An unhide. Visibility, } @@ -136,8 +140,11 @@ impl ContactDetailState { ) -> Option> { let draft = self.draft_for(&contact_id)?; let note = normalized_note(&draft.text); - self.begin_write(owner, contact_id, PendingWrite::Note(note.clone())) - .then_some(note) + let write = PendingWrite::Note { + note: note.clone(), + before: draft.baseline.clone(), + }; + self.begin_write(owner, contact_id, write).then_some(note) } /// Claim the write slot for unhiding `contact_id`. `false` when a write to @@ -304,7 +311,10 @@ mod tests { assert_eq!( state.finish_write(&id(1), &id(5)), - Some(PendingWrite::Note(Some("Bao".into()))) + Some(PendingWrite::Note { + note: Some("Bao".into()), + before: None + }) ); assert!(!state.is_writing(&id(1), &id(5))); state.sync(&contact(5, Some("Bao"))); @@ -350,7 +360,10 @@ mod tests { assert!(!state.begin_visibility_write(id(1), id(5))); assert_eq!( state.finish_write(&id(1), &id(5)), - Some(PendingWrite::Note(Some("First note".into()))) + Some(PendingWrite::Note { + note: Some("First note".into()), + before: None + }) ); assert_eq!( state.begin_save(id(1), id(5)), @@ -375,7 +388,10 @@ mod tests { ); assert_eq!( state.finish_write(&id(1), &id(5)), - Some(PendingWrite::Note(Some("Bao".into()))) + Some(PendingWrite::Note { + note: Some("Bao".into()), + before: None + }) ); } } diff --git a/src/ui/state/contacts_view.rs b/src/ui/state/contacts_view.rs index 84230e83f..51507c915 100644 --- a/src/ui/state/contacts_view.rs +++ b/src/ui/state/contacts_view.rs @@ -410,7 +410,7 @@ impl ContactsState { let Some(write) = self.detail.finish_write(owner, contact_id) else { return false; }; - let PendingWrite::Note(note) = write else { + let PendingWrite::Note { note, before } = write else { return true; }; let listed = if self.owner == Some((network, *owner)) { @@ -421,7 +421,13 @@ impl ContactsState { } else { None }; - let lagging = listed.as_ref().map(|contact| contact.note.clone()); + // The list read last, else the note the edit started from: lists of + // another identity are on screen when the save lands. + let lagging = Some( + listed + .as_ref() + .map_or(before, |contact| contact.note.clone()), + ); self.confirmed_notes.insert( (network, *owner, *contact_id), ConfirmedNote { From 27a440f06aa201e97a706e5cd5e09481aee3386a Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:39:31 +0000 Subject: [PATCH 34/73] fix(dashpay): fail a contact details read when the wallet is not loaded dashpay_open_contact_infos turned every wallet-resolution failure (WalletNotLoaded, WalletLockedNotLoaded, WalletStateInconsistent) into an empty "nothing published" result. A save reads that result for each field it keeps, so a note-only edit could publish an empty nickname and hidden = false if the wallet became available before the write. Propagate the error. The save stops before publishing; the contacts list already degrades an unreadable published read to an empty map. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/wallet_backend/contact_info.rs | 44 ++++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/src/wallet_backend/contact_info.rs b/src/wallet_backend/contact_info.rs index 35776b1e1..ee9c09cb4 100644 --- a/src/wallet_backend/contact_info.rs +++ b/src/wallet_backend/contact_info.rs @@ -160,8 +160,10 @@ impl WalletBackend { /// /// # Errors /// - /// The seed could not be used, for example because the password prompt - /// was cancelled. + /// The identity's wallet is not loaded or not registered + /// ([`TaskError::WalletNotLoaded`], [`TaskError::WalletLockedNotLoaded`], + /// [`TaskError::WalletStateInconsistent`]), or the seed could not be used, + /// for example because the password prompt was cancelled. pub(crate) async fn dashpay_open_contact_infos( &self, identity: &QualifiedIdentity, @@ -173,9 +175,10 @@ impl WalletBackend { let Some(seed_hash) = identity.dashpay_wallet_seed_hash() else { return Ok(BTreeMap::new()); }; - let Ok(wallet) = self.resolve_wallet(&seed_hash).await else { - return Ok(BTreeMap::new()); - }; + // A wallet that cannot be resolved is an error: a save keeps every + // field it does not replace from this read, so an empty result here + // would publish empty fields. Display callers degrade explicitly. + let wallet = self.resolve_wallet(&seed_hash).await?; let owner = identity.identity.id(); let identity_index = { let state = wallet.state().await; @@ -664,6 +667,37 @@ mod tests { assert_eq!(contact_info_write_index(Some(3), true).expect("index"), 3); } + /// PRRT_kwDOM8GK3c6vvZQ5: an identity whose wallet cannot be resolved is + /// an error, not "no details published". A save reads this baseline for + /// every field it keeps, so an empty one would publish empty fields. + #[tokio::test] + async fn an_unresolved_wallet_is_an_error_not_an_empty_baseline() { + use crate::model::wallet::Wallet as DetWallet; + use std::sync::RwLock; + let dir = tempfile::tempdir().expect("temp dir"); + let context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = context.wallet_backend().expect("backend wired"); + let wallet = DetWallet::new_from_seed(SEED, NETWORK, None, None).expect("wallet"); + let mut identity = + crate::context::test_support::bare_user_identity(Identifier::from([5; 32]), NETWORK); + identity.associated_wallets = + BTreeMap::from([(wallet.seed_hash(), Arc::new(RwLock::new(wallet)))]); + let crypto = ContactInfoCrypto::new(&SEED, NETWORK, IDENTITY_INDEX); + let sealed = crypto + .contact_info_seal(&root(IDENTITY_INDEX, 2), 0, &[7; 32], b"", &[0; 16]) + .await + .expect("seal"); + + let result = backend + .dashpay_open_contact_infos(&identity, &[stored_document(1, 2, 0, &sealed)]) + .await; + + assert!( + matches!(result, Err(TaskError::WalletNotLoaded { .. })), + "{result:?}" + ); + } + /// Everything other than contactInfo is refused rather than served. #[tokio::test] async fn other_crypto_requests_are_refused() { From 46d868ee3dd929f3101042775bc9c542192a9edb Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:44:35 +0000 Subject: [PATCH 35/73] fix(dashpay): save only the edited fields from the contact details screen The legacy contact details screen opens from this device's copy of the nickname, note and hidden flag, which can be older than what another device or the Identity Hub published, and saved a replacement of all three. Editing one field republished the stale local values of the other two. Remember the details the editor opened with and replace only the fields the user changed (ContactInfoUpdate::edits). The backend fills every preserved field from the published contactInfo, as the Identity Hub's field-level saves already do. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/model/dashpay.rs | 55 ++++++++++++++++ src/ui/dashpay/contact_details.rs | 104 ++++++++++++++++++++++++++---- 2 files changed, 145 insertions(+), 14 deletions(-) diff --git a/src/model/dashpay.rs b/src/model/dashpay.rs index 2cd1949a6..bcfad821e 100644 --- a/src/model/dashpay.rs +++ b/src/model/dashpay.rs @@ -165,6 +165,28 @@ impl ContactInfoUpdate { } } + /// Replace only the fields that differ between `opened`, the details an + /// editor started from, and `edited`, what the user left in it; every + /// other field keeps the latest saved value. + /// + /// An editor that starts from a local copy must save this way: replacing + /// a field the user did not touch would overwrite a newer value saved + /// from another device with the local copy's older one. + pub fn edits(opened: &ContactDetails, edited: ContactDetails) -> Self { + fn field(opened: &T, edited: T) -> ContactInfoField { + if *opened == edited { + ContactInfoField::Preserve + } else { + ContactInfoField::Replace(edited) + } + } + Self { + nickname: field(&opened.nickname, edited.nickname), + note: field(&opened.note, edited.note), + display_hidden: field(&opened.hidden, edited.hidden), + } + } + /// The details to save: `current` with this update's replacements. pub fn apply_to(&self, current: ContactDetails) -> ContactDetails { fn pick(field: &ContactInfoField, current: T) -> T { @@ -552,6 +574,39 @@ mod tests { ); } + /// Only the fields an editor changed are replaced. + #[test] + fn edits_replace_only_the_changed_fields() { + let opened = ContactDetails { + nickname: Some("Bao".into()), + note: None, + hidden: false, + }; + assert_eq!( + ContactInfoUpdate::edits(&opened, opened.clone()), + ContactInfoUpdate { + nickname: ContactInfoField::Preserve, + note: ContactInfoField::Preserve, + display_hidden: ContactInfoField::Preserve, + } + ); + assert_eq!( + ContactInfoUpdate::edits( + &opened, + ContactDetails { + nickname: None, + note: Some("n".into()), + hidden: false, + } + ), + ContactInfoUpdate { + nickname: ContactInfoField::Replace(None), + note: ContactInfoField::Replace(Some("n".into())), + display_hidden: ContactInfoField::Preserve, + } + ); + } + #[test] fn contact_request_recipient_reads_the_to_user_id() { assert_eq!( diff --git a/src/ui/dashpay/contact_details.rs b/src/ui/dashpay/contact_details.rs index 4a9e3cfdc..4a6f2d344 100644 --- a/src/ui/dashpay/contact_details.rs +++ b/src/ui/dashpay/contact_details.rs @@ -4,7 +4,7 @@ use crate::backend_task::error::TaskError; use crate::backend_task::{BackendTask, BackendTaskSuccessResult}; use crate::context::AppContext; use crate::context::feature_gate::FeatureGate; -use crate::model::dashpay::{ContactInfoField, ContactInfoUpdate}; +use crate::model::dashpay::{ContactDetails, ContactInfoField, ContactInfoUpdate}; use crate::model::fee_estimation::format_duffs_as_dash; use crate::model::qualified_identity::QualifiedIdentity; use crate::ui::components::MessageBanner; @@ -63,6 +63,9 @@ pub struct ContactDetailsScreen { edit_nickname: String, edit_note: String, edit_hidden: bool, + /// The details the editor opened with, so a save replaces only the + /// fields the user changed. + edit_opened: ContactDetails, loading: bool, show_info_popup: bool, needs_backend_fetch: bool, @@ -85,6 +88,7 @@ impl ContactDetailsScreen { edit_nickname: String::new(), edit_note: String::new(), edit_hidden: false, + edit_opened: ContactDetails::default(), loading: false, show_info_popup: false, needs_backend_fetch: true, @@ -167,24 +171,27 @@ impl ContactDetailsScreen { self.edit_nickname = info.nickname.clone().unwrap_or_default(); self.edit_note = info.note.clone().unwrap_or_default(); self.edit_hidden = info.is_hidden; + self.edit_opened = ContactDetails { + nickname: info.nickname.clone(), + note: info.note.clone(), + hidden: info.is_hidden, + }; self.editing_info = true; } } fn save_contact_info(&mut self) -> AppAction { - let update = ContactInfoUpdate { - nickname: ContactInfoField::Replace(if self.edit_nickname.is_empty() { - None - } else { - Some(self.edit_nickname.clone()) - }), - note: ContactInfoField::Replace(if self.edit_note.is_empty() { - None - } else { - Some(self.edit_note.clone()) - }), - display_hidden: ContactInfoField::Replace(self.edit_hidden), - }; + let non_empty = |text: &str| (!text.is_empty()).then(|| text.to_string()); + // The editor opens from this device's copy, which can be older than + // the published details; untouched fields keep the published ones. + let update = ContactInfoUpdate::edits( + &self.edit_opened, + ContactDetails { + nickname: non_empty(&self.edit_nickname), + note: non_empty(&self.edit_note), + hidden: self.edit_hidden, + }, + ); self.pending_update = Some(update.clone()); self.loading = true; @@ -721,3 +728,72 @@ impl ScreenLike for ContactDetailsScreen { false } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::context::test_support::{bare_user_identity, test_app_context}; + use dash_sdk::dpp::dashcore::Network; + + fn dispatched_update(action: AppAction) -> ContactInfoUpdate { + match action { + AppAction::BackendTask(BackendTask::DashPayTask(task)) => match *task { + DashPayTask::UpdateContactInfo { update, .. } => update, + other => panic!("expected UpdateContactInfo, got {other:?}"), + }, + _ => panic!("expected a DashPay backend task"), + } + } + + /// This screen opens from this device's copy of the details, which can be + /// older than what another device or the Identity Hub published. Saving + /// an edited note must keep the published nickname and visibility rather + /// than republish the stale local ones. + #[test] + fn saving_one_edited_field_keeps_the_published_others() { + let dir = tempfile::tempdir().expect("temp dir"); + let context = test_app_context(dir.path()); + let identity = bare_user_identity(Identifier::from([1; 32]), Network::Testnet); + let mut screen = ContactDetailsScreen::new(context, identity, Identifier::from([2; 32])); + + screen.start_editing(); + screen.edit_note = "Met at the meetup".to_string(); + let update = dispatched_update(screen.save_contact_info()); + + assert_eq!( + update, + ContactInfoUpdate { + nickname: ContactInfoField::Preserve, + note: ContactInfoField::Replace(Some("Met at the meetup".into())), + display_hidden: ContactInfoField::Preserve, + } + ); + } + + /// Clearing a field is an edit too: it is sent as a replacement with no + /// value, not dropped. + #[test] + fn clearing_and_hiding_are_sent_as_edits() { + let dir = tempfile::tempdir().expect("temp dir"); + let context = test_app_context(dir.path()); + let identity = bare_user_identity(Identifier::from([1; 32]), Network::Testnet); + let mut screen = ContactDetailsScreen::new(context, identity, Identifier::from([2; 32])); + if let Some(info) = &mut screen.contact_info { + info.nickname = Some("Bao".into()); + } + + screen.start_editing(); + screen.edit_nickname.clear(); + screen.edit_hidden = true; + let update = dispatched_update(screen.save_contact_info()); + + assert_eq!( + update, + ContactInfoUpdate { + nickname: ContactInfoField::Replace(None), + note: ContactInfoField::Preserve, + display_hidden: ContactInfoField::Replace(true), + } + ); + } +} From 71341fb84354e60eae78cf15b78619c8bebb9af1 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:52:23 +0000 Subject: [PATCH 36/73] fix(dashpay): hide withdrawn requests from the offline contacts list load_contacts_offline, which the DashPay Contacts screen reads after a restart, listed every sent request from platform-wallet without checking the withdrawal marker, so a request withdrawn on this device came back as a pending contact. The network list already hides it. Skip withdrawn peers in load_contacts_offline. DashpayView::contacts is left unfiltered: its other callers register contact payment addresses and must keep every contact. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contacts.rs | 78 ++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index bf8e77ad1..dfb6caa69 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -628,6 +628,13 @@ pub async fn load_contacts_offline( if contact_id == owner_id { continue; } + // A withdrawn request stays hidden, as in the network list + // (`mutual_contacts`). Filtered here rather than in + // `DashpayView::contacts`, whose other callers register payment + // addresses and must keep every contact. + if backend.dashpay_is_withdrawn(&owner_id, &contact_id) { + continue; + } let cached = backend.contact_profile_cache().get(&contact_id); let memo = backend @@ -707,6 +714,77 @@ fn cache_contact_profiles(app_context: &Arc, contacts: &[ContactData mod tests { use super::*; + /// After a restart the contacts list is built offline; a request the + /// owner withdrew stays hidden there, as it does in the network list. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn the_offline_list_hides_a_withdrawn_request() { + use crate::model::wallet::Wallet; + use crate::model::wallet::birth_height::WalletOrigin; + use dash_sdk::dpp::dashcore::Network; + use dash_sdk::dpp::identity::Identity; + use dash_sdk::dpp::version::PlatformVersion; + + let dir = tempfile::tempdir().expect("temp dir"); + let context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = context.wallet_backend().expect("backend wired"); + let seed = [0x3Cu8; 64]; + let wallet = + Wallet::new_from_seed(seed, Network::Testnet, Some("w".into()), None).expect("wallet"); + let (seed_hash, wallet) = context + .register_wallet(wallet, &seed, WalletOrigin::Fresh) + .expect("register wallet"); + backend + .register_wallet_from_seed(&seed_hash, &seed, Some(0)) + .await + .expect("register upstream"); + let owner = Identifier::from([0x11; 32]); + let withdrawn = Identifier::from([0x22; 32]); + let pending = Identifier::from([0x33; 32]); + let identity = + Identity::create_basic_identity(owner, PlatformVersion::latest()).expect("identity"); + backend + .ensure_identity_managed(&seed_hash, &identity, 0) + .await + .expect("manage identity"); + for recipient in [withdrawn, pending] { + backend + .record_sent_contact_request( + &seed_hash, + &owner, + platform_wallet::ContactRequest::new( + owner, + recipient, + 0, + 0, + 0, + vec![0u8; 96], + 100_000, + 1, + ), + ) + .await + .expect("record sent request"); + } + backend + .dashpay_mark_withdrawn(&owner, &withdrawn) + .expect("withdraw"); + let mut qualified = + crate::context::test_support::bare_user_identity(owner, Network::Testnet); + qualified.associated_wallets = BTreeMap::from([(seed_hash, wallet)]); + + let result = load_contacts_offline(&context, qualified) + .await + .expect("offline list"); + + let BackendTaskSuccessResult::DashPayContactsWithInfo { contacts, .. } = result else { + panic!("expected DashPayContactsWithInfo, got {result:?}"); + }; + assert_eq!( + contacts.iter().map(|c| c.identity_id).collect::>(), + vec![pending] + ); + } + fn details(note: &str) -> ContactDetails { ContactDetails { nickname: None, From 22cc687a910d6156d32717a0be5df27d84979a52 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 23 Oct 2026 21:02:53 +0000 Subject: [PATCH 37/73] fix(dashpay): report a sent contact request this device could not finish After a contact request was published, failures clearing the old decline or withdrawal markers, or lifting platform-wallet's ignore, were only debug-logged and the send reported success. The person could stay hidden on this device, including after a restart, with no way to retry. Re-engage through the same steps as a restore (lift the ignore first, then clear the markers) and report a failure as the new TaskError::DashPayContactRequestSentNotUpdated, which asks the user to send again. Sending again now also restores the existing request when a decline marker is still standing, so that retry finishes the update without publishing a duplicate. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contact_requests.rs | 102 +++++++++++++++---- src/backend_task/error.rs | 11 ++ src/wallet_backend/dashpay.rs | 11 ++ 3 files changed, 106 insertions(+), 18 deletions(-) diff --git a/src/backend_task/dashpay/contact_requests.rs b/src/backend_task/dashpay/contact_requests.rs index a07a74bee..dab9a73ec 100644 --- a/src/backend_task/dashpay/contact_requests.rs +++ b/src/backend_task/dashpay/contact_requests.rs @@ -304,7 +304,8 @@ pub async fn send_contact_request_with_proof( if !existing.is_empty() { // A withdrawn request still stands on Platform: sending again restores - // it instead of publishing a duplicate. + // it instead of publishing a duplicate. This also finishes a send whose + // re-engagement failed after it was published. if let Ok(backend) = app_context.wallet_backend() && restore_withdrawn_request(&PlatformReEngage { backend: &backend, @@ -631,20 +632,12 @@ pub async fn send_contact_request_with_proof( // Sending to someone retires an earlier decline of their request and an // earlier withdrawal of ours: the user has deliberately re-engaged, so // neither direction may stay filtered out of the list. - // Both markers are cleared unconditionally — a failure on one must not - // leave the other standing. - let declined = backend.dashpay_unmark_declined(&owner_id, &to_identity_id); - let withdrawn = backend.dashpay_unmark_withdrawn(&owner_id, &to_identity_id); - let ignored = backend - .dashpay_unignore_contact_sender(&owner_id, &to_identity_id) - .await; - if let Err(err) = declined.and(withdrawn).and(ignored) { - tracing::debug!( - %err, - "Clearing the stale resolution markers failed; an earlier declined or \ - withdrawn request involving this person may stay hidden", - ); - } + re_engage_after_send(&PlatformReEngage { + backend: &backend, + owner: owner_id, + peer: to_identity_id, + }) + .await?; } Ok(BackendTaskSuccessResult::DashPayContactRequestSent( @@ -829,20 +822,44 @@ trait ReEngageOps { /// /// The withdrawal record could not be read. fn is_withdrawn(&self) -> Result; + /// # Errors + /// + /// The decline record could not be read. + fn is_declined(&self) -> Result; /// Lift the ignore and clear the withdrawal and decline markers. fn re_engage(&self) -> impl Future> + Send; } -/// Restore a withdrawn request the owner sent earlier, which still stands on -/// Platform; returns whether there was one. Nothing is published. +/// Restore a request the owner sent earlier, which still stands on Platform, +/// when this device still hides the person; returns whether it did. Nothing +/// is published. +/// +/// The person is hidden after a withdrawal, or after a decline that a send +/// could not clear (see [`re_engage_after_send`]), so sending again retries. async fn restore_withdrawn_request(ops: &O) -> Result { - if !ops.is_withdrawn()? { + if !(ops.is_withdrawn()? || ops.is_declined()?) { return Ok(false); } ops.re_engage().await?; Ok(true) } +/// Re-engage the recipient of a request that was just published. +/// +/// # Errors +/// +/// [`TaskError::DashPayContactRequestSentNotUpdated`] when this device could +/// not be updated. The ignore is lifted before the markers are cleared, so a +/// failure leaves a marker standing and sending again finishes the update +/// through [`restore_withdrawn_request`]. +async fn re_engage_after_send(ops: &O) -> Result<(), TaskError> { + ops.re_engage() + .await + .map_err(|source| TaskError::DashPayContactRequestSentNotUpdated { + source: Box::new(source), + }) +} + struct PlatformReEngage<'a> { backend: &'a crate::wallet_backend::WalletBackend, owner: Identifier, @@ -855,6 +872,11 @@ impl ReEngageOps for PlatformReEngage<'_> { .dashpay_withdrawal_recorded(&self.owner, &self.peer) } + fn is_declined(&self) -> Result { + self.backend + .dashpay_decline_recorded(&self.owner, &self.peer) + } + async fn re_engage(&self) -> Result<(), TaskError> { // The ignore first: the withdrawal keeps the person out of the lists // until it is lifted, so a failure here leaves a retry possible. @@ -1366,7 +1388,9 @@ mod tests { #[derive(Default)] struct ScriptedReEngage { withdrawn: bool, + declined: bool, unreadable: bool, + re_engage_fails: bool, re_engaged: std::sync::Mutex, } @@ -1380,12 +1404,54 @@ mod tests { Ok(self.withdrawn) } + fn is_declined(&self) -> Result { + Ok(self.declined) + } + async fn re_engage(&self) -> Result<(), TaskError> { + if self.re_engage_fails { + return Err(TaskError::DashpaySidecarStorage { + source: crate::wallet_backend::KvAdapterError::Truncated, + }); + } *self.re_engaged.lock().unwrap() = true; Ok(()) } } + /// A send that reached Platform but could not update this device is + /// reported, not shown as complete: the person could stay hidden here. + #[tokio::test] + async fn a_failed_re_engagement_after_a_send_is_reported() { + let ops = ScriptedReEngage { + re_engage_fails: true, + ..Default::default() + }; + + assert!(matches!( + re_engage_after_send(&ops).await, + Err(TaskError::DashPayContactRequestSentNotUpdated { .. }) + )); + assert!( + re_engage_after_send(&ScriptedReEngage::default()) + .await + .is_ok() + ); + } + + /// Sending again retries a re-engagement a failed send left unfinished: + /// the decline it did not clear is cleared now, with nothing published. + #[tokio::test] + async fn a_decline_left_by_a_failed_send_is_retried_on_the_next_send() { + let ops = ScriptedReEngage { + declined: true, + ..Default::default() + }; + + assert!(restore_withdrawn_request(&ops).await.expect("restored")); + assert!(*ops.re_engaged.lock().unwrap()); + } + /// PRRT_kwDOM8GK3c6vWRKe: accepting (or sending again) where the owner's /// withdrawn request still stands restores it without a new publish. #[tokio::test] diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 0f3e7f1c4..dc838fba5 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -1365,6 +1365,17 @@ pub enum TaskError { source: crate::wallet_backend::KvAdapterError, }, + /// A contact request was published, but this device could not stop + /// hiding the person it was sent to (an earlier decline or withdrawal). + /// Sending the request again finishes the update without publishing. + #[error( + "Your contact request was sent, but this device could not update your contacts. Send the request to this person again to finish." + )] + DashPayContactRequestSentNotUpdated { + #[source] + source: Box, + }, + /// A private contact note exceeds the application's byte limit. #[error("This note is too long. Shorten it to save it.")] DashPayContactNoteTooLong { diff --git a/src/wallet_backend/dashpay.rs b/src/wallet_backend/dashpay.rs index 2969123d2..8706f59ac 100644 --- a/src/wallet_backend/dashpay.rs +++ b/src/wallet_backend/dashpay.rs @@ -1267,6 +1267,17 @@ impl WalletBackend { kv_contains(&self.kv(), owner, KV_PREFIX_DECLINED, counterparty_id) } + /// [`Self::dashpay_is_declined`] for a decision that changes state: a + /// failed read is an error, not "not declined". + pub(crate) fn dashpay_decline_recorded( + &self, + owner: &Identifier, + counterparty_id: &Identifier, + ) -> Result { + kv_marker_present(&self.kv(), owner, KV_PREFIX_DECLINED, counterparty_id) + .map_err(|source| TaskError::DashPayLocalStateRead { source }) + } + /// Clear `owner`'s decline marker for `counterparty_id`. Idempotent — /// clearing an absent marker is `Ok(())`. /// From 0180288061dac02df0600eb8139418b6f8b28e19 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 23 Oct 2026 21:03:05 +0000 Subject: [PATCH 38/73] docs(dashpay): tag the contactInfo reader TODO with its upstream request The host-side contactInfo reader stands in for a platform-wallet operation that does not exist yet. Name the drafted upstream request (dip15-contactinfo-reader) and why platform-wallet's own path cannot be used, so the duplicate is removed once it lands. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/wallet_backend/contact_info.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/wallet_backend/contact_info.rs b/src/wallet_backend/contact_info.rs index ee9c09cb4..8b15be373 100644 --- a/src/wallet_backend/contact_info.rs +++ b/src/wallet_backend/contact_info.rs @@ -206,8 +206,10 @@ impl WalletBackend { /// Open `documents` (oldest first) through `crypto`; the newest readable /// document per contact wins. -// TODO: replace with a platform-wallet contactInfo-only read for seedless -// wallets once one exists (upstream issue drafted, not yet filed). +// TODO(upstream): dip15-contactinfo-reader — replace with a platform-wallet +// contactInfo-only, provider-backed read for seedless wallets once one exists; +// platform-wallet's own drain is crate-private and runs unrelated contact work. +// Upstream request drafted, not yet filed. async fn open_contact_info_documents( crypto: &ContactInfoCrypto<'_>, documents: &[Document], From 2810f4e78fbc5fc7d7ee33ad98c0e56d934f42cd Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 23 Oct 2026 22:41:28 +0000 Subject: [PATCH 39/73] docs(dashpay): drop review thread IDs from test comments Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contact_requests.rs | 8 ++++---- src/wallet_backend/contact_info.rs | 2 +- src/wallet_backend/dashpay.rs | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/backend_task/dashpay/contact_requests.rs b/src/backend_task/dashpay/contact_requests.rs index dab9a73ec..702761410 100644 --- a/src/backend_task/dashpay/contact_requests.rs +++ b/src/backend_task/dashpay/contact_requests.rs @@ -1355,7 +1355,7 @@ mod tests { )); } - /// PRRT_kwDOM8GK3c6vWRKJ: after the owner withdraws their request to + /// After the owner withdraws their request to /// id(3), id(3)'s later request is listed for the owner to answer; the /// pair is not taken for a contact and both rows dropped. #[test] @@ -1452,7 +1452,7 @@ mod tests { assert!(*ops.re_engaged.lock().unwrap()); } - /// PRRT_kwDOM8GK3c6vWRKe: accepting (or sending again) where the owner's + /// Accepting (or sending again) where the owner's /// withdrawn request still stands restores it without a new publish. #[tokio::test] async fn an_existing_withdrawn_request_is_restored() { @@ -1472,7 +1472,7 @@ mod tests { assert!(!*pending.re_engaged.lock().unwrap()); } - /// PRRT_kwDOM8GK3c6vbDgP: an unreadable withdrawal record fails the + /// An unreadable withdrawal record fails the /// accept or send instead of reporting success with the withdrawal still /// in force. #[tokio::test] @@ -1625,7 +1625,7 @@ mod tests { } } - /// PRRT_kwDOM8GK3c6vbDgL: the reply is taken in and the contact + /// The reply is taken in and the contact /// established after the reciprocal query; the cancellation then reports /// the contact and records no withdrawal. #[tokio::test] diff --git a/src/wallet_backend/contact_info.rs b/src/wallet_backend/contact_info.rs index 8b15be373..81d01c4c9 100644 --- a/src/wallet_backend/contact_info.rs +++ b/src/wallet_backend/contact_info.rs @@ -669,7 +669,7 @@ mod tests { assert_eq!(contact_info_write_index(Some(3), true).expect("index"), 3); } - /// PRRT_kwDOM8GK3c6vvZQ5: an identity whose wallet cannot be resolved is + /// An identity whose wallet cannot be resolved is /// an error, not "no details published". A save reads this baseline for /// every field it keeps, so an empty one would publish empty fields. #[tokio::test] diff --git a/src/wallet_backend/dashpay.rs b/src/wallet_backend/dashpay.rs index 8706f59ac..2fe526a96 100644 --- a/src/wallet_backend/dashpay.rs +++ b/src/wallet_backend/dashpay.rs @@ -2712,7 +2712,7 @@ mod tests { ); } - /// PRRT_kwDOM8GK3c6vZ6qO / vbDgP: the synced and withdrawn markers are + /// The synced and withdrawn markers are /// read for presence only, so /// a value in an unknown encoding still counts; a failed read is an error. #[test] From 7aadc72e8883afcbb3806750609486547410b916 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:01:39 +0000 Subject: [PATCH 40/73] fix(dashpay): show platform-wallet's contact details in the offline list load_contacts_offline rebuilt each contact's nickname, note and hidden flag from this device's private-info copy only, although platform-wallet holds the details it synced from Platform. After a restart a contact hidden on another device could be listed as visible, or the other way round. Use platform-wallet's details through shown_contact_details, the same precedence the network list uses, with the private-info copy as the fallback for contacts platform-wallet never held details for. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contacts.rs | 120 ++++++++++++++++++++++++--- src/wallet_backend/contact_info.rs | 34 ++++++++ 2 files changed, 141 insertions(+), 13 deletions(-) diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index dfb6caa69..1358a113a 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -601,9 +601,11 @@ pub async fn load_contacts( } /// Read the contact list for `identity` entirely from offline state: contact -/// relationships and private memos come from the upstream-rehydrated -/// `ManagedIdentity` (via [`crate::wallet_backend::DashpayView`]), and each -/// contact's display profile is served from the DET contact-profile cache. +/// relationships and contact details come from the upstream-rehydrated +/// `ManagedIdentity` (via [`crate::wallet_backend::DashpayView`]), with this +/// device's private-info copy as a fallback (see [`shown_contact_details`]), +/// and each contact's display profile is served from the DET contact-profile +/// cache. /// /// No network round-trip — a view rendered from this result does not require /// connectivity. Profiles a contact has not yet been fetched for are returned @@ -617,6 +619,9 @@ pub async fn load_contacts_offline( let backend = app_context.wallet_backend()?; let stored = backend.dashpay_view().contacts(&owner_id).await; + // The details platform-wallet holds win, as in the network list; this + // device's private-info copy only stands in where it never held any. + let mut synced = backend.dashpay_contact_details(&owner_id).await; let mut contact_list = Vec::with_capacity(stored.len()); for sc in stored { @@ -639,19 +644,28 @@ pub async fn load_contacts_offline( let cached = backend.contact_profile_cache().get(&contact_id); let memo = backend .dashpay_get_private_info(&owner_id, &contact_id) - .unwrap_or(None); + .unwrap_or_else(|error| { + tracing::debug!(?error, "LoadContactsOffline: private info not read"); + None + }) + .map(|memo| ContactDetails { + nickname: Some(memo.nickname).filter(|s| !s.is_empty()), + note: Some(memo.notes).filter(|s| !s.is_empty()), + hidden: memo.is_hidden, + }); + let synced_before = backend + .dashpay_details_synced(&owner_id, &contact_id) + .unwrap_or_else(|error| { + tracing::debug!(?error, "LoadContactsOffline: synced record not read"); + false + }); + let details = shown_contact_details(None, synced.remove(&contact_id), synced_before, memo); contact_list.push(ContactData { identity_id: contact_id, - nickname: memo - .as_ref() - .map(|m| m.nickname.clone()) - .filter(|s| !s.is_empty()), - note: memo - .as_ref() - .map(|m| m.notes.clone()) - .filter(|s| !s.is_empty()), - is_hidden: memo.as_ref().map(|m| m.is_hidden).unwrap_or(false), + nickname: details.nickname, + note: details.note, + is_hidden: details.hidden, // Carry the cached account reference so the "Account #N" badge shows // and offline ordering matches the post-refresh view. Falls back to // 0 ("default account") when no network read has cached one yet. @@ -714,6 +728,86 @@ fn cache_contact_profiles(app_context: &Arc, contacts: &[ContactData mod tests { use super::*; + /// After a restart the offline list shows the details platform-wallet + /// holds (synced from Platform) rather than this device's older copy, so + /// a contact hidden on another device is not listed as visible here. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn the_offline_list_shows_platform_wallets_details() { + use crate::model::wallet::Wallet; + use crate::model::wallet::birth_height::WalletOrigin; + use dash_sdk::dpp::dashcore::Network; + use dash_sdk::dpp::identity::Identity; + use dash_sdk::dpp::version::PlatformVersion; + + let dir = tempfile::tempdir().expect("temp dir"); + let context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = context.wallet_backend().expect("backend wired"); + let seed = [0x4Du8; 64]; + let wallet = + Wallet::new_from_seed(seed, Network::Testnet, Some("w".into()), None).expect("wallet"); + let (seed_hash, wallet) = context + .register_wallet(wallet, &seed, WalletOrigin::Fresh) + .expect("register wallet"); + backend + .register_wallet_from_seed(&seed_hash, &seed, Some(0)) + .await + .expect("register upstream"); + let owner = Identifier::from([0x11; 32]); + let contact = Identifier::from([0x22; 32]); + let identity = + Identity::create_basic_identity(owner, PlatformVersion::latest()).expect("identity"); + backend + .ensure_identity_managed(&seed_hash, &identity, 0) + .await + .expect("manage identity"); + let request = |from, to| { + platform_wallet::ContactRequest::new(from, to, 0, 0, 0, vec![0u8; 96], 100_000, 1) + }; + backend + .record_sent_contact_request(&seed_hash, &owner, request(owner, contact)) + .await + .expect("record sent request"); + backend + .record_incoming_contact_request(&seed_hash, &owner, request(contact, owner)) + .await + .expect("record incoming request"); + // This device's older copy. + backend + .dashpay_set_private_info( + &owner, + &contact, + &crate::model::dashpay::ContactPrivateInfo { + nickname: "Old".to_string(), + notes: "old note".to_string(), + is_hidden: false, + }, + ) + .expect("sidecar written"); + let synced = ContactDetails { + nickname: Some("Bao".into()), + note: None, + hidden: true, + }; + backend + .set_contact_details_for_tests(&seed_hash, &owner, &contact, synced.clone()) + .await; + let mut qualified = + crate::context::test_support::bare_user_identity(owner, Network::Testnet); + qualified.associated_wallets = BTreeMap::from([(seed_hash, wallet)]); + + let result = load_contacts_offline(&context, qualified) + .await + .expect("offline list"); + + let BackendTaskSuccessResult::DashPayContactsWithInfo { contacts, .. } = result else { + panic!("expected DashPayContactsWithInfo, got {result:?}"); + }; + let [row] = contacts.as_slice() else { + panic!("expected one contact, got {contacts:?}"); + }; + assert_eq!(row.details(), synced); + } + /// After a restart the contacts list is built offline; a request the /// owner withdrew stays hidden there, as it does in the network list. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] diff --git a/src/wallet_backend/contact_info.rs b/src/wallet_backend/contact_info.rs index 81d01c4c9..e2918db06 100644 --- a/src/wallet_backend/contact_info.rs +++ b/src/wallet_backend/contact_info.rs @@ -151,6 +151,40 @@ impl WalletBackend { } } +#[cfg(test)] +impl WalletBackend { + /// Set the details platform-wallet holds for `contact_id`, as a sync from + /// another device would, without publishing anything. + pub(crate) async fn set_contact_details_for_tests( + &self, + seed_hash: &crate::model::wallet::WalletSeedHash, + owner: &Identifier, + contact_id: &Identifier, + details: ContactDetails, + ) { + use platform_wallet::wallet::identity::crypto::ContactInfoPrivateData; + let wallet = self.resolve_wallet(seed_hash).await.expect("wallet"); + let persister = wallet.persister().clone(); + let mut manager = wallet.wallet_manager().write().await; + let applied = manager + .get_wallet_info_mut(&wallet.wallet_id()) + .and_then(|info| info.identity_manager.managed_identity_mut(owner)) + .expect("managed identity") + .set_contact_metadata( + contact_id, + ContactInfoPrivateData { + alias_name: details.nickname, + note: details.note, + display_hidden: details.hidden, + accepted_accounts: Vec::new(), + }, + &persister, + ) + .expect("metadata saved"); + assert!(applied, "the contact must be established"); + } +} + impl WalletBackend { /// The details `identity`'s DIP-0015 `contactInfo` documents hold, read /// with platform-wallet's keys and codec; `documents` are oldest first and From 548d6c86df245ca91047b5aa21a392e086825138 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Sat, 24 Oct 2026 17:09:19 +0000 Subject: [PATCH 41/73] fix(dashpay): open the contact details editor from the published details The legacy contact details screen read the nickname, note and hidden flag only from this device's private-info copy, so after a restart or an edit on another device it showed, and opened the editor with, stale or empty values. Add DashPayTask::LoadContactDetails, which reads the details with the precedence the save path and the Identity Hub use (published, then platform-wallet's, then a legacy-key document), and send it with the profile fetch when the screen opens. Editing waits for that read; a later refresh of the screen keeps its result. If the read fails the screen keeps this device's copy, and a save still replaces only the edited fields. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay.rs | 10 ++ src/backend_task/dashpay/contact_info.rs | 92 ++++++++++++----- src/backend_task/mod.rs | 6 ++ src/ui/dashpay/contact_details.rs | 125 ++++++++++++++++++++--- 4 files changed, 196 insertions(+), 37 deletions(-) diff --git a/src/backend_task/dashpay.rs b/src/backend_task/dashpay.rs index 27c3f7e3c..4b330618c 100644 --- a/src/backend_task/dashpay.rs +++ b/src/backend_task/dashpay.rs @@ -67,6 +67,12 @@ pub enum DashPayTask { identity: QualifiedIdentity, contact_id: Identifier, }, + /// Read the nickname, note and hidden flag shown for one contact, with + /// the same precedence as the contacts list (published first). + LoadContactDetails { + identity: QualifiedIdentity, + contact_id: Identifier, + }, /// Fetch an avatar image for a URL, consulting and populating the DET avatar /// disk cache. Off the egui frame loop; the result flows back to the /// screen's [`AvatarCache`](crate::ui::state::avatar_cache::AvatarCache). @@ -179,6 +185,10 @@ impl AppContext { identity, contact_id, } => Ok(profile::fetch_contact_profile(self, sdk, identity, contact_id).await?), + DashPayTask::LoadContactDetails { + identity, + contact_id, + } => Ok(contact_info::load_contact_details(self, sdk, identity, contact_id).await?), DashPayTask::FetchAvatar { url } => { let bytes = avatar_processing::fetch_avatar_cached(self, &url).await; Ok(BackendTaskSuccessResult::DashPayAvatar { url, bytes }) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index d64f59e62..bcb84b08a 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -91,6 +91,65 @@ pub async fn create_or_update_contact_info( }) } +/// Read the details shown for `contact_id`, the ones a contact details +/// editor starts from. +/// +/// # Errors +/// +/// As for [`shown_details_for`]. +pub async fn load_contact_details( + app_context: &Arc, + sdk: &Sdk, + identity: QualifiedIdentity, + contact_id: Identifier, +) -> Result { + let backend = app_context.wallet_backend()?; + let details = shown_details_for(app_context, sdk, &backend, &identity, &contact_id).await?; + Ok(BackendTaskSuccessResult::DashPayContactDetails { + identity: identity.identity.id(), + contact_id, + details, + }) +} + +/// The details shown for `contact_id`, with the precedence of +/// [`super::contacts::shown_contact_details`]: published, then +/// platform-wallet's on this device, then a legacy-key document. +/// +/// # Errors +/// +/// Fails when the details sync, the document fetch, or reading the published +/// or legacy documents fails (a cancelled password prompt included), rather +/// than guessing: a save keeps every field it does not replace from this. +async fn shown_details_for( + app_context: &Arc, + sdk: &Sdk, + backend: &WalletBackend, + identity: &QualifiedIdentity, + contact_id: &Identifier, +) -> Result { + let owner = identity.identity.id(); + backend.dashpay_sync_contact_infos(&owner).await?; + let local = backend + .dashpay_contact_details(&owner) + .await + .remove(contact_id); + let stored = super::contacts::stored_contact_details(app_context, sdk, identity).await?; + let published = stored.published?.remove(contact_id); + let legacy = stored.legacy?; + let synced_before = backend.dashpay_details_synced(&owner, contact_id)? + || super::contacts::holds_details(published.as_ref(), local.as_ref()); + let legacy = legacy + .get(contact_id) + .map(super::contacts::ContactData::details); + Ok(super::contacts::shown_contact_details( + published, + local, + synced_before, + legacy, + )) +} + /// The reads and writes one contact details save performs, behind a trait so /// their order and failures can be driven in tests. trait SaveOps { @@ -154,31 +213,14 @@ struct PlatformSaveOps<'a> { impl SaveOps for PlatformSaveOps<'_> { async fn current(&self) -> Result { - let owner = self.identity.identity.id(); - self.backend.dashpay_sync_contact_infos(&owner).await?; - let local = self - .backend - .dashpay_contact_details(&owner) - .await - .remove(&self.contact_id); - let stored = - super::contacts::stored_contact_details(self.app_context, self.sdk, self.identity) - .await?; - let published = stored.published?.remove(&self.contact_id); - let legacy = stored.legacy?; - let synced_before = self - .backend - .dashpay_details_synced(&owner, &self.contact_id)? - || super::contacts::holds_details(published.as_ref(), local.as_ref()); - let legacy = legacy - .get(&self.contact_id) - .map(super::contacts::ContactData::details); - Ok(super::contacts::shown_contact_details( - published, - local, - synced_before, - legacy, - )) + shown_details_for( + self.app_context, + self.sdk, + &self.backend, + self.identity, + &self.contact_id, + ) + .await } async fn publish( diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index 23ce417df..fcf931941 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -903,6 +903,12 @@ pub enum BackendTaskSuccessResult { request_id: Identifier, contact_id: Identifier, }, + /// The details shown for one contact; see `DashPayTask::LoadContactDetails`. + DashPayContactDetails { + identity: Identifier, + contact_id: Identifier, + details: crate::model::dashpay::ContactDetails, + }, DashPayContactInfoUpdated { /// Identity that owns the encrypted `contactInfo` document. identity: Identifier, diff --git a/src/ui/dashpay/contact_details.rs b/src/ui/dashpay/contact_details.rs index 4a6f2d344..1663ee1fb 100644 --- a/src/ui/dashpay/contact_details.rs +++ b/src/ui/dashpay/contact_details.rs @@ -1,4 +1,4 @@ -use crate::app::AppAction; +use crate::app::{AppAction, BackendTasksExecutionMode}; use crate::backend_task::dashpay::DashPayTask; use crate::backend_task::error::TaskError; use crate::backend_task::{BackendTask, BackendTaskSuccessResult}; @@ -67,6 +67,12 @@ pub struct ContactDetailsScreen { /// fields the user changed. edit_opened: ContactDetails, loading: bool, + /// The details read is running; editing waits for it so the editor opens + /// from the published details rather than this device's copy. + details_loading: bool, + /// `contact_info`'s nickname, note and hidden flag came from the details + /// read, so a reread of this device's copy keeps them. + details_read: bool, show_info_popup: bool, needs_backend_fetch: bool, pending_update: Option, @@ -90,6 +96,8 @@ impl ContactDetailsScreen { edit_hidden: false, edit_opened: ContactDetails::default(), loading: false, + details_loading: false, + details_read: false, show_info_popup: false, needs_backend_fetch: true, pending_update: None, @@ -98,9 +106,11 @@ impl ContactDetailsScreen { screen } - /// Initialise `contact_info` from local-only data (private notes / hidden flag). - /// Public profile fields (username, display_name, avatar, bio) are populated - /// asynchronously by `FetchContactProfile` — see `display_task_result`. + /// Initialise `contact_info` from this device's copy of the nickname, note + /// and hidden flag, until `LoadContactDetails` returns the details shown + /// everywhere else. Public profile fields (username, display_name, avatar, + /// bio) are populated asynchronously by `FetchContactProfile` — see + /// `display_task_result`. fn load_from_database(&mut self) { let identity_id = self.identity.identity.id(); @@ -126,6 +136,15 @@ impl ContactDetailsScreen { Some(nickname) }; let note = if note.is_empty() { None } else { Some(note) }; + // Details read from the backend outrank this device's copy. + let (nickname, note, is_hidden) = match self.contact_info.as_ref() { + Some(existing) if self.details_read => ( + existing.nickname.clone(), + existing.note.clone(), + existing.is_hidden, + ), + _ => (nickname, note, is_hidden), + }; // Preserve any public profile fields already in `contact_info`; otherwise // start empty and let the async fetch fill them in. @@ -154,19 +173,32 @@ impl ContactDetailsScreen { }); } - /// Trigger a backend fetch to refresh contact profile data from Platform. + /// Trigger backend reads of the contact's public profile and of the + /// details shown for it (published first; see `LoadContactDetails`). fn trigger_backend_fetch(&mut self) -> AppAction { self.loading = true; + self.details_loading = true; - AppAction::BackendTask(BackendTask::DashPayTask(Box::new( - DashPayTask::FetchContactProfile { - identity: self.identity.clone(), - contact_id: self.contact_id, - }, - ))) + let task = |task| BackendTask::DashPayTask(Box::new(task)); + AppAction::BackendTasks( + vec![ + task(DashPayTask::FetchContactProfile { + identity: self.identity.clone(), + contact_id: self.contact_id, + }), + task(DashPayTask::LoadContactDetails { + identity: self.identity.clone(), + contact_id: self.contact_id, + }), + ], + BackendTasksExecutionMode::Concurrent, + ) } fn start_editing(&mut self) { + if self.details_loading { + return; + } if let Some(info) = &self.contact_info { self.edit_nickname = info.nickname.clone().unwrap_or_default(); self.edit_note = info.note.clone().unwrap_or_default(); @@ -366,7 +398,10 @@ impl ContactDetailsScreen { if ui.button("Save").clicked() { action = self.save_contact_info(); } - } else if ui.button("Edit").clicked() { + } else if ui + .add_enabled(!self.details_loading, egui::Button::new("Edit")) + .clicked() + { self.start_editing(); } }); @@ -597,13 +632,31 @@ impl ScreenLike for ContactDetailsScreen { fn display_message(&mut self, _message: &str, _message_type: MessageType) { // Banner display is handled globally by AppState; this is only for side-effects. + // A failed read leaves this device's copy in place; a save from it + // still replaces only the fields the user edits. self.loading = false; + self.details_loading = false; } fn display_task_result(&mut self, result: BackendTaskSuccessResult) { self.loading = false; match result { + BackendTaskSuccessResult::DashPayContactDetails { + identity, + contact_id, + details, + } => { + if identity == self.identity.identity.id() && contact_id == self.contact_id { + self.details_loading = false; + self.details_read = true; + if let Some(info) = &mut self.contact_info { + info.nickname = details.nickname; + info.note = details.note; + info.is_hidden = details.hidden; + } + } + } BackendTaskSuccessResult::DashPayContactProfile(Some(doc)) => { // Update contact info with fresh profile data from Platform use dash_sdk::dpp::document::DocumentV0Getters; @@ -770,6 +823,54 @@ mod tests { ); } + /// The editor opens from the details shown for the contact everywhere + /// else (published first), read by the backend when the screen opens, + /// not from this device's older copy. It stays closed until that read + /// returns. + #[test] + fn the_editor_opens_from_the_published_details() { + let dir = tempfile::tempdir().expect("temp dir"); + let context = test_app_context(dir.path()); + let owner = Identifier::from([1; 32]); + let contact = Identifier::from([2; 32]); + let identity = bare_user_identity(owner, Network::Testnet); + let mut screen = ContactDetailsScreen::new(context, identity, contact); + + let AppAction::BackendTasks(tasks, _) = screen.trigger_backend_fetch() else { + panic!("expected the profile and details reads"); + }; + assert!(tasks.iter().any(|task| matches!( + task, + BackendTask::DashPayTask(task) if matches!( + task.as_ref(), + DashPayTask::LoadContactDetails { contact_id, .. } if *contact_id == contact + ) + ))); + screen.start_editing(); + assert!( + !screen.editing_info, + "the editor waits for the details read" + ); + + screen.display_task_result(BackendTaskSuccessResult::DashPayContactDetails { + identity: owner, + contact_id: contact, + details: ContactDetails { + nickname: Some("Bao".into()), + note: Some("published".into()), + hidden: true, + }, + }); + // A refresh rereads this device's copy, which must not replace them. + screen.refresh(); + screen.start_editing(); + + assert!(screen.editing_info); + assert_eq!(screen.edit_nickname, "Bao"); + assert_eq!(screen.edit_note, "published"); + assert!(screen.edit_hidden); + } + /// Clearing a field is an edit too: it is sent as a replacement with no /// value, not dropped. #[test] From ee5c16d8997fff32590e250aa2a3c9e6281adb09 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:02:19 +0000 Subject: [PATCH 42/73] fix(dashpay): keep contact details editing closed until its own read ends Contact Details dispatches the profile read and the details read together, and display_message cleared details_loading for any failure. A failed profile read could open the editor from this device's older copy while the published details were still loading. LoadContactDetails now carries its own BackendTaskContext, and the screen reopens the editor only when that read fails or returns. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/mod.rs | 23 ++++++++++ src/ui/dashpay/contact_details.rs | 70 +++++++++++++++++++++++++++++-- 2 files changed, 89 insertions(+), 4 deletions(-) diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index 0d95fdfc3..42196d24a 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -354,6 +354,11 @@ pub enum BackendTaskContext { identity_id: Identifier, contact_id: Identifier, }, + /// A read of the details shown for one contact. + DashPayContactDetailsLoad { + identity_id: Identifier, + contact_id: Identifier, + }, /// A read of an identity's contacts or contact requests. DashPayContactsLoad { network: Network, @@ -565,6 +570,17 @@ impl BackendTaskContext { } } + /// Identify a contact-details read through dispatch wrappers. + pub(crate) fn dashpay_contact_details_target(&self) -> Option<(Identifier, Identifier)> { + match self.operation() { + Self::DashPayContactDetailsLoad { + identity_id, + contact_id, + } => Some((*identity_id, *contact_id)), + _ => None, + } + } + pub(crate) fn dashpay_profile_update_identity(&self) -> Option { match self.operation() { Self::DashPayProfileUpdate(identity_id) => Some(*identity_id), @@ -697,6 +713,13 @@ impl From<&BackendTask> for BackendTaskContext { identity_id: identity.identity.id(), kind: crate::model::dashpay::ContactsLoadKind::Requests, }, + DashPayTask::LoadContactDetails { + identity, + contact_id, + } => Self::DashPayContactDetailsLoad { + identity_id: identity.identity.id(), + contact_id: *contact_id, + }, DashPayTask::UpdateProfile { identity, .. } => { Self::DashPayProfileUpdate(identity.identity.id()) } diff --git a/src/ui/dashpay/contact_details.rs b/src/ui/dashpay/contact_details.rs index 1663ee1fb..91b06b2c7 100644 --- a/src/ui/dashpay/contact_details.rs +++ b/src/ui/dashpay/contact_details.rs @@ -1,7 +1,7 @@ use crate::app::{AppAction, BackendTasksExecutionMode}; use crate::backend_task::dashpay::DashPayTask; use crate::backend_task::error::TaskError; -use crate::backend_task::{BackendTask, BackendTaskSuccessResult}; +use crate::backend_task::{BackendTask, BackendTaskContext, BackendTaskSuccessResult}; use crate::context::AppContext; use crate::context::feature_gate::FeatureGate; use crate::model::dashpay::{ContactDetails, ContactInfoField, ContactInfoUpdate}; @@ -632,10 +632,19 @@ impl ScreenLike for ContactDetailsScreen { fn display_message(&mut self, _message: &str, _message_type: MessageType) { // Banner display is handled globally by AppState; this is only for side-effects. - // A failed read leaves this device's copy in place; a save from it - // still replaces only the fields the user edits. self.loading = false; - self.details_loading = false; + } + + fn display_backend_task_error(&mut self, context: &BackendTaskContext, _error: &TaskError) { + // Only this screen's own details read reopens the editor: a failed + // profile read must not unlock it from this device's older copy while + // the details read is still pending. A failed details read leaves that + // copy in place; a save from it still replaces only the edited fields. + if context.dashpay_contact_details_target() + == Some((self.identity.identity.id(), self.contact_id)) + { + self.details_loading = false; + } } fn display_task_result(&mut self, result: BackendTaskSuccessResult) { @@ -871,6 +880,59 @@ mod tests { assert!(screen.edit_hidden); } + /// A failed profile read does not open the editor while the details read + /// is still pending; only the details read's own failure does, leaving + /// this device's copy in place. + #[test] + fn a_failed_profile_read_keeps_the_editor_closed_until_the_details_read_ends() { + let dir = tempfile::tempdir().expect("temp dir"); + let context = test_app_context(dir.path()); + let owner = Identifier::from([1; 32]); + let contact = Identifier::from([2; 32]); + let identity = bare_user_identity(owner, Network::Testnet); + let mut screen = ContactDetailsScreen::new(context, identity, contact); + + let AppAction::BackendTasks(tasks, _) = screen.trigger_backend_fetch() else { + panic!("expected the profile and details reads"); + }; + let is_details_read = |task: &BackendTask| { + matches!( + task, + BackendTask::DashPayTask(task) + if matches!(task.as_ref(), DashPayTask::LoadContactDetails { .. }) + ) + }; + let profile = tasks + .iter() + .find(|task| !is_details_read(task)) + .expect("profile read"); + let details = tasks + .iter() + .find(|task| is_details_read(task)) + .expect("details read"); + // What AppState delivers for a failure the screen does not handle. + let fail = |screen: &mut ContactDetailsScreen, task: &BackendTask| { + let error = TaskError::ContactWalletSeedUnavailable; + screen.display_backend_task_error(&BackendTaskContext::for_dispatch(task), &error); + assert!(!screen.display_task_error(&error)); + screen.display_message(&error.to_string(), MessageType::Error); + }; + + fail(&mut screen, profile); + screen.start_editing(); + assert!( + !screen.editing_info, + "the editor still waits for the details read" + ); + + fail(&mut screen, details); + screen.start_editing(); + assert!( + screen.editing_info, + "a failed details read opens the editor" + ); + } + /// Clearing a field is an edit too: it is sent as a replacement with no /// value, not dropped. #[test] From 1b354ff5562faa64944d4c2345c6b96785afccf7 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:02:19 +0000 Subject: [PATCH 43/73] fix(dashpay): stop claiming a device-only contact save reached the network A save that platform-wallet defers until a second contact exists publishes nothing. When recording its synced marker then failed, the user saw DashpaySidecarStorage, which says the change reached the network. That save now fails with DashPayContactDetailsNotRecorded, which asks the user to save again. A published save keeps the old message. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contact_info.rs | 49 +++++++++++++++++++++--- src/backend_task/error.rs | 9 +++++ 2 files changed, 53 insertions(+), 5 deletions(-) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 4720a817a..7b7f11ea8 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -191,7 +191,17 @@ async fn save_contact_details( })?; let outcome = ops.publish(details).await?; - ops.mark_synced()?; + match ops.mark_synced() { + Ok(()) => {} + // A deferred save published nothing, so the storage error's claim + // that the change reached the network would be false. + Err(TaskError::DashpaySidecarStorage { source }) + if outcome == ContactInfoPublishOutcome::DeferredUntilTwoContacts => + { + return Err(TaskError::DashPayContactDetailsNotRecorded { source }); + } + Err(error) => return Err(error), + } match outcome { ContactInfoPublishOutcome::Published => Ok(true), ContactInfoPublishOutcome::DeferredUntilTwoContacts => Ok(false), @@ -378,6 +388,7 @@ mod tests { struct ScriptedSave { current: std::sync::Mutex>>, mark_fails: bool, + outcome: ContactInfoPublishOutcome, published: std::sync::Mutex>, } @@ -386,9 +397,15 @@ mod tests { Self { current: std::sync::Mutex::new(Some(current)), mark_fails, + outcome: ContactInfoPublishOutcome::DeferredUntilTwoContacts, published: std::sync::Mutex::new(Vec::new()), } } + + fn with_outcome(mut self, outcome: ContactInfoPublishOutcome) -> Self { + self.outcome = outcome; + self + } } impl SaveOps for ScriptedSave { @@ -401,7 +418,7 @@ mod tests { details: ContactDetails, ) -> Result { self.published.lock().unwrap().push(details); - Ok(ContactInfoPublishOutcome::DeferredUntilTwoContacts) + Ok(self.outcome) } fn mark_synced(&self) -> Result<(), TaskError> { @@ -427,11 +444,13 @@ mod tests { assert!(ops.published.lock().unwrap().is_empty()); } - /// A save whose synced record fails is not reported as saved: on reload - /// the old legacy details would show again. + /// A published save whose synced record fails is not reported as saved: + /// on reload the old legacy details would show again. The details did + /// reach the network, and the error says so. #[tokio::test] async fn a_failed_synced_record_fails_the_save() { - let ops = ScriptedSave::new(Ok(ContactDetails::default()), true); + let ops = ScriptedSave::new(Ok(ContactDetails::default()), true) + .with_outcome(ContactInfoPublishOutcome::Published); let result = save_contact_details(&ops, &ContactInfoUpdate::replace_all(None, None, false)).await; @@ -442,6 +461,26 @@ mod tests { )); } + /// A save kept on this device until a second contact exists published + /// nothing, so a failed synced record must not claim the change reached + /// the network; the user is asked to save again. + #[tokio::test] + async fn a_failed_synced_record_of_a_deferred_save_claims_no_publish() { + let ops = ScriptedSave::new(Ok(ContactDetails::default()), true); + + let result = + save_contact_details(&ops, &ContactInfoUpdate::replace_all(None, None, false)).await; + + let Err(error) = result else { + panic!("a failed synced record fails the save"); + }; + assert!( + matches!(error, TaskError::DashPayContactDetailsNotRecorded { .. }), + "got {error:?}" + ); + assert!(!error.to_string().contains("reached the network")); + } + #[tokio::test] async fn a_save_keeps_the_fields_it_does_not_replace() { let current = ContactDetails { diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 3a21ad698..0ca42673a 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -1459,6 +1459,15 @@ pub enum TaskError { source: crate::wallet_backend::KvAdapterError, }, + /// A contact-details save that stayed on this device, because publishing + /// waits for a second contact, could not record which details this device + /// holds; on reload the older details would show again. + #[error("Could not finish saving your contact details on this device. Try saving them again.")] + DashPayContactDetailsNotRecorded { + #[source] + source: crate::wallet_backend::KvAdapterError, + }, + /// A DashPay record this device keeps (which contact details it holds, /// which requests were withdrawn) could not be read, so an action that /// depends on it cannot tell what to do. From 964d30b661e2709ca82b477cfee23320ac430602 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:01:47 +0000 Subject: [PATCH 44/73] fix(dashpay): read contact details from documents as Platform returns them DPP decodes contactInfo's fixed 32-byte encToUserId as Value::Bytes32, whoever wrote the document, but the contacts load accepted only Value::Bytes. It skipped every fetched document, so saved nicknames, notes and hidden flags never showed. The load now accepts any binary variant. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contact_info.rs | 38 ++++++++++++++++++++++++ src/backend_task/dashpay/contacts.rs | 7 ++++- 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 66fc47b1c..78a1e170c 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -1183,6 +1183,44 @@ mod tests { assert!(ordered, "pages follow the order the write lookup uses"); } + /// A contactInfo document as Platform returns it: DPP decodes the fixed + /// 32-byte `encToUserId` as `Value::Bytes32`, whoever wrote the document. + /// Its saved note must still load. + #[tokio::test] + async fn the_contact_details_load_reads_a_document_as_platform_returns_it() { + use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; + use dash_sdk::dpp::document::serialization_traits::DocumentPlatformConversionMethodsV0; + let platform_version = PlatformVersion::latest(); + let contract = load_system_data_contract(SystemDataContract::Dashpay, platform_version) + .expect("DashPay contract fixture"); + let document_type = contract + .document_type_for_name("contactInfo") + .expect("contactInfo type"); + let contact = id(201); + let mut written = saved_note_document(1, contact, "kept"); + written.set_created_at(Some(1)); + written.set_updated_at(Some(1)); + let bytes = written + .serialize(document_type, &contract, platform_version) + .expect("serialize"); + let returned = + Document::from_bytes(&bytes, document_type, platform_version).expect("deserialize"); + assert!( + matches!( + returned.properties().get("encToUserId"), + Some(Value::Bytes32(_)) + ), + "precondition: Platform returns encToUserId as Bytes32" + ); + + let (details, _) = load_details(vec![contact_details_page([returned])]).await; + + assert_eq!( + details.get(&contact).and_then(|c| c.note.clone()), + Some("kept".to_string()) + ); + } + /// With two documents for one contact, the load shows the one a save /// rewrites: the first in that order. #[tokio::test] diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index 6195813ae..c0a860273 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -163,7 +163,12 @@ where let Ok((enc_user_id_key, private_data_key)) = derive_keys(deriv_idx).await else { continue; }; - let Some(Value::Bytes(enc_user_id)) = props.get("encToUserId") else { + // Platform returns the fixed 32-byte field as `Value::Bytes32`; a + // document built locally carries `Value::Bytes`. + let Some(enc_user_id) = props + .get("encToUserId") + .and_then(|value| value.as_bytes_slice().ok()) + else { continue; }; let Ok(decrypted_id) = decrypt_to_user_id(enc_user_id, &enc_user_id_key) else { From 42e830f0b96a006fa5885aaf34efc29ca16f1396 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:05:01 +0000 Subject: [PATCH 45/73] fix(dashpay): keep contacts with unreadable details hidden and say so When a contactInfo privateData failed to decrypt or decode, the contacts load used empty details. A hidden contact could then reappear in the active list. ContactData now carries details_unreadable. Such a contact stays hidden, and the hub's hidden section explains why under its name. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contact_info.rs | 45 ++++++++++++++++++++ src/backend_task/dashpay/contacts.rs | 27 +++++++++--- src/ui/identity/contacts.rs | 16 +++++++ src/ui/identity/hub_screen.rs | 5 +++ src/ui/state/contact_detail_view.rs | 1 + src/ui/state/contacts_view.rs | 3 ++ tests/kittest/identity_home.rs | 3 ++ tests/kittest/identity_hub.rs | 2 + tests/kittest/identity_hub_contact_detail.rs | 40 +++++++++++++++++ tests/kittest/identity_hub_contacts.rs | 1 + tests/kittest/identity_hub_layout.rs | 1 + 11 files changed, 137 insertions(+), 7 deletions(-) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 78a1e170c..312817105 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -1221,6 +1221,51 @@ mod tests { ); } + /// Stored details that cannot be decrypted or decoded are not "no + /// details": the contact is marked unreadable and kept hidden, since its + /// hidden flag cannot be read. + #[tokio::test] + async fn unreadable_contact_details_keep_the_contact_hidden() { + let undecryptable = id(201); + let undecodable = id(202); + let mut first = lookup_contact_info_document( + 1, + 1, + encrypt_to_user_id(&undecryptable.to_buffer(), &KEY).expect("encrypt"), + ); + first.set("privateData", Value::Bytes(vec![0xA5; 48])); + let mut second = lookup_contact_info_document( + 2, + 2, + encrypt_to_user_id(&undecodable.to_buffer(), &KEY).expect("encrypt"), + ); + second.set( + "privateData", + Value::Bytes(encrypt_private_data(&[0xFF; 40], &KEY).expect("encrypt")), + ); + + let (details, _) = load_details(vec![contact_details_page([first, second])]).await; + + for contact in [undecryptable, undecodable] { + let shown = details.get(&contact).expect("the contact is listed"); + assert!(shown.details_unreadable, "{contact} is marked unreadable"); + assert!(shown.is_hidden, "{contact} stays hidden"); + assert_eq!(shown.note, None); + } + } + + /// Readable details are not marked unreadable. + #[tokio::test] + async fn readable_contact_details_are_not_marked_unreadable() { + let contact = id(201); + let (details, _) = load_details(vec![contact_details_page([saved_note_document( + 1, contact, "n", + )])]) + .await; + + assert!(!details.get(&contact).expect("listed").details_unreadable); + } + /// With two documents for one contact, the load shows the one a save /// rewrites: the first in that order. #[tokio::test] diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index c0a860273..72f2a7f4f 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -14,7 +14,7 @@ use dash_sdk::drive::query::{OrderClause, WhereClause, WhereOperator}; use dash_sdk::platform::{Document, DocumentQuery, Fetch, FetchMany, Identifier}; use dash_sdk::query_types::Documents; use futures::future::join_all; -use platform_wallet::wallet::identity::crypto::decode_private_data; +use platform_wallet::wallet::identity::crypto::{ContactInfoPrivateData, decode_private_data}; use std::collections::{HashMap, HashSet}; use std::future::Future; use std::sync::Arc; @@ -185,15 +185,22 @@ where continue; } - // The DIP-15 codec platform-wallet writes with; an unreadable payload - // shows as no stored details. + // The DIP-15 codec platform-wallet writes with. A payload that is + // present but cannot be opened is not "no details": its hidden flag + // is unknown, so the contact stays hidden. let private_data = match props.get("privateData") { - Some(Value::Bytes(encrypted)) => decrypt_private_data(encrypted, &private_data_key) + None => Some(ContactInfoPrivateData::default()), + Some(value) => value + .as_bytes_slice() .ok() + .and_then(|encrypted| decrypt_private_data(encrypted, &private_data_key).ok()) .and_then(|plaintext| decode_private_data(&plaintext).ok()), - _ => None, - } - .unwrap_or_default(); + }; + let details_unreadable = private_data.is_none(); + let private_data = private_data.unwrap_or(ContactInfoPrivateData { + display_hidden: true, + ..Default::default() + }); contact_info_map.insert( contact_id, @@ -203,6 +210,7 @@ where nickname: private_data.alias_name, note: private_data.note, is_hidden: private_data.display_hidden, + details_unreadable, username: None, display_name: None, avatar_url: None, @@ -220,6 +228,9 @@ pub struct ContactData { pub nickname: Option, pub note: Option, pub is_hidden: bool, + /// The stored details exist but could not be decrypted or decoded. Such a + /// contact is kept hidden, since its hidden flag cannot be read. + pub details_unreadable: bool, pub account_reference: u32, // Profile data (fetched from Platform) pub username: Option, @@ -324,6 +335,7 @@ pub async fn load_contacts( nickname: None, note: None, is_hidden: false, + details_unreadable: false, account_reference: 0, username: None, display_name: None, @@ -461,6 +473,7 @@ pub async fn load_contacts_offline( .map(|m| m.notes.clone()) .filter(|s| !s.is_empty()), is_hidden: memo.as_ref().map(|m| m.is_hidden).unwrap_or(false), + details_unreadable: false, // Carry the cached account reference so the "Account #N" badge shows // and offline ordering matches the post-refresh view. Falls back to // 0 ("default account") when no network read has cached one yet. diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index 2d661fb2b..f283319f0 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -78,6 +78,11 @@ pub const UNHIDE_TOOLTIP: &str = "Show this contact in your contact list again." /// count tells the user there is something to recover. pub const SHOW_HIDDEN_LABEL: &str = "Show hidden contacts"; +/// Shown under a hidden contact whose saved details could not be read: its +/// hidden flag is unknown, so it stays hidden until the user unhides it. +pub const UNREADABLE_DETAILS_NOTE: &str = "The details you saved for this contact could not be read, so it stays \ + hidden. Unhide it to show it in your list again."; + /// Why a contact the user never hid by hand can still be in this section: /// declining or cancelling a request hides that person, and a contact that is /// later established with them stays hidden until it is unhidden here. @@ -995,6 +1000,13 @@ fn hidden_section( } }, ); + if contact.details_unreadable { + ui.label( + RichText::new(UNREADABLE_DETAILS_NOTE) + .small() + .color(DashColors::text_secondary(dark_mode)), + ); + } ui.add_space(4.0); } @@ -1289,6 +1301,7 @@ mod tests { nickname: Some("Bao".into()), note: None, is_hidden: false, + details_unreadable: false, account_reference: 0, username: None, display_name: None, @@ -1308,6 +1321,7 @@ mod tests { nickname: Some(nickname.into()), note: None, is_hidden: false, + details_unreadable: false, account_reference: 0, username: None, display_name: None, @@ -1513,6 +1527,7 @@ mod tests { fn hidden_bao() -> ContactData { ContactData { is_hidden: true, + details_unreadable: false, ..contact_with_note(None) } } @@ -1720,6 +1735,7 @@ mod tests { nickname: nickname.map(str::to_string), note: note.map(str::to_string), is_hidden: true, + details_unreadable: false, account_reference: 0, username: None, display_name: None, diff --git a/src/ui/identity/hub_screen.rs b/src/ui/identity/hub_screen.rs index 2e587b538..cd8748525 100644 --- a/src/ui/identity/hub_screen.rs +++ b/src/ui/identity/hub_screen.rs @@ -2689,6 +2689,7 @@ mod tests { nickname: None, note: None, is_hidden: false, + details_unreadable: false, account_reference: 0, username: None, display_name: None, @@ -2722,6 +2723,7 @@ mod tests { nickname: None, note: None, is_hidden: false, + details_unreadable: false, account_reference: 0, username: None, display_name: None, @@ -2763,6 +2765,7 @@ mod tests { nickname: None, note: None, is_hidden: false, + details_unreadable: false, account_reference: 0, username: None, display_name: None, @@ -2858,6 +2861,7 @@ mod tests { nickname: None, note: note.map(Into::into), is_hidden: false, + details_unreadable: false, account_reference: 0, username: None, display_name: None, @@ -3058,6 +3062,7 @@ mod tests { nickname: None, note: Some(note.into()), is_hidden: false, + details_unreadable: false, account_reference: 0, username: None, display_name: None, diff --git a/src/ui/state/contact_detail_view.rs b/src/ui/state/contact_detail_view.rs index 5dada5037..aa6a168dd 100644 --- a/src/ui/state/contact_detail_view.rs +++ b/src/ui/state/contact_detail_view.rs @@ -202,6 +202,7 @@ mod tests { nickname: None, note: note.map(str::to_string), is_hidden: false, + details_unreadable: false, account_reference: 0, username: None, display_name: None, diff --git a/src/ui/state/contacts_view.rs b/src/ui/state/contacts_view.rs index e6919c42c..ec8c168ac 100644 --- a/src/ui/state/contacts_view.rs +++ b/src/ui/state/contacts_view.rs @@ -664,6 +664,7 @@ mod tests { nickname: nickname.map(str::to_string), note: None, is_hidden: false, + details_unreadable: false, account_reference: 0, username: username.map(str::to_string), display_name: display.map(str::to_string), @@ -718,6 +719,7 @@ mod tests { state.record_contacts(vec![ContactData { is_hidden: true, + details_unreadable: false, ..contact(Some("Bao"), None, None) }]); assert!( @@ -889,6 +891,7 @@ mod tests { ContactData { identity_id, is_hidden: true, + details_unreadable: false, ..contact(Some(nickname), None, None) } } diff --git a/tests/kittest/identity_home.rs b/tests/kittest/identity_home.rs index 83a73b8cd..44054c164 100644 --- a/tests/kittest/identity_home.rs +++ b/tests/kittest/identity_home.rs @@ -816,6 +816,7 @@ fn home_contacts_follow_an_identity_selected_outside_the_hub() { nickname: Some("Bao".into()), note: None, is_hidden: false, + details_unreadable: false, account_reference: 0, username: None, display_name: None, @@ -902,6 +903,7 @@ fn contact(byte: u8, name: &str) -> dash_evo_tool::backend_task::dashpay::Contac nickname: Some(name.into()), note: None, is_hidden: false, + details_unreadable: false, account_reference: 0, username: None, display_name: None, @@ -1012,6 +1014,7 @@ fn home_contact_preview_shows_the_first_six_contacts() { nickname: Some((*name).into()), note: None, is_hidden: false, + details_unreadable: false, account_reference: 0, username: None, display_name: None, diff --git a/tests/kittest/identity_hub.rs b/tests/kittest/identity_hub.rs index c1ac86ca8..af332ea46 100644 --- a/tests/kittest/identity_hub.rs +++ b/tests/kittest/identity_hub.rs @@ -381,6 +381,7 @@ pub(crate) mod loads { nickname: Some(name.into()), note: None, is_hidden: false, + details_unreadable: false, account_reference: 0, username: None, display_name: None, @@ -725,6 +726,7 @@ pub(crate) mod loads { nickname: Some(name.into()), note: None, is_hidden: false, + details_unreadable: false, account_reference: 0, username: None, display_name: None, diff --git a/tests/kittest/identity_hub_contact_detail.rs b/tests/kittest/identity_hub_contact_detail.rs index c3afae6c6..73e21782a 100644 --- a/tests/kittest/identity_hub_contact_detail.rs +++ b/tests/kittest/identity_hub_contact_detail.rs @@ -30,6 +30,7 @@ fn bao(note: Option<&str>) -> ContactData { nickname: None, note: note.map(str::to_string), is_hidden: false, + details_unreadable: false, account_reference: 0, username: Some("bao".into()), display_name: Some("Bao Nguyen".into()), @@ -632,6 +633,45 @@ fn a_foreign_same_contact_failure_does_not_release_the_hubs_note() { }); } +/// A hidden contact whose saved details could not be read says so; a +/// readable hidden contact does not. +#[test] +fn an_unreadable_hidden_contact_is_labelled() { + use dash_evo_tool::ui::identity::contacts::{SHOW_HIDDEN_LABEL, UNREADABLE_DETAILS_NOTE}; + for unreadable in [true, false] { + with_isolated_data_dir(|| { + let runtime = tokio::runtime::Runtime::new().expect("runtime"); + let _guard = runtime.enter(); + let app = crate::support::mount_app( + dash_evo_tool::ui::RootScreenType::RootScreenWalletsBalances, + ); + let app_context = app.state().current_app_context().clone(); + let owner = seed_identity_with_usernames(&app_context); + let mut hub = hub_for( + &app_context, + owner, + WIDE, + IdentityHubTab::Contacts, + |hub, owner| { + let mut contact = bao(None); + contact.is_hidden = true; + contact.details_unreadable = unreadable; + deliver(hub, owner, contact); + }, + ); + hub.get_by_label(&format!("{SHOW_HIDDEN_LABEL} · 1")) + .click(); + hub.run_steps(2); + + assert_eq!( + hub.query_by_label(UNREADABLE_DETAILS_NOTE).is_some(), + unreadable, + "unreadable = {unreadable}" + ); + }); + } +} + #[test] fn failed_unhide_behind_another_screen_restores_the_hidden_row() { use dash_evo_tool::backend_task::error::TaskError; diff --git a/tests/kittest/identity_hub_contacts.rs b/tests/kittest/identity_hub_contacts.rs index 4156cb82c..affdbbd62 100644 --- a/tests/kittest/identity_hub_contacts.rs +++ b/tests/kittest/identity_hub_contacts.rs @@ -151,6 +151,7 @@ fn contacts_tab_follows_an_identity_selected_outside_the_hub() { nickname: Some("Bao".into()), note: None, is_hidden: false, + details_unreadable: false, account_reference: 0, username: None, display_name: None, diff --git a/tests/kittest/identity_hub_layout.rs b/tests/kittest/identity_hub_layout.rs index 358cef9cc..c94703e18 100644 --- a/tests/kittest/identity_hub_layout.rs +++ b/tests/kittest/identity_hub_layout.rs @@ -165,6 +165,7 @@ fn deliver_contact_with( nickname: Some(nickname.into()), note: None, is_hidden, + details_unreadable: false, account_reference: 0, username, display_name: None, From aee88cb178d43a59df9c5b1bdefd4f8e8d6d298a Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:03:15 +0000 Subject: [PATCH 46/73] fix(deps): take platform-encryption from the shared Platform pin platform-encryption was pinned at 9f7ed169 while every other Platform crate is at 575d961f. The build linked a second copy (4.2.0-beta.3, with secp256k1 0.30), so the host sealed contact details with a different crate than platform-wallet. Both revisions expose the same four functions DET uses. The lock now holds one platform-encryption and one secp256k1. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- Cargo.lock | 49 ++++++++----------------------------------------- Cargo.toml | 2 +- 2 files changed, 9 insertions(+), 42 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6023e5d14..1bc0faa7e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -991,7 +991,7 @@ dependencies = [ "bitcoin-primitives 0.103.1", "bitcoin_hashes 1.2.0 (git+https://github.com/rust-bitcoin/rust-bitcoin?rev=7ba35c7c1dd63892bfb9c9395bbd80e2ab5df516)", "hex-conservative 1.3.0", - "secp256k1 0.33.1", + "secp256k1", "serde", ] @@ -2216,7 +2216,7 @@ dependencies = [ "native-dialog", "nix", "objc2 0.6.5", - "platform-encryption 4.2.0-beta.3", + "platform-encryption", "platform-wallet", "platform-wallet-storage", "qrcode", @@ -2336,7 +2336,7 @@ dependencies = [ "group 0.14.0", "hex-conservative 1.3.0", "rand_core 0.10.1", - "secp256k1 0.33.1", + "secp256k1", "serde", "sha2 0.11.1", "subtle", @@ -2400,7 +2400,7 @@ dependencies = [ "http", "js-sys", "lru", - "platform-encryption 5.0.0-rc.8", + "platform-encryption", "rs-dapi-client", "serde", "serde_json", @@ -2970,7 +2970,7 @@ dependencies = [ "platform-versioning", "rand 0.8.8", "regex", - "secp256k1 0.33.1", + "secp256k1", "serde", "serde_json", "serde_repr", @@ -6883,19 +6883,6 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" -[[package]] -name = "platform-encryption" -version = "4.2.0-beta.3" -source = "git+https://github.com/dashpay/platform?rev=9f7ed16935bd540e4c2a542688800d2953f9f67a#9f7ed16935bd540e4c2a542688800d2953f9f67a" -dependencies = [ - "aes 0.8.4", - "cbc 0.1.2", - "hmac", - "secp256k1 0.30.0", - "sha2 0.10.9", - "thiserror 1.0.69", -] - [[package]] name = "platform-encryption" version = "5.0.0-rc.8" @@ -6904,7 +6891,7 @@ dependencies = [ "aes 0.8.4", "cbc 0.1.2", "hmac", - "secp256k1 0.33.1", + "secp256k1", "sha2 0.10.9", "thiserror 1.0.69", ] @@ -6991,7 +6978,7 @@ dependencies = [ "key-wallet", "key-wallet-manager", "log", - "platform-encryption 5.0.0-rc.8", + "platform-encryption", "rusqlite", "serde", "serde_json", @@ -8307,17 +8294,6 @@ dependencies = [ "tiny-skia 0.11.4", ] -[[package]] -name = "secp256k1" -version = "0.30.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b50c5943d326858130af85e049f2661ba3c78b26589b8ab98e65e80ae44a1252" -dependencies = [ - "bitcoin_hashes 0.14.101", - "rand 0.8.8", - "secp256k1-sys 0.10.1", -] - [[package]] name = "secp256k1" version = "0.33.1" @@ -8325,19 +8301,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7f404a8dab7a7a5a631e741d8699aa9c8e1d689fc26ccf897c7187565490b69" dependencies = [ "rand 0.9.5", - "secp256k1-sys 0.14.1", + "secp256k1-sys", "serde", ] -[[package]] -name = "secp256k1-sys" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4387882333d3aa8cb20530a17c69a3752e97837832f34f6dccc760e715001d9" -dependencies = [ - "cc", -] - [[package]] name = "secp256k1-sys" version = "0.14.1" diff --git a/Cargo.toml b/Cargo.toml index 6a2452051..5524436c7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -48,7 +48,7 @@ platform-wallet-storage = { git = "https://github.com/dashpay/platform", rev = " ] } # DIP-15 contactInfo AES primitives for the host-side `ContactCryptoProvider`; # the same crate platform-wallet seals and opens with. -platform-encryption = { git = "https://github.com/dashpay/platform", rev = "9f7ed16935bd540e4c2a542688800d2953f9f67a" } +platform-encryption = { git = "https://github.com/dashpay/platform", rev = "575d961fe0c54bd7e01a3cf3823494e58c6c4fdb" } zip32 = "0.2.1" grovestark = { git = "https://www.github.com/dashpay/grovestark", rev = "5b9e289cca54c79b1305d5f4f40bf1148f1eb0e3" } rayon = "1.12.0" From a78aef12a9efbfa4bff76a1a4bb62bdfa92dcda5 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:03:16 +0000 Subject: [PATCH 47/73] fix(dashpay): keep a contact hidden when its newest published details cannot be read The published contactInfo reader skipped a document whose details did not decrypt or decode. An older readable document then won, and could show a hidden contact as active. A document that still opens to its contact id now records the contact as unreadable. Through PublishedContactInfos::take the contact list then shows it hidden and labelled, like an unreadable legacy document. Also correct legacy_details_from's doc comment and cover more inputs in the legacy_details_shown test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contact_info.rs | 5 +- src/backend_task/dashpay/contacts.rs | 28 ++-- src/wallet_backend/contact_info.rs | 155 +++++++++++++++++++---- src/wallet_backend/mod.rs | 1 + 4 files changed, 154 insertions(+), 35 deletions(-) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index c15e8c2c1..5d0da7581 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -135,7 +135,10 @@ async fn shown_details_for( .await .remove(contact_id); let stored = super::contacts::stored_contact_details(app_context, sdk, identity).await?; - let published = stored.published?.remove(contact_id); + let published = stored + .published? + .take(contact_id) + .map(|(details, _)| details); let legacy = stored.legacy?; let synced_before = backend.dashpay_details_synced(&owner, contact_id)? || super::contacts::holds_details(published.as_ref(), local.as_ref()); diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index 11497ba20..56acccbfa 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -15,7 +15,7 @@ use dash_sdk::platform::{Document, DocumentQuery, Fetch, FetchMany, Identifier}; use dash_sdk::query_types::Documents; use futures::future::join_all; use platform_wallet::wallet::identity::crypto::{ContactInfoPrivateData, decode_private_data}; -use std::collections::{BTreeMap, HashMap, HashSet}; +use std::collections::{HashMap, HashSet}; use std::future::Future; use std::sync::Arc; use zeroize::Zeroizing; @@ -171,8 +171,10 @@ where } /// The details `documents` (oldest first) hold under the legacy key root; -/// a later document for a contact replaces an earlier one. A document that -/// does not open is skipped. +/// a later document for a contact replaces an earlier one. A document whose +/// keys or contact id do not open is skipped, since nothing tells whose it +/// is. One whose details do not decrypt or decode marks its contact +/// unreadable and hidden. /// /// # Errors /// @@ -261,7 +263,7 @@ pub(super) struct StoredContactDetails { /// From DIP-0015 documents platform-wallet can read, newest per contact; /// an error when the seed could not be used to read them. A save must not /// guess past that error; the contacts list may. - pub(super) published: Result, TaskError>, + pub(super) published: Result, /// From documents older versions of this app wrote under the legacy /// key root, newest per contact; an error as for `published`. pub(super) legacy: Result, TaskError>, @@ -300,7 +302,7 @@ pub(super) async fn stored_contact_details( .dashpay_open_contact_infos(identity, &documents) .await } - Err(_) => Ok(BTreeMap::new()), + Err(_) => Ok(crate::wallet_backend::PublishedContactInfos::default()), }; // Without a wallet seed no legacy key exists, so no document opens. let legacy = if identity.dashpay_wallet_seed_hash().is_some() { @@ -493,7 +495,7 @@ pub async fn load_contacts( stored_contact_details(app_context, sdk, &identity).await?; let mut published = published.unwrap_or_else(|error| { tracing::debug!(?error, "LoadContacts: published contact details not read"); - BTreeMap::new() + crate::wallet_backend::PublishedContactInfos::default() }); let legacy = legacy.unwrap_or_else(|error| { tracing::debug!(?error, "LoadContacts: legacy contact details not read"); @@ -506,7 +508,10 @@ pub async fn load_contacts( .map(|contact_id| { let legacy = legacy.get(&contact_id); let synced = synced.remove(&contact_id); - let published = published.remove(&contact_id); + let (published, published_unreadable) = match published.take(&contact_id) { + Some((details, unreadable)) => (Some(details), unreadable), + None => (None, false), + }; let synced_before = backend.as_ref().is_some_and(|backend| { let synced_before = backend .dashpay_details_synced(&identity_id, &contact_id) @@ -523,8 +528,8 @@ pub async fn load_contacts( } synced_before }); - let details_unreadable = - legacy_details_shown(published.as_ref(), synced.as_ref(), synced_before) + let details_unreadable = published_unreadable + || legacy_details_shown(published.as_ref(), synced.as_ref(), synced_before) && legacy.is_some_and(|legacy| legacy.details_unreadable); let details = shown_contact_details( published, @@ -758,6 +763,7 @@ fn cache_contact_profiles(app_context: &Arc, contacts: &[ContactData #[cfg(test)] mod tests { use super::*; + use std::collections::BTreeMap; /// After a restart the offline list shows the details platform-wallet /// holds (synced from Platform) rather than this device's older copy, so @@ -990,7 +996,11 @@ mod tests { (None, Some(&empty), false), (None, Some(¬e), false), (None, None, true), + (None, Some(&empty), true), + (None, Some(¬e), true), (Some(&empty), None, false), + (Some(¬e), None, false), + (Some(¬e), Some(¬e), true), ] { let legacy = details("legacy"); assert_eq!( diff --git a/src/wallet_backend/contact_info.rs b/src/wallet_backend/contact_info.rs index bb9cf1048..669381bbd 100644 --- a/src/wallet_backend/contact_info.rs +++ b/src/wallet_backend/contact_info.rs @@ -7,7 +7,7 @@ //! platform-wallet's own `derive_contact_info_keys`, the AES steps from the //! `platform-encryption` crate it uses, so both sides always agree. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use dash_sdk::dpp::dashcore::Network; @@ -202,12 +202,12 @@ impl WalletBackend { &self, identity: &QualifiedIdentity, documents: &[Document], - ) -> Result, TaskError> { + ) -> Result { if documents.is_empty() { - return Ok(BTreeMap::new()); + return Ok(PublishedContactInfos::default()); } let Some(seed_hash) = identity.dashpay_wallet_seed_hash() else { - return Ok(BTreeMap::new()); + return Ok(PublishedContactInfos::default()); }; // A wallet that cannot be resolved is an error: a save keeps every // field it does not replace from this read, so an empty result here @@ -222,7 +222,7 @@ impl WalletBackend { .and_then(|managed| managed.identity_index) }; let Some(identity_index) = identity_index else { - return Ok(BTreeMap::new()); + return Ok(PublishedContactInfos::default()); }; let network = identity.network; self.secret_access() @@ -238,8 +238,37 @@ impl WalletBackend { } } -/// Open `documents` (oldest first) through `crypto`; the newest readable -/// document per contact wins. +/// The details published `contactInfo` documents hold, from the newest +/// document per contact. +#[derive(Debug, Default, PartialEq)] +pub(crate) struct PublishedContactInfos { + details: BTreeMap, + /// Contacts whose newest document opens to their id but whose details do + /// not decrypt or decode. It may also hold ids of no contact, from + /// documents sealed under another key. + unreadable: BTreeSet, +} + +impl PublishedContactInfos { + /// Take the published details for `contact_id`, and whether they are + /// unreadable. Unreadable details stand in as hidden: their hidden flag + /// cannot be read, and must not be taken as cleared. + pub(crate) fn take(&mut self, contact_id: &Identifier) -> Option<(ContactDetails, bool)> { + if self.unreadable.remove(contact_id) { + let hidden = ContactDetails { + hidden: true, + ..Default::default() + }; + return Some((hidden, true)); + } + self.details + .remove(contact_id) + .map(|details| (details, false)) + } +} + +/// Open `documents` (oldest first) through `crypto`; the newest document per +/// contact wins, readable or not. // TODO(upstream): dip15-contactinfo-reader — replace with a platform-wallet // contactInfo-only, provider-backed read for seedless wallets once one exists; // platform-wallet's own drain is crate-private and runs unrelated contact work. @@ -247,8 +276,8 @@ impl WalletBackend { async fn open_contact_info_documents( crypto: &ContactInfoCrypto<'_>, documents: &[Document], -) -> BTreeMap { - let mut opened = BTreeMap::new(); +) -> PublishedContactInfos { + let mut opened = PublishedContactInfos::default(); for document in documents { let Some(stored) = StoredContactInfo::of(document) else { continue; @@ -261,7 +290,7 @@ async fn open_contact_info_documents( ) else { continue; }; - let Ok(contact) = crypto + let (contact_id, data) = match crypto .contact_info_open( &root_path, stored.derivation_index, @@ -269,20 +298,42 @@ async fn open_contact_info_documents( stored.private_data, ) .await - else { - continue; - }; - let Ok(data) = decode_private_data(&contact.private_data) else { - continue; - }; - opened.insert( - Identifier::from(contact.contact_id), - ContactDetails { - nickname: data.alias_name, - note: data.note, - hidden: data.display_hidden, + { + Ok(contact) => ( + contact.contact_id, + decode_private_data(&contact.private_data).ok(), + ), + // The contact id still opens: the document is that contact's, + // with details that do not decrypt. + Err(_) => match crypto.keys(&root_path, stored.derivation_index) { + Ok(keys) => ( + platform_encryption::decrypt_enc_to_user_id( + &keys.enc_to_user_id_key, + &stored.enc_to_user_id, + ), + None, + ), + Err(_) => continue, }, - ); + }; + let contact_id = Identifier::from(contact_id); + match data { + Some(data) => { + opened.unreadable.remove(&contact_id); + opened.details.insert( + contact_id, + ContactDetails { + nickname: data.alias_name, + note: data.note, + hidden: data.display_hidden, + }, + ); + } + None => { + opened.details.remove(&contact_id); + opened.unreadable.insert(contact_id); + } + } } opened } @@ -627,7 +678,8 @@ mod tests { /// SEC-003: DIP-0015 documents are read back without platform-wallet /// holding the seed; the newest per contact wins, and documents that do - /// not open (another key root, or garbage) are skipped, not fatal. + /// not open (another key root, or garbage) give no details and are not + /// fatal. #[tokio::test] async fn dip15_documents_are_read_back_newest_first() { let crypto = ContactInfoCrypto::new(&SEED, NETWORK, IDENTITY_INDEX); @@ -661,7 +713,7 @@ mod tests { let opened = open_contact_info_documents(&crypto, &documents).await; assert_eq!( - opened, + opened.details, BTreeMap::from([ (Identifier::from([7; 32]), note("newer")), ( @@ -675,6 +727,59 @@ mod tests { ); } + /// A newest document that names its contact but whose details do not + /// decrypt or decode is not skipped in favour of an older readable one: + /// the contact stays hidden, marked unreadable, since its hidden flag + /// cannot be read. + #[tokio::test] + async fn an_unreadable_newest_document_keeps_its_contact_hidden() { + let crypto = ContactInfoCrypto::new(&SEED, NETWORK, IDENTITY_INDEX); + let shown = ContactDetails { + note: Some("older".into()), + ..Default::default() + }; + let older = sealed(&crypto, 0, [7; 32], shown.clone()).await; + let mut undecryptable = sealed(&crypto, 1, [7; 32], shown.clone()).await; + undecryptable.private_data = vec![9; 48]; + let older_other = sealed(&crypto, 2, [8; 32], shown.clone()).await; + let undecodable = { + let keys = crypto + .keys(&root(IDENTITY_INDEX, 2), 3) + .expect("own root keys"); + ContactInfoSealed { + enc_to_user_id: platform_encryption::encrypt_enc_to_user_id( + &keys.enc_to_user_id_key, + &[8; 32], + ), + private_data: platform_encryption::encrypt_private_data( + &keys.private_data_key, + &[4; 16], + &[0xFF; 40], + ), + } + }; + let documents = [ + stored_document(1, 2, 0, &older), + stored_document(2, 2, 1, &undecryptable), + stored_document(3, 2, 2, &older_other), + stored_document(4, 2, 3, &undecodable), + ]; + + let mut opened = open_contact_info_documents(&crypto, &documents).await; + + let hidden = ContactDetails { + hidden: true, + ..Default::default() + }; + for contact in [[7; 32], [8; 32]] { + assert_eq!( + opened.take(&Identifier::from(contact)), + Some((hidden.clone(), true)), + "{contact:?}" + ); + } + } + /// A root that belongs to another wallet identity is refused. #[tokio::test] async fn another_identitys_root_is_refused() { diff --git a/src/wallet_backend/mod.rs b/src/wallet_backend/mod.rs index d0b9bc1f0..2d431a8e4 100644 --- a/src/wallet_backend/mod.rs +++ b/src/wallet_backend/mod.rs @@ -83,6 +83,7 @@ pub(crate) use dashpay::{ ContactRequestActionKind, derive_contact_info_encryption_keys, derive_contact_xpub_material, }; +pub(crate) use contact_info::PublishedContactInfos; pub(crate) use det_platform_signer::{DetPlatformSigner, PlatformPathIndex}; pub(crate) use det_signer::{DetSigner, DetSignerError}; pub use identity_key_store::IdentityKeyView; From bdbd01d40d30b1273b439ea99d2b1249fc539ba1 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:51:02 +0000 Subject: [PATCH 48/73] fix(dashpay): stop claiming the network for a failed local decline or withdrawal Declining and withdrawing a contact request publish nothing, but a failed local record surfaced as DashpaySidecarStorage, whose message says the change reached the network. Both flows now report DashPayRequestDecisionNotRecorded, which says nothing was sent and asks the user to try again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contact_requests.rs | 55 ++++++++++++++++++-- src/backend_task/error.rs | 8 +++ 2 files changed, 59 insertions(+), 4 deletions(-) diff --git a/src/backend_task/dashpay/contact_requests.rs b/src/backend_task/dashpay/contact_requests.rs index 61a116e60..8a7bcbb6f 100644 --- a/src/backend_task/dashpay/contact_requests.rs +++ b/src/backend_task/dashpay/contact_requests.rs @@ -943,10 +943,23 @@ trait RejectOps { fn sender_id(&self) -> Identifier; } +/// A decline or withdrawal changes only this device, so a failed local +/// record must not be reported as one whose change reached the network. +fn recorded_on_this_device(error: TaskError) -> TaskError { + match error { + TaskError::DashpaySidecarStorage { source } => { + TaskError::DashPayRequestDecisionNotRecorded { source } + } + error => error, + } +} + async fn reject_flow(ops: &O) -> Result { let _action_guard = ops.lock_action().await?; let result = if ops.ignore_sender().await? { - complete_rejection(ops.request_id(), || ops.mark_declined())? + complete_rejection(ops.request_id(), || { + ops.mark_declined().map_err(recorded_on_this_device) + })? } else { // The contact was established before the ignore took effect. BackendTaskSuccessResult::DashPayContactAlreadyEstablished { @@ -954,7 +967,7 @@ async fn reject_flow(ops: &O) -> Result(ops: &O) -> Result let outcome = if ops.reciprocal_request_exists().await? { CancelOutcome::AlreadyEstablished } else if ops.ignore_recipient().await? { - ops.mark_withdrawn()?; + ops.mark_withdrawn().map_err(recorded_on_this_device)?; CancelOutcome::Withdrawn } else { // The reply was taken in after the query, before the ignore. CancelOutcome::AlreadyEstablished }; - ops.clear_phase()?; + ops.clear_phase().map_err(recorded_on_this_device)?; Ok(outcome) } @@ -1719,6 +1732,7 @@ mod tests { struct ScriptedRejectOps { action_lock: Arc>, ignore_fails: bool, + decline_fails: bool, established_meanwhile: bool, ignored: Mutex, declined: Mutex, @@ -1745,6 +1759,11 @@ mod tests { } fn mark_declined(&self) -> Result<(), TaskError> { + if self.decline_fails { + return Err(TaskError::DashpaySidecarStorage { + source: crate::wallet_backend::KvAdapterError::Truncated, + }); + } *self.declined.lock().unwrap() = true; Ok(()) } @@ -1788,6 +1807,34 @@ mod tests { assert!(*ops.declined.lock().unwrap()); } + /// Declining and withdrawing publish nothing, so a failed local record + /// must not tell the user that the change reached the network. + #[tokio::test] + async fn a_failed_local_decision_record_does_not_claim_the_network() { + let decline = ScriptedRejectOps { + decline_fails: true, + ..Default::default() + }; + let withdraw = ScriptedOps { + withdraw_fails: true, + ..Default::default() + }; + + for error in [ + reject_flow(&decline) + .await + .expect_err("decline record fails"), + cancel_flow(&withdraw) + .await + .expect_err("withdrawal record fails"), + ] { + assert!( + matches!(error, TaskError::DashPayRequestDecisionNotRecorded { .. }), + "{error:?}" + ); + } + } + #[tokio::test] async fn a_failed_ignore_records_no_decline() { let ops = ScriptedRejectOps { diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 0ca42673a..a68d9dee3 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -1459,6 +1459,14 @@ pub enum TaskError { source: crate::wallet_backend::KvAdapterError, }, + /// A decline or a withdrawal, which only change this device, could not be + /// recorded here; the request would be listed again on reload. + #[error("Could not save this change on this device. Nothing was sent to the network. Try again.")] + DashPayRequestDecisionNotRecorded { + #[source] + source: crate::wallet_backend::KvAdapterError, + }, + /// A contact-details save that stayed on this device, because publishing /// waits for a second contact, could not record which details this device /// holds; on reload the older details would show again. From d16e72c1bae0cf7db974caa7802a8e86ecb7b09a Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 26 Oct 2026 23:51:02 +0000 Subject: [PATCH 49/73] fix(dashpay): let the contacts list's details sync wait for a save platform-wallet stores a save's details on this device before it publishes them, so a list refresh syncing in between put the older published details back over them. The list's sync now takes the owner's contact-info write lock, as saves do. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contacts.rs | 42 +++++++++++++++++++++++++++- src/context/mod.rs | 1 + 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index 56acccbfa..1d4fc0404 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -258,6 +258,19 @@ where Ok(contact_info_map) } +/// Run `sync` once no contact details save of `owner` is in flight. +/// +/// A save stores its details on this device before it publishes them; a +/// sync in between would put the older published details back over them. +async fn after_details_saves( + writes: &crate::context::ContactInfoWrites, + owner: Identifier, + sync: impl Future, +) -> T { + let _write_guard = writes.acquire(owner).await; + sync.await +} + /// The details the owner's stored `contactInfo` documents hold. pub(super) struct StoredContactDetails { /// From DIP-0015 documents platform-wallet can read, newest per contact; @@ -478,7 +491,13 @@ pub async fn load_contacts( "LoadContacts: DashPay sync degraded; using cached state" ); } - if let Err(error) = backend.dashpay_sync_contact_infos(&identity_id).await { + let synced = after_details_saves( + &app_context.contact_info_writes, + identity_id, + backend.dashpay_sync_contact_infos(&identity_id), + ) + .await; + if let Err(error) = synced { tracing::debug!( ?error, "LoadContacts: contact details sync degraded; using cached state" @@ -765,6 +784,27 @@ mod tests { use super::*; use std::collections::BTreeMap; + /// The contacts list's details sync waits for a save of the same owner, + /// so it cannot put older published details over the save's own. + #[tokio::test] + async fn the_list_details_sync_waits_for_a_save() { + use std::sync::atomic::{AtomicBool, Ordering}; + let writes = crate::context::ContactInfoWrites::default(); + let owner = Identifier::from([1; 32]); + let ran = AtomicBool::new(false); + let save = writes.acquire(owner).await; + + let mut sync = Box::pin(after_details_saves(&writes, owner, async { + ran.store(true, Ordering::SeqCst); + })); + assert!(futures::poll!(&mut sync).is_pending()); + assert!(!ran.load(Ordering::SeqCst), "the sync waits for the save"); + + drop(save); + sync.await; + assert!(ran.load(Ordering::SeqCst)); + } + /// After a restart the offline list shows the details platform-wallet /// holds (synced from Platform) rather than this device's older copy, so /// a contact hidden on another device is not listed as visible here. diff --git a/src/context/mod.rs b/src/context/mod.rs index ed71eead1..af9a960ed 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -1,5 +1,6 @@ pub mod connection_status; mod contact_info_writes; +pub(crate) use contact_info_writes::ContactInfoWrites; mod contested_names_db; mod contract_token_db; mod dapi_addresses; From aeb1d5875026b6b665ddb5bdd4d50d7177b796c9 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 00:15:49 +0000 Subject: [PATCH 50/73] fix(dashpay): do not fail a recorded decline or withdrawal on leftover cleanup Once the decline or withdrawal marker is written, the progress record an older version kept is read by nothing. Failing to delete it made the action report "Could not save this change" although the decision was recorded. It is now logged and the action succeeds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contact_requests.rs | 52 +++++++++++++++++++- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/src/backend_task/dashpay/contact_requests.rs b/src/backend_task/dashpay/contact_requests.rs index 8a7bcbb6f..7be25c324 100644 --- a/src/backend_task/dashpay/contact_requests.rs +++ b/src/backend_task/dashpay/contact_requests.rs @@ -954,6 +954,18 @@ fn recorded_on_this_device(error: TaskError) -> TaskError { } } +/// The progress record an older version kept is read by nothing once the +/// decision is recorded, so failing to forget it leaves an inert entry and +/// does not fail the action. +fn forget_phase(cleared: Result<(), TaskError>) { + if let Err(error) = cleared { + tracing::warn!( + ?error, + "could not forget an old contact request progress record" + ); + } +} + async fn reject_flow(ops: &O) -> Result { let _action_guard = ops.lock_action().await?; let result = if ops.ignore_sender().await? { @@ -967,7 +979,7 @@ async fn reject_flow(ops: &O) -> Result(ops: &O) -> Result // The reply was taken in after the query, before the ignore. CancelOutcome::AlreadyEstablished }; - ops.clear_phase().map_err(recorded_on_this_device)?; + forget_phase(ops.clear_phase()); Ok(outcome) } @@ -1611,6 +1623,7 @@ mod tests { withdrawn: Mutex, withdraw_fails: bool, phase_cleared: Mutex, + phase_fails: bool, ignored: Mutex, /// The reply is taken in between the reciprocal query and the ignore. established_meanwhile: bool, @@ -1622,6 +1635,11 @@ mod tests { } fn clear_phase(&self) -> Result<(), TaskError> { + if self.phase_fails { + return Err(TaskError::DashpaySidecarStorage { + source: crate::wallet_backend::KvAdapterError::Truncated, + }); + } *self.phase_cleared.lock().unwrap() = true; Ok(()) } @@ -1733,6 +1751,7 @@ mod tests { action_lock: Arc>, ignore_fails: bool, decline_fails: bool, + phase_fails: bool, established_meanwhile: bool, ignored: Mutex, declined: Mutex, @@ -1744,6 +1763,11 @@ mod tests { } fn clear_phase(&self) -> Result<(), TaskError> { + if self.phase_fails { + return Err(TaskError::DashpaySidecarStorage { + source: crate::wallet_backend::KvAdapterError::Truncated, + }); + } Ok(()) } @@ -1807,6 +1831,30 @@ mod tests { assert!(*ops.declined.lock().unwrap()); } + /// The old progress record is inert once the decision is recorded, so + /// failing to forget it does not fail a decline or a withdrawal. + #[tokio::test] + async fn a_leftover_progress_record_does_not_fail_a_recorded_decision() { + let decline = ScriptedRejectOps { + phase_fails: true, + ..Default::default() + }; + let withdraw = ScriptedOps { + phase_fails: true, + ..Default::default() + }; + + assert!(matches!( + reject_flow(&decline).await, + Ok(BackendTaskSuccessResult::DashPayContactRequestRejected(_)) + )); + assert!(*decline.declined.lock().unwrap()); + assert_eq!( + cancel_flow(&withdraw).await.expect("withdrawn"), + CancelOutcome::Withdrawn + ); + } + /// Declining and withdrawing publish nothing, so a failed local record /// must not tell the user that the change reached the network. #[tokio::test] From 03b0e0b52ead123d3eed1cecfc19baf5ea6207af Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 00:15:49 +0000 Subject: [PATCH 51/73] fix(dashpay): skip contact details syncs while a save runs instead of waiting The contacts list waited for a running save, so it stalled behind the save's password prompt or a slow publish. The contact details load synced with no lock at all. Both reads now sync only when no save of the owner holds the write lock (ContactInfoWrites::try_acquire), and otherwise show the details this device holds. The save syncs under its own lock. The list records synced details only when no save runs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contact_info.rs | 27 ++++++++--- src/backend_task/dashpay/contacts.rs | 58 ++++++++++++++++-------- src/context/contact_info_writes.rs | 38 ++++++++++------ 3 files changed, 83 insertions(+), 40 deletions(-) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 5d0da7581..53934d7c9 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -92,11 +92,12 @@ pub async fn create_or_update_contact_info( } /// Read the details shown for `contact_id`, the ones a contact details -/// editor starts from. +/// editor starts from. While a save of the owner runs, the details are not +/// synced first; see [`super::contacts::unless_saving`]. /// /// # Errors /// -/// As for [`shown_details_for`]. +/// The details sync fails, or as for [`shown_details_for`]. pub async fn load_contact_details( app_context: &Arc, sdk: &Sdk, @@ -104,6 +105,16 @@ pub async fn load_contact_details( contact_id: Identifier, ) -> Result { let backend = app_context.wallet_backend()?; + let owner = identity.identity.id(); + if let Some(synced) = super::contacts::unless_saving( + &app_context.contact_info_writes, + owner, + backend.dashpay_sync_contact_infos(&owner), + ) + .await + { + synced?; + } let details = shown_details_for(app_context, sdk, &backend, &identity, &contact_id).await?; Ok(BackendTaskSuccessResult::DashPayContactDetails { identity: identity.identity.id(), @@ -118,9 +129,10 @@ pub async fn load_contact_details( /// /// # Errors /// -/// Fails when the details sync, the document fetch, or reading the published -/// or legacy documents fails (a cancelled password prompt included), rather -/// than guessing: a save keeps every field it does not replace from this. +/// Fails when the document fetch, or reading the published or legacy +/// documents fails (a cancelled password prompt included), rather than +/// guessing: a save keeps every field it does not replace from this. Callers +/// sync platform-wallet's details first, under the owner's write lock. async fn shown_details_for( app_context: &Arc, sdk: &Sdk, @@ -129,7 +141,6 @@ async fn shown_details_for( contact_id: &Identifier, ) -> Result { let owner = identity.identity.id(); - backend.dashpay_sync_contact_infos(&owner).await?; let local = backend .dashpay_contact_details(&owner) .await @@ -226,6 +237,10 @@ struct PlatformSaveOps<'a> { impl SaveOps for PlatformSaveOps<'_> { async fn current(&self) -> Result { + // The save holds the owner's write lock, so this sync cannot race one. + self.backend + .dashpay_sync_contact_infos(&self.identity.identity.id()) + .await?; shown_details_for( self.app_context, self.sdk, diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index 1d4fc0404..9ba9077f1 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -258,17 +258,20 @@ where Ok(contact_info_map) } -/// Run `sync` once no contact details save of `owner` is in flight. +/// Run `sync` unless a contact details save of `owner` is in flight; `None` +/// when one is. /// /// A save stores its details on this device before it publishes them; a /// sync in between would put the older published details back over them. -async fn after_details_saves( +/// A read does not wait for the save, which can sit behind a password prompt +/// or a slow publish: it shows the details this device already holds. +pub(super) async fn unless_saving( writes: &crate::context::ContactInfoWrites, owner: Identifier, sync: impl Future, -) -> T { - let _write_guard = writes.acquire(owner).await; - sync.await +) -> Option { + let _write_guard = writes.try_acquire(owner)?; + Some(sync.await) } /// The details the owner's stored `contactInfo` documents hold. @@ -491,17 +494,21 @@ pub async fn load_contacts( "LoadContacts: DashPay sync degraded; using cached state" ); } - let synced = after_details_saves( + match unless_saving( &app_context.contact_info_writes, identity_id, backend.dashpay_sync_contact_infos(&identity_id), ) - .await; - if let Err(error) = synced { - tracing::debug!( + .await + { + Some(Ok(())) => {} + Some(Err(error)) => tracing::debug!( ?error, "LoadContacts: contact details sync degraded; using cached state" - ); + ), + None => tracing::debug!( + "LoadContacts: a contact details save is running; using cached state" + ), } backend.dashpay_contact_details(&identity_id).await } @@ -521,6 +528,10 @@ pub async fn load_contacts( HashMap::new() }); + // Recording which details platform-wallet holds must not race a save, + // which stores its details here before it publishes them: with a save + // running, nothing is recorded this time. + let record_guard = app_context.contact_info_writes.try_acquire(identity_id); // Build enriched contact list with basic data let mut contact_list: Vec = contacts .into_iter() @@ -539,6 +550,7 @@ pub async fn load_contacts( false }); if !synced_before + && record_guard.is_some() && holds_details(published.as_ref(), synced.as_ref()) && let Err(error) = backend.dashpay_mark_details_synced(&identity_id, &contact_id) @@ -570,6 +582,8 @@ pub async fn load_contacts( } }) .collect(); + // Saves wait on this guard: it must not be held through the profile reads. + drop(record_guard); // Fetch profiles and usernames for all contacts in parallel with bounded concurrency. // Each contact requires two network queries (profile + DPNS username), so parallelizing @@ -784,24 +798,30 @@ mod tests { use super::*; use std::collections::BTreeMap; - /// The contacts list's details sync waits for a save of the same owner, - /// so it cannot put older published details over the save's own. + /// A details sync is skipped, not queued, while a save of the same owner + /// runs: it would put older published details over the save's own, and + /// waiting would hold the contacts behind the save's password prompt. #[tokio::test] - async fn the_list_details_sync_waits_for_a_save() { + async fn a_details_sync_is_skipped_while_a_save_runs() { use std::sync::atomic::{AtomicBool, Ordering}; + use std::task::Poll; let writes = crate::context::ContactInfoWrites::default(); let owner = Identifier::from([1; 32]); let ran = AtomicBool::new(false); + let sync = || async { + ran.store(true, Ordering::SeqCst); + }; let save = writes.acquire(owner).await; - let mut sync = Box::pin(after_details_saves(&writes, owner, async { - ran.store(true, Ordering::SeqCst); - })); - assert!(futures::poll!(&mut sync).is_pending()); - assert!(!ran.load(Ordering::SeqCst), "the sync waits for the save"); + let mut skipped = Box::pin(unless_saving(&writes, owner, sync())); + assert!(matches!(futures::poll!(&mut skipped), Poll::Ready(None))); + assert!( + !ran.load(Ordering::SeqCst), + "nothing synced during the save" + ); drop(save); - sync.await; + assert_eq!(unless_saving(&writes, owner, sync()).await, Some(())); assert!(ran.load(Ordering::SeqCst)); } diff --git a/src/context/contact_info_writes.rs b/src/context/contact_info_writes.rs index 8d6e17c99..59cd31067 100644 --- a/src/context/contact_info_writes.rs +++ b/src/context/contact_info_writes.rs @@ -14,22 +14,30 @@ pub(crate) struct ContactInfoWrites { impl ContactInfoWrites { /// Hold through the network read, merge and confirmed document write. pub(crate) async fn acquire(&self, owner: Identifier) -> OwnedMutexGuard<()> { - let gate = { - let mut owners = self - .owners - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - owners.retain(|_, gate| gate.strong_count() > 0); - match owners.get(&owner).and_then(Weak::upgrade) { - Some(gate) => gate, - None => { - let gate = Arc::new(AsyncMutex::new(())); - owners.insert(owner, Arc::downgrade(&gate)); - gate - } + self.gate(owner).lock_owned().await + } + + /// [`Self::acquire`] without waiting: `None` while a write holds it. + pub(crate) fn try_acquire(&self, owner: Identifier) -> Option> { + self.gate(owner).try_lock_owned().ok() + } + + /// The owner's gate. The map's std mutex is released on return, never + /// held across an await. + fn gate(&self, owner: Identifier) -> Arc> { + let mut owners = self + .owners + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + owners.retain(|_, gate| gate.strong_count() > 0); + match owners.get(&owner).and_then(Weak::upgrade) { + Some(gate) => gate, + None => { + let gate = Arc::new(AsyncMutex::new(())); + owners.insert(owner, Arc::downgrade(&gate)); + gate } - }; - gate.lock_owned().await + } } } From 41000cbe03d17be2001e876be77f45def22f1e1d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 00:20:28 +0000 Subject: [PATCH 52/73] fix(dashpay): save to and show the newest contactInfo document of a contact A save looked for the contact's document by matching encToUserId only as Value::Bytes, but Platform returns that fixed 32-byte field as Value::Bytes32. A save never found the existing document and created another one. It now reads the field through as_bytes_slice. With two documents for one contact, the save rewrote the oldest and the load showed the oldest. The rewrite makes that document the newest, so the next load showed the untouched one, and the saved note seemed lost. The save and the load now both take the newest document. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contact_info.rs | 65 ++++++++++++++++++++---- src/backend_task/dashpay/contacts.rs | 6 +-- 2 files changed, 56 insertions(+), 15 deletions(-) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 312817105..63a8ea7e9 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -393,10 +393,10 @@ fn has_contact_info_key_material(document: &Document) -> bool { .get("rootEncryptionKeyIndex") .and_then(|value| value.to_integer::().ok()) .is_some() - && matches!( - document.properties().get("encToUserId"), - Some(Value::Bytes(_)) - ) + && document + .properties() + .get("encToUserId") + .is_some_and(|value| value.as_bytes_slice().is_ok()) } fn find_existing_contact_info( @@ -407,7 +407,9 @@ fn find_existing_contact_info( where F: FnMut(u32) -> Result, { - for document in documents { + // Documents come oldest first; the newest match is the one the contacts + // load shows, and a rewrite keeps it the newest. + for document in documents.into_iter().rev() { let Some(derivation_index) = contact_info_derivation_index(&document) else { continue; }; @@ -418,7 +420,12 @@ where let Ok((enc_user_id_key, private_data_key)) = derive_keys(derivation_index) else { continue; }; - let Some(Value::Bytes(enc_user_id)) = document.properties().get("encToUserId") else { + // Platform returns the fixed 32-byte field as `Value::Bytes32`. + let Some(enc_user_id) = document + .properties() + .get("encToUserId") + .and_then(|value| value.as_bytes_slice().ok()) + else { continue; }; if decrypt_to_user_id(enc_user_id, &enc_user_id_key).ok() @@ -945,9 +952,10 @@ mod tests { encrypt_to_user_id(&contact_user_id.to_buffer(), &KEY).expect("encrypt target"); let encrypted_other = encrypt_to_user_id(&id(211).to_buffer(), &KEY).expect("encrypt other"); + // Newest last: the scan starts from the newest document. let documents = vec![ - lookup_contact_info_document(1, 3, encrypted_target), lookup_contact_info_document(2, 4, encrypted_other), + lookup_contact_info_document(1, 3, encrypted_target), ]; let mut derived_indices = Vec::new(); @@ -1266,14 +1274,16 @@ mod tests { assert!(!details.get(&contact).expect("listed").details_unreadable); } - /// With two documents for one contact, the load shows the one a save - /// rewrites: the first in that order. + /// With two documents for one contact, the load shows the newest, the + /// one a save rewrites. A rewrite keeps it the newest, so the load and + /// the save stay on the same document; with the oldest, a rewrite would + /// move it to the end and the load would show the untouched one. #[tokio::test] async fn the_contact_details_load_shows_the_document_a_save_rewrites() { let contact = id(201); let page = contact_details_page([ - saved_note_document(1, contact, "kept"), - saved_note_document(2, contact, "stale"), + saved_note_document(1, contact, "stale"), + saved_note_document(2, contact, "kept"), ]); let (details, _) = load_details(vec![page]).await; @@ -1282,6 +1292,39 @@ mod tests { details.get(&contact).and_then(|c| c.note.as_deref()), Some("kept") ); + + let documents = vec![ + saved_note_document(1, contact, "stale"), + saved_note_document(2, contact, "kept"), + ]; + let existing = find_existing_contact_info(documents, contact, |_| { + Ok((Zeroizing::new(KEY), Zeroizing::new(KEY))) + }); + assert_eq!(existing.map(|existing| existing.derivation_index), Some(2)); + } + + /// Platform returns the fixed 32-byte `encToUserId` as `Value::Bytes32`; + /// a save must still find the contact's document instead of creating a + /// second one. + #[tokio::test] + async fn a_save_finds_a_document_as_platform_returns_it() { + let contact = id(230); + let encrypted = encrypt_to_user_id(&contact.to_buffer(), &KEY).expect("encrypt"); + let mut document = lookup_contact_info_document(1, 5, encrypted); + document.set("encToUserId", Value::Bytes32(encrypted)); + + let lookup = scan_contact_info_documents(vec![document], contact, |documents, target| { + ready(Ok(find_existing_contact_info(documents, target, |_| { + Ok((Zeroizing::new(KEY), Zeroizing::new(OTHER_KEY))) + }))) + }) + .await + .expect("scan"); + + assert_eq!( + lookup.existing.map(|existing| existing.derivation_index), + Some(5) + ); } #[test] diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index 72f2a7f4f..2f6369727 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -181,10 +181,8 @@ where ); continue; }; - if contact_info_map.contains_key(&contact_id) { - continue; - } - + // Documents come oldest first, so the newest replaces older ones: it + // is the one a save rewrites, and the rewrite keeps it the newest. // The DIP-15 codec platform-wallet writes with. A payload that is // present but cannot be opened is not "no details": its hidden flag // is unknown, so the contact stays hidden. From d8ac50ab53bdaa62b7d65a13f834b62502974f04 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 00:27:39 +0000 Subject: [PATCH 53/73] docs(dashpay): say the newest contactInfo document wins, next to its insert Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contacts.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index 2f6369727..c7ba14bdf 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -131,8 +131,9 @@ pub(super) fn decrypt_private_data( /// The nickname, note and visibility the owner stored for each contact, read /// from every page of the owner's `contactInfo` documents. /// -/// Pages follow the order the write lookup scans, and the first document for -/// a contact wins, so the load shows the document a save rewrites. +/// Documents come oldest first, the order the write lookup scans, and the +/// newest document for a contact wins, so the load shows the document a save +/// rewrites. pub(super) async fn load_contact_details( query: DocumentQuery, fetch_page: P, @@ -181,8 +182,6 @@ where ); continue; }; - // Documents come oldest first, so the newest replaces older ones: it - // is the one a save rewrites, and the rewrite keeps it the newest. // The DIP-15 codec platform-wallet writes with. A payload that is // present but cannot be opened is not "no details": its hidden flag // is unknown, so the contact stays hidden. @@ -200,6 +199,8 @@ where ..Default::default() }); + // Documents come oldest first, so the newest replaces older ones: it + // is the one a save rewrites, and the rewrite keeps it the newest. contact_info_map.insert( contact_id, ContactData { From 04793b8baecb5911b215e136498b0ae7c7699120 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:08:40 +0000 Subject: [PATCH 54/73] fix(dashpay): serialize request actions per person and keep declined senders out of contacts - Accept, decline and cancel lock per person, not only per request. A cancel of the owner's request no longer records a withdrawal while an accept of that person's request establishes the contact. - A declined sender is not a contact while the decline stands, even when the owner's own request to them exists. The request lists and the contacts list both apply this, so the sent request stays listed and sending it again finishes the re-engagement. - unless_saving's doc no longer claims a read during a save shows the newest details. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contact_requests.rs | 75 ++++++++++++++++++-- src/backend_task/dashpay/contacts.rs | 12 ++-- src/wallet_backend/dashpay.rs | 2 + 3 files changed, 80 insertions(+), 9 deletions(-) diff --git a/src/backend_task/dashpay/contact_requests.rs b/src/backend_task/dashpay/contact_requests.rs index 7be25c324..b7135024b 100644 --- a/src/backend_task/dashpay/contact_requests.rs +++ b/src/backend_task/dashpay/contact_requests.rs @@ -127,8 +127,9 @@ pub async fn load_contact_requests( } /// Keep only the requests still waiting for an answer: drop the pairs that -/// are contacts (both sides sent a request, unless the owner withdrew theirs — -/// a reply to a withdrawn request is a new request to answer), then every +/// are contacts (both sides sent a request, unless the owner withdrew theirs +/// or declined the other's — a reply to a withdrawn request is a new request +/// to answer), then every /// request the user resolved on this device; see [`retain_unresolved`]. fn pending_requests( incoming: &mut Vec<(Identifier, Document)>, @@ -136,7 +137,11 @@ fn pending_requests( is_declined: impl Fn(&Identifier) -> bool, is_withdrawn: impl Fn(&Identifier) -> bool, ) { - let contacts_established = super::contacts::mutual_contacts(incoming, outgoing, &is_withdrawn); + // A sender the owner declined is not a contact until the owner + // re-engages, which clears the decline. + let contacts_established = super::contacts::mutual_contacts(incoming, outgoing, |peer| { + is_withdrawn(peer) || is_declined(peer) + }); // An outgoing document with an unreadable recipient is kept: it cannot be // attributed, and hiding a request the user may still be waiting on is // the worse failure. @@ -694,6 +699,13 @@ pub async fn accept_contact_request( // Verify the request was addressed to us before acting on it, and get the // sender's identity (the owner of the incoming request). let from_identity_id = sender_of_received_request(&doc, &identity.identity.id())?; + // Accept, decline and cancel lock on the person too: a cancel of the + // owner's request to them must not record a withdrawal while this accept + // establishes the contact. + let _peer_guard = app_context + .wallet_backend()? + .dashpay_lock_contact_request_action(&owner_id, &from_identity_id) + .await; // Check if we already sent a contact request to this identity let mut existing_query = contact_request_query(app_context)?; @@ -995,7 +1007,7 @@ impl RejectOps for PlatformRejectOps<'_> { Ok(self .app_context .wallet_backend()? - .dashpay_lock_contact_request_action(&self.owner_id, &self.request_id) + .dashpay_lock_contact_request_action(&self.owner_id, &self.from_identity_id) .await) } @@ -1121,7 +1133,7 @@ impl CancelOps for PlatformCancelOps<'_> { Ok(self .app_context .wallet_backend()? - .dashpay_lock_contact_request_action(&self.owner_id, &self.request_id) + .dashpay_lock_contact_request_action(&self.owner_id, &self.to_identity_id) .await) } @@ -1418,6 +1430,59 @@ mod tests { assert!(outgoing.is_empty(), "the withdrawn request is not listed"); } + /// A declined sender is not a contact until the owner re-engages, even + /// when the owner's own request to them is still on Platform: that sent + /// request stays listed, so sending it again can finish the update. + #[test] + fn a_declined_sender_with_a_sent_request_is_not_a_contact() { + let owner = id(9); + let mut incoming = vec![(id(10), request_doc(id(3), Some(owner)))]; + let mut outgoing = vec![(id(12), request_doc(owner, Some(id(3))))]; + + pending_requests( + &mut incoming, + &mut outgoing, + |peer| *peer == id(3), + |_| false, + ); + + assert!(incoming.is_empty(), "the declined request stays declined"); + assert_eq!( + outgoing.iter().map(|(id, _)| *id).collect::>(), + vec![id(12)] + ); + } + + /// Actions on requests with the same person run one at a time, whichever + /// request they act on: a cancel must not record a withdrawal while an + /// accept of that person's request establishes the contact. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn request_actions_with_one_person_run_one_at_a_time() { + let dir = tempfile::tempdir().expect("temp dir"); + let app_context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let sdk = app_context.sdk(); + let (owner, peer) = (id(1), id(2)); + let cancel = PlatformCancelOps { + app_context: &app_context, + sdk: &sdk, + owner_id: owner, + to_identity_id: peer, + request_id: id(10), + }; + let decline = PlatformRejectOps { + app_context: &app_context, + owner_id: owner, + from_identity_id: peer, + request_id: id(11), + }; + + let held = cancel.lock_action().await.expect("lock"); + let mut waiting = Box::pin(decline.lock_action()); + assert!(futures::poll!(&mut waiting).is_pending()); + drop(held); + drop(waiting.await.expect("lock")); + } + #[derive(Default)] struct ScriptedReEngage { withdrawn: bool, diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index 9ba9077f1..48667afb6 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -264,7 +264,8 @@ where /// A save stores its details on this device before it publishes them; a /// sync in between would put the older published details back over them. /// A read does not wait for the save, which can sit behind a password prompt -/// or a slow publish: it shows the details this device already holds. +/// or a slow publish. Until the save lands, the read can show the details as +/// they were before it; the contacts list reloads once it does. pub(super) async fn unless_saving( writes: &crate::context::ContactInfoWrites, owner: Identifier, @@ -478,10 +479,13 @@ pub async fn load_contacts( // Find mutual contacts (where both parties have sent requests to each other) let backend = app_context.wallet_backend().ok(); + // As for the request lists: withdrawn and declined people are not + // contacts until the owner re-engages. let contacts = mutual_contacts(&incoming, &outgoing, |peer| { - backend - .as_ref() - .is_some_and(|backend| backend.dashpay_is_withdrawn(&identity_id, peer)) + backend.as_ref().is_some_and(|backend| { + backend.dashpay_is_withdrawn(&identity_id, peer) + || backend.dashpay_is_declined(&identity_id, peer) + }) }); // platform-wallet's synced details first; a refresh failure leaves the diff --git a/src/wallet_backend/dashpay.rs b/src/wallet_backend/dashpay.rs index 606298b16..413b77d62 100644 --- a/src/wallet_backend/dashpay.rs +++ b/src/wallet_backend/dashpay.rs @@ -1373,6 +1373,8 @@ impl WalletBackend { .map_err(|source| TaskError::DashPayLocalStateRead { source }) } + /// Serialize `owner`'s request actions keyed by `request_id`: a request + /// id, or the id of the person the requests are with. pub(crate) async fn dashpay_lock_contact_request_action( &self, owner: &Identifier, From 96e5a92dfe4ae55a332df55882f96eb577b7e28d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:08:40 +0000 Subject: [PATCH 55/73] fix(dashpay): never save over unreadable contact details by accident, and keep a failed publish's details - A save whose baseline stands in for saved details that could not be read is refused with TaskError::DashPayContactDetailsUnreadable when it keeps a text field: the field would be published as empty. Unhiding an unreadable contact replaces its details on purpose, and its hidden-list note says so. - When a publish fails after platform-wallet stored the details on this device, the details are still recorded as held. A cleared field then does not fall back to an older legacy document on reload, as the PR's known limitation describes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contact_info.rs | 160 +++++++++++++++++++---- src/backend_task/error.rs | 7 + src/ui/identity/contacts.rs | 38 ++++-- 3 files changed, 173 insertions(+), 32 deletions(-) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 53934d7c9..00dbbefc9 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -8,7 +8,9 @@ use crate::backend_task::BackendTaskSuccessResult; use crate::backend_task::error::TaskError; use crate::context::AppContext; -use crate::model::dashpay::{ContactDetails, ContactInfoUpdate, validate_contact_note}; +use crate::model::dashpay::{ + ContactDetails, ContactInfoField, ContactInfoUpdate, validate_contact_note, +}; use crate::model::qualified_identity::QualifiedIdentity; use crate::wallet_backend::WalletBackend; use dash_sdk::Sdk; @@ -115,7 +117,8 @@ pub async fn load_contact_details( { synced?; } - let details = shown_details_for(app_context, sdk, &backend, &identity, &contact_id).await?; + let (details, _) = + shown_details_for(app_context, sdk, &backend, &identity, &contact_id).await?; Ok(BackendTaskSuccessResult::DashPayContactDetails { identity: identity.identity.id(), contact_id, @@ -125,7 +128,8 @@ pub async fn load_contact_details( /// The details shown for `contact_id`, with the precedence of /// [`super::contacts::shown_contact_details`]: published, then -/// platform-wallet's on this device, then a legacy-key document. +/// platform-wallet's on this device, then a legacy-key document; and whether +/// they stand in for saved details that could not be read. /// /// # Errors /// @@ -139,36 +143,37 @@ async fn shown_details_for( backend: &WalletBackend, identity: &QualifiedIdentity, contact_id: &Identifier, -) -> Result { +) -> Result<(ContactDetails, bool), TaskError> { let owner = identity.identity.id(); let local = backend .dashpay_contact_details(&owner) .await .remove(contact_id); let stored = super::contacts::stored_contact_details(app_context, sdk, identity).await?; - let published = stored - .published? - .take(contact_id) - .map(|(details, _)| details); + let (published, published_unreadable) = match stored.published?.take(contact_id) { + Some((details, unreadable)) => (Some(details), unreadable), + None => (None, false), + }; let legacy = stored.legacy?; let synced_before = backend.dashpay_details_synced(&owner, contact_id)? || super::contacts::holds_details(published.as_ref(), local.as_ref()); - let legacy = legacy - .get(contact_id) - .map(super::contacts::ContactData::details); - Ok(super::contacts::shown_contact_details( - published, - local, - synced_before, - legacy, + let legacy = legacy.get(contact_id); + let unreadable = published_unreadable + || super::contacts::legacy_details_shown(published.as_ref(), local.as_ref(), synced_before) + && legacy.is_some_and(|legacy| legacy.details_unreadable); + let legacy = legacy.map(super::contacts::ContactData::details); + Ok(( + super::contacts::shown_contact_details(published, local, synced_before, legacy), + unreadable, )) } /// The reads and writes one contact details save performs, behind a trait so /// their order and failures can be driven in tests. trait SaveOps { - /// The details shown for the contact now; the fields an update keeps. - fn current(&self) -> impl Future> + Send; + /// The details shown for the contact now, the fields an update keeps, and + /// whether they are a stand-in for saved details that could not be read. + fn current(&self) -> impl Future> + Send; fn publish( &self, details: ContactDetails, @@ -176,6 +181,8 @@ trait SaveOps { /// Record that platform-wallet holds the contact's details, so a legacy /// document no longer stands in for them. fn mark_synced(&self) -> Result<(), TaskError>; + /// Whether platform-wallet holds `details` for the contact on this device. + fn holds_locally(&self, details: &ContactDetails) -> impl Future + Send; } /// Save `update` and return whether the details reached Platform. @@ -190,7 +197,16 @@ async fn save_contact_details( ops: &O, update: &ContactInfoUpdate, ) -> Result { - let details = update.apply_to(ops.current().await?); + let (current, unreadable) = ops.current().await?; + // Unreadable saved details are not empty ones: a text field the update + // keeps would be published as empty, and the saved one lost. + if unreadable + && (matches!(update.nickname, ContactInfoField::Preserve) + || matches!(update.note, ContactInfoField::Preserve)) + { + return Err(TaskError::DashPayContactDetailsUnreadable); + } + let details = update.apply_to(current); validate_contact_note(details.note.as_deref().unwrap_or_default())?; // The bound platform-wallet enforces, checked before it saves anything. @@ -204,7 +220,20 @@ async fn save_contact_details( source: Box::new(source), })?; - let outcome = ops.publish(details).await?; + let outcome = match ops.publish(details.clone()).await { + Ok(outcome) => outcome, + Err(error) => { + // platform-wallet stores the details here before it publishes + // them. Once it has, a legacy document must not stand in for them + // on reload: this device stays ahead of Platform until next save. + if ops.holds_locally(&details).await + && let Err(mark) = ops.mark_synced() + { + tracing::debug!(error = ?mark, "contact details held here but not recorded"); + } + return Err(error); + } + }; match ops.mark_synced() { Ok(()) => {} // A deferred save published nothing, so the storage error's claim @@ -236,7 +265,7 @@ struct PlatformSaveOps<'a> { } impl SaveOps for PlatformSaveOps<'_> { - async fn current(&self) -> Result { + async fn current(&self) -> Result<(ContactDetails, bool), TaskError> { // The save holds the owner's write lock, so this sync cannot race one. self.backend .dashpay_sync_contact_infos(&self.identity.identity.id()) @@ -265,6 +294,14 @@ impl SaveOps for PlatformSaveOps<'_> { self.backend .dashpay_mark_details_synced(&self.identity.identity.id(), &self.contact_id) } + + async fn holds_locally(&self, details: &ContactDetails) -> bool { + self.backend + .dashpay_contact_details(&self.identity.identity.id()) + .await + .get(&self.contact_id) + == Some(details) + } } #[cfg(test)] @@ -405,7 +442,11 @@ mod tests { struct ScriptedSave { current: std::sync::Mutex>>, + unreadable: bool, mark_fails: bool, + marked: std::sync::Mutex, + publish_fails: bool, + holds_locally: bool, outcome: ContactInfoPublishOutcome, published: std::sync::Mutex>, } @@ -414,7 +455,11 @@ mod tests { fn new(current: Result, mark_fails: bool) -> Self { Self { current: std::sync::Mutex::new(Some(current)), + unreadable: false, mark_fails, + marked: std::sync::Mutex::new(false), + publish_fails: false, + holds_locally: false, outcome: ContactInfoPublishOutcome::DeferredUntilTwoContacts, published: std::sync::Mutex::new(Vec::new()), } @@ -427,24 +472,37 @@ mod tests { } impl SaveOps for ScriptedSave { - async fn current(&self) -> Result { - self.current.lock().unwrap().take().expect("read once") + async fn current(&self) -> Result<(ContactDetails, bool), TaskError> { + self.current + .lock() + .unwrap() + .take() + .expect("read once") + .map(|details| (details, self.unreadable)) } async fn publish( &self, details: ContactDetails, ) -> Result { + if self.publish_fails { + return Err(TaskError::WalletStateInconsistent); + } self.published.lock().unwrap().push(details); Ok(self.outcome) } + async fn holds_locally(&self, _details: &ContactDetails) -> bool { + self.holds_locally + } + fn mark_synced(&self) -> Result<(), TaskError> { if self.mark_fails { return Err(TaskError::DashpaySidecarStorage { source: crate::wallet_backend::KvAdapterError::Truncated, }); } + *self.marked.lock().unwrap() = true; Ok(()) } } @@ -462,6 +520,62 @@ mod tests { assert!(ops.published.lock().unwrap().is_empty()); } + /// A publish that fails after platform-wallet stored the details here + /// still records them as held, so a cleared field does not fall back to + /// an older legacy document on reload: this device stays ahead of + /// Platform until the next save. The save is still reported as failed. + #[tokio::test] + async fn a_failed_publish_of_details_held_here_records_them() { + for holds_locally in [true, false] { + let ops = ScriptedSave { + publish_fails: true, + holds_locally, + ..ScriptedSave::new(Ok(ContactDetails::default()), false) + }; + + let result = + save_contact_details(&ops, &ContactInfoUpdate::replace_all(None, None, false)) + .await; + + assert!(result.is_err()); + assert_eq!(*ops.marked.lock().unwrap(), holds_locally); + } + } + + /// Saved details that could not be read are not empty ones: a save that + /// keeps a text field would publish it as empty and lose it. Only an + /// update that replaces every text field may write over them. + #[tokio::test] + async fn unreadable_saved_details_are_replaced_only_on_purpose() { + let unreadable = || ScriptedSave { + unreadable: true, + ..ScriptedSave::new( + Ok(ContactDetails { + hidden: true, + ..Default::default() + }), + false, + ) + }; + + let ops = unreadable(); + let result = save_contact_details(&ops, &ContactInfoUpdate::visibility(false)).await; + assert!(matches!( + result, + Err(TaskError::DashPayContactDetailsUnreadable) + )); + assert!(ops.published.lock().unwrap().is_empty()); + + let ops = unreadable(); + save_contact_details(&ops, &ContactInfoUpdate::replace_all(None, None, false)) + .await + .expect("an explicit replacement"); + assert_eq!( + *ops.published.lock().unwrap(), + vec![ContactDetails::default()] + ); + } + /// A published save whose synced record fails is not reported as saved: /// on reload the old legacy details would show again. The details did /// reach the network, and the error says so. diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index a68d9dee3..fc3c4b6fb 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -1467,6 +1467,13 @@ pub enum TaskError { source: crate::wallet_backend::KvAdapterError, }, + /// The details saved for a contact could not be read, and a save would + /// keep some of them: it would publish them as empty. Nothing was saved. + #[error( + "The details saved for this contact could not be read, so nothing was changed. Unhide the contact in the Contacts tab to replace them, then edit it." + )] + DashPayContactDetailsUnreadable, + /// A contact-details save that stayed on this device, because publishing /// waits for a second contact, could not record which details this device /// holds; on reload the older details would show again. diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index 4807a9fef..24c14d9fb 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -83,7 +83,7 @@ pub const SHOW_HIDDEN_LABEL: &str = "Show hidden contacts"; /// Shown under a hidden contact whose saved details could not be read: its /// hidden flag is unknown, so it stays hidden until the user unhides it. pub const UNREADABLE_DETAILS_NOTE: &str = "The details you saved for this contact could not be read, so it stays \ - hidden. Unhide it to show it in your list again."; + hidden. Unhide it to show it in your list again; this clears the unreadable details."; /// Hidden-section caption. Only an explicit hide puts a contact here; /// declining or cancelling a request writes no contact details. @@ -299,18 +299,19 @@ pub fn request_task( } } -/// Backend task that makes a hidden contact visible again. -/// -/// Unhiding is a `contactInfo` broadcast with `display_hidden` cleared — the -/// same document the decline / cancel paths set it on. The whole document is -/// rewritten, so everything unhiding has no opinion about rides along untouched: -/// the nickname and note are carried over, and the accepted accounts are -/// preserved rather than replaced with an empty list. +/// Backend task that makes a hidden contact visible again, keeping its +/// nickname and note. Details that could not be read cannot be kept: unhiding +/// such a contact replaces them, as its note in the hidden list says. pub fn unhide_task(identity: QualifiedIdentity, contact: &ContactData) -> DashPayTask { + let update = if contact.details_unreadable { + ContactInfoUpdate::replace_all(None, None, false) + } else { + ContactInfoUpdate::visibility(false) + }; DashPayTask::UpdateContactInfo { identity, contact_id: contact.identity_id, - update: ContactInfoUpdate::visibility(false), + update, } } @@ -1522,6 +1523,25 @@ mod tests { ); } + /// Unhiding keeps a readable contact's nickname and note, and replaces + /// unreadable ones on purpose: the backend refuses to keep them. + #[test] + fn unhiding_replaces_only_unreadable_details() { + let unhide = |contact: &ContactData| match unhide_task(qualified_identity(id(1)), contact) { + DashPayTask::UpdateContactInfo { update, .. } => update, + other => panic!("expected UpdateContactInfo, got {other:?}"), + }; + assert_eq!(unhide(&hidden_bao()), ContactInfoUpdate::visibility(false)); + let unreadable = ContactData { + details_unreadable: true, + ..hidden_bao() + }; + assert_eq!( + unhide(&unreadable), + ContactInfoUpdate::replace_all(None, None, false) + ); + } + fn hidden_bao() -> ContactData { ContactData { is_hidden: true, From ee6b5cafccc41fdbcedb3cc8e32b9eb072c3b887 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:08:40 +0000 Subject: [PATCH 56/73] test(dashpay): generate the contact info provider tests' seed at run time Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/wallet_backend/contact_info.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/wallet_backend/contact_info.rs b/src/wallet_backend/contact_info.rs index 669381bbd..0abfcba0a 100644 --- a/src/wallet_backend/contact_info.rs +++ b/src/wallet_backend/contact_info.rs @@ -552,7 +552,8 @@ impl ContactCryptoProvider for ContactInfoCrypto<'_> { mod tests { use super::*; - const SEED: [u8; 64] = [0x42; 64]; + /// Generated each run, so no seed bytes are committed. + static SEED: std::sync::LazyLock<[u8; 64]> = std::sync::LazyLock::new(rand::random); const NETWORK: Network = Network::Testnet; const IDENTITY_INDEX: u32 = 1; @@ -567,7 +568,7 @@ mod tests { } fn upstream_keys(key_id: u32, derivation_index: u32) -> ContactInfoKeys { - let wallet = Wallet::from_seed_bytes(SEED, NETWORK, WalletAccountCreationOptions::None) + let wallet = Wallet::from_seed_bytes(*SEED, NETWORK, WalletAccountCreationOptions::None) .expect("wallet"); derive_contact_info_keys(&wallet, NETWORK, IDENTITY_INDEX, key_id, derivation_index) .expect("upstream keys") @@ -818,7 +819,7 @@ mod tests { let dir = tempfile::tempdir().expect("temp dir"); let context = crate::context::test_support::wired_test_app_context(dir.path()).await; let backend = context.wallet_backend().expect("backend wired"); - let wallet = DetWallet::new_from_seed(SEED, NETWORK, None, None).expect("wallet"); + let wallet = DetWallet::new_from_seed(*SEED, NETWORK, None, None).expect("wallet"); let mut identity = crate::context::test_support::bare_user_identity(Identifier::from([5; 32]), NETWORK); identity.associated_wallets = From b8fcb59f1e8497fc2557b8468e6b93f1f7864517 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:25:23 +0000 Subject: [PATCH 57/73] fix(dashpay): record nothing on a failed publish, and let the backend decide what unhide replaces - A failed publish no longer marks the details synced. platform-wallet's error does not say whether it stored them first, and an empty attempt equals empty details that were never stored, so the marker could hide legacy details nothing replaced. - Unhide always sends a visibility update. Over details the save reads as unreadable, the backend replaces them, as the hidden list says. A stale list flag can no longer wipe details that have since become readable. Other saves that keep a text field over unreadable details stay refused. - The unreadable-baseline rule is a pure function with its own test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contact_info.rs | 202 ++++++++++++++--------- src/model/dashpay.rs | 6 + src/ui/identity/contacts.rs | 30 +--- 3 files changed, 137 insertions(+), 101 deletions(-) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 00dbbefc9..f7de8944b 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -8,9 +8,7 @@ use crate::backend_task::BackendTaskSuccessResult; use crate::backend_task::error::TaskError; use crate::context::AppContext; -use crate::model::dashpay::{ - ContactDetails, ContactInfoField, ContactInfoUpdate, validate_contact_note, -}; +use crate::model::dashpay::{ContactDetails, ContactInfoUpdate, validate_contact_note}; use crate::model::qualified_identity::QualifiedIdentity; use crate::wallet_backend::WalletBackend; use dash_sdk::Sdk; @@ -158,9 +156,13 @@ async fn shown_details_for( let synced_before = backend.dashpay_details_synced(&owner, contact_id)? || super::contacts::holds_details(published.as_ref(), local.as_ref()); let legacy = legacy.get(contact_id); - let unreadable = published_unreadable - || super::contacts::legacy_details_shown(published.as_ref(), local.as_ref(), synced_before) - && legacy.is_some_and(|legacy| legacy.details_unreadable); + let unreadable = baseline_unreadable( + published_unreadable, + published.as_ref(), + local.as_ref(), + synced_before, + legacy, + ); let legacy = legacy.map(super::contacts::ContactData::details); Ok(( super::contacts::shown_contact_details(published, local, synced_before, legacy), @@ -168,6 +170,21 @@ async fn shown_details_for( )) } +/// Whether the shown details stand in for saved ones that could not be read: +/// a published document that did not open, or an unreadable legacy document +/// while it is the one shown. +fn baseline_unreadable( + published_unreadable: bool, + published: Option<&ContactDetails>, + local: Option<&ContactDetails>, + synced_before: bool, + legacy: Option<&super::contacts::ContactData>, +) -> bool { + published_unreadable + || super::contacts::legacy_details_shown(published, local, synced_before) + && legacy.is_some_and(|legacy| legacy.details_unreadable) +} + /// The reads and writes one contact details save performs, behind a trait so /// their order and failures can be driven in tests. trait SaveOps { @@ -181,8 +198,6 @@ trait SaveOps { /// Record that platform-wallet holds the contact's details, so a legacy /// document no longer stands in for them. fn mark_synced(&self) -> Result<(), TaskError>; - /// Whether platform-wallet holds `details` for the contact on this device. - fn holds_locally(&self, details: &ContactDetails) -> impl Future + Send; } /// Save `update` and return whether the details reached Platform. @@ -191,19 +206,20 @@ trait SaveOps { /// /// Nothing is written when the current details cannot be read (a cancelled /// password prompt included): a field the update keeps would otherwise be -/// saved from a guess. A save whose synced record fails is reported as -/// failed, since the old legacy details would show again on reload. +/// saved from a guess. Over saved details that could not be read, a save that +/// keeps a text field, other than unhiding, is refused with +/// [`TaskError::DashPayContactDetailsUnreadable`]. A save whose synced record +/// fails is reported as failed, since the old legacy details would show +/// again on reload. async fn save_contact_details( ops: &O, update: &ContactInfoUpdate, ) -> Result { let (current, unreadable) = ops.current().await?; // Unreadable saved details are not empty ones: a text field the update - // keeps would be published as empty, and the saved one lost. - if unreadable - && (matches!(update.nickname, ContactInfoField::Preserve) - || matches!(update.note, ContactInfoField::Preserve)) - { + // keeps would be published as empty, and the saved one lost. Unhiding + // replaces them on purpose, as the hidden list says. + if unreadable && update.keeps_text() && *update != ContactInfoUpdate::visibility(false) { return Err(TaskError::DashPayContactDetailsUnreadable); } let details = update.apply_to(current); @@ -220,20 +236,10 @@ async fn save_contact_details( source: Box::new(source), })?; - let outcome = match ops.publish(details.clone()).await { - Ok(outcome) => outcome, - Err(error) => { - // platform-wallet stores the details here before it publishes - // them. Once it has, a legacy document must not stand in for them - // on reload: this device stays ahead of Platform until next save. - if ops.holds_locally(&details).await - && let Err(mark) = ops.mark_synced() - { - tracing::debug!(error = ?mark, "contact details held here but not recorded"); - } - return Err(error); - } - }; + // A failed publish records nothing. platform-wallet stores the details + // here before it publishes, but its error does not say whether it got + // that far, and an attempt can equal details that were never stored. + let outcome = ops.publish(details).await?; match ops.mark_synced() { Ok(()) => {} // A deferred save published nothing, so the storage error's claim @@ -294,14 +300,6 @@ impl SaveOps for PlatformSaveOps<'_> { self.backend .dashpay_mark_details_synced(&self.identity.identity.id(), &self.contact_id) } - - async fn holds_locally(&self, details: &ContactDetails) -> bool { - self.backend - .dashpay_contact_details(&self.identity.identity.id()) - .await - .get(&self.contact_id) - == Some(details) - } } #[cfg(test)] @@ -446,7 +444,6 @@ mod tests { mark_fails: bool, marked: std::sync::Mutex, publish_fails: bool, - holds_locally: bool, outcome: ContactInfoPublishOutcome, published: std::sync::Mutex>, } @@ -459,7 +456,6 @@ mod tests { mark_fails, marked: std::sync::Mutex::new(false), publish_fails: false, - holds_locally: false, outcome: ContactInfoPublishOutcome::DeferredUntilTwoContacts, published: std::sync::Mutex::new(Vec::new()), } @@ -492,10 +488,6 @@ mod tests { Ok(self.outcome) } - async fn holds_locally(&self, _details: &ContactDetails) -> bool { - self.holds_locally - } - fn mark_synced(&self) -> Result<(), TaskError> { if self.mark_fails { return Err(TaskError::DashpaySidecarStorage { @@ -520,33 +512,90 @@ mod tests { assert!(ops.published.lock().unwrap().is_empty()); } - /// A publish that fails after platform-wallet stored the details here - /// still records them as held, so a cleared field does not fall back to - /// an older legacy document on reload: this device stays ahead of - /// Platform until the next save. The save is still reported as failed. + /// The baseline is unreadable when the published document did not open, + /// or when an unreadable legacy document is the one shown; not when + /// readable details shown ahead of it replace it. + #[test] + fn a_baseline_is_unreadable_only_when_unreadable_details_are_shown() { + let legacy = |details_unreadable| super::super::contacts::ContactData { + identity_id: Identifier::default(), + nickname: None, + note: None, + is_hidden: true, + details_unreadable, + account_reference: 0, + username: None, + display_name: None, + avatar_url: None, + bio: None, + }; + let saved = ContactDetails { + note: Some("n".into()), + ..Default::default() + }; + + assert!(baseline_unreadable(true, Some(&saved), None, true, None)); + assert!(baseline_unreadable( + false, + None, + None, + false, + Some(&legacy(true)) + )); + assert!(!baseline_unreadable( + false, + None, + None, + false, + Some(&legacy(false)) + )); + assert!(!baseline_unreadable( + false, + Some(&saved), + None, + false, + Some(&legacy(true)) + )); + assert!(!baseline_unreadable( + false, + None, + Some(&saved), + false, + Some(&legacy(true)) + )); + assert!(!baseline_unreadable( + false, + None, + None, + true, + Some(&legacy(true)) + )); + } + + /// A failed publish records nothing, even when this device's details + /// already equal the attempt: platform-wallet's error does not say + /// whether it stored them first, and an empty attempt equals empty + /// details that were never stored. #[tokio::test] - async fn a_failed_publish_of_details_held_here_records_them() { - for holds_locally in [true, false] { - let ops = ScriptedSave { - publish_fails: true, - holds_locally, - ..ScriptedSave::new(Ok(ContactDetails::default()), false) - }; - - let result = - save_contact_details(&ops, &ContactInfoUpdate::replace_all(None, None, false)) - .await; - - assert!(result.is_err()); - assert_eq!(*ops.marked.lock().unwrap(), holds_locally); - } + async fn a_failed_publish_records_nothing() { + let ops = ScriptedSave { + publish_fails: true, + ..ScriptedSave::new(Ok(ContactDetails::default()), false) + }; + + let result = + save_contact_details(&ops, &ContactInfoUpdate::replace_all(None, None, false)).await; + + assert!(result.is_err()); + assert!(!*ops.marked.lock().unwrap()); } /// Saved details that could not be read are not empty ones: a save that - /// keeps a text field would publish it as empty and lose it. Only an - /// update that replaces every text field may write over them. + /// keeps a text field would publish it as empty and lose it. Unhiding is + /// the one such save allowed, since the hidden list says it clears them; + /// the backend decides from the details it reads, not the list's flag. #[tokio::test] - async fn unreadable_saved_details_are_replaced_only_on_purpose() { + async fn unreadable_saved_details_are_replaced_only_by_unhiding() { let unreadable = || ScriptedSave { unreadable: true, ..ScriptedSave::new( @@ -558,18 +607,23 @@ mod tests { ) }; - let ops = unreadable(); - let result = save_contact_details(&ops, &ContactInfoUpdate::visibility(false)).await; - assert!(matches!( - result, - Err(TaskError::DashPayContactDetailsUnreadable) - )); - assert!(ops.published.lock().unwrap().is_empty()); + for update in [ + ContactInfoUpdate::note(Some("n".into())), + ContactInfoUpdate::visibility(true), + ] { + let ops = unreadable(); + let result = save_contact_details(&ops, &update).await; + assert!( + matches!(result, Err(TaskError::DashPayContactDetailsUnreadable)), + "{update:?}" + ); + assert!(ops.published.lock().unwrap().is_empty()); + } let ops = unreadable(); - save_contact_details(&ops, &ContactInfoUpdate::replace_all(None, None, false)) + save_contact_details(&ops, &ContactInfoUpdate::visibility(false)) .await - .expect("an explicit replacement"); + .expect("unhiding replaces them"); assert_eq!( *ops.published.lock().unwrap(), vec![ContactDetails::default()] diff --git a/src/model/dashpay.rs b/src/model/dashpay.rs index 9bf18ef56..b0087d648 100644 --- a/src/model/dashpay.rs +++ b/src/model/dashpay.rs @@ -165,6 +165,12 @@ impl ContactInfoUpdate { } } + /// Whether the update keeps the saved nickname or note. + pub fn keeps_text(&self) -> bool { + matches!(self.nickname, ContactInfoField::Preserve) + || matches!(self.note, ContactInfoField::Preserve) + } + /// Replace only the fields that differ between `opened`, the details an /// editor started from, and `edited`, what the user left in it; every /// other field keeps the latest saved value. diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index 24c14d9fb..d2e89395d 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -300,18 +300,13 @@ pub fn request_task( } /// Backend task that makes a hidden contact visible again, keeping its -/// nickname and note. Details that could not be read cannot be kept: unhiding -/// such a contact replaces them, as its note in the hidden list says. +/// nickname and note. Details that could not be read cannot be kept: the +/// backend replaces them when it reads them so, as the hidden list says. pub fn unhide_task(identity: QualifiedIdentity, contact: &ContactData) -> DashPayTask { - let update = if contact.details_unreadable { - ContactInfoUpdate::replace_all(None, None, false) - } else { - ContactInfoUpdate::visibility(false) - }; DashPayTask::UpdateContactInfo { identity, contact_id: contact.identity_id, - update, + update: ContactInfoUpdate::visibility(false), } } @@ -1523,25 +1518,6 @@ mod tests { ); } - /// Unhiding keeps a readable contact's nickname and note, and replaces - /// unreadable ones on purpose: the backend refuses to keep them. - #[test] - fn unhiding_replaces_only_unreadable_details() { - let unhide = |contact: &ContactData| match unhide_task(qualified_identity(id(1)), contact) { - DashPayTask::UpdateContactInfo { update, .. } => update, - other => panic!("expected UpdateContactInfo, got {other:?}"), - }; - assert_eq!(unhide(&hidden_bao()), ContactInfoUpdate::visibility(false)); - let unreadable = ContactData { - details_unreadable: true, - ..hidden_bao() - }; - assert_eq!( - unhide(&unreadable), - ContactInfoUpdate::replace_all(None, None, false) - ); - } - fn hidden_bao() -> ContactData { ContactData { is_hidden: true, From c0a81af25292819833c64ebc4f3b64f1b3d6cf97 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:25:23 +0000 Subject: [PATCH 58/73] test(dashpay): pin that every send retires a decline, and share the not-a-contact rule - One WalletBackend predicate, dashpay_disengaged_from, decides whether a withdrawal or decline keeps a pair from being contacts in load_contacts. - A wired test checks that the re-engagement every send runs, a first send included, clears both markers. - Reflow the pending_requests doc. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contact_requests.rs | 31 ++++++++++++++++++-- src/backend_task/dashpay/contacts.rs | 7 ++--- src/wallet_backend/dashpay.rs | 6 ++++ 3 files changed, 38 insertions(+), 6 deletions(-) diff --git a/src/backend_task/dashpay/contact_requests.rs b/src/backend_task/dashpay/contact_requests.rs index b7135024b..ccdc93ec4 100644 --- a/src/backend_task/dashpay/contact_requests.rs +++ b/src/backend_task/dashpay/contact_requests.rs @@ -129,8 +129,8 @@ pub async fn load_contact_requests( /// Keep only the requests still waiting for an answer: drop the pairs that /// are contacts (both sides sent a request, unless the owner withdrew theirs /// or declined the other's — a reply to a withdrawn request is a new request -/// to answer), then every -/// request the user resolved on this device; see [`retain_unresolved`]. +/// to answer), then every request the user resolved on this device; see +/// [`retain_unresolved`]. fn pending_requests( incoming: &mut Vec<(Identifier, Document)>, outgoing: &mut Vec<(Identifier, Document)>, @@ -1453,6 +1453,33 @@ mod tests { ); } + /// Every send re-engages, a first one included: a declined or withdrawn + /// person is a contact again once the owner sends them a request. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_send_retires_a_decline_and_a_withdrawal() { + let dir = tempfile::tempdir().expect("temp dir"); + let app_context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = app_context.wallet_backend().expect("backend"); + let (owner, peer) = (id(1), id(2)); + backend + .dashpay_mark_declined(&owner, &peer) + .expect("decline"); + backend + .dashpay_mark_withdrawn(&owner, &peer) + .expect("withdraw"); + assert!(backend.dashpay_disengaged_from(&owner, &peer)); + + re_engage_after_send(&PlatformReEngage { + backend: &backend, + owner, + peer, + }) + .await + .expect("re-engaged"); + + assert!(!backend.dashpay_disengaged_from(&owner, &peer)); + } + /// Actions on requests with the same person run one at a time, whichever /// request they act on: a cancel must not record a withdrawal while an /// accept of that person's request establishes the contact. diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index 48667afb6..dce87720d 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -482,10 +482,9 @@ pub async fn load_contacts( // As for the request lists: withdrawn and declined people are not // contacts until the owner re-engages. let contacts = mutual_contacts(&incoming, &outgoing, |peer| { - backend.as_ref().is_some_and(|backend| { - backend.dashpay_is_withdrawn(&identity_id, peer) - || backend.dashpay_is_declined(&identity_id, peer) - }) + backend + .as_ref() + .is_some_and(|backend| backend.dashpay_disengaged_from(&identity_id, peer)) }); // platform-wallet's synced details first; a refresh failure leaves the diff --git a/src/wallet_backend/dashpay.rs b/src/wallet_backend/dashpay.rs index 413b77d62..c06041510 100644 --- a/src/wallet_backend/dashpay.rs +++ b/src/wallet_backend/dashpay.rs @@ -1260,6 +1260,12 @@ impl WalletBackend { .map_err(|source| TaskError::DashPayLocalStateRead { source }) } + /// Whether `owner` withdrew their request to `peer` or declined `peer`'s: + /// either keeps the pair from being contacts until the owner re-engages. + pub fn dashpay_disengaged_from(&self, owner: &Identifier, peer: &Identifier) -> bool { + self.dashpay_is_withdrawn(owner, peer) || self.dashpay_is_declined(owner, peer) + } + /// Clear `owner`'s decline marker for `counterparty_id`. Idempotent — /// clearing an absent marker is `Ok(())`. /// From d00edb084f03df1c5bc7395e194fad0fdc5ed57d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:27:34 +0000 Subject: [PATCH 59/73] refactor(dashpay): name the unhide-only update instead of comparing to a constructor ContactInfoUpdate::unhides_only checks the fields directly, so the unreadable-baseline rule doesn't depend on how the constructor builds the update. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/dashpay/contact_info.rs | 2 +- src/model/dashpay.rs | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index f7de8944b..5494e31ff 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -219,7 +219,7 @@ async fn save_contact_details( // Unreadable saved details are not empty ones: a text field the update // keeps would be published as empty, and the saved one lost. Unhiding // replaces them on purpose, as the hidden list says. - if unreadable && update.keeps_text() && *update != ContactInfoUpdate::visibility(false) { + if unreadable && update.keeps_text() && !update.unhides_only() { return Err(TaskError::DashPayContactDetailsUnreadable); } let details = update.apply_to(current); diff --git a/src/model/dashpay.rs b/src/model/dashpay.rs index b0087d648..a2996ed3a 100644 --- a/src/model/dashpay.rs +++ b/src/model/dashpay.rs @@ -171,6 +171,13 @@ impl ContactInfoUpdate { || matches!(self.note, ContactInfoField::Preserve) } + /// Whether the update only unhides the contact. + pub fn unhides_only(&self) -> bool { + matches!(self.nickname, ContactInfoField::Preserve) + && matches!(self.note, ContactInfoField::Preserve) + && matches!(self.display_hidden, ContactInfoField::Replace(false)) + } + /// Replace only the fields that differ between `opened`, the details an /// editor started from, and `edited`, what the user left in it; every /// other field keeps the latest saved value. From 4887235e2fa0259bc1be6cfe373e035e593aa69a Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:57:28 +0000 Subject: [PATCH 60/73] refactor(dashpay): build and use contact QR codes through platform-wallet MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace DET's own DIP-15 auto-accept code with platform-wallet's. - The QR owner's auto-accept key is now derived from the wallet seed, lent by the secret seam, at m/9'/coin'/16'/expiry'. Before, DET fed the identity's ENCRYPTION private key into the derivation as if it were the seed, so the key did not follow DIP-15. - platform-wallet's build_auto_accept_qr builds the code. A narrow provider (AutoAcceptKeyExport) serves only that path and refuses every other path and every other crypto request. - Codes use DIP-15's `dash:?du=&dapk=…` instead of the non-standard `di=`. Codes from older builds no longer scan. - A code is valid for one hour, as platform-wallet fixes it, because it carries a usable key. The validity and account-index fields are removed. - Scanned codes are parsed and validated once in model::dashpay_contact_qr. The proof is signed with platform-wallet's sign_auto_accept_proof over the final accountReference, and the recipient is resolved from the code's username. - The unused receive-side handler, DET's proof codec, and derive_auto_accept_key are removed. The stringly-typed InvalidQrCode is replaced with typed errors. Co-Authored-By: Claude Opus 5.5 --- src/backend_task/dashpay.rs | 79 ++-- .../dashpay/auto_accept_handler.rs | 117 ------ src/backend_task/dashpay/auto_accept_proof.rs | 365 ------------------ src/backend_task/dashpay/contact_requests.rs | 27 +- src/backend_task/dashpay/errors.rs | 27 +- src/model/dashpay_contact_qr.rs | 240 ++++++++++++ src/model/dashpay_derivation/hd.rs | 68 +--- src/model/dashpay_derivation/mod.rs | 9 +- src/model/mod.rs | 1 + src/ui/dashpay/qr_code_generator.rs | 107 +---- src/ui/dashpay/qr_scanner.rs | 39 +- src/wallet_backend/auto_accept.rs | 358 +++++++++++++++++ src/wallet_backend/mod.rs | 1 + 13 files changed, 710 insertions(+), 728 deletions(-) delete mode 100644 src/backend_task/dashpay/auto_accept_handler.rs delete mode 100644 src/backend_task/dashpay/auto_accept_proof.rs create mode 100644 src/model/dashpay_contact_qr.rs create mode 100644 src/wallet_backend/auto_accept.rs diff --git a/src/backend_task/dashpay.rs b/src/backend_task/dashpay.rs index 2ca68c35b..13de552a1 100644 --- a/src/backend_task/dashpay.rs +++ b/src/backend_task/dashpay.rs @@ -4,8 +4,6 @@ use crate::context::AppContext; use dash_sdk::Sdk; use std::sync::Arc; -pub mod auto_accept_handler; -pub mod auto_accept_proof; pub mod avatar_processing; pub mod contact_info; pub mod contact_requests; @@ -91,12 +89,13 @@ pub enum DashPayTask { to_username: String, account_label: Option, }, + /// Send a contact request to the owner of a scanned contact QR code, + /// carrying the `autoAcceptProof` the code's key signs, so the owner's + /// wallet can accept it without asking. SendContactRequestWithProof { identity: QualifiedIdentity, signing_key: IdentityPublicKey, - to_identity_id: Identifier, - account_label: Option, - qr_auto_accept: crate::backend_task::dashpay::auto_accept_proof::AutoAcceptProofData, + qr_code: crate::model::dashpay_contact_qr::ContactQrCode, }, AcceptContactRequest { identity: QualifiedIdentity, @@ -144,13 +143,12 @@ pub enum DashPayTask { DetectIncomingContactPayments { outputs: Vec, }, - /// Build an auto-accept contact QR payload. Resolves the ENCRYPTION key and - /// derives the auto-accept key through the JIT chokepoint in the backend, so - /// the UI never reads a seed. + /// Build a contact QR code (DIP-0015 auto-accept) for `identity`, valid + /// for one hour. platform-wallet builds it; the auto-accept key comes from + /// the identity's wallet seed through the secret seam, so the UI never + /// reads a seed. GenerateAutoAcceptQrCode { identity: QualifiedIdentity, - account_reference: u32, - validity_hours: u32, }, } @@ -216,20 +214,30 @@ impl AppContext { DashPayTask::SendContactRequestWithProof { identity, signing_key, - to_identity_id, - account_label, - qr_auto_accept, - } => Ok(contact_requests::send_contact_request_with_proof( - self, - sdk, - identity, - signing_key, - to_identity_id - .to_string(dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58), - account_label, - Some(qr_auto_accept), - ) - .await?), + qr_code, + } => { + let current_time = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|_| DashPayError::SystemClockInvalid)? + .as_secs(); + if qr_code.is_expired_at(current_time) { + return Err(DashPayError::QrCodeExpired { + expired_at: u64::from(qr_code.expires_at()), + current_time, + } + .into()); + } + Ok(contact_requests::send_contact_request_with_proof( + self, + sdk, + identity, + signing_key, + qr_code.full_username(), + None, + Some(qr_code), + ) + .await?) + } DashPayTask::AcceptContactRequest { identity, request_id, @@ -379,20 +387,15 @@ impl AppContext { )) } } - DashPayTask::GenerateAutoAcceptQrCode { - identity, - account_reference, - validity_hours, - } => { - let proof = auto_accept_proof::generate_auto_accept_proof( - &identity, - account_reference, - validity_hours, - ) - .await?; - Ok(BackendTaskSuccessResult::DashPayAutoAcceptQrCode( - proof.to_qr_string(), - )) + DashPayTask::GenerateAutoAcceptQrCode { identity } => { + // An empty name lets platform-wallet look the username up on + // Platform, for identities whose names are not cached here. + let username = self.main_username(&identity).unwrap_or_default(); + let qr = self + .wallet_backend()? + .dashpay_build_contact_qr(&identity, &username) + .await?; + Ok(BackendTaskSuccessResult::DashPayAutoAcceptQrCode(qr)) } } } diff --git a/src/backend_task/dashpay/auto_accept_handler.rs b/src/backend_task/dashpay/auto_accept_handler.rs deleted file mode 100644 index 95781088a..000000000 --- a/src/backend_task/dashpay/auto_accept_handler.rs +++ /dev/null @@ -1,117 +0,0 @@ -use crate::backend_task::dashpay::auto_accept_proof::verify_auto_accept_proof; -use crate::backend_task::dashpay::contact_request_query; -use crate::backend_task::dashpay::contact_requests::accept_contact_request; -use crate::backend_task::error::TaskError; -use crate::context::AppContext; -use crate::model::qualified_identity::QualifiedIdentity; -use dash_sdk::Sdk; -use dash_sdk::dpp::document::DocumentV0Getters; -use dash_sdk::dpp::identity::accessors::IdentityGettersV0; -use dash_sdk::dpp::platform_value::Value; -use dash_sdk::dpp::platform_value::string_encoding::Encoding; -use dash_sdk::drive::query::{OrderClause, WhereClause, WhereOperator}; -use dash_sdk::platform::{Document, FetchMany, Identifier}; -use std::sync::Arc; - -/// Process incoming contact requests and check for autoAcceptProof -/// -/// This function checks all incoming contact requests for valid autoAcceptProof -/// and automatically accepts and reciprocates if the proof is valid. -pub async fn process_auto_accept_requests( - app_context: &Arc, - sdk: &Sdk, - identity: QualifiedIdentity, -) -> Result, TaskError> { - let identity_id = identity.identity.id(); - - // Query for incoming contact requests - let mut incoming_query = contact_request_query(app_context)?; - - incoming_query = incoming_query.with_where(WhereClause { - field: "toUserId".to_string(), - operator: WhereOperator::Equal, - value: Value::Identifier(identity_id.to_buffer()), - }); - - // Add orderBy to avoid platform bug - incoming_query = incoming_query.with_order_by(OrderClause { - field: "$createdAt".to_string(), - ascending: true, - }); - incoming_query.limit = 100; - - let incoming_docs = Document::fetch_many(sdk, incoming_query).await?; - - // Stateless verification; no stored proofs needed - - let mut auto_accepted_requests = Vec::new(); - - for (request_id, doc) in incoming_docs { - if let Some(doc) = doc { - let from_id = doc.owner_id(); - let props = doc.properties(); - - // Check if this request has an autoAcceptProof - if let Some(Value::Bytes(proof_data)) = props.get("autoAcceptProof") { - tracing::debug!( - "Found contact request with autoAcceptProof from {}", - from_id.to_string(Encoding::Base58) - ); - - // Extract accountReference for message construction (default to 0 if missing) - let account_reference = props - .get("accountReference") - .and_then(|value| value.to_integer::().ok()) - .unwrap_or_default(); - - // Verify the proof per DIP-0015 - match verify_auto_accept_proof( - proof_data, - from_id, - identity.identity.id(), - &identity, - account_reference, - ) - .await - { - Ok(true) => { - tracing::debug!( - "Valid autoAcceptProof, auto-accepting contact request from {}", - from_id.to_string(Encoding::Base58) - ); - - // Accept the request (which sends a reciprocal request) - match accept_contact_request(app_context, sdk, identity.clone(), request_id) - .await - { - Ok(_) => { - auto_accepted_requests.push((from_id, true)); - - // Stateless: no persistence required - } - Err(e) => { - tracing::error!("Failed to auto-accept contact request: {}", e); - auto_accepted_requests.push((from_id, false)); - } - } - } - Ok(false) => { - tracing::warn!( - "Invalid or expired autoAcceptProof from {}", - from_id.to_string(Encoding::Base58) - ); - } - Err(e) => { - tracing::error!("Failed to verify autoAcceptProof: {}", e); - } - } - } - } - } - - Ok(auto_accepted_requests) -} - -// No DB persistence required - -// Proof creation moved to contact_requests::send_contact_request_with_proof diff --git a/src/backend_task/dashpay/auto_accept_proof.rs b/src/backend_task/dashpay/auto_accept_proof.rs deleted file mode 100644 index cfa8e52a7..000000000 --- a/src/backend_task/dashpay/auto_accept_proof.rs +++ /dev/null @@ -1,365 +0,0 @@ -use crate::backend_task::error::TaskError; -use crate::model::dashpay_derivation::derive_auto_accept_key; -use crate::model::qualified_identity::QualifiedIdentity; -use dash_sdk::dpp::dashcore::ecdsa::EcdsaSecretKey; -use dash_sdk::dpp::identity::accessors::IdentityGettersV0; -use dash_sdk::dpp::identity::{KeyType, Purpose, SecurityLevel}; -use dash_sdk::dpp::secp256k1::Message; -use dash_sdk::platform::Identifier; -use serde::{Deserialize, Serialize}; -use sha2::{Digest, Sha256}; -use std::collections::HashSet; - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -pub struct AutoAcceptProofData { - pub identity_id: Identifier, - pub proof_key: [u8; 32], - pub account_reference: u32, - pub expires_at: u64, // Unix timestamp -} - -impl AutoAcceptProofData { - pub fn to_qr_string(&self) -> String { - // Format according to DIP-0015: dash:?du={username}&dapk={key_data} - // Key data format: key_type (1 byte) + timestamp (4 bytes) + key_size (1 byte) + key (32 bytes) - let mut key_data = Vec::new(); - key_data.push(0u8); // Key type 0 for ECDSA_SECP256K1 - key_data.extend_from_slice(&(self.expires_at as u32).to_be_bytes()); // Timestamp/expiration - key_data.push(32u8); // Key size - key_data.extend_from_slice(&self.proof_key); // The actual key - - // Encode key data in base58 using dashcore's base58 implementation - let key_data_base58 = dash_sdk::dpp::platform_value::string_encoding::encode( - &key_data, - dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58, - ); - - // For QR codes without username (identity-based) - format!( - "dash:?di={}&dapk={}", - self.identity_id - .to_string(dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58), - key_data_base58 - ) - } - - pub fn from_qr_string(qr_data: &str) -> Result { - // Parse DIP-0015 format: dash:?du={username}&dapk={key_data} or dash:?di={identity}&dapk={key_data} - if !qr_data.starts_with("dash:?") { - return Err("Invalid QR code format - must start with 'dash:?'".to_string()); - } - - let query_string = &qr_data[6..]; // Skip "dash:?" - let mut identity_id = None; - let mut key_data_base58 = None; - let mut account_reference = 0u32; // Default to account 0 - - // Parse query parameters - for param in query_string.split('&') { - let parts: Vec<&str> = param.split('=').collect(); - if parts.len() != 2 { - continue; - } - - match parts[0] { - "di" => { - identity_id = Some( - Identifier::from_string( - parts[1], - dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58, - ) - .map_err(|e| format!("Invalid identity ID: {}", e))?, - ) - } - "dapk" => { - key_data_base58 = Some(parts[1].to_string()); - } - "account" => { - account_reference = parts[1] - .parse::() - .map_err(|e| format!("Invalid account reference: {}", e))?; - } - _ => {} // Ignore unknown parameters - } - } - - let identity_id = identity_id.ok_or("Missing identity ID in QR code".to_string())?; - let key_data_base58 = - key_data_base58.ok_or("Missing proof key data in QR code".to_string())?; - - // Decode the key data from base58 - let key_data = dash_sdk::dpp::dashcore::base58::decode(&key_data_base58) - .map_err(|e| format!("Invalid base58 key data: {}", e))?; - - // Parse key data format: key_type (1) + timestamp (4) + key_size (1) + key (32-64) - if key_data.len() < 38 { - return Err("Key data too short".to_string()); - } - - let _key_type = key_data[0]; - let expires_at = - u32::from_be_bytes([key_data[1], key_data[2], key_data[3], key_data[4]]) as u64; - let key_size = key_data[5] as usize; - - if key_data.len() < 6 + key_size { - return Err("Invalid key data length".to_string()); - } - - let mut proof_key = [0u8; 32]; - if key_size == 32 { - proof_key.copy_from_slice(&key_data[6..38]); - } else { - return Err(format!("Unsupported key size: {}", key_size)); - } - - Ok(Self { - identity_id, - proof_key, - account_reference, - expires_at, - }) - } -} - -/// Generate an auto-accept proof for QR code sharing -/// -/// According to DIP-0015, the autoAcceptProof is a signature that allows the recipient -/// to automatically accept the contact request and send one back without user interaction. -pub async fn generate_auto_accept_proof( - identity: &QualifiedIdentity, - account_reference: u32, - validity_hours: u32, -) -> Result { - use crate::backend_task::dashpay::errors::DashPayError; - - // Calculate expiration timestamp - let expires_at = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_err(|_| DashPayError::SystemClockInvalid)? - .as_secs() - + (validity_hours as u64 * 3600); - - // Get wallet seed for HD derivation - use ENCRYPTION key (ECDSA_SECP256K1) as per DIP-15 - // The auto-accept proof uses HD derivation from the wallet, and ENCRYPTION keys are ECDSA_SECP256K1 - let signing_key = identity - .identity - .get_first_public_key_matching( - Purpose::ENCRYPTION, - HashSet::from([SecurityLevel::MEDIUM]), - HashSet::from([KeyType::ECDSA_SECP256K1]), - false, - ) - .ok_or(DashPayError::MissingEncryptionKey)?; - - // Resolve the ENCRYPTION private key through the JIT chokepoint — no - // parked-seed read. - let wallet_seed = identity - .resolve_private_key_bytes(signing_key) - .await? - .map(|(_, private_key)| private_key) - .ok_or(TaskError::WalletLocked)?; - - // Determine network from the identity - let network = identity.network; - - // Derive the auto-accept key using DIP-0015 path: m/9'/coin'/16'/timestamp' - // Using expiration timestamp as the derivation index - let auto_accept_xprv = derive_auto_accept_key( - &wallet_seed[..], - network, - expires_at as u32, // Truncate to u32 for derivation - ) - .map_err(|e| TaskError::DashPay(DashPayError::from(e)))?; - - // Extract the private key bytes (32 bytes) - let proof_key = *auto_accept_xprv.private_key.to_bytes(); - - Ok(AutoAcceptProofData { - identity_id: identity.identity.id(), - proof_key, - account_reference, - expires_at, - }) -} - -/// Create the autoAcceptProof bytes for inclusion in a contact request -/// -/// Format according to DIP-0015: -/// - key type (1 byte) -/// - key index (4 bytes) - the timestamp used for derivation -/// - signature size (1 byte) -/// - signature (32-96 bytes) -pub fn create_auto_accept_proof_bytes_with_key( - expires_at: u64, - signing_key_bytes: &[u8; 32], - sender_id: &Identifier, - recipient_id: &Identifier, - account_reference: u32, -) -> Result, String> { - // Derive the auto-accept key - // Sign using the provided ephemeral key from the QR - - // Create the message to sign: ownerId + toUserId + accountReference - let mut message_data = Vec::new(); - message_data.extend_from_slice(&sender_id.to_buffer()); - message_data.extend_from_slice(&recipient_id.to_buffer()); - message_data.extend_from_slice(&account_reference.to_le_bytes()); - - // Hash the message - let mut hasher = Sha256::new(); - hasher.update(&message_data); - let message_hash = hasher.finalize(); - - // Sign the digest. The key erases itself when it drops. The signature is - // low-S with a low R ground as Dash Core grinds it; any ECDSA verifier - // accepts it. - let secret_key = EcdsaSecretKey::from_bytes(signing_key_bytes) - .map_err(|e| format!("Failed to create secret key: {}", e))?; - - let sig_bytes = secret_key.sign(&message_hash.into()).to_bytes(); - - // Build the proof bytes - let mut proof_bytes = Vec::new(); - proof_bytes.push(0u8); // Key type 0 for ECDSA_SECP256K1 - proof_bytes.extend_from_slice(&(expires_at as u32).to_be_bytes()); // Key index (timestamp) - proof_bytes.push(sig_bytes.len() as u8); // Signature size - proof_bytes.extend_from_slice(&sig_bytes); // The signature - - Ok(proof_bytes) -} - -/// Verify an auto-accept proof from a contact request -/// -/// This would be called when receiving a contact request with an autoAcceptProof field -/// to determine if we should automatically accept and reciprocate. -pub async fn verify_auto_accept_proof( - proof_data: &[u8], - sender_identity_id: Identifier, - recipient_identity_id: Identifier, - our_identity: &QualifiedIdentity, - account_reference: u32, -) -> Result { - // Parse: key type (1) | key index/timestamp (4) | sig size (1) | signature - if proof_data.len() < 6 { - return Ok(false); - } - let _key_type = proof_data[0]; - let key_index = - u32::from_be_bytes([proof_data[1], proof_data[2], proof_data[3], proof_data[4]]); - let sig_len = proof_data[5] as usize; - // Compact ECDSA signatures are exactly 64 bytes - if sig_len != 64 { - return Ok(false); - } - if proof_data.len() < 6 + sig_len { - return Ok(false); - } - let signature_bytes = &proof_data[6..6 + sig_len]; - - // Expiry check - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_err(|e| format!("Time error: {}", e))? - .as_secs(); - if now > key_index as u64 { - return Ok(false); - } - - // Message: ownerId + toUserId + accountReference - let mut message_data = Vec::new(); - message_data.extend_from_slice(&sender_identity_id.to_buffer()); - message_data.extend_from_slice(&recipient_identity_id.to_buffer()); - message_data.extend_from_slice(&account_reference.to_le_bytes()); - let mut hasher = Sha256::new(); - hasher.update(&message_data); - let message_hash = hasher.finalize(); - let message = Message::from_digest(message_hash.into()); - - // Derive expected pubkey from our seed and key index (timestamp) - // Use ENCRYPTION key (ECDSA_SECP256K1) for HD derivation as per DIP-15 - let signing_key = our_identity - .identity - .get_first_public_key_matching( - Purpose::ENCRYPTION, - HashSet::from([SecurityLevel::MEDIUM]), - HashSet::from([KeyType::ECDSA_SECP256K1]), - false, - ) - .ok_or("No suitable key found. This operation requires a MEDIUM security level ECDSA_SECP256K1 ENCRYPTION key.")?; - // Resolve the ENCRYPTION private key through the JIT chokepoint — no - // parked-seed read. - let wallet_seed = our_identity - .resolve_private_key_bytes(signing_key) - .await - .map_err(|e| format!("Error resolving private key: {}", e))? - .map(|(_, private_key)| private_key) - .ok_or("Private key not found")?; - let xprv = derive_auto_accept_key(&wallet_seed[..], our_identity.network, key_index) - .map_err(|e| format!("Failed to derive auto-accept key: {}", e))?; - let pubkey = dash_sdk::dpp::secp256k1::PublicKey::from(xprv.private_key.public_key()); - let sig = dash_sdk::dpp::secp256k1::ecdsa::Signature::from_compact(signature_bytes) - .map_err(|e| format!("Invalid signature bytes: {}", e))?; - - match dash_sdk::dpp::secp256k1::ecdsa::verify(&sig, message, &pubkey) { - Ok(_) => Ok(true), - Err(_) => Ok(false), - } -} - -// No local persistence required - -#[cfg(test)] -mod tests { - use super::*; - use dash_sdk::dpp::secp256k1::{PublicKey, SecretKey, ecdsa}; - - /// The proof's signature verifies, the way `verify_auto_accept_proof` - /// checks it, against the public key of the key it was signed with. The - /// signature is low-S with a low R ground as Dash Core grinds it; R lands - /// low half the time on its own, so this signs for many accounts. - #[test] - fn proof_signature_verifies_and_has_low_r() { - let key_bytes = [0x2Bu8; 32]; - let public_key = - PublicKey::from_secret_key(&SecretKey::from_secret_bytes(key_bytes).expect("valid")); - let sender = Identifier::from([0x01; 32]); - let recipient = Identifier::from([0x02; 32]); - let expires_at = 1_900_000_000u64; - - for account_reference in 0..32u32 { - let proof = create_auto_accept_proof_bytes_with_key( - expires_at, - &key_bytes, - &sender, - &recipient, - account_reference, - ) - .expect("proof"); - - assert_eq!(proof[0], 0, "key type"); - assert_eq!( - &proof[1..5], - &(expires_at as u32).to_be_bytes(), - "key index" - ); - assert_eq!(proof[5], 64, "signature size"); - assert_eq!(proof.len(), 6 + 64); - - let mut message_data = Vec::new(); - message_data.extend_from_slice(&sender.to_buffer()); - message_data.extend_from_slice(&recipient.to_buffer()); - message_data.extend_from_slice(&account_reference.to_le_bytes()); - let digest: [u8; 32] = Sha256::digest(&message_data).into(); - - let signature = ecdsa::Signature::from_compact(&proof[6..]).expect("compact"); - let mut normalized = signature; - normalized.normalize_s(); - assert_eq!(normalized, signature, "high S for {account_reference}"); - assert!( - ecdsa::verify(&signature, Message::from_digest(digest), &public_key).is_ok(), - "proof does not verify for {account_reference}" - ); - assert!(proof[6] < 0x80, "R is not low for {account_reference}"); - } - } -} diff --git a/src/backend_task/dashpay/contact_requests.rs b/src/backend_task/dashpay/contact_requests.rs index ccdc93ec4..6397836bf 100644 --- a/src/backend_task/dashpay/contact_requests.rs +++ b/src/backend_task/dashpay/contact_requests.rs @@ -5,9 +5,6 @@ use super::encryption::{ use super::errors::DashPayError; use super::validation::validate_contact_request_before_send; use crate::backend_task::BackendTaskSuccessResult; -use crate::backend_task::dashpay::auto_accept_proof::{ - AutoAcceptProofData, create_auto_accept_proof_bytes_with_key, -}; use crate::backend_task::error::TaskError; use crate::context::AppContext; use crate::model::dashpay::contact_request_recipient; @@ -238,7 +235,7 @@ pub async fn send_contact_request_with_proof( signing_key: IdentityPublicKey, to_username_or_id: String, account_label: Option, - qr_auto_accept: Option, + qr_code: Option, ) -> Result { if let Some(label) = account_label.as_deref() && let Err(error) = crate::model::dashpay::validate_account_label(label) @@ -506,23 +503,11 @@ pub async fn send_contact_request_with_proof( ); } - // If QR auto-accept data is provided, create the proof bytes now to match the final accountReference - if let Some(qr) = qr_auto_accept { - // Ensure the QR target matches the resolved recipient - if qr.identity_id != to_identity_id { - return Err(DashPayError::InvalidQrCode { - reason: "QR code target identity does not match recipient".to_string(), - } - .into()); - } - let proof = create_auto_accept_proof_bytes_with_key( - qr.expires_at, - &qr.proof_key, - &identity.identity.id(), - &to_identity_id, - account_reference, - ) - .map_err(|e| TaskError::EncryptionError { detail: e })?; + // A scanned contact QR code signs the autoAcceptProof over the final + // accountReference. The recipient was resolved from the code's own + // username, so the proof is always addressed to the code's owner. + if let Some(qr) = qr_code { + let proof = qr.sign_proof(&identity.identity.id(), &to_identity_id, account_reference); tracing::debug!( "Including autoAcceptProof in contact request ({} bytes)", proof.len() diff --git a/src/backend_task/dashpay/errors.rs b/src/backend_task/dashpay/errors.rs index a8561ed0c..c970ca4d0 100644 --- a/src/backend_task/dashpay/errors.rs +++ b/src/backend_task/dashpay/errors.rs @@ -66,13 +66,31 @@ pub enum DashPayError { #[error("The contact request could not be verified. Please check the details and try again.")] ValidationFailed { errors: Vec }, - // Auto Accept Proof Errors - #[error("The QR code format is not recognized. Please scan a valid contact QR code.")] - InvalidQrCode { reason: String }, - + // Contact QR code (DIP-0015 auto-accept) errors #[error("This QR code has expired. Please ask for a new one.")] QrCodeExpired { expired_at: u64, current_time: u64 }, + /// Contact QR codes are built from the identity's wallet, which an + /// identity added without its wallet does not have here. + #[error( + "Contact QR codes can be created only for an identity loaded from its wallet. Load this identity from the wallet that created it, then try again." + )] + ContactQrIdentityNotFromWallet, + + /// The secret seam lent something other than the wallet's recovery + /// phrase for the identity's wallet. + #[error("Unlock the wallet for this identity, then create the contact QR code again.")] + ContactQrWalletSeedUnavailable, + + /// platform-wallet could not build the contact QR code. + #[error( + "The contact QR code could not be created. Make sure this identity has a username, then try again." + )] + ContactQrBuildFailed { + #[source] + source: std::sync::Arc, + }, + // Network/SDK Errors #[error("Network connection failed. Please check your internet connection and retry.")] NetworkError, @@ -177,7 +195,6 @@ impl DashPayError { matches!( self, DashPayError::UsernameResolutionFailed { .. } - | DashPayError::InvalidQrCode { .. } | DashPayError::QrCodeExpired { .. } | DashPayError::ValidationFailed { .. } | DashPayError::AccountLabelTooLong { .. } diff --git a/src/model/dashpay_contact_qr.rs b/src/model/dashpay_contact_qr.rs new file mode 100644 index 000000000..6635cb13c --- /dev/null +++ b/src/model/dashpay_contact_qr.rs @@ -0,0 +1,240 @@ +//! DashPay contact QR codes (DIP-0015 `dash:?du=&dapk=`). +//! +//! The format, the key blob and the proof all come from platform-wallet's +//! `auto_accept` module; this type only validates a scanned code once and +//! carries the result to the backend. The `dapk` key is the QR owner's +//! auto-accept key, a short-lived bearer credential: it lets the scanner sign +//! the `autoAcceptProof` of its contact request, nothing else. + +use std::sync::Arc; + +use dash_sdk::dpp::secp256k1::SecretKey; +use dash_sdk::platform::Identifier; +use platform_wallet::error::PlatformWalletError; +use platform_wallet::wallet::identity::crypto::auto_accept::{ + decode_auto_accept_key_blob, parse_dashpay_contact_uri, sign_auto_accept_proof, +}; + +/// A scanned contact QR code that passed validation. +#[derive(Clone, PartialEq)] +pub struct ContactQrCode { + username: String, + key: SecretKey, + expires_at: u32, +} + +/// Why a scanned text is not a usable contact QR code. +#[derive(Debug, Clone, thiserror::Error)] +pub enum ContactQrCodeError { + /// The text is not a DIP-0015 contact code, or its key cannot be read. + /// Codes from older Dash Evo Tool versions (`dash:?di=…`) land here. + #[error( + "This is not a DashPay contact QR code. Ask your contact for a new code and try again." + )] + Unreadable { + #[source] + source: Arc, + }, + /// The code names something that is not a Dash username. + #[error( + "This QR code does not name a valid Dash username. Ask your contact for a new code and try again." + )] + InvalidUsername, +} + +impl ContactQrCode { + /// Parse and validate a scanned or pasted contact QR code. + pub fn parse(text: &str) -> Result { + let unreadable = |source| ContactQrCodeError::Unreadable { + source: Arc::new(source), + }; + let (username, key_blob) = parse_dashpay_contact_uri(text.trim()).map_err(unreadable)?; + let username = username.trim().to_string(); + if username.is_empty() || crate::model::dpns::validate_dpns_input(&username).is_err() { + return Err(ContactQrCodeError::InvalidUsername); + } + let (key, expires_at) = decode_auto_accept_key_blob(&key_blob).map_err(unreadable)?; + Ok(Self { + username, + key, + expires_at, + }) + } + + /// The QR owner's Dash username, as written in the code. + pub fn username(&self) -> &str { + &self.username + } + + /// The username in its full `.dash` form, so a lookup always resolves it + /// through DPNS and never mistakes it for an identity ID. + pub fn full_username(&self) -> String { + if crate::model::dpns::has_dash_suffix(&self.username) { + self.username.clone() + } else { + format!("{}.dash", self.username) + } + } + + /// The Unix time (seconds) after which the code no longer auto-accepts. + pub fn expires_at(&self) -> u32 { + self.expires_at + } + + /// Whether the code has expired at `now_secs` (Unix seconds). + pub fn is_expired_at(&self, now_secs: u64) -> bool { + now_secs > u64::from(self.expires_at) + } + + /// The `autoAcceptProof` for a contact request from `sender` to + /// `recipient` (the QR owner) carrying `account_reference`. + pub fn sign_proof( + &self, + sender: &Identifier, + recipient: &Identifier, + account_reference: u32, + ) -> Vec { + sign_auto_accept_proof( + &self.key, + sender, + recipient, + account_reference, + self.expires_at, + ) + } +} + +impl std::fmt::Debug for ContactQrCode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ContactQrCode") + .field("username", &self.username) + .field("key", &"") + .field("expires_at", &self.expires_at) + .finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use dash_sdk::dpp::secp256k1::PublicKey; + use platform_wallet::wallet::identity::crypto::auto_accept::{ + encode_auto_accept_key_blob, encode_dashpay_contact_uri, + verify_auto_accept_proof_with_pubkey, + }; + + const EXPIRY: u32 = 1_900_000_000; + + fn key() -> SecretKey { + SecretKey::from_secret_bytes(rand::random()).expect("key") + } + + fn uri(username: &str, key: &SecretKey) -> String { + encode_dashpay_contact_uri(username, &encode_auto_accept_key_blob(key, EXPIRY)) + } + + /// A code platform-wallet builds parses back to its username, expiry and + /// key, and the proof it signs verifies against the owner's public key + /// for exactly that sender, recipient and account reference. + #[test] + fn a_platform_wallet_code_parses_and_signs_a_verifiable_proof() { + let key = key(); + let qr = ContactQrCode::parse(&uri("alice", &key)).expect("parse"); + assert_eq!(qr.username(), "alice"); + assert_eq!(qr.full_username(), "alice.dash"); + assert_eq!(qr.expires_at(), EXPIRY); + + let (scanner, owner) = (Identifier::from([1; 32]), Identifier::from([2; 32])); + let proof = qr.sign_proof(&scanner, &owner, 7); + let public = PublicKey::from_secret_key(&key); + assert!(verify_auto_accept_proof_with_pubkey( + &public, &proof, &scanner, &owner, 7 + )); + assert!(!verify_auto_accept_proof_with_pubkey( + &public, &proof, &scanner, &owner, 8 + )); + assert!(!verify_auto_accept_proof_with_pubkey( + &public, + &proof, + &Identifier::from([3; 32]), + &owner, + 7 + )); + } + + /// Codes from older Dash Evo Tool versions named the identity (`di=`) + /// instead of the username (`du=`) and are refused. + #[test] + fn an_old_identity_id_code_is_refused() { + let blob = encode_auto_accept_key_blob(&key(), EXPIRY); + let old = format!( + "dash:?di={}&dapk={}", + Identifier::from([9; 32]) + .to_string(dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58), + dash_sdk::dpp::platform_value::string_encoding::encode( + &blob, + dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58 + ) + ); + assert!(matches!( + ContactQrCode::parse(&old), + Err(ContactQrCodeError::Unreadable { .. }) + )); + } + + #[test] + fn malformed_codes_are_refused() { + for text in [ + "", + "hello", + "http:?du=alice&dapk=abc", + "dash:?du=alice", + "dash:?du=alice&dapk=0OIl", + "dash:?du=alice&dapk=abc", + ] { + assert!( + matches!( + ContactQrCode::parse(text), + Err(ContactQrCodeError::Unreadable { .. }) + ), + "{text}" + ); + } + } + + #[test] + fn a_code_without_a_dash_username_is_refused() { + for username in ["", " ", "alice.com"] { + assert!( + matches!( + ContactQrCode::parse(&uri(username, &key())), + Err(ContactQrCodeError::InvalidUsername) + ), + "{username:?}" + ); + } + } + + #[test] + fn a_full_username_is_kept_as_is() { + let qr = ContactQrCode::parse(&uri("alice.dash", &key())).expect("parse"); + assert_eq!(qr.full_username(), "alice.dash"); + } + + #[test] + fn expiry_is_inclusive_of_the_last_second() { + let qr = ContactQrCode::parse(&uri("alice", &key())).expect("parse"); + assert!(!qr.is_expired_at(u64::from(EXPIRY))); + assert!(qr.is_expired_at(u64::from(EXPIRY) + 1)); + } + + /// The bearer key never reaches logs through `Debug`. + #[test] + fn debug_output_hides_the_key() { + let key = key(); + let qr = ContactQrCode::parse(&uri("alice", &key)).expect("parse"); + let debug = format!("{qr:?}"); + assert!(debug.contains("")); + assert!(!debug.contains(&hex::encode(key.to_secret_bytes()))); + } +} diff --git a/src/model/dashpay_derivation/hd.rs b/src/model/dashpay_derivation/hd.rs index 9ca674a03..8b4bb921a 100644 --- a/src/model/dashpay_derivation/hd.rs +++ b/src/model/dashpay_derivation/hd.rs @@ -1,17 +1,11 @@ use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::dashcore::hashes::{Hash, HashEngine}; -use dash_sdk::dpp::key_wallet::bip32::{ - ChildNumber, DerivationPath, ExtendedPrivKey, ExtendedPubKey, -}; +use dash_sdk::dpp::key_wallet::bip32::{ChildNumber, ExtendedPubKey}; use dash_sdk::platform::Identifier; -use std::str::FromStr; use super::DerivationError; use super::dip14::derive_dashpay_incoming_xpub_dip14; -/// DashPay auto-accept proof feature index - use the constant from dip9 if available -const DASHPAY_AUTO_ACCEPT_FEATURE: u32 = 16; - /// Derive the DashPay incoming funds extended public key for a contact relationship /// Path: m/9'/coin'/15'/account'/(sender_id)/(recipient_id) /// @@ -75,30 +69,6 @@ pub fn generate_contact_xpub_data( Ok((parent_fingerprint, chain_code, public_key_bytes)) } -/// Derive auto-accept proof key according to DIP-0015 -/// Path: m/9'/coin'/16'/timestamp' -pub fn derive_auto_accept_key( - master_seed: &[u8], - network: Network, - timestamp: u32, -) -> Result { - use crate::model::wallet::coin_type_for_network; - - // Create extended private key from seed - let master_xprv = ExtendedPrivKey::new_master(network, master_seed)?; - - // Build derivation path: m/9'/coin'/16'/timestamp' - let coin_type = coin_type_for_network(network); - let path = DerivationPath::from_str(&format!( - "m/9'/{coin_type}'/{DASHPAY_AUTO_ACCEPT_FEATURE}'/{timestamp}'" - ))?; - - // Derive the key - let auto_accept_key = master_xprv.derive_priv(&path)?; - - Ok(auto_accept_key) -} - /// Calculate account reference as specified in DIP-0015 pub fn calculate_account_reference( sender_secret_key: &[u8], @@ -132,6 +102,8 @@ pub fn calculate_account_reference( #[cfg(test)] mod tests { use super::*; + use dash_sdk::dpp::key_wallet::bip32::{DerivationPath, ExtendedPrivKey}; + use std::str::FromStr; #[test] fn test_dashpay_derivation_path() { @@ -221,40 +193,6 @@ mod tests { ); } - #[test] - fn test_auto_accept_key_derivation() { - // Test auto-accept key derivation - let network = Network::Testnet; - let master_seed = [0x42u8; 64]; - let timestamp = 1700000000u32; - - let key = derive_auto_accept_key(&master_seed, network, timestamp) - .expect("Should derive auto-accept key"); - - // Verify the key was derived correctly - assert_eq!(key.network, network); - assert_eq!(key.depth, 4); // m/9'/1'/16'/timestamp' on testnet = depth 4 - } - - #[test] - fn test_auto_accept_key_different_timestamps() { - // Different timestamps should produce different keys - let network = Network::Testnet; - let master_seed = [0x42u8; 64]; - - let key1 = - derive_auto_accept_key(&master_seed, network, 1700000000).expect("Should derive key 1"); - let key2 = - derive_auto_accept_key(&master_seed, network, 1700000001).expect("Should derive key 2"); - - // Different timestamps should produce different keys - assert_ne!( - key1.private_key.to_bytes(), - key2.private_key.to_bytes(), - "Different timestamps should produce different keys" - ); - } - #[test] fn test_generate_contact_xpub_data() { // Test generating contact xpub data diff --git a/src/model/dashpay_derivation/mod.rs b/src/model/dashpay_derivation/mod.rs index 5ed877885..b8d8bb6d5 100644 --- a/src/model/dashpay_derivation/mod.rs +++ b/src/model/dashpay_derivation/mod.rs @@ -1,15 +1,16 @@ //! Pure DashPay HD key derivation (DIP-14 / DIP-15). //! -//! Stateless derivation of contact payment keys and auto-accept proof keys -//! from a wallet seed. No `AppContext`, `Sdk`, database, or `BackendTask` +//! Stateless derivation of contact payment keys from a wallet seed. The +//! auto-accept (QR) key comes from platform-wallet; see +//! `wallet_backend::auto_accept`. No `AppContext`, `Sdk`, database, or `BackendTask` //! dependency — the single source of truth for DashPay derivation math. pub mod dip14; pub mod hd; pub use hd::{ - calculate_account_reference, derive_auto_accept_key, derive_dashpay_incoming_xpub, - derive_payment_address, generate_contact_xpub_data, + calculate_account_reference, derive_dashpay_incoming_xpub, derive_payment_address, + generate_contact_xpub_data, }; use thiserror::Error; diff --git a/src/model/mod.rs b/src/model/mod.rs index 7648d0387..c0427328e 100644 --- a/src/model/mod.rs +++ b/src/model/mod.rs @@ -5,6 +5,7 @@ pub mod avatar; pub mod backup_retention; pub mod contested_name; pub mod dashpay; +pub mod dashpay_contact_qr; pub mod dashpay_derivation; pub(crate) mod data_migration; pub mod datetime; diff --git a/src/ui/dashpay/qr_code_generator.rs b/src/ui/dashpay/qr_code_generator.rs index 2f2a22ede..63315a403 100644 --- a/src/ui/dashpay/qr_code_generator.rs +++ b/src/ui/dashpay/qr_code_generator.rs @@ -19,33 +19,27 @@ use crate::ui::dashpay::dashpay_screen::DashPaySubscreen; use crate::ui::identity::get_selected_wallet; use crate::ui::theme::DashColors; use crate::ui::{MessageType, RootScreenType, ScreenLike}; -use egui::{RichText, ScrollArea, TextEdit, Ui}; +use egui::{RichText, ScrollArea, Ui}; use std::sync::{Arc, RwLock}; const QR_CODE_INFO_TEXT: &str = "About Contact QR Codes:\n\n\ QR codes allow instant mutual contact establishment.\n\n\ - The recipient can scan to automatically send and accept contact requests.\n\n\ - QR codes expire after the specified validity period.\n\n\ - Each QR code is unique and can only be used once.\n\n\ - WARNING: Anyone with this QR code can automatically become your contact."; - -const ACCOUNT_INDEX_INFO_TEXT: &str = "Account Index:\n\n\ - The account index determines which HD wallet account is used for this contact relationship.\n\n\ - Most users should leave this at 0 (the default).\n\n\ - Advanced users may use different account indices to segregate contacts \ - (e.g., separate personal and business contacts into different wallet accounts).\n\n\ - The account index is used in the derivation path: m/9'/5'/15'/account'/..."; + Someone who scans your code sends you a contact request that proves you invited them.\n\n\ + Each QR code is valid for 1 hour. Create a new one when it expires.\n\n\ + The code shows your username, so your identity needs a username.\n\n\ + WARNING: Anyone with this QR code can automatically become your contact until it expires."; + +/// How long a contact QR code stays valid, in plain words. platform-wallet +/// fixes it (`AUTO_ACCEPT_TTL_SECS`): the code carries a usable key. +const QR_CODE_VALIDITY_TEXT: &str = "Valid for 1 hour."; pub struct QRCodeGeneratorScreen { pub app_context: Arc, pub selected_identity: Option, selected_identity_string: String, - account_index: String, - validity_hours: String, generated_qr_data: Option, qr_code: Option, show_info_popup: bool, - show_advanced_options: bool, selected_wallet: Option>>, wallet_unlock_popup: WalletUnlockPopup, wallet_open_attempted: bool, @@ -57,12 +51,9 @@ impl QRCodeGeneratorScreen { app_context: app_context.clone(), selected_identity: None, selected_identity_string: String::new(), - account_index: "0".to_string(), - validity_hours: "24".to_string(), generated_qr_data: None, qr_code: None, show_info_popup: false, - show_advanced_options: false, selected_wallet: None, wallet_unlock_popup: WalletUnlockPopup::new(), wallet_open_attempted: false, @@ -92,8 +83,9 @@ impl QRCodeGeneratorScreen { new_self } - /// Dispatch the auto-accept QR build to the backend, which resolves the key - /// and derives the proof through the JIT chokepoint (no seed in the UI). + /// Dispatch the contact QR build to the backend, which derives the + /// auto-accept key from the wallet seed through the secret seam (no seed + /// in the UI). fn generate_qr_code(&mut self) -> AppAction { let Some(identity) = &self.selected_identity else { MessageBanner::set_global( @@ -104,35 +96,9 @@ impl QRCodeGeneratorScreen { return AppAction::None; }; - let account_idx = match self.account_index.parse::() { - Ok(v) => v, - Err(_) => { - MessageBanner::set_global( - self.app_context.egui_ctx(), - "Invalid account index number", - MessageType::Error, - ); - return AppAction::None; - } - }; - - let validity = match self.validity_hours.parse::() { - Ok(v) if v > 0 && v <= 720 => v, // Max 30 days - _ => { - MessageBanner::set_global( - self.app_context.egui_ctx(), - "Validity hours must be between 1 and 720", - MessageType::Error, - ); - return AppAction::None; - } - }; - AppAction::BackendTask(BackendTask::DashPayTask(Box::new( DashPayTask::GenerateAutoAcceptQrCode { identity: identity.clone(), - account_reference: account_idx, - validity_hours: validity, }, ))) } @@ -151,9 +117,6 @@ impl QRCodeGeneratorScreen { if crate::ui::helpers::info_icon_button(ui, QR_CODE_INFO_TEXT).clicked() { self.show_info_popup = true; } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.checkbox(&mut self.show_advanced_options, "Advanced Options"); - }); }); ui.separator(); @@ -223,47 +186,6 @@ impl QRCodeGeneratorScreen { ui.end_row(); }); - // Advanced options (only shown when checkbox is checked) - if self.show_advanced_options { - ui.add_space(10.0); - egui::Grid::new("qr_advanced_config_grid") - .num_columns(2) - .spacing([10.0, 10.0]) - .show(ui, |ui| { - ui.horizontal(|ui| { - ui.label( - RichText::new("Account Index:") - .color(DashColors::text_primary(dark_mode)), - ); - crate::ui::helpers::info_icon_button(ui, ACCOUNT_INDEX_INFO_TEXT); - }); - ui.add( - TextEdit::singleline(&mut self.account_index) - .hint_text("0") - .desired_width(100.0), - ); - ui.end_row(); - - ui.label( - RichText::new("Validity (hours):") - .color(DashColors::text_primary(dark_mode)), - ); - ui.horizontal(|ui| { - ui.add( - TextEdit::singleline(&mut self.validity_hours) - .hint_text("24") - .desired_width(100.0), - ); - ui.label( - RichText::new("How long the QR code remains valid (default: 24)") - .small() - .color(DashColors::text_secondary(dark_mode)), - ); - }); - ui.end_row(); - }); - } - ui.add_space(10.0); // Check wallet lock status before showing generate button @@ -349,6 +271,11 @@ impl QRCodeGeneratorScreen { ui.add_space(10.0); + ui.label( + RichText::new(QR_CODE_VALIDITY_TEXT) + .small() + .color(DashColors::text_secondary(dark_mode)), + ); ui.label( RichText::new( "Share this QR code with someone to establish a mutual contact", diff --git a/src/ui/dashpay/qr_scanner.rs b/src/ui/dashpay/qr_scanner.rs index 6730a1e3c..1d0495e75 100644 --- a/src/ui/dashpay/qr_scanner.rs +++ b/src/ui/dashpay/qr_scanner.rs @@ -1,8 +1,8 @@ use crate::app::AppAction; use crate::backend_task::dashpay::DashPayTask; -use crate::backend_task::dashpay::auto_accept_proof::AutoAcceptProofData; use crate::backend_task::{BackendTask, BackendTaskSuccessResult}; use crate::context::AppContext; +use crate::model::dashpay_contact_qr::ContactQrCode; use crate::model::qualified_identity::QualifiedIdentity; use crate::model::wallet::Wallet; use crate::ui::components::dashpay_subscreen_chooser_panel::add_dashpay_subscreen_chooser_panel; @@ -28,7 +28,7 @@ pub struct QRScannerScreen { pub selected_identity: Option, selected_identity_string: String, qr_data_input: String, - parsed_qr_data: Option, + parsed_qr_data: Option, sending: bool, selected_wallet: Option>>, wallet_unlock_popup: WalletUnlockPopup, @@ -80,7 +80,7 @@ impl QRScannerScreen { return; } - match AutoAcceptProofData::from_qr_string(&self.qr_data_input) { + match ContactQrCode::parse(&self.qr_data_input) { Ok(data) => { self.parsed_qr_data = Some(data); MessageBanner::set_global( @@ -93,7 +93,7 @@ impl QRScannerScreen { self.parsed_qr_data = None; MessageBanner::set_global( self.app_context.egui_ctx(), - "The QR code is not valid for DashPay. Scan a DashPay code and try again.", + error.to_string(), MessageType::Error, ) .with_details(error); @@ -133,12 +133,7 @@ impl QRScannerScreen { BackendTask::DashPayTask(Box::new(DashPayTask::SendContactRequestWithProof { identity: identity.clone(), signing_key: signing_key.clone(), - to_identity_id: qr_data.identity_id, - account_label: Some(format!( - "QR Contact (Account #{})", - qr_data.account_reference - )), - qr_auto_accept: qr_data.clone(), + qr_code: qr_data.clone(), })); return AppAction::BackendTask(task); @@ -233,7 +228,7 @@ impl QRScannerScreen { ui.add( TextEdit::multiline(&mut self.qr_data_input) - .hint_text("dash:?di=...") + .hint_text("dash:?du=...") .desired_rows(3) .desired_width(f32::INFINITY) ); @@ -262,19 +257,18 @@ impl QRScannerScreen { .num_columns(2) .spacing([10.0, 5.0]) .show(ui, |ui| { - ui.label("Contact Identity:"); - ui.label(qr_data.identity_id.to_string( - dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58 - )); - ui.end_row(); - - ui.label("Account Reference:"); - ui.label(format!("{}", qr_data.account_reference)); + ui.label("Contact Username:"); + ui.label(qr_data.full_username()); ui.end_row(); ui.label("Expires:"); - let expiry_time = std::time::UNIX_EPOCH + std::time::Duration::from_secs(qr_data.expires_at); - ui.label(format!("{:?}", expiry_time)); + ui.label( + crate::model::datetime::instant_from_unix_secs(u64::from( + qr_data.expires_at(), + )) + .map(crate::model::datetime::local_date_time) + .unwrap_or_default(), + ); ui.end_row(); }); @@ -330,8 +324,7 @@ impl QRScannerScreen { ui.label("• QR codes enable instant mutual contact establishment"); ui.label("• The contact request is automatically accepted by both parties"); ui.label("• No manual approval is needed when using valid QR codes"); - ui.label("• QR codes expire after the specified time period"); - ui.label("• Each QR code can only be used once"); + ui.label("• Contact QR codes are valid for 1 hour after they are created"); }); }); diff --git a/src/wallet_backend/auto_accept.rs b/src/wallet_backend/auto_accept.rs new file mode 100644 index 000000000..adb94c1f5 --- /dev/null +++ b/src/wallet_backend/auto_accept.rs @@ -0,0 +1,358 @@ +//! DashPay contact QR codes (DIP-0015 auto-accept) through platform-wallet. +//! +//! platform-wallet builds the QR (`dash:?du=&dapk=`) and picks +//! its expiry; it asks the host for one thing only, the auto-accept private key +//! at `m/9'/coin'/16'/expiry'`. [`AutoAcceptKeyExport`] derives that key from +//! the wallet seed the secret seam lends for one operation, and refuses every +//! other path and every other crypto request. + +use std::sync::Arc; + +use dash_sdk::dpp::dashcore::Network; +use dash_sdk::dpp::identity::accessors::IdentityGettersV0; +use dash_sdk::dpp::key_wallet::bip32::{ChildNumber, DerivationPath, ExtendedPubKey}; +use dash_sdk::dpp::key_wallet::wallet::Wallet; +use dash_sdk::dpp::key_wallet::wallet::initialization::WalletAccountCreationOptions; +use dash_sdk::dpp::secp256k1::{PublicKey, SecretKey}; +use platform_wallet::error::PlatformWalletError; +use platform_wallet::wallet::identity::crypto::auto_accept::{ + auto_accept_derivation_path, derive_auto_accept_private_key, +}; +use platform_wallet::wallet::identity::network::{ + ContactCryptoProvider, ContactInfoOpened, ContactInfoSealed, +}; +use zeroize::Zeroizing; + +use crate::backend_task::dashpay::errors::DashPayError; +use crate::backend_task::error::TaskError; +use crate::model::qualified_identity::QualifiedIdentity; +use crate::wallet_backend::{SecretScope, WalletBackend}; + +impl WalletBackend { + /// Build a contact QR code for `identity`, valid for one hour. + /// + /// `username` is the identity's DPNS name to put in the code; pass an + /// empty string to have platform-wallet look it up on Platform. + /// + /// # Errors + /// + /// The identity has no wallet in this app + /// ([`DashPayError::ContactQrIdentityNotFromWallet`]) or its wallet is not + /// loaded; the user cancels the wallet password prompt; or + /// platform-wallet cannot build the code, typically because the identity + /// has no username ([`DashPayError::ContactQrBuildFailed`]). + pub(crate) async fn dashpay_build_contact_qr( + &self, + identity: &QualifiedIdentity, + username: &str, + ) -> Result { + let owner = identity.identity.id(); + let seed_hash = identity + .dashpay_wallet_seed_hash() + .ok_or(DashPayError::ContactQrIdentityNotFromWallet)?; + let wallet = self.resolve_wallet(&seed_hash).await?; + let network = identity.network; + let identity_wallet = wallet.identity(); + let dashpay = identity_wallet.dashpay(); + + self.secret_access() + .with_secret_session(&SecretScope::HdSeed { seed_hash }, async |session| { + let plaintext = session.plaintext(); + let seed = plaintext + .expose_hd_seed() + .ok_or(DashPayError::ContactQrWalletSeedUnavailable)?; + let provider = AutoAcceptKeyExport::new(seed, network); + dashpay + .build_auto_accept_qr(&owner, username, &provider) + .await + .map_err(|source| { + DashPayError::ContactQrBuildFailed { + source: Arc::new(source), + } + .into() + }) + }) + .await + } +} + +/// Serves platform-wallet the DIP-0015 auto-accept key, and nothing else. +/// +/// Holds a borrow of the seed for one operation only; it never copies the +/// seed out of that operation. +pub(crate) struct AutoAcceptKeyExport<'a> { + seed: &'a [u8; 64], + network: Network, +} + +impl<'a> AutoAcceptKeyExport<'a> { + pub(crate) fn new(seed: &'a [u8; 64], network: Network) -> Self { + Self { seed, network } + } + + /// The expiry index of `path` when it is exactly this network's + /// auto-accept path `m/9'/coin'/16'/expiry'`, all hardened. + #[expect( + clippy::result_large_err, + reason = "ContactCryptoProvider fixes PlatformWalletError as the error type" + )] + fn auto_accept_expiry(&self, path: &DerivationPath) -> Result { + let expected = auto_accept_derivation_path(self.network, 0)?; + let (path, expected) = (path.as_ref(), expected.as_ref()); + match path { + [feature @ .., ChildNumber::Hardened { index }] + if path.len() == expected.len() && feature == &expected[..expected.len() - 1] => + { + Ok(*index) + } + _ => Err(not_auto_accept()), + } + } +} + +fn not_auto_accept() -> PlatformWalletError { + PlatformWalletError::InvalidParameter( + "this crypto provider serves the DashPay auto-accept key only".to_string(), + ) +} + +#[async_trait::async_trait] +impl ContactCryptoProvider for AutoAcceptKeyExport<'_> { + async fn receiving_xpub( + &self, + _path: &DerivationPath, + ) -> Result { + Err(not_auto_accept()) + } + + async fn ecdh_shared_secret( + &self, + _path: &DerivationPath, + _peer: &PublicKey, + ) -> Result, PlatformWalletError> { + Err(not_auto_accept()) + } + + async fn export_auto_accept_private_key( + &self, + path: &DerivationPath, + ) -> Result { + let expiry = self.auto_accept_expiry(path)?; + let wallet = + Wallet::from_seed_bytes(*self.seed, self.network, WalletAccountCreationOptions::None) + .map_err(|error| PlatformWalletError::KeyDerivation(error.to_string()))?; + derive_auto_accept_private_key(&wallet, self.network, expiry) + } + + async fn export_invitation_private_key( + &self, + _path: &DerivationPath, + ) -> Result { + Err(not_auto_accept()) + } + + async fn account_reference( + &self, + _path: &DerivationPath, + _compact_xpub: &[u8], + _account_index: u32, + _version: u32, + ) -> Result { + Err(not_auto_accept()) + } + + async fn unmask_account_reference( + &self, + _path: &DerivationPath, + _compact_xpub: &[u8], + _account_reference: u32, + ) -> Result<(u32, u32), PlatformWalletError> { + Err(not_auto_accept()) + } + + async fn contact_info_seal( + &self, + _root_path: &DerivationPath, + _derivation_index: u32, + _contact_id: &[u8; 32], + _private_data_plaintext: &[u8], + _private_data_iv: &[u8; 16], + ) -> Result { + Err(not_auto_accept()) + } + + async fn contact_info_open( + &self, + _root_path: &DerivationPath, + _derivation_index: u32, + _enc_to_user_id: &[u8; 32], + _private_data_blob: &[u8], + ) -> Result { + Err(not_auto_accept()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::model::dashpay_contact_qr::ContactQrCode; + use dash_sdk::platform::Identifier; + use platform_wallet::wallet::identity::crypto::auto_accept::{ + AUTO_ACCEPT_TTL_SECS, verify_auto_accept_proof_with_pubkey, + }; + use std::str::FromStr; + + /// Generated each run, so no seed bytes are committed. + static SEED: std::sync::LazyLock<[u8; 64]> = std::sync::LazyLock::new(rand::random); + const NETWORK: Network = Network::Testnet; + const EXPIRY: u32 = 1_900_000_000; + + /// The key the wallet seed itself yields at `expiry`, derived by + /// platform-wallet with no DET code in between. + fn seed_key(seed: &[u8; 64], network: Network, expiry: u32) -> SecretKey { + let wallet = Wallet::from_seed_bytes(*seed, network, WalletAccountCreationOptions::None) + .expect("wallet"); + derive_auto_accept_private_key(&wallet, network, expiry).expect("derive") + } + + #[tokio::test] + async fn exports_the_key_the_wallet_seed_derives() { + let provider = AutoAcceptKeyExport::new(&SEED, NETWORK); + let path = auto_accept_derivation_path(NETWORK, EXPIRY).expect("path"); + let key = provider + .export_auto_accept_private_key(&path) + .await + .expect("export"); + assert_eq!(key, seed_key(&SEED, NETWORK, EXPIRY)); + } + + /// Only this network's `m/9'/coin'/16'/expiry'` is served: no other + /// feature, coin, depth or a non-hardened expiry. + #[tokio::test] + async fn refuses_every_path_but_the_auto_accept_one() { + let provider = AutoAcceptKeyExport::new(&SEED, NETWORK); + for path in [ + "m", + "m/9'/1'/16'", + "m/9'/1'/16'/5", + "m/9'/1'/16'/5'/0'", + "m/9'/1'/15'/5'", + "m/9'/1'/5'/5'", + "m/9'/5'/16'/5'", + "m/44'/1'/16'/5'", + "m/9/1'/16'/5'", + ] { + let path = DerivationPath::from_str(path).expect("path"); + assert!( + provider + .export_auto_accept_private_key(&path) + .await + .is_err(), + "{path}" + ); + } + } + + #[tokio::test] + async fn refuses_every_other_crypto_request() { + let provider = AutoAcceptKeyExport::new(&SEED, NETWORK); + let path = auto_accept_derivation_path(NETWORK, EXPIRY).expect("path"); + assert!(provider.receiving_xpub(&path).await.is_err()); + let peer = PublicKey::from_secret_key(&seed_key(&SEED, NETWORK, EXPIRY)); + assert!(provider.ecdh_shared_secret(&path, &peer).await.is_err()); + assert!(provider.export_invitation_private_key(&path).await.is_err()); + assert!(provider.account_reference(&path, &[], 0, 0).await.is_err()); + assert!( + provider + .unmask_account_reference(&path, &[], 0) + .await + .is_err() + ); + assert!( + provider + .contact_info_seal(&path, 0, &[0; 32], b"", &[0; 16]) + .await + .is_err() + ); + assert!( + provider + .contact_info_open(&path, 0, &[0; 32], b"") + .await + .is_err() + ); + } + + /// The QR the backend builds carries the identity's username and the key + /// its wallet seed derives, expires in one hour, and a scanner's proof + /// made with it verifies against that seed's public key. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn the_qr_carries_the_wallet_seed_auto_accept_key() { + use crate::model::wallet::Wallet as DetWallet; + use crate::model::wallet::birth_height::WalletOrigin; + use std::collections::BTreeMap; + + let dir = tempfile::tempdir().expect("temp dir"); + let context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = context.wallet_backend().expect("backend wired"); + let seed: [u8; 64] = rand::random(); + let wallet = DetWallet::new_from_seed(seed, NETWORK, Some("w".into()), None).expect("w"); + let (seed_hash, wallet) = context + .register_wallet(wallet, &seed, WalletOrigin::Fresh) + .expect("register wallet"); + backend + .register_wallet_from_seed(&seed_hash, &seed, Some(0)) + .await + .expect("register upstream"); + let owner = Identifier::from([0x11; 32]); + let mut identity = crate::context::test_support::bare_user_identity(owner, NETWORK); + identity.associated_wallets = BTreeMap::from([(seed_hash, wallet)]); + + let before = now_secs(); + let uri = backend + .dashpay_build_contact_qr(&identity, "alice") + .await + .expect("build QR"); + let qr = ContactQrCode::parse(&uri).expect("parse"); + + assert!(uri.starts_with("dash:?du=alice&dapk="), "{uri}"); + assert_eq!(qr.username(), "alice"); + let expiry = u64::from(qr.expires_at()); + let ttl = u64::from(AUTO_ACCEPT_TTL_SECS); + assert!((before + ttl..=now_secs() + ttl).contains(&expiry)); + + let scanner = Identifier::from([0x22; 32]); + let proof = qr.sign_proof(&scanner, &owner, 3); + let owner_key = PublicKey::from_secret_key(&seed_key(&seed, NETWORK, qr.expires_at())); + assert!(verify_auto_accept_proof_with_pubkey( + &owner_key, &proof, &scanner, &owner, 3 + )); + } + + #[tokio::test] + async fn an_identity_without_a_wallet_cannot_build_a_qr() { + let dir = tempfile::tempdir().expect("temp dir"); + let context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = context.wallet_backend().expect("backend wired"); + let identity = + crate::context::test_support::bare_user_identity(Identifier::from([5; 32]), NETWORK); + + let result = backend.dashpay_build_contact_qr(&identity, "alice").await; + + assert!( + matches!( + result, + Err(TaskError::DashPay( + DashPayError::ContactQrIdentityNotFromWallet + )) + ), + "{result:?}" + ); + } + + fn now_secs() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("clock") + .as_secs() + } +} diff --git a/src/wallet_backend/mod.rs b/src/wallet_backend/mod.rs index ec360fd29..145890cc2 100644 --- a/src/wallet_backend/mod.rs +++ b/src/wallet_backend/mod.rs @@ -23,6 +23,7 @@ pub mod auth_pubkey_cache; #[cfg(not(any(test, feature = "bench")))] pub(crate) mod auth_pubkey_cache; +mod auto_accept; mod avatar_cache; mod contact_info; mod contact_profile_cache; From 39b610b6ececa3cdb3fdd0bf40681593d0a0fd83 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:14:49 +0000 Subject: [PATCH 61/73] fix(dashpay): harden contact QR parsing and the auto-accept key export MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-ups from the security review of the platform-wallet contact QR change: - A scanned code's `du` must be a valid DPNS label: [a-zA-Z0-9-], 3–63 characters, no leading or trailing hyphen, optionally followed by `.dash` in any case. Bidi overrides, zero-width and control characters, dotted names and over-long strings are refused with ContactQrCodeError::NotADashUsername. - AutoAcceptKeyExport refuses a key whose expiry is later than now plus one QR lifetime plus 300 s of clock skew. The refusal is the typed AutoAcceptKeyRefusal::ExpiryTooFar, so the provider cannot mint a long-lived bearer key. - The built QR travels in ContactQrUri, whose Debug is redacted, so the dapk key can never reach logs through the task result. - The scanner and generator text no longer claims Dash Evo Tool accepts QR requests automatically, because it does not yet. A TODO in dashpay_sync records the missing drain_pending_contact_crypto_verified wiring. Co-Authored-By: Claude Opus 5.5 --- src/backend_task/mod.rs | 7 +- src/model/dashpay_contact_qr.rs | 112 +++++++++++++++++++---- src/ui/dashpay/qr_code_generator.rs | 13 +-- src/ui/dashpay/qr_scanner.rs | 12 +-- src/wallet_backend/auto_accept.rs | 135 +++++++++++++++++++++++----- src/wallet_backend/dashpay.rs | 8 ++ 6 files changed, 230 insertions(+), 57 deletions(-) diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index fabd599f7..4a792c987 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -975,9 +975,10 @@ pub enum BackendTaskSuccessResult { /// fire; the app responds by calling /// [`queue_all_wallets_identity_discovery`](crate::context::AppContext::queue_all_wallets_identity_discovery). PlatformReadyDiscoverIdentities, - /// Auto-accept contact QR payload, ready to render. The proof is built - /// through the JIT chokepoint in the backend so the UI never touches a seed. - DashPayAutoAcceptQrCode(String), + /// Contact QR code (DIP-0015 auto-accept), ready to render. The key comes + /// from the wallet seed through the secret seam in the backend, so the UI + /// never touches a seed; `Debug` hides the code, which carries that key. + DashPayAutoAcceptQrCode(crate::model::dashpay_contact_qr::ContactQrUri), GeneratedZKProof(ProofDataOutput), VerifiedZKProof(bool, ProofDataOutput), GeneratedReceiveAddress { diff --git a/src/model/dashpay_contact_qr.rs b/src/model/dashpay_contact_qr.rs index 6635cb13c..c5c1e57c7 100644 --- a/src/model/dashpay_contact_qr.rs +++ b/src/model/dashpay_contact_qr.rs @@ -35,11 +35,12 @@ pub enum ContactQrCodeError { #[source] source: Arc, }, - /// The code names something that is not a Dash username. + /// The code's `du` is not a DPNS label (`[a-zA-Z0-9-]`, 3 to 63 + /// characters, no leading or trailing hyphen), with or without `.dash`. #[error( - "This QR code does not name a valid Dash username. Ask your contact for a new code and try again." + "This QR code does not contain a valid Dash username. Ask your contact for a new code and try again." )] - InvalidUsername, + NotADashUsername, } impl ContactQrCode { @@ -49,10 +50,9 @@ impl ContactQrCode { source: Arc::new(source), }; let (username, key_blob) = parse_dashpay_contact_uri(text.trim()).map_err(unreadable)?; - let username = username.trim().to_string(); - if username.is_empty() || crate::model::dpns::validate_dpns_input(&username).is_err() { - return Err(ContactQrCodeError::InvalidUsername); - } + let username = dpns_label(&username) + .ok_or(ContactQrCodeError::NotADashUsername)? + .to_string(); let (key, expires_at) = decode_auto_accept_key_blob(&key_blob).map_err(unreadable)?; Ok(Self { username, @@ -61,7 +61,7 @@ impl ContactQrCode { }) } - /// The QR owner's Dash username, as written in the code. + /// The QR owner's Dash username, without the `.dash` suffix. pub fn username(&self) -> &str { &self.username } @@ -69,11 +69,7 @@ impl ContactQrCode { /// The username in its full `.dash` form, so a lookup always resolves it /// through DPNS and never mistakes it for an identity ID. pub fn full_username(&self) -> String { - if crate::model::dpns::has_dash_suffix(&self.username) { - self.username.clone() - } else { - format!("{}.dash", self.username) - } + format!("{}.dash", self.username) } /// The Unix time (seconds) after which the code no longer auto-accepts. @@ -104,6 +100,45 @@ impl ContactQrCode { } } +/// The DPNS label `username` names, with an optional `.dash` suffix +/// (any case) removed; `None` unless the label is a valid DPNS label. +fn dpns_label(username: &str) -> Option<&str> { + const SUFFIX: &str = ".dash"; + let label = match username.len().checked_sub(SUFFIX.len()) { + Some(at) + if username.is_char_boundary(at) && username[at..].eq_ignore_ascii_case(SUFFIX) => + { + &username[..at] + } + _ => username, + }; + (crate::model::dpns::validate_dpns_name(label) + == crate::model::dpns::DpnsNameValidationResult::Valid) + .then_some(label) +} + +/// A contact QR code built for this app's identity. The text carries the +/// owner's auto-accept key, so `Debug` never prints it. +#[derive(Clone, PartialEq, Eq)] +pub struct ContactQrUri(String); + +impl ContactQrUri { + pub fn new(uri: String) -> Self { + Self(uri) + } + + /// The code's text, to render as a QR image or copy. + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Debug for ContactQrUri { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("ContactQrUri()") + } +} + impl std::fmt::Debug for ContactQrCode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ContactQrCode") @@ -202,13 +237,32 @@ mod tests { } } + /// Only a DPNS label (`[a-zA-Z0-9-]`, 3 to 63 characters) is accepted, so + /// a hostile code cannot smuggle bidi overrides, invisible or control + /// characters, or a huge string into the screen and the name lookup. #[test] fn a_code_without_a_dash_username_is_refused() { - for username in ["", " ", "alice.com"] { + let too_long = "a".repeat(64); + for username in [ + "", + " ", + " alice", + "ab", + "-alice", + "alice-", + "alice.com", + "a.b.dash", + "ali\u{202E}ce", + "ali\u{200B}ce", + "ali\nce", + "alice\u{0}", + "äli", + too_long.as_str(), + ] { assert!( matches!( ContactQrCode::parse(&uri(username, &key())), - Err(ContactQrCodeError::InvalidUsername) + Err(ContactQrCodeError::NotADashUsername) ), "{username:?}" ); @@ -216,9 +270,31 @@ mod tests { } #[test] - fn a_full_username_is_kept_as_is() { - let qr = ContactQrCode::parse(&uri("alice.dash", &key())).expect("parse"); - assert_eq!(qr.full_username(), "alice.dash"); + fn the_longest_dpns_label_is_accepted() { + let longest = "a".repeat(63); + let qr = ContactQrCode::parse(&uri(&longest, &key())).expect("parse"); + assert_eq!(qr.username(), longest); + } + + #[test] + fn a_full_username_is_read_as_its_label() { + for username in ["alice.dash", "alice.DASH"] { + let qr = ContactQrCode::parse(&uri(username, &key())).expect("parse"); + assert_eq!(qr.username(), "alice"); + assert_eq!(qr.full_username(), "alice.dash"); + } + } + + /// The built code reaches results and logs only through `ContactQrUri`, + /// whose `Debug` hides it. + #[test] + fn a_built_code_is_hidden_from_debug_output() { + let text = uri("alice", &key()); + let built = ContactQrUri::new(text.clone()); + assert_eq!(built.as_str(), text); + let debug = format!("{built:?}"); + assert!(debug.contains("")); + assert!(!debug.contains("dapk")); } #[test] diff --git a/src/ui/dashpay/qr_code_generator.rs b/src/ui/dashpay/qr_code_generator.rs index 63315a403..02808fba1 100644 --- a/src/ui/dashpay/qr_code_generator.rs +++ b/src/ui/dashpay/qr_code_generator.rs @@ -23,11 +23,12 @@ use egui::{RichText, ScrollArea, Ui}; use std::sync::{Arc, RwLock}; const QR_CODE_INFO_TEXT: &str = "About Contact QR Codes:\n\n\ - QR codes allow instant mutual contact establishment.\n\n\ + A contact QR code lets someone send you a contact request without typing your username.\n\n\ Someone who scans your code sends you a contact request that proves you invited them.\n\n\ Each QR code is valid for 1 hour. Create a new one when it expires.\n\n\ The code shows your username, so your identity needs a username.\n\n\ - WARNING: Anyone with this QR code can automatically become your contact until it expires."; + Other Dash apps that use this identity may accept such requests automatically. Dash Evo Tool does not yet accept them automatically, so requests from your code wait for you to accept them.\n\n\ + WARNING: Share this code only with people you want as contacts. Anyone who has it can use it until it expires."; /// How long a contact QR code stays valid, in plain words. platform-wallet /// fixes it (`AUTO_ACCEPT_TTL_SECS`): the code carries a usable key. @@ -278,14 +279,14 @@ impl QRCodeGeneratorScreen { ); ui.label( RichText::new( - "Share this QR code with someone to establish a mutual contact", + "Share this QR code with someone you want as a contact.", ) .small() .color(DashColors::text_secondary(dark_mode)), ); ui.label( RichText::new( - "WARNING: Anyone with this QR code can automatically become your contact", + "WARNING: Anyone who has this QR code can use it until it expires.", ) .small() .color(DashColors::warning_color(dark_mode)), @@ -370,8 +371,8 @@ impl ScreenLike for QRCodeGeneratorScreen { } fn display_task_result(&mut self, result: BackendTaskSuccessResult) { - if let BackendTaskSuccessResult::DashPayAutoAcceptQrCode(qr_string) = result { - self.generated_qr_data = Some(qr_string); + if let BackendTaskSuccessResult::DashPayAutoAcceptQrCode(qr) = result { + self.generated_qr_data = Some(qr.as_str().to_string()); } } } diff --git a/src/ui/dashpay/qr_scanner.rs b/src/ui/dashpay/qr_scanner.rs index 1d0495e75..9f0dc70c6 100644 --- a/src/ui/dashpay/qr_scanner.rs +++ b/src/ui/dashpay/qr_scanner.rs @@ -310,8 +310,8 @@ impl QRScannerScreen { ui.add_space(10.0); - ui.label(RichText::new("ℹ️ This will send a contact request that will be automatically accepted").small()); - ui.label(RichText::new("⚡ Both you and the contact will become mutual contacts instantly").small()); + ui.label(RichText::new("This sends a contact request that proves your contact invited you.").small()); + ui.label(RichText::new("Your contact's app can accept it automatically. Otherwise, your contact accepts it like any other request.").small()); }); } @@ -321,10 +321,10 @@ impl QRScannerScreen { ui.group(|ui| { ui.label(RichText::new("ℹ️ About QR Code Scanning").strong()); ui.separator(); - ui.label("• QR codes enable instant mutual contact establishment"); - ui.label("• The contact request is automatically accepted by both parties"); - ui.label("• No manual approval is needed when using valid QR codes"); - ui.label("• Contact QR codes are valid for 1 hour after they are created"); + ui.label("• Scanning a contact QR code sends a contact request to the person who shared it."); + ui.label("• Their app can accept the request automatically, without asking them."); + ui.label("• Dash Evo Tool does not yet accept such requests automatically. Requests you receive this way wait for you to accept them."); + ui.label("• Contact QR codes are valid for 1 hour after they are created."); }); }); diff --git a/src/wallet_backend/auto_accept.rs b/src/wallet_backend/auto_accept.rs index adb94c1f5..15187a8c7 100644 --- a/src/wallet_backend/auto_accept.rs +++ b/src/wallet_backend/auto_accept.rs @@ -16,7 +16,7 @@ use dash_sdk::dpp::key_wallet::wallet::initialization::WalletAccountCreationOpti use dash_sdk::dpp::secp256k1::{PublicKey, SecretKey}; use platform_wallet::error::PlatformWalletError; use platform_wallet::wallet::identity::crypto::auto_accept::{ - auto_accept_derivation_path, derive_auto_accept_private_key, + AUTO_ACCEPT_TTL_SECS, auto_accept_derivation_path, derive_auto_accept_private_key, }; use platform_wallet::wallet::identity::network::{ ContactCryptoProvider, ContactInfoOpened, ContactInfoSealed, @@ -25,6 +25,7 @@ use zeroize::Zeroizing; use crate::backend_task::dashpay::errors::DashPayError; use crate::backend_task::error::TaskError; +use crate::model::dashpay_contact_qr::ContactQrUri; use crate::model::qualified_identity::QualifiedIdentity; use crate::wallet_backend::{SecretScope, WalletBackend}; @@ -45,7 +46,7 @@ impl WalletBackend { &self, identity: &QualifiedIdentity, username: &str, - ) -> Result { + ) -> Result { let owner = identity.identity.id(); let seed_hash = identity .dashpay_wallet_seed_hash() @@ -65,6 +66,7 @@ impl WalletBackend { dashpay .build_auto_accept_qr(&owner, username, &provider) .await + .map(ContactQrUri::new) .map_err(|source| { DashPayError::ContactQrBuildFailed { source: Arc::new(source), @@ -76,6 +78,10 @@ impl WalletBackend { } } +/// How far the device clock may lag platform-wallet's when it picks a QR +/// expiry, in seconds. +const CLOCK_SKEW_SECS: u64 = 300; + /// Serves platform-wallet the DIP-0015 auto-accept key, and nothing else. /// /// Holds a borrow of the seed for one operation only; it never copies the @@ -83,37 +89,80 @@ impl WalletBackend { pub(crate) struct AutoAcceptKeyExport<'a> { seed: &'a [u8; 64], network: Network, + /// The latest expiry (Unix seconds) a key is exported for: one QR + /// lifetime from now, plus [`CLOCK_SKEW_SECS`]. A key for a later expiry + /// would be a bearer credential that outlives the code it was built for. + latest_expiry: u64, +} + +/// Why [`AutoAcceptKeyExport`] refused a request. Crosses platform-wallet's +/// `ContactCryptoProvider` boundary as [`PlatformWalletError::InvalidParameter`], +/// the only shape that trait allows; the user sees +/// [`DashPayError::ContactQrBuildFailed`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub(crate) enum AutoAcceptKeyRefusal { + /// The request is not for this network's `m/9'/coin'/16'/expiry'`. + #[error("this crypto provider serves the DashPay auto-accept key only")] + NotServed, + /// The requested key would stay valid longer than one QR lifetime. + #[error("an auto-accept key expiring at {expiry} outlives the latest allowed {latest}")] + ExpiryTooFar { expiry: u32, latest: u64 }, +} + +impl From for PlatformWalletError { + fn from(refusal: AutoAcceptKeyRefusal) -> Self { + PlatformWalletError::InvalidParameter(refusal.to_string()) + } } impl<'a> AutoAcceptKeyExport<'a> { pub(crate) fn new(seed: &'a [u8; 64], network: Network) -> Self { - Self { seed, network } + // A clock before 1970 refuses every key rather than any key. + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|elapsed| elapsed.as_secs()) + .unwrap_or_default(); + Self::at(seed, network, now) + } + + /// The provider as it would be at Unix time `now_secs`. + fn at(seed: &'a [u8; 64], network: Network, now_secs: u64) -> Self { + Self { + seed, + network, + latest_expiry: now_secs + .saturating_add(u64::from(AUTO_ACCEPT_TTL_SECS)) + .saturating_add(CLOCK_SKEW_SECS), + } } /// The expiry index of `path` when it is exactly this network's - /// auto-accept path `m/9'/coin'/16'/expiry'`, all hardened. - #[expect( - clippy::result_large_err, - reason = "ContactCryptoProvider fixes PlatformWalletError as the error type" - )] - fn auto_accept_expiry(&self, path: &DerivationPath) -> Result { - let expected = auto_accept_derivation_path(self.network, 0)?; + /// auto-accept path `m/9'/coin'/16'/expiry'`, all hardened, and the expiry + /// is no later than [`Self::latest_expiry`](AutoAcceptKeyExport). + fn auto_accept_expiry(&self, path: &DerivationPath) -> Result { + let expected = auto_accept_derivation_path(self.network, 0) + .map_err(|_| AutoAcceptKeyRefusal::NotServed)?; let (path, expected) = (path.as_ref(), expected.as_ref()); - match path { + let expiry = match path { [feature @ .., ChildNumber::Hardened { index }] if path.len() == expected.len() && feature == &expected[..expected.len() - 1] => { - Ok(*index) + *index } - _ => Err(not_auto_accept()), + _ => return Err(AutoAcceptKeyRefusal::NotServed), + }; + if u64::from(expiry) > self.latest_expiry { + return Err(AutoAcceptKeyRefusal::ExpiryTooFar { + expiry, + latest: self.latest_expiry, + }); } + Ok(expiry) } } fn not_auto_accept() -> PlatformWalletError { - PlatformWalletError::InvalidParameter( - "this crypto provider serves the DashPay auto-accept key only".to_string(), - ) + AutoAcceptKeyRefusal::NotServed.into() } #[async_trait::async_trait] @@ -197,15 +246,19 @@ mod tests { use super::*; use crate::model::dashpay_contact_qr::ContactQrCode; use dash_sdk::platform::Identifier; - use platform_wallet::wallet::identity::crypto::auto_accept::{ - AUTO_ACCEPT_TTL_SECS, verify_auto_accept_proof_with_pubkey, - }; + use platform_wallet::wallet::identity::crypto::auto_accept::verify_auto_accept_proof_with_pubkey; use std::str::FromStr; /// Generated each run, so no seed bytes are committed. static SEED: std::sync::LazyLock<[u8; 64]> = std::sync::LazyLock::new(rand::random); const NETWORK: Network = Network::Testnet; const EXPIRY: u32 = 1_900_000_000; + /// A moment at which a QR built now expires at [`EXPIRY`]. + const NOW: u64 = EXPIRY as u64 - AUTO_ACCEPT_TTL_SECS as u64; + + fn provider() -> AutoAcceptKeyExport<'static> { + AutoAcceptKeyExport::at(&SEED, NETWORK, NOW) + } /// The key the wallet seed itself yields at `expiry`, derived by /// platform-wallet with no DET code in between. @@ -217,7 +270,7 @@ mod tests { #[tokio::test] async fn exports_the_key_the_wallet_seed_derives() { - let provider = AutoAcceptKeyExport::new(&SEED, NETWORK); + let provider = provider(); let path = auto_accept_derivation_path(NETWORK, EXPIRY).expect("path"); let key = provider .export_auto_accept_private_key(&path) @@ -230,7 +283,7 @@ mod tests { /// feature, coin, depth or a non-hardened expiry. #[tokio::test] async fn refuses_every_path_but_the_auto_accept_one() { - let provider = AutoAcceptKeyExport::new(&SEED, NETWORK); + let provider = provider(); for path in [ "m", "m/9'/1'/16'", @@ -253,9 +306,43 @@ mod tests { } } + /// A key that would outlive one QR lifetime (plus clock skew) is refused, + /// so the provider cannot mint a long-lived bearer credential. + #[tokio::test] + async fn refuses_a_key_that_outlives_one_qr_lifetime() { + let provider = provider(); + let latest = NOW + u64::from(AUTO_ACCEPT_TTL_SECS) + CLOCK_SKEW_SECS; + let latest_index = u32::try_from(latest).expect("index"); + let at = |expiry| auto_accept_derivation_path(NETWORK, expiry).expect("path"); + + assert_eq!( + provider.auto_accept_expiry(&at(latest_index)), + Ok(latest_index) + ); + assert!( + provider + .export_auto_accept_private_key(&at(latest_index)) + .await + .is_ok() + ); + assert_eq!( + provider.auto_accept_expiry(&at(latest_index + 1)), + Err(AutoAcceptKeyRefusal::ExpiryTooFar { + expiry: latest_index + 1, + latest, + }) + ); + assert!( + provider + .export_auto_accept_private_key(&at(latest_index + 1)) + .await + .is_err() + ); + } + #[tokio::test] async fn refuses_every_other_crypto_request() { - let provider = AutoAcceptKeyExport::new(&SEED, NETWORK); + let provider = provider(); let path = auto_accept_derivation_path(NETWORK, EXPIRY).expect("path"); assert!(provider.receiving_xpub(&path).await.is_err()); let peer = PublicKey::from_secret_key(&seed_key(&SEED, NETWORK, EXPIRY)); @@ -312,9 +399,9 @@ mod tests { .dashpay_build_contact_qr(&identity, "alice") .await .expect("build QR"); - let qr = ContactQrCode::parse(&uri).expect("parse"); + let qr = ContactQrCode::parse(uri.as_str()).expect("parse"); - assert!(uri.starts_with("dash:?du=alice&dapk="), "{uri}"); + assert!(uri.as_str().starts_with("dash:?du=alice&dapk=")); assert_eq!(qr.username(), "alice"); let expiry = u64::from(qr.expires_at()); let ttl = u64::from(AUTO_ACCEPT_TTL_SECS); diff --git a/src/wallet_backend/dashpay.rs b/src/wallet_backend/dashpay.rs index c06041510..f74b95192 100644 --- a/src/wallet_backend/dashpay.rs +++ b/src/wallet_backend/dashpay.rs @@ -1073,6 +1073,14 @@ impl WalletBackend { }; let identity = wallet.identity(); let dashpay = identity.dashpay(); + // TODO(dashpay auto-accept): `sync_contact_requests` queues an + // `AutoAccept` op for every incoming request that carries a DIP-0015 + // `autoAcceptProof`, but DET never drains that queue, so requests + // from scanned contact QR codes wait for a manual accept. Wire + // `PlatformWallet::drain_pending_contact_crypto_verified(provider, + // Some(signer), deadline)` after this sync; it needs a full + // seed-backed `ContactCryptoProvider` (receiving xpub, ECDH, + // accountReference), not the narrow `AutoAcceptKeyExport`. dashpay.sync_contact_requests().await.map_err(|e| { crate::backend_task::error::TaskError::WalletBackend { source: Arc::new(e), From 03260fac1aa87e469984a1ad330b6e08145e79e9 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:42:34 +0000 Subject: [PATCH 62/73] fix(dashpay): hide declined people from the offline contacts list load_contacts_offline filtered out only withdrawn requests, while the network list hides anyone the owner withdrew from or declined (dashpay_disengaged_from). A person whose request the owner declined therefore reappeared after a restart while the owner's own request to them still stood. The offline list now uses the same predicate. Co-Authored-By: Claude Opus 5.5 --- src/backend_task/dashpay/contacts.rs | 72 +++++++++++++++++++++++++++- 1 file changed, 70 insertions(+), 2 deletions(-) diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index 3b0143c8d..8e877f8e9 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -705,11 +705,11 @@ pub async fn load_contacts_offline( if contact_id == owner_id { continue; } - // A withdrawn request stays hidden, as in the network list + // Withdrawn and declined people stay hidden, as in the network list // (`mutual_contacts`). Filtered here rather than in // `DashpayView::contacts`, whose other callers register payment // addresses and must keep every contact. - if backend.dashpay_is_withdrawn(&owner_id, &contact_id) { + if backend.dashpay_disengaged_from(&owner_id, &contact_id) { continue; } @@ -980,6 +980,74 @@ mod tests { ); } + /// Declining someone's request hides them from the offline list even + /// while the owner's own request to them still stands, as in the network + /// list (`dashpay_disengaged_from`). + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn the_offline_list_hides_a_declined_person() { + use crate::model::wallet::Wallet; + use crate::model::wallet::birth_height::WalletOrigin; + use dash_sdk::dpp::dashcore::Network; + use dash_sdk::dpp::identity::Identity; + use dash_sdk::dpp::version::PlatformVersion; + + let dir = tempfile::tempdir().expect("temp dir"); + let context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = context.wallet_backend().expect("backend wired"); + let seed = [0x5Eu8; 64]; + let wallet = + Wallet::new_from_seed(seed, Network::Testnet, Some("w".into()), None).expect("wallet"); + let (seed_hash, wallet) = context + .register_wallet(wallet, &seed, WalletOrigin::Fresh) + .expect("register wallet"); + backend + .register_wallet_from_seed(&seed_hash, &seed, Some(0)) + .await + .expect("register upstream"); + let owner = Identifier::from([0x11; 32]); + let declined = Identifier::from([0x22; 32]); + let kept = Identifier::from([0x33; 32]); + let identity = + Identity::create_basic_identity(owner, PlatformVersion::latest()).expect("identity"); + backend + .ensure_identity_managed(&seed_hash, &identity, 0) + .await + .expect("manage identity"); + let request = |from, to| { + platform_wallet::ContactRequest::new(from, to, 0, 0, 0, vec![0u8; 96], 100_000, 1) + }; + for peer in [declined, kept] { + backend + .record_sent_contact_request(&seed_hash, &owner, request(owner, peer)) + .await + .expect("record sent request"); + } + backend + .record_incoming_contact_request(&seed_hash, &owner, request(declined, owner)) + .await + .expect("record incoming request"); + // Only the decline marker: the owner's own request still stands. + backend + .dashpay_mark_declined(&owner, &declined) + .expect("decline"); + assert!(!backend.dashpay_is_withdrawn(&owner, &declined)); + let mut qualified = + crate::context::test_support::bare_user_identity(owner, Network::Testnet); + qualified.associated_wallets = BTreeMap::from([(seed_hash, wallet)]); + + let result = load_contacts_offline(&context, qualified) + .await + .expect("offline list"); + + let BackendTaskSuccessResult::DashPayContactsWithInfo { contacts, .. } = result else { + panic!("expected DashPayContactsWithInfo, got {result:?}"); + }; + assert_eq!( + contacts.iter().map(|c| c.identity_id).collect::>(), + vec![kept] + ); + } + fn details(note: &str) -> ContactDetails { ContactDetails { nickname: None, From 771d850686ca0c334590a301698ed1a34d05d3cc Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:51:09 +0000 Subject: [PATCH 63/73] fix(dashpay): never leave a contact ignored after a failed decline or cancel Declining or cancelling ignores the person in platform-wallet first and then writes the DET decline/withdrawn marker. When the marker write failed, the ignore stayed while no marker recorded it. A later send or accept then checked only the DET markers, reported AlreadySent or AlreadyEstablished, and never lifted the ignore, so the person's reply could never establish the contact. The fix is both: - Rollback: when the marker cannot be written, the ignore is lifted again, so no half-done decision remains. The user still sees DashPayRequestDecisionNotRecorded. A failed rollback is only logged. - Backstop: restore_withdrawn_request also treats platform-wallet's ignore (ManagedIdentity::is_sender_ignored, read through the new WalletBackend::dashpay_sender_ignored) as a reason to re-engage. That covers a failed rollback and a crash between the two writes, which the rollback alone cannot cover, because the ignore and the marker live in different stores. Co-Authored-By: Claude Opus 5.5 --- src/backend_task/dashpay/contact_requests.rs | 165 ++++++++++++++++++- src/wallet_backend/dashpay.rs | 69 ++++++++ 2 files changed, 229 insertions(+), 5 deletions(-) diff --git a/src/backend_task/dashpay/contact_requests.rs b/src/backend_task/dashpay/contact_requests.rs index 6397836bf..03284ea97 100644 --- a/src/backend_task/dashpay/contact_requests.rs +++ b/src/backend_task/dashpay/contact_requests.rs @@ -829,6 +829,10 @@ trait ReEngageOps { /// /// The decline record could not be read. fn is_declined(&self) -> Result; + /// Whether platform-wallet still ignores the person. A decline or + /// withdrawal ignores them before writing its marker, so an ignore can + /// outlive a marker write that failed (and a rollback that failed too). + fn is_ignored(&self) -> impl Future + Send; /// Lift the ignore and clear the withdrawal and decline markers. fn re_engage(&self) -> impl Future> + Send; } @@ -839,8 +843,10 @@ trait ReEngageOps { /// /// The person is hidden after a withdrawal, or after a decline that a send /// could not clear (see [`re_engage_after_send`]), so sending again retries. +/// An ignore left in platform-wallet without either marker is lifted the same +/// way; otherwise their reply would never establish the contact. async fn restore_withdrawn_request(ops: &O) -> Result { - if !(ops.is_withdrawn()? || ops.is_declined()?) { + if !(ops.is_withdrawn()? || ops.is_declined()? || ops.is_ignored().await) { return Ok(false); } ops.re_engage().await?; @@ -880,6 +886,12 @@ impl ReEngageOps for PlatformReEngage<'_> { .dashpay_decline_recorded(&self.owner, &self.peer) } + async fn is_ignored(&self) -> bool { + self.backend + .dashpay_sender_ignored(&self.owner, &self.peer) + .await + } + async fn re_engage(&self) -> Result<(), TaskError> { // The ignore first: the withdrawal keeps the person out of the lists // until it is lifted, so a failure here leaves a retry possible. @@ -935,6 +947,8 @@ trait RejectOps { /// Ignore the sender in platform-wallet (local only), unless the contact /// is already established there; returns whether the ignore stands. fn ignore_sender(&self) -> impl Future> + Send; + /// Undo [`Self::ignore_sender`] when the decline cannot be recorded. + fn unignore_sender(&self) -> impl Future> + Send; fn mark_declined(&self) -> Result<(), TaskError>; fn request_id(&self) -> Identifier; fn sender_id(&self) -> Identifier; @@ -951,6 +965,32 @@ fn recorded_on_this_device(error: TaskError) -> TaskError { } } +/// Record a decline or withdrawal whose ignore already stands; if the record +/// cannot be written, lift the ignore again so no half-done decision is left. +/// +/// The ignore and the marker live in different stores (platform-wallet's and +/// DET's), so they cannot change together. A rollback that fails too is only +/// logged: the user is told the decision was not recorded, and the next send +/// or accept lifts the leftover ignore (see [`restore_withdrawn_request`]). +async fn record_or_unignore( + mark: Result<(), TaskError>, + unignore: impl FnOnce() -> U, +) -> Result<(), TaskError> +where + U: Future>, +{ + let Err(error) = mark else { + return Ok(()); + }; + if let Err(rollback) = unignore().await { + tracing::warn!( + ?rollback, + "could not lift the ignore of a decision that was not recorded" + ); + } + Err(recorded_on_this_device(error)) +} + /// The progress record an older version kept is read by nothing once the /// decision is recorded, so failing to forget it leaves an inert entry and /// does not fail the action. @@ -966,9 +1006,8 @@ fn forget_phase(cleared: Result<(), TaskError>) { async fn reject_flow(ops: &O) -> Result { let _action_guard = ops.lock_action().await?; let result = if ops.ignore_sender().await? { - complete_rejection(ops.request_id(), || { - ops.mark_declined().map_err(recorded_on_this_device) - })? + let recorded = record_or_unignore(ops.mark_declined(), || ops.unignore_sender()).await; + complete_rejection(ops.request_id(), || recorded)? } else { // The contact was established before the ignore took effect. BackendTaskSuccessResult::DashPayContactAlreadyEstablished { @@ -1013,6 +1052,13 @@ impl RejectOps for PlatformRejectOps<'_> { .await } + async fn unignore_sender(&self) -> Result<(), TaskError> { + self.app_context + .wallet_backend()? + .dashpay_unignore_contact_sender(&self.owner_id, &self.from_identity_id) + .await + } + fn mark_declined(&self) -> Result<(), TaskError> { self.app_context .wallet_backend()? @@ -1074,6 +1120,9 @@ trait CancelOps { /// in first and the contact is already established. fn ignore_recipient(&self) -> impl Future> + Send; + /// Undo [`Self::ignore_recipient`] when the withdrawal cannot be recorded. + fn unignore_recipient(&self) -> impl Future> + Send; + /// Record the withdrawal in the DET sidecar so the request stops being /// listed as pending. /// @@ -1092,7 +1141,7 @@ async fn cancel_flow(ops: &O) -> Result let outcome = if ops.reciprocal_request_exists().await? { CancelOutcome::AlreadyEstablished } else if ops.ignore_recipient().await? { - ops.mark_withdrawn().map_err(recorded_on_this_device)?; + record_or_unignore(ops.mark_withdrawn(), || ops.unignore_recipient()).await?; CancelOutcome::Withdrawn } else { // The reply was taken in after the query, before the ignore. @@ -1162,6 +1211,13 @@ impl CancelOps for PlatformCancelOps<'_> { .dashpay_ignore_unless_established(&self.owner_id, &self.to_identity_id) .await } + + async fn unignore_recipient(&self) -> Result<(), TaskError> { + self.app_context + .wallet_backend()? + .dashpay_unignore_contact_sender(&self.owner_id, &self.to_identity_id) + .await + } } /// Cancel a contact request this identity sent and that is still pending. @@ -1499,6 +1555,8 @@ mod tests { struct ScriptedReEngage { withdrawn: bool, declined: bool, + /// platform-wallet still ignores the person, with no DET marker. + ignored: bool, unreadable: bool, re_engage_fails: bool, re_engaged: std::sync::Mutex, @@ -1518,6 +1576,10 @@ mod tests { Ok(self.declined) } + async fn is_ignored(&self) -> bool { + self.ignored + } + async fn re_engage(&self) -> Result<(), TaskError> { if self.re_engage_fails { return Err(TaskError::DashpaySidecarStorage { @@ -1562,6 +1624,21 @@ mod tests { assert!(*ops.re_engaged.lock().unwrap()); } + /// A decline or withdrawal whose marker write failed after the ignore + /// stood (and whose rollback failed too) leaves only platform-wallet's + /// ignore. Sending or accepting again still lifts it, rather than + /// reporting the request as already sent while the person stays ignored. + #[tokio::test] + async fn an_ignore_left_without_a_marker_is_lifted_on_re_engagement() { + let ops = ScriptedReEngage { + ignored: true, + ..Default::default() + }; + + assert!(restore_withdrawn_request(&ops).await.expect("restored")); + assert!(*ops.re_engaged.lock().unwrap()); + } + /// Accepting (or sending again) where the owner's /// withdrawn request still stands restores it without a new publish. #[tokio::test] @@ -1702,6 +1779,7 @@ mod tests { phase_cleared: Mutex, phase_fails: bool, ignored: Mutex, + unignore_fails: bool, /// The reply is taken in between the reciprocal query and the ignore. established_meanwhile: bool, } @@ -1730,6 +1808,14 @@ mod tests { Ok(!self.established_meanwhile) } + async fn unignore_recipient(&self) -> Result<(), TaskError> { + if self.unignore_fails { + return Err(TaskError::WalletStateInconsistent); + } + *self.ignored.lock().unwrap() = false; + Ok(()) + } + fn mark_withdrawn(&self) -> Result<(), TaskError> { if self.withdraw_fails { return Err(TaskError::DashpaySidecarStorage { @@ -1809,6 +1895,65 @@ mod tests { assert!(cancel_flow(&ops).await.is_err()); } + /// A withdrawal whose marker cannot be written lifts the ignore it just + /// set, so nothing is left half-done: no marker means no ignore. + #[tokio::test] + async fn a_failed_withdrawal_record_lifts_the_ignore_again() { + let ops = ScriptedOps { + withdraw_fails: true, + ..Default::default() + }; + + assert!(matches!( + cancel_flow(&ops).await, + Err(TaskError::DashPayRequestDecisionNotRecorded { .. }) + )); + assert!(!*ops.ignored.lock().unwrap()); + } + + /// The decline twin of `a_failed_withdrawal_record_lifts_the_ignore_again`. + #[tokio::test] + async fn a_failed_decline_record_lifts_the_ignore_again() { + let ops = ScriptedRejectOps { + decline_fails: true, + ..Default::default() + }; + + assert!(matches!( + reject_flow(&ops).await, + Err(TaskError::DashPayRequestDecisionNotRecorded { .. }) + )); + assert!(*ops.unignored.lock().unwrap()); + } + + /// When the rollback fails too, the user still sees why the decision + /// was not recorded, not the rollback's error; the ignore left behind is + /// lifted by the next send or accept + /// (`an_ignore_left_without_a_marker_is_lifted_on_re_engagement`). + #[tokio::test] + async fn a_failed_rollback_reports_the_unrecorded_decision() { + let decline = ScriptedRejectOps { + decline_fails: true, + unignore_fails: true, + ..Default::default() + }; + let withdraw = ScriptedOps { + withdraw_fails: true, + unignore_fails: true, + ..Default::default() + }; + + assert!(matches!( + reject_flow(&decline).await, + Err(TaskError::DashPayRequestDecisionNotRecorded { .. }) + )); + assert!(matches!( + cancel_flow(&withdraw).await, + Err(TaskError::DashPayRequestDecisionNotRecorded { .. }) + )); + assert!(*withdraw.ignored.lock().unwrap()); + } + #[test] fn failed_mark_declined_write_surfaces_error_instead_of_rejected() { let result = complete_rejection(id(7), || { @@ -1831,6 +1976,8 @@ mod tests { phase_fails: bool, established_meanwhile: bool, ignored: Mutex, + unignore_fails: bool, + unignored: Mutex, declined: Mutex, } @@ -1859,6 +2006,14 @@ mod tests { Ok(true) } + async fn unignore_sender(&self) -> Result<(), TaskError> { + if self.unignore_fails { + return Err(TaskError::WalletStateInconsistent); + } + *self.unignored.lock().unwrap() = true; + Ok(()) + } + fn mark_declined(&self) -> Result<(), TaskError> { if self.decline_fails { return Err(TaskError::DashpaySidecarStorage { diff --git a/src/wallet_backend/dashpay.rs b/src/wallet_backend/dashpay.rs index f74b95192..3e11e8ffc 100644 --- a/src/wallet_backend/dashpay.rs +++ b/src/wallet_backend/dashpay.rs @@ -1225,6 +1225,24 @@ impl WalletBackend { }) } + /// Whether platform-wallet ignores `sender`'s contact requests for + /// `owner`. `false` when no wallet manages `owner`. + pub(crate) async fn dashpay_sender_ignored( + &self, + owner: &Identifier, + sender: &Identifier, + ) -> bool { + let Some(wallet) = self.find_wallet_for_identity(owner).await else { + return false; + }; + wallet + .state() + .await + .identity_manager + .managed_identity(owner) + .is_some_and(|managed| managed.is_sender_ignored(sender)) + } + /// Undo [`Self::dashpay_ignore_contact_sender`]: platform-wallet skips an /// ignored sender's requests entirely, so re-engaging with them must /// lift the ignore or their reply never establishes the contact. @@ -3736,4 +3754,55 @@ mod tests { "the unselected wallet's seed must derive a different xpub" ); } + + /// `dashpay_sender_ignored` reads platform-wallet's ignore as decline, + /// withdrawal and their rollback leave it, and is `false` for an identity + /// no wallet manages. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn the_ignore_query_follows_ignore_and_unignore() { + use crate::model::wallet::Wallet; + use crate::model::wallet::birth_height::WalletOrigin; + use dash_sdk::dpp::dashcore::Network; + use dash_sdk::dpp::identity::Identity; + use dash_sdk::dpp::version::PlatformVersion; + + let dir = tempfile::tempdir().expect("temp dir"); + let context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = context.wallet_backend().expect("backend wired"); + let seed = [0x6Fu8; 64]; + let wallet = + Wallet::new_from_seed(seed, Network::Testnet, Some("w".into()), None).expect("wallet"); + let (seed_hash, _wallet) = context + .register_wallet(wallet, &seed, WalletOrigin::Fresh) + .expect("register wallet"); + backend + .register_wallet_from_seed(&seed_hash, &seed, Some(0)) + .await + .expect("register upstream"); + let owner = id_from_byte(0x11); + let peer = id_from_byte(0x22); + let identity = + Identity::create_basic_identity(owner, PlatformVersion::latest()).expect("identity"); + backend + .ensure_identity_managed(&seed_hash, &identity, 0) + .await + .expect("manage identity"); + + assert!(!backend.dashpay_sender_ignored(&owner, &peer).await); + backend + .dashpay_ignore_contact_sender(&owner, &peer) + .await + .expect("ignore"); + assert!(backend.dashpay_sender_ignored(&owner, &peer).await); + backend + .dashpay_unignore_contact_sender(&owner, &peer) + .await + .expect("unignore"); + assert!(!backend.dashpay_sender_ignored(&owner, &peer).await); + assert!( + !backend + .dashpay_sender_ignored(&id_from_byte(0x33), &peer) + .await + ); + } } From 70f2bf3c4dfa1dc650c3717319f7f1de73afdbcf Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 28 Oct 2026 15:49:12 +0000 Subject: [PATCH 64/73] docs(dashpay): link the upstream issue for a failed contact-details publish Co-Authored-By: Claude Opus 5.5 --- src/backend_task/dashpay/contact_info.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index c87823576..14589212f 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -240,6 +240,12 @@ async fn save_contact_details( // A failed publish records nothing. platform-wallet stores the details // here before it publishes, but its error does not say whether it got // that far, and an attempt can equal details that were never stored. + // TODO(upstream): https://github.com/dashpay/platform/issues/5646 — + // platform-wallet keeps its local change when the publish fails, so this + // device can show details Platform never got (or, for a contact with only + // a legacy document, the legacy details again). Once platform-wallet rolls + // the local change back or reports it in a typed outcome, nothing here + // needs to change for the rollback; a typed outcome gets its own arm. let outcome = ops.publish(details).await?; match ops.mark_synced() { Ok(()) => {} From 12f88f36269b0c3fd3b12c3eff92c6472a832d54 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:08:26 +0000 Subject: [PATCH 65/73] test(dashpay): generate the offline tests' wallet seeds at runtime The three offline contacts-list tests and the platform-wallet ignore-query test used constant 64-byte wallet seeds. Each now generates its seed with rand::random(), as the contact-QR and contactInfo provider tests already do, so no wallet seed is committed. Co-Authored-By: Claude Opus 5.5 --- src/backend_task/dashpay/contacts.rs | 6 +++--- src/wallet_backend/dashpay.rs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/backend_task/dashpay/contacts.rs b/src/backend_task/dashpay/contacts.rs index 8e877f8e9..5895b5025 100644 --- a/src/backend_task/dashpay/contacts.rs +++ b/src/backend_task/dashpay/contacts.rs @@ -843,7 +843,7 @@ mod tests { let dir = tempfile::tempdir().expect("temp dir"); let context = crate::context::test_support::wired_test_app_context(dir.path()).await; let backend = context.wallet_backend().expect("backend wired"); - let seed = [0x4Du8; 64]; + let seed: [u8; 64] = rand::random(); let wallet = Wallet::new_from_seed(seed, Network::Testnet, Some("w".into()), None).expect("wallet"); let (seed_hash, wallet) = context @@ -922,7 +922,7 @@ mod tests { let dir = tempfile::tempdir().expect("temp dir"); let context = crate::context::test_support::wired_test_app_context(dir.path()).await; let backend = context.wallet_backend().expect("backend wired"); - let seed = [0x3Cu8; 64]; + let seed: [u8; 64] = rand::random(); let wallet = Wallet::new_from_seed(seed, Network::Testnet, Some("w".into()), None).expect("wallet"); let (seed_hash, wallet) = context @@ -994,7 +994,7 @@ mod tests { let dir = tempfile::tempdir().expect("temp dir"); let context = crate::context::test_support::wired_test_app_context(dir.path()).await; let backend = context.wallet_backend().expect("backend wired"); - let seed = [0x5Eu8; 64]; + let seed: [u8; 64] = rand::random(); let wallet = Wallet::new_from_seed(seed, Network::Testnet, Some("w".into()), None).expect("wallet"); let (seed_hash, wallet) = context diff --git a/src/wallet_backend/dashpay.rs b/src/wallet_backend/dashpay.rs index e5ff8a5ac..127a43b50 100644 --- a/src/wallet_backend/dashpay.rs +++ b/src/wallet_backend/dashpay.rs @@ -3766,7 +3766,7 @@ mod tests { let dir = tempfile::tempdir().expect("temp dir"); let context = crate::context::test_support::wired_test_app_context(dir.path()).await; let backend = context.wallet_backend().expect("backend wired"); - let seed = [0x6Fu8; 64]; + let seed: [u8; 64] = rand::random(); let wallet = Wallet::new_from_seed(seed, Network::Testnet, Some("w".into()), None).expect("wallet"); let (seed_hash, _wallet) = context From bcd571042095c9a4aecf1cc767d9db17d602521e Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 29 Oct 2026 08:38:25 +0000 Subject: [PATCH 66/73] fix(dashpay): keep a send from re-engaging halfway through a cancel A send's re-engagement could land between a cancel's ignore and its withdrawal marker, leaving the fresh request withdrawn. The send now records and re-engages under the person's request-action lock; accept, which already holds that lock, hands it down instead of locking again. Co-Authored-By: Claude Opus 5.5 --- src/backend_task/dashpay/contact_requests.rs | 208 +++++++++++++++++-- 1 file changed, 187 insertions(+), 21 deletions(-) diff --git a/src/backend_task/dashpay/contact_requests.rs b/src/backend_task/dashpay/contact_requests.rs index 319dfaebd..3f5457ecc 100644 --- a/src/backend_task/dashpay/contact_requests.rs +++ b/src/backend_task/dashpay/contact_requests.rs @@ -237,6 +237,32 @@ pub async fn send_contact_request_with_proof( to_username_or_id: String, account_label: Option, qr_code: Option, +) -> Result { + send_contact_request_inner( + app_context, + sdk, + identity, + signing_key, + to_username_or_id, + account_label, + qr_code, + None, + ) + .await +} + +/// Body of [`send_contact_request_with_proof`]; `held` is the request-action +/// lock a caller already holds for the recipient, if any. +#[allow(clippy::too_many_arguments)] +async fn send_contact_request_inner( + app_context: &Arc, + sdk: &Sdk, + identity: QualifiedIdentity, + signing_key: IdentityPublicKey, + to_username_or_id: String, + account_label: Option, + qr_code: Option, + held: Option<&HeldPeerLock<'_>>, ) -> Result { if let Some(label) = account_label.as_deref() && let Err(error) = crate::model::dashpay::validate_account_label(label) @@ -592,25 +618,14 @@ pub async fn send_contact_request_with_proof( created_at_ts, ); if let Ok(backend) = app_context.wallet_backend() { - if let Err(err) = backend - .record_sent_contact_request(&seed_hash, &owner_id, contact_record) - .await - { - tracing::warn!( - %err, - "record_sent_contact_request failed; contact was sent but \ - local wallet-manager state not updated", - ); - } - - // Sending to someone retires an earlier decline of their request and an - // earlier withdrawal of ours: the user has deliberately re-engaged, so - // neither direction may stay filtered out of the list. - re_engage_after_send(&PlatformReEngage { - backend: &backend, - owner: owner_id, - peer: to_identity_id, - }) + finish_send( + &backend, + &seed_hash, + owner_id, + to_identity_id, + contact_record, + held, + ) .await?; } @@ -619,6 +634,59 @@ pub async fn send_contact_request_with_proof( )) } +/// A caller's borrow of the request-action lock it holds for `owner` and +/// `peer` (see `WalletBackend::dashpay_lock_contact_request_action`). The lock +/// is not reentrant, so code running under it is handed this instead of +/// locking again. +struct HeldPeerLock<'a> { + owner: Identifier, + peer: Identifier, + _guard: &'a tokio::sync::OwnedMutexGuard<()>, +} + +/// Record a just-published request locally and re-engage its recipient. +async fn finish_send( + backend: &crate::wallet_backend::WalletBackend, + seed_hash: &crate::model::wallet::WalletSeedHash, + owner_id: Identifier, + to_identity_id: Identifier, + contact_record: UpstreamContactRequest, + held: Option<&HeldPeerLock<'_>>, +) -> Result<(), TaskError> { + // A cancel ignores the person and then records the withdrawal; a + // re-engagement landing in between would leave this fresh request + // withdrawn, so it waits for the person's lock. + let _peer_guard = match held { + Some(held) if held.owner == owner_id && held.peer == to_identity_id => None, + _ => Some( + backend + .dashpay_lock_contact_request_action(&owner_id, &to_identity_id) + .await, + ), + }; + + if let Err(err) = backend + .record_sent_contact_request(seed_hash, &owner_id, contact_record) + .await + { + tracing::warn!( + %err, + "record_sent_contact_request failed; contact was sent but \ + local wallet-manager state not updated", + ); + } + + // Sending to someone retires an earlier decline of their request and an + // earlier withdrawal of ours: the user has deliberately re-engaged, so + // neither direction may stay filtered out of the list. + re_engage_after_send(&PlatformReEngage { + backend, + owner: owner_id, + peer: to_identity_id, + }) + .await +} + async fn resolve_username_to_identity(sdk: &Sdk, username: &str) -> Result { // The name's own record names its identity, which after a transfer is not // the document's owner. @@ -665,7 +733,7 @@ pub async fn accept_contact_request( // Accept, decline and cancel lock on the person too: a cancel of the // owner's request to them must not record a withdrawal while this accept // establishes the contact. - let _peer_guard = app_context + let peer_guard = app_context .wallet_backend()? .dashpay_lock_contact_request_action(&owner_id, &from_identity_id) .await; @@ -778,13 +846,21 @@ pub async fn accept_contact_request( } } - let result = send_contact_request( + // The reply is sent under the person's lock taken above, which the send + // would otherwise wait on forever. + let result = send_contact_request_inner( app_context, sdk, identity, signing_key, from_identity_id.to_string(Encoding::Base58), Some("Accepted contact".to_string()), + None, + Some(&HeldPeerLock { + owner: owner_id, + peer: from_identity_id, + _guard: &peer_guard, + }), ) .await; @@ -1472,6 +1548,96 @@ mod tests { ); } + /// A request record for `finish_send`; this test wallet has no such + /// identity, so recording it only logs. + fn sent_record(owner: Identifier, peer: Identifier) -> UpstreamContactRequest { + UpstreamContactRequest::new( + owner, + peer, + 0, + 0, + 0, + bip39::rand::random::<[u8; 32]>().to_vec(), + 0, + 0, + ) + } + + /// A cancel holding the person's lock is not undone halfway: the send + /// waits for it, then retires the withdrawal it recorded, so the fresh + /// request stays listed. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_send_finishing_during_a_cancel_waits_and_then_retires_the_withdrawal() { + let dir = tempfile::tempdir().expect("temp dir"); + let app_context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = app_context.wallet_backend().expect("backend"); + let (owner, peer) = (id(1), id(2)); + let cancel_guard = backend + .dashpay_lock_contact_request_action(&owner, &peer) + .await; + + let send_backend = Arc::clone(&backend); + let seed_hash = bip39::rand::random::<[u8; 32]>(); + let send = tokio::spawn(async move { + finish_send( + &send_backend, + &seed_hash, + owner, + peer, + sent_record(owner, peer), + None, + ) + .await + }); + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + assert!(!send.is_finished(), "the send must wait for the cancel"); + + backend + .dashpay_mark_withdrawn(&owner, &peer) + .expect("withdraw"); + drop(cancel_guard); + send.await.expect("send task").expect("send finished"); + + assert!(!backend.dashpay_disengaged_from(&owner, &peer)); + } + + /// An accept sends its reply under the person's lock it already holds; + /// finishing that send must not wait on the same lock again. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_send_under_the_callers_own_lock_finishes() { + let dir = tempfile::tempdir().expect("temp dir"); + let app_context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = app_context.wallet_backend().expect("backend"); + let (owner, peer) = (id(1), id(2)); + backend + .dashpay_mark_withdrawn(&owner, &peer) + .expect("withdraw"); + let guard = backend + .dashpay_lock_contact_request_action(&owner, &peer) + .await; + + let finished = tokio::time::timeout( + std::time::Duration::from_secs(5), + finish_send( + &backend, + &bip39::rand::random::<[u8; 32]>(), + owner, + peer, + sent_record(owner, peer), + Some(&HeldPeerLock { + owner, + peer, + _guard: &guard, + }), + ), + ) + .await + .expect("the send must not wait on its caller's lock"); + + finished.expect("send finished"); + assert!(!backend.dashpay_disengaged_from(&owner, &peer)); + } + /// Every send re-engages, a first one included: a declined or withdrawn /// person is a contact again once the owner sends them a request. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] From 566581b8dc364d17af5b823dd4b01bd929b3254a Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 29 Oct 2026 08:38:25 +0000 Subject: [PATCH 67/73] docs(dashpay): say cancel is local only and link the upstream issues Co-Authored-By: Claude Opus 5.5 --- docs/user-stories.md | 2 +- src/backend_task/dashpay/contact_info.rs | 5 ++++- src/wallet_backend/contact_info.rs | 8 ++++---- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/docs/user-stories.md b/docs/user-stories.md index caf9e332a..87503decc 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -1171,7 +1171,7 @@ As a user, I want to cancel a contact request I sent so that it stops sitting in - A DashPay contact request is immutable on Platform and cannot be deleted, so cancelling cannot un-send it. The UI states this plainly rather than implying a withdrawal. - Cancelling re-checks the request against the network first: it must still exist, must have been sent by the acting identity, and must not have already been answered. -- Cancelling publishes a hidden contact-info document and records the withdrawal locally, so the request leaves the sent list and stays gone across restarts. +- Cancelling records the withdrawal on this device only and publishes nothing, so the request leaves the sent list and stays gone across restarts. - A request the other person already accepted is reported as an established contact instead of being cancelled. --- diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 14589212f..65bd2d062 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -297,7 +297,10 @@ impl SaveOps for PlatformSaveOps<'_> { &self, details: ContactDetails, ) -> Result { - // TODO: preserved fields come from `current()`'s read; upstream set_contact_info has no expected-revision check, so a newer edit from another device in between is overwritten. + // TODO(upstream): https://github.com/dashpay/platform/issues/5545 — + // preserved fields come from `current()`'s read; upstream + // set_contact_info has no expected-revision check, so a newer edit from + // another device in between is overwritten. self.backend .dashpay_set_contact_info(self.identity, &self.contact_id, details) .await diff --git a/src/wallet_backend/contact_info.rs b/src/wallet_backend/contact_info.rs index 0abfcba0a..adc6d88be 100644 --- a/src/wallet_backend/contact_info.rs +++ b/src/wallet_backend/contact_info.rs @@ -269,10 +269,10 @@ impl PublishedContactInfos { /// Open `documents` (oldest first) through `crypto`; the newest document per /// contact wins, readable or not. -// TODO(upstream): dip15-contactinfo-reader — replace with a platform-wallet -// contactInfo-only, provider-backed read for seedless wallets once one exists; -// platform-wallet's own drain is crate-private and runs unrelated contact work. -// Upstream request drafted, not yet filed. +// TODO(upstream): https://github.com/dashpay/platform/issues/5595 — replace +// with a platform-wallet contactInfo-only, provider-backed read for seedless +// wallets once one exists; platform-wallet's own drain is crate-private and +// runs unrelated contact work. async fn open_contact_info_documents( crypto: &ContactInfoCrypto<'_>, documents: &[Document], From 09a38b8c086b3b80fef305ae48ea94ac5b824072 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 29 Oct 2026 08:39:13 +0000 Subject: [PATCH 68/73] docs(dashpay): link the upstream issue for erased accepted accounts Co-Authored-By: Claude Opus 5.5 --- src/backend_task/dashpay/contact_info.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 65bd2d062..854544abb 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -231,6 +231,9 @@ async fn save_contact_details( alias_name: details.nickname.clone(), note: details.note.clone(), display_hidden: details.hidden, + // TODO(upstream): https://github.com/dashpay/platform/issues/5657 — + // platform-wallet's save writes an empty list too, erasing the accepted + // accounts already stored for the contact. accepted_accounts: Vec::new(), }) .map_err(|source| TaskError::DashPayContactInfoEncoding { From 33fe2b6fa07bbf03d2dde5adedc3aabe3959c38a Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 29 Oct 2026 08:44:30 +0000 Subject: [PATCH 69/73] refactor(dashpay): mint a held peer lock only from the lock helper The lock a caller hands down now carries the owner and person it was taken for and can be built only by WalletBackend::dashpay_lock_contact_peer, so a send can't be handed a guard for a different pair. Co-Authored-By: Claude Opus 5.5 --- src/backend_task/dashpay/contact_requests.rs | 38 +++++--------------- src/wallet_backend/dashpay.rs | 32 +++++++++++++++++ src/wallet_backend/mod.rs | 3 +- 3 files changed, 43 insertions(+), 30 deletions(-) diff --git a/src/backend_task/dashpay/contact_requests.rs b/src/backend_task/dashpay/contact_requests.rs index 3f5457ecc..a32e49daf 100644 --- a/src/backend_task/dashpay/contact_requests.rs +++ b/src/backend_task/dashpay/contact_requests.rs @@ -10,7 +10,7 @@ use crate::context::AppContext; use crate::model::dashpay::contact_request_recipient; use crate::model::document::new_document_for_creation; use crate::model::qualified_identity::QualifiedIdentity; -use crate::wallet_backend::ContactRequestActionKind; +use crate::wallet_backend::{ContactRequestActionKind, HeldPeerLock}; // Upstream contact-request type: used to record the sent request in the // local wallet-manager so dashpay_sync can auto-establish the contact. use bip39::rand::{SeedableRng, rngs::StdRng}; @@ -262,7 +262,7 @@ async fn send_contact_request_inner( to_username_or_id: String, account_label: Option, qr_code: Option, - held: Option<&HeldPeerLock<'_>>, + held: Option<&HeldPeerLock>, ) -> Result { if let Some(label) = account_label.as_deref() && let Err(error) = crate::model::dashpay::validate_account_label(label) @@ -634,16 +634,6 @@ async fn send_contact_request_inner( )) } -/// A caller's borrow of the request-action lock it holds for `owner` and -/// `peer` (see `WalletBackend::dashpay_lock_contact_request_action`). The lock -/// is not reentrant, so code running under it is handed this instead of -/// locking again. -struct HeldPeerLock<'a> { - owner: Identifier, - peer: Identifier, - _guard: &'a tokio::sync::OwnedMutexGuard<()>, -} - /// Record a just-published request locally and re-engage its recipient. async fn finish_send( backend: &crate::wallet_backend::WalletBackend, @@ -651,13 +641,13 @@ async fn finish_send( owner_id: Identifier, to_identity_id: Identifier, contact_record: UpstreamContactRequest, - held: Option<&HeldPeerLock<'_>>, + held: Option<&HeldPeerLock>, ) -> Result<(), TaskError> { // A cancel ignores the person and then records the withdrawal; a // re-engagement landing in between would leave this fresh request // withdrawn, so it waits for the person's lock. let _peer_guard = match held { - Some(held) if held.owner == owner_id && held.peer == to_identity_id => None, + Some(held) if held.covers(&owner_id, &to_identity_id) => None, _ => Some( backend .dashpay_lock_contact_request_action(&owner_id, &to_identity_id) @@ -733,9 +723,9 @@ pub async fn accept_contact_request( // Accept, decline and cancel lock on the person too: a cancel of the // owner's request to them must not record a withdrawal while this accept // establishes the contact. - let peer_guard = app_context + let peer_lock = app_context .wallet_backend()? - .dashpay_lock_contact_request_action(&owner_id, &from_identity_id) + .dashpay_lock_contact_peer(&owner_id, &from_identity_id) .await; // Check if we already sent a contact request to this identity @@ -856,11 +846,7 @@ pub async fn accept_contact_request( from_identity_id.to_string(Encoding::Base58), Some("Accepted contact".to_string()), None, - Some(&HeldPeerLock { - owner: owner_id, - peer: from_identity_id, - _guard: &peer_guard, - }), + Some(&peer_lock), ) .await; @@ -1612,9 +1598,7 @@ mod tests { backend .dashpay_mark_withdrawn(&owner, &peer) .expect("withdraw"); - let guard = backend - .dashpay_lock_contact_request_action(&owner, &peer) - .await; + let peer_lock = backend.dashpay_lock_contact_peer(&owner, &peer).await; let finished = tokio::time::timeout( std::time::Duration::from_secs(5), @@ -1624,11 +1608,7 @@ mod tests { owner, peer, sent_record(owner, peer), - Some(&HeldPeerLock { - owner, - peer, - _guard: &guard, - }), + Some(&peer_lock), ), ) .await diff --git a/src/wallet_backend/dashpay.rs b/src/wallet_backend/dashpay.rs index 127a43b50..86954d081 100644 --- a/src/wallet_backend/dashpay.rs +++ b/src/wallet_backend/dashpay.rs @@ -389,6 +389,23 @@ impl ContactRequestActionLocks { } } +/// `owner`'s request-action lock for `peer`, held while this lives. The lock +/// is not reentrant, so code running under it is handed this instead of +/// locking again. Only [`WalletBackend::dashpay_lock_contact_peer`] mints it, +/// so the pair it names is the pair it locks. +pub(crate) struct HeldPeerLock { + owner: Identifier, + peer: Identifier, + _guard: tokio::sync::OwnedMutexGuard<()>, +} + +impl HeldPeerLock { + /// Whether this is `owner`'s lock for `peer`. + pub(crate) fn covers(&self, owner: &Identifier, peer: &Identifier) -> bool { + self.owner == *owner && self.peer == *peer + } +} + /// Contact-request expiry threshold. A pending outgoing request older /// than this is surfaced as `"expired"` rather than `"pending"`. DET /// has no protocol-level expiry — this is purely a UX gate so the @@ -1418,6 +1435,21 @@ impl WalletBackend { .await } + /// [`Self::dashpay_lock_contact_request_action`] keyed by the person, + /// returned as a [`HeldPeerLock`] that code running under it is handed + /// instead of locking again. + pub(crate) async fn dashpay_lock_contact_peer( + &self, + owner: &Identifier, + peer: &Identifier, + ) -> HeldPeerLock { + HeldPeerLock { + owner: *owner, + peer: *peer, + _guard: self.dashpay_lock_contact_request_action(owner, peer).await, + } + } + pub(crate) fn dashpay_clear_contact_request_action( &self, owner: &Identifier, diff --git a/src/wallet_backend/mod.rs b/src/wallet_backend/mod.rs index 145890cc2..f24a089d9 100644 --- a/src/wallet_backend/mod.rs +++ b/src/wallet_backend/mod.rs @@ -81,7 +81,8 @@ pub(crate) mod wallet_seed_store; pub use dashpay::DashpayView; pub(crate) use dashpay::{ - ContactRequestActionKind, derive_contact_info_encryption_keys, derive_contact_xpub_material, + ContactRequestActionKind, HeldPeerLock, derive_contact_info_encryption_keys, + derive_contact_xpub_material, }; pub(crate) use contact_info::PublishedContactInfos; From e25ea74b1d7faf6925d2dca21f106f1813e51c28 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 29 Oct 2026 08:49:56 +0000 Subject: [PATCH 70/73] test(dashpay): pin that accept's handed-down lock never deadlocks its reply Co-Authored-By: Claude Opus 5.5 --- src/backend_task/dashpay/contact_requests.rs | 37 ++++++++++++++++++-- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/src/backend_task/dashpay/contact_requests.rs b/src/backend_task/dashpay/contact_requests.rs index a32e49daf..a6500de2f 100644 --- a/src/backend_task/dashpay/contact_requests.rs +++ b/src/backend_task/dashpay/contact_requests.rs @@ -1587,10 +1587,11 @@ mod tests { assert!(!backend.dashpay_disengaged_from(&owner, &peer)); } - /// An accept sends its reply under the person's lock it already holds; - /// finishing that send must not wait on the same lock again. + /// An accept sends its reply under the person's lock it already holds and + /// hands that lock down; `finish_send` is the only place the send path + /// takes the lock, so the reply finishes instead of waiting on itself. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn a_send_under_the_callers_own_lock_finishes() { + async fn an_accepts_reply_under_its_own_peer_lock_finishes() { let dir = tempfile::tempdir().expect("temp dir"); let app_context = crate::context::test_support::wired_test_app_context(dir.path()).await; let backend = app_context.wallet_backend().expect("backend"); @@ -1618,6 +1619,36 @@ mod tests { assert!(!backend.dashpay_disengaged_from(&owner, &peer)); } + /// A lock held for someone else does not stand in for the recipient's: + /// the send still waits for a cancel holding the recipient's lock. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_lock_held_for_another_person_does_not_skip_the_wait() { + let dir = tempfile::tempdir().expect("temp dir"); + let app_context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = app_context.wallet_backend().expect("backend"); + let (owner, peer, other) = (id(1), id(2), id(3)); + let other_lock = backend.dashpay_lock_contact_peer(&owner, &other).await; + let cancel_guard = backend + .dashpay_lock_contact_request_action(&owner, &peer) + .await; + + let waited = tokio::time::timeout( + std::time::Duration::from_millis(300), + finish_send( + &backend, + &bip39::rand::random::<[u8; 32]>(), + owner, + peer, + sent_record(owner, peer), + Some(&other_lock), + ), + ) + .await; + + assert!(waited.is_err(), "the send must wait for the cancel"); + drop(cancel_guard); + } + /// Every send re-engages, a first one included: a declined or withdrawn /// person is a contact again once the owner sends them a request. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] From 9b072e96bf98ce3250166172162e8ed3431db7cf Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:13:56 +0000 Subject: [PATCH 71/73] fix(dashpay): restore a withdrawn request under the person's lock Sending again to someone whose earlier request still stands restores it locally instead of publishing. That restore ran outside the per-peer lock a cancel holds while it ignores the person and records the withdrawal, so a restore landing in between lifted the ignore and reported the request sent while the cancel's withdrawal still hid it. The restore now takes the same lock, honouring the lock accept hands down, and accept's own restore goes through the same helper. The send-during-cancel test drives the send on its own task instead of spawning it, so it can no longer pass when the send never got to run. Co-Authored-By: Claude Opus 5.5 --- src/backend_task/dashpay/contact_requests.rs | 154 +++++++++++++++---- 1 file changed, 120 insertions(+), 34 deletions(-) diff --git a/src/backend_task/dashpay/contact_requests.rs b/src/backend_task/dashpay/contact_requests.rs index a6500de2f..e11b5ad75 100644 --- a/src/backend_task/dashpay/contact_requests.rs +++ b/src/backend_task/dashpay/contact_requests.rs @@ -336,12 +336,8 @@ async fn send_contact_request_inner( // it instead of publishing a duplicate. This also finishes a send whose // re-engagement failed after it was published. if let Ok(backend) = app_context.wallet_backend() - && restore_withdrawn_request(&PlatformReEngage { - backend: &backend, - owner: identity.identity.id(), - peer: to_identity_id, - }) - .await? + && restore_under_peer_lock(&backend, identity.identity.id(), to_identity_id, held) + .await? { return Ok(BackendTaskSuccessResult::DashPayContactRequestSent( to_username_or_id.to_string(), @@ -646,14 +642,7 @@ async fn finish_send( // A cancel ignores the person and then records the withdrawal; a // re-engagement landing in between would leave this fresh request // withdrawn, so it waits for the person's lock. - let _peer_guard = match held { - Some(held) if held.covers(&owner_id, &to_identity_id) => None, - _ => Some( - backend - .dashpay_lock_contact_request_action(&owner_id, &to_identity_id) - .await, - ), - }; + let _peer_guard = lock_peer_unless_held(backend, owner_id, to_identity_id, held).await; if let Err(err) = backend .record_sent_contact_request(seed_hash, &owner_id, contact_record) @@ -677,6 +666,44 @@ async fn finish_send( .await } +/// `owner`'s request-action lock for `peer`, or `None` when `held` already +/// is that lock: it is not reentrant, so a caller holding it hands it down. +/// Callers take it only around local writes, never across a network call. +async fn lock_peer_unless_held( + backend: &crate::wallet_backend::WalletBackend, + owner: Identifier, + peer: Identifier, + held: Option<&HeldPeerLock>, +) -> Option> { + match held { + Some(held) if held.covers(&owner, &peer) => None, + _ => Some( + backend + .dashpay_lock_contact_request_action(&owner, &peer) + .await, + ), + } +} + +/// [`restore_withdrawn_request`] under `owner`'s lock for `peer`. A cancel +/// ignores the person and then records the withdrawal under that lock; a +/// restore landing in between would lift the ignore and leave the request +/// withdrawn while reporting it sent. +async fn restore_under_peer_lock( + backend: &crate::wallet_backend::WalletBackend, + owner: Identifier, + peer: Identifier, + held: Option<&HeldPeerLock>, +) -> Result { + let _peer_guard = lock_peer_unless_held(backend, owner, peer, held).await; + restore_withdrawn_request(&PlatformReEngage { + backend, + owner, + peer, + }) + .await +} + async fn resolve_username_to_identity(sdk: &Sdk, username: &str) -> Result { // The name's own record names its identity, which after a transfer is not // the document's owner. @@ -750,11 +777,12 @@ pub async fn accept_contact_request( // Our earlier request still stands on Platform. If it was withdrawn, // accepting restores it, and with it the contact. let backend = app_context.wallet_backend()?; - let restored = restore_withdrawn_request(&PlatformReEngage { - backend: &backend, - owner: identity.identity.id(), - peer: from_identity_id, - }) + let restored = restore_under_peer_lock( + &backend, + identity.identity.id(), + from_identity_id, + Some(&peer_lock), + ) .await?; return Ok(if restored { BackendTaskSuccessResult::DashPayContactRequestAccepted(request_id) @@ -1562,28 +1590,86 @@ mod tests { .dashpay_lock_contact_request_action(&owner, &peer) .await; - let send_backend = Arc::clone(&backend); + // Driven on this task, not spawned, so it has run before the cancel + // records its withdrawal whether or not it waits. let seed_hash = bip39::rand::random::<[u8; 32]>(); - let send = tokio::spawn(async move { - finish_send( - &send_backend, - &seed_hash, - owner, - peer, - sent_record(owner, peer), - None, - ) - .await - }); - tokio::time::sleep(std::time::Duration::from_millis(300)).await; - assert!(!send.is_finished(), "the send must wait for the cancel"); + let mut send = Box::pin(finish_send( + &backend, + &seed_hash, + owner, + peer, + sent_record(owner, peer), + None, + )); + assert_waits(&mut send).await; backend .dashpay_mark_withdrawn(&owner, &peer) .expect("withdraw"); drop(cancel_guard); - send.await.expect("send task").expect("send finished"); + send.await.expect("send finished"); + + assert!(!backend.dashpay_disengaged_from(&owner, &peer)); + } + + /// Drive `fut` long enough for it to finish if nothing blocks it, and + /// assert it did not: it waits on a lock held by the test. + async fn assert_waits(fut: &mut F) { + assert!( + tokio::time::timeout(std::time::Duration::from_millis(300), fut) + .await + .is_err(), + "it must wait for the cancel" + ); + } + + /// Sending again to someone whose request still stands restores it, and + /// waits for a cancel holding the person's lock: restoring between the + /// cancel's ignore and its withdrawal record would report the request + /// sent while leaving it withdrawn. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn a_restore_during_a_cancel_waits_and_then_retires_the_withdrawal() { + let dir = tempfile::tempdir().expect("temp dir"); + let app_context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = app_context.wallet_backend().expect("backend"); + let (owner, peer) = (id(1), id(2)); + let cancel_guard = backend + .dashpay_lock_contact_request_action(&owner, &peer) + .await; + + let mut restore = Box::pin(restore_under_peer_lock(&backend, owner, peer, None)); + assert_waits(&mut restore).await; + + backend + .dashpay_mark_withdrawn(&owner, &peer) + .expect("withdraw"); + drop(cancel_guard); + + assert!(restore.await.expect("restore finished"), "restored"); + assert!(!backend.dashpay_disengaged_from(&owner, &peer)); + } + + /// An accept restores its earlier request under the person's lock it + /// already holds; the restore must not wait on that lock. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn an_accepts_restore_under_its_own_peer_lock_finishes() { + let dir = tempfile::tempdir().expect("temp dir"); + let app_context = crate::context::test_support::wired_test_app_context(dir.path()).await; + let backend = app_context.wallet_backend().expect("backend"); + let (owner, peer) = (id(1), id(2)); + backend + .dashpay_mark_withdrawn(&owner, &peer) + .expect("withdraw"); + let peer_lock = backend.dashpay_lock_contact_peer(&owner, &peer).await; + + let restored = tokio::time::timeout( + std::time::Duration::from_secs(5), + restore_under_peer_lock(&backend, owner, peer, Some(&peer_lock)), + ) + .await + .expect("the restore must not wait on its caller's lock"); + assert!(restored.expect("restore finished"), "restored"); assert!(!backend.dashpay_disengaged_from(&owner, &peer)); } From c76261c828611fd667eae9e2ffa586d2609ed21c Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:13:37 +0000 Subject: [PATCH 72/73] fix(dashpay): adapt merged base code to the reshaped DashPay tasks The fee-payer classification and its test from the base branch name DashPay task variants and fields this branch removed or reshaped; the contact-info fee test used the renamed fee estimator constructor. Co-Authored-By: Claude Opus 5.5 --- src/backend_task/dashpay/contact_info.rs | 9 ++++--- src/backend_task/mod.rs | 30 ++++++++++++++---------- 2 files changed, 24 insertions(+), 15 deletions(-) diff --git a/src/backend_task/dashpay/contact_info.rs b/src/backend_task/dashpay/contact_info.rs index 7e50d21c5..49988566b 100644 --- a/src/backend_task/dashpay/contact_info.rs +++ b/src/backend_task/dashpay/contact_info.rs @@ -606,7 +606,7 @@ mod tests { #[test] fn contact_info_fee_estimate_covers_the_largest_details() { use crate::model::fee_estimation::PlatformFeeEstimator; - let estimator = PlatformFeeEstimator::new(); + let estimator = PlatformFeeEstimator::latest(); for len in [0, 252, 253, 255] { let text = (len > 0).then(|| "x".repeat(len)); let encoded = encode_private_data_bounded(&ContactInfoPrivateData { @@ -1063,8 +1063,11 @@ mod tests { encrypt_to_user_id(&undecryptable.to_buffer(), &key()), ); first.set("privateData", Value::Bytes(vec![0xA5; 48])); - let mut second = - lookup_contact_info_document(2, 2, encrypt_to_user_id(&undecodable.to_buffer(), &key())); + let mut second = lookup_contact_info_document( + 2, + 2, + encrypt_to_user_id(&undecodable.to_buffer(), &key()), + ); second.set( "privateData", Value::Bytes(platform_encryption::encrypt_private_data( diff --git a/src/backend_task/mod.rs b/src/backend_task/mod.rs index 25e5d1d31..7d60ab0e9 100644 --- a/src/backend_task/mod.rs +++ b/src/backend_task/mod.rs @@ -420,6 +420,7 @@ impl BackendTask { | DashPayTask::LoadContacts { .. } | DashPayTask::LoadContactsOffline { .. } | DashPayTask::LoadContactRequests { .. } + | DashPayTask::LoadContactDetails { .. } | DashPayTask::FetchContactProfile { .. } | DashPayTask::FetchAvatar { .. } | DashPayTask::SearchProfiles { .. } @@ -2852,9 +2853,9 @@ mod tests { /// its stored balance is read back after the task; reads name nobody. #[test] fn paid_tasks_name_the_identity_that_pays_for_them() { - use crate::backend_task::dashpay::auto_accept_proof::AutoAcceptProofData; use crate::backend_task::tokens::TokenContractParams; - use crate::model::dashpay::{ContactInfoUpdate, UnreadableContactInfoPolicy}; + use crate::model::dashpay::ContactInfoUpdate; + use crate::model::dashpay_contact_qr::ContactQrCode; use crate::model::qualified_contract::QualifiedContract; use crate::ui::tokens::tokens_screen::IdentityTokenInfo; use dash_sdk::dpp::data_contract::TokenConfiguration; @@ -2868,6 +2869,9 @@ mod tests { use dash_sdk::dpp::system_data_contracts::load_system_data_contract; use dash_sdk::dpp::version::PlatformVersion; use dash_sdk::platform::IdentityPublicKey; + use platform_wallet::wallet::identity::crypto::auto_accept::{ + encode_auto_accept_key_blob, encode_dashpay_contact_uri, + }; // Every other identity-typed field holds a different identity, so a // payer read from the wrong field fails the comparison. @@ -3115,14 +3119,14 @@ mod tests { dashpay(DashPayTask::SendContactRequestWithProof { identity: payer.clone(), signing_key: key.clone(), - to_identity_id: other, - account_label: None, - qr_auto_accept: AutoAcceptProofData { - identity_id: other, - proof_key: [0; 32], - account_reference: 0, - expires_at: 0, - }, + qr_code: ContactQrCode::parse(&encode_dashpay_contact_uri( + "bob", + &encode_auto_accept_key_blob( + &crate::test_support::keys::secret_key(), + 1_900_000_000, + ), + )) + .expect("contact QR code"), }), dashpay(DashPayTask::AcceptContactRequest { identity: payer.clone(), @@ -3131,12 +3135,10 @@ mod tests { dashpay(DashPayTask::RejectContactRequest { identity: payer.clone(), request_id: other, - unreadable: UnreadableContactInfoPolicy::Abort, }), dashpay(DashPayTask::CancelContactRequest { identity: payer.clone(), request_id: other, - unreadable: UnreadableContactInfoPolicy::Abort, }), dashpay(DashPayTask::UpdateContactInfo { identity: payer.clone(), @@ -3161,6 +3163,10 @@ mod tests { dashpay(DashPayTask::LoadProfile { identity: payer.clone(), }), + dashpay(DashPayTask::LoadContactDetails { + identity: payer.clone(), + contact_id: other, + }), dashpay(DashPayTask::SendPaymentToContact { identity: payer.clone(), contact_id: other, From 171e479670217f3026fb9dd36f48a3c75e10f2aa Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 16 Nov 2026 08:37:28 +0000 Subject: [PATCH 73/73] fix(dashpay): show the note fee only when the save publishes With fewer than two contacts DIP-0015 keeps contact details on this device and the save costs nothing, so the editor no longer shows a fee or says the note is stored on Dash Platform in that case. Co-Authored-By: Claude Opus 5.5 --- src/model/dashpay.rs | 18 ++++++++ src/ui/identity/contacts.rs | 46 ++++++++++++++----- tests/kittest/identity_hub_contact_detail.rs | 47 ++++++++++++++++++-- 3 files changed, 95 insertions(+), 16 deletions(-) diff --git a/src/model/dashpay.rs b/src/model/dashpay.rs index a2996ed3a..f02fe1893 100644 --- a/src/model/dashpay.rs +++ b/src/model/dashpay.rs @@ -58,6 +58,16 @@ pub fn validate_contact_note(note: &str) -> Result<(), ContactNoteTooLong> { Ok(()) } +/// DIP-0015 publishes contact details only once the owner has this many +/// established contacts; until then a save stays on this device and is free. +pub const MIN_CONTACTS_TO_PUBLISH_DETAILS: usize = 2; + +/// Whether saving contact details publishes them to Platform, and so pays a +/// fee, for an owner with `contacts` established contacts. +pub fn contact_details_save_publishes(contacts: usize) -> bool { + contacts >= MIN_CONTACTS_TO_PUBLISH_DETAILS +} + /// The recipient (`toUserId`) of a DashPay `contactRequest` document. /// /// Returns `None` when the field is absent or does not hold a readable @@ -496,6 +506,14 @@ mod tests { Identifier::from_bytes(&[byte; 32]).expect("32-byte identifier") } + #[test] + fn contact_details_publish_from_two_contacts() { + assert!(!contact_details_save_publishes(0)); + assert!(!contact_details_save_publishes(1)); + assert!(contact_details_save_publishes(2)); + assert!(contact_details_save_publishes(3)); + } + /// A `contactRequest`-shaped document. `to` of `None` omits `toUserId` /// entirely, modelling a malformed document. fn request_doc(to: Option) -> Document { diff --git a/src/ui/identity/contacts.rs b/src/ui/identity/contacts.rs index eafa43783..a5c5c3a97 100644 --- a/src/ui/identity/contacts.rs +++ b/src/ui/identity/contacts.rs @@ -24,7 +24,10 @@ use crate::backend_task::dashpay::{ContactData, DashPayTask}; use crate::backend_task::{BackendTask, BackendTaskContext}; use crate::context::AppContext; use crate::context::feature_gate::FeatureGate; -use crate::model::dashpay::{ContactInfoUpdate, MAX_CONTACT_NOTE_BYTES, validate_contact_note}; +use crate::model::dashpay::{ + ContactInfoUpdate, MAX_CONTACT_NOTE_BYTES, contact_details_save_publishes, + validate_contact_note, +}; use crate::model::fee_estimation::format_credits_as_dash; use crate::model::qualified_identity::QualifiedIdentity; use crate::ui::ScreenType; @@ -54,11 +57,16 @@ pub const DETAIL_HEADING: &str = "Contact details"; pub const NO_SELECTION: &str = "Select a contact to see their details."; pub const NOTE_HEADING: &str = "Private note"; pub const NOTE_HINT: &str = "Only you can see this note. It is stored encrypted on Dash Platform."; +/// [`NOTE_HINT`] while DIP-0015 keeps contact details on this device. +pub const NOTE_HINT_ON_THIS_DEVICE: &str = "Only you can see this note. Until this identity has two contacts, it is stored on this device only."; pub const NOTE_PLACEHOLDER: &str = "Add a note that only you can see"; pub const SAVE_NOTE_LABEL: &str = "Save note"; pub const SAVING_NOTE_LABEL: &str = "Saving…"; pub const NOTE_UNCHANGED_TOOLTIP: &str = "There are no changes to save."; pub const NOTE_SAVE_TOOLTIP: &str = "Save this note on Dash Platform. Saving costs a small fee."; +/// [`NOTE_SAVE_TOOLTIP`] while DIP-0015 keeps contact details on this device. +pub const NOTE_SAVE_ON_THIS_DEVICE_TOOLTIP: &str = + "Save this note on this device. Saving is free until this identity has two contacts."; pub const NOTE_SAVED: &str = "Your note is saved."; /// Shown when contact details are kept on this device only: DIP-0015 holds /// them back until the identity has two contacts, and nothing publishes them @@ -735,6 +743,8 @@ fn note_editor( dark_mode: bool, ) -> bool { let contact_id = contact.identity_id; + // With fewer than two contacts the save stays on this device: no fee. + let publishes = contact_details_save_publishes(state.contacts_len()); let saving = state .detail() .is_writing(&identity.identity.id(), &contact_id); @@ -749,9 +759,13 @@ fn note_editor( .color(DashColors::text_primary(dark_mode)), ); ui.label( - RichText::new(NOTE_HINT) - .small() - .color(DashColors::text_secondary(dark_mode)), + RichText::new(if publishes { + NOTE_HINT + } else { + NOTE_HINT_ON_THIS_DEVICE + }) + .small() + .color(DashColors::text_secondary(dark_mode)), ); ui.add_space(6.0); ui.add_enabled( @@ -773,13 +787,15 @@ fn note_editor( } ui.add_space(8.0); - let fee = app_context.fee_estimator().estimate_contact_info_write(); - ui.label( - RichText::new(note_fee_text(&format_credits_as_dash(fee))) - .small() - .color(DashColors::text_secondary(dark_mode)), - ); - ui.add_space(6.0); + if publishes { + let fee = app_context.fee_estimator().estimate_contact_info_write(); + ui.label( + RichText::new(note_fee_text(&format_credits_as_dash(fee))) + .small() + .color(DashColors::text_secondary(dark_mode)), + ); + ui.add_space(6.0); + } let dirty = detail.is_dirty(&contact_id); let can_save = dirty && invalid.is_none() && !saving; @@ -790,7 +806,11 @@ fn note_editor( }; let save = ComponentStyles::add_primary_button_enabled(ui, can_save, label); let save = if can_save { - save.clickable_tooltip(NOTE_SAVE_TOOLTIP) + save.clickable_tooltip(if publishes { + NOTE_SAVE_TOOLTIP + } else { + NOTE_SAVE_ON_THIS_DEVICE_TOOLTIP + }) } else if saving { save.disabled_tooltip(NOTE_SAVING_TOOLTIP) } else if let Some(error) = invalid { @@ -1657,8 +1677,10 @@ mod tests { for line in [ NO_SELECTION, NOTE_HINT, + NOTE_HINT_ON_THIS_DEVICE, NOTE_UNCHANGED_TOOLTIP, NOTE_SAVE_TOOLTIP, + NOTE_SAVE_ON_THIS_DEVICE_TOOLTIP, NOTE_SAVED, SELECT_CONTACT_TOOLTIP, NO_RECEIVED_EMPTY, diff --git a/tests/kittest/identity_hub_contact_detail.rs b/tests/kittest/identity_hub_contact_detail.rs index 7f7b645af..d9adb4f77 100644 --- a/tests/kittest/identity_hub_contact_detail.rs +++ b/tests/kittest/identity_hub_contact_detail.rs @@ -15,8 +15,8 @@ use dash_evo_tool::ui::ScreenLike; use dash_evo_tool::ui::components::MessageBanner; use dash_evo_tool::ui::identity::IdentityHubTab; use dash_evo_tool::ui::identity::contacts::{ - DETAIL_HEADING, DETAILS_SAVED_ON_THIS_DEVICE, NO_SELECTION, NOTE_HEADING, NOTE_SAVED, - SAVE_NOTE_LABEL, SAVING_NOTE_LABEL, + DETAIL_HEADING, DETAILS_SAVED_ON_THIS_DEVICE, NO_SELECTION, NOTE_HEADING, NOTE_HINT, + NOTE_HINT_ON_THIS_DEVICE, NOTE_SAVED, SAVE_NOTE_LABEL, SAVING_NOTE_LABEL, }; use dash_sdk::platform::Identifier; use egui::accesskit::Role; @@ -59,11 +59,31 @@ fn deliver_all(hub: &mut HubHarness, owner: Identifier, contacts: Vec ContactData { + ContactData { + identity_id: Identifier::from([0xC4; 32]), + username: Some("cai".into()), + display_name: Some("Cai Lin".into()), + bio: None, + ..bao(None) + } +} + /// The Contacts tab with Bao listed, then Bao selected. fn hub_with_bao_selected( app_context: &std::sync::Arc, width: f32, note: Option<&'static str>, +) -> (HubHarness, Identifier) { + hub_with_bao_selected_among(app_context, width, vec![bao(note)]) +} + +/// The Contacts tab with `contacts` listed, then Bao selected. +fn hub_with_bao_selected_among( + app_context: &std::sync::Arc, + width: f32, + contacts: Vec, ) -> (HubHarness, Identifier) { let owner = seed_identity_with_usernames(app_context); let mut hub = hub_for( @@ -71,7 +91,7 @@ fn hub_with_bao_selected( owner, width, IdentityHubTab::Contacts, - move |hub, owner| deliver(hub, owner, bao(note)), + move |hub, owner| deliver_all(hub, owner, contacts), ); hub.get_by_role_and_label(Role::Button, "Bao Nguyen") .click(); @@ -240,7 +260,9 @@ fn selecting_a_contact_shows_its_details_beside_the_list() { fn save_note_shows_the_fee_first_and_sends_the_note_once() { with_isolated_data_dir(|| { let (_runtime, app_context) = fresh_app_context(); - let (mut hub, owner) = hub_with_bao_selected(&app_context, WIDE, None); + let (mut hub, owner) = + hub_with_bao_selected_among(&app_context, WIDE, vec![bao(None), cai()]); + assert!(hub.query_by_label(NOTE_HINT).is_some()); assert!( hub.query_by_label_contains("Estimated fee for saving this note: up to") @@ -304,6 +326,23 @@ fn save_note_shows_the_fee_first_and_sends_the_note_once() { }); } +/// With one contact the note is kept on this device: no fee is shown, and +/// the hint does not claim it is stored on Dash Platform. +#[test] +fn a_note_with_one_contact_shows_no_fee() { + with_isolated_data_dir(|| { + let (_runtime, app_context) = fresh_app_context(); + let (hub, _owner) = hub_with_bao_selected(&app_context, WIDE, None); + assert!( + hub.query_by_label_contains("Estimated fee for saving this note") + .is_none(), + "a device-only save costs nothing" + ); + assert!(hub.query_by_label(NOTE_HINT_ON_THIS_DEVICE).is_some()); + assert!(hub.query_by_label(NOTE_HINT).is_none()); + }); +} + /// DIP-0015 holds contact details back until the identity has two contacts; /// the user is told the note is kept on this device instead of "saved". #[test]