diff --git a/crates/p2p_proto/src/common.rs b/crates/p2p_proto/src/common.rs index 46b92472e5..13188f4a84 100644 --- a/crates/p2p_proto/src/common.rs +++ b/crates/p2p_proto/src/common.rs @@ -247,13 +247,14 @@ pub enum ExecutionStatus { impl TryFromProtobuf for ExecutionStatus { fn try_from_protobuf(input: i32, field_name: &'static str) -> Result { - match input { - 0 => Ok(ExecutionStatus::Succeeded), - 1 => Ok(ExecutionStatus::Reverted), - _ => Err(std::io::Error::new( - std::io::ErrorKind::InvalidData, - format!("Failed to parse {field_name}: missing txn field"), - )), + let status = proto::common::ExecutionStatus::from_i32(input).ok_or(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("Failed to convert protobuf output for {field_name}: {input} did not match any known execution status"), + ))?; + + match status { + proto::common::ExecutionStatus::Succeeded => Ok(Self::Succeeded), + proto::common::ExecutionStatus::Reverted => Ok(Self::Reverted), } } } diff --git a/crates/rpc/fixtures/mainnet.sqlite b/crates/rpc/fixtures/mainnet.sqlite index 23e60594ec..483cac8f9e 100644 Binary files a/crates/rpc/fixtures/mainnet.sqlite and b/crates/rpc/fixtures/mainnet.sqlite differ diff --git a/crates/rpc/src/j2.rs b/crates/rpc/src/j2.rs new file mode 100644 index 0000000000..93ecd6982d --- /dev/null +++ b/crates/rpc/src/j2.rs @@ -0,0 +1,188 @@ +// #![allow(dead_code)] + +// use std::collections::HashMap; +// use std::marker::PhantomData; + +// use futures::Future; +// use serde::de::DeserializeOwned; +// use serde_json::Value; + +// use crate::context::RpcContext; + +// #[derive(Default)] +// struct MethodRouter { +// methods: HashMap<&'static str, Box>, +// } + +// impl MethodRouter { +// fn register( +// mut self, +// method_name: &'static str, +// method: impl IntoMethod + 'static, +// ) -> Self { +// self.methods.insert(method_name, method.into_method()); +// self +// } + +// async fn invoke( +// &self, +// method: &str, +// input: Value, +// state: RpcContext, +// ) -> Result { +// match self.methods.get(method) { +// Some(method) => method.invoke(input, state).await.map_err(Into::into), +// None => Err(crate::jsonrpc::RpcError::MethodNotFound { +// method: method.to_owned(), +// }), +// } +// } +// } + +// #[axum::async_trait] +// trait Method { +// async fn invoke( +// &self, +// input: Value, +// state: RpcContext, +// ) -> Result; +// } + +// trait IntoMethod { +// fn into_method(self) -> Box; +// } + +// /// impl for +// /// () -> T +// /// input only +// /// state only +// /// input and state + + + +// impl<'de, Func, Fut, Input> IntoMethod<((), Input)> for Func +// where +// Func: Fn(Input) -> Fut + Clone + 'static + std::marker::Sync + std::marker::Send, +// Fut: Future + std::marker::Send + 'static, +// Input: DeserializeOwned + std::marker::Sync + std::marker::Send + 'static, +// { +// fn into_method(self) -> Box { +// struct HandlerImpl +// where +// Func: Fn(Input) -> Fut + Clone, +// Fut: Future, +// { +// f: Func, +// _marker: PhantomData, +// } + +// #[axum::async_trait] +// impl<'de, Func, Fut, Input> Method for HandlerImpl +// where +// Func: Fn(Input) -> Fut + Clone + 'static + std::marker::Sync + std::marker::Send, +// Fut: Future + std::marker::Send, +// Input: DeserializeOwned + std::marker::Sync + std::marker::Send + 'static, +// { +// async fn invoke(&self, input: Value) -> u32 { +// let input: Input = serde_json::from_value(input).unwrap(); +// let f = self.f.clone(); +// async move { f(input).await }.await +// } +// } + +// Box::new(HandlerImpl { +// f: self, +// _marker: Default::default(), +// }) as Box +// } +// } + +// impl IntoMethod for Func +// where +// Func: Fn(u32) -> Fut + Clone + 'static + std::marker::Sync + std::marker::Send, +// Fut: Future + std::marker::Send + 'static, +// { +// fn into_method(self) -> Box { +// struct HandlerImpl +// where +// Func: Fn(u32) -> Fut + Clone, +// Fut: Future, +// { +// f: Func, +// } + +// #[derive(serde::Deserialize)] +// struct Input(u32); + +// #[axum::async_trait] +// impl Method for HandlerImpl +// where +// Func: Fn(u32) -> Fut + Clone + std::marker::Sync + std::marker::Send, +// Fut: Future + std::marker::Send, +// { +// async fn invoke(&self, input: Value) -> u32 { +// let input: Input = serde_json::from_value(input).unwrap(); +// let f = self.f.clone(); +// f(input.0).await +// } +// } + +// Box::new(HandlerImpl { f: self }) as Box +// } +// } + +// impl IntoMethod<()> for Func +// where +// Func: Fn() -> Value + Clone + 'static + std::marker::Sync, +// { +// fn into_method(self) -> Box { +// struct HandlerImpl u32 + Clone> { +// f: Func, +// } + +// #[axum::async_trait] +// impl u32 + Clone + std::marker::Sync> Method for HandlerImpl { +// async fn invoke(&self, _input: Value) -> u32 { +// let f = self.f.clone(); +// f() +// } +// } + +// Box::new(HandlerImpl { f: self }) as Box +// } +// } + +// #[tokio::test] +// async fn feature() { +// async fn echo(x: u32) -> u32 { +// x +// } + +// fn always_10() -> u32 { +// 10 +// } + +// async fn double(x: u32) -> u32 { +// x * 2 +// } + +// #[derive(serde::Deserialize)] +// struct In(u32); + +// async fn echo_serde(input: In) -> u32 { +// input.0 +// } + +// let router = MethodRouter::default() +// .register::("echo", echo) +// .register("always_10", always_10) +// .register::("double", double) +// .register("echo_serde", echo_serde); + +// let input = Value::Number(20.into()); + +// assert_eq!(router.invoke("echo_serde", input.clone()).await, 20); +// assert_eq!(router.invoke("echo", input.clone()).await, 20); +// assert_eq!(router.invoke("always_10", input.clone()).await, 10); +// assert_eq!(router.invoke("double", input).await, 20 * 2); +// } diff --git a/crates/storage/src/connection/block.rs b/crates/storage/src/connection/block.rs index 041a826016..4bd4402c21 100644 --- a/crates/storage/src/connection/block.rs +++ b/crates/storage/src/connection/block.rs @@ -13,7 +13,7 @@ pub(super) fn insert_block_header( // Insert the header tx.inner().execute( - r"INSERT INTO headers + r"INSERT INTO block_headers ( number, hash, storage_commitment, timestamp, gas_price, sequencer_address, version_id, transaction_commitment, event_commitment, state_commitment, class_commitment, transaction_count, event_count) VALUES (:number, :hash, :storage_commitment, :timestamp, :gas_price, :sequencer_address, :version_id, :transaction_commitment, :event_commitment, :state_commitment, :class_commitment, :transaction_count, :event_count)", named_params! { @@ -104,8 +104,11 @@ pub(super) fn purge_block(tx: &Transaction<'_>, block: BlockNumber) -> anyhow::R .context("Deleting block from canonical_blocks table")?; tx.inner() - .execute("DELETE FROM headers WHERE number = ?", params![&block]) - .context("Deleting block from headers table")?; + .execute( + "DELETE FROM block_headers WHERE number = ?", + params![&block], + ) + .context("Deleting block from block_headers table")?; Ok(()) } @@ -173,7 +176,7 @@ pub(super) fn block_header( block: BlockId, ) -> anyhow::Result> { // TODO: is LEFT JOIN reasonable? It's required because version ID can be null for non-existent versions. - const BASE_SQL: &str = "SELECT * FROM headers LEFT JOIN starknet_versions ON headers.version_id = starknet_versions.id"; + const BASE_SQL: &str = "SELECT * FROM block_headers LEFT JOIN starknet_versions ON block_headers.version_id = starknet_versions.id"; let sql = match block { BlockId::Latest => format!("{BASE_SQL} ORDER BY number DESC LIMIT 1"), BlockId::Number(_) => format!("{BASE_SQL} WHERE number = ?"), @@ -235,7 +238,7 @@ pub(super) fn block_header( let parent_hash = tx .inner() .query_row( - "SELECT hash FROM headers WHERE number = ?", + "SELECT hash FROM block_headers WHERE number = ?", params![&(header.number - 1)], |row| row.get_block_hash(0), ) @@ -388,7 +391,7 @@ mod tests { // Overwrite the commitment fields to NULL. tx.inner().execute( - r"UPDATE headers + r"UPDATE block_headers SET transaction_commitment=NULL, event_commitment=NULL, class_commitment=NULL, version_id=NULL WHERE number=?", params![&target.number], diff --git a/crates/storage/src/connection/event.rs b/crates/storage/src/connection/event.rs index 90fc301472..fab64b2475 100644 --- a/crates/storage/src/connection/event.rs +++ b/crates/storage/src/connection/event.rs @@ -150,7 +150,7 @@ pub(super) fn get_events( let base_query = r#"SELECT block_number, - headers.hash as block_hash, + block_headers.hash as block_hash, transaction_hash, starknet_transactions.idx as transaction_idx, from_address, @@ -158,7 +158,7 @@ pub(super) fn get_events( starknet_events.keys as keys FROM starknet_events INNER JOIN starknet_transactions ON (starknet_transactions.hash = starknet_events.transaction_hash) - INNER JOIN headers ON (headers.number = starknet_events.block_number)"#; + INNER JOIN block_headers ON (block_headers.number = starknet_events.block_number)"#; let (mut base_query, mut params) = event_query( base_query, diff --git a/crates/storage/src/connection/state_update.rs b/crates/storage/src/connection/state_update.rs index 84a3cb40dc..1486b1a843 100644 --- a/crates/storage/src/connection/state_update.rs +++ b/crates/storage/src/connection/state_update.rs @@ -97,8 +97,8 @@ fn block_details( ) -> anyhow::Result> { use const_format::formatcp; - const PREFIX: &str = r"SELECT b1.number, b1.hash, b1.storage_commitment, b1.class_commitment, b2.storage_commitment, b2.class_commitment FROM headers b1 - LEFT OUTER JOIN headers b2 ON b2.number = b1.number - 1"; + const PREFIX: &str = r"SELECT b1.number, b1.hash, b1.storage_commitment, b1.class_commitment, b2.storage_commitment, b2.class_commitment FROM block_headers b1 + LEFT OUTER JOIN block_headers b2 ON b2.number = b1.number - 1"; const LATEST: &str = formatcp!("{PREFIX} ORDER BY b1.number DESC LIMIT 1"); const NUMBER: &str = formatcp!("{PREFIX} WHERE b1.number = ?"); diff --git a/crates/storage/src/connection/transaction.rs b/crates/storage/src/connection/transaction.rs index 0315f8bc5f..41ea6cf863 100644 --- a/crates/storage/src/connection/transaction.rs +++ b/crates/storage/src/connection/transaction.rs @@ -156,7 +156,7 @@ pub(super) fn transaction_count(tx: &Transaction<'_>, block: BlockId) -> anyhow: .inner() .query_row( "SELECT COUNT(*) FROM starknet_transactions - JOIN headers ON starknet_transactions.block_hash = headers.hash + JOIN block_headers ON starknet_transactions.block_hash = block_headers.hash WHERE number = ?1", params![&number], |row| row.get(0), diff --git a/crates/storage/src/schema/revision_0039.rs b/crates/storage/src/schema/revision_0039.rs index 5ad1696031..ee15a3e395 100644 --- a/crates/storage/src/schema/revision_0039.rs +++ b/crates/storage/src/schema/revision_0039.rs @@ -2,63 +2,63 @@ use anyhow::Context; use rusqlite::OptionalExtension; use stark_hash::Felt; -/// This migration renames the starknet_blocks to headers and adds the state_commitment, +/// This migration renames the starknet_blocks to block_headers and adds the state_commitment, /// transaction_count and event_count columns, and also renames the root column to storage_commitment. pub(crate) fn migrate(tx: &rusqlite::Transaction<'_>) -> anyhow::Result<()> { - tracing::info!("Refactoring the headers table, this may take a while"); + tracing::info!("Refactoring the block_headers table, this may take a while"); - tx.execute("ALTER TABLE starknet_blocks RENAME TO headers", []) - .context("Renaming starknet_blocks table to headers")?; + tx.execute("ALTER TABLE starknet_blocks RENAME TO block_headers", []) + .context("Renaming starknet_blocks table to block_headers")?; tx.execute( - "ALTER TABLE headers RENAME COLUMN root TO storage_commitment", + "ALTER TABLE block_headers RENAME COLUMN root TO storage_commitment", [], ) - .context("Renaming headers.root table to headers.storage_commitment")?; + .context("Renaming block_headers.root column to block_headers.storage_commitment")?; tx.execute( - "ALTER TABLE headers ADD COLUMN state_commitment BLOB NOT NULL DEFAULT x'0000000000000000000000000000000000000000000000000000000000000000'", + "ALTER TABLE block_headers ADD COLUMN state_commitment BLOB NOT NULL DEFAULT x'0000000000000000000000000000000000000000000000000000000000000000'", [], ) .context("Adding state_commitment column")?; tx.execute( - "ALTER TABLE headers ADD COLUMN transaction_count INTEGER NOT NULL DEFAULT 0", + "ALTER TABLE block_headers ADD COLUMN transaction_count INTEGER NOT NULL DEFAULT 0", [], ) .context("Adding transaction_count column")?; tx.execute( - "ALTER TABLE headers ADD COLUMN event_count INTEGER NOT NULL DEFAULT 0", + "ALTER TABLE block_headers ADD COLUMN event_count INTEGER NOT NULL DEFAULT 0", [], ) .context("Adding event_count column")?; tx.execute( - r"UPDATE headers SET transaction_count = ( - SELECT COUNT(1) FROM starknet_transactions WHERE starknet_transactions.block_hash = headers.hash + r"UPDATE block_headers SET transaction_count = ( + SELECT COUNT(1) FROM starknet_transactions WHERE starknet_transactions.block_hash = block_headers.hash )", [], ) .context("Setting tx counts")?; tx.execute( - r"UPDATE headers SET event_count = ( - SELECT COUNT(1) FROM starknet_events WHERE starknet_events.block_number = headers.number + r"UPDATE block_headers SET event_count = ( + SELECT COUNT(1) FROM starknet_events WHERE starknet_events.block_number = block_headers.number )", [], ) .context("Setting event counts")?; tx.execute( - r"UPDATE headers SET state_commitment = storage_commitment WHERE class_commitment IS NULL OR class_commitment = x'0000000000000000000000000000000000000000000000000000000000000000'", + r"UPDATE block_headers SET state_commitment = storage_commitment WHERE class_commitment IS NULL OR class_commitment = x'0000000000000000000000000000000000000000000000000000000000000000'", [], ) .context("Setting state_commitment = storage_commitment")?; let Some(start): Option = tx .query_row( - "SELECT number FROM headers WHERE state_commitment = x'0000000000000000000000000000000000000000000000000000000000000000' ORDER BY number ASC LIMIT 1", + "SELECT number FROM block_headers WHERE state_commitment = x'0000000000000000000000000000000000000000000000000000000000000000' ORDER BY number ASC LIMIT 1", [], |row| row.get(0), ) @@ -69,11 +69,11 @@ pub(crate) fn migrate(tx: &rusqlite::Transaction<'_>) -> anyhow::Result<()> { let mut reader = tx .prepare( - "SELECT number, storage_commitment, class_commitment FROM headers WHERE number >= ?", + "SELECT number, storage_commitment, class_commitment FROM block_headers WHERE number >= ?", ) .context("Preparing commitment reader statement")?; let mut writer = tx - .prepare("UPDATE headers SET state_commitment = ? WHERE number = ?") + .prepare("UPDATE block_headers SET state_commitment = ? WHERE number = ?") .context("Preparing commitment writer statement")?; let rows = reader diff --git a/py/src/pathfinder_worker/call.py b/py/src/pathfinder_worker/call.py index 0404e397e9..10427734c4 100644 --- a/py/src/pathfinder_worker/call.py +++ b/py/src/pathfinder_worker/call.py @@ -608,7 +608,7 @@ def resolve_block( ) -> Tuple[BlockInfo, int, int]: """ forced_gas_price is the gas price we must use for this blockinfo, if None, - the one from headers will be used. this allows the caller to select + the one from block_headers will be used. this allows the caller to select where the gas_price information is coming from, and for example, select different one for latest pointed out by hash or tag. """ @@ -617,11 +617,11 @@ def resolve_block( # it has been decided that the latest is whatever pathfinder knows to be latest synced block # regardless of it being the highest known (not yet synced) cursor = connection.execute( - "select number, timestamp, storage_commitment, gas_price, sequencer_address, class_commitment, sn_ver.version from headers left join starknet_versions sn_ver on (sn_ver.id = version_id) order by number desc limit 1" + "select number, timestamp, storage_commitment, gas_price, sequencer_address, class_commitment, sn_ver.version from block_headers left join starknet_versions sn_ver on (sn_ver.id = version_id) order by number desc limit 1" ) elif isinstance(at_block, int): cursor = connection.execute( - "select number, timestamp, storage_commitment, gas_price, sequencer_address, class_commitment, sn_ver.version from headers left join starknet_versions sn_ver on (sn_ver.id = version_id) where number = ?", + "select number, timestamp, storage_commitment, gas_price, sequencer_address, class_commitment, sn_ver.version from block_headers left join starknet_versions sn_ver on (sn_ver.id = version_id) where number = ?", [at_block], ) else: @@ -631,7 +631,7 @@ def resolve_block( at_block = b"\x00" * (32 - len(at_block)) + at_block cursor = connection.execute( - "select number, timestamp, storage_commitment, gas_price, sequencer_address, class_commitment, sn_ver.version from headers left join starknet_versions sn_ver on (sn_ver.id = version_id) where hash = ?", + "select number, timestamp, storage_commitment, gas_price, sequencer_address, class_commitment, sn_ver.version from block_headers left join starknet_versions sn_ver on (sn_ver.id = version_id) where hash = ?", [at_block], ) diff --git a/py/tests/pathfinder_worker/test_call.py b/py/tests/pathfinder_worker/test_call.py index 7359f37722..f27040b38a 100644 --- a/py/tests/pathfinder_worker/test_call.py +++ b/py/tests/pathfinder_worker/test_call.py @@ -198,7 +198,7 @@ def inmemory_with_tables(): CREATE TABLE class_definitions ( hash BLOB PRIMARY KEY, definition BLOB, - block_number INTEGER REFERENCES headers(number) NOT NULL + block_number INTEGER REFERENCES block_headers(number) NOT NULL ); -- This is missing the foreign key definition @@ -216,7 +216,7 @@ def inmemory_with_tables(): version TEXT NOT NULL UNIQUE ); - CREATE TABLE headers ( + CREATE TABLE block_headers ( number INTEGER PRIMARY KEY, hash BLOB NOT NULL, storage_commitment BLOB NOT NULL, @@ -445,7 +445,7 @@ def populate_test_contract_with_132_on_3(con): # interestingly python sqlite does not accept X'0' here: cur.execute( - """insert into headers (hash, number, timestamp, storage_commitment, gas_price, sequencer_address, class_commitment) values (?, 1, 1, ?, ?, ?, ?)""", + """insert into block_headers (hash, number, timestamp, storage_commitment, gas_price, sequencer_address, class_commitment) values (?, 1, 1, ?, ?, ?, ?)""", [ b"some blockhash somewhere".rjust(32, b"\x00"), felt_to_bytes(state_root), @@ -615,7 +615,7 @@ def test_no_such_block(): common_command_data = f'"contract_address": "{contract_address}", "entry_point_selector": "{entry_point}", "calldata": ["0x84"], "gas_price": 0, "chain": "TESTNET", "pending_updates": {{}}, "pending_deployed": [], "pending_nonces": {{}}, "pending_timestamp": 0' - con.execute("delete from headers") + con.execute("delete from block_headers") con.commit() output = default_132_on_3_scenario( @@ -824,7 +824,7 @@ def test_starknet_version_is_resolved(): ) version_id = cursor.lastrowid - con.execute("UPDATE headers SET version_id = ?", [version_id]) + con.execute("UPDATE block_headers SET version_id = ?", [version_id]) (info, _root, _class_commitment) = resolve_block(con, "latest", 0) assert info.starknet_version == "0.9.1" @@ -1152,7 +1152,7 @@ def test_nonce_with_dummy(): ) cur.executemany( - "insert into headers (hash, number, storage_commitment, timestamp, gas_price, sequencer_address, version_id) values (?, ?, ?, ?, ?, ?, ?)", + "insert into block_headers (hash, number, storage_commitment, timestamp, gas_price, sequencer_address, version_id) values (?, ?, ?, ?, ?, ?, ?)", [ ( b"another block".rjust(32, b"\x00"), @@ -1452,7 +1452,7 @@ def setup_account_and_sierra_contract( # Block cur.execute( - """insert into headers (hash, number, timestamp, storage_commitment, gas_price, sequencer_address, class_commitment) values (?, 1, 1, ?, ?, ?, ?)""", + """insert into block_headers (hash, number, timestamp, storage_commitment, gas_price, sequencer_address, class_commitment) values (?, 1, 1, ?, ?, ?, ?)""", [ b"some blockhash somewhere".rjust(32, b"\x00"), felt_to_bytes(storage_root_node.hash()), @@ -1713,7 +1713,7 @@ def test_estimate_fee_for_deploy_newly_declared_account(): # Block cur.execute( - """insert into headers (hash, number, timestamp, storage_commitment, gas_price, sequencer_address, class_commitment) values (?, 1, 1, ?, ?, ?, ?)""", + """insert into block_headers (hash, number, timestamp, storage_commitment, gas_price, sequencer_address, class_commitment) values (?, 1, 1, ?, ?, ?, ?)""", [ b"some blockhash somewhere".rjust(32, b"\x00"), felt_to_bytes(0), @@ -2194,7 +2194,7 @@ def test_simulate_transaction_succeeds(): ) con.execute( - """insert into headers (hash, number, timestamp, storage_commitment, gas_price, sequencer_address) values (?, 1, 1, ?, ?, ?)""", + """insert into block_headers (hash, number, timestamp, storage_commitment, gas_price, sequencer_address) values (?, 1, 1, ?, ?, ?)""", [ b"some blockhash somewhere".rjust(32, b"\x00"), b"\x00" * 32, @@ -2324,7 +2324,7 @@ def deploy_contract(con, name, contract_address, class_hash): state_root = root_node.hash() cur.execute( - """insert into headers (hash, number, timestamp, storage_commitment, gas_price, sequencer_address, class_commitment) values (?, 1, 1, ?, ?, ?, ?)""", + """insert into block_headers (hash, number, timestamp, storage_commitment, gas_price, sequencer_address, class_commitment) values (?, 1, 1, ?, ?, ?, ?)""", [ b"some blockhash somewhere".rjust(32, b"\x00"), felt_to_bytes(state_root),