Skip to content

Commit e72d188

Browse files
authored
Both: deleting a wallet removes its Hyperliquid trading key (#1963)
* Deleting a wallet removes its Hyperliquid agent key docs/product/wallet.md says Delete removes everything the wallet owned on the device. GemWalletService now takes the gateway's secure store, and delete_wallet removes the agent key and address of each HyperCore account no other signing wallet holds, before the wallet's secret goes, so a failed removal leaves the wallet whole and Delete can be tried again. Agent::remove_credentials owns the key names and regenerate_credentials uses it. iOS passes the gateway's encrypted store and Android its GemSecureStore binding. * Core: deleting a wallet removes its Hyperliquid agent keys through one helper, and the address rule is named for HyperCore * Core: a wallet is still deleted when its Hyperliquid agent key cannot be removed
1 parent 920aa81 commit e72d188

10 files changed

Lines changed: 119 additions & 9 deletions

File tree

‎android/data/services/gemstone/src/main/kotlin/com/gemwallet/android/data/services/gemstone/di/KeystoreModule.kt‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import uniffi.gemstone.GemNameService
2424
import uniffi.gemstone.GemPaymentService
2525
import uniffi.gemstone.GemPreferencesService
2626
import uniffi.gemstone.GemRecentActivityService
27+
import uniffi.gemstone.GemSecureStore
2728
import uniffi.gemstone.GemSignMessageService
2829
import uniffi.gemstone.GemSwapService
2930
import uniffi.gemstone.GemSwapServiceInterface
@@ -54,6 +55,7 @@ object KeystoreModule {
5455
explorerService: GemExplorerService,
5556
nameService: GemNameService,
5657
avatarService: GemAvatarService,
58+
securePreferences: GemSecureStore,
5759
): GemWalletService = GemWalletService(
5860
keystore,
5961
GemstoneKeystorePassword(passwordStore, deviceAuthentication),
@@ -65,6 +67,7 @@ object KeystoreModule {
6567
explorerService,
6668
nameService,
6769
avatarService,
70+
securePreferences,
6871
)
6972

7073
@Provides

‎core/crates/gem_hypercore/src/agent.rs‎

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,15 +32,16 @@ impl Agent {
3232
}
3333

3434
pub fn regenerate_credentials(&self, sender_address: &str) -> Result<(String, String), Box<dyn Error + Send + Sync>> {
35-
let address_key = self.address_key(sender_address);
36-
let private_key_key = self.private_key_key(sender_address);
37-
38-
self.preferences.remove(address_key)?;
39-
self.preferences.remove(private_key_key)?;
35+
self.remove_credentials(sender_address)?;
4036

4137
self.create_new_credentials(sender_address)
4238
}
4339

40+
pub fn remove_credentials(&self, sender_address: &str) -> Result<(), Box<dyn Error + Send + Sync>> {
41+
self.preferences.remove(self.private_key_key(sender_address))?;
42+
self.preferences.remove(self.address_key(sender_address))
43+
}
44+
4445
fn create_new_credentials(&self, sender_address: &str) -> Result<(String, String), Box<dyn Error + Send + Sync>> {
4546
let agent_private_key = self.generate_private_key()?;
4647
let agent_address = self.derive_address(&agent_private_key)?;
@@ -137,4 +138,19 @@ mod tests {
137138
assert_ne!(addr1, addr2);
138139
assert_ne!(key1, key2);
139140
}
141+
142+
#[test]
143+
fn test_remove_credentials() {
144+
let preferences = Arc::new(InMemoryPreferences::new());
145+
let agent = Agent::new(preferences.clone());
146+
147+
let kept = agent.get_or_create_credentials("kept_wallet").unwrap();
148+
agent.get_or_create_credentials("test_wallet").unwrap();
149+
agent.remove_credentials("test_wallet").unwrap();
150+
agent.remove_credentials("unknown_wallet").unwrap();
151+
152+
assert_eq!(preferences.get("test_wallet_agent_address".to_string()).unwrap(), None);
153+
assert_eq!(preferences.get("test_wallet_agent_key".to_string()).unwrap(), None);
154+
assert_eq!(agent.get_or_create_credentials("kept_wallet").unwrap(), kept);
155+
}
140156
}

‎core/gemstone/src/services/preferences/testkit.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ impl GemPreferencesStore for MemoryPreferencesStore {
3333
#[derive(Default)]
3434
pub struct MemorySecureStore {
3535
pub values: Mutex<HashMap<String, String>>,
36+
pub remove_error: Mutex<Option<GemServiceError>>,
3637
}
3738

3839
impl GemSecureStore for MemorySecureStore {
@@ -46,6 +47,9 @@ impl GemSecureStore for MemorySecureStore {
4647
}
4748

4849
fn remove(&self, key: String) -> Result<(), GemServiceError> {
50+
if let Some(error) = self.remove_error.lock().unwrap().clone() {
51+
return Err(error);
52+
}
4953
self.values.lock().unwrap().remove(&key);
5054
Ok(())
5155
}

‎core/gemstone/src/services/wallet/mod.rs‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,11 @@ pub(crate) mod testkit;
3030

3131
use std::sync::Arc;
3232

33+
use gem_hypercore::agent::Agent;
3334
use gem_keystore::Mnemonic;
3435
use primitives::{Chain, ChainAsset, NFTData, Wallet, WalletId, WalletSource, WalletType};
3536

37+
use crate::gateway::SecureStoreWrapper;
3638
use crate::keystore::decode_password;
3739
use crate::keystore::{GemImportType, GemKeystore, GemWalletImport, keystore_id_for_wallet};
3840
use crate::models::state::GemListPhase;
@@ -45,7 +47,7 @@ use crate::services::localization::GemLocalizedText;
4547
use crate::services::name::GemNameService;
4648
use crate::services::nft::model::GemNftList;
4749
use crate::services::nft::rules as nft_rules;
48-
use crate::services::preferences::GemPreferencesService;
50+
use crate::services::preferences::{GemPreferencesService, GemSecureStore};
4951
use crate::services::wallet_preferences::GemWalletPreferencesService;
5052
use crate::services::wallet_session::GemWalletSessionService;
5153

@@ -75,6 +77,7 @@ pub struct GemWalletService {
7577
explorer: Arc<GemExplorerService>,
7678
names: Arc<GemNameService>,
7779
avatar: Arc<GemAvatarService>,
80+
secure_preferences: Arc<dyn GemSecureStore>,
7881
}
7982

8083
#[uniffi::export]
@@ -91,6 +94,7 @@ impl GemWalletService {
9194
explorer: Arc<GemExplorerService>,
9295
names: Arc<GemNameService>,
9396
avatar: Arc<GemAvatarService>,
97+
secure_preferences: Arc<dyn GemSecureStore>,
9498
) -> Self {
9599
Self {
96100
keystore,
@@ -103,6 +107,7 @@ impl GemWalletService {
103107
explorer,
104108
names,
105109
avatar,
110+
secure_preferences,
106111
}
107112
}
108113

@@ -152,6 +157,7 @@ impl GemWalletService {
152157
pub async fn delete_wallet(&self, wallet_id: WalletId) -> Result<GemWalletDeletion, GemServiceError> {
153158
let wallet = self.wallet(wallet_id.clone()).await?;
154159
if wallet.wallet_type != WalletType::View {
160+
self.remove_hypercore_agents(&wallet).await?;
155161
self.keystore.delete_wallet_secrets(wallet.id.id(), rules::legacy_keystore_id(&wallet))?;
156162
}
157163
self.store.delete_wallet(wallet.id.clone()).await?;
@@ -385,6 +391,14 @@ impl GemWalletService {
385391
self.store_wallet(wallet).await
386392
}
387393

394+
async fn remove_hypercore_agents(&self, wallet: &Wallet) -> Result<(), GemServiceError> {
395+
let agent = Agent::new(Arc::new(SecureStoreWrapper { store: self.secure_preferences.clone() }));
396+
for address in rules::hypercore_agent_addresses(wallet, &self.store.get_wallets().await?) {
397+
let _ = agent.remove_credentials(&address);
398+
}
399+
Ok(())
400+
}
401+
388402
async fn store_wallet(&self, wallet: &Wallet) -> Result<(), GemServiceError> {
389403
self.store.add_wallet(wallet.clone()).await?;
390404
self.names.save_names(rules::wallet_address_names(wallet)).await
@@ -476,6 +490,39 @@ mod tests {
476490
});
477491
}
478492

493+
#[test]
494+
fn test_delete_wallet_removes_its_hyperliquid_agent_key_and_keeps_another_wallets() {
495+
block_on(async {
496+
let context = WalletTestkit::new();
497+
let kept = context.import_chains("Kept", OTHER_PHRASE, vec![Chain::HyperCore]).await;
498+
let deleted = context.import_chains("Deleted", PHRASE, vec![Chain::HyperCore]).await;
499+
let agent = Agent::new(Arc::new(SecureStoreWrapper { store: context.secure_store.clone() }));
500+
agent.get_or_create_credentials(&kept.accounts[0].address).unwrap();
501+
let kept_values = context.secure_store.values.lock().unwrap().clone();
502+
agent.get_or_create_credentials(&deleted.accounts[0].address).unwrap();
503+
504+
context.service.delete_wallet(deleted.id.clone()).await.unwrap();
505+
506+
assert_eq!(*context.secure_store.values.lock().unwrap(), kept_values);
507+
assert_eq!(kept_values.len(), 2);
508+
});
509+
}
510+
511+
#[test]
512+
fn test_delete_wallet_removes_the_wallet_and_its_secret_when_the_agent_key_cannot_be_removed() {
513+
block_on(async {
514+
let context = WalletTestkit::new();
515+
let wallet = context.import_chains("Deleted", PHRASE, vec![Chain::HyperCore]).await;
516+
*context.secure_store.remove_error.lock().unwrap() = Some(GemServiceError::Platform { msg: "locked".to_string() });
517+
518+
let outcome = context.service.delete_wallet(wallet.id.clone()).await.unwrap();
519+
520+
assert_eq!(outcome, GemWalletDeletion::LastWalletDeleted);
521+
assert!(!context.keystore_path(&wallet).exists());
522+
assert_eq!(context.service.wallets().await.unwrap().len(), 0);
523+
});
524+
}
525+
479526
#[test]
480527
fn test_wallet_accounts_are_named_after_the_wallet_until_it_is_deleted() {
481528
block_on(async {

‎core/gemstone/src/services/wallet/rules.rs‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,17 @@ pub fn wallet_address_names(wallet: &Wallet) -> Vec<AddressName> {
371371
.collect()
372372
}
373373

374+
pub fn hypercore_agent_addresses(wallet: &Wallet, wallets: &[Wallet]) -> Vec<String> {
375+
let is_hypercore = |account: &&Account| account.chain.chain_type() == ChainType::HyperCore;
376+
let held: Vec<&String> = wallets
377+
.iter()
378+
.filter(|other| other.id != wallet.id && other.wallet_type != WalletType::View)
379+
.flat_map(|other| other.accounts.iter().filter(is_hypercore))
380+
.map(|account| &account.address)
381+
.collect();
382+
wallet.accounts.iter().filter(is_hypercore).map(|account| &account.address).filter(|address| !held.contains(address)).cloned().collect()
383+
}
384+
374385
pub fn next_current_wallet(wallets: &[Wallet]) -> Option<WalletId> {
375386
wallets.iter().min_by_key(|wallet| wallet_order(&wallet.id, wallet.index)).map(|wallet| wallet.id.clone())
376387
}
@@ -733,6 +744,20 @@ mod tests {
733744
assert_eq!(next_current_wallet(&[]), None);
734745
}
735746

747+
#[test]
748+
fn test_hypercore_agent_addresses_are_the_ones_no_other_signing_wallet_holds() {
749+
let chains = [Chain::Ethereum, Chain::HyperCore];
750+
let wallet = Wallet::mock_with_id(WalletId::Multicoin("0x1".to_string()), &chains);
751+
let key_wallet = Wallet::mock_with_id(WalletId::PrivateKey(Chain::HyperCore, "0x1".to_string()), &chains);
752+
let view = Wallet::mock_with_id(WalletId::View(Chain::HyperCore, "0x1".to_string()), &chains);
753+
let mut other = Wallet::mock_with_id(WalletId::Multicoin("0x2".to_string()), &chains);
754+
other.accounts = Account::mock_chains(&chains, "other");
755+
756+
assert_eq!(hypercore_agent_addresses(&wallet, &[wallet.clone(), view, other]), vec!["address"]);
757+
assert_eq!(hypercore_agent_addresses(&wallet, &[wallet.clone(), key_wallet]), Vec::<String>::new());
758+
assert_eq!(hypercore_agent_addresses(&Wallet::mock_with_chains(&[Chain::Ethereum]), &[]), Vec::<String>::new());
759+
}
760+
736761
#[test]
737762
fn test_show_collections_follows_the_first_account_chain_outside_multicoin() {
738763
assert!(show_collections(WalletType::Multicoin, &[Chain::Bitcoin]));

‎core/gemstone/src/services/wallet/testkit.rs‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ use crate::services::avatar::GemAvatarService;
2222
use crate::services::explorer::GemExplorerService;
2323
use crate::services::file::testkit::NoopFileStore;
2424
use crate::services::preferences::GemPreferencesService;
25-
use crate::services::preferences::testkit::MemoryPreferencesStore;
25+
use crate::services::preferences::testkit::{MemoryPreferencesStore, MemorySecureStore};
2626
use crate::services::wallet_preferences::GemWalletPreferencesService;
2727
use crate::services::wallet_preferences::testkit::MemoryWalletPreferencesStore;
2828
use crate::services::wallet_session::GemWalletSessionService;
@@ -155,6 +155,7 @@ pub struct WalletTestkit {
155155
pub wallets: Arc<MemoryWalletStore>,
156156
pub passwords: Arc<MemoryKeystorePassword>,
157157
pub keystore: Arc<GemKeystore>,
158+
pub secure_store: Arc<MemorySecureStore>,
158159
pub directory: TempDir,
159160
}
160161

@@ -165,6 +166,7 @@ impl WalletTestkit {
165166
let passwords = Arc::new(MemoryKeystorePassword::default());
166167
let addresses = Arc::new(MemoryAddressStore::default());
167168
let preferences = Arc::new(MemoryPreferencesStore::default());
169+
let secure_store = Arc::new(MemorySecureStore::default());
168170
let keystore = GemKeystore::new(directory.path().to_string_lossy().to_string()).unwrap();
169171
let session = Arc::new(GemWalletSessionService::mock(wallets.clone(), None));
170172
let app_preferences = Arc::new(GemPreferencesService::new(preferences));
@@ -183,20 +185,26 @@ impl WalletTestkit {
183185
Arc::new(GemExplorerService::new(app_preferences)),
184186
names,
185187
Arc::new(GemAvatarService::mock(wallets.clone(), Arc::new(NoopFileStore))),
188+
secure_store.clone(),
186189
));
187190
Self {
188191
service,
189192
wallets,
190193
passwords,
191194
keystore,
195+
secure_store,
192196
directory,
193197
}
194198
}
195199

196200
pub async fn import(&self, name: &str, words: [&str; 12]) -> Wallet {
201+
self.import_chains(name, words, vec![Chain::Ethereum]).await
202+
}
203+
204+
pub async fn import_chains(&self, name: &str, words: [&str; 12], chains: Vec<Chain>) -> Wallet {
197205
let import = GemWalletImportType::MulticoinPhrase {
198206
words: words.iter().map(ToString::to_string).collect(),
199-
chains: vec![Chain::Ethereum],
207+
chains,
200208
};
201209
self.service.store_import(name.to_string(), import, WalletSource::Import).await.unwrap().wallet()
202210
}

‎docs/product/wallet.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,8 @@ flowchart LR
9999
| A wallet imported from a private key shows its key | the security reminders and the warning above the key name the private key, never the Secret Phrase | the phrase wording on a key screen misled users (#1394) |
100100
| A wallet is deleted | the app switches to the next wallet: Multi-Coin first, then the oldest | |
101101
| The last wallet is deleted | the app returns to onboarding | |
102+
| A wallet that trades perpetuals is deleted | the Hyperliquid key that signed its orders leaves the device with it, unless another wallet on the device has the same address | the key keeps trading the account until its approval expires |
103+
| The Hyperliquid key of a deleted wallet cannot be removed | the wallet and its Secret Phrase or private key are still deleted | the secret leaving the device matters more than a trading key whose approval expires |
102104
| A network is retired | it is no longer offered anywhere; Multi-Coin wallets lose its account and everything stored for it; watch-only wallets on it are removed; a single-network or private key wallet on it stays with its address, so its Secret Phrase or private key can still be shown | the network no longer works, but deleting a wallet that holds a key could lose that key for good |
103105

104106
Showing and copying a Secret Phrase or private key follow the shared [Secrets](../PRODUCT.md#secrets) section.

‎ios/Gem/Services/ServicesFactory.swift‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,12 @@ struct ServicesFactory {
6262
let gemstoneAddressStore = GemstoneAddressStore(store: stores.addressStore)
6363
let gemstoneBannerStore = GemstoneBannerStore(store: stores.bannerStore)
6464
let gemstoneNotificationStore = GemstoneNotificationStore(store: stores.inAppNotificationStore)
65+
let gatewaySecurePreferences = GemstoneEncryptedPreferencesStore(namespace: "gateway")
6566
let gatewayService = GatewayService(
6667
provider: nativeProvider,
6768
nodes: nodeService,
6869
preferences: GemstonePreferencesStore(namespace: "gateway"),
69-
securePreferences: GemstoneEncryptedPreferencesStore(namespace: "gateway"),
70+
securePreferences: gatewaySecurePreferences,
7071
)
7172
let nameService = Gemstone.GemNameService(api: deviceApiClient, store: gemstoneAddressStore)
7273
let assetsService = gatewayService.assetsService(api: apiClient, store: gemstoneAssetStore, price: priceService, preferences: preferencesService)
@@ -98,6 +99,7 @@ struct ServicesFactory {
9899
explorer: explorerService,
99100
names: nameService,
100101
avatar: avatarService,
102+
securePreferences: gatewaySecurePreferences,
101103
)
102104
let pushNotificationEnablerService = PushNotificationEnablerService(preferencesService: preferencesService, systemPrompt: storages.systemPrompt)
103105
let notificationPermissions = GemstoneNotificationPermissions(service: pushNotificationEnablerService)

‎ios/Packages/GemstoneServices/Sources/Keystore/LocalKeystore+Services.swift‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ public extension LocalKeystore {
1313
explorer: GemExplorerService,
1414
names: GemNameService,
1515
avatar: GemAvatarService,
16+
securePreferences: any GemSecureStore,
1617
) -> GemWalletService {
1718
GemWalletService(
1819
keystore: gemKeystore,
@@ -25,6 +26,7 @@ public extension LocalKeystore {
2526
explorer: explorer,
2627
names: names,
2728
avatar: avatar,
29+
securePreferences: securePreferences,
2830
)
2931
}
3032

‎ios/Packages/GemstoneServices/TestKit/GemWalletService+TestKit.swift‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ public extension GemWalletService {
3838
explorer: GemExplorerService(preferences: appPreferences),
3939
names: .mock(),
4040
avatar: GemAvatarService(wallets: gemWalletStore, files: GemstoneFileStore(), provider: NativeProvider()),
41+
securePreferences: GemSecureStoreMock(),
4142
)
4243
}
4344
}

0 commit comments

Comments
 (0)