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(katana): state trie #2607

Merged
merged 2 commits into from
Nov 1, 2024
Merged
Show file tree
Hide file tree
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
69 changes: 59 additions & 10 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ members = [
"crates/katana/storage/db",
"crates/katana/storage/provider",
"crates/katana/tasks",
"crates/katana/trie",
"crates/metrics",
"crates/saya/core",
"crates/saya/provider",
Expand Down Expand Up @@ -100,6 +101,7 @@ katana-rpc-types-builder = { path = "crates/katana/rpc/rpc-types-builder" }
katana-runner = { path = "crates/katana/runner" }
katana-slot-controller = { path = "crates/katana/controller" }
katana-tasks = { path = "crates/katana/tasks" }
katana-trie = { path = "crates/katana/trie" }

# torii
torii-client = { path = "crates/torii/client" }
Expand Down Expand Up @@ -254,4 +256,6 @@ alloy-transport = { version = "0.3", default-features = false }

starknet = "0.12.0"
starknet-crypto = "0.7.1"
starknet-types-core = { version = "0.1.6", features = [ "arbitrary" ] }
starknet-types-core = { version = "0.1.7", features = [ "arbitrary", "hash" ] }

bitvec = "1.0.1"
6 changes: 5 additions & 1 deletion crates/katana/storage/db/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ version.workspace = true

[dependencies]
katana-primitives = { workspace = true, features = [ "arbitrary" ] }
katana-trie.workspace = true

anyhow.workspace = true
dojo-metrics.workspace = true
Expand All @@ -17,12 +18,16 @@ parking_lot.workspace = true
roaring = { version = "0.10.3", features = [ "serde" ] }
serde.workspace = true
serde_json.workspace = true
starknet.workspace = true
starknet-types-core.workspace = true
tempfile.workspace = true
thiserror.workspace = true
tracing.workspace = true

# codecs
bitvec.workspace = true
postcard = { workspace = true, optional = true }
smallvec = "1.13.2"

[dependencies.libmdbx]
git = "https://github.com/paradigmxyz/reth.git"
Expand All @@ -32,7 +37,6 @@ rev = "b34b0d3"
[dev-dependencies]
arbitrary.workspace = true
criterion.workspace = true
starknet.workspace = true

[features]
default = [ "postcard" ]
Expand Down
2 changes: 2 additions & 0 deletions crates/katana/storage/db/src/codecs/postcard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use crate::error::CodecError;
use crate::models::block::StoredBlockBodyIndices;
use crate::models::contract::ContractInfoChangeList;
use crate::models::list::BlockList;
use crate::models::trie::TrieDatabaseValue;

macro_rules! impl_compress_and_decompress_for_table_values {
($($name:ty),*) => {
Expand Down Expand Up @@ -38,6 +39,7 @@ impl_compress_and_decompress_for_table_values!(
Header,
Receipt,
Felt,
TrieDatabaseValue,
ContractAddress,
BlockList,
GenericContractInfo,
Expand Down
1 change: 1 addition & 0 deletions crates/katana/storage/db/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub mod error;
pub mod mdbx;
pub mod models;
pub mod tables;
pub mod trie;
pub mod utils;
pub mod version;

Expand Down
1 change: 1 addition & 0 deletions crates/katana/storage/db/src/models/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ pub mod class;
pub mod contract;
pub mod list;
pub mod storage;
pub mod trie;
81 changes: 81 additions & 0 deletions crates/katana/storage/db/src/models/trie.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
use katana_trie::bonsai::ByteVec;
use serde::{Deserialize, Serialize};

use crate::codecs::{Decode, Encode};
use crate::error::CodecError;

#[repr(u8)]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]

Check warning on line 8 in crates/katana/storage/db/src/models/trie.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/storage/db/src/models/trie.rs#L8

Added line #L8 was not covered by tests
pub enum TrieDatabaseKeyType {
Trie = 0,
Flat,
TrieLog,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]

Check warning on line 15 in crates/katana/storage/db/src/models/trie.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/storage/db/src/models/trie.rs#L15

Added line #L15 was not covered by tests
pub struct TrieDatabaseKey {
pub r#type: TrieDatabaseKeyType,
pub key: Vec<u8>,
}

pub type TrieDatabaseValue = ByteVec;

impl Encode for TrieDatabaseKey {
type Encoded = Vec<u8>;

fn encode(self) -> Self::Encoded {
let mut encoded = Vec::new();
encoded.push(self.r#type as u8);
encoded.extend(self.key);
encoded
}
}

impl Decode for TrieDatabaseKey {
fn decode<B: AsRef<[u8]>>(bytes: B) -> Result<Self, CodecError> {
let bytes = bytes.as_ref();
if bytes.is_empty() {
panic!("emptyy buffer")

Check warning on line 38 in crates/katana/storage/db/src/models/trie.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/storage/db/src/models/trie.rs#L38

Added line #L38 was not covered by tests
}

let r#type = match bytes[0] {
0 => TrieDatabaseKeyType::Trie,
1 => TrieDatabaseKeyType::Flat,
2 => TrieDatabaseKeyType::TrieLog,
_ => panic!("Invalid trie database key type"),

Check warning on line 45 in crates/katana/storage/db/src/models/trie.rs

View check run for this annotation

Codecov / codecov/patch

crates/katana/storage/db/src/models/trie.rs#L45

Added line #L45 was not covered by tests
};

let key = bytes[1..].to_vec();

Ok(TrieDatabaseKey { r#type, key })
}
}
Comment on lines +34 to +52
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Improve error handling and code clarity, sensei!

A few suggestions to enhance robustness and maintainability:

  1. Fix the typo in the panic message
  2. Consider using Result instead of panic for error cases
  3. Use enum variants directly in the match statement

Here's how to improve it:

 impl Decode for TrieDatabaseKey {
     fn decode<B: AsRef<[u8]>>(bytes: B) -> Result<Self, CodecError> {
         let bytes = bytes.as_ref();
         if bytes.is_empty() {
-            panic!("emptyy buffer")
+            return Err(CodecError::InvalidInput("empty buffer".into()));
         }
 
         let r#type = match bytes[0] {
-            0 => TrieDatabaseKeyType::Trie,
-            1 => TrieDatabaseKeyType::Flat,
-            2 => TrieDatabaseKeyType::TrieLog,
-            _ => panic!("Invalid trie database key type"),
+            x if x == TrieDatabaseKeyType::Trie as u8 => TrieDatabaseKeyType::Trie,
+            x if x == TrieDatabaseKeyType::Flat as u8 => TrieDatabaseKeyType::Flat,
+            x if x == TrieDatabaseKeyType::TrieLog as u8 => TrieDatabaseKeyType::TrieLog,
+            _ => return Err(CodecError::InvalidInput("invalid trie database key type".into())),
         };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
impl Decode for TrieDatabaseKey {
fn decode<B: AsRef<[u8]>>(bytes: B) -> Result<Self, CodecError> {
let bytes = bytes.as_ref();
if bytes.is_empty() {
panic!("emptyy buffer")
}
let r#type = match bytes[0] {
0 => TrieDatabaseKeyType::Trie,
1 => TrieDatabaseKeyType::Flat,
2 => TrieDatabaseKeyType::TrieLog,
_ => panic!("Invalid trie database key type"),
};
let key = bytes[1..].to_vec();
Ok(TrieDatabaseKey { r#type, key })
}
}
impl Decode for TrieDatabaseKey {
fn decode<B: AsRef<[u8]>>(bytes: B) -> Result<Self, CodecError> {
let bytes = bytes.as_ref();
if bytes.is_empty() {
return Err(CodecError::InvalidInput("empty buffer".into()));
}
let r#type = match bytes[0] {
x if x == TrieDatabaseKeyType::Trie as u8 => TrieDatabaseKeyType::Trie,
x if x == TrieDatabaseKeyType::Flat as u8 => TrieDatabaseKeyType::Flat,
x if x == TrieDatabaseKeyType::TrieLog as u8 => TrieDatabaseKeyType::TrieLog,
_ => return Err(CodecError::InvalidInput("invalid trie database key type".into())),
};
let key = bytes[1..].to_vec();
Ok(TrieDatabaseKey { r#type, key })
}
}


#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_trie_key_roundtrip() {
let key = TrieDatabaseKey { r#type: TrieDatabaseKeyType::Trie, key: vec![1, 2, 3] };
let encoded = key.clone().encode();
let decoded = TrieDatabaseKey::decode(encoded).unwrap();
assert_eq!(key, decoded);
}

#[test]
fn test_flat_key_roundtrip() {
let key = TrieDatabaseKey { r#type: TrieDatabaseKeyType::Flat, key: vec![4, 5, 6] };
let encoded = key.clone().encode();
let decoded = TrieDatabaseKey::decode(encoded).unwrap();
assert_eq!(key, decoded);
}

#[test]
fn test_trielog_key_roundtrip() {
let key = TrieDatabaseKey { r#type: TrieDatabaseKeyType::TrieLog, key: vec![7, 8, 9] };
let encoded = key.clone().encode();
let decoded = TrieDatabaseKey::decode(encoded).unwrap();
assert_eq!(key, decoded);
}
}
Loading
Loading