Skip to content

Commit bee78b4

Browse files
Daniils TolmacovsDaniils Tolmacovs
Daniils Tolmacovs
authored and
Daniils Tolmacovs
committed
feat(basic_bitcoin): cache ecdsa
1 parent bf706c7 commit bee78b4

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

rust/basic_bitcoin/src/basic_bitcoin/src/ecdsa_api.rs

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,22 @@ use ic_cdk::api::management_canister::ecdsa::{
22
ecdsa_public_key, sign_with_ecdsa, EcdsaCurve, EcdsaKeyId, EcdsaPublicKeyArgument,
33
SignWithEcdsaArgument,
44
};
5+
use std::cell::RefCell;
6+
use std::collections::HashMap;
7+
8+
// stores the ecdsa to maintain state across different calls to the canister (not across updates)
9+
thread_local! {
10+
/* flexible */ static ECDSA: RefCell<Option<HashMap<Vec<Vec<u8>>/*derivation path*/, Vec<u8> /*public key*/>>> = RefCell::default();
11+
}
512

613
/// Returns the ECDSA public key of this canister at the given derivation path.
714
pub async fn get_ecdsa_public_key(key_name: String, derivation_path: Vec<Vec<u8>>) -> Vec<u8> {
15+
// Retrieve already stored public key
16+
if let Some(key) = ECDSA.with(|ecdsa| {
17+
ecdsa.borrow().as_ref().and_then(|map| map.get(&derivation_path).cloned())
18+
}) {
19+
return key;
20+
}
821
// Retrieve the public key of this canister at the given derivation path
922
// from the ECDSA API.
1023
let canister_id = None;
@@ -15,12 +28,23 @@ pub async fn get_ecdsa_public_key(key_name: String, derivation_path: Vec<Vec<u8>
1528

1629
let res = ecdsa_public_key(EcdsaPublicKeyArgument {
1730
canister_id,
18-
derivation_path,
31+
derivation_path: derivation_path.clone(),
1932
key_id,
2033
})
2134
.await;
2235

23-
res.unwrap().0.public_key
36+
let public_key = res.unwrap().0.public_key;
37+
38+
// Cache the public key
39+
ECDSA.with(|ecdsa| {
40+
let mut map = ecdsa.borrow_mut();
41+
if map.is_none() {
42+
*map = Some(HashMap::new());
43+
}
44+
map.as_mut().unwrap().insert(derivation_path, public_key.clone());
45+
});
46+
47+
public_key
2448
}
2549

2650
pub async fn get_ecdsa_signature(

0 commit comments

Comments
 (0)