Skip to content

Commit

Permalink
chore: update with latest ic packages
Browse files Browse the repository at this point in the history
  • Loading branch information
zensh committed Nov 23, 2024
1 parent e800f3a commit 4ce2c1e
Show file tree
Hide file tree
Showing 13 changed files with 219 additions and 860 deletions.
880 changes: 65 additions & 815 deletions Cargo.lock

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ strip = true
opt-level = 's'

[workspace.package]
version = "0.3.6"
version = "0.4.0"
edition = "2021"
repository = "https://github.com/ldclabs/ic-cose"
keywords = ["config", "cbor", "canister", "icp", "encryption"]
Expand Down Expand Up @@ -37,3 +37,5 @@ icrc-ledger-types = "0.1"
getrandom = { version = "0.2", features = ["custom"] }
coset = "0.3"
aes-gcm = "0.10"
ic-crypto-secp256k1 = { git = "https://github.com/dfinity/ic/", rev = "5d202894864f4db4a5a46f44422aebc80c3d321b" }
ic-crypto-ed25519 = { git = "https://github.com/dfinity/ic/", rev = "5d202894864f4db4a5a46f44422aebc80c3d321b" }
6 changes: 3 additions & 3 deletions src/ic_cose_canister/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ serde = { workspace = true }
serde_bytes = { workspace = true }
ic-cdk-timers = { workspace = true }
ic-stable-structures = { workspace = true }
ic-crypto-secp256k1 = { workspace = true }
ic-crypto-ed25519 = { workspace = true }
getrandom = { version = "0.2", features = ["custom"] }
ic_cose_types = { path = "../ic_cose_types", version = "0.3" }
ic-crypto-extended-bip32 = { git = "https://github.com/dfinity/ic/", rev = "d19fa446ab35780b2c6d8b82ea32d808cca558d5" }
ic-crypto-ed25519 = { git = "https://github.com/dfinity/ic/", rev = "d19fa446ab35780b2c6d8b82ea32d808cca558d5" }
ic_cose_types = { path = "../ic_cose_types", version = "0.4" }
5 changes: 5 additions & 0 deletions src/ic_cose_canister/ic_cose_canister.did
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ type ECDHOutput = record { public_key : blob; payload : blob };
type InitArgs = record {
freezing_threshold : nat64;
ecdsa_key_name : text;
governance_canister : opt principal;
name : text;
schnorr_key_name : text;
allowed_apis : vec text;
Expand Down Expand Up @@ -101,7 +102,10 @@ type StateInfo = record {
managers : vec principal;
name : text;
auditors : vec principal;
schnorr_secp256k1_public_key : opt PublicKeyOutput;
ecdsa_public_key : opt PublicKeyOutput;
schnorr_key_name : text;
schnorr_ed25519_public_key : opt PublicKeyOutput;
allowed_apis : vec text;
subnet_size : nat64;
namespace_total : nat64;
Expand All @@ -127,6 +131,7 @@ type UpdateSettingPayloadInput = record {
};
type UpgradeArgs = record {
freezing_threshold : opt nat64;
governance_canister : opt principal;
name : opt text;
subnet_size : opt nat64;
};
Expand Down
18 changes: 15 additions & 3 deletions src/ic_cose_canister/src/api_cose.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,11 @@ async fn ecdh_cose_encrypted_key(
let spk = store::SettingPathKey::from_path(path, caller);
store::ns::with(&spk.0, |ns| {
if !ns.has_setting_kek_permission(&caller, &spk) {
Err("no permission".to_string())?;
Err(format!(
"ecdh_cose_encrypted_key: {} has no permission for {}",
caller.to_text(),
spk
))?;
}
Ok(())
})?;
Expand Down Expand Up @@ -132,7 +136,11 @@ async fn vetkd_public_key(path: SettingPath) -> Result<ByteBuf, String> {
let spk = store::SettingPathKey::from_path(path, caller);
store::ns::with(&spk.0, |ns| {
if !ns.has_setting_kek_permission(&caller, &spk) {
Err("no permission".to_string())?;
Err(format!(
"vetkd_public_key: {} has no permission for {}",
caller.to_text(),
spk
))?;
}
Ok(())
})?;
Expand All @@ -154,7 +162,11 @@ async fn vetkd_encrypted_key(
let spk = store::SettingPathKey::from_path(path, caller);
store::ns::with(&spk.0, |ns| {
if !ns.has_setting_kek_permission(&caller, &spk) {
Err("no permission".to_string())?;
Err(format!(
"vetkd_encrypted_key: {} has no permission for {}",
caller.to_text(),
spk
))?;
}
Ok(())
})?;
Expand Down
8 changes: 7 additions & 1 deletion src/ic_cose_canister/src/api_init.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use candid::CandidType;
use candid::{CandidType, Principal};
use serde::Deserialize;
use std::{collections::BTreeSet, time::Duration};

Expand All @@ -20,13 +20,15 @@ pub struct InitArgs {
allowed_apis: BTreeSet<String>,
subnet_size: u64, // set to 0 to disable receiving cycles
freezing_threshold: u64, // in cycles
governance_canister: Option<Principal>,
}

#[derive(Clone, Debug, CandidType, Deserialize)]
pub struct UpgradeArgs {
name: Option<String>, // seconds
subnet_size: Option<u64>,
freezing_threshold: Option<u64>, // in cycles
governance_canister: Option<Principal>,
}

#[ic_cdk::init]
Expand All @@ -45,6 +47,7 @@ fn init(args: Option<ChainArgs>) {
} else {
1_000_000_000_000
};
s.governance_canister = args.governance_canister;
});
}
ChainArgs::Upgrade(_) => {
Expand Down Expand Up @@ -80,6 +83,9 @@ fn post_upgrade(args: Option<ChainArgs>) {
if let Some(freezing_threshold) = args.freezing_threshold {
s.freezing_threshold = freezing_threshold;
}
if let Some(governance_canister) = args.governance_canister {
s.governance_canister = Some(governance_canister);
}
});
}
Some(ChainArgs::Init(_)) => {
Expand Down
5 changes: 3 additions & 2 deletions src/ic_cose_canister/src/api_namespace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ use ic_cose_types::{
};
use std::collections::BTreeSet;

use crate::{is_authenticated, store};
use crate::{is_authenticated, is_controller_or_manager, store};

#[ic_cdk::query]
fn state_get_info() -> Result<StateInfo, String> {
store::state::with(|s| {
let mut info = s.to_info();
let with_keys = is_controller_or_manager().is_ok();
let mut info = s.to_info(with_keys);
info.namespace_total = store::ns::namespace_count();
Ok(info)
})
Expand Down
24 changes: 17 additions & 7 deletions src/ic_cose_canister/src/ecdsa.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,31 @@
use ic_cdk::api::management_canister::ecdsa;
use ic_cose_types::{format_error, types::PublicKeyOutput};
use ic_crypto_extended_bip32::{DerivationIndex, DerivationPath, ExtendedBip32DerivationOutput};
use serde_bytes::ByteBuf;

/// Returns a valid extended BIP-32 derivation path from an Account (Principal + subaccount)
pub fn derive_public_key(
ecdsa_public_key: &PublicKeyOutput,
derivation_path: Vec<Vec<u8>>,
) -> Result<PublicKeyOutput, String> {
let ExtendedBip32DerivationOutput {
derived_public_key,
derived_chain_code,
} = DerivationPath::new(derivation_path.into_iter().map(DerivationIndex).collect())
.public_key_derivation(&ecdsa_public_key.public_key, &ecdsa_public_key.chain_code)
let path = ic_crypto_secp256k1::DerivationPath::new(
derivation_path
.into_iter()
.map(ic_crypto_secp256k1::DerivationIndex)
.collect(),
);

let chain_code: [u8; 32] = ecdsa_public_key
.chain_code
.to_vec()
.try_into()
.map_err(format_error)?;
let pk = ic_crypto_secp256k1::PublicKey::deserialize_sec1(&ecdsa_public_key.public_key)
.map_err(format_error)?;
let (derived_public_key, derived_chain_code) =
pk.derive_subkey_with_chain_code(&path, &chain_code);

Ok(PublicKeyOutput {
public_key: ByteBuf::from(derived_public_key),
public_key: ByteBuf::from(derived_public_key.serialize_sec1(true)),
chain_code: ByteBuf::from(derived_chain_code),
})
}
Expand Down
14 changes: 13 additions & 1 deletion src/ic_cose_canister/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,25 @@ use api_init::ChainArgs;

fn is_controller() -> Result<(), String> {
let caller = ic_cdk::caller();
if ic_cdk::api::is_controller(&caller) {
if ic_cdk::api::is_controller(&caller) || store::state::is_controller(&caller) {
Ok(())
} else {
Err("user is not a controller".to_string())
}
}

fn is_controller_or_manager() -> Result<(), String> {
let caller = ic_cdk::caller();
if ic_cdk::api::is_controller(&caller)
|| store::state::is_controller(&caller)
|| store::state::is_manager(&caller)
{
Ok(())
} else {
Err("user is not a controller or manager".to_string())
}
}

fn is_authenticated() -> Result<(), String> {
if ic_cdk::caller() == ANONYMOUS {
Err("anonymous user is not allowed".to_string())
Expand Down
24 changes: 17 additions & 7 deletions src/ic_cose_canister/src/schnorr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use ic_cose_types::{
format_error,
types::{PublicKeyOutput, SchnorrAlgorithm},
};
use ic_crypto_extended_bip32::{DerivationIndex, DerivationPath, ExtendedBip32DerivationOutput};
use serde::{Deserialize, Serialize};
use serde_bytes::ByteBuf;

Expand All @@ -16,14 +15,25 @@ pub fn derive_schnorr_public_key(
) -> Result<PublicKeyOutput, String> {
match alg {
SchnorrAlgorithm::Bip340Secp256k1 => {
let ExtendedBip32DerivationOutput {
derived_public_key,
derived_chain_code,
} = DerivationPath::new(derivation_path.into_iter().map(DerivationIndex).collect())
.public_key_derivation(&public_key.public_key, &public_key.chain_code)
let path = ic_crypto_secp256k1::DerivationPath::new(
derivation_path
.into_iter()
.map(ic_crypto_secp256k1::DerivationIndex)
.collect(),
);

let chain_code: [u8; 32] = public_key
.chain_code
.to_vec()
.try_into()
.map_err(format_error)?;
let pk = ic_crypto_secp256k1::PublicKey::deserialize_sec1(&public_key.public_key)
.map_err(format_error)?;
let (derived_public_key, derived_chain_code) =
pk.derive_subkey_with_chain_code(&path, &chain_code);

Ok(PublicKeyOutput {
public_key: ByteBuf::from(derived_public_key),
public_key: ByteBuf::from(derived_public_key.serialize_sec1(true)),
chain_code: ByteBuf::from(derived_chain_code),
})
}
Expand Down
38 changes: 34 additions & 4 deletions src/ic_cose_canister/src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ use std::{
borrow::Cow,
cell::RefCell,
collections::{btree_map::Entry, BTreeMap, BTreeSet},
fmt, ops,
fmt::{self, Debug},
ops,
};

use crate::{
Expand Down Expand Up @@ -62,10 +63,12 @@ pub struct State {
pub freezing_threshold: u64, // freezing writing threshold in cycles
#[serde(default, rename = "iv")]
pub init_vector: ByteArray<32>, // should not be exposed
#[serde(default, rename = "gov")]
pub governance_canister: Option<Principal>,
}

impl State {
pub fn to_info(&self) -> StateInfo {
pub fn to_info(&self, with_keys: bool) -> StateInfo {
StateInfo {
name: self.name.clone(),
ecdsa_key_name: self.ecdsa_key_name.clone(),
Expand All @@ -77,6 +80,21 @@ impl State {
namespace_total: 0,
subnet_size: self.subnet_size,
freezing_threshold: self.freezing_threshold,
ecdsa_public_key: if with_keys {
self.ecdsa_public_key.clone()
} else {
None
},
schnorr_ed25519_public_key: if with_keys {
self.schnorr_ed25519_public_key.clone()
} else {
None
},
schnorr_secp256k1_public_key: if with_keys {
self.schnorr_secp256k1_public_key.clone()
} else {
None
},
}
}
}
Expand Down Expand Up @@ -402,11 +420,23 @@ pub mod state {
use super::*;

pub fn with<R>(f: impl FnOnce(&State) -> R) -> R {
STATE.with(|r| f(&r.borrow()))
STATE.with_borrow(f)
}

pub fn with_mut<R>(f: impl FnOnce(&mut State) -> R) -> R {
STATE.with(|r| f(&mut r.borrow_mut()))
STATE.with_borrow_mut(f)
}

pub fn is_controller(caller: &Principal) -> bool {
STATE.with_borrow(|s| {
s.governance_canister
.as_ref()
.map_or(false, |p| p == caller)
})
}

pub fn is_manager(caller: &Principal) -> bool {
STATE.with_borrow(|s| s.managers.contains(caller))
}

pub fn allowed_api(api: &str) -> Result<(), String> {
Expand Down
48 changes: 32 additions & 16 deletions src/ic_cose_types/src/cose/k256.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,22 +40,38 @@ pub fn secp256k1_verify_any(
}
}

// wait for [email protected]
// pub fn schnorr_secp256k1_verify_any(
// public_keys: &[schnorr::VerifyingKey],
// message: &[u8],
// signature: &[u8],
// ) -> Result<(), String> {
// let sig = schnorr::Signature::try_from(signature).map_err(format_error)?;
// let digest = sha256(message);
// match public_keys
// .iter()
// .any(|key| key.verify_raw(&digest, &sig).is_ok())
// {
// true => Ok(()),
// false => Err("schnorr secp256k1 signature verification failed".to_string()),
// }
// }
pub fn schnorr_secp256k1_verify(
public_key: &[u8],
message: &[u8],
signature: &[u8],
) -> Result<(), String> {
let key = schnorr::VerifyingKey::from_bytes(if public_key.len() == 33 {
&public_key[1..]
} else {
public_key
})
.map_err(format_error)?;
let sig = schnorr::Signature::try_from(signature).map_err(format_error)?;
match key.verify_raw(message, &sig).is_ok() {
true => Ok(()),
false => Err("schnorr secp256k1 signature verification failed".to_string()),
}
}

pub fn schnorr_secp256k1_verify_any(
public_keys: &[schnorr::VerifyingKey],
message: &[u8],
signature: &[u8],
) -> Result<(), String> {
let sig = schnorr::Signature::try_from(signature).map_err(format_error)?;
match public_keys
.iter()
.any(|key| key.verify_raw(message, &sig).is_ok())
{
true => Ok(()),
false => Err("schnorr secp256k1 signature verification failed".to_string()),
}
}

#[cfg(test)]
mod test {
Expand Down
5 changes: 5 additions & 0 deletions src/ic_cose_types/src/types/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ use candid::{CandidType, Principal};
use serde::{Deserialize, Serialize};
use std::collections::BTreeSet;

use super::PublicKeyOutput;

#[derive(CandidType, Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
pub struct StateInfo {
pub name: String,
Expand All @@ -15,4 +17,7 @@ pub struct StateInfo {
pub namespace_total: u64,
pub subnet_size: u64,
pub freezing_threshold: u64,
pub ecdsa_public_key: Option<PublicKeyOutput>,
pub schnorr_ed25519_public_key: Option<PublicKeyOutput>,
pub schnorr_secp256k1_public_key: Option<PublicKeyOutput>,
}

0 comments on commit 4ce2c1e

Please sign in to comment.