Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(basic_bitcoin): cache ecdsa #1024

Merged
merged 1 commit into from
Oct 21, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading