Skip to content

Commit

Permalink
Merge pull request #1024 from dantol29/cache-ecdsa
Browse files Browse the repository at this point in the history
feat(basic_bitcoin): cache ecdsa
  • Loading branch information
altkdf authored Oct 21, 2024
2 parents 6e86fc7 + 0c3031b commit 94b2d62
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions rust/basic_bitcoin/src/basic_bitcoin/src/ecdsa_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,22 @@ use ic_cdk::api::management_canister::ecdsa::{
ecdsa_public_key, sign_with_ecdsa, EcdsaCurve, EcdsaKeyId, EcdsaPublicKeyArgument,
SignWithEcdsaArgument,
};
use std::cell::RefCell;
use std::collections::HashMap;

// stores the ecdsa to maintain state across different calls to the canister (not across updates)
thread_local! {
/* flexible */ static ECDSA: RefCell<Option<HashMap<Vec<Vec<u8>> /*derivation path*/, Vec<u8> /*public key*/>>> = RefCell::default();
}

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

let res = ecdsa_public_key(EcdsaPublicKeyArgument {
canister_id,
derivation_path,
derivation_path: derivation_path.clone(),
key_id,
})
.await;

res.unwrap().0.public_key
let public_key = res.unwrap().0.public_key;

// Cache the public key
ECDSA.with(|ecdsa| {
let mut map = ecdsa.borrow_mut();
if map.is_none() {
*map = Some(HashMap::new());
}
map.as_mut().unwrap().insert(derivation_path, public_key.clone());
});

public_key
}

pub async fn get_ecdsa_signature(
Expand Down

0 comments on commit 94b2d62

Please sign in to comment.