diff --git a/.github/readme.png b/.github/readme.png new file mode 100644 index 0000000..a4ceb2a Binary files /dev/null and b/.github/readme.png differ diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b906fc8 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,33 @@ +name: CI + +on: + push: + branches: + - main + pull_request: + branches: + - main + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: stable + + - name: Install clippy + run: rustup component add clippy + + - name: Install rustfmt + run: rustup component add rustfmt + + - name: Run clippy for native + run: cargo clippy --all --all-targets -- -D warnings + + - name: Run fmt + run: cargo fmt -- --check + + - name: Run tests + run: cargo test --all --all-targets -- --nocapture diff --git a/Cargo.lock b/Cargo.lock index cf2ee26..0bfcff7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -38,7 +38,7 @@ checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5" [[package]] name = "alloy-consensus" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#52d16d33e125670e952b38d888eaefc560738cc2" +source = "git+https://github.com/alloy-rs/alloy?rev=52d16d3#52d16d33e125670e952b38d888eaefc560738cc2" dependencies = [ "alloy-eips", "alloy-primitives", @@ -48,7 +48,7 @@ dependencies = [ [[package]] name = "alloy-eips" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#52d16d33e125670e952b38d888eaefc560738cc2" +source = "git+https://github.com/alloy-rs/alloy?rev=52d16d3#52d16d33e125670e952b38d888eaefc560738cc2" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -58,7 +58,7 @@ dependencies = [ [[package]] name = "alloy-json-rpc" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#6fada4ceda1d0101974e3cb361761944c08dd553" +source = "git+https://github.com/alloy-rs/alloy?rev=52d16d3#52d16d33e125670e952b38d888eaefc560738cc2" dependencies = [ "alloy-primitives", "serde", @@ -69,7 +69,7 @@ dependencies = [ [[package]] name = "alloy-network" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#52d16d33e125670e952b38d888eaefc560738cc2" +source = "git+https://github.com/alloy-rs/alloy?rev=52d16d3#52d16d33e125670e952b38d888eaefc560738cc2" dependencies = [ "alloy-consensus", "alloy-eips", @@ -108,7 +108,7 @@ dependencies = [ [[package]] name = "alloy-provider" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#52d16d33e125670e952b38d888eaefc560738cc2" +source = "git+https://github.com/alloy-rs/alloy?rev=52d16d3#52d16d33e125670e952b38d888eaefc560738cc2" dependencies = [ "alloy-json-rpc", "alloy-network", @@ -155,7 +155,7 @@ dependencies = [ [[package]] name = "alloy-rpc-client" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#6fada4ceda1d0101974e3cb361761944c08dd553" +source = "git+https://github.com/alloy-rs/alloy?rev=52d16d3#52d16d33e125670e952b38d888eaefc560738cc2" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -175,7 +175,7 @@ dependencies = [ [[package]] name = "alloy-rpc-trace-types" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#52d16d33e125670e952b38d888eaefc560738cc2" +source = "git+https://github.com/alloy-rs/alloy?rev=52d16d3#52d16d33e125670e952b38d888eaefc560738cc2" dependencies = [ "alloy-primitives", "alloy-rpc-types", @@ -187,7 +187,7 @@ dependencies = [ [[package]] name = "alloy-rpc-types" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#6fada4ceda1d0101974e3cb361761944c08dd553" +source = "git+https://github.com/alloy-rs/alloy?rev=52d16d3#52d16d33e125670e952b38d888eaefc560738cc2" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -201,7 +201,7 @@ dependencies = [ [[package]] name = "alloy-serde" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#6fada4ceda1d0101974e3cb361761944c08dd553" +source = "git+https://github.com/alloy-rs/alloy?rev=52d16d3#52d16d33e125670e952b38d888eaefc560738cc2" dependencies = [ "alloy-primitives", "serde", @@ -211,7 +211,7 @@ dependencies = [ [[package]] name = "alloy-signer" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#52d16d33e125670e952b38d888eaefc560738cc2" +source = "git+https://github.com/alloy-rs/alloy?rev=52d16d3#52d16d33e125670e952b38d888eaefc560738cc2" dependencies = [ "alloy-primitives", "async-trait", @@ -224,7 +224,7 @@ dependencies = [ [[package]] name = "alloy-transport" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#6fada4ceda1d0101974e3cb361761944c08dd553" +source = "git+https://github.com/alloy-rs/alloy?rev=52d16d3#52d16d33e125670e952b38d888eaefc560738cc2" dependencies = [ "alloy-json-rpc", "base64 0.22.0", @@ -242,7 +242,7 @@ dependencies = [ [[package]] name = "alloy-transport-http" version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy#6fada4ceda1d0101974e3cb361761944c08dd553" +source = "git+https://github.com/alloy-rs/alloy?rev=52d16d3#52d16d33e125670e952b38d888eaefc560738cc2" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -252,43 +252,6 @@ dependencies = [ "url", ] -[[package]] -name = "alloy-trie" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b9e1498416f7e7f09af8061970e14936846b6271e153aa5ba539a22a7eb414d" -dependencies = [ - "alloy-primitives", - "alloy-rlp", - "derive_more", - "hashbrown 0.14.3", - "nybbles", - "serde", - "smallvec", - "tracing", -] - -[[package]] -name = "android-tzdata" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" - -[[package]] -name = "android_system_properties" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" -dependencies = [ - "libc", -] - -[[package]] -name = "anyhow" -version = "1.0.81" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0952808a6c2afd1aa8947271f3a60f1a6763c7b912d210184c5149b5cf147247" - [[package]] name = "ark-ff" version = "0.3.0" @@ -443,9 +406,9 @@ dependencies = [ [[package]] name = "async-trait" -version = "0.1.77" +version = "0.1.78" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c980ee35e870bd1a4d2c8294d4c04d0499e67bca1e4b5cefcc693c2fa00caea9" +checksum = "461abc97219de0eaaf81fe3ef974a540158f3d079c2ab200f891f1a2ef201e85" dependencies = [ "proc-macro2", "quote", @@ -595,19 +558,6 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" -[[package]] -name = "chrono" -version = "0.4.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8eaf5903dcbc0a39312feb77df2ff4c76387d591b9fc7b04a238dcf8bb62639a" -dependencies = [ - "android-tzdata", - "iana-time-zone", - "num-traits", - "serde", - "windows-targets 0.52.4", -] - [[package]] name = "const-hex" version = "1.11.3" @@ -686,41 +636,6 @@ dependencies = [ "typenum", ] -[[package]] -name = "darling" -version = "0.20.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54e36fcd13ed84ffdfda6f5be89b31287cbb80c439841fe69e04841435464391" -dependencies = [ - "darling_core", - "darling_macro", -] - -[[package]] -name = "darling_core" -version = "0.20.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c2cf1c23a687a1feeb728783b993c4e1ad83d99f351801977dd809b48d0a70f" -dependencies = [ - "fnv", - "ident_case", - "proc-macro2", - "quote", - "strsim", - "syn 2.0.52", -] - -[[package]] -name = "darling_macro" -version = "0.20.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a668eda54683121533a393014d8692171709ff57a7d61f187b6e782719f8933f" -dependencies = [ - "darling_core", - "quote", - "syn 2.0.52", -] - [[package]] name = "dashmap" version = "5.5.3" @@ -728,7 +643,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" dependencies = [ "cfg-if", - "hashbrown 0.14.3", + "hashbrown", "lock_api", "once_cell", "parking_lot_core", @@ -744,16 +659,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "deranged" -version = "0.3.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" -dependencies = [ - "powerfmt", - "serde", -] - [[package]] name = "derivative" version = "2.2.0" @@ -863,6 +768,27 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "eth-trie-proofs" +version = "0.1.0" +dependencies = [ + "alloy-consensus", + "alloy-eips", + "alloy-network", + "alloy-primitives", + "alloy-provider", + "alloy-rlp", + "alloy-rpc-client", + "alloy-rpc-types", + "alloy-transport", + "alloy-transport-http", + "eth_trie", + "ethereum-types", + "reqwest", + "tokio", + "url", +] + [[package]] name = "eth_trie" version = "0.4.0" @@ -870,7 +796,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec3aeb0284b473041df2419a28e3cdf0c64a78d2b9511af4b6e40bad3964b172" dependencies = [ "ethereum-types", - "hashbrown 0.14.3", + "hashbrown", "keccak-hash", "log", "parking_lot", @@ -1125,19 +1051,13 @@ dependencies = [ "futures-sink", "futures-util", "http", - "indexmap 2.2.5", + "indexmap", "slab", "tokio", "tokio-util", "tracing", ] -[[package]] -name = "hashbrown" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" - [[package]] name = "hashbrown" version = "0.14.3" @@ -1249,35 +1169,6 @@ dependencies = [ "tokio-native-tls", ] -[[package]] -name = "iana-time-zone" -version = "0.1.60" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7ffbb5a1b541ea2561f8c41c087286cc091e21e556a4f09a8f6cbf17b69b141" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "ident_case" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" - [[package]] name = "idna" version = "0.5.0" @@ -1326,17 +1217,6 @@ dependencies = [ "syn 1.0.109", ] -[[package]] -name = "indexmap" -version = "1.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" -dependencies = [ - "autocfg", - "hashbrown 0.12.3", - "serde", -] - [[package]] name = "indexmap" version = "2.2.5" @@ -1344,8 +1224,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b0b929d511467233429c45a44ac1dcaa21ba0f5ba11e4879e6ed28ddb4f9df4" dependencies = [ "equivalent", - "hashbrown 0.14.3", - "serde", + "hashbrown", ] [[package]] @@ -1467,7 +1346,7 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3262e75e648fce39813cb56ac41f3c3e3f65217ebf3844d818d1f9398cfb0dc" dependencies = [ - "hashbrown 0.14.3", + "hashbrown", ] [[package]] @@ -1531,12 +1410,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "num-conv" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" - [[package]] name = "num-integer" version = "0.1.46" @@ -1566,19 +1439,6 @@ dependencies = [ "libc", ] -[[package]] -name = "nybbles" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95f06be0417d97f81fe4e5c86d7d01b392655a9cac9c19a848aa033e18937b23" -dependencies = [ - "alloy-rlp", - "const-hex", - "proptest", - "serde", - "smallvec", -] - [[package]] name = "object" version = "0.32.2" @@ -1758,12 +1618,6 @@ version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" -[[package]] -name = "powerfmt" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" - [[package]] name = "ppv-lite86" version = "0.2.17" @@ -2176,36 +2030,6 @@ dependencies = [ "serde", ] -[[package]] -name = "serde_with" -version = "3.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee80b0e361bbf88fd2f6e242ccd19cfda072cb0faa6ae694ecee08199938569a" -dependencies = [ - "base64 0.21.7", - "chrono", - "hex", - "indexmap 1.9.3", - "indexmap 2.2.5", - "serde", - "serde_derive", - "serde_json", - "serde_with_macros", - "time", -] - -[[package]] -name = "serde_with_macros" -version = "3.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6561dc161a9224638a31d876ccdfefbc1df91d3f3a8342eddb35f055d48c7655" -dependencies = [ - "darling", - "proc-macro2", - "quote", - "syn 2.0.52", -] - [[package]] name = "sha2" version = "0.10.8" @@ -2278,12 +2102,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" -[[package]] -name = "strsim" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" - [[package]] name = "subtle" version = "2.5.0" @@ -2377,37 +2195,6 @@ dependencies = [ "syn 2.0.52", ] -[[package]] -name = "time" -version = "0.3.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8248b6521bb14bc45b4067159b9b6ad792e2d6d754d6c41fb50e29fefe38749" -dependencies = [ - "deranged", - "itoa", - "num-conv", - "powerfmt", - "serde", - "time-core", - "time-macros", -] - -[[package]] -name = "time-core" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" - -[[package]] -name = "time-macros" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ba3a3ef41e6672a2f0f001392bb5dcd3ff0a9992d618ca761a11c3121547774" -dependencies = [ - "num-conv", - "time-core", -] - [[package]] name = "tiny-keccak" version = "2.0.2" @@ -2508,7 +2295,7 @@ version = "0.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338" dependencies = [ - "indexmap 2.2.5", + "indexmap", "toml_datetime", "winnow", ] @@ -2578,32 +2365,6 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" -[[package]] -name = "tx-trie" -version = "0.1.0" -dependencies = [ - "alloy-consensus", - "alloy-eips", - "alloy-network", - "alloy-primitives", - "alloy-provider", - "alloy-rlp", - "alloy-rpc-client", - "alloy-rpc-types", - "alloy-transport", - "alloy-transport-http", - "alloy-trie", - "anyhow", - "eth_trie", - "ethereum-types", - "reqwest", - "serde", - "serde_json", - "serde_with", - "tokio", - "url", -] - [[package]] name = "typenum" version = "1.17.0" @@ -2784,15 +2545,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "windows-core" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" -dependencies = [ - "windows-targets 0.52.4", -] - [[package]] name = "windows-sys" version = "0.48.0" diff --git a/Cargo.toml b/Cargo.toml index fb5882b..f194f71 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,28 +1,32 @@ [package] -name = "tx-trie" +name = "eth-trie-proofs" version = "0.1.0" edition = "2021" +description = "Ethereum Transaction Trie Proofs" +readme = "README.md" +license-file = "LICENSE" +repository = "https://github.com/HerodotusDev/eth-trie-proofs" +keywords = ["mpt", "trie", "ethereum"] +categories = ["cryptography", "data-structures", "blockchain"] +exclude = [".github"] + # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -alloy-trie = "0.3.0" -anyhow = "1.0.81" -serde = "1.0.197" -serde_json = "1.0.114" tokio = { version = "1.36.0", features = ["rt", "rt-multi-thread", "macros"] } -alloy-network = { git = "https://github.com/alloy-rs/alloy" } -alloy-provider = { git = "https://github.com/alloy-rs/alloy" } -alloy-rpc-client = { git = "https://github.com/alloy-rs/alloy" } -alloy-rpc-types = { git = "https://github.com/alloy-rs/alloy" } -alloy-transport = { git = "https://github.com/alloy-rs/alloy" } -alloy-transport-http = { git = "https://github.com/alloy-rs/alloy" } -alloy-consensus = { git = "https://github.com/alloy-rs/alloy" } -alloy-eips = { git = "https://github.com/alloy-rs/alloy" } +# alloy is still yet stable, important to pin the revision +alloy-network = { git = "https://github.com/alloy-rs/alloy", rev = "52d16d3" } +alloy-provider = { git = "https://github.com/alloy-rs/alloy", rev = "52d16d3" } +alloy-rpc-client = { git = "https://github.com/alloy-rs/alloy", rev = "52d16d3" } +alloy-rpc-types = { git = "https://github.com/alloy-rs/alloy", rev = "52d16d3" } +alloy-transport = { git = "https://github.com/alloy-rs/alloy", rev = "52d16d3" } +alloy-transport-http = { git = "https://github.com/alloy-rs/alloy", rev = "52d16d3" } +alloy-consensus = { git = "https://github.com/alloy-rs/alloy", rev = "52d16d3" } +alloy-eips = { git = "https://github.com/alloy-rs/alloy", rev = "52d16d3" } alloy-primitives = "0.6.4" url = "2.5.0" reqwest = "0.11.26" alloy-rlp = "0.3.4" eth_trie = "0.4.0" ethereum-types = "0.14.1" -serde_with = { version = "3.7.0", features = ["hex"] } diff --git a/LICENCE b/LICENCE new file mode 100644 index 0000000..e72bfdd --- /dev/null +++ b/LICENCE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..7f358a9 --- /dev/null +++ b/README.md @@ -0,0 +1,86 @@ +![](.github/readme.png) + +# eth-trie-proofs + +A comprehensive proofs handler for Ethereum trie. Tested with various EIPs including Legacy, EIP-2930, EIP-1559, and EIP-4844. + +## Features + +- **Transaction Trie Handler** + + - [x] Build a trie with a target block number + - [x] Build a trie with a target transaction hash + - [x] Retrieve proof by transaction index + - [x] Verify proof + +- **Transaction Receipt Trie Handler** + - [x] Build a trie with a target block number + - [x] Build a trie with a target transaction hash + - [x] Retrieve proof by transaction index + - [x] Verify proof + +## Installation + +Use the following command to add `eth-trie-proofs` to your project: + +```bash +❯ cargo add eth-trie-proofs +``` + +## Example + +### Building a Transaction Trie with a Target Block Number or Target Transaction Hash + +```rust +let target_tx_hash = B256::from(hex!( + "1fcb1196d8a3bff0bcf13309d2d2bb1a23ae1ac13f5674c801be0ff9254d5ab5" +)); + +let mut txs_mpt_handler = TxsMptHandler::new(MAINNET_RPC_URL)?; + +txs_mpt_handler + .build_tx_tree_from_block(4370000) + .await?; + +let tx_index = txs_mpt_handler.tx_hash_to_tx_index(target_tx_hash)?; +let proof = txs_mpt_handler.get_proof(tx_index)?; +txs_mpt_handler + .verify_proof(tx_index, proof.clone())?; + +// You can either build with target tx hash. Both roots match. +let mut txs_mpt_handler2 = TxsMptHandler::new(MAINNET_RPC_URL)?; +txs_mpt_handler2 + .build_tx_tree_from_tx_hash(target_tx_hash) + .await?; + +assert_eq!( + txs_mpt_handler.get_root().unwrap(), + txs_mpt_handler2.get_root().unwrap() +); +``` + +### Building a Transaction Receipts Trie with a Target Block Number + +```rust +// 4844 transaction +let target_tx_hash = B256::from(hex!( + "9c1fbda4f649ac806ab0faefbe94e1a60282eb374ead6aa01bac042f52b28a8c" +)); + +let mut tx_receipts_mpt_handler = TxReceiptsMptHandler::new(MAINNET_RPC_URL)?; +tx_receipts_mpt_handler + .build_tx_receipts_tree_from_block(19426589) + .await?; + +let tx_index = tx_receipts_mpt_handler + .tx_hash_to_tx_index(target_tx_hash) + .await?; +let proof = tx_receipts_mpt_handler.get_proof(tx_index)?; +tx_receipts_mpt_handler + .verify_proof(tx_index, proof.clone())?; +``` + +### Credit + +For trie implementation, this project depends on the [eth_trie](https://crates.io/crates/eth_trie). +For transaction and transaction receipt types, heavily depends on the [alloy](https://github.com/alloy-rs/alloy). diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..3a19c61 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,42 @@ +use alloy_transport::{RpcError, TransportErrorKind}; +use eth_trie::TrieError; + +mod rpc; +pub mod tx; +pub mod tx_receipt; +pub mod tx_receipt_trie; +pub mod tx_trie; + +#[derive(Debug)] +pub enum Error { + Trie(TrieError), + Rlp(alloy_rlp::Error), + RPC(RpcError), + TxNotFound, + BlockNotFound, + InvalidTxVersion, + ConversionError(Field), + UnexpectedRoot, + InvalidMPTProof, + TrieNotFound, +} + +#[derive(Debug)] +pub enum Field { + ChainId, + Nonce, + GasPrice, + GasLimit, + Input, + AccessList, + MaxFeePerGas, + MaxPriorityFeePerGas, + MaxFeePerBlobGas, + Signature, +} + +impl From for Error { + fn from(err: TrieError) -> Self { + Error::Trie(err) + } +} diff --git a/src/main.rs b/src/main.rs deleted file mode 100644 index 69b985a..0000000 --- a/src/main.rs +++ /dev/null @@ -1,72 +0,0 @@ -mod proof; -mod rpc; -mod tx; - -use crate::tx::{ConsensusTx, RpcTx}; - -use alloy_primitives::{hex, B256}; - -use alloy_transport::{RpcError, TransportErrorKind}; -use eth_trie::TrieError; -use proof::mpt; -use rpc::RpcProvider; - -#[tokio::main] -async fn main() -> Result<(), Error> { - let provider = RpcProvider::new(); - let tx_hash = B256::from(hex!( - "ef1503cc8bd82da1552389183a097126bae21a889390a7be556b1f69d8c75c29" - )); - let height = RpcProvider::get_tx_block_height(&provider, tx_hash).await?; - let (txs, tx_root, tx_index) = provider.get_block_transactions(height, tx_hash).await?; - let converted: Vec = txs - .iter() - .map(|tx| RpcTx(tx.clone()).try_into()) - .collect::, _>>()?; - - let mut trie = mpt::build_tx_tree(converted, tx_root)?; - let proof = mpt::get_proof(&mut trie, tx_index)?; - mpt::verify_proof(&trie, tx_root, tx_index, proof.clone())?; - - let proof_obj = proof::MptProof { - proof, - tx_root, - tx_hash, - }; - println!("{}", serde_json::to_string(&proof_obj).unwrap()); - - Ok(()) -} - -#[derive(Debug)] -pub enum Error { - Trie(TrieError), - Rlp(alloy_rlp::Error), - RPC(RpcError), - TxNotFound, - BlockNotFound, - InvalidTxVersion, - ConversionError(Field), - UnexpectedRoot, - InvalidMPTProof, -} -#[derive(Debug)] -pub enum Field { - ChainId, - Nonce, - GasPrice, - GasLimit, - Input, - AccessList, - MaxFeePerGas, - MaxPriorityFeePerGas, - MaxFeePerBlobGas, - Signature, -} - -// #[cfg(test)] -// mod tests { -// 19462159 -> all tx types except 4844 -// 19460281 -> 4844 - -// } diff --git a/src/proof.rs b/src/proof.rs deleted file mode 100644 index c2acd38..0000000 --- a/src/proof.rs +++ /dev/null @@ -1,72 +0,0 @@ -use alloy_primitives::B256; -use crate::Error; -use eth_trie::TrieError; -use serde::Serialize; - -#[serde_with::serde_as] -#[derive(Serialize, Debug)] -pub struct MptProof { - #[serde_as(as = "Vec")] - pub proof: Vec>, - pub tx_root: B256, - pub tx_hash: B256, -} - -pub(crate) mod mpt { - use crate::tx::ConsensusTx; - use crate::Error; - use alloy_eips::eip2718::Encodable2718; - use alloy_primitives::{B256, U256}; - use eth_trie::{EthTrie, MemoryDB, Trie}; - use ethereum_types::H256; - use std::sync::Arc; - - pub fn build_tx_tree( - txs: Vec, - expected_root: B256, - ) -> Result, Error> { - let memdb = Arc::new(MemoryDB::new(true)); - let mut trie = EthTrie::new(memdb.clone()); - - for (idx, tx) in txs.iter().enumerate() { - let key = alloy_rlp::encode(U256::from(idx)); - let rlp = tx.0.encoded_2718(); - trie.insert(key.as_slice(), rlp.as_slice())?; - } - - if trie.root_hash()?.as_bytes() != expected_root.as_slice() { - return Err(Error::UnexpectedRoot); - } - - Ok(trie) - } - - pub fn get_proof(trie: &mut EthTrie, index: u64) -> Result>, Error> { - let key = alloy_rlp::encode(U256::from(index)); - let proof = trie.get_proof(key.as_slice())?; - - Ok(proof) - } - - pub fn verify_proof( - trie: &EthTrie, - tx_root: B256, - tx_index: u64, - proof: Vec>, - ) -> Result<(), Error> { - match trie.verify_proof( - H256::from_slice(tx_root.as_slice()), - alloy_rlp::encode(U256::from(tx_index)).as_slice(), - proof, - ) { - Ok(Some(_)) => Ok(()), - _ => Err(Error::InvalidMPTProof), - } - } -} - -impl From for Error { - fn from(err: TrieError) -> Self { - Error::Trie(err) - } -} diff --git a/src/rpc.rs b/src/rpc.rs index 9294dfc..df1ca2c 100644 --- a/src/rpc.rs +++ b/src/rpc.rs @@ -3,33 +3,27 @@ use alloy_network::Ethereum; use alloy_primitives::B256; use alloy_provider::{Provider, ProviderBuilder, RootProvider}; use alloy_rpc_client::RpcClient; -use alloy_rpc_types::{BlockTransactions, Transaction}; +use alloy_rpc_types::{BlockTransactions, Transaction, TransactionReceipt}; use alloy_transport::{RpcError, TransportErrorKind}; use alloy_transport_http::Http; use reqwest::Client; -pub struct RpcProvider { +pub(crate) struct RpcProvider { provider: RootProvider>, } impl RpcProvider { - pub fn new() -> Self { - let http = Http::::new( - "https://mainnet.infura.io/v3/da91aac0e91048b3bf3be813262d43a6" - .to_string() - .parse() - .unwrap(), - ); + pub(crate) fn new(url: &str) -> Self { + let http = Http::::new(url.to_string().parse().unwrap()); let provider = ProviderBuilder::<_, Ethereum>::new() .provider(RootProvider::new(RpcClient::new(http, true))); Self { provider } } - pub async fn get_block_transactions( + pub(crate) async fn get_block_transactions( &self, block_number: u64, - tx_hash: B256, - ) -> Result<(Vec, B256, u64), Error> { + ) -> Result<(Vec, B256), Error> { let block = self .provider .get_block(block_number.into(), true) @@ -41,15 +35,40 @@ impl RpcProvider { _ => return Err(Error::TxNotFound), }; - let tx_index = txs - .iter() - .position(|tx| tx.hash == tx_hash) - .ok_or(Error::TxNotFound)?; + Ok((txs, block.header.transactions_root)) + } + + pub(crate) async fn get_block_transaction_receipts( + &self, + block_number: u64, + ) -> Result<(Vec, B256), Error> { + let block = self + .provider + .get_block(block_number.into(), true) + .await? + .ok_or_else(|| Error::BlockNotFound)?; + + let tx_receipts = self + .provider + .get_block_receipts(block_number.into()) + .await? + .ok_or_else(|| Error::BlockNotFound)?; + + Ok((tx_receipts, block.header.receipts_root)) + } + + pub(crate) async fn get_tx_index_by_hash(&self, tx_hash: B256) -> Result { + let tx = self.provider.get_transaction_by_hash(tx_hash).await?; + + let index: u64 = match tx.transaction_index { + Some(index) => index.try_into().map_err(|_| Error::TxNotFound)?, + None => return Err(Error::TxNotFound), + }; - Ok((txs, block.header.transactions_root, tx_index as u64)) + Ok(index) } - pub async fn get_tx_block_height(&self, tx_hash: B256) -> Result { + pub(crate) async fn get_tx_block_height(&self, tx_hash: B256) -> Result { let tx = self.provider.get_transaction_by_hash(tx_hash).await?; let height: u64 = match tx.block_number { diff --git a/src/tx.rs b/src/tx.rs index 2248d17..53bb454 100644 --- a/src/tx.rs +++ b/src/tx.rs @@ -4,13 +4,22 @@ use alloy_consensus::{ }; use alloy_eips::eip2930::AccessList; use alloy_eips::eip2930::AccessListItem; +use alloy_network::eip2718::Encodable2718; use alloy_primitives::{Parity, Signature, TxKind, U64}; use alloy_rpc_types::Transaction; #[derive(Debug, Clone)] pub struct ConsensusTx(pub TxEnvelope); + +impl ConsensusTx { + pub fn rlp_encode(&self) -> Vec { + self.0.encoded_2718() + } +} + #[derive(Debug, Clone)] -pub struct RpcTx(pub Transaction); +pub(crate) struct RpcTx(pub Transaction); + impl TryFrom for ConsensusTx { type Error = Error; fn try_from(tx: RpcTx) -> Result { diff --git a/src/tx_receipt.rs b/src/tx_receipt.rs new file mode 100644 index 0000000..0ce18b1 --- /dev/null +++ b/src/tx_receipt.rs @@ -0,0 +1,111 @@ +use crate::Error; +use alloy_consensus::{Receipt, ReceiptWithBloom}; +use alloy_consensus::{ReceiptEnvelope, TxType}; + +use alloy_primitives::U64; +use alloy_primitives::{Bloom, Log, LogData, U8}; +use alloy_rpc_types::{Log as RpcLog, TransactionReceipt}; + +#[derive(Debug, Clone)] +pub struct ConsensusTxReceipt(pub ReceiptEnvelope); + +#[derive(Debug, Clone)] +pub(crate) struct RpcTxReceipt(pub TransactionReceipt); + +impl TryFrom for ConsensusTxReceipt { + type Error = Error; + fn try_from(tx: RpcTxReceipt) -> Result { + match &tx.version()? { + TxType::Legacy => { + let res = ReceiptEnvelope::Legacy(ReceiptWithBloom { + receipt: Receipt { + success: tx.success(), + cumulative_gas_used: tx.cumulative_gas_used(), + logs: tx.logs(), + }, + bloom: tx.bloom(), + }); + Ok(ConsensusTxReceipt(res)) + } + TxType::Eip2930 => { + let res = ReceiptEnvelope::Eip2930(ReceiptWithBloom { + receipt: Receipt { + success: tx.success(), + cumulative_gas_used: tx.cumulative_gas_used(), + logs: tx.logs(), + }, + bloom: tx.bloom(), + }); + Ok(ConsensusTxReceipt(res)) + } + TxType::Eip1559 => { + let res = ReceiptEnvelope::Eip1559(ReceiptWithBloom { + receipt: Receipt { + success: tx.success(), + cumulative_gas_used: tx.cumulative_gas_used(), + logs: tx.logs(), + }, + bloom: tx.bloom(), + }); + Ok(ConsensusTxReceipt(res)) + } + TxType::Eip4844 => { + let res = ReceiptEnvelope::Eip4844(ReceiptWithBloom { + receipt: Receipt { + success: tx.success(), + cumulative_gas_used: tx.cumulative_gas_used(), + logs: tx.logs(), + }, + bloom: tx.bloom(), + }); + Ok(ConsensusTxReceipt(res)) + } + } + } +} + +impl RpcTxReceipt { + fn version(&self) -> Result { + match &self.0.transaction_type { + // Legacy + tx_type if tx_type == &U8::from(0) => Ok(TxType::Legacy), + // EIP-2930 + tx_type if tx_type == &U8::from(1) => Ok(TxType::Eip2930), + // EIP-1559 + tx_type if tx_type == &U8::from(2) => Ok(TxType::Eip1559), + // EIP-4844 + tx_type if tx_type == &U8::from(3) => Ok(TxType::Eip4844), + _ => Err(Error::InvalidTxVersion), + } + } + + fn success(&self) -> bool { + match &self.0.status_code { + Some(status) => status == &U64::from(1), + None => false, + } + } + + fn cumulative_gas_used(&self) -> u64 { + self.0.cumulative_gas_used.try_into().unwrap() + } + + fn logs(&self) -> Vec> { + let mut logs = Vec::new(); + for log in &self.0.logs { + let rpc_log: RpcLog = log.clone(); + let log_data = LogData::try_from(rpc_log).unwrap(); + let result = Log { + address: log.address, + data: log_data, + }; + logs.push(result); + } + + logs + } + + fn bloom(&self) -> Bloom { + self.0.logs_bloom + } +} diff --git a/src/tx_receipt_trie.rs b/src/tx_receipt_trie.rs new file mode 100644 index 0000000..5d8a9b4 --- /dev/null +++ b/src/tx_receipt_trie.rs @@ -0,0 +1,251 @@ +use std::sync::Arc; + +use alloy_network::eip2718::Encodable2718; +use alloy_primitives::{B256, U256}; +use eth_trie::{EthTrie, MemoryDB, Trie}; +use ethereum_types::H256; + +use crate::{ + rpc::RpcProvider, + tx_receipt::{ConsensusTxReceipt, RpcTxReceipt}, + Error, +}; + +/// Represents a handler for transactions Merkle Patricia Trie (MPT) operations, +/// including building the [`TxReceiptsMpt`] from transaction receipts and fetching proofs. +pub struct TxReceiptsMptHandler { + /// Provides access to blockchain data via [`RpcProvider`]. + provider: RpcProvider, + /// Optional MPT structure to hold transaction receipts. + /// If `None`, the trie has not been built yet. + trie: Option, +} + +/// The [`TxReceiptsMpt`] struct encapsulates the MPT (Merkle Patricia Trie) specifically for transaction receipts, +/// including the trie structure itself, the [`ConsensusTxReceipt`] as elements, and the root hash. +pub struct TxReceiptsMpt { + trie: EthTrie, + elements: Vec, + root: B256, +} + +impl TxReceiptsMptHandler { + /// Creates a new [`TxReceiptsMptHandler`] with a given RPC provider URL. + /// + /// This does not initialize the trie yet. + pub fn new(url: &str) -> Result { + let provider = RpcProvider::new(url); + Ok(Self { + provider, + trie: None, + }) + } + + /// Retrieves the index of a transaction within the trie based on its hash. + /// + /// Returns an error if the trie is not found or the transaction does not exist. + pub async fn tx_hash_to_tx_index(&self, tx_hash: B256) -> Result { + let tx_index = self.provider.get_tx_index_by_hash(tx_hash).await?; + Ok(tx_index) + } + + /// Builds the transaction receipts trie from a given block number. + /// + /// This involves fetching the transactions for the block and [`build_trie`]. + pub async fn build_tx_receipts_tree_from_block( + &mut self, + block_number: u64, + ) -> Result<(), Error> { + let (txs, tx_receipt_root) = self + .provider + .get_block_transaction_receipts(block_number) + .await?; + + let converted_tx_receipts: Vec = txs + .iter() + .map(|tx_receipt| RpcTxReceipt(tx_receipt.clone()).try_into()) + .collect::, _>>() + .unwrap(); + self.build_trie(converted_tx_receipts, tx_receipt_root)?; + Ok(()) + } + + /// Constructs the MPT from a vector of [`ConsensusTxReceipt`] and an expected root hash. + /// + /// Verifies the constructed trie's root against the expected root, returning an error if they do not match. + pub fn build_trie( + &mut self, + tx_receipts: Vec, + expected_root: B256, + ) -> Result<(), Error> { + let memdb = Arc::new(MemoryDB::new(true)); + let mut trie = EthTrie::new(memdb.clone()); + + for (idx, tx) in tx_receipts.iter().enumerate() { + let key = alloy_rlp::encode(U256::from(idx)); + let rlp = tx.0.encoded_2718(); + trie.insert(key.as_slice(), rlp.as_slice())?; + } + + if trie.root_hash()?.as_bytes() != expected_root.as_slice() { + return Err(Error::UnexpectedRoot); + } + + let result_mpt = TxReceiptsMpt { + trie, + elements: tx_receipts, + root: expected_root, + }; + + self.trie = Some(result_mpt); + Ok(()) + } + + /// Generates a proof for a transaction at a given index within the trie. + pub fn get_proof(&mut self, tx_index: u64) -> Result>, Error> { + let target_trie = self.trie.as_mut().ok_or(Error::TrieNotFound)?; + let key = alloy_rlp::encode(U256::from(tx_index)); + let proof = target_trie.trie.get_proof(key.as_slice())?; + + Ok(proof) + } + + /// Verifies a proof for a transaction at a given index against the stored trie. + pub fn verify_proof(&self, tx_index: u64, proof: Vec>) -> Result<(), Error> { + let target_trie = self.trie.as_ref().ok_or(Error::TrieNotFound)?; + match target_trie.trie.verify_proof( + H256::from_slice(target_trie.root.as_slice()), + alloy_rlp::encode(U256::from(tx_index)).as_slice(), + proof, + ) { + Ok(Some(_)) => Ok(()), + _ => Err(Error::InvalidMPTProof), + } + } + + /// Retrieves a [`ConsensusTxReceipt`] by its index within the trie. + pub fn get_tx_receipt(&self, tx_index: u64) -> Result { + let target_trie = self.trie.as_ref().ok_or(Error::TrieNotFound)?; + target_trie + .elements + .get(tx_index as usize) + .ok_or(Error::TxNotFound) + .cloned() + } + + /// Retrieves all elements within the trie. + pub fn get_elements(&self) -> Result, Error> { + let target_trie = self.trie.as_ref().ok_or(Error::TrieNotFound)?; + Ok(target_trie.elements.to_vec()) + } + + /// Retrieves the root hash of the trie. + pub fn get_root(&self) -> Result { + let target_trie = self.trie.as_ref().ok_or(Error::TrieNotFound)?; + Ok(target_trie.root) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::hex; + use alloy_primitives::B256; + + const MAINNET_RPC_URL: &str = "https://mainnet.infura.io/v3/da91aac0e91048b3bf3be813262d43a6"; + + // Test cases + // Byzantium: 4370000 + // EIP-2930(Berlin): 12244000 + // EIP-1559(London): 12965000 + // EIP-4844(Dencun): 19426589 + + #[tokio::test] + async fn test_tx_receipt_byzantium() { + let target_tx_hash = B256::from(hex!( + "1fcb1196d8a3bff0bcf13309d2d2bb1a23ae1ac13f5674c801be0ff9254d5ab5" + )); + + let mut tx_receipts_mpt_handler = TxReceiptsMptHandler::new(MAINNET_RPC_URL).unwrap(); + tx_receipts_mpt_handler + .build_tx_receipts_tree_from_block(4370000) + .await + .unwrap(); + + let tx_index = tx_receipts_mpt_handler + .tx_hash_to_tx_index(target_tx_hash) + .await + .unwrap(); + let proof = tx_receipts_mpt_handler.get_proof(tx_index).unwrap(); + tx_receipts_mpt_handler + .verify_proof(tx_index, proof.clone()) + .unwrap(); + } + + #[tokio::test] + async fn test_tx_receipt_2930() { + let target_tx_hash = B256::from(hex!( + "aa40dd75b18f375df1ae9a7f7de217fa3bc49b94db3c4da7b3974130990aefef" + )); + + let mut tx_receipts_mpt_handler = TxReceiptsMptHandler::new(MAINNET_RPC_URL).unwrap(); + tx_receipts_mpt_handler + .build_tx_receipts_tree_from_block(12244000) + .await + .unwrap(); + + let tx_index = tx_receipts_mpt_handler + .tx_hash_to_tx_index(target_tx_hash) + .await + .unwrap(); + let proof = tx_receipts_mpt_handler.get_proof(tx_index).unwrap(); + tx_receipts_mpt_handler + .verify_proof(tx_index, proof.clone()) + .unwrap(); + } + + #[tokio::test] + async fn test_tx_receipt_1559() { + let target_tx_hash = B256::from(hex!( + "2055b7e01304f87f9412cd44758cd248bc2da2dab95c97026064ffb084711735" + )); + + let mut tx_receipts_mpt_handler = TxReceiptsMptHandler::new(MAINNET_RPC_URL).unwrap(); + tx_receipts_mpt_handler + .build_tx_receipts_tree_from_block(12965000) + .await + .unwrap(); + + let tx_index = tx_receipts_mpt_handler + .tx_hash_to_tx_index(target_tx_hash) + .await + .unwrap(); + let proof = tx_receipts_mpt_handler.get_proof(tx_index).unwrap(); + tx_receipts_mpt_handler + .verify_proof(tx_index, proof.clone()) + .unwrap(); + } + + #[tokio::test] + async fn test_tx_receipt_4844() { + // 4844 transaction + let target_tx_hash = B256::from(hex!( + "9c1fbda4f649ac806ab0faefbe94e1a60282eb374ead6aa01bac042f52b28a8c" + )); + + let mut tx_receipts_mpt_handler = TxReceiptsMptHandler::new(MAINNET_RPC_URL).unwrap(); + tx_receipts_mpt_handler + .build_tx_receipts_tree_from_block(19426589) + .await + .unwrap(); + + let tx_index = tx_receipts_mpt_handler + .tx_hash_to_tx_index(target_tx_hash) + .await + .unwrap(); + let proof = tx_receipts_mpt_handler.get_proof(tx_index).unwrap(); + tx_receipts_mpt_handler + .verify_proof(tx_index, proof.clone()) + .unwrap(); + } +} diff --git a/src/tx_trie.rs b/src/tx_trie.rs new file mode 100644 index 0000000..a73e29c --- /dev/null +++ b/src/tx_trie.rs @@ -0,0 +1,327 @@ +use std::sync::Arc; + +use alloy_network::eip2718::Encodable2718; +use alloy_primitives::{B256, U256}; +use eth_trie::{EthTrie, MemoryDB, Trie as _}; +use ethereum_types::H256; + +use crate::{ + rpc::RpcProvider, + tx::{ConsensusTx, RpcTx}, + Error, +}; + +/// Represents a handler for transactions Merkle Patricia Trie (MPT) operations, +/// including building the [`TxsMpt`] from transactions and fetching proofs. +pub struct TxsMptHandler { + /// Provides access to blockchain data via [`RpcProvider`]. + provider: RpcProvider, + /// Optional MPT structure to hold transactions. + /// If `None`, the trie has not been built yet. + trie: Option, +} + +/// The [`TxsMpt`] struct encapsulates the MPT (Merkle Patricia Trie) specifically for transactions, +/// including the trie structure itself, the [`ConsensusTx`] as elements, and the root hash. +pub struct TxsMpt { + trie: EthTrie, + elements: Vec, + root: B256, +} + +impl TxsMptHandler { + /// Creates a new [`TxsMptHandler`] with a given RPC provider URL. + /// + /// This does not initialize the trie yet. + pub fn new(url: &str) -> Result { + let provider = RpcProvider::new(url); + Ok(Self { + provider, + trie: None, + }) + } + + /// Retrieves the index of a transaction within the trie based on its hash. + /// + /// Returns an error if the trie is not found or the transaction does not exist. + pub fn tx_hash_to_tx_index(&self, tx_hash: B256) -> Result { + let target_trie = self.trie.as_ref().ok_or(Error::TrieNotFound)?; + let tx_index = target_trie + .elements + .iter() + .position(|tx| tx.0.trie_hash() == tx_hash) + .ok_or(Error::TxNotFound)?; + Ok(tx_index as u64) + } + + /// Builds the transaction trie from a specific transaction hash. + /// + /// This fetches the block height for the transaction and delegates to [`build_tx_tree_from_block`]. + pub async fn build_tx_tree_from_tx_hash(&mut self, tx_hash: B256) -> Result<(), Error> { + let height = self.provider.get_tx_block_height(tx_hash).await?; + self.build_tx_tree_from_block(height).await?; + Ok(()) + } + + /// Builds the transactions trie from a given block number. + /// + /// This involves fetching the transactions for the block and [`build_trie`]. + pub async fn build_tx_tree_from_block(&mut self, block_number: u64) -> Result<(), Error> { + let (txs, tx_root) = self.provider.get_block_transactions(block_number).await?; + let converted_txs: Vec = txs + .iter() + .map(|tx| RpcTx(tx.clone()).try_into()) + .collect::, _>>() + .unwrap(); + self.build_trie(converted_txs, tx_root)?; + Ok(()) + } + + /// Constructs the MPT from a vector of [`ConsensusTx`] and an expected root hash. + /// + /// Verifies the constructed trie's root against the expected root, returning an error if they do not match. + pub fn build_trie(&mut self, txs: Vec, expected_root: B256) -> Result<(), Error> { + let memdb = Arc::new(MemoryDB::new(true)); + let mut trie = EthTrie::new(memdb.clone()); + + for (idx, tx) in txs.iter().enumerate() { + let key = alloy_rlp::encode(U256::from(idx)); + let rlp = tx.0.encoded_2718(); + trie.insert(key.as_slice(), rlp.as_slice())?; + } + + if trie.root_hash()?.as_bytes() != expected_root.as_slice() { + return Err(Error::UnexpectedRoot); + } + + let result_mpt = TxsMpt { + trie, + elements: txs, + root: expected_root, + }; + + self.trie = Some(result_mpt); + Ok(()) + } + + /// Generates a proof for a transaction at a given index within the trie. + pub fn get_proof(&mut self, tx_index: u64) -> Result>, Error> { + let target_trie = self.trie.as_mut().ok_or(Error::TrieNotFound)?; + let key = alloy_rlp::encode(U256::from(tx_index)); + let proof = target_trie.trie.get_proof(key.as_slice())?; + + Ok(proof) + } + + /// Verifies a proof for a transaction at a given index against the stored trie. + pub fn verify_proof(&self, tx_index: u64, proof: Vec>) -> Result<(), Error> { + let target_trie = self.trie.as_ref().ok_or(Error::TrieNotFound)?; + match target_trie.trie.verify_proof( + H256::from_slice(target_trie.root.as_slice()), + alloy_rlp::encode(U256::from(tx_index)).as_slice(), + proof, + ) { + Ok(Some(_)) => Ok(()), + _ => Err(Error::InvalidMPTProof), + } + } + + /// Retrieves a [`ConsensusTx`] by its index within the trie. + pub fn get_tx(&self, tx_index: u64) -> Result { + let target_trie = self.trie.as_ref().ok_or(Error::TrieNotFound)?; + target_trie + .elements + .get(tx_index as usize) + .ok_or(Error::TxNotFound) + .cloned() + } + + /// Retrieves all elements within the trie. + pub fn get_elements(&self) -> Result, Error> { + let target_trie = self.trie.as_ref().ok_or(Error::TrieNotFound)?; + Ok(target_trie.elements.to_vec()) + } + + /// Retrieves the root hash of the trie. + pub fn get_root(&self) -> Result { + let target_trie = self.trie.as_ref().ok_or(Error::TrieNotFound)?; + Ok(target_trie.root) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::hex; + use alloy_primitives::B256; + + const MAINNET_RPC_URL: &str = "https://mainnet.infura.io/v3/da91aac0e91048b3bf3be813262d43a6"; + + // Test cases + // Frontier: 46147 + // Byzantium: 4370000 + // EIP-2930(Berlin): 12244000 + // EIP-1559(London): 12965000 + // EIP-4844(Dencun): 19426589 + + #[tokio::test] + async fn test_tx_mpt_frontier() { + let target_tx_hash = B256::from(hex!( + "5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060" + )); + + let mut txs_mpt_handler = TxsMptHandler::new(MAINNET_RPC_URL).unwrap(); + + txs_mpt_handler + .build_tx_tree_from_block(46147) + .await + .unwrap(); + + let tx_index = txs_mpt_handler.tx_hash_to_tx_index(target_tx_hash).unwrap(); + let proof = txs_mpt_handler.get_proof(tx_index).unwrap(); + txs_mpt_handler + .verify_proof(tx_index, proof.clone()) + .unwrap(); + + let mut txs_mpt_handler2 = TxsMptHandler::new(MAINNET_RPC_URL).unwrap(); + + txs_mpt_handler2 + .build_tx_tree_from_tx_hash(target_tx_hash) + .await + .unwrap(); + + assert_eq!( + txs_mpt_handler.get_root().unwrap(), + txs_mpt_handler2.get_root().unwrap() + ); + } + + #[tokio::test] + async fn test_tx_mpt_byzantium() { + let target_tx_hash = B256::from(hex!( + "1fcb1196d8a3bff0bcf13309d2d2bb1a23ae1ac13f5674c801be0ff9254d5ab5" + )); + + let mut txs_mpt_handler = TxsMptHandler::new(MAINNET_RPC_URL).unwrap(); + + txs_mpt_handler + .build_tx_tree_from_block(4370000) + .await + .unwrap(); + + let tx_index = txs_mpt_handler.tx_hash_to_tx_index(target_tx_hash).unwrap(); + let proof = txs_mpt_handler.get_proof(tx_index).unwrap(); + txs_mpt_handler + .verify_proof(tx_index, proof.clone()) + .unwrap(); + + let mut txs_mpt_handler2 = TxsMptHandler::new(MAINNET_RPC_URL).unwrap(); + + txs_mpt_handler2 + .build_tx_tree_from_tx_hash(target_tx_hash) + .await + .unwrap(); + + assert_eq!( + txs_mpt_handler.get_root().unwrap(), + txs_mpt_handler2.get_root().unwrap() + ); + } + + #[tokio::test] + async fn test_tx_mpt_2930() { + let target_tx_hash = B256::from(hex!( + "aa40dd75b18f375df1ae9a7f7de217fa3bc49b94db3c4da7b3974130990aefef" + )); + + let mut txs_mpt_handler = TxsMptHandler::new(MAINNET_RPC_URL).unwrap(); + + txs_mpt_handler + .build_tx_tree_from_block(12244000) + .await + .unwrap(); + + let tx_index = txs_mpt_handler.tx_hash_to_tx_index(target_tx_hash).unwrap(); + let proof = txs_mpt_handler.get_proof(tx_index).unwrap(); + txs_mpt_handler + .verify_proof(tx_index, proof.clone()) + .unwrap(); + + let mut txs_mpt_handler2 = TxsMptHandler::new(MAINNET_RPC_URL).unwrap(); + + txs_mpt_handler2 + .build_tx_tree_from_tx_hash(target_tx_hash) + .await + .unwrap(); + + assert_eq!( + txs_mpt_handler.get_root().unwrap(), + txs_mpt_handler2.get_root().unwrap() + ); + } + + #[tokio::test] + async fn test_tx_mpt_1559() { + let target_tx_hash = B256::from(hex!( + "2055b7e01304f87f9412cd44758cd248bc2da2dab95c97026064ffb084711735" + )); + + let mut txs_mpt_handler = TxsMptHandler::new(MAINNET_RPC_URL).unwrap(); + + txs_mpt_handler + .build_tx_tree_from_block(12965000) + .await + .unwrap(); + + let tx_index = txs_mpt_handler.tx_hash_to_tx_index(target_tx_hash).unwrap(); + let proof = txs_mpt_handler.get_proof(tx_index).unwrap(); + txs_mpt_handler + .verify_proof(tx_index, proof.clone()) + .unwrap(); + + let mut txs_mpt_handler2 = TxsMptHandler::new(MAINNET_RPC_URL).unwrap(); + + txs_mpt_handler2 + .build_tx_tree_from_tx_hash(target_tx_hash) + .await + .unwrap(); + + assert_eq!( + txs_mpt_handler.get_root().unwrap(), + txs_mpt_handler2.get_root().unwrap() + ); + } + + #[tokio::test] + async fn test_tx_mpt_4844() { + // 4844 transaction + let target_tx_hash = B256::from(hex!( + "9c1fbda4f649ac806ab0faefbe94e1a60282eb374ead6aa01bac042f52b28a8c" + )); + + let mut txs_mpt_handler = TxsMptHandler::new(MAINNET_RPC_URL).unwrap(); + + txs_mpt_handler + .build_tx_tree_from_block(19426589) + .await + .unwrap(); + + let tx_index = txs_mpt_handler.tx_hash_to_tx_index(target_tx_hash).unwrap(); + let proof = txs_mpt_handler.get_proof(tx_index).unwrap(); + txs_mpt_handler + .verify_proof(tx_index, proof.clone()) + .unwrap(); + + let mut txs_mpt_handler2 = TxsMptHandler::new(MAINNET_RPC_URL).unwrap(); + + txs_mpt_handler2 + .build_tx_tree_from_tx_hash(target_tx_hash) + .await + .unwrap(); + + assert_eq!( + txs_mpt_handler.get_root().unwrap(), + txs_mpt_handler2.get_root().unwrap() + ); + } +}