diff --git a/.gitignore b/.gitignore index 990e0ad..4ad55d4 100644 --- a/.gitignore +++ b/.gitignore @@ -7,7 +7,7 @@ /tmp # will have compiled files and executables -/target +**/target # These are backup files generated by rustfmt **/*.rs.bk diff --git a/.gitmodules b/.gitmodules index 1af6d86..8e328b0 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,5 +1,5 @@ [submodule "rust-lightning"] path = rust-lightning - url = https://github.com/RGB-Tools/rust-lightning.git - branch = rgb + url = https://github.com/dcorral/rust-lightning.git + branch = persistence-layer shallow = true diff --git a/Cargo.lock b/Cargo.lock index a4a2436..bc29712 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1630,6 +1630,28 @@ dependencies = [ "syn 2.0.104", ] +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.104", + "unicode-xid", +] + [[package]] name = "des" version = "0.8.1" @@ -3946,13 +3968,13 @@ dependencies = [ [[package]] name = "regex" -version = "1.11.1" +version = "1.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" +checksum = "843bc0191f75f3e22651ae5f1e72939ab2f72a4bc30fa80a066bd66edefc24d4" dependencies = [ "aho-corasick", "memchr", - "regex-automata 0.4.9", + "regex-automata 0.4.13", "regex-syntax 0.8.5", ] @@ -3967,9 +3989,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.9" +version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" +checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c" dependencies = [ "aho-corasick", "memchr", @@ -4182,7 +4204,9 @@ dependencies = [ "regex", "reqwest", "rgb-lib", + "rln-migration", "scrypt", + "sea-orm", "serde", "serde_json", "serial_test", @@ -4283,6 +4307,14 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "rln-migration" +version = "0.1.0" +dependencies = [ + "async-std", + "sea-orm-migration", +] + [[package]] name = "rsa" version = "0.9.8" @@ -4562,14 +4594,15 @@ dependencies = [ [[package]] name = "sea-orm" -version = "1.1.14" +version = "1.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34963b2d68331ef5fbc8aa28a53781471c15f90ba1ad4f2689d21ce8b9a9d1f1" +checksum = "6d945f62558fac19e5988680d2fdf747b734c2dbc6ce2cb81ba33ed8dde5b103" dependencies = [ "async-stream", "async-trait", "bigdecimal", "chrono", + "derive_more", "futures-util", "log", "ouroboros", @@ -4591,10 +4624,11 @@ dependencies = [ [[package]] name = "sea-orm-cli" -version = "1.1.14" +version = "1.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edc17cb2b24e93fc1d56de7751a12222f2303c06e83ed4d7a1e929e39f30c7d7" +checksum = "c94492e2ab6c045b4cc38013809ce255d14c3d352c9f0d11e6b920e2adc948ad" dependencies = [ + "async-std", "chrono", "clap", "dotenvy", @@ -4609,9 +4643,9 @@ dependencies = [ [[package]] name = "sea-orm-macros" -version = "1.1.14" +version = "1.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a489127c872766445b4e28f846825f89a076ac3af2591d1365503a68f93e974c" +checksum = "84c2e64a50a9cc8339f10a27577e10062c7f995488e469f2c95762c5ee847832" dependencies = [ "heck 0.5.0", "proc-macro2", @@ -4623,9 +4657,9 @@ dependencies = [ [[package]] name = "sea-orm-migration" -version = "1.1.14" +version = "1.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "695e830a1332a4e3e57b5972eee00574a36060e1938afca7041a524e0955d5ba" +checksum = "7315c0cadb7e60fb17ee2bb282aa27d01911fc2a7e5836ec1d4ac37d19250bb4" dependencies = [ "async-trait", "clap", @@ -5876,6 +5910,12 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e70f2a8b45122e719eb623c01822704c4e0907e7e426a05927e1a1cfff5b75d0" +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + [[package]] name = "universal-hash" version = "0.5.1" diff --git a/Cargo.toml b/Cargo.toml index d62f805..fe0e715 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,6 +40,12 @@ rgb-lib = { version = "0.3.0-beta.4", features = [ "electrum", "esplora", ] } +rln-migration = { path = "migration" } +sea-orm = { version = "1.1.19", default-features = false, features = [ + "macros", + "runtime-async-std-rustls", + "sqlx-sqlite", +] } scrypt = "0.11.0" serde = { version = "^1.0", features = ["derive"] } serde_json = "1.0" diff --git a/migration/Cargo.lock b/migration/Cargo.lock new file mode 100644 index 0000000..0e91ca4 --- /dev/null +++ b/migration/Cargo.lock @@ -0,0 +1,2775 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "aliasable" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "250f629c0161ad8107cf89319e990051fae62832fd343083bea452d93e2205fd" + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "0.6.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" + +[[package]] +name = "anstyle-parse" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-attributes" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3203e79f4dd9bdda415ed03cf14dae5a2bf775c683a00f94e9cd1faf0f596e5" +dependencies = [ + "quote", + "syn 1.0.109", +] + +[[package]] +name = "async-channel" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35" +dependencies = [ + "concurrent-queue", + "event-listener 2.5.3", + "futures-core", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "497c00e0fd83a72a79a39fcbd8e3e2f055d6f6c7e025f3b3d91f4f8e76527fb8" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand 2.3.0", + "futures-lite 2.6.1", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-global-executor" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05b1b633a2115cd122d73b955eadd9916c18c8f510ec9cd1686404c60ad1c29c" +dependencies = [ + "async-channel 2.5.0", + "async-executor", + "async-io 2.6.0", + "async-lock 3.4.2", + "blocking", + "futures-lite 2.6.1", + "once_cell", + "tokio", +] + +[[package]] +name = "async-io" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fc5b45d93ef0529756f812ca52e44c221b35341892d3dcc34132ac02f3dd2af" +dependencies = [ + "async-lock 2.8.0", + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-lite 1.13.0", + "log", + "parking", + "polling 2.8.0", + "rustix 0.37.28", + "slab", + "socket2", + "waker-fn", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite 2.6.1", + "parking", + "polling 3.11.0", + "rustix 1.1.3", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "287272293e9d8c41773cec55e365490fe034813a2f172f502d6ddcf75b2f582b" +dependencies = [ + "event-listener 2.5.3", +] + +[[package]] +name = "async-lock" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +dependencies = [ + "event-listener 5.4.1", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-std" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c8e079a4ab67ae52b7403632e4618815d6db36d2a010cfe41b02c1b1578f93b" +dependencies = [ + "async-attributes", + "async-channel 1.9.0", + "async-global-executor", + "async-io 2.6.0", + "async-lock 3.4.2", + "crossbeam-utils", + "futures-channel", + "futures-core", + "futures-io", + "futures-lite 2.6.1", + "gloo-timers", + "kv-log-macro", + "log", + "memchr", + "once_cell", + "pin-project-lite", + "pin-utils", + "slab", + "wasm-bindgen-futures", +] + +[[package]] +name = "async-stream" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" +dependencies = [ + "async-stream-impl", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.114", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.114", +] + +[[package]] +name = "atoi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +dependencies = [ + "num-traits", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "blocking" +version = "1.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21" +dependencies = [ + "async-channel 2.5.0", + "async-task", + "futures-io", + "futures-lite 2.6.1", + "piper", +] + +[[package]] +name = "bumpalo" +version = "3.19.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dd9dc738b7a8311c7ade152424974d8115f2cdad61e8dab8dac9f2362298510" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b35204fbdc0b3f4446b89fc1ac2cf84a8a68971995d0bf2e925ec7cd960f9cb3" + +[[package]] +name = "cc" +version = "1.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6354c81bbfd62d9cfa9cb3c773c2b7b2a3a482d569de977fd0e961f6e7c00583" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "chrono" +version = "0.4.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fac4744fb15ae8337dc853fee7fb3f4e48c0fbaa23d0afe49c447b4fab126118" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link", +] + +[[package]] +name = "clap" +version = "4.5.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75ca66430e33a14957acc24c5077b503e7d374151b2b4b3a10c83b4ceb4be0e" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.5.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "793207c7fa6300a0608d1080b858e5fdbe713cdc1c8db9fb17777d8a13e63df0" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.5.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a92793da1a46a5f2a02a6f4c46c6496b28c43638adea8306fcb0caa1634f24e5" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.114", +] + +[[package]] +name = "clap_lex" +version = "0.7.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e64b0cc0439b12df2fa678eae89a1c56a529fd067a9115f7827f1fffd22b32" + +[[package]] +name = "colorchoice" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5" + +[[package]] +name = "crossbeam-queue" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "darling" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "syn 2.0.114", +] + +[[package]] +name = "darling_macro" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.114", +] + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.114", + "unicode-xid", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", + "subtle", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.114", +] + +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + +[[package]] +name = "either" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" +dependencies = [ + "serde", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "etcetera" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943" +dependencies = [ + "cfg-if", + "home", + "windows-sys 0.48.0", +] + +[[package]] +name = "event-listener" +version = "2.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" + +[[package]] +name = "event-listener" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +dependencies = [ + "concurrent-queue", + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener 5.4.1", + "pin-project-lite", +] + +[[package]] +name = "fastrand" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be" +dependencies = [ + "instant", +] + +[[package]] +name = "fastrand" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" + +[[package]] +name = "find-msvc-tools" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8591b0bcc8a98a64310a2fae1bb3e9b8564dd10e381e6e28010fde8e8e8568db" + +[[package]] +name = "flume" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095" +dependencies = [ + "futures-core", + "futures-sink", + "spin", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" + +[[package]] +name = "futures-executor" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-intrusive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" +dependencies = [ + "futures-core", + "lock_api", + "parking_lot", +] + +[[package]] +name = "futures-io" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" + +[[package]] +name = "futures-lite" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49a9d51ce47660b1e808d3c990b4709f2f415d928835a17dfd16991515c46bce" +dependencies = [ + "fastrand 1.9.0", + "futures-core", + "futures-io", + "memchr", + "parking", + "pin-project-lite", + "waker-fn", +] + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand 2.3.0", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-sink" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7" + +[[package]] +name = "futures-task" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" + +[[package]] +name = "futures-util" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" +dependencies = [ + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "glob" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" + +[[package]] +name = "gloo-timers" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994" +dependencies = [ + "futures-channel", + "futures-core", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" + +[[package]] +name = "hashlink" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[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.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" + +[[package]] +name = "hermit-abi" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +dependencies = [ + "displaydoc", + "potential_utf", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" + +[[package]] +name = "icu_properties" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af" + +[[package]] +name = "icu_provider" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" +dependencies = [ + "equivalent", + "hashbrown 0.16.1", +] + +[[package]] +name = "inherent" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c727f80bfa4a6c6e2508d2f05b6f4bfce242030bd88ed15ae5331c5b5d30fba7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.114", +] + +[[package]] +name = "instant" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "io-lifetimes" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" +dependencies = [ + "hermit-abi 0.3.9", + "libc", + "windows-sys 0.48.0", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" + +[[package]] +name = "js-sys" +version = "0.3.85" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c942ebf8e95485ca0d52d97da7c5a2c387d0e7f0ba4c35e93bfcaee045955b3" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "kv-log-macro" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de8b303297635ad57c9f5059fd9cee7a47f8e8daa09df0fcd07dd39fb22977f" +dependencies = [ + "log", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.180" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bcc35a38544a891a5f7c865aca548a982ccb3b8650a5b06d0fd33a10283c56fc" + +[[package]] +name = "libredox" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d0b95e02c851351f877147b7deea7b1afb1df71b63aa5f8270716e0c5720616" +dependencies = [ + "bitflags 2.10.0", + "libc", + "redox_syscall 0.7.0", +] + +[[package]] +name = "libsqlite3-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" + +[[package]] +name = "linux-raw-sys" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" + +[[package]] +name = "litemap" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" +dependencies = [ + "value-bag", +] + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + +[[package]] +name = "memchr" +version = "2.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "ordered-float" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bb71e1b3fa6ca1c61f383464aaf2bb0e2f8e772a1f01d486832464de363b951" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ouroboros" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0f050db9c44b97a94723127e6be766ac5c340c48f2c4bb3ffa11713744be59" +dependencies = [ + "aliasable", + "ouroboros_macro", + "static_assertions", +] + +[[package]] +name = "ouroboros_macro" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c7028bdd3d43083f6d8d4d5187680d0d3560d54df4cc9d752005268b41e64d0" +dependencies = [ + "heck 0.4.1", + "proc-macro2", + "proc-macro2-diagnostics", + "quote", + "syn 2.0.114", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "piper" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c8c490f422ef9a4efd2cb5b42b76c8613d7e7dfc1caf667b8a3350a5acc066" +dependencies = [ + "atomic-waker", + "fastrand 2.3.0", + "futures-io", +] + +[[package]] +name = "pkg-config" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" + +[[package]] +name = "polling" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b2d323e8ca7996b3e23126511a523f7e62924d93ecd5ae73b333815b0eb3dce" +dependencies = [ + "autocfg", + "bitflags 1.3.2", + "cfg-if", + "concurrent-queue", + "libc", + "log", + "pin-project-lite", + "windows-sys 0.48.0", +] + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi 0.5.2", + "pin-project-lite", + "rustix 1.1.3", + "windows-sys 0.61.2", +] + +[[package]] +name = "potential_utf" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro-error-attr2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "proc-macro-error2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" +dependencies = [ + "proc-macro-error-attr2", + "proc-macro2", + "quote", + "syn 2.0.114", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proc-macro2-diagnostics" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.114", + "version_check", + "yansi", +] + +[[package]] +name = "quote" +version = "1.0.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.10.0", +] + +[[package]] +name = "redox_syscall" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49f3fe0889e69e2ae9e41f4d6c4c0181701d00e4697b356fb1f74173a5e0ee27" +dependencies = [ + "bitflags 2.10.0", +] + +[[package]] +name = "regex" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843bc0191f75f3e22651ae5f1e72939ab2f72a4bc30fa80a066bd66edefc24d4" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rln-migration" +version = "0.1.0" +dependencies = [ + "async-std", + "sea-orm-migration", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "0.37.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "519165d378b97752ca44bbe15047d5d3409e875f39327546b42ac81d7e18c1b6" +dependencies = [ + "bitflags 1.3.2", + "errno", + "io-lifetimes", + "libc", + "linux-raw-sys 0.3.8", + "windows-sys 0.48.0", +] + +[[package]] +name = "rustix" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34" +dependencies = [ + "bitflags 2.10.0", + "errno", + "libc", + "linux-raw-sys 0.11.0", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c665f33d38cea657d9614f766881e4d510e0eda4239891eea56b4cadcf01801b" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "ryu" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a50f4cf475b65d88e057964e0e9bb1f0aa9bbb2036dc65c64596b42932536984" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sea-bae" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f694a6ab48f14bc063cfadff30ab551d3c7e46d8f81836c51989d548f44a2a25" +dependencies = [ + "heck 0.4.1", + "proc-macro-error2", + "proc-macro2", + "quote", + "syn 2.0.114", +] + +[[package]] +name = "sea-orm" +version = "1.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d945f62558fac19e5988680d2fdf747b734c2dbc6ce2cb81ba33ed8dde5b103" +dependencies = [ + "async-stream", + "async-trait", + "derive_more", + "futures-util", + "log", + "ouroboros", + "sea-orm-macros", + "sea-query", + "sea-query-binder", + "serde", + "sqlx", + "strum", + "thiserror", + "tracing", + "url", +] + +[[package]] +name = "sea-orm-cli" +version = "1.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c94492e2ab6c045b4cc38013809ce255d14c3d352c9f0d11e6b920e2adc948ad" +dependencies = [ + "async-std", + "chrono", + "clap", + "dotenvy", + "glob", + "regex", + "sea-schema", + "sqlx", + "tracing", + "tracing-subscriber", + "url", +] + +[[package]] +name = "sea-orm-macros" +version = "1.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84c2e64a50a9cc8339f10a27577e10062c7f995488e469f2c95762c5ee847832" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "sea-bae", + "syn 2.0.114", + "unicode-ident", +] + +[[package]] +name = "sea-orm-migration" +version = "1.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7315c0cadb7e60fb17ee2bb282aa27d01911fc2a7e5836ec1d4ac37d19250bb4" +dependencies = [ + "async-trait", + "clap", + "dotenvy", + "sea-orm", + "sea-orm-cli", + "sea-schema", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "sea-query" +version = "0.32.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a5d1c518eaf5eda38e5773f902b26ab6d5e9e9e2bb2349ca6c64cf96f80448c" +dependencies = [ + "inherent", + "ordered-float", + "sea-query-derive", +] + +[[package]] +name = "sea-query-binder" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0019f47430f7995af63deda77e238c17323359af241233ec768aba1faea7608" +dependencies = [ + "sea-query", + "sqlx", +] + +[[package]] +name = "sea-query-derive" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bae0cbad6ab996955664982739354128c58d16e126114fe88c2a493642502aab" +dependencies = [ + "darling", + "heck 0.4.1", + "proc-macro2", + "quote", + "syn 2.0.114", + "thiserror", +] + +[[package]] +name = "sea-schema" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2239ff574c04858ca77485f112afea1a15e53135d3097d0c86509cef1def1338" +dependencies = [ + "futures", + "sea-query", + "sea-query-binder", + "sea-schema-derive", + "sqlx", +] + +[[package]] +name = "sea-schema-derive" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "debdc8729c37fdbf88472f97fd470393089f997a909e535ff67c544d18cfccf0" +dependencies = [ + "heck 0.4.1", + "proc-macro2", + "quote", + "syn 2.0.114", +] + +[[package]] +name = "semver" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.114", +] + +[[package]] +name = "serde_json" +version = "1.0.149" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "slab" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +dependencies = [ + "serde", +] + +[[package]] +name = "socket2" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7916fc008ca5542385b89a3d3ce689953c143e9304a9bf8beec1de48994c0d" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "spin" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" +dependencies = [ + "lock_api", +] + +[[package]] +name = "sqlx" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc" +dependencies = [ + "sqlx-core", + "sqlx-macros", + "sqlx-postgres", + "sqlx-sqlite", +] + +[[package]] +name = "sqlx-core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6" +dependencies = [ + "async-io 1.13.0", + "async-std", + "base64", + "bytes", + "crc", + "crossbeam-queue", + "either", + "event-listener 5.4.1", + "futures-core", + "futures-intrusive", + "futures-io", + "futures-util", + "hashbrown 0.15.5", + "hashlink", + "indexmap", + "log", + "memchr", + "once_cell", + "percent-encoding", + "rustls", + "serde", + "serde_json", + "sha2", + "smallvec", + "thiserror", + "tracing", + "url", + "webpki-roots 0.26.11", +] + +[[package]] +name = "sqlx-macros" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2d452988ccaacfbf5e0bdbc348fb91d7c8af5bee192173ac3636b5fb6e6715d" +dependencies = [ + "proc-macro2", + "quote", + "sqlx-core", + "sqlx-macros-core", + "syn 2.0.114", +] + +[[package]] +name = "sqlx-macros-core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19a9c1841124ac5a61741f96e1d9e2ec77424bf323962dd894bdb93f37d5219b" +dependencies = [ + "async-std", + "dotenvy", + "either", + "heck 0.5.0", + "hex", + "once_cell", + "proc-macro2", + "quote", + "serde", + "serde_json", + "sha2", + "sqlx-core", + "sqlx-postgres", + "sqlx-sqlite", + "syn 2.0.114", + "url", +] + +[[package]] +name = "sqlx-postgres" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46" +dependencies = [ + "atoi", + "base64", + "bitflags 2.10.0", + "byteorder", + "crc", + "dotenvy", + "etcetera", + "futures-channel", + "futures-core", + "futures-util", + "hex", + "hkdf", + "hmac", + "home", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "rand", + "serde", + "serde_json", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "whoami", +] + +[[package]] +name = "sqlx-sqlite" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2d12fe70b2c1b4401038055f90f151b78208de1f9f89a7dbfd41587a10c3eea" +dependencies = [ + "atoi", + "flume", + "futures-channel", + "futures-core", + "futures-executor", + "futures-intrusive", + "futures-util", + "libsqlite3-sys", + "log", + "percent-encoding", + "serde", + "serde_urlencoded", + "sqlx-core", + "thiserror", + "tracing", + "url", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4d107df263a3013ef9b1879b0df87d706ff80f65a86ea879bd9c31f9b307c2a" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.114", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.114", +] + +[[package]] +name = "thread_local" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tinystr" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.49.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.114", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f30143827ddab0d256fd843b7a66d164e9f271cfa0dde49142c5ca0ca291f1e" +dependencies = [ + "matchers", + "once_cell", + "regex-automata", + "sharded-slab", + "thread_local", + "tracing", + "tracing-core", +] + +[[package]] +name = "typenum" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5" + +[[package]] +name = "unicode-normalization" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "value-bag" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ba6f5989077681266825251a52748b8c1d8a4ad098cc37e440103d0ea717fc0" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "waker-fn" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "317211a0dc0ceedd78fb2ca9a44aed3d7b9b26f81870d485c07122b4350673b7" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[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.108" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64024a30ec1e37399cf85a7ffefebdb72205ca1c972291c51512360d90bd8566" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70a6e77fd0ae8029c9ea0063f87c46fde723e7d887703d74ad2616d792e51e6f" +dependencies = [ + "cfg-if", + "futures-util", + "js-sys", + "once_cell", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.108" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "008b239d9c740232e71bd39e8ef6429d27097518b6b30bdf9086833bd5b6d608" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.108" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5256bae2d58f54820e6490f9839c49780dff84c65aeab9e772f15d5f0e913a55" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.114", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.108" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f01b580c9ac74c8d8f0c0e4afb04eeef2acf145458e52c03845ee9cd23e3d12" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.85" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "312e32e551d92129218ea9a2452120f4aabc03529ef03e4d0d82fb2780608598" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.5", +] + +[[package]] +name = "webpki-roots" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12bed680863276c63889429bfd6cab3b99943659923822de1c8a39c49e4d722c" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "whoami" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d" +dependencies = [ + "libredox", + "wasite", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.114", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.114", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "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.6", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "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.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[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.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[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.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[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.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[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.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[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.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[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.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" + +[[package]] +name = "yansi" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" + +[[package]] +name = "yoke" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.114", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dafd85c832c1b68bbb4ec0c72c7f6f4fc5179627d2bc7c26b30e4c0cc11e76cc" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cb7e4e8436d9db52fbd6625dbf2f45243ab84994a72882ec8227b99e72b439a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.114", +] + +[[package]] +name = "zerofrom" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.114", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" + +[[package]] +name = "zerotrie" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.114", +] + +[[package]] +name = "zmij" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02aae0f83f69aafc94776e879363e9771d7ecbffe2c7fbb6c14c5e00dfe88439" diff --git a/migration/Cargo.toml b/migration/Cargo.toml new file mode 100644 index 0000000..fcd13dd --- /dev/null +++ b/migration/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "rln-migration" +version = "0.1.0" +edition = "2021" +publish = false + +[lib] +name = "rln_migration" +path = "src/lib.rs" + +[dependencies] +async-std = { version = "1.13", default-features = false, features = [ + "attributes", + "tokio1", +] } +sea-orm-migration = { version = "1.1.19", default-features = false, features = [ + "cli", + "runtime-async-std-rustls", + "sqlx-postgres", + "sqlx-sqlite", +] } diff --git a/migration/README.md b/migration/README.md new file mode 100644 index 0000000..d563447 --- /dev/null +++ b/migration/README.md @@ -0,0 +1,57 @@ +# DB migrations + +Every time a change to a DB object or table is needed, a migration has to be +created. + +In rgb-lightning-node we use sea-orm tools to handle the DB and its migrations. + +To generate new migrations the [sea-orm-cli] tool is needed. You should install +the same version that has been previously used. You can find this in the +`src/database/entities/mod.rs` file, where the first line will specify `//! +SeaORM Entity. Generated by sea-orm-codegen `. Install it with: +```sh +cargo install sea-orm-cli --version +``` + +Then, to generate a new migration file, run: +```sh +sea-orm-cli migrate generate +``` + +This command will create a new file where you'll find the `up` and `down` +methods (see `migration/src/m20250127_000001_init_db.rs` for an example). These +methods will be empty and will need to be implemented in order to give +instructions on how to respectively update and revert the new changes. + +Once the migration file is ready, you'll need to run a local postgres DB and +use it to refresh the migration and generate entities with `sea-orm-cli`. This +is accomplished with: +```sh +docker pull postgres:latest + +docker run -p 127.0.0.1:5432:5432/tcp --name migration-postgres \ + -e POSTGRES_PASSWORD=mysecretpassword -d postgres + +DATABASE_URL=postgres://postgres:mysecretpassword@localhost:5432 \ + sea-orm-cli migrate up + +DATABASE_URL=postgres://postgres:mysecretpassword@localhost:5432 \ + sea-orm-cli migrate refresh + +DATABASE_URL=postgres://postgres:mysecretpassword@localhost:5432/postgres \ + sea-orm-cli generate entity -o src/database/entities --expanded-format + +docker rm -f migration-postgres +``` + +The command to generate entities will apply some unwanted changes, for example +it will change the enum fields to integers and will remove some extra `derive`s +that we manually added. Those changes will need to be discarded, so please be +sure to add only the code that is related to the new changes you just applied. +To do this we suggest to first refresh the migration and generate entities with +`sea-orm-cli` on the branch you are about to apply the DB changes on. The +generated diff will only include unwanted changes, so they can be used as a +reference to revert them. + + +[sea-orm-cli]: https://github.com/SeaQL/sea-orm/tree/master/sea-orm-cli diff --git a/migration/src/lib.rs b/migration/src/lib.rs new file mode 100644 index 0000000..540be39 --- /dev/null +++ b/migration/src/lib.rs @@ -0,0 +1,12 @@ +pub use sea_orm_migration::prelude::*; + +mod m20250127_000001_init_db; + +pub struct Migrator; + +#[async_trait::async_trait] +impl MigratorTrait for Migrator { + fn migrations() -> Vec> { + vec![Box::new(m20250127_000001_init_db::Migration)] + } +} diff --git a/migration/src/m20250127_000001_init_db.rs b/migration/src/m20250127_000001_init_db.rs new file mode 100644 index 0000000..7697126 --- /dev/null +++ b/migration/src/m20250127_000001_init_db.rs @@ -0,0 +1,166 @@ +use sea_orm_migration::{prelude::*, schema::*}; + +#[derive(DeriveMigrationName)] +pub struct Migration; + +#[async_trait::async_trait] +impl MigrationTrait for Migration { + async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .create_table( + Table::create() + .table(Mnemonic::Table) + .if_not_exists() + .col( + ColumnDef::new(Mnemonic::Id) + .integer() + .not_null() + .primary_key() + .default(1), + ) + .col(string(Mnemonic::EncryptedMnemonic)) + .col(big_unsigned(Mnemonic::CreatedAt)) + .col(big_unsigned(Mnemonic::UpdatedAt)) + .to_owned(), + ) + .await?; + + manager + .create_table( + Table::create() + .table(KvStore::Table) + .if_not_exists() + .col(string(KvStore::PrimaryNamespace)) + .col(string(KvStore::SecondaryNamespace)) + .col(string(KvStore::Key)) + .col(blob(KvStore::Value)) + .primary_key( + Index::create() + .col(KvStore::PrimaryNamespace) + .col(KvStore::SecondaryNamespace) + .col(KvStore::Key), + ) + .to_owned(), + ) + .await?; + + manager + .create_table( + Table::create() + .table(Config::Table) + .if_not_exists() + .col( + ColumnDef::new(Config::Key) + .string() + .not_null() + .primary_key(), + ) + .col(ColumnDef::new(Config::Value).string().not_null()) + .col(ColumnDef::new(Config::CreatedAt).big_integer().not_null()) + .col(ColumnDef::new(Config::UpdatedAt).big_integer().not_null()) + .to_owned(), + ) + .await?; + + manager + .create_table( + Table::create() + .table(RevokedToken::Table) + .if_not_exists() + .col( + ColumnDef::new(RevokedToken::TokenId) + .string() + .not_null() + .primary_key(), + ) + .col( + ColumnDef::new(RevokedToken::RevokedAt) + .big_integer() + .not_null(), + ) + .to_owned(), + ) + .await?; + + manager + .create_table( + Table::create() + .table(ChannelPeer::Table) + .if_not_exists() + .col( + ColumnDef::new(ChannelPeer::Pubkey) + .string() + .not_null() + .primary_key(), + ) + .col(ColumnDef::new(ChannelPeer::Address).string().not_null()) + .col( + ColumnDef::new(ChannelPeer::CreatedAt) + .big_integer() + .not_null(), + ) + .to_owned(), + ) + .await + } + + async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { + manager + .drop_table(Table::drop().table(ChannelPeer::Table).to_owned()) + .await?; + manager + .drop_table(Table::drop().table(RevokedToken::Table).to_owned()) + .await?; + manager + .drop_table(Table::drop().table(Config::Table).to_owned()) + .await?; + manager + .drop_table(Table::drop().table(KvStore::Table).to_owned()) + .await?; + manager + .drop_table(Table::drop().table(Mnemonic::Table).to_owned()) + .await + } +} + +#[derive(DeriveIden)] +enum Mnemonic { + Table, + Id, + EncryptedMnemonic, + CreatedAt, + UpdatedAt, +} + +#[derive(DeriveIden)] +enum KvStore { + Table, + PrimaryNamespace, + SecondaryNamespace, + Key, + Value, +} + +#[derive(DeriveIden)] +enum Config { + Table, + Key, + Value, + CreatedAt, + UpdatedAt, +} + +#[derive(DeriveIden)] +enum RevokedToken { + Table, + TokenId, + RevokedAt, +} + +#[derive(DeriveIden)] +enum ChannelPeer { + Table, + Pubkey, + Address, + CreatedAt, +} diff --git a/migration/src/main.rs b/migration/src/main.rs new file mode 100644 index 0000000..b5d0929 --- /dev/null +++ b/migration/src/main.rs @@ -0,0 +1,6 @@ +use sea_orm_migration::prelude::*; + +#[async_std::main] +async fn main() { + cli::run_cli(rln_migration::Migrator).await; +} diff --git a/rust-lightning b/rust-lightning index 961313c..b061470 160000 --- a/rust-lightning +++ b/rust-lightning @@ -1 +1 @@ -Subproject commit 961313c75d410a5c92118b5eda8255809a8eac20 +Subproject commit b061470f756108519d43bbfdcbb7cb846ed36342 diff --git a/src/auth.rs b/src/auth.rs index 42ef7a0..805a52a 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -6,22 +6,13 @@ use axum::{ response::Response, }; use biscuit_auth::{macros::authorizer, Biscuit, PublicKey}; -use std::{ - collections::HashSet, - fs, - io::{BufRead, BufReader, Write as IoWrite}, - path::PathBuf, - sync::Arc, -}; -use tempfile::NamedTempFile; +use std::{collections::HashSet, sync::Arc}; use crate::{ error::{APIError, AppError}, utils::{hex_str, hex_str_to_vec, AppState}, }; -const REVOKED_TOKENS_FILE: &str = "revoked_tokens.txt"; - const READ_ONLY_OPS: [&str; 23] = [ "/assetbalance", "/assetmetadata", @@ -189,55 +180,14 @@ fn is_token_expired(token: &Biscuit) -> bool { impl AppState { pub(crate) fn revoke_token(&self, token_to_revoke: &Biscuit) -> Result<(), APIError> { let revocation_ids = token_to_revoke.revocation_identifiers(); + let db = self.get_db(); - let file_body = { - let mut revoked = self.revoked_tokens.lock().unwrap(); - for id in revocation_ids { - revoked.insert(id); - } - - let mut updated_list = String::new(); - for token_id in revoked.iter() { - updated_list.push_str(&hex_str(token_id)); - updated_list.push('\n'); - } - updated_list - }; // drop lock - - let path = self.get_revoked_tokens_path(); - - // write to a temp file - let dir = path.parent().expect("parent defined"); - let mut tmp = NamedTempFile::new_in(dir).map_err(|e| { - tracing::error!( - "Failed to create temporary file in {}: {}", - dir.display(), - e - ); - APIError::IO(e) - })?; - tmp.as_file_mut() - .write_all(file_body.as_bytes()) - .and_then(|_| tmp.as_file_mut().flush()) - .and_then(|_| tmp.as_file().sync_all()) - .map_err(|e| { - tracing::error!( - "Failed to write/flush/sync temporary revoked-tokens file: {}", - e - ); - APIError::IO(e) - })?; - - // atomically replace the destination file with the synced temp file - tmp.persist(&path).map_err(|persist_err| { - let e = persist_err.error; - tracing::error!( - "Failed to persist temporary file to {}: {}", - path.display(), - e - ); - APIError::IO(e) - })?; + let mut revoked = self.revoked_tokens.lock().unwrap(); + for id in revocation_ids { + let token_id_hex = hex_str(&id); + db.add_revoked_token(&token_id_hex)?; + revoked.insert(id); + } Ok(()) } @@ -248,64 +198,15 @@ impl AppState { !revocation_ids.is_disjoint(&*revoked) } - fn get_revoked_tokens_path(&self) -> PathBuf { - self.static_state.storage_dir_path.join(REVOKED_TOKENS_FILE) - } - pub(crate) fn load_revoked_tokens(&self) -> Result>, AppError> { - let path = self.get_revoked_tokens_path(); - - let file = match fs::File::open(&path) { - Ok(f) => f, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => { - tracing::info!( - "No revoked tokens file found at {}, starting with empty set", - path.display() - ); - return Ok(HashSet::new()); - } - Err(e) => { - tracing::error!( - "Failed to open revoked tokens file {}: {}", - path.display(), - e - ); - return Err(AppError::IO(e)); - } - }; - - let mut revoked: HashSet> = HashSet::new(); - let reader = BufReader::new(file); - for (lineno, line_res) in reader.lines().enumerate() { - let line = line_res.map_err(|e| { - tracing::error!( - "I/O error while reading {} at line {}: {}", - path.display(), - lineno + 1, - e - ); - AppError::IO(e) - })?; - let s = line.trim(); - if s.is_empty() || s.starts_with('#') { - continue; - } - match hex_str_to_vec(s) { - Some(token_id) => { - revoked.insert(token_id); - } - None => { - tracing::error!( - "Invalid hex string in revoked tokens at {}:{} -> {:?}", - path.display(), - lineno + 1, - s - ); - return Err(AppError::InvalidRevokedTokensFile); - } - } - } - tracing::info!("Loaded {} revoked tokens", revoked.len()); + let db = self.get_db(); + let revoked = db.load_revoked_tokens().map_err(|e| { + tracing::error!("Failed to load revoked tokens from database: {e:?}"); + AppError::IO(std::io::Error::other(format!( + "Failed to load revoked tokens: {e:?}" + ))) + })?; + tracing::info!("Loaded {} revoked tokens from database", revoked.len()); Ok(revoked) } } diff --git a/src/database/entities/channel_peer.rs b/src/database/entities/channel_peer.rs new file mode 100644 index 0000000..58abfc4 --- /dev/null +++ b/src/database/entities/channel_peer.rs @@ -0,0 +1,60 @@ +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.19 + +use sea_orm::entity::prelude::*; + +#[derive(Copy, Clone, Default, Debug, DeriveEntity)] +pub struct Entity; + +impl EntityName for Entity { + fn table_name(&self) -> &str { + "channel_peer" + } +} + +#[derive(Clone, Debug, PartialEq, DeriveModel, DeriveActiveModel, Eq)] +pub struct Model { + pub pubkey: String, + pub address: String, + pub created_at: i64, +} + +#[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)] +pub enum Column { + Pubkey, + Address, + CreatedAt, +} + +#[derive(Copy, Clone, Debug, EnumIter, DerivePrimaryKey)] +pub enum PrimaryKey { + Pubkey, +} + +impl PrimaryKeyTrait for PrimaryKey { + type ValueType = String; + fn auto_increment() -> bool { + false + } +} + +#[derive(Copy, Clone, Debug, EnumIter)] +pub enum Relation {} + +impl ColumnTrait for Column { + type EntityName = Entity; + fn def(&self) -> ColumnDef { + match self { + Self::Pubkey => ColumnType::String(StringLen::None).def(), + Self::Address => ColumnType::String(StringLen::None).def(), + Self::CreatedAt => ColumnType::BigInteger.def(), + } + } +} + +impl RelationTrait for Relation { + fn def(&self) -> RelationDef { + panic!("No RelationDef") + } +} + +impl ActiveModelBehavior for ActiveModel {} diff --git a/src/database/entities/config.rs b/src/database/entities/config.rs new file mode 100644 index 0000000..ff26c6d --- /dev/null +++ b/src/database/entities/config.rs @@ -0,0 +1,63 @@ +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.19 + +use sea_orm::entity::prelude::*; + +#[derive(Copy, Clone, Default, Debug, DeriveEntity)] +pub struct Entity; + +impl EntityName for Entity { + fn table_name(&self) -> &str { + "config" + } +} + +#[derive(Clone, Debug, PartialEq, DeriveModel, DeriveActiveModel, Eq)] +pub struct Model { + pub key: String, + pub value: String, + pub created_at: i64, + pub updated_at: i64, +} + +#[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)] +pub enum Column { + Key, + Value, + CreatedAt, + UpdatedAt, +} + +#[derive(Copy, Clone, Debug, EnumIter, DerivePrimaryKey)] +pub enum PrimaryKey { + Key, +} + +impl PrimaryKeyTrait for PrimaryKey { + type ValueType = String; + fn auto_increment() -> bool { + false + } +} + +#[derive(Copy, Clone, Debug, EnumIter)] +pub enum Relation {} + +impl ColumnTrait for Column { + type EntityName = Entity; + fn def(&self) -> ColumnDef { + match self { + Self::Key => ColumnType::String(StringLen::None).def(), + Self::Value => ColumnType::String(StringLen::None).def(), + Self::CreatedAt => ColumnType::BigInteger.def(), + Self::UpdatedAt => ColumnType::BigInteger.def(), + } + } +} + +impl RelationTrait for Relation { + fn def(&self) -> RelationDef { + panic!("No RelationDef") + } +} + +impl ActiveModelBehavior for ActiveModel {} diff --git a/src/database/entities/kv_store.rs b/src/database/entities/kv_store.rs new file mode 100644 index 0000000..38c7a68 --- /dev/null +++ b/src/database/entities/kv_store.rs @@ -0,0 +1,65 @@ +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.19 + +use sea_orm::entity::prelude::*; + +#[derive(Copy, Clone, Default, Debug, DeriveEntity)] +pub struct Entity; + +impl EntityName for Entity { + fn table_name(&self) -> &str { + "kv_store" + } +} + +#[derive(Clone, Debug, PartialEq, DeriveModel, DeriveActiveModel, Eq)] +pub struct Model { + pub primary_namespace: String, + pub secondary_namespace: String, + pub key: String, + pub value: Vec, +} + +#[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)] +pub enum Column { + PrimaryNamespace, + SecondaryNamespace, + Key, + Value, +} + +#[derive(Copy, Clone, Debug, EnumIter, DerivePrimaryKey)] +pub enum PrimaryKey { + PrimaryNamespace, + SecondaryNamespace, + Key, +} + +impl PrimaryKeyTrait for PrimaryKey { + type ValueType = (String, String, String); + fn auto_increment() -> bool { + false + } +} + +#[derive(Copy, Clone, Debug, EnumIter)] +pub enum Relation {} + +impl ColumnTrait for Column { + type EntityName = Entity; + fn def(&self) -> ColumnDef { + match self { + Self::PrimaryNamespace => ColumnType::String(StringLen::None).def(), + Self::SecondaryNamespace => ColumnType::String(StringLen::None).def(), + Self::Key => ColumnType::String(StringLen::None).def(), + Self::Value => ColumnType::VarBinary(StringLen::None).def(), + } + } +} + +impl RelationTrait for Relation { + fn def(&self) -> RelationDef { + panic!("No RelationDef") + } +} + +impl ActiveModelBehavior for ActiveModel {} diff --git a/src/database/entities/mnemonic.rs b/src/database/entities/mnemonic.rs new file mode 100644 index 0000000..68ad3dd --- /dev/null +++ b/src/database/entities/mnemonic.rs @@ -0,0 +1,63 @@ +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.19 + +use sea_orm::entity::prelude::*; + +#[derive(Copy, Clone, Default, Debug, DeriveEntity)] +pub struct Entity; + +impl EntityName for Entity { + fn table_name(&self) -> &str { + "mnemonic" + } +} + +#[derive(Clone, Debug, PartialEq, DeriveModel, DeriveActiveModel, Eq)] +pub struct Model { + pub id: i32, + pub encrypted_mnemonic: String, + pub created_at: i64, + pub updated_at: i64, +} + +#[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)] +pub enum Column { + Id, + EncryptedMnemonic, + CreatedAt, + UpdatedAt, +} + +#[derive(Copy, Clone, Debug, EnumIter, DerivePrimaryKey)] +pub enum PrimaryKey { + Id, +} + +impl PrimaryKeyTrait for PrimaryKey { + type ValueType = i32; + fn auto_increment() -> bool { + false + } +} + +#[derive(Copy, Clone, Debug, EnumIter)] +pub enum Relation {} + +impl ColumnTrait for Column { + type EntityName = Entity; + fn def(&self) -> ColumnDef { + match self { + Self::Id => ColumnType::Integer.def(), + Self::EncryptedMnemonic => ColumnType::String(StringLen::None).def(), + Self::CreatedAt => ColumnType::BigInteger.def(), + Self::UpdatedAt => ColumnType::BigInteger.def(), + } + } +} + +impl RelationTrait for Relation { + fn def(&self) -> RelationDef { + panic!("No RelationDef") + } +} + +impl ActiveModelBehavior for ActiveModel {} diff --git a/src/database/entities/mod.rs b/src/database/entities/mod.rs new file mode 100644 index 0000000..63327c7 --- /dev/null +++ b/src/database/entities/mod.rs @@ -0,0 +1,22 @@ +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.19 + +pub mod channel_peer; +pub mod config; +pub mod kv_store; +pub mod mnemonic; +pub mod revoked_token; + +pub use channel_peer::{ + ActiveModel as ChannelPeerActMod, Column as ChannelPeerColumn, Entity as ChannelPeerEntity, +}; +pub use config::{ActiveModel as ConfigActMod, Column as ConfigColumn, Entity as ConfigEntity}; +pub use kv_store::{ + ActiveModel as KvStoreActMod, Column as KvStoreColumn, Entity as KvStoreEntity, +}; +pub use mnemonic::{ + ActiveModel as DbMnemonicActMod, Column as MnemonicColumn, Entity as MnemonicEntity, + Model as DbMnemonic, +}; +pub use revoked_token::{ + ActiveModel as RevokedTokenActMod, Column as RevokedTokenColumn, Entity as RevokedTokenEntity, +}; diff --git a/src/database/entities/revoked_token.rs b/src/database/entities/revoked_token.rs new file mode 100644 index 0000000..ae176b2 --- /dev/null +++ b/src/database/entities/revoked_token.rs @@ -0,0 +1,57 @@ +//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.19 + +use sea_orm::entity::prelude::*; + +#[derive(Copy, Clone, Default, Debug, DeriveEntity)] +pub struct Entity; + +impl EntityName for Entity { + fn table_name(&self) -> &str { + "revoked_token" + } +} + +#[derive(Clone, Debug, PartialEq, DeriveModel, DeriveActiveModel, Eq)] +pub struct Model { + pub token_id: String, + pub revoked_at: i64, +} + +#[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)] +pub enum Column { + TokenId, + RevokedAt, +} + +#[derive(Copy, Clone, Debug, EnumIter, DerivePrimaryKey)] +pub enum PrimaryKey { + TokenId, +} + +impl PrimaryKeyTrait for PrimaryKey { + type ValueType = String; + fn auto_increment() -> bool { + false + } +} + +#[derive(Copy, Clone, Debug, EnumIter)] +pub enum Relation {} + +impl ColumnTrait for Column { + type EntityName = Entity; + fn def(&self) -> ColumnDef { + match self { + Self::TokenId => ColumnType::String(StringLen::None).def(), + Self::RevokedAt => ColumnType::BigInteger.def(), + } + } +} + +impl RelationTrait for Relation { + fn def(&self) -> RelationDef { + panic!("No RelationDef") + } +} + +impl ActiveModelBehavior for ActiveModel {} diff --git a/src/database/mod.rs b/src/database/mod.rs new file mode 100644 index 0000000..c21d502 --- /dev/null +++ b/src/database/mod.rs @@ -0,0 +1,203 @@ +pub(crate) mod entities; + +use std::collections::{HashMap, HashSet}; +use std::net::SocketAddr; +use std::str::FromStr; + +use bitcoin::secp256k1::PublicKey; +use futures::executor::block_on; +use sea_orm::sea_query::OnConflict; +use sea_orm::{ActiveValue, ColumnTrait, DatabaseConnection, EntityTrait, ModelTrait, QueryFilter}; + +use crate::database::entities::{ + ChannelPeerActMod, ChannelPeerColumn, ChannelPeerEntity, ConfigActMod, ConfigColumn, + ConfigEntity, DbMnemonic, DbMnemonicActMod, MnemonicColumn, MnemonicEntity, RevokedTokenActMod, + RevokedTokenColumn, RevokedTokenEntity, +}; +use crate::error::APIError; + +pub struct RlnDatabase { + connection: DatabaseConnection, +} + +impl RlnDatabase { + pub fn new(connection: DatabaseConnection) -> Self { + Self { connection } + } + + pub fn get_connection(&self) -> &DatabaseConnection { + &self.connection + } + + pub fn add_revoked_token(&self, token_id_hex: &str) -> Result<(), APIError> { + let now = crate::utils::get_current_timestamp() as i64; + + let token = RevokedTokenActMod { + token_id: ActiveValue::Set(token_id_hex.to_string()), + revoked_at: ActiveValue::Set(now), + }; + + // Use on_conflict to ignore duplicates + block_on( + RevokedTokenEntity::insert(token) + .on_conflict( + OnConflict::column(RevokedTokenColumn::TokenId) + .do_nothing() + .to_owned(), + ) + .exec(self.get_connection()), + ) + .map_err(|e| std::io::Error::other(format!("Database write failed: {e}")))?; + + Ok(()) + } + + pub fn delete_channel_peer(&self, pubkey: &str) -> Result<(), APIError> { + let result = block_on( + ChannelPeerEntity::find() + .filter(ChannelPeerColumn::Pubkey.eq(pubkey)) + .one(self.get_connection()), + ) + .map_err(|e| std::io::Error::other(format!("Database query failed: {e}")))?; + + if let Some(peer) = result { + block_on(peer.delete(self.get_connection())) + .map_err(|e| std::io::Error::other(format!("Database delete failed: {e}")))?; + } + + Ok(()) + } + + pub fn get_config(&self, key: &str) -> Result, APIError> { + let result = block_on( + ConfigEntity::find() + .filter(ConfigColumn::Key.eq(key)) + .one(self.get_connection()), + ) + .map_err(|e| std::io::Error::other(format!("Database query failed: {e}")))?; + + Ok(result.map(|r| r.value)) + } + + pub fn get_mnemonic(&self) -> Result, APIError> { + block_on(MnemonicEntity::find_by_id(1).one(self.get_connection())) + .map_err(|e| std::io::Error::other(format!("Database query failed: {e}"))) + .map_err(APIError::IO) + } + + pub fn load_revoked_tokens(&self) -> Result>, APIError> { + let results = block_on(RevokedTokenEntity::find().all(self.get_connection())) + .map_err(|e| std::io::Error::other(format!("Database query failed: {e}")))?; + + let mut revoked = HashSet::new(); + for record in results { + if let Some(token_bytes) = crate::utils::hex_str_to_vec(&record.token_id) { + revoked.insert(token_bytes); + } + } + + Ok(revoked) + } + + pub fn mnemonic_exists(&self) -> Result { + let result = block_on(MnemonicEntity::find_by_id(1).one(self.get_connection())) + .map_err(|e| std::io::Error::other(format!("Database query failed: {e}")))?; + Ok(result.is_some()) + } + + pub fn persist_channel_peer( + &self, + pubkey: &PublicKey, + address: &SocketAddr, + ) -> Result<(), APIError> { + let now = crate::utils::get_current_timestamp() as i64; + + let peer = ChannelPeerActMod { + pubkey: ActiveValue::Set(pubkey.to_string()), + address: ActiveValue::Set(address.to_string()), + created_at: ActiveValue::Set(now), + }; + + block_on( + ChannelPeerEntity::insert(peer) + .on_conflict( + OnConflict::column(ChannelPeerColumn::Pubkey) + .update_column(ChannelPeerColumn::Address) + .to_owned(), + ) + .exec(self.get_connection()), + ) + .map_err(|e| std::io::Error::other(format!("Database write failed: {e}")))?; + + tracing::info!("persisted peer (pubkey: {pubkey}, addr: {address})"); + Ok(()) + } + + pub fn read_channel_peer_data(&self) -> Result, APIError> { + let results = block_on(ChannelPeerEntity::find().all(self.get_connection())) + .map_err(|e| std::io::Error::other(format!("Database query failed: {e}")))?; + + let mut peer_data = HashMap::new(); + for record in results { + if let (Ok(pubkey), Ok(address)) = ( + PublicKey::from_str(&record.pubkey), + SocketAddr::from_str(&record.address), + ) { + peer_data.insert(pubkey, address); + } + } + + Ok(peer_data) + } + + pub fn save_mnemonic(&self, encrypted_mnemonic: String) -> Result<(), APIError> { + let now = crate::utils::get_current_timestamp() as i64; + + let mnemonic = DbMnemonicActMod { + id: ActiveValue::Set(1), + encrypted_mnemonic: ActiveValue::Set(encrypted_mnemonic), + created_at: ActiveValue::Set(now), + updated_at: ActiveValue::Set(now), + }; + + block_on( + MnemonicEntity::insert(mnemonic) + .on_conflict( + OnConflict::column(MnemonicColumn::Id) + .update_columns([ + MnemonicColumn::EncryptedMnemonic, + MnemonicColumn::UpdatedAt, + ]) + .to_owned(), + ) + .exec(self.get_connection()), + ) + .map_err(|e| std::io::Error::other(format!("Database write failed: {e}")))?; + + Ok(()) + } + + pub fn set_config(&self, key: &str, value: &str) -> Result<(), APIError> { + let now = crate::utils::get_current_timestamp() as i64; + + let config = ConfigActMod { + key: ActiveValue::Set(key.to_string()), + value: ActiveValue::Set(value.to_string()), + created_at: ActiveValue::Set(now), + updated_at: ActiveValue::Set(now), + }; + + block_on( + ConfigEntity::insert(config) + .on_conflict( + OnConflict::column(ConfigColumn::Key) + .update_columns([ConfigColumn::Value, ConfigColumn::UpdatedAt]) + .to_owned(), + ) + .exec(self.get_connection()), + ) + .map_err(|e| std::io::Error::other(format!("Database write failed: {e}")))?; + + Ok(()) + } +} diff --git a/src/disk.rs b/src/disk.rs index 6c6f104..b8e4033 100644 --- a/src/disk.rs +++ b/src/disk.rs @@ -1,39 +1,19 @@ -use bitcoin::secp256k1::PublicKey; use bitcoin::Network; use chrono::Utc; use lightning::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringDecayParameters}; -use lightning::util::hash_tables::new_hash_map; use lightning::util::logger::{Logger, Record}; -use lightning::util::ser::{Readable, ReadableArgs, Writer}; -use std::collections::HashMap; +use lightning::util::ser::{ReadableArgs, Writer}; use std::fs; use std::fs::File; -use std::io::{BufRead, BufReader}; -use std::net::SocketAddr; +use std::io::BufReader; use std::path::{Path, PathBuf}; use std::sync::Arc; -use crate::error::APIError; -use crate::ldk::{ - ChannelIdsMap, InboundPaymentInfoStorage, NetworkGraph, OutboundPaymentInfoStorage, - OutputSpenderTxes, SwapMap, -}; -use crate::utils::{parse_peer_info, LOGS_DIR}; +use crate::ldk::NetworkGraph; +use crate::utils::LOGS_DIR; pub(crate) const LDK_LOGS_FILE: &str = "logs.txt"; -pub(crate) const INBOUND_PAYMENTS_FNAME: &str = "inbound_payments"; -pub(crate) const OUTBOUND_PAYMENTS_FNAME: &str = "outbound_payments"; - -pub(crate) const CHANNEL_PEER_DATA: &str = "channel_peer_data"; - -pub(crate) const OUTPUT_SPENDER_TXES: &str = "output_spender_txes"; - -pub(crate) const CHANNEL_IDS_FNAME: &str = "channel_ids"; - -pub(crate) const MAKER_SWAPS_FNAME: &str = "maker_swaps"; -pub(crate) const TAKER_SWAPS_FNAME: &str = "taker_swaps"; - pub(crate) struct FilesystemLogger { data_dir: PathBuf, } @@ -73,76 +53,6 @@ impl Logger for FilesystemLogger { } } -pub(crate) fn persist_channel_peer( - path: &Path, - pubkey: &PublicKey, - address: &SocketAddr, -) -> Result<(), APIError> { - let pubkey = pubkey.to_string(); - let peer_info = if path.exists() { - let mut updated_peer_info = fs::read_to_string(path)? - .lines() - .filter(|&line| !line.trim().starts_with(&pubkey)) - .map(|line| line.trim()) - .collect::>() - .join("\n"); - updated_peer_info += format!( - "{}{pubkey}@{address}", - if updated_peer_info.is_empty() { - "" - } else { - "\n" - } - ) - .as_str(); - updated_peer_info - } else { - format!("{pubkey}@{address}") - }; - let mut tmp_path = path.to_path_buf(); - tmp_path.set_extension("ptmp"); - fs::write(&tmp_path, peer_info.to_string().as_bytes())?; - fs::rename(tmp_path, path)?; - tracing::info!("persisted peer (pubkey: {pubkey}, addr: {address})"); - Ok(()) -} - -pub(crate) fn delete_channel_peer(path: &Path, pubkey: String) -> Result<(), APIError> { - if path.exists() { - let updated_peer_info = fs::read_to_string(path)? - .lines() - .filter(|&line| !line.trim().starts_with(&pubkey)) - .map(|line| line.trim()) - .collect::>() - .join("\n"); - let mut tmp_path = path.to_path_buf(); - tmp_path.set_extension("dtmp"); - fs::write(&tmp_path, updated_peer_info.to_string().as_bytes())?; - fs::rename(tmp_path, path)?; - } - Ok(()) -} - -pub(crate) fn read_channel_peer_data( - path: &Path, -) -> Result, APIError> { - let mut peer_data = HashMap::new(); - if !path.exists() { - return Ok(HashMap::new()); - } - let file = File::open(path)?; - let reader = BufReader::new(file); - for line in reader.lines() { - match parse_peer_info(line.unwrap()) { - Ok((pubkey, socket_addr)) => { - peer_data.insert(pubkey, socket_addr.expect("saved info with address")); - } - Err(e) => return Err(e), - } - } - Ok(peer_data) -} - pub(crate) fn read_network( path: &Path, network: Network, @@ -156,48 +66,6 @@ pub(crate) fn read_network( NetworkGraph::new(network, logger) } -pub(crate) fn read_inbound_payment_info(path: &Path) -> InboundPaymentInfoStorage { - if let Ok(file) = File::open(path) { - if let Ok(info) = InboundPaymentInfoStorage::read(&mut BufReader::new(file)) { - return info; - } - } - InboundPaymentInfoStorage { - payments: new_hash_map(), - } -} - -pub(crate) fn read_outbound_payment_info(path: &Path) -> OutboundPaymentInfoStorage { - if let Ok(file) = File::open(path) { - if let Ok(info) = OutboundPaymentInfoStorage::read(&mut BufReader::new(file)) { - return info; - } - } - OutboundPaymentInfoStorage { - payments: new_hash_map(), - } -} - -pub(crate) fn read_output_spender_txes(path: &Path) -> OutputSpenderTxes { - if let Ok(file) = File::open(path) { - if let Ok(info) = OutputSpenderTxes::read(&mut BufReader::new(file)) { - return info; - } - } - new_hash_map() -} - -pub(crate) fn read_swaps_info(path: &Path) -> SwapMap { - if let Ok(file) = File::open(path) { - if let Ok(info) = SwapMap::read(&mut BufReader::new(file)) { - return info; - } - } - SwapMap { - swaps: new_hash_map(), - } -} - pub(crate) fn read_scorer( path: &Path, graph: Arc, @@ -212,14 +80,3 @@ pub(crate) fn read_scorer( } ProbabilisticScorer::new(params, graph, logger) } - -pub(crate) fn read_channel_ids_info(path: &Path) -> ChannelIdsMap { - if let Ok(file) = File::open(path) { - if let Ok(info) = ChannelIdsMap::read(&mut BufReader::new(file)) { - return info; - } - } - ChannelIdsMap { - channel_ids: new_hash_map(), - } -} diff --git a/src/error.rs b/src/error.rs index 52e0477..e809665 100644 --- a/src/error.rs +++ b/src/error.rs @@ -72,9 +72,6 @@ pub enum APIError { #[error("Failed to issue asset: {0}")] FailedIssuingAsset(String), - #[error("Unable to create keys seed file {0}: {1}")] - FailedKeysCreation(String, String), - #[error("Failed to open channel: {0}")] FailedOpenChannel(String), @@ -403,7 +400,6 @@ impl IntoResponse for APIError { APIError::FailedClosingChannel(_) | APIError::FailedInvoiceCreation(_) | APIError::FailedIssuingAsset(_) - | APIError::FailedKeysCreation(_, _) | APIError::FailedOpenChannel(_) | APIError::FailedPayment(_) | APIError::FailedPeerDisconnection(_) @@ -529,9 +525,6 @@ pub enum AppError { #[error("The provided authentication args are invalid")] InvalidAuthenticationArgs, - #[error("The revoked tokens file contains an invalid entry")] - InvalidRevokedTokensFile, - #[error("The provided root public key is invalid")] InvalidRootKey, diff --git a/src/kv_store.rs b/src/kv_store.rs new file mode 100644 index 0000000..f642777 --- /dev/null +++ b/src/kv_store.rs @@ -0,0 +1,208 @@ +use std::sync::Arc; + +use bitcoin::io; +use futures::executor::block_on; +use lightning::util::persist::KVStoreSync; +use sea_orm::sea_query::OnConflict; + +use crate::database::entities::{KvStoreActMod, KvStoreColumn, KvStoreEntity}; +use sea_orm::{ActiveValue, ColumnTrait, DatabaseConnection, EntityTrait, QueryFilter}; + +/// Sea-ORM based KVStore implementation for LDK persistence. +/// Uses block_on for sync context. +pub struct SeaOrmKvStore { + connection: Arc, +} + +impl SeaOrmKvStore { + /// Create a SeaOrmKvStore from an existing shared connection. + /// Does NOT run migrations (assumes they were already run). + pub fn from_connection(connection: Arc) -> Self { + tracing::info!("SeaOrmKvStore initialized from shared connection"); + Self { connection } + } + + fn get_connection(&self) -> &DatabaseConnection { + &self.connection + } +} + +impl KVStoreSync for SeaOrmKvStore { + fn read( + &self, + primary_namespace: &str, + secondary_namespace: &str, + key: &str, + ) -> Result, io::Error> { + tracing::trace!(primary_namespace, secondary_namespace, key, "KVStore read"); + + let result = block_on( + KvStoreEntity::find() + .filter(KvStoreColumn::PrimaryNamespace.eq(primary_namespace)) + .filter(KvStoreColumn::SecondaryNamespace.eq(secondary_namespace)) + .filter(KvStoreColumn::Key.eq(key)) + .one(self.get_connection()), + ) + .map_err(|e| { + tracing::error!( + primary_namespace, + secondary_namespace, + key, + error = %e, + "KVStore read failed" + ); + io::Error::new(io::ErrorKind::Other, format!("Database read failed: {e}")) + })?; + + match result { + Some(record) => { + tracing::trace!( + primary_namespace, + secondary_namespace, + key, + value_len = record.value.len(), + "KVStore read success" + ); + Ok(record.value) + } + None => { + tracing::trace!( + primary_namespace, + secondary_namespace, + key, + "KVStore key not found" + ); + Err(io::Error::new(io::ErrorKind::NotFound, "Key not found")) + } + } + } + + fn write( + &self, + primary_namespace: &str, + secondary_namespace: &str, + key: &str, + buf: Vec, + ) -> Result<(), io::Error> { + tracing::trace!( + primary_namespace, + secondary_namespace, + key, + value_len = buf.len(), + "KVStore write" + ); + + let model = KvStoreActMod { + primary_namespace: ActiveValue::Set(primary_namespace.to_string()), + secondary_namespace: ActiveValue::Set(secondary_namespace.to_string()), + key: ActiveValue::Set(key.to_string()), + value: ActiveValue::Set(buf), + }; + + // Use UPSERT (INSERT ... ON CONFLICT DO UPDATE) for atomic write + // This handles both insert and update in a single statement + block_on( + KvStoreEntity::insert(model) + .on_conflict( + OnConflict::columns([ + KvStoreColumn::PrimaryNamespace, + KvStoreColumn::SecondaryNamespace, + KvStoreColumn::Key, + ]) + .update_column(KvStoreColumn::Value) + .to_owned(), + ) + .exec(self.get_connection()), + ) + .map_err(|e| { + tracing::error!( + primary_namespace, + secondary_namespace, + key, + error = %e, + "KVStore write failed" + ); + io::Error::new(io::ErrorKind::Other, format!("Database write failed: {e}")) + })?; + + Ok(()) + } + + fn remove( + &self, + primary_namespace: &str, + secondary_namespace: &str, + key: &str, + lazy: bool, + ) -> Result<(), io::Error> { + tracing::trace!( + primary_namespace, + secondary_namespace, + key, + lazy, + "KVStore remove" + ); + + let result = block_on( + KvStoreEntity::delete_many() + .filter(KvStoreColumn::PrimaryNamespace.eq(primary_namespace)) + .filter(KvStoreColumn::SecondaryNamespace.eq(secondary_namespace)) + .filter(KvStoreColumn::Key.eq(key)) + .exec(self.get_connection()), + ) + .map_err(|e| { + tracing::error!( + primary_namespace, + secondary_namespace, + key, + error = %e, + "KVStore remove failed" + ); + io::Error::new(io::ErrorKind::Other, format!("Database delete failed: {e}")) + })?; + + tracing::trace!( + primary_namespace, + secondary_namespace, + key, + rows_affected = result.rows_affected, + "KVStore remove complete" + ); + + Ok(()) + } + + fn list( + &self, + primary_namespace: &str, + secondary_namespace: &str, + ) -> Result, io::Error> { + tracing::trace!(primary_namespace, secondary_namespace, "KVStore list"); + + let results = block_on( + KvStoreEntity::find() + .filter(KvStoreColumn::PrimaryNamespace.eq(primary_namespace)) + .filter(KvStoreColumn::SecondaryNamespace.eq(secondary_namespace)) + .all(self.get_connection()), + ) + .map_err(|e| { + tracing::error!( + primary_namespace, + secondary_namespace, + error = %e, + "KVStore list failed" + ); + io::Error::new(io::ErrorKind::Other, format!("Database list failed: {e}")) + })?; + + let keys: Vec = results.into_iter().map(|r| r.key).collect(); + tracing::trace!( + primary_namespace, + secondary_namespace, + count = keys.len(), + "KVStore list complete" + ); + + Ok(keys) + } +} diff --git a/src/ldk.rs b/src/ldk.rs index 32608d4..34aa6e4 100644 --- a/src/ldk.rs +++ b/src/ldk.rs @@ -1,3 +1,4 @@ +use crate::kv_store::SeaOrmKvStore; use amplify::{map, s}; use bitcoin::blockdata::locktime::absolute::LockTime; use bitcoin::psbt::{ExtractTxError, Psbt}; @@ -22,10 +23,9 @@ use lightning::onion_message::messenger::{ DefaultMessageRouter, OnionMessenger as LdkOnionMessenger, }; use lightning::rgb_utils::{ - get_rgb_channel_info_pending, is_channel_rgb, parse_rgb_payment_info, read_rgb_transfer_info, - update_rgb_channel_amount, BITCOIN_NETWORK_FNAME, INDEXER_URL_FNAME, STATIC_BLINDING, - WALLET_ACCOUNT_XPUB_COLORED_FNAME, WALLET_ACCOUNT_XPUB_VANILLA_FNAME, WALLET_FINGERPRINT_FNAME, - WALLET_MASTER_FINGERPRINT_FNAME, + get_rgb_channel_info_pending, is_channel_rgb, read_rgb_transfer_info, + update_rgb_channel_amount, RgbPaymentInfo, RGB_PAYMENT_INFO_INBOUND_NS, + RGB_PAYMENT_INFO_OUTBOUND_NS, RGB_PRIMARY_NS, STATIC_BLINDING, }; use lightning::routing::gossip; use lightning::routing::gossip::{NodeId, P2PGossipSync}; @@ -38,12 +38,14 @@ use lightning::sign::{ use lightning::types::payment::{PaymentHash, PaymentPreimage}; use lightning::util::config::UserConfig; use lightning::util::hash_tables::hash_map::Entry; -use lightning::util::hash_tables::HashMap as LdkHashMap; +use lightning::util::hash_tables::{new_hash_map, HashMap as LdkHashMap}; use lightning::util::persist::{ - KVStoreSync, MonitorUpdatingPersister, OUTPUT_SWEEPER_PERSISTENCE_KEY, - OUTPUT_SWEEPER_PERSISTENCE_PRIMARY_NAMESPACE, OUTPUT_SWEEPER_PERSISTENCE_SECONDARY_NAMESPACE, + KVStoreSync, KVStoreSyncWrapper, MonitorUpdatingPersister, CHANNEL_MANAGER_PERSISTENCE_KEY, + CHANNEL_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE, CHANNEL_MANAGER_PERSISTENCE_SECONDARY_NAMESPACE, + OUTPUT_SWEEPER_PERSISTENCE_KEY, OUTPUT_SWEEPER_PERSISTENCE_PRIMARY_NAMESPACE, + OUTPUT_SWEEPER_PERSISTENCE_SECONDARY_NAMESPACE, }; -use lightning::util::ser::{ReadableArgs, Writeable}; +use lightning::util::ser::{Readable, ReadableArgs, Writeable}; use lightning::util::sweep as ldk_sweep; use lightning::{chain, impl_writeable_tlv_based}; use lightning_background_processor::{process_events_async, GossipSync, NO_LIQUIDITY_MANAGER}; @@ -55,7 +57,6 @@ use lightning_block_sync::UnboundedCache; use lightning_dns_resolver::OMDomainResolver; use lightning_invoice::PaymentSecret; use lightning_net_tokio::SocketDescriptor; -use lightning_persister::fs_store::FilesystemStore; use rand::RngCore; use rgb_lib::{ bdk_wallet::keys::{bip39::Mnemonic, DerivableKey, ExtendedKey}, @@ -78,7 +79,6 @@ use std::collections::HashMap; use std::convert::TryInto; use std::fs; use std::hash::{DefaultHasher, Hash, Hasher}; -use std::io::BufReader; use std::net::ToSocketAddrs; use std::net::{SocketAddr, TcpListener}; use std::path::{Path, PathBuf}; @@ -92,10 +92,23 @@ use tokio::sync::watch::Sender; use tokio::task::JoinHandle; use crate::bitcoind::BitcoindClient; -use crate::disk::{ - self, FilesystemLogger, CHANNEL_IDS_FNAME, CHANNEL_PEER_DATA, INBOUND_PAYMENTS_FNAME, - MAKER_SWAPS_FNAME, OUTBOUND_PAYMENTS_FNAME, OUTPUT_SPENDER_TXES, TAKER_SWAPS_FNAME, -}; +use crate::database::RlnDatabase; +use crate::disk::{self, FilesystemLogger}; + +const INBOUND_PAYMENTS_KEY: &str = "inbound_payments"; +const OUTBOUND_PAYMENTS_KEY: &str = "outbound_payments"; +const CHANNEL_IDS_KEY: &str = "channel_ids"; +const MAKER_SWAPS_KEY: &str = "maker_swaps"; +const TAKER_SWAPS_KEY: &str = "taker_swaps"; +const OUTPUT_SPENDER_TXES_KEY: &str = "output_spender_txes"; +const PSBT_NAMESPACE: &str = "psbt"; +const CONFIG_INDEXER_URL: &str = "indexer_url"; +const CONFIG_BITCOIN_NETWORK: &str = "bitcoin_network"; +const CONFIG_WALLET_FINGERPRINT: &str = "wallet_fingerprint"; +const CONFIG_WALLET_ACCOUNT_XPUB_VANILLA: &str = "wallet_account_xpub_vanilla"; +const CONFIG_WALLET_ACCOUNT_XPUB_COLORED: &str = "wallet_account_xpub_colored"; +const CONFIG_WALLET_MASTER_FINGERPRINT: &str = "wallet_master_fingerprint"; + use crate::error::APIError; use crate::rgb::{check_rgb_proxy_endpoint, get_rgb_channel_info_optional, RgbLibWalletWrapper}; use crate::routes::{HTLCStatus, SwapStatus, UnlockRequest, DUST_LIMIT_MSAT}; @@ -111,6 +124,47 @@ pub(crate) const FEE_RATE: u64 = 7; pub(crate) const UTXO_SIZE_SAT: u32 = 32000; pub(crate) const MIN_CHANNEL_CONFIRMATIONS: u8 = 6; +/// Save config to database (source of truth) and sync to file for rust-lightning compatibility. +fn save_config_and_sync_file( + database: &sea_orm::DatabaseConnection, + storage_dir_path: &Path, + key: &str, + value: &str, +) -> Result<(), APIError> { + // Save to database (source of truth) + let db = RlnDatabase::new(database.clone()); + db.set_config(key, value)?; + + // Write to file for rust-lightning compatibility + fs::write(storage_dir_path.join(key), value).map_err(APIError::IO)?; + + Ok(()) +} + +/// Sync config from database to files on startup. +/// This ensures files are restored with DB as source of truth. +fn sync_config_to_files( + database: &sea_orm::DatabaseConnection, + storage_dir_path: &Path, +) -> Result<(), APIError> { + let db = RlnDatabase::new(database.clone()); + + for key in [ + CONFIG_INDEXER_URL, + CONFIG_BITCOIN_NETWORK, + CONFIG_WALLET_FINGERPRINT, + CONFIG_WALLET_ACCOUNT_XPUB_VANILLA, + CONFIG_WALLET_ACCOUNT_XPUB_COLORED, + CONFIG_WALLET_MASTER_FINGERPRINT, + ] { + if let Some(value) = db.get_config(key)? { + fs::write(storage_dir_path.join(key), &value).map_err(APIError::IO)?; + } + } + + Ok(()) +} + pub(crate) struct LdkBackgroundServices { stop_processing: Arc, peer_manager: Arc, @@ -221,14 +275,14 @@ impl UnlockedAppState { } fn save_maker_swaps(&self, swaps: MutexGuard) { - self.fs_store - .write("", "", MAKER_SWAPS_FNAME, swaps.encode()) + self.kv_store + .write("", "", MAKER_SWAPS_KEY, swaps.encode()) .unwrap(); } fn save_taker_swaps(&self, swaps: MutexGuard) { - self.fs_store - .write("", "", TAKER_SWAPS_FNAME, swaps.encode()) + self.kv_store + .write("", "", TAKER_SWAPS_KEY, swaps.encode()) .unwrap(); } @@ -292,14 +346,14 @@ impl UnlockedAppState { } fn save_inbound_payments(&self, inbound: MutexGuard) { - self.fs_store - .write("", "", INBOUND_PAYMENTS_FNAME, inbound.encode()) + self.kv_store + .write("", "", INBOUND_PAYMENTS_KEY, inbound.encode()) .unwrap(); } fn save_outbound_payments(&self, outbound: MutexGuard) { - self.fs_store - .write("", "", OUTBOUND_PAYMENTS_FNAME, outbound.encode()) + self.kv_store + .write("", "", OUTBOUND_PAYMENTS_KEY, outbound.encode()) .unwrap(); } @@ -397,8 +451,8 @@ impl UnlockedAppState { } fn save_channel_ids_map(&self, channel_ids: MutexGuard) { - self.fs_store - .write("", "", CHANNEL_IDS_FNAME, channel_ids.encode()) + self.kv_store + .write("", "", CHANNEL_IDS_KEY, channel_ids.encode()) .unwrap(); } } @@ -411,7 +465,7 @@ pub(crate) type ChainMonitor = chainmonitor::ChainMonitor< Arc, Arc< MonitorUpdatingPersister< - Arc, + Arc, Arc, Arc, Arc, @@ -480,7 +534,7 @@ pub(crate) struct RgbOutputSpender { static_state: Arc, rgb_wallet_wrapper: Arc, keys_manager: Arc, - fs_store: Arc, + kv_store: Arc, txes: Arc>, proxy_endpoint: String, } @@ -490,37 +544,96 @@ pub(crate) type OutputSweeper = ldk_sweep::OutputSweeper< Arc, Arc, Arc, - Arc, + KVStoreSyncWrapper>, Arc, Arc, >; -fn _update_rgb_channel_amount(ldk_data_dir: &Path, payment_hash: &PaymentHash, receiver: bool) { +fn _update_rgb_channel_amount( + payment_hash: &PaymentHash, + receiver: bool, + kv_store: &Arc, +) { let payment_hash_str = hex_str(&payment_hash.0); - for entry in fs::read_dir(ldk_data_dir).unwrap() { - let file = entry.unwrap(); - let file_name = file.file_name(); - let file_name_str = file_name.to_string_lossy(); - let mut file_path_no_ext = file.path().clone(); - file_path_no_ext.set_extension(""); - let file_name_str_no_ext = file_path_no_ext.file_name().unwrap().to_string_lossy(); - if file_name_str.contains(&payment_hash_str) && file_name_str_no_ext != payment_hash_str { - let rgb_payment_info = parse_rgb_payment_info(&file.path()); - let channel_id_str = file_name_str_no_ext.replace(&payment_hash_str, ""); - - if rgb_payment_info.swap_payment && receiver != rgb_payment_info.inbound { - continue; + tracing::info!( + "DEBUG: _update_rgb_channel_amount called for payment_hash={}, receiver={}", + payment_hash_str, + receiver + ); + + // Check both inbound and outbound namespaces + for inbound in [true, false] { + let namespace = if inbound { + RGB_PAYMENT_INFO_INBOUND_NS + } else { + RGB_PAYMENT_INFO_OUTBOUND_NS + }; + + // List all keys in the namespace + if let Ok(keys) = kv_store.list(RGB_PRIMARY_NS, namespace) { + tracing::info!( + "DEBUG: Listed {} keys in namespace {}", + keys.len(), + namespace + ); + for key in &keys { + tracing::info!("DEBUG: Checking key: {}", key); } + for key in keys { + // Keys that contain payment_hash but are not just the payment_hash + // are proxy keys in format: {channel_id}_{payment_hash} + if key.contains(&payment_hash_str) && key != payment_hash_str { + tracing::info!("DEBUG: Found matching proxy key: {}", key); + // Read the payment info from the proxy key + if let Ok(data) = kv_store.read(RGB_PRIMARY_NS, namespace, &key) { + let rgb_payment_info: RgbPaymentInfo = match serde_json::from_slice(&data) { + Ok(info) => info, + Err(e) => { + tracing::info!("DEBUG: Failed to parse payment info: {}", e); + continue; + } + }; + + // Extract channel_id from the key (format: {channel_id}_{payment_hash}) + let channel_id_str = key.replace(&format!("_{}", payment_hash_str), ""); + tracing::info!("DEBUG: Extracted channel_id: {}", channel_id_str); + + if rgb_payment_info.swap_payment && receiver != rgb_payment_info.inbound { + tracing::info!( + "DEBUG: Skipping due to swap_payment={}, receiver={}, inbound={}", + rgb_payment_info.swap_payment, + receiver, + rgb_payment_info.inbound + ); + continue; + } - let (offered, received) = if receiver { - (0, rgb_payment_info.amount) - } else { - (rgb_payment_info.amount, 0) - }; - update_rgb_channel_amount(&channel_id_str, offered, received, ldk_data_dir, false); - break; + let (offered, received) = if receiver { + (0, rgb_payment_info.amount) + } else { + (rgb_payment_info.amount, 0) + }; + tracing::info!("DEBUG: Calling update_rgb_channel_amount with channel_id={}, offered={}, received={}", + channel_id_str, offered, received); + update_rgb_channel_amount( + &channel_id_str, + offered, + received, + false, + kv_store.as_ref(), + ); + return; + } + } + } + } else { + tracing::info!("DEBUG: Failed to list keys in namespace {}", namespace); } } + tracing::info!( + "DEBUG: No matching payment info found for payment_hash={}", + payment_hash_str + ); } async fn handle_ldk_events( @@ -550,14 +663,12 @@ async fn handle_ldk_events( .expect("Lightning funding tx should always be to a SegWit output"); let script_buf = ScriptBuf::from_bytes(addr.to_scriptpubkey()); - let is_colored = is_channel_rgb( - &temporary_channel_id, - &PathBuf::from(&static_state.ldk_data_dir), - ); + let is_colored = + is_channel_rgb(&temporary_channel_id, unlocked_state.kv_store.as_ref()); let (unsigned_psbt, asset_id) = if is_colored { - let (rgb_info, _) = get_rgb_channel_info_pending( + let rgb_info = get_rgb_channel_info_pending( &temporary_channel_id, - &PathBuf::from(&static_state.ldk_data_dir), + unlocked_state.kv_store.as_ref(), ); let channel_rgb_amount: u64 = rgb_info.local_rgb_amount; @@ -604,10 +715,16 @@ async fn handle_ldk_events( let funding_txid = funding_tx.compute_txid().to_string(); tracing::info!("Funding TXID: {funding_txid}"); - let psbt_path = static_state - .ldk_data_dir - .join(format!("psbt_{funding_txid}")); - fs::write(psbt_path, psbt.to_string()).unwrap(); + // Store PSBT in database for later use when channel is funded + unlocked_state + .kv_store + .write( + PSBT_NAMESPACE, + "", + &funding_txid, + psbt.to_string().into_bytes(), + ) + .unwrap(); if let Some(asset_id) = asset_id { let unlocked_state_copy = unlocked_state.clone(); @@ -752,7 +869,9 @@ async fn handle_ldk_events( } } - _update_rgb_channel_amount(&static_state.ldk_data_dir, &payment_hash, true); + let kv_store_dyn: Arc = + Arc::clone(&unlocked_state.kv_store) as Arc; + _update_rgb_channel_amount(&payment_hash, true, &kv_store_dyn); if is_maker_swap { unlocked_state.update_maker_swap_status(&payment_hash, SwapStatus::Succeeded); } else { @@ -773,7 +892,13 @@ async fn handle_ldk_events( payment_id, .. } => { - _update_rgb_channel_amount(&static_state.ldk_data_dir, &payment_hash, false); + tracing::info!( + "DEBUG: PaymentSent event received for payment_hash={}", + payment_hash + ); + let kv_store_dyn: Arc = + Arc::clone(&unlocked_state.kv_store) as Arc; + _update_rgb_channel_amount(&payment_hash, false, &kv_store_dyn); if unlocked_state.is_maker_swap(&payment_hash) { tracing::info!( @@ -898,8 +1023,8 @@ async fn handle_ldk_events( &next_channel_id_str, outbound_amount_forwarded_rgb, 0, - &static_state.ldk_data_dir, false, + unlocked_state.kv_store.as_ref(), ); } if let Some(inbound_amount_forwarded_rgb) = inbound_amount_forwarded_rgb { @@ -907,8 +1032,8 @@ async fn handle_ldk_events( &prev_channel_id_str, 0, inbound_amount_forwarded_rgb, - &static_state.ldk_data_dir, false, + unlocked_state.kv_store.as_ref(), ); } @@ -1011,52 +1136,57 @@ async fn handle_ldk_events( unlocked_state.add_channel_id(former_temporary_channel_id.unwrap(), channel_id); let funding_txid = funding_txo.txid.to_string(); - let psbt_path = static_state - .ldk_data_dir - .join(format!("psbt_{funding_txid}")); - if psbt_path.exists() { - let psbt_str = fs::read_to_string(psbt_path).unwrap(); + // Check if we have a stored PSBT (initiator case) + match unlocked_state + .kv_store + .read(PSBT_NAMESPACE, "", &funding_txid) + { + Ok(psbt_bytes) => { + let psbt_str = String::from_utf8(psbt_bytes).unwrap(); - let state_copy = unlocked_state.clone(); - let psbt_str_copy = psbt_str.clone(); + let state_copy = unlocked_state.clone(); + let psbt_str_copy = psbt_str.clone(); - let is_chan_colored = - is_channel_rgb(&channel_id, &PathBuf::from(&static_state.ldk_data_dir)); - tracing::info!("Initiator of the channel (colored: {})", is_chan_colored); + let is_chan_colored = + is_channel_rgb(&channel_id, unlocked_state.kv_store.as_ref()); + tracing::info!("Initiator of the channel (colored: {})", is_chan_colored); - let _txid = tokio::task::spawn_blocking(move || { - if is_chan_colored { - state_copy.rgb_send_end(psbt_str_copy).map(|r| r.txid) - } else { - state_copy.rgb_send_btc_end(psbt_str_copy) - } - }) - .await - .unwrap() - .map_err(|e| { - tracing::error!("Error completing channel opening: {e:?}"); - ReplayEvent() - })?; + let _txid = tokio::task::spawn_blocking(move || { + if is_chan_colored { + state_copy.rgb_send_end(psbt_str_copy).map(|r| r.txid) + } else { + state_copy.rgb_send_btc_end(psbt_str_copy) + } + }) + .await + .unwrap() + .map_err(|e| { + tracing::error!("Error completing channel opening: {e:?}"); + ReplayEvent() + })?; - *unlocked_state.rgb_send_lock.lock().unwrap() = false; - } else { - // acceptor - let consignment_path = static_state - .ldk_data_dir - .join(format!("consignment_{funding_txid}")); - if !consignment_path.exists() { - // vanilla channel - return Ok(()); + *unlocked_state.rgb_send_lock.lock().unwrap() = false; } - let consignment = - RgbTransfer::load_file(consignment_path).expect("successful consignment load"); + Err(e) if e.kind() == io::ErrorKind::NotFound => { + // acceptor + let consignment_path = static_state + .ldk_data_dir + .join(format!("consignment_{funding_txid}")); + if !consignment_path.exists() { + // vanilla channel + return Ok(()); + } + let consignment = RgbTransfer::load_file(consignment_path) + .expect("successful consignment load"); - match unlocked_state.rgb_save_new_asset(consignment, funding_txid) { - Ok(_) => {} - Err(e) if e.to_string().contains("UNIQUE constraint failed") => {} - Err(e) => panic!("Failed saving asset: {e}"), + match unlocked_state.rgb_save_new_asset(consignment, funding_txid) { + Ok(_) => {} + Err(e) if e.to_string().contains("UNIQUE constraint failed") => {} + Err(e) => panic!("Failed saving asset: {e}"), + } } + Err(e) => panic!("Failed to read PSBT from KVStore: {e}"), } } Event::ChannelReady { @@ -1132,18 +1262,14 @@ async fn handle_ldk_events( } let get_rgb_info = |channel_id| { - get_rgb_channel_info_optional( - channel_id, - &PathBuf::from(&static_state.ldk_data_dir), - true, - ) - .map(|(rgb_info, _)| { - ( - rgb_info.contract_id, - rgb_info.local_rgb_amount, - rgb_info.remote_rgb_amount, - ) - }) + get_rgb_channel_info_optional(channel_id, true, unlocked_state.kv_store.as_ref()) + .map(|rgb_info| { + ( + rgb_info.contract_id, + rgb_info.local_rgb_amount, + rgb_info.remote_rgb_amount, + ) + }) }; let inbound_channel = unlocked_state @@ -1319,14 +1445,10 @@ impl OutputSpender for RgbOutputSpender { let txid = outpoint.txid; let txid_str = txid.to_string(); - let transfer_info_path = self - .static_state - .ldk_data_dir - .join(format!("{txid_str}_transfer_info")); - if !transfer_info_path.exists() { - continue; + let transfer_info = match read_rgb_transfer_info(self.kv_store.as_ref(), &txid_str) { + Ok(info) => info, + Err(_) => continue, // Not found in DB, skip }; - let transfer_info = read_rgb_transfer_info(&transfer_info_path); if transfer_info.rgb_amount == 0 { continue; } @@ -1489,8 +1611,8 @@ impl OutputSpender for RgbOutputSpender { } txes.insert(descriptors_hash, spending_tx.clone()); - self.fs_store - .write("", "", OUTPUT_SPENDER_TXES, txes.encode()) + self.kv_store + .write("", "", OUTPUT_SPENDER_TXES_KEY, txes.encode()) .unwrap(); Ok(spending_tx) @@ -1504,6 +1626,9 @@ pub(crate) async fn start_ldk( ) -> Result<(LdkBackgroundServices, Arc), APIError> { let static_state = &app_state.static_state; + // Sync config from database to files + sync_config_to_files(&static_state.database, &static_state.storage_dir_path)?; + let ldk_data_dir = static_state.ldk_data_dir.clone(); let ldk_data_dir_path = PathBuf::from(&ldk_data_dir); let logger = static_state.logger.clone(); @@ -1575,12 +1700,18 @@ pub(crate) async fn start_ldk( } }; let storage_dir_path = app_state.static_state.storage_dir_path.clone(); - fs::write(storage_dir_path.join(INDEXER_URL_FNAME), indexer_url).expect("able to write"); - fs::write( - storage_dir_path.join(BITCOIN_NETWORK_FNAME), - bitcoin_network.to_string(), - ) - .expect("able to write"); + save_config_and_sync_file( + &app_state.static_state.database, + &storage_dir_path, + CONFIG_INDEXER_URL, + indexer_url, + )?; + save_config_and_sync_file( + &app_state.static_state.database, + &storage_dir_path, + CONFIG_BITCOIN_NETWORK, + &bitcoin_network.to_string(), + )?; // Initialize the FeeEstimator // BitcoindClient implements the FeeEstimator trait, so it'll act as our fee estimator. @@ -1608,18 +1739,25 @@ pub(crate) async fn start_ldk( let cur = SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .unwrap(); + + // Initialize Persistence using shared database connection + let kv_store = Arc::new(SeaOrmKvStore::from_connection(Arc::clone( + &static_state.database, + ))); + + let kv_store_dyn: Arc = + Arc::clone(&kv_store) as Arc; let keys_manager = Arc::new(KeysManager::new( &ldk_seed, cur.as_secs(), cur.subsec_nanos(), true, ldk_data_dir_path.clone(), + kv_store_dyn.clone(), )); - // Initialize Persistence - let fs_store = Arc::new(FilesystemStore::new(ldk_data_dir.clone())); let persister = Arc::new(MonitorUpdatingPersister::new( - Arc::clone(&fs_store), + Arc::clone(&kv_store), Arc::clone(&logger), 1000, Arc::clone(&keys_manager), @@ -1687,52 +1825,64 @@ pub(crate) async fn start_ldk( user_config.manually_accept_inbound_channels = true; let mut restarting_node = true; let (channel_manager_blockhash, channel_manager) = { - if let Ok(f) = fs::File::open(ldk_data_dir.join("manager")) { - let mut channel_monitor_references = Vec::new(); - for (_, channel_monitor) in channelmonitors.iter() { - channel_monitor_references.push(channel_monitor); + match kv_store.read( + CHANNEL_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE, + CHANNEL_MANAGER_PERSISTENCE_SECONDARY_NAMESPACE, + CHANNEL_MANAGER_PERSISTENCE_KEY, + ) { + Ok(bytes) => { + let mut channel_monitor_references = Vec::new(); + for (_, channel_monitor) in channelmonitors.iter() { + channel_monitor_references.push(channel_monitor); + } + let read_args = ChannelManagerReadArgs::new( + keys_manager.clone(), + keys_manager.clone(), + keys_manager.clone(), + fee_estimator.clone(), + chain_monitor.clone(), + broadcaster.clone(), + router.clone(), + Arc::clone(&message_router), + logger.clone(), + user_config, + channel_monitor_references, + ldk_data_dir_path.clone(), + Arc::clone(&kv_store) as Arc, + ); + <(BlockHash, ChannelManager)>::read(&mut &bytes[..], read_args).unwrap() + } + Err(e) if e.kind() == io::ErrorKind::NotFound => { + // We're starting a fresh node. + restarting_node = false; + + let polled_best_block = polled_chain_tip.to_best_block(); + let polled_best_block_hash = polled_best_block.block_hash; + let chain_params = ChainParameters { + network, + best_block: polled_best_block, + }; + let fresh_channel_manager = channelmanager::ChannelManager::new( + fee_estimator.clone(), + chain_monitor.clone(), + broadcaster.clone(), + router.clone(), + Arc::clone(&message_router), + logger.clone(), + keys_manager.clone(), + keys_manager.clone(), + keys_manager.clone(), + user_config, + chain_params, + cur.as_secs() as u32, + ldk_data_dir_path.clone(), + Arc::clone(&kv_store) as Arc, + ); + (polled_best_block_hash, fresh_channel_manager) + } + Err(e) => { + panic!("Failed to read channel manager from KVStore: {e}"); } - let read_args = ChannelManagerReadArgs::new( - keys_manager.clone(), - keys_manager.clone(), - keys_manager.clone(), - fee_estimator.clone(), - chain_monitor.clone(), - broadcaster.clone(), - router.clone(), - Arc::clone(&message_router), - logger.clone(), - user_config, - channel_monitor_references, - ldk_data_dir_path.clone(), - ); - <(BlockHash, ChannelManager)>::read(&mut BufReader::new(f), read_args).unwrap() - } else { - // We're starting a fresh node. - restarting_node = false; - - let polled_best_block = polled_chain_tip.to_best_block(); - let polled_best_block_hash = polled_best_block.block_hash; - let chain_params = ChainParameters { - network, - best_block: polled_best_block, - }; - let fresh_channel_manager = channelmanager::ChannelManager::new( - fee_estimator.clone(), - chain_monitor.clone(), - broadcaster.clone(), - router.clone(), - Arc::clone(&message_router), - logger.clone(), - keys_manager.clone(), - keys_manager.clone(), - keys_manager.clone(), - user_config, - chain_params, - cur.as_secs() as u32, - ldk_data_dir_path.clone(), - ); - (polled_best_block_hash, fresh_channel_manager) } }; @@ -1765,32 +1915,30 @@ pub(crate) async fn start_ldk( .await .unwrap(); let rgb_online = rgb_wallet.go_online(false, indexer_url.to_string())?; - fs::write( - static_state.storage_dir_path.join(WALLET_FINGERPRINT_FNAME), - account_xpub_colored.fingerprint().to_string(), - ) - .expect("able to write"); - fs::write( - static_state - .storage_dir_path - .join(WALLET_ACCOUNT_XPUB_COLORED_FNAME), - account_xpub_colored.to_string(), - ) - .expect("able to write"); - fs::write( - static_state - .storage_dir_path - .join(WALLET_ACCOUNT_XPUB_VANILLA_FNAME), - account_xpub_vanilla.to_string(), - ) - .expect("able to write"); - fs::write( - static_state - .storage_dir_path - .join(WALLET_MASTER_FINGERPRINT_FNAME), - master_fingerprint.to_string(), - ) - .expect("able to write"); + save_config_and_sync_file( + &static_state.database, + &static_state.storage_dir_path, + CONFIG_WALLET_FINGERPRINT, + &account_xpub_colored.fingerprint().to_string(), + )?; + save_config_and_sync_file( + &static_state.database, + &static_state.storage_dir_path, + CONFIG_WALLET_ACCOUNT_XPUB_COLORED, + &account_xpub_colored.to_string(), + )?; + save_config_and_sync_file( + &static_state.database, + &static_state.storage_dir_path, + CONFIG_WALLET_ACCOUNT_XPUB_VANILLA, + &account_xpub_vanilla.to_string(), + )?; + save_config_and_sync_file( + &static_state.database, + &static_state.storage_dir_path, + CONFIG_WALLET_MASTER_FINGERPRINT, + &master_fingerprint.to_string(), + )?; let rgb_wallet_wrapper = Arc::new(RgbLibWalletWrapper::new( Arc::new(Mutex::new(rgb_wallet)), @@ -1798,18 +1946,21 @@ pub(crate) async fn start_ldk( )); // Initialize the OutputSweeper. - let txes = Arc::new(Mutex::new(disk::read_output_spender_txes( - &ldk_data_dir.join(OUTPUT_SPENDER_TXES), - ))); + let txes: OutputSpenderTxes = match kv_store.read("", "", OUTPUT_SPENDER_TXES_KEY) { + Ok(bytes) => OutputSpenderTxes::read(&mut &bytes[..]).unwrap_or_else(|_| new_hash_map()), + Err(e) if e.kind() == io::ErrorKind::NotFound => new_hash_map(), + Err(e) => panic!("Failed to read output spender txes from KVStore: {e}"), + }; + let txes = Arc::new(Mutex::new(txes)); let rgb_output_spender = Arc::new(RgbOutputSpender { static_state: static_state.clone(), rgb_wallet_wrapper: rgb_wallet_wrapper.clone(), keys_manager: keys_manager.clone(), - fs_store: fs_store.clone(), + kv_store: kv_store.clone(), txes, proxy_endpoint: proxy_endpoint.to_string(), }); - let (sweeper_best_block, output_sweeper) = match fs_store.read( + let (sweeper_best_block, output_sweeper) = match kv_store.read( OUTPUT_SWEEPER_PERSISTENCE_PRIMARY_NAMESPACE, OUTPUT_SWEEPER_PERSISTENCE_SECONDARY_NAMESPACE, OUTPUT_SWEEPER_PERSISTENCE_KEY, @@ -1822,7 +1973,7 @@ pub(crate) async fn start_ldk( None, rgb_output_spender, rgb_wallet_wrapper.clone(), - fs_store.clone(), + KVStoreSyncWrapper(kv_store.clone()), logger.clone(), ); (channel_manager.current_best_block(), sweeper) @@ -1834,7 +1985,7 @@ pub(crate) async fn start_ldk( None, rgb_output_spender.clone(), rgb_wallet_wrapper.clone(), - fs_store.clone(), + KVStoreSyncWrapper(kv_store.clone()), logger.clone(), ); let mut reader = io::Cursor::new(&mut bytes); @@ -2029,12 +2180,31 @@ pub(crate) async fn start_ldk( } }); - let inbound_payments = Arc::new(Mutex::new(disk::read_inbound_payment_info( - &ldk_data_dir.join(INBOUND_PAYMENTS_FNAME), - ))); - let outbound_payments = Arc::new(Mutex::new(disk::read_outbound_payment_info( - &ldk_data_dir.join(OUTBOUND_PAYMENTS_FNAME), - ))); + // Read payment info from KVStore + let inbound_payments = Arc::new(Mutex::new({ + match kv_store.read("", "", INBOUND_PAYMENTS_KEY) { + Ok(bytes) => InboundPaymentInfoStorage::read(&mut &bytes[..]).unwrap_or_else(|_| { + InboundPaymentInfoStorage { + payments: new_hash_map(), + } + }), + Err(_) => InboundPaymentInfoStorage { + payments: new_hash_map(), + }, + } + })); + let outbound_payments = Arc::new(Mutex::new({ + match kv_store.read("", "", OUTBOUND_PAYMENTS_KEY) { + Ok(bytes) => OutboundPaymentInfoStorage::read(&mut &bytes[..]).unwrap_or_else(|_| { + OutboundPaymentInfoStorage { + payments: new_hash_map(), + } + }), + Err(_) => OutboundPaymentInfoStorage { + payments: new_hash_map(), + }, + } + })); let bump_tx_event_handler = Arc::new(BumpTransactionEventHandler::new( Arc::clone(&broadcaster), @@ -2044,20 +2214,41 @@ pub(crate) async fn start_ldk( )); // Persist ChannelManager and NetworkGraph - let persister = Arc::new(FilesystemStore::new(ldk_data_dir_path.clone())); - - // Read swaps info - let maker_swaps = Arc::new(Mutex::new(disk::read_swaps_info( - &ldk_data_dir.join(MAKER_SWAPS_FNAME), - ))); - let taker_swaps = Arc::new(Mutex::new(disk::read_swaps_info( - &ldk_data_dir.join(TAKER_SWAPS_FNAME), - ))); - - // Read channel IDs info - let channel_ids_map = Arc::new(Mutex::new(disk::read_channel_ids_info( - &ldk_data_dir.join(CHANNEL_IDS_FNAME), - ))); + let persister = KVStoreSyncWrapper(Arc::clone(&kv_store)); + + // Read swaps info from KVStore + let maker_swaps = Arc::new(Mutex::new({ + match kv_store.read("", "", MAKER_SWAPS_KEY) { + Ok(bytes) => SwapMap::read(&mut &bytes[..]).unwrap_or_else(|_| SwapMap { + swaps: new_hash_map(), + }), + Err(_) => SwapMap { + swaps: new_hash_map(), + }, + } + })); + let taker_swaps = Arc::new(Mutex::new({ + match kv_store.read("", "", TAKER_SWAPS_KEY) { + Ok(bytes) => SwapMap::read(&mut &bytes[..]).unwrap_or_else(|_| SwapMap { + swaps: new_hash_map(), + }), + Err(_) => SwapMap { + swaps: new_hash_map(), + }, + } + })); + + // Read channel IDs info from KVStore + let channel_ids_map = Arc::new(Mutex::new({ + match kv_store.read("", "", CHANNEL_IDS_KEY) { + Ok(bytes) => ChannelIdsMap::read(&mut &bytes[..]).unwrap_or_else(|_| ChannelIdsMap { + channel_ids: new_hash_map(), + }), + Err(_) => ChannelIdsMap { + channel_ids: new_hash_map(), + }, + } + })); let unlocked_state = Arc::new(UnlockedAppState { channel_manager: Arc::clone(&channel_manager), @@ -2068,7 +2259,7 @@ pub(crate) async fn start_ldk( onion_messenger: onion_messenger.clone(), outbound_payments, peer_manager: Arc::clone(&peer_manager), - fs_store: Arc::clone(&fs_store), + kv_store: Arc::clone(&kv_store), bump_tx_event_handler, rgb_wallet_wrapper, maker_swaps, @@ -2137,14 +2328,15 @@ pub(crate) async fn start_ldk( // Regularly reconnect to channel peers. let connect_cm = Arc::clone(&channel_manager); let connect_pm = Arc::clone(&peer_manager); - let peer_data_path = ldk_data_dir.join(CHANNEL_PEER_DATA); + let connect_db = Arc::clone(&static_state.database); let stop_connect = Arc::clone(&stop_processing); tokio::spawn(async move { let mut interval = tokio::time::interval(Duration::from_secs(1)); interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); loop { interval.tick().await; - match disk::read_channel_peer_data(&peer_data_path) { + let db = RlnDatabase::new((*connect_db).clone()); + match db.read_channel_peer_data() { Ok(info) => { for node_id in connect_cm .list_channels() @@ -2165,7 +2357,7 @@ pub(crate) async fn start_ldk( } } Err(e) => tracing::error!( - "ERROR: errored reading channel peer info from disk: {:?}", + "ERROR: errored reading channel peer info from database: {:?}", e ), } diff --git a/src/main.rs b/src/main.rs index 60dc428..af15579 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,8 +2,10 @@ mod args; mod auth; mod backup; mod bitcoind; +mod database; mod disk; mod error; +mod kv_store; mod ldk; mod rgb; mod routes; diff --git a/src/rgb.rs b/src/rgb.rs index 3400487..801edf9 100644 --- a/src/rgb.rs +++ b/src/rgb.rs @@ -7,11 +7,10 @@ use bitcoin::{Address, Network, OutPoint, Transaction, TxOut, WPubkeyHash}; use hex::DisplayHex; use lightning::events::bump_transaction::{Utxo, WalletSource}; use lightning::ln::types::ChannelId; -use lightning::rgb_utils::{ - get_rgb_channel_info_path, is_channel_rgb, parse_rgb_channel_info, RgbInfo, -}; +use lightning::rgb_utils::{read_rgb_channel_info, RgbInfo}; use lightning::sign::ChangeDestinationSource; use lightning::util::async_poll::AsyncResult; +use lightning::util::persist::KVStoreSync; use rgb_lib::{ bdk_wallet::SignOptions, bitcoin::psbt::Psbt as BitcoinPsbt, @@ -735,14 +734,9 @@ pub(crate) async fn check_rgb_proxy_endpoint(proxy_endpoint: &str) -> Result<(), pub(crate) fn get_rgb_channel_info_optional( channel_id: &ChannelId, - ldk_data_dir: &Path, pending: bool, -) -> Option<(RgbInfo, PathBuf)> { - if !is_channel_rgb(channel_id, ldk_data_dir) { - return None; - } - let info_file_path = - get_rgb_channel_info_path(&channel_id.0.as_hex().to_string(), ldk_data_dir, pending); - let rgb_info = parse_rgb_channel_info(&info_file_path); - Some((rgb_info, info_file_path)) + kv_store: &dyn KVStoreSync, +) -> Option { + let channel_id_str = channel_id.0.as_hex().to_string(); + read_rgb_channel_info(kv_store, &channel_id_str, pending).ok() } diff --git a/src/routes.rs b/src/routes.rs index 4d2c007..a250847 100644 --- a/src/routes.rs +++ b/src/routes.rs @@ -14,13 +14,13 @@ use lightning::ln::{channelmanager::OptionalOfferPaymentParams, types::ChannelId use lightning::offers::offer::{self, Offer}; use lightning::onion_message::messenger::Destination; use lightning::rgb_utils::{ - get_rgb_channel_info_path, get_rgb_payment_info_path, parse_rgb_channel_info, - parse_rgb_payment_info, STATIC_BLINDING, + read_rgb_channel_info, read_rgb_payment_info, write_rgb_channel_info, STATIC_BLINDING, }; use lightning::routing::gossip::RoutingFees; use lightning::routing::router::{Path as LnPath, Route, RouteHint, RouteHintHop}; use lightning::sign::EntropySource; use lightning::util::config::ChannelConfig; +use lightning::util::persist::KVStoreSync; use lightning::{chain::channelmonitor::Balance, impl_writeable_tlv_based_enum}; use lightning::{ ln::channel_state::ChannelShutdownState, onion_message::messenger::MessageSendInstructions, @@ -32,7 +32,7 @@ use lightning::{ }; use lightning::{ ln::channelmanager::{PaymentId, RecipientOnionFields, Retry}, - rgb_utils::{write_rgb_channel_info, write_rgb_payment_info_file, RgbInfo}, + rgb_utils::{write_rgb_payment_info_file, RgbInfo}, routing::{ gossip::NodeId, router::{PaymentParameters, RouteParameters}, @@ -61,12 +61,7 @@ use rgb_lib::{ }; use serde::{Deserialize, Serialize}; use std::{ - collections::HashMap, - net::ToSocketAddrs, - path::{Path, PathBuf}, - str::FromStr, - sync::Arc, - time::Duration, + collections::HashMap, net::ToSocketAddrs, path::Path, str::FromStr, sync::Arc, time::Duration, }; use tokio::{ fs::File, @@ -78,7 +73,7 @@ use crate::ldk::{start_ldk, stop_ldk, LdkBackgroundServices, MIN_CHANNEL_CONFIRM use crate::swap::{SwapData, SwapInfo, SwapString}; use crate::utils::{ check_already_initialized, check_channel_id, check_password_strength, check_password_validity, - encrypt_and_save_mnemonic, get_max_local_rgb_amount, get_mnemonic_path, get_route, hex_str, + encrypt_and_save_mnemonic, get_max_local_rgb_amount, get_route, hex_str, hex_str_to_compressed_pubkey, hex_str_to_vec, UnlockedAppState, UserOnionMessageContents, }; use crate::{ @@ -86,7 +81,6 @@ use crate::{ rgb::{check_rgb_proxy_endpoint, get_rgb_channel_info_optional}, }; use crate::{ - disk::{self, CHANNEL_PEER_DATA}, error::APIError, ldk::{PaymentInfo, FEE_RATE, UTXO_SIZE_SAT}, utils::{ @@ -1296,15 +1290,14 @@ pub(crate) async fn asset_balance( let mut offchain_outbound = 0; let mut offchain_inbound = 0; for chan_info in unlocked_state.channel_manager.list_channels() { - let info_file_path = get_rgb_channel_info_path( - &chan_info.channel_id.0.as_hex().to_string(), - &state.static_state.ldk_data_dir, - false, - ); - if !info_file_path.exists() { - continue; - } - let rgb_info = parse_rgb_channel_info(&info_file_path); + let channel_id_str = chan_info.channel_id.0.as_hex().to_string(); + + let rgb_info = + match read_rgb_channel_info(unlocked_state.kv_store.as_ref(), &channel_id_str, false) { + Ok(info) => info, + Err(_) => continue, + }; + if rgb_info.contract_id == contract_id { offchain_outbound += rgb_info.local_rgb_amount; offchain_inbound += rgb_info.remote_rgb_amount; @@ -1355,8 +1348,7 @@ pub(crate) async fn backup( no_cancel(async move { let _guard = state.check_locked().await?; - let _mnemonic = - check_password_validity(&payload.password, &state.static_state.storage_dir_path)?; + let _mnemonic = check_password_validity(&payload.password, &state.static_state.database)?; do_backup( &state.static_state.storage_dir_path, @@ -1403,12 +1395,12 @@ pub(crate) async fn change_password( check_password_strength(payload.new_password.clone())?; let mnemonic = - check_password_validity(&payload.old_password, &state.static_state.storage_dir_path)?; + check_password_validity(&payload.old_password, &state.static_state.database)?; encrypt_and_save_mnemonic( payload.new_password, mnemonic.to_string(), - &get_mnemonic_path(&state.static_state.storage_dir_path), + &state.static_state.database, )?; Ok(Json(EmptyResponse {})) @@ -1524,11 +1516,8 @@ pub(crate) async fn connect_peer( if let Some(peer_addr) = peer_addr { connect_peer_if_necessary(peer_pubkey, peer_addr, unlocked_state.peer_manager.clone()) .await?; - disk::persist_channel_peer( - &state.static_state.ldk_data_dir.join(CHANNEL_PEER_DATA), - &peer_pubkey, - &peer_addr, - )?; + let db = state.get_db(); + db.persist_channel_peer(&peer_pubkey, &peer_addr)?; } else { return Err(APIError::InvalidPeerInfo(s!( "incorrectly formatted peer info. Should be formatted as: `pubkey@host:port`" @@ -1629,10 +1618,8 @@ pub(crate) async fn disconnect_peer( } } - disk::delete_channel_peer( - &state.static_state.ldk_data_dir.join(CHANNEL_PEER_DATA), - payload.peer_pubkey, - )?; + let db = state.get_db(); + db.delete_channel_peer(&payload.peer_pubkey)?; //check the pubkey matches a valid connected peer if unlocked_state @@ -1730,82 +1717,6 @@ pub(crate) async fn get_channel_id( Ok(Json(GetChannelIdResponse { channel_id })) } -pub(crate) async fn get_payment( - State(state): State>, - WithRejection(Json(payload), _): WithRejection, APIError>, -) -> Result, APIError> { - let guard = state.check_unlocked().await?; - let unlocked_state = guard.as_ref().unwrap(); - - let payment_hash_vec = hex_str_to_vec(&payload.payment_hash); - if payment_hash_vec.is_none() || payment_hash_vec.as_ref().unwrap().len() != 32 { - return Err(APIError::InvalidPaymentHash(payload.payment_hash)); - } - let requested_ph = PaymentHash(payment_hash_vec.unwrap().try_into().unwrap()); - - let inbound_payments = unlocked_state.inbound_payments(); - let outbound_payments = unlocked_state.outbound_payments(); - - for (payment_hash, payment_info) in &inbound_payments { - if payment_hash == &requested_ph { - let rgb_payment_info_path_inbound = - get_rgb_payment_info_path(payment_hash, &state.static_state.ldk_data_dir, true); - - let (asset_amount, asset_id) = if rgb_payment_info_path_inbound.exists() { - let info = parse_rgb_payment_info(&rgb_payment_info_path_inbound); - (Some(info.amount), Some(info.contract_id.to_string())) - } else { - (None, None) - }; - - return Ok(Json(GetPaymentResponse { - payment: Payment { - amt_msat: payment_info.amt_msat, - asset_amount, - asset_id, - payment_hash: hex_str(&payment_hash.0), - inbound: true, - status: payment_info.status, - created_at: payment_info.created_at, - updated_at: payment_info.updated_at, - payee_pubkey: payment_info.payee_pubkey.to_string(), - }, - })); - } - } - - for (payment_id, payment_info) in &outbound_payments { - let payment_hash = &PaymentHash(payment_id.0); - if payment_hash == &requested_ph { - let rgb_payment_info_path_outbound = - get_rgb_payment_info_path(payment_hash, &state.static_state.ldk_data_dir, false); - - let (asset_amount, asset_id) = if rgb_payment_info_path_outbound.exists() { - let info = parse_rgb_payment_info(&rgb_payment_info_path_outbound); - (Some(info.amount), Some(info.contract_id.to_string())) - } else { - (None, None) - }; - - return Ok(Json(GetPaymentResponse { - payment: Payment { - amt_msat: payment_info.amt_msat, - asset_amount, - asset_id, - payment_hash: hex_str(&payment_hash.0), - inbound: false, - status: payment_info.status, - created_at: payment_info.created_at, - updated_at: payment_info.updated_at, - payee_pubkey: payment_info.payee_pubkey.to_string(), - }, - })); - } - } - - Err(APIError::PaymentNotFound(payload.payment_hash)) -} - pub(crate) async fn get_swap( State(state): State>, WithRejection(Json(payload), _): WithRejection, APIError>, @@ -1877,14 +1788,17 @@ pub(crate) async fn init( check_password_strength(payload.password.clone())?; - let mnemonic_path = get_mnemonic_path(&state.static_state.storage_dir_path); - check_already_initialized(&mnemonic_path)?; + check_already_initialized(&state.static_state.database)?; let keys = generate_keys(state.static_state.network); let mnemonic = keys.mnemonic; - encrypt_and_save_mnemonic(payload.password, mnemonic.clone(), &mnemonic_path)?; + encrypt_and_save_mnemonic( + payload.password, + mnemonic.clone(), + &state.static_state.database, + )?; Ok(Json(InitResponse { mnemonic })) }) @@ -2078,12 +1992,12 @@ pub(crate) async fn keysend( )?; if let Some((contract_id, rgb_amount)) = rgb_payment { write_rgb_payment_info_file( - &PathBuf::from(&state.static_state.ldk_data_dir), &payment_hash, contract_id, rgb_amount, false, false, + &(Arc::clone(&unlocked_state.kv_store) as Arc), ); } @@ -2135,15 +2049,14 @@ pub(crate) async fn list_assets( let mut offchain_balances = HashMap::new(); for chan_info in unlocked_state.channel_manager.list_channels() { - let info_file_path = get_rgb_channel_info_path( - &chan_info.channel_id.0.as_hex().to_string(), - &state.static_state.ldk_data_dir, - false, - ); - if !info_file_path.exists() { - continue; - } - let rgb_info = parse_rgb_channel_info(&info_file_path); + let channel_id_str = chan_info.channel_id.0.as_hex().to_string(); + + let rgb_info = + match read_rgb_channel_info(unlocked_state.kv_store.as_ref(), &channel_id_str, false) { + Ok(info) => info, + Err(_) => continue, + }; + offchain_balances .entry(rgb_info.contract_id.to_string()) .and_modify(|(offchain_outbound, offchain_inbound)| { @@ -2258,17 +2171,15 @@ pub(crate) async fn list_channels( channel.short_channel_id = Some(id); } - let info_file_path = get_rgb_channel_info_path( - &chan_info.channel_id.0.as_hex().to_string(), - &state.static_state.ldk_data_dir, - false, - ); - if info_file_path.exists() { - let rgb_info = parse_rgb_channel_info(&info_file_path); + // Read RGB channel info from KVStore + let channel_id_str = chan_info.channel_id.0.as_hex().to_string(); + if let Ok(rgb_info) = + read_rgb_channel_info(unlocked_state.kv_store.as_ref(), &channel_id_str, false) + { channel.asset_id = Some(rgb_info.contract_id.to_string()); channel.asset_local_amount = Some(rgb_info.local_rgb_amount); channel.asset_remote_amount = Some(rgb_info.remote_rgb_amount); - }; + } channels.push(channel); } @@ -2287,15 +2198,11 @@ pub(crate) async fn list_payments( let mut payments = vec![]; for (payment_hash, payment_info) in &inbound_payments { - let rgb_payment_info_path_inbound = - get_rgb_payment_info_path(payment_hash, &state.static_state.ldk_data_dir, true); - - let (asset_amount, asset_id) = if rgb_payment_info_path_inbound.exists() { - let info = parse_rgb_payment_info(&rgb_payment_info_path_inbound); - (Some(info.amount), Some(info.contract_id.to_string())) - } else { - (None, None) - }; + let (asset_amount, asset_id) = + match read_rgb_payment_info(unlocked_state.kv_store.as_ref(), payment_hash, true) { + Ok(info) => (Some(info.amount), Some(info.contract_id.to_string())), + Err(_) => (None, None), + }; payments.push(Payment { amt_msat: payment_info.amt_msat, @@ -2313,15 +2220,11 @@ pub(crate) async fn list_payments( for (payment_id, payment_info) in &outbound_payments { let payment_hash = &PaymentHash(payment_id.0); - let rgb_payment_info_path_outbound = - get_rgb_payment_info_path(payment_hash, &state.static_state.ldk_data_dir, false); - - let (asset_amount, asset_id) = if rgb_payment_info_path_outbound.exists() { - let info = parse_rgb_payment_info(&rgb_payment_info_path_outbound); - (Some(info.amount), Some(info.contract_id.to_string())) - } else { - (None, None) - }; + let (asset_amount, asset_id) = + match read_rgb_payment_info(unlocked_state.kv_store.as_ref(), payment_hash, false) { + Ok(info) => (Some(info.amount), Some(info.contract_id.to_string())), + Err(_) => (None, None), + }; payments.push(Payment { amt_msat: payment_info.amt_msat, @@ -2339,6 +2242,74 @@ pub(crate) async fn list_payments( Ok(Json(ListPaymentsResponse { payments })) } +pub(crate) async fn get_payment( + State(state): State>, + WithRejection(Json(payload), _): WithRejection, APIError>, +) -> Result, APIError> { + let guard = state.check_unlocked().await?; + let unlocked_state = guard.as_ref().unwrap(); + + let payment_hash_vec = hex_str_to_vec(&payload.payment_hash); + if payment_hash_vec.is_none() || payment_hash_vec.as_ref().unwrap().len() != 32 { + return Err(APIError::InvalidPaymentHash(payload.payment_hash)); + } + let requested_ph = PaymentHash(payment_hash_vec.unwrap().try_into().unwrap()); + + let inbound_payments = unlocked_state.inbound_payments(); + let outbound_payments = unlocked_state.outbound_payments(); + + for (payment_hash, payment_info) in &inbound_payments { + if payment_hash == &requested_ph { + let (asset_amount, asset_id) = + read_rgb_payment_info(unlocked_state.kv_store.as_ref(), payment_hash, true) + .ok() + .map(|info| (Some(info.amount), Some(info.contract_id.to_string()))) + .unwrap_or((None, None)); + + return Ok(Json(GetPaymentResponse { + payment: Payment { + amt_msat: payment_info.amt_msat, + asset_amount, + asset_id, + payment_hash: hex_str(&payment_hash.0), + inbound: true, + status: payment_info.status, + created_at: payment_info.created_at, + updated_at: payment_info.updated_at, + payee_pubkey: payment_info.payee_pubkey.to_string(), + }, + })); + } + } + + for (payment_id, payment_info) in &outbound_payments { + let payment_hash = &PaymentHash(payment_id.0); + if payment_hash == &requested_ph { + let (asset_amount, asset_id) = + read_rgb_payment_info(unlocked_state.kv_store.as_ref(), payment_hash, false) + .ok() + .map(|info| (Some(info.amount), Some(info.contract_id.to_string()))) + .unwrap_or((None, None)); + + return Ok(Json(GetPaymentResponse { + payment: Payment { + amt_msat: payment_info.amt_msat, + asset_amount, + asset_id, + payment_hash: hex_str(&payment_hash.0), + inbound: false, + status: payment_info.status, + created_at: payment_info.created_at, + updated_at: payment_info.updated_at, + payee_pubkey: payment_info.payee_pubkey.to_string(), + }, + })); + } + } + + Err(APIError::PaymentNotFound(payload.payment_hash)) +} + pub(crate) async fn list_peers( State(state): State>, ) -> Result, APIError> { @@ -2642,13 +2613,11 @@ pub(crate) async fn maker_execute( .filter(|details| { match get_rgb_channel_info_optional( &details.channel_id, - &state.static_state.ldk_data_dir, false, + unlocked_state.kv_store.as_ref(), ) { _ if swap_info.is_from_btc() => true, - Some((rgb_info, _)) if Some(rgb_info.contract_id) == swap_info.from_asset => { - true - } + Some(rgb_info) if Some(rgb_info.contract_id) == swap_info.from_asset => true, _ => false, } }) @@ -2776,12 +2745,12 @@ pub(crate) async fn maker_execute( if swap_info.is_to_asset() { write_rgb_payment_info_file( - &state.static_state.ldk_data_dir, &swapstring.payment_hash, swap_info.to_asset.unwrap(), swap_info.qty_to, true, false, + &(Arc::clone(&unlocked_state.kv_store) as Arc), ); } @@ -2868,8 +2837,8 @@ pub(crate) async fn maker_init( if let Some(to_asset) = to_asset { let max_balance = get_max_local_rgb_amount( to_asset, - &state.static_state.ldk_data_dir, unlocked_state.channel_manager.list_channels().iter(), + unlocked_state.kv_store.as_ref(), ); if swap_info.qty_to > max_balance { return Err(APIError::InsufficientAssets); @@ -3042,7 +3011,7 @@ pub(crate) async fn open_channel( let (peer_pubkey, mut peer_addr) = parse_peer_info(payload.peer_pubkey_and_opt_addr.to_string())?; - let peer_data_path = state.static_state.ldk_data_dir.join(CHANNEL_PEER_DATA); + let db = state.get_db(); if peer_addr.is_none() { if let Some(peer) = unlocked_state.peer_manager.peer_by_node_id(&peer_pubkey) { if let Some(socket_address) = peer.socket_address { @@ -3054,7 +3023,7 @@ pub(crate) async fn open_channel( } } if peer_addr.is_none() { - let peer_info = disk::read_channel_peer_data(&peer_data_path)?; + let peer_info = db.read_channel_peer_data()?; for (pubkey, addr) in peer_info.into_iter() { if pubkey == peer_pubkey { peer_addr = Some(addr); @@ -3065,7 +3034,7 @@ pub(crate) async fn open_channel( if let Some(peer_addr) = peer_addr { connect_peer_if_necessary(peer_pubkey, peer_addr, unlocked_state.peer_manager.clone()) .await?; - disk::persist_channel_peer(&peer_data_path, &peer_pubkey, &peer_addr)?; + db.persist_channel_peer(&peer_pubkey, &peer_addr)?; } else { return Err(APIError::InvalidPeerInfo(s!( "cannot find the address for the provided pubkey" @@ -3198,21 +3167,18 @@ pub(crate) async fn open_channel( local_rgb_amount: *asset_amount, remote_rgb_amount: 0, }; - write_rgb_channel_info( - &get_rgb_channel_info_path( - &temporary_channel_id, - &state.static_state.ldk_data_dir, - true, - ), + // Write to KVStore + let _ = write_rgb_channel_info( + unlocked_state.kv_store.as_ref(), + &temporary_channel_id, &rgb_info, + true, ); - write_rgb_channel_info( - &get_rgb_channel_info_path( - &temporary_channel_id, - &state.static_state.ldk_data_dir, - false, - ), + let _ = write_rgb_channel_info( + unlocked_state.kv_store.as_ref(), + &temporary_channel_id, &rgb_info, + false, ); } @@ -3298,8 +3264,7 @@ pub(crate) async fn restore( no_cancel(async move { let _unlocked_state = state.check_locked().await?; - let mnemonic_path = get_mnemonic_path(&state.static_state.storage_dir_path); - check_already_initialized(&mnemonic_path)?; + check_already_initialized(&state.static_state.database)?; restore_backup( Path::new(&payload.backup_path), @@ -3307,8 +3272,7 @@ pub(crate) async fn restore( &state.static_state.storage_dir_path, )?; - let _mnemonic = - check_password_validity(&payload.password, &state.static_state.storage_dir_path)?; + let _mnemonic = check_password_validity(&payload.password, &state.static_state.database)?; Ok(Json(EmptyResponse {})) }) @@ -3584,12 +3548,12 @@ pub(crate) async fn send_payment( let payment_hash = PaymentHash(invoice.payment_hash().to_byte_array()); if let Some((contract_id, rgb_amount)) = rgb_payment { write_rgb_payment_info_file( - &PathBuf::from(&state.static_state.ldk_data_dir), &payment_hash, contract_id, rgb_amount, false, false, + &(Arc::clone(&unlocked_state.kv_store) as Arc), ); } @@ -3729,8 +3693,8 @@ pub(crate) async fn taker( if let Some(from_asset) = swapstring.swap_info.from_asset { let max_balance = get_max_local_rgb_amount( from_asset, - &state.static_state.ldk_data_dir, unlocked_state.channel_manager.list_channels().iter(), + unlocked_state.kv_store.as_ref(), ); if swapstring.swap_info.qty_from > max_balance { return Err(APIError::InsufficientAssets); @@ -3764,16 +3728,14 @@ pub(crate) async fn unlock( } } - let mnemonic = match check_password_validity( - &payload.password, - &state.static_state.storage_dir_path, - ) { - Ok(mnemonic) => mnemonic, - Err(e) => { - state.update_changing_state(false); - return Err(e); - } - }; + let mnemonic = + match check_password_validity(&payload.password, &state.static_state.database) { + Ok(mnemonic) => mnemonic, + Err(e) => { + state.update_changing_state(false); + return Err(e); + } + }; tracing::debug!("Starting LDK..."); let (new_ldk_background_services, new_unlocked_app_state) = diff --git a/src/test/authentication.rs b/src/test/authentication.rs index e4f7a73..fcac56c 100644 --- a/src/test/authentication.rs +++ b/src/test/authentication.rs @@ -194,6 +194,46 @@ async fn authentication() { .unwrap(); assert_eq!(res.status(), reqwest::StatusCode::UNAUTHORIZED); + // revoked token remains rejected after node restart (DB persistence check) + let res = reqwest::Client::new() + .post(format!("http://{node_address}/shutdown")) + .bearer_auth(&admin_token) + .send() + .await + .unwrap(); + _check_response_is_ok(res).await; + let t_0 = OffsetDateTime::now_utc(); + loop { + tokio::time::sleep(std::time::Duration::from_secs(1)).await; + if TcpListener::bind(node_address).await.is_ok() { + break; + } + if (OffsetDateTime::now_utc() - t_0).as_seconds_f32() > 10.0 { + panic!("node socket not becoming available") + } + } + let node_address = start_daemon(&test_dir_node1, NODE1_PEER_PORT, Some(root_public_key)).await; + let payload = unlock_req(password); + let res = reqwest::Client::new() + .post(format!("http://{node_address}/unlock")) + .json(&payload) + .bearer_auth(&admin_token) + .send() + .await + .unwrap(); + _check_response_is_ok(res) + .await + .json::() + .await + .unwrap(); + let res = reqwest::Client::new() + .get(format!("http://{node_address}/nodeinfo")) + .bearer_auth(&user_token) + .send() + .await + .unwrap(); + assert_eq!(res.status(), reqwest::StatusCode::UNAUTHORIZED); + // with no token no API can be called let res = reqwest::Client::new() .get(format!("http://{node_address}/nodeinfo")) diff --git a/src/test/mod.rs b/src/test/mod.rs index 83acf31..6c05b9b 100644 --- a/src/test/mod.rs +++ b/src/test/mod.rs @@ -1178,8 +1178,8 @@ async fn open_channel_raw( && c.asset_id == asset_id.map(|id| id.to_string()) && c.asset_local_amount == asset_amount }) { - if let Some(txid) = &channel.funding_txid { - let txout = _get_txout(txid); + if let Some(funding_txid) = &channel.funding_txid { + let txout = _get_txout(funding_txid); if !txout.is_empty() { mine_n_blocks(false, 6); channel_id = Some(channel.channel_id.clone()); diff --git a/src/utils.rs b/src/utils.rs index c214f08..02dd23f 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,6 +1,9 @@ +use crate::database::RlnDatabase; +use crate::kv_store::SeaOrmKvStore; use amplify::s; use bitcoin::io; use bitcoin::secp256k1::PublicKey; +use futures::executor::block_on; use futures::Future; use lightning::ln::channel_state::ChannelDetails; use lightning::ln::types::ChannelId; @@ -11,15 +14,16 @@ use lightning::routing::router::{ use lightning::{ onion_message::packet::OnionMessageContents, sign::KeysManager, + util::persist::KVStoreSync, util::ser::{Writeable, Writer}, }; -use lightning_persister::fs_store::FilesystemStore; use magic_crypt::{new_magic_crypt, MagicCryptTrait}; use rgb_lib::{bdk_wallet::keys::bip39::Mnemonic, BitcoinNetwork, ContractId}; +use rln_migration::{Migrator, MigratorTrait}; +use sea_orm::{ConnectOptions, Database, DatabaseConnection}; use std::{ collections::HashSet, fmt::Write, - fs, net::{SocketAddr, TcpStream, ToSocketAddrs}, path::Path, path::PathBuf, @@ -66,6 +70,10 @@ pub(crate) struct AppState { } impl AppState { + pub(crate) fn get_db(&self) -> RlnDatabase { + RlnDatabase::new((*self.static_state.database).clone()) + } + pub(crate) fn get_changing_state(&self) -> MutexGuard<'_, bool> { self.changing_state.lock().unwrap() } @@ -90,6 +98,8 @@ pub(crate) struct StaticState { pub(crate) ldk_data_dir: PathBuf, pub(crate) logger: Arc, pub(crate) max_media_upload_size_mb: u16, + /// Shared database connection for mnemonic storage and LDK KVStore + pub(crate) database: Arc, } pub(crate) struct UnlockedAppState { @@ -101,7 +111,7 @@ pub(crate) struct UnlockedAppState { pub(crate) onion_messenger: Arc, pub(crate) outbound_payments: Arc>, pub(crate) peer_manager: Arc, - pub(crate) fs_store: Arc, + pub(crate) kv_store: Arc, pub(crate) bump_tx_event_handler: Arc, pub(crate) maker_swaps: Arc>, pub(crate) taker_swaps: Arc>, @@ -156,8 +166,9 @@ impl Writeable for UserOnionMessageContents { } } -pub(crate) fn check_already_initialized(mnemonic_path: &Path) -> Result<(), APIError> { - if mnemonic_path.exists() { +pub(crate) fn check_already_initialized(database: &DatabaseConnection) -> Result<(), APIError> { + let db = crate::database::RlnDatabase::new(database.clone()); + if db.mnemonic_exists()? { return Err(APIError::AlreadyInitialized); } Ok(()) @@ -174,13 +185,13 @@ pub(crate) fn check_password_strength(password: String) -> Result<(), APIError> pub(crate) fn check_password_validity( password: &str, - storage_dir_path: &Path, + database: &DatabaseConnection, ) -> Result { - let mnemonic_path = get_mnemonic_path(storage_dir_path); - if let Ok(encrypted_mnemonic) = fs::read_to_string(mnemonic_path) { + let db = crate::database::RlnDatabase::new(database.clone()); + if let Some(mnemonic_record) = db.get_mnemonic()? { let mcrypt = new_magic_crypt!(password, 256); let mnemonic_str = mcrypt - .decrypt_base64_to_string(encrypted_mnemonic) + .decrypt_base64_to_string(mnemonic_record.encrypted_mnemonic) .map_err(|_| APIError::WrongPassword)?; Ok(Mnemonic::from_str(&mnemonic_str).expect("valid mnemonic")) } else { @@ -206,27 +217,21 @@ pub(crate) fn check_port_is_available(port: u16) -> Result<(), AppError> { Ok(()) } -pub(crate) fn get_mnemonic_path(storage_dir_path: &Path) -> PathBuf { - storage_dir_path.join("mnemonic") +pub(crate) fn get_db_path(storage_dir_path: &Path) -> PathBuf { + storage_dir_path.join("rln_db") } pub(crate) fn encrypt_and_save_mnemonic( password: String, mnemonic: String, - mnemonic_path: &Path, + database: &DatabaseConnection, ) -> Result<(), APIError> { let mcrypt = new_magic_crypt!(password, 256); let encrypted_mnemonic = mcrypt.encrypt_str_to_base64(mnemonic); - match fs::write(mnemonic_path, encrypted_mnemonic) { - Ok(()) => { - tracing::info!("Created a new wallet"); - Ok(()) - } - Err(e) => Err(APIError::FailedKeysCreation( - mnemonic_path.to_string_lossy().to_string(), - e.to_string(), - )), - } + let db = crate::database::RlnDatabase::new(database.clone()); + db.save_mnemonic(encrypted_mnemonic)?; + tracing::info!("Saved wallet mnemonic"); + Ok(()) } pub(crate) async fn connect_peer_if_necessary( @@ -350,6 +355,28 @@ pub(crate) async fn start_daemon(args: &UserArgs) -> Result, AppEr let ldk_data_dir = args.storage_dir_path.join(LDK_DIR); let logger = Arc::new(FilesystemLogger::new(ldk_data_dir.clone())); + // Initialize the shared database connection + let db_path = get_db_path(&args.storage_dir_path); + let connection_string = format!("sqlite:{}?mode=rwc", db_path.display()); + let mut opt = ConnectOptions::new(connection_string); + // Use single connection to avoid deadlocks + opt.max_connections(1) + .min_connections(0) + .connect_timeout(Duration::from_secs(8)) + .idle_timeout(Duration::from_secs(8)) + .max_lifetime(Duration::from_secs(8)); + + let database = block_on(Database::connect(opt)).map_err(|e| { + AppError::IO(std::io::Error::other(format!( + "Database connection failed: {e}" + ))) + })?; + + block_on(Migrator::up(&database, None)) + .map_err(|e| AppError::IO(std::io::Error::other(format!("Migration failed: {e}"))))?; + + tracing::info!(db_path = %db_path.display(), "Shared database initialized"); + let cancel_token = CancellationToken::new(); let static_state = Arc::new(StaticState { @@ -359,6 +386,7 @@ pub(crate) async fn start_daemon(args: &UserArgs) -> Result, AppEr ldk_data_dir, logger, max_media_upload_size_mb: args.max_media_upload_size_mb, + database: Arc::new(database), }); let app_state = Arc::new(AppState { @@ -389,13 +417,13 @@ pub(crate) fn get_current_timestamp() -> u64 { pub(crate) fn get_max_local_rgb_amount<'r>( contract_id: ContractId, - ldk_data_dir_path: &Path, channels: impl Iterator, + kv_store: &dyn KVStoreSync, ) -> u64 { let mut max_balance = 0; for chan_info in channels { - if let Some((rgb_info, _)) = - get_rgb_channel_info_optional(&chan_info.channel_id, ldk_data_dir_path, false) + if let Some(rgb_info) = + get_rgb_channel_info_optional(&chan_info.channel_id, false, kv_store) { if rgb_info.contract_id == contract_id && rgb_info.local_rgb_amount > max_balance { max_balance = rgb_info.local_rgb_amount;