Skip to content

Commit 18bbfc9

Browse files
35359595Brechtpdjohntaiko
authored
chore(raiko-lib): auto logging (#219)
* chore(install): source env if sp1 bin not in path * chore: actual new line instead of `\n` symbols * chore(log): tracing logs instead println; levels; * chore: debug assertinos print inline * chore: removed unnecesary re-init; prints in db; * chore: warnings and cfg fixes * console only progress tracking * fix * feat: disable inplace print in container env * fix; merge conflict fixes * chore: cleaned up repeated output for info/debug --------- Co-authored-by: brechtpd <[email protected]> Co-authored-by: john xu <[email protected]>
1 parent 93c8f61 commit 18bbfc9

File tree

19 files changed

+93
-72
lines changed

19 files changed

+93
-72
lines changed

Cargo.lock

+1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

core/src/interfaces.rs

+5-7
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
use std::{collections::HashMap, path::Path, str::FromStr};
2-
1+
use crate::{merge, prover::NativeProver};
32
use alloy_primitives::{Address, B256};
43
use clap::{Args, ValueEnum};
54
use raiko_lib::{
@@ -9,10 +8,9 @@ use raiko_lib::{
98
use serde::{Deserialize, Serialize};
109
use serde_json::Value;
1110
use serde_with::{serde_as, DisplayFromStr};
11+
use std::{collections::HashMap, path::Path, str::FromStr};
1212
use utoipa::ToSchema;
1313

14-
use crate::{merge, prover::NativeProver};
15-
1614
#[derive(Debug, thiserror::Error, ToSchema)]
1715
pub enum RaikoError {
1816
/// For invalid proof type generation request.
@@ -139,23 +137,23 @@ impl ProofType {
139137
return sp1_driver::Sp1Prover::run(input, output, config)
140138
.await
141139
.map_err(|e| e.into());
142-
140+
#[cfg(not(feature = "sp1"))]
143141
Err(RaikoError::FeatureNotSupportedError(self.clone()))
144142
}
145143
ProofType::Risc0 => {
146144
#[cfg(feature = "risc0")]
147145
return risc0_driver::Risc0Prover::run(input, output, config)
148146
.await
149147
.map_err(|e| e.into());
150-
148+
#[cfg(not(feature = "risc0"))]
151149
Err(RaikoError::FeatureNotSupportedError(self.clone()))
152150
}
153151
ProofType::Sgx => {
154152
#[cfg(feature = "sgx")]
155153
return sgx_prover::SgxProver::run(input, output, config)
156154
.await
157155
.map_err(|e| e.into());
158-
156+
#[cfg(not(feature = "sgx"))]
159157
Err(RaikoError::FeatureNotSupportedError(self.clone()))
160158
}
161159
}

core/src/lib.rs

+3-4
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
use std::collections::HashMap;
2-
31
use alloy_primitives::{Address, FixedBytes};
42
use alloy_rpc_types::EIP1186AccountProofResponse;
53
use raiko_lib::{
@@ -11,7 +9,8 @@ use raiko_lib::{
119
utils::HeaderHasher,
1210
};
1311
use serde_json::Value;
14-
use tracing::{error, info, warn};
12+
use std::collections::HashMap;
13+
use tracing::{debug, error, info, warn};
1514

1615
pub mod interfaces;
1716
pub mod preflight;
@@ -68,7 +67,7 @@ impl Raiko {
6867
Ok((header, _mpt_node)) => {
6968
info!("Verifying final state using provider data ...");
7069
info!("Final block hash derived successfully. {}", header.hash());
71-
info!("Final block header derived successfully. {header:?}");
70+
debug!("Final block header derived successfully. {header:?}");
7271
let pi = ProtocolInstance::new(input, &header, VerifierType::None)?.instance_hash();
7372

7473
// Check against the expected value of all fields for easy debugability

core/src/preflight.rs

+24-15
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
use crate::{
2+
interfaces::{RaikoError, RaikoResult},
3+
provider::{db::ProviderDb, rpc::RpcBlockDataProvider, BlockDataProvider},
4+
};
15
use alloy_consensus::{
26
SignableTransaction, TxEip1559, TxEip2930, TxEip4844, TxEip4844Variant, TxEnvelope, TxLegacy,
37
};
@@ -11,7 +15,9 @@ use raiko_lib::{
1115
builder::{
1216
prepare::TaikoHeaderPrepStrategy, BlockBuilder, OptimisticDatabase, TkoTxExecStrategy,
1317
},
18+
clear_line,
1419
consts::ChainSpec,
20+
inplace_print,
1521
input::{
1622
decode_anchor, proposeBlockCall, BlockProposed, GuestInput, TaikoGuestInput,
1723
TaikoProverData,
@@ -25,12 +31,7 @@ use raiko_lib::{
2531
};
2632
use serde::{Deserialize, Serialize};
2733
use std::{collections::HashSet, sync::Arc};
28-
use tracing::{info, warn};
29-
30-
use crate::{
31-
interfaces::{RaikoError, RaikoResult},
32-
provider::{db::ProviderDb, rpc::RpcBlockDataProvider, BlockDataProvider},
33-
};
34+
use tracing::{debug, info, warn};
3435

3536
pub async fn preflight<BDP: BlockDataProvider>(
3637
provider: BDP,
@@ -58,10 +59,13 @@ pub async fn preflight<BDP: BlockDataProvider>(
5859
RaikoError::Preflight("No block hash for the requested block".to_string())
5960
})?;
6061

61-
info!("\nblock.hash: {hash:?}");
62-
info!("block.parent_hash: {:?}", block.header.parent_hash);
63-
info!("block gas used: {:?}", block.header.gas_used);
64-
info!("block transactions: {:?}", block.transactions.len());
62+
info!(
63+
"Processing block {:?} with block.hash: {:?}",
64+
block.header.number, block.header.hash
65+
);
66+
debug!("block.parent_hash: {:?}", block.header.parent_hash);
67+
debug!("block gas used: {:?}", block.header.gas_used);
68+
debug!("block transactions: {:?}", block.transactions.len());
6569

6670
let taiko_guest_input = if taiko_chain_spec.is_taiko() {
6771
prepare_taiko_chain_input(
@@ -162,14 +166,17 @@ pub async fn preflight<BDP: BlockDataProvider>(
162166
let mut done = false;
163167
let mut num_iterations = 0;
164168
while !done {
165-
info!("Execution iteration {num_iterations}...");
169+
inplace_print(&format!("Execution iteration {num_iterations}..."));
166170
builder.mut_db().unwrap().optimistic = num_iterations + 1 < max_iterations;
167171
builder = builder.execute_transactions::<TkoTxExecStrategy>()?;
168172
if builder.mut_db().unwrap().fetch_data().await {
169173
done = true;
170174
}
171175
num_iterations += 1;
172176
}
177+
clear_line();
178+
println!("State data fetched in {num_iterations} iterations");
179+
173180
let provider_db = builder.mut_db().unwrap();
174181

175182
// Gather inclusion proofs for the initial and final state
@@ -233,8 +240,10 @@ async fn prepare_taiko_chain_input(
233240
let l1_state_block_number = anchor_call.l1BlockId;
234241
let l1_inclusion_block_number = l1_state_block_number + 1;
235242

236-
info!("anchor L1 block id: {:?}", anchor_call.l1BlockId);
237-
info!("anchor L1 state root: {:?}", anchor_call.l1StateRoot);
243+
debug!(
244+
"anchor L1 block id: {:?}\nanchor L1 state root: {:?}",
245+
anchor_call.l1BlockId, anchor_call.l1StateRoot
246+
);
238247

239248
// Get the L1 block in which the L2 block was included so we can fetch the DA data.
240249
// Also get the L1 state block header so that we can prove the L1 state root.
@@ -250,7 +259,7 @@ async fn prepare_taiko_chain_input(
250259
RaikoError::Preflight("No L1 state block hash for the requested block".to_owned())
251260
})?;
252261

253-
info!("l1_state_root_block hash: {l1_state_block_hash:?}");
262+
debug!("l1_state_root_block hash: {l1_state_block_hash:?}");
254263

255264
let l1_inclusion_block_hash = l1_inclusion_block.header.hash.ok_or_else(|| {
256265
RaikoError::Preflight("No L1 inclusion block hash for the requested block".to_owned())
@@ -267,7 +276,7 @@ async fn prepare_taiko_chain_input(
267276

268277
// Fetch the tx data from either calldata or blobdata
269278
let (tx_data, tx_blob_hash) = if proposal_event.meta.blobUsed {
270-
info!("blob active");
279+
debug!("blob active");
271280
// Get the blob hashes attached to the propose tx
272281
let blob_hashes = proposal_tx.blob_versioned_hashes.unwrap_or_default();
273282
assert!(!blob_hashes.is_empty());

core/src/provider/rpc.rs

+10-6
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
use std::collections::HashMap;
2-
31
use alloy_primitives::{Address, Bytes, StorageKey, Uint, U256};
42
use alloy_provider::{ProviderBuilder, ReqwestProvider, RootProvider};
53
use alloy_rpc_client::{ClientBuilder, RpcClient};
64
use alloy_rpc_types::{Block, BlockId, BlockNumberOrTag, EIP1186AccountProofResponse};
75
use alloy_transport_http::Http;
8-
use raiko_lib::{clear_line, inplace_print};
6+
use raiko_lib::clear_line;
97
use reqwest_alloy::Client;
108
use revm::primitives::{AccountInfo, Bytecode};
9+
use std::collections::HashMap;
10+
use tracing::trace;
1111

1212
use crate::{
1313
interfaces::{RaikoError, RaikoResult},
@@ -229,9 +229,13 @@ impl BlockDataProvider for RpcBlockDataProvider {
229229

230230
let batch_limit = 1000;
231231
while !accounts.is_empty() {
232-
inplace_print(&format!(
233-
"fetching storage proof {idx}/{num_storage_proofs}..."
234-
));
232+
if cfg!(debug_assertions) {
233+
raiko_lib::inplace_print(&format!(
234+
"fetching storage proof {idx}/{num_storage_proofs}..."
235+
));
236+
} else {
237+
trace!("Fetching storage proof {idx}/{num_storage_proofs}...");
238+
}
235239

236240
// Create a batch for all storage proofs
237241
let mut batch = self.client.new_batch();

docker/entrypoint.sh

+2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
set -xeo pipefail
44

5+
export IN_CONTAINER=1
6+
57
GRAMINE_PRIV_KEY="$HOME/.config/gramine/enclave-key.pem"
68
RAIKO_DOCKER_VOLUME_PATH="/root/.config/raiko"
79
RAIKO_DOCKER_VOLUME_CONFIG_PATH="$RAIKO_DOCKER_VOLUME_PATH/config"

host/src/bin/main.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
#![allow(incomplete_features)]
2-
use std::path::PathBuf;
3-
42
use raiko_host::{interfaces::HostResult, server::serve, ProverState};
5-
use tracing::info;
3+
use std::path::PathBuf;
4+
use tracing::{debug, info};
65
use tracing_appender::{
76
non_blocking::WorkerGuard,
87
rolling::{Builder, Rotation},
@@ -18,6 +17,8 @@ async fn main() -> HostResult<()> {
1817
&state.opts.log_level,
1918
state.opts.max_log,
2019
);
20+
debug!("Start config:\n{:#?}", state.opts.proof_request_opt);
21+
debug!("Args:\n{:#?}", state.opts);
2122

2223
info!("Supported chains: {:?}", state.chain_specs);
2324
info!("Start config:\n{:#?}", state.opts.proof_request_opt);

host/src/lib.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ impl ProverState {
151151
}
152152

153153
mod memory {
154-
use tracing::info;
154+
use tracing::debug;
155155

156156
use crate::ALLOCATOR;
157157

@@ -165,7 +165,7 @@ mod memory {
165165

166166
pub(crate) fn print_stats(title: &str) {
167167
let max_memory = get_max_allocated();
168-
info!(
168+
debug!(
169169
"{title}{}.{:06} MB",
170170
max_memory / 1_000_000,
171171
max_memory % 1_000_000

host/src/server/mod.rs

+4-6
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
1-
use std::{net::SocketAddr, str::FromStr};
2-
1+
use crate::{interfaces::HostError, server::api::create_router, ProverState};
32
use anyhow::Context;
3+
use std::{net::SocketAddr, str::FromStr};
44
use tokio::net::TcpListener;
5-
use tracing::debug;
6-
7-
use crate::{interfaces::HostError, server::api::create_router, ProverState};
5+
use tracing::info;
86

97
pub mod api;
108

@@ -14,7 +12,7 @@ pub async fn serve(state: ProverState) -> anyhow::Result<()> {
1412
.map_err(|_| HostError::InvalidAddress(state.opts.address.clone()))?;
1513
let listener = TcpListener::bind(addr).await?;
1614

17-
debug!("Listening on: {}", listener.local_addr()?);
15+
info!("Listening on: {}", listener.local_addr()?);
1816

1917
let router = create_router(
2018
state.opts.concurrency_limit,

lib/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ sha2 = { workspace = true }
3636
sha3 = { workspace = true }
3737
rlp = { workspace = true, features = ["std"] }
3838
cfg-if = { workspace = true }
39+
tracing = { workspace = true }
3940

4041
# [target.'cfg(feature = "std")'.dependencies]
4142
flate2 = { workspace = true, optional = true }

lib/src/builder/execute.rs

+15-14
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,10 @@
1212
// See the License for the specific language governing permissions and
1313
// limitations under the License.
1414

15-
use core::{fmt::Debug, mem::take, str::from_utf8};
16-
use std::collections::HashSet;
17-
1815
use alloy_consensus::{constants::BEACON_ROOTS_ADDRESS, TxEnvelope};
1916
use alloy_primitives::{TxKind, U256};
2017
use anyhow::{anyhow, bail, ensure, Context, Error, Result};
18+
use core::{fmt::Debug, mem::take, str::from_utf8};
2119
#[cfg(feature = "std")]
2220
use log::debug;
2321
use revm::{
@@ -28,6 +26,8 @@ use revm::{
2826
},
2927
taiko, Database, DatabaseCommit, Evm, JournaledState,
3028
};
29+
use std::collections::HashSet;
30+
use tracing::trace;
3131
cfg_if::cfg_if! {
3232
if #[cfg(feature = "tracer")] {
3333
use std::{fs::{OpenOptions, File}, io::{BufWriter, Write}, sync::{Arc, Mutex}};
@@ -48,7 +48,6 @@ use crate::{
4848
print_duration,
4949
time::{AddAssign, Duration, Instant},
5050
utils::{check_anchor_tx, generate_transactions},
51-
Measurement,
5251
};
5352

5453
/// Minimum supported protocol version: SHANGHAI
@@ -83,7 +82,7 @@ impl TxExecStrategy for TkoTxExecStrategy {
8382
let chain_spec = &block_builder.input.chain_spec;
8483
let chain_id = chain_spec.chain_id();
8584
let is_taiko = chain_spec.is_taiko();
86-
println!("spec_id: {spec_id:?}");
85+
trace!("spec_id: {spec_id:?}");
8786

8887
// generate the transactions from the tx list
8988
// For taiko blocks, insert the anchor tx as the first transaction
@@ -176,7 +175,11 @@ impl TxExecStrategy for TkoTxExecStrategy {
176175
let mut actual_tx_no = 0usize;
177176
let num_transactions = transactions.len();
178177
for (tx_no, tx) in take(&mut transactions).into_iter().enumerate() {
179-
inplace_print(&format!("\rprocessing tx {tx_no}/{num_transactions}..."));
178+
if !is_optimistic {
179+
inplace_print(&format!("\rprocessing tx {tx_no}/{num_transactions}..."));
180+
} else {
181+
trace!("\rprocessing tx {tx_no}/{num_transactions}...");
182+
}
180183

181184
#[cfg(feature = "tracer")]
182185
let trace = set_trace_writer(
@@ -284,7 +287,7 @@ impl TxExecStrategy for TkoTxExecStrategy {
284287
}
285288
};
286289
#[cfg(feature = "std")]
287-
debug!(" Ok: {result:?}");
290+
trace!(" Ok: {result:?}");
288291

289292
#[cfg(feature = "tracer")]
290293
// Flush the trace writer
@@ -332,14 +335,15 @@ impl TxExecStrategy for TkoTxExecStrategy {
332335

333336
tx_misc_duration.add_assign(start.elapsed());
334337
}
335-
clear_line();
336-
print_duration("Tx transact time: ", tx_transact_duration);
337-
print_duration("Tx misc time: ", tx_misc_duration);
338+
if !is_optimistic {
339+
clear_line();
340+
print_duration("Tx transact time: ", tx_transact_duration);
341+
print_duration("Tx misc time: ", tx_misc_duration);
342+
}
338343

339344
let mut db = &mut evm.context.evm.db;
340345

341346
// process withdrawals unconditionally after any transactions
342-
let measurement = Measurement::start("Processing withdrawals...", true);
343347
let mut withdrawals_trie = MptNode::default();
344348
for (i, withdrawal) in block_builder.input.withdrawals.iter().enumerate() {
345349
// the withdrawal amount is given in Gwei
@@ -354,10 +358,8 @@ impl TxExecStrategy for TkoTxExecStrategy {
354358
.insert_rlp(&i.to_rlp(), withdrawal)
355359
.with_context(|| "failed to insert withdrawal")?;
356360
}
357-
measurement.stop();
358361

359362
// Update result header with computed values
360-
let measurement = Measurement::start("Generating block header...", true);
361363
header.transactions_root = tx_trie.hash();
362364
header.receipts_root = receipt_trie.hash();
363365
header.logs_bloom = logs_bloom;
@@ -368,7 +370,6 @@ impl TxExecStrategy for TkoTxExecStrategy {
368370
if spec_id >= SpecId::CANCUN {
369371
header.blob_gas_used = Some(blob_gas_used.into());
370372
}
371-
measurement.stop();
372373

373374
// Leak memory, save cycles
374375
guest_mem_forget([tx_trie, receipt_trie, withdrawals_trie]);

0 commit comments

Comments
 (0)