From 9c3503649f49bcd1b57e672c2756c217de8840db Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Fri, 22 Mar 2024 13:36:12 +0530 Subject: [PATCH 01/66] feat: add server config from .env and settings.toml --- .gitignore | 1 + Cargo.lock | 1078 +++++++++++++++++++---------------- server/.env_example | 5 + server/Cargo.toml | 3 +- server/src/server_config.rs | 62 +- 5 files changed, 646 insertions(+), 503 deletions(-) create mode 100644 server/.env_example diff --git a/.gitignore b/.gitignore index ea8c4bf7..860734b0 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /target +/server/.env diff --git a/Cargo.lock b/Cargo.lock index 92e3a261..68a9eba3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -29,9 +29,9 @@ dependencies = [ [[package]] name = "aes" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac1f845298e95f983ff1944b728ae08b8cebab80d684f0a832ed0fc74dfa27e2" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ "cfg-if", "cipher", @@ -54,9 +54,9 @@ dependencies = [ [[package]] name = "ahash" -version = "0.7.6" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" +checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9" dependencies = [ "getrandom", "once_cell", @@ -65,21 +65,22 @@ dependencies = [ [[package]] name = "ahash" -version = "0.8.3" +version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c99f64d1e06488f620f932677e24bc6e2897582980441ae90a671415bd7ec2f" +checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" dependencies = [ "cfg-if", "getrandom", "once_cell", "version_check", + "zerocopy", ] [[package]] name = "aho-corasick" -version = "1.1.2" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2969dcb958b36655471fc61f7e416fa76033bdd4bfed0678d8fee1e2d07a1f0" +checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" dependencies = [ "memchr", ] @@ -107,9 +108,9 @@ dependencies = [ [[package]] name = "anstream" -version = "0.6.4" +version = "0.6.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ab91ebe16eb252986481c5b62f6098f3b698a45e34b5b98200cf20dd2484a44" +checksum = "d96bd03f33fe50a863e394ee9718a706f988b9079b20c3784fb726e7678b62fb" dependencies = [ "anstyle", "anstyle-parse", @@ -121,43 +122,43 @@ dependencies = [ [[package]] name = "anstyle" -version = "1.0.4" +version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7079075b41f533b8c61d2a4d073c4676e1f8b249ff94a393b0595db304e0dd87" +checksum = "8901269c6307e8d93993578286ac0edf7f195079ffff5ebdeea6a59ffb7e36bc" [[package]] name = "anstyle-parse" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "317b9a89c1868f5ea6ff1d9539a69f45dffc21ce321ac1fd1160dfa48c8e2140" +checksum = "c75ac65da39e5fe5ab759307499ddad880d724eed2f6ce5b5e8a26f4f387928c" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" -version = "1.0.0" +version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ca11d4be1bab0c8bc8734a9aa7bf4ee8316d462a08c6ac5052f888fef5b494b" +checksum = "e28923312444cdd728e4738b3f9c9cac739500909bb3d3c94b43551b16517648" dependencies = [ - "windows-sys", + "windows-sys 0.52.0", ] [[package]] name = "anstyle-wincon" -version = "3.0.1" +version = "3.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0699d10d2f4d628a98ee7b57b289abbc98ff3bad977cb3152709d4bf2330628" +checksum = "1cd54b81ec8d6180e24654d0b371ad22fc3dd083b6ff8ba325b72e00c87660a7" dependencies = [ "anstyle", - "windows-sys", + "windows-sys 0.52.0", ] [[package]] name = "anyhow" -version = "1.0.75" +version = "1.0.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6" +checksum = "0952808a6c2afd1aa8947271f3a60f1a6763c7b912d210184c5149b5cf147247" [[package]] name = "arrayref" @@ -184,18 +185,18 @@ checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.53", ] [[package]] name = "async-trait" -version = "0.1.74" +version = "0.1.78" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9" +checksum = "461abc97219de0eaaf81fe3ef974a540158f3d079c2ab200f891f1a2ef201e85" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.53", ] [[package]] @@ -251,9 +252,9 @@ checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" [[package]] name = "base64" -version = "0.21.4" +version = "0.21.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ba43ea6f343b788c8764558649e08df62f86c6ef251fdaeb1ffd010a9ae50a2" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" [[package]] name = "base64ct" @@ -287,9 +288,9 @@ dependencies = [ [[package]] name = "bitcoin" -version = "0.30.1" +version = "0.30.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e99ff7289b20a7385f66a0feda78af2fc119d28fb56aea8886a9cd0a4abdd75" +checksum = "1945a5048598e4189e239d3f809b19bdad4845c4b2ba400d304d2dcf26d2c462" dependencies = [ "base64 0.13.1", "bech32", @@ -341,9 +342,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.4.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635" +checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" dependencies = [ "serde", ] @@ -359,15 +360,15 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.14.0" +version = "3.15.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec" +checksum = "7ff69b9dd49fd426c69a0db9fc04dd934cdb6645ff000864d98f7e2af8830eaa" [[package]] name = "bytemuck" -version = "1.14.0" +version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "374d28ec25809ee0e23827c2ab573d729e293f281dfe393500e7ad618baa61c6" +checksum = "5d6d68c57235a3a081186990eca2867354726650f42f7516ca50c28d6281fd15" [[package]] name = "byteorder" @@ -383,12 +384,9 @@ checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223" [[package]] name = "cc" -version = "1.0.83" +version = "1.0.90" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" -dependencies = [ - "libc", -] +checksum = "8cd6604a82acf3039f1144f54b8eb34e91ffba622051189e71b781822d5ee1f5" [[package]] name = "cfg-if" @@ -398,16 +396,16 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "chrono" -version = "0.4.31" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f2c685bad3eb3d45a01354cedb7d5faa66194d1d58ba6e267a8de788f79db38" +checksum = "8eaf5903dcbc0a39312feb77df2ff4c76387d591b9fc7b04a238dcf8bb62639a" dependencies = [ "android-tzdata", "iana-time-zone", "js-sys", "num-traits", "wasm-bindgen", - "windows-targets", + "windows-targets 0.52.4", ] [[package]] @@ -422,9 +420,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.4.6" +version = "4.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d04704f56c2cde07f43e8e2c154b43f216dc5c92fc98ada720177362f953b956" +checksum = "949626d00e063efc93b6dca932419ceb5432f99769911c0b995f7e884c778813" dependencies = [ "clap_builder", "clap_derive", @@ -432,9 +430,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.4.6" +version = "4.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e231faeaca65ebd1ea3c737966bf858971cd38c3849107aa3ea7de90a804e45" +checksum = "ae129e2e766ae0ec03484e609954119f123cc1fe650337e155d03b022f24f7b4" dependencies = [ "anstream", "anstyle", @@ -444,21 +442,21 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.4.2" +version = "4.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0862016ff20d69b84ef8247369fabf5c008a7417002411897d40ee1f4532b873" +checksum = "90239a040c80f5e14809ca132ddc4176ab33d5e17e49691793296e3fcb34d72f" dependencies = [ - "heck", + "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.53", ] [[package]] name = "clap_lex" -version = "0.5.1" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd7cc57abe963c6d3b9d8be5b06ba7c8957a930305ca90304f24ef040aa6f961" +checksum = "98cc8fbded0c607b7ba9dd60cd98df59af97e84d24e49c8557331cfc26d301ce" [[package]] name = "client-rust" @@ -482,7 +480,7 @@ dependencies = [ "serde_json", "sqlx", "tokio", - "uuid 1.4.1", + "uuid 1.8.0", ] [[package]] @@ -493,9 +491,9 @@ checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" [[package]] name = "config" -version = "0.13.3" +version = "0.13.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d379af7f68bfc21714c6c7dea883544201741d2ce8274bb12fa54f89507f52a7" +checksum = "23738e11972c7643e4ec947840fc463b6a571afcd3e735bdfce7d03c7a784aca" dependencies = [ "async-trait", "json5", @@ -522,15 +520,15 @@ dependencies = [ [[package]] name = "const-oid" -version = "0.9.5" +version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28c122c3980598d243d63d9a704629a2d748d101f278052ff068be5a4423ab6f" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" [[package]] name = "cookie" -version = "0.17.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7efb37c3e1ccb1ff97164ad95ac1606e8ccd35b3fa0a7d99a304c7f4a428cc24" +checksum = "3cd91cf61412820176e137621345ee43b3f4423e589e7ae4e50d601d93e35ef8" dependencies = [ "percent-encoding", "time", @@ -539,9 +537,9 @@ dependencies = [ [[package]] name = "core-foundation" -version = "0.9.3" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "194a7a9e6de53fa55116934067c844d9d749312f75c6f6d0980e8c252f8c2146" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" dependencies = [ "core-foundation-sys", "libc", @@ -549,15 +547,15 @@ dependencies = [ [[package]] name = "core-foundation-sys" -version = "0.8.4" +version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" +checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f" [[package]] name = "cpufeatures" -version = "0.2.9" +version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a17b76ff3a4162b0b27f354a0c87015ddad39d35f9c0c36607a3bdd175dde1f1" +checksum = "53fe5e26ff1b7aef8bca9c6080520cfb8d9333c7568e1829cef191a9723e5504" dependencies = [ "libc", ] @@ -573,28 +571,24 @@ dependencies = [ [[package]] name = "crc-catalog" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cace84e55f07e7301bae1c519df89cdad8cc3cd868413d3fdbdeca9ff3db484" +checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5" [[package]] name = "crossbeam-queue" -version = "0.3.8" +version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1cfb3ea8a53f37c40dea2c7bedcbd88bdfae54f5e2175d6ecaff1c988353add" +checksum = "df0346b5d5e76ac2fe4e327c5fd1118d6be7c51dfb18f9b7922923f287471e35" dependencies = [ - "cfg-if", "crossbeam-utils", ] [[package]] name = "crossbeam-utils" -version = "0.8.16" +version = "0.8.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294" -dependencies = [ - "cfg-if", -] +checksum = "248e3bacc7dc6baa3b21e405ee045c3047101a49145e7e9eca583ab4c2ca5345" [[package]] name = "crunchy" @@ -634,9 +628,12 @@ dependencies = [ [[package]] name = "deranged" -version = "0.3.8" +version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2696e8a945f658fd14dc3b87242e6b80cd0f36ff04ea560fa39082368847946" +checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" +dependencies = [ + "powerfmt", +] [[package]] name = "devise" @@ -664,11 +661,11 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35b50dba0afdca80b187392b24f2499a88c336d5a8493e4b4ccfb608708be56a" dependencies = [ - "bitflags 2.4.0", + "bitflags 2.5.0", "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.38", + "syn 2.0.53", ] [[package]] @@ -698,6 +695,12 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0688c2a7f92e427f44895cd63841bff7b29f8d7a1648b9e7e07a4a365b2e1257" +[[package]] +name = "dotenv" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77c90badedccf4105eca100756a0b1289e191f6fcbdadd3cee1d2f614f97da8f" + [[package]] name = "dotenvy" version = "0.15.7" @@ -706,9 +709,9 @@ checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" [[package]] name = "dyn-clone" -version = "1.0.14" +version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23d2f3407d9a573d666de4b5bdf10569d73ca9478087346697dcbae6244bfbcd" +checksum = "0d6ef0072f8a535281e4876be788938b528e9a1d43900b82c2569af7da799125" [[package]] name = "ecies" @@ -730,9 +733,9 @@ dependencies = [ [[package]] name = "either" -version = "1.9.0" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07" +checksum = "11157ac094ffbdde99aa67b23417ebdd801842852b500e395a45a9c0aac03e4a" dependencies = [ "serde", ] @@ -773,12 +776,12 @@ checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" [[package]] name = "errno" -version = "0.3.5" +version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3e13f66a2f95e32a39eaa81f6b95d42878ca0e1db0c7543723dfe12557e860" +checksum = "a258e46cdc063eb8519c00b9fc845fc47bcfca4130e2f08e88665ceda8474245" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.52.0", ] [[package]] @@ -789,7 +792,7 @@ checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943" dependencies = [ "cfg-if", "home", - "windows-sys", + "windows-sys 0.48.0", ] [[package]] @@ -806,14 +809,14 @@ checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" [[package]] name = "figment" -version = "0.10.11" +version = "0.10.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a014ac935975a70ad13a3bff2463b1c1b083b35ae4cb6309cfc59476aa7a181f" +checksum = "7270677e7067213e04f323b55084586195f18308cd7546cfac9f873344ccceb6" dependencies = [ "atomic 0.6.0", "pear", "serde", - "toml 0.8.2", + "toml 0.8.12", "uncased", "version_check", ] @@ -858,18 +861,18 @@ checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" [[package]] name = "form_urlencoded" -version = "1.2.0" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652" +checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" dependencies = [ "percent-encoding", ] [[package]] name = "futures" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23342abe12aba583913b2e62f22225ff9c950774065e4bfb61a19cd9770fec40" +checksum = "645c6916888f6cb6350d2550b80fb63e734897a8498abe35cfb732b6487804b0" dependencies = [ "futures-channel", "futures-core", @@ -881,9 +884,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "955518d47e09b25bbebc7a18df10b81f0c766eaf4c4f1cccef2fca5f2a4fb5f2" +checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78" dependencies = [ "futures-core", "futures-sink", @@ -891,15 +894,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bca583b7e26f571124fe5b7561d49cb2868d79116cfa0eefce955557c6fee8c" +checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d" [[package]] name = "futures-executor" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccecee823288125bd88b4d7f565c9e58e41858e47ab72e8ea2d64e93624386e0" +checksum = "a576fc72ae164fca6b9db127eaa9a9dda0d61316034f33a0a0d4eda41f02b01d" dependencies = [ "futures-core", "futures-task", @@ -919,27 +922,27 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964" +checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" [[package]] name = "futures-sink" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f43be4fe21a13b9781a69afa4985b0f6ee0e1afab2c6f454a8cf30e2b2237b6e" +checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5" [[package]] name = "futures-task" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76d3d132be6c0e6aa1534069c705a74a5997a356c0dc2f86a47765e5617c5b65" +checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" [[package]] name = "futures-util" -version = "0.3.28" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b01e40b772d54cf6c6d721c1d1abd0647a0106a12ecaa1c186273392a69533" +checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" dependencies = [ "futures-channel", "futures-core", @@ -977,9 +980,9 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.10" +version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be4136b2a15dd319360be1c07d9933517ccf0be8f16bf62a3bee4f0d618df427" +checksum = "190092ea657667030ac6a35e305e62fc4dd69fd98ac98631e5d3a2b1575a12b5" dependencies = [ "cfg-if", "js-sys", @@ -990,9 +993,9 @@ dependencies = [ [[package]] name = "ghash" -version = "0.5.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d930750de5717d2dd0b8c0d42c076c0e884c81a73e6cab859bbd2339c71e3e40" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" dependencies = [ "opaque-debug", "polyval", @@ -1000,9 +1003,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.28.0" +version = "0.28.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fb8d784f27acf97159b40fc4db5ecd8aa23b9ad5ef69cdd136d3bc80665f0c0" +checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253" [[package]] name = "glob" @@ -1012,9 +1015,9 @@ checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" [[package]] name = "h2" -version = "0.3.21" +version = "0.3.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91fc23aa11be92976ef4729127f1a74adf36d8436f7816b185d18df956790833" +checksum = "4fbd2820c5e49886948654ab546d0688ff24530286bdcf8fca3cefb16d4618eb" dependencies = [ "bytes", "fnv", @@ -1022,7 +1025,7 @@ dependencies = [ "futures-sink", "futures-util", "http", - "indexmap 1.9.3", + "indexmap", "slab", "tokio", "tokio-util", @@ -1035,16 +1038,16 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" dependencies = [ - "ahash 0.7.6", + "ahash 0.7.8", ] [[package]] name = "hashbrown" -version = "0.14.1" +version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dfda62a12f55daeae5015f81b0baea145391cb4520f86c248fc615d72640d12" +checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" dependencies = [ - "ahash 0.8.3", + "ahash 0.8.11", "allocator-api2", ] @@ -1054,7 +1057,7 @@ version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8094feaf31ff591f651a2664fb9cfd92bba7a60ce3197265e9482ebe753c8f7" dependencies = [ - "hashbrown 0.14.1", + "hashbrown 0.14.3", ] [[package]] @@ -1066,11 +1069,17 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + [[package]] name = "hermit-abi" -version = "0.3.3" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d77f7ec81a6d05a3abb01ab6eb7590f6083d08449fe5a1c8b1e620283546ccb7" +checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" [[package]] name = "hex" @@ -1086,9 +1095,9 @@ checksum = "3011d1213f159867b13cfd6ac92d2cd5f1345762c63be3554e84092d85a50bbd" [[package]] name = "hkdf" -version = "0.12.3" +version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "791a029f6b9fc27657f6f188ec6e5e43f6911f6f878e0dc5501396e09809d437" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" dependencies = [ "hmac", ] @@ -1104,18 +1113,18 @@ dependencies = [ [[package]] name = "home" -version = "0.5.5" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5444c27eef6923071f7ebcc33e3444508466a76f7a2b93da00ed6e19f30c1ddb" +checksum = "e3d1354bf6b7235cb4a0576c2619fd4ed18183f689b12b006a0ee7329eeff9a5" dependencies = [ - "windows-sys", + "windows-sys 0.52.0", ] [[package]] name = "http" -version = "0.2.9" +version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd6effc99afb63425aff9b05836f029929e345a6148a14b7ecd5ab67af944482" +checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" dependencies = [ "bytes", "fnv", @@ -1124,9 +1133,9 @@ dependencies = [ [[package]] name = "http-body" -version = "0.4.5" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1" +checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" dependencies = [ "bytes", "http", @@ -1147,9 +1156,9 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "hyper" -version = "0.14.27" +version = "0.14.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffb1cfd654a8219eaef89881fdb3bb3b1cdc5fa75ded05d6933b2b382e395468" +checksum = "bf96e135eb83a2a8ddf766e426a841d8ddd7449d5f00d34ea02b41d2f19eef80" dependencies = [ "bytes", "futures-channel", @@ -1162,7 +1171,7 @@ dependencies = [ "httpdate", "itoa", "pin-project-lite", - "socket2 0.4.9", + "socket2", "tokio", "tower-service", "tracing", @@ -1184,9 +1193,9 @@ dependencies = [ [[package]] name = "iana-time-zone" -version = "0.1.58" +version = "0.1.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8326b86b6cff230b97d0d312a6c40a60726df3332e721f72a1b035f451663b20" +checksum = "e7ffbb5a1b541ea2561f8c41c087286cc091e21e556a4f09a8f6cbf17b69b141" dependencies = [ "android_system_properties", "core-foundation-sys", @@ -1218,23 +1227,13 @@ dependencies = [ [[package]] name = "indexmap" -version = "1.9.3" +version = "2.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" -dependencies = [ - "autocfg", - "hashbrown 0.12.3", - "serde", -] - -[[package]] -name = "indexmap" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8adf3ddd720272c6ea8bf59463c04e0f93d0bbf7c5439b691bca2987e0270897" +checksum = "7b0b929d511467233429c45a44ac1dcaa21ba0f5ba11e4879e6ed28ddb4f9df4" dependencies = [ "equivalent", - "hashbrown 0.14.1", + "hashbrown 0.14.3", + "serde", ] [[package]] @@ -1254,41 +1253,41 @@ dependencies = [ [[package]] name = "ipnet" -version = "2.8.0" +version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28b29a3cd74f0f4598934efe3aeba42bae0eb4680554128851ebbecb02af14e6" +checksum = "8f518f335dce6725a761382244631d86cf0ccb2863413590b31338feb467f9c3" [[package]] name = "is-terminal" -version = "0.4.9" +version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb0889898416213fab133e1d33a0e5858a48177452750691bde3666d0fdbaf8b" +checksum = "f23ff5ef2b80d608d61efee834934d862cd92461afc0560dedf493e4c033738b" dependencies = [ "hermit-abi", - "rustix", - "windows-sys", + "libc", + "windows-sys 0.52.0", ] [[package]] name = "itertools" -version = "0.11.0" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" +checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" dependencies = [ "either", ] [[package]] name = "itoa" -version = "1.0.9" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" +checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" [[package]] name = "js-sys" -version = "0.3.64" +version = "0.3.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a" +checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d" dependencies = [ "wasm-bindgen", ] @@ -1315,9 +1314,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.149" +version = "0.2.153" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a08173bc88b7955d1b3145aa561539096c421ac8debde8cbc3612ec635fee29b" +checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" [[package]] name = "libm" @@ -1372,9 +1371,9 @@ dependencies = [ [[package]] name = "libsqlite3-sys" -version = "0.26.0" +version = "0.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afc22eff61b133b115c6e8c74e818c628d6d5e7a502afea6f64dee076dd94326" +checksum = "cf4e226dcd58b4be396f7bd3c20da8fdee2911400705297ba7d2d7cc2c30f716" dependencies = [ "cc", "pkg-config", @@ -1389,15 +1388,15 @@ checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" [[package]] name = "linux-raw-sys" -version = "0.4.10" +version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da2479e8c062e40bf0066ffa0bc823de0a9368974af99c9f6df941d2c231e03f" +checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c" [[package]] name = "lock_api" -version = "0.4.10" +version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1cc9717a20b1bb222f333e6a92fd32f7d8a18ddc5a3191a11af45dcbf4dcd16" +checksum = "3c168f8615b12bc01f9c17e2eb0cc07dcae1940121185446edc3744920e8ef45" dependencies = [ "autocfg", "scopeguard", @@ -1405,9 +1404,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.20" +version = "0.4.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" +checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" [[package]] name = "loom" @@ -1457,9 +1456,9 @@ dependencies = [ [[package]] name = "memchr" -version = "2.6.4" +version = "2.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f665ee40bc4a3c5590afb1e9677db74a508659dfd71e126420da8274909a0167" +checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149" [[package]] name = "mercury-client" @@ -1482,7 +1481,7 @@ dependencies = [ "serde_json", "sqlx", "tokio", - "uuid 1.4.1", + "uuid 1.8.0", ] [[package]] @@ -1506,6 +1505,7 @@ version = "0.1.0" dependencies = [ "bitcoin", "config", + "dotenv", "hex", "mercury-lib", "rand", @@ -1516,7 +1516,7 @@ dependencies = [ "serde", "serde_json", "sqlx", - "uuid 1.4.1", + "uuid 1.8.0", ] [[package]] @@ -1551,22 +1551,22 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.7.1" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7810e0be55b428ada41041c41f32c9f1a42817901b4ccf45fa3d4b6561e74c7" +checksum = "9d811f3e15f28568be3407c8e7fdb6514c1cda3cb30683f15b6a1a1dc4ea14a7" dependencies = [ "adler", ] [[package]] name = "mio" -version = "0.8.8" +version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "927a765cd3fc26206e66b296465fa9d3e5ab003e651c1b3c060e7956d96b19d2" +checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c" dependencies = [ "libc", "wasi", - "windows-sys", + "windows-sys 0.48.0", ] [[package]] @@ -1640,25 +1640,30 @@ dependencies = [ "num-iter", "num-traits", "rand", - "smallvec 1.11.1", + "smallvec 1.13.2", "zeroize", ] +[[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.45" +version = "0.1.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" dependencies = [ - "autocfg", "num-traits", ] [[package]] name = "num-iter" -version = "0.1.43" +version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d03e6c028c5dc5cac6e2dec0efda81fc887605bb3d884578bb6d6bf7514e252" +checksum = "d869c01cc0c455284163fd0092f1f93835385ccab5a98a0dcc497b2f8bf055a9" dependencies = [ "autocfg", "num-integer", @@ -1667,9 +1672,9 @@ dependencies = [ [[package]] name = "num-traits" -version = "0.2.17" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39e3200413f237f41ab11ad6d161bc7239c84dcb631773ccd7de3dfe4b5c267c" +checksum = "da0df0e5185db44f69b44f26786fe401b6c293d1907744beaa7fa62b2e5a517a" dependencies = [ "autocfg", "libm", @@ -1687,32 +1692,32 @@ dependencies = [ [[package]] name = "object" -version = "0.32.1" +version = "0.32.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cf5f9dd3933bd50a9e1f149ec995f39ae2c496d31fd772c1fd45ebc27e902b0" +checksum = "a6a622008b6e321afc04970976f62ee297fdbaa6f95318ca343e3eebb9648441" dependencies = [ "memchr", ] [[package]] name = "once_cell" -version = "1.18.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" +checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" [[package]] name = "opaque-debug" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" [[package]] name = "openssl" -version = "0.10.57" +version = "0.10.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bac25ee399abb46215765b1cb35bc0212377e58a061560d8b29b024fd0430e7c" +checksum = "95a0481286a310808298130d22dd1fef0fa571e05a8f44ec801801e84b216b1f" dependencies = [ - "bitflags 2.4.0", + "bitflags 2.5.0", "cfg-if", "foreign-types", "libc", @@ -1729,7 +1734,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.53", ] [[package]] @@ -1740,9 +1745,9 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-sys" -version = "0.9.93" +version = "0.9.101" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db4d56a4c0478783083cfafcc42493dd4a981d41669da64b4572a2a089b51b1d" +checksum = "dda2b0f344e78efc2facf7d195d098df0dd72151b26ab98da807afc26c198dff" dependencies = [ "cc", "libc", @@ -1778,15 +1783,15 @@ dependencies = [ [[package]] name = "parking_lot_core" -version = "0.9.8" +version = "0.9.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93f00c865fe7cabf650081affecd3871070f26767e7b2070a3ffae14c654b447" +checksum = "4c42a9226546d68acdd9c0a280d17ce19bfe27a46bf68784e4066115788d008e" dependencies = [ "cfg-if", "libc", "redox_syscall", - "smallvec 1.11.1", - "windows-targets", + "smallvec 1.13.2", + "windows-targets 0.48.5", ] [[package]] @@ -1803,25 +1808,25 @@ checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd" [[package]] name = "pear" -version = "0.2.7" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61a386cd715229d399604b50d1361683fe687066f42d56f54be995bc6868f71c" +checksum = "bdeeaa00ce488657faba8ebf44ab9361f9365a97bd39ffb8a60663f57ff4b467" dependencies = [ "inlinable_string", "pear_codegen", - "yansi 1.0.0-rc.1", + "yansi", ] [[package]] name = "pear_codegen" -version = "0.2.7" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da9f0f13dac8069c139e8300a6510e3f4143ecf5259c60b116a9b271b4ca0d54" +checksum = "4bab5b985dc082b345f812b7df84e1bef27e7207b39e448439ba8bd69c93f147" dependencies = [ "proc-macro2", "proc-macro2-diagnostics", "quote", - "syn 2.0.38", + "syn 2.0.53", ] [[package]] @@ -1835,15 +1840,15 @@ dependencies = [ [[package]] name = "percent-encoding" -version = "2.3.0" +version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94" +checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "pest" -version = "2.7.4" +version = "2.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c022f1e7b65d6a24c0dbbd5fb344c66881bc01f3e5ae74a1c8100f2f985d98a4" +checksum = "56f8023d0fb78c8e03784ea1c7f3fa36e68a723138990b8d5a47d916b651e7a8" dependencies = [ "memchr", "thiserror", @@ -1852,9 +1857,9 @@ dependencies = [ [[package]] name = "pest_derive" -version = "2.7.4" +version = "2.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35513f630d46400a977c4cb58f78e1bfbe01434316e60c37d27b9ad6139c66d8" +checksum = "b0d24f72393fd16ab6ac5738bc33cdb6a9aa73f8b902e8fe29cf4e67d7dd1026" dependencies = [ "pest", "pest_generator", @@ -1862,22 +1867,22 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.7.4" +version = "2.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc9fc1b9e7057baba189b5c626e2d6f40681ae5b6eb064dc7c7834101ec8123a" +checksum = "fdc17e2a6c7d0a492f0158d7a4bd66cc17280308bbaff78d5bef566dca35ab80" dependencies = [ "pest", "pest_meta", "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.53", ] [[package]] name = "pest_meta" -version = "2.7.4" +version = "2.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1df74e9e7ec4053ceb980e7c0c8bd3594e977fde1af91daba9c928e8e8c6708d" +checksum = "934cd7631c050f4674352a6e835d5f6711ffbfb9345c2fc0107155ac495ae293" dependencies = [ "once_cell", "pest", @@ -1919,15 +1924,15 @@ dependencies = [ [[package]] name = "pkg-config" -version = "0.3.27" +version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964" +checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" [[package]] name = "polyval" -version = "0.6.1" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d52cff9d1d4dee5fe6d03729099f4a310a41179e0a10dbf542039873f2e826fb" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" dependencies = [ "cfg-if", "cpufeatures", @@ -1935,6 +1940,12 @@ dependencies = [ "universal-hash", ] +[[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" @@ -1943,9 +1954,9 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "proc-macro2" -version = "1.0.69" +version = "1.0.79" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "134c189feb4956b20f6f547d2cf727d4c0fe06722b20a0eec87ed445a97f92da" +checksum = "e835ff2298f5721608eb1a980ecaee1aef2c132bf95ecc026a11b7bf3c01c02e" dependencies = [ "unicode-ident", ] @@ -1958,16 +1969,16 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.53", "version_check", - "yansi 1.0.0-rc.1", + "yansi", ] [[package]] name = "quote" -version = "1.0.33" +version = "1.0.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" +checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" dependencies = [ "proc-macro2", ] @@ -2010,43 +2021,43 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.3.5" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" dependencies = [ "bitflags 1.3.2", ] [[package]] name = "ref-cast" -version = "1.0.20" +version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "acde58d073e9c79da00f2b5b84eed919c8326832648a5b109b3fce1bb1175280" +checksum = "c4846d4c50d1721b1a3bef8af76924eef20d5e723647333798c1b519b3a9473f" dependencies = [ "ref-cast-impl", ] [[package]] name = "ref-cast-impl" -version = "1.0.20" +version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f7473c2cfcf90008193dd0e3e16599455cb601a9fce322b5bb55de799664925" +checksum = "5fddb4f8d99b0a2ebafc65a87a69a7b9875e4b1ae1f00db265d300ef7f28bccc" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.53", ] [[package]] name = "regex" -version = "1.10.0" +version = "1.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d119d7c7ca818f8a53c300863d4f87566aac09943aef5b355bb83969dae75d87" +checksum = "b62dbe01f0b06f9d8dc7d49e05a0785f153b00b2c227856282f671e0318c9b15" dependencies = [ "aho-corasick", "memchr", - "regex-automata 0.4.1", - "regex-syntax 0.8.0", + "regex-automata 0.4.6", + "regex-syntax 0.8.2", ] [[package]] @@ -2060,13 +2071,13 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.1" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "465c6fc0621e4abc4187a2bda0937bfd4f722c2730b29562e19689ea796c9a4b" +checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea" dependencies = [ "aho-corasick", "memchr", - "regex-syntax 0.8.0", + "regex-syntax 0.8.2", ] [[package]] @@ -2077,17 +2088,17 @@ checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" [[package]] name = "regex-syntax" -version = "0.8.0" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3cbb081b9784b07cceb8824c8583f86db4814d172ab043f3c23f7dc600bf83d" +checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" [[package]] name = "reqwest" -version = "0.11.22" +version = "0.11.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "046cd98826c46c2ac8ddecae268eb5c2e58628688a5fc7a2643704a73faba95b" +checksum = "dd67538700a17451e7cba03ac727fb961abb7607553461627b97de0b89cf4a62" dependencies = [ - "base64 0.21.4", + "base64 0.21.7", "bytes", "encoding_rs", "futures-core", @@ -2105,9 +2116,11 @@ dependencies = [ "once_cell", "percent-encoding", "pin-project-lite", + "rustls-pemfile", "serde", "serde_json", "serde_urlencoded", + "sync_wrapper", "system-configuration", "tokio", "tokio-native-tls", @@ -2122,38 +2135,24 @@ dependencies = [ [[package]] name = "ring" -version = "0.16.20" +version = "0.17.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" -dependencies = [ - "cc", - "libc", - "once_cell", - "spin 0.5.2", - "untrusted 0.7.1", - "web-sys", - "winapi", -] - -[[package]] -name = "ring" -version = "0.17.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9babe80d5c16becf6594aa32ad2be8fe08498e7ae60b77de8df700e67f191d7e" +checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d" dependencies = [ "cc", + "cfg-if", "getrandom", "libc", "spin 0.9.8", - "untrusted 0.9.0", - "windows-sys", + "untrusted", + "windows-sys 0.52.0", ] [[package]] name = "rocket" -version = "0.5.0-rc.3" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58734f7401ae5cfd129685b48f61182331745b357b96f2367f01aebaf1cc9cc9" +checksum = "9e7bb57ccb26670d73b6a47396c83139447b9e7878cab627fdfe9ea8da489150" dependencies = [ "async-stream", "async-trait", @@ -2163,8 +2162,7 @@ dependencies = [ "either", "figment", "futures", - "indexmap 1.9.3", - "is-terminal", + "indexmap", "log", "memchr", "multer", @@ -2185,37 +2183,38 @@ dependencies = [ "tokio-util", "ubyte", "version_check", - "yansi 0.5.1", + "yansi", ] [[package]] name = "rocket_codegen" -version = "0.5.0-rc.3" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7093353f14228c744982e409259fb54878ba9563d08214f2d880d59ff2fc508b" +checksum = "a2238066abf75f21be6cd7dc1a09d5414a671f4246e384e49fe3f8a4936bd04c" dependencies = [ "devise", "glob", - "indexmap 1.9.3", + "indexmap", "proc-macro2", "quote", "rocket_http", - "syn 2.0.38", + "syn 2.0.53", "unicode-xid", + "version_check", ] [[package]] name = "rocket_http" -version = "0.5.0-rc.3" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "936012c99162a03a67f37f9836d5f938f662e26f2717809761a9ac46432090f4" +checksum = "37a1663694d059fe5f943ea5481363e48050acedd241d46deb2e27f71110389e" dependencies = [ "cookie", "either", "futures", "http", "hyper", - "indexmap 1.9.3", + "indexmap", "log", "memchr", "pear", @@ -2223,7 +2222,7 @@ dependencies = [ "pin-project-lite", "ref-cast", "serde", - "smallvec 1.11.1", + "smallvec 1.13.2", "stable-pattern", "state", "time", @@ -2244,16 +2243,14 @@ dependencies = [ [[package]] name = "rsa" -version = "0.9.2" +version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ab43bb47d23c1a631b4b680199a45255dce26fa9ab2fa902581f624ff13e6a8" +checksum = "5d0e5124fcb30e76a7e79bfee683a2746db83784b86289f6251b54b7950a0dfc" dependencies = [ - "byteorder", "const-oid", "digest 0.10.7", "num-bigint-dig", "num-integer", - "num-iter", "num-traits", "pkcs1", "pkcs8", @@ -2282,37 +2279,46 @@ checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" [[package]] name = "rustix" -version = "0.38.18" +version = "0.38.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a74ee2d7c2581cd139b42447d7d9389b889bdaad3a73f1ebb16f2a3237bb19c" +checksum = "65e04861e65f21776e67888bfbea442b3642beaa0138fdb1dd7a84a52dffdb89" dependencies = [ - "bitflags 2.4.0", + "bitflags 2.5.0", "errno", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.52.0", ] [[package]] name = "rustls" -version = "0.21.7" +version = "0.21.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd8d6c9f025a446bc4d18ad9632e69aec8f287aa84499ee335599fabd20c3fd8" +checksum = "f9d5a6813c0759e4609cd494e8e725babae6a2ca7b62a5536a13daaec6fcb7ba" dependencies = [ "log", - "ring 0.16.20", + "ring", "rustls-webpki", "sct", ] +[[package]] +name = "rustls-pemfile" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c" +dependencies = [ + "base64 0.21.7", +] + [[package]] name = "rustls-webpki" -version = "0.101.6" +version = "0.101.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c7d5dece342910d9ba34d259310cae3e0154b873b35408b787b59bce53d34fe" +checksum = "8b6275d1ee7a1cd780b64aca7726599a1dbc893b1e64144529e55c3c2f745765" dependencies = [ - "ring 0.16.20", - "untrusted 0.7.1", + "ring", + "untrusted", ] [[package]] @@ -2323,24 +2329,24 @@ checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" [[package]] name = "ryu" -version = "1.0.15" +version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" +checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1" [[package]] name = "schannel" -version = "0.1.22" +version = "0.1.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c3733bf4cf7ea0880754e19cb5a462007c4a8c1914bff372ccc95b464f1df88" +checksum = "fbc91545643bcf3a0bbb6569265615222618bdf33ce4ffbbd13c4bbd4c093534" dependencies = [ - "windows-sys", + "windows-sys 0.52.0", ] [[package]] name = "schemars" -version = "0.8.15" +version = "0.8.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f7b0ce13155372a76ee2e1c5ffba1fe61ede73fbea5630d61eee6fac4929c0c" +checksum = "45a28f4c49489add4ce10783f7911893516f15afe45d015608d41faca6bc4d29" dependencies = [ "chrono", "dyn-clone", @@ -2352,9 +2358,9 @@ dependencies = [ [[package]] name = "schemars_derive" -version = "0.8.15" +version = "0.8.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e85e2a16b12bdb763244c69ab79363d71db2b4b918a2def53f80b02e0574b13c" +checksum = "c767fd6fa65d9ccf9cf026122c1b555f2ef9a4f0cea69da4d7dbc3e258d30967" dependencies = [ "proc-macro2", "quote", @@ -2376,12 +2382,12 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "sct" -version = "0.7.0" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4" +checksum = "da046153aa2352493d6cb7da4b6e5c0c057d8a1d0a9aa8560baffdd945acd414" dependencies = [ - "ring 0.16.20", - "untrusted 0.7.1", + "ring", + "untrusted", ] [[package]] @@ -2450,9 +2456,9 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.188" +version = "1.0.197" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf9e0fcba69a370eed61bcf2b728575f726b50b55cba78064753d708ddc7549e" +checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2" dependencies = [ "serde_derive", ] @@ -2470,13 +2476,13 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.188" +version = "1.0.197" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2" +checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.53", ] [[package]] @@ -2492,9 +2498,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.107" +version = "1.0.114" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b420ce6e3d8bd882e9b243c6eed35dbc9a6110c9769e74b584e0d68d1f20c65" +checksum = "c5f09b1bd632ef549eaa9f60a1f8de742bdbc698e6cee2095fc84dde5f549ae0" dependencies = [ "itoa", "ryu", @@ -2503,9 +2509,9 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "0.6.3" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96426c9936fd7a0124915f9185ea1d20aa9445cc9821142f0a73bc9207a2e186" +checksum = "eb3622f419d1296904700073ea6cc23ad690adbd66f13ea683df73298736f0c1" dependencies = [ "serde", ] @@ -2564,9 +2570,9 @@ dependencies = [ [[package]] name = "signature" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e1788eed21689f9cf370582dfc467ef36ed9c707f073528ddafa8d83e3b8500" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ "digest 0.10.7", "rand_core 0.6.4", @@ -2592,28 +2598,18 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "942b4a808e05215192e39f4ab80813e599068285906cc91aa64f923db842bd5a" - -[[package]] -name = "socket2" -version = "0.4.9" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64a4a911eed85daf18834cfaa86a79b7d266ff93ff5ba14005426219480ed662" -dependencies = [ - "libc", - "winapi", -] +checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" [[package]] name = "socket2" -version = "0.5.4" +version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4031e820eb552adee9295814c0ced9e5cf38ddf1e8b7d566d6de8e2538ea989e" +checksum = "05ffd9c0a93b7543e062e759284fcf5f5e3b098501104bfbdde4d404db792871" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.52.0", ] [[package]] @@ -2633,9 +2629,9 @@ dependencies = [ [[package]] name = "spki" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d1e996ef02c474957d681f1b05213dfb0abab947b446a62d37770b23500184a" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" dependencies = [ "base64ct", "der", @@ -2643,9 +2639,9 @@ dependencies = [ [[package]] name = "sqlformat" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b7b278788e7be4d0d29c0f39497a0eef3fba6bbc8e70d8bf7fde46edeaa9e85" +checksum = "ce81b7bd7c4493975347ef60d8c7e8b742d4694f4c49f93e0a12ea263938176c" dependencies = [ "itertools", "nom", @@ -2654,9 +2650,9 @@ dependencies = [ [[package]] name = "sqlx" -version = "0.7.2" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e50c216e3624ec8e7ecd14c6a6a6370aad6ee5d8cfc3ab30b5162eeeef2ed33" +checksum = "c9a2ccff1a000a5a59cd33da541d9f2fdcd9e6e8229cc200565942bff36d0aaa" dependencies = [ "sqlx-core", "sqlx-macros", @@ -2667,17 +2663,16 @@ dependencies = [ [[package]] name = "sqlx-core" -version = "0.7.2" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d6753e460c998bbd4cd8c6f0ed9a64346fcca0723d6e75e52fdc351c5d2169d" +checksum = "24ba59a9342a3d9bab6c56c118be528b27c9b60e490080e9711a04dccac83ef6" dependencies = [ - "ahash 0.8.3", + "ahash 0.8.11", "atoi", "byteorder", "bytes", "crc", "crossbeam-queue", - "dotenvy", "either", "event-listener", "futures-channel", @@ -2687,7 +2682,7 @@ dependencies = [ "futures-util", "hashlink", "hex", - "indexmap 2.0.2", + "indexmap", "log", "memchr", "once_cell", @@ -2696,7 +2691,7 @@ dependencies = [ "serde", "serde_json", "sha2", - "smallvec 1.11.1", + "smallvec 1.13.2", "sqlformat", "thiserror", "time", @@ -2704,14 +2699,14 @@ dependencies = [ "tokio-stream", "tracing", "url", - "uuid 1.4.1", + "uuid 1.8.0", ] [[package]] name = "sqlx-macros" -version = "0.7.2" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a793bb3ba331ec8359c1853bd39eed32cdd7baaf22c35ccf5c92a7e8d1189ec" +checksum = "4ea40e2345eb2faa9e1e5e326db8c34711317d2b5e08d0d5741619048a803127" dependencies = [ "proc-macro2", "quote", @@ -2722,13 +2717,13 @@ dependencies = [ [[package]] name = "sqlx-macros-core" -version = "0.7.2" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a4ee1e104e00dedb6aa5ffdd1343107b0a4702e862a84320ee7cc74782d96fc" +checksum = "5833ef53aaa16d860e92123292f1f6a3d53c34ba8b1969f152ef1a7bb803f3c8" dependencies = [ "dotenvy", "either", - "heck", + "heck 0.4.1", "hex", "once_cell", "proc-macro2", @@ -2748,13 +2743,13 @@ dependencies = [ [[package]] name = "sqlx-mysql" -version = "0.7.2" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "864b869fdf56263f4c95c45483191ea0af340f9f3e3e7b4d57a61c7c87a970db" +checksum = "1ed31390216d20e538e447a7a9b959e06ed9fc51c37b514b46eb758016ecd418" dependencies = [ "atoi", - "base64 0.21.4", - "bitflags 2.4.0", + "base64 0.21.7", + "bitflags 2.5.0", "byteorder", "bytes", "crc", @@ -2780,25 +2775,25 @@ dependencies = [ "serde", "sha1", "sha2", - "smallvec 1.11.1", + "smallvec 1.13.2", "sqlx-core", "stringprep", "thiserror", "time", "tracing", - "uuid 1.4.1", + "uuid 1.8.0", "whoami", ] [[package]] name = "sqlx-postgres" -version = "0.7.2" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb7ae0e6a97fb3ba33b23ac2671a5ce6e3cabe003f451abd5a56e7951d975624" +checksum = "7c824eb80b894f926f89a0b9da0c7f435d27cdd35b8c655b114e58223918577e" dependencies = [ "atoi", - "base64 0.21.4", - "bitflags 2.4.0", + "base64 0.21.7", + "bitflags 2.5.0", "byteorder", "crc", "dotenvy", @@ -2819,23 +2814,22 @@ dependencies = [ "rand", "serde", "serde_json", - "sha1", "sha2", - "smallvec 1.11.1", + "smallvec 1.13.2", "sqlx-core", "stringprep", "thiserror", "time", "tracing", - "uuid 1.4.1", + "uuid 1.8.0", "whoami", ] [[package]] name = "sqlx-sqlite" -version = "0.7.2" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d59dc83cf45d89c555a577694534fcd1b55c545a816c816ce51f20bbe56a4f3f" +checksum = "b244ef0a8414da0bed4bb1910426e890b19e5e9bccc27ada6b797d05c55ae0aa" dependencies = [ "atoi", "flume", @@ -2852,7 +2846,8 @@ dependencies = [ "time", "tracing", "url", - "uuid 1.4.1", + "urlencoding", + "uuid 1.8.0", ] [[package]] @@ -2866,9 +2861,9 @@ dependencies = [ [[package]] name = "state" -version = "0.5.3" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbe866e1e51e8260c9eed836a042a5e7f6726bb2b411dffeaa712e19c388f23b" +checksum = "2b8c4a4445d81357df8b1a650d0d0d6fbbbfe99d064aa5e02f3e4022061476d8" dependencies = [ "loom", ] @@ -2886,9 +2881,9 @@ dependencies = [ [[package]] name = "strsim" -version = "0.10.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" +checksum = "5ee073c9e4cd00e28217186dbe12796d692868f432bf2e97ee73bed0c56dfa01" [[package]] name = "subtle" @@ -2909,15 +2904,21 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.38" +version = "2.0.53" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e96b79aaa137db8f61e26363a0c9b47d8b4ec75da28b7d1d614c2303e232408b" +checksum = "7383cd0e49fff4b6b90ca5670bfd3e9d6a733b3f90c686605aa7eec8c4996032" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" + [[package]] name = "system-configuration" version = "0.5.1" @@ -2941,42 +2942,41 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.8.0" +version = "3.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb94d2f3cc536af71caac6b6fcebf65860b347e7ce0cc9ebe8f70d3e521054ef" +checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" dependencies = [ "cfg-if", "fastrand", - "redox_syscall", "rustix", - "windows-sys", + "windows-sys 0.52.0", ] [[package]] name = "thiserror" -version = "1.0.49" +version = "1.0.58" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1177e8c6d7ede7afde3585fd2513e611227efd6481bd78d2e82ba1ce16557ed4" +checksum = "03468839009160513471e86a034bb2c5c0e4baae3b43f79ffc55c4a5427b3297" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.49" +version = "1.0.58" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10712f02019e9288794769fba95cd6847df9874d49d871d062172f9dd41bc4cc" +checksum = "c61f3ba182994efc43764a46c018c347bc492c79f024e705f46567b418f6d4f7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.53", ] [[package]] name = "thread_local" -version = "1.1.7" +version = "1.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fdd6f064ccff2d6567adcb3873ca630700f00b5ad3f060c25b5dcfd9a4ce152" +checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c" dependencies = [ "cfg-if", "once_cell", @@ -2984,12 +2984,14 @@ dependencies = [ [[package]] name = "time" -version = "0.3.29" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "426f806f4089c493dcac0d24c29c01e2c38baf8e30f1b716ee37e83d200b18fe" +checksum = "c8248b6521bb14bc45b4067159b9b6ad792e2d6d754d6c41fb50e29fefe38749" dependencies = [ "deranged", "itoa", + "num-conv", + "powerfmt", "serde", "time-core", "time-macros", @@ -3003,10 +3005,11 @@ checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" [[package]] name = "time-macros" -version = "0.2.15" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ad70d68dba9e1f8aceda7aa6711965dfec1cac869f311a51bd08b3a2ccbce20" +checksum = "7ba3a3ef41e6672a2f0f001392bb5dcd3ff0a9992d618ca761a11c3121547774" dependencies = [ + "num-conv", "time-core", ] @@ -3024,14 +3027,14 @@ dependencies = [ "serde", "serde_json", "sqlx", - "uuid 1.4.1", + "uuid 1.8.0", ] [[package]] name = "tokio" -version = "1.33.0" +version = "1.36.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f38200e3ef7995e5ef13baec2f432a6da0aa9ac495b2c0e8f3b7eec2c92d653" +checksum = "61285f6515fa018fb2d1e46eb21223fff441ee8db5d0f1435e8ab4f5cdb80931" dependencies = [ "backtrace", "bytes", @@ -3041,20 +3044,20 @@ dependencies = [ "parking_lot", "pin-project-lite", "signal-hook-registry", - "socket2 0.5.4", + "socket2", "tokio-macros", - "windows-sys", + "windows-sys 0.48.0", ] [[package]] name = "tokio-macros" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" +checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.53", ] [[package]] @@ -3081,9 +3084,9 @@ dependencies = [ [[package]] name = "tokio-stream" -version = "0.1.14" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "397c988d37662c7dda6d2208364a706264bf3d6138b11d436cbac0ad38832842" +checksum = "267ac89e0bec6e691e5813911606935d77c476ff49024f98abcea3e7b15e37af" dependencies = [ "futures-core", "pin-project-lite", @@ -3092,9 +3095,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.9" +version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d68074620f57a0b21594d9735eb2e98ab38b17f80d3fcb189fca266771ca60d" +checksum = "5419f34732d9eb6ee4c3578b7989078579b7f039cbbb9ca2c4da015749371e15" dependencies = [ "bytes", "futures-core", @@ -3115,9 +3118,9 @@ dependencies = [ [[package]] name = "toml" -version = "0.8.2" +version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d" +checksum = "e9dd1545e8208b4a5af1aa9bbd0b4cf7e9ea08fabc5d0a5c67fcaafa17433aa3" dependencies = [ "serde", "serde_spanned", @@ -3127,20 +3130,20 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "0.6.3" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" +checksum = "3550f4e9685620ac18a50ed434eb3aec30db8ba93b0287467bca5826ea25baf1" dependencies = [ "serde", ] [[package]] name = "toml_edit" -version = "0.20.2" +version = "0.22.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338" +checksum = "8e40bb779c5187258fd7aad0eb68cb8706a0a81fa712fbea808ab43c4b8374c4" dependencies = [ - "indexmap 2.0.2", + "indexmap", "serde", "serde_spanned", "toml_datetime", @@ -3155,11 +3158,10 @@ checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" [[package]] name = "tracing" -version = "0.1.37" +version = "0.1.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" +checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" dependencies = [ - "cfg-if", "log", "pin-project-lite", "tracing-attributes", @@ -3168,20 +3170,20 @@ dependencies = [ [[package]] name = "tracing-attributes" -version = "0.1.26" +version = "0.1.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f4f31f56159e98206da9efd823404b79b6ef3143b4a7ab76e67b1751b25a4ab" +checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.53", ] [[package]] name = "tracing-core" -version = "0.1.31" +version = "0.1.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0955b8137a1df6f1a2e9a37d8a6656291ff0297c1a97c24e0d8425fe2312f79a" +checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" dependencies = [ "once_cell", "valuable", @@ -3189,27 +3191,27 @@ dependencies = [ [[package]] name = "tracing-log" -version = "0.1.3" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ddad33d2d10b1ed7eb9d1f518a5674713876e97e5bb9b7345a7984fbb4f922" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" dependencies = [ - "lazy_static", "log", + "once_cell", "tracing-core", ] [[package]] name = "tracing-subscriber" -version = "0.3.17" +version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30a651bc37f915e81f087d86e62a18eec5f79550c7faff886f7090b4ea757c77" +checksum = "ad0f048c97dbd9faa9b7df56362b8ebcaa52adb06b498c050d2f4e32f90a7a8b" dependencies = [ "matchers", "nu-ansi-term", "once_cell", "regex", "sharded-slab", - "smallvec 1.11.1", + "smallvec 1.13.2", "thread_local", "tracing", "tracing-core", @@ -3218,9 +3220,9 @@ dependencies = [ [[package]] name = "try-lock" -version = "0.2.4" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] name = "typenum" @@ -3245,9 +3247,9 @@ checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9" [[package]] name = "uncased" -version = "0.9.9" +version = "0.9.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b9bc53168a4be7402ab86c3aad243a84dd7381d09be0eddc81280c1da95ca68" +checksum = "e1b88fcfe09e89d3866a5c11019378088af2d24c3fbd4f0543f96b479ec90697" dependencies = [ "serde", "version_check", @@ -3255,9 +3257,9 @@ dependencies = [ [[package]] name = "unicode-bidi" -version = "0.3.13" +version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460" +checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75" [[package]] name = "unicode-ident" @@ -3276,9 +3278,9 @@ dependencies = [ [[package]] name = "unicode-segmentation" -version = "1.10.1" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36" +checksum = "d4c87d22b6e3f4a18d4d40ef354e97c90fcb14dd91d7dc0aa9d8a1172ebf7202" [[package]] name = "unicode-xid" @@ -3302,12 +3304,6 @@ dependencies = [ "subtle", ] -[[package]] -name = "untrusted" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" - [[package]] name = "untrusted" version = "0.9.0" @@ -3325,6 +3321,12 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "urlencoding" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + [[package]] name = "utf8parse" version = "0.2.1" @@ -3339,9 +3341,9 @@ checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7" [[package]] name = "uuid" -version = "1.4.1" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79daa5ed5740825c40b389c5e50312b9c86df53fccd33f281df655642b43869d" +checksum = "a183cf7feeba97b4dd1c0d46788634f6221d87fa961b305bed08c851829efcc0" dependencies = [ "getrandom", "serde", @@ -3380,11 +3382,17 @@ version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +[[package]] +name = "wasite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" + [[package]] name = "wasm-bindgen" -version = "0.2.87" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342" +checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8" dependencies = [ "cfg-if", "wasm-bindgen-macro", @@ -3392,24 +3400,24 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.87" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd" +checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.53", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" -version = "0.4.37" +version = "0.4.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c02dbc21516f9f1f04f187958890d7e6026df8d16540b7ad9492bc34a67cea03" +checksum = "76bc14366121efc8dbb487ab05bcc9d346b3b5ec0eaa76e46594cabbe51762c0" dependencies = [ "cfg-if", "js-sys", @@ -3419,9 +3427,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.87" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d" +checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -3429,28 +3437,28 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.87" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" +checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.38", + "syn 2.0.53", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.87" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1" +checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" [[package]] name = "wasm-bindgen-test" -version = "0.3.37" +version = "0.3.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e6e302a7ea94f83a6d09e78e7dc7d9ca7b186bc2829c24a22d0753efd680671" +checksum = "d9bf62a58e0780af3e852044583deee40983e5886da43a271dd772379987667b" dependencies = [ "console_error_panic_hook", "js-sys", @@ -3462,19 +3470,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-test-macro" -version = "0.3.37" +version = "0.3.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecb993dd8c836930ed130e020e77d9b2e65dd0fbab1b67c790b0f5d80b11a575" +checksum = "b7f89739351a2e03cb94beb799d47fb2cac01759b40ec441f7de39b00cbf7ef0" dependencies = [ "proc-macro2", "quote", + "syn 2.0.53", ] [[package]] name = "web-sys" -version = "0.3.64" +version = "0.3.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b85cbef8c220a6abc02aefd892dfc0fc23afb1c6a426316ec33253a3877249b" +checksum = "77afa9a11836342370f4817622a2f0f418b134426d91a82dfb48f532d2ec13ef" dependencies = [ "js-sys", "wasm-bindgen", @@ -3486,8 +3495,8 @@ version = "0.22.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed63aea5ce73d0ff405984102c42de94fc55a6b75765d621c65262469b3c9b53" dependencies = [ - "ring 0.17.3", - "untrusted 0.9.0", + "ring", + "untrusted", ] [[package]] @@ -3501,9 +3510,13 @@ dependencies = [ [[package]] name = "whoami" -version = "1.4.1" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22fc3756b8a9133049b26c7f61ab35416c130e8c09b660f5b3958b446f52cc50" +checksum = "a44ab49fad634e88f55bf8f9bb3abd2f27d7204172a112c7c9987e01c1c94ea9" +dependencies = [ + "redox_syscall", + "wasite", +] [[package]] name = "winapi" @@ -3533,16 +3546,16 @@ version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" dependencies = [ - "windows-targets", + "windows-targets 0.48.5", ] [[package]] name = "windows-core" -version = "0.51.1" +version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1f8cf84f35d2db49a46868f947758c7a1138116f7fac3bc844f43ade1292e64" +checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" dependencies = [ - "windows-targets", + "windows-targets 0.52.4", ] [[package]] @@ -3551,7 +3564,16 @@ version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ - "windows-targets", + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.4", ] [[package]] @@ -3560,13 +3582,28 @@ version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd37b7e5ab9018759f893a1952c9420d060016fc19a472b4bb20d1bdd694d1b" +dependencies = [ + "windows_aarch64_gnullvm 0.52.4", + "windows_aarch64_msvc 0.52.4", + "windows_i686_gnu 0.52.4", + "windows_i686_msvc 0.52.4", + "windows_x86_64_gnu 0.52.4", + "windows_x86_64_gnullvm 0.52.4", + "windows_x86_64_msvc 0.52.4", ] [[package]] @@ -3575,47 +3612,89 @@ version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bcf46cf4c365c6f2d1cc93ce535f2c8b244591df96ceee75d8e83deb70a9cac9" + [[package]] name = "windows_aarch64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da9f259dd3bcf6990b55bffd094c4f7235817ba4ceebde8e6d11cd0c5633b675" + [[package]] name = "windows_i686_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" +[[package]] +name = "windows_i686_gnu" +version = "0.52.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b474d8268f99e0995f25b9f095bc7434632601028cf86590aea5c8a5cb7801d3" + [[package]] name = "windows_i686_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" +[[package]] +name = "windows_i686_msvc" +version = "0.52.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1515e9a29e5bed743cb4415a9ecf5dfca648ce85ee42e15873c3cd8610ff8e02" + [[package]] name = "windows_x86_64_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eee091590e89cc02ad514ffe3ead9eb6b660aedca2183455434b93546371a03" + [[package]] name = "windows_x86_64_gnullvm" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ca79f2451b49fa9e2af39f0747fe999fcda4f5e241b2898624dca97a1f2177" + [[package]] name = "windows_x86_64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32b752e52a2da0ddfbdbcc6fceadfeede4c939ed16d13e648833a61dfb611ed8" + [[package]] name = "winnow" -version = "0.5.16" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "037711d82167854aff2018dfd193aa0fef5370f456732f0d5a0c59b0f1b4b907" +checksum = "dffa400e67ed5a4dd237983829e66475f0a4a26938c4b04c21baede6262215b8" dependencies = [ "memchr", ] @@ -3627,7 +3706,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1" dependencies = [ "cfg-if", - "windows-sys", + "windows-sys 0.48.0", ] [[package]] @@ -3641,18 +3720,35 @@ dependencies = [ [[package]] name = "yansi" -version = "0.5.1" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" +dependencies = [ + "is-terminal", +] [[package]] -name = "yansi" -version = "1.0.0-rc.1" +name = "zerocopy" +version = "0.7.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1367295b8f788d371ce2dbc842c7b709c73ee1364d30351dd300ec2203b12377" +checksum = "74d4d3961e53fa4c9a25a8637fc2bfaf2595b3d3ae34875568a5cf64787716be" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.7.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.53", +] [[package]] name = "zeroize" -version = "1.6.0" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a0956f1ba7c7909bfb66c2e9e4124ab6f6482560f6628b5aaeba39207c9aad9" +checksum = "525b4ec142c6b68a2d10f01f7bbf6755599ca3f81ea53b8431b7dd348f5fdb2d" diff --git a/server/.env_example b/server/.env_example new file mode 100644 index 00000000..28584a0d --- /dev/null +++ b/server/.env_example @@ -0,0 +1,5 @@ +LOCKBOX = +NETWORK = +LOCKHEIGHT_INIT = +LH_DECREMENT = +CONNECTION_STRING = diff --git a/server/Cargo.toml b/server/Cargo.toml index 02b1d170..6a447216 100644 --- a/server/Cargo.toml +++ b/server/Cargo.toml @@ -18,7 +18,8 @@ uuid = { version = "1.3.1", features = ["v4", "serde"] } rand = "0.8.5" hex = "0.4.3" secp256k1-zkp = { git = "https://github.com/ssantos21/rust-secp256k1-zkp.git", branch = "blinded-musig-scheme", features = [ "rand-std", "bitcoin_hashes", "std" ] } +dotenv = "0.15.0" # secp256k1-zkp = { path = "../ss-rust-secp256k1-zkp", features = [ "rand-std", "bitcoin_hashes", "std" ] } [dependencies.mercury-lib] -path = "../lib" \ No newline at end of file +path = "../lib" diff --git a/server/src/server_config.rs b/server/src/server_config.rs index d0b5619a..f47623a0 100644 --- a/server/src/server_config.rs +++ b/server/src/server_config.rs @@ -1,5 +1,7 @@ -use config::Config; +use config::{Config as ConfigRs, Environment, File}; use serde::{Serialize, Deserialize}; +use std::env; +use dotenv::dotenv; /// Config struct storing all StataChain Entity config #[derive(Debug, Serialize, Deserialize)] @@ -16,19 +18,57 @@ pub struct ServerConfig { pub connection_string: String, } +impl Default for ServerConfig { + fn default() -> ServerConfig { + ServerConfig { + lockbox: None, + network: String::from("regtest"), + lockheight_init: 10000, + lh_decrement: 100, + connection_string: String::from("postgresql://postgres:postgres@localhost/mercury"), + } + } +} + +impl From for ServerConfig { + fn from(config: ConfigRs) -> Self { + ServerConfig { + lockbox: config.get::>("lockbox").unwrap_or(None), + network: config.get::("network").unwrap_or_else(|_| String::new()), + lockheight_init: config.get::("lockheight_init").unwrap_or(0), + lh_decrement: config.get::("lh_decrement").unwrap_or(0), + connection_string: config.get::("connection_string").unwrap_or_else(|_| String::new()), + } + } +} + impl ServerConfig { pub fn load() -> Self { - let settings = Config::builder() - .add_source(config::File::with_name("Settings")) - .build() - .unwrap(); + let mut conf_rs = ConfigRs::default(); + let _ = conf_rs + // First merge struct default config + .merge(ConfigRs::try_from(&ServerConfig::default()).unwrap()); + // Override with settings in file Settings.toml if exists + conf_rs.merge(File::with_name("Settings").required(false)); + // Override with settings in file Rocket.toml if exists + conf_rs.merge(File::with_name("Rocket").required(false)); - ServerConfig { - lockbox: Some(settings.get_string("lockbox").unwrap()), - network: settings.get_string("network").unwrap(), - lockheight_init: settings.get_int("lockheight_init").unwrap() as u32, - lh_decrement: settings.get_int("lh_decrement").unwrap() as u32, - connection_string: settings.get_string("connection_string").unwrap(), + dotenv().ok(); + if let Ok(v) = env::var("LOCKBOX") { + let _ = conf_rs.set("lockbox", v); + } + if let Ok(v) = env::var("NETWORK") { + let _ = conf_rs.set("network", v); + } + if let Ok(v) = env::var("LOCKHEIGHT_INIT") { + let _ = conf_rs.set("lockheight_init", v); + } + if let Ok(v) = env::var("LH_DECREMENT") { + let _ = conf_rs.set("lh_decrement", v); + } + if let Ok(v) = env::var("CONNECTION_STRING") { + let _ = conf_rs.set("connection_string", v); } + conf_rs.try_into().unwrap() } } \ No newline at end of file From 08c7aba0f2e8cfce33a49bf84cb56839dd12e30f Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Fri, 22 Mar 2024 15:10:35 +0530 Subject: [PATCH 02/66] fix: server config for token server --- .gitignore | 1 + Cargo.lock | 1 + token-server/.env_example | 5 +++ token-server/Cargo.toml | 1 + token-server/src/server_config.rs | 63 +++++++++++++++++++++++++------ 5 files changed, 60 insertions(+), 11 deletions(-) create mode 100644 token-server/.env_example diff --git a/.gitignore b/.gitignore index 860734b0..f93e7deb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /target /server/.env +/token-server/.env diff --git a/Cargo.lock b/Cargo.lock index 68a9eba3..47a75828 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3018,6 +3018,7 @@ name = "token-server" version = "0.1.0" dependencies = [ "config", + "dotenv", "hex", "mercury-lib", "rand", diff --git a/token-server/.env_example b/token-server/.env_example new file mode 100644 index 00000000..a3e024e8 --- /dev/null +++ b/token-server/.env_example @@ -0,0 +1,5 @@ +PROCESSOR_URL = +API_KEY = +FEE = +DELAY = +CONNECTION_STRING = diff --git a/token-server/Cargo.toml b/token-server/Cargo.toml index b5026d43..cf55dd71 100644 --- a/token-server/Cargo.toml +++ b/token-server/Cargo.toml @@ -16,6 +16,7 @@ schemars = { version = "0.8.12", features = ["chrono", "uuid"] } uuid = { version = "1.3.1", features = ["v4", "serde"] } rand = "0.8.5" hex = "0.4.3" +dotenv = "0.15.0" [dependencies.mercury-lib] path = "../lib" diff --git a/token-server/src/server_config.rs b/token-server/src/server_config.rs index 83de2bb2..7a07d3c0 100644 --- a/token-server/src/server_config.rs +++ b/token-server/src/server_config.rs @@ -1,5 +1,7 @@ -use config::Config; +use config::{Config as ConfigRs, Environment, File}; use serde::{Serialize, Deserialize}; +use std::env; +use dotenv::dotenv; /// Config struct storing all StataChain Entity config #[derive(Debug, Serialize, Deserialize)] @@ -16,20 +18,59 @@ pub struct ServerConfig { pub connection_string: String, } +impl Default for ServerConfig { + fn default() -> ServerConfig { + ServerConfig { + processor_url: String::from("http://0.0.0.0:18080"), + api_key: String::from("aaaaa"), + fee: String::from("10000"), + delay: 3600, + connection_string: String::from("postgresql://postgres:postgres@localhost/mercury"), + } + } +} + +impl From for ServerConfig { + fn from(config: ConfigRs) -> Self { + ServerConfig { + processor_url: config.get::("processor_url").unwrap_or_else(|_| String::new()), + api_key: config.get::("api_key").unwrap_or_else(|_| String::new()), + fee: config.get::("fee").unwrap_or_else(|_| String::new()), + delay: config.get::("delay").unwrap_or(0), + connection_string: config.get::("connection_string").unwrap_or_else(|_| String::new()), + } + } +} + impl ServerConfig { pub fn load() -> Self { - let settings = Config::builder() - .add_source(config::File::with_name("Settings")) - .build() - .unwrap(); + let mut conf_rs = ConfigRs::default(); + // let _ = conf_rs + // // First merge struct default config + // .merge(ConfigRs::try_from(&ServerConfig::default()).unwrap()); + // Override with settings in file Settings.toml if exists + conf_rs.merge(File::with_name("Settings").required(false)); + // Override with settings in file Rocket.toml if exists + conf_rs.merge(File::with_name("Rocket").required(false)); - ServerConfig { - processor_url: settings.get_string("processor_url").unwrap(), - api_key: settings.get_string("api_key").unwrap(), - fee: settings.get_string("fee").unwrap(), - delay: settings.get_int("delay").unwrap() as u64, - connection_string: settings.get_string("connection_string").unwrap(), + dotenv().ok(); + if let Ok(v) = env::var("PROCESSOR_URL") { + let _ = conf_rs.set("processor_url", v); + } + if let Ok(v) = env::var("API_KEY") { + let _ = conf_rs.set("api_key", v); + } + if let Ok(v) = env::var("FEE") { + let _ = conf_rs.set("fee", v); + } + if let Ok(v) = env::var("DELAY") { + let _ = conf_rs.set("delay", v); + } + if let Ok(v) = env::var("CONNECTION_STRING") { + let _ = conf_rs.set("connection_string", v); } + print!("{:?}", conf_rs); + conf_rs.try_into().unwrap() } } From 77971c9d8bddb75c9db656255140c2c762940fe2 Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Tue, 26 Mar 2024 13:56:28 +0530 Subject: [PATCH 03/66] feat: add docker build for github actions --- .github/workflows/ci.yaml | 39 +++++++++++++++++++++++++++++++++ lib/src/wallet/mod.rs | 8 +++---- server/Dockerfile | 14 ++++++++++++ server/src/endpoints/deposit.rs | 4 ++-- token-server/Dockerfile | 14 ++++++++++++ wasm/src/lib.rs | 12 +++++----- 6 files changed, 79 insertions(+), 12 deletions(-) create mode 100644 .github/workflows/ci.yaml create mode 100644 server/Dockerfile create mode 100644 token-server/Dockerfile diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml new file mode 100644 index 00000000..9b698113 --- /dev/null +++ b/.github/workflows/ci.yaml @@ -0,0 +1,39 @@ +name: ci + +on: + push: + branches: + - "main" + +jobs: + build: + runs-on: ubuntu-latest + steps: + - + name: Checkout + uses: actions/checkout@v4 + - + name: Login to Docker Hub + uses: docker/login-action@v3 + with: + username: commerceblockx + password: ${{ secrets.DOCKER_HUB_PASSWORD }} + - + name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + - + name: Build and push + uses: docker/build-push-action@v5 + with: + context: . + file: ./server/Dockerfile + push: true + tags: commerceblockx/mercury-server:latest + - + name: Build and push + uses: docker/build-push-action@v5 + with: + context: . + file: ./token-server/Dockerfile + push: true + tags: commerceblockx/token-server:latest diff --git a/lib/src/wallet/mod.rs b/lib/src/wallet/mod.rs index cfbe6c50..90d39c0f 100644 --- a/lib/src/wallet/mod.rs +++ b/lib/src/wallet/mod.rs @@ -24,7 +24,7 @@ pub struct Wallet { pub tokens: Vec, pub activities: Vec, pub coins: Vec, - pub settings: Settings, + // pub settings: Settings, } @@ -48,14 +48,14 @@ pub struct Settings { } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Token { - pub btc_payment_address: String, - pub fee: String, + // pub btc_payment_address: String, + // pub fee: String, pub lightning_invoice: String, pub processor_id: String, pub token_id: String, pub confirmed: bool, pub spent: bool, - pub expiry: String, + // pub expiry: String, } #[derive(Debug, Serialize, Deserialize, Clone)] diff --git a/server/Dockerfile b/server/Dockerfile new file mode 100644 index 00000000..1443f869 --- /dev/null +++ b/server/Dockerfile @@ -0,0 +1,14 @@ +FROM rust:1.77.0 + +# Set working directory +WORKDIR /app/lib +COPY ../lib . + +# Copy the project code +WORKDIR /app +COPY . . + +RUN cargo build --release + +# Run the application +CMD ["cargo", "run"] diff --git a/server/src/endpoints/deposit.rs b/server/src/endpoints/deposit.rs index 0dd73d6a..f5f4abf4 100644 --- a/server/src/endpoints/deposit.rs +++ b/server/src/endpoints/deposit.rs @@ -126,7 +126,7 @@ pub async fn token_init(statechain_entity: &State) -> status:: let token_id = uuid::Uuid::new_v4().to_string(); let processor_id = uuid::Uuid::new_v4().to_string(); - let invoice = String::from("lnbc10u1pj3knpdsp5k9f25s2wpzewkf9c78pftkgnkuuz82erkcjml7zkgsp7znyhs5yspp5rxz3tkc7ydgln3u7ez6duhp0g6jpzgtnn7ph5xrjy6muh9xm07wqdp2f9h8vmmfvdjjqen0wgsy6ctfdeehgcteyp6x76m9dcxqyjw5qcqpj9qyysgq6z9whs8am75r6mzcgt76vlwgk5g9yq5g8xefdxx6few6d5why7fs7h5g2dx9hk7s60ywtnkyc0f3p0cha4a9kmgkq5jvu5e7hvsaawqpjtf8p4"); + let lightning_invoice = String::from("lnbc10u1pj3knpdsp5k9f25s2wpzewkf9c78pftkgnkuuz82erkcjml7zkgsp7znyhs5yspp5rxz3tkc7ydgln3u7ez6duhp0g6jpzgtnn7ph5xrjy6muh9xm07wqdp2f9h8vmmfvdjjqen0wgsy6ctfdeehgcteyp6x76m9dcxqyjw5qcqpj9qyysgq6z9whs8am75r6mzcgt76vlwgk5g9yq5g8xefdxx6few6d5why7fs7h5g2dx9hk7s60ywtnkyc0f3p0cha4a9kmgkq5jvu5e7hvsaawqpjtf8p4"); let confirmed = false; let spent = false; @@ -134,7 +134,7 @@ pub async fn token_init(statechain_entity: &State) -> status:: let token = mercury_lib::wallet::Token { token_id, - invoice, + lightning_invoice, processor_id, confirmed, spent, diff --git a/token-server/Dockerfile b/token-server/Dockerfile new file mode 100644 index 00000000..1443f869 --- /dev/null +++ b/token-server/Dockerfile @@ -0,0 +1,14 @@ +FROM rust:1.77.0 + +# Set working directory +WORKDIR /app/lib +COPY ../lib . + +# Copy the project code +WORKDIR /app +COPY . . + +RUN cargo build --release + +# Run the application +CMD ["cargo", "run"] diff --git a/wasm/src/lib.rs b/wasm/src/lib.rs index 6a4fac5e..08051132 100644 --- a/wasm/src/lib.rs +++ b/wasm/src/lib.rs @@ -428,24 +428,24 @@ pub fn getCoin(wallet_json: JsValue, statechain_id: String) -> JsValue { pub fn getMockWallet() -> JsValue { let tokens = vec![ Token { - btc_payment_address: String::from("bc1..."), - fee: String::from("0.001"), + // btc_payment_address: String::from("bc1..."), + // fee: String::from("0.001"), lightning_invoice: String::from("lnbc10u1pj3knpdsp5k9f25s2wpzewkf9c78pftkgnkuuz82erkcjml7zkgsp7znyhs5yspp5rxz3tkc7ydgln3u7ez6duhp0g6jpzgtnn7ph5xrjy6muh9xm07wqdp2f9h8vmmfvdjjqen0wgsy6ctfdeehgcteyp6x76m9dcxqyjw5qcqpj9qyysgq6z9whs8am75r6mzcgt76vlwgk5g9yq5g8xefdxx6few6d5why7fs7h5g2dx9hk7s60ywtnkyc0f3p0cha4a9kmgkq5jvu5e7hvsaawqpjtf8p4"), processor_id: String::from("e04r5e00-cgdd-5yb7-y704-52631405720e"), token_id: String::from("e08aee00-cfed-4ab7-b304-38d61405720e"), confirmed: true, spent: false, - expiry: "2023-11-07T12:34:56.789Z".to_string() + // expiry: "2023-11-07T12:34:56.789Z".to_string() }, Token { - btc_payment_address: String::from("bc1..."), - fee: String::from("0.001"), + // btc_payment_address: String::from("bc1..."), + // fee: String::from("0.001"), processor_id: String::from("e04r5e00-cgdd-5yb7-y704-52631405720e"), lightning_invoice: String::from("lnbc10u1pj3knpdsp5k9f25s2wpzewkf9c78pftkgnkuuz82erkcjml7zkgsp7znyhs5yspp5rxz3tkc7ydgln3u7ez6duhp0g6jpzgtnn7ph5xrjy6muh9xm07wqdp2f9h8vmmfvdjjqen0wgsy6ctfdeehgcteyp6x76m9dcxqyjw5qcqpj9qyysgq6z9whs8am75r6mzcgt76vlwgk5g9yq5g8xefdxx6few6d5why7fs7h5g2dx9hk7s60ywtnkyc0f3p0cha4a9kmgkq5jvu5e7hvsaawqpjtf8p4"), token_id: String::from("aed9a34c-5666-4d83-940f-9b74e16b8672"), confirmed: true, spent: false, - expiry: "2023-11-07T12:34:56.789Z".to_string() + // expiry: "2023-11-07T12:34:56.789Z".to_string() } ]; From 6a02b48faa2ca9b54b5f3f9f6210e8ebb9c6a5be Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Tue, 26 Mar 2024 14:05:50 +0530 Subject: [PATCH 04/66] feat: add dev branch to yaml --- .github/workflows/ci.yaml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 9b698113..c09cb26c 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -1,9 +1,12 @@ name: ci on: + pull_request: + branches: + - dev push: branches: - - "main" + - main jobs: build: From fb9414ecebed7dc1a3955b99e800e0b3ffd59ab6 Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Wed, 27 Mar 2024 20:40:44 +0530 Subject: [PATCH 05/66] fix: token server port --- token-server/src/main.rs | 1 + token-server/src/server_config.rs | 2 -- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/token-server/src/main.rs b/token-server/src/main.rs index 522701cd..92e9ccd1 100644 --- a/token-server/src/main.rs +++ b/token-server/src/main.rs @@ -44,6 +44,7 @@ async fn main() { .manage(token_server) .attach(Cors) // .attach(MercuryPgDatabase::fairing()) + .listen(8001) .launch() .await; } diff --git a/token-server/src/server_config.rs b/token-server/src/server_config.rs index 7a07d3c0..6a02b1a8 100644 --- a/token-server/src/server_config.rs +++ b/token-server/src/server_config.rs @@ -69,8 +69,6 @@ impl ServerConfig { if let Ok(v) = env::var("CONNECTION_STRING") { let _ = conf_rs.set("connection_string", v); } - print!("{:?}", conf_rs); conf_rs.try_into().unwrap() } } - From 3cfdab5e409abe5baa2ad6bce16e54c389703704 Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Wed, 27 Mar 2024 21:10:03 +0530 Subject: [PATCH 06/66] fix: config for token server port --- token-server/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/token-server/src/main.rs b/token-server/src/main.rs index 92e9ccd1..044c1487 100644 --- a/token-server/src/main.rs +++ b/token-server/src/main.rs @@ -44,7 +44,7 @@ async fn main() { .manage(token_server) .attach(Cors) // .attach(MercuryPgDatabase::fairing()) - .listen(8001) + .configure(rocket::Config::figment().merge(("port", 8001))) .launch() .await; } From 8abadd9efc5e9b1bef3951c3c0367b02722f774a Mon Sep 17 00:00:00 2001 From: "S. Santos" Date: Sat, 30 Mar 2024 23:09:05 -0300 Subject: [PATCH 07/66] [WIP] Add Sealing Key --- enclave/App/App.cpp | 73 ++++--- enclave/App/database/db_manager.cpp | 99 +++++++++ enclave/App/database/db_manager.h | 15 ++ enclave/App/remote-attestation.cpp | 150 ------------- enclave/App/remote-attestation.h | 30 --- .../sealing_key_manager.cpp | 201 ++++++++++++++++++ .../sealing_key_manager/sealing_key_manager.h | 53 +++++ enclave/App/utilities/utilities.cpp | 19 ++ enclave/App/utilities/utilities.h | 20 ++ enclave/Enclave/Enclave.cpp | 125 +++++++---- enclave/Enclave/Enclave.edl | 9 +- enclave/Makefile | 8 +- enclave/README.md | 22 ++ 13 files changed, 563 insertions(+), 261 deletions(-) create mode 100644 enclave/App/database/db_manager.cpp create mode 100644 enclave/App/database/db_manager.h delete mode 100644 enclave/App/remote-attestation.cpp delete mode 100644 enclave/App/remote-attestation.h create mode 100644 enclave/App/sealing_key_manager/sealing_key_manager.cpp create mode 100644 enclave/App/sealing_key_manager/sealing_key_manager.h create mode 100644 enclave/App/utilities/utilities.cpp create mode 100644 enclave/App/utilities/utilities.h diff --git a/enclave/App/App.cpp b/enclave/App/App.cpp index 45b41bfb..662dd12c 100644 --- a/enclave/App/App.cpp +++ b/enclave/App/App.cpp @@ -19,7 +19,8 @@ #include "../utils/include_secp256k1_zkp_lib.h" #include "../utils/strencodings.h" -#include "remote-attestation.h" +#include "utilities/utilities.h" +#include "sealing_key_manager/sealing_key_manager.h" #include "App.h" #include "Enclave_u.h" @@ -28,19 +29,6 @@ # define ENCLAVE_FILENAME "enclave.signed.so" -// extracted from sdk/tseal/tSeal_util.cpp -uint32_t sgx_calc_sealed_data_size(const uint32_t add_mac_txt_size, const uint32_t txt_encrypt_size) -{ - if(add_mac_txt_size > UINT32_MAX - txt_encrypt_size) - return UINT32_MAX; - uint32_t payload_size = add_mac_txt_size + txt_encrypt_size; //Calculate the payload size - - if(payload_size > UINT32_MAX - sizeof(sgx_sealed_data_t)) - return UINT32_MAX; - return (uint32_t)(sizeof(sgx_sealed_data_t) + payload_size); -} - - bool save_generated_public_key( std::string& database_connection_string, char* sealed, size_t sealed_size, @@ -291,6 +279,14 @@ int SGX_CDECL main(int argc, char *argv[]) (void)(argc); (void)(argv); + sealing_key_manager::SealingKeyManager sealing_key_manager; + + if (sealing_key_manager.isSeedEmpty()) { + printf("Seed is empty\n"); + } else { + printf("Seed is not empty\n"); + } + crow::SimpleApp app; sgx_enclave_id_t enclave_id = 0; @@ -328,7 +324,7 @@ int SGX_CDECL main(int argc, char *argv[]) size_t server_pubkey_size = 33; // serialized compressed public keys are 33-byte array unsigned char server_pubkey[server_pubkey_size]; - size_t sealedprivkey_size = sgx_calc_sealed_data_size(0U, sizeof(secp256k1_keypair)); + size_t sealedprivkey_size = utils::sgx_calc_sealed_data_size(0U, sizeof(secp256k1_keypair)); char sealedprivkey[sealedprivkey_size]; const std::lock_guard lock(mutex_enclave_id); @@ -375,10 +371,10 @@ int SGX_CDECL main(int argc, char *argv[]) std::string statechain_id = req_body["statechain_id"].s(); - size_t sealed_keypair_size = sgx_calc_sealed_data_size(0U, sizeof(secp256k1_keypair)); + size_t sealed_keypair_size = utils::sgx_calc_sealed_data_size(0U, sizeof(secp256k1_keypair)); std::vector sealed_keypair(sealed_keypair_size); // Using a vector to manage dynamic-sized array. - size_t sealed_secnonce_size = sgx_calc_sealed_data_size(0U, sizeof(secp256k1_musig_secnonce)); + size_t sealed_secnonce_size = utils::sgx_calc_sealed_data_size(0U, sizeof(secp256k1_musig_secnonce)); std::vector sealed_secnonce(sealed_secnonce_size); // Using a vector to manage dynamic-sized array. unsigned char serialized_server_pubnonce[66]; @@ -464,10 +460,10 @@ int SGX_CDECL main(int argc, char *argv[]) return crow::response(400, "Invalid session length. Must be 133 bytes!"); } - size_t sealed_keypair_size = sgx_calc_sealed_data_size(0U, sizeof(secp256k1_keypair)); + size_t sealed_keypair_size = utils::sgx_calc_sealed_data_size(0U, sizeof(secp256k1_keypair)); std::vector sealed_keypair(sealed_keypair_size); // Using a vector to manage dynamic-sized array. - size_t sealed_secnonce_size = sgx_calc_sealed_data_size(0U, sizeof(secp256k1_musig_secnonce)); + size_t sealed_secnonce_size = utils::sgx_calc_sealed_data_size(0U, sizeof(secp256k1_musig_secnonce)); std::vector sealed_secnonce(sealed_secnonce_size); // Using a vector to manage dynamic-sized array. unsigned char serialized_server_pubnonce[66]; @@ -595,10 +591,10 @@ int SGX_CDECL main(int argc, char *argv[]) return crow::response(400, "Invalid x1 length. Must be 32 bytes!"); } - size_t sealed_keypair_size = sgx_calc_sealed_data_size(0U, sizeof(secp256k1_keypair)); + size_t sealed_keypair_size = utils::sgx_calc_sealed_data_size(0U, sizeof(secp256k1_keypair)); std::vector sealed_keypair(sealed_keypair_size); // Using a vector to manage dynamic-sized array. - size_t sealed_secnonce_size = sgx_calc_sealed_data_size(0U, sizeof(secp256k1_musig_secnonce)); + size_t sealed_secnonce_size = utils::sgx_calc_sealed_data_size(0U, sizeof(secp256k1_musig_secnonce)); std::vector sealed_secnonce(sealed_secnonce_size); // Using a vector to manage dynamic-sized array. unsigned char serialized_server_pubnonce[66]; @@ -630,7 +626,7 @@ int SGX_CDECL main(int argc, char *argv[]) size_t new_server_pubkey_size = 33; // serialized compressed public keys are 33-byte array unsigned char new_server_pubkey[new_server_pubkey_size]; - size_t new_sealedkeypair_size = sgx_calc_sealed_data_size(0U, sizeof(secp256k1_keypair)); + size_t new_sealedkeypair_size = utils::sgx_calc_sealed_data_size(0U, sizeof(secp256k1_keypair)); char new_sealedkeypair[new_sealedkeypair_size]; const std::lock_guard lock(mutex_enclave_id); @@ -687,15 +683,36 @@ int SGX_CDECL main(int argc, char *argv[]) } }); - CROW_ROUTE(app,"/test_ra") - ([&enclave_id, &mutex_enclave_id](){ - const std::lock_guard lock(mutex_enclave_id); - ExecuteRemoteAttestation(); + CROW_ROUTE(app, "/add_mnemonic") + .methods("POST"_method)([&enclave_id, &mutex_enclave_id, &sealing_key_manager](const crow::request& req) { + + auto req_body = crow::json::load(req.body); + if (!req_body) { + return crow::response(400); + } + + if (req_body.count("mnemonic") == 0 || + req_body.count("index") == 0 || + req_body.count("threshold") == 0) { + return crow::response(400, "Invalid parameters. They must be 'mnemonic', 'index' and 'threshold'."); + } + + std::string mnemonic = req_body["mnemonic"].s(); + int64_t index = req_body["index"].i(); + int64_t threshold = req_body["threshold"].i(); - crow::json::wvalue result({{"message", "Tested."}}); - return crow::response{result}; + const std::lock_guard lock(mutex_enclave_id); + + auto ret = sealing_key_manager.addMnemonic(enclave_id, mnemonic, (size_t) index, (size_t) threshold); + + if (!ret.success) { + return crow::response(ret.code, ret.message); + } + + crow::json::wvalue result({{"message", "OK."}}); + return crow::response{result}; }); app.port(18080).multithreaded().run(); diff --git a/enclave/App/database/db_manager.cpp b/enclave/App/database/db_manager.cpp new file mode 100644 index 00000000..76e16713 --- /dev/null +++ b/enclave/App/database/db_manager.cpp @@ -0,0 +1,99 @@ +#include "db_manager.h" + +#include "../lib/toml.hpp" +#include +#include + +namespace db_manager { + + bool add_sealed_seed(char* sealed_secret, size_t sealed_secret_size, std::string& error_message) { + + auto config = toml::parse_file("Settings.toml"); + auto database_connection_string = config["intel_sgx"]["database_connection_string"].as_string()->get(); + + try + { + pqxx::connection conn(database_connection_string); + if (conn.is_open()) { + + std::string create_table_query = + "CREATE TABLE IF NOT EXISTS seed ( " + "id SERIAL PRIMARY KEY, " + "sealed_seed BYTEA NOT NULL);"; + + pqxx::work txn(conn); + txn.exec(create_table_query); + txn.commit(); + + std::string insert_command = "INSERT INTO seed (sealed_seed) VALUES ($1);"; + pqxx::work txn2(conn); + + std::basic_string_view sealed_data_view(reinterpret_cast(sealed_secret), sealed_secret_size); + + txn2.exec_params(insert_command, sealed_data_view); + txn2.commit(); + + conn.close(); + return true; + } else { + error_message = "Failed to connect to the database!"; + return false; + } + } + catch (std::exception const &e) + { + error_message = e.what(); + return false; + } + + return true; + + } // add_sealed_seed + + bool get_sealed_seed(char* sealed_secret, size_t sealed_secret_size, std::string& error_message) { + + auto config = toml::parse_file("Settings.toml"); + auto database_connection_string = config["intel_sgx"]["database_connection_string"].as_string()->get(); + + try + { + pqxx::connection conn(database_connection_string); + if (conn.is_open()) { + + std::string select_command = "SELECT sealed_seed FROM seed ORDER BY id DESC LIMIT 1;"; + pqxx::work txn(conn); + + pqxx::result result = txn.exec(select_command); + + if (result.size() == 0) { + error_message = "No sealed seed found!"; + return false; + } + + pqxx::binarystring sealed_data = result[0]["sealed_seed"].as(); + + if (sealed_data.size() != sealed_secret_size) { + error_message = "Failed to retrieve keypair. Different size than expected !"; + return false; + } + + std::memcpy(sealed_secret, sealed_data.data(), sealed_data.size()); + + txn.commit(); + conn.close(); + return true; + } else { + error_message = "Failed to connect to the database!"; + return false; + } + } + catch (std::exception const &e) + { + error_message = e.what(); + return false; + } + + return true; + + } // get_sealed_seed +} \ No newline at end of file diff --git a/enclave/App/database/db_manager.h b/enclave/App/database/db_manager.h new file mode 100644 index 00000000..86ff9362 --- /dev/null +++ b/enclave/App/database/db_manager.h @@ -0,0 +1,15 @@ +#pragma once + +#ifndef DB_MANAGER_H +#define DB_MANAGER_H + +#include + +namespace db_manager { + + // Remove these 2 functions. Sealed seeds should be stored in the file system. + bool add_sealed_seed(char* sealed_secret, size_t sealed_secret_size, std::string& error_message); + bool get_sealed_seed(char* sealed_secret, size_t sealed_secret_size, std::string& error_message); +} + +#endif // DB_MANAGER_H \ No newline at end of file diff --git a/enclave/App/remote-attestation.cpp b/enclave/App/remote-attestation.cpp deleted file mode 100644 index 05959374..00000000 --- a/enclave/App/remote-attestation.cpp +++ /dev/null @@ -1,150 +0,0 @@ -#include "remote-attestation.h" -#include - -#include -#include -#include -#include - -#include "Enclave_u.h" - -// Needed to call untrusted key exchange library APIs, i.e. sgx_ra_proc_msg2. -// #include "sgx_ukey_exchange.h" - -// Needed to create enclave and do ecall. -#include "sgx_urts.h" - -// Needed to query extended epid group id. -#include "sgx_uae_epid.h" -#include "sgx_uae_quote_ex.h" - -#ifndef SAFE_FREE -#define SAFE_FREE(ptr) {if (NULL != (ptr)) {free(ptr); (ptr) = NULL;}} -#endif - -void format_egid_to_big_endian_hex_string(uint32_t gid, char* outStr) { - sprintf(outStr, "%02X%02X%02X%02X", - (gid >> 24) & 0xFF, - (gid >> 16) & 0xFF, - (gid >> 8) & 0xFF, - gid & 0xFF); -} - -// Some utility functions to output some of the data structures passed between -// the ISV app and the remote attestation service provider. -void PRINT_BYTE_ARRAY(FILE *file, void *mem, uint32_t len) -{ - if(!mem || !len) - { - fprintf(file, "\n( null )\n"); - return; - } - uint8_t *array = (uint8_t *)mem; - fprintf(file, "%u bytes:\n{\n", len); - uint32_t i = 0; - for(i = 0; i < len - 1; i++) - { - fprintf(file, "0x%x, ", array[i]); - if(i % 8 == 7) fprintf(file, "\n"); - } - fprintf(file, "0x%x ", array[i]); - fprintf(file, "\n}\n"); -} - -int ExecuteRemoteAttestation() { - // ra_samp_request_header_t *p_msg0_full = NULL; - - sgx_ra_context_t context = INT_MAX; - sgx_enclave_id_t enclave_id = 0; - sgx_status_t status = SGX_SUCCESS; - FILE* OUTPUT = stdout; - - int ret = 0; - - auto config = toml::parse_file("Settings.toml"); - auto base_url = config["intel_sgx"]["base_url"].as_string()->get(); - auto primary_key = config["intel_sgx"]["primary_key"].as_string()->get(); - - cpr::Response cpr_response; - std::string url; - char egid_hex_big_endian[9]; // 8 characters + null terminator - std::string body; - - uint32_t extended_epid_group_id = 0; - ret = sgx_get_extended_epid_group_id(&extended_epid_group_id); - if (SGX_SUCCESS != ret) - { - ret = -1; - fprintf(OUTPUT, "\nError, call sgx_get_extended_epid_group_id fail [%s].", - __FUNCTION__); - return ret; - } - fprintf(OUTPUT, "\nCall sgx_get_extended_epid_group_id success."); - - format_egid_to_big_endian_hex_string(extended_epid_group_id, egid_hex_big_endian); - body = std::string(egid_hex_big_endian); - - std::cout << "body: " << body << "\n"; - - /* p_msg0_full = (ra_samp_request_header_t*) malloc(sizeof(ra_samp_request_header_t) + sizeof(uint32_t)); - if (NULL == p_msg0_full) - { - ret = -1; - goto CLEANUP; - } - p_msg0_full->type = TYPE_RA_MSG0; - p_msg0_full->size = sizeof(uint32_t); - - *(uint32_t*)((uint8_t*)p_msg0_full + sizeof(ra_samp_request_header_t)) = extended_epid_group_id; - { - - // fprintf(OUTPUT, "\nMSG0 body generated -\n"); - - // PRINT_BYTE_ARRAY(OUTPUT, p_msg0_full->body, p_msg0_full->size); - - }*/ - // The ISV application sends msg0 to the SP. - // The ISV decides whether to support this extended epid group id. - fprintf(OUTPUT, "\nSending msg0 to remote attestation service provider.\n"); - - url = base_url + std::string("attestation/v5/sigrl/"+ body); - - cpr_response = cpr::Get(cpr::Url{url}, cpr::Header{{"Ocp-Apim-Subscription-Key", primary_key}}); - - if (cpr_response.status_code != 200) { - std::cout << "Error: " << cpr_response.status_code << std::endl; - ret = -1; - goto CLEANUP; - } else { - std::cout << "Success: " << cpr_response.status_code << std::endl; - - } - - CLEANUP: - // Clean-up - // Need to close the RA key state. - if(INT_MAX != context) - { - int ret_save = ret; - ret = enclave_ra_close(enclave_id, &status, context); - if(SGX_SUCCESS != ret || status) - { - ret = -1; - fprintf(OUTPUT, "\nError, call enclave_ra_close fail [%s].", - __FUNCTION__); - } - else - { - // enclave_ra_close was successful, let's restore the value that - // led us to this point in the code. - ret = ret_save; - } - fprintf(OUTPUT, "\nCall enclave_ra_close success."); - } - - sgx_destroy_enclave(enclave_id); - - // SAFE_FREE(p_msg0_full); - - return ret; -} \ No newline at end of file diff --git a/enclave/App/remote-attestation.h b/enclave/App/remote-attestation.h deleted file mode 100644 index 58253b48..00000000 --- a/enclave/App/remote-attestation.h +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once - -#ifndef REMOTE_ATTESTATION_H -#define REMOTE_ATTESTATION_H - -#include - -/* Enum for all possible message types between the ISV app and - * the ISV SP. Requests and responses in the remote attestation - * sample. - */ -typedef enum _ra_msg_type_t -{ - TYPE_RA_MSG0, - TYPE_RA_MSG1, - TYPE_RA_MSG2, - TYPE_RA_MSG3, - TYPE_RA_ATT_RESULT, -}ra_msg_type_t; - -typedef struct _ra_samp_request_header_t{ - uint8_t type; /* set to one of ra_msg_type_t*/ - uint32_t size; /*size of request body*/ - uint8_t align[3]; - uint8_t body[]; -}ra_samp_request_header_t; - -int ExecuteRemoteAttestation(); - -#endif // REMOTE_ATTESTATION_H \ No newline at end of file diff --git a/enclave/App/sealing_key_manager/sealing_key_manager.cpp b/enclave/App/sealing_key_manager/sealing_key_manager.cpp new file mode 100644 index 00000000..fda509a8 --- /dev/null +++ b/enclave/App/sealing_key_manager/sealing_key_manager.cpp @@ -0,0 +1,201 @@ +#include "sealing_key_manager.h" + +#include "../../utils/strencodings.h" +#include "../database/db_manager.h" +#include "../Enclave_u.h" +#include "../utilities/utilities.h" + +#include +#include +#include +#include +#include + +namespace sealing_key_manager { + + utils::APIResponse SealingKeyManager::addKeyShare(sgx_enclave_id_t& enclave_id, const KeyShare& new_key_share, size_t _threshold) { + + if (threshold == 0) { + threshold = _threshold; + } else if (threshold != _threshold) { + return utils::APIResponse { + .success = false, + .code = 400, + .message = "Threshold mismatch" + }; + } + + for (const auto& key_share : key_shares) { + if (key_share.index == new_key_share.index) { + return utils::APIResponse { + .success = false, + .code = 400, + .message = "Index already used" + }; + } + } + + for (const auto& key_share : key_shares) { + if (key_share.data_size == new_key_share.data_size && std::memcmp(key_share.data, new_key_share.data, key_share.data_size) == 0) { + return utils::APIResponse { + .success = false, + .code = 400, + .message = "Key share already exists" + }; + } + } + + std::lock_guard lock(mutex_key_shares); + key_shares.push_back(new_key_share); + + listKeyShares(); + + if (key_shares.size() == threshold) { + // Recover seed + auto ret = recoverSeed(enclave_id); + if (!ret.success) { + return ret; + } + } + + if (!isSeedEmpty()) { + std::string error_message; + auto ret = db_manager::add_sealed_seed(sealed_seed, sealed_seed_size, error_message); + if (!ret) { + return utils::APIResponse { + .success = false, + .code = 500, + .message = error_message + }; + } + } + + return utils::APIResponse { + .success = true, + .code = 0, + .message = "" + }; + } + + utils::APIResponse SealingKeyManager::addMnemonic(sgx_enclave_id_t& enclave_id, const std::string& mnemonic, size_t index, size_t _threshold) { + + size_t max_secret_len = SECRET_SIZE; + uint8_t secret[max_secret_len]; + memset(secret, 0, max_secret_len); + size_t secret_len = bip39_secret_from_mnemonics(mnemonic.c_str(), secret, max_secret_len); + + // const auto key_share = KeyShare { + // .index = index, + // .data = (char *) secret, + // .data_size = secret_len + // }; + + auto key_share = KeyShare(); + key_share.index = index; + key_share.data_size = secret_len; + key_share.data = new char[secret_len]; + + memcpy(key_share.data, secret, secret_len); + + auto secret_hex = key_to_string((unsigned char *) secret, secret_len); + + printf("secret_hex: %s\n", secret_hex.c_str()); + + return addKeyShare(enclave_id, key_share, _threshold); + + // auto secret_hex = key_to_string((unsigned char *) secret, secret_len); + + // printf("secret_hex: %s\n", secret_hex.c_str()); + } + + void SealingKeyManager::listKeyShares() { + // std::lock_guard lock(mutex_key_shares); + for (const auto& key_share : key_shares) { + auto key_share_data_hex = key_to_string((unsigned char *) key_share.data, key_share.data_size); + + printf("Key share: %s index: %zu\n", key_share_data_hex.c_str(), key_share.index); + } + } + + bool SealingKeyManager::isSeedEmpty() { + auto is_null = sealed_seed == nullptr; + bool is_seed_empty = std::all_of(sealed_seed, sealed_seed + sealed_seed_size, [](unsigned char c) { + return c == 0; + }); + return is_null || is_seed_empty; + } + + utils::APIResponse SealingKeyManager::recoverSeed(sgx_enclave_id_t& enclave_id) { + + // Calculate the total size needed for all sealed_data + size_t total_size = 0; + for (const auto& ks : key_shares) { + total_size += ks.data_size; + } + + // Allocate memory for all_key_shares + char* all_key_shares = new char[total_size]; + + size_t key_shares_size = key_shares.size(); + + // Allocate memory for key_share_indexes + uint8_t key_share_indexes[key_shares_size]; + + // Fill the arrays + size_t current_position = 0; + for (size_t i = 0; i < key_shares_size; ++i) { + + // Copy sealed_data into all_key_shares + memcpy(all_key_shares + current_position, key_shares[i].data, key_shares[i].data_size); + current_position += key_shares[i].data_size; + + // Fill key_share_indexes + key_share_indexes[i] = (uint8_t) key_shares[i].index; + } + + // auto all_key_shares_hex = key_to_string((unsigned char *) all_key_shares, total_size); + + // printf("all key shares: %s \n", all_key_shares_hex.c_str()); + + // for (size_t i = 0; i < key_shares_size; ++i) { + // printf("key_share_indexes[%zu]: %u\n", i, key_share_indexes[i]); + // } + + size_t key_share_data_size = key_shares[0].data_size; + size_t num_key_shares = key_shares_size; + + sealed_seed_size = utils::sgx_calc_sealed_data_size(0U, (uint32_t) SECRET_SIZE); + sealed_seed = new char[sealed_seed_size]; + memset(sealed_seed, 0, sealed_seed_size); + + sgx_status_t ecall_ret; + sgx_status_t status = recover_seed( + enclave_id, &ecall_ret, + all_key_shares, total_size, + key_share_indexes, num_key_shares, + key_share_data_size, threshold, + sealed_seed, sealed_seed_size); + + if (ecall_ret != SGX_SUCCESS) { + return utils::APIResponse { + .success = false, + .code = 500, + .message = "Recove Seed Ecall failed " + }; + } if (status != SGX_SUCCESS) { + return utils::APIResponse { + .success = false, + .code = 500, + .message = "Recove Seed failed " + }; + } + + return utils::APIResponse { + .success = true, + .code = 0, + .message = "" + }; + + } + +} \ No newline at end of file diff --git a/enclave/App/sealing_key_manager/sealing_key_manager.h b/enclave/App/sealing_key_manager/sealing_key_manager.h new file mode 100644 index 00000000..c9a54eb1 --- /dev/null +++ b/enclave/App/sealing_key_manager/sealing_key_manager.h @@ -0,0 +1,53 @@ +#pragma once + +#ifndef SEALING_KEY_MANAGER_H +#define SEALING_KEY_MANAGER_H + +#include +#include +#include + +#include "../Enclave_u.h" +#include "../utilities/utilities.h" + +const size_t SECRET_SIZE = 32; + +namespace sealing_key_manager { + + struct KeyShare { + size_t index; + char* data; + size_t data_size; + }; + + struct Seed { + size_t index; + char* sealed_data; + size_t sealed_data_size; + }; + + struct SealingKeyManager + { + std::vector key_shares; + std::mutex mutex_key_shares; // protects key_shares + + size_t threshold = 0; + + size_t sealed_seed_size = 0; + char* sealed_seed = nullptr; + + + utils::APIResponse addKeyShare(sgx_enclave_id_t& enclave_id, const KeyShare& key_share, size_t _threshold); + utils::APIResponse addMnemonic(sgx_enclave_id_t& enclave_id, const std::string& mnemonic, size_t index, size_t _threshold); + utils::APIResponse recoverSeed(sgx_enclave_id_t& enclave_id); + bool isSeedEmpty(); + bool writeSeedToFile(); + void listKeyShares(); + }; + + + + +} + +#endif // SEALING_KEY_MANAGER_H \ No newline at end of file diff --git a/enclave/App/utilities/utilities.cpp b/enclave/App/utilities/utilities.cpp new file mode 100644 index 00000000..e639684a --- /dev/null +++ b/enclave/App/utilities/utilities.cpp @@ -0,0 +1,19 @@ +#include "utilities.h" + +#include "sgx_tseal.h" + +namespace utils { + + // extracted from sdk/tseal/tSeal_util.cpp + uint32_t sgx_calc_sealed_data_size(const uint32_t add_mac_txt_size, const uint32_t txt_encrypt_size) + { + if(add_mac_txt_size > UINT32_MAX - txt_encrypt_size) + return UINT32_MAX; + uint32_t payload_size = add_mac_txt_size + txt_encrypt_size; //Calculate the payload size + + if(payload_size > UINT32_MAX - sizeof(sgx_sealed_data_t)) + return UINT32_MAX; + return (uint32_t)(sizeof(sgx_sealed_data_t) + payload_size); + } + +} // namespace utils \ No newline at end of file diff --git a/enclave/App/utilities/utilities.h b/enclave/App/utilities/utilities.h new file mode 100644 index 00000000..4c7e39cd --- /dev/null +++ b/enclave/App/utilities/utilities.h @@ -0,0 +1,20 @@ +#pragma once + +#ifndef UTILITIES_H +#define UTILITIES_H + +#include + +namespace utils { + + struct APIResponse { + bool success; + int code; + std::string message; + }; + + uint32_t sgx_calc_sealed_data_size(const uint32_t add_mac_txt_size, const uint32_t txt_encrypt_size); + +} + +#endif // UTILS_H \ No newline at end of file diff --git a/enclave/Enclave/Enclave.cpp b/enclave/Enclave/Enclave.cpp index 719afe78..1f298c12 100644 --- a/enclave/Enclave/Enclave.cpp +++ b/enclave/Enclave/Enclave.cpp @@ -4,6 +4,8 @@ #include #include +#include + #include "../utils/include_secp256k1_zkp_lib.h" #include "sgx_tkey_exchange.h" @@ -11,22 +13,6 @@ #include "sgx_trts.h" #include "sgx_tseal.h" -static const sgx_ec256_public_t g_sp_pub_key = { - { - 0xcb, 0xfc, 0x2d, 0x35, 0x79, 0x77, 0xf8, 0xfc, - 0x87, 0x38, 0x6e, 0xaf, 0x97, 0xbd, 0xe7, 0x06, - 0xde, 0xfd, 0x7a, 0x1b, 0xd6, 0x25, 0x46, 0xcb, - 0x34, 0xda, 0x66, 0x79, 0x82, 0xd0, 0x53, 0xda - }, - { - 0xae, 0xaf, 0xb0, 0xa1, 0x44, 0xdf, 0x67, 0xa7, - 0xf7, 0xf7, 0x9e, 0xdc, 0x4d, 0x86, 0x43, 0xb5, - 0xbe, 0x8c, 0x05, 0x2a, 0x3e, 0xe7, 0x58, 0x36, - 0xc3, 0xba, 0x6f, 0x93, 0xfd, 0x8b, 0x7c, 0x61 - } - -}; - sgx_status_t generate_new_keypair( unsigned char *compressed_server_pubkey, size_t compressed_server_pubkey_size, @@ -383,40 +369,85 @@ sgx_status_t key_update( return ret; } -// This ecall is a wrapper of sgx_ra_init to create the trusted -// KE exchange key context needed for the remote attestation -// SIGMA API's. Input pointers aren't checked since the trusted stubs -// copy them into EPC memory. -// -// @param b_pse Indicates whether the ISV app is using the -// platform services. -// @param p_context Pointer to the location where the returned -// key context is to be copied. -// -// @return Any error returned from the trusted key exchange API -// for creating a key context. - -sgx_status_t enclave_init_ra( - int b_pse, - sgx_ra_context_t *p_context) +char* data_to_hex(uint8_t* in, size_t insz) { - // isv enclave call to trusted key exchange library. - sgx_status_t ret; - ret = sgx_ra_init(&g_sp_pub_key, b_pse, p_context); - return ret; + char* out = (char*) malloc(insz * 2 + 1); + uint8_t* pin = in; + const char * hex = "0123456789abcdef"; + char* pout = out; + for(; pin < in + insz; pout += 2, pin++){ + pout[0] = hex[(*pin>>4) & 0xF]; + pout[1] = hex[ *pin & 0xF]; + } + pout[0] = 0; + return out; } -// Closes the tKE key context used during the SIGMA key -// exchange. -// -// @param context The trusted KE library key context. -// -// @return Return value from the key context close API +/* +sgx_status_t status = recover_seed( + + all_key_shares, total_size, + key_share_indexes, num_key_shares, + key_share_data_size, threshold, + sealed_seed, sealed_seed_size);*/ + +sgx_status_t recover_seed( + char* all_key_shares, size_t total_size, + unsigned char* indexes, size_t num_key_shares, + size_t key_share_data_size, size_t threshold, + char* sealed_seed, size_t sealed_seed_size) { + + (void) total_size; + + sgx_status_t ret = SGX_SUCCESS; + + uint8_t* shares[threshold]; + + uint32_t unsealed_data_size = key_share_data_size; + + for (size_t i = 0; i < num_key_shares; ++i) { + shares[i] = new uint8_t[key_share_data_size]; + memcpy(shares[i], all_key_shares + i * key_share_data_size, key_share_data_size); + } + + assert(threshold == num_key_shares); + + uint8_t secret_data[unsealed_data_size]; + + for (size_t i = 0; i < threshold; ++i) { + ocall_print_int("share ", (const int *) &i); + ocall_print_hex((const unsigned char**) &shares[i], (int *) &key_share_data_size); + } + + for (size_t i = 0; i < threshold; ++i) { + ocall_print_int("index ", (const int *) &i); + ocall_print_int("value ", (const int *) &indexes[i]); + } + + int32_t secret_data_len = recover_secret((uint8_t) threshold, (const uint8_t*) indexes, (const uint8_t **)shares, unsealed_data_size, secret_data); + + ocall_print_int("secret_data_len ", (const int *) &secret_data_len); + assert(secret_data_len == (int32_t) unsealed_data_size); + + char* seed = data_to_hex(secret_data, unsealed_data_size); + ocall_print_string("Seed:"); + ocall_print_string(seed); + + if (sealed_seed_size >= sgx_calc_sealed_data_size(0U, unsealed_data_size)) + { + if ((ret = sgx_seal_data(0U, NULL, unsealed_data_size, secret_data, (uint32_t) sealed_seed_size, (sgx_sealed_data_t *)sealed_seed)) != SGX_SUCCESS) + { + ocall_print_string("\nTrustedApp: sgx_seal_data() failed !\n"); + ret = SGX_ERROR_UNEXPECTED; + } + } + else + { + ocall_print_string("\nTrustedApp: Size allocated for sealedprivkey by untrusted app is less than the required size !\n"); + ret = SGX_ERROR_INVALID_PARAMETER; + } -sgx_status_t SGXAPI enclave_ra_close( - sgx_ra_context_t context) -{ - sgx_status_t ret; - ret = sgx_ra_close(context); return ret; + } + diff --git a/enclave/Enclave/Enclave.edl b/enclave/Enclave/Enclave.edl index b25d32a9..8a4ec612 100644 --- a/enclave/Enclave/Enclave.edl +++ b/enclave/Enclave/Enclave.edl @@ -41,8 +41,13 @@ enclave { [out, size=sealedkeypair_size] char* sealedkeypair, size_t sealedkeypair_size ); - public sgx_status_t enclave_init_ra(int b_pse, [out] sgx_ra_context_t *p_context); - public sgx_status_t enclave_ra_close(sgx_ra_context_t context); + public sgx_status_t recover_seed( + [in, size=sealed_total_share_size] char* sealed_shares, size_t sealed_total_share_size, + [in, size=num_key_sealed_shares] unsigned char* indexes, size_t num_key_sealed_shares, + size_t sealed_share_data_size, + size_t threshold, + [out, size=sealed_secret_size] char* sealed_secret, size_t sealed_secret_size + ); }; diff --git a/enclave/Makefile b/enclave/Makefile index 55ea4d4c..da30f739 100644 --- a/enclave/Makefile +++ b/enclave/Makefile @@ -62,7 +62,7 @@ else Urts_Library_Name := sgx_urts endif -App_Cpp_Files := App/App.cpp utils/strencodings.cpp App/remote-attestation.cpp +App_Cpp_Files := App/App.cpp utils/strencodings.cpp App/utilities/utilities.cpp App/database/db_manager.cpp App/sealing_key_manager/sealing_key_manager.cpp App_Include_Paths := -IApp -I$(SGX_SDK)/include -I./secp256k1-zkp/include App_C_Flags := -fPIC -Wno-attributes $(App_Include_Paths) @@ -80,7 +80,7 @@ else endif App_Cpp_Flags := $(App_C_Flags) -App_Link_Flags := -L$(SGX_LIBRARY_PATH) -l$(Urts_Library_Name) -L. -lsgx_ukey_exchange -lpthread -lpqxx -lpq -lcpr +App_Link_Flags := -L$(SGX_LIBRARY_PATH) -l$(Urts_Library_Name) -L. -lsgx_ukey_exchange -lpthread -lpqxx -lpq -lcpr -lbc-bip39 -lbc-crypto-base ifneq ($(SGX_MODE), HW) App_Link_Flags += -lsgx_epid_sim -lsgx_quote_ex_sim @@ -104,7 +104,7 @@ endif Crypto_Library_Name := sgx_tcrypto Enclave_Cpp_Files := Enclave/Enclave.cpp -Enclave_Include_Paths := -IEnclave -I$(SGX_SDK)/include -I$(SGX_SDK)/include/tlibc -I$(SGX_SDK)/include/libcxx -I./secp256k1-zkp/include +Enclave_Include_Paths := -IEnclave -I$(SGX_SDK)/include -I$(SGX_SDK)/include/tlibc -I$(SGX_SDK)/include/libcxx -I./secp256k1-zkp/include -I/usr/local/include Enclave_C_Flags := $(Enclave_Include_Paths) -nostdinc -fvisibility=hidden -fpie -ffunction-sections -fdata-sections $(MITIGATION_CFLAGS) CC_BELOW_4_9 := $(shell expr "`$(CC) -dumpversion`" \< "4.9") @@ -129,7 +129,7 @@ Enclave_Security_Link_Flags := -Wl,-z,relro,-z,now,-z,noexecstack Enclave_Link_Flags := $(MITIGATION_LDFLAGS) $(Enclave_Security_Link_Flags) \ -Wl,--no-undefined -nostdlib -nodefaultlibs -nostartfiles -L$(SGX_TRUSTED_LIBRARY_PATH) \ -Wl,--whole-archive -l$(Trts_Library_Name) -Wl,--no-whole-archive \ - -Wl,--start-group -lsgx_tstdc -lsgx_tcxx -lsgx_tkey_exchange -l$(Crypto_Library_Name) -l$(Service_Library_Name) -Wl,--end-group \ + -Wl,--start-group -lbc-shamir -lbc-crypto-base -lsgx_tstdc -lsgx_tcxx -lsgx_tkey_exchange -l$(Crypto_Library_Name) -l$(Service_Library_Name) -Wl,--end-group \ -Wl,-Bstatic -Wl,-Bsymbolic -Wl,--no-undefined \ -Wl,-pie,-eenclave_entry -Wl,--export-dynamic \ -Wl,--defsym,__ImageBase=0 -Wl,--gc-sections \ diff --git a/enclave/README.md b/enclave/README.md index 42df9d56..7db6b134 100644 --- a/enclave/README.md +++ b/enclave/README.md @@ -43,6 +43,28 @@ $ sudo cmake --install . # found in the directories specified on the command line $ sudo ldconfig +# Install https://github.com/ssantos21/bc-crypto-base +$ git clone https://github.com/ssantos21/bc-crypto-base +$ cd bc-crypto-base +$ ./configure +$ make check +$ sudo make install + +# Install https://github.com/ssantos21/bc-shamir +$ git clone https://github.com/ssantos21/bc-shamir +$ cd bc-shamir +$ ./configure +$ make check +$ sudo make install + +# Install https://github.com/ssantos21/bc-bip39 +$ sudo apt-get install make clang +$ git clone https://github.com/ssantos21/bc-bip39 +$ cd bc-bip39 +$ export CC="clang-14" && ./configure +$ make check +$ sudo make install + # clone this repo $ git clone https://github.com/commerceblock/mercurylayer $ git checkout -b dev origin/dev From 629560432fc4d1f3b285d26e6ee544bcbed33de8 Mon Sep 17 00:00:00 2001 From: "S. Santos" Date: Sun, 31 Mar 2024 09:54:56 -0300 Subject: [PATCH 08/66] [WIP] Add Sealing Key --- enclave/.gitignore | 3 +- enclave/App/App.cpp | 15 +- .../sealing_key_manager.cpp | 131 +++++++++++++----- .../sealing_key_manager/sealing_key_manager.h | 3 +- enclave/utils/strencodings.cpp | 2 +- enclave/utils/strencodings.h | 2 +- 6 files changed, 113 insertions(+), 43 deletions(-) diff --git a/enclave/.gitignore b/enclave/.gitignore index 7529e7d0..26d1dd83 100644 --- a/enclave/.gitignore +++ b/enclave/.gitignore @@ -37,4 +37,5 @@ App/Enclave_u.h Enclave/Enclave_t.c Enclave/Enclave_t.h app -Settings.toml \ No newline at end of file +Settings.toml +node.sealed_seed \ No newline at end of file diff --git a/enclave/App/App.cpp b/enclave/App/App.cpp index 662dd12c..9a8c8e6b 100644 --- a/enclave/App/App.cpp +++ b/enclave/App/App.cpp @@ -279,14 +279,6 @@ int SGX_CDECL main(int argc, char *argv[]) (void)(argc); (void)(argv); - sealing_key_manager::SealingKeyManager sealing_key_manager; - - if (sealing_key_manager.isSeedEmpty()) { - printf("Seed is empty\n"); - } else { - printf("Seed is not empty\n"); - } - crow::SimpleApp app; sgx_enclave_id_t enclave_id = 0; @@ -308,6 +300,13 @@ int SGX_CDECL main(int argc, char *argv[]) } } + sealing_key_manager::SealingKeyManager sealing_key_manager; + if (sealing_key_manager.readSeedFromFile()) { + std::cout << "Seed loaded" << std::endl; + } else { + std::cout << "Seed not loaded" << std::endl; + } + CROW_ROUTE(app, "/get_public_key") .methods("POST"_method)([&enclave_id, &mutex_enclave_id, &database_connection_string](const crow::request& req) { diff --git a/enclave/App/sealing_key_manager/sealing_key_manager.cpp b/enclave/App/sealing_key_manager/sealing_key_manager.cpp index fda509a8..30396c50 100644 --- a/enclave/App/sealing_key_manager/sealing_key_manager.cpp +++ b/enclave/App/sealing_key_manager/sealing_key_manager.cpp @@ -8,6 +8,8 @@ #include #include #include +#include +#include #include #include @@ -59,15 +61,7 @@ namespace sealing_key_manager { } if (!isSeedEmpty()) { - std::string error_message; - auto ret = db_manager::add_sealed_seed(sealed_seed, sealed_seed_size, error_message); - if (!ret) { - return utils::APIResponse { - .success = false, - .code = 500, - .message = error_message - }; - } + writeSeedToFile(); } return utils::APIResponse { @@ -79,17 +73,19 @@ namespace sealing_key_manager { utils::APIResponse SealingKeyManager::addMnemonic(sgx_enclave_id_t& enclave_id, const std::string& mnemonic, size_t index, size_t _threshold) { + if (!isSeedEmpty()) { + return utils::APIResponse { + .success = false, + .code = 400, + .message = "Seed already exists" + }; + } + size_t max_secret_len = SECRET_SIZE; uint8_t secret[max_secret_len]; memset(secret, 0, max_secret_len); size_t secret_len = bip39_secret_from_mnemonics(mnemonic.c_str(), secret, max_secret_len); - // const auto key_share = KeyShare { - // .index = index, - // .data = (char *) secret, - // .data_size = secret_len - // }; - auto key_share = KeyShare(); key_share.index = index; key_share.data_size = secret_len; @@ -97,15 +93,7 @@ namespace sealing_key_manager { memcpy(key_share.data, secret, secret_len); - auto secret_hex = key_to_string((unsigned char *) secret, secret_len); - - printf("secret_hex: %s\n", secret_hex.c_str()); - return addKeyShare(enclave_id, key_share, _threshold); - - // auto secret_hex = key_to_string((unsigned char *) secret, secret_len); - - // printf("secret_hex: %s\n", secret_hex.c_str()); } void SealingKeyManager::listKeyShares() { @@ -153,14 +141,6 @@ namespace sealing_key_manager { key_share_indexes[i] = (uint8_t) key_shares[i].index; } - // auto all_key_shares_hex = key_to_string((unsigned char *) all_key_shares, total_size); - - // printf("all key shares: %s \n", all_key_shares_hex.c_str()); - - // for (size_t i = 0; i < key_shares_size; ++i) { - // printf("key_share_indexes[%zu]: %u\n", i, key_share_indexes[i]); - // } - size_t key_share_data_size = key_shares[0].data_size; size_t num_key_shares = key_shares_size; @@ -198,4 +178,93 @@ namespace sealing_key_manager { } + bool SealingKeyManager::writeSeedToFile() { + // Check if the file exists + const std::string filename = "node.sealed_seed"; + if (std::filesystem::exists(filename)) { + return false; // File already exists, so we don't overwrite it + } + + if (isSeedEmpty()) { + return false; // Sealed seed is empty + } + + // Open file in binary mode to write + std::ofstream file(filename, std::ios::binary | std::ios::out); + if (!file.is_open()) { + return false; // Failed to open file for writing + } + + // Write sealed_seed to file + file.write(sealed_seed, sealed_seed_size); + bool success = file.good(); // Check if write operation was successful + + file.close(); + return success; + } + + bool SealingKeyManager::readSeedFromFile() { + const std::string filename = "node.sealed_seed"; + + // Check if the file exists and is not empty + if (!std::filesystem::exists(filename) || std::filesystem::is_empty(filename)) { + return false; // File does not exist or is empty + } + + // Open the file in binary mode + std::ifstream file(filename, std::ios::binary | std::ios::ate); + if (!file.is_open()) { + return false; // Failed to open file + } + + // Get the size of the file + std::streamsize size = file.tellg(); + file.seekg(0, std::ios::beg); // Move to the beginning of the file + + // Allocate memory for sealed_seed + sealed_seed = new char[size]; + + // Read the contents of the file into sealed_seed + if (!file.read(sealed_seed, size)) { + delete[] sealed_seed; // Clean up in case of read failure + sealed_seed = nullptr; + return false; + } + + // Update the size of the data read + sealed_seed_size = static_cast(size); + return true; + } + + /* bool SealingKeyManager::testSealedSeed(sgx_enclave_id_t& enclave_id) { + + if (isSeedEmpty()) { + std::cout << "[test] seed empty" << std::endl; + return false; + } + + size_t raw_data_size = SECRET_SIZE; + unsigned char* raw_data = new unsigned char[raw_data_size]; + memset(raw_data, 0, raw_data_size); + + sgx_status_t ecall_ret; + sgx_status_t status = unseal( + enclave_id, &ecall_ret, + sealed_seed, sealed_seed_size, + raw_data, raw_data_size); + + if (ecall_ret != SGX_SUCCESS) { + std::cout << "unseal failed " << std::endl; + } if (status != SGX_SUCCESS) { + std::cout << "unseal failed " << std::endl; + } + + std::string raw_data_hex = key_to_string(raw_data, raw_data_size); + std::cout << "raw_data_hex: " << raw_data_hex << std::endl; + + delete[] raw_data; + + return true; + } */ + } \ No newline at end of file diff --git a/enclave/App/sealing_key_manager/sealing_key_manager.h b/enclave/App/sealing_key_manager/sealing_key_manager.h index c9a54eb1..09711792 100644 --- a/enclave/App/sealing_key_manager/sealing_key_manager.h +++ b/enclave/App/sealing_key_manager/sealing_key_manager.h @@ -36,12 +36,13 @@ namespace sealing_key_manager { size_t sealed_seed_size = 0; char* sealed_seed = nullptr; - utils::APIResponse addKeyShare(sgx_enclave_id_t& enclave_id, const KeyShare& key_share, size_t _threshold); utils::APIResponse addMnemonic(sgx_enclave_id_t& enclave_id, const std::string& mnemonic, size_t index, size_t _threshold); utils::APIResponse recoverSeed(sgx_enclave_id_t& enclave_id); bool isSeedEmpty(); bool writeSeedToFile(); + bool readSeedFromFile(); + // bool testSealedSeed(sgx_enclave_id_t& enclave_id); void listKeyShares(); }; diff --git a/enclave/utils/strencodings.cpp b/enclave/utils/strencodings.cpp index 034533cd..1878b05e 100644 --- a/enclave/utils/strencodings.cpp +++ b/enclave/utils/strencodings.cpp @@ -71,4 +71,4 @@ std::string key_to_string(const unsigned char* key, size_t keylen) { for (int i = 0; i < keylen; i++) sb << std::hex << std::setw(2) << std::setfill('0') << (int)key[i]; return sb.str(); -} \ No newline at end of file +} diff --git a/enclave/utils/strencodings.h b/enclave/utils/strencodings.h index b212ec68..42bd404b 100644 --- a/enclave/utils/strencodings.h +++ b/enclave/utils/strencodings.h @@ -17,4 +17,4 @@ std::vector ParseHex(std::string_view str); bool hex_to_bytes(const std::string& hex, unsigned char* output); std::string key_to_string(const unsigned char* key, size_t keylen); -#endif // BITCOIN_UTIL_STRENCODINGS_H \ No newline at end of file +#endif // BITCOIN_UTIL_STRENCODINGS_H From 37768f35897401cadb4523d78ff9393052ca4637 Mon Sep 17 00:00:00 2001 From: "S. Santos" Date: Tue, 2 Apr 2024 12:07:08 -0300 Subject: [PATCH 09/66] [WIP] Add Sealing Key --- clients/rust/Settings.toml | 7 ++++--- clients/rust/src/client_config.rs | 4 ++++ clients/rust/src/wallet.rs | 32 +++++++++++++++++++++++++++--- docs/tokens.md | 4 ++-- lib/src/wallet/mod.rs | 1 - server/src/endpoints/deposit.rs | 33 ------------------------------- server/src/main.rs | 1 - 7 files changed, 39 insertions(+), 43 deletions(-) diff --git a/clients/rust/Settings.toml b/clients/rust/Settings.toml index 781687aa..10cac6f7 100644 --- a/clients/rust/Settings.toml +++ b/clients/rust/Settings.toml @@ -1,9 +1,10 @@ -#statechain_entity = "http://127.0.0.1:8000" -statechain_entity = "http://j23wevaeducxuy3zahd6bpn4x76cymwz2j3bdixv7ow4awjrg5p6jaid.onion" +statechain_entity = "http://127.0.0.1:8000" +#statechain_entity = "http://j23wevaeducxuy3zahd6bpn4x76cymwz2j3bdixv7ow4awjrg5p6jaid.onion" #electrum_server = "tcp://127.0.0.1:50001" electrum_server = "tcp://signet-electrumx.wakiyamap.dev:50001" +electrum_type = "electrs" network = "signet" fee_rate_tolerance = 5 database_file="wallet.db" confirmation_target = 2 -tor_proxy = "socks5h://localhost:9050" \ No newline at end of file +#tor_proxy = "socks5h://localhost:9050" \ No newline at end of file diff --git a/clients/rust/src/client_config.rs b/clients/rust/src/client_config.rs index 40f119d9..11e59b41 100644 --- a/clients/rust/src/client_config.rs +++ b/clients/rust/src/client_config.rs @@ -11,6 +11,8 @@ pub struct ClientConfig { pub electrum_client: electrum_client::Client, /// Electrum server url pub electrum_server_url: String, + /// Electrum server type (e.g. electrs, electrumx, etc.) + pub electrum_type: String, /// Bitcoin network name (testnet, regtest, mainnet) pub network: Network, /// Fee rate tolerance @@ -32,6 +34,7 @@ impl ClientConfig { let statechain_entity = settings.get_string("statechain_entity").unwrap(); let electrum_server = settings.get_string("electrum_server").unwrap(); + let electrum_type = settings.get_string("electrum_type").unwrap(); let network = settings.get_string("network").unwrap(); let fee_rate_tolerance = settings.get_int("fee_rate_tolerance").unwrap() as u32; let database_file = settings.get_string("database_file").unwrap(); @@ -75,6 +78,7 @@ impl ClientConfig { statechain_entity, electrum_client, electrum_server_url: electrum_server, + electrum_type, network, fee_rate_tolerance, confirmation_target, diff --git a/clients/rust/src/wallet.rs b/clients/rust/src/wallet.rs index cdc5f5ca..05533b2d 100644 --- a/clients/rust/src/wallet.rs +++ b/clients/rust/src/wallet.rs @@ -1,6 +1,6 @@ use anyhow::Result; use electrum_client::ElectrumApi; -use mercury_lib::wallet::{Wallet, generate_mnemonic}; +use mercury_lib::wallet::{generate_mnemonic, Settings, Wallet}; use crate::{utils::info_config, client_config::ClientConfig}; @@ -15,19 +15,45 @@ pub async fn create_wallet( let block_header = client_config.electrum_client.block_headers_subscribe_raw()?; let blockheight = block_header.height as u32; + let electrum_endpoint = client_config.electrum_server_url.to_string(); + let (electrum_protocol, rest) = electrum_endpoint.split_once("://").expect("Could not find protocol separator"); + + let (electrum_host, electrum_port) = rest.rsplit_once(':').expect("Could not find port separator"); + + let notifications = false; + let tutorials = false; + + let settings = Settings { + network: client_config.network.to_string(), + block_explorerURL: None, + torProxyHost: None, + torProxyPort: None, + torProxyControlPassword: None, + torProxyControlPort: None, + statechainEntityApi: client_config.statechain_entity.to_string(), + torStatechainEntityApi: None, + electrumProtocol: electrum_protocol.to_string(), + electrumHost: electrum_host.to_string(), + electrumPort: electrum_port.to_string(), + electrumType: client_config.electrum_type.to_string(), + notifications, + tutorials, + }; + let wallet = Wallet { name: name.to_string(), mnemonic, version: String::from("0.1.0"), state_entity_endpoint: client_config.statechain_entity.to_string(), - electrum_endpoint: client_config.electrum_server_url.to_string(), + electrum_endpoint, network: client_config.network.to_string(), blockheight, initlock: server_info.initlock, interval: server_info.interval, tokens: Vec::new(), activities: Vec::new(), - coins: Vec::new() + coins: Vec::new(), + settings, }; // save wallet to database diff --git a/docs/tokens.md b/docs/tokens.md index bdf5ff82..9dcef645 100644 --- a/docs/tokens.md +++ b/docs/tokens.md @@ -61,5 +61,5 @@ The logic for initialising a statecoin deposit proceeds as follows: 1. First deposit screen: user selects statecoin deposit amount 2. Wallet accesses `tokens` array. If there is a `token_id` with `confirmed = true` and `spent = false`, then deposit init is performed using this `token_id`. Once deposit init has completed, that `token_id` in the tokens array is updated as status `spent = true` and the wallet saved. -3. If there is a `token_id` with `confirmed = false` and `spent = false`, then the `tokens/token_verify/` endpoint is called. If it returns `true`, then update `token_id` entry in `tokens` to `confirmed = true` and save the wallet. Then deposit init is performed using this `token_id`. Once deposit init has completed, that `token_id` in the tokens array is updated as status `spent = true` and the wallet saved. If `tokens/token_verify/` returns `false`, go to next step. -4. Otherwise, call `tokens/token_init` endpoint. Save returned `token_id` and `processor_id` in `tokens` array with `confirmed = false` and `spent = false`. Use `processor_id` to get invoice and fee address from the payment processor and display (as QR codes) in the wallet UI. Then poll `tokens/token_verify/` until it returns `true`, and then update `token_id` entry in `tokens` to `confirmed = true` and save the wallet. Then deposit init is performed using this `token_id`. Once deposit init has completed, that `token_id` in the tokens array is updated as status `spent = true` and the wallet saved. +3. If there is a `token_id` with `confirmed = false` and `spent = false`, then the `token/token_verify/` endpoint is called. If it returns `true`, then update `token_id` entry in `tokens` to `confirmed = true` and save the wallet. Then deposit init is performed using this `token_id`. Once deposit init has completed, that `token_id` in the tokens array is updated as status `spent = true` and the wallet saved. If `token/token_verify/` returns `false`, go to next step. +4. Otherwise, call `token/token_init` endpoint. Save returned `token_id` and `processor_id` in `tokens` array with `confirmed = false` and `spent = false`. Use `processor_id` to get invoice and fee address from the payment processor and display (as QR codes) in the wallet UI. Then poll `token/token_verify/` until it returns `true`, and then update `token_id` entry in `tokens` to `confirmed = true` and save the wallet. Then deposit init is performed using this `token_id`. Once deposit init has completed, that `token_id` in the tokens array is updated as status `spent = true` and the wallet saved. diff --git a/lib/src/wallet/mod.rs b/lib/src/wallet/mod.rs index cfbe6c50..af0ec440 100644 --- a/lib/src/wallet/mod.rs +++ b/lib/src/wallet/mod.rs @@ -27,7 +27,6 @@ pub struct Wallet { pub settings: Settings, } - #[allow(non_snake_case)] #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Settings { diff --git a/server/src/endpoints/deposit.rs b/server/src/endpoints/deposit.rs index 0dd73d6a..dc2f9f1d 100644 --- a/server/src/endpoints/deposit.rs +++ b/server/src/endpoints/deposit.rs @@ -112,39 +112,6 @@ pub async fn get_token(statechain_entity: &State) -> status::C return status::Custom(Status::Ok, Json(response_body)); } -#[get("/tokens/token_init")] -pub async fn token_init(statechain_entity: &State) -> status::Custom> { - - if statechain_entity.config.network == "mainnet" { - let response_body = json!({ - "error": "Internal Server Error", - "message": "Token generation not supported on mainnet." - }); - - return status::Custom(Status::InternalServerError, Json(response_body)); - } - - let token_id = uuid::Uuid::new_v4().to_string(); - let processor_id = uuid::Uuid::new_v4().to_string(); - let invoice = String::from("lnbc10u1pj3knpdsp5k9f25s2wpzewkf9c78pftkgnkuuz82erkcjml7zkgsp7znyhs5yspp5rxz3tkc7ydgln3u7ez6duhp0g6jpzgtnn7ph5xrjy6muh9xm07wqdp2f9h8vmmfvdjjqen0wgsy6ctfdeehgcteyp6x76m9dcxqyjw5qcqpj9qyysgq6z9whs8am75r6mzcgt76vlwgk5g9yq5g8xefdxx6few6d5why7fs7h5g2dx9hk7s60ywtnkyc0f3p0cha4a9kmgkq5jvu5e7hvsaawqpjtf8p4"); - let confirmed = false; - let spent = false; - - insert_new_token(&statechain_entity.pool, &token_id).await; - - let token = mercury_lib::wallet::Token { - token_id, - invoice, - processor_id, - confirmed, - spent, - }; - - let response_body = json!(token); - - return status::Custom(Status::Ok, Json(response_body)); -} - #[post("/deposit/init/pod", format = "json", data = "")] pub async fn post_deposit(statechain_entity: &State, deposit_msg1: Json) -> status::Custom> { diff --git a/server/src/main.rs b/server/src/main.rs index e500268e..2db95b9c 100644 --- a/server/src/main.rs +++ b/server/src/main.rs @@ -41,7 +41,6 @@ async fn main() { .mount("/", routes![ endpoints::deposit::post_deposit, endpoints::deposit::get_token, - endpoints::deposit::token_init, endpoints::sign::sign_first, endpoints::sign::sign_second, endpoints::transfer_sender::transfer_sender, From a0d06ce7f9c8c229d057a3c5fc922f75cb628087 Mon Sep 17 00:00:00 2001 From: "S. Santos" Date: Tue, 2 Apr 2024 18:51:42 -0300 Subject: [PATCH 10/66] [WIP] Add Sealing Key --- .gitignore | 1 + enclave/App/App.cpp | 33 +- enclave/App/database/db_manager.cpp | 44 + enclave/App/database/db_manager.h | 7 + enclave/Enclave/Enclave.cpp | 94 +- enclave/Enclave/Enclave.edl | 15 + enclave/Enclave/libs/monocypher.c | 2956 +++++++++++++++++++++++++++ enclave/Enclave/libs/monocypher.h | 321 +++ enclave/Makefile | 4 +- 9 files changed, 3459 insertions(+), 16 deletions(-) create mode 100644 enclave/Enclave/libs/monocypher.c create mode 100644 enclave/Enclave/libs/monocypher.h diff --git a/.gitignore b/.gitignore index ea8c4bf7..ccb51663 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /target +.vscode \ No newline at end of file diff --git a/enclave/App/App.cpp b/enclave/App/App.cpp index 9a8c8e6b..a059a742 100644 --- a/enclave/App/App.cpp +++ b/enclave/App/App.cpp @@ -274,6 +274,23 @@ void ocall_print_hex(const unsigned char** key, const int *keylen) printf("%s\n", key_to_string(*key, *keylen).c_str()); } +void initialize_encrypted_data(chacha20_poly1305_encrypted_data& encrypted_data, size_t data_len, sealing_key_manager::SealingKeyManager& sealing_key_manager) { + + // initialize encrypted_data + encrypted_data.data_len = data_len; + encrypted_data.data = new unsigned char[encrypted_data.data_len]; + memset(encrypted_data.data, 0, encrypted_data.data_len); + + memset(encrypted_data.mac, 0, sizeof(encrypted_data.mac)); + memset(encrypted_data.nonce, 0, sizeof(encrypted_data.nonce)); + + // copy sealed seed + encrypted_data.sealed_key_len = sealing_key_manager.sealed_seed_size; + encrypted_data.sealed_key = new char[encrypted_data.sealed_key_len]; + memcpy(encrypted_data.sealed_key, sealing_key_manager.sealed_seed, encrypted_data.sealed_key_len); + +} + int SGX_CDECL main(int argc, char *argv[]) { (void)(argc); @@ -308,7 +325,11 @@ int SGX_CDECL main(int argc, char *argv[]) } CROW_ROUTE(app, "/get_public_key") - .methods("POST"_method)([&enclave_id, &mutex_enclave_id, &database_connection_string](const crow::request& req) { + .methods("POST"_method)([&enclave_id, &mutex_enclave_id, &database_connection_string, &sealing_key_manager](const crow::request& req) { + + if (sealing_key_manager.isSeedEmpty()) { + return crow::response(500, "Sealing key is empty."); + } auto req_body = crow::json::load(req.body); if (!req_body) @@ -340,6 +361,16 @@ int SGX_CDECL main(int argc, char *argv[]) return crow::response(500, "Key aggregation failed "); } + // new encryption scheme + chacha20_poly1305_encrypted_data encrypted_data; + initialize_encrypted_data(encrypted_data, sizeof(secp256k1_keypair), sealing_key_manager); + + size_t server_pubkey_size2 = 33; // serialized compressed public keys are 33-byte array + unsigned char server_pubkey2[server_pubkey_size2]; + + sgx_status_t ecall_ret2; + generate_new_keypair2(enclave_id, &ecall_ret2, server_pubkey2, server_pubkey_size2, &encrypted_data); + auto server_seckey_hex = key_to_string(server_pubkey, server_pubkey_size); std::string error_message; diff --git a/enclave/App/database/db_manager.cpp b/enclave/App/database/db_manager.cpp index 76e16713..5885398b 100644 --- a/enclave/App/database/db_manager.cpp +++ b/enclave/App/database/db_manager.cpp @@ -1,5 +1,6 @@ #include "db_manager.h" +#include "../Enclave_u.h" #include "../lib/toml.hpp" #include #include @@ -96,4 +97,47 @@ namespace db_manager { return true; } // get_sealed_seed + + bool save_generated_public_key( + chacha20_poly1305_encrypted_data& encrypted_data, + unsigned char* server_public_key, size_t server_public_key_size, + std::string& statechain_id, + std::string& error_message) { + + auto config = toml::parse_file("Settings.toml"); + auto database_connection_string = config["intel_sgx"]["database_connection_string"].as_string()->get(); + + try + { + pqxx::connection conn(database_connection_string); + if (conn.is_open()) { + + std::string create_table_query = + "CREATE TABLE IF NOT EXISTS generated_public_key ( " + "id SERIAL PRIMARY KEY, " + "statechain_id varchar(50), " + "sealed_keypair BYTEA, " + "sealed_secnonce BYTEA, " + "public_nonce BYTEA, " + "public_key BYTEA UNIQUE, " + "sig_count INTEGER DEFAULT 0);"; + + pqxx::work txn(conn); + txn.exec(create_table_query); + txn.commit(); + + return true; + } else { + error_message = "Failed to connect to the database!"; + return false; + } + } + catch (std::exception const &e) + { + error_message = e.what(); + return false; + } + + return true; + } } \ No newline at end of file diff --git a/enclave/App/database/db_manager.h b/enclave/App/database/db_manager.h index 86ff9362..1f48452f 100644 --- a/enclave/App/database/db_manager.h +++ b/enclave/App/database/db_manager.h @@ -3,6 +3,7 @@ #ifndef DB_MANAGER_H #define DB_MANAGER_H +#include "../Enclave_u.h" #include namespace db_manager { @@ -10,6 +11,12 @@ namespace db_manager { // Remove these 2 functions. Sealed seeds should be stored in the file system. bool add_sealed_seed(char* sealed_secret, size_t sealed_secret_size, std::string& error_message); bool get_sealed_seed(char* sealed_secret, size_t sealed_secret_size, std::string& error_message); + + bool save_generated_public_key( + chacha20_poly1305_encrypted_data& encrypted_data, + unsigned char* server_public_key, size_t server_public_key_size, + std::string& statechain_id, + std::string& error_message); } #endif // DB_MANAGER_H \ No newline at end of file diff --git a/enclave/Enclave/Enclave.cpp b/enclave/Enclave/Enclave.cpp index 1f298c12..30e05f30 100644 --- a/enclave/Enclave/Enclave.cpp +++ b/enclave/Enclave/Enclave.cpp @@ -7,12 +7,92 @@ #include #include "../utils/include_secp256k1_zkp_lib.h" +#include "libs/monocypher.h" #include "sgx_tkey_exchange.h" #include "sgx_tcrypto.h" #include "sgx_trts.h" #include "sgx_tseal.h" +char* data_to_hex(uint8_t* in, size_t insz) +{ + char* out = (char*) malloc(insz * 2 + 1); + uint8_t* pin = in; + const char * hex = "0123456789abcdef"; + char* pout = out; + for(; pin < in + insz; pout += 2, pin++){ + pout[0] = hex[(*pin>>4) & 0xF]; + pout[1] = hex[ *pin & 0xF]; + } + pout[0] = 0; + return out; +} + +void encrypt_data( + chacha20_poly1305_encrypted_data *encrypted_data, + uint8_t* raw_data, size_t raw_data_size) +{ + unsigned char seed[32]; + memset(seed, 0, 32); + + unseal(encrypted_data->sealed_key, encrypted_data->sealed_key_len, seed, sizeof(seed)); + + // Associated data (optional, can be NULL if not used) + uint8_t *ad = NULL; + size_t ad_size = 0; + + sgx_read_rand(encrypted_data->nonce, sizeof(encrypted_data->nonce)); + + assert(encrypted_data->data_len == raw_data_size); + crypto_aead_lock(encrypted_data->data, encrypted_data->mac, seed, encrypted_data->nonce, ad, ad_size, raw_data, raw_data_size); +} + +sgx_status_t generate_new_keypair2( + unsigned char *compressed_server_pubkey, + size_t compressed_server_pubkey_size, + chacha20_poly1305_encrypted_data *encrypted_data) +{ + + (void) compressed_server_pubkey_size; + + sgx_status_t ret = SGX_SUCCESS; + + secp256k1_context* ctx = secp256k1_context_create(SECP256K1_CONTEXT_NONE); + + unsigned char server_privkey[32]; + memset(server_privkey, 0, 32); + + do { + sgx_read_rand(server_privkey, 32); + } while (!secp256k1_ec_seckey_verify(ctx, server_privkey)); + + secp256k1_keypair server_keypair; + + int return_val = secp256k1_keypair_create(ctx, &server_keypair, server_privkey); + assert(return_val); + + secp256k1_pubkey server_pubkey; + return_val = secp256k1_keypair_pub(ctx, &server_pubkey, &server_keypair); + assert(return_val); + + unsigned char local_compressed_server_pubkey[33]; + memset(local_compressed_server_pubkey, 0, 33); + + size_t len = sizeof(local_compressed_server_pubkey); + return_val = secp256k1_ec_pubkey_serialize(ctx, local_compressed_server_pubkey, &len, &server_pubkey, SECP256K1_EC_COMPRESSED); + assert(return_val); + // Should be the same size as the size of the output, because we passed a 33 byte array. + assert(len == sizeof(local_compressed_server_pubkey)); + + memcpy(compressed_server_pubkey, local_compressed_server_pubkey, 33); + + secp256k1_context_destroy(ctx); + + encrypt_data(encrypted_data, server_keypair.data, sizeof(secp256k1_keypair::data)); + + return ret; +} + sgx_status_t generate_new_keypair( unsigned char *compressed_server_pubkey, size_t compressed_server_pubkey_size, @@ -369,20 +449,6 @@ sgx_status_t key_update( return ret; } -char* data_to_hex(uint8_t* in, size_t insz) -{ - char* out = (char*) malloc(insz * 2 + 1); - uint8_t* pin = in; - const char * hex = "0123456789abcdef"; - char* pout = out; - for(; pin < in + insz; pout += 2, pin++){ - pout[0] = hex[(*pin>>4) & 0xF]; - pout[1] = hex[ *pin & 0xF]; - } - pout[0] = 0; - return out; -} - /* sgx_status_t status = recover_seed( diff --git a/enclave/Enclave/Enclave.edl b/enclave/Enclave/Enclave.edl index 8a4ec612..843b6354 100644 --- a/enclave/Enclave/Enclave.edl +++ b/enclave/Enclave/Enclave.edl @@ -8,7 +8,22 @@ enclave { include "sgx_tcrypto.h" include "sgx_tseal.h" + struct chacha20_poly1305_encrypted_data { + size_t data_len; + [size=data_len] unsigned char* data; + unsigned char nonce[24]; + unsigned char mac[16]; + size_t sealed_key_len; + [size=sealed_key_len] char* sealed_key; + }; + trusted { + + public sgx_status_t generate_new_keypair2( + [out, size=compressed_server_pubkey_size] unsigned char *compressed_server_pubkey, + size_t compressed_server_pubkey_size, + [in, out] struct chacha20_poly1305_encrypted_data* encrypted_data); + public sgx_status_t generate_new_keypair( [out, size=compressed_server_pubkey_size] unsigned char *compressed_server_pubkey, size_t compressed_server_pubkey_size, diff --git a/enclave/Enclave/libs/monocypher.c b/enclave/Enclave/libs/monocypher.c new file mode 100644 index 00000000..0accae75 --- /dev/null +++ b/enclave/Enclave/libs/monocypher.c @@ -0,0 +1,2956 @@ +// Monocypher version __git__ +// +// This file is dual-licensed. Choose whichever licence you want from +// the two licences listed below. +// +// The first licence is a regular 2-clause BSD licence. The second licence +// is the CC-0 from Creative Commons. It is intended to release Monocypher +// to the public domain. The BSD licence serves as a fallback option. +// +// SPDX-License-Identifier: BSD-2-Clause OR CC0-1.0 +// +// ------------------------------------------------------------------------ +// +// Copyright (c) 2017-2020, Loup Vaillant +// All rights reserved. +// +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// ------------------------------------------------------------------------ +// +// Written in 2017-2020 by Loup Vaillant +// +// To the extent possible under law, the author(s) have dedicated all copyright +// and related neighboring rights to this software to the public domain +// worldwide. This software is distributed without any warranty. +// +// You should have received a copy of the CC0 Public Domain Dedication along +// with this software. If not, see +// + +#include "monocypher.h" + +#ifdef MONOCYPHER_CPP_NAMESPACE +namespace MONOCYPHER_CPP_NAMESPACE { +#endif + +///////////////// +/// Utilities /// +///////////////// +#define FOR_T(type, i, start, end) for (type i = (start); i < (end); i++) +#define FOR(i, start, end) FOR_T(size_t, i, start, end) +#define COPY(dst, src, size) FOR(_i_, 0, size) (dst)[_i_] = (src)[_i_] +#define ZERO(buf, size) FOR(_i_, 0, size) (buf)[_i_] = 0 +#define WIPE_CTX(ctx) crypto_wipe(ctx , sizeof(*(ctx))) +#define WIPE_BUFFER(buffer) crypto_wipe(buffer, sizeof(buffer)) +#define MIN(a, b) ((a) <= (b) ? (a) : (b)) +#define MAX(a, b) ((a) >= (b) ? (a) : (b)) + +typedef int8_t i8; +typedef uint8_t u8; +typedef int16_t i16; +typedef uint32_t u32; +typedef int32_t i32; +typedef int64_t i64; +typedef uint64_t u64; + +static const u8 zero[128] = {0}; + +// returns the smallest positive integer y such that +// (x + y) % pow_2 == 0 +// Basically, y is the "gap" missing to align x. +// Only works when pow_2 is a power of 2. +// Note: we use ~x+1 instead of -x to avoid compiler warnings +static size_t gap(size_t x, size_t pow_2) +{ + return (~x + 1) & (pow_2 - 1); +} + +static u32 load24_le(const u8 s[3]) +{ + return + ((u32)s[0] << 0) | + ((u32)s[1] << 8) | + ((u32)s[2] << 16); +} + +static u32 load32_le(const u8 s[4]) +{ + return + ((u32)s[0] << 0) | + ((u32)s[1] << 8) | + ((u32)s[2] << 16) | + ((u32)s[3] << 24); +} + +static u64 load64_le(const u8 s[8]) +{ + return load32_le(s) | ((u64)load32_le(s+4) << 32); +} + +static void store32_le(u8 out[4], u32 in) +{ + out[0] = in & 0xff; + out[1] = (in >> 8) & 0xff; + out[2] = (in >> 16) & 0xff; + out[3] = (in >> 24) & 0xff; +} + +static void store64_le(u8 out[8], u64 in) +{ + store32_le(out , (u32)in ); + store32_le(out + 4, in >> 32); +} + +static void load32_le_buf (u32 *dst, const u8 *src, size_t size) { + FOR(i, 0, size) { dst[i] = load32_le(src + i*4); } +} +static void load64_le_buf (u64 *dst, const u8 *src, size_t size) { + FOR(i, 0, size) { dst[i] = load64_le(src + i*8); } +} +static void store32_le_buf(u8 *dst, const u32 *src, size_t size) { + FOR(i, 0, size) { store32_le(dst + i*4, src[i]); } +} +static void store64_le_buf(u8 *dst, const u64 *src, size_t size) { + FOR(i, 0, size) { store64_le(dst + i*8, src[i]); } +} + +static u64 rotr64(u64 x, u64 n) { return (x >> n) ^ (x << (64 - n)); } +static u32 rotl32(u32 x, u32 n) { return (x << n) ^ (x >> (32 - n)); } + +static int neq0(u64 diff) +{ + // constant time comparison to zero + // return diff != 0 ? -1 : 0 + u64 half = (diff >> 32) | ((u32)diff); + return (1 & ((half - 1) >> 32)) - 1; +} + +static u64 x16(const u8 a[16], const u8 b[16]) +{ + return (load64_le(a + 0) ^ load64_le(b + 0)) + | (load64_le(a + 8) ^ load64_le(b + 8)); +} +static u64 x32(const u8 a[32],const u8 b[32]){return x16(a,b)| x16(a+16, b+16);} +static u64 x64(const u8 a[64],const u8 b[64]){return x32(a,b)| x32(a+32, b+32);} +int crypto_verify16(const u8 a[16], const u8 b[16]){ return neq0(x16(a, b)); } +int crypto_verify32(const u8 a[32], const u8 b[32]){ return neq0(x32(a, b)); } +int crypto_verify64(const u8 a[64], const u8 b[64]){ return neq0(x64(a, b)); } + +void crypto_wipe(void *secret, size_t size) +{ + volatile u8 *v_secret = (u8*)secret; + ZERO(v_secret, size); +} + +///////////////// +/// Chacha 20 /// +///////////////// +#define QUARTERROUND(a, b, c, d) \ + a += b; d = rotl32(d ^ a, 16); \ + c += d; b = rotl32(b ^ c, 12); \ + a += b; d = rotl32(d ^ a, 8); \ + c += d; b = rotl32(b ^ c, 7) + +static void chacha20_rounds(u32 out[16], const u32 in[16]) +{ + // The temporary variables make Chacha20 10% faster. + u32 t0 = in[ 0]; u32 t1 = in[ 1]; u32 t2 = in[ 2]; u32 t3 = in[ 3]; + u32 t4 = in[ 4]; u32 t5 = in[ 5]; u32 t6 = in[ 6]; u32 t7 = in[ 7]; + u32 t8 = in[ 8]; u32 t9 = in[ 9]; u32 t10 = in[10]; u32 t11 = in[11]; + u32 t12 = in[12]; u32 t13 = in[13]; u32 t14 = in[14]; u32 t15 = in[15]; + + FOR (i, 0, 10) { // 20 rounds, 2 rounds per loop. + QUARTERROUND(t0, t4, t8 , t12); // column 0 + QUARTERROUND(t1, t5, t9 , t13); // column 1 + QUARTERROUND(t2, t6, t10, t14); // column 2 + QUARTERROUND(t3, t7, t11, t15); // column 3 + QUARTERROUND(t0, t5, t10, t15); // diagonal 0 + QUARTERROUND(t1, t6, t11, t12); // diagonal 1 + QUARTERROUND(t2, t7, t8 , t13); // diagonal 2 + QUARTERROUND(t3, t4, t9 , t14); // diagonal 3 + } + out[ 0] = t0; out[ 1] = t1; out[ 2] = t2; out[ 3] = t3; + out[ 4] = t4; out[ 5] = t5; out[ 6] = t6; out[ 7] = t7; + out[ 8] = t8; out[ 9] = t9; out[10] = t10; out[11] = t11; + out[12] = t12; out[13] = t13; out[14] = t14; out[15] = t15; +} + +static const u8 *chacha20_constant = (const u8*)"expand 32-byte k"; // 16 bytes + +void crypto_chacha20_h(u8 out[32], const u8 key[32], const u8 in [16]) +{ + u32 block[16]; + load32_le_buf(block , chacha20_constant, 4); + load32_le_buf(block + 4, key , 8); + load32_le_buf(block + 12, in , 4); + + chacha20_rounds(block, block); + + // prevent reversal of the rounds by revealing only half of the buffer. + store32_le_buf(out , block , 4); // constant + store32_le_buf(out+16, block+12, 4); // counter and nonce + WIPE_BUFFER(block); +} + +u64 crypto_chacha20_djb(u8 *cipher_text, const u8 *plain_text, + size_t text_size, const u8 key[32], const u8 nonce[8], + u64 ctr) +{ + u32 input[16]; + load32_le_buf(input , chacha20_constant, 4); + load32_le_buf(input + 4, key , 8); + load32_le_buf(input + 14, nonce , 2); + input[12] = (u32) ctr; + input[13] = (u32)(ctr >> 32); + + // Whole blocks + u32 pool[16]; + size_t nb_blocks = text_size >> 6; + FOR (i, 0, nb_blocks) { + chacha20_rounds(pool, input); + if (plain_text != NULL) { + FOR (j, 0, 16) { + u32 p = pool[j] + input[j]; + store32_le(cipher_text, p ^ load32_le(plain_text)); + cipher_text += 4; + plain_text += 4; + } + } else { + FOR (j, 0, 16) { + u32 p = pool[j] + input[j]; + store32_le(cipher_text, p); + cipher_text += 4; + } + } + input[12]++; + if (input[12] == 0) { + input[13]++; + } + } + text_size &= 63; + + // Last (incomplete) block + if (text_size > 0) { + if (plain_text == NULL) { + plain_text = zero; + } + chacha20_rounds(pool, input); + u8 tmp[64]; + FOR (i, 0, 16) { + store32_le(tmp + i*4, pool[i] + input[i]); + } + FOR (i, 0, text_size) { + cipher_text[i] = tmp[i] ^ plain_text[i]; + } + WIPE_BUFFER(tmp); + } + ctr = input[12] + ((u64)input[13] << 32) + (text_size > 0); + + WIPE_BUFFER(pool); + WIPE_BUFFER(input); + return ctr; +} + +u32 crypto_chacha20_ietf(u8 *cipher_text, const u8 *plain_text, + size_t text_size, + const u8 key[32], const u8 nonce[12], u32 ctr) +{ + u64 big_ctr = ctr + ((u64)load32_le(nonce) << 32); + return (u32)crypto_chacha20_djb(cipher_text, plain_text, text_size, + key, nonce + 4, big_ctr); +} + +u64 crypto_chacha20_x(u8 *cipher_text, const u8 *plain_text, + size_t text_size, + const u8 key[32], const u8 nonce[24], u64 ctr) +{ + u8 sub_key[32]; + crypto_chacha20_h(sub_key, key, nonce); + ctr = crypto_chacha20_djb(cipher_text, plain_text, text_size, + sub_key, nonce + 16, ctr); + WIPE_BUFFER(sub_key); + return ctr; +} + +///////////////// +/// Poly 1305 /// +///////////////// + +// h = (h + c) * r +// preconditions: +// ctx->h <= 4_ffffffff_ffffffff_ffffffff_ffffffff +// ctx->r <= 0ffffffc_0ffffffc_0ffffffc_0fffffff +// end <= 1 +// Postcondition: +// ctx->h <= 4_ffffffff_ffffffff_ffffffff_ffffffff +static void poly_blocks(crypto_poly1305_ctx *ctx, const u8 *in, + size_t nb_blocks, unsigned end) +{ + // Local all the things! + const u32 r0 = ctx->r[0]; + const u32 r1 = ctx->r[1]; + const u32 r2 = ctx->r[2]; + const u32 r3 = ctx->r[3]; + const u32 rr0 = (r0 >> 2) * 5; // lose 2 bits... + const u32 rr1 = (r1 >> 2) + r1; // rr1 == (r1 >> 2) * 5 + const u32 rr2 = (r2 >> 2) + r2; // rr1 == (r2 >> 2) * 5 + const u32 rr3 = (r3 >> 2) + r3; // rr1 == (r3 >> 2) * 5 + const u32 rr4 = r0 & 3; // ...recover 2 bits + u32 h0 = ctx->h[0]; + u32 h1 = ctx->h[1]; + u32 h2 = ctx->h[2]; + u32 h3 = ctx->h[3]; + u32 h4 = ctx->h[4]; + + FOR (i, 0, nb_blocks) { + // h + c, without carry propagation + const u64 s0 = (u64)h0 + load32_le(in); in += 4; + const u64 s1 = (u64)h1 + load32_le(in); in += 4; + const u64 s2 = (u64)h2 + load32_le(in); in += 4; + const u64 s3 = (u64)h3 + load32_le(in); in += 4; + const u32 s4 = h4 + end; + + // (h + c) * r, without carry propagation + const u64 x0 = s0*r0+ s1*rr3+ s2*rr2+ s3*rr1+ s4*rr0; + const u64 x1 = s0*r1+ s1*r0 + s2*rr3+ s3*rr2+ s4*rr1; + const u64 x2 = s0*r2+ s1*r1 + s2*r0 + s3*rr3+ s4*rr2; + const u64 x3 = s0*r3+ s1*r2 + s2*r1 + s3*r0 + s4*rr3; + const u32 x4 = s4*rr4; + + // partial reduction modulo 2^130 - 5 + const u32 u5 = x4 + (x3 >> 32); // u5 <= 7ffffff5 + const u64 u0 = (u5 >> 2) * 5 + (x0 & 0xffffffff); + const u64 u1 = (u0 >> 32) + (x1 & 0xffffffff) + (x0 >> 32); + const u64 u2 = (u1 >> 32) + (x2 & 0xffffffff) + (x1 >> 32); + const u64 u3 = (u2 >> 32) + (x3 & 0xffffffff) + (x2 >> 32); + const u32 u4 = (u3 >> 32) + (u5 & 3); // u4 <= 4 + + // Update the hash + h0 = u0 & 0xffffffff; + h1 = u1 & 0xffffffff; + h2 = u2 & 0xffffffff; + h3 = u3 & 0xffffffff; + h4 = u4; + } + ctx->h[0] = h0; + ctx->h[1] = h1; + ctx->h[2] = h2; + ctx->h[3] = h3; + ctx->h[4] = h4; +} + +void crypto_poly1305_init(crypto_poly1305_ctx *ctx, const u8 key[32]) +{ + ZERO(ctx->h, 5); // Initial hash is zero + ctx->c_idx = 0; + // load r and pad (r has some of its bits cleared) + load32_le_buf(ctx->r , key , 4); + load32_le_buf(ctx->pad, key+16, 4); + FOR (i, 0, 1) { ctx->r[i] &= 0x0fffffff; } + FOR (i, 1, 4) { ctx->r[i] &= 0x0ffffffc; } +} + +void crypto_poly1305_update(crypto_poly1305_ctx *ctx, + const u8 *message, size_t message_size) +{ + // Avoid undefined NULL pointer increments with empty messages + if (message_size == 0) { + return; + } + + // Align ourselves with block boundaries + size_t aligned = MIN(gap(ctx->c_idx, 16), message_size); + FOR (i, 0, aligned) { + ctx->c[ctx->c_idx] = *message; + ctx->c_idx++; + message++; + message_size--; + } + + // If block is complete, process it + if (ctx->c_idx == 16) { + poly_blocks(ctx, ctx->c, 1, 1); + ctx->c_idx = 0; + } + + // Process the message block by block + size_t nb_blocks = message_size >> 4; + poly_blocks(ctx, message, nb_blocks, 1); + message += nb_blocks << 4; + message_size &= 15; + + // remaining bytes (we never complete a block here) + FOR (i, 0, message_size) { + ctx->c[ctx->c_idx] = message[i]; + ctx->c_idx++; + } +} + +void crypto_poly1305_final(crypto_poly1305_ctx *ctx, u8 mac[16]) +{ + // Process the last block (if any) + // We move the final 1 according to remaining input length + // (this will add less than 2^130 to the last input block) + if (ctx->c_idx != 0) { + ZERO(ctx->c + ctx->c_idx, 16 - ctx->c_idx); + ctx->c[ctx->c_idx] = 1; + poly_blocks(ctx, ctx->c, 1, 0); + } + + // check if we should subtract 2^130-5 by performing the + // corresponding carry propagation. + u64 c = 5; + FOR (i, 0, 4) { + c += ctx->h[i]; + c >>= 32; + } + c += ctx->h[4]; + c = (c >> 2) * 5; // shift the carry back to the beginning + // c now indicates how many times we should subtract 2^130-5 (0 or 1) + FOR (i, 0, 4) { + c += (u64)ctx->h[i] + ctx->pad[i]; + store32_le(mac + i*4, (u32)c); + c = c >> 32; + } + WIPE_CTX(ctx); +} + +void crypto_poly1305(u8 mac[16], const u8 *message, + size_t message_size, const u8 key[32]) +{ + crypto_poly1305_ctx ctx; + crypto_poly1305_init (&ctx, key); + crypto_poly1305_update(&ctx, message, message_size); + crypto_poly1305_final (&ctx, mac); +} + +//////////////// +/// BLAKE2 b /// +//////////////// +static const u64 iv[8] = { + 0x6a09e667f3bcc908, 0xbb67ae8584caa73b, + 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, + 0x510e527fade682d1, 0x9b05688c2b3e6c1f, + 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179, +}; + +static void blake2b_compress(crypto_blake2b_ctx *ctx, int is_last_block) +{ + static const u8 sigma[12][16] = { + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, + { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, + { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, + { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, + { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, + { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, + { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, + { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, + { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, + { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, + { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, + }; + + // increment input offset + u64 *x = ctx->input_offset; + size_t y = ctx->input_idx; + x[0] += y; + if (x[0] < y) { + x[1]++; + } + + // init work vector + u64 v0 = ctx->hash[0]; u64 v8 = iv[0]; + u64 v1 = ctx->hash[1]; u64 v9 = iv[1]; + u64 v2 = ctx->hash[2]; u64 v10 = iv[2]; + u64 v3 = ctx->hash[3]; u64 v11 = iv[3]; + u64 v4 = ctx->hash[4]; u64 v12 = iv[4] ^ ctx->input_offset[0]; + u64 v5 = ctx->hash[5]; u64 v13 = iv[5] ^ ctx->input_offset[1]; + u64 v6 = ctx->hash[6]; u64 v14 = iv[6] ^ (u64)~(is_last_block - 1); + u64 v7 = ctx->hash[7]; u64 v15 = iv[7]; + + // mangle work vector + u64 *input = ctx->input; +#define BLAKE2_G(a, b, c, d, x, y) \ + a += b + x; d = rotr64(d ^ a, 32); \ + c += d; b = rotr64(b ^ c, 24); \ + a += b + y; d = rotr64(d ^ a, 16); \ + c += d; b = rotr64(b ^ c, 63) +#define BLAKE2_ROUND(i) \ + BLAKE2_G(v0, v4, v8 , v12, input[sigma[i][ 0]], input[sigma[i][ 1]]); \ + BLAKE2_G(v1, v5, v9 , v13, input[sigma[i][ 2]], input[sigma[i][ 3]]); \ + BLAKE2_G(v2, v6, v10, v14, input[sigma[i][ 4]], input[sigma[i][ 5]]); \ + BLAKE2_G(v3, v7, v11, v15, input[sigma[i][ 6]], input[sigma[i][ 7]]); \ + BLAKE2_G(v0, v5, v10, v15, input[sigma[i][ 8]], input[sigma[i][ 9]]); \ + BLAKE2_G(v1, v6, v11, v12, input[sigma[i][10]], input[sigma[i][11]]); \ + BLAKE2_G(v2, v7, v8 , v13, input[sigma[i][12]], input[sigma[i][13]]); \ + BLAKE2_G(v3, v4, v9 , v14, input[sigma[i][14]], input[sigma[i][15]]) + +#ifdef BLAKE2_NO_UNROLLING + FOR (i, 0, 12) { + BLAKE2_ROUND(i); + } +#else + BLAKE2_ROUND(0); BLAKE2_ROUND(1); BLAKE2_ROUND(2); BLAKE2_ROUND(3); + BLAKE2_ROUND(4); BLAKE2_ROUND(5); BLAKE2_ROUND(6); BLAKE2_ROUND(7); + BLAKE2_ROUND(8); BLAKE2_ROUND(9); BLAKE2_ROUND(10); BLAKE2_ROUND(11); +#endif + + // update hash + ctx->hash[0] ^= v0 ^ v8; ctx->hash[1] ^= v1 ^ v9; + ctx->hash[2] ^= v2 ^ v10; ctx->hash[3] ^= v3 ^ v11; + ctx->hash[4] ^= v4 ^ v12; ctx->hash[5] ^= v5 ^ v13; + ctx->hash[6] ^= v6 ^ v14; ctx->hash[7] ^= v7 ^ v15; +} + +void crypto_blake2b_keyed_init(crypto_blake2b_ctx *ctx, size_t hash_size, + const u8 *key, size_t key_size) +{ + // initial hash + COPY(ctx->hash, iv, 8); + ctx->hash[0] ^= 0x01010000 ^ (key_size << 8) ^ hash_size; + + ctx->input_offset[0] = 0; // beginning of the input, no offset + ctx->input_offset[1] = 0; // beginning of the input, no offset + ctx->hash_size = hash_size; + ctx->input_idx = 0; + ZERO(ctx->input, 16); + + // if there is a key, the first block is that key (padded with zeroes) + if (key_size > 0) { + u8 key_block[128] = {0}; + COPY(key_block, key, key_size); + // same as calling crypto_blake2b_update(ctx, key_block , 128) + load64_le_buf(ctx->input, key_block, 16); + ctx->input_idx = 128; + } +} + +void crypto_blake2b_init(crypto_blake2b_ctx *ctx, size_t hash_size) +{ + crypto_blake2b_keyed_init(ctx, hash_size, 0, 0); +} + +void crypto_blake2b_update(crypto_blake2b_ctx *ctx, + const u8 *message, size_t message_size) +{ + // Avoid undefined NULL pointer increments with empty messages + if (message_size == 0) { + return; + } + + // Align with word boundaries + if ((ctx->input_idx & 7) != 0) { + size_t nb_bytes = MIN(gap(ctx->input_idx, 8), message_size); + size_t word = ctx->input_idx >> 3; + size_t byte = ctx->input_idx & 7; + FOR (i, 0, nb_bytes) { + ctx->input[word] |= (u64)message[i] << ((byte + i) << 3); + } + ctx->input_idx += nb_bytes; + message += nb_bytes; + message_size -= nb_bytes; + } + + // Align with block boundaries (faster than byte by byte) + if ((ctx->input_idx & 127) != 0) { + size_t nb_words = MIN(gap(ctx->input_idx, 128), message_size) >> 3; + load64_le_buf(ctx->input + (ctx->input_idx >> 3), message, nb_words); + ctx->input_idx += nb_words << 3; + message += nb_words << 3; + message_size -= nb_words << 3; + } + + // Process block by block + size_t nb_blocks = message_size >> 7; + FOR (i, 0, nb_blocks) { + if (ctx->input_idx == 128) { + blake2b_compress(ctx, 0); + } + load64_le_buf(ctx->input, message, 16); + message += 128; + ctx->input_idx = 128; + } + message_size &= 127; + + if (message_size != 0) { + // Compress block & flush input buffer as needed + if (ctx->input_idx == 128) { + blake2b_compress(ctx, 0); + ctx->input_idx = 0; + } + if (ctx->input_idx == 0) { + ZERO(ctx->input, 16); + } + // Fill remaining words (faster than byte by byte) + size_t nb_words = message_size >> 3; + load64_le_buf(ctx->input, message, nb_words); + ctx->input_idx += nb_words << 3; + message += nb_words << 3; + message_size -= nb_words << 3; + + // Fill remaining bytes + FOR (i, 0, message_size) { + size_t word = ctx->input_idx >> 3; + size_t byte = ctx->input_idx & 7; + ctx->input[word] |= (u64)message[i] << (byte << 3); + ctx->input_idx++; + } + } +} + +void crypto_blake2b_final(crypto_blake2b_ctx *ctx, u8 *hash) +{ + blake2b_compress(ctx, 1); // compress the last block + size_t hash_size = MIN(ctx->hash_size, 64); + size_t nb_words = hash_size >> 3; + store64_le_buf(hash, ctx->hash, nb_words); + FOR (i, nb_words << 3, hash_size) { + hash[i] = (ctx->hash[i >> 3] >> (8 * (i & 7))) & 0xff; + } + WIPE_CTX(ctx); +} + +void crypto_blake2b_keyed(u8 *hash, size_t hash_size, + const u8 *key, size_t key_size, + const u8 *message, size_t message_size) +{ + crypto_blake2b_ctx ctx; + crypto_blake2b_keyed_init(&ctx, hash_size, key, key_size); + crypto_blake2b_update (&ctx, message, message_size); + crypto_blake2b_final (&ctx, hash); +} + +void crypto_blake2b(u8 *hash, size_t hash_size, const u8 *msg, size_t msg_size) +{ + crypto_blake2b_keyed(hash, hash_size, 0, 0, msg, msg_size); +} + +////////////// +/// Argon2 /// +////////////// +// references to R, Z, Q etc. come from the spec + +// Argon2 operates on 1024 byte blocks. +typedef struct { u64 a[128]; } blk; + +// updates a BLAKE2 hash with a 32 bit word, little endian. +static void blake_update_32(crypto_blake2b_ctx *ctx, u32 input) +{ + u8 buf[4]; + store32_le(buf, input); + crypto_blake2b_update(ctx, buf, 4); + WIPE_BUFFER(buf); +} + +static void blake_update_32_buf(crypto_blake2b_ctx *ctx, + const u8 *buf, u32 size) +{ + blake_update_32(ctx, size); + crypto_blake2b_update(ctx, buf, size); +} + + +static void copy_block(blk *o,const blk*in){FOR(i, 0, 128) o->a[i] = in->a[i];} +static void xor_block(blk *o,const blk*in){FOR(i, 0, 128) o->a[i] ^= in->a[i];} + +// Hash with a virtually unlimited digest size. +// Doesn't extract more entropy than the base hash function. +// Mainly used for filling a whole kilobyte block with pseudo-random bytes. +// (One could use a stream cipher with a seed hash as the key, but +// this would introduce another dependency —and point of failure.) +static void extended_hash(u8 *digest, u32 digest_size, + const u8 *input , u32 input_size) +{ + crypto_blake2b_ctx ctx; + crypto_blake2b_init (&ctx, MIN(digest_size, 64)); + blake_update_32 (&ctx, digest_size); + crypto_blake2b_update(&ctx, input, input_size); + crypto_blake2b_final (&ctx, digest); + + if (digest_size > 64) { + // the conversion to u64 avoids integer overflow on + // ludicrously big hash sizes. + u32 r = (u32)(((u64)digest_size + 31) >> 5) - 2; + u32 i = 1; + u32 in = 0; + u32 out = 32; + while (i < r) { + // Input and output overlap. This is intentional + crypto_blake2b(digest + out, 64, digest + in, 64); + i += 1; + in += 32; + out += 32; + } + crypto_blake2b(digest + out, digest_size - (32 * r), digest + in , 64); + } +} + +#define LSB(x) ((u64)(u32)x) +#define G(a, b, c, d) \ + a += b + ((LSB(a) * LSB(b)) << 1); d ^= a; d = rotr64(d, 32); \ + c += d + ((LSB(c) * LSB(d)) << 1); b ^= c; b = rotr64(b, 24); \ + a += b + ((LSB(a) * LSB(b)) << 1); d ^= a; d = rotr64(d, 16); \ + c += d + ((LSB(c) * LSB(d)) << 1); b ^= c; b = rotr64(b, 63) +#define ROUND(v0, v1, v2, v3, v4, v5, v6, v7, \ + v8, v9, v10, v11, v12, v13, v14, v15) \ + G(v0, v4, v8, v12); G(v1, v5, v9, v13); \ + G(v2, v6, v10, v14); G(v3, v7, v11, v15); \ + G(v0, v5, v10, v15); G(v1, v6, v11, v12); \ + G(v2, v7, v8, v13); G(v3, v4, v9, v14) + +// Core of the compression function G. Computes Z from R in place. +static void g_rounds(blk *b) +{ + // column rounds (work_block = Q) + for (int i = 0; i < 128; i += 16) { + ROUND(b->a[i ], b->a[i+ 1], b->a[i+ 2], b->a[i+ 3], + b->a[i+ 4], b->a[i+ 5], b->a[i+ 6], b->a[i+ 7], + b->a[i+ 8], b->a[i+ 9], b->a[i+10], b->a[i+11], + b->a[i+12], b->a[i+13], b->a[i+14], b->a[i+15]); + } + // row rounds (b = Z) + for (int i = 0; i < 16; i += 2) { + ROUND(b->a[i ], b->a[i+ 1], b->a[i+ 16], b->a[i+ 17], + b->a[i+32], b->a[i+33], b->a[i+ 48], b->a[i+ 49], + b->a[i+64], b->a[i+65], b->a[i+ 80], b->a[i+ 81], + b->a[i+96], b->a[i+97], b->a[i+112], b->a[i+113]); + } +} + +const crypto_argon2_extras crypto_argon2_no_extras = { 0, 0, 0, 0 }; + +void crypto_argon2(u8 *hash, u32 hash_size, void *work_area, + crypto_argon2_config config, + crypto_argon2_inputs inputs, + crypto_argon2_extras extras) +{ + const u32 segment_size = config.nb_blocks / config.nb_lanes / 4; + const u32 lane_size = segment_size * 4; + const u32 nb_blocks = lane_size * config.nb_lanes; // rounding down + + // work area seen as blocks (must be suitably aligned) + blk *blocks = (blk*)work_area; + { + u8 initial_hash[72]; // 64 bytes plus 2 words for future hashes + crypto_blake2b_ctx ctx; + crypto_blake2b_init (&ctx, 64); + blake_update_32 (&ctx, config.nb_lanes ); // p: number of "threads" + blake_update_32 (&ctx, hash_size); + blake_update_32 (&ctx, config.nb_blocks); + blake_update_32 (&ctx, config.nb_passes); + blake_update_32 (&ctx, 0x13); // v: version number + blake_update_32 (&ctx, config.algorithm); // y: Argon2i, Argon2d... + blake_update_32_buf (&ctx, inputs.pass, inputs.pass_size); + blake_update_32_buf (&ctx, inputs.salt, inputs.salt_size); + blake_update_32_buf (&ctx, extras.key, extras.key_size); + blake_update_32_buf (&ctx, extras.ad, extras.ad_size); + crypto_blake2b_final(&ctx, initial_hash); // fill 64 first bytes only + + // fill first 2 blocks of each lane + u8 hash_area[1024]; + FOR_T(u32, l, 0, config.nb_lanes) { + FOR_T(u32, i, 0, 2) { + store32_le(initial_hash + 64, i); // first additional word + store32_le(initial_hash + 68, l); // second additional word + extended_hash(hash_area, 1024, initial_hash, 72); + load64_le_buf(blocks[l * lane_size + i].a, hash_area, 128); + } + } + + WIPE_BUFFER(initial_hash); + WIPE_BUFFER(hash_area); + } + + // Argon2i and Argon2id start with constant time indexing + int constant_time = config.algorithm != CRYPTO_ARGON2_D; + + // Fill (and re-fill) the rest of the blocks + // + // Note: even though each segment within the same slice can be + // computed in parallel, (one thread per lane), we are computing + // them sequentially, because Monocypher doesn't support threads. + // + // Yet optimal performance (and therefore security) requires one + // thread per lane. The only reason Monocypher supports multiple + // lanes is compatibility. + blk tmp; + FOR_T(u32, pass, 0, config.nb_passes) { + FOR_T(u32, slice, 0, 4) { + // On the first slice of the first pass, + // blocks 0 and 1 are already filled, hence pass_offset. + u32 pass_offset = pass == 0 && slice == 0 ? 2 : 0; + u32 slice_offset = slice * segment_size; + + // Argon2id switches back to non-constant time indexing + // after the first two slices of the first pass + if (slice == 2 && config.algorithm == CRYPTO_ARGON2_ID) { + constant_time = 0; + } + + // Each iteration of the following loop may be performed in + // a separate thread. All segments must be fully completed + // before we start filling the next slice. + FOR_T(u32, segment, 0, config.nb_lanes) { + blk index_block; + u32 index_ctr = 1; + FOR_T (u32, block, pass_offset, segment_size) { + // Current and previous blocks + u32 lane_offset = segment * lane_size; + blk *segment_start = blocks + lane_offset + slice_offset; + blk *current = segment_start + block; + blk *previous = + block == 0 && slice_offset == 0 + ? segment_start + lane_size - 1 + : segment_start + block - 1; + + u64 index_seed; + if (constant_time) { + if (block == pass_offset || (block % 128) == 0) { + // Fill or refresh deterministic indices block + + // seed the beginning of the block... + ZERO(index_block.a, 128); + index_block.a[0] = pass; + index_block.a[1] = segment; + index_block.a[2] = slice; + index_block.a[3] = nb_blocks; + index_block.a[4] = config.nb_passes; + index_block.a[5] = config.algorithm; + index_block.a[6] = index_ctr; + index_ctr++; + + // ... then shuffle it + copy_block(&tmp, &index_block); + g_rounds (&index_block); + xor_block (&index_block, &tmp); + copy_block(&tmp, &index_block); + g_rounds (&index_block); + xor_block (&index_block, &tmp); + } + index_seed = index_block.a[block % 128]; + } else { + index_seed = previous->a[0]; + } + + // Establish the reference set. *Approximately* comprises: + // - The last 3 slices (if they exist yet) + // - The already constructed blocks in the current segment + u32 next_slice = ((slice + 1) % 4) * segment_size; + u32 window_start = pass == 0 ? 0 : next_slice; + u32 nb_segments = pass == 0 ? slice : 3; + u32 lane = + pass == 0 && slice == 0 + ? segment + : (index_seed >> 32) % config.nb_lanes; + u32 window_size = + nb_segments * segment_size + + (lane == segment ? block-1 : + block == 0 ? (u32)-1 : 0); + + // Find reference block + u64 j1 = index_seed & 0xffffffff; // block selector + u64 x = (j1 * j1) >> 32; + u64 y = (window_size * x) >> 32; + u64 z = (window_size - 1) - y; + u32 ref = (window_start + z) % lane_size; + u32 index = lane * lane_size + ref; + blk *reference = blocks + index; + + // Shuffle the previous & reference block + // into the current block + copy_block(&tmp, previous); + xor_block (&tmp, reference); + if (pass == 0) { copy_block(current, &tmp); } + else { xor_block (current, &tmp); } + g_rounds (&tmp); + xor_block (current, &tmp); + } + } + } + } + + // Wipe temporary block + volatile u64* p = tmp.a; + ZERO(p, 128); + + // XOR last blocks of each lane + blk *last_block = blocks + lane_size - 1; + FOR_T (u32, lane, 1, config.nb_lanes) { + blk *next_block = last_block + lane_size; + xor_block(next_block, last_block); + last_block = next_block; + } + + // Serialize last block + u8 final_block[1024]; + store64_le_buf(final_block, last_block->a, 128); + + // Wipe work area + p = (u64*)work_area; + ZERO(p, 128 * nb_blocks); + + // Hash the very last block with H' into the output hash + extended_hash(hash, hash_size, final_block, 1024); + WIPE_BUFFER(final_block); +} + +//////////////////////////////////// +/// Arithmetic modulo 2^255 - 19 /// +//////////////////////////////////// +// Originally taken from SUPERCOP's ref10 implementation. +// A bit bigger than TweetNaCl, over 4 times faster. + +// field element +typedef i32 fe[10]; + +// field constants +// +// fe_one : 1 +// sqrtm1 : sqrt(-1) +// d : -121665 / 121666 +// D2 : 2 * -121665 / 121666 +// lop_x, lop_y: low order point in Edwards coordinates +// ufactor : -sqrt(-1) * 2 +// A2 : 486662^2 (A squared) +static const fe fe_one = {1}; +static const fe sqrtm1 = { + -32595792, -7943725, 9377950, 3500415, 12389472, + -272473, -25146209, -2005654, 326686, 11406482, +}; +static const fe d = { + -10913610, 13857413, -15372611, 6949391, 114729, + -8787816, -6275908, -3247719, -18696448, -12055116, +}; +static const fe D2 = { + -21827239, -5839606, -30745221, 13898782, 229458, + 15978800, -12551817, -6495438, 29715968, 9444199, +}; +static const fe lop_x = { + 21352778, 5345713, 4660180, -8347857, 24143090, + 14568123, 30185756, -12247770, -33528939, 8345319, +}; +static const fe lop_y = { + -6952922, -1265500, 6862341, -7057498, -4037696, + -5447722, 31680899, -15325402, -19365852, 1569102, +}; +static const fe ufactor = { + -1917299, 15887451, -18755900, -7000830, -24778944, + 544946, -16816446, 4011309, -653372, 10741468, +}; +static const fe A2 = { + 12721188, 3529, 0, 0, 0, 0, 0, 0, 0, 0, +}; + +static void fe_0(fe h) { ZERO(h , 10); } +static void fe_1(fe h) { h[0] = 1; ZERO(h+1, 9); } + +static void fe_copy(fe h,const fe f ){FOR(i,0,10) h[i] = f[i]; } +static void fe_neg (fe h,const fe f ){FOR(i,0,10) h[i] = -f[i]; } +static void fe_add (fe h,const fe f,const fe g){FOR(i,0,10) h[i] = f[i] + g[i];} +static void fe_sub (fe h,const fe f,const fe g){FOR(i,0,10) h[i] = f[i] - g[i];} + +static void fe_cswap(fe f, fe g, int b) +{ + i32 mask = -b; // -1 = 0xffffffff + FOR (i, 0, 10) { + i32 x = (f[i] ^ g[i]) & mask; + f[i] = f[i] ^ x; + g[i] = g[i] ^ x; + } +} + +static void fe_ccopy(fe f, const fe g, int b) +{ + i32 mask = -b; // -1 = 0xffffffff + FOR (i, 0, 10) { + i32 x = (f[i] ^ g[i]) & mask; + f[i] = f[i] ^ x; + } +} + + +// Signed carry propagation +// ------------------------ +// +// Let t be a number. It can be uniquely decomposed thus: +// +// t = h*2^26 + l +// such that -2^25 <= l < 2^25 +// +// Let c = (t + 2^25) / 2^26 (rounded down) +// c = (h*2^26 + l + 2^25) / 2^26 (rounded down) +// c = h + (l + 2^25) / 2^26 (rounded down) +// c = h (exactly) +// Because 0 <= l + 2^25 < 2^26 +// +// Let u = t - c*2^26 +// u = h*2^26 + l - h*2^26 +// u = l +// Therefore, -2^25 <= u < 2^25 +// +// Additionally, if |t| < x, then |h| < x/2^26 (rounded down) +// +// Notations: +// - In C, 1<<25 means 2^25. +// - In C, x>>25 means floor(x / (2^25)). +// - All of the above applies with 25 & 24 as well as 26 & 25. +// +// +// Note on negative right shifts +// ----------------------------- +// +// In C, x >> n, where x is a negative integer, is implementation +// defined. In practice, all platforms do arithmetic shift, which is +// equivalent to division by 2^26, rounded down. Some compilers, like +// GCC, even guarantee it. +// +// If we ever stumble upon a platform that does not propagate the sign +// bit (we won't), visible failures will show at the slightest test, and +// the signed shifts can be replaced by the following: +// +// typedef struct { i64 x:39; } s25; +// typedef struct { i64 x:38; } s26; +// i64 shift25(i64 x) { s25 s; s.x = ((u64)x)>>25; return s.x; } +// i64 shift26(i64 x) { s26 s; s.x = ((u64)x)>>26; return s.x; } +// +// Current compilers cannot optimise this, causing a 30% drop in +// performance. Fairly expensive for something that never happens. +// +// +// Precondition +// ------------ +// +// |t0| < 2^63 +// |t1|..|t9| < 2^62 +// +// Algorithm +// --------- +// c = t0 + 2^25 / 2^26 -- |c| <= 2^36 +// t0 -= c * 2^26 -- |t0| <= 2^25 +// t1 += c -- |t1| <= 2^63 +// +// c = t4 + 2^25 / 2^26 -- |c| <= 2^36 +// t4 -= c * 2^26 -- |t4| <= 2^25 +// t5 += c -- |t5| <= 2^63 +// +// c = t1 + 2^24 / 2^25 -- |c| <= 2^38 +// t1 -= c * 2^25 -- |t1| <= 2^24 +// t2 += c -- |t2| <= 2^63 +// +// c = t5 + 2^24 / 2^25 -- |c| <= 2^38 +// t5 -= c * 2^25 -- |t5| <= 2^24 +// t6 += c -- |t6| <= 2^63 +// +// c = t2 + 2^25 / 2^26 -- |c| <= 2^37 +// t2 -= c * 2^26 -- |t2| <= 2^25 < 1.1 * 2^25 (final t2) +// t3 += c -- |t3| <= 2^63 +// +// c = t6 + 2^25 / 2^26 -- |c| <= 2^37 +// t6 -= c * 2^26 -- |t6| <= 2^25 < 1.1 * 2^25 (final t6) +// t7 += c -- |t7| <= 2^63 +// +// c = t3 + 2^24 / 2^25 -- |c| <= 2^38 +// t3 -= c * 2^25 -- |t3| <= 2^24 < 1.1 * 2^24 (final t3) +// t4 += c -- |t4| <= 2^25 + 2^38 < 2^39 +// +// c = t7 + 2^24 / 2^25 -- |c| <= 2^38 +// t7 -= c * 2^25 -- |t7| <= 2^24 < 1.1 * 2^24 (final t7) +// t8 += c -- |t8| <= 2^63 +// +// c = t4 + 2^25 / 2^26 -- |c| <= 2^13 +// t4 -= c * 2^26 -- |t4| <= 2^25 < 1.1 * 2^25 (final t4) +// t5 += c -- |t5| <= 2^24 + 2^13 < 1.1 * 2^24 (final t5) +// +// c = t8 + 2^25 / 2^26 -- |c| <= 2^37 +// t8 -= c * 2^26 -- |t8| <= 2^25 < 1.1 * 2^25 (final t8) +// t9 += c -- |t9| <= 2^63 +// +// c = t9 + 2^24 / 2^25 -- |c| <= 2^38 +// t9 -= c * 2^25 -- |t9| <= 2^24 < 1.1 * 2^24 (final t9) +// t0 += c * 19 -- |t0| <= 2^25 + 2^38*19 < 2^44 +// +// c = t0 + 2^25 / 2^26 -- |c| <= 2^18 +// t0 -= c * 2^26 -- |t0| <= 2^25 < 1.1 * 2^25 (final t0) +// t1 += c -- |t1| <= 2^24 + 2^18 < 1.1 * 2^24 (final t1) +// +// Postcondition +// ------------- +// |t0|, |t2|, |t4|, |t6|, |t8| < 1.1 * 2^25 +// |t1|, |t3|, |t5|, |t7|, |t9| < 1.1 * 2^24 +#define FE_CARRY \ + i64 c; \ + c = (t0 + ((i64)1<<25)) >> 26; t0 -= c * ((i64)1 << 26); t1 += c; \ + c = (t4 + ((i64)1<<25)) >> 26; t4 -= c * ((i64)1 << 26); t5 += c; \ + c = (t1 + ((i64)1<<24)) >> 25; t1 -= c * ((i64)1 << 25); t2 += c; \ + c = (t5 + ((i64)1<<24)) >> 25; t5 -= c * ((i64)1 << 25); t6 += c; \ + c = (t2 + ((i64)1<<25)) >> 26; t2 -= c * ((i64)1 << 26); t3 += c; \ + c = (t6 + ((i64)1<<25)) >> 26; t6 -= c * ((i64)1 << 26); t7 += c; \ + c = (t3 + ((i64)1<<24)) >> 25; t3 -= c * ((i64)1 << 25); t4 += c; \ + c = (t7 + ((i64)1<<24)) >> 25; t7 -= c * ((i64)1 << 25); t8 += c; \ + c = (t4 + ((i64)1<<25)) >> 26; t4 -= c * ((i64)1 << 26); t5 += c; \ + c = (t8 + ((i64)1<<25)) >> 26; t8 -= c * ((i64)1 << 26); t9 += c; \ + c = (t9 + ((i64)1<<24)) >> 25; t9 -= c * ((i64)1 << 25); t0 += c * 19; \ + c = (t0 + ((i64)1<<25)) >> 26; t0 -= c * ((i64)1 << 26); t1 += c; \ + h[0]=(i32)t0; h[1]=(i32)t1; h[2]=(i32)t2; h[3]=(i32)t3; h[4]=(i32)t4; \ + h[5]=(i32)t5; h[6]=(i32)t6; h[7]=(i32)t7; h[8]=(i32)t8; h[9]=(i32)t9 + +// Decodes a field element from a byte buffer. +// mask specifies how many bits we ignore. +// Traditionally we ignore 1. It's useful for EdDSA, +// which uses that bit to denote the sign of x. +// Elligator however uses positive representatives, +// which means ignoring 2 bits instead. +static void fe_frombytes_mask(fe h, const u8 s[32], unsigned nb_mask) +{ + u32 mask = 0xffffff >> nb_mask; + i64 t0 = load32_le(s); // t0 < 2^32 + i64 t1 = load24_le(s + 4) << 6; // t1 < 2^30 + i64 t2 = load24_le(s + 7) << 5; // t2 < 2^29 + i64 t3 = load24_le(s + 10) << 3; // t3 < 2^27 + i64 t4 = load24_le(s + 13) << 2; // t4 < 2^26 + i64 t5 = load32_le(s + 16); // t5 < 2^32 + i64 t6 = load24_le(s + 20) << 7; // t6 < 2^31 + i64 t7 = load24_le(s + 23) << 5; // t7 < 2^29 + i64 t8 = load24_le(s + 26) << 4; // t8 < 2^28 + i64 t9 = (load24_le(s + 29) & mask) << 2; // t9 < 2^25 + FE_CARRY; // Carry precondition OK +} + +static void fe_frombytes(fe h, const u8 s[32]) +{ + fe_frombytes_mask(h, s, 1); +} + + +// Precondition +// |h[0]|, |h[2]|, |h[4]|, |h[6]|, |h[8]| < 1.1 * 2^25 +// |h[1]|, |h[3]|, |h[5]|, |h[7]|, |h[9]| < 1.1 * 2^24 +// +// Therefore, |h| < 2^255-19 +// There are two possibilities: +// +// - If h is positive, all we need to do is reduce its individual +// limbs down to their tight positive range. +// - If h is negative, we also need to add 2^255-19 to it. +// Or just remove 19 and chop off any excess bit. +static void fe_tobytes(u8 s[32], const fe h) +{ + i32 t[10]; + COPY(t, h, 10); + i32 q = (19 * t[9] + (((i32) 1) << 24)) >> 25; + // |t9| < 1.1 * 2^24 + // -1.1 * 2^24 < t9 < 1.1 * 2^24 + // -21 * 2^24 < 19 * t9 < 21 * 2^24 + // -2^29 < 19 * t9 + 2^24 < 2^29 + // -2^29 / 2^25 < (19 * t9 + 2^24) / 2^25 < 2^29 / 2^25 + // -16 < (19 * t9 + 2^24) / 2^25 < 16 + FOR (i, 0, 5) { + q += t[2*i ]; q >>= 26; // q = 0 or -1 + q += t[2*i+1]; q >>= 25; // q = 0 or -1 + } + // q = 0 iff h >= 0 + // q = -1 iff h < 0 + // Adding q * 19 to h reduces h to its proper range. + q *= 19; // Shift carry back to the beginning + FOR (i, 0, 5) { + t[i*2 ] += q; q = t[i*2 ] >> 26; t[i*2 ] -= q * ((i32)1 << 26); + t[i*2+1] += q; q = t[i*2+1] >> 25; t[i*2+1] -= q * ((i32)1 << 25); + } + // h is now fully reduced, and q represents the excess bit. + + store32_le(s + 0, ((u32)t[0] >> 0) | ((u32)t[1] << 26)); + store32_le(s + 4, ((u32)t[1] >> 6) | ((u32)t[2] << 19)); + store32_le(s + 8, ((u32)t[2] >> 13) | ((u32)t[3] << 13)); + store32_le(s + 12, ((u32)t[3] >> 19) | ((u32)t[4] << 6)); + store32_le(s + 16, ((u32)t[5] >> 0) | ((u32)t[6] << 25)); + store32_le(s + 20, ((u32)t[6] >> 7) | ((u32)t[7] << 19)); + store32_le(s + 24, ((u32)t[7] >> 13) | ((u32)t[8] << 12)); + store32_le(s + 28, ((u32)t[8] >> 20) | ((u32)t[9] << 6)); + + WIPE_BUFFER(t); +} + +// Precondition +// ------------- +// |f0|, |f2|, |f4|, |f6|, |f8| < 1.65 * 2^26 +// |f1|, |f3|, |f5|, |f7|, |f9| < 1.65 * 2^25 +// +// |g0|, |g2|, |g4|, |g6|, |g8| < 1.65 * 2^26 +// |g1|, |g3|, |g5|, |g7|, |g9| < 1.65 * 2^25 +static void fe_mul_small(fe h, const fe f, i32 g) +{ + i64 t0 = f[0] * (i64) g; i64 t1 = f[1] * (i64) g; + i64 t2 = f[2] * (i64) g; i64 t3 = f[3] * (i64) g; + i64 t4 = f[4] * (i64) g; i64 t5 = f[5] * (i64) g; + i64 t6 = f[6] * (i64) g; i64 t7 = f[7] * (i64) g; + i64 t8 = f[8] * (i64) g; i64 t9 = f[9] * (i64) g; + // |t0|, |t2|, |t4|, |t6|, |t8| < 1.65 * 2^26 * 2^31 < 2^58 + // |t1|, |t3|, |t5|, |t7|, |t9| < 1.65 * 2^25 * 2^31 < 2^57 + + FE_CARRY; // Carry precondition OK +} + +// Precondition +// ------------- +// |f0|, |f2|, |f4|, |f6|, |f8| < 1.65 * 2^26 +// |f1|, |f3|, |f5|, |f7|, |f9| < 1.65 * 2^25 +// +// |g0|, |g2|, |g4|, |g6|, |g8| < 1.65 * 2^26 +// |g1|, |g3|, |g5|, |g7|, |g9| < 1.65 * 2^25 +static void fe_mul(fe h, const fe f, const fe g) +{ + // Everything is unrolled and put in temporary variables. + // We could roll the loop, but that would make curve25519 twice as slow. + i32 f0 = f[0]; i32 f1 = f[1]; i32 f2 = f[2]; i32 f3 = f[3]; i32 f4 = f[4]; + i32 f5 = f[5]; i32 f6 = f[6]; i32 f7 = f[7]; i32 f8 = f[8]; i32 f9 = f[9]; + i32 g0 = g[0]; i32 g1 = g[1]; i32 g2 = g[2]; i32 g3 = g[3]; i32 g4 = g[4]; + i32 g5 = g[5]; i32 g6 = g[6]; i32 g7 = g[7]; i32 g8 = g[8]; i32 g9 = g[9]; + i32 F1 = f1*2; i32 F3 = f3*2; i32 F5 = f5*2; i32 F7 = f7*2; i32 F9 = f9*2; + i32 G1 = g1*19; i32 G2 = g2*19; i32 G3 = g3*19; + i32 G4 = g4*19; i32 G5 = g5*19; i32 G6 = g6*19; + i32 G7 = g7*19; i32 G8 = g8*19; i32 G9 = g9*19; + // |F1|, |F3|, |F5|, |F7|, |F9| < 1.65 * 2^26 + // |G0|, |G2|, |G4|, |G6|, |G8| < 2^31 + // |G1|, |G3|, |G5|, |G7|, |G9| < 2^30 + + i64 t0 = f0*(i64)g0 + F1*(i64)G9 + f2*(i64)G8 + F3*(i64)G7 + f4*(i64)G6 + + F5*(i64)G5 + f6*(i64)G4 + F7*(i64)G3 + f8*(i64)G2 + F9*(i64)G1; + i64 t1 = f0*(i64)g1 + f1*(i64)g0 + f2*(i64)G9 + f3*(i64)G8 + f4*(i64)G7 + + f5*(i64)G6 + f6*(i64)G5 + f7*(i64)G4 + f8*(i64)G3 + f9*(i64)G2; + i64 t2 = f0*(i64)g2 + F1*(i64)g1 + f2*(i64)g0 + F3*(i64)G9 + f4*(i64)G8 + + F5*(i64)G7 + f6*(i64)G6 + F7*(i64)G5 + f8*(i64)G4 + F9*(i64)G3; + i64 t3 = f0*(i64)g3 + f1*(i64)g2 + f2*(i64)g1 + f3*(i64)g0 + f4*(i64)G9 + + f5*(i64)G8 + f6*(i64)G7 + f7*(i64)G6 + f8*(i64)G5 + f9*(i64)G4; + i64 t4 = f0*(i64)g4 + F1*(i64)g3 + f2*(i64)g2 + F3*(i64)g1 + f4*(i64)g0 + + F5*(i64)G9 + f6*(i64)G8 + F7*(i64)G7 + f8*(i64)G6 + F9*(i64)G5; + i64 t5 = f0*(i64)g5 + f1*(i64)g4 + f2*(i64)g3 + f3*(i64)g2 + f4*(i64)g1 + + f5*(i64)g0 + f6*(i64)G9 + f7*(i64)G8 + f8*(i64)G7 + f9*(i64)G6; + i64 t6 = f0*(i64)g6 + F1*(i64)g5 + f2*(i64)g4 + F3*(i64)g3 + f4*(i64)g2 + + F5*(i64)g1 + f6*(i64)g0 + F7*(i64)G9 + f8*(i64)G8 + F9*(i64)G7; + i64 t7 = f0*(i64)g7 + f1*(i64)g6 + f2*(i64)g5 + f3*(i64)g4 + f4*(i64)g3 + + f5*(i64)g2 + f6*(i64)g1 + f7*(i64)g0 + f8*(i64)G9 + f9*(i64)G8; + i64 t8 = f0*(i64)g8 + F1*(i64)g7 + f2*(i64)g6 + F3*(i64)g5 + f4*(i64)g4 + + F5*(i64)g3 + f6*(i64)g2 + F7*(i64)g1 + f8*(i64)g0 + F9*(i64)G9; + i64 t9 = f0*(i64)g9 + f1*(i64)g8 + f2*(i64)g7 + f3*(i64)g6 + f4*(i64)g5 + + f5*(i64)g4 + f6*(i64)g3 + f7*(i64)g2 + f8*(i64)g1 + f9*(i64)g0; + // t0 < 0.67 * 2^61 + // t1 < 0.41 * 2^61 + // t2 < 0.52 * 2^61 + // t3 < 0.32 * 2^61 + // t4 < 0.38 * 2^61 + // t5 < 0.22 * 2^61 + // t6 < 0.23 * 2^61 + // t7 < 0.13 * 2^61 + // t8 < 0.09 * 2^61 + // t9 < 0.03 * 2^61 + + FE_CARRY; // Everything below 2^62, Carry precondition OK +} + +// Precondition +// ------------- +// |f0|, |f2|, |f4|, |f6|, |f8| < 1.65 * 2^26 +// |f1|, |f3|, |f5|, |f7|, |f9| < 1.65 * 2^25 +// +// Note: we could use fe_mul() for this, but this is significantly faster +static void fe_sq(fe h, const fe f) +{ + i32 f0 = f[0]; i32 f1 = f[1]; i32 f2 = f[2]; i32 f3 = f[3]; i32 f4 = f[4]; + i32 f5 = f[5]; i32 f6 = f[6]; i32 f7 = f[7]; i32 f8 = f[8]; i32 f9 = f[9]; + i32 f0_2 = f0*2; i32 f1_2 = f1*2; i32 f2_2 = f2*2; i32 f3_2 = f3*2; + i32 f4_2 = f4*2; i32 f5_2 = f5*2; i32 f6_2 = f6*2; i32 f7_2 = f7*2; + i32 f5_38 = f5*38; i32 f6_19 = f6*19; i32 f7_38 = f7*38; + i32 f8_19 = f8*19; i32 f9_38 = f9*38; + // |f0_2| , |f2_2| , |f4_2| , |f6_2| , |f8_2| < 1.65 * 2^27 + // |f1_2| , |f3_2| , |f5_2| , |f7_2| , |f9_2| < 1.65 * 2^26 + // |f5_38|, |f6_19|, |f7_38|, |f8_19|, |f9_38| < 2^31 + + i64 t0 = f0 *(i64)f0 + f1_2*(i64)f9_38 + f2_2*(i64)f8_19 + + f3_2*(i64)f7_38 + f4_2*(i64)f6_19 + f5 *(i64)f5_38; + i64 t1 = f0_2*(i64)f1 + f2 *(i64)f9_38 + f3_2*(i64)f8_19 + + f4 *(i64)f7_38 + f5_2*(i64)f6_19; + i64 t2 = f0_2*(i64)f2 + f1_2*(i64)f1 + f3_2*(i64)f9_38 + + f4_2*(i64)f8_19 + f5_2*(i64)f7_38 + f6 *(i64)f6_19; + i64 t3 = f0_2*(i64)f3 + f1_2*(i64)f2 + f4 *(i64)f9_38 + + f5_2*(i64)f8_19 + f6 *(i64)f7_38; + i64 t4 = f0_2*(i64)f4 + f1_2*(i64)f3_2 + f2 *(i64)f2 + + f5_2*(i64)f9_38 + f6_2*(i64)f8_19 + f7 *(i64)f7_38; + i64 t5 = f0_2*(i64)f5 + f1_2*(i64)f4 + f2_2*(i64)f3 + + f6 *(i64)f9_38 + f7_2*(i64)f8_19; + i64 t6 = f0_2*(i64)f6 + f1_2*(i64)f5_2 + f2_2*(i64)f4 + + f3_2*(i64)f3 + f7_2*(i64)f9_38 + f8 *(i64)f8_19; + i64 t7 = f0_2*(i64)f7 + f1_2*(i64)f6 + f2_2*(i64)f5 + + f3_2*(i64)f4 + f8 *(i64)f9_38; + i64 t8 = f0_2*(i64)f8 + f1_2*(i64)f7_2 + f2_2*(i64)f6 + + f3_2*(i64)f5_2 + f4 *(i64)f4 + f9 *(i64)f9_38; + i64 t9 = f0_2*(i64)f9 + f1_2*(i64)f8 + f2_2*(i64)f7 + + f3_2*(i64)f6 + f4 *(i64)f5_2; + // t0 < 0.67 * 2^61 + // t1 < 0.41 * 2^61 + // t2 < 0.52 * 2^61 + // t3 < 0.32 * 2^61 + // t4 < 0.38 * 2^61 + // t5 < 0.22 * 2^61 + // t6 < 0.23 * 2^61 + // t7 < 0.13 * 2^61 + // t8 < 0.09 * 2^61 + // t9 < 0.03 * 2^61 + + FE_CARRY; +} + +// Parity check. Returns 0 if even, 1 if odd +static int fe_isodd(const fe f) +{ + u8 s[32]; + fe_tobytes(s, f); + u8 isodd = s[0] & 1; + WIPE_BUFFER(s); + return isodd; +} + +// Returns 1 if equal, 0 if not equal +static int fe_isequal(const fe f, const fe g) +{ + u8 fs[32]; + u8 gs[32]; + fe_tobytes(fs, f); + fe_tobytes(gs, g); + int isdifferent = crypto_verify32(fs, gs); + WIPE_BUFFER(fs); + WIPE_BUFFER(gs); + return 1 + isdifferent; +} + +// Inverse square root. +// Returns true if x is a square, false otherwise. +// After the call: +// isr = sqrt(1/x) if x is a non-zero square. +// isr = sqrt(sqrt(-1)/x) if x is not a square. +// isr = 0 if x is zero. +// We do not guarantee the sign of the square root. +// +// Notes: +// Let quartic = x^((p-1)/4) +// +// x^((p-1)/2) = chi(x) +// quartic^2 = chi(x) +// quartic = sqrt(chi(x)) +// quartic = 1 or -1 or sqrt(-1) or -sqrt(-1) +// +// Note that x is a square if quartic is 1 or -1 +// There are 4 cases to consider: +// +// if quartic = 1 (x is a square) +// then x^((p-1)/4) = 1 +// x^((p-5)/4) * x = 1 +// x^((p-5)/4) = 1/x +// x^((p-5)/8) = sqrt(1/x) or -sqrt(1/x) +// +// if quartic = -1 (x is a square) +// then x^((p-1)/4) = -1 +// x^((p-5)/4) * x = -1 +// x^((p-5)/4) = -1/x +// x^((p-5)/8) = sqrt(-1) / sqrt(x) +// x^((p-5)/8) * sqrt(-1) = sqrt(-1)^2 / sqrt(x) +// x^((p-5)/8) * sqrt(-1) = -1/sqrt(x) +// x^((p-5)/8) * sqrt(-1) = -sqrt(1/x) or sqrt(1/x) +// +// if quartic = sqrt(-1) (x is not a square) +// then x^((p-1)/4) = sqrt(-1) +// x^((p-5)/4) * x = sqrt(-1) +// x^((p-5)/4) = sqrt(-1)/x +// x^((p-5)/8) = sqrt(sqrt(-1)/x) or -sqrt(sqrt(-1)/x) +// +// Note that the product of two non-squares is always a square: +// For any non-squares a and b, chi(a) = -1 and chi(b) = -1. +// Since chi(x) = x^((p-1)/2), chi(a)*chi(b) = chi(a*b) = 1. +// Therefore a*b is a square. +// +// Since sqrt(-1) and x are both non-squares, their product is a +// square, and we can compute their square root. +// +// if quartic = -sqrt(-1) (x is not a square) +// then x^((p-1)/4) = -sqrt(-1) +// x^((p-5)/4) * x = -sqrt(-1) +// x^((p-5)/4) = -sqrt(-1)/x +// x^((p-5)/8) = sqrt(-sqrt(-1)/x) +// x^((p-5)/8) = sqrt( sqrt(-1)/x) * sqrt(-1) +// x^((p-5)/8) * sqrt(-1) = sqrt( sqrt(-1)/x) * sqrt(-1)^2 +// x^((p-5)/8) * sqrt(-1) = sqrt( sqrt(-1)/x) * -1 +// x^((p-5)/8) * sqrt(-1) = -sqrt(sqrt(-1)/x) or sqrt(sqrt(-1)/x) +static int invsqrt(fe isr, const fe x) +{ + fe t0, t1, t2; + + // t0 = x^((p-5)/8) + // Can be achieved with a simple double & add ladder, + // but it would be slower. + fe_sq(t0, x); + fe_sq(t1,t0); fe_sq(t1, t1); fe_mul(t1, x, t1); + fe_mul(t0, t0, t1); + fe_sq(t0, t0); fe_mul(t0, t1, t0); + fe_sq(t1, t0); FOR (i, 1, 5) { fe_sq(t1, t1); } fe_mul(t0, t1, t0); + fe_sq(t1, t0); FOR (i, 1, 10) { fe_sq(t1, t1); } fe_mul(t1, t1, t0); + fe_sq(t2, t1); FOR (i, 1, 20) { fe_sq(t2, t2); } fe_mul(t1, t2, t1); + fe_sq(t1, t1); FOR (i, 1, 10) { fe_sq(t1, t1); } fe_mul(t0, t1, t0); + fe_sq(t1, t0); FOR (i, 1, 50) { fe_sq(t1, t1); } fe_mul(t1, t1, t0); + fe_sq(t2, t1); FOR (i, 1, 100) { fe_sq(t2, t2); } fe_mul(t1, t2, t1); + fe_sq(t1, t1); FOR (i, 1, 50) { fe_sq(t1, t1); } fe_mul(t0, t1, t0); + fe_sq(t0, t0); FOR (i, 1, 2) { fe_sq(t0, t0); } fe_mul(t0, t0, x); + + // quartic = x^((p-1)/4) + i32 *quartic = t1; + fe_sq (quartic, t0); + fe_mul(quartic, quartic, x); + + i32 *check = t2; + fe_0 (check); int z0 = fe_isequal(x , check); + fe_1 (check); int p1 = fe_isequal(quartic, check); + fe_neg(check, check ); int m1 = fe_isequal(quartic, check); + fe_neg(check, sqrtm1); int ms = fe_isequal(quartic, check); + + // if quartic == -1 or sqrt(-1) + // then isr = x^((p-1)/4) * sqrt(-1) + // else isr = x^((p-1)/4) + fe_mul(isr, t0, sqrtm1); + fe_ccopy(isr, t0, 1 - (m1 | ms)); + + WIPE_BUFFER(t0); + WIPE_BUFFER(t1); + WIPE_BUFFER(t2); + return p1 | m1 | z0; +} + +// Inverse in terms of inverse square root. +// Requires two additional squarings to get rid of the sign. +// +// 1/x = x * (+invsqrt(x^2))^2 +// = x * (-invsqrt(x^2))^2 +// +// A fully optimised exponentiation by p-1 would save 6 field +// multiplications, but it would require more code. +static void fe_invert(fe out, const fe x) +{ + fe tmp; + fe_sq(tmp, x); + invsqrt(tmp, tmp); + fe_sq(tmp, tmp); + fe_mul(out, tmp, x); + WIPE_BUFFER(tmp); +} + +// trim a scalar for scalar multiplication +void crypto_eddsa_trim_scalar(u8 out[32], const u8 in[32]) +{ + COPY(out, in, 32); + out[ 0] &= 248; + out[31] &= 127; + out[31] |= 64; +} + +// get bit from scalar at position i +static int scalar_bit(const u8 s[32], int i) +{ + if (i < 0) { return 0; } // handle -1 for sliding windows + return (s[i>>3] >> (i&7)) & 1; +} + +/////////////// +/// X-25519 /// Taken from SUPERCOP's ref10 implementation. +/////////////// +static void scalarmult(u8 q[32], const u8 scalar[32], const u8 p[32], + int nb_bits) +{ + // computes the scalar product + fe x1; + fe_frombytes(x1, p); + + // computes the actual scalar product (the result is in x2 and z2) + fe x2, z2, x3, z3, t0, t1; + // Montgomery ladder + // In projective coordinates, to avoid divisions: x = X / Z + // We don't care about the y coordinate, it's only 1 bit of information + fe_1(x2); fe_0(z2); // "zero" point + fe_copy(x3, x1); fe_1(z3); // "one" point + int swap = 0; + for (int pos = nb_bits-1; pos >= 0; --pos) { + // constant time conditional swap before ladder step + int b = scalar_bit(scalar, pos); + swap ^= b; // xor trick avoids swapping at the end of the loop + fe_cswap(x2, x3, swap); + fe_cswap(z2, z3, swap); + swap = b; // anticipates one last swap after the loop + + // Montgomery ladder step: replaces (P2, P3) by (P2*2, P2+P3) + // with differential addition + fe_sub(t0, x3, z3); + fe_sub(t1, x2, z2); + fe_add(x2, x2, z2); + fe_add(z2, x3, z3); + fe_mul(z3, t0, x2); + fe_mul(z2, z2, t1); + fe_sq (t0, t1 ); + fe_sq (t1, x2 ); + fe_add(x3, z3, z2); + fe_sub(z2, z3, z2); + fe_mul(x2, t1, t0); + fe_sub(t1, t1, t0); + fe_sq (z2, z2 ); + fe_mul_small(z3, t1, 121666); + fe_sq (x3, x3 ); + fe_add(t0, t0, z3); + fe_mul(z3, x1, z2); + fe_mul(z2, t1, t0); + } + // last swap is necessary to compensate for the xor trick + // Note: after this swap, P3 == P2 + P1. + fe_cswap(x2, x3, swap); + fe_cswap(z2, z3, swap); + + // normalises the coordinates: x == X / Z + fe_invert(z2, z2); + fe_mul(x2, x2, z2); + fe_tobytes(q, x2); + + WIPE_BUFFER(x1); + WIPE_BUFFER(x2); WIPE_BUFFER(z2); WIPE_BUFFER(t0); + WIPE_BUFFER(x3); WIPE_BUFFER(z3); WIPE_BUFFER(t1); +} + +void crypto_x25519(u8 raw_shared_secret[32], + const u8 your_secret_key [32], + const u8 their_public_key [32]) +{ + // restrict the possible scalar values + u8 e[32]; + crypto_eddsa_trim_scalar(e, your_secret_key); + scalarmult(raw_shared_secret, e, their_public_key, 255); + WIPE_BUFFER(e); +} + +void crypto_x25519_public_key(u8 public_key[32], + const u8 secret_key[32]) +{ + static const u8 base_point[32] = {9}; + crypto_x25519(public_key, secret_key, base_point); +} + +/////////////////////////// +/// Arithmetic modulo L /// +/////////////////////////// +static const u32 L[8] = { + 0x5cf5d3ed, 0x5812631a, 0xa2f79cd6, 0x14def9de, + 0x00000000, 0x00000000, 0x00000000, 0x10000000, +}; + +// p = a*b + p +static void multiply(u32 p[16], const u32 a[8], const u32 b[8]) +{ + FOR (i, 0, 8) { + u64 carry = 0; + FOR (j, 0, 8) { + carry += p[i+j] + (u64)a[i] * b[j]; + p[i+j] = (u32)carry; + carry >>= 32; + } + p[i+8] = (u32)carry; + } +} + +static int is_above_l(const u32 x[8]) +{ + // We work with L directly, in a 2's complement encoding + // (-L == ~L + 1) + u64 carry = 1; + FOR (i, 0, 8) { + carry += (u64)x[i] + (~L[i] & 0xffffffff); + carry >>= 32; + } + return (int)carry; // carry is either 0 or 1 +} + +// Final reduction modulo L, by conditionally removing L. +// if x < l , then r = x +// if l <= x 2*l, then r = x-l +// otherwise the result will be wrong +static void remove_l(u32 r[8], const u32 x[8]) +{ + u64 carry = (u64)is_above_l(x); + u32 mask = ~(u32)carry + 1; // carry == 0 or 1 + FOR (i, 0, 8) { + carry += (u64)x[i] + (~L[i] & mask); + r[i] = (u32)carry; + carry >>= 32; + } +} + +// Full reduction modulo L (Barrett reduction) +static void mod_l(u8 reduced[32], const u32 x[16]) +{ + static const u32 r[9] = { + 0x0a2c131b,0xed9ce5a3,0x086329a7,0x2106215d, + 0xffffffeb,0xffffffff,0xffffffff,0xffffffff,0xf, + }; + // xr = x * r + u32 xr[25] = {0}; + FOR (i, 0, 9) { + u64 carry = 0; + FOR (j, 0, 16) { + carry += xr[i+j] + (u64)r[i] * x[j]; + xr[i+j] = (u32)carry; + carry >>= 32; + } + xr[i+16] = (u32)carry; + } + // xr = floor(xr / 2^512) * L + // Since the result is guaranteed to be below 2*L, + // it is enough to only compute the first 256 bits. + // The division is performed by saying xr[i+16]. (16 * 32 = 512) + ZERO(xr, 8); + FOR (i, 0, 8) { + u64 carry = 0; + FOR (j, 0, 8-i) { + carry += xr[i+j] + (u64)xr[i+16] * L[j]; + xr[i+j] = (u32)carry; + carry >>= 32; + } + } + // xr = x - xr + u64 carry = 1; + FOR (i, 0, 8) { + carry += (u64)x[i] + (~xr[i] & 0xffffffff); + xr[i] = (u32)carry; + carry >>= 32; + } + // Final reduction modulo L (conditional subtraction) + remove_l(xr, xr); + store32_le_buf(reduced, xr, 8); + + WIPE_BUFFER(xr); +} + +void crypto_eddsa_reduce(u8 reduced[32], const u8 expanded[64]) +{ + u32 x[16]; + load32_le_buf(x, expanded, 16); + mod_l(reduced, x); + WIPE_BUFFER(x); +} + +// r = (a * b) + c +void crypto_eddsa_mul_add(u8 r[32], + const u8 a[32], const u8 b[32], const u8 c[32]) +{ + u32 A[8]; load32_le_buf(A, a, 8); + u32 B[8]; load32_le_buf(B, b, 8); + u32 p[16]; load32_le_buf(p, c, 8); ZERO(p + 8, 8); + multiply(p, A, B); + mod_l(r, p); + WIPE_BUFFER(p); + WIPE_BUFFER(A); + WIPE_BUFFER(B); +} + +/////////////// +/// Ed25519 /// +/////////////// + +// Point (group element, ge) in a twisted Edwards curve, +// in extended projective coordinates. +// ge : x = X/Z, y = Y/Z, T = XY/Z +// ge_cached : Yp = X+Y, Ym = X-Y, T2 = T*D2 +// ge_precomp: Z = 1 +typedef struct { fe X; fe Y; fe Z; fe T; } ge; +typedef struct { fe Yp; fe Ym; fe Z; fe T2; } ge_cached; +typedef struct { fe Yp; fe Ym; fe T2; } ge_precomp; + +static void ge_zero(ge *p) +{ + fe_0(p->X); + fe_1(p->Y); + fe_1(p->Z); + fe_0(p->T); +} + +static void ge_tobytes(u8 s[32], const ge *h) +{ + fe recip, x, y; + fe_invert(recip, h->Z); + fe_mul(x, h->X, recip); + fe_mul(y, h->Y, recip); + fe_tobytes(s, y); + s[31] ^= fe_isodd(x) << 7; + + WIPE_BUFFER(recip); + WIPE_BUFFER(x); + WIPE_BUFFER(y); +} + +// h = -s, where s is a point encoded in 32 bytes +// +// Variable time! Inputs must not be secret! +// => Use only to *check* signatures. +// +// From the specifications: +// The encoding of s contains y and the sign of x +// x = sqrt((y^2 - 1) / (d*y^2 + 1)) +// In extended coordinates: +// X = x, Y = y, Z = 1, T = x*y +// +// Note that num * den is a square iff num / den is a square +// If num * den is not a square, the point was not on the curve. +// From the above: +// Let num = y^2 - 1 +// Let den = d*y^2 + 1 +// x = sqrt((y^2 - 1) / (d*y^2 + 1)) +// x = sqrt(num / den) +// x = sqrt(num^2 / (num * den)) +// x = num * sqrt(1 / (num * den)) +// +// Therefore, we can just compute: +// num = y^2 - 1 +// den = d*y^2 + 1 +// isr = invsqrt(num * den) // abort if not square +// x = num * isr +// Finally, negate x if its sign is not as specified. +static int ge_frombytes_neg_vartime(ge *h, const u8 s[32]) +{ + fe_frombytes(h->Y, s); + fe_1(h->Z); + fe_sq (h->T, h->Y); // t = y^2 + fe_mul(h->X, h->T, d ); // x = d*y^2 + fe_sub(h->T, h->T, h->Z); // t = y^2 - 1 + fe_add(h->X, h->X, h->Z); // x = d*y^2 + 1 + fe_mul(h->X, h->T, h->X); // x = (y^2 - 1) * (d*y^2 + 1) + int is_square = invsqrt(h->X, h->X); + if (!is_square) { + return -1; // Not on the curve, abort + } + fe_mul(h->X, h->T, h->X); // x = sqrt((y^2 - 1) / (d*y^2 + 1)) + if (fe_isodd(h->X) == (s[31] >> 7)) { + fe_neg(h->X, h->X); + } + fe_mul(h->T, h->X, h->Y); + return 0; +} + +static void ge_cache(ge_cached *c, const ge *p) +{ + fe_add (c->Yp, p->Y, p->X); + fe_sub (c->Ym, p->Y, p->X); + fe_copy(c->Z , p->Z ); + fe_mul (c->T2, p->T, D2 ); +} + +// Internal buffers are not wiped! Inputs must not be secret! +// => Use only to *check* signatures. +static void ge_add(ge *s, const ge *p, const ge_cached *q) +{ + fe a, b; + fe_add(a , p->Y, p->X ); + fe_sub(b , p->Y, p->X ); + fe_mul(a , a , q->Yp); + fe_mul(b , b , q->Ym); + fe_add(s->Y, a , b ); + fe_sub(s->X, a , b ); + + fe_add(s->Z, p->Z, p->Z ); + fe_mul(s->Z, s->Z, q->Z ); + fe_mul(s->T, p->T, q->T2); + fe_add(a , s->Z, s->T ); + fe_sub(b , s->Z, s->T ); + + fe_mul(s->T, s->X, s->Y); + fe_mul(s->X, s->X, b ); + fe_mul(s->Y, s->Y, a ); + fe_mul(s->Z, a , b ); +} + +// Internal buffers are not wiped! Inputs must not be secret! +// => Use only to *check* signatures. +static void ge_sub(ge *s, const ge *p, const ge_cached *q) +{ + ge_cached neg; + fe_copy(neg.Ym, q->Yp); + fe_copy(neg.Yp, q->Ym); + fe_copy(neg.Z , q->Z ); + fe_neg (neg.T2, q->T2); + ge_add(s, p, &neg); +} + +static void ge_madd(ge *s, const ge *p, const ge_precomp *q, fe a, fe b) +{ + fe_add(a , p->Y, p->X ); + fe_sub(b , p->Y, p->X ); + fe_mul(a , a , q->Yp); + fe_mul(b , b , q->Ym); + fe_add(s->Y, a , b ); + fe_sub(s->X, a , b ); + + fe_add(s->Z, p->Z, p->Z ); + fe_mul(s->T, p->T, q->T2); + fe_add(a , s->Z, s->T ); + fe_sub(b , s->Z, s->T ); + + fe_mul(s->T, s->X, s->Y); + fe_mul(s->X, s->X, b ); + fe_mul(s->Y, s->Y, a ); + fe_mul(s->Z, a , b ); +} + +// Internal buffers are not wiped! Inputs must not be secret! +// => Use only to *check* signatures. +static void ge_msub(ge *s, const ge *p, const ge_precomp *q, fe a, fe b) +{ + ge_precomp neg; + fe_copy(neg.Ym, q->Yp); + fe_copy(neg.Yp, q->Ym); + fe_neg (neg.T2, q->T2); + ge_madd(s, p, &neg, a, b); +} + +static void ge_double(ge *s, const ge *p, ge *q) +{ + fe_sq (q->X, p->X); + fe_sq (q->Y, p->Y); + fe_sq (q->Z, p->Z); // qZ = pZ^2 + fe_mul_small(q->Z, q->Z, 2); // qZ = pZ^2 * 2 + fe_add(q->T, p->X, p->Y); + fe_sq (s->T, q->T); + fe_add(q->T, q->Y, q->X); + fe_sub(q->Y, q->Y, q->X); + fe_sub(q->X, s->T, q->T); + fe_sub(q->Z, q->Z, q->Y); + + fe_mul(s->X, q->X , q->Z); + fe_mul(s->Y, q->T , q->Y); + fe_mul(s->Z, q->Y , q->Z); + fe_mul(s->T, q->X , q->T); +} + +// 5-bit signed window in cached format (Niels coordinates, Z=1) +static const ge_precomp b_window[8] = { + {{25967493,-14356035,29566456,3660896,-12694345, + 4014787,27544626,-11754271,-6079156,2047605,}, + {-12545711,934262,-2722910,3049990,-727428, + 9406986,12720692,5043384,19500929,-15469378,}, + {-8738181,4489570,9688441,-14785194,10184609, + -12363380,29287919,11864899,-24514362,-4438546,},}, + {{15636291,-9688557,24204773,-7912398,616977, + -16685262,27787600,-14772189,28944400,-1550024,}, + {16568933,4717097,-11556148,-1102322,15682896, + -11807043,16354577,-11775962,7689662,11199574,}, + {30464156,-5976125,-11779434,-15670865,23220365, + 15915852,7512774,10017326,-17749093,-9920357,},}, + {{10861363,11473154,27284546,1981175,-30064349, + 12577861,32867885,14515107,-15438304,10819380,}, + {4708026,6336745,20377586,9066809,-11272109, + 6594696,-25653668,12483688,-12668491,5581306,}, + {19563160,16186464,-29386857,4097519,10237984, + -4348115,28542350,13850243,-23678021,-15815942,},}, + {{5153746,9909285,1723747,-2777874,30523605, + 5516873,19480852,5230134,-23952439,-15175766,}, + {-30269007,-3463509,7665486,10083793,28475525, + 1649722,20654025,16520125,30598449,7715701,}, + {28881845,14381568,9657904,3680757,-20181635, + 7843316,-31400660,1370708,29794553,-1409300,},}, + {{-22518993,-6692182,14201702,-8745502,-23510406, + 8844726,18474211,-1361450,-13062696,13821877,}, + {-6455177,-7839871,3374702,-4740862,-27098617, + -10571707,31655028,-7212327,18853322,-14220951,}, + {4566830,-12963868,-28974889,-12240689,-7602672, + -2830569,-8514358,-10431137,2207753,-3209784,},}, + {{-25154831,-4185821,29681144,7868801,-6854661, + -9423865,-12437364,-663000,-31111463,-16132436,}, + {25576264,-2703214,7349804,-11814844,16472782, + 9300885,3844789,15725684,171356,6466918,}, + {23103977,13316479,9739013,-16149481,817875, + -15038942,8965339,-14088058,-30714912,16193877,},}, + {{-33521811,3180713,-2394130,14003687,-16903474, + -16270840,17238398,4729455,-18074513,9256800,}, + {-25182317,-4174131,32336398,5036987,-21236817, + 11360617,22616405,9761698,-19827198,630305,}, + {-13720693,2639453,-24237460,-7406481,9494427, + -5774029,-6554551,-15960994,-2449256,-14291300,},}, + {{-3151181,-5046075,9282714,6866145,-31907062, + -863023,-18940575,15033784,25105118,-7894876,}, + {-24326370,15950226,-31801215,-14592823,-11662737, + -5090925,1573892,-2625887,2198790,-15804619,}, + {-3099351,10324967,-2241613,7453183,-5446979, + -2735503,-13812022,-16236442,-32461234,-12290683,},}, +}; + +// Incremental sliding windows (left to right) +// Based on Roberto Maria Avanzi[2005] +typedef struct { + i16 next_index; // position of the next signed digit + i8 next_digit; // next signed digit (odd number below 2^window_width) + u8 next_check; // point at which we must check for a new window +} slide_ctx; + +static void slide_init(slide_ctx *ctx, const u8 scalar[32]) +{ + // scalar is guaranteed to be below L, either because we checked (s), + // or because we reduced it modulo L (h_ram). L is under 2^253, so + // so bits 253 to 255 are guaranteed to be zero. No need to test them. + // + // Note however that L is very close to 2^252, so bit 252 is almost + // always zero. If we were to start at bit 251, the tests wouldn't + // catch the off-by-one error (constructing one that does would be + // prohibitively expensive). + // + // We should still check bit 252, though. + int i = 252; + while (i > 0 && scalar_bit(scalar, i) == 0) { + i--; + } + ctx->next_check = (u8)(i + 1); + ctx->next_index = -1; + ctx->next_digit = -1; +} + +static int slide_step(slide_ctx *ctx, int width, int i, const u8 scalar[32]) +{ + if (i == ctx->next_check) { + if (scalar_bit(scalar, i) == scalar_bit(scalar, i - 1)) { + ctx->next_check--; + } else { + // compute digit of next window + int w = MIN(width, i + 1); + int v = -(scalar_bit(scalar, i) << (w-1)); + FOR_T (int, j, 0, w-1) { + v += scalar_bit(scalar, i-(w-1)+j) << j; + } + v += scalar_bit(scalar, i-w); + int lsb = v & (~v + 1); // smallest bit of v + int s = // log2(lsb) + (((lsb & 0xAA) != 0) << 0) | + (((lsb & 0xCC) != 0) << 1) | + (((lsb & 0xF0) != 0) << 2); + ctx->next_index = (i16)(i-(w-1)+s); + ctx->next_digit = (i8) (v >> s ); + ctx->next_check -= (u8) w; + } + } + return i == ctx->next_index ? ctx->next_digit: 0; +} + +#define P_W_WIDTH 3 // Affects the size of the stack +#define B_W_WIDTH 5 // Affects the size of the binary +#define P_W_SIZE (1<<(P_W_WIDTH-2)) + +int crypto_eddsa_check_equation(const u8 signature[64], const u8 public_key[32], + const u8 h[32]) +{ + ge minus_A; // -public_key + ge minus_R; // -first_half_of_signature + const u8 *s = signature + 32; + + // Check that A and R are on the curve + // Check that 0 <= S < L (prevents malleability) + // *Allow* non-cannonical encoding for A and R + { + u32 s32[8]; + load32_le_buf(s32, s, 8); + if (ge_frombytes_neg_vartime(&minus_A, public_key) || + ge_frombytes_neg_vartime(&minus_R, signature) || + is_above_l(s32)) { + return -1; + } + } + + // look-up table for minus_A + ge_cached lutA[P_W_SIZE]; + { + ge minus_A2, tmp; + ge_double(&minus_A2, &minus_A, &tmp); + ge_cache(&lutA[0], &minus_A); + FOR (i, 1, P_W_SIZE) { + ge_add(&tmp, &minus_A2, &lutA[i-1]); + ge_cache(&lutA[i], &tmp); + } + } + + // sum = [s]B - [h]A + // Merged double and add ladder, fused with sliding + slide_ctx h_slide; slide_init(&h_slide, h); + slide_ctx s_slide; slide_init(&s_slide, s); + int i = MAX(h_slide.next_check, s_slide.next_check); + ge *sum = &minus_A; // reuse minus_A for the sum + ge_zero(sum); + while (i >= 0) { + ge tmp; + ge_double(sum, sum, &tmp); + int h_digit = slide_step(&h_slide, P_W_WIDTH, i, h); + int s_digit = slide_step(&s_slide, B_W_WIDTH, i, s); + if (h_digit > 0) { ge_add(sum, sum, &lutA[ h_digit / 2]); } + if (h_digit < 0) { ge_sub(sum, sum, &lutA[-h_digit / 2]); } + fe t1, t2; + if (s_digit > 0) { ge_madd(sum, sum, b_window + s_digit/2, t1, t2); } + if (s_digit < 0) { ge_msub(sum, sum, b_window + -s_digit/2, t1, t2); } + i--; + } + + // Compare [8](sum-R) and the zero point + // The multiplication by 8 eliminates any low-order component + // and ensures consistency with batched verification. + ge_cached cached; + u8 check[32]; + static const u8 zero_point[32] = {1}; // Point of order 1 + ge_cache(&cached, &minus_R); + ge_add(sum, sum, &cached); + ge_double(sum, sum, &minus_R); // reuse minus_R as temporary + ge_double(sum, sum, &minus_R); // reuse minus_R as temporary + ge_double(sum, sum, &minus_R); // reuse minus_R as temporary + ge_tobytes(check, sum); + return crypto_verify32(check, zero_point); +} + +// 5-bit signed comb in cached format (Niels coordinates, Z=1) +static const ge_precomp b_comb_low[8] = { + {{-6816601,-2324159,-22559413,124364,18015490, + 8373481,19993724,1979872,-18549925,9085059,}, + {10306321,403248,14839893,9633706,8463310, + -8354981,-14305673,14668847,26301366,2818560,}, + {-22701500,-3210264,-13831292,-2927732,-16326337, + -14016360,12940910,177905,12165515,-2397893,},}, + {{-12282262,-7022066,9920413,-3064358,-32147467, + 2927790,22392436,-14852487,2719975,16402117,}, + {-7236961,-4729776,2685954,-6525055,-24242706, + -15940211,-6238521,14082855,10047669,12228189,}, + {-30495588,-12893761,-11161261,3539405,-11502464, + 16491580,-27286798,-15030530,-7272871,-15934455,},}, + {{17650926,582297,-860412,-187745,-12072900, + -10683391,-20352381,15557840,-31072141,-5019061,}, + {-6283632,-2259834,-4674247,-4598977,-4089240, + 12435688,-31278303,1060251,6256175,10480726,}, + {-13871026,2026300,-21928428,-2741605,-2406664, + -8034988,7355518,15733500,-23379862,7489131,},}, + {{6883359,695140,23196907,9644202,-33430614, + 11354760,-20134606,6388313,-8263585,-8491918,}, + {-7716174,-13605463,-13646110,14757414,-19430591, + -14967316,10359532,-11059670,-21935259,12082603,}, + {-11253345,-15943946,10046784,5414629,24840771, + 8086951,-6694742,9868723,15842692,-16224787,},}, + {{9639399,11810955,-24007778,-9320054,3912937, + -9856959,996125,-8727907,-8919186,-14097242,}, + {7248867,14468564,25228636,-8795035,14346339, + 8224790,6388427,-7181107,6468218,-8720783,}, + {15513115,15439095,7342322,-10157390,18005294, + -7265713,2186239,4884640,10826567,7135781,},}, + {{-14204238,5297536,-5862318,-6004934,28095835, + 4236101,-14203318,1958636,-16816875,3837147,}, + {-5511166,-13176782,-29588215,12339465,15325758, + -15945770,-8813185,11075932,-19608050,-3776283,}, + {11728032,9603156,-4637821,-5304487,-7827751, + 2724948,31236191,-16760175,-7268616,14799772,},}, + {{-28842672,4840636,-12047946,-9101456,-1445464, + 381905,-30977094,-16523389,1290540,12798615,}, + {27246947,-10320914,14792098,-14518944,5302070, + -8746152,-3403974,-4149637,-27061213,10749585,}, + {25572375,-6270368,-15353037,16037944,1146292, + 32198,23487090,9585613,24714571,-1418265,},}, + {{19844825,282124,-17583147,11004019,-32004269, + -2716035,6105106,-1711007,-21010044,14338445,}, + {8027505,8191102,-18504907,-12335737,25173494, + -5923905,15446145,7483684,-30440441,10009108,}, + {-14134701,-4174411,10246585,-14677495,33553567, + -14012935,23366126,15080531,-7969992,7663473,},}, +}; + +static const ge_precomp b_comb_high[8] = { + {{33055887,-4431773,-521787,6654165,951411, + -6266464,-5158124,6995613,-5397442,-6985227,}, + {4014062,6967095,-11977872,3960002,8001989, + 5130302,-2154812,-1899602,-31954493,-16173976,}, + {16271757,-9212948,23792794,731486,-25808309, + -3546396,6964344,-4767590,10976593,10050757,},}, + {{2533007,-4288439,-24467768,-12387405,-13450051, + 14542280,12876301,13893535,15067764,8594792,}, + {20073501,-11623621,3165391,-13119866,13188608, + -11540496,-10751437,-13482671,29588810,2197295,}, + {-1084082,11831693,6031797,14062724,14748428, + -8159962,-20721760,11742548,31368706,13161200,},}, + {{2050412,-6457589,15321215,5273360,25484180, + 124590,-18187548,-7097255,-6691621,-14604792,}, + {9938196,2162889,-6158074,-1711248,4278932, + -2598531,-22865792,-7168500,-24323168,11746309,}, + {-22691768,-14268164,5965485,9383325,20443693, + 5854192,28250679,-1381811,-10837134,13717818,},}, + {{-8495530,16382250,9548884,-4971523,-4491811, + -3902147,6182256,-12832479,26628081,10395408,}, + {27329048,-15853735,7715764,8717446,-9215518, + -14633480,28982250,-5668414,4227628,242148,}, + {-13279943,-7986904,-7100016,8764468,-27276630, + 3096719,29678419,-9141299,3906709,11265498,},}, + {{11918285,15686328,-17757323,-11217300,-27548967, + 4853165,-27168827,6807359,6871949,-1075745,}, + {-29002610,13984323,-27111812,-2713442,28107359, + -13266203,6155126,15104658,3538727,-7513788,}, + {14103158,11233913,-33165269,9279850,31014152, + 4335090,-1827936,4590951,13960841,12787712,},}, + {{1469134,-16738009,33411928,13942824,8092558, + -8778224,-11165065,1437842,22521552,-2792954,}, + {31352705,-4807352,-25327300,3962447,12541566, + -9399651,-27425693,7964818,-23829869,5541287,}, + {-25732021,-6864887,23848984,3039395,-9147354, + 6022816,-27421653,10590137,25309915,-1584678,},}, + {{-22951376,5048948,31139401,-190316,-19542447, + -626310,-17486305,-16511925,-18851313,-12985140,}, + {-9684890,14681754,30487568,7717771,-10829709, + 9630497,30290549,-10531496,-27798994,-13812825,}, + {5827835,16097107,-24501327,12094619,7413972, + 11447087,28057551,-1793987,-14056981,4359312,},}, + {{26323183,2342588,-21887793,-1623758,-6062284, + 2107090,-28724907,9036464,-19618351,-13055189,}, + {-29697200,14829398,-4596333,14220089,-30022969, + 2955645,12094100,-13693652,-5941445,7047569,}, + {-3201977,14413268,-12058324,-16417589,-9035655, + -7224648,9258160,1399236,30397584,-5684634,},}, +}; + +static void lookup_add(ge *p, ge_precomp *tmp_c, fe tmp_a, fe tmp_b, + const ge_precomp comb[8], const u8 scalar[32], int i) +{ + u8 teeth = (u8)((scalar_bit(scalar, i) ) + + (scalar_bit(scalar, i + 32) << 1) + + (scalar_bit(scalar, i + 64) << 2) + + (scalar_bit(scalar, i + 96) << 3)); + u8 high = teeth >> 3; + u8 index = (teeth ^ (high - 1)) & 7; + FOR (j, 0, 8) { + i32 select = 1 & (((j ^ index) - 1) >> 8); + fe_ccopy(tmp_c->Yp, comb[j].Yp, select); + fe_ccopy(tmp_c->Ym, comb[j].Ym, select); + fe_ccopy(tmp_c->T2, comb[j].T2, select); + } + fe_neg(tmp_a, tmp_c->T2); + fe_cswap(tmp_c->T2, tmp_a , high ^ 1); + fe_cswap(tmp_c->Yp, tmp_c->Ym, high ^ 1); + ge_madd(p, p, tmp_c, tmp_a, tmp_b); +} + +// p = [scalar]B, where B is the base point +static void ge_scalarmult_base(ge *p, const u8 scalar[32]) +{ + // twin 4-bits signed combs, from Mike Hamburg's + // Fast and compact elliptic-curve cryptography (2012) + // 1 / 2 modulo L + static const u8 half_mod_L[32] = { + 247,233,122,46,141,49,9,44,107,206,123,81,239,124,111,10, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8, + }; + // (2^256 - 1) / 2 modulo L + static const u8 half_ones[32] = { + 142,74,204,70,186,24,118,107,184,231,190,57,250,173,119,99, + 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,7, + }; + + // All bits set form: 1 means 1, 0 means -1 + u8 s_scalar[32]; + crypto_eddsa_mul_add(s_scalar, scalar, half_mod_L, half_ones); + + // Double and add ladder + fe tmp_a, tmp_b; // temporaries for addition + ge_precomp tmp_c; // temporary for comb lookup + ge tmp_d; // temporary for doubling + fe_1(tmp_c.Yp); + fe_1(tmp_c.Ym); + fe_0(tmp_c.T2); + + // Save a double on the first iteration + ge_zero(p); + lookup_add(p, &tmp_c, tmp_a, tmp_b, b_comb_low , s_scalar, 31); + lookup_add(p, &tmp_c, tmp_a, tmp_b, b_comb_high, s_scalar, 31+128); + // Regular double & add for the rest + for (int i = 30; i >= 0; i--) { + ge_double(p, p, &tmp_d); + lookup_add(p, &tmp_c, tmp_a, tmp_b, b_comb_low , s_scalar, i); + lookup_add(p, &tmp_c, tmp_a, tmp_b, b_comb_high, s_scalar, i+128); + } + // Note: we could save one addition at the end if we assumed the + // scalar fit in 252 bits. Which it does in practice if it is + // selected at random. However, non-random, non-hashed scalars + // *can* overflow 252 bits in practice. Better account for that + // than leaving that kind of subtle corner case. + + WIPE_BUFFER(tmp_a); WIPE_CTX(&tmp_d); + WIPE_BUFFER(tmp_b); WIPE_CTX(&tmp_c); + WIPE_BUFFER(s_scalar); +} + +void crypto_eddsa_scalarbase(u8 point[32], const u8 scalar[32]) +{ + ge P; + ge_scalarmult_base(&P, scalar); + ge_tobytes(point, &P); + WIPE_CTX(&P); +} + +void crypto_eddsa_key_pair(u8 secret_key[64], u8 public_key[32], u8 seed[32]) +{ + // To allow overlaps, observable writes happen in this order: + // 1. seed + // 2. secret_key + // 3. public_key + u8 a[64]; + COPY(a, seed, 32); + crypto_wipe(seed, 32); + COPY(secret_key, a, 32); + crypto_blake2b(a, 64, a, 32); + crypto_eddsa_trim_scalar(a, a); + crypto_eddsa_scalarbase(secret_key + 32, a); + COPY(public_key, secret_key + 32, 32); + WIPE_BUFFER(a); +} + +static void hash_reduce(u8 h[32], + const u8 *a, size_t a_size, + const u8 *b, size_t b_size, + const u8 *c, size_t c_size) +{ + u8 hash[64]; + crypto_blake2b_ctx ctx; + crypto_blake2b_init (&ctx, 64); + crypto_blake2b_update(&ctx, a, a_size); + crypto_blake2b_update(&ctx, b, b_size); + crypto_blake2b_update(&ctx, c, c_size); + crypto_blake2b_final (&ctx, hash); + crypto_eddsa_reduce(h, hash); +} + +// Digital signature of a message with from a secret key. +// +// The secret key comprises two parts: +// - The seed that generates the key (secret_key[ 0..31]) +// - The public key (secret_key[32..63]) +// +// The seed and the public key are bundled together to make sure users +// don't use mismatched seeds and public keys, which would instantly +// leak the secret scalar and allow forgeries (allowing this to happen +// has resulted in critical vulnerabilities in the wild). +// +// The seed is hashed to derive the secret scalar and a secret prefix. +// The sole purpose of the prefix is to generate a secret random nonce. +// The properties of that nonce must be as follows: +// - Unique: we need a different one for each message. +// - Secret: third parties must not be able to predict it. +// - Random: any detectable bias would break all security. +// +// There are two ways to achieve these properties. The obvious one is +// to simply generate a random number. Here that would be a parameter +// (Monocypher doesn't have an RNG). It works, but then users may reuse +// the nonce by accident, which _also_ leaks the secret scalar and +// allows forgeries. This has happened in the wild too. +// +// This is no good, so instead we generate that nonce deterministically +// by reducing modulo L a hash of the secret prefix and the message. +// The secret prefix makes the nonce unpredictable, the message makes it +// unique, and the hash/reduce removes all bias. +// +// The cost of that safety is hashing the message twice. If that cost +// is unacceptable, there are two alternatives: +// +// - Signing a hash of the message instead of the message itself. This +// is fine as long as the hash is collision resistant. It is not +// compatible with existing "pure" signatures, but at least it's safe. +// +// - Using a random nonce. Please exercise **EXTREME CAUTION** if you +// ever do that. It is absolutely **critical** that the nonce is +// really an unbiased random number between 0 and L-1, never reused, +// and wiped immediately. +// +// To lower the likelihood of complete catastrophe if the RNG is +// either flawed or misused, you can hash the RNG output together with +// the secret prefix and the beginning of the message, and use the +// reduction of that hash instead of the RNG output itself. It's not +// foolproof (you'd need to hash the whole message) but it helps. +// +// Signing a message involves the following operations: +// +// scalar, prefix = HASH(secret_key) +// r = HASH(prefix || message) % L +// R = [r]B +// h = HASH(R || public_key || message) % L +// S = ((h * a) + r) % L +// signature = R || S +void crypto_eddsa_sign(u8 signature [64], const u8 secret_key[64], + const u8 *message, size_t message_size) +{ + u8 a[64]; // secret scalar and prefix + u8 r[32]; // secret deterministic "random" nonce + u8 h[32]; // publically verifiable hash of the message (not wiped) + u8 R[32]; // first half of the signature (allows overlapping inputs) + + crypto_blake2b(a, 64, secret_key, 32); + crypto_eddsa_trim_scalar(a, a); + hash_reduce(r, a + 32, 32, message, message_size, 0, 0); + crypto_eddsa_scalarbase(R, r); + hash_reduce(h, R, 32, secret_key + 32, 32, message, message_size); + COPY(signature, R, 32); + crypto_eddsa_mul_add(signature + 32, h, a, r); + + WIPE_BUFFER(a); + WIPE_BUFFER(r); +} + +// To check the signature R, S of the message M with the public key A, +// there are 3 steps: +// +// compute h = HASH(R || A || message) % L +// check that A is on the curve. +// check that R == [s]B - [h]A +// +// The last two steps are done in crypto_eddsa_check_equation() +int crypto_eddsa_check(const u8 signature[64], const u8 public_key[32], + const u8 *message, size_t message_size) +{ + u8 h[32]; + hash_reduce(h, signature, 32, public_key, 32, message, message_size); + return crypto_eddsa_check_equation(signature, public_key, h); +} + +///////////////////////// +/// EdDSA <--> X25519 /// +///////////////////////// +void crypto_eddsa_to_x25519(u8 x25519[32], const u8 eddsa[32]) +{ + // (u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x) + // Only converting y to u, the sign of x is ignored. + fe t1, t2; + fe_frombytes(t2, eddsa); + fe_add(t1, fe_one, t2); + fe_sub(t2, fe_one, t2); + fe_invert(t2, t2); + fe_mul(t1, t1, t2); + fe_tobytes(x25519, t1); + WIPE_BUFFER(t1); + WIPE_BUFFER(t2); +} + +void crypto_x25519_to_eddsa(u8 eddsa[32], const u8 x25519[32]) +{ + // (x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1)) + // Only converting u to y, x is assumed positive. + fe t1, t2; + fe_frombytes(t2, x25519); + fe_sub(t1, t2, fe_one); + fe_add(t2, t2, fe_one); + fe_invert(t2, t2); + fe_mul(t1, t1, t2); + fe_tobytes(eddsa, t1); + WIPE_BUFFER(t1); + WIPE_BUFFER(t2); +} + +///////////////////////////////////////////// +/// Dirty ephemeral public key generation /// +///////////////////////////////////////////// + +// Those functions generates a public key, *without* clearing the +// cofactor. Sending that key over the network leaks 3 bits of the +// private key. Use only to generate ephemeral keys that will be hidden +// with crypto_curve_to_hidden(). +// +// The public key is otherwise compatible with crypto_x25519(), which +// properly clears the cofactor. +// +// Note that the distribution of the resulting public keys is almost +// uniform. Flipping the sign of the v coordinate (not provided by this +// function), covers the entire key space almost perfectly, where +// "almost" means a 2^-128 bias (undetectable). This uniformity is +// needed to ensure the proper randomness of the resulting +// representatives (once we apply crypto_curve_to_hidden()). +// +// Recall that Curve25519 has order C = 2^255 + e, with e < 2^128 (not +// to be confused with the prime order of the main subgroup, L, which is +// 8 times less than that). +// +// Generating all points would require us to multiply a point of order C +// (the base point plus any point of order 8) by all scalars from 0 to +// C-1. Clamping limits us to scalars between 2^254 and 2^255 - 1. But +// by negating the resulting point at random, we also cover scalars from +// -2^255 + 1 to -2^254 (which modulo C is congruent to e+1 to 2^254 + e). +// +// In practice: +// - Scalars from 0 to e + 1 are never generated +// - Scalars from 2^255 to 2^255 + e are never generated +// - Scalars from 2^254 + 1 to 2^254 + e are generated twice +// +// Since e < 2^128, detecting this bias requires observing over 2^100 +// representatives from a given source (this will never happen), *and* +// recovering enough of the private key to determine that they do, or do +// not, belong to the biased set (this practically requires solving +// discrete logarithm, which is conjecturally intractable). +// +// In practice, this means the bias is impossible to detect. + +// s + (x*L) % 8*L +// Guaranteed to fit in 256 bits iff s fits in 255 bits. +// L < 2^253 +// x%8 < 2^3 +// L * (x%8) < 2^255 +// s < 2^255 +// s + L * (x%8) < 2^256 +static void add_xl(u8 s[32], u8 x) +{ + u64 mod8 = x & 7; + u64 carry = 0; + FOR (i , 0, 8) { + carry = carry + load32_le(s + 4*i) + L[i] * mod8; + store32_le(s + 4*i, (u32)carry); + carry >>= 32; + } +} + +// "Small" dirty ephemeral key. +// Use if you need to shrink the size of the binary, and can afford to +// slow down by a factor of two (compared to the fast version) +// +// This version works by decoupling the cofactor from the main factor. +// +// - The trimmed scalar determines the main factor +// - The clamped bits of the scalar determine the cofactor. +// +// Cofactor and main factor are combined into a single scalar, which is +// then multiplied by a point of order 8*L (unlike the base point, which +// has prime order). That "dirty" base point is the addition of the +// regular base point (9), and a point of order 8. +void crypto_x25519_dirty_small(u8 public_key[32], const u8 secret_key[32]) +{ + // Base point of order 8*L + // Raw scalar multiplication with it does not clear the cofactor, + // and the resulting public key will reveal 3 bits of the scalar. + // + // The low order component of this base point has been chosen + // to yield the same results as crypto_x25519_dirty_fast(). + static const u8 dirty_base_point[32] = { + 0xd8, 0x86, 0x1a, 0xa2, 0x78, 0x7a, 0xd9, 0x26, + 0x8b, 0x74, 0x74, 0xb6, 0x82, 0xe3, 0xbe, 0xc3, + 0xce, 0x36, 0x9a, 0x1e, 0x5e, 0x31, 0x47, 0xa2, + 0x6d, 0x37, 0x7c, 0xfd, 0x20, 0xb5, 0xdf, 0x75, + }; + // separate the main factor & the cofactor of the scalar + u8 scalar[32]; + crypto_eddsa_trim_scalar(scalar, secret_key); + + // Separate the main factor and the cofactor + // + // The scalar is trimmed, so its cofactor is cleared. The three + // least significant bits however still have a main factor. We must + // remove it for X25519 compatibility. + // + // cofactor = lsb * L (modulo 8*L) + // combined = scalar + cofactor (modulo 8*L) + add_xl(scalar, secret_key[0]); + scalarmult(public_key, scalar, dirty_base_point, 256); + WIPE_BUFFER(scalar); +} + +// Select low order point +// We're computing the [cofactor]lop scalar multiplication, where: +// +// cofactor = tweak & 7. +// lop = (lop_x, lop_y) +// lop_x = sqrt((sqrt(d + 1) + 1) / d) +// lop_y = -lop_x * sqrtm1 +// +// The low order point has order 8. There are 4 such points. We've +// chosen the one whose both coordinates are positive (below p/2). +// The 8 low order points are as follows: +// +// [0]lop = ( 0 , 1 ) +// [1]lop = ( lop_x , lop_y) +// [2]lop = ( sqrt(-1), -0 ) +// [3]lop = ( lop_x , -lop_y) +// [4]lop = (-0 , -1 ) +// [5]lop = (-lop_x , -lop_y) +// [6]lop = (-sqrt(-1), 0 ) +// [7]lop = (-lop_x , lop_y) +// +// The x coordinate is either 0, sqrt(-1), lop_x, or their opposite. +// The y coordinate is either 0, -1 , lop_y, or their opposite. +// The pattern for both is the same, except for a rotation of 2 (modulo 8) +// +// This helper function captures the pattern, and we can use it thus: +// +// select_lop(x, lop_x, sqrtm1, cofactor); +// select_lop(y, lop_y, fe_one, cofactor + 2); +// +// This is faster than an actual scalar multiplication, +// and requires less code than naive constant time look up. +static void select_lop(fe out, const fe x, const fe k, u8 cofactor) +{ + fe tmp; + fe_0(out); + fe_ccopy(out, k , (cofactor >> 1) & 1); // bit 1 + fe_ccopy(out, x , (cofactor >> 0) & 1); // bit 0 + fe_neg (tmp, out); + fe_ccopy(out, tmp, (cofactor >> 2) & 1); // bit 2 + WIPE_BUFFER(tmp); +} + +// "Fast" dirty ephemeral key +// We use this one by default. +// +// This version works by performing a regular scalar multiplication, +// then add a low order point. The scalar multiplication is done in +// Edwards space for more speed (*2 compared to the "small" version). +// The cost is a bigger binary for programs that don't also sign messages. +void crypto_x25519_dirty_fast(u8 public_key[32], const u8 secret_key[32]) +{ + // Compute clean scalar multiplication + u8 scalar[32]; + ge pk; + crypto_eddsa_trim_scalar(scalar, secret_key); + ge_scalarmult_base(&pk, scalar); + + // Compute low order point + fe t1, t2; + select_lop(t1, lop_x, sqrtm1, secret_key[0]); + select_lop(t2, lop_y, fe_one, secret_key[0] + 2); + ge_precomp low_order_point; + fe_add(low_order_point.Yp, t2, t1); + fe_sub(low_order_point.Ym, t2, t1); + fe_mul(low_order_point.T2, t2, t1); + fe_mul(low_order_point.T2, low_order_point.T2, D2); + + // Add low order point to the public key + ge_madd(&pk, &pk, &low_order_point, t1, t2); + + // Convert to Montgomery u coordinate (we ignore the sign) + fe_add(t1, pk.Z, pk.Y); + fe_sub(t2, pk.Z, pk.Y); + fe_invert(t2, t2); + fe_mul(t1, t1, t2); + + fe_tobytes(public_key, t1); + + WIPE_BUFFER(t1); WIPE_CTX(&pk); + WIPE_BUFFER(t2); WIPE_CTX(&low_order_point); + WIPE_BUFFER(scalar); +} + +/////////////////// +/// Elligator 2 /// +/////////////////// +static const fe A = {486662}; + +// Elligator direct map +// +// Computes the point corresponding to a representative, encoded in 32 +// bytes (little Endian). Since positive representatives fits in 254 +// bits, The two most significant bits are ignored. +// +// From the paper: +// w = -A / (fe(1) + non_square * r^2) +// e = chi(w^3 + A*w^2 + w) +// u = e*w - (fe(1)-e)*(A//2) +// v = -e * sqrt(u^3 + A*u^2 + u) +// +// We ignore v because we don't need it for X25519 (the Montgomery +// ladder only uses u). +// +// Note that e is either 0, 1 or -1 +// if e = 0 u = 0 and v = 0 +// if e = 1 u = w +// if e = -1 u = -w - A = w * non_square * r^2 +// +// Let r1 = non_square * r^2 +// Let r2 = 1 + r1 +// Note that r2 cannot be zero, -1/non_square is not a square. +// We can (tediously) verify that: +// w^3 + A*w^2 + w = (A^2*r1 - r2^2) * A / r2^3 +// Therefore: +// chi(w^3 + A*w^2 + w) = chi((A^2*r1 - r2^2) * (A / r2^3)) +// chi(w^3 + A*w^2 + w) = chi((A^2*r1 - r2^2) * (A / r2^3)) * 1 +// chi(w^3 + A*w^2 + w) = chi((A^2*r1 - r2^2) * (A / r2^3)) * chi(r2^6) +// chi(w^3 + A*w^2 + w) = chi((A^2*r1 - r2^2) * (A / r2^3) * r2^6) +// chi(w^3 + A*w^2 + w) = chi((A^2*r1 - r2^2) * A * r2^3) +// Corollary: +// e = 1 if (A^2*r1 - r2^2) * A * r2^3) is a non-zero square +// e = -1 if (A^2*r1 - r2^2) * A * r2^3) is not a square +// Note that w^3 + A*w^2 + w (and therefore e) can never be zero: +// w^3 + A*w^2 + w = w * (w^2 + A*w + 1) +// w^3 + A*w^2 + w = w * (w^2 + A*w + A^2/4 - A^2/4 + 1) +// w^3 + A*w^2 + w = w * (w + A/2)^2 - A^2/4 + 1) +// which is zero only if: +// w = 0 (impossible) +// (w + A/2)^2 = A^2/4 - 1 (impossible, because A^2/4-1 is not a square) +// +// Let isr = invsqrt((A^2*r1 - r2^2) * A * r2^3) +// isr = sqrt(1 / ((A^2*r1 - r2^2) * A * r2^3)) if e = 1 +// isr = sqrt(sqrt(-1) / ((A^2*r1 - r2^2) * A * r2^3)) if e = -1 +// +// if e = 1 +// let u1 = -A * (A^2*r1 - r2^2) * A * r2^2 * isr^2 +// u1 = w +// u1 = u +// +// if e = -1 +// let ufactor = -non_square * sqrt(-1) * r^2 +// let vfactor = sqrt(ufactor) +// let u2 = -A * (A^2*r1 - r2^2) * A * r2^2 * isr^2 * ufactor +// u2 = w * -1 * -non_square * r^2 +// u2 = w * non_square * r^2 +// u2 = u +void crypto_elligator_map(u8 curve[32], const u8 hidden[32]) +{ + fe r, u, t1, t2, t3; + fe_frombytes_mask(r, hidden, 2); // r is encoded in 254 bits. + fe_sq(r, r); + fe_add(t1, r, r); + fe_add(u, t1, fe_one); + fe_sq (t2, u); + fe_mul(t3, A2, t1); + fe_sub(t3, t3, t2); + fe_mul(t3, t3, A); + fe_mul(t1, t2, u); + fe_mul(t1, t3, t1); + int is_square = invsqrt(t1, t1); + fe_mul(u, r, ufactor); + fe_ccopy(u, fe_one, is_square); + fe_sq (t1, t1); + fe_mul(u, u, A); + fe_mul(u, u, t3); + fe_mul(u, u, t2); + fe_mul(u, u, t1); + fe_neg(u, u); + fe_tobytes(curve, u); + + WIPE_BUFFER(t1); WIPE_BUFFER(r); + WIPE_BUFFER(t2); WIPE_BUFFER(u); + WIPE_BUFFER(t3); +} + +// Elligator inverse map +// +// Computes the representative of a point, if possible. If not, it does +// nothing and returns -1. Note that the success of the operation +// depends only on the point (more precisely its u coordinate). The +// tweak parameter is used only upon success +// +// The tweak should be a random byte. Beyond that, its contents are an +// implementation detail. Currently, the tweak comprises: +// - Bit 1 : sign of the v coordinate (0 if positive, 1 if negative) +// - Bit 2-5: not used +// - Bits 6-7: random padding +// +// From the paper: +// Let sq = -non_square * u * (u+A) +// if sq is not a square, or u = -A, there is no mapping +// Assuming there is a mapping: +// if v is positive: r = sqrt(-u / (non_square * (u+A))) +// if v is negative: r = sqrt(-(u+A) / (non_square * u )) +// +// We compute isr = invsqrt(-non_square * u * (u+A)) +// if it wasn't a square, abort. +// else, isr = sqrt(-1 / (non_square * u * (u+A)) +// +// If v is positive, we return isr * u: +// isr * u = sqrt(-1 / (non_square * u * (u+A)) * u +// isr * u = sqrt(-u / (non_square * (u+A)) +// +// If v is negative, we return isr * (u+A): +// isr * (u+A) = sqrt(-1 / (non_square * u * (u+A)) * (u+A) +// isr * (u+A) = sqrt(-(u+A) / (non_square * u) +int crypto_elligator_rev(u8 hidden[32], const u8 public_key[32], u8 tweak) +{ + fe t1, t2, t3; + fe_frombytes(t1, public_key); // t1 = u + + fe_add(t2, t1, A); // t2 = u + A + fe_mul(t3, t1, t2); + fe_mul_small(t3, t3, -2); + int is_square = invsqrt(t3, t3); // t3 = sqrt(-1 / non_square * u * (u+A)) + if (is_square) { + // The only variable time bit. This ultimately reveals how many + // tries it took us to find a representable key. + // This does not affect security as long as we try keys at random. + + fe_ccopy (t1, t2, tweak & 1); // multiply by u if v is positive, + fe_mul (t3, t1, t3); // multiply by u+A otherwise + fe_mul_small(t1, t3, 2); + fe_neg (t2, t3); + fe_ccopy (t3, t2, fe_isodd(t1)); + fe_tobytes(hidden, t3); + + // Pad with two random bits + hidden[31] |= tweak & 0xc0; + } + + WIPE_BUFFER(t1); + WIPE_BUFFER(t2); + WIPE_BUFFER(t3); + return is_square - 1; +} + +void crypto_elligator_key_pair(u8 hidden[32], u8 secret_key[32], u8 seed[32]) +{ + u8 pk [32]; // public key + u8 buf[64]; // seed + representative + COPY(buf + 32, seed, 32); + do { + crypto_chacha20_djb(buf, 0, 64, buf+32, zero, 0); + crypto_x25519_dirty_fast(pk, buf); // or the "small" version + } while(crypto_elligator_rev(buf+32, pk, buf[32])); + // Note that the return value of crypto_elligator_rev() is + // independent from its tweak parameter. + // Therefore, buf[32] is not actually reused. Either we loop one + // more time and buf[32] is used for the new seed, or we succeeded, + // and buf[32] becomes the tweak parameter. + + crypto_wipe(seed, 32); + COPY(hidden , buf + 32, 32); + COPY(secret_key, buf , 32); + WIPE_BUFFER(buf); + WIPE_BUFFER(pk); +} + +/////////////////////// +/// Scalar division /// +/////////////////////// + +// Montgomery reduction. +// Divides x by (2^256), and reduces the result modulo L +// +// Precondition: +// x < L * 2^256 +// Constants: +// r = 2^256 (makes division by r trivial) +// k = (r * (1/r) - 1) // L (1/r is computed modulo L ) +// Algorithm: +// s = (x * k) % r +// t = x + s*L (t is always a multiple of r) +// u = (t/r) % L (u is always below 2*L, conditional subtraction is enough) +static void redc(u32 u[8], u32 x[16]) +{ + static const u32 k[8] = { + 0x12547e1b, 0xd2b51da3, 0xfdba84ff, 0xb1a206f2, + 0xffa36bea, 0x14e75438, 0x6fe91836, 0x9db6c6f2, + }; + + // s = x * k (modulo 2^256) + // This is cheaper than the full multiplication. + u32 s[8] = {0}; + FOR (i, 0, 8) { + u64 carry = 0; + FOR (j, 0, 8-i) { + carry += s[i+j] + (u64)x[i] * k[j]; + s[i+j] = (u32)carry; + carry >>= 32; + } + } + u32 t[16] = {0}; + multiply(t, s, L); + + // t = t + x + u64 carry = 0; + FOR (i, 0, 16) { + carry += (u64)t[i] + x[i]; + t[i] = (u32)carry; + carry >>= 32; + } + + // u = (t / 2^256) % L + // Note that t / 2^256 is always below 2*L, + // So a constant time conditional subtraction is enough + remove_l(u, t+8); + + WIPE_BUFFER(s); + WIPE_BUFFER(t); +} + +void crypto_x25519_inverse(u8 blind_salt [32], const u8 private_key[32], + const u8 curve_point[32]) +{ + static const u8 Lm2[32] = { // L - 2 + 0xeb, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, + 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, + }; + // 1 in Montgomery form + u32 m_inv [8] = { + 0x8d98951d, 0xd6ec3174, 0x737dcf70, 0xc6ef5bf4, + 0xfffffffe, 0xffffffff, 0xffffffff, 0x0fffffff, + }; + + u8 scalar[32]; + crypto_eddsa_trim_scalar(scalar, private_key); + + // Convert the scalar in Montgomery form + // m_scl = scalar * 2^256 (modulo L) + u32 m_scl[8]; + { + u32 tmp[16]; + ZERO(tmp, 8); + load32_le_buf(tmp+8, scalar, 8); + mod_l(scalar, tmp); + load32_le_buf(m_scl, scalar, 8); + WIPE_BUFFER(tmp); // Wipe ASAP to save stack space + } + + // Compute the inverse + u32 product[16]; + for (int i = 252; i >= 0; i--) { + ZERO(product, 16); + multiply(product, m_inv, m_inv); + redc(m_inv, product); + if (scalar_bit(Lm2, i)) { + ZERO(product, 16); + multiply(product, m_inv, m_scl); + redc(m_inv, product); + } + } + // Convert the inverse *out* of Montgomery form + // scalar = m_inv / 2^256 (modulo L) + COPY(product, m_inv, 8); + ZERO(product + 8, 8); + redc(m_inv, product); + store32_le_buf(scalar, m_inv, 8); // the *inverse* of the scalar + + // Clear the cofactor of scalar: + // cleared = scalar * (3*L + 1) (modulo 8*L) + // cleared = scalar + scalar * 3 * L (modulo 8*L) + // Note that (scalar * 3) is reduced modulo 8, so we only need the + // first byte. + add_xl(scalar, scalar[0] * 3); + + // Recall that 8*L < 2^256. However it is also very close to + // 2^255. If we spanned the ladder over 255 bits, random tests + // wouldn't catch the off-by-one error. + scalarmult(blind_salt, scalar, curve_point, 256); + + WIPE_BUFFER(scalar); WIPE_BUFFER(m_scl); + WIPE_BUFFER(product); WIPE_BUFFER(m_inv); +} + +//////////////////////////////// +/// Authenticated encryption /// +//////////////////////////////// +static void lock_auth(u8 mac[16], const u8 auth_key[32], + const u8 *ad , size_t ad_size, + const u8 *cipher_text, size_t text_size) +{ + u8 sizes[16]; // Not secret, not wiped + store64_le(sizes + 0, ad_size); + store64_le(sizes + 8, text_size); + crypto_poly1305_ctx poly_ctx; // auto wiped... + crypto_poly1305_init (&poly_ctx, auth_key); + crypto_poly1305_update(&poly_ctx, ad , ad_size); + crypto_poly1305_update(&poly_ctx, zero , gap(ad_size, 16)); + crypto_poly1305_update(&poly_ctx, cipher_text, text_size); + crypto_poly1305_update(&poly_ctx, zero , gap(text_size, 16)); + crypto_poly1305_update(&poly_ctx, sizes , 16); + crypto_poly1305_final (&poly_ctx, mac); // ...here +} + +void crypto_aead_init_x(crypto_aead_ctx *ctx, + u8 const key[32], const u8 nonce[24]) +{ + crypto_chacha20_h(ctx->key, key, nonce); + COPY(ctx->nonce, nonce + 16, 8); + ctx->counter = 0; +} + +void crypto_aead_init_djb(crypto_aead_ctx *ctx, + const u8 key[32], const u8 nonce[8]) +{ + COPY(ctx->key , key , 32); + COPY(ctx->nonce, nonce, 8); + ctx->counter = 0; +} + +void crypto_aead_init_ietf(crypto_aead_ctx *ctx, + const u8 key[32], const u8 nonce[12]) +{ + COPY(ctx->key , key , 32); + COPY(ctx->nonce, nonce + 4, 8); + ctx->counter = (u64)load32_le(nonce) << 32; +} + +void crypto_aead_write(crypto_aead_ctx *ctx, u8 *cipher_text, u8 mac[16], + const u8 *ad, size_t ad_size, + const u8 *plain_text, size_t text_size) +{ + u8 auth_key[64]; // the last 32 bytes are used for rekeying. + crypto_chacha20_djb(auth_key, 0, 64, ctx->key, ctx->nonce, ctx->counter); + crypto_chacha20_djb(cipher_text, plain_text, text_size, + ctx->key, ctx->nonce, ctx->counter + 1); + lock_auth(mac, auth_key, ad, ad_size, cipher_text, text_size); + COPY(ctx->key, auth_key + 32, 32); + WIPE_BUFFER(auth_key); +} + +int crypto_aead_read(crypto_aead_ctx *ctx, u8 *plain_text, const u8 mac[16], + const u8 *ad, size_t ad_size, + const u8 *cipher_text, size_t text_size) +{ + u8 auth_key[64]; // the last 32 bytes are used for rekeying. + u8 real_mac[16]; + crypto_chacha20_djb(auth_key, 0, 64, ctx->key, ctx->nonce, ctx->counter); + lock_auth(real_mac, auth_key, ad, ad_size, cipher_text, text_size); + int mismatch = crypto_verify16(mac, real_mac); + if (!mismatch) { + crypto_chacha20_djb(plain_text, cipher_text, text_size, + ctx->key, ctx->nonce, ctx->counter + 1); + COPY(ctx->key, auth_key + 32, 32); + } + WIPE_BUFFER(auth_key); + WIPE_BUFFER(real_mac); + return mismatch; +} + +void crypto_aead_lock(u8 *cipher_text, u8 mac[16], const u8 key[32], + const u8 nonce[24], const u8 *ad, size_t ad_size, + const u8 *plain_text, size_t text_size) +{ + crypto_aead_ctx ctx; + crypto_aead_init_x(&ctx, key, nonce); + crypto_aead_write(&ctx, cipher_text, mac, ad, ad_size, + plain_text, text_size); + crypto_wipe(&ctx, sizeof(ctx)); +} + +int crypto_aead_unlock(u8 *plain_text, const u8 mac[16], const u8 key[32], + const u8 nonce[24], const u8 *ad, size_t ad_size, + const u8 *cipher_text, size_t text_size) +{ + crypto_aead_ctx ctx; + crypto_aead_init_x(&ctx, key, nonce); + int mismatch = crypto_aead_read(&ctx, plain_text, mac, ad, ad_size, + cipher_text, text_size); + crypto_wipe(&ctx, sizeof(ctx)); + return mismatch; +} + +#ifdef MONOCYPHER_CPP_NAMESPACE +} +#endif diff --git a/enclave/Enclave/libs/monocypher.h b/enclave/Enclave/libs/monocypher.h new file mode 100644 index 00000000..cf635e88 --- /dev/null +++ b/enclave/Enclave/libs/monocypher.h @@ -0,0 +1,321 @@ +// Monocypher version __git__ +// +// This file is dual-licensed. Choose whichever licence you want from +// the two licences listed below. +// +// The first licence is a regular 2-clause BSD licence. The second licence +// is the CC-0 from Creative Commons. It is intended to release Monocypher +// to the public domain. The BSD licence serves as a fallback option. +// +// SPDX-License-Identifier: BSD-2-Clause OR CC0-1.0 +// +// ------------------------------------------------------------------------ +// +// Copyright (c) 2017-2019, Loup Vaillant +// All rights reserved. +// +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// ------------------------------------------------------------------------ +// +// Written in 2017-2019 by Loup Vaillant +// +// To the extent possible under law, the author(s) have dedicated all copyright +// and related neighboring rights to this software to the public domain +// worldwide. This software is distributed without any warranty. +// +// You should have received a copy of the CC0 Public Domain Dedication along +// with this software. If not, see +// + +#ifndef MONOCYPHER_H +#define MONOCYPHER_H + +#include +#include + +#ifdef MONOCYPHER_CPP_NAMESPACE +namespace MONOCYPHER_CPP_NAMESPACE { +#elif defined(__cplusplus) +extern "C" { +#endif + +// Constant time comparisons +// ------------------------- + +// Return 0 if a and b are equal, -1 otherwise +int crypto_verify16(const uint8_t a[16], const uint8_t b[16]); +int crypto_verify32(const uint8_t a[32], const uint8_t b[32]); +int crypto_verify64(const uint8_t a[64], const uint8_t b[64]); + + +// Erase sensitive data +// -------------------- +void crypto_wipe(void *secret, size_t size); + + +// Authenticated encryption +// ------------------------ +void crypto_aead_lock(uint8_t *cipher_text, + uint8_t mac [16], + const uint8_t key [32], + const uint8_t nonce[24], + const uint8_t *ad, size_t ad_size, + const uint8_t *plain_text, size_t text_size); +int crypto_aead_unlock(uint8_t *plain_text, + const uint8_t mac [16], + const uint8_t key [32], + const uint8_t nonce[24], + const uint8_t *ad, size_t ad_size, + const uint8_t *cipher_text, size_t text_size); + +// Authenticated stream +// -------------------- +typedef struct { + uint64_t counter; + uint8_t key[32]; + uint8_t nonce[8]; +} crypto_aead_ctx; + +void crypto_aead_init_x(crypto_aead_ctx *ctx, + const uint8_t key[32], const uint8_t nonce[24]); +void crypto_aead_init_djb(crypto_aead_ctx *ctx, + const uint8_t key[32], const uint8_t nonce[8]); +void crypto_aead_init_ietf(crypto_aead_ctx *ctx, + const uint8_t key[32], const uint8_t nonce[12]); + +void crypto_aead_write(crypto_aead_ctx *ctx, + uint8_t *cipher_text, + uint8_t mac[16], + const uint8_t *ad , size_t ad_size, + const uint8_t *plain_text, size_t text_size); +int crypto_aead_read(crypto_aead_ctx *ctx, + uint8_t *plain_text, + const uint8_t mac[16], + const uint8_t *ad , size_t ad_size, + const uint8_t *cipher_text, size_t text_size); + + +// General purpose hash (BLAKE2b) +// ------------------------------ + +// Direct interface +void crypto_blake2b(uint8_t *hash, size_t hash_size, + const uint8_t *message, size_t message_size); + +void crypto_blake2b_keyed(uint8_t *hash, size_t hash_size, + const uint8_t *key, size_t key_size, + const uint8_t *message, size_t message_size); + +// Incremental interface +typedef struct { + // Do not rely on the size or contents of this type, + // for they may change without notice. + uint64_t hash[8]; + uint64_t input_offset[2]; + uint64_t input[16]; + size_t input_idx; + size_t hash_size; +} crypto_blake2b_ctx; + +void crypto_blake2b_init(crypto_blake2b_ctx *ctx, size_t hash_size); +void crypto_blake2b_keyed_init(crypto_blake2b_ctx *ctx, size_t hash_size, + const uint8_t *key, size_t key_size); +void crypto_blake2b_update(crypto_blake2b_ctx *ctx, + const uint8_t *message, size_t message_size); +void crypto_blake2b_final(crypto_blake2b_ctx *ctx, uint8_t *hash); + + +// Password key derivation (Argon2) +// -------------------------------- +#define CRYPTO_ARGON2_D 0 +#define CRYPTO_ARGON2_I 1 +#define CRYPTO_ARGON2_ID 2 + +typedef struct { + uint32_t algorithm; // Argon2d, Argon2i, Argon2id + uint32_t nb_blocks; // memory hardness, >= 8 * nb_lanes + uint32_t nb_passes; // CPU hardness, >= 1 (>= 3 recommended for Argon2i) + uint32_t nb_lanes; // parallelism level (single threaded anyway) +} crypto_argon2_config; + +typedef struct { + const uint8_t *pass; + const uint8_t *salt; + uint32_t pass_size; + uint32_t salt_size; // 16 bytes recommended +} crypto_argon2_inputs; + +typedef struct { + const uint8_t *key; // may be NULL if no key + const uint8_t *ad; // may be NULL if no additional data + uint32_t key_size; // 0 if no key (32 bytes recommended otherwise) + uint32_t ad_size; // 0 if no additional data +} crypto_argon2_extras; + +extern const crypto_argon2_extras crypto_argon2_no_extras; + +void crypto_argon2(uint8_t *hash, uint32_t hash_size, void *work_area, + crypto_argon2_config config, + crypto_argon2_inputs inputs, + crypto_argon2_extras extras); + + +// Key exchange (X-25519) +// ---------------------- + +// Shared secrets are not quite random. +// Hash them to derive an actual shared key. +void crypto_x25519_public_key(uint8_t public_key[32], + const uint8_t secret_key[32]); +void crypto_x25519(uint8_t raw_shared_secret[32], + const uint8_t your_secret_key [32], + const uint8_t their_public_key [32]); + +// Conversion to EdDSA +void crypto_x25519_to_eddsa(uint8_t eddsa[32], const uint8_t x25519[32]); + +// scalar "division" +// Used for OPRF. Be aware that exponential blinding is less secure +// than Diffie-Hellman key exchange. +void crypto_x25519_inverse(uint8_t blind_salt [32], + const uint8_t private_key[32], + const uint8_t curve_point[32]); + +// "Dirty" versions of x25519_public_key(). +// Use with crypto_elligator_rev(). +// Leaks 3 bits of the private key. +void crypto_x25519_dirty_small(uint8_t pk[32], const uint8_t sk[32]); +void crypto_x25519_dirty_fast (uint8_t pk[32], const uint8_t sk[32]); + + +// Signatures +// ---------- + +// EdDSA with curve25519 + BLAKE2b +void crypto_eddsa_key_pair(uint8_t secret_key[64], + uint8_t public_key[32], + uint8_t seed[32]); +void crypto_eddsa_sign(uint8_t signature [64], + const uint8_t secret_key[64], + const uint8_t *message, size_t message_size); +int crypto_eddsa_check(const uint8_t signature [64], + const uint8_t public_key[32], + const uint8_t *message, size_t message_size); + +// Conversion to X25519 +void crypto_eddsa_to_x25519(uint8_t x25519[32], const uint8_t eddsa[32]); + +// EdDSA building blocks +void crypto_eddsa_trim_scalar(uint8_t out[32], const uint8_t in[32]); +void crypto_eddsa_reduce(uint8_t reduced[32], const uint8_t expanded[64]); +void crypto_eddsa_mul_add(uint8_t r[32], + const uint8_t a[32], + const uint8_t b[32], + const uint8_t c[32]); +void crypto_eddsa_scalarbase(uint8_t point[32], const uint8_t scalar[32]); +int crypto_eddsa_check_equation(const uint8_t signature[64], + const uint8_t public_key[32], + const uint8_t h_ram[32]); + + +// Chacha20 +// -------- + +// Specialised hash. +// Used to hash X25519 shared secrets. +void crypto_chacha20_h(uint8_t out[32], + const uint8_t key[32], + const uint8_t in [16]); + +// Unauthenticated stream cipher. +// Don't forget to add authentication. +uint64_t crypto_chacha20_djb(uint8_t *cipher_text, + const uint8_t *plain_text, + size_t text_size, + const uint8_t key[32], + const uint8_t nonce[8], + uint64_t ctr); +uint32_t crypto_chacha20_ietf(uint8_t *cipher_text, + const uint8_t *plain_text, + size_t text_size, + const uint8_t key[32], + const uint8_t nonce[12], + uint32_t ctr); +uint64_t crypto_chacha20_x(uint8_t *cipher_text, + const uint8_t *plain_text, + size_t text_size, + const uint8_t key[32], + const uint8_t nonce[24], + uint64_t ctr); + + +// Poly 1305 +// --------- + +// This is a *one time* authenticator. +// Disclosing the mac reveals the key. +// See crypto_lock() on how to use it properly. + +// Direct interface +void crypto_poly1305(uint8_t mac[16], + const uint8_t *message, size_t message_size, + const uint8_t key[32]); + +// Incremental interface +typedef struct { + // Do not rely on the size or contents of this type, + // for they may change without notice. + uint8_t c[16]; // chunk of the message + size_t c_idx; // How many bytes are there in the chunk. + uint32_t r [4]; // constant multiplier (from the secret key) + uint32_t pad[4]; // random number added at the end (from the secret key) + uint32_t h [5]; // accumulated hash +} crypto_poly1305_ctx; + +void crypto_poly1305_init (crypto_poly1305_ctx *ctx, const uint8_t key[32]); +void crypto_poly1305_update(crypto_poly1305_ctx *ctx, + const uint8_t *message, size_t message_size); +void crypto_poly1305_final (crypto_poly1305_ctx *ctx, uint8_t mac[16]); + + +// Elligator 2 +// ----------- + +// Elligator mappings proper +void crypto_elligator_map(uint8_t curve [32], const uint8_t hidden[32]); +int crypto_elligator_rev(uint8_t hidden[32], const uint8_t curve [32], + uint8_t tweak); + +// Easy to use key pair generation +void crypto_elligator_key_pair(uint8_t hidden[32], uint8_t secret_key[32], + uint8_t seed[32]); + +#ifdef __cplusplus +} +#endif + +#endif // MONOCYPHER_H diff --git a/enclave/Makefile b/enclave/Makefile index da30f739..37c4f102 100644 --- a/enclave/Makefile +++ b/enclave/Makefile @@ -104,6 +104,7 @@ endif Crypto_Library_Name := sgx_tcrypto Enclave_Cpp_Files := Enclave/Enclave.cpp +Enclave_C_Files := Enclave/libs/monocypher.c Enclave_Include_Paths := -IEnclave -I$(SGX_SDK)/include -I$(SGX_SDK)/include/tlibc -I$(SGX_SDK)/include/libcxx -I./secp256k1-zkp/include -I/usr/local/include Enclave_C_Flags := $(Enclave_Include_Paths) -nostdinc -fvisibility=hidden -fpie -ffunction-sections -fdata-sections $(MITIGATION_CFLAGS) @@ -136,6 +137,7 @@ Enclave_Link_Flags := $(MITIGATION_LDFLAGS) $(Enclave_Security_Link_Flags) \ -Wl,--version-script=Enclave/Enclave.lds Enclave_Cpp_Objects := $(sort $(Enclave_Cpp_Files:.cpp=.o)) +Enclave_C_Objects := $(sort $(Enclave_C_Files:.c=.o)) Enclave_Name := enclave.so Signed_Enclave_Name := enclave.signed.so @@ -240,7 +242,7 @@ Enclave/%.o: Enclave/%.cpp Enclave/Enclave_t.h @$(CXX) $(SGX_COMMON_CXXFLAGS) $(Enclave_Cpp_Flags) -c $< -o $@ @echo "CXX <= $<" -$(Enclave_Name): Enclave/Enclave_t.o $(Enclave_Cpp_Objects) $(SECP256K1_LIB) +$(Enclave_Name): Enclave/Enclave_t.o $(Enclave_Cpp_Objects) $(Enclave_C_Objects) $(SECP256K1_LIB) @$(CXX) $^ -o $@ $(Enclave_Link_Flags) @echo "LINK => $@" From f308e683d4bc7c10904eb50fe2c9a2f8c478de16 Mon Sep 17 00:00:00 2001 From: "S. Santos" Date: Tue, 2 Apr 2024 20:15:22 -0300 Subject: [PATCH 11/66] [WIP] Add Sealing Key --- enclave/App/App.cpp | 22 +++--- enclave/App/database/db_manager.cpp | 104 +++++++++++++++++++++++++++- enclave/App/database/db_manager.h | 2 +- enclave/Enclave/Enclave.cpp | 25 ++++++- enclave/Enclave/Enclave.edl | 3 +- 5 files changed, 139 insertions(+), 17 deletions(-) diff --git a/enclave/App/App.cpp b/enclave/App/App.cpp index a059a742..191cc1df 100644 --- a/enclave/App/App.cpp +++ b/enclave/App/App.cpp @@ -20,6 +20,7 @@ #include "../utils/include_secp256k1_zkp_lib.h" #include "../utils/strencodings.h" #include "utilities/utilities.h" +#include "database/db_manager.h" #include "sealing_key_manager/sealing_key_manager.h" #include "App.h" @@ -274,7 +275,7 @@ void ocall_print_hex(const unsigned char** key, const int *keylen) printf("%s\n", key_to_string(*key, *keylen).c_str()); } -void initialize_encrypted_data(chacha20_poly1305_encrypted_data& encrypted_data, size_t data_len, sealing_key_manager::SealingKeyManager& sealing_key_manager) { +void initialize_encrypted_data(chacha20_poly1305_encrypted_data& encrypted_data, size_t data_len) { // initialize encrypted_data encrypted_data.data_len = data_len; @@ -283,12 +284,6 @@ void initialize_encrypted_data(chacha20_poly1305_encrypted_data& encrypted_data, memset(encrypted_data.mac, 0, sizeof(encrypted_data.mac)); memset(encrypted_data.nonce, 0, sizeof(encrypted_data.nonce)); - - // copy sealed seed - encrypted_data.sealed_key_len = sealing_key_manager.sealed_seed_size; - encrypted_data.sealed_key = new char[encrypted_data.sealed_key_len]; - memcpy(encrypted_data.sealed_key, sealing_key_manager.sealed_seed, encrypted_data.sealed_key_len); - } int SGX_CDECL main(int argc, char *argv[]) @@ -362,14 +357,21 @@ int SGX_CDECL main(int argc, char *argv[]) } // new encryption scheme - chacha20_poly1305_encrypted_data encrypted_data; - initialize_encrypted_data(encrypted_data, sizeof(secp256k1_keypair), sealing_key_manager); + /* chacha20_poly1305_encrypted_data encrypted_data; + initialize_encrypted_data(encrypted_data, sizeof(secp256k1_keypair)); size_t server_pubkey_size2 = 33; // serialized compressed public keys are 33-byte array unsigned char server_pubkey2[server_pubkey_size2]; sgx_status_t ecall_ret2; - generate_new_keypair2(enclave_id, &ecall_ret2, server_pubkey2, server_pubkey_size2, &encrypted_data); + generate_new_keypair2(enclave_id, &ecall_ret2, + server_pubkey2, server_pubkey_size2, + sealing_key_manager.sealed_seed, sealing_key_manager.sealed_seed_size, + &encrypted_data); + + std::string error_message2; + db_manager::save_generated_public_key(encrypted_data, server_pubkey2, server_pubkey_size2, statechain_id, error_message2); + */ auto server_seckey_hex = key_to_string(server_pubkey, server_pubkey_size); diff --git a/enclave/App/database/db_manager.cpp b/enclave/App/database/db_manager.cpp index 5885398b..1725592b 100644 --- a/enclave/App/database/db_manager.cpp +++ b/enclave/App/database/db_manager.cpp @@ -2,6 +2,8 @@ #include "../Enclave_u.h" #include "../lib/toml.hpp" +#include "../../utils/strencodings.h" +#include #include #include @@ -98,8 +100,64 @@ namespace db_manager { } // get_sealed_seed + // Assumes the buffer is large enough. In a real application, ensure buffer safety. + void serialize(const chacha20_poly1305_encrypted_data* src, unsigned char* buffer, size_t* serialized_len) { + // Copy `data_len`, `nonce`, and `mac` directly + size_t offset = 0; + memcpy(buffer + offset, &src->data_len, sizeof(src->data_len)); + offset += sizeof(src->data_len); + + memcpy(buffer + offset, src->nonce, sizeof(src->nonce)); + offset += sizeof(src->nonce); + + memcpy(buffer + offset, src->mac, sizeof(src->mac)); + offset += sizeof(src->mac); + + // Now copy dynamic `data` + memcpy(buffer + offset, src->data, src->data_len); + offset += src->data_len; + + *serialized_len = offset; + } + + // Returns a newly allocated structure that must be freed by the caller. + bool deserialize(const unsigned char* buffer, size_t serialized_len, chacha20_poly1305_encrypted_data* dest) { + + // chacha20_poly1305_encrypted_data* dest = new chacha20_poly1305_encrypted_data; + // if (!dest) return NULL; + + if (!dest) return false; + + size_t offset = 0; + memcpy(&dest->data_len, buffer + offset, sizeof(dest->data_len)); + offset += sizeof(dest->data_len); + + memcpy(dest->nonce, buffer + offset, sizeof(dest->nonce)); + offset += sizeof(dest->nonce); + + memcpy(dest->mac, buffer + offset, sizeof(dest->mac)); + offset += sizeof(dest->mac); + + dest->data = new unsigned char[dest->data_len]; + if (!dest->data) { + return false; // NULL; + } + memcpy(dest->data, buffer + offset, dest->data_len); + // offset += dest->data_len; // Not needed unless you're reading more data after this + + // return dest; + return true; + } + + void print_encrypted_data(const chacha20_poly1305_encrypted_data* data) { + std::cout << "data_len: " << data->data_len << std::endl; + std::cout << "nonce: " << key_to_string(data->nonce, sizeof(data->nonce)) << std::endl; + std::cout << "mac: " << key_to_string(data->mac, sizeof(data->mac)) << std::endl; + std::cout << "data: " << key_to_string(data->data, data->data_len) << std::endl; + } + bool save_generated_public_key( - chacha20_poly1305_encrypted_data& encrypted_data, + const chacha20_poly1305_encrypted_data& encrypted_keypair, unsigned char* server_public_key, size_t server_public_key_size, std::string& statechain_id, std::string& error_message) { @@ -126,6 +184,50 @@ namespace db_manager { txn.exec(create_table_query); txn.commit(); + + size_t serialized_len = 0; + + size_t bufferSize = sizeof(encrypted_keypair.data_len) + sizeof(encrypted_keypair.nonce) + sizeof(encrypted_keypair.mac) + encrypted_keypair.data_len; + unsigned char* buffer = (unsigned char*) malloc(bufferSize); + + if (!buffer) { + error_message = "Failed to allocate memory for serialization!"; + return false; + } + + serialize(&encrypted_keypair, buffer, &serialized_len); + assert(serialized_len == bufferSize); + + /* auto buffer_hex = key_to_string(buffer, serialized_len); + + std::cout << "---- " << std::endl; + print_encrypted_data(&encrypted_keypair); + std::cout << "---- " << std::endl; + std::cout << "buffer: " << buffer_hex << std::endl; + + // chacha20_poly1305_encrypted_data* dest = new chacha20_poly1305_encrypted_keypair; + auto dest = std::make_unique(); + bool res = deserialize(buffer, serialized_len, dest.get()); + + std::cout << "---- " << std::endl; + std::cout << "res: " << res << std::endl; + print_encrypted_data(dest.get()); + + free(buffer); */ + + std::basic_string_view sealed_data_view(reinterpret_cast(buffer), bufferSize); + std::basic_string_view public_key_data_view(reinterpret_cast(server_public_key), server_public_key_size); + + std::string insert_query = + "INSERT INTO generated_public_key (sealed_keypair, public_key, statechain_id) VALUES ($1, $2, $3);"; + pqxx::work txn2(conn); + + txn2.exec_params(insert_query, sealed_data_view, public_key_data_view, statechain_id); + txn2.commit(); + + conn.close(); + return true; + return true; } else { error_message = "Failed to connect to the database!"; diff --git a/enclave/App/database/db_manager.h b/enclave/App/database/db_manager.h index 1f48452f..6d1ba7ea 100644 --- a/enclave/App/database/db_manager.h +++ b/enclave/App/database/db_manager.h @@ -13,7 +13,7 @@ namespace db_manager { bool get_sealed_seed(char* sealed_secret, size_t sealed_secret_size, std::string& error_message); bool save_generated_public_key( - chacha20_poly1305_encrypted_data& encrypted_data, + const chacha20_poly1305_encrypted_data& encrypted_data, unsigned char* server_public_key, size_t server_public_key_size, std::string& statechain_id, std::string& error_message); diff --git a/enclave/Enclave/Enclave.cpp b/enclave/Enclave/Enclave.cpp index 30e05f30..048097fe 100644 --- a/enclave/Enclave/Enclave.cpp +++ b/enclave/Enclave/Enclave.cpp @@ -30,12 +30,13 @@ char* data_to_hex(uint8_t* in, size_t insz) void encrypt_data( chacha20_poly1305_encrypted_data *encrypted_data, + char* sealed_seed, size_t sealed_seed_len, uint8_t* raw_data, size_t raw_data_size) { unsigned char seed[32]; memset(seed, 0, 32); - unseal(encrypted_data->sealed_key, encrypted_data->sealed_key_len, seed, sizeof(seed)); + unseal(sealed_seed, sealed_seed_len, seed, sizeof(seed)); // Associated data (optional, can be NULL if not used) uint8_t *ad = NULL; @@ -45,11 +46,29 @@ void encrypt_data( assert(encrypted_data->data_len == raw_data_size); crypto_aead_lock(encrypted_data->data, encrypted_data->mac, seed, encrypted_data->nonce, ad, ad_size, raw_data, raw_data_size); + + /* char* seed_hex = data_to_hex(seed, sizeof(seed)); + ocall_print_string("seed:"); + ocall_print_string(seed_hex); + + char* mac_hex = data_to_hex(encrypted_data->mac, sizeof(encrypted_data->mac)); + ocall_print_string("mac:"); + ocall_print_string(mac_hex); + + char* nonce_hex = data_to_hex(encrypted_data->nonce, sizeof(encrypted_data->nonce)); + ocall_print_string("nonce:"); + ocall_print_string(nonce_hex); + + char* encrypted_hex = data_to_hex(encrypted_data->data, encrypted_data->data_len); + ocall_print_string("encrypted:"); + ocall_print_string(encrypted_hex); */ + } sgx_status_t generate_new_keypair2( unsigned char *compressed_server_pubkey, size_t compressed_server_pubkey_size, + char* sealed_seed, size_t sealed_seed_len, chacha20_poly1305_encrypted_data *encrypted_data) { @@ -88,7 +107,7 @@ sgx_status_t generate_new_keypair2( secp256k1_context_destroy(ctx); - encrypt_data(encrypted_data, server_keypair.data, sizeof(secp256k1_keypair::data)); + encrypt_data(encrypted_data, sealed_seed, sealed_seed_len, server_keypair.data, sizeof(secp256k1_keypair::data)); return ret; } @@ -469,7 +488,7 @@ sgx_status_t recover_seed( uint8_t* shares[threshold]; - uint32_t unsealed_data_size = key_share_data_size; + uint32_t unsealed_data_size = (uint32_t) key_share_data_size; for (size_t i = 0; i < num_key_shares; ++i) { shares[i] = new uint8_t[key_share_data_size]; diff --git a/enclave/Enclave/Enclave.edl b/enclave/Enclave/Enclave.edl index 843b6354..f0794272 100644 --- a/enclave/Enclave/Enclave.edl +++ b/enclave/Enclave/Enclave.edl @@ -13,8 +13,6 @@ enclave { [size=data_len] unsigned char* data; unsigned char nonce[24]; unsigned char mac[16]; - size_t sealed_key_len; - [size=sealed_key_len] char* sealed_key; }; trusted { @@ -22,6 +20,7 @@ enclave { public sgx_status_t generate_new_keypair2( [out, size=compressed_server_pubkey_size] unsigned char *compressed_server_pubkey, size_t compressed_server_pubkey_size, + [in, size=sealed_seed_len] char* sealed_seed, size_t sealed_seed_len, [in, out] struct chacha20_poly1305_encrypted_data* encrypted_data); public sgx_status_t generate_new_keypair( From 1e6577fa9c16d4c2f6d87a0a08add8b0e4752d15 Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Wed, 3 Apr 2024 18:27:01 +0530 Subject: [PATCH 12/66] fix: comment settings attribute of wallet --- clients/rust/src/wallet.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clients/rust/src/wallet.rs b/clients/rust/src/wallet.rs index 05533b2d..3e1985b4 100644 --- a/clients/rust/src/wallet.rs +++ b/clients/rust/src/wallet.rs @@ -53,7 +53,7 @@ pub async fn create_wallet( tokens: Vec::new(), activities: Vec::new(), coins: Vec::new(), - settings, + // settings, }; // save wallet to database From a809302b4453a31a99e70dd60e85a8792111d795 Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Thu, 4 Apr 2024 11:55:15 +0530 Subject: [PATCH 13/66] fix: dockerfile --- server/Dockerfile | 2 +- token-server/Dockerfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/server/Dockerfile b/server/Dockerfile index 28c5f8c5..70ba0c62 100644 --- a/server/Dockerfile +++ b/server/Dockerfile @@ -11,4 +11,4 @@ COPY . . RUN cargo build --release EXPOSE 8000 # Run the application -CMD ["cargo", "run"] +CMD ["cargo", "run", "--bin", "mercury-server"] diff --git a/token-server/Dockerfile b/token-server/Dockerfile index 29de27ac..e62903cd 100644 --- a/token-server/Dockerfile +++ b/token-server/Dockerfile @@ -11,4 +11,4 @@ COPY . . RUN cargo build --release EXPOSE 8001 # Run the application -CMD ["cargo", "run"] +CMD ["cargo", "run", "--bin", "token-server"] From 2ca8a852696231e60ee225880b20eaad328e66b4 Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Fri, 5 Apr 2024 21:20:59 +0530 Subject: [PATCH 14/66] fix: add Rocket.toml to parent folder --- Rocket.toml | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Rocket.toml diff --git a/Rocket.toml b/Rocket.toml new file mode 100644 index 00000000..313e173a --- /dev/null +++ b/Rocket.toml @@ -0,0 +1,3 @@ +[global] +address = "0.0.0.0" +port = 8000 From 4289d2d0c5956852f4c4e8f1f744e5bdeae710ab Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Mon, 8 Apr 2024 16:52:36 +0530 Subject: [PATCH 15/66] fix: remove Rocket.toml from sub folder --- mercury-server-deployment.yaml | 33 +++++++++++++++++++++++++++++++++ mercury-server-service.yaml | 13 +++++++++++++ nginx-deployment.yaml | 21 +++++++++++++++++++++ nginx-service.yaml | 12 ++++++++++++ server/Rocket.toml | 3 --- token-server-deployment.yaml | 31 +++++++++++++++++++++++++++++++ token-server-service.yaml | 15 +++++++++++++++ token-server/Rocket.toml | 3 --- 8 files changed, 125 insertions(+), 6 deletions(-) create mode 100644 mercury-server-deployment.yaml create mode 100644 mercury-server-service.yaml create mode 100644 nginx-deployment.yaml create mode 100644 nginx-service.yaml delete mode 100644 server/Rocket.toml create mode 100644 token-server-deployment.yaml create mode 100644 token-server-service.yaml delete mode 100644 token-server/Rocket.toml diff --git a/mercury-server-deployment.yaml b/mercury-server-deployment.yaml new file mode 100644 index 00000000..c3d4b92f --- /dev/null +++ b/mercury-server-deployment.yaml @@ -0,0 +1,33 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: mercury-server + labels: + app: mercury-server +spec: + selector: + matchLabels: + app: mercury-server + replicas: 1 + template: + metadata: + labels: + app: mercury-server + spec: + containers: + - name: mercury-server + image: commerceblockx/mercury-server:latest + ports: + - containerPort: 8000 + command: ["cargo", "run", "--bin", "mercury-server"] + env: + - name: LOCKBOX + value: "http://78.141.209.195:18080" + - name: NETWORK + value: "testnet" + - name: LOCKHEIGHT_INIT + value: "1000" + - name: LH_DECREMENT + value: "10" + - name: CONNECTION_STRING + value: "postgresql://postgres:password1@45.76.136.11/mercury_token2" diff --git a/mercury-server-service.yaml b/mercury-server-service.yaml new file mode 100644 index 00000000..25118d0c --- /dev/null +++ b/mercury-server-service.yaml @@ -0,0 +1,13 @@ +apiVersion: v1 +kind: Service +metadata: + name: mercury-server-service +spec: + ports: + - port: 8000 + nodePort: 32450 + protocol: TCP + targetPort: 8000 + selector: + app: mercury-server + type: NodePort diff --git a/nginx-deployment.yaml b/nginx-deployment.yaml new file mode 100644 index 00000000..726169eb --- /dev/null +++ b/nginx-deployment.yaml @@ -0,0 +1,21 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: nginx + labels: + app: nginx +spec: + replicas: 1 + selector: + matchLabels: + app: nginx + template: + metadata: + labels: + app: nginx + spec: + containers: + - name: nginx + image: nginx + ports: + - containerPort: 80 diff --git a/nginx-service.yaml b/nginx-service.yaml new file mode 100644 index 00000000..59f597f8 --- /dev/null +++ b/nginx-service.yaml @@ -0,0 +1,12 @@ +apiVersion: v1 +kind: Service +metadata: + name: ngnix-service +spec: + selector: + app: nginx + type: NodePort + ports: + - protocol: TCP + port: 80 + targetPort: 80 \ No newline at end of file diff --git a/server/Rocket.toml b/server/Rocket.toml deleted file mode 100644 index 313e173a..00000000 --- a/server/Rocket.toml +++ /dev/null @@ -1,3 +0,0 @@ -[global] -address = "0.0.0.0" -port = 8000 diff --git a/token-server-deployment.yaml b/token-server-deployment.yaml new file mode 100644 index 00000000..d198dec5 --- /dev/null +++ b/token-server-deployment.yaml @@ -0,0 +1,31 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: token-server +spec: + selector: + matchLabels: + app: token-server + replicas: 1 + template: + metadata: + labels: + app: token-server + spec: + containers: + - name: token-server + image: commerceblockx/token-server:latest + ports: + - containerPort: 8001 + command: ["cargo", "run", "--bin", "token-server"] + env: + - name: PROCESSOR_URL + value: "https://api.swiss-bitcoin-pay.ch" + - name: API_KEY + value: "684e8697137644bf9a97f6a5d2132349" + - name: FEE + value: "0.001" + - name: DELAY + value: "60" + - name: CONNECTION_STRING + value: "postgresql://postgres:password1@45.76.136.11/mercury_token2" diff --git a/token-server-service.yaml b/token-server-service.yaml new file mode 100644 index 00000000..3fa5721f --- /dev/null +++ b/token-server-service.yaml @@ -0,0 +1,15 @@ +apiVersion: v1 +kind: Service +metadata: + labels: + app: token-server + name: token-server +spec: + ports: + - port: 80 + nodePort: 32451 + protocol: TCP + targetPort: 8001 + selector: + app: token-server + type: NodePort diff --git a/token-server/Rocket.toml b/token-server/Rocket.toml deleted file mode 100644 index 313e173a..00000000 --- a/token-server/Rocket.toml +++ /dev/null @@ -1,3 +0,0 @@ -[global] -address = "0.0.0.0" -port = 8000 From e570b976e406c83f48910552019d1a38527e6152 Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Wed, 10 Apr 2024 22:06:52 +0530 Subject: [PATCH 16/66] fix: add tls-rustls feature to sqlx --- server/Cargo.toml | 2 +- token-server/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/server/Cargo.toml b/server/Cargo.toml index 6a447216..c98dbac0 100644 --- a/server/Cargo.toml +++ b/server/Cargo.toml @@ -10,7 +10,7 @@ bitcoin = { version = "0.30.1", features = ["serde", "base64", "rand-std", "std" config = "0.13.1" reqwest = { version = "0.11.16", features = ["blocking", "json", "socks"] } rocket = { version = "0.5.0-rc", features = ["json"] } -sqlx = { version = "0.7", features = [ "runtime-tokio", "postgres", "time", "uuid" ] } +sqlx = { version = "0.7", features = [ "runtime-tokio", "postgres", "time", "uuid", "tls-rustls" ] } serde = { version = "1.0.163", features = ["derive"] } serde_json = "1.0.96" schemars = { version = "0.8.12", features = ["chrono", "uuid"] } diff --git a/token-server/Cargo.toml b/token-server/Cargo.toml index cf55dd71..8599b154 100644 --- a/token-server/Cargo.toml +++ b/token-server/Cargo.toml @@ -9,7 +9,7 @@ edition = "2021" config = "0.13.1" reqwest = { version = "0.11.16", features = ["blocking", "json", "socks"] } rocket = { version = "0.5.0-rc", features = ["json"] } -sqlx = { version = "0.7", features = [ "runtime-tokio", "postgres", "time", "uuid" ] } +sqlx = { version = "0.7", features = [ "runtime-tokio", "postgres", "time", "uuid", "tls-rustls" ] } serde = { version = "1.0.163", features = ["derive"] } serde_json = "1.0.96" schemars = { version = "0.8.12", features = ["chrono", "uuid"] } From 42de8adc99828ca618ccf144cf50a9a9c8c0cd9a Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Thu, 11 Apr 2024 20:19:25 +0530 Subject: [PATCH 17/66] fix: route for endpoint /info --- Cargo.lock | 11 ++++++++++- mercury-server-deployment.yaml | 33 --------------------------------- mercury-server-service.yaml | 13 ------------- nginx-deployment.yaml | 21 --------------------- nginx-service.yaml | 12 ------------ server/src/endpoints/utils.rs | 4 ++-- token-server-deployment.yaml | 31 ------------------------------- token-server-service.yaml | 15 --------------- 8 files changed, 12 insertions(+), 128 deletions(-) delete mode 100644 mercury-server-deployment.yaml delete mode 100644 mercury-server-service.yaml delete mode 100644 nginx-deployment.yaml delete mode 100644 nginx-service.yaml delete mode 100644 token-server-deployment.yaml delete mode 100644 token-server-service.yaml diff --git a/Cargo.lock b/Cargo.lock index 47a75828..b6c05ae6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -755,7 +755,7 @@ dependencies = [ "serde", "serde_json", "webpki", - "webpki-roots", + "webpki-roots 0.22.6", "winapi", ] @@ -2688,6 +2688,8 @@ dependencies = [ "once_cell", "paste", "percent-encoding", + "rustls", + "rustls-pemfile", "serde", "serde_json", "sha2", @@ -2700,6 +2702,7 @@ dependencies = [ "tracing", "url", "uuid 1.8.0", + "webpki-roots 0.25.4", ] [[package]] @@ -3509,6 +3512,12 @@ dependencies = [ "webpki", ] +[[package]] +name = "webpki-roots" +version = "0.25.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f20c57d8d7db6d3b86154206ae5d8fba62dd39573114de97c2cb0578251f8e1" + [[package]] name = "whoami" version = "1.5.1" diff --git a/mercury-server-deployment.yaml b/mercury-server-deployment.yaml deleted file mode 100644 index c3d4b92f..00000000 --- a/mercury-server-deployment.yaml +++ /dev/null @@ -1,33 +0,0 @@ -apiVersion: apps/v1 -kind: Deployment -metadata: - name: mercury-server - labels: - app: mercury-server -spec: - selector: - matchLabels: - app: mercury-server - replicas: 1 - template: - metadata: - labels: - app: mercury-server - spec: - containers: - - name: mercury-server - image: commerceblockx/mercury-server:latest - ports: - - containerPort: 8000 - command: ["cargo", "run", "--bin", "mercury-server"] - env: - - name: LOCKBOX - value: "http://78.141.209.195:18080" - - name: NETWORK - value: "testnet" - - name: LOCKHEIGHT_INIT - value: "1000" - - name: LH_DECREMENT - value: "10" - - name: CONNECTION_STRING - value: "postgresql://postgres:password1@45.76.136.11/mercury_token2" diff --git a/mercury-server-service.yaml b/mercury-server-service.yaml deleted file mode 100644 index 25118d0c..00000000 --- a/mercury-server-service.yaml +++ /dev/null @@ -1,13 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - name: mercury-server-service -spec: - ports: - - port: 8000 - nodePort: 32450 - protocol: TCP - targetPort: 8000 - selector: - app: mercury-server - type: NodePort diff --git a/nginx-deployment.yaml b/nginx-deployment.yaml deleted file mode 100644 index 726169eb..00000000 --- a/nginx-deployment.yaml +++ /dev/null @@ -1,21 +0,0 @@ -apiVersion: apps/v1 -kind: Deployment -metadata: - name: nginx - labels: - app: nginx -spec: - replicas: 1 - selector: - matchLabels: - app: nginx - template: - metadata: - labels: - app: nginx - spec: - containers: - - name: nginx - image: nginx - ports: - - containerPort: 80 diff --git a/nginx-service.yaml b/nginx-service.yaml deleted file mode 100644 index 59f597f8..00000000 --- a/nginx-service.yaml +++ /dev/null @@ -1,12 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - name: ngnix-service -spec: - selector: - app: nginx - type: NodePort - ports: - - protocol: TCP - port: 80 - targetPort: 80 \ No newline at end of file diff --git a/server/src/endpoints/utils.rs b/server/src/endpoints/utils.rs index 2c42a14e..0a8853cc 100644 --- a/server/src/endpoints/utils.rs +++ b/server/src/endpoints/utils.rs @@ -43,7 +43,7 @@ pub async fn validate_signature(pool: &sqlx::PgPool, signed_message_hex: &str, s secp.verify_schnorr(&signed_message, &msg, &auth_key).is_ok() } -#[get("/info/config", format = "json")] +#[get("/info/config")] pub async fn info_config(statechain_entity: &State) -> status::Custom> { let statechain_entity = statechain_entity.inner(); @@ -57,7 +57,7 @@ pub async fn info_config(statechain_entity: &State) -> status: return status::Custom(Status::Ok, Json(response_body)); } -#[get("/info/keylist", format = "json")] +#[get("/info/keylist")] pub async fn info_keylist(statechain_entity: &State) -> status::Custom> { let query = "\ diff --git a/token-server-deployment.yaml b/token-server-deployment.yaml deleted file mode 100644 index d198dec5..00000000 --- a/token-server-deployment.yaml +++ /dev/null @@ -1,31 +0,0 @@ -apiVersion: apps/v1 -kind: Deployment -metadata: - name: token-server -spec: - selector: - matchLabels: - app: token-server - replicas: 1 - template: - metadata: - labels: - app: token-server - spec: - containers: - - name: token-server - image: commerceblockx/token-server:latest - ports: - - containerPort: 8001 - command: ["cargo", "run", "--bin", "token-server"] - env: - - name: PROCESSOR_URL - value: "https://api.swiss-bitcoin-pay.ch" - - name: API_KEY - value: "684e8697137644bf9a97f6a5d2132349" - - name: FEE - value: "0.001" - - name: DELAY - value: "60" - - name: CONNECTION_STRING - value: "postgresql://postgres:password1@45.76.136.11/mercury_token2" diff --git a/token-server-service.yaml b/token-server-service.yaml deleted file mode 100644 index 3fa5721f..00000000 --- a/token-server-service.yaml +++ /dev/null @@ -1,15 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - labels: - app: token-server - name: token-server -spec: - ports: - - port: 80 - nodePort: 32451 - protocol: TCP - targetPort: 8001 - selector: - app: token-server - type: NodePort From 8bb0c08d0b5ecc0962f2978ffdf7782e79005f51 Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Mon, 15 Apr 2024 14:34:38 +0530 Subject: [PATCH 18/66] feat: add dockerfile for explorer --- .github/workflows/ci.yaml | 8 +++ explorer/Dockerfile | 14 +++++ explorer/index.html | 112 ++++++++++++++++++++++++++++++++++++++ explorer/main.js | 10 ++++ 4 files changed, 144 insertions(+) create mode 100644 explorer/Dockerfile create mode 100644 explorer/index.html create mode 100644 explorer/main.js diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index c09cb26c..93727452 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -40,3 +40,11 @@ jobs: file: ./token-server/Dockerfile push: true tags: commerceblockx/token-server:latest + - + name: Build and push + uses: docker/build-push-action@v5 + with: + context: . + file: ./explorer/Dockerfile + push: true + tags: commerceblockx/mercury-explorer:latest diff --git a/explorer/Dockerfile b/explorer/Dockerfile new file mode 100644 index 00000000..f7bb0e60 --- /dev/null +++ b/explorer/Dockerfile @@ -0,0 +1,14 @@ +# Use the official nginx image as the base +FROM nginx:latest + +# Define a working directory for the container +WORKDIR /usr/share/nginx/html + +# Copy the contents of your local /explorer folder to the container's working directory +COPY ./. . + +# Expose port 80 for web traffic +EXPOSE 80 + +# Use the default nginx configuration (serves content from the working directory) +CMD ["nginx", "-g", "daemon off;"] diff --git a/explorer/index.html b/explorer/index.html new file mode 100644 index 00000000..87e3afea --- /dev/null +++ b/explorer/index.html @@ -0,0 +1,112 @@ + + + + + + JSON Data Display + + + + +

Mercury layer lockbox status

+ +
+ + + + + \ No newline at end of file diff --git a/explorer/main.js b/explorer/main.js new file mode 100644 index 00000000..09a7e0dd --- /dev/null +++ b/explorer/main.js @@ -0,0 +1,10 @@ +document.addEventListener('DOMContentLoaded', function () { + // Fetch JSON data + fetch('https://api.mercurywallet.io/info/keylist') + .then(response => response.json()) + .then(data => { + // Display JSON data in a
 tag
+            document.getElementById('json-display').textContent = JSON.stringify(data, null, 2);
+        })
+        .catch(error => console.error('Error fetching data:', error));
+});
\ No newline at end of file

From 0309e5bb691c6050287a48196e37b74dbf779ddd Mon Sep 17 00:00:00 2001
From: DhananjayPurohit 
Date: Mon, 15 Apr 2024 21:30:24 +0530
Subject: [PATCH 19/66] fix: copy cmd for explorer dockerfile

---
 explorer/Dockerfile | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/explorer/Dockerfile b/explorer/Dockerfile
index f7bb0e60..9a5503e9 100644
--- a/explorer/Dockerfile
+++ b/explorer/Dockerfile
@@ -5,7 +5,7 @@ FROM nginx:latest
 WORKDIR /usr/share/nginx/html
 
 # Copy the contents of your local /explorer folder to the container's working directory
-COPY ./. .
+COPY ./. /usr/share/nginx/html
 
 # Expose port 80 for web traffic
 EXPOSE 80

From 5a9db1c0a47900ec72929c9171a2d95bdbc4a783 Mon Sep 17 00:00:00 2001
From: DhananjayPurohit 
Date: Mon, 15 Apr 2024 22:25:53 +0530
Subject: [PATCH 20/66] fix: dockerfile for explorer

---
 explorer/Dockerfile | 3 ---
 1 file changed, 3 deletions(-)

diff --git a/explorer/Dockerfile b/explorer/Dockerfile
index 9a5503e9..7798e19b 100644
--- a/explorer/Dockerfile
+++ b/explorer/Dockerfile
@@ -1,9 +1,6 @@
 # Use the official nginx image as the base
 FROM nginx:latest
 
-# Define a working directory for the container
-WORKDIR /usr/share/nginx/html
-
 # Copy the contents of your local /explorer folder to the container's working directory
 COPY ./. /usr/share/nginx/html
 

From 06caa6c67bf77d53b1a86ada3ad605d06f087dc6 Mon Sep 17 00:00:00 2001
From: DhananjayPurohit 
Date: Tue, 16 Apr 2024 11:16:13 +0530
Subject: [PATCH 21/66] fix: dockerfile copy cmds

---
 explorer/Dockerfile | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/explorer/Dockerfile b/explorer/Dockerfile
index 7798e19b..442d0d6e 100644
--- a/explorer/Dockerfile
+++ b/explorer/Dockerfile
@@ -2,7 +2,8 @@
 FROM nginx:latest
 
 # Copy the contents of your local /explorer folder to the container's working directory
-COPY ./. /usr/share/nginx/html
+COPY ./index.html /usr/share/nginx/html
+COPY ./main.js /usr/share/nginx/html
 
 # Expose port 80 for web traffic
 EXPOSE 80

From 84efc789190dddad4c3dde3d8b7d239319668d60 Mon Sep 17 00:00:00 2001
From: DhananjayPurohit 
Date: Tue, 16 Apr 2024 11:27:28 +0530
Subject: [PATCH 22/66] fix: path for copy cmd

---
 explorer/Dockerfile | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/explorer/Dockerfile b/explorer/Dockerfile
index 442d0d6e..552d8872 100644
--- a/explorer/Dockerfile
+++ b/explorer/Dockerfile
@@ -2,8 +2,8 @@
 FROM nginx:latest
 
 # Copy the contents of your local /explorer folder to the container's working directory
-COPY ./index.html /usr/share/nginx/html
-COPY ./main.js /usr/share/nginx/html
+COPY ../explorer/index.html /usr/share/nginx/html
+COPY ../explorer/main.js /usr/share/nginx/html
 
 # Expose port 80 for web traffic
 EXPOSE 80

From 2df2e532520c6baea7e69cd85f04254b28e454af Mon Sep 17 00:00:00 2001
From: DhananjayPurohit 
Date: Tue, 16 Apr 2024 12:04:48 +0530
Subject: [PATCH 23/66] fix: dockerfile dir for static files

---
 explorer/Dockerfile | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/explorer/Dockerfile b/explorer/Dockerfile
index 552d8872..8e947ad5 100644
--- a/explorer/Dockerfile
+++ b/explorer/Dockerfile
@@ -1,6 +1,9 @@
 # Use the official nginx image as the base
 FROM nginx:latest
 
+# Create a directory for the static files
+RUN mkdir -p /usr/share/nginx/html
+
 # Copy the contents of your local /explorer folder to the container's working directory
 COPY ../explorer/index.html /usr/share/nginx/html
 COPY ../explorer/main.js /usr/share/nginx/html

From c11debe8f78c506bc79236c3eae2476325bb89d9 Mon Sep 17 00:00:00 2001
From: DhananjayPurohit 
Date: Tue, 16 Apr 2024 12:44:31 +0530
Subject: [PATCH 24/66] fix: remove dir creation from explorer dockerfile

---
 explorer/Dockerfile | 3 ---
 1 file changed, 3 deletions(-)

diff --git a/explorer/Dockerfile b/explorer/Dockerfile
index 8e947ad5..552d8872 100644
--- a/explorer/Dockerfile
+++ b/explorer/Dockerfile
@@ -1,9 +1,6 @@
 # Use the official nginx image as the base
 FROM nginx:latest
 
-# Create a directory for the static files
-RUN mkdir -p /usr/share/nginx/html
-
 # Copy the contents of your local /explorer folder to the container's working directory
 COPY ../explorer/index.html /usr/share/nginx/html
 COPY ../explorer/main.js /usr/share/nginx/html

From 94b5493065cc51b6fa6bb7dbacd5eb94cceaa797 Mon Sep 17 00:00:00 2001
From: DhananjayPurohit 
Date: Tue, 16 Apr 2024 13:06:38 +0530
Subject: [PATCH 25/66] fix: change index.html to explorer.html

---
 explorer/Dockerfile                    | 2 +-
 explorer/{index.html => explorer.html} | 0
 2 files changed, 1 insertion(+), 1 deletion(-)
 rename explorer/{index.html => explorer.html} (100%)

diff --git a/explorer/Dockerfile b/explorer/Dockerfile
index 552d8872..75114600 100644
--- a/explorer/Dockerfile
+++ b/explorer/Dockerfile
@@ -2,7 +2,7 @@
 FROM nginx:latest
 
 # Copy the contents of your local /explorer folder to the container's working directory
-COPY ../explorer/index.html /usr/share/nginx/html
+COPY ../explorer/explorer.html /usr/share/nginx/html
 COPY ../explorer/main.js /usr/share/nginx/html
 
 # Expose port 80 for web traffic
diff --git a/explorer/index.html b/explorer/explorer.html
similarity index 100%
rename from explorer/index.html
rename to explorer/explorer.html

From 6cd8d77782c75e50c021471a11fbd78ec3b6e2d8 Mon Sep 17 00:00:00 2001
From: DhananjayPurohit 
Date: Tue, 16 Apr 2024 13:41:57 +0530
Subject: [PATCH 26/66] fix: rename explorer.html to index.html

---
 explorer/Dockerfile                    | 2 +-
 explorer/{explorer.html => index.html} | 0
 2 files changed, 1 insertion(+), 1 deletion(-)
 rename explorer/{explorer.html => index.html} (100%)

diff --git a/explorer/Dockerfile b/explorer/Dockerfile
index 75114600..552d8872 100644
--- a/explorer/Dockerfile
+++ b/explorer/Dockerfile
@@ -2,7 +2,7 @@
 FROM nginx:latest
 
 # Copy the contents of your local /explorer folder to the container's working directory
-COPY ../explorer/explorer.html /usr/share/nginx/html
+COPY ../explorer/index.html /usr/share/nginx/html
 COPY ../explorer/main.js /usr/share/nginx/html
 
 # Expose port 80 for web traffic
diff --git a/explorer/explorer.html b/explorer/index.html
similarity index 100%
rename from explorer/explorer.html
rename to explorer/index.html

From 67ac1e5e7a2b11d1e26736c2c1584af4fd8f7ff1 Mon Sep 17 00:00:00 2001
From: DhananjayPurohit 
Date: Tue, 16 Apr 2024 14:40:26 +0530
Subject: [PATCH 27/66] feat: configure nginx.conf

---
 explorer/Dockerfile |  1 +
 explorer/nginx.conf | 13 +++++++++++++
 2 files changed, 14 insertions(+)
 create mode 100644 explorer/nginx.conf

diff --git a/explorer/Dockerfile b/explorer/Dockerfile
index 552d8872..f53e7f16 100644
--- a/explorer/Dockerfile
+++ b/explorer/Dockerfile
@@ -4,6 +4,7 @@ FROM nginx:latest
 # Copy the contents of your local /explorer folder to the container's working directory
 COPY ../explorer/index.html /usr/share/nginx/html
 COPY ../explorer/main.js /usr/share/nginx/html
+COPY ../explorer/nginx.conf /etc/nginx/nginx.conf
 
 # Expose port 80 for web traffic
 EXPOSE 80
diff --git a/explorer/nginx.conf b/explorer/nginx.conf
new file mode 100644
index 00000000..3d7a676d
--- /dev/null
+++ b/explorer/nginx.conf
@@ -0,0 +1,13 @@
+http {
+
+    server {
+        listen 0.0.0.0:80;
+        server_name api.mercurywallet.io;
+
+        location / {
+            root /var/www/html;
+            index index.html;
+            try_files $uri $uri/ =404;
+        }
+    }
+}

From d5728bcb7986eb5a61330f5d7f79a3da13d601ee Mon Sep 17 00:00:00 2001
From: DhananjayPurohit 
Date: Tue, 16 Apr 2024 14:49:47 +0530
Subject: [PATCH 28/66] fix: nginx.conf

---
 explorer/nginx.conf | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/explorer/nginx.conf b/explorer/nginx.conf
index 3d7a676d..11e28c20 100644
--- a/explorer/nginx.conf
+++ b/explorer/nginx.conf
@@ -1,3 +1,13 @@
+user  nginx;
+worker_processes  auto;
+
+error_log  /var/log/nginx/error.log notice;
+pid        /var/run/nginx.pid;
+
+events {
+    worker_connections  1024;
+}
+
 http {
 
     server {

From 732d98b227259820f08d9814fc492097fd6f1907 Mon Sep 17 00:00:00 2001
From: DhananjayPurohit 
Date: Tue, 16 Apr 2024 15:01:45 +0530
Subject: [PATCH 29/66] fix: root path for nginx.conf

---
 explorer/nginx.conf | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/explorer/nginx.conf b/explorer/nginx.conf
index 11e28c20..ba09169f 100644
--- a/explorer/nginx.conf
+++ b/explorer/nginx.conf
@@ -15,7 +15,7 @@ http {
         server_name api.mercurywallet.io;
 
         location / {
-            root /var/www/html;
+            root /usr/share/nginx/html;
             index index.html;
             try_files $uri $uri/ =404;
         }

From 9bddce55ca69ee853e31addf3cc122f748d9a1f0 Mon Sep 17 00:00:00 2001
From: DhananjayPurohit 
Date: Wed, 17 Apr 2024 21:53:02 +0530
Subject: [PATCH 30/66] feat: add dockerfile and script for keylist cronjob

---
 .github/workflows/ci.yaml      | 14 +++++++++---
 keylistCron/Dockerfile         |  9 ++++++++
 keylistCron/crontab.txt        |  1 +
 keylistCron/send_commitment.sh | 39 ++++++++++++++++++++++++++++++++++
 4 files changed, 60 insertions(+), 3 deletions(-)
 create mode 100644 keylistCron/Dockerfile
 create mode 100644 keylistCron/crontab.txt
 create mode 100644 keylistCron/send_commitment.sh

diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml
index 93727452..b7e30758 100644
--- a/.github/workflows/ci.yaml
+++ b/.github/workflows/ci.yaml
@@ -25,7 +25,7 @@ jobs:
           name: Set up Docker Buildx
           uses: docker/setup-buildx-action@v3
         -
-          name: Build and push
+          name: Build and push for mercury-server
           uses: docker/build-push-action@v5
           with:
             context: .
@@ -33,7 +33,7 @@ jobs:
             push: true
             tags: commerceblockx/mercury-server:latest
         -
-          name: Build and push
+          name: Build and push for token-server
           uses: docker/build-push-action@v5
           with:
             context: .
@@ -41,10 +41,18 @@ jobs:
             push: true
             tags: commerceblockx/token-server:latest
         -
-          name: Build and push
+          name: Build and push for mercury-explorer
           uses: docker/build-push-action@v5
           with:
             context: .
             file: ./explorer/Dockerfile
             push: true
             tags: commerceblockx/mercury-explorer:latest
+        -
+          name: Build and push for keylist-cronjob
+          uses: docker/build-push-action@v5
+          with:
+            context: .
+            file: ./keylistCron/Dockerfile
+            push: true
+            tags: commerceblockx/keylist-cronjob:latest
diff --git a/keylistCron/Dockerfile b/keylistCron/Dockerfile
new file mode 100644
index 00000000..32ecfed4
--- /dev/null
+++ b/keylistCron/Dockerfile
@@ -0,0 +1,9 @@
+FROM alpine:latest
+
+WORKDIR /app
+
+COPY ../keylistCron/send_commitment.sh .
+COPY ../keylistCron/crontab.txt .
+
+# CMD to run cron and keep container running
+CMD ["sh", "-c", "crontab ./crontab.txt && tail -f /dev/null"]
diff --git a/keylistCron/crontab.txt b/keylistCron/crontab.txt
new file mode 100644
index 00000000..ccff9d6e
--- /dev/null
+++ b/keylistCron/crontab.txt
@@ -0,0 +1 @@
+0 0 * * * /app/send_commitment.sh
diff --git a/keylistCron/send_commitment.sh b/keylistCron/send_commitment.sh
new file mode 100644
index 00000000..ceb899ae
--- /dev/null
+++ b/keylistCron/send_commitment.sh
@@ -0,0 +1,39 @@
+#!/bin/bash
+
+# Fetch keylist JSON from the provided URL
+KEYLIST_URL="https://api.mercurywallet.io/info/keylist"
+KEYLIST_JSON=$(curl -sSL "$KEYLIST_URL")
+
+# Check if the GET request was successful
+if [[ $? -ne 0 ]]; then
+  echo "Error: Failed to retrieve keylist JSON from $KEYLIST_URL"
+  exit 1
+fi
+
+# Calculate SHA256 hash of the keylist JSON
+KEYLIST_HASH=$(echo "$KEYLIST_JSON" | sha256sum | awk '{print $1}')
+
+# Define mainstay slot URL
+MAINSTAY_URL="https://testnet.mainstay.xyz/ctrl/sendcommitment"
+
+# Attestation data
+POSITION="3"
+TOKEN="0972e199-6cf8-4164-8445-235528b6afa5"
+
+# Construct the POST request body
+PAYLOAD="{
+  \"position\": \"$POSITION\",
+  \"token\": \"$TOKEN\",
+  \"commitment\": \"$KEYLIST_HASH\"
+}"
+
+# Send POST request to mainstay slot
+curl --header "Content-Type: application/json" --request POST --data "$PAYLOAD" "$MAINSTAY_URL"
+
+# Check if the POST request was successful
+if [[ $? -ne 0 ]]; then
+  echo "Error: Failed to send attestation data to $MAINSTAY_URL"
+  exit 1
+fi
+
+echo "Keylist $KEYLIST_HASH attestation completed successfully!"

From 85a155e9ebded3a9bbbcdb63b09e9ec1ce0710a1 Mon Sep 17 00:00:00 2001
From: "S. Santos" 
Date: Wed, 17 Apr 2024 23:02:35 -0300
Subject: [PATCH 31/66] Add docker files to the enclave - HW mode

---
 Usage.md                          | 24 ++++++++
 docker-compose.yml                |  2 -
 enclave/Dockerfiles/HW/Dockerfile | 94 +++++++++++++++++++++++++++++++
 3 files changed, 118 insertions(+), 2 deletions(-)
 create mode 100644 Usage.md
 create mode 100644 enclave/Dockerfiles/HW/Dockerfile

diff --git a/Usage.md b/Usage.md
new file mode 100644
index 00000000..03881cef
--- /dev/null
+++ b/Usage.md
@@ -0,0 +1,24 @@
+# Usage
+
+## Simulation mode
+
+### Bulid and run docker containers
+
+```bash
+$ cd mercurylayer
+$ docker compose build
+$ docker compose up
+```
+### Add mmnemonics
+
+```bash
+$ docker exec -it mercurylayer-enclave-sgx bash
+$ curl -X POST http://0.0.0.0:18080/add_mnemonic \
+-H "Content-Type: application/json" \
+-d '{
+    "mnemonic": "achieve merry hidden lyrics element brand student armed dismiss vague fury avocado grief crazy garlic gallery blur spider bag bless motor crawl surround copper",
+    "password": "b1gHKyfXTzs6",
+    "index": 0,
+    "threshold": 2
+}'
+```
\ No newline at end of file
diff --git a/docker-compose.yml b/docker-compose.yml
index bf09ac3a..eef4fa71 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -9,8 +9,6 @@ services:
       - db_enclave
     environment:
       - ENCLAVE_DATABASE_URL=postgres://postgres:postgres@db_enclave:5432/enclave
-    ports:
-      - "18080:18080"
 
   mercury-server:
     build:
diff --git a/enclave/Dockerfiles/HW/Dockerfile b/enclave/Dockerfiles/HW/Dockerfile
new file mode 100644
index 00000000..d3608dc8
--- /dev/null
+++ b/enclave/Dockerfiles/HW/Dockerfile
@@ -0,0 +1,94 @@
+FROM ubuntu:22.04 as sgxbase
+RUN apt-get update && apt-get install -y \
+    gnupg \
+    wget
+
+RUN echo 'deb [arch=amd64] https://download.01.org/intel-sgx/sgx_repo/ubuntu jammy main' > /etc/apt/sources.list.d/intel-sgx.list
+RUN wget -qO - https://download.01.org/intel-sgx/sgx_repo/ubuntu/intel-sgx-deb.key | apt-key add -
+RUN apt-get update 
+
+FROM sgxbase as sgx_sample_builder
+# App build time dependencies
+RUN apt-get install -y build-essential libpq-dev clang git cmake
+
+WORKDIR /opt/intel
+RUN wget https://download.01.org/intel-sgx/sgx-linux/2.23/distro/ubuntu22.04-server/sgx_linux_x64_sdk_2.23.100.2.bin
+RUN chmod +x sgx_linux_x64_sdk_2.23.100.2.bin
+RUN echo 'yes' | ./sgx_linux_x64_sdk_2.23.100.2.bin
+
+# Add SSS dependencies
+RUN git clone https://github.com/jtv/libpqxx.git && cd libpqxx && git checkout 7.8.1 && \
+    cd cmake && cmake .. && cmake --build . && cmake --install .
+
+# RUN git clone https://github.com/libcpr/cpr.git \
+#     && mkdir cpr/build \
+#     && cd cpr/build \
+#     && cmake .. -DCPR_USE_SYSTEM_CURL=ON \
+#     && cmake --build . \
+#     && cmake --install .
+
+RUN git clone https://github.com/libcpr/cpr.git
+
+RUN cd cpr && git checkout 1.10.5
+
+RUN cd cpr && mkdir build && cd build && cmake .. -DCPR_USE_SYSTEM_CURL=ON
+
+RUN cd cpr/build && cmake --build .
+
+RUN cd cpr/build && cmake --install .
+
+RUN ldconfig
+
+RUN git clone https://github.com/ssantos21/bc-crypto-base.git && cd bc-crypto-base && \
+    ./configure && make && make install
+
+RUN git clone https://github.com/ssantos21/bc-shamir.git && cd bc-shamir && \
+    ./configure && make && make install
+
+RUN git clone https://github.com/ssantos21/bc-bip39.git && cd bc-bip39 && \
+    export CC="clang-14" && ./configure && make && make install
+
+RUN rm sgx_linux_x64_sdk_2.23.100.2.bin && rm -rf libpqxx bc-crypto-base bc-shamir bc-bip39 cpr
+
+COPY . /home/lockbox-sgx
+
+WORKDIR /home/lockbox-sgx
+
+RUN rm -rf Dockerfiles
+
+RUN SGX_DEBUG=0 SGX_MODE=HW SGX_PRERELEASE=1 INCLUDE_SECP256K1_ZKP=1 make
+
+FROM sgxbase as sample
+RUN apt-get install -y \
+    libcurl4 \
+    libprotobuf-dev \
+    libssl-dev \
+    libpq-dev
+
+# No AESM daemon, only AESM client side API support for launch.
+# For applications requiring attestation, add libsgx-quote-ex
+RUN apt-get install -y --no-install-recommends libsgx-launch libsgx-urts
+
+COPY --from=sgx_sample_builder /lockbox-sgx/app lockbox-sgx-app
+COPY --from=sgx_sample_builder /lockbox-sgx/enclave.signed.so .
+
+RUN adduser -q --disabled-password --gecos "" --no-create-home sgxuser
+USER sgxuser
+
+ENTRYPOINT ["/lockbox-sgx-app"]
+
+FROM sgxbase as aesm 
+RUN apt-get install -y \
+    libcurl4 \
+    libprotobuf-dev \
+    libssl-dev \
+    make \
+    kmod
+
+# More aesm plugins, e.g libsgx-aesm-quote-ex-plugin, are needed if application requires attestation. See installation guide.
+RUN apt-get install -y libsgx-aesm-launch-plugin
+
+WORKDIR /opt/intel/sgx-aesm-service/aesm
+ENV LD_LIBRARY_PATH=.
+CMD ./aesm_service --no-daemon
+

From cd8470bbf168c79d4947167a6bba2e3979bdcd36 Mon Sep 17 00:00:00 2001
From: "S. Santos" 
Date: Thu, 18 Apr 2024 01:13:50 -0300
Subject: [PATCH 32/66] Add docker files to the enclave - HW mode

---
 Usage.md                                     |  5 +-
 build_compose_hw_run.sh                      |  5 ++
 docker-compose-hw.yml                        | 74 ++++++++++++++++++++
 docker-compose.yml => docker-compose-sim.yml |  0
 4 files changed, 81 insertions(+), 3 deletions(-)
 create mode 100644 build_compose_hw_run.sh
 create mode 100644 docker-compose-hw.yml
 rename docker-compose.yml => docker-compose-sim.yml (100%)

diff --git a/Usage.md b/Usage.md
index 03881cef..9455e68c 100644
--- a/Usage.md
+++ b/Usage.md
@@ -6,13 +6,12 @@
 
 ```bash
 $ cd mercurylayer
-$ docker compose build
-$ docker compose up
+$ docker compose -f docker-compose-sim.yml up --build
 ```
 ### Add mmnemonics
 
 ```bash
-$ docker exec -it mercurylayer-enclave-sgx bash
+$ docker exec -it mercurylayer-enclave-sgx-1 bash
 $ curl -X POST http://0.0.0.0:18080/add_mnemonic \
 -H "Content-Type: application/json" \
 -d '{
diff --git a/build_compose_hw_run.sh b/build_compose_hw_run.sh
new file mode 100644
index 00000000..ad45db12
--- /dev/null
+++ b/build_compose_hw_run.sh
@@ -0,0 +1,5 @@
+set -e
+
+docker volume create --driver local --opt type=tmpfs --opt device=tmpfs --opt o=rw aesmd-socket
+
+docker compose -f docker-compose-hw.yml up --build
diff --git a/docker-compose-hw.yml b/docker-compose-hw.yml
new file mode 100644
index 00000000..9f6b5860
--- /dev/null
+++ b/docker-compose-hw.yml
@@ -0,0 +1,74 @@
+version: '3.8'
+
+services:
+  aesm:
+    build:
+      context: enclave
+      dockerfile: Dockerfiles/HW/Dockerfile
+      target: aesm
+    image: sgx_aesm
+    devices:
+      - /dev/isgx
+    volumes:
+      - aesmd-socket:/var/run/aesmd
+    stdin_open: true
+    tty: true
+
+  enclave-sgx:
+    build:
+      context: enclave
+      dockerfile: Dockerfiles/HW/Dockerfile
+    depends_on:
+      - aesm
+      - db_enclave
+    environment:
+      - ENCLAVE_DATABASE_URL=postgres://postgres:postgres@db_enclave:5432/enclave
+    devices:
+      - /dev/isgx
+    volumes:
+      - aesmd-socket:/var/run/aesmd
+    stdin_open: true
+    tty: true
+
+  mercury-server:
+    build:
+      context: .
+      dockerfile: server/Dockerfile
+    depends_on:
+      - db_server
+    environment:
+      - LOCKBOX_URL=http://enclave-sgx:18080
+      - BITCOIN_NETWORK=testnet
+      - LOCKHEIGHT_INIT=1000
+      - LH_DECREMENT=10
+      - DATABASE_CONNECTION_STRING=postgres://postgres:postgres@db_server:5432/mercury
+    ports:
+      - "8000:8000"
+
+  db_enclave:
+    image: postgres:16.2
+    environment:
+      POSTGRES_PASSWORD: postgres
+      POSTGRES_DB: enclave
+    ports:
+      - "5433:5432"
+    volumes:
+      - postgres_enclave_data:/var/lib/postgresql/data
+
+  db_server:
+    image: postgres:16.2
+    environment:
+      POSTGRES_PASSWORD: postgres
+      POSTGRES_DB: mercury
+    ports:
+      - "5432:5432"
+    volumes:
+      - postgres_server_data:/var/lib/postgresql/data
+
+
+volumes:
+  aesmd-socket:
+    external: true
+  postgres_enclave_data:
+  postgres_server_data:
+
diff --git a/docker-compose.yml b/docker-compose-sim.yml
similarity index 100%
rename from docker-compose.yml
rename to docker-compose-sim.yml

From ad630756f08208c0cd16cb7ba793983e21739013 Mon Sep 17 00:00:00 2001
From: "S. Santos" 
Date: Thu, 18 Apr 2024 01:36:44 -0300
Subject: [PATCH 33/66] Add docker files to the enclave - HW mode

---
 docker-compose-hw.yml | 1 +
 1 file changed, 1 insertion(+)

diff --git a/docker-compose-hw.yml b/docker-compose-hw.yml
index 9f6b5860..5c804d86 100644
--- a/docker-compose-hw.yml
+++ b/docker-compose-hw.yml
@@ -18,6 +18,7 @@ services:
     build:
       context: enclave
       dockerfile: Dockerfiles/HW/Dockerfile
+      target: sample
     depends_on:
       - aesm
       - db_enclave

From 9db60625708686b4f3b174d62472a675342fa72c Mon Sep 17 00:00:00 2001
From: "S. Santos" 
Date: Thu, 18 Apr 2024 01:39:09 -0300
Subject: [PATCH 34/66] Add docker files to the enclave - HW mode

---
 build_compose_hw_run.sh | 0
 1 file changed, 0 insertions(+), 0 deletions(-)
 mode change 100644 => 100755 build_compose_hw_run.sh

diff --git a/build_compose_hw_run.sh b/build_compose_hw_run.sh
old mode 100644
new mode 100755

From dfb55fdb95c91ef0708a2dfdb58acbe47710f67e Mon Sep 17 00:00:00 2001
From: "S. Santos" 
Date: Thu, 18 Apr 2024 03:13:19 -0300
Subject: [PATCH 35/66] Add docker files to the enclave - HW mode

---
 clients/rust/rust-toolchain.toml  | 2 ++
 enclave/Dockerfiles/HW/Dockerfile | 8 ++++----
 server/rust-toolchain.toml        | 2 ++
 3 files changed, 8 insertions(+), 4 deletions(-)
 create mode 100644 clients/rust/rust-toolchain.toml
 create mode 100644 server/rust-toolchain.toml

diff --git a/clients/rust/rust-toolchain.toml b/clients/rust/rust-toolchain.toml
new file mode 100644
index 00000000..1a4239ae
--- /dev/null
+++ b/clients/rust/rust-toolchain.toml
@@ -0,0 +1,2 @@
+[toolchain]
+channel = "1.76.0"
\ No newline at end of file
diff --git a/enclave/Dockerfiles/HW/Dockerfile b/enclave/Dockerfiles/HW/Dockerfile
index d3608dc8..2b580fdc 100644
--- a/enclave/Dockerfiles/HW/Dockerfile
+++ b/enclave/Dockerfiles/HW/Dockerfile
@@ -9,7 +9,7 @@ RUN apt-get update
 
 FROM sgxbase as sgx_sample_builder
 # App build time dependencies
-RUN apt-get install -y build-essential libpq-dev clang git cmake
+RUN apt-get install -y build-essential libpq-dev clang git cmake libcurl4-openssl-dev autoconf libtool libboost-dev libboost-system-dev libboost-thread-dev
 
 WORKDIR /opt/intel
 RUN wget https://download.01.org/intel-sgx/sgx-linux/2.23/distro/ubuntu22.04-server/sgx_linux_x64_sdk_2.23.100.2.bin
@@ -67,10 +67,10 @@ RUN apt-get install -y \
 
 # No AESM daemon, only AESM client side API support for launch.
 # For applications requiring attestation, add libsgx-quote-ex
-RUN apt-get install -y --no-install-recommends libsgx-launch libsgx-urts
+RUN apt-get install -y --no-install-recommends libsgx-launch libsgx-urts curl
 
-COPY --from=sgx_sample_builder /lockbox-sgx/app lockbox-sgx-app
-COPY --from=sgx_sample_builder /lockbox-sgx/enclave.signed.so .
+COPY --from=sgx_sample_builder /home/lockbox-sgx/app lockbox-sgx-app
+COPY --from=sgx_sample_builder /home/lockbox-sgx/enclave.signed.so .
 
 RUN adduser -q --disabled-password --gecos "" --no-create-home sgxuser
 USER sgxuser
diff --git a/server/rust-toolchain.toml b/server/rust-toolchain.toml
new file mode 100644
index 00000000..1a4239ae
--- /dev/null
+++ b/server/rust-toolchain.toml
@@ -0,0 +1,2 @@
+[toolchain]
+channel = "1.76.0"
\ No newline at end of file

From eae1e4db7c787209bcd38dc794c7727aa4cfcb5e Mon Sep 17 00:00:00 2001
From: DhananjayPurohit 
Date: Thu, 18 Apr 2024 18:04:49 +0530
Subject: [PATCH 36/66] fix: mercury server build failure

---
 server/src/server_config.rs | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/server/src/server_config.rs b/server/src/server_config.rs
index bac5462a..da96c701 100644
--- a/server/src/server_config.rs
+++ b/server/src/server_config.rs
@@ -52,6 +52,11 @@ impl ServerConfig {
         // Override with settings in file Rocket.toml if exists
         conf_rs.merge(File::with_name("Rocket").required(false));
 
+        let settings = ConfigRs::builder()
+            .add_source(File::with_name("Settings"))
+            .build()
+            .unwrap();
+
         // Function to fetch a setting from the environment or fallback to the config file
         let get_env_or_config = |key: &str, env_var: &str| -> String {
             env::var(env_var).unwrap_or_else(|_| settings.get_string(key).unwrap())
@@ -63,7 +68,7 @@ impl ServerConfig {
             lockheight_init: get_env_or_config("lockheight_init", "LOCKHEIGHT_INIT").parse::().unwrap(),
             lh_decrement: get_env_or_config("lh_decrement", "LH_DECREMENT").parse::().unwrap(),
             connection_string: get_env_or_config("connection_string", "DATABASE_CONNECTION_STRING"),
-        }
+        };
         conf_rs.try_into().unwrap()
     }
 }
\ No newline at end of file

From 3dfaab370ae5fd19b03f8550e0a7e86f2f1c3d01 Mon Sep 17 00:00:00 2001
From: DhananjayPurohit 
Date: Fri, 19 Apr 2024 19:11:01 +0530
Subject: [PATCH 37/66] fix: file permission in dockerfile for cron

---
 keylistCron/Dockerfile | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/keylistCron/Dockerfile b/keylistCron/Dockerfile
index 32ecfed4..cdf04e3f 100644
--- a/keylistCron/Dockerfile
+++ b/keylistCron/Dockerfile
@@ -5,5 +5,7 @@ WORKDIR /app
 COPY ../keylistCron/send_commitment.sh .
 COPY ../keylistCron/crontab.txt .
 
+RUN chmod +x /app/send_commitment.sh
+
 # CMD to run cron and keep container running
 CMD ["sh", "-c", "crontab ./crontab.txt && tail -f /dev/null"]

From 199cea3ec9a572df6f225240461cd33c2243b01f Mon Sep 17 00:00:00 2001
From: DhananjayPurohit 
Date: Fri, 19 Apr 2024 23:39:36 +0530
Subject: [PATCH 38/66] fix: dockerfile for cronjob

---
 keylistCron/Dockerfile | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/keylistCron/Dockerfile b/keylistCron/Dockerfile
index cdf04e3f..de0e4acc 100644
--- a/keylistCron/Dockerfile
+++ b/keylistCron/Dockerfile
@@ -1,11 +1,11 @@
 FROM alpine:latest
 
+RUN apk update && apk add --no-cache curl
 WORKDIR /app
 
-COPY ../keylistCron/send_commitment.sh .
-COPY ../keylistCron/crontab.txt .
+COPY ./send_commitment.sh .
 
 RUN chmod +x /app/send_commitment.sh
 
 # CMD to run cron and keep container running
-CMD ["sh", "-c", "crontab ./crontab.txt && tail -f /dev/null"]
+CMD ["sh", "send_commitment.sh"]

From 338930327d7fe48104a5c0f94d9a8fc09115e154 Mon Sep 17 00:00:00 2001
From: DhananjayPurohit 
Date: Fri, 19 Apr 2024 23:51:59 +0530
Subject: [PATCH 39/66] fix: path in cronjob dockerfile

---
 keylistCron/Dockerfile | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/keylistCron/Dockerfile b/keylistCron/Dockerfile
index de0e4acc..4617198a 100644
--- a/keylistCron/Dockerfile
+++ b/keylistCron/Dockerfile
@@ -3,7 +3,7 @@ FROM alpine:latest
 RUN apk update && apk add --no-cache curl
 WORKDIR /app
 
-COPY ./send_commitment.sh .
+COPY ../keylistCron/send_commitment.sh .
 
 RUN chmod +x /app/send_commitment.sh
 

From baf1924f753f43da6e8d4499bd387da1dfc2e8e6 Mon Sep 17 00:00:00 2001
From: DhananjayPurohit 
Date: Mon, 22 Apr 2024 12:49:08 +0530
Subject: [PATCH 40/66] fix: keylist url

---
 keylistCron/send_commitment.sh | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/keylistCron/send_commitment.sh b/keylistCron/send_commitment.sh
index ceb899ae..c067cb37 100644
--- a/keylistCron/send_commitment.sh
+++ b/keylistCron/send_commitment.sh
@@ -1,7 +1,7 @@
 #!/bin/bash
 
 # Fetch keylist JSON from the provided URL
-KEYLIST_URL="https://api.mercurywallet.io/info/keylist"
+KEYLIST_URL="http://45.77.225.72:32450/info/keylist"
 KEYLIST_JSON=$(curl -sSL "$KEYLIST_URL")
 
 # Check if the GET request was successful

From 55db5eaf7ed8543235ba23d9e2b82feedbac0a25 Mon Sep 17 00:00:00 2001
From: DhananjayPurohit 
Date: Mon, 22 Apr 2024 17:07:12 +0530
Subject: [PATCH 41/66] fix: add sql connection for saving keylist

---
 keylistCron/Dockerfile         |  2 +-
 keylistCron/send_commitment.sh | 14 ++++++++++++++
 2 files changed, 15 insertions(+), 1 deletion(-)

diff --git a/keylistCron/Dockerfile b/keylistCron/Dockerfile
index 4617198a..d1c5089f 100644
--- a/keylistCron/Dockerfile
+++ b/keylistCron/Dockerfile
@@ -1,6 +1,6 @@
 FROM alpine:latest
 
-RUN apk update && apk add --no-cache curl
+RUN apk update && apk add --no-cache curl postgresql-client
 WORKDIR /app
 
 COPY ../keylistCron/send_commitment.sh .
diff --git a/keylistCron/send_commitment.sh b/keylistCron/send_commitment.sh
index c067cb37..922b355b 100644
--- a/keylistCron/send_commitment.sh
+++ b/keylistCron/send_commitment.sh
@@ -37,3 +37,17 @@ if [[ $? -ne 0 ]]; then
 fi
 
 echo "Keylist $KEYLIST_HASH attestation completed successfully!"
+
+# Connect to the database and save the keylist JSON
+PG_COMMAND="psql -h $DB_HOST -p $DB_PORT -d $DB_NAME -U $DB_USER -c \"INSERT INTO keylist (json_data) VALUES ('$KEYLIST_JSON');\""
+
+# Execute the PostgreSQL command
+eval "$PG_COMMAND"
+
+# Check if the command was successful
+if [[ $? -ne 0 ]]; then
+  echo "Error: Failed to save keylist JSON to the database"
+  exit 1
+fi
+
+echo "Keylist JSON saved to the database successfully!"

From ed2a5a1c263f8ee30948a49afc9271517010e106 Mon Sep 17 00:00:00 2001
From: DhananjayPurohit 
Date: Wed, 24 Apr 2024 17:09:08 +0530
Subject: [PATCH 42/66] fix: merge conflicts

---
 .github/workflows/ci.yaml      |  6 ++++++
 keylistCron/Dockerfile         |  2 +-
 keylistCron/send_commitment.sh | 11 ++++++++---
 3 files changed, 15 insertions(+), 4 deletions(-)

diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml
index b7e30758..81320a2a 100644
--- a/.github/workflows/ci.yaml
+++ b/.github/workflows/ci.yaml
@@ -56,3 +56,9 @@ jobs:
             file: ./keylistCron/Dockerfile
             push: true
             tags: commerceblockx/keylist-cronjob:latest
+          env:
+            DB_HOST: ${{ secrets.DB_HOST }}
+            DB_PORT: ${{ secrets.DB_PORT }}
+            DB_NAME: ${{ secrets.DB_NAME }}
+            DB_USER: ${{ secrets.DB_USER }}
+            DB_PASSWORD: ${{ secrets.DB_PASSWORD }}
diff --git a/keylistCron/Dockerfile b/keylistCron/Dockerfile
index d1c5089f..1bf53ecd 100644
--- a/keylistCron/Dockerfile
+++ b/keylistCron/Dockerfile
@@ -1,6 +1,6 @@
 FROM alpine:latest
 
-RUN apk update && apk add --no-cache curl postgresql-client
+RUN apk update && apk add --no-cache curl postgresql-client jq
 WORKDIR /app
 
 COPY ../keylistCron/send_commitment.sh .
diff --git a/keylistCron/send_commitment.sh b/keylistCron/send_commitment.sh
index 922b355b..2f097ae6 100644
--- a/keylistCron/send_commitment.sh
+++ b/keylistCron/send_commitment.sh
@@ -1,8 +1,8 @@
 #!/bin/bash
 
 # Fetch keylist JSON from the provided URL
-KEYLIST_URL="http://45.77.225.72:32450/info/keylist"
-KEYLIST_JSON=$(curl -sSL "$KEYLIST_URL")
+KEYLIST_URL="https://api.mercurywallet.io/info/keylist"
+KEYLIST_JSON=$(curl -sSL "$KEYLIST_URL" | jq -r '.list_keyinfo')
 
 # Check if the GET request was successful
 if [[ $? -ne 0 ]]; then
@@ -39,7 +39,12 @@ fi
 echo "Keylist $KEYLIST_HASH attestation completed successfully!"
 
 # Connect to the database and save the keylist JSON
-PG_COMMAND="psql -h $DB_HOST -p $DB_PORT -d $DB_NAME -U $DB_USER -c \"INSERT INTO keylist (json_data) VALUES ('$KEYLIST_JSON');\""
+PG_COMMAND="PGPASSWORD=\"$DB_PASSWORD\" psql -h $DB_HOST -p $DB_PORT -d $DB_NAME -U $DB_USER -c \"
+    CREATE TABLE IF NOT EXISTS keylist_info (
+      json_data json NOT NULL
+    );
+    INSERT INTO keylist_info (json_data) VALUES ('$KEYLIST_JSON');
+  \""
 
 # Execute the PostgreSQL command
 eval "$PG_COMMAND"

From 6052254ec875fc40cb3b97de0edf3f814c4172c7 Mon Sep 17 00:00:00 2001
From: DhananjayPurohit 
Date: Wed, 24 Apr 2024 22:07:44 +0530
Subject: [PATCH 43/66] fix: merge conflicts with cargo.lock

---
 Cargo.lock | 59 ++++++++++++++++++++----------------------------------
 1 file changed, 22 insertions(+), 37 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock
index bbc02a3c..e4f7c9b4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -526,15 +526,9 @@ checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
 
 [[package]]
 name = "cookie"
-<<<<<<< HEAD
-version = "0.18.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3cd91cf61412820176e137621345ee43b3f4423e589e7ae4e50d601d93e35ef8"
-=======
 version = "0.18.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747"
->>>>>>> d9d56ba672fd8ea638c9e8a20e155efa8b5a8bbc
 dependencies = [
  "percent-encoding",
  "time",
@@ -1235,27 +1229,10 @@ dependencies = [
 name = "indexmap"
 version = "2.2.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-<<<<<<< HEAD
 checksum = "7b0b929d511467233429c45a44ac1dcaa21ba0f5ba11e4879e6ed28ddb4f9df4"
 dependencies = [
  "equivalent",
  "hashbrown 0.14.3",
-=======
-checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"
-dependencies = [
- "autocfg",
- "hashbrown 0.12.3",
-]
-
-[[package]]
-name = "indexmap"
-version = "2.0.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8adf3ddd720272c6ea8bf59463c04e0f93d0bbf7c5439b691bca2987e0270897"
-dependencies = [
- "equivalent",
- "hashbrown 0.14.1",
->>>>>>> d9d56ba672fd8ea638c9e8a20e155efa8b5a8bbc
  "serde",
 ]
 
@@ -2185,11 +2162,7 @@ dependencies = [
  "either",
  "figment",
  "futures",
-<<<<<<< HEAD
  "indexmap",
-=======
- "indexmap 2.0.2",
->>>>>>> d9d56ba672fd8ea638c9e8a20e155efa8b5a8bbc
  "log",
  "memchr",
  "multer",
@@ -2221,11 +2194,7 @@ checksum = "a2238066abf75f21be6cd7dc1a09d5414a671f4246e384e49fe3f8a4936bd04c"
 dependencies = [
  "devise",
  "glob",
-<<<<<<< HEAD
  "indexmap",
-=======
- "indexmap 2.0.2",
->>>>>>> d9d56ba672fd8ea638c9e8a20e155efa8b5a8bbc
  "proc-macro2",
  "quote",
  "rocket_http",
@@ -2245,11 +2214,7 @@ dependencies = [
  "futures",
  "http",
  "hyper",
-<<<<<<< HEAD
  "indexmap",
-=======
- "indexmap 2.0.2",
->>>>>>> d9d56ba672fd8ea638c9e8a20e155efa8b5a8bbc
  "log",
  "memchr",
  "pear",
@@ -3765,13 +3730,33 @@ dependencies = [
 
 [[package]]
 name = "yansi"
-version = "1.0.0-rc.1"
+version = "1.0.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1367295b8f788d371ce2dbc842c7b709c73ee1364d30351dd300ec2203b12377"
+checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049"
 dependencies = [
  "is-terminal",
 ]
 
+[[package]]
+name = "zerocopy"
+version = "0.7.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "74d4d3961e53fa4c9a25a8637fc2bfaf2595b3d3ae34875568a5cf64787716be"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.7.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.53",
+]
+
 [[package]]
 name = "zeroize"
 version = "1.7.0"

From f13e4c0bbac078d4a522cd37475725eaf72dfa12 Mon Sep 17 00:00:00 2001
From: DhananjayPurohit 
Date: Fri, 26 Apr 2024 08:31:27 +0530
Subject: [PATCH 44/66] fix: cargo.lock and remove blind_commitment field

---
 Cargo.lock                                    | 326 +++++++++---------
 .../standalone-rust/src/transfer_receiver.rs  |   8 -
 2 files changed, 171 insertions(+), 163 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock
index e4f7c9b4..6e7ea74f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -87,9 +87,9 @@ dependencies = [
 
 [[package]]
 name = "allocator-api2"
-version = "0.2.16"
+version = "0.2.18"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5"
+checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f"
 
 [[package]]
 name = "android-tzdata"
@@ -156,9 +156,9 @@ dependencies = [
 
 [[package]]
 name = "anyhow"
-version = "1.0.81"
+version = "1.0.82"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0952808a6c2afd1aa8947271f3a60f1a6763c7b912d210184c5149b5cf147247"
+checksum = "f538837af36e6f6a9be0faa67f9a314f8119e4e4b5867c6ab40ed60360142519"
 
 [[package]]
 name = "arrayref"
@@ -185,18 +185,18 @@ checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193"
 dependencies = [
  "proc-macro2",
  "quote",
- "syn 2.0.53",
+ "syn 2.0.60",
 ]
 
 [[package]]
 name = "async-trait"
-version = "0.1.78"
+version = "0.1.80"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "461abc97219de0eaaf81fe3ef974a540158f3d079c2ab200f891f1a2ef201e85"
+checksum = "c6fa2087f2753a7da8cc1c0dbfcf89579dd57458e36769de5ac750b4671737ca"
 dependencies = [
  "proc-macro2",
  "quote",
- "syn 2.0.53",
+ "syn 2.0.60",
 ]
 
 [[package]]
@@ -225,15 +225,15 @@ dependencies = [
 
 [[package]]
 name = "autocfg"
-version = "1.1.0"
+version = "1.2.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
+checksum = "f1fdabc7756949593fe60f30ec81974b613357de856987752631dea1e3394c80"
 
 [[package]]
 name = "backtrace"
-version = "0.3.69"
+version = "0.3.71"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2089b7e3f35b9dd2d0ed921ead4f6d318c27680d4a5bd167b3ee120edb105837"
+checksum = "26b05800d2e817c8b3b4b54abd461726265fa9789ae34330622f2db9ee696f9d"
 dependencies = [
  "addr2line",
  "cc",
@@ -360,9 +360,9 @@ dependencies = [
 
 [[package]]
 name = "bumpalo"
-version = "3.15.4"
+version = "3.16.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7ff69b9dd49fd426c69a0db9fc04dd934cdb6645ff000864d98f7e2af8830eaa"
+checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
 
 [[package]]
 name = "bytemuck"
@@ -378,15 +378,15 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
 
 [[package]]
 name = "bytes"
-version = "1.5.0"
+version = "1.6.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223"
+checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9"
 
 [[package]]
 name = "cc"
-version = "1.0.90"
+version = "1.0.95"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8cd6604a82acf3039f1144f54b8eb34e91ffba622051189e71b781822d5ee1f5"
+checksum = "d32a725bc159af97c3e629873bb9f88fb8cf8a4867175f76dc987815ea07c83b"
 
 [[package]]
 name = "cfg-if"
@@ -396,16 +396,16 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
 
 [[package]]
 name = "chrono"
-version = "0.4.35"
+version = "0.4.38"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8eaf5903dcbc0a39312feb77df2ff4c76387d591b9fc7b04a238dcf8bb62639a"
+checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401"
 dependencies = [
  "android-tzdata",
  "iana-time-zone",
  "js-sys",
  "num-traits",
  "wasm-bindgen",
- "windows-targets 0.52.4",
+ "windows-targets 0.52.5",
 ]
 
 [[package]]
@@ -420,9 +420,9 @@ dependencies = [
 
 [[package]]
 name = "clap"
-version = "4.5.3"
+version = "4.5.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "949626d00e063efc93b6dca932419ceb5432f99769911c0b995f7e884c778813"
+checksum = "90bc066a67923782aa8515dbaea16946c5bcc5addbd668bb80af688e53e548a0"
 dependencies = [
  "clap_builder",
  "clap_derive",
@@ -442,14 +442,14 @@ dependencies = [
 
 [[package]]
 name = "clap_derive"
-version = "4.5.3"
+version = "4.5.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "90239a040c80f5e14809ca132ddc4176ab33d5e17e49691793296e3fcb34d72f"
+checksum = "528131438037fd55894f62d6e9f068b8f45ac57ffa77517819645d10aed04f64"
 dependencies = [
  "heck 0.5.0",
  "proc-macro2",
  "quote",
- "syn 2.0.53",
+ "syn 2.0.60",
 ]
 
 [[package]]
@@ -562,9 +562,9 @@ dependencies = [
 
 [[package]]
 name = "crc"
-version = "3.0.1"
+version = "3.2.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "86ec7a15cbe22e59248fc7eadb1907dab5ba09372595da4d73dd805ed4417dfe"
+checksum = "69e6e4d7b33a94f0991c26729976b10ebde1d34c3ee82408fb536164fa10d636"
 dependencies = [
  "crc-catalog",
 ]
@@ -617,9 +617,9 @@ dependencies = [
 
 [[package]]
 name = "der"
-version = "0.7.8"
+version = "0.7.9"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fffa369a668c8af7dbf8b5e56c9f744fbd399949ed171606040001947de40b1c"
+checksum = "f55bf8e7b65898637379c1b74eb1551107c8294ed26d855ceb9fd1a09cfc9bc0"
 dependencies = [
  "const-oid",
  "pem-rfc7468",
@@ -665,7 +665,7 @@ dependencies = [
  "proc-macro2",
  "proc-macro2-diagnostics",
  "quote",
- "syn 2.0.53",
+ "syn 2.0.60",
 ]
 
 [[package]]
@@ -733,9 +733,9 @@ dependencies = [
 
 [[package]]
 name = "either"
-version = "1.10.0"
+version = "1.11.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "11157ac094ffbdde99aa67b23417ebdd801842852b500e395a45a9c0aac03e4a"
+checksum = "a47c1c47d2f5964e29c61246e81db715514cd532db6b5116a25ea3c03d6780a2"
 dependencies = [
  "serde",
 ]
@@ -761,9 +761,9 @@ dependencies = [
 
 [[package]]
 name = "encoding_rs"
-version = "0.8.33"
+version = "0.8.34"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7268b386296a025e474d5140678f75d6de9493ae55a5d709eeb9dd08149945e1"
+checksum = "b45de904aa0b010bce2ab45264d0631681847fa7b6f2eaa7dab7619943bc4f59"
 dependencies = [
  "cfg-if",
 ]
@@ -803,15 +803,15 @@ checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0"
 
 [[package]]
 name = "fastrand"
-version = "2.0.1"
+version = "2.0.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5"
+checksum = "658bd65b1cf4c852a3cc96f18a8ce7b5640f6b703f905c7d74532294c2a63984"
 
 [[package]]
 name = "figment"
-version = "0.10.15"
+version = "0.10.18"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7270677e7067213e04f323b55084586195f18308cd7546cfac9f873344ccceb6"
+checksum = "d032832d74006f99547004d49410a4b4218e4c33382d56ca3ff89df74f86b953"
 dependencies = [
  "atomic 0.6.0",
  "pear",
@@ -980,9 +980,9 @@ dependencies = [
 
 [[package]]
 name = "getrandom"
-version = "0.2.12"
+version = "0.2.14"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "190092ea657667030ac6a35e305e62fc4dd69fd98ac98631e5d3a2b1575a12b5"
+checksum = "94b22e06ecb0110981051723910cbf0b5f5e09a2062dd7663334ee79a9d1286c"
 dependencies = [
  "cfg-if",
  "js-sys",
@@ -1015,9 +1015,9 @@ checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b"
 
 [[package]]
 name = "h2"
-version = "0.3.25"
+version = "0.3.26"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4fbd2820c5e49886948654ab546d0688ff24530286bdcf8fca3cefb16d4618eb"
+checksum = "81fe527a889e1532da5c525686d96d4c2e74cdd345badf8dfef9f6b39dd5f5e8"
 dependencies = [
  "bytes",
  "fnv",
@@ -1227,9 +1227,9 @@ dependencies = [
 
 [[package]]
 name = "indexmap"
-version = "2.2.5"
+version = "2.2.6"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7b0b929d511467233429c45a44ac1dcaa21ba0f5ba11e4879e6ed28ddb4f9df4"
+checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26"
 dependencies = [
  "equivalent",
  "hashbrown 0.14.3",
@@ -1279,9 +1279,9 @@ dependencies = [
 
 [[package]]
 name = "itoa"
-version = "1.0.10"
+version = "1.0.11"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c"
+checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b"
 
 [[package]]
 name = "js-sys"
@@ -1394,9 +1394,9 @@ checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c"
 
 [[package]]
 name = "lock_api"
-version = "0.4.11"
+version = "0.4.12"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3c168f8615b12bc01f9c17e2eb0cc07dcae1940121185446edc3744920e8ef45"
+checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17"
 dependencies = [
  "autocfg",
  "scopeguard",
@@ -1456,9 +1456,9 @@ dependencies = [
 
 [[package]]
 name = "memchr"
-version = "2.7.1"
+version = "2.7.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149"
+checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d"
 
 [[package]]
 name = "mercury-client"
@@ -1734,7 +1734,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
 dependencies = [
  "proc-macro2",
  "quote",
- "syn 2.0.53",
+ "syn 2.0.60",
 ]
 
 [[package]]
@@ -1745,9 +1745,9 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"
 
 [[package]]
 name = "openssl-sys"
-version = "0.9.101"
+version = "0.9.102"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dda2b0f344e78efc2facf7d195d098df0dd72151b26ab98da807afc26c198dff"
+checksum = "c597637d56fbc83893a35eb0dd04b2b8e7a50c91e64e9493e398b5df4fb45fa2"
 dependencies = [
  "cc",
  "libc",
@@ -1773,9 +1773,9 @@ checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"
 
 [[package]]
 name = "parking_lot"
-version = "0.12.1"
+version = "0.12.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f"
+checksum = "7e4af0ca4f6caed20e900d564c242b8e5d4903fdacf31d3daf527b66fe6f42fb"
 dependencies = [
  "lock_api",
  "parking_lot_core",
@@ -1783,15 +1783,15 @@ dependencies = [
 
 [[package]]
 name = "parking_lot_core"
-version = "0.9.9"
+version = "0.9.10"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4c42a9226546d68acdd9c0a280d17ce19bfe27a46bf68784e4066115788d008e"
+checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8"
 dependencies = [
  "cfg-if",
  "libc",
- "redox_syscall",
+ "redox_syscall 0.5.1",
  "smallvec 1.13.2",
- "windows-targets 0.48.5",
+ "windows-targets 0.52.5",
 ]
 
 [[package]]
@@ -1826,7 +1826,7 @@ dependencies = [
  "proc-macro2",
  "proc-macro2-diagnostics",
  "quote",
- "syn 2.0.53",
+ "syn 2.0.60",
 ]
 
 [[package]]
@@ -1846,9 +1846,9 @@ checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e"
 
 [[package]]
 name = "pest"
-version = "2.7.8"
+version = "2.7.9"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "56f8023d0fb78c8e03784ea1c7f3fa36e68a723138990b8d5a47d916b651e7a8"
+checksum = "311fb059dee1a7b802f036316d790138c613a4e8b180c822e3925a662e9f0c95"
 dependencies = [
  "memchr",
  "thiserror",
@@ -1857,9 +1857,9 @@ dependencies = [
 
 [[package]]
 name = "pest_derive"
-version = "2.7.8"
+version = "2.7.9"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b0d24f72393fd16ab6ac5738bc33cdb6a9aa73f8b902e8fe29cf4e67d7dd1026"
+checksum = "f73541b156d32197eecda1a4014d7f868fd2bcb3c550d5386087cfba442bf69c"
 dependencies = [
  "pest",
  "pest_generator",
@@ -1867,22 +1867,22 @@ dependencies = [
 
 [[package]]
 name = "pest_generator"
-version = "2.7.8"
+version = "2.7.9"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fdc17e2a6c7d0a492f0158d7a4bd66cc17280308bbaff78d5bef566dca35ab80"
+checksum = "c35eeed0a3fab112f75165fdc026b3913f4183133f19b49be773ac9ea966e8bd"
 dependencies = [
  "pest",
  "pest_meta",
  "proc-macro2",
  "quote",
- "syn 2.0.53",
+ "syn 2.0.60",
 ]
 
 [[package]]
 name = "pest_meta"
-version = "2.7.8"
+version = "2.7.9"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "934cd7631c050f4674352a6e835d5f6711ffbfb9345c2fc0107155ac495ae293"
+checksum = "2adbf29bb9776f28caece835398781ab24435585fe0d4dc1374a61db5accedca"
 dependencies = [
  "once_cell",
  "pest",
@@ -1891,9 +1891,9 @@ dependencies = [
 
 [[package]]
 name = "pin-project-lite"
-version = "0.2.13"
+version = "0.2.14"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58"
+checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02"
 
 [[package]]
 name = "pin-utils"
@@ -1954,9 +1954,9 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
 
 [[package]]
 name = "proc-macro2"
-version = "1.0.79"
+version = "1.0.81"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e835ff2298f5721608eb1a980ecaee1aef2c132bf95ecc026a11b7bf3c01c02e"
+checksum = "3d1597b0c024618f09a9c3b8655b7e430397a36d23fdafec26d6965e9eec3eba"
 dependencies = [
  "unicode-ident",
 ]
@@ -1969,16 +1969,16 @@ checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8"
 dependencies = [
  "proc-macro2",
  "quote",
- "syn 2.0.53",
+ "syn 2.0.60",
  "version_check",
  "yansi",
 ]
 
 [[package]]
 name = "quote"
-version = "1.0.35"
+version = "1.0.36"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef"
+checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7"
 dependencies = [
  "proc-macro2",
 ]
@@ -2028,6 +2028,15 @@ dependencies = [
  "bitflags 1.3.2",
 ]
 
+[[package]]
+name = "redox_syscall"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "469052894dcb553421e483e4209ee581a45100d31b4018de03e5a7ad86374a7e"
+dependencies = [
+ "bitflags 2.5.0",
+]
+
 [[package]]
 name = "ref-cast"
 version = "1.0.22"
@@ -2045,19 +2054,19 @@ checksum = "5fddb4f8d99b0a2ebafc65a87a69a7b9875e4b1ae1f00db265d300ef7f28bccc"
 dependencies = [
  "proc-macro2",
  "quote",
- "syn 2.0.53",
+ "syn 2.0.60",
 ]
 
 [[package]]
 name = "regex"
-version = "1.10.3"
+version = "1.10.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b62dbe01f0b06f9d8dc7d49e05a0785f153b00b2c227856282f671e0318c9b15"
+checksum = "c117dbdfde9c8308975b6a18d71f3f385c89461f7b3fb054288ecf2a2058ba4c"
 dependencies = [
  "aho-corasick",
  "memchr",
  "regex-automata 0.4.6",
- "regex-syntax 0.8.2",
+ "regex-syntax 0.8.3",
 ]
 
 [[package]]
@@ -2077,7 +2086,7 @@ checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea"
 dependencies = [
  "aho-corasick",
  "memchr",
- "regex-syntax 0.8.2",
+ "regex-syntax 0.8.3",
 ]
 
 [[package]]
@@ -2088,9 +2097,9 @@ checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1"
 
 [[package]]
 name = "regex-syntax"
-version = "0.8.2"
+version = "0.8.3"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f"
+checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56"
 
 [[package]]
 name = "reqwest"
@@ -2198,7 +2207,7 @@ dependencies = [
  "proc-macro2",
  "quote",
  "rocket_http",
- "syn 2.0.53",
+ "syn 2.0.60",
  "unicode-xid",
  "version_check",
 ]
@@ -2279,9 +2288,9 @@ checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76"
 
 [[package]]
 name = "rustix"
-version = "0.38.32"
+version = "0.38.34"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "65e04861e65f21776e67888bfbea442b3642beaa0138fdb1dd7a84a52dffdb89"
+checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f"
 dependencies = [
  "bitflags 2.5.0",
  "errno",
@@ -2292,9 +2301,9 @@ dependencies = [
 
 [[package]]
 name = "rustls"
-version = "0.21.10"
+version = "0.21.11"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f9d5a6813c0759e4609cd494e8e725babae6a2ca7b62a5536a13daaec6fcb7ba"
+checksum = "7fecbfb7b1444f477b345853b1fce097a2c6fb637b2bfb87e6bc5db0f043fae4"
 dependencies = [
  "log",
  "ring",
@@ -2323,9 +2332,9 @@ dependencies = [
 
 [[package]]
 name = "rustversion"
-version = "1.0.14"
+version = "1.0.15"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4"
+checksum = "80af6f9131f277a45a3fba6ce8e2258037bb0477a67e610d3c1fe046ab31de47"
 
 [[package]]
 name = "ryu"
@@ -2433,9 +2442,9 @@ dependencies = [
 
 [[package]]
 name = "security-framework"
-version = "2.9.2"
+version = "2.10.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "05b64fb303737d99b81884b2c63433e9ae28abebe5eb5045dcdd175dc2ecf4de"
+checksum = "770452e37cad93e0a50d5abc3990d2bc351c36d0328f86cefec2f2fb206eaef6"
 dependencies = [
  "bitflags 1.3.2",
  "core-foundation",
@@ -2446,9 +2455,9 @@ dependencies = [
 
 [[package]]
 name = "security-framework-sys"
-version = "2.9.1"
+version = "2.10.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e932934257d3b408ed8f30db49d85ea163bfe74961f017f405b025af298f0c7a"
+checksum = "41f3cc463c0ef97e11c3461a9d3787412d30e8e7eb907c79180c4a57bf7c04ef"
 dependencies = [
  "core-foundation-sys",
  "libc",
@@ -2456,9 +2465,9 @@ dependencies = [
 
 [[package]]
 name = "serde"
-version = "1.0.197"
+version = "1.0.198"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2"
+checksum = "9846a40c979031340571da2545a4e5b7c4163bdae79b301d5f86d03979451fcc"
 dependencies = [
  "serde_derive",
 ]
@@ -2476,13 +2485,13 @@ dependencies = [
 
 [[package]]
 name = "serde_derive"
-version = "1.0.197"
+version = "1.0.198"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b"
+checksum = "e88edab869b01783ba905e7d0153f9fc1a6505a96e4ad3018011eedb838566d9"
 dependencies = [
  "proc-macro2",
  "quote",
- "syn 2.0.53",
+ "syn 2.0.60",
 ]
 
 [[package]]
@@ -2498,9 +2507,9 @@ dependencies = [
 
 [[package]]
 name = "serde_json"
-version = "1.0.114"
+version = "1.0.116"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c5f09b1bd632ef549eaa9f60a1f8de742bdbc698e6cee2095fc84dde5f549ae0"
+checksum = "3e17db7126d17feb94eb3fad46bf1a96b034e8aacbc2e775fe81505f8b0b2813"
 dependencies = [
  "itoa",
  "ryu",
@@ -2561,9 +2570,9 @@ dependencies = [
 
 [[package]]
 name = "signal-hook-registry"
-version = "1.4.1"
+version = "1.4.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1"
+checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1"
 dependencies = [
  "libc",
 ]
@@ -2884,9 +2893,9 @@ dependencies = [
 
 [[package]]
 name = "strsim"
-version = "0.11.0"
+version = "0.11.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5ee073c9e4cd00e28217186dbe12796d692868f432bf2e97ee73bed0c56dfa01"
+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
 
 [[package]]
 name = "subtle"
@@ -2907,9 +2916,9 @@ dependencies = [
 
 [[package]]
 name = "syn"
-version = "2.0.53"
+version = "2.0.60"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7383cd0e49fff4b6b90ca5670bfd3e9d6a733b3f90c686605aa7eec8c4996032"
+checksum = "909518bc7b1c9b779f1bbf07f2929d35af9f0f37e47c6e9ef7f9dddc1e1821f3"
 dependencies = [
  "proc-macro2",
  "quote",
@@ -2957,22 +2966,22 @@ dependencies = [
 
 [[package]]
 name = "thiserror"
-version = "1.0.58"
+version = "1.0.59"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "03468839009160513471e86a034bb2c5c0e4baae3b43f79ffc55c4a5427b3297"
+checksum = "f0126ad08bff79f29fc3ae6a55cc72352056dfff61e3ff8bb7129476d44b23aa"
 dependencies = [
  "thiserror-impl",
 ]
 
 [[package]]
 name = "thiserror-impl"
-version = "1.0.58"
+version = "1.0.59"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c61f3ba182994efc43764a46c018c347bc492c79f024e705f46567b418f6d4f7"
+checksum = "d1cd413b5d558b4c5bf3680e324a6fa5014e7b7c067a51e69dbdf47eb7148b66"
 dependencies = [
  "proc-macro2",
  "quote",
- "syn 2.0.53",
+ "syn 2.0.60",
 ]
 
 [[package]]
@@ -2987,9 +2996,9 @@ dependencies = [
 
 [[package]]
 name = "time"
-version = "0.3.34"
+version = "0.3.36"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c8248b6521bb14bc45b4067159b9b6ad792e2d6d754d6c41fb50e29fefe38749"
+checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885"
 dependencies = [
  "deranged",
  "itoa",
@@ -3008,9 +3017,9 @@ checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3"
 
 [[package]]
 name = "time-macros"
-version = "0.2.17"
+version = "0.2.18"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7ba3a3ef41e6672a2f0f001392bb5dcd3ff0a9992d618ca761a11c3121547774"
+checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf"
 dependencies = [
  "num-conv",
  "time-core",
@@ -3036,9 +3045,9 @@ dependencies = [
 
 [[package]]
 name = "tokio"
-version = "1.36.0"
+version = "1.37.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "61285f6515fa018fb2d1e46eb21223fff441ee8db5d0f1435e8ab4f5cdb80931"
+checksum = "1adbebffeca75fcfd058afa480fb6c0b81e165a0323f9c9d39c9697e37c46787"
 dependencies = [
  "backtrace",
  "bytes",
@@ -3061,7 +3070,7 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b"
 dependencies = [
  "proc-macro2",
  "quote",
- "syn 2.0.53",
+ "syn 2.0.60",
 ]
 
 [[package]]
@@ -3143,9 +3152,9 @@ dependencies = [
 
 [[package]]
 name = "toml_edit"
-version = "0.22.9"
+version = "0.22.12"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8e40bb779c5187258fd7aad0eb68cb8706a0a81fa712fbea808ab43c4b8374c4"
+checksum = "d3328d4f68a705b2a4498da1d580585d39a6510f98318a2cec3018a7ec61ddef"
 dependencies = [
  "indexmap",
  "serde",
@@ -3180,7 +3189,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7"
 dependencies = [
  "proc-macro2",
  "quote",
- "syn 2.0.53",
+ "syn 2.0.60",
 ]
 
 [[package]]
@@ -3413,7 +3422,7 @@ dependencies = [
  "once_cell",
  "proc-macro2",
  "quote",
- "syn 2.0.53",
+ "syn 2.0.60",
  "wasm-bindgen-shared",
 ]
 
@@ -3447,7 +3456,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7"
 dependencies = [
  "proc-macro2",
  "quote",
- "syn 2.0.53",
+ "syn 2.0.60",
  "wasm-bindgen-backend",
  "wasm-bindgen-shared",
 ]
@@ -3480,7 +3489,7 @@ checksum = "b7f89739351a2e03cb94beb799d47fb2cac01759b40ec441f7de39b00cbf7ef0"
 dependencies = [
  "proc-macro2",
  "quote",
- "syn 2.0.53",
+ "syn 2.0.60",
 ]
 
 [[package]]
@@ -3524,7 +3533,7 @@ version = "1.5.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "a44ab49fad634e88f55bf8f9bb3abd2f27d7204172a112c7c9987e01c1c94ea9"
 dependencies = [
- "redox_syscall",
+ "redox_syscall 0.4.1",
  "wasite",
 ]
 
@@ -3565,7 +3574,7 @@ version = "0.52.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9"
 dependencies = [
- "windows-targets 0.52.4",
+ "windows-targets 0.52.5",
 ]
 
 [[package]]
@@ -3583,7 +3592,7 @@ version = "0.52.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
 dependencies = [
- "windows-targets 0.52.4",
+ "windows-targets 0.52.5",
 ]
 
 [[package]]
@@ -3603,17 +3612,18 @@ dependencies = [
 
 [[package]]
 name = "windows-targets"
-version = "0.52.4"
+version = "0.52.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7dd37b7e5ab9018759f893a1952c9420d060016fc19a472b4bb20d1bdd694d1b"
+checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb"
 dependencies = [
- "windows_aarch64_gnullvm 0.52.4",
- "windows_aarch64_msvc 0.52.4",
- "windows_i686_gnu 0.52.4",
- "windows_i686_msvc 0.52.4",
- "windows_x86_64_gnu 0.52.4",
- "windows_x86_64_gnullvm 0.52.4",
- "windows_x86_64_msvc 0.52.4",
+ "windows_aarch64_gnullvm 0.52.5",
+ "windows_aarch64_msvc 0.52.5",
+ "windows_i686_gnu 0.52.5",
+ "windows_i686_gnullvm",
+ "windows_i686_msvc 0.52.5",
+ "windows_x86_64_gnu 0.52.5",
+ "windows_x86_64_gnullvm 0.52.5",
+ "windows_x86_64_msvc 0.52.5",
 ]
 
 [[package]]
@@ -3624,9 +3634,9 @@ checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
 
 [[package]]
 name = "windows_aarch64_gnullvm"
-version = "0.52.4"
+version = "0.52.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bcf46cf4c365c6f2d1cc93ce535f2c8b244591df96ceee75d8e83deb70a9cac9"
+checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263"
 
 [[package]]
 name = "windows_aarch64_msvc"
@@ -3636,9 +3646,9 @@ checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
 
 [[package]]
 name = "windows_aarch64_msvc"
-version = "0.52.4"
+version = "0.52.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "da9f259dd3bcf6990b55bffd094c4f7235817ba4ceebde8e6d11cd0c5633b675"
+checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6"
 
 [[package]]
 name = "windows_i686_gnu"
@@ -3648,9 +3658,15 @@ checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
 
 [[package]]
 name = "windows_i686_gnu"
-version = "0.52.4"
+version = "0.52.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b474d8268f99e0995f25b9f095bc7434632601028cf86590aea5c8a5cb7801d3"
+checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9"
 
 [[package]]
 name = "windows_i686_msvc"
@@ -3660,9 +3676,9 @@ checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
 
 [[package]]
 name = "windows_i686_msvc"
-version = "0.52.4"
+version = "0.52.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1515e9a29e5bed743cb4415a9ecf5dfca648ce85ee42e15873c3cd8610ff8e02"
+checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf"
 
 [[package]]
 name = "windows_x86_64_gnu"
@@ -3672,9 +3688,9 @@ checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
 
 [[package]]
 name = "windows_x86_64_gnu"
-version = "0.52.4"
+version = "0.52.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5eee091590e89cc02ad514ffe3ead9eb6b660aedca2183455434b93546371a03"
+checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9"
 
 [[package]]
 name = "windows_x86_64_gnullvm"
@@ -3684,9 +3700,9 @@ checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
 
 [[package]]
 name = "windows_x86_64_gnullvm"
-version = "0.52.4"
+version = "0.52.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "77ca79f2451b49fa9e2af39f0747fe999fcda4f5e241b2898624dca97a1f2177"
+checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596"
 
 [[package]]
 name = "windows_x86_64_msvc"
@@ -3696,15 +3712,15 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
 
 [[package]]
 name = "windows_x86_64_msvc"
-version = "0.52.4"
+version = "0.52.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "32b752e52a2da0ddfbdbcc6fceadfeede4c939ed16d13e648833a61dfb611ed8"
+checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0"
 
 [[package]]
 name = "winnow"
-version = "0.6.5"
+version = "0.6.6"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dffa400e67ed5a4dd237983829e66475f0a4a26938c4b04c21baede6262215b8"
+checksum = "f0c976aaaa0e1f90dbb21e9587cdaf1d9679a1cde8875c0d6bd83ab96a208352"
 dependencies = [
  "memchr",
 ]
@@ -3754,7 +3770,7 @@ checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6"
 dependencies = [
  "proc-macro2",
  "quote",
- "syn 2.0.53",
+ "syn 2.0.60",
 ]
 
 [[package]]
diff --git a/clients/standalone-rust/src/transfer_receiver.rs b/clients/standalone-rust/src/transfer_receiver.rs
index f2e6cf75..81abd5fb 100644
--- a/clients/standalone-rust/src/transfer_receiver.rs
+++ b/clients/standalone-rust/src/transfer_receiver.rs
@@ -199,14 +199,6 @@ async fn verify_blinded_musig_scheme(backup_tx: &mercury_lib::transfer::Receiver
     let blind_commitment = sha256::Hash::hash(blinding_factor.as_bytes());
     let r2_commitment = sha256::Hash::hash(&client_public_nonce.serialize());
 
-    if statechain_info.blind_commitment != blind_commitment.to_string() {
-        return Err(CError::Generic("blind_commitment is not correct".to_string()));
-    }
-
-    if statechain_info.r2_commitment != r2_commitment.to_string() {
-        return Err(CError::Generic("r2_commitment is not correct".to_string()));
-    }
-
     let secp = Secp256k1::new();
 
     // TODO: this code is repeated in client/src/transaction/mod.rs. Move it to a common place.

From 1f947b8f9b71491568f035bb1d6e1273dc5d0724 Mon Sep 17 00:00:00 2001
From: "S. Santos" 
Date: Fri, 26 Apr 2024 06:29:58 -0300
Subject: [PATCH 45/66] Add address validation and remove standalone rust
 client

---
 clients/rust/Cargo.toml                       |  20 +-
 clients/rust/src/broadcast_backup_tx.rs       |   6 +
 clients/rust/src/deposit.rs                   |   2 +-
 clients/rust/src/main.rs                      |  34 +-
 clients/rust/src/transaction.rs               |  16 +-
 clients/rust/src/transfer_receiver.rs         |   2 +-
 clients/rust/src/transfer_sender.rs           |   8 +-
 clients/rust/src/utils.rs                     |   2 -
 clients/rust/src/withdraw.rs                  |   8 +-
 clients/standalone-rust/.gitignore            |   3 -
 clients/standalone-rust/Cargo.toml            |  28 -
 clients/standalone-rust/README.md             |  30 --
 clients/standalone-rust/Settings.toml         |   6 -
 .../migrations/0001_signer_data_table.sql     |  65 ---
 .../standalone-rust/src/client_config/mod.rs  |  80 ---
 .../client_config/sqilte_manager/common.rs    |  71 ---
 .../client_config/sqilte_manager/deposit.rs   |  90 ----
 .../sqilte_manager/key_derivation.rs          | 101 ----
 .../src/client_config/sqilte_manager/mod.rs   |   7 -
 .../sqilte_manager/transaction.rs             |  19 -
 .../sqilte_manager/transfer_receiver.rs       | 117 ----
 .../sqilte_manager/transfer_sender.rs         | 120 -----
 .../client_config/sqilte_manager/withdraw.rs  |  88 ---
 clients/standalone-rust/src/deposit.rs        | 202 -------
 clients/standalone-rust/src/electrum.rs       |  35 --
 clients/standalone-rust/src/error.rs          |   7 -
 clients/standalone-rust/src/key_derivation.rs | 129 -----
 clients/standalone-rust/src/main.rs           | 225 --------
 clients/standalone-rust/src/send_backup.rs    | 259 ---------
 clients/standalone-rust/src/transaction.rs    | 373 -------------
 .../standalone-rust/src/transfer_receiver.rs  | 500 ------------------
 .../standalone-rust/src/transfer_sender.rs    | 249 ---------
 clients/standalone-rust/src/utils.rs          |  44 --
 clients/standalone-rust/src/wallet.rs         | 183 -------
 clients/standalone-rust/src/withdraw.rs       |  76 ---
 lib/src/lib.rs                                |  36 +-
 lib/src/transaction.rs                        |  14 +-
 lib/src/transfer/sender.rs                    |   4 +-
 lib/src/wallet/mod.rs                         |   1 +
 39 files changed, 106 insertions(+), 3154 deletions(-)
 delete mode 100644 clients/standalone-rust/.gitignore
 delete mode 100644 clients/standalone-rust/Cargo.toml
 delete mode 100644 clients/standalone-rust/README.md
 delete mode 100644 clients/standalone-rust/Settings.toml
 delete mode 100644 clients/standalone-rust/migrations/0001_signer_data_table.sql
 delete mode 100644 clients/standalone-rust/src/client_config/mod.rs
 delete mode 100644 clients/standalone-rust/src/client_config/sqilte_manager/common.rs
 delete mode 100644 clients/standalone-rust/src/client_config/sqilte_manager/deposit.rs
 delete mode 100644 clients/standalone-rust/src/client_config/sqilte_manager/key_derivation.rs
 delete mode 100644 clients/standalone-rust/src/client_config/sqilte_manager/mod.rs
 delete mode 100644 clients/standalone-rust/src/client_config/sqilte_manager/transaction.rs
 delete mode 100644 clients/standalone-rust/src/client_config/sqilte_manager/transfer_receiver.rs
 delete mode 100644 clients/standalone-rust/src/client_config/sqilte_manager/transfer_sender.rs
 delete mode 100644 clients/standalone-rust/src/client_config/sqilte_manager/withdraw.rs
 delete mode 100644 clients/standalone-rust/src/deposit.rs
 delete mode 100644 clients/standalone-rust/src/electrum.rs
 delete mode 100644 clients/standalone-rust/src/error.rs
 delete mode 100644 clients/standalone-rust/src/key_derivation.rs
 delete mode 100644 clients/standalone-rust/src/main.rs
 delete mode 100644 clients/standalone-rust/src/send_backup.rs
 delete mode 100644 clients/standalone-rust/src/transaction.rs
 delete mode 100644 clients/standalone-rust/src/transfer_receiver.rs
 delete mode 100644 clients/standalone-rust/src/transfer_sender.rs
 delete mode 100644 clients/standalone-rust/src/utils.rs
 delete mode 100644 clients/standalone-rust/src/wallet.rs
 delete mode 100644 clients/standalone-rust/src/withdraw.rs

diff --git a/clients/rust/Cargo.toml b/clients/rust/Cargo.toml
index 8f3dac81..a234e5ce 100644
--- a/clients/rust/Cargo.toml
+++ b/clients/rust/Cargo.toml
@@ -6,24 +6,24 @@ edition = "2021"
 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
 
 [dependencies]
+anyhow = "1.0"
+bech32 = { version = "0.9.1", default-features = false }
 bitcoin = { version = "0.30.1", features = ["serde", "base64", "rand-std", "std", "bitcoinconsensus"], default-features = false }
 bip39 = "1.2.0"
-bech32 = { version = "0.9.1", default-features = false }
+clap = { version = "4.2.5", features = ["derive"]}
+chrono = "0.4.31"
 config = "0.13.1"
 electrum-client = "0.18.0"
+hex = "0.4.3"
+rand = "0.8.5"
 reqwest = { version = "0.11.16", features = ["blocking", "json", "socks"] }
-tokio = { version = "1.27.0", features = ["full"] }
-sqlx = { version = "0.7", features = [ "runtime-tokio", "sqlite", "time", "uuid" ] }
+schemars = { version = "0.8.12", features = ["chrono", "uuid"] }
+secp256k1-zkp = { git = "https://github.com/ssantos21/rust-secp256k1-zkp.git", branch = "blinded-musig-scheme", features = [ "rand-std", "bitcoin_hashes", "std" ] }
 serde = { version = "1.0.163", features = ["derive"] }
 serde_json = "1.0.96"
-schemars = { version = "0.8.12", features = ["chrono", "uuid"] }
+sqlx = { version = "0.7", features = [ "runtime-tokio", "sqlite", "time", "uuid" ] }
+tokio = { version = "1.27.0", features = ["full"] }
 uuid = { version = "1.3.1", features = ["v4", "serde"] }
-clap = { version = "4.2.5", features = ["derive"]}
-rand = "0.8.5"
-hex = "0.4.3"
-secp256k1-zkp = { git = "https://github.com/ssantos21/rust-secp256k1-zkp.git", branch = "blinded-musig-scheme", features = [ "rand-std", "bitcoin_hashes", "std" ] }
-anyhow = "1.0"
-chrono = "0.4.31"
 
 [dependencies.mercury-lib]
 path = "../../lib"
\ No newline at end of file
diff --git a/clients/rust/src/broadcast_backup_tx.rs b/clients/rust/src/broadcast_backup_tx.rs
index a80d6684..f7042cc4 100644
--- a/clients/rust/src/broadcast_backup_tx.rs
+++ b/clients/rust/src/broadcast_backup_tx.rs
@@ -7,6 +7,12 @@ pub async fn execute(client_config: &ClientConfig, wallet_name: &str, statechain
     
     let mut wallet: mercury_lib::wallet::Wallet = get_wallet(&client_config.pool, &wallet_name).await?;
 
+    let is_address_valid = mercury_lib::validate_address(to_address, &wallet.network)?;
+
+    if !is_address_valid {
+        return Err(anyhow!("Invalid address"));
+    }
+
     let backup_txs = get_backup_txs(&client_config.pool, &statechain_id).await?;
     
     let backup_tx = backup_txs.iter().max_by_key(|tx| tx.tx_n);
diff --git a/clients/rust/src/deposit.rs b/clients/rust/src/deposit.rs
index b2bec99d..7b6b969d 100644
--- a/clients/rust/src/deposit.rs
+++ b/clients/rust/src/deposit.rs
@@ -39,7 +39,7 @@ pub async fn create_tx1(client_config: &ClientConfig, coin: &mut Coin, wallet_ne
 
     let to_address = get_user_backup_address(&coin, wallet_netwotk.to_string())?;
 
-    let signed_tx = new_transaction(&client_config, coin, &to_address, 0, false, None, wallet_netwotk).await?;
+    let signed_tx = new_transaction(&client_config, coin, &to_address, 0, false, None, wallet_netwotk, None).await?;
 
     if coin.public_nonce.is_none() {
         return Err(anyhow::anyhow!("coin.public_nonce is None"));
diff --git a/clients/rust/src/main.rs b/clients/rust/src/main.rs
index b3f7314d..126d61d9 100644
--- a/clients/rust/src/main.rs
+++ b/clients/rust/src/main.rs
@@ -27,33 +27,38 @@ struct Cli {
 #[derive(Subcommand)]
 enum Commands {
     /// Create a wallet
-    CreateWallet { name: String },
-    /*
-    /// Create Aggregated Public Key
-    Deposit { wallet_name: String, token_id: String, amount: u32 },
-    */
+    CreateWallet { 
+        /// The name of the wallet to create
+        name: String 
+    },
     /// Get new token.
     NewToken { },
     /// Get new deposit address. Used to fund a new statecoin.
     NewDepositAddress { wallet_name: String, token_id: String, amount: u32 },
-    /* /// Create a new statecoin from a deposit address
-    CreateStatecoin { wallet_name: String, deposit_address: String }, */
     /// Broadcast the backup transaction to the network
-    BroadcastBackupTransaction { wallet_name: String, statechain_id: String, to_address: String, fee_rate: Option },
+    BroadcastBackupTransaction { 
+        wallet_name: String,
+        statechain_id: String,
+        to_address: String,
+        /// Transaction fee rate in sats per byte
+        fee_rate: Option
+    },
     /// Broadcast the backup transaction to the network
     ListStatecoins { wallet_name: String },
     /// Withdraw funds from a statechain coin to a bitcoin address
-    Withdraw { wallet_name: String, statechain_id: String, to_address: String, fee_rate: Option },
+    Withdraw { 
+        wallet_name: String, 
+        statechain_id: String, 
+        to_address: String, 
+        /// Transaction fee rate in sats per byte
+        fee_rate: Option
+    },
     /// Generate a transfer address to receive funds
     NewTransferAddress { wallet_name: String },
     /// Send a statechain coin to a transfer address
     TransferSend { wallet_name: String, statechain_id: String, to_address: String,  },
     /// Send a statechain coin to a transfer address
     TransferReceive { wallet_name: String },
-    /*
-    /// Update Coins]
-    UpdateCoins { wallet_name: String },
-    */
 }
 
 #[tokio::main(flavor = "current_thread")]
@@ -120,9 +125,6 @@ async fn main() -> Result<()> {
             coin_status::update_coins(&client_config, &wallet_name).await?;
             transfer_receiver::execute(&client_config, &wallet_name).await?;
         },
-        /*Commands::UpdateCoins { wallet_name }  => {
-            utils::update_coins(&client_config, &wallet_name).await?;
-        }*/
     }
 
     client_config.pool.close().await;
diff --git a/clients/rust/src/transaction.rs b/clients/rust/src/transaction.rs
index ebada1b5..bd1563e7 100644
--- a/clients/rust/src/transaction.rs
+++ b/clients/rust/src/transaction.rs
@@ -4,7 +4,15 @@ use anyhow::Result;
 use secp256k1_zkp::musig::MusigPartialSignature;
 use crate::{client_config::ClientConfig, utils::info_config};
 
-pub async fn new_transaction(client_config: &ClientConfig, coin: &mut Coin, to_address: &str, qt_backup_tx: u32, is_withdrawal: bool, block_height: Option, network: &str) -> Result {
+pub async fn new_transaction(
+    client_config: &ClientConfig, 
+    coin: &mut Coin, 
+    to_address: &str, 
+    qt_backup_tx: u32, 
+    is_withdrawal: bool, 
+    block_height: Option, 
+    network: &str, 
+    fee_rate: Option) -> Result {
 
     // TODO: validate address first
 
@@ -29,7 +37,11 @@ pub async fn new_transaction(client_config: &ClientConfig, coin: &mut Coin, to_a
            
     let initlock = server_info.initlock;
     let interval = server_info.interval;
-    let fee_rate_sats_per_byte = server_info.fee_rate_sats_per_byte as u32;
+
+    let fee_rate_sats_per_byte = match fee_rate {
+        Some(fee_rate) => fee_rate as u32,
+        None => server_info.fee_rate_sats_per_byte as u32,
+    };
 
     let partial_sig_request = get_partial_sig_request(
         &coin, 
diff --git a/clients/rust/src/transfer_receiver.rs b/clients/rust/src/transfer_receiver.rs
index d22bbd7a..715bf7ba 100644
--- a/clients/rust/src/transfer_receiver.rs
+++ b/clients/rust/src/transfer_receiver.rs
@@ -5,7 +5,7 @@ use anyhow::{anyhow, Result};
 use bitcoin::{Txid, Address};
 use chrono::Utc;
 use electrum_client::ElectrumApi;
-use mercury_lib::{transfer::receiver::{GetMsgAddrResponsePayload, verify_transfer_signature, StatechainInfoResponsePayload, validate_tx0_output_pubkey, verify_latest_backup_tx_pays_to_user_pubkey, TxOutpoint, verify_transaction_signature, verify_blinded_musig_scheme, create_transfer_receiver_request_payload, TransferReceiverRequestPayload, get_new_key_info}, wallet::{Coin, Wallet, Activity, CoinStatus}, utils::{get_network, InfoConfig, get_blockheight}};
+use mercury_lib::{transfer::receiver::{GetMsgAddrResponsePayload, verify_transfer_signature, StatechainInfoResponsePayload, validate_tx0_output_pubkey, verify_latest_backup_tx_pays_to_user_pubkey, TxOutpoint, verify_transaction_signature, verify_blinded_musig_scheme, create_transfer_receiver_request_payload, TransferReceiverRequestPayload, get_new_key_info}, wallet::{Coin, Activity, CoinStatus}, utils::{get_network, InfoConfig, get_blockheight}};
 use serde_json::Value;
 
 pub async fn new_transfer_address(client_config: &ClientConfig, wallet_name: &str) -> Result{
diff --git a/clients/rust/src/transfer_sender.rs b/clients/rust/src/transfer_sender.rs
index 0cdb2691..14d34ea1 100644
--- a/clients/rust/src/transfer_sender.rs
+++ b/clients/rust/src/transfer_sender.rs
@@ -7,6 +7,12 @@ pub async fn execute(client_config: &ClientConfig, recipient_address: &str, wall
 
     let mut wallet: mercury_lib::wallet::Wallet = get_wallet(&client_config.pool, &wallet_name).await?;
 
+    let is_address_valid = mercury_lib::validate_address(recipient_address, &wallet.network)?;
+
+    if !is_address_valid {
+        return Err(anyhow!("Invalid address"));
+    }
+
     let mut backup_transactions = get_backup_txs(&client_config.pool, &statechain_id).await?;
 
     if backup_transactions.len() == 0 {
@@ -109,7 +115,7 @@ async fn create_backup_tx_to_receiver(client_config: &ClientConfig, coin: &mut C
     let block_height = Some(get_blockheight(bkp_tx1)?);
 
     let is_withdrawal = false;
-    let signed_tx = new_transaction(client_config, coin, recipient_address, qt_backup_tx, is_withdrawal, block_height, network).await?;
+    let signed_tx = new_transaction(client_config, coin, recipient_address, qt_backup_tx, is_withdrawal, block_height, network, None).await?;
 
     Ok(signed_tx)
 }
diff --git a/clients/rust/src/utils.rs b/clients/rust/src/utils.rs
index 89ae84e6..a959a656 100644
--- a/clients/rust/src/utils.rs
+++ b/clients/rust/src/utils.rs
@@ -30,8 +30,6 @@ pub async fn info_config(client_config: &ClientConfig) -> Result{
 
     let fee_rate_sats_per_byte = (fee_rate_btc_per_kb * 100000.0) as u64;
 
-    println!("fee_rate_sats_per_byte: {}", fee_rate_sats_per_byte);
-
     Ok(InfoConfig {    
         initlock,
         interval,
diff --git a/clients/rust/src/withdraw.rs b/clients/rust/src/withdraw.rs
index 22e3abcd..89a2716d 100644
--- a/clients/rust/src/withdraw.rs
+++ b/clients/rust/src/withdraw.rs
@@ -8,6 +8,12 @@ pub async fn execute(client_config: &ClientConfig, wallet_name: &str, statechain
 
     let mut wallet: mercury_lib::wallet::Wallet = get_wallet(&client_config.pool, &wallet_name).await?;
 
+    let is_address_valid = mercury_lib::validate_address(to_address, &wallet.network)?;
+
+    if !is_address_valid {
+        return Err(anyhow!("Invalid address"));
+    }
+
     let mut backup_txs = get_backup_txs(&client_config.pool, &statechain_id).await?;
     
     if backup_txs.len() == 0 {
@@ -39,7 +45,7 @@ pub async fn execute(client_config: &ClientConfig, wallet_name: &str, statechain
         return Err(anyhow::anyhow!("Coin status must be CONFIRMED to withdraw it. The current status is {}", coin.status));
     }
 
-    let signed_tx = new_transaction(client_config, coin, &to_address, qt_backup_tx, true, None, &wallet.network).await?;
+    let signed_tx = new_transaction(client_config, coin, &to_address, qt_backup_tx, true, None, &wallet.network, fee_rate).await?;
 
     if coin.public_nonce.is_none() {
         return Err(anyhow::anyhow!("coin.public_nonce is None"));
diff --git a/clients/standalone-rust/.gitignore b/clients/standalone-rust/.gitignore
deleted file mode 100644
index a0c4a4b8..00000000
--- a/clients/standalone-rust/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-/target
-wallet.db*
-wallet.json
diff --git a/clients/standalone-rust/Cargo.toml b/clients/standalone-rust/Cargo.toml
deleted file mode 100644
index dcfcd2d5..00000000
--- a/clients/standalone-rust/Cargo.toml
+++ /dev/null
@@ -1,28 +0,0 @@
-[package]
-name = "mercury-client"
-version = "0.1.0"
-edition = "2021"
-
-# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
-
-[dependencies]
-bitcoin = { version = "0.30.1", features = ["serde", "base64", "rand-std", "std", "bitcoinconsensus"], default-features = false }
-bip39 = "1.2.0"
-bech32 = { version = "0.9.1", default-features = false }
-config = "0.13.1"
-ecies = {version = "0.2", default-features = false, features = ["pure"]}
-electrum-client = "0.18.0"
-reqwest = { version = "0.11.16", features = ["blocking", "json", "socks"] }
-tokio = { version = "1.27.0", features = ["full"] }
-sqlx = { version = "0.7", features = [ "runtime-tokio", "sqlite", "time", "uuid" ] }
-serde = { version = "1.0.163", features = ["derive"] }
-serde_json = "1.0.96"
-schemars = { version = "0.8.12", features = ["chrono", "uuid"] }
-uuid = { version = "1.3.1", features = ["v4", "serde"] }
-clap = { version = "4.2.5", features = ["derive"]}
-rand = "0.8.5"
-hex = "0.4.3"
-secp256k1-zkp = { git = "https://github.com/ssantos21/rust-secp256k1-zkp.git", branch = "blinded-musig-scheme", features = [ "rand-std", "bitcoin_hashes", "std" ] }
-
-[dependencies.mercury-lib]
-path = "../../lib"
\ No newline at end of file
diff --git a/clients/standalone-rust/README.md b/clients/standalone-rust/README.md
deleted file mode 100644
index e43a14c3..00000000
--- a/clients/standalone-rust/README.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# Mercury Layer Client
-
-Mercury layer client provides a user interface to the Mercury Layer protocol, via the Mercury Layer server. 
-
-# Running
-
-1. Run the `server` project on localhost
-2. Run one of the commands below
-
-# Some commands
-
-`cargo run show-mnemonic` shows wallet mnemonic
-
-`cargo run deposit  ` creates a new statechain coin
-
-`cargo run get-balance` shows wallet balance
-
-`cargo run broadcast-backup-transaction ` broadcasts the backup transaction to the network
-
-`cargo run send-backup ` send all backup funds to the address provided
-
-`cargo run new-transfer-address` generates a statechain address to receive statechain coins
-
-`cargo run transfer-send  ` transfers the specified statechain coin to the specified address
-
-`cargo run transfer-receive` scans for new statechain transfers
-
-`cargo run withdraw  ` withdraws the statechain coin to the specified bitcoin address
-
-This is a work in progress. Several changes to the project are expected.
\ No newline at end of file
diff --git a/clients/standalone-rust/Settings.toml b/clients/standalone-rust/Settings.toml
deleted file mode 100644
index a39a8594..00000000
--- a/clients/standalone-rust/Settings.toml
+++ /dev/null
@@ -1,6 +0,0 @@
-statechain_entity = "http://j23wevaeducxuy3zahd6bpn4x76cymwz2j3bdixv7ow4awjrg5p6jaid.onion"
-tor_proxy = "socks5h://localhost:9050"
-electrum_server = "tcp://127.0.0.1:50001"
-network = "signet"
-fee_rate_tolerance = 5
-database_file="wallet.db"
\ No newline at end of file
diff --git a/clients/standalone-rust/migrations/0001_signer_data_table.sql b/clients/standalone-rust/migrations/0001_signer_data_table.sql
deleted file mode 100644
index c555615f..00000000
--- a/clients/standalone-rust/migrations/0001_signer_data_table.sql
+++ /dev/null
@@ -1,65 +0,0 @@
-CREATE TABLE IF NOT EXISTS signer_seed (
-    seed BLOB NOT NULL,
-    blockheight INT,
-    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
-);
-
-CREATE TABLE IF NOT EXISTS signer_data (
- 
-    client_seckey_share BLOB UNIQUE,
-    client_pubkey_share BLOB UNIQUE,
-    backup_address TEXT,   
-
-    client_derivation_path TEXT,
-    auth_derivation_path TEXT,
-    change_index INT,
-    address_index INT,
-
-    auth_seckey BLOB UNIQUE,
-    auth_pubkey BLOB UNIQUE,
-
-    transfer_address TEXT,
-    
-    fingerprint TEXT,
-    
-    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
-);
-
-CREATE TABLE IF NOT EXISTS statechain_data (
-
-    token_id TEXT,
-
-    statechain_id TEXT,
-    signed_statechain_id TEXT,
-
-    amount INT,
-    server_pubkey_share BLOB,
-    aggregated_pubkey BLOB,
-    p2tr_agg_address TEXT,
-
-    funding_txid TEXT,
-    funding_vout INT,
-
-    status TEXT,
-    locktime INT,
-
-    client_pubkey_share BLOB,
-
-    tx_withdraw TEXT,
-    
-    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
-);
-
-CREATE TABLE IF NOT EXISTS backup_transaction (
-
-    tx_n INT,
-    statechain_id TEXT,
-    client_public_nonce BLOB,
-    server_public_nonce BLOB,
-    client_pubkey BLOB,
-    server_pubkey BLOB,
-    blinding_factor BLOB,
-    backup_tx BLOB,
-    recipient_address TEXT,
-    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
-);
\ No newline at end of file
diff --git a/clients/standalone-rust/src/client_config/mod.rs b/clients/standalone-rust/src/client_config/mod.rs
deleted file mode 100644
index b6224067..00000000
--- a/clients/standalone-rust/src/client_config/mod.rs
+++ /dev/null
@@ -1,80 +0,0 @@
-pub mod sqilte_manager;
-
-use bitcoin::Network;
-use config::Config;
-use sqlx::{Sqlite, migrate::MigrateDatabase, SqlitePool};
-
-/// Config struct storing all StataChain Entity config
-pub struct ClientConfig {
-    /// Active lockbox server addresses
-    pub statechain_entity: String,
-    /// Tor SOCKS5 proxy address
-    pub tor_proxy: String,
-    /// Electrum client
-    pub electrum_client: electrum_client::Client,
-    /// Electrum server url
-    pub electrum_server_url: String,
-    /// Bitcoin network name (testnet, regtest, mainnet)
-    pub network: Network,
-    /// Initial deposit backup nlocktime
-    pub fee_rate_tolerance: u32,
-    /// Database connection pool
-    pub pool: sqlx::Pool,
-}
-
-impl ClientConfig {
-    pub async fn load() -> Self {
-        let settings = Config::builder()
-            .add_source(config::File::with_name("Settings"))
-            .build()
-            .unwrap();
-
-        let statechain_entity = settings.get_string("statechain_entity").unwrap();
-        let tor_proxy = settings.get_string("tor_proxy").unwrap();
-        let electrum_server = settings.get_string("electrum_server").unwrap();
-        let network = settings.get_string("network").unwrap();
-        let fee_rate_tolerance = settings.get_int("fee_rate_tolerance").unwrap() as u32;
-        let database_file = settings.get_string("database_file").unwrap();
-
-        // Open database connection pool
-
-        if !Sqlite::database_exists(&database_file).await.unwrap_or(false) {
-            match Sqlite::create_database(&database_file).await {
-                Ok(_) => println!("Create db success"),
-                Err(error) => panic!("error: {}", error),
-            }
-        }
-    
-        let pool: sqlx::Pool = SqlitePool::connect(&database_file).await.unwrap();
-    
-        sqlx::migrate!("./migrations")
-            .run(&pool)
-            .await
-            .unwrap();
-
-        // Convert network string to Network enum
-
-        let network = match network.as_str() {
-            "signet" => Network::Signet,
-            "testnet" => Network::Testnet,
-            "regtest" => Network::Regtest,
-            "mainnet" => Network::Bitcoin,
-            _ => panic!("Invalid network name"),
-        };
-
-        // Create Electrum client
-
-        let electrum_client = electrum_client::Client::new(electrum_server.as_str()).unwrap();
-
-
-        ClientConfig {
-            statechain_entity,
-            tor_proxy,
-            electrum_client,
-            electrum_server_url: electrum_server,
-            network,
-            fee_rate_tolerance,
-            pool,
-        }
-    }
-}
diff --git a/clients/standalone-rust/src/client_config/sqilte_manager/common.rs b/clients/standalone-rust/src/client_config/sqilte_manager/common.rs
deleted file mode 100644
index 490f81b1..00000000
--- a/clients/standalone-rust/src/client_config/sqilte_manager/common.rs
+++ /dev/null
@@ -1,71 +0,0 @@
-use secp256k1_zkp::PublicKey;
-use sqlx::Row;
-
-use crate::{client_config::ClientConfig, error::CError};
-
-impl ClientConfig {
-
-    pub async fn insert_transaction(
-        &self,
-        tx_n: u32, 
-        tx_bytes: &Vec, 
-        client_pub_nonce: &[u8; 66], 
-        server_pub_nonce: &[u8; 66], 
-        client_pubkey: &PublicKey, 
-        server_pubkey: &PublicKey, 
-        blinding_factor: &[u8; 32], 
-        statechain_id: &str, 
-        recipient_address: &str) -> Result<(), CError>{ 
-    
-        let row = sqlx::query("SELECT MAX(tx_n) FROM backup_transaction WHERE statechain_id = $1")
-            .bind(statechain_id)
-            .fetch_one(&self.pool)
-            .await
-            .unwrap();
-    
-        let mut new_tx_n = row.get::(0);
-    
-        new_tx_n = new_tx_n + 1;
-    
-        if tx_n != new_tx_n {
-            let msg = format!("tx_n {} is not equal to the next tx_n {} in the database", tx_n, new_tx_n).to_string();
-            return Err(CError::Generic(msg));
-        }
-    
-        let query = "INSERT INTO backup_transaction \
-            (tx_n, statechain_id, client_public_nonce, server_public_nonce, client_pubkey, server_pubkey, blinding_factor, backup_tx, recipient_address) \
-            VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)";
-            
-        let _ = sqlx::query(query)
-            .bind(tx_n)
-            .bind(statechain_id)
-            .bind(client_pub_nonce.to_vec())
-            .bind(server_pub_nonce.to_vec())
-            .bind(client_pubkey.serialize().to_vec())
-            .bind(server_pubkey.serialize().to_vec())
-            .bind(blinding_factor.to_vec())
-            .bind(tx_bytes)
-            .bind(recipient_address)
-            .execute(&self.pool)
-            .await
-            .unwrap();
-    
-        Ok(())
-    
-    }
-
-    pub async fn update_coin_status_and_tx_withdraw(&self, statechain_id: &str, new_status: &str, txid: Option) {
-
-        let query = "UPDATE statechain_data \
-            SET status = $1, tx_withdraw = $2 \
-            WHERE statechain_id = $3";
-    
-        let _ = sqlx::query(query)
-            .bind(new_status)
-            .bind(txid)
-            .bind(statechain_id)
-            .execute(&self.pool)
-            .await
-            .unwrap();
-    }
-}
\ No newline at end of file
diff --git a/clients/standalone-rust/src/client_config/sqilte_manager/deposit.rs b/clients/standalone-rust/src/client_config/sqilte_manager/deposit.rs
deleted file mode 100644
index d2c7c54b..00000000
--- a/clients/standalone-rust/src/client_config/sqilte_manager/deposit.rs
+++ /dev/null
@@ -1,90 +0,0 @@
-use bitcoin::{Address, Txid};
-use secp256k1_zkp::{PublicKey, schnorr::Signature};
-use sqlx::Row;
-
-use crate::{error::CError, client_config::ClientConfig};
-
-impl ClientConfig {
-    
-    pub async fn insert_agg_pub_key(
-        &self,
-        token_id: &uuid::Uuid,
-        statechain_id: &str, 
-        amount: u32,  
-        server_pubkey_share: &PublicKey, 
-        aggregated_pubkey: &PublicKey, 
-        p2tr_agg_address: &Address, 
-        client_pubkey_share: &PublicKey,
-        signed_statechain_id: &Signature) -> Result<(), CError> {
-    
-        let query = "\
-            INSERT INTO statechain_data (token_id, statechain_id, amount, server_pubkey_share, aggregated_pubkey, p2tr_agg_address, client_pubkey_share, signed_statechain_id, status) \
-            VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'AVAILABLE')";
-    
-        let _ = sqlx::query(query)
-            .bind(token_id.to_string())
-            .bind(statechain_id)
-            .bind(amount)
-            .bind(server_pubkey_share.serialize().to_vec())
-            .bind(aggregated_pubkey.serialize().to_vec())
-            .bind(p2tr_agg_address.to_string())
-            .bind(client_pubkey_share.serialize().to_vec())
-            .bind(signed_statechain_id.to_string())
-            .execute(&self.pool)
-            .await
-            .unwrap();
-    
-        Ok(())
-    
-    }
-
-    pub async fn update_funding_tx_outpoint(&self, txid: &Txid, vout: u32, statechain_id: &str) {
-
-        let query = "\
-            UPDATE statechain_data \
-            SET funding_txid = $1, funding_vout = $2 \
-            WHERE statechain_id = $3";
-    
-        let _ = sqlx::query(query)
-            .bind(&txid.to_string())
-            .bind(vout)
-            .bind(statechain_id)
-            .execute(&self.pool)
-            .await
-            .unwrap();
-    }
-
-    pub async fn update_locktime(&self, statechain_id: &str, locktime: u32) {
-
-        let query = "\
-            UPDATE statechain_data \
-            SET locktime = $1 \
-            WHERE statechain_id = $2";
-
-        let _ = sqlx::query(query)
-            .bind(locktime)
-            .bind(statechain_id)
-            .execute(&self.pool)
-            .await
-            .unwrap();
-    }
-
-    pub async fn get_backup_tx(&self, statechain_id: &str) -> Vec {
-    
-        let query = "\
-            SELECT backup_tx \
-            FROM backup_transaction \
-            WHERE tx_n = (SELECT MAX(tx_n) FROM backup_transaction WHERE statechain_id = $1)
-            AND statechain_id = $1";
-    
-        let row = sqlx::query(query)
-            .bind(statechain_id)
-            .fetch_one(&self.pool)
-            .await
-            .unwrap();
-    
-        let tx_bytes = row.get::, _>("backup_tx");
-    
-        tx_bytes
-    }
-}
diff --git a/clients/standalone-rust/src/client_config/sqilte_manager/key_derivation.rs b/clients/standalone-rust/src/client_config/sqilte_manager/key_derivation.rs
deleted file mode 100644
index 75e13d88..00000000
--- a/clients/standalone-rust/src/client_config/sqilte_manager/key_derivation.rs
+++ /dev/null
@@ -1,101 +0,0 @@
-use bitcoin::Address;
-use secp256k1_zkp::PublicKey;
-use sqlx::Row;
-
-use crate::{client_config::ClientConfig, electrum, key_derivation::KeyData};
-
-impl ClientConfig {
-
-    pub async fn generate_or_get_seed(&self) -> ([u8; 32], u32) {
-
-        let rows = sqlx::query("SELECT * FROM signer_seed")
-            .fetch_all(&self.pool)
-            .await
-            .unwrap();
-    
-        if rows.len() > 1 {
-            panic!("More than one seed in database");
-        }
-    
-        if rows.len() == 1 {
-            let row = rows.get(0).unwrap();
-            let seed = row.get::, _>("seed");
-            let block_height = row.get::("blockheight");
-            let mut seed_array = [0u8; 32];
-            seed_array.copy_from_slice(&seed);
-            return (seed_array, block_height);
-        } else {
-            let mut seed = [0u8; 32];  // 256 bits
-            rand::RngCore::fill_bytes(&mut rand::thread_rng(), &mut seed);
-    
-            // TODO: Now that this function gets the block height, it is better to split this function into two
-            // One for generating the seed and one for getting the seed
-            let block_header = electrum::block_headers_subscribe_raw(&self.electrum_client);
-            let block_height = block_header.height;
-            
-            let query = "INSERT INTO signer_seed (seed, blockheight) VALUES ($1, $2)";
-            let _ = sqlx::query(query)
-                .bind(seed.to_vec())
-                .bind(block_height as u32)
-                .execute(&self.pool)
-                .await
-                .unwrap();
-    
-            (seed, block_height as u32)
-        }   
-    }
-
-    pub async fn get_next_address_index(&self, change_index: u32) -> u32 {
-
-        let row = sqlx::query("SELECT MAX(address_index) FROM signer_data WHERE change_index = $1")
-            .bind(change_index)
-            .fetch_one(&self.pool)
-            .await
-            .unwrap();
-    
-        let index = row.get::, _>(0);
-    
-        if index.is_some() {
-            return index.unwrap() + 1;
-        } else {
-            return 0;
-        }
-    }
-
-    pub async fn insert_agg_key_data(&self, key_data: &KeyData, backup_address: &Address)  {
-
-        let query = 
-            "INSERT INTO signer_data (client_seckey_share, client_pubkey_share, backup_address, fingerprint, client_derivation_path, change_index, address_index) \
-            VALUES ($1, $2, $3, $4, $5, $6, $7)";
-    
-        let _ = sqlx::query(query)
-            .bind(&key_data.secret_key.secret_bytes().to_vec())
-            .bind(&key_data.public_key.serialize().to_vec())
-            .bind(&backup_address.to_string())
-            .bind(&key_data.fingerprint)
-            .bind(&key_data.derivation_path)
-            .bind(key_data.change_index)
-            .bind(key_data.address_index)
-            .execute(&self.pool)
-            .await
-            .unwrap();
-    }
-
-    pub async fn update_auth_key_data(&self, key_data: &KeyData, client_pubkey_share: &PublicKey, transfer_address: &str)  {
-
-        let query = "\
-            UPDATE signer_data \
-            SET auth_derivation_path = $1, auth_seckey = $2, auth_pubkey = $3, transfer_address = $4 \
-            WHERE client_pubkey_share = $5";
-    
-        let _ = sqlx::query(query)
-            .bind(&key_data.derivation_path)
-            .bind(&key_data.secret_key.secret_bytes().to_vec())
-            .bind(&key_data.public_key.serialize().to_vec())
-            .bind(transfer_address)
-            .bind(&client_pubkey_share.serialize().to_vec())
-            .execute(&self.pool)
-            .await
-            .unwrap();
-    }
-}
\ No newline at end of file
diff --git a/clients/standalone-rust/src/client_config/sqilte_manager/mod.rs b/clients/standalone-rust/src/client_config/sqilte_manager/mod.rs
deleted file mode 100644
index 17326ac3..00000000
--- a/clients/standalone-rust/src/client_config/sqilte_manager/mod.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-pub mod deposit;
-pub mod common;
-pub mod key_derivation;
-pub mod transaction;
-pub mod transfer_sender;
-pub mod withdraw;
-pub mod transfer_receiver;
diff --git a/clients/standalone-rust/src/client_config/sqilte_manager/transaction.rs b/clients/standalone-rust/src/client_config/sqilte_manager/transaction.rs
deleted file mode 100644
index 1eedd3ad..00000000
--- a/clients/standalone-rust/src/client_config/sqilte_manager/transaction.rs
+++ /dev/null
@@ -1,19 +0,0 @@
-use sqlx::Row;
-
-use crate::client_config::ClientConfig;
-
-impl ClientConfig {
-
-    pub async fn count_backup_tx(&self, statechain_id: &str) -> u32 {
-
-        let row = sqlx::query("SELECT count(*) FROM backup_transaction WHERE statechain_id = $1")
-            .bind(statechain_id)
-            .fetch_one(&self.pool)
-            .await
-            .unwrap();
-
-        let count = row.get::(0);
-
-        count
-    }
-}
\ No newline at end of file
diff --git a/clients/standalone-rust/src/client_config/sqilte_manager/transfer_receiver.rs b/clients/standalone-rust/src/client_config/sqilte_manager/transfer_receiver.rs
deleted file mode 100644
index 7031ef9a..00000000
--- a/clients/standalone-rust/src/client_config/sqilte_manager/transfer_receiver.rs
+++ /dev/null
@@ -1,117 +0,0 @@
-use bitcoin::{Address, Txid};
-use secp256k1_zkp::{PublicKey, SecretKey, schnorr::Signature};
-use sqlx::Row;
-
-use crate::client_config::ClientConfig;
-
-impl ClientConfig {
-    pub async fn get_all_auth_pubkey(&self) -> Vec::<(SecretKey, PublicKey, SecretKey, PublicKey)>{
-        let rows = sqlx::query("SELECT auth_seckey, auth_pubkey, client_seckey_share, client_pubkey_share FROM signer_data")
-            .fetch_all(&self.pool)
-            .await
-            .unwrap();
-    
-        let mut auth_pubkeys = Vec::<(SecretKey, PublicKey, SecretKey, PublicKey)>::new();
-    
-        for row in rows {
-    
-            let auth_secret_key_bytes = row.get::, _>("auth_seckey");
-            let auth_secret_key = SecretKey::from_slice(&auth_secret_key_bytes).unwrap();
-    
-            let auth_pubkey_bytes = row.get::, _>("auth_pubkey");
-            let auth_pubkey = PublicKey::from_slice(&auth_pubkey_bytes).unwrap();
-    
-            let client_seckey_share_bytes = row.get::, _>("client_seckey_share");
-            let client_seckey_share = SecretKey::from_slice(&client_seckey_share_bytes).unwrap();
-    
-            let client_pubkey_bytes = row.get::, _>("client_pubkey_share");
-            let client_pubkey = PublicKey::from_slice(&client_pubkey_bytes).unwrap();
-    
-            auth_pubkeys.push((auth_secret_key, auth_pubkey, client_seckey_share, client_pubkey));
-        }
-    
-        auth_pubkeys
-    }
-
-    pub async fn insert_or_update_new_statechain(
-        &self,
-        statechain_id: &str, 
-        amount: u32,  
-        server_pubkey_share: &PublicKey, 
-        aggregated_pubkey: &PublicKey, 
-        p2tr_agg_address: &Address, 
-        client_pubkey_share: &PublicKey,
-        signed_statechain_id: &Signature,
-        txid: &Txid,
-        vout: u32,
-        locktime: u32,
-        vec_backup_transactions: &Vec) {
-    
-        let mut transaction = self.pool.begin().await.unwrap();
-    
-        let query = "\
-            DELETE FROM backup_transaction \
-            WHERE statechain_id = $1";
-    
-        let _ = sqlx::query(query)
-            .bind(statechain_id)
-            .execute(&mut *transaction)
-            .await
-            .unwrap();
-        
-        let query = "\
-            DELETE FROM statechain_data \
-            WHERE statechain_id = $1";
-    
-        let _ = sqlx::query(query)
-            .bind(statechain_id)
-            .execute(&mut *transaction)
-            .await
-            .unwrap();
-    
-        let query = "\
-            INSERT INTO statechain_data (statechain_id, amount, server_pubkey_share, aggregated_pubkey, p2tr_agg_address, funding_txid, funding_vout, client_pubkey_share, signed_statechain_id, locktime, status) \
-            VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, 'AVAILABLE')";
-    
-        let _ = sqlx::query(query)
-            .bind(statechain_id)
-            .bind(amount)
-            .bind(server_pubkey_share.serialize().to_vec())
-            .bind(aggregated_pubkey.serialize().to_vec())
-            .bind(p2tr_agg_address.to_string())
-            .bind(txid.to_string())
-            .bind(vout)
-            .bind(client_pubkey_share.serialize().to_vec())
-            .bind(signed_statechain_id.to_string())
-            .bind(locktime)
-            .execute(&mut *transaction)
-            .await
-            .unwrap();
-    
-        for backup_tx in vec_backup_transactions {
-            
-            let query = "INSERT INTO backup_transaction \
-                (tx_n, statechain_id, client_public_nonce, server_public_nonce, client_pubkey, server_pubkey, blinding_factor, backup_tx, recipient_address) \
-                VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)";
-    
-            let tx_bytes = bitcoin::consensus::encode::serialize(&backup_tx.tx);
-                
-            let _ = sqlx::query(query)
-                .bind(backup_tx.tx_n)
-                .bind(statechain_id)
-                .bind(backup_tx.client_public_nonce.serialize().to_vec())
-                .bind(backup_tx.server_public_nonce.serialize().to_vec())
-                .bind(backup_tx.client_public_key.serialize().to_vec())
-                .bind(backup_tx.server_public_key.serialize().to_vec())
-                .bind(backup_tx.blinding_factor.as_bytes().to_vec())
-                .bind(tx_bytes)
-                .bind(backup_tx.recipient_address.clone())
-                .execute(&mut *transaction)
-                .await
-                .unwrap();
-        }
-    
-        transaction.commit().await.unwrap();
-        
-    }
-}
\ No newline at end of file
diff --git a/clients/standalone-rust/src/client_config/sqilte_manager/transfer_sender.rs b/clients/standalone-rust/src/client_config/sqilte_manager/transfer_sender.rs
deleted file mode 100644
index 2f586e03..00000000
--- a/clients/standalone-rust/src/client_config/sqilte_manager/transfer_sender.rs
+++ /dev/null
@@ -1,120 +0,0 @@
-use std::str::FromStr;
-
-use bitcoin::{Transaction, Address};
-use secp256k1_zkp::{PublicKey, SecretKey, Secp256k1};
-use sqlx::Row;
-
-use crate::client_config::ClientConfig;
-
-pub struct StatechainCoinDetails {
-    pub client_seckey: SecretKey,
-    pub client_pubkey: PublicKey,
-    pub amount: u64,
-    pub server_pubkey: PublicKey,
-    pub aggregated_pubkey: PublicKey,
-    pub p2tr_agg_address: Address,
-    pub auth_seckey: SecretKey,
-}
-
-impl ClientConfig {
-
-    pub async fn get_backup_transactions(&self, statechain_id: &str) -> Vec:: {
-
-        let rows = sqlx::query("SELECT * FROM backup_transaction WHERE statechain_id = $1")
-            .bind(statechain_id)
-            .fetch_all(&self.pool)
-            .await
-            .unwrap();
-    
-        let mut backup_transactions = Vec::::new();
-    
-        for row in rows {
-            let row_statechain_id = row.get::("statechain_id");
-            assert!(row_statechain_id == statechain_id);
-            
-            let tx_n = row.get::("tx_n");
-    
-            let client_public_nonce = row.get::, _>("client_public_nonce");
-    
-            let server_public_nonce = row.get::, _>("server_public_nonce");
-    
-            let client_public_key_bytes = row.get::, _>("client_pubkey");
-            let client_public_key = PublicKey::from_slice(&client_public_key_bytes).unwrap();
-    
-            let server_public_key_bytes = row.get::, _>("server_pubkey");
-            let server_public_key = PublicKey::from_slice(&server_public_key_bytes).unwrap();
-    
-            let blinding_factor = row.get::, _>("blinding_factor");
-    
-            let tx_bytes = row.get::, _>("backup_tx");
-            let tx = bitcoin::consensus::deserialize::(&tx_bytes).unwrap();
-    
-            let recipient_address = row.get::("recipient_address");
-    
-            backup_transactions.push(mercury_lib::transfer::SenderBackupTransaction {
-                statechain_id: row_statechain_id,
-                tx_n,
-                tx,
-                client_public_nonce,
-                server_public_nonce,
-                client_public_key,
-                server_public_key,
-                blinding_factor,
-                recipient_address,
-            });
-        }
-    
-        backup_transactions
-    }
-
-    pub async fn get_statechain_coin_details(&self,statechain_id: &str) -> StatechainCoinDetails {
-
-        let query = "\
-                SELECT sid.client_seckey_share, sid.client_pubkey_share, std.amount, std.server_pubkey_share, std.aggregated_pubkey, std.p2tr_agg_address, sid.auth_seckey \
-                FROM signer_data sid INNER JOIN statechain_data std \
-                ON sid.client_pubkey_share = std.client_pubkey_share \
-                WHERE std.statechain_id = $1";
-    
-        let row = sqlx::query(query)
-            .bind(statechain_id)
-            .fetch_one(&self.pool)
-            .await
-            .unwrap();
-    
-        let secret_key_bytes = row.get::, _>("client_seckey_share");
-        let client_seckey = SecretKey::from_slice(&secret_key_bytes).unwrap();
-    
-        let client_public_key_bytes = row.get::, _>("client_pubkey_share");
-        let client_pubkey = PublicKey::from_slice(&client_public_key_bytes).unwrap();
-    
-        let amount = row.get::("amount") as u64;
-    
-        let server_public_key_bytes = row.get::, _>("server_pubkey_share");
-        let server_pubkey = PublicKey::from_slice(&server_public_key_bytes).unwrap();
-    
-        let agg_public_key_bytes = row.get::, _>("aggregated_pubkey");
-        let aggregated_pubkey = PublicKey::from_slice(&agg_public_key_bytes).unwrap();
-    
-        let agg_address_str = row.get::("p2tr_agg_address");
-        let p2tr_agg_address = Address::from_str(&agg_address_str).unwrap().require_network(self.network).unwrap();
-    
-        let auth_seckey_bytes = row.get::, _>("auth_seckey");
-        let auth_seckey = SecretKey::from_slice(&auth_seckey_bytes).unwrap();
-    
-        let aggregated_xonly_pubkey = aggregated_pubkey.x_only_public_key().0;
-        let address = Address::p2tr(&Secp256k1::new(), aggregated_xonly_pubkey, None, self.network);
-    
-        assert!(address.to_string() == p2tr_agg_address.to_string());
-    
-        StatechainCoinDetails {
-            client_seckey,
-            client_pubkey,
-            amount,
-            server_pubkey,
-            aggregated_pubkey,
-            p2tr_agg_address,
-            auth_seckey,
-        }
-    
-    }
-}
\ No newline at end of file
diff --git a/clients/standalone-rust/src/client_config/sqilte_manager/withdraw.rs b/clients/standalone-rust/src/client_config/sqilte_manager/withdraw.rs
deleted file mode 100644
index e1d7d9e2..00000000
--- a/clients/standalone-rust/src/client_config/sqilte_manager/withdraw.rs
+++ /dev/null
@@ -1,88 +0,0 @@
-use std::str::FromStr;
-
-use bitcoin::{Address, Txid};
-use mercury_lib::withdraw::CoinKeyDetails;
-use secp256k1_zkp::{SecretKey, PublicKey, schnorr::Signature};
-use sqlx::Row;
-
-use crate::client_config::ClientConfig;
-
-impl ClientConfig {
-    pub async fn get_coin_and_key_info(&self, statechain_id: &str) -> CoinKeyDetails {
-
-        let query = "SELECT \
-            sid.client_seckey_share, \
-            sid.client_pubkey_share, \
-            std.amount, \
-            std.server_pubkey_share, \
-            std.aggregated_pubkey, \
-            std.p2tr_agg_address, \
-            sid.auth_seckey, \
-            std.signed_statechain_id, \
-            std.funding_txid, \
-            std.funding_vout \
-            FROM signer_data sid INNER JOIN statechain_data std \
-            ON sid.client_pubkey_share = std.client_pubkey_share \
-            WHERE std.statechain_id = $1";
-    
-        let row = sqlx::query(query)
-            .bind(statechain_id)
-            .fetch_one(&self.pool)
-            .await
-            .unwrap();
-    
-        let amount = row.get::("amount");
-    
-        let client_seckey_share_bytes = row.get::, _>("client_seckey_share");
-        let client_seckey_share = SecretKey::from_slice(&client_seckey_share_bytes).unwrap();
-    
-        let server_pubkey_share_bytes = row.get::, _>("server_pubkey_share");
-        let server_pubkey_share = PublicKey::from_slice(&server_pubkey_share_bytes).unwrap();
-    
-        let aggregated_pubkey_bytes = row.get::, _>("aggregated_pubkey");
-        let aggregated_pubkey = PublicKey::from_slice(&aggregated_pubkey_bytes).unwrap();
-    
-        let agg_address_str = row.get::("p2tr_agg_address");
-        let p2tr_agg_address = Address::from_str(&agg_address_str).unwrap().require_network(self.network).unwrap();
-    
-        let client_pubkey_share_bytes = row.get::, _>("client_pubkey_share");
-        let client_pubkey_share = PublicKey::from_slice(&client_pubkey_share_bytes).unwrap();
-    
-        let auth_seckey_bytes = row.get::, _>("auth_seckey");
-        let auth_seckey = SecretKey::from_slice(&auth_seckey_bytes).unwrap();
-    
-        let signed_statechain_id = row.get::("signed_statechain_id");
-        let signed_statechain_id = Signature::from_str(&signed_statechain_id).unwrap();
-    
-        let utxo_tx_hash = row.get::("funding_txid");
-        let utxo_tx_hash = Txid::from_str(&utxo_tx_hash).unwrap();
-    
-        let utxo_vout = row.get::("funding_vout");
-    
-        let row = sqlx::query("SELECT MAX(tx_n) FROM backup_transaction WHERE statechain_id = $1")
-            .bind(statechain_id)
-            .fetch_one(&self.pool)
-            .await
-            .unwrap();
-    
-        let mut new_tx_n = row.get::(0);
-    
-        new_tx_n = new_tx_n + 1;
-    
-        let coin_key_details = CoinKeyDetails {
-            new_tx_n,
-            client_seckey: client_seckey_share,
-            client_pubkey: client_pubkey_share,
-            amount: amount as u64,
-            server_pubkey: server_pubkey_share,
-            aggregated_pubkey,
-            p2tr_agg_address,
-            auth_seckey,
-            signed_statechain_id,
-            utxo_tx_hash,
-            utxo_vout,
-        };
-    
-        coin_key_details
-    }
-}
\ No newline at end of file
diff --git a/clients/standalone-rust/src/deposit.rs b/clients/standalone-rust/src/deposit.rs
deleted file mode 100644
index fab79afe..00000000
--- a/clients/standalone-rust/src/deposit.rs
+++ /dev/null
@@ -1,202 +0,0 @@
-use std::{str::FromStr, thread, time::Duration};
-
-use bitcoin::{secp256k1, hashes::sha256, Address, Txid};
-use electrum_client::ListUnspentRes;
-use secp256k1_zkp::{Secp256k1, Message, PublicKey, schnorr::Signature};
-use serde::{Serialize, Deserialize};
-
-use crate::{key_derivation, error::CError, electrum, client_config::ClientConfig};
-
-#[derive(Debug, Serialize, Deserialize)]
-pub struct DepositRequestPayload {
-    amount: u64,
-    auth_key: String,
-    token_id: String,
-    signed_token_id: String,
-}
-
-pub async fn execute(client_config: &ClientConfig, token_id: uuid::Uuid, amount: u64) -> Result {
-
-    let address_data = key_derivation::get_new_address(client_config).await;
-
-    let (statechain_id, 
-        server_pubkey_share, 
-        signed_statechain_id) = init(client_config, &address_data, token_id, amount).await;
-    
-    let secp = Secp256k1::new();
-
-    let aggregate_pubkey = address_data.client_pubkey_share.combine(&server_pubkey_share).unwrap();
-
-    let aggregated_xonly_pubkey = aggregate_pubkey.x_only_public_key().0; 
-
-    let aggregate_address = Address::p2tr(&secp, aggregated_xonly_pubkey, None, client_config.network);
-
-    client_config.insert_agg_pub_key(
-        &token_id,
-        &statechain_id, 
-        amount as u32, 
-        &server_pubkey_share, 
-        &aggregate_pubkey, 
-        &aggregate_address,
-        &address_data.client_pubkey_share,
-        &signed_statechain_id).await.unwrap();
-
-    println!("address: {}", aggregate_address.to_string());
-
-    println!("waiting for deposit ....");
-
-    let delay = Duration::from_secs(5);
-
-    let mut utxo: Option = None;
-
-    loop {
-        let utxo_list = electrum::get_script_list_unspent(&client_config.electrum_client, &aggregate_address);
-
-        for unspent in utxo_list {
-            if unspent.value == amount {
-                utxo = Some(unspent);
-                break;
-            }
-        }
-
-        if utxo.is_some() {
-            break;
-        }
-
-        thread::sleep(delay);
-    }
-
-    let utxo = utxo.unwrap();
-
-    client_config.update_funding_tx_outpoint(&utxo.tx_hash, utxo.tx_pos as u32, &statechain_id).await;
-
-    let block_header = electrum::block_headers_subscribe_raw(&client_config.electrum_client);
-    let block_height = block_header.height;
-
-    let to_address = address_data.backup_address;
-
-    let (tx, client_pub_nonce, server_pub_nonce, blinding_factor) = crate::transaction::new_backup_transaction(
-        client_config,         
-        block_height as u32,
-        &statechain_id,
-        &signed_statechain_id,
-        &address_data.client_secret_key,
-        &address_data.client_pubkey_share,
-        &server_pubkey_share,
-        utxo.tx_hash, 
-        utxo.tx_pos as u32, 
-        &aggregate_pubkey, 
-        &aggregate_address.script_pubkey(), 
-        amount,
-        &to_address,
-        false,).await.unwrap();
-
-    let lock_time = tx.lock_time.to_consensus_u32();
-
-    client_config.update_locktime(&statechain_id, lock_time).await;
-
-    let tx_bytes = bitcoin::consensus::encode::serialize(&tx);
-
-    client_config.insert_transaction(
-        1, 
-        &tx_bytes, 
-        &client_pub_nonce.serialize(), 
-        &server_pub_nonce.serialize(), 
-        &address_data.client_pubkey_share, &server_pubkey_share, 
-        blinding_factor.as_bytes(), 
-        &statechain_id, 
-        &address_data.transfer_address
-    ).await.unwrap();
-
-    Ok(statechain_id)
-
-}
-
-pub async fn init(client_config: &ClientConfig, address_data: &key_derivation::AddressData ,token_id: uuid::Uuid, amount: u64) -> (String, PublicKey, Signature) {
-
-    let msg = Message::from_hashed_data::(token_id.to_string().as_bytes());
-
-    let secp = Secp256k1::new();
-    let auth_secret_key = address_data.auth_secret_key;
-    let keypair = secp256k1::KeyPair::from_seckey_slice(&secp, auth_secret_key.as_ref()).unwrap();
-    let signed_token_id = secp.sign_schnorr(&msg, &keypair);
-    
-    let deposit_request_payload = DepositRequestPayload {
-        amount,
-        auth_key: address_data.auth_xonly_pubkey.to_string(),
-        token_id: token_id.to_string(),
-        signed_token_id: signed_token_id.to_string(),
-    };
-
-    let endpoint = client_config.statechain_entity.clone();
-    let path = "deposit/init/pod";
-
-    let tor_proxy = client_config.tor_proxy.clone();
-
-    let mut client: reqwest::Client = reqwest::Client::new();
-    if tor_proxy != "".to_string() {
-        let tor_proxy = reqwest::Proxy::all(tor_proxy).unwrap();
-        client = reqwest::Client::builder().proxy(tor_proxy).build().unwrap();
-    }
-
-    let request = client.post(&format!("{}/{}", endpoint, path));
-
-    let value = match request.json(&deposit_request_payload).send().await {
-        Ok(response) => {
-            let text = response.text().await.unwrap();
-            text
-        },
-        Err(err) => {
-            // return Err(CError::Generic(err.to_string()));
-            panic!("error: {}", err);
-        },
-    };
-
-    let response: mercury_lib::deposit::DepositMsg1Response = serde_json::from_str(value.as_str()).expect(&format!("failed to parse: {}", value.as_str()));
-
-    let server_pubkey_share = PublicKey::from_str(&response.server_pubkey).unwrap();
-
-    let statechain_id = response.statechain_id.to_string();
-
-    let msg = Message::from_hashed_data::(statechain_id.to_string().as_bytes());
-    let signed_statechain_id = secp.sign_schnorr(&msg, &keypair);
-
-    (statechain_id, server_pubkey_share, signed_statechain_id)
-}
-
-pub async fn broadcast_backup_tx(client_config: &ClientConfig, statechain_id: &str) -> Txid {
-    
-    let tx_bytes = client_config.get_backup_tx(statechain_id).await;
-
-    let txid = electrum::transaction_broadcast_raw(&client_config.electrum_client, &tx_bytes);
-
-    txid
-}
-
-pub async fn get_token(client_config: &ClientConfig) -> String {
-
-    let endpoint = client_config.statechain_entity.clone();
-    let path = "deposit/get_token";
-
-    let tor_proxy = client_config.tor_proxy.clone();
-
-    let mut client: reqwest::Client = reqwest::Client::new();
-    if tor_proxy != "".to_string() {
-        let tor_proxy = reqwest::Proxy::all(tor_proxy).unwrap();
-        client = reqwest::Client::builder().proxy(tor_proxy).build().unwrap();
-    }
-    let request = client.get(&format!("{}/{}", endpoint, path));
-
-    let response = request.send().await.unwrap();
-
-    if response.status() != 200 {
-        let response_body = response.text().await.unwrap();
-        panic!("error: {}", response_body);
-    }
-
-    let value = response.text().await.unwrap();
-
-    let token: mercury_lib::deposit::TokenID = serde_json::from_str(value.as_str()).unwrap();
-
-    return token.token_id;
-}
diff --git a/clients/standalone-rust/src/electrum.rs b/clients/standalone-rust/src/electrum.rs
deleted file mode 100644
index 362a66c0..00000000
--- a/clients/standalone-rust/src/electrum.rs
+++ /dev/null
@@ -1,35 +0,0 @@
-use bitcoin::{Txid, Script};
-use electrum_client::{GetBalanceRes, ElectrumApi, GetHistoryRes, ListUnspentRes, RawHeaderNotification};
-
-/// return balance of address
-pub fn get_address_balance(electrum_client: &electrum_client::Client, address: &bitcoin::Address) -> GetBalanceRes {
-    electrum_client.script_get_balance(&address.script_pubkey()).unwrap()
-}
-
-pub fn get_address_history(electrum_client: &electrum_client::Client, address: &bitcoin::Address) -> Vec {
-    electrum_client.script_get_history(&address.script_pubkey()).unwrap()
-}
-
-pub fn get_script_list_unspent(electrum_client: &electrum_client::Client, address: &bitcoin::Address) -> Vec {    
-    electrum_client.script_list_unspent(&address.script_pubkey()).unwrap()
-}
-
-pub fn get_script_pubkey_list_unspent(electrum_client: &electrum_client::Client, script_pubkey: &Script) -> Vec {    
-    electrum_client.script_list_unspent(&script_pubkey).unwrap()
-}
-
-pub fn transaction_broadcast_raw(electrum_client: &electrum_client::Client, raw_tx: &[u8]) -> Txid {    
-    electrum_client.transaction_broadcast_raw(raw_tx).unwrap()
-}
-
-pub fn block_headers_subscribe_raw(electrum_client: &electrum_client::Client) -> RawHeaderNotification {    
-    electrum_client.block_headers_subscribe_raw().unwrap()
-}
-
-pub fn estimate_fee(electrum_client: &electrum_client::Client, number: usize) -> f64 {
-    electrum_client.estimate_fee(number).unwrap()
-}
-
-pub fn batch_transaction_get_raw(electrum_client: &electrum_client::Client, txids: &[Txid]) -> Vec> {
-    electrum_client.batch_transaction_get_raw(txids).unwrap()
-}
\ No newline at end of file
diff --git a/clients/standalone-rust/src/error.rs b/clients/standalone-rust/src/error.rs
deleted file mode 100644
index da70245e..00000000
--- a/clients/standalone-rust/src/error.rs
+++ /dev/null
@@ -1,7 +0,0 @@
-use serde::{Serialize, Deserialize};
-
-#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
-pub enum CError {
-    /// Generic error from string error message
-    Generic(String)
-}
\ No newline at end of file
diff --git a/clients/standalone-rust/src/key_derivation.rs b/clients/standalone-rust/src/key_derivation.rs
deleted file mode 100644
index f6ce8dca..00000000
--- a/clients/standalone-rust/src/key_derivation.rs
+++ /dev/null
@@ -1,129 +0,0 @@
-use std::str::FromStr;
-
-use bip39::{Mnemonic, Language};
-use bitcoin::{bip32::{ExtendedPrivKey, DerivationPath, ExtendedPubKey, ChildNumber}, Address};
-use secp256k1_zkp::{PublicKey, ffi::types::AlignedType, Secp256k1, SecretKey, XOnlyPublicKey};
-use bech32::{self, FromBase32, Variant};
-
-use crate::{error::CError, client_config::ClientConfig};
-
-pub async fn generate_new_key(client_config: &ClientConfig, derivation_path: &str, change_index: u32, address_index:u32) -> KeyData {
-
-    let (seed, _) = client_config.generate_or_get_seed().await;
-
-    // we need secp256k1 context for key derivation
-    let mut buf: Vec = Vec::new();
-    buf.resize(Secp256k1::preallocate_size(), AlignedType::zeroed());
-    let secp = Secp256k1::preallocated_new(buf.as_mut_slice()).unwrap();
-
-    // calculate root key from seed
-    let root = ExtendedPrivKey::new_master(client_config.network, &seed).unwrap();
-
-    let fingerprint = root.fingerprint(&secp).to_string();
-
-    // derive child xpub
-    let path = DerivationPath::from_str(derivation_path).unwrap();
-    let child = root.derive_priv(&secp, &path).unwrap();
-    let xpub = ExtendedPubKey::from_priv(&secp, &child);
-
-    // generate first receiving address at m/0/0
-    // manually creating indexes this time
-    let change_index_number = ChildNumber::from_normal_idx(change_index).unwrap();
-    let address_index_number = ChildNumber::from_normal_idx(address_index).unwrap();
-
-    let derivation_path = format!("{}/{}/{}", derivation_path, change_index, address_index );
-
-    let secret_key = child.derive_priv(&secp, &[change_index_number, address_index_number]).unwrap().private_key;
-    let public_key: secp256k1_zkp::PublicKey = xpub.derive_pub(&secp, &[change_index_number, address_index_number]).unwrap().public_key;
-
-    KeyData {
-        secret_key,
-        public_key,
-        fingerprint,
-        derivation_path,
-        change_index,
-        address_index,
-    }
-}
-
-pub struct KeyData {
-    pub secret_key: SecretKey,
-    pub public_key: PublicKey,
-    pub fingerprint: String,
-    pub derivation_path: String,
-    pub change_index: u32,
-    pub address_index: u32,
-}
-
-pub async fn get_mnemonic_and_block_height(client_config: &ClientConfig,) -> (String, u32) {
-    let (seed, block_height) = client_config.generate_or_get_seed().await;
-
-    let mnemonic = Mnemonic::from_entropy_in(Language::English,&seed).unwrap();
-
-    (mnemonic.to_string(), block_height)
-}
-
-pub struct AddressData {
-    pub client_secret_key: SecretKey,
-    pub client_pubkey_share: PublicKey,
-    pub auth_secret_key: SecretKey,
-    pub auth_xonly_pubkey: XOnlyPublicKey,
-    pub backup_address: Address,
-    pub transfer_address: String,
-}
-
-pub fn decode_transfer_address(sc_address: &str) -> Result<(u8, PublicKey, PublicKey), CError> {
-    let (hrp, data, variant)  = bech32::decode(sc_address).unwrap();
-
-    if hrp != "sc" {
-        return Err(CError::Generic("Invalid address".to_string()));
-    }
-
-    if variant != Variant::Bech32m {
-        return Err(CError::Generic("Invalid address".to_string()));
-    }
-
-    let decoded_data = Vec::::from_base32(&data).unwrap();
-
-    let version = decoded_data[0];
-    let user_pubkey = PublicKey::from_slice(&decoded_data[1..34]).unwrap();
-    let auth_pubkey = PublicKey::from_slice(&decoded_data[34..67]).unwrap();
-
-    Ok((version, user_pubkey, auth_pubkey))
-}
-
-
-pub async fn get_new_address(client_config: &ClientConfig) -> AddressData {
-
-    let derivation_path = "m/86h/0h/0h";
-    let change_index = 0;
-    let address_index = client_config.get_next_address_index(change_index).await;
-    let agg_key_data = generate_new_key(client_config, derivation_path, change_index, address_index).await;
-
-    let client_secret_key = agg_key_data.secret_key;
-    let client_pubkey_share = agg_key_data.public_key;
-    let backup_address = Address::p2tr(&Secp256k1::new(), client_pubkey_share.x_only_public_key().0, None, client_config.network);
-
-    client_config.insert_agg_key_data(&agg_key_data, &backup_address).await;
-
-    let derivation_path = "m/89h/0h/0h";
-    let auth_key_data = generate_new_key(client_config, derivation_path, change_index, address_index).await;
-
-    assert!(auth_key_data.fingerprint == agg_key_data.fingerprint);
-    assert!(auth_key_data.address_index == agg_key_data.address_index);
-    assert!(auth_key_data.change_index == agg_key_data.change_index);
-    assert!(auth_key_data.derivation_path != agg_key_data.derivation_path);
-
-    let transfer_address = mercury_lib::encode_sc_address(&client_pubkey_share, &auth_key_data.public_key);
-
-    client_config.update_auth_key_data(&auth_key_data, &client_pubkey_share, &transfer_address).await;
-
-    AddressData {
-        client_secret_key,
-        client_pubkey_share,
-        auth_secret_key: auth_key_data.secret_key,
-        auth_xonly_pubkey: auth_key_data.public_key.x_only_public_key().0,
-        backup_address,
-        transfer_address,
-    }
-}
diff --git a/clients/standalone-rust/src/main.rs b/clients/standalone-rust/src/main.rs
deleted file mode 100644
index 32b4240f..00000000
--- a/clients/standalone-rust/src/main.rs
+++ /dev/null
@@ -1,225 +0,0 @@
-mod deposit;
-mod key_derivation;
-mod error;
-mod electrum;
-mod wallet;
-mod transaction;
-mod send_backup;
-mod transfer_sender;
-mod transfer_receiver;
-mod utils;
-mod client_config;
-mod withdraw;
-
-use std::{str::FromStr, fs::File, io::Write};
-
-use bitcoin::Address;
-use clap::{Parser, Subcommand};
-use client_config::ClientConfig;
-use electrum_client::ListUnspentRes;
-use serde::{Serialize, Deserialize};
-use serde_json::json;
-
-#[derive(Parser)]
-#[command(author, version, about, long_about = None)]
-#[command(propagate_version = true)]
-struct Cli {
-    #[command(subcommand)]
-    command: Commands,
-}
-
-#[derive(Subcommand)]
-enum Commands {
-    /// Show mnemonic
-    ShowMnemonic { },
-    /// Get new token
-    NewToken { },
-    /// Create Aggregated Public Key
-    Deposit { token_id: String, amount: u64 },
-    /// Get a wallet balance
-    GetBalance { },
-    /// Broadcast the backup transaction to the network
-    BroadcastBackupTransaction { statechain_id: String },
-    /// Send all backup funds to the address provided
-    SendBackup { address: String, fee_rate: Option },
-    /// Generate a transfer address to receive funds
-    NewTransferAddress { },
-    /// Send a statechain coin to a transfer address
-    TransferSend { recipient_address: String, statechain_id: String },
-    /// Retrieve coins from server
-    TransferReceive { },
-    /// Withdraw funds from a statechain coin to a bitcoin address
-    Withdraw { recipient_address: String, statechain_id: String, fee_rate: Option },
-    /// Export wallet to JSON
-    ExportWallet { },
-}
-
-#[tokio::main(flavor = "current_thread")]
-async fn main() {
-
-    let cli = Cli::parse();
-
-    let client_config = ClientConfig::load().await;
-
-    match cli.command {
-        Commands::ShowMnemonic { } => {
-            let (mnemonic, _) = key_derivation::get_mnemonic_and_block_height(&client_config).await;
-            println!("{}", serde_json::to_string_pretty(&json!({
-                "mnemonic": mnemonic,
-            })).unwrap());
-        },
-        Commands::NewToken { } => {
-            let token_id = deposit::get_token(&client_config).await;
-            println!("{}", token_id);
-        },
-        Commands::Deposit { token_id, amount } => {
-            let token_id = uuid::Uuid::parse_str(&token_id).unwrap();
-            let statechain_id = deposit::execute(&client_config, token_id, amount).await.unwrap();
-            println!("{}", serde_json::to_string_pretty(&json!({
-                "statechain_id": statechain_id,
-            })).unwrap());
-        },
-        Commands::GetBalance {  } => {
-
-            #[derive(Serialize, Deserialize, Debug)]
-            struct Balance {
-                address: String,
-                balance: u64,
-                unconfirmed_balance: i64,
-            }
-
-            let (agg_addresses, backup_addresses) = wallet::get_all_addresses(&client_config).await;
-
-            let agg_result: Vec = agg_addresses.iter().map(|address| {
-                let balance_res = electrum::get_address_balance(&client_config.electrum_client, &address);
-                Balance {
-                    address: address.to_string(),
-                    balance: balance_res.confirmed,
-                    unconfirmed_balance: balance_res.unconfirmed,
-                }
-            }).collect();
-
-            let backup_result: Vec = backup_addresses.iter().map(|address| {
-                let balance_res = electrum::get_address_balance(&client_config.electrum_client, &address);
-                Balance {
-                    address: address.to_string(),
-                    balance: balance_res.confirmed,
-                    unconfirmed_balance: balance_res.unconfirmed,
-                }
-            }).collect();
-
-            println!("{}", serde_json::to_string_pretty(&json!({
-                "statecoins": agg_result,
-                "backup addresses": backup_result,
-            })).unwrap());
-        },
-        Commands::BroadcastBackupTransaction { statechain_id } => {
-
-            let txid = deposit::broadcast_backup_tx(&client_config, &statechain_id).await;
-
-            println!("{}", serde_json::to_string_pretty(&json!({
-                "txid": txid,
-            })).unwrap());
-        },
-        Commands::SendBackup { address, fee_rate } => {
-
-            let to_address = bitcoin::Address::from_str(&address).unwrap().require_network(client_config.network).unwrap();
-
-            let fee_rate = match fee_rate {
-                Some(fee_rate) => fee_rate,
-                None => {
-                    let fee_rate_btc_per_kb = electrum::estimate_fee(&client_config.electrum_client, 1);
-                    let fee_rate_sats_per_byte = (fee_rate_btc_per_kb * 100000.0) as u64;
-                    fee_rate_sats_per_byte
-                },
-            };
-
-            let (_, backup_addresses) = wallet::get_all_addresses(&client_config).await;
-
-            let mut list_unspent = Vec::<(ListUnspentRes, Address)>::new(); 
-
-            for address in backup_addresses {
-                let address_utxos = electrum::get_script_list_unspent(&client_config.electrum_client, &address);
-                for utxo in address_utxos {
-                    list_unspent.push((utxo, address.clone()));
-                }
-            }
-
-            if list_unspent.len() == 0 {
-                println!("No backup funds to send");
-                return;
-            }
-
-            let list_utxo = send_backup::get_address_info(&client_config.pool, list_unspent).await;
-
-
-            send_backup::send_all_funds(&list_utxo, &to_address, fee_rate, &client_config.electrum_client);
-        },
-        Commands::NewTransferAddress { } => {
-            let address_data = key_derivation::get_new_address(&client_config).await;
-            println!("{}", serde_json::to_string_pretty(&json!({
-                "transfer_address": address_data.transfer_address,
-            })).unwrap());
-        },
-        Commands::TransferSend { recipient_address, statechain_id } => {
-
-            transfer_sender::init(&client_config, &recipient_address, &statechain_id).await.unwrap();
-
-            println!("{}", serde_json::to_string_pretty(&json!({
-                "sent": true,
-            })).unwrap());
-
-
-        },
-        Commands::TransferReceive { } => {
-            transfer_receiver::receive( &client_config).await;
-        },
-        Commands::Withdraw { recipient_address, statechain_id, fee_rate } => {
-                
-                let to_address = bitcoin::Address::from_str(&recipient_address).unwrap().require_network(client_config.network).unwrap();
-    
-                let fee_rate = match fee_rate {
-                    Some(fee_rate) => fee_rate,
-                    None => {
-                        let fee_rate_btc_per_kb = electrum::estimate_fee(&client_config.electrum_client, 1);
-                        let fee_rate_sats_per_byte = (fee_rate_btc_per_kb * 100000.0) as u64;
-                        fee_rate_sats_per_byte
-                    },
-                };
-
-                let txid = withdraw::execute(&client_config, &statechain_id, &to_address, fee_rate).await.unwrap();
-    
-                println!("{}", serde_json::to_string_pretty(&json!({
-                    "txid": txid,
-                })).unwrap());
-        },
-        Commands::ExportWallet {  } => {
-            let (mnemonic, block_height) = key_derivation::get_mnemonic_and_block_height(&client_config).await;
-            
-            let coins = wallet::get_coins(&client_config).await;
-
-            let state_entity_endpoint = client_config.statechain_entity.clone();
-            let electrum_endpoint = client_config.electrum_server_url.clone();
-
-            let wallet_json = serde_json::to_string_pretty(&json!({
-                "wallet": {
-                    "name": "default",
-                    "network": client_config.network.to_string(),
-                    "mnemonic": mnemonic,
-                    "version": 0.1,
-                    "state_entity_endpoint": state_entity_endpoint,
-                    "electrum_endpoint": electrum_endpoint,
-                    "blockheight": block_height,
-                    "coins": coins,
-                }
-            })).unwrap();
-            println!("{}", wallet_json);
-
-            let mut file = File::create("wallet.json").unwrap();
-            file.write_all(wallet_json.as_bytes()).unwrap();
-            println!("JSON written to output.json");
-        },
-    };
-
-    client_config.pool.close().await;
-}
diff --git a/clients/standalone-rust/src/send_backup.rs b/clients/standalone-rust/src/send_backup.rs
deleted file mode 100644
index 8499fceb..00000000
--- a/clients/standalone-rust/src/send_backup.rs
+++ /dev/null
@@ -1,259 +0,0 @@
-use std::{collections::{HashMap, BTreeMap}, str::FromStr};
-
-use bitcoin::{Address, TxOut, Transaction, OutPoint, TxIn, ScriptBuf, Witness, absolute, psbt::{Psbt, Input, PsbtSighashType, self}, bip32::{Fingerprint, DerivationPath}, Amount, sighash::{TapSighashType, SighashCache, self, TapSighash}, taproot::{TapLeafHash, self}, secp256k1, key::TapTweak};
-use electrum_client::ListUnspentRes;
-use secp256k1_zkp::{SecretKey, XOnlyPublicKey, PublicKey, Secp256k1};
-use sqlx::{Sqlite, Row};
-
-use crate::electrum;
-
-#[derive(Debug)]
-pub struct AddressInfo {
-    pub address: Address,
-    pub secret_key: SecretKey,
-    pub xonly_public_key: XOnlyPublicKey,
-    pub fingerprint: String,
-    pub derivation_path: String,
-    /// Confirmation height of the transaction that created this output.
-    pub height: usize,
-    /// Txid of the transaction
-    pub tx_hash: bitcoin::Txid,
-    /// Index of the output in the transaction.
-    pub tx_pos: usize,
-    /// Value of the output.
-    pub value: u64,
-}
-
-pub async fn get_address_info(pool: &sqlx::Pool, list_utxo: Vec::<(ListUnspentRes, Address)>) -> Vec:: {
-
-    let mut list_unspent = Vec::::new(); 
-
-    for (utxo, backup_address) in list_utxo {
-
-        let query = "SELECT client_seckey_share, client_pubkey_share, fingerprint, client_derivation_path \
-            FROM signer_data \
-            WHERE backup_address = $1";
-
-        let row = sqlx::query(query)
-            .bind(&backup_address.to_string())
-            .fetch_one(pool)
-            .await
-            .unwrap();
-
-        let secret_key_bytes = row.get::, _>("client_seckey_share");
-        let secret_key = SecretKey::from_slice(&secret_key_bytes).unwrap();
-
-        let public_key_bytes = row.get::, _>("client_pubkey_share");
-        let xonly_public_key = PublicKey::from_slice(&public_key_bytes).unwrap().x_only_public_key().0;
-
-        let fingerprint = row.get::("fingerprint");
-        let derivation_path = row.get::("client_derivation_path");
-
-        list_unspent.push(AddressInfo {
-            address: backup_address,
-            secret_key,
-            xonly_public_key,
-            fingerprint,
-            derivation_path,
-            height: utxo.height,
-            tx_hash: utxo.tx_hash,
-            tx_pos: utxo.tx_pos,
-            value: utxo.value,
-        });
-    }
-
-    list_unspent
-
-}
-
-pub fn send_all_funds(list_utxo: &Vec::, to_address: &Address, fee_rate_sats_per_byte: u64, electrum_client: &electrum_client::Client) {
-
-    let input_amount: u64 = list_utxo.iter().map(|s| s.value).sum();
-
-    let outputs = vec![
-        TxOut { value: input_amount, script_pubkey: to_address.script_pubkey() },
-    ];
-
-    let tx = create_transaction(list_utxo, &outputs).unwrap();
-
-    let absolute_fee: u64 = tx.vsize() as u64 * fee_rate_sats_per_byte;
-
-    let amount_out = input_amount - absolute_fee;
-
-    let outputs = vec![
-            TxOut { value: amount_out, script_pubkey: to_address.script_pubkey() },
-    ];
-
-    let tx = create_transaction(list_utxo, &outputs).unwrap();
-
-    let tx_bytes = bitcoin::consensus::encode::serialize(&tx);
-    let txid = electrum::transaction_broadcast_raw(&electrum_client, &tx_bytes);
-
-    println!("--> txid sent: {}", txid);
-
-
-}
-
-fn create_transaction(inputs_info: &Vec::, outputs: &Vec) -> Result> {
-
-    let secp = Secp256k1::new();
-
-    let mut tx_inputs = Vec::::new();
-
-    let mut secret_keys = HashMap::new();
-
-    for input in inputs_info {
-        secret_keys.insert(input.xonly_public_key, input.secret_key);
-    }
-
-    for input in inputs_info {
-        let input_utxo = OutPoint { txid: input.tx_hash, vout: input.tx_pos as u32 };
-        let input = TxIn {
-            previous_output: input_utxo,
-            script_sig: ScriptBuf::new(),
-            sequence: bitcoin::Sequence(0xFFFFFFFF), // Ignore nSequence.
-            witness: Witness::default(),
-        };
-        tx_inputs.push(input);
-    }
-
-    let tx1 = Transaction {
-        version: 2,
-        lock_time: absolute::LockTime::ZERO,
-        input: tx_inputs,
-        output: outputs.clone(),
-    };
-    let mut psbt = Psbt::from_unsigned_tx(tx1).unwrap();
-
-    let mut origins = BTreeMap::new();
-    for input in inputs_info {
-        origins.insert(
-            input.xonly_public_key,
-            (
-                vec![],
-                (
-                    Fingerprint::from_str(&input.fingerprint).unwrap(),
-                    DerivationPath::from_str(&input.derivation_path).unwrap(),
-                ),
-            ),
-        );
-    }
-
-    let mut psbt_inputs = Vec::::new();
-
-    for input_info in inputs_info {
-        let mut input = Input {
-            witness_utxo: {
-                let script_pubkey = input_info.address.script_pubkey();
-                let amount = Amount::from_sat(input_info.value);
-    
-                Some(TxOut { value: amount.to_sat(), script_pubkey })
-            },
-            tap_key_origins: origins.clone(),
-            ..Default::default()
-        };
-        let ty = PsbtSighashType::from_str("SIGHASH_ALL").unwrap();
-        input.sighash_type = Some(ty);
-        input.tap_internal_key = Some(input_info.xonly_public_key);
-        psbt_inputs.push(input);
-    }
-
-    psbt.inputs = psbt_inputs;
-
-    // SIGNER
-    let unsigned_tx = psbt.unsigned_tx.clone();
-
-    let mut input_txouts = Vec::::new();
-    for input_info in inputs_info {
-        input_txouts.push(TxOut { value: input_info.value, script_pubkey: input_info.address.script_pubkey() });
-    }
-
-    psbt.inputs.iter_mut().enumerate().try_for_each::<_, Result<(), Box>>(
-        |(vout, input)| {
-
-            let hash_ty = input
-                .sighash_type
-                .and_then(|psbt_sighash_type| psbt_sighash_type.taproot_hash_ty().ok())
-                .unwrap_or(TapSighashType::All);
-
-            let hash = SighashCache::new(&unsigned_tx).taproot_key_spend_signature_hash(
-                vout,
-                &sighash::Prevouts::All(&input_txouts.as_slice()),
-                hash_ty,
-            ).unwrap();
-
-            let secret_key = secret_keys.get(&input.tap_internal_key.ok_or("Internal key missing in PSBT")?).unwrap();
-
-            sign_psbt_taproot(
-                &secret_key,
-                input.tap_internal_key.unwrap(),
-                None,
-                input,
-                hash,
-                hash_ty,
-                &secp,
-            );
-
-            Ok(())
-        },
-    ).unwrap();
-
-    // FINALIZER
-    psbt.inputs.iter_mut().for_each(|input| {
-        let mut script_witness: Witness = Witness::new();
-        script_witness.push(input.tap_key_sig.unwrap().to_vec());
-        input.final_script_witness = Some(script_witness);
-
-        // Clear all the data fields as per the spec.
-        input.partial_sigs = BTreeMap::new();
-        input.sighash_type = None;
-        input.redeem_script = None;
-        input.witness_script = None;
-        input.bip32_derivation = BTreeMap::new();
-    });
-
-    let tx = psbt.extract_tx();
-    
-    //let mut prev_out_verify = Vec::::new();
-    for input in inputs_info {
-        let script_pubkey_hex = input.address.script_pubkey().to_hex_string();
-        let amount = Amount::from_sat(input.value);
-
-        //prev_out_verify.push(TxOut { value: amount.to_sat(), script_pubkey });
-        tx.verify(|_| {
-            Some(TxOut { 
-                value: amount.to_sat(), 
-                script_pubkey: ScriptBuf::from_hex(&script_pubkey_hex).unwrap() 
-            })
-        })
-        .expect("failed to verify transaction");
-    }
-
-    Ok(tx)
-}
-
-fn sign_psbt_taproot(
-    secret_key: &SecretKey,
-    pubkey: XOnlyPublicKey,
-    leaf_hash: Option,
-    psbt_input: &mut psbt::Input,
-    hash: TapSighash,
-    hash_ty: TapSighashType,
-    secp: &Secp256k1,
-) {
-    let keypair = secp256k1::KeyPair::from_seckey_slice(secp, secret_key.as_ref()).unwrap();
-    let keypair = match leaf_hash {
-        None => keypair.tap_tweak(secp, psbt_input.tap_merkle_root).to_inner(),
-        Some(_) => keypair, // no tweak for script spend
-    };
-
-    let sig = secp.sign_schnorr(&hash.into(), &keypair);
-
-    let final_signature = taproot::Signature { sig, hash_ty };
-
-    if let Some(lh) = leaf_hash {
-        psbt_input.tap_script_sigs.insert((pubkey, lh), final_signature);
-    } else {
-        psbt_input.tap_key_sig = Some(final_signature);
-    }
-}
\ No newline at end of file
diff --git a/clients/standalone-rust/src/transaction.rs b/clients/standalone-rust/src/transaction.rs
deleted file mode 100644
index 28ca431d..00000000
--- a/clients/standalone-rust/src/transaction.rs
+++ /dev/null
@@ -1,373 +0,0 @@
-use std::{str::FromStr, collections::BTreeMap};
-
-use bitcoin::{Txid, ScriptBuf, Transaction, absolute, TxIn, OutPoint, Witness, TxOut, psbt::{Psbt, Input, PsbtSighashType}, sighash::{TapSighashType, SighashCache, self, TapSighash}, secp256k1, taproot::{TapTweakHash, self}, hashes::{Hash, sha256}, Address};
-use mercury_lib::transaction::{ServerPublicNonceResponsePayload, PartialSignatureResponsePayload};
-use rand::Rng;
-use secp256k1_zkp::{SecretKey, PublicKey,  Secp256k1, schnorr::Signature, Message, musig::{MusigSessionId, MusigPubNonce, BlindingFactor, MusigSession, MusigPartialSignature, blinded_musig_pubkey_xonly_tweak_add, blinded_musig_negate_seckey, MusigAggNonce}, new_musig_nonce_pair, KeyPair};
-use serde::{Serialize, Deserialize};
-
-use crate::{error::CError, client_config::ClientConfig};
-
-/// The purpose of this function is to get a random locktime for the withdrawal transaction.
-/// This is done to improve privacy and discourage fee sniping.
-/// This function assumes that the block_height is the current block height.
-fn get_locktime_for_withdrawal_transaction (block_height: u32) -> u32 {
-
-    let mut locktime = block_height as i32;
-
-    let mut rng = rand::thread_rng();
-    let number = rng.gen_range(0..=10);
-
-    // sometimes locktime is set a bit further back, for privacy reasons
-    if number == 0 {
-        locktime = locktime - rng.gen_range(0..=99);
-    }
-
-    std::cmp::max(0, locktime) as u32
-}
-
-pub async fn new_backup_transaction(
-    client_config: &ClientConfig,
-    block_height: u32,
-    statechain_id: &str,
-    signed_statechain_id: &Signature,
-    client_seckey: &SecretKey,
-    client_pubkey: &PublicKey,
-    server_pubkey: &PublicKey,
-    input_txid: Txid, 
-    input_vout: u32, 
-    input_pubkey: &PublicKey, 
-    input_scriptpubkey: &ScriptBuf, 
-    input_amount: u64, 
-    to_address: &Address,
-    is_withdrawal: bool) 
-    -> Result<(Transaction, MusigPubNonce, MusigPubNonce, BlindingFactor), CError>  {
-
-    const BACKUP_TX_SIZE: u64 = 112; // virtual size one input P2TR and one output P2TR
-    // 163 is the real size one input P2TR and one output P2TR
-
-    let info_config_data = crate::utils::info_config(&client_config.statechain_entity, &client_config.electrum_client, &client_config.tor_proxy).await.unwrap();
-
-    let initlock = info_config_data.initlock;
-    let interval = info_config_data.interval;
-    let fee_rate_sats_per_byte = info_config_data.fee_rate_sats_per_byte;
-
-    let qt_backup_tx = client_config.count_backup_tx(statechain_id).await as u32;
-
-    let absolute_fee: u64 = BACKUP_TX_SIZE * fee_rate_sats_per_byte; 
-    let amount_out = input_amount - absolute_fee;
-
-    let tx_out = TxOut { value: amount_out, script_pubkey: to_address.script_pubkey() };
-
-    // if qt_backup_tx == 0, it means this is the first backup transaction (Tx0)
-    // In this case, the block_height is equal to the current block height
-    // Otherwise, block_height is equal to the Tx0.lock_time + initlock
-    let initlock = if qt_backup_tx == 0 { initlock } else { 0 };
-
-    let block_height = if is_withdrawal { get_locktime_for_withdrawal_transaction(block_height) } else { (block_height + initlock) - (interval * qt_backup_tx) };
-
-    let (tx, client_pub_nonce, server_pub_nonce, blinding_factor) = create(
-        client_config,
-        block_height,
-        statechain_id,
-        signed_statechain_id,
-        client_seckey,
-        client_pubkey,
-        server_pubkey,
-        input_txid, 
-        input_vout, 
-        input_pubkey, 
-        input_scriptpubkey, 
-        input_amount, 
-        tx_out).await.unwrap();
-
-    Ok((tx, client_pub_nonce, server_pub_nonce, blinding_factor))
-
-}
-
-async fn create(
-    client_config: &ClientConfig,
-    block_height: u32,
-    statechain_id: &str,
-    signed_statechain_id: &Signature,
-    client_seckey: &SecretKey,
-    client_pubkey: &PublicKey,
-    server_pubkey: &PublicKey,
-    input_txid: Txid, 
-    input_vout: u32, 
-    input_pubkey: &PublicKey, 
-    input_scriptpubkey: &ScriptBuf, 
-    input_amount: u64, 
-    output: TxOut) -> Result<(Transaction, MusigPubNonce, MusigPubNonce, BlindingFactor), Box> {
-
-    let input_xonly_pubkey = input_pubkey.x_only_public_key().0;
-
-    let outputs = [output].to_vec();
-
-    let lock_time = absolute::LockTime::from_height(block_height).expect("valid height");
-
-    let tx1 = Transaction {
-        version: 2,
-        lock_time,
-        input: vec![TxIn {
-            previous_output: OutPoint { txid: input_txid, vout: input_vout },
-            script_sig: ScriptBuf::new(),
-            sequence: bitcoin::Sequence(0xFFFFFFFF), // Ignore nSequence.
-            witness: Witness::default(),
-        }],
-        output: outputs,
-    };
-    let mut psbt = Psbt::from_unsigned_tx(tx1)?;
-
-    let mut input = Input {
-        witness_utxo: Some(TxOut { value: input_amount, script_pubkey: input_scriptpubkey.to_owned() }),
-        ..Default::default()
-    };
-    let ty = PsbtSighashType::from_str("SIGHASH_ALL")?;
-    input.sighash_type = Some(ty);
-    input.tap_internal_key = Some(input_xonly_pubkey.to_owned());
-    psbt.inputs = vec![input];
-
-    let secp = Secp256k1::new();
-    
-    let unsigned_tx = psbt.unsigned_tx.clone();
-
-    // There must not be more than one input.
-    // The input is the funding transaction and the output the backup address.
-    // If there is more than one input, the UPDATE command below will rewrite the client_sec_nonce and blinding_factor.
-    assert!(psbt.inputs.len() == 1);
-
-    // for (vout, input) in psbt.inputs.iter_mut().enumerate() {
-
-        let vout = 0;
-        let input = psbt.inputs.iter_mut().nth(vout).unwrap();
-
-        let hash_ty = input
-            .sighash_type
-            .and_then(|psbt_sighash_type| psbt_sighash_type.taproot_hash_ty().ok())
-            .unwrap_or(TapSighashType::All);
-
-        let hash = SighashCache::new(&unsigned_tx).taproot_key_spend_signature_hash(
-            vout,
-            &sighash::Prevouts::All(&[TxOut {
-                value: input.witness_utxo.as_ref().unwrap().value,
-                script_pubkey: input.witness_utxo.as_ref().unwrap().script_pubkey.clone(),
-            }]),
-            hash_ty,
-        ).unwrap();
-
-        let (sig, client_pub_nonce, server_pub_nonce, blinding_factor) = musig_sign_psbt_taproot(
-            client_config,
-            statechain_id,
-            signed_statechain_id,
-            client_seckey,
-            client_pubkey,
-            server_pubkey,
-            input_pubkey,
-            hash,
-            &secp,
-        ).await.unwrap();
-
-        let final_signature = taproot::Signature { sig, hash_ty };
-
-        input.tap_key_sig = Some(final_signature);
-    // }
-
-    // FINALIZER
-    psbt.inputs.iter_mut().for_each(|input| {
-        let mut script_witness: Witness = Witness::new();
-        script_witness.push(input.tap_key_sig.unwrap().to_vec());
-        input.final_script_witness = Some(script_witness);
-
-        // Clear all the data fields as per the spec.
-        input.partial_sigs = BTreeMap::new();
-        input.sighash_type = None;
-        input.redeem_script = None;
-        input.witness_script = None;
-        input.bip32_derivation = BTreeMap::new();
-    });
-
-    let tx = psbt.extract_tx();
-
-    tx.verify(|_| {
-        Some(TxOut {
-            value: input_amount,
-            script_pubkey: input_scriptpubkey.to_owned(),
-        })
-    })
-    .expect("failed to verify transaction");
-
-
-    Ok((tx, client_pub_nonce, server_pub_nonce, blinding_factor))
-}
-
-
-#[derive(Serialize, Deserialize)]
-pub struct SignFirstRequestPayload<'r> {
-    statechain_id: &'r str,
-    r2_commitment: &'r str,
-    blind_commitment: &'r str,
-    signed_statechain_id: &'r str,
-}
-
-async fn musig_sign_psbt_taproot(
-    client_config: &ClientConfig,
-    statechain_id: &str,
-    signed_statechain_id: &Signature,
-    client_seckey: &SecretKey,
-    client_pubkey: &PublicKey,
-    server_pubkey: &PublicKey,
-    input_pubkey: &PublicKey,
-    hash: TapSighash,
-    secp: &Secp256k1,
-)  -> Result<(Signature, MusigPubNonce, MusigPubNonce, BlindingFactor), CError>  {
-    let msg: Message = hash.into();
-
-    let client_session_id = MusigSessionId::new(&mut rand::thread_rng());
-
-    let (client_sec_nonce, client_pub_nonce) = new_musig_nonce_pair(&secp, client_session_id, None, Some(client_seckey.to_owned()), client_pubkey.to_owned(), None, None).unwrap();
-
-    let r2_commitment = sha256::Hash::hash(&client_pub_nonce.serialize());
-
-    let blinding_factor = BlindingFactor::new(&mut rand::thread_rng());
-    let blind_commitment = sha256::Hash::hash(blinding_factor.as_bytes());
-
-    let endpoint = client_config.statechain_entity.clone();
-    let path = "sign/first";
-
-    let tor_proxy = client_config.tor_proxy.clone();
-
-    let mut client: reqwest::Client = reqwest::Client::new();
-    if tor_proxy != "".to_string() {
-        let tor_proxy = reqwest::Proxy::all(tor_proxy).unwrap();
-        client = reqwest::Client::builder().proxy(tor_proxy).build().unwrap();
-    }
-    let request = client.post(&format!("{}/{}", endpoint, path));
-
-    let sign_first_request_payload = SignFirstRequestPayload {
-        statechain_id,
-        r2_commitment: &r2_commitment.to_string(),
-        blind_commitment: &blind_commitment.to_string(),
-        signed_statechain_id: &signed_statechain_id.to_string(),
-    };
-
-    let value = match request.json(&sign_first_request_payload).send().await {
-        Ok(response) => {
-            let text = response.text().await.unwrap();
-            text
-        },
-        Err(err) => {
-            return Err(CError::Generic(err.to_string()));
-        },
-    };
-
-    let response: ServerPublicNonceResponsePayload = serde_json::from_str(value.as_str()).expect(&format!("failed to parse: {}", value.as_str()));
-
-    let mut server_pubnonce_hex = response.server_pubnonce.to_string();
-
-    if server_pubnonce_hex.starts_with("0x") {
-        server_pubnonce_hex = server_pubnonce_hex[2..].to_string();
-    }
-
-    let server_pub_nonce_bytes = hex::decode(server_pubnonce_hex.clone()).unwrap();
-    
-    let server_pub_nonce = MusigPubNonce::from_slice(server_pub_nonce_bytes.as_slice()).unwrap();
-
-    let aggregate_pubkey = client_pubkey.combine(&server_pubkey).unwrap();
-
-    if aggregate_pubkey != input_pubkey.to_owned() {
-        return Err(CError::Generic("Input public key is different than the combination of client and server public keys.".to_string()));
-    }
-
-    let tap_tweak = TapTweakHash::from_key_and_tweak(aggregate_pubkey.x_only_public_key().0, None);
-    let tap_tweak_bytes = tap_tweak.as_byte_array();
-
-    // tranform tweak: Scalar to SecretKey
-    let tweak = SecretKey::from_slice(tap_tweak_bytes).unwrap();
-
-    let (parity_acc, output_pubkey, out_tweak32) = blinded_musig_pubkey_xonly_tweak_add(&secp, &aggregate_pubkey, tweak);
-
-    let aggnonce = MusigAggNonce::new(&secp, &[client_pub_nonce, server_pub_nonce]);
-
-    let session = MusigSession::new_blinded_without_key_agg_cache(
-        &secp,
-        &output_pubkey,
-        aggnonce,
-        msg,
-        None,
-        &blinding_factor,
-        out_tweak32
-    );
-
-    let negate_seckey = blinded_musig_negate_seckey(
-        &secp,
-        &output_pubkey,
-        parity_acc,
-    );
-
-    let client_keypair = KeyPair::from_secret_key(&secp, &client_seckey);
-
-    let client_partial_sig = session.blinded_partial_sign_without_keyaggcoeff(&secp, client_sec_nonce, &client_keypair, negate_seckey).unwrap();
-
-    assert!(session.blinded_musig_partial_sig_verify(&secp, &client_partial_sig, &client_pub_nonce, &client_pubkey, &output_pubkey, parity_acc));
-
-    session.remove_fin_nonce_from_session();
-
-    let negate_seckey = match negate_seckey {
-        true => 1,
-        false => 0,
-    };
-
-    let blinded_session = session.remove_fin_nonce_from_session();
-
-    let payload = mercury_lib::transaction::PartialSignatureRequestPayload {
-        statechain_id: statechain_id.to_string(),
-        negate_seckey,
-        session: hex::encode(blinded_session.serialize()).to_string(),
-        signed_statechain_id: signed_statechain_id.to_string(),
-        server_pub_nonce: server_pubnonce_hex,
-    };
-
-    let path = "sign/second";
-
-    let tor_proxy = client_config.tor_proxy.clone();
-
-    let mut client: reqwest::Client = reqwest::Client::new();
-    if tor_proxy != "".to_string() {
-        let tor_proxy = reqwest::Proxy::all(tor_proxy).unwrap();
-        client = reqwest::Client::builder().proxy(tor_proxy).build().unwrap();
-    }
-    let request = client.post(&format!("{}/{}", endpoint, path));
-
-    let value = match request.json(&payload).send().await {
-        Ok(response) => {
-            let text = response.text().await.unwrap();
-            text
-        },
-        Err(err) => {
-            return Err(CError::Generic(err.to_string()));
-        },
-    };
-
-    let response: PartialSignatureResponsePayload = serde_json::from_str(value.as_str()).expect(&format!("failed to parse: {}", value.as_str()));
-
-    let mut server_partial_sig_hex = response.partial_sig.to_string();
-
-    if server_partial_sig_hex.starts_with("0x") {
-        server_partial_sig_hex = server_partial_sig_hex[2..].to_string();
-    }
-
-    let server_partial_sig_bytes = hex::decode(server_partial_sig_hex).unwrap();
-
-    let server_partial_sig = MusigPartialSignature::from_slice(server_partial_sig_bytes.as_slice()).unwrap();
-
-    assert!(session.blinded_musig_partial_sig_verify(&secp, &server_partial_sig, &server_pub_nonce, &server_pubkey, &output_pubkey, parity_acc));
-
-    let sig = session.partial_sig_agg(&[client_partial_sig, server_partial_sig]);
-
-    let x_only_key_tweaked = output_pubkey.x_only_public_key().0;
-
-    assert!(secp.verify_schnorr(&sig, &msg, &x_only_key_tweaked).is_ok());
-   
-    Ok((sig, client_pub_nonce, server_pub_nonce, blinding_factor))
-}
diff --git a/clients/standalone-rust/src/transfer_receiver.rs b/clients/standalone-rust/src/transfer_receiver.rs
deleted file mode 100644
index f2e6cf75..00000000
--- a/clients/standalone-rust/src/transfer_receiver.rs
+++ /dev/null
@@ -1,500 +0,0 @@
-use std::str::FromStr;
-
-use bitcoin::{Transaction, Network, Address, Txid, sighash::{SighashCache, TapSighashType, self}, TxOut, taproot::TapTweakHash, hashes::{Hash, sha256}, secp256k1};
-use mercury_lib::transfer::receiver::{GetMsgAddrResponsePayload, StatechainInfoResponsePayload, StatechainInfo};
-use secp256k1_zkp::{SecretKey, PublicKey, Secp256k1, schnorr::Signature, XOnlyPublicKey, Message, musig::{MusigAggNonce,  MusigSession,  blinded_musig_pubkey_xonly_tweak_add}, Scalar};
-use serde::{Serialize, Deserialize};
-use serde_json::Value;
-
-use crate::{error::CError, electrum, utils::InfoConfig, client_config::ClientConfig};
-
-async fn get_msg_addr(auth_pubkey: &secp256k1_zkp::PublicKey, statechain_entity_url: &str, client_config: &ClientConfig) -> Result, CError> {
-    let endpoint = statechain_entity_url;
-    let path = format!("transfer/get_msg_addr/{}", auth_pubkey.to_string());
-
-    let tor_proxy = client_config.tor_proxy.clone();
-
-    let mut client: reqwest::Client = reqwest::Client::new();
-    if tor_proxy != "".to_string() {
-        let tor_proxy = reqwest::Proxy::all(tor_proxy).unwrap();
-        client = reqwest::Client::builder().proxy(tor_proxy).build().unwrap();
-    }
-    let request = client.get(&format!("{}/{}", endpoint, path));
-
-    let value = match request.send().await {
-        Ok(response) => {
-            let text = response.text().await.unwrap();
-            text
-        },
-        Err(err) => {
-            return Err(CError::Generic(err.to_string()));
-        },
-    };
-
-    let response: GetMsgAddrResponsePayload = serde_json::from_str(value.as_str()).expect(&format!("failed to parse: {}", value.as_str()));
-
-    Ok(response.list_enc_transfer_msg)
-}
-
-fn validate_t1pub(t1: &[u8; 32], x1_pub: &PublicKey, sender_public_key: &PublicKey) -> bool {
-
-    let secret_t1 = SecretKey::from_slice(t1).unwrap();
-    let public_t1 = secret_t1.public_key(&Secp256k1::new());
-
-    let result_pubkey = sender_public_key.combine(&x1_pub).unwrap();
-
-    result_pubkey == public_t1
-}
-
-fn calculate_t2(transfer_msg: &mercury_lib::transfer::TransferMsg1, client_seckey_share: &SecretKey,) -> SecretKey {
-
-    let t1 = Scalar::from_be_bytes(transfer_msg.t1).unwrap();
-
-    let negated_seckey = client_seckey_share.negate();
-
-    let t2 = negated_seckey.add_tweak(&t1).unwrap();
-
-    t2
-}
-
-/// step 3. Owner 2 verifies that the latest backup transaction pays to their key O2 and that the input (Tx0) is unspent.
-async fn verify_latest_backup_tx_pays_to_user_pubkey(transfer_msg: &mercury_lib::transfer::TransferMsg1, client_pubkey_share: &PublicKey, network: Network,) -> bool {
-
-    let last_tx = transfer_msg.backup_transactions.last().unwrap();
-
-    let backup_tx = last_tx.deserialize();
-
-    let output = &backup_tx.tx.output[0];
-
-    let aggregate_address = Address::p2tr(&Secp256k1::new(), client_pubkey_share.x_only_public_key().0, None, network);
-
-    output.script_pubkey == aggregate_address.script_pubkey()
-}
-
-fn get_tx_hash(transaction: &Transaction, electrum_client: &electrum_client::Client) -> Message {
-
-    let witness = transaction.input[0].witness.clone();
-
-    let witness_data = witness.nth(0).unwrap();
-
-    let vout = transaction.input[0].previous_output.vout as usize;
-
-    let txid = transaction.input[0].previous_output.txid.to_string();
-
-    let res = electrum::batch_transaction_get_raw(electrum_client, &[Txid::from_str(&txid).unwrap()]);
-
-    let funding_tx_bytes = res[0].clone();
-
-    let funding_tx: Transaction = bitcoin::consensus::encode::deserialize(&funding_tx_bytes).unwrap();
-
-    let funding_tx_output = funding_tx.output[vout].clone();
-
-    let sighash_type = TapSighashType::from_consensus_u8(witness_data.last().unwrap().to_owned()).unwrap();
-
-    let hash = SighashCache::new(transaction).taproot_key_spend_signature_hash(
-        0,
-        &sighash::Prevouts::All(&[TxOut {
-            value: funding_tx_output.value,
-            script_pubkey: funding_tx_output.script_pubkey.clone(),
-        }]),
-        sighash_type,
-    ).unwrap();
-
-    let msg: Message = hash.into();
-
-    msg
-}
-
-/// step 4a. Verifiy if the signature is valid.
-async fn verify_transaction_signature(transaction: &Transaction, fee_rate_sats_per_byte: u64, client_config: &ClientConfig) -> Result<(), CError> {
-
-    let witness = transaction.input[0].witness.clone();
-
-    let witness_data = witness.nth(0).unwrap();
-
-    // the last element is the hash type
-    let signature_data = witness_data.split_last().unwrap().1;
-
-    let signature = Signature::from_slice(signature_data).unwrap();
-
-    let txid = transaction.input[0].previous_output.txid.to_string();
-
-    let res = electrum::batch_transaction_get_raw(&client_config.electrum_client, &[Txid::from_str(&txid).unwrap()]);
-
-    let funding_tx_bytes = res[0].clone();
-
-    let funding_tx: Transaction = bitcoin::consensus::encode::deserialize(&funding_tx_bytes).unwrap();
-
-    let vout = transaction.input[0].previous_output.vout as usize;
-
-    let funding_tx_output = funding_tx.output[vout].clone();
-
-    let res = electrum::get_script_pubkey_list_unspent(&client_config.electrum_client, &funding_tx_output.script_pubkey.as_script());
-
-    if res.len() == 0 {
-        return Err(CError::Generic("The funding UTXO is spent".to_string()));
-    } 
-
-    let xonly_pubkey = XOnlyPublicKey::from_slice(funding_tx_output.script_pubkey[2..].as_bytes()).unwrap();
-
-    let sighash_type = TapSighashType::from_consensus_u8(witness_data.last().unwrap().to_owned()).unwrap();
-
-    let hash = SighashCache::new(transaction).taproot_key_spend_signature_hash(
-        0,
-        &sighash::Prevouts::All(&[TxOut {
-            value: funding_tx_output.value,
-            script_pubkey: funding_tx_output.script_pubkey.clone(),
-        }]),
-        sighash_type,
-    ).unwrap();
-
-    let msg: Message = hash.into();
-
-    let fee = funding_tx_output.value - transaction.output[0].value;
-    let fee_rate = fee / transaction.vsize() as u64;
-
-    if (fee_rate as i64 + client_config.fee_rate_tolerance as i64) < fee_rate_sats_per_byte as i64 {
-        return Err(CError::Generic("Fee rate too low".to_string()));
-    }
-
-    if (fee_rate as i64 - client_config.fee_rate_tolerance as i64) > fee_rate_sats_per_byte as i64 {
-        return Err(CError::Generic("Fee rate too high".to_string()));
-    }
-
-    if !Secp256k1::new().verify_schnorr(&signature, &msg, &xonly_pubkey).is_ok() {
-        return Err(CError::Generic("Invalid signature".to_string()));
-    }
-
-    Ok(())
-
-}
-
-async fn get_funding_transaction_info(transaction: &Transaction, electrum_client: &electrum_client::Client) -> (XOnlyPublicKey, Txid, usize, u64) {
-
-    let txid = transaction.input[0].previous_output.txid;
-
-    let res = electrum::batch_transaction_get_raw(&electrum_client, &[txid]);
-
-    let funding_tx_bytes = res[0].clone();
-
-    let funding_tx: Transaction = bitcoin::consensus::encode::deserialize(&funding_tx_bytes).unwrap();
-
-    let vout = transaction.input[0].previous_output.vout as usize;
-
-    let funding_tx_output = funding_tx.output[vout].clone();
-
-    let xonly_pubkey = XOnlyPublicKey::from_slice(funding_tx_output.script_pubkey[2..].as_bytes()).unwrap();
-
-    (xonly_pubkey, txid, vout, funding_tx_output.value)
-}
-
-async fn verify_blinded_musig_scheme(backup_tx: &mercury_lib::transfer::ReceiverBackupTransaction, statechain_info: &StatechainInfo, electrum_client: &electrum_client::Client) -> Result<(), CError> {
-
-    let client_public_nonce = backup_tx.client_public_nonce.clone();
-    let server_public_nonce = backup_tx.server_public_nonce.clone();
-    let client_public_key = backup_tx.client_public_key.clone();
-    let server_public_key = backup_tx.server_public_key.clone();
-    let blinding_factor = &backup_tx.blinding_factor;
-
-    let blind_commitment = sha256::Hash::hash(blinding_factor.as_bytes());
-    let r2_commitment = sha256::Hash::hash(&client_public_nonce.serialize());
-
-    if statechain_info.blind_commitment != blind_commitment.to_string() {
-        return Err(CError::Generic("blind_commitment is not correct".to_string()));
-    }
-
-    if statechain_info.r2_commitment != r2_commitment.to_string() {
-        return Err(CError::Generic("r2_commitment is not correct".to_string()));
-    }
-
-    let secp = Secp256k1::new();
-
-    // TODO: this code is repeated in client/src/transaction/mod.rs. Move it to a common place.
-    let aggregate_pubkey = client_public_key.combine(&server_public_key).unwrap();
-
-    let tap_tweak = TapTweakHash::from_key_and_tweak(aggregate_pubkey.x_only_public_key().0, None);
-    let tap_tweak_bytes = tap_tweak.as_byte_array();
-
-    let tweak = SecretKey::from_slice(tap_tweak_bytes).unwrap();
-
-    let (_, output_pubkey, out_tweak32) = blinded_musig_pubkey_xonly_tweak_add(&secp, &aggregate_pubkey, tweak);
-    
-    let aggnonce = MusigAggNonce::new(&secp, &[client_public_nonce, server_public_nonce]);
-
-    let msg = get_tx_hash(&backup_tx.tx, electrum_client);
-
-    let session = MusigSession::new_blinded_without_key_agg_cache(
-        &secp,
-        &output_pubkey,
-        aggnonce,
-        msg,
-        None,
-        &blinding_factor,
-        out_tweak32
-    );
-    // END repeated code
-
-    let challenge = session.get_challenge_from_session();
-    let challenge = hex::encode(challenge);
-
-    if statechain_info.challenge != challenge {
-        return Err(CError::Generic("challenge is not correct".to_string()));
-    }
-
-    Ok(())
-
-}
-
-async fn get_statechain_info(statechain_id: &str, statechain_entity_url: &str, client_config: &ClientConfig) -> Result {
-
-    let endpoint = statechain_entity_url;
-    let path = format!("info/statechain/{}", statechain_id.to_string());
-
-    println!("statechain_id: {}", statechain_id.to_string());
-    println!("path: {}", path);
-
-    let tor_proxy = client_config.tor_proxy.clone();
-
-    let mut client: reqwest::Client = reqwest::Client::new();
-    if tor_proxy != "".to_string() {
-        let tor_proxy = reqwest::Proxy::all(tor_proxy).unwrap();
-        client = reqwest::Client::builder().proxy(tor_proxy).build().unwrap();
-    }
-    let request = client.get(&format!("{}/{}", endpoint, path));
-
-    let value = match request.send().await {
-        Ok(response) => {
-            let text = response.text().await.unwrap();
-            text
-        },
-        Err(err) => {
-            return Err(CError::Generic(err.to_string()));
-        },
-    };
-
-    let response: StatechainInfoResponsePayload = serde_json::from_str(value.as_str()).expect(&format!("failed to parse: {}", value.as_str()));
-
-    Ok(response)
-}
-
-fn verify_transfer_signature(new_user_pubkey: &PublicKey, input_txid: &Txid, input_vout: u32, signature: &Signature, sender_public_key: &XOnlyPublicKey) -> bool {
-
-    let secp = Secp256k1::new();
-
-    let mut data_to_verify = Vec::::new();
-    data_to_verify.extend_from_slice(&input_txid[..]);
-    data_to_verify.extend_from_slice(&input_vout.to_le_bytes());
-    data_to_verify.extend_from_slice(&new_user_pubkey.serialize()[..]);
-
-    let msg = Message::from_hashed_data::(&data_to_verify);
-
-    secp.verify_schnorr(signature, &msg, &sender_public_key).is_ok()
-}
-
-async fn process_encrypted_message(
-    client_config: &ClientConfig, 
-    client_auth_key: &SecretKey, 
-    client_seckey_share: &SecretKey, 
-    client_pubkey_share: &PublicKey, 
-    enc_messages: &Vec, 
-    info_config: &InfoConfig) -> Result<(), CError> {
-
-    for enc_message in enc_messages {
-
-        let decoded_enc_message = hex::decode(enc_message).unwrap();
-
-        let decrypted_msg = ecies::decrypt(client_auth_key.secret_bytes().as_slice(), decoded_enc_message.as_slice()).unwrap();
-
-        let decrypted_msg_str = String::from_utf8(decrypted_msg).unwrap();
-
-        let transfer_msg: mercury_lib::transfer::TransferMsg1 = serde_json::from_str(decrypted_msg_str.as_str()).unwrap();
-
-        let statechain_info = get_statechain_info(&transfer_msg.statechain_id, &client_config.statechain_entity, client_config).await.unwrap();
-
-        let backup_transaction = transfer_msg.backup_transactions.first().unwrap();
-
-        let backup_transaction = backup_transaction.deserialize(); 
-
-        let (funding_xonly_pubkey, txid, vout, amount) = get_funding_transaction_info(&backup_transaction.tx, &client_config.electrum_client).await;
-
-        let sender_public_key = PublicKey::from_str(&transfer_msg.user_public_key).unwrap();
-
-        let transfer_signature = Signature::from_str(&transfer_msg.transfer_signature).unwrap();
-
-        let is_transfer_signature_valid = verify_transfer_signature(
-            &client_pubkey_share, 
-            &txid, 
-            vout as u32, 
-            &transfer_signature, 
-            &sender_public_key.x_only_public_key().0
-        );
-
-        if !is_transfer_signature_valid {
-            println!("Invalid transfer signature");
-            continue;
-        }
-
-        // validate tranfer.pub_key + client_pub_key = funding_xonly_pubkey
-        let enclave_public_key = PublicKey::from_str(&statechain_info.enclave_public_key).unwrap();
-
-        let transfer_aggregate_pubkey = sender_public_key.combine(&enclave_public_key).unwrap();
-        let transfer_aggregate_xonly_pubkey = transfer_aggregate_pubkey.x_only_public_key().0;
-
-        let secp = Secp256k1::new();
-
-        let transfer_aggregate_address = Address::p2tr(&secp, transfer_aggregate_xonly_pubkey, None, client_config.network);
-
-        let transfer_aggregate_xonly_pubkey = XOnlyPublicKey::from_slice(transfer_aggregate_address.script_pubkey()[2..].as_bytes()).unwrap();
-        
-        if transfer_aggregate_xonly_pubkey != funding_xonly_pubkey {
-            println!("Aggregated public keys do not match. This statecoin may have been updated.");
-            continue;
-        }
-
-        if !verify_latest_backup_tx_pays_to_user_pubkey(&transfer_msg, client_pubkey_share, client_config.network).await {
-            return Err(CError::Generic("Latest backup tx does not pay to user pubkey".to_string()));
-        }
-
-        if statechain_info.num_sigs != transfer_msg.backup_transactions.len() as u32 {
-            return Err(CError::Generic("num_sigs is not correct".to_string()));
-        }
-
-        let mut previous_lock_time: Option = None;
-
-        for (index, backup_tx) in transfer_msg.backup_transactions.iter().enumerate() {
-
-            let statechain_info = statechain_info.statechain_info.get(index).unwrap();
-
-            let backup_tx = backup_tx.deserialize(); 
-            let is_signature_valid = verify_transaction_signature(&backup_tx.tx, info_config.fee_rate_sats_per_byte, client_config).await;
-            if is_signature_valid.is_err() {
-                return Err(is_signature_valid.err().unwrap());
-            }
-
-            let is_blinded_musig_scheme_valid = verify_blinded_musig_scheme(&backup_tx, statechain_info, &client_config.electrum_client).await;
-            if is_blinded_musig_scheme_valid.is_err() {
-                return Err(is_blinded_musig_scheme_valid.err().unwrap());
-            }
-
-            if previous_lock_time.is_some() {
-                let prev_lock_time = previous_lock_time.unwrap();
-                let current_lock_time = backup_tx.tx.lock_time.to_consensus_u32();
-                if (prev_lock_time - current_lock_time) as i32 != info_config.interval as i32 {
-                    return Err(CError::Generic("interval is not correct".to_string()));
-                }
-            }
-
-            previous_lock_time = Some(backup_tx.tx.lock_time.to_consensus_u32());
-        }
-
-        let x1_pub = PublicKey::from_str(&statechain_info.x1_pub).unwrap();
-
-        if !validate_t1pub(&transfer_msg.t1, &x1_pub, &sender_public_key) {
-            return Err(CError::Generic("Invalid t1".to_string()));
-        }
-
-        let t2 = calculate_t2(&transfer_msg, &client_seckey_share);
-
-        let t2_hex = hex::encode(t2.secret_bytes());
-
-        
-        let client_auth_keypair = secp256k1::KeyPair::from_seckey_slice(&secp, client_auth_key.as_ref()).unwrap();
-        let msg = Message::from_hashed_data::(t2_hex.as_bytes());
-        let auth_sig = secp.sign_schnorr(&msg, &client_auth_keypair);
-
-        let transfer_receiver_request_payload = mercury_lib::transfer::receiver::TransferReceiverRequestPayload {
-            statechain_id: transfer_msg.statechain_id.clone(),
-            batch_data: None,
-            t2: t2_hex,
-            auth_sig: auth_sig.to_string(),
-        };
-
-        let endpoint = client_config.statechain_entity.clone();
-        let path = "transfer/receiver";
-
-        let tor_proxy = client_config.tor_proxy.clone();
-
-        let mut client: reqwest::Client = reqwest::Client::new();
-        if tor_proxy != "".to_string() {
-            let tor_proxy = reqwest::Proxy::all(tor_proxy).unwrap();
-            client = reqwest::Client::builder().proxy(tor_proxy).build().unwrap();
-        }
-        let request = client.post(&format!("{}/{}", endpoint, path));
-
-        let value = match request.json(&transfer_receiver_request_payload).send().await {
-            Ok(response) => {
-                let text = response.text().await.unwrap();
-                text
-            },
-            Err(err) => {
-                return Err(CError::Generic(err.to_string()));
-            },
-        };
-
-        let response: Value = serde_json::from_str(value.as_str()).expect(&format!("failed to parse: {}", value.as_str()));
-
-        let server_public_key_hex = response.get("server_pubkey").unwrap().as_str().unwrap();
-
-        let server_pubkey_share = PublicKey::from_str(server_public_key_hex).unwrap();
-
-        let aggregate_pubkey = client_pubkey_share.combine(&server_pubkey_share).unwrap();
-
-        let aggregated_xonly_pubkey = aggregate_pubkey.x_only_public_key().0;
-
-        let aggregate_address = Address::p2tr(&secp, aggregated_xonly_pubkey, None, client_config.network);
-
-        let xonly_pubkey = XOnlyPublicKey::from_slice(aggregate_address.script_pubkey()[2..].as_bytes()).unwrap();
-
-        if funding_xonly_pubkey != xonly_pubkey {
-            return Err(CError::Generic("Aggregated public key is not correct".to_string()));
-        }
-
-        let statechain_id = transfer_msg.statechain_id.clone();
-
-        println!("statechain_id: {}", statechain_id);
-
-        let p2tr_agg_address = Address::p2tr(&secp, aggregated_xonly_pubkey, None, client_config.network);
-
-        let msg = Message::from_hashed_data::(statechain_id.to_string().as_bytes());
-        let signed_statechain_id = secp.sign_schnorr(&msg, &client_auth_keypair);
-
-        let vec_backup_transactions: Vec = transfer_msg.backup_transactions.iter().map(|x| x.deserialize()).collect();
-    
-        client_config.insert_or_update_new_statechain(
-            &statechain_id, 
-            amount as u32,  
-            &server_pubkey_share, 
-            &aggregate_pubkey, 
-            &p2tr_agg_address, 
-            client_pubkey_share,
-            &signed_statechain_id,
-            &txid,
-            vout as u32,
-            previous_lock_time.unwrap(),
-            &vec_backup_transactions).await;
-    }
-
-    Ok(())
-}
-
-pub async fn receive(client_config: &ClientConfig) {
-
-    let info_config = crate::utils::info_config(&client_config.statechain_entity, &client_config.electrum_client, &client_config.tor_proxy).await.unwrap();
-
-    let client_keys = client_config.get_all_auth_pubkey().await;
-
-    for client_key in client_keys {
-        let enc_messages = get_msg_addr(&client_key.1, &client_config.statechain_entity, client_config).await.unwrap();
-        if enc_messages.len() == 0 {
-            continue;
-        }
-        process_encrypted_message(
-            client_config, 
-            &client_key.0, 
-            &client_key.2,
-            &client_key.3, 
-            &enc_messages, 
-            &info_config, 
-        ).await.unwrap();
-    }
-}
\ No newline at end of file
diff --git a/clients/standalone-rust/src/transfer_sender.rs b/clients/standalone-rust/src/transfer_sender.rs
deleted file mode 100644
index 2fc775d6..00000000
--- a/clients/standalone-rust/src/transfer_sender.rs
+++ /dev/null
@@ -1,249 +0,0 @@
-use bitcoin::{Transaction, Address, secp256k1, hashes::sha256, Txid};
-use mercury_lib::transfer::sender::{TransferSenderRequestPayload, TransferSenderResponsePayload, TransferUpdateMsgRequestPayload};
-use secp256k1_zkp::{PublicKey, SecretKey, Secp256k1, Message, musig::{MusigPubNonce, BlindingFactor}, schnorr::Signature, Scalar};
-use serde::{Deserialize, Serialize};
-use serde_json::json;
-
-use crate::{error::CError, key_derivation, client_config::ClientConfig};
-
-// Step 7. Owner 1 then concatinates the Tx0 outpoint with the Owner 2 public key (O2) and signs it with their key o1 to generate SC_sig_1.
-fn create_transfer_signature(new_user_pubkey: PublicKey, input_txid: &Txid, input_vout: u32, client_seckey: &SecretKey) -> Signature {
-
-    let secp = Secp256k1::new();
-    let keypair = secp256k1::KeyPair::from_seckey_slice(&secp, client_seckey.as_ref()).unwrap();
-
-    let mut data_to_sign = Vec::::new();
-    data_to_sign.extend_from_slice(&input_txid[..]);
-    data_to_sign.extend_from_slice(&input_vout.to_le_bytes());
-    data_to_sign.extend_from_slice(&new_user_pubkey.serialize()[..]);
-
-    let msg = Message::from_hashed_data::(&data_to_sign);
-    let signature = secp.sign_schnorr(&msg, &keypair);
-
-    signature
-}
-
-async fn get_new_x1(client_config: &ClientConfig,  statechain_id: &str, signed_statechain_id: &Signature, new_auth_pubkey: &PublicKey) -> Result, CError> {
-    
-    let endpoint = client_config.statechain_entity.clone();
-    let path = "transfer/sender";
-
-    let tor_proxy = client_config.tor_proxy.clone();
-
-    let mut client: reqwest::Client = reqwest::Client::new();
-    if tor_proxy != "".to_string() {
-        let tor_proxy = reqwest::Proxy::all(tor_proxy).unwrap();
-        client = reqwest::Client::builder().proxy(tor_proxy).build().unwrap();
-    }
-    let request = client.post(&format!("{}/{}", endpoint, path));
-
-    let transfer_sender_request_payload = TransferSenderRequestPayload {
-        statechain_id: statechain_id.to_string(),
-        auth_sig: signed_statechain_id.to_string(),
-        new_user_auth_key: new_auth_pubkey.to_string(),
-        batch_id: None,
-    };
-
-    let value = match request.json(&transfer_sender_request_payload).send().await {
-        Ok(response) => {
-
-            let status = response.status();
-            let text = response.text().await.unwrap_or("Unexpected error".to_string());
-
-            if status.is_success() {
-                text
-            } else {
-                return Err(CError::Generic(format!("status: {}, error: {}", status, text)));
-            }
-        },
-        Err(err) => {
-            return Err(CError::Generic(format!("status: {}, error: {}", err.status().unwrap(),err.to_string())));
-        },
-    };
-
-    let response: TransferSenderResponsePayload = serde_json::from_str(value.as_str()).expect(&format!("failed to parse: {}", value.as_str()));
-
-    let x1 = hex::decode(response.x1).unwrap();
-
-    Ok(x1)
-}
-
-pub async fn save_new_backup_transaction(client_config: &ClientConfig, backup_transaction: &mercury_lib::transfer::SenderBackupTransaction) {
-
-    let tx_n = backup_transaction.tx_n; 
-    let tx_bytes = bitcoin::consensus::encode::serialize(&backup_transaction.tx);
-    let client_pub_nonce: [u8; 66] = backup_transaction.client_public_nonce.clone().try_into().unwrap();
-    let server_pub_nonce: [u8; 66] = backup_transaction.server_public_nonce.clone().try_into().unwrap();
-    let client_pubkey = &backup_transaction.client_public_key;
-    let server_pubkey = &backup_transaction.server_public_key;
-    let blinding_factor: [u8; 32] = backup_transaction.blinding_factor.clone().try_into().unwrap();
-    let statechain_id = &backup_transaction.statechain_id;
-    let recipient_address = &backup_transaction.recipient_address;
-
-    client_config.insert_transaction(tx_n, &tx_bytes, &client_pub_nonce, &server_pub_nonce, client_pubkey, server_pubkey, &blinding_factor, &statechain_id, recipient_address).await.unwrap();
-}
-
-pub async fn init(client_config: &ClientConfig, recipient_address: &str, statechain_id: &str) -> Result<(), CError>{
-
-    let (_, recipient_user_pubkey, recipient_auth_pubkey) = key_derivation::decode_transfer_address(recipient_address).unwrap();
-
-    let mut backup_transactions = client_config.get_backup_transactions(&statechain_id).await;
-
-    if backup_transactions.len() == 0 {
-        return Err(CError::Generic("No backup transactions found".to_string()));
-    }   
-
-    backup_transactions.sort_by(|a, b| a.tx_n.cmp(&b.tx_n));
-
-    let tx1 = &backup_transactions[0];
-
-    let (client_seckey, 
-        client_public_key, 
-        server_public_key,
-        input_txid, 
-        input_vout, 
-        transaction, 
-        client_pub_nonce, 
-        server_pub_nonce,
-        blinding_factor, 
-        signed_statechain_id) = 
-    create_backup_tx_to_receiver(&client_config, &tx1.tx, recipient_user_pubkey, &statechain_id).await;
-
-    let x1 = get_new_x1(client_config, &statechain_id, &signed_statechain_id, &recipient_auth_pubkey).await;
-
-    let new_tx_n = backup_transactions.last().unwrap().tx_n + 1;
-
-    let new_bakup_tx = mercury_lib::transfer::SenderBackupTransaction {
-        statechain_id: statechain_id.to_string(),
-        tx_n: new_tx_n,
-        tx: transaction,
-        client_public_nonce: client_pub_nonce.serialize().to_vec(),
-        server_public_nonce: server_pub_nonce.serialize().to_vec(),
-        client_public_key,
-        server_public_key,
-        blinding_factor: blinding_factor.as_bytes().to_vec(),
-        recipient_address: recipient_address.to_string(),
-    };
-
-    backup_transactions.push(new_bakup_tx.clone());
-
-    let mut serialized_backup_transactions = Vec::::new();
-
-    for backup_tx in backup_transactions {
-        serialized_backup_transactions.push(backup_tx.serialize());
-    }
-
-    let transfer_signature = create_transfer_signature(recipient_user_pubkey, &input_txid, input_vout, &client_seckey);
-
-    let x1: [u8; 32] = x1?.try_into().unwrap();
-    let x1 = Scalar::from_be_bytes(x1).unwrap();
-
-    let t1 = client_seckey.add_tweak(&x1).unwrap();
-
-    let transfer_msg = mercury_lib::transfer::TransferMsg1 {
-        statechain_id: statechain_id.to_string(),
-        transfer_signature: transfer_signature.to_string(),
-        backup_transactions: serialized_backup_transactions,
-        t1: t1.secret_bytes(),
-        user_public_key: client_public_key.to_string(),
-    };
-
-    let transfer_msg_json = json!(&transfer_msg);
-
-    let transfer_msg_json_str = serde_json::to_string_pretty(&transfer_msg_json).unwrap();
-
-    let msg = transfer_msg_json_str.as_bytes();
-
-    let serialized_new_auth_pubkey = &recipient_auth_pubkey.serialize();
-    let encrypted_msg = ecies::encrypt(serialized_new_auth_pubkey, msg).unwrap();
-
-    let encrypted_msg_string = hex::encode(&encrypted_msg);
-
-    let transfer_update_msg_request_payload = TransferUpdateMsgRequestPayload {
-        statechain_id: statechain_id.to_string(),
-        auth_sig: signed_statechain_id.to_string(),
-        new_user_auth_key: recipient_auth_pubkey.to_string(),
-        enc_transfer_msg: encrypted_msg_string.clone(),
-    };
-
-    let endpoint = client_config.statechain_entity.clone();
-    let path = "transfer/update_msg";
-
-    let tor_proxy = client_config.tor_proxy.clone();
-
-    let mut client: reqwest::Client = reqwest::Client::new();
-    if tor_proxy != "".to_string() {
-        let tor_proxy = reqwest::Proxy::all(tor_proxy).unwrap();
-        client = reqwest::Client::builder().proxy(tor_proxy).build().unwrap();
-    }
-    let request = client.post(&format!("{}/{}", endpoint, path));
-
-    match request.json(&transfer_update_msg_request_payload).send().await {
-        Ok(response) => {
-            let status = response.status();
-            if !status.is_success() {
-                return Err(CError::Generic("Failed to update transfer message".to_string()));
-            }
-        },
-        Err(err) => 
-            return Err(CError::Generic(err.to_string()))
-        ,
-    };
-
-    // Now it is sucessfully sent to the server, we can save it to the database
-    save_new_backup_transaction(client_config, &new_bakup_tx).await;
-
-    client_config.update_coin_status_and_tx_withdraw(statechain_id, "SPENT", None).await;
-
-    Ok(()) 
-}
-
-pub async fn create_backup_tx_to_receiver(client_config: &ClientConfig, tx1: &Transaction, new_user_pubkey: PublicKey, statechain_id: &str) 
-    -> (SecretKey, PublicKey, PublicKey, Txid, u32, Transaction, MusigPubNonce, MusigPubNonce, BlindingFactor, Signature) {
-
-    let lock_time = tx1.lock_time;
-    assert!(lock_time.is_block_height());
-    let block_height = lock_time.to_consensus_u32();
-
-    assert!(tx1.input.len() == 1);
-    let input = &tx1.input[0];
-    
-    let statechain_coin_details = client_config.get_statechain_coin_details(&statechain_id).await;
-
-    let auth_secret_key = statechain_coin_details.auth_seckey;
-
-    let secp = Secp256k1::new();
-    let keypair = secp256k1::KeyPair::from_seckey_slice(&secp, auth_secret_key.as_ref()).unwrap();
-    let msg = Message::from_hashed_data::(statechain_id.to_string().as_bytes());
-    let signed_statechain_id = secp.sign_schnorr(&msg, &keypair);
-
-    let client_seckey = statechain_coin_details.client_seckey;
-    let client_pubkey = statechain_coin_details.client_pubkey;
-    let server_pubkey = statechain_coin_details.server_pubkey;
-    let input_txid = input.previous_output.txid;
-    let input_vout = input.previous_output.vout;
-    let input_pubkey = statechain_coin_details.aggregated_pubkey;
-    let input_scriptpubkey = statechain_coin_details.p2tr_agg_address.script_pubkey();
-    let input_amount = statechain_coin_details.amount;
-
-    let to_address = Address::p2tr(&Secp256k1::new(), new_user_pubkey.x_only_public_key().0, None, client_config.network);
-
-    let (new_tx, client_pub_nonce, server_pub_nonce, blinding_factor) = crate::transaction::new_backup_transaction(
-        client_config, 
-        block_height,
-        statechain_id,
-        &signed_statechain_id,
-        &client_seckey,
-        &client_pubkey,
-        &server_pubkey,
-        input_txid, 
-        input_vout, 
-        &input_pubkey, 
-        &input_scriptpubkey, 
-        input_amount, 
-        &to_address,
-        false,).await.unwrap();
-
-    (client_seckey, client_pubkey, server_pubkey, input_txid, input_vout, new_tx, client_pub_nonce, server_pub_nonce, blinding_factor, signed_statechain_id)
-
-}
\ No newline at end of file
diff --git a/clients/standalone-rust/src/utils.rs b/clients/standalone-rust/src/utils.rs
deleted file mode 100644
index 03262c46..00000000
--- a/clients/standalone-rust/src/utils.rs
+++ /dev/null
@@ -1,44 +0,0 @@
-use crate::{error::CError, electrum};
-use crate::client_config::ClientConfig;
-
-pub struct InfoConfig {
-    pub initlock: u32,
-    pub interval: u32,
-    pub fee_rate_sats_per_byte: u64,
-}
-
-pub async fn info_config(statechain_entity_url: &str, electrum_client: &electrum_client::Client, tor_proxy: &str) -> Result{
-
-    let path = "info/config";
-
-    let mut client: reqwest::Client = reqwest::Client::new();
-    if tor_proxy != "".to_string() {
-        let tor_proxy = reqwest::Proxy::all(tor_proxy).unwrap();
-        client = reqwest::Client::builder().proxy(tor_proxy).build().unwrap();
-    }
-    let request = client.get(&format!("{}/{}", statechain_entity_url, path));
-
-    let value = match request.send().await {
-        Ok(response) => {
-            let text = response.text().await.unwrap();
-            text
-        },
-        Err(err) => {
-            return Err(CError::Generic(err.to_string()));
-        },
-    };
-
-    let server_config: mercury_lib::utils::ServerConfig = serde_json::from_str(value.as_str()).expect(&format!("failed to parse: {}", value.as_str()));
-
-    let initlock = server_config.initlock;
-    let interval = server_config.interval;
-
-    let fee_rate_btc_per_kb = electrum::estimate_fee(&electrum_client, 3);
-    let fee_rate_sats_per_byte = (fee_rate_btc_per_kb * 100000.0) as u64;
-
-    Ok(InfoConfig {    
-        initlock,
-        interval,
-        fee_rate_sats_per_byte,
-    })
-}
\ No newline at end of file
diff --git a/clients/standalone-rust/src/wallet.rs b/clients/standalone-rust/src/wallet.rs
deleted file mode 100644
index 9822f9f4..00000000
--- a/clients/standalone-rust/src/wallet.rs
+++ /dev/null
@@ -1,183 +0,0 @@
-use std::str::FromStr;
-
-use bitcoin::{Network, Address, Txid, PrivateKey};
-use secp256k1_zkp::SecretKey;
-use serde::{Serialize, Deserialize};
-use sqlx::{Sqlite, Row};
-
-use crate::client_config::ClientConfig;
-
-pub async fn get_all_addresses(client_config: &ClientConfig) -> (Vec::
, Vec::
){ - let mut agg_addresses = Vec::
::new(); - let mut backup_addresses = Vec::
::new(); - - let query = "SELECT backup_address FROM signer_data"; - - let rows = sqlx::query(query) - .fetch_all(&client_config.pool) - .await - .unwrap(); - - for row in rows { - - let backup_address_str = row.get::("backup_address"); - let backup_address = Address::from_str(&backup_address_str).unwrap().require_network(client_config.network).unwrap(); - backup_addresses.push(backup_address); - } - - let query = "SELECT p2tr_agg_address FROM statechain_data"; - - let rows = sqlx::query(query) - .fetch_all(&client_config.pool) - .await - .unwrap(); - - for row in rows { - - let p2tr_agg_address = row.get::("p2tr_agg_address"); - - if p2tr_agg_address.is_empty() { - continue; - } - - let agg_address = Address::from_str(&p2tr_agg_address).unwrap().require_network(client_config.network).unwrap(); - agg_addresses.push(agg_address); - } - - (agg_addresses, backup_addresses) -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct BackupTransactionJSON { - tx_n: u32, - tx: String, - client_public_nonce: String, - blinding_factor: String, -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct CoinJSON { - pub utxo: String, - pub address: String, - pub amount: u32, - pub statechain_id: String, - pub privkey: String, - pub auth_key: String, - pub locktime: u32, - pub status: String, - pub tx_withdraw: Option, - pub backup_txs: Vec, -} - -pub async fn get_backup_tx(pool: &sqlx::Pool, statechain_id: &str) -> Vec:: { - - let rows = sqlx::query("SELECT * FROM backup_transaction WHERE statechain_id = $1") - .bind(statechain_id) - .fetch_all(pool) - .await - .unwrap(); - - let mut backup_transactions = Vec::::new(); - - for row in rows { - let row_statechain_id = row.get::("statechain_id"); - assert!(row_statechain_id == statechain_id); - - let tx_n = row.get::("tx_n"); - - let client_public_nonce = row.get::, _>("client_public_nonce"); - let client_public_nonce = hex::encode(client_public_nonce); - - let blinding_factor = row.get::, _>("blinding_factor"); - let blinding_factor = hex::encode(blinding_factor); - - let tx_bytes = row.get::, _>("backup_tx"); - let tx = hex::encode(tx_bytes); - - backup_transactions.push(BackupTransactionJSON { - tx_n, - tx, - client_public_nonce, - blinding_factor - }); - } - - backup_transactions - -} - -pub async fn get_coins(client_config: &ClientConfig) -> Vec { - - let query = "SELECT \ - std.funding_txid, \ - std.funding_vout, \ - std.p2tr_agg_address, \ - std.amount, \ - std.statechain_id, \ - sid.client_seckey_share, \ - sid.auth_seckey, \ - std.locktime, \ - std.status, \ - std.tx_withdraw \ - FROM signer_data sid INNER JOIN statechain_data std \ - ON sid.client_pubkey_share = std.client_pubkey_share"; - - let rows = sqlx::query(query) - .fetch_all(&client_config.pool) - .await - .unwrap(); - - let mut coins = Vec::::new(); - - for row in rows { - - let utxo_tx_hash = row.get::("funding_txid"); - let utxo_tx_hash = Txid::from_str(&utxo_tx_hash).unwrap(); - - let utxo_vout = row.get::("funding_vout"); - - let utxo = format!("{}:{}", utxo_tx_hash, utxo_vout); - - let agg_address_str = row.get::("p2tr_agg_address"); - let p2tr_agg_address = Address::from_str(&agg_address_str).unwrap().require_network(client_config.network).unwrap(); - - let amount = row.get::("amount"); - - let statechain_id = row.get::("statechain_id"); - - let client_seckey_share_bytes = row.get::, _>("client_seckey_share"); - let client_seckey_share = SecretKey::from_slice(&client_seckey_share_bytes).unwrap(); - - let privkey = PrivateKey::new(client_seckey_share, client_config.network); - - let auth_seckey_bytes = row.get::, _>("auth_seckey"); - let auth_seckey = SecretKey::from_slice(&auth_seckey_bytes).unwrap(); - - let auth_key = PrivateKey::new(auth_seckey, client_config.network); - - let locktime = row.get::("locktime"); - - let status = row.get::("status"); - - let tx_withdraw: Option = row.get::, _>("tx_withdraw"); - - let backup_txs = get_backup_tx(&client_config.pool, &statechain_id).await; - - coins.push(CoinJSON { - utxo, - address: p2tr_agg_address.to_string(), - amount, - statechain_id, - privkey: privkey.to_wif(), - auth_key: auth_key.to_wif(), - locktime, - status, - tx_withdraw, - backup_txs - }); - } - - coins - - -} \ No newline at end of file diff --git a/clients/standalone-rust/src/withdraw.rs b/clients/standalone-rust/src/withdraw.rs deleted file mode 100644 index 127fa2a3..00000000 --- a/clients/standalone-rust/src/withdraw.rs +++ /dev/null @@ -1,76 +0,0 @@ -use bitcoin::Address; - -use crate::{electrum, error::CError, client_config::ClientConfig}; - -pub async fn execute(client_config: &ClientConfig, statechain_id: &str, to_address: &Address, fee_rate: u64) -> Result { - - let block_header = electrum::block_headers_subscribe_raw(&client_config.electrum_client); - let block_height = block_header.height; - - let coin_key_details = client_config.get_coin_and_key_info(statechain_id).await; - - let (tx, client_pub_nonce, server_pub_nonce, blinding_factor) = crate::transaction::new_backup_transaction( - client_config, - block_height as u32, - &statechain_id, - &coin_key_details.signed_statechain_id, - &coin_key_details.client_seckey, - &coin_key_details.client_pubkey, - &coin_key_details.server_pubkey, - coin_key_details.utxo_tx_hash, - coin_key_details.utxo_vout, - &coin_key_details.aggregated_pubkey, - &coin_key_details.p2tr_agg_address.script_pubkey(), - coin_key_details.amount, - &to_address, - true).await.unwrap(); - - let tx_bytes = bitcoin::consensus::encode::serialize(&tx); - - client_config.insert_transaction( - coin_key_details.new_tx_n, - &tx_bytes, - &client_pub_nonce.serialize(), - &server_pub_nonce.serialize(), - &coin_key_details.client_pubkey, - &coin_key_details.server_pubkey, - blinding_factor.as_bytes(), - &statechain_id, - &to_address.to_string() - ).await.unwrap(); - - let txid = electrum::transaction_broadcast_raw(&client_config.electrum_client, &tx_bytes); - - client_config.update_coin_status_and_tx_withdraw(statechain_id, "WITHDRAWN", Some(txid.to_string())).await; - - // delete statechain on the server - let delete_statechain_payload = mercury_lib::withdraw::DeleteStatechainPayload { - statechain_id: statechain_id.to_string(), - signed_statechain_id: coin_key_details.signed_statechain_id.to_string(), - }; - - let endpoint = client_config.statechain_entity.clone(); - let path = "delete_statechain"; - - let tor_proxy = client_config.tor_proxy.clone(); - - let mut client: reqwest::Client = reqwest::Client::new(); - if tor_proxy != "".to_string() { - let tor_proxy = reqwest::Proxy::all(tor_proxy).unwrap(); - client = reqwest::Client::builder().proxy(tor_proxy).build().unwrap(); - } - let request = client.delete(&format!("{}/{}", endpoint, path)); - - let _ = match request.json(&delete_statechain_payload).send().await { - Ok(response) => { - let text = response.text().await.unwrap(); - text - }, - Err(err) => { - return Err(CError::Generic(err.to_string())); - }, - }; - - Ok(txid.to_string()) - -} \ No newline at end of file diff --git a/lib/src/lib.rs b/lib/src/lib.rs index 1fccb6de..e2f0b07a 100644 --- a/lib/src/lib.rs +++ b/lib/src/lib.rs @@ -9,9 +9,9 @@ use std::str::FromStr; use bech32::{Variant, ToBase32, FromBase32}; use bip39::Mnemonic; -use bitcoin::{bip32::{ChildNumber, DerivationPath, ExtendedPrivKey}, secp256k1::{ffi::types::AlignedType, AllPreallocated, PublicKey, Secp256k1, SecretKey}}; +use bitcoin::{bip32::{ChildNumber, DerivationPath, ExtendedPrivKey}, secp256k1::{ffi::types::AlignedType, AllPreallocated, PublicKey, Secp256k1, SecretKey}, Address}; -use anyhow::{Result, anyhow}; +use anyhow::{anyhow, Result}; const MAINNET_HRP : &str = "ml"; const TESTNET_HRP : &str = "tml"; @@ -99,6 +99,38 @@ pub fn get_sc_address(mnemonic: &str, index: u32, network: &str) -> Result Result { + + let network = utils::get_network(network)?; + + if address.starts_with(MAINNET_HRP) || address.starts_with(TESTNET_HRP) { + if address.starts_with(MAINNET_HRP) && network != bitcoin::Network::Bitcoin { + return Err(anyhow!("Statechain address does not match the network")); + } + + if address.starts_with(TESTNET_HRP) && network == bitcoin::Network::Bitcoin { + return Err(anyhow!("Statechain address does not match the network")); + } + + match decode_transfer_address(address) { + Ok(_) => Ok(true), + Err(_) => Err(anyhow::anyhow!("Invalid statechain address")), + } + } + else { + match Address::from_str(address) { + Ok(addr) => { + + match addr.require_network(network) { + Ok(_) => Ok(true), + Err(_) => Err(anyhow::anyhow!("Bitcoin address does not match the network")), + } + }, + Err(_) => Err(anyhow::anyhow!("Invalid bitcoin address")), + } + + } +} #[cfg(test)] mod tests { diff --git a/lib/src/transaction.rs b/lib/src/transaction.rs index e31ef644..c10c0652 100644 --- a/lib/src/transaction.rs +++ b/lib/src/transaction.rs @@ -1,6 +1,6 @@ use std::{str::FromStr, collections::BTreeMap}; -use bitcoin::{Txid, ScriptBuf, Transaction, absolute, TxIn, OutPoint, Witness, TxOut, psbt::{Psbt, Input, PsbtSighashType}, sighash::{TapSighashType, SighashCache, self, TapSighash}, taproot::{TapTweakHash, self}, hashes::{Hash, sha256}, Address, PrivateKey, Network}; +use bitcoin::{Txid, ScriptBuf, Transaction, absolute, TxIn, OutPoint, Witness, TxOut, psbt::{Psbt, Input, PsbtSighashType}, sighash::{TapSighashType, SighashCache, self, TapSighash}, taproot::{TapTweakHash, self}, hashes::Hash, Address, PrivateKey, Network}; use secp256k1_zkp::{SecretKey, PublicKey, Secp256k1, schnorr::Signature, Message, musig::{MusigSessionId, MusigPubNonce, BlindingFactor, MusigSession, MusigPartialSignature, blinded_musig_pubkey_xonly_tweak_add, blinded_musig_negate_seckey, MusigAggNonce, MusigSecNonce}, new_musig_nonce_pair, KeyPair, rand::{self, Rng}}; use serde::{Serialize, Deserialize}; @@ -115,18 +115,14 @@ pub fn create_tx_out( let absolute_fee: u64 = BACKUP_TX_SIZE * fee_rate_sats_per_byte; let amount_out = input_amount - absolute_fee; - let mut recipient_address: Option
= None; - - if to_address.starts_with(crate::MAINNET_HRP) || to_address.starts_with(crate::TESTNET_HRP) { + let recipient_address = if to_address.starts_with(crate::MAINNET_HRP) || to_address.starts_with(crate::TESTNET_HRP) { let (_, recipient_user_pubkey, _) = decode_transfer_address(to_address)?; let new_address = Address::p2tr(&Secp256k1::new(), recipient_user_pubkey.x_only_public_key().0, None, network); - recipient_address = Some(new_address); + new_address } else { let new_address = Address::from_str(&to_address).unwrap().require_network(network)?; - recipient_address = Some(new_address); - } - - let recipient_address = recipient_address.unwrap(); + new_address + }; let tx_out = TxOut { value: amount_out, script_pubkey: recipient_address.script_pubkey() }; diff --git a/lib/src/transfer/sender.rs b/lib/src/transfer/sender.rs index a19d674c..f7d8afc3 100644 --- a/lib/src/transfer/sender.rs +++ b/lib/src/transfer/sender.rs @@ -1,9 +1,9 @@ use std::str::FromStr; use bitcoin::{secp256k1, hashes::sha256, Txid, PrivateKey}; -use secp256k1_zkp::{Secp256k1, Message, PublicKey, Scalar}; +use secp256k1_zkp::{Secp256k1, Message, Scalar}; use serde::{Serialize, Deserialize}; -use anyhow::{Result, anyhow}; +use anyhow::Result; use serde_json::json; use crate::{decode_transfer_address, wallet::{Coin, BackupTx}}; diff --git a/lib/src/wallet/mod.rs b/lib/src/wallet/mod.rs index af0ec440..9140bbb3 100644 --- a/lib/src/wallet/mod.rs +++ b/lib/src/wallet/mod.rs @@ -103,6 +103,7 @@ pub struct Coin { } #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] +#[allow(non_camel_case_types)] pub enum CoinStatus { INITIALISED, // address generated but no Tx0 yet IN_MEMPOOL, // Tx0 in mempool From 549fd54d7865924880eb9b2e2f5f43f513824ca2 Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Fri, 26 Apr 2024 18:46:46 +0530 Subject: [PATCH 46/66] fix: build failure with wasm --- wasm/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wasm/src/lib.rs b/wasm/src/lib.rs index 6a4354bb..fef709e2 100644 --- a/wasm/src/lib.rs +++ b/wasm/src/lib.rs @@ -143,7 +143,7 @@ pub fn fromMnemonic(name: String, mnemonic: String) -> JsValue { tokens: Vec::new(), activities: Vec::new(), coins: Vec::new(), - settings + // settings }; serde_wasm_bindgen::to_value(&wallet).unwrap() } @@ -551,7 +551,7 @@ pub fn getMockWallet() -> JsValue { tokens, activities: activity, coins: Vec::new(), // coins - settings + // settings }; serde_wasm_bindgen::to_value(&wallet).unwrap() } \ No newline at end of file From 1ceb56143402789b54feebab4614becd40d73ef5 Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Tue, 30 Apr 2024 12:23:06 +0530 Subject: [PATCH 47/66] fix: postgres command --- keylistCron/send_commitment.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keylistCron/send_commitment.sh b/keylistCron/send_commitment.sh index 2f097ae6..16d0e458 100644 --- a/keylistCron/send_commitment.sh +++ b/keylistCron/send_commitment.sh @@ -39,7 +39,7 @@ fi echo "Keylist $KEYLIST_HASH attestation completed successfully!" # Connect to the database and save the keylist JSON -PG_COMMAND="PGPASSWORD=\"$DB_PASSWORD\" psql -h $DB_HOST -p $DB_PORT -d $DB_NAME -U $DB_USER -c \" +PG_COMMAND="PGPASSWORD=\"$DB_PASSWORD\" psql -h \"$DB_HOST\" -p \"$DB_PORT\" -d \"$DB_NAME\" -U \"$DB_USER\" -c \" CREATE TABLE IF NOT EXISTS keylist_info ( json_data json NOT NULL ); From 25b7630f7ef7583c53c2cbe7c4e5ef27a2cbdb10 Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Tue, 30 Apr 2024 16:18:09 +0530 Subject: [PATCH 48/66] debug: pg command --- keylistCron/send_commitment.sh | 2 ++ 1 file changed, 2 insertions(+) diff --git a/keylistCron/send_commitment.sh b/keylistCron/send_commitment.sh index 16d0e458..03e2e4a6 100644 --- a/keylistCron/send_commitment.sh +++ b/keylistCron/send_commitment.sh @@ -46,6 +46,8 @@ PG_COMMAND="PGPASSWORD=\"$DB_PASSWORD\" psql -h \"$DB_HOST\" -p \"$DB_PORT\" -d INSERT INTO keylist_info (json_data) VALUES ('$KEYLIST_JSON'); \"" +echo "PG_COMMAND: $PG_COMMAND" + # Execute the PostgreSQL command eval "$PG_COMMAND" From c3d551c1820f33632110b60a692f82dcd9b7f5fb Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Tue, 30 Apr 2024 21:48:27 +0530 Subject: [PATCH 49/66] fix: bash script --- keylistCron/send_commitment.sh | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/keylistCron/send_commitment.sh b/keylistCron/send_commitment.sh index 03e2e4a6..80950c5d 100644 --- a/keylistCron/send_commitment.sh +++ b/keylistCron/send_commitment.sh @@ -39,15 +39,9 @@ fi echo "Keylist $KEYLIST_HASH attestation completed successfully!" # Connect to the database and save the keylist JSON -PG_COMMAND="PGPASSWORD=\"$DB_PASSWORD\" psql -h \"$DB_HOST\" -p \"$DB_PORT\" -d \"$DB_NAME\" -U \"$DB_USER\" -c \" - CREATE TABLE IF NOT EXISTS keylist_info ( - json_data json NOT NULL - ); - INSERT INTO keylist_info (json_data) VALUES ('$KEYLIST_JSON'); - \"" - -echo "PG_COMMAND: $PG_COMMAND" +PG_COMMAND="PGPASSWORD=mercurypass@12345 psql -h vultr-prod-e795780f-1f41-4d13-978d-5fd624923873-vultr-prod-86c1.vultrdb.com -p 16751 -d defaultdb -U mercury -c \"CREATE TABLE IF NOT EXISTS keylist_info ( json_data json NOT NULL ); INSERT INTO keylist_info (json_data) VALUES ('$KEYLIST_JSON');\"" +echo "PG_COMMAND $PG_COMMAND" # Execute the PostgreSQL command eval "$PG_COMMAND" From 56482f5f4585060068525fc478aacf2f1384ea2f Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Wed, 1 May 2024 12:54:54 +0530 Subject: [PATCH 50/66] fix: keylist url --- keylistCron/send_commitment.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keylistCron/send_commitment.sh b/keylistCron/send_commitment.sh index 80950c5d..4abac84f 100644 --- a/keylistCron/send_commitment.sh +++ b/keylistCron/send_commitment.sh @@ -1,7 +1,7 @@ #!/bin/bash # Fetch keylist JSON from the provided URL -KEYLIST_URL="https://api.mercurywallet.io/info/keylist" +KEYLIST_URL="http://45.76.136.11:8000/info/keylist" KEYLIST_JSON=$(curl -sSL "$KEYLIST_URL" | jq -r '.list_keyinfo') # Check if the GET request was successful From f6131c86ec1f6f7616e63b77c2beb6291e5e4c14 Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Wed, 1 May 2024 13:10:02 +0530 Subject: [PATCH 51/66] fix: postgres command --- keylistCron/send_commitment.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keylistCron/send_commitment.sh b/keylistCron/send_commitment.sh index 4abac84f..28ed99eb 100644 --- a/keylistCron/send_commitment.sh +++ b/keylistCron/send_commitment.sh @@ -39,7 +39,7 @@ fi echo "Keylist $KEYLIST_HASH attestation completed successfully!" # Connect to the database and save the keylist JSON -PG_COMMAND="PGPASSWORD=mercurypass@12345 psql -h vultr-prod-e795780f-1f41-4d13-978d-5fd624923873-vultr-prod-86c1.vultrdb.com -p 16751 -d defaultdb -U mercury -c \"CREATE TABLE IF NOT EXISTS keylist_info ( json_data json NOT NULL ); INSERT INTO keylist_info (json_data) VALUES ('$KEYLIST_JSON');\"" +PG_COMMAND="PGPASSWORD=mercurypass@12345 psql -h vultr-prod-e795780f-1f41-4d13-978d-5fd624923873-vultr-prod-86c1.vultrdb.com -p 16751 -d defaultdb -U mercury -c \"CREATE TABLE IF NOT EXISTS keylist_info ( json_data json NOT NULL ); INSERT INTO keylist_info (json_data) VALUES ($KEYLIST_JSON);\"" echo "PG_COMMAND $PG_COMMAND" # Execute the PostgreSQL command From 1e6e9605dbd60d6ebc4a8a8aa34e8a5864861f87 Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Wed, 1 May 2024 16:13:10 +0530 Subject: [PATCH 52/66] fix: postgres command to store json as text --- keylistCron/send_commitment.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keylistCron/send_commitment.sh b/keylistCron/send_commitment.sh index 28ed99eb..a1416546 100644 --- a/keylistCron/send_commitment.sh +++ b/keylistCron/send_commitment.sh @@ -39,7 +39,7 @@ fi echo "Keylist $KEYLIST_HASH attestation completed successfully!" # Connect to the database and save the keylist JSON -PG_COMMAND="PGPASSWORD=mercurypass@12345 psql -h vultr-prod-e795780f-1f41-4d13-978d-5fd624923873-vultr-prod-86c1.vultrdb.com -p 16751 -d defaultdb -U mercury -c \"CREATE TABLE IF NOT EXISTS keylist_info ( json_data json NOT NULL ); INSERT INTO keylist_info (json_data) VALUES ($KEYLIST_JSON);\"" +PG_COMMAND="PGPASSWORD=mercurypass@12345 psql -h vultr-prod-e795780f-1f41-4d13-978d-5fd624923873-vultr-prod-86c1.vultrdb.com -p 16751 -d defaultdb -U mercury -c \"CREATE TABLE IF NOT EXISTS keylist_info ( json_data LONGTEXT NOT NULL, keylist_hash TEXT NOT NULL ); INSERT INTO keylist_info (json_data, keylist_hash) VALUES ('$KEYLIST_JSON', '$KEYLIST_HASH');\"" echo "PG_COMMAND $PG_COMMAND" # Execute the PostgreSQL command From cec05728cc92bb1b0f166172287cd5d61fb3e9e9 Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Wed, 1 May 2024 21:22:09 +0530 Subject: [PATCH 53/66] fix: string handling for json --- keylistCron/send_commitment.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/keylistCron/send_commitment.sh b/keylistCron/send_commitment.sh index a1416546..1b63f803 100644 --- a/keylistCron/send_commitment.sh +++ b/keylistCron/send_commitment.sh @@ -2,7 +2,7 @@ # Fetch keylist JSON from the provided URL KEYLIST_URL="http://45.76.136.11:8000/info/keylist" -KEYLIST_JSON=$(curl -sSL "$KEYLIST_URL" | jq -r '.list_keyinfo') +KEYLIST_JSON=$(curl -sSL "$KEYLIST_URL" | jq -r '.list_keyinfo' | sed 's/"/\\"/g') # Check if the GET request was successful if [[ $? -ne 0 ]]; then @@ -39,7 +39,7 @@ fi echo "Keylist $KEYLIST_HASH attestation completed successfully!" # Connect to the database and save the keylist JSON -PG_COMMAND="PGPASSWORD=mercurypass@12345 psql -h vultr-prod-e795780f-1f41-4d13-978d-5fd624923873-vultr-prod-86c1.vultrdb.com -p 16751 -d defaultdb -U mercury -c \"CREATE TABLE IF NOT EXISTS keylist_info ( json_data LONGTEXT NOT NULL, keylist_hash TEXT NOT NULL ); INSERT INTO keylist_info (json_data, keylist_hash) VALUES ('$KEYLIST_JSON', '$KEYLIST_HASH');\"" +PG_COMMAND="PGPASSWORD=mercurypass@12345 psql -h vultr-prod-e795780f-1f41-4d13-978d-5fd624923873-vultr-prod-86c1.vultrdb.com -p 16751 -d defaultdb -U mercury -c \"CREATE TABLE IF NOT EXISTS keylist_info ( json_data TEXT NOT NULL, keylist_hash TEXT NOT NULL ); INSERT INTO keylist_info (json_data, keylist_hash) VALUES ('$KEYLIST_JSON', '$KEYLIST_HASH');\"" echo "PG_COMMAND $PG_COMMAND" # Execute the PostgreSQL command From e3c9b26ec0e42fc4e587493f21f933ab4c2a7b12 Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Wed, 1 May 2024 21:46:31 +0530 Subject: [PATCH 54/66] fix: postgres command connection details --- keylistCron/send_commitment.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keylistCron/send_commitment.sh b/keylistCron/send_commitment.sh index 1b63f803..13c6deb0 100644 --- a/keylistCron/send_commitment.sh +++ b/keylistCron/send_commitment.sh @@ -39,7 +39,7 @@ fi echo "Keylist $KEYLIST_HASH attestation completed successfully!" # Connect to the database and save the keylist JSON -PG_COMMAND="PGPASSWORD=mercurypass@12345 psql -h vultr-prod-e795780f-1f41-4d13-978d-5fd624923873-vultr-prod-86c1.vultrdb.com -p 16751 -d defaultdb -U mercury -c \"CREATE TABLE IF NOT EXISTS keylist_info ( json_data TEXT NOT NULL, keylist_hash TEXT NOT NULL ); INSERT INTO keylist_info (json_data, keylist_hash) VALUES ('$KEYLIST_JSON', '$KEYLIST_HASH');\"" +PG_COMMAND="PGPASSWORD=$DB_PASSWORD psql -h $DB_HOST -p $DB_PORT -d $DB_NAME -U $DB_USER -c \"CREATE TABLE IF NOT EXISTS keylist_info ( json_data TEXT NOT NULL, keylist_hash TEXT NOT NULL ); INSERT INTO keylist_info (json_data, keylist_hash) VALUES ('$KEYLIST_JSON', '$KEYLIST_HASH');\"" echo "PG_COMMAND $PG_COMMAND" # Execute the PostgreSQL command From 93ece38309614de408db6aeb60288b9c69977a60 Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Thu, 2 May 2024 13:06:28 +0530 Subject: [PATCH 55/66] fix: add env variables to dockerfile --- keylistCron/Dockerfile | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/keylistCron/Dockerfile b/keylistCron/Dockerfile index 1bf53ecd..b3f602b1 100644 --- a/keylistCron/Dockerfile +++ b/keylistCron/Dockerfile @@ -1,5 +1,19 @@ FROM alpine:latest +# Define build arguments +ARG DB_HOST +ARG DB_PORT +ARG DB_NAME +ARG DB_USER +ARG DB_PASSWORD + +# Set environment variables +ENV DB_HOST=$DB_HOST +ENV DB_PORT=$DB_PORT +ENV DB_NAME=$DB_NAME +ENV DB_USER=$DB_USER +ENV DB_PASSWORD=$DB_PASSWORD + RUN apk update && apk add --no-cache curl postgresql-client jq WORKDIR /app From 4e53fa213f18b1c52e840256300be3a4a193785d Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Thu, 2 May 2024 17:40:33 +0530 Subject: [PATCH 56/66] fix: remove env variables --- .github/workflows/ci.yaml | 6 ------ keylistCron/Dockerfile | 14 -------------- keylistCron/send_commitment.sh | 1 - 3 files changed, 21 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 81320a2a..b7e30758 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -56,9 +56,3 @@ jobs: file: ./keylistCron/Dockerfile push: true tags: commerceblockx/keylist-cronjob:latest - env: - DB_HOST: ${{ secrets.DB_HOST }} - DB_PORT: ${{ secrets.DB_PORT }} - DB_NAME: ${{ secrets.DB_NAME }} - DB_USER: ${{ secrets.DB_USER }} - DB_PASSWORD: ${{ secrets.DB_PASSWORD }} diff --git a/keylistCron/Dockerfile b/keylistCron/Dockerfile index b3f602b1..1bf53ecd 100644 --- a/keylistCron/Dockerfile +++ b/keylistCron/Dockerfile @@ -1,19 +1,5 @@ FROM alpine:latest -# Define build arguments -ARG DB_HOST -ARG DB_PORT -ARG DB_NAME -ARG DB_USER -ARG DB_PASSWORD - -# Set environment variables -ENV DB_HOST=$DB_HOST -ENV DB_PORT=$DB_PORT -ENV DB_NAME=$DB_NAME -ENV DB_USER=$DB_USER -ENV DB_PASSWORD=$DB_PASSWORD - RUN apk update && apk add --no-cache curl postgresql-client jq WORKDIR /app diff --git a/keylistCron/send_commitment.sh b/keylistCron/send_commitment.sh index 13c6deb0..3b7e3bfd 100644 --- a/keylistCron/send_commitment.sh +++ b/keylistCron/send_commitment.sh @@ -41,7 +41,6 @@ echo "Keylist $KEYLIST_HASH attestation completed successfully!" # Connect to the database and save the keylist JSON PG_COMMAND="PGPASSWORD=$DB_PASSWORD psql -h $DB_HOST -p $DB_PORT -d $DB_NAME -U $DB_USER -c \"CREATE TABLE IF NOT EXISTS keylist_info ( json_data TEXT NOT NULL, keylist_hash TEXT NOT NULL ); INSERT INTO keylist_info (json_data, keylist_hash) VALUES ('$KEYLIST_JSON', '$KEYLIST_HASH');\"" -echo "PG_COMMAND $PG_COMMAND" # Execute the PostgreSQL command eval "$PG_COMMAND" From 852fafa56da1244e8fa025841db66b05e6d268f0 Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Mon, 20 May 2024 20:54:27 +0530 Subject: [PATCH 57/66] fix: token and serverconfig fields --- lib/src/wallet/mod.rs | 6 +++--- server/src/server_config.rs | 2 ++ wasm/src/lib.rs | 12 ++++++------ 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/lib/src/wallet/mod.rs b/lib/src/wallet/mod.rs index 96658807..28511988 100644 --- a/lib/src/wallet/mod.rs +++ b/lib/src/wallet/mod.rs @@ -49,14 +49,14 @@ pub struct Settings { #[derive(Debug, Serialize, Deserialize, Clone)] #[cfg_attr(feature = "bindings", derive(uniffi::Record))] pub struct Token { - // pub btc_payment_address: String, - // pub fee: String, + pub btc_payment_address: String, + pub fee: String, pub lightning_invoice: String, pub processor_id: String, pub token_id: String, pub confirmed: bool, pub spent: bool, - // pub expiry: String, + pub expiry: String, } #[derive(Debug, Serialize, Deserialize, Clone)] diff --git a/server/src/server_config.rs b/server/src/server_config.rs index a02c59ce..784000aa 100644 --- a/server/src/server_config.rs +++ b/server/src/server_config.rs @@ -27,6 +27,7 @@ impl Default for ServerConfig { lockheight_init: 10000, lh_decrement: 100, connection_string: String::from("postgresql://postgres:postgres@localhost/mercury"), + batch_timeout: 120, } } } @@ -39,6 +40,7 @@ impl From for ServerConfig { lockheight_init: config.get::("lockheight_init").unwrap_or(0), lh_decrement: config.get::("lh_decrement").unwrap_or(0), connection_string: config.get::("connection_string").unwrap_or_else(|_| String::new()), + batch_timeout: config.get::("batch_timeout").unwrap_or(0), } } } diff --git a/wasm/src/lib.rs b/wasm/src/lib.rs index 7f420752..5a7d2c9e 100644 --- a/wasm/src/lib.rs +++ b/wasm/src/lib.rs @@ -443,24 +443,24 @@ pub fn isEnclavePubkeyPartOfCoin(coin: JsValue, enclave_pubkey: String) -> bool pub fn getMockWallet() -> JsValue { let tokens = vec![ Token { - // btc_payment_address: String::from("bc1..."), - // fee: String::from("0.001"), + btc_payment_address: String::from("bc1..."), + fee: String::from("0.001"), lightning_invoice: String::from("lnbc10u1pj3knpdsp5k9f25s2wpzewkf9c78pftkgnkuuz82erkcjml7zkgsp7znyhs5yspp5rxz3tkc7ydgln3u7ez6duhp0g6jpzgtnn7ph5xrjy6muh9xm07wqdp2f9h8vmmfvdjjqen0wgsy6ctfdeehgcteyp6x76m9dcxqyjw5qcqpj9qyysgq6z9whs8am75r6mzcgt76vlwgk5g9yq5g8xefdxx6few6d5why7fs7h5g2dx9hk7s60ywtnkyc0f3p0cha4a9kmgkq5jvu5e7hvsaawqpjtf8p4"), processor_id: String::from("e04r5e00-cgdd-5yb7-y704-52631405720e"), token_id: String::from("e08aee00-cfed-4ab7-b304-38d61405720e"), confirmed: true, spent: false, - // expiry: "2023-11-07T12:34:56.789Z".to_string() + expiry: "2023-11-07T12:34:56.789Z".to_string() }, Token { - // btc_payment_address: String::from("bc1..."), - // fee: String::from("0.001"), + btc_payment_address: String::from("bc1..."), + fee: String::from("0.001"), processor_id: String::from("e04r5e00-cgdd-5yb7-y704-52631405720e"), lightning_invoice: String::from("lnbc10u1pj3knpdsp5k9f25s2wpzewkf9c78pftkgnkuuz82erkcjml7zkgsp7znyhs5yspp5rxz3tkc7ydgln3u7ez6duhp0g6jpzgtnn7ph5xrjy6muh9xm07wqdp2f9h8vmmfvdjjqen0wgsy6ctfdeehgcteyp6x76m9dcxqyjw5qcqpj9qyysgq6z9whs8am75r6mzcgt76vlwgk5g9yq5g8xefdxx6few6d5why7fs7h5g2dx9hk7s60ywtnkyc0f3p0cha4a9kmgkq5jvu5e7hvsaawqpjtf8p4"), token_id: String::from("aed9a34c-5666-4d83-940f-9b74e16b8672"), confirmed: true, spent: false, - // expiry: "2023-11-07T12:34:56.789Z".to_string() + expiry: "2023-11-07T12:34:56.789Z".to_string() } ]; From b504675140b1c87cfd6947ee78f8020832fc6e4c Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Tue, 21 May 2024 19:03:44 +0530 Subject: [PATCH 58/66] debug: connection string --- server/src/server.rs | 1 + server/src/server_config.rs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/server/src/server.rs b/server/src/server.rs index e2a859b2..d6a3a2f1 100644 --- a/server/src/server.rs +++ b/server/src/server.rs @@ -11,6 +11,7 @@ impl StateChainEntity { pub async fn new() -> Self { let config = ServerConfig::load(); + println!("Config: {:?}", config); let pool = PgPoolOptions::new() diff --git a/server/src/server_config.rs b/server/src/server_config.rs index 784000aa..e0ca67f1 100644 --- a/server/src/server_config.rs +++ b/server/src/server_config.rs @@ -71,7 +71,7 @@ impl ServerConfig { network: get_env_or_config("network", "BITCOIN_NETWORK"), lockheight_init: get_env_or_config("lockheight_init", "LOCKHEIGHT_INIT").parse::().unwrap(), lh_decrement: get_env_or_config("lh_decrement", "LH_DECREMENT").parse::().unwrap(), - connection_string: get_env_or_config("connection_string", "DATABASE_CONNECTION_STRING"), + connection_string: get_env_or_config("connection_string", "CONNECTION_STRING"), batch_timeout: get_env_or_config("batch_timeout", "BATCH_TIMEOUT").parse::().unwrap(), } } From b83a2e6fd47e59f10f1a23030d18c366625789ed Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Tue, 21 May 2024 20:05:48 +0530 Subject: [PATCH 59/66] debug: token server db connection --- token-server/src/server.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/token-server/src/server.rs b/token-server/src/server.rs index e93b2d45..67e76596 100644 --- a/token-server/src/server.rs +++ b/token-server/src/server.rs @@ -11,6 +11,7 @@ impl TokenServer { pub async fn new() -> Self { let config = ServerConfig::load(); + println!("Config: {:?}", config); let pool = PgPoolOptions::new() From 7c6442972ec1c5e99fa6f8de2342764aea42420d Mon Sep 17 00:00:00 2001 From: Tom Trevethan Date: Tue, 21 May 2024 22:08:25 +0100 Subject: [PATCH 60/66] add tls feature to sqlx --- server/Cargo.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/Cargo.toml b/server/Cargo.toml index 76b2b073..9a59bfcf 100644 --- a/server/Cargo.toml +++ b/server/Cargo.toml @@ -10,7 +10,7 @@ bitcoin = { version = "0.30.1", features = ["serde", "base64", "rand-std", "std" config = "0.13.1" reqwest = { version = "0.11.16", features = ["blocking", "json", "socks"] } rocket = { version = "0.5.0", features = ["json"] } -sqlx = { version = "0.7", features = [ "runtime-tokio", "postgres", "time", "uuid", "chrono" ] } +sqlx = { version = "0.7", features = [ "runtime-tokio", "postgres", "time", "uuid", "chrono", "tls-rustls" ] } serde = { version = "1.0.163", features = ["derive"] } serde_json = "1.0.96" schemars = { version = "0.8.12", features = ["chrono", "uuid"] } @@ -20,4 +20,4 @@ hex = "0.4.3" secp256k1-zkp = { git = "https://github.com/ssantos21/rust-secp256k1-zkp.git", branch = "blinded-musig-scheme", features = [ "rand-std", "bitcoin_hashes", "std" ] } # secp256k1-zkp = { path = "../ss-rust-secp256k1-zkp", features = [ "rand-std", "bitcoin_hashes", "std" ] } mercurylib = { path = "../lib" } -chrono = "0.4.31" \ No newline at end of file +chrono = "0.4.31" From 5f959900178f6c2d14e75e6cf4c4542474976e2c Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Wed, 22 May 2024 16:38:06 +0530 Subject: [PATCH 61/66] fix: version for docker images in ci/cd --- .github/workflows/ci.yaml | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index b7e30758..e74494da 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -24,6 +24,10 @@ jobs: - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 + - + name: Get last commit hash + id: get_commit_hash + run: echo "COMMIT_HASH=$(git rev-parse --short HEAD)" >> $GITHUB_ENV - name: Build and push for mercury-server uses: docker/build-push-action@v5 @@ -39,7 +43,7 @@ jobs: context: . file: ./token-server/Dockerfile push: true - tags: commerceblockx/token-server:latest + tags: commerceblockx/token-server:${{ env.COMMIT_HASH }} - name: Build and push for mercury-explorer uses: docker/build-push-action@v5 @@ -47,7 +51,7 @@ jobs: context: . file: ./explorer/Dockerfile push: true - tags: commerceblockx/mercury-explorer:latest + tags: commerceblockx/mercury-explorer:${{ env.COMMIT_HASH }} - name: Build and push for keylist-cronjob uses: docker/build-push-action@v5 @@ -55,4 +59,4 @@ jobs: context: . file: ./keylistCron/Dockerfile push: true - tags: commerceblockx/keylist-cronjob:latest + tags: commerceblockx/keylist-cronjob:${{ env.COMMIT_HASH }} From 128fdecd28d4535e04f66340c688b9802c7df3db Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Wed, 22 May 2024 16:53:32 +0530 Subject: [PATCH 62/66] fix: version for mercury server image --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index e74494da..913dc54e 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -35,7 +35,7 @@ jobs: context: . file: ./server/Dockerfile push: true - tags: commerceblockx/mercury-server:latest + tags: commerceblockx/mercury-server:${{ env.COMMIT_HASH }} - name: Build and push for token-server uses: docker/build-push-action@v5 From 5905d6762993409df144062396aa1a1e2859580a Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Wed, 22 May 2024 17:13:12 +0530 Subject: [PATCH 63/66] fix: version commit hash by github actions --- .github/workflows/ci.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 913dc54e..ded60eda 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -15,6 +15,8 @@ jobs: - name: Checkout uses: actions/checkout@v4 + with: + fetch-depth: 0 - name: Login to Docker Hub uses: docker/login-action@v3 From ddf5640b8f1dbe1c413cb2fe4e8579c8a9125d2f Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Wed, 22 May 2024 17:26:35 +0530 Subject: [PATCH 64/66] fix: last commit hash for actions --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index ded60eda..7963124e 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -29,7 +29,7 @@ jobs: - name: Get last commit hash id: get_commit_hash - run: echo "COMMIT_HASH=$(git rev-parse --short HEAD)" >> $GITHUB_ENV + run: echo "COMMIT_HASH=${{ github.sha }}" >> $GITHUB_ENV - name: Build and push for mercury-server uses: docker/build-push-action@v5 From 66e9b445d8568b72ed5fde4adf803709c527cceb Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Wed, 22 May 2024 17:45:28 +0530 Subject: [PATCH 65/66] fix: revert commit hashes to smaller string --- .github/workflows/ci.yaml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 7963124e..913dc54e 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -15,8 +15,6 @@ jobs: - name: Checkout uses: actions/checkout@v4 - with: - fetch-depth: 0 - name: Login to Docker Hub uses: docker/login-action@v3 @@ -29,7 +27,7 @@ jobs: - name: Get last commit hash id: get_commit_hash - run: echo "COMMIT_HASH=${{ github.sha }}" >> $GITHUB_ENV + run: echo "COMMIT_HASH=$(git rev-parse --short HEAD)" >> $GITHUB_ENV - name: Build and push for mercury-server uses: docker/build-push-action@v5 From 8fd62d5b059469eb15be012d67492a61386d4d87 Mon Sep 17 00:00:00 2001 From: DhananjayPurohit Date: Wed, 22 May 2024 19:23:39 +0530 Subject: [PATCH 66/66] fix: add position, token, url as env variable --- explorer/index.html | 2 +- explorer/main.js | 2 +- explorer/nginx.conf | 2 +- keylistCron/send_commitment.sh | 8 -------- 4 files changed, 3 insertions(+), 11 deletions(-) diff --git a/explorer/index.html b/explorer/index.html index 87e3afea..72291f61 100644 --- a/explorer/index.html +++ b/explorer/index.html @@ -47,7 +47,7 @@

Mercury layer lockbox status