From 167bbca10441ad0d592328bbe2df4b799224dcea Mon Sep 17 00:00:00 2001 From: polydez <155382956+polydez@users.noreply.github.com> Date: Tue, 8 Oct 2024 13:19:52 +0500 Subject: [PATCH] feat(faucet): migrate to axum from actix (#511) --- CHANGELOG.md | 3 +- Cargo.lock | 585 ++++--------------------------------- Cargo.toml | 2 +- bin/faucet/Cargo.toml | 12 +- bin/faucet/src/client.rs | 73 +++-- bin/faucet/src/config.rs | 6 - bin/faucet/src/errors.rs | 69 +++-- bin/faucet/src/handlers.rs | 83 ++++-- bin/faucet/src/main.rs | 88 +++--- bin/faucet/src/state.rs | 19 +- 10 files changed, 266 insertions(+), 674 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ee919517..b9bd903ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,8 @@ - Improve `--version` by adding build metadata (#495). - [BREAKING] Introduced additional limits for note/account number (#503). - [BREAKING] Removed support for basic wallets in genesis creation (#510). -- Added `GetAccountStates` endpoint (#506). +- Added `GetAccountProofs` endpoint (#506). +- Migrated faucet from actix-web to axum (#511). ## 0.5.1 (2024-09-12) diff --git a/Cargo.lock b/Cargo.lock index cf34633e8..e110537a5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,216 +2,6 @@ # It is not intended for manual editing. version = 3 -[[package]] -name = "actix-codec" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f7b0a21988c1bf877cf4759ef5ddaac04c1c9fe808c9142ecb78ba97d97a28a" -dependencies = [ - "bitflags", - "bytes", - "futures-core", - "futures-sink", - "memchr", - "pin-project-lite", - "tokio", - "tokio-util", - "tracing", -] - -[[package]] -name = "actix-cors" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9e772b3bcafe335042b5db010ab7c09013dad6eac4915c91d8d50902769f331" -dependencies = [ - "actix-utils", - "actix-web", - "derive_more", - "futures-util", - "log", - "once_cell", - "smallvec", -] - -[[package]] -name = "actix-http" -version = "3.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d48f96fc3003717aeb9856ca3d02a8c7de502667ad76eeacd830b48d2e91fac4" -dependencies = [ - "actix-codec", - "actix-rt", - "actix-service", - "actix-utils", - "ahash", - "base64", - "bitflags", - "brotli", - "bytes", - "bytestring", - "derive_more", - "encoding_rs", - "flate2", - "futures-core", - "h2 0.3.26", - "http 0.2.12", - "httparse", - "httpdate", - "itoa", - "language-tags", - "local-channel", - "mime", - "percent-encoding", - "pin-project-lite", - "rand", - "sha1", - "smallvec", - "tokio", - "tokio-util", - "tracing", - "zstd", -] - -[[package]] -name = "actix-macros" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e01ed3140b2f8d422c68afa1ed2e85d996ea619c988ac834d255db32138655cb" -dependencies = [ - "quote", - "syn", -] - -[[package]] -name = "actix-router" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13d324164c51f63867b57e73ba5936ea151b8a41a1d23d1031eeb9f70d0236f8" -dependencies = [ - "bytestring", - "cfg-if", - "http 0.2.12", - "regex", - "regex-lite", - "serde", - "tracing", -] - -[[package]] -name = "actix-rt" -version = "2.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24eda4e2a6e042aa4e55ac438a2ae052d3b5da0ecf83d7411e1a368946925208" -dependencies = [ - "futures-core", - "tokio", -] - -[[package]] -name = "actix-server" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ca2549781d8dd6d75c40cf6b6051260a2cc2f3c62343d761a969a0640646894" -dependencies = [ - "actix-rt", - "actix-service", - "actix-utils", - "futures-core", - "futures-util", - "mio", - "socket2", - "tokio", - "tracing", -] - -[[package]] -name = "actix-service" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b894941f818cfdc7ccc4b9e60fa7e53b5042a2e8567270f9147d5591893373a" -dependencies = [ - "futures-core", - "paste", - "pin-project-lite", -] - -[[package]] -name = "actix-utils" -version = "3.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88a1dcdff1466e3c2488e1cb5c36a71822750ad43839937f85d2f4d9f8b705d8" -dependencies = [ - "local-waker", - "pin-project-lite", -] - -[[package]] -name = "actix-web" -version = "4.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9180d76e5cc7ccbc4d60a506f2c727730b154010262df5b910eb17dbe4b8cb38" -dependencies = [ - "actix-codec", - "actix-http", - "actix-macros", - "actix-router", - "actix-rt", - "actix-server", - "actix-service", - "actix-utils", - "actix-web-codegen", - "ahash", - "bytes", - "bytestring", - "cfg-if", - "cookie", - "derive_more", - "encoding_rs", - "futures-core", - "futures-util", - "impl-more", - "itoa", - "language-tags", - "log", - "mime", - "once_cell", - "pin-project-lite", - "regex", - "regex-lite", - "serde", - "serde_json", - "serde_urlencoded", - "smallvec", - "socket2", - "time", - "url", -] - -[[package]] -name = "actix-web-codegen" -version = "4.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f591380e2e68490b5dfaf1dd1aa0ebe78d84ba7067078512b4ea6e4492d622b8" -dependencies = [ - "actix-router", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "actix-web-static-files" -version = "4.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adf6d1ef6d7a60e084f9e0595e2a5234abda14e76c105ecf8e2d0e8800c41a1f" -dependencies = [ - "actix-web", - "derive_more", - "futures-util", - "static-files", -] - [[package]] name = "addr2line" version = "0.24.1" @@ -234,7 +24,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" dependencies = [ "cfg-if", - "getrandom", "once_cell", "version_check", "zerocopy", @@ -249,21 +38,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "alloc-no-stdlib" -version = "2.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" - -[[package]] -name = "alloc-stdlib" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" -dependencies = [ - "alloc-no-stdlib", -] - [[package]] name = "android-tzdata" version = "0.1.1" @@ -355,15 +129,6 @@ dependencies = [ "term", ] -[[package]] -name = "async-mutex" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479db852db25d9dbf6204e6cb6253698f175c15726470f78af0d918e99d6156e" -dependencies = [ - "event-listener", -] - [[package]] name = "async-stream" version = "0.3.5" @@ -420,17 +185,19 @@ checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" [[package]] name = "axum" -version = "0.7.6" +version = "0.7.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f43644eed690f5374f1af436ecd6aea01cd201f6fbdf0178adaf6907afb2cec" +checksum = "504e3947307ac8326a5437504c517c4b56716c9d98fac0028c2acc7ca47d70ae" dependencies = [ "async-trait", "axum-core", "bytes", "futures-util", - "http 1.1.0", + "http", "http-body", "http-body-util", + "hyper", + "hyper-util", "itoa", "matchit", "memchr", @@ -439,22 +206,27 @@ dependencies = [ "pin-project-lite", "rustversion", "serde", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", "sync_wrapper 1.0.1", + "tokio", "tower 0.5.1", "tower-layer", "tower-service", + "tracing", ] [[package]] name = "axum-core" -version = "0.4.4" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e6b8ba012a258d63c9adfa28b9ddcf66149da6f986c5b5452e629d5ee64bf00" +checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199" dependencies = [ "async-trait", "bytes", "futures-util", - "http 1.1.0", + "http", "http-body", "http-body-util", "mime", @@ -463,6 +235,7 @@ dependencies = [ "sync_wrapper 1.0.1", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -564,27 +337,6 @@ dependencies = [ "generic-array", ] -[[package]] -name = "brotli" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74f7971dbd9326d58187408ab83117d8ac1bb9c17b085fdacd1cf2f598719b6b" -dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", - "brotli-decompressor", -] - -[[package]] -name = "brotli-decompressor" -version = "4.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a45bd2e4095a8b518033b128020dd4a55aab1c0a381ba4404a472630f4bc362" -dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", -] - [[package]] name = "bumpalo" version = "3.16.0" @@ -609,15 +361,6 @@ version = "1.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "428d9aa8fbc0670b7b8d6030a7fadd0f86151cae55e4dbbece15f3780a3dfaf3" -[[package]] -name = "bytestring" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74d80203ea6b29df88012294f62733de21cfeab47f17b41af3a38bc30a03ee72" -dependencies = [ - "bytes", -] - [[package]] name = "camino" version = "1.1.9" @@ -763,23 +506,6 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6" -[[package]] -name = "convert_case" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" - -[[package]] -name = "cookie" -version = "0.16.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e859cd57d0710d9e06c381b550c06e76992472a8c6d527aecd2fc673dcc231fb" -dependencies = [ - "percent-encoding", - "time", - "version_check", -] - [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -795,15 +521,6 @@ dependencies = [ "libc", ] -[[package]] -name = "crc32fast" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" -dependencies = [ - "cfg-if", -] - [[package]] name = "crossbeam-deque" version = "0.8.5" @@ -960,19 +677,6 @@ dependencies = [ "syn", ] -[[package]] -name = "derive_more" -version = "0.99.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f33878137e4dafd7fa914ad4e259e18a4e8e532b9617a2d0150262bf53abfce" -dependencies = [ - "convert_case", - "proc-macro2", - "quote", - "rustc_version 0.4.1", - "syn", -] - [[package]] name = "digest" version = "0.10.7" @@ -1046,15 +750,6 @@ dependencies = [ "log", ] -[[package]] -name = "encoding_rs" -version = "0.8.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b45de904aa0b010bce2ab45264d0631681847fa7b6f2eaa7dab7619943bc4f59" -dependencies = [ - "cfg-if", -] - [[package]] name = "equivalent" version = "1.0.1" @@ -1071,12 +766,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "event-listener" -version = "2.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" - [[package]] name = "fallible-iterator" version = "0.3.0" @@ -1117,16 +806,6 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" -[[package]] -name = "flate2" -version = "1.0.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1b589b4dc103969ad3cf85c950899926ec64300a1a46d76c03a6072957036f0" -dependencies = [ - "crc32fast", - "miniz_oxide", -] - [[package]] name = "fnv" version = "1.0.7" @@ -1201,7 +880,6 @@ dependencies = [ "futures-task", "pin-project-lite", "pin-utils", - "slab", ] [[package]] @@ -1250,25 +928,6 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" -[[package]] -name = "h2" -version = "0.3.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81fe527a889e1532da5c525686d96d4c2e74cdd345badf8dfef9f6b39dd5f5e8" -dependencies = [ - "bytes", - "fnv", - "futures-core", - "futures-sink", - "futures-util", - "http 0.2.12", - "indexmap 2.5.0", - "slab", - "tokio", - "tokio-util", - "tracing", -] - [[package]] name = "h2" version = "0.4.6" @@ -1280,7 +939,7 @@ dependencies = [ "fnv", "futures-core", "futures-sink", - "http 1.1.0", + "http", "indexmap 2.5.0", "slab", "tokio", @@ -1330,17 +989,6 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" -[[package]] -name = "http" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - [[package]] name = "http" version = "1.1.0" @@ -1359,7 +1007,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" dependencies = [ "bytes", - "http 1.1.0", + "http", ] [[package]] @@ -1370,7 +1018,7 @@ checksum = "793429d76616a256bcb62c2a2ec2bed781c8307e797e2598c50010f2bee2544f" dependencies = [ "bytes", "futures-util", - "http 1.1.0", + "http", "http-body", "pin-project-lite", ] @@ -1396,8 +1044,8 @@ dependencies = [ "bytes", "futures-channel", "futures-util", - "h2 0.4.6", - "http 1.1.0", + "h2", + "http", "http-body", "httparse", "httpdate", @@ -1430,7 +1078,7 @@ dependencies = [ "bytes", "futures-channel", "futures-util", - "http 1.1.0", + "http", "http-body", "hyper", "pin-project-lite", @@ -1469,22 +1117,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" -[[package]] -name = "idna" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6" -dependencies = [ - "unicode-bidi", - "unicode-normalization", -] - -[[package]] -name = "impl-more" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "206ca75c9c03ba3d4ace2460e57b189f39f43de612c2f85836e65c929701bb2d" - [[package]] name = "indenter" version = "0.3.3" @@ -1616,12 +1248,6 @@ version = "0.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "507460a910eb7b32ee961886ff48539633b788a36b65692b95f225b844c82553" -[[package]] -name = "language-tags" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4345964bb142484797b161f473a503a434de77149dd8c7427788c6e13379388" - [[package]] name = "lazy_static" version = "1.5.0" @@ -1684,23 +1310,6 @@ version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" -[[package]] -name = "local-channel" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6cbc85e69b8df4b8bb8b89ec634e7189099cea8927a276b7384ce5488e53ec8" -dependencies = [ - "futures-core", - "futures-sink", - "local-waker", -] - -[[package]] -name = "local-waker" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d873d7c67ce09b42110d801813efbc9364414e356be9935700d368351657487" - [[package]] name = "lock_api" version = "0.4.12" @@ -1857,25 +1466,27 @@ dependencies = [ name = "miden-faucet" version = "0.6.0" dependencies = [ - "actix-cors", - "actix-web", - "actix-web-static-files", - "async-mutex", + "axum", "clap", - "derive_more", "figment", + "http", + "http-body-util", "miden-lib", "miden-node-proto", "miden-node-utils", "miden-objects", "miden-tx", + "mime", "rand", "rand_chacha", "serde", "static-files", "thiserror", + "tokio", "toml", "tonic", + "tower 0.5.1", + "tower-http 0.6.1", "tracing", ] @@ -2250,7 +1861,6 @@ checksum = "80e04d1dcff3aae0704555fe5fee3bcfaf3d1fdf8a7e521d5b9d2b42acb52cec" dependencies = [ "hermit-abi", "libc", - "log", "wasi", "windows-sys 0.52.0", ] @@ -2453,12 +2063,6 @@ dependencies = [ "windows-targets 0.52.6", ] -[[package]] -name = "paste" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" - [[package]] name = "path-matchers" version = "1.0.2" @@ -2852,12 +2456,6 @@ dependencies = [ "regex-syntax 0.8.4", ] -[[package]] -name = "regex-lite" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53a49587ad06b26609c52e423de037e7f57f20d53535d66e08c695f347df952a" - [[package]] name = "regex-syntax" version = "0.6.29" @@ -3038,6 +2636,16 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af99884400da37c88f5e9146b7f1fd0fbcae8f6eec4e9da38b67d05486f814a6" +dependencies = [ + "itoa", + "serde", +] + [[package]] name = "serde_spanned" version = "0.6.8" @@ -3059,17 +2667,6 @@ dependencies = [ "serde", ] -[[package]] -name = "sha1" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" -dependencies = [ - "cfg-if", - "cpufeatures", - "digest", -] - [[package]] name = "sha3" version = "0.10.8" @@ -3095,15 +2692,6 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" -[[package]] -name = "signal-hook-registry" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" -dependencies = [ - "libc", -] - [[package]] name = "siphasher" version = "0.3.11" @@ -3356,21 +2944,6 @@ dependencies = [ "crunchy", ] -[[package]] -name = "tinyvec" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "445e881f4f6d382d5f27c034e25eb92edd7c784ceab92a0937db7f2e9471b938" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" - [[package]] name = "tokio" version = "1.40.0" @@ -3381,9 +2954,7 @@ dependencies = [ "bytes", "libc", "mio", - "parking_lot", "pin-project-lite", - "signal-hook-registry", "socket2", "tokio-macros", "windows-sys 0.52.0", @@ -3469,8 +3040,8 @@ dependencies = [ "axum", "base64", "bytes", - "h2 0.4.6", - "http 1.1.0", + "h2", + "http", "http-body", "http-body-util", "hyper", @@ -3510,13 +3081,13 @@ checksum = "5299dd20801ad736dccb4a5ea0da7376e59cd98f213bf1c3d478cf53f4834b58" dependencies = [ "base64", "bytes", - "http 1.1.0", + "http", "http-body", "http-body-util", "pin-project", "tokio-stream", "tonic", - "tower-http", + "tower-http 0.5.2", "tower-layer", "tower-service", "tracing", @@ -3552,8 +3123,10 @@ dependencies = [ "futures-util", "pin-project-lite", "sync_wrapper 0.1.2", + "tokio", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -3564,7 +3137,7 @@ checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5" dependencies = [ "bitflags", "bytes", - "http 1.1.0", + "http", "http-body", "http-body-util", "pin-project-lite", @@ -3572,6 +3145,22 @@ dependencies = [ "tower-service", ] +[[package]] +name = "tower-http" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8437150ab6bbc8c5f0f519e3d5ed4aa883a83dd4cdd3d1b21f9482936046cb97" +dependencies = [ + "bitflags", + "bytes", + "http", + "http-body", + "pin-project-lite", + "tower-layer", + "tower-service", + "tracing", +] + [[package]] name = "tower-layer" version = "0.3.3" @@ -3723,12 +3312,6 @@ dependencies = [ "version_check", ] -[[package]] -name = "unicode-bidi" -version = "0.3.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75" - [[package]] name = "unicode-ident" version = "1.0.13" @@ -3741,15 +3324,6 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" -[[package]] -name = "unicode-normalization" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5033c97c4262335cded6d6fc3e5c18ab755e1a3dc96376350f3d8e9f009ad956" -dependencies = [ - "tinyvec", -] - [[package]] name = "unicode-width" version = "0.1.14" @@ -3762,17 +3336,6 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" -[[package]] -name = "url" -version = "2.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22784dbdf76fdde8af1aeda5622b546b422b6fc585325248a2bf9f5e41e94d6c" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", -] - [[package]] name = "utf8parse" version = "0.2.2" @@ -4357,31 +3920,3 @@ dependencies = [ "quote", "syn", ] - -[[package]] -name = "zstd" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcf2b778a664581e31e389454a7072dab1647606d44f7feea22cd5abb9c9f3f9" -dependencies = [ - "zstd-safe", -] - -[[package]] -name = "zstd-safe" -version = "7.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54a3ab4db68cea366acc5c897c7b4d4d1b8994a9cd6e6f841f8964566a419059" -dependencies = [ - "zstd-sys", -] - -[[package]] -name = "zstd-sys" -version = "2.0.13+zstd.1.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38ff0f21cfee8f97d94cef41359e0c89aa6113028ab0291aa8ca0038995a95aa" -dependencies = [ - "cc", - "pkg-config", -] diff --git a/Cargo.toml b/Cargo.toml index 7e2f0c5cc..656515f39 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,7 +41,7 @@ miden-stdlib = { version = "0.10", default-features = false } miden-tx = { git = "https://github.com/0xPolygonMiden/miden-base.git", branch = "next" } prost = { version = "0.13" } thiserror = { version = "1.0" } -tokio = { version = "1.40" } +tokio = { version = "1.40", features = ["rt-multi-thread"] } tokio-stream = { version = "0.1" } tonic = { version = "0.12" } tracing = { version = "0.1" } diff --git a/bin/faucet/Cargo.toml b/bin/faucet/Cargo.toml index f08e37729..fc03a81ad 100644 --- a/bin/faucet/Cargo.toml +++ b/bin/faucet/Cargo.toml @@ -17,25 +17,27 @@ repository.workspace = true testing = ["miden-objects/testing", "miden-lib/testing"] [dependencies] -actix-cors = "0.7" -actix-web = "4.8" -actix-web-static-files = "4.0" -async-mutex = "1.4" +axum = { version = "0.7", features = ["tokio"] } clap = { version = "4.5", features = ["derive", "string"] } -derive_more = "0.99" figment = { version = "0.10", features = ["toml", "env"] } +http = "1.1" +http-body-util = "0.1" miden-lib = { workspace = true, features = ["concurrent"] } miden-node-proto = { workspace = true } miden-node-utils = { workspace = true } miden-objects = { workspace = true , features = ["concurrent"] } miden-tx = { workspace = true, features = ["concurrent"] } +mime = "0.3" rand = { version = "0.8" } rand_chacha = "0.3" serde = { version = "1.0", features = ["derive"] } static-files = "0.2" thiserror = { workspace = true } +tokio = { workspace = true } toml = { version = "0.8" } tonic = { workspace = true } +tower = "0.5" +tower-http = { version = "0.6", features = ["cors", "set-header", "trace"] } tracing = { workspace = true } [build-dependencies] diff --git a/bin/faucet/src/client.rs b/bin/faucet/src/client.rs index 595709b5c..d02f4a138 100644 --- a/bin/faucet/src/client.rs +++ b/bin/faucet/src/client.rs @@ -30,7 +30,10 @@ use rand::{rngs::StdRng, thread_rng, Rng}; use rand_chacha::{rand_core::SeedableRng, ChaCha20Rng}; use tonic::transport::Channel; -use crate::{config::FaucetConfig, errors::FaucetError}; +use crate::{ + config::FaucetConfig, + errors::{InitError, ProcessError}, +}; pub const DISTRIBUTE_FUNGIBLE_ASSET_SCRIPT: &str = include_str!("transaction_scripts/distribute_fungible_asset.masm"); @@ -52,7 +55,7 @@ unsafe impl Send for FaucetClient {} unsafe impl Sync for FaucetClient {} impl FaucetClient { - pub async fn new(config: FaucetConfig) -> Result { + pub async fn new(config: FaucetConfig) -> Result { let (rpc_api, root_block_header, root_chain_mmr) = initialize_faucet_client(config.clone()).await?; @@ -87,9 +90,9 @@ impl FaucetClient { target_account_id: AccountId, is_private_note: bool, asset_amount: u64, - ) -> Result<(ExecutedTransaction, Note), FaucetError> { + ) -> Result<(ExecutedTransaction, Note), ProcessError> { let asset = FungibleAsset::new(self.id, asset_amount) - .map_err(|err| FaucetError::InternalServerError(err.to_string()))?; + .map_err(|err| ProcessError::InternalServerError(err.to_string()))?; let note_type = if is_private_note { NoteType::Private @@ -105,7 +108,7 @@ impl FaucetClient { Default::default(), &mut self.rng, ) - .map_err(|err| FaucetError::InternalServerError(err.to_string()))?; + .map_err(|err| ProcessError::InternalServerError(err.to_string()))?; let transaction_args = build_transaction_arguments(&output_note, note_type, asset)?; @@ -113,7 +116,7 @@ impl FaucetClient { .executor .execute_transaction(self.id, 0, &[], transaction_args) .map_err(|err| { - FaucetError::InternalServerError(format!("Failed to execute transaction: {}", err)) + ProcessError::InternalServerError(format!("Failed to execute transaction: {err}")) })?; Ok((executed_tx, output_note)) @@ -123,27 +126,32 @@ impl FaucetClient { pub async fn prove_and_submit_transaction( &mut self, executed_tx: ExecutedTransaction, - ) -> Result { - let transaction_prover = LocalTransactionProver::new(ProvingOptions::default()); - + ) -> Result { let delta = executed_tx.account_delta().clone(); - let proven_transaction = transaction_prover.prove(executed_tx).map_err(|err| { - FaucetError::InternalServerError(format!("Failed to prove transaction: {}", err)) - })?; + // Prepare request with proven transaction. + // This is needed to be in a separated code block in order to release reference to avoid + // borrow checker error. + let request = { + let transaction_prover = LocalTransactionProver::new(ProvingOptions::default()); - let request = SubmitProvenTransactionRequest { - transaction: proven_transaction.to_bytes(), + let proven_transaction = transaction_prover.prove(executed_tx).map_err(|err| { + ProcessError::InternalServerError(format!("Failed to prove transaction: {err}")) + })?; + + SubmitProvenTransactionRequest { + transaction: proven_transaction.to_bytes(), + } }; let response = self .rpc_api .submit_proven_transaction(request) .await - .map_err(|err| FaucetError::InternalServerError(err.to_string()))?; + .map_err(|err| ProcessError::InternalServerError(err.to_string()))?; self.data_store.update_faucet_account(&delta).map_err(|err| { - FaucetError::InternalServerError(format!("Failed to update account: {}", err)) + ProcessError::InternalServerError(format!("Failed to update account: {err}")) })?; Ok(response.into_inner().block_height) @@ -181,11 +189,11 @@ impl FaucetDataStore { } /// Updates the stored faucet account with the provided delta. - fn update_faucet_account(&mut self, delta: &AccountDelta) -> Result<(), FaucetError> { + fn update_faucet_account(&mut self, delta: &AccountDelta) -> Result<(), ProcessError> { self.faucet_account .borrow_mut() .apply_delta(delta) - .map_err(|err| FaucetError::InternalServerError(err.to_string())) + .map_err(|err| ProcessError::InternalServerError(err.to_string())) } } @@ -221,13 +229,13 @@ impl DataStore for FaucetDataStore { /// Builds a new faucet account with the provided configuration. /// /// Returns the created account, its seed, and the secret key used to sign transactions. -fn build_account(config: FaucetConfig) -> Result<(Account, Word, SecretKey), FaucetError> { +fn build_account(config: FaucetConfig) -> Result<(Account, Word, SecretKey), InitError> { let token_symbol = TokenSymbol::new(config.token_symbol.as_str()) - .map_err(|err| FaucetError::AccountCreationError(err.to_string()))?; + .map_err(|err| InitError::AccountCreationError(err.to_string()))?; let seed: [u8; 32] = [0; 32]; - // Instantiate keypair and authscheme + // Instantiate keypair and auth scheme let mut rng = ChaCha20Rng::from_seed(seed); let secret = SecretKey::with_rng(&mut rng); let auth_scheme = AuthScheme::RpoFalcon512 { pub_key: secret.public_key() }; @@ -237,11 +245,11 @@ fn build_account(config: FaucetConfig) -> Result<(Account, Word, SecretKey), Fau token_symbol, config.decimals, Felt::try_from(config.max_supply) - .map_err(|err| FaucetError::InternalServerError(err.to_string()))?, + .map_err(|err| InitError::AccountCreationError(err.to_string()))?, AccountStorageMode::Private, auth_scheme, ) - .map_err(|err| FaucetError::AccountCreationError(err.to_string()))?; + .map_err(|err| InitError::AccountCreationError(err.to_string()))?; Ok((faucet_account, account_seed, secret)) } @@ -249,26 +257,27 @@ fn build_account(config: FaucetConfig) -> Result<(Account, Word, SecretKey), Fau /// Initializes the faucet client by connecting to the node and fetching the root block header. pub async fn initialize_faucet_client( config: FaucetConfig, -) -> Result<(ApiClient, BlockHeader, ChainMmr), FaucetError> { +) -> Result<(ApiClient, BlockHeader, ChainMmr), InitError> { let endpoint = tonic::transport::Endpoint::try_from(config.node_url.clone()) - .map_err(|_| FaucetError::InternalServerError("Failed to connect to node.".to_string()))? + .map_err(|_| InitError::ClientInitFailed("Failed to connect to node.".to_string()))? .timeout(Duration::from_millis(config.timeout_ms)); let mut rpc_api = ApiClient::connect(endpoint) .await - .map_err(|err| FaucetError::InternalServerError(err.to_string()))?; + .map_err(|err| InitError::ClientInitFailed(err.to_string()))?; let request = GetBlockHeaderByNumberRequest { block_num: Some(0), include_mmr_proof: Some(true), }; - let response = rpc_api.get_block_header_by_number(request).await.map_err(|err| { - FaucetError::InternalServerError(format!("Failed to get block header: {}", err)) - })?; + let response = rpc_api + .get_block_header_by_number(request) + .await + .map_err(|err| InitError::ClientInitFailed(format!("Failed to get block header: {err}")))?; let root_block_header = response.into_inner().block_header.unwrap(); let root_block_header: BlockHeader = root_block_header.try_into().map_err(|err| { - FaucetError::InternalServerError(format!("Failed to parse block header: {}", err)) + InitError::ClientInitFailed(format!("Failed to parse block header: {err}")) })?; let root_chain_mmr = ChainMmr::new( @@ -287,7 +296,7 @@ fn build_transaction_arguments( output_note: &Note, note_type: NoteType, asset: FungibleAsset, -) -> Result { +) -> Result { let recipient = output_note .recipient() .digest() @@ -310,7 +319,7 @@ fn build_transaction_arguments( let script = TransactionScript::compile(script, vec![], TransactionKernel::assembler()) .map_err(|err| { - FaucetError::InternalServerError(format!("Failed to compile script: {}", err)) + ProcessError::InternalServerError(format!("Failed to compile script: {err}")) })?; let mut transaction_args = TransactionArgs::new(Some(script), None, AdviceMap::new()); diff --git a/bin/faucet/src/config.rs b/bin/faucet/src/config.rs index 16ce094eb..1e443585a 100644 --- a/bin/faucet/src/config.rs +++ b/bin/faucet/src/config.rs @@ -25,12 +25,6 @@ pub struct FaucetConfig { pub max_supply: u64, } -impl FaucetConfig { - pub fn endpoint_url(&self) -> String { - self.endpoint.to_string() - } -} - impl Display for FaucetConfig { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_fmt(format_args!( diff --git a/bin/faucet/src/errors.rs b/bin/faucet/src/errors.rs index 4e167e855..50777c719 100644 --- a/bin/faucet/src/errors.rs +++ b/bin/faucet/src/errors.rs @@ -1,47 +1,62 @@ -use actix_web::{ - error, - http::{header::ContentType, StatusCode}, - HttpResponse, +use axum::{ + http::{header, StatusCode}, + response::{IntoResponse, Response}, }; use thiserror::Error; #[derive(Debug, Error)] -pub enum FaucetError { +pub enum InitError { #[error("Failed to start faucet: {0}")] - StartError(String), + FaucetFailedToStart(String), - #[error("Client has submitted a bad request: {0}")] - BadRequest(String), + #[error("Failed to initialize client: {0}")] + ClientInitFailed(String), #[error("Failed to configure faucet: {0}")] ConfigurationError(String), + #[error("Failed to create Miden account: {0}")] + AccountCreationError(String), +} + +#[derive(Debug, Error)] +pub enum ProcessError { + #[error("Client has submitted a bad request: {0}")] + BadRequest(String), + #[error("Server has encountered an internal error: {0}")] InternalServerError(String), - #[error("Failed to create Miden account: {0}")] - AccountCreationError(String), + #[error("Page not found: {0}")] + NotFound(String), } -impl error::ResponseError for FaucetError { - fn error_response(&self) -> HttpResponse { - let message = match self { - FaucetError::StartError(msg) => msg.to_string(), - FaucetError::BadRequest(msg) => msg.to_string(), - FaucetError::ConfigurationError(msg) => msg.to_string(), - FaucetError::InternalServerError(msg) => msg.to_string(), - FaucetError::AccountCreationError(msg) => msg.to_string(), - }; - - HttpResponse::build(self.status_code()) - .insert_header(ContentType::html()) - .body(message.to_owned()) +impl ProcessError { + fn status_code(&self) -> StatusCode { + match *self { + Self::BadRequest(_) => StatusCode::BAD_REQUEST, + Self::NotFound(_) => StatusCode::NOT_FOUND, + Self::InternalServerError(_) => StatusCode::INTERNAL_SERVER_ERROR, + } } - fn status_code(&self) -> actix_web::http::StatusCode { - match *self { - FaucetError::BadRequest(_) => StatusCode::BAD_REQUEST, - _ => StatusCode::INTERNAL_SERVER_ERROR, + fn message(&self) -> String { + match self { + Self::BadRequest(msg) => msg, + Self::InternalServerError(_) => "Error processing request", + Self::NotFound(msg) => msg, } + .to_string() + } +} + +impl IntoResponse for ProcessError { + fn into_response(self) -> Response { + ( + self.status_code(), + [(header::CONTENT_TYPE, mime::TEXT_HTML_UTF_8.as_ref())], + self.message(), + ) + .into_response() } } diff --git a/bin/faucet/src/handlers.rs b/bin/faucet/src/handlers.rs index a98daec6f..5e51e4fda 100644 --- a/bin/faucet/src/handlers.rs +++ b/bin/faucet/src/handlers.rs @@ -1,60 +1,71 @@ -use actix_web::{get, http::header, post, web, HttpResponse, Result}; +use axum::{ + extract::{Path, State}, + http::{Response, StatusCode}, + response::IntoResponse, + Json, +}; +use http::header; +use http_body_util::Full; use miden_objects::{ accounts::AccountId, notes::{NoteDetails, NoteExecutionMode, NoteFile, NoteId, NoteTag}, utils::serde::Serializable, }; use serde::{Deserialize, Serialize}; +use tonic::body; use tracing::info; -use crate::{errors::FaucetError, state::FaucetState}; +use crate::{errors::ProcessError, state::FaucetState, COMPONENT}; #[derive(Deserialize)] -struct FaucetRequest { +pub struct FaucetRequest { account_id: String, is_private_note: bool, asset_amount: u64, } #[derive(Serialize)] -struct FaucetMetadataReponse { +pub struct FaucetMetadataReponse { id: String, asset_amount_options: Vec, } -#[get("/get_metadata")] -pub async fn get_metadata(state: web::Data) -> HttpResponse { +pub async fn get_metadata( + State(state): State, +) -> (StatusCode, Json) { let response = FaucetMetadataReponse { id: state.id.to_string(), asset_amount_options: state.config.asset_amount_options.clone(), }; - HttpResponse::Ok().json(response) + (StatusCode::OK, Json(response)) } -#[post("/get_tokens")] pub async fn get_tokens( - req: web::Json, - state: web::Data, -) -> Result { + State(state): State, + Json(req): Json, +) -> Result { info!( - "Received a request with account_id: {}, is_private_note: {}, asset_amount: {}", - req.account_id, req.is_private_note, req.asset_amount + target: COMPONENT, + account_id = %req.account_id, + is_private_note = %req.is_private_note, + asset_amount = %req.asset_amount, + "Received a request", ); // Check that the amount is in the asset amount options if !state.config.asset_amount_options.contains(&req.asset_amount) { - return Err(FaucetError::BadRequest("Invalid asset amount.".to_string()).into()); + return Err(ProcessError::BadRequest("Invalid asset amount".to_string())); } let mut client = state.client.lock().await; // Receive and hex user account id let target_account_id = AccountId::from_hex(req.account_id.as_str()) - .map_err(|err| FaucetError::BadRequest(err.to_string()))?; + .map_err(|err| ProcessError::BadRequest(err.to_string()))?; // Execute transaction - info!("Executing mint transaction for account."); + info!(target: COMPONENT, "Executing mint transaction for account."); let (executed_tx, created_note) = client.execute_mint_transaction( target_account_id, req.is_private_note, @@ -62,7 +73,7 @@ pub async fn get_tokens( )?; // Run transaction prover & send transaction to node - info!("Proving and submitting transaction."); + info!(target: COMPONENT, "Proving and submitting transaction."); let block_height = client.prove_and_submit_transaction(executed_tx).await?; let note_id: NoteId = created_note.id(); @@ -80,17 +91,33 @@ pub async fn get_tokens( } .to_bytes(); - info!("A new note has been created: {}", note_id); + info!(target: COMPONENT, %note_id, "A new note has been created"); // Send generated note to user - Ok(HttpResponse::Ok() - .content_type("application/octet-stream") - .append_header(header::ContentDisposition { - disposition: actix_web::http::header::DispositionType::Attachment, - parameters: vec![actix_web::http::header::DispositionParam::Filename( - "note.mno".to_string(), - )], - }) - .append_header(("Note-Id", note_id.to_string())) - .body(bytes)) + Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_TYPE, "application/octet-stream") + .header(header::CONTENT_DISPOSITION, "attachment; filename=note.mno") + .header("Note-Id", note_id.to_string()) + .body(body::boxed(Full::from(bytes))) + .map_err(|err| ProcessError::InternalServerError(err.to_string())) +} + +pub async fn get_index(state: State) -> Result { + get_static_file(state, Path("index.html".to_string())).await +} + +pub async fn get_static_file( + State(state): State, + Path(path): Path, +) -> Result { + info!(target: COMPONENT, path, "Serving static file"); + + let static_file = state.static_files.get(path.as_str()).ok_or(ProcessError::NotFound(path))?; + + Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_TYPE, static_file.mime_type) + .body(body::boxed(Full::from(static_file.data))) + .map_err(|err| ProcessError::InternalServerError(err.to_string())) } diff --git a/bin/faucet/src/main.rs b/bin/faucet/src/main.rs index 3247a4f31..f58f9f184 100644 --- a/bin/faucet/src/main.rs +++ b/bin/faucet/src/main.rs @@ -6,22 +6,24 @@ mod state; use std::{fs::File, io::Write, path::PathBuf}; -use actix_cors::Cors; -use actix_web::{ - middleware::{DefaultHeaders, Logger}, - web, App, HttpServer, +use axum::{ + routing::{get, post}, + Router, }; use clap::{Parser, Subcommand}; -use errors::FaucetError; +use http::HeaderValue; use miden_node_utils::{config::load_config, version::LongVersion}; use state::FaucetState; +use tokio::net::TcpListener; +use tower::ServiceBuilder; +use tower_http::{cors::CorsLayer, set_header::SetResponseHeaderLayer, trace::TraceLayer}; use tracing::info; use crate::{ config::FaucetConfig, - handlers::{get_metadata, get_tokens}, + errors::InitError, + handlers::{get_index, get_metadata, get_static_file, get_tokens}, }; - // CONSTANTS // ================================================================================================= @@ -56,69 +58,71 @@ pub enum Command { // MAIN // ================================================================================================= -#[actix_web::main] -async fn main() -> Result<(), FaucetError> { +#[tokio::main] +async fn main() -> Result<(), InitError> { miden_node_utils::logging::setup_logging() - .map_err(|err| FaucetError::StartError(err.to_string()))?; + .map_err(|err| InitError::FaucetFailedToStart(err.to_string()))?; let cli = Cli::parse(); match &cli.command { Command::Start { config } => { let config: FaucetConfig = load_config(config) - .map_err(|err| FaucetError::ConfigurationError(err.to_string()))?; + .map_err(|err| InitError::ConfigurationError(err.to_string()))?; let faucet_state = FaucetState::new(config.clone()).await?; info!(target: COMPONENT, %config, "Initializing server"); - info!("Server is now running on: {}", config.endpoint_url()); - - HttpServer::new(move || { - let cors = Cors::default().allow_any_origin().allow_any_method(); - App::new() - .app_data(web::Data::new(faucet_state.clone())) - .wrap(cors) - .wrap(Logger::default()) - .wrap(DefaultHeaders::new().add(("Cache-Control", "no-cache"))) - .service(get_metadata) - .service(get_tokens) - .service(actix_web_static_files::ResourceFiles::new( - "/", - static_resources::generate(), - )) - }) - .bind((config.endpoint.host, config.endpoint.port)) - .map_err(|err| FaucetError::StartError(err.to_string()))? - .run() - .await - .map_err(|err| FaucetError::StartError(err.to_string()))?; + let app = Router::new() + .route("/", get(get_index)) + .route("/get_metadata", get(get_metadata)) + .route("/get_tokens", post(get_tokens)) + .route("/*path", get(get_static_file)) + .layer( + ServiceBuilder::new() + .layer(TraceLayer::new_for_http()) + .layer(SetResponseHeaderLayer::if_not_present( + http::header::CACHE_CONTROL, + HeaderValue::from_static("no-cache"), + )) + .layer( + CorsLayer::new() + .allow_origin(tower_http::cors::Any) + .allow_methods(tower_http::cors::Any), + ), + ) + .with_state(faucet_state); + + let listener = TcpListener::bind((config.endpoint.host.as_str(), config.endpoint.port)) + .await + .map_err(|err| InitError::FaucetFailedToStart(err.to_string()))?; + + info!(target: COMPONENT, endpoint = %config.endpoint, "Server started"); + + axum::serve(listener, app).await.unwrap(); }, Command::Init { config_path } => { let current_dir = std::env::current_dir().map_err(|err| { - FaucetError::ConfigurationError(format!("failed to open current directory: {err}")) + InitError::ConfigurationError(format!("failed to open current directory: {err}")) })?; - let mut config_file_path = current_dir.clone(); - config_file_path.push(config_path); - + let config_file_path = current_dir.join(config_path); let config = FaucetConfig::default(); let config_as_toml_string = toml::to_string(&config).map_err(|err| { - FaucetError::ConfigurationError(format!( - "Failed to serialize default config: {err}" - )) + InitError::ConfigurationError(format!("Failed to serialize default config: {err}")) })?; let mut file_handle = File::options().write(true).create_new(true).open(&config_file_path).map_err( - |err| FaucetError::ConfigurationError(format!("Error opening the file: {err}")), + |err| InitError::ConfigurationError(format!("Error opening the file: {err}")), )?; file_handle.write(config_as_toml_string.as_bytes()).map_err(|err| { - FaucetError::ConfigurationError(format!("Error writing to file: {err}")) + InitError::ConfigurationError(format!("Error writing to file: {err}")) })?; - println!("Config file successfully created at: {:?}", config_file_path); + println!("Config file successfully created at: {config_file_path:?}"); }, } diff --git a/bin/faucet/src/state.rs b/bin/faucet/src/state.rs index c94175caf..898a5e7bd 100644 --- a/bin/faucet/src/state.rs +++ b/bin/faucet/src/state.rs @@ -1,11 +1,13 @@ -use std::sync::Arc; +use std::{collections::HashMap, sync::Arc}; -use async_mutex::Mutex; use miden_objects::accounts::AccountId; +use static_files::Resource; +use tokio::sync::Mutex; use tracing::info; -use crate::{client::FaucetClient, config::FaucetConfig, errors::FaucetError}; - +use crate::{ + client::FaucetClient, config::FaucetConfig, errors::InitError, static_resources, COMPONENT, +}; // FAUCET STATE // ================================================================================================ @@ -18,15 +20,18 @@ pub struct FaucetState { pub id: AccountId, pub client: Arc>, pub config: FaucetConfig, + pub static_files: Arc>, } impl FaucetState { - pub async fn new(config: FaucetConfig) -> Result { + pub async fn new(config: FaucetConfig) -> Result { let client = FaucetClient::new(config.clone()).await?; let id = client.get_faucet_id(); let client = Arc::new(Mutex::new(client)); - info!("Faucet initialization successful, account id: {}", id); + let static_files = Arc::new(static_resources::generate()); + + info!(target: COMPONENT, account_id = %id, "Faucet initialization successful"); - Ok(FaucetState { client, id, config }) + Ok(FaucetState { client, id, config, static_files }) } }