Skip to content

Commit fa80a0b

Browse files
authored
chore: add more logs to core enclave (#318)
1 parent b395f3d commit fa80a0b

File tree

6 files changed

+95
-19
lines changed

6 files changed

+95
-19
lines changed

crates/enclave/core/src/attestor.rs

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use std::{
44
io::{Error as IoError, ErrorKind, Write},
55
};
66

7+
use log::{debug, error, trace};
78
use mc_sgx_dcap_sys_types::sgx_ql_qve_collateral_t;
89
use quartz_contract_core::{
910
msg::{
@@ -58,6 +59,7 @@ impl Attestor for DcapAttestor {
5859
type RawAttestation = RawDcapAttestation;
5960

6061
fn quote(&self, user_data: impl HasUserData) -> Result<Vec<u8>, Self::Error> {
62+
debug!("Generating DCAP quote");
6163
let user_data = user_data.user_data();
6264
let mut user_report_data = File::create("/dev/attestation/user_report_data")?;
6365
user_report_data.write_all(user_data.as_slice())?;
@@ -66,16 +68,20 @@ impl Attestor for DcapAttestor {
6668
}
6769

6870
fn mr_enclave(&self) -> Result<MrEnclave, Self::Error> {
71+
debug!("Retrieving MRENCLAVE");
6972
let quote = self.quote(NullUserData)?;
7073
Ok(quote[112..(112 + 32)]
7174
.try_into()
7275
.expect("hardcoded array size"))
7376
}
7477

7578
fn attestation(&self, user_data: impl HasUserData) -> Result<Self::Attestation, Self::Error> {
79+
debug!("Generating DCAP attestation");
80+
7681
fn pccs_query_pck(pccs_url: Url) -> Result<(Vec<u8>, String), Box<dyn Error>> {
7782
let mut pccs_url = pccs_url.join("pckcrl/").expect("hardcoded URL");
7883
pccs_url.set_query(Some("ca=processor"));
84+
trace!("Querying PCCS for PCK certificate: {pccs_url}");
7985

8086
let client = Client::builder()
8187
.danger_accept_invalid_certs(true) // FIXME(hu55a1n1): required?
@@ -144,15 +150,20 @@ impl Attestor for DcapAttestor {
144150
let quote = self.quote(user_data)?;
145151

146152
let collateral = {
147-
let (pck_crl, pck_crl_issuer_chain) = pccs_query_pck(self.pccs_url.clone())
148-
.map_err(|e| IoError::new(ErrorKind::Other, e.to_string()))?;
153+
let (pck_crl, pck_crl_issuer_chain) =
154+
pccs_query_pck(self.pccs_url.clone()).map_err(|e| {
155+
error!("Failed to query PCCS: {}", e);
156+
IoError::new(ErrorKind::Other, e.to_string())
157+
})?;
149158
collateral(&self.fmspc.to_string(), pck_crl, pck_crl_issuer_chain)
150159
};
151160

161+
debug!("Successfully generated DCAP attestation");
152162
Ok(DcapAttestation::new(
153-
quote
154-
.try_into()
155-
.map_err(|e: Quote3Error| IoError::other(e.to_string()))?,
163+
quote.try_into().map_err(|e: Quote3Error| {
164+
error!("Failed to convert quote: {}", e);
165+
IoError::other(e.to_string())
166+
})?,
156167
collateral,
157168
))
158169
}
@@ -169,15 +180,18 @@ impl Attestor for MockAttestor {
169180
type RawAttestation = RawMockAttestation;
170181

171182
fn quote(&self, user_data: impl HasUserData) -> Result<Vec<u8>, Self::Error> {
183+
debug!("Generating mock quote");
172184
let user_data = user_data.user_data();
173185
Ok(user_data.to_vec())
174186
}
175187

176188
fn mr_enclave(&self) -> Result<MrEnclave, Self::Error> {
189+
debug!("Retrieving mock MRENCLAVE");
177190
Ok(Default::default())
178191
}
179192

180193
fn attestation(&self, user_data: impl HasUserData) -> Result<Self::Attestation, Self::Error> {
194+
debug!("Generating mock attestation");
181195
Ok(MockAttestation(user_data.user_data()))
182196
}
183197
}

crates/enclave/core/src/chain_client/default.rs

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use anyhow::anyhow;
22
use cosmrs::{crypto::secp256k1::SigningKey, AccountId};
33
use cw_client::{CwClient, GrpcClient};
44
use futures_util::StreamExt;
5+
use log::{debug, error, info, trace};
56
use quartz_tm_prover::{
67
config::{Config as TmProverConfig, ProofOutput},
78
prover::prove,
@@ -38,6 +39,7 @@ impl DefaultChainClient {
3839
trusted_height: Height,
3940
trusted_hash: Hash,
4041
) -> Self {
42+
info!("Creating new default chain client for chain ID: {chain_id}");
4143
DefaultChainClient {
4244
chain_id,
4345
grpc_client: GrpcClient::new(signer, grpc_url),
@@ -80,9 +82,16 @@ impl ChainClient for DefaultChainClient {
8082
contract: &Self::Contract,
8183
query: impl Into<Self::Query> + Send,
8284
) -> Result<R, Self::Error> {
85+
debug!("Querying contract: {contract}");
8386
match query.into() {
84-
Query::Json(q) => self.grpc_client.query_smart(contract, q).await,
85-
Query::String(q) => self.grpc_client.query_raw(contract, q).await,
87+
Query::Json(q) => {
88+
trace!("Executing JSON query");
89+
self.grpc_client.query_smart(contract, q).await
90+
}
91+
Query::String(q) => {
92+
trace!("Executing raw query");
93+
self.grpc_client.query_raw(contract, q).await
94+
}
8695
}
8796
}
8897

@@ -91,6 +100,8 @@ impl ChainClient for DefaultChainClient {
91100
contract: &Self::Contract,
92101
storage_key: &str,
93102
) -> Result<Self::Proof, Self::Error> {
103+
debug!("Generating existence proof for contract {contract} with storage key {storage_key}");
104+
94105
let prover_config = TmProverConfig {
95106
primary: self.node_url.as_str().parse()?,
96107
witnesses: self.node_url.as_str().parse()?,
@@ -104,12 +115,14 @@ impl ChainClient for DefaultChainClient {
104115
};
105116

106117
let proof_output = tokio::task::spawn_blocking(move || {
118+
trace!("Spawning blocking task for proof generation");
107119
// Create a new runtime inside the blocking thread.
108120
let rt = tokio::runtime::Runtime::new()?;
109121
rt.block_on(async {
110-
prove(prover_config)
111-
.await
112-
.map_err(|report| anyhow!("Tendermint prover failed. Report: {}", report))
122+
prove(prover_config).await.map_err(|report| {
123+
error!("Tendermint prover failed: {}", report);
124+
anyhow!("Tendermint prover failed. Report: {}", report)
125+
})
113126
})
114127
})
115128
.await??; // Handle both JoinError and your custom error
@@ -122,6 +135,10 @@ impl ChainClient for DefaultChainClient {
122135
tx: T,
123136
config: Self::TxConfig,
124137
) -> Result<Self::TxOutput, Self::Error> {
138+
debug!(
139+
"Sending transaction to contract {contract} with gas {}",
140+
config.gas
141+
);
125142
self.grpc_client
126143
.tx_execute(
127144
contract,
@@ -134,7 +151,8 @@ impl ChainClient for DefaultChainClient {
134151
.await
135152
}
136153

137-
async fn wait_for_blocks(&self, _blocks: u8) -> Result<(), Self::Error> {
154+
async fn wait_for_blocks(&self, blocks: u8) -> Result<(), Self::Error> {
155+
debug!("Waiting for {} blocks", blocks);
138156
let (client, driver) = WebSocketClient::new(self.ws_url.to_string().as_str()).await?;
139157

140158
let driver_handle = tokio::spawn(async move { driver.run().await });
@@ -148,6 +166,7 @@ impl ChainClient for DefaultChainClient {
148166
while let Some(res) = subs.next().await {
149167
let _ev = res?;
150168
ev_count -= 1;
169+
trace!("Received new block event, {} remaining", ev_count);
151170
if ev_count == 0 {
152171
break;
153172
}

crates/enclave/core/src/handler.rs

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use cosmrs::AccountId;
22
use k256::ecdsa::VerifyingKey;
3+
use log::{debug, error};
34
use quartz_proto::quartz::{
45
InstantiateRequest, InstantiateResponse, SessionCreateRequest, SessionCreateResponse,
56
SessionSetPubKeyRequest, SessionSetPubKeyResponse,
@@ -69,16 +70,21 @@ where
6970
async fn handle(self, ctx: &E) -> Result<Self::Response, Self::Error> {
7071
match self {
7172
CoreEnclaveRequest::Instantiate(req) => {
73+
debug!("Handling instantiate request");
7274
req.handle(ctx).await.map(CoreEnclaveResponse::Instantiate)
7375
}
74-
CoreEnclaveRequest::SessionCreate(req) => req
75-
.handle(ctx)
76-
.await
77-
.map(CoreEnclaveResponse::SessionCreate),
78-
CoreEnclaveRequest::SessionSetPubKey(req) => req
79-
.handle(ctx)
80-
.await
81-
.map(CoreEnclaveResponse::SessionSetPubKey),
76+
CoreEnclaveRequest::SessionCreate(req) => {
77+
debug!("Handling session create request");
78+
req.handle(ctx)
79+
.await
80+
.map(CoreEnclaveResponse::SessionCreate)
81+
}
82+
CoreEnclaveRequest::SessionSetPubKey(req) => {
83+
debug!("Handling session set pubkey request");
84+
req.handle(ctx)
85+
.await
86+
.map(CoreEnclaveResponse::SessionSetPubKey)
87+
}
8288
}
8389
}
8490
}
@@ -88,17 +94,31 @@ pub fn ensure_seq_num_consistency(
8894
seq_num_on_chain: u64,
8995
pending_sequenced_requests: usize,
9096
) -> Result<(), Status> {
97+
debug!(
98+
"Checking sequence number consistency - store: {}, chain: {}, pending: {}",
99+
seq_num_in_store, seq_num_on_chain, pending_sequenced_requests
100+
);
101+
91102
if seq_num_on_chain < seq_num_in_store {
103+
error!(
104+
"Replay attempt detected - chain seq num ({}) < store seq num ({})",
105+
seq_num_on_chain, seq_num_in_store
106+
);
92107
return Err(Status::failed_precondition("replay attempted"));
93108
}
94109

95110
// make sure number of pending requests are equal to the diff b/w on-chain v/s in-mem seq num
96111
let seq_num_diff = seq_num_on_chain - seq_num_in_store;
97112
if seq_num_diff != pending_sequenced_requests as u64 {
113+
error!(
114+
"Sequence number mismatch - diff: {}, pending: {}",
115+
seq_num_diff, pending_sequenced_requests
116+
);
98117
return Err(Status::failed_precondition(format!(
99118
"seq_num_diff mismatch: num({seq_num_diff}) v/s diff({pending_sequenced_requests})"
100119
)));
101120
}
102121

122+
debug!("Sequence number consistency check passed");
103123
Ok(())
104124
}

crates/enclave/core/src/key_manager/default.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use k256::ecdsa::{SigningKey, VerifyingKey};
2+
use log::{debug, info};
23

34
use crate::key_manager::KeyManager;
45

@@ -10,6 +11,7 @@ pub struct DefaultKeyManager {
1011

1112
impl Default for DefaultKeyManager {
1213
fn default() -> Self {
14+
info!("Creating new default key manager with random signing key");
1315
Self {
1416
sk: SigningKey::random(&mut rand::thread_rng()),
1517
}
@@ -21,6 +23,7 @@ impl KeyManager for DefaultKeyManager {
2123
type PubKey = PubKey;
2224

2325
async fn pub_key(&self) -> Self::PubKey {
26+
debug!("Retrieving public key from key manager");
2427
PubKey(self.sk.clone().into())
2528
}
2629
}

crates/enclave/core/src/lib.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ See the app enclaves in the `examples` directory for usage examples.
8080
)]
8181

8282
use cosmrs::AccountId;
83+
use log::{debug, trace, warn};
8384
use quartz_contract_core::state::Config;
8485

8586
use crate::{
@@ -168,6 +169,7 @@ impl<C: Send + Sync + 'static> DefaultSharedEnclave<C> {
168169
self,
169170
key_manager: K,
170171
) -> DefaultEnclave<C, <Self as Enclave>::Attestor, K, <Self as Enclave>::Store> {
172+
debug!("Updating enclave with new key manager");
171173
DefaultEnclave {
172174
attestor: self.attestor,
173175
key_manager,
@@ -190,14 +192,17 @@ where
190192
type Store = S;
191193

192194
async fn attestor(&self) -> Self::Attestor {
195+
trace!("Retrieving enclave attestor");
193196
self.attestor.clone()
194197
}
195198

196199
async fn key_manager(&self) -> Self::KeyManager {
200+
trace!("Retrieving enclave key manager");
197201
self.key_manager.clone()
198202
}
199203

200204
async fn store(&self) -> &Self::Store {
205+
trace!("Retrieving enclave store");
201206
&self.store
202207
}
203208
}

crates/enclave/core/src/store/default.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use std::sync::Arc;
22

33
use cosmrs::AccountId;
44
use displaydoc::Display;
5+
use log::{debug, info, trace};
56
use quartz_contract_core::state::{Config, Nonce};
67
use tokio::sync::RwLock;
78

@@ -18,6 +19,7 @@ pub struct DefaultStore {
1819

1920
impl DefaultStore {
2021
pub fn new(config: Config) -> Self {
22+
info!("Creating new default store with config: {config:?}");
2123
DefaultStore {
2224
config: Arc::new(RwLock::new(Some(config))),
2325
contract: Default::default(),
@@ -36,40 +38,53 @@ impl Store for DefaultStore {
3638
type Error = StoreError;
3739

3840
async fn get_config(&self) -> Result<Option<Config>, Self::Error> {
41+
debug!("Retrieving enclave configuration");
3942
Ok(self.config.read().await.clone())
4043
}
4144

4245
async fn set_config(&self, config: Config) -> Result<Option<Config>, Self::Error> {
46+
debug!("Setting new enclave configuration");
4347
Ok(self.config.write().await.replace(config))
4448
}
4549

4650
async fn get_contract(&self) -> Result<Option<Self::Contract>, Self::Error> {
51+
debug!("Retrieving enclave contract");
4752
Ok(self.contract.read().await.clone())
4853
}
4954

5055
async fn set_contract(
5156
&self,
5257
contract: Self::Contract,
5358
) -> Result<Option<Self::Contract>, Self::Error> {
59+
debug!("Setting new enclave contract: {contract}");
5460
Ok(self.contract.write().await.replace(contract))
5561
}
5662

5763
async fn get_nonce(&self) -> Result<Option<Nonce>, Self::Error> {
64+
debug!("Retrieving enclave nonce");
5865
Ok(*self.nonce.read().await)
5966
}
6067

6168
async fn set_nonce(&self, nonce: Nonce) -> Result<Option<Nonce>, Self::Error> {
69+
debug!("Setting new enclave nonce: {nonce:?}");
6270
Ok(self.nonce.write().await.replace(nonce))
6371
}
6472

6573
async fn get_seq_num(&self) -> Result<u64, Self::Error> {
74+
debug!("Retrieving sequence number");
6675
Ok(*self.seq_num.read().await)
6776
}
6877

6978
async fn inc_seq_num(&self, count: usize) -> Result<u64, Self::Error> {
79+
debug!("Incrementing sequence number by {count}");
7080
let mut seq_num = self.seq_num.write().await;
7181
let prev_seq_num = *seq_num;
7282
*seq_num += count as u64;
83+
trace!(
84+
"Sequence number incremented from {} to {}",
85+
prev_seq_num,
86+
*seq_num
87+
);
7388
Ok(prev_seq_num)
7489
}
7590
}

0 commit comments

Comments
 (0)