diff --git a/.github/workflows/android-bindgen.yml b/.github/workflows/android-bindgen.yml index 6282c053..98afa30c 100644 --- a/.github/workflows/android-bindgen.yml +++ b/.github/workflows/android-bindgen.yml @@ -60,7 +60,7 @@ jobs: android-bindgen: name: Android Bindgen runs-on: ubuntu-latest - timeout-minutes: 60 + timeout-minutes: 90 steps: - name: Checkout diff --git a/AGENTS.md b/AGENTS.md index a69ac772..7577cf8d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,7 +20,7 @@ Android bindings are built and published by `.github/workflows/gradle-publish.ym ```bash cargo test # All tests -cargo test modules:: # Single module (scanner, lnurl, onchain, activity, blocktank, boltz, trezor, jade, hardware_wallet, ur, pubky, paykit_route, usdt) +cargo test modules:: # Single module (scanner, lnurl, onchain, activity, blocktank, boltz, trezor, jade, hardware_wallet, ur, pubky, paykit_route, pubky_swaps, usdt) ``` ## Lint & Format @@ -35,7 +35,7 @@ Android bindings use ktlint via Gradle plugin (`org.jlleitschuh.gradle.ktlint`), ## Architecture - `src/lib.rs` — UniFFI exports and module re-exports -- `src/modules/`: core modules: scanner, lnurl, onchain, activity, blocktank, boltz, trezor, jade, hardware_wallet, ur, pubky, paykit_route, usdt +- `src/modules/`: core modules: scanner, lnurl, onchain, activity, blocktank, boltz, trezor, jade, hardware_wallet, ur, pubky, paykit_route, pubky_swaps, usdt - `bindings/` — Platform-specific binding outputs (ios/, android/, python/) - `build.sh`, `build_ios.sh`, `build_android.sh`, `build_python.sh` — Build scripts diff --git a/Cargo.lock b/Cargo.lock index 037b74d0..3eb8b6dc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -101,7 +101,7 @@ dependencies = [ "fixed-cache", "foldhash 0.2.0", "hashbrown 0.17.1", - "indexmap 2.13.0", + "indexmap 2.14.2", "itoa", "k256", "keccak-asm", @@ -149,7 +149,7 @@ dependencies = [ "alloy-sol-macro-input", "const-hex", "heck", - "indexmap 2.13.0", + "indexmap 2.14.2", "proc-macro-error3", "proc-macro2", "quote", @@ -278,6 +278,15 @@ version = "1.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" +[[package]] +name = "arc-swap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "380962b3d93b99642e50b9febf72c071e97e8b32d86eae9cf4ef582bb960ae6e" +dependencies = [ + "rustversion", +] + [[package]] name = "argon2" version = "0.5.3" @@ -631,6 +640,17 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "async_io_stream" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d7b9decdf35d8908a7e3ef02f64c5e9b1695e230154c0e8de3969142d9b94c" +dependencies = [ + "futures", + "pharos", + "rustc_version 0.4.1", +] + [[package]] name = "atomic-polyfill" version = "1.0.3" @@ -646,6 +666,18 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" +[[package]] +name = "attohttpc" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16e2cdb6d5ed835199484bb92bb8b3edd526effe995c61732580439c1a67e2e9" +dependencies = [ + "base64 0.22.1", + "http", + "log", + "url", +] + [[package]] name = "auto_impl" version = "1.3.0" @@ -686,12 +718,29 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "backon" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cffb0e931875b666fc4fcb20fee52e9bbd1ef836fd9e9e04ec21555f9f85f7ef" +dependencies = [ + "fastrand", + "gloo-timers", + "tokio", +] + [[package]] name = "base16ct" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" +[[package]] +name = "base16ct" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" + [[package]] name = "base32" version = "0.5.1" @@ -726,6 +775,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "base64ct" version = "1.8.3" @@ -809,7 +864,7 @@ dependencies = [ "rand_core 0.6.4", "ripemd", "secp256k1 0.27.0", - "sha2", + "sha2 0.10.9", "subtle", "zeroize", ] @@ -888,7 +943,7 @@ dependencies = [ "secp256k1 0.30.0", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "zeroize", ] @@ -986,7 +1041,7 @@ dependencies = [ [[package]] name = "bitkitcore" -version = "0.8.0-rc13" +version = "0.8.0-swaps.11" dependencies = [ "aes-gcm", "alloy-primitives", @@ -1002,9 +1057,12 @@ dependencies = [ "boltz-client", "btleplug", "chrono", + "ed25519-dalek 2.2.0", + "electrum-client 0.25.0", "hex", + "iroh", "jade-client-rs", - "jni", + "jni 0.19.0", "lazy-regex", "lightning-invoice 0.32.0", "lnurl-rs", @@ -1020,13 +1078,14 @@ dependencies = [ "r2d2_sqlite", "rand 0.8.5", "regex", - "reqwest", + "reqwest 0.12.28", "rusqlite", "rust-blocktank-client", "rust_decimal", "serde", "serde_json", "serial_test", + "swap-common", "tempfile", "test-case", "thiserror 2.0.18", @@ -1107,7 +1166,16 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" dependencies = [ - "objc2", + "objc2 0.5.2", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2 0.6.5", ] [[package]] @@ -1161,7 +1229,7 @@ dependencies = [ "lightning", "lightning-invoice 0.34.1", "log", - "reqwest", + "reqwest 0.12.28", "secp256k1 0.32.0-beta.2", "serde", "serde_json", @@ -1212,7 +1280,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" dependencies = [ - "sha2", + "sha2 0.10.9", "tinyvec", ] @@ -1228,20 +1296,20 @@ dependencies = [ "dashmap 6.1.0", "dbus", "futures", - "jni", + "jni 0.19.0", "jni-utils", "log", - "objc2", + "objc2 0.5.2", "objc2-core-bluetooth", - "objc2-foundation", + "objc2-foundation 0.2.2", "once_cell", "static_assertions", "thiserror 2.0.18", "tokio", "tokio-stream", "uuid", - "windows", - "windows-future", + "windows 0.61.3", + "windows-future 0.2.1", ] [[package]] @@ -1360,9 +1428,20 @@ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "cfg_aliases" -version = "0.2.1" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] [[package]] name = "chacha20" @@ -1375,6 +1454,19 @@ dependencies = [ "rand_core 0.10.0", ] +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20 0.9.1", + "cipher", + "poly1305", + "zeroize", +] + [[package]] name = "chrono" version = "0.4.44" @@ -1475,6 +1567,12 @@ dependencies = [ "cc", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "cobs" version = "0.3.0" @@ -1518,6 +1616,12 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "const_format" version = "0.2.36" @@ -1731,6 +1835,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ "hybrid-array", + "rand_core 0.10.0", ] [[package]] @@ -1757,6 +1862,15 @@ dependencies = [ "cipher", ] +[[package]] +name = "ctutils" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2376ffd6f96d8a9db59875b4b6b0237d6900b5baf64279714e05493ce64828a" +dependencies = [ + "cmov", +] + [[package]] name = "curve25519-dalek" version = "4.1.3" @@ -1767,8 +1881,26 @@ dependencies = [ "cpufeatures 0.2.17", "curve25519-dalek-derive", "digest 0.10.7", - "fiat-crypto", + "fiat-crypto 0.2.9", + "rustc_version 0.4.1", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "curve25519-dalek-derive", + "digest 0.11.3", + "fiat-crypto 0.3.0", + "rand_core 0.10.0", "rustc_version 0.4.1", + "serde", "subtle", "zeroize", ] @@ -1813,9 +1945,29 @@ dependencies = [ [[package]] name = "data-encoding" -version = "2.11.0" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "data-encoding-macro" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6a127ecbb3c4632e1525380e04c0c3fcf8dcb44d32a79ea290d8a36906edcd8" +dependencies = [ + "data-encoding", + "data-encoding-macro-internal", +] + +[[package]] +name = "data-encoding-macro-internal" +version = "0.1.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8" +checksum = "c54e03a951783e8b327515db3f2a2fd0e3bed362a96b066f341ce66ed49b4ead" +dependencies = [ + "data-encoding", + "syn 3.0.6", +] [[package]] name = "dbus" @@ -1879,7 +2031,18 @@ version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ - "const-oid", + "const-oid 0.9.6", + "zeroize", +] + +[[package]] +name = "der" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" +dependencies = [ + "const-oid 0.10.2", + "pem-rfc7468", "zeroize", ] @@ -1949,7 +2112,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer 0.10.4", - "const-oid", + "const-oid 0.9.6", "crypto-common 0.1.7", "subtle", ] @@ -1964,6 +2127,18 @@ dependencies = [ "crypto-common 0.2.2", ] +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.11.0", + "block2 0.6.2", + "libc", + "objc2 0.6.5", +] + [[package]] name = "displaydoc" version = "0.2.5" @@ -1975,6 +2150,17 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "dlopen2" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e2c5bd4158e66d1e215c49b837e11d62f3267b30c92f1d171c4d3105e3dc4d4" +dependencies = [ + "libc", + "once_cell", + "winapi", +] + [[package]] name = "dnssec-prover" version = "0.6.8" @@ -2017,12 +2203,12 @@ version = "0.16.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" dependencies = [ - "der", + "der 0.7.10", "digest 0.10.7", "elliptic-curve", "rfc6979", - "signature", - "spki", + "signature 2.2.0", + "spki 0.7.3", ] [[package]] @@ -2031,9 +2217,20 @@ version = "2.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" dependencies = [ - "pkcs8", + "pkcs8 0.10.2", "serde", - "signature", + "signature 2.2.0", +] + +[[package]] +name = "ed25519" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a" +dependencies = [ + "pkcs8 0.11.0", + "serdect", + "signature 3.0.0", ] [[package]] @@ -2042,10 +2239,26 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" dependencies = [ - "curve25519-dalek", - "ed25519", + "curve25519-dalek 4.1.3", + "ed25519 2.2.3", + "serde", + "sha2 0.10.9", + "subtle", + "zeroize", +] + +[[package]] +name = "ed25519-dalek" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de" +dependencies = [ + "curve25519-dalek 5.0.0", + "ed25519 3.0.0", + "rand_core 0.10.0", "serde", - "sha2", + "sha2 0.11.1", + "signature 3.0.0", "subtle", "zeroize", ] @@ -2123,13 +2336,13 @@ version = "0.13.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" dependencies = [ - "base16ct", + "base16ct 0.2.0", "crypto-bigint", "digest 0.10.7", "ff", "generic-array", "group", - "pkcs8", + "pkcs8 0.10.2", "rand_core 0.6.4", "sec1", "subtle", @@ -2157,6 +2370,17 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" +[[package]] +name = "enum-assoc" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0590c4a94da3372e83493b956755a6e2266830b6e4e3b101afe66e3f39477b91" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "enum-ordinalize" version = "4.4.2" @@ -2223,7 +2447,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -2282,6 +2506,12 @@ version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" +[[package]] +name = "fiat-crypto" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" + [[package]] name = "find-msvc-tools" version = "0.1.9" @@ -2337,6 +2567,12 @@ dependencies = [ "spin 0.9.8", ] +[[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" @@ -2554,7 +2790,7 @@ dependencies = [ "libc", "log", "rustversion", - "windows-link 0.2.1", + "windows-link 0.1.3", "windows-result 0.4.1", ] @@ -2660,6 +2896,25 @@ dependencies = [ "subtle", ] +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap 2.14.2", + "slab", + "tokio", + "tokio-util", + "tracing", +] + [[package]] name = "half" version = "2.7.1" @@ -2713,12 +2968,6 @@ dependencies = [ "foldhash 0.1.5", ] -[[package]] -name = "hashbrown" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" - [[package]] name = "hashbrown" version = "0.17.1" @@ -2896,9 +3145,11 @@ dependencies = [ "bytes", "futures-channel", "futures-core", + "h2", "http", "http-body", "httparse", + "httpdate", "itoa", "pin-project-lite", "pin-utils", @@ -2922,7 +3173,7 @@ dependencies = [ "tokio", "tokio-rustls", "tower-service", - "webpki-roots 1.0.6", + "webpki-roots 1.0.11", ] [[package]] @@ -3075,6 +3326,12 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" +[[package]] +name = "identity-hash" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfdd7caa900436d8f13b2346fe10257e0c05c1f1f9e351f4f5d57c03bd5f45da" + [[package]] name = "idna" version = "1.1.0" @@ -3096,6 +3353,26 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "igd-next" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de7238d487a9aff61f81b5ab41c0a841532a115a398b5fa92a2fadd0885e2581" +dependencies = [ + "attohttpc", + "bytes", + "futures", + "http", + "http-body-util", + "hyper", + "hyper-util", + "log", + "rand 0.10.3", + "tokio", + "url", + "xmltree", +] + [[package]] name = "impl-codec" version = "0.6.0" @@ -3129,12 +3406,12 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.13.0" +version = "2.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", - "hashbrown 0.16.1", + "hashbrown 0.17.1", "serde", "serde_core", ] @@ -3168,6 +3445,19 @@ dependencies = [ "mach2", ] +[[package]] +name = "ipconfig" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d40460c0ce33d6ce4b0630ad68ff63d6661961c48b6dba35e5a4d81cfb48222" +dependencies = [ + "socket2", + "widestring", + "windows-registry", + "windows-result 0.4.1", + "windows-sys 0.61.2", +] + [[package]] name = "ipnet" version = "2.12.0" @@ -3185,34 +3475,198 @@ dependencies = [ ] [[package]] -name = "is_terminal_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" - -[[package]] -name = "itertools" -version = "0.10.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" -dependencies = [ - "either", -] - -[[package]] -name = "itertools" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" -dependencies = [ - "either", -] - -[[package]] -name = "itertools" -version = "0.14.0" +name = "iroh" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +checksum = "b2f8d1cfffc83efe39a1031aab423ce09cb8048071baba550508931e9a81ce46" +dependencies = [ + "backon", + "blake3", + "bytes", + "cfg_aliases", + "ctutils", + "data-encoding", + "derive_more", + "ed25519-dalek 3.0.0", + "futures-util", + "getrandom 0.4.2", + "http", + "ipnet", + "iroh-base", + "iroh-dns", + "iroh-metrics", + "iroh-relay", + "n0-error", + "n0-future", + "n0-watcher", + "netwatch", + "noq", + "noq-proto", + "noq-udp", + "papaya", + "pin-project", + "portable-atomic", + "portmapper", + "rand 0.10.3", + "reqwest 0.13.5", + "rustc-hash", + "rustls 0.23.46", + "rustls-pki-types", + "serde", + "smallvec", + "strum", + "time", + "tokio", + "tokio-stream", + "tokio-util", + "tracing", + "url", + "wasm-bindgen-futures", +] + +[[package]] +name = "iroh-base" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b72366b16001af3a51574233df88ca6d62da0215807549a769e7de887da803" +dependencies = [ + "curve25519-dalek 5.0.0", + "data-encoding", + "data-encoding-macro", + "derive_more", + "ed25519-dalek 3.0.0", + "getrandom 0.4.2", + "n0-error", + "rand 0.10.3", + "serde", + "url", + "zeroize", +] + +[[package]] +name = "iroh-dns" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7481d0792dde1035a2b06ec06ed3cf6d01fcb1a494e6931b489e32073382048d" +dependencies = [ + "arc-swap", + "cfg_aliases", + "derive_more", + "iroh-base", + "n0-dns-resolver", + "n0-error", + "n0-future", + "portable-atomic", + "rand 0.10.3", + "rustls 0.23.46", + "simple-dns 0.12.0", + "strum", + "tokio", + "tracing", + "url", +] + +[[package]] +name = "iroh-metrics" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ede55536349842337f7cdc63012ec33dc637945f3259c98a0763aac364cdf09" +dependencies = [ + "iroh-metrics-derive", + "itoa", + "n0-error", + "portable-atomic", + "ryu", + "serde", + "tracing", +] + +[[package]] +name = "iroh-metrics-derive" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ae5f0c4405d1fbc9fb16ff422ca40620e93dc36c30ecaba0c2aee3992b7bd48" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "iroh-relay" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e5589e7c1475700686603a970275687f760df853bc6525c7eb1347aa31d7230" +dependencies = [ + "blake3", + "bytes", + "cfg_aliases", + "data-encoding", + "derive_more", + "getrandom 0.4.2", + "http", + "http-body-util", + "hyper", + "hyper-util", + "iroh-base", + "iroh-dns", + "iroh-metrics", + "lru 0.18.5", + "n0-error", + "n0-future", + "noq", + "noq-proto", + "num_enum", + "percent-encoding", + "pin-project", + "postcard", + "rand 0.10.3", + "reqwest 0.13.5", + "rustls 0.23.46", + "rustls-pki-types", + "serde", + "serde_bytes", + "strum", + "tokio", + "tokio-rustls", + "tokio-util", + "tokio-websockets", + "tracing", + "url", + "webpki-roots 1.0.11", + "ws_stream_wasm", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" dependencies = [ "either", ] @@ -3235,7 +3689,7 @@ dependencies = [ "log", "minicbor", "rand 0.8.5", - "reqwest", + "reqwest 0.12.28", "serde", "serde_bytes", "serde_json", @@ -3296,18 +3750,83 @@ checksum = "c6df18c2e3db7e453d3c6ac5b3e9d5182664d28788126d39b91f2d1e22b017ec" dependencies = [ "cesu8", "combine", - "jni-sys", + "jni-sys 0.3.0", "log", "thiserror 1.0.69", "walkdir", ] +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys 0.3.0", + "log", + "thiserror 1.0.69", + "walkdir", + "windows-sys 0.45.0", +] + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.18", + "walkdir", + "windows-link 0.2.1", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version 0.4.1", + "simd_cesu8", + "syn 2.0.117", +] + [[package]] name = "jni-sys" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.117", +] + [[package]] name = "jni-utils" version = "0.1.1" @@ -3316,7 +3835,7 @@ checksum = "259e9f2c3ead61de911f147000660511f07ab00adeed1d84f5ac4d0386e7a6c4" dependencies = [ "dashmap 5.5.3", "futures", - "jni", + "jni 0.19.0", "log", "once_cell", "static_assertions", @@ -3353,7 +3872,7 @@ dependencies = [ "ecdsa", "elliptic-curve", "once_cell", - "sha2", + "sha2 0.10.9", ] [[package]] @@ -3591,7 +4110,7 @@ dependencies = [ "bitcoin 0.32.8", "cbc", "email_address", - "reqwest", + "reqwest 0.12.28", "serde", "serde_json", "ureq", @@ -3632,12 +4151,27 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "227748d55f2f0ab4735d87fd623798cb6b664512fe979705f829c9f81c934465" +[[package]] +name = "lru" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef9ac18847474e638e3702b76c65d4eb93428471a74778ef0f1be711717f89b5" +dependencies = [ + "hashbrown 0.17.1", +] + [[package]] name = "lru-slab" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" +[[package]] +name = "mac-addr" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3d25b0e0b648a86960ac23b7ad4abb9717601dec6f66c165f5b037f3f03065f" + [[package]] name = "mach2" version = "0.4.3" @@ -3667,11 +4201,11 @@ dependencies = [ "crc", "document-features", "dyn-clone", - "ed25519-dalek", + "ed25519-dalek 2.2.0", "flume", "futures-lite", "getrandom 0.2.17", - "lru", + "lru 0.13.0", "serde", "serde_bencode", "serde_bytes", @@ -3761,6 +4295,99 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" +[[package]] +name = "musig2" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "183312a1f782d0e27c2e9aa4d68c151301caa39b38f48ea125c1d55ab1ff29f0" +dependencies = [ + "base16ct 0.2.0", + "hmac", + "secp", + "secp256k1 0.31.1", + "sha2 0.10.9", + "subtle", +] + +[[package]] +name = "n0-dns-resolver" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "535c99c9a786bee714155d2ee4fc2477405c2c43536e1bc6a51de09a0d1448f7" +dependencies = [ + "derive_more", + "ipconfig", + "jni 0.22.4", + "lru 0.18.5", + "n0-error", + "n0-future", + "ndk-context", + "rand 0.10.3", + "reqwest 0.13.5", + "rustc-hash", + "rustls 0.23.46", + "simple-dns 0.12.0", + "system-configuration", + "tokio", + "tokio-rustls", + "tracing", + "webpki-roots 1.0.11", +] + +[[package]] +name = "n0-error" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26c59ea174675ce6bc196878851e5049e11b8b1f9af3ba87e4d6df8d828bb001" +dependencies = [ + "n0-error-macros", + "spez", +] + +[[package]] +name = "n0-error-macros" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4412346410d6616f3668c40e53c298e5320c7b856f7a960e5914e442601be79f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "n0-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2ab99dfb861450e68853d34ae665243a88b8c493d01ba957321a1e9b2312bbe" +dependencies = [ + "cfg_aliases", + "derive_more", + "futures-buffered", + "futures-lite", + "futures-util", + "js-sys", + "pin-project", + "send_wrapper", + "tokio", + "tokio-util", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-time", +] + +[[package]] +name = "n0-watcher" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64bf1ecb076a87e0e3f5edcf726e7d29e788c273bb0161ba30666b53f085906c" +dependencies = [ + "derive_more", + "n0-error", + "n0-future", + "slotmap", +] + [[package]] name = "native-tls" version = "0.2.18" @@ -3778,6 +4405,180 @@ dependencies = [ "tempfile", ] +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "netdev" +version = "0.45.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "096c44b66a9b09b99b4dd36b1c295ff3a492039ccecaf55466bd6ddcdba59968" +dependencies = [ + "block2 0.6.2", + "dispatch2", + "dlopen2", + "ipnet", + "jni 0.21.1", + "libc", + "mac-addr", + "ndk-context", + "netlink-packet-core 0.8.2", + "netlink-packet-route 0.31.0", + "netlink-sys 0.8.8", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-wlan", + "objc2-foundation 0.3.2", + "objc2-system-configuration", + "once_cell", + "plist", + "windows-sys 0.61.2", +] + +[[package]] +name = "netdev" +version = "0.46.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3c52c2584961c68f5a6e3356797344061f818c93b8acc9cd6d7e284795e563e" +dependencies = [ + "block2 0.6.2", + "dispatch2", + "dlopen2", + "ipnet", + "jni 0.21.1", + "libc", + "mac-addr", + "ndk-context", + "netlink-packet-core 0.9.0", + "netlink-packet-route 0.33.0", + "netlink-sys 0.9.0", + "objc2-core-foundation", + "objc2-system-configuration", + "once_cell", + "plist", + "windows-sys 0.61.2", +] + +[[package]] +name = "netlink-packet-core" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b897d7bd4f0af82e68d40d0344cf37e97f9c97ddf74a098de3e4da05e96ca395" +dependencies = [ + "paste", +] + +[[package]] +name = "netlink-packet-core" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6e2daf9a8c2e21302714706860a0e6be02e03d17294ecc66b354ea7d4059dd" + +[[package]] +name = "netlink-packet-route" +version = "0.31.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2288fcb784eb3defd5fb16f4c4160d5f477de192eac730f43e1d11c24d9a007" +dependencies = [ + "bitflags 2.11.0", + "libc", + "log", + "netlink-packet-core 0.8.2", +] + +[[package]] +name = "netlink-packet-route" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59d48ffc8b73a506e1ff0878528c72668f2bfbc3d875b6be890a96be5d0d5576" +dependencies = [ + "bitflags 2.11.0", + "libc", + "log", + "netlink-packet-core 0.9.0", + "zerocopy", +] + +[[package]] +name = "netlink-proto" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93af8261786086024cd5e96e0a991dd65ced07bbf7c233a487bbc96b971d5539" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "log", + "netlink-packet-core 0.8.2", + "netlink-sys 0.8.8", + "thiserror 2.0.18", +] + +[[package]] +name = "netlink-sys" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd6c30ed10fa69cc491d491b85cc971f6bdeb8e7367b7cde2ee6cc878d583fae" +dependencies = [ + "bytes", + "futures-util", + "libc", + "log", + "tokio", +] + +[[package]] +name = "netlink-sys" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c99d38e00b420df49e940fe0826e667c3dad82ac68eb4c2bbf754c1c14a83a10" +dependencies = [ + "bytes", + "libc", + "log", +] + +[[package]] +name = "netwatch" +version = "0.19.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39da9cad5f23aa43401f09497d3b280e51b5feba115d9ffbf38ca35d6ff95e96" +dependencies = [ + "atomic-waker", + "bytes", + "cfg_aliases", + "derive_more", + "ipnet", + "js-sys", + "libc", + "n0-error", + "n0-future", + "n0-watcher", + "netdev 0.45.1", + "netdev 0.46.3", + "netlink-packet-core 0.8.2", + "netlink-packet-route 0.31.0", + "netlink-proto", + "netlink-sys 0.8.8", + "noq-udp", + "objc2-core-foundation", + "objc2-system-configuration", + "pin-project-lite", + "serde", + "socket2", + "time", + "tokio", + "tokio-util", + "tracing", + "web-sys", + "windows 0.62.2", + "windows-result 0.4.1", + "wmi", +] + [[package]] name = "nix" version = "0.26.4" @@ -3799,6 +4600,68 @@ dependencies = [ "minimal-lexical", ] +[[package]] +name = "noq" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6249a065adc1edbc1704a95436f38dd60476064dbc3b7c47cf279e02d1590eb5" +dependencies = [ + "bytes", + "cfg_aliases", + "derive_more", + "noq-proto", + "noq-udp", + "pin-project-lite", + "rustc-hash", + "rustls 0.23.46", + "socket2", + "thiserror 2.0.18", + "tokio", + "tokio-stream", + "tracing", + "web-time", +] + +[[package]] +name = "noq-proto" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c01a35be3ed37558c8db69554419f24eff8a63599b54f711bbe3863ec727c47d" +dependencies = [ + "aes-gcm", + "bytes", + "derive_more", + "enum-assoc", + "getrandom 0.4.2", + "identity-hash", + "lru-slab", + "rand 0.10.3", + "rand_pcg", + "ring", + "rustc-hash", + "rustls 0.23.46", + "rustls-pki-types", + "slab", + "sorted-index-buffer", + "thiserror 2.0.18", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "noq-udp" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d0160422832eea1cc11c34be04ee6d5a046452b0b46cfb14695d55a1f24c954" +dependencies = [ + "cfg_aliases", + "libc", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + [[package]] name = "ntimestamp" version = "1.0.0" @@ -3820,7 +4683,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -3852,10 +4715,32 @@ dependencies = [ name = "num-traits" version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" dependencies = [ - "autocfg", - "libm", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.117", ] [[package]] @@ -3874,6 +4759,15 @@ dependencies = [ "objc2-encode", ] +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", +] + [[package]] name = "objc2-core-bluetooth" version = "0.2.2" @@ -3881,8 +4775,35 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a644b62ffb826a5277f536cf0f701493de420b13d40e700c452c36567771111" dependencies = [ "bitflags 2.11.0", - "objc2", - "objc2-foundation", + "objc2 0.5.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.11.0", + "block2 0.6.2", + "dispatch2", + "libc", + "objc2 0.6.5", +] + +[[package]] +name = "objc2-core-wlan" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c71e34919aba0d701380d911702455038a8a3587467fe0141d6a71501e7ffe48" +dependencies = [ + "bitflags 2.11.0", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-security", + "objc2-security-foundation", ] [[package]] @@ -3898,9 +4819,57 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" dependencies = [ "bitflags 2.11.0", - "block2", + "block2 0.5.1", + "libc", + "objc2 0.5.2", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.11.0", + "block2 0.6.2", + "libc", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-security" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe137109bd1e8b5a99390f77a7d8b2961dafc1a1c5db8f2e60329ad6d895a" +dependencies = [ + "bitflags 2.11.0", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-security-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef76382e9cedd18123099f17638715cc3d81dba3637d4c0d39ab69df2ef345a5" +dependencies = [ + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-system-configuration" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7216bd11cbda54ccabcab84d523dc93b858ec75ecfb3a7d89513fa22464da396" +dependencies = [ + "bitflags 2.11.0", + "dispatch2", "libc", - "objc2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-security", ] [[package]] @@ -3985,6 +4954,16 @@ dependencies = [ "winapi", ] +[[package]] +name = "papaya" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da2442474a9404698c42509b8967f437249dbc7b50493e83020333d3943ec0ae" +dependencies = [ + "equivalent", + "seize", +] + [[package]] name = "parity-scale-codec" version = "3.7.5" @@ -4094,6 +5073,15 @@ dependencies = [ "hmac", ] +[[package]] +name = "pem-rfc7468" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -4117,7 +5105,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772" dependencies = [ "fixedbitset", - "indexmap 2.13.0", + "indexmap 2.14.2", +] + +[[package]] +name = "pharos" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9567389417feee6ce15dd6527a8a1ecac205ef62c2932bcf3d9f6fc5b78b414" +dependencies = [ + "futures", + "rustc_version 0.4.1", ] [[package]] @@ -4162,6 +5160,26 @@ dependencies = [ "siphasher 1.0.2", ] +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -4187,24 +5205,24 @@ dependencies = [ "cfg_aliases", "document-features", "dyn-clone", - "ed25519-dalek", + "ed25519-dalek 2.2.0", "futures-buffered", "futures-lite", "genawaiter", "getrandom 0.2.17", "heed", "log", - "lru", + "lru 0.13.0", "mainline", "ntimestamp", "page_size", - "reqwest", + "reqwest 0.12.28", "rustls 0.23.46", "rustls-webpki 0.102.8", "self_cell", "serde", "sha1_smol", - "simple-dns", + "simple-dns 0.9.3", "thiserror 2.0.18", "tokio", "tracing", @@ -4218,8 +5236,18 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" dependencies = [ - "der", - "spki", + "der 0.7.10", + "spki 0.7.3", +] + +[[package]] +name = "pkcs8" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" +dependencies = [ + "der 0.8.3", + "spki 0.8.1", ] [[package]] @@ -4234,6 +5262,19 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" +[[package]] +name = "plist" +version = "1.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "327a4cb2ad49dc48adfdc9da89e22c64d488b508c67a044d71ba729e4521a285" +dependencies = [ + "base64 0.23.1", + "indexmap 2.14.2", + "quick-xml", + "serde", + "time", +] + [[package]] name = "poly1305" version = "0.8.0" @@ -4262,6 +5303,9 @@ name = "portable-atomic" version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" +dependencies = [ + "serde", +] [[package]] name = "portable-atomic-util" @@ -4272,6 +5316,35 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "portmapper" +version = "0.19.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca97242f016e090a25330613bc2382aab65eb22f9149dbe84d8f8e711d49a530" +dependencies = [ + "base64 0.22.1", + "bytes", + "derive_more", + "hyper-util", + "igd-next", + "iroh-metrics", + "libc", + "n0-error", + "n0-future", + "netwatch", + "num_enum", + "rand 0.10.3", + "serde", + "smallvec", + "socket2", + "time", + "tokio", + "tokio-util", + "tower-layer", + "tracing", + "url", +] + [[package]] name = "possiblyrandom" version = "0.2.1" @@ -4291,9 +5364,21 @@ dependencies = [ "embedded-io 0.4.0", "embedded-io 0.6.1", "heapless", + "postcard-derive", "serde", ] +[[package]] +name = "postcard-derive" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0232bd009a197ceec9cc881ba46f727fcd8060a2d8d6a9dde7a69030a6fe2bb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "potential_utf" version = "0.1.4" @@ -4511,7 +5596,7 @@ dependencies = [ "log", "pkarr", "pubky-common 0.5.4", - "reqwest", + "reqwest 0.12.28", "thiserror 2.0.18", "tokio", "tracing", @@ -4534,7 +5619,7 @@ dependencies = [ "log", "pkarr", "pubky-common 0.6.0", - "reqwest", + "reqwest 0.12.28", "thiserror 2.0.18", "tokio", "tracing", @@ -4572,7 +5657,7 @@ dependencies = [ "base32", "blake3", "crypto_secretbox", - "ed25519-dalek", + "ed25519-dalek 2.2.0", "js-sys", "once_cell", "pkarr", @@ -4593,7 +5678,7 @@ dependencies = [ "base32", "blake3", "crypto_secretbox", - "ed25519-dalek", + "ed25519-dalek 2.2.0", "js-sys", "once_cell", "pkarr", @@ -4630,6 +5715,15 @@ dependencies = [ "psl-types", ] +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", +] + [[package]] name = "quinn" version = "0.11.9" @@ -4763,7 +5857,7 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ - "chacha20", + "chacha20 0.10.0", "getrandom 0.4.2", "rand_core 0.10.0", ] @@ -4966,7 +6060,44 @@ dependencies = [ "wasm-bindgen", "wasm-bindgen-futures", "web-sys", - "webpki-roots 1.0.6", + "webpki-roots 1.0.11", +] + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "rustls 0.23.46", + "rustls-pki-types", + "rustls-platform-verifier", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", ] [[package]] @@ -5107,7 +6238,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "011a0e743459d488c261488a5900f9efce5adb022812aad9c7a09117fea7bef5" dependencies = [ "chrono", - "reqwest", + "reqwest 0.12.28", "serde", "serde_json", "thiserror 2.0.18", @@ -5133,9 +6264,9 @@ dependencies = [ [[package]] name = "rustc-hash" -version = "2.1.1" +version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" [[package]] name = "rustc-hex" @@ -5171,7 +6302,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -5224,6 +6355,33 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni 0.22.4", + "log", + "once_cell", + "rustls 0.23.46", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki 0.103.15", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + [[package]] name = "rustls-webpki" version = "0.101.7" @@ -5398,14 +6556,25 @@ version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" dependencies = [ - "base16ct", - "der", + "base16ct 0.2.0", + "der 0.7.10", "generic-array", - "pkcs8", + "pkcs8 0.10.2", "subtle", "zeroize", ] +[[package]] +name = "secp" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3ef0ffc3b1b2720b00b919f6c697b1e64aca7bba54b93e0ef4b8560fac6f946" +dependencies = [ + "base16ct 0.2.0", + "secp256k1 0.31.1", + "subtle", +] + [[package]] name = "secp256k1" version = "0.27.0" @@ -5544,6 +6713,12 @@ dependencies = [ "libc", ] +[[package]] +name = "seize" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b55fb86dfd3a2f5f76ea78310a88f96c4ea21a3031f8d212443d56123fd0521" + [[package]] name = "self_cell" version = "1.2.2" @@ -5578,6 +6753,12 @@ dependencies = [ "pest", ] +[[package]] +name = "send_wrapper" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73" + [[package]] name = "serde" version = "1.0.228" @@ -5687,7 +6868,7 @@ dependencies = [ "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.13.0", + "indexmap 2.14.2", "jiff", "schemars 0.9.0", "schemars 1.2.2", @@ -5696,6 +6877,16 @@ dependencies = [ "time", ] +[[package]] +name = "serdect" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" +dependencies = [ + "base16ct 1.0.0", + "serde", +] + [[package]] name = "serial_test" version = "3.4.0" @@ -5768,6 +6959,17 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "digest 0.11.3", +] + [[package]] name = "sha3" version = "0.10.9" @@ -5833,12 +7035,31 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "signature" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" +dependencies = [ + "rand_core 0.10.0", +] + [[package]] name = "simd-adler32" version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2" +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version 0.4.1", + "simdutf8", +] + [[package]] name = "simdutf8" version = "0.1.5" @@ -5847,9 +7068,18 @@ checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" [[package]] name = "simple-dns" -version = "0.9.3" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dee851d0e5e7af3721faea1843e8015e820a234f81fda3dea9247e15bac9a86a" +dependencies = [ + "bitflags 2.11.0", +] + +[[package]] +name = "simple-dns" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dee851d0e5e7af3721faea1843e8015e820a234f81fda3dea9247e15bac9a86a" +checksum = "2b6f884fa9a8d48101774bfbd3aeb81e968dd22cffd19a372da69f183db22c1a" dependencies = [ "bitflags 2.11.0", ] @@ -5888,6 +7118,15 @@ dependencies = [ "parking_lot 0.11.2", ] +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + [[package]] name = "smallvec" version = "1.15.1" @@ -5921,6 +7160,23 @@ dependencies = [ "winapi", ] +[[package]] +name = "sorted-index-buffer" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea06cc588e43c632923a55450401b8f25e628131571d4e1baea1bdfdb2b5ed06" + +[[package]] +name = "spez" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c87e960f4dca2788eeb86bbdde8dd246be8948790b7618d656e68f9b720a86e8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "spin" version = "0.9.8" @@ -5943,7 +7199,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" dependencies = [ "base64ct", - "der", + "der 0.7.10", +] + +[[package]] +name = "spki" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" +dependencies = [ + "base64ct", + "der 0.8.3", ] [[package]] @@ -5964,12 +7230,54 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "subtle" version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "swap-common" +version = "0.1.0" +source = "git+https://github.com/coreyphillips/pubky-swap?rev=f45e204ee7646dc91983d90e4782d40760b6c72b#f45e204ee7646dc91983d90e4782d40760b6c72b" +dependencies = [ + "anyhow", + "base64 0.22.1", + "bitcoin 0.32.8", + "chacha20poly1305", + "ed25519-dalek 2.2.0", + "hex", + "musig2", + "rand 0.8.5", + "serde", + "serde_json", + "thiserror 1.0.69", + "tokio", + "tracing", + "uuid", +] + [[package]] name = "syn" version = "1.0.109" @@ -6044,6 +7352,27 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "system-configuration" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "501336eb7ba9e417300a6a0fa985721065467aa83a6dcf0422a8e43e4c0328fa" +dependencies = [ + "bitflags 2.11.0", + "core-foundation", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "tap" version = "1.0.1" @@ -6060,7 +7389,7 @@ dependencies = [ "getrandom 0.4.2", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -6162,6 +7491,7 @@ checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" dependencies = [ "deranged", "itoa", + "js-sys", "num-conv", "powerfmt", "serde_core", @@ -6315,10 +7645,34 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "futures-util", "pin-project-lite", "tokio", ] +[[package]] +name = "tokio-websockets" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d52efb639344a7c6adb8e62c6f3d2c19c001ff1b79a5041ba1c6ed42e19c6aa5" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "futures-sink", + "getrandom 0.4.2", + "http", + "httparse", + "rand 0.10.3", + "ring", + "rustls-pki-types", + "sha1_smol", + "simdutf8", + "tokio", + "tokio-rustls", + "tokio-util", +] + [[package]] name = "toml" version = "0.5.11" @@ -6343,7 +7697,7 @@ version = "0.25.4+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7193cbd0ce53dc966037f54351dbbcf0d5a642c7f0038c382ef9e677ce8c13f2" dependencies = [ - "indexmap 2.13.0", + "indexmap 2.14.2", "toml_datetime", "toml_parser", "winnow 0.7.15", @@ -6409,6 +7763,7 @@ 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", @@ -6489,7 +7844,7 @@ dependencies = [ "rusb", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "thiserror 1.0.69", "tokio", "tracing", @@ -6620,7 +7975,7 @@ dependencies = [ "glob", "goblin", "heck", - "indexmap 2.13.0", + "indexmap 2.14.2", "once_cell", "serde", "tempfile", @@ -6652,7 +8007,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09acd2ce09c777dd65ee97c251d33c8a972afc04873f1e3b21eb3492ade16933" dependencies = [ "anyhow", - "indexmap 2.13.0", + "indexmap 2.14.2", "proc-macro2", "quote", "syn 2.0.117", @@ -6695,7 +8050,7 @@ checksum = "dd76b3ac8a2d964ca9fce7df21c755afb4c77b054a85ad7a029ad179cc5abb8a" dependencies = [ "anyhow", "heck", - "indexmap 2.13.0", + "indexmap 2.14.2", "tempfile", "uniffi_internal_macros", ] @@ -6799,6 +8154,7 @@ dependencies = [ "getrandom 0.4.2", "js-sys", "rand 0.10.3", + "serde_core", "wasm-bindgen", ] @@ -6939,11 +8295,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" dependencies = [ "anyhow", - "indexmap 2.13.0", + "indexmap 2.14.2", "wasm-encoder", "wasmparser", ] +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "wasmparser" version = "0.244.0" @@ -6952,7 +8321,7 @@ checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" dependencies = [ "bitflags 2.11.0", "hashbrown 0.15.5", - "indexmap 2.13.0", + "indexmap 2.14.2", "semver 1.0.27", ] @@ -6986,6 +8355,15 @@ dependencies = [ "untrusted", ] +[[package]] +name = "webpki-root-certs" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "webpki-roots" version = "0.22.6" @@ -7007,14 +8385,14 @@ version = "0.26.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" dependencies = [ - "webpki-roots 1.0.6", + "webpki-roots 1.0.11", ] [[package]] name = "webpki-roots" -version = "1.0.6" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22cfaf3c063993ff62e73cb4311efde4db1efb31ab78a3e5c457939ad5cc0bed" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" dependencies = [ "rustls-pki-types", ] @@ -7028,6 +8406,12 @@ dependencies = [ "nom", ] +[[package]] +name = "widestring" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" + [[package]] name = "winapi" version = "0.3.9" @@ -7050,7 +8434,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -7065,11 +8449,23 @@ version = "0.61.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" dependencies = [ - "windows-collections", + "windows-collections 0.2.0", "windows-core 0.61.2", - "windows-future", + "windows-future 0.2.1", "windows-link 0.1.3", - "windows-numerics", + "windows-numerics 0.2.0", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections 0.3.2", + "windows-core 0.62.2", + "windows-future 0.3.2", + "windows-numerics 0.3.1", ] [[package]] @@ -7081,6 +8477,15 @@ dependencies = [ "windows-core 0.61.2", ] +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core 0.62.2", +] + [[package]] name = "windows-core" version = "0.61.2" @@ -7115,7 +8520,18 @@ checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" dependencies = [ "windows-core 0.61.2", "windows-link 0.1.3", - "windows-threading", + "windows-threading 0.1.0", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core 0.62.2", + "windows-link 0.2.1", + "windows-threading 0.2.1", ] [[package]] @@ -7162,6 +8578,27 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core 0.62.2", + "windows-link 0.2.1", +] + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + [[package]] name = "windows-result" version = "0.3.4" @@ -7198,13 +8635,22 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + [[package]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -7213,7 +8659,7 @@ version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -7225,20 +8671,35 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "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]] @@ -7250,18 +8711,45 @@ dependencies = [ "windows-link 0.1.3", ] +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + [[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.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + [[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.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + [[package]] name = "windows_i686_gnu" version = "0.52.6" @@ -7274,24 +8762,48 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + [[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.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + [[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.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + [[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.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + [[package]] name = "windows_x86_64_msvc" version = "0.52.6" @@ -7344,7 +8856,7 @@ checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" dependencies = [ "anyhow", "heck", - "indexmap 2.13.0", + "indexmap 2.14.2", "prettyplease", "syn 2.0.117", "wasm-metadata", @@ -7375,7 +8887,7 @@ checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" dependencies = [ "anyhow", "bitflags 2.11.0", - "indexmap 2.13.0", + "indexmap 2.14.2", "log", "serde", "serde_derive", @@ -7394,7 +8906,7 @@ checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" dependencies = [ "anyhow", "id-arena", - "indexmap 2.13.0", + "indexmap 2.14.2", "log", "semver 1.0.27", "serde", @@ -7404,12 +8916,46 @@ dependencies = [ "wasmparser", ] +[[package]] +name = "wmi" +version = "0.18.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c81b85c57a57500e56669586496bf2abd5cf082b9d32995251185d105208b64" +dependencies = [ + "chrono", + "futures", + "log", + "serde", + "thiserror 2.0.18", + "windows 0.61.3", + "windows-core 0.62.2", +] + [[package]] name = "writeable" version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" +[[package]] +name = "ws_stream_wasm" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c173014acad22e83f16403ee360115b38846fe754e735c5d9d3803fe70c6abc" +dependencies = [ + "async_io_stream", + "futures", + "js-sys", + "log", + "pharos", + "rustc_version 0.4.1", + "send_wrapper", + "thiserror 2.0.18", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "wyz" version = "0.5.1" @@ -7425,7 +8971,7 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" dependencies = [ - "curve25519-dalek", + "curve25519-dalek 4.1.3", "rand_core 0.6.4", "serde", "zeroize", @@ -7437,6 +8983,21 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8aa498d22c9bbaf482329839bc5620c46be275a19a812e9a22a2b07529a642a" +[[package]] +name = "xml-rs" +version = "0.8.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" + +[[package]] +name = "xmltree" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d8a75eaf6557bb84a65ace8609883db44a29951042ada9b393151532e41fcb" +dependencies = [ + "xml-rs", +] + [[package]] name = "yoke" version = "0.8.1" @@ -7503,18 +9064,18 @@ dependencies = [ [[package]] name = "zeroize" -version = "1.8.2" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" dependencies = [ "zeroize_derive", ] [[package]] name = "zeroize_derive" -version = "1.4.3" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85a5b4158499876c763cb03bc4e49185d3cccbabb15b33c627f7884f43db852e" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index b2776c16..3835f68d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,8 +1,8 @@ [package] name = "bitkitcore" -version = "0.8.0-rc13" +version = "0.8.0-swaps.11" edition = "2021" -rust-version = "1.90" +rust-version = "1.91" [lib] crate-type = ["cdylib", "staticlib", "rlib"] @@ -40,12 +40,19 @@ bip39 = { version = "2.0", features = ["zeroize"] } bdk = { version = "0.30.2", features = ["all-keys"] } boltz-client = { version = "0.4.1", default-features = false, features = ["electrum", "ws"] } base64 = "0.22" +# Paykit Capabilities §5 signatures on providers' delegations (already in the lockfile). +ed25519-dalek = "2" aes-gcm = "0.10.3" minicbor = { version = "2", features = ["alloc"] } ur = "0.5.2" log = "0.4" pubky = "0.6.0" pubky-app-specs = "0.4" +# Pubky Swaps client: wire types, contract checks and HTLC spends from pubky-swap, +# requests over its iroh `pubky-swap/direct/1` protocol, lockups read over Electrum. +swap-common = { git = "https://github.com/coreyphillips/pubky-swap", rev = "f45e204ee7646dc91983d90e4782d40760b6c72b" } +iroh = "=1.2.0" +electrum-client = { version = "0.25", default-features = false, features = ["proxy", "use-rustls-ring"] } # Bluetooth (for Android JNI initialization) # btleplug is also pulled in transitively by trezor-connect-rs diff --git a/Package.swift b/Package.swift index 9dfe98a9..11c4b4fd 100644 --- a/Package.swift +++ b/Package.swift @@ -4,8 +4,8 @@ import PackageDescription import Foundation -let tag = "v0.8.0-rc13" -let checksum = "228ce302b86d6c05a06e84033e8a681ff28b48af47d94d1df3c518ce8c7715b8" +let tag = "v0.8.0-swaps.11" +let checksum = "4b1b516058db0fdd1cb456233d1e62db1e57110d134b0eedc35fa475c93d5d00" let url = "https://github.com/synonymdev/bitkit-core/releases/download/\(tag)/BitkitCore.xcframework.zip" let localBinary = ProcessInfo.processInfo.environment["BITKIT_CORE_LOCAL"] == "1" @@ -27,7 +27,9 @@ let package = Package( name: "BitkitCore", dependencies: ["BitkitCoreFFI"], path: "./bindings/ios", - sources: ["bitkitcore.swift"] + sources: ["bitkitcore.swift"], + // iroh reads network interfaces through Network.framework. + linkerSettings: [.linkedFramework("Network")] ), localBinary ? .binaryTarget( diff --git a/bindings/android/gradle.properties b/bindings/android/gradle.properties index 494c62aa..d99476a9 100644 --- a/bindings/android/gradle.properties +++ b/bindings/android/gradle.properties @@ -3,4 +3,4 @@ android.useAndroidX=true android.enableJetifier=true kotlin.code.style=official group=com.synonym -version=0.8.0-rc13 +version=0.8.0-swaps.11 diff --git a/bindings/ios/bitkitcore.swift b/bindings/ios/bitkitcore.swift index c847d06d..335393f2 100644 --- a/bindings/ios/bitkitcore.swift +++ b/bindings/ios/bitkitcore.swift @@ -11676,6 +11676,15 @@ public struct PaykitRouteRequest { * contact's on-chain address, each already quoted by the app's engine for that service. */ public var serviceLegs: [ServiceRouteLeg] + /** + * Candidate Pubky Swaps providers as pubkys, usually the user's contacts. Only + * `pubky_swaps_route_paykit_payment` asks them; a contact that runs no provider is skipped. + */ + public var providers: [String] + /** + * Fee rate for the wallet's own claim transaction on a swap route. + */ + public var feeRateSatVb: UInt64 // Default memberwise initializers are never public by default, so we // declare one manually. @@ -11694,12 +11703,21 @@ public struct PaykitRouteRequest { /** * Legs through services the wallet holds a balance on, such as a Spark withdrawal to the * contact's on-chain address, each already quoted by the app's engine for that service. - */serviceLegs: [ServiceRouteLeg]) { + */serviceLegs: [ServiceRouteLeg], + /** + * Candidate Pubky Swaps providers as pubkys, usually the user's contacts. Only + * `pubky_swaps_route_paykit_payment` asks them; a contact that runs no provider is skipped. + */providers: [String], + /** + * Fee rate for the wallet's own claim transaction on a swap route. + */feeRateSatVb: UInt64) { self.amountSat = amountSat self.contactEndpoints = contactEndpoints self.lightningSpendableSat = lightningSpendableSat self.onchainSpendableSat = onchainSpendableSat self.serviceLegs = serviceLegs + self.providers = providers + self.feeRateSatVb = feeRateSatVb } } @@ -11725,6 +11743,12 @@ extension PaykitRouteRequest: Equatable, Hashable { if lhs.serviceLegs != rhs.serviceLegs { return false } + if lhs.providers != rhs.providers { + return false + } + if lhs.feeRateSatVb != rhs.feeRateSatVb { + return false + } return true } @@ -11734,6 +11758,8 @@ extension PaykitRouteRequest: Equatable, Hashable { hasher.combine(lightningSpendableSat) hasher.combine(onchainSpendableSat) hasher.combine(serviceLegs) + hasher.combine(providers) + hasher.combine(feeRateSatVb) } } @@ -11752,7 +11778,9 @@ public struct FfiConverterTypePaykitRouteRequest: FfiConverterRustBuffer { contactEndpoints: FfiConverterSequenceTypePaykitEndpoint.read(from: &buf), lightningSpendableSat: FfiConverterUInt64.read(from: &buf), onchainSpendableSat: FfiConverterUInt64.read(from: &buf), - serviceLegs: FfiConverterSequenceTypeServiceRouteLeg.read(from: &buf) + serviceLegs: FfiConverterSequenceTypeServiceRouteLeg.read(from: &buf), + providers: FfiConverterSequenceString.read(from: &buf), + feeRateSatVb: FfiConverterUInt64.read(from: &buf) ) } @@ -11762,6 +11790,8 @@ public struct FfiConverterTypePaykitRouteRequest: FfiConverterRustBuffer { FfiConverterUInt64.write(value.lightningSpendableSat, into: &buf) FfiConverterUInt64.write(value.onchainSpendableSat, into: &buf) FfiConverterSequenceTypeServiceRouteLeg.write(value.serviceLegs, into: &buf) + FfiConverterSequenceString.write(value.providers, into: &buf) + FfiConverterUInt64.write(value.feeRateSatVb, into: &buf) } } @@ -12287,70 +12317,168 @@ public func FfiConverterTypePubkyProfileLink_lower(_ value: PubkyProfileLink) -> /** - * Result of creating a reverse swap (Lightning -> onchain). - * - * The caller pays `invoice` from its Lightning node; once Boltz locks funds at - * `lockup_address`, the module claims them to the provided onchain address. + * What `pubky_swaps_restore` found, by swap id. */ -public struct ReverseSwapResponse { - public var id: String +public struct PubkySwapRestoreReport { /** - * Hold invoice the caller must pay via Lightning. + * Swaps rebuilt now; drive each with `pubky_swaps_advance`. */ - public var invoice: String + public var restored: [String] /** - * Address Boltz locks the onchain funds to. + * Swaps already on record, listed again; drive the unfinished ones with `pubky_swaps_advance`. */ - public var lockupAddress: String + public var known: [String] /** - * Amount in satoshis that will be received onchain (after Boltz fees). + * Swaps the provider lists as finished, which get no record. */ - public var onchainAmountSat: UInt64 + public var finished: [String] /** - * Onchain timeout height for the swap. + * Providers whose list was not read in full; restore again later to finish it. */ - public var timeoutBlockHeight: UInt64 + public var incompleteProviders: [String] // Default memberwise initializers are never public by default, so we // declare one manually. - public init(id: String, + public init( /** - * Hold invoice the caller must pay via Lightning. - */invoice: String, + * Swaps rebuilt now; drive each with `pubky_swaps_advance`. + */restored: [String], /** - * Address Boltz locks the onchain funds to. - */lockupAddress: String, + * Swaps already on record, listed again; drive the unfinished ones with `pubky_swaps_advance`. + */known: [String], /** - * Amount in satoshis that will be received onchain (after Boltz fees). - */onchainAmountSat: UInt64, + * Swaps the provider lists as finished, which get no record. + */finished: [String], /** - * Onchain timeout height for the swap. - */timeoutBlockHeight: UInt64) { - self.id = id + * Providers whose list was not read in full; restore again later to finish it. + */incompleteProviders: [String]) { + self.restored = restored + self.known = known + self.finished = finished + self.incompleteProviders = incompleteProviders + } +} + +#if compiler(>=6) +extension PubkySwapRestoreReport: Sendable {} +#endif + + +extension PubkySwapRestoreReport: Equatable, Hashable { + public static func ==(lhs: PubkySwapRestoreReport, rhs: PubkySwapRestoreReport) -> Bool { + if lhs.restored != rhs.restored { + return false + } + if lhs.known != rhs.known { + return false + } + if lhs.finished != rhs.finished { + return false + } + if lhs.incompleteProviders != rhs.incompleteProviders { + return false + } + return true + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(restored) + hasher.combine(known) + hasher.combine(finished) + hasher.combine(incompleteProviders) + } +} + +extension PubkySwapRestoreReport: Codable {} + + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypePubkySwapRestoreReport: FfiConverterRustBuffer { + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PubkySwapRestoreReport { + return + try PubkySwapRestoreReport( + restored: FfiConverterSequenceString.read(from: &buf), + known: FfiConverterSequenceString.read(from: &buf), + finished: FfiConverterSequenceString.read(from: &buf), + incompleteProviders: FfiConverterSequenceString.read(from: &buf) + ) + } + + public static func write(_ value: PubkySwapRestoreReport, into buf: inout [UInt8]) { + FfiConverterSequenceString.write(value.restored, into: &buf) + FfiConverterSequenceString.write(value.known, into: &buf) + FfiConverterSequenceString.write(value.finished, into: &buf) + FfiConverterSequenceString.write(value.incompleteProviders, into: &buf) + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypePubkySwapRestoreReport_lift(_ buf: RustBuffer) throws -> PubkySwapRestoreReport { + return try FfiConverterTypePubkySwapRestoreReport.lift(buf) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypePubkySwapRestoreReport_lower(_ value: PubkySwapRestoreReport) -> RustBuffer { + return FfiConverterTypePubkySwapRestoreReport.lower(value) +} + + +/** + * A committed swap: the hold invoice the wallet pays to start it. + */ +public struct PubkySwapRoutePayment { + public var swapId: String + public var invoice: String + public var debitSat: UInt64 + public var deliveredSat: UInt64 + public var destinationAddress: String + public var htlcAddress: String + public var timeoutBlockHeight: UInt32 + + // Default memberwise initializers are never public by default, so we + // declare one manually. + public init(swapId: String, invoice: String, debitSat: UInt64, deliveredSat: UInt64, destinationAddress: String, htlcAddress: String, timeoutBlockHeight: UInt32) { + self.swapId = swapId self.invoice = invoice - self.lockupAddress = lockupAddress - self.onchainAmountSat = onchainAmountSat + self.debitSat = debitSat + self.deliveredSat = deliveredSat + self.destinationAddress = destinationAddress + self.htlcAddress = htlcAddress self.timeoutBlockHeight = timeoutBlockHeight } } #if compiler(>=6) -extension ReverseSwapResponse: Sendable {} +extension PubkySwapRoutePayment: Sendable {} #endif -extension ReverseSwapResponse: Equatable, Hashable { - public static func ==(lhs: ReverseSwapResponse, rhs: ReverseSwapResponse) -> Bool { - if lhs.id != rhs.id { +extension PubkySwapRoutePayment: Equatable, Hashable { + public static func ==(lhs: PubkySwapRoutePayment, rhs: PubkySwapRoutePayment) -> Bool { + if lhs.swapId != rhs.swapId { return false } if lhs.invoice != rhs.invoice { return false } - if lhs.lockupAddress != rhs.lockupAddress { + if lhs.debitSat != rhs.debitSat { return false } - if lhs.onchainAmountSat != rhs.onchainAmountSat { + if lhs.deliveredSat != rhs.deliveredSat { + return false + } + if lhs.destinationAddress != rhs.destinationAddress { + return false + } + if lhs.htlcAddress != rhs.htlcAddress { return false } if lhs.timeoutBlockHeight != rhs.timeoutBlockHeight { @@ -12360,39 +12488,45 @@ extension ReverseSwapResponse: Equatable, Hashable { } public func hash(into hasher: inout Hasher) { - hasher.combine(id) + hasher.combine(swapId) hasher.combine(invoice) - hasher.combine(lockupAddress) - hasher.combine(onchainAmountSat) + hasher.combine(debitSat) + hasher.combine(deliveredSat) + hasher.combine(destinationAddress) + hasher.combine(htlcAddress) hasher.combine(timeoutBlockHeight) } } -extension ReverseSwapResponse: Codable {} +extension PubkySwapRoutePayment: Codable {} #if swift(>=5.8) @_documentation(visibility: private) #endif -public struct FfiConverterTypeReverseSwapResponse: FfiConverterRustBuffer { - public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ReverseSwapResponse { +public struct FfiConverterTypePubkySwapRoutePayment: FfiConverterRustBuffer { + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PubkySwapRoutePayment { return - try ReverseSwapResponse( - id: FfiConverterString.read(from: &buf), + try PubkySwapRoutePayment( + swapId: FfiConverterString.read(from: &buf), invoice: FfiConverterString.read(from: &buf), - lockupAddress: FfiConverterString.read(from: &buf), - onchainAmountSat: FfiConverterUInt64.read(from: &buf), - timeoutBlockHeight: FfiConverterUInt64.read(from: &buf) + debitSat: FfiConverterUInt64.read(from: &buf), + deliveredSat: FfiConverterUInt64.read(from: &buf), + destinationAddress: FfiConverterString.read(from: &buf), + htlcAddress: FfiConverterString.read(from: &buf), + timeoutBlockHeight: FfiConverterUInt32.read(from: &buf) ) } - public static func write(_ value: ReverseSwapResponse, into buf: inout [UInt8]) { - FfiConverterString.write(value.id, into: &buf) + public static func write(_ value: PubkySwapRoutePayment, into buf: inout [UInt8]) { + FfiConverterString.write(value.swapId, into: &buf) FfiConverterString.write(value.invoice, into: &buf) - FfiConverterString.write(value.lockupAddress, into: &buf) - FfiConverterUInt64.write(value.onchainAmountSat, into: &buf) - FfiConverterUInt64.write(value.timeoutBlockHeight, into: &buf) + FfiConverterUInt64.write(value.debitSat, into: &buf) + FfiConverterUInt64.write(value.deliveredSat, into: &buf) + FfiConverterString.write(value.destinationAddress, into: &buf) + FfiConverterString.write(value.htlcAddress, into: &buf) + FfiConverterUInt32.write(value.timeoutBlockHeight, into: &buf) } } @@ -12400,29 +12534,30 @@ public struct FfiConverterTypeReverseSwapResponse: FfiConverterRustBuffer { #if swift(>=5.8) @_documentation(visibility: private) #endif -public func FfiConverterTypeReverseSwapResponse_lift(_ buf: RustBuffer) throws -> ReverseSwapResponse { - return try FfiConverterTypeReverseSwapResponse.lift(buf) +public func FfiConverterTypePubkySwapRoutePayment_lift(_ buf: RustBuffer) throws -> PubkySwapRoutePayment { + return try FfiConverterTypePubkySwapRoutePayment.lift(buf) } #if swift(>=5.8) @_documentation(visibility: private) #endif -public func FfiConverterTypeReverseSwapResponse_lower(_ value: ReverseSwapResponse) -> RustBuffer { - return FfiConverterTypeReverseSwapResponse.lower(value) +public func FfiConverterTypePubkySwapRoutePayment_lower(_ value: PubkySwapRoutePayment) -> RustBuffer { + return FfiConverterTypePubkySwapRoutePayment.lower(value) } /** - * A one-leg route through a service the wallet holds a balance on, such as a Spark withdrawal - * to the contact's on-chain address. The app quotes it and runs it. + * A firm `swap/1` quote for one route, with everything the review screen shows. */ -public struct ServiceRouteLeg { +public struct PubkySwapRouteQuote { + public var providerPubky: String /** - * The service, such as `spark`. + * The wallet's id for this route, which `pubky_swaps_commit_route` takes. The provider's own + * quote id stays inside bitkit-core. */ - public var service: String + public var quoteId: String /** - * The contact endpoint the service delivers to. It must be one the contact published. + * The contact endpoint the swap delivers to. */ public var endpoint: PaykitEndpoint /** @@ -12430,56 +12565,79 @@ public struct ServiceRouteLeg { */ public var deliveredSat: UInt64 /** - * What the wallet's balance on the service is debited. + * What the provider locks on chain: the delivered amount plus the wallet's claim fee. + */ + public var lockSat: UInt64 + /** + * What the wallet pays over Lightning. */ public var debitSat: UInt64 + public var serviceFeeSat: UInt64 + public var providerOnchainFeeSat: UInt64 + public var claimFeeSat: UInt64 /** - * Who the wallet trusts to complete the leg: `trusted` for Spark's operators. + * `debit_sat - delivered_sat`. */ + public var totalFeeSat: UInt64 public var atomicity: String + public var validUntilUnix: UInt64 /** - * When the quote stops holding, or 0 when it does not expire. + * How many providers were asked for a quote. */ - public var validUntilUnix: UInt64 + public var providersQuoted: UInt32 // Default memberwise initializers are never public by default, so we // declare one manually. - public init( + public init(providerPubky: String, /** - * The service, such as `spark`. - */service: String, + * The wallet's id for this route, which `pubky_swaps_commit_route` takes. The provider's own + * quote id stays inside bitkit-core. + */quoteId: String, /** - * The contact endpoint the service delivers to. It must be one the contact published. + * The contact endpoint the swap delivers to. */endpoint: PaykitEndpoint, /** * What the contact receives. */deliveredSat: UInt64, /** - * What the wallet's balance on the service is debited. - */debitSat: UInt64, + * What the provider locks on chain: the delivered amount plus the wallet's claim fee. + */lockSat: UInt64, /** - * Who the wallet trusts to complete the leg: `trusted` for Spark's operators. - */atomicity: String, + * What the wallet pays over Lightning. + */debitSat: UInt64, serviceFeeSat: UInt64, providerOnchainFeeSat: UInt64, claimFeeSat: UInt64, /** - * When the quote stops holding, or 0 when it does not expire. - */validUntilUnix: UInt64) { - self.service = service + * `debit_sat - delivered_sat`. + */totalFeeSat: UInt64, atomicity: String, validUntilUnix: UInt64, + /** + * How many providers were asked for a quote. + */providersQuoted: UInt32) { + self.providerPubky = providerPubky + self.quoteId = quoteId self.endpoint = endpoint self.deliveredSat = deliveredSat + self.lockSat = lockSat self.debitSat = debitSat + self.serviceFeeSat = serviceFeeSat + self.providerOnchainFeeSat = providerOnchainFeeSat + self.claimFeeSat = claimFeeSat + self.totalFeeSat = totalFeeSat self.atomicity = atomicity self.validUntilUnix = validUntilUnix + self.providersQuoted = providersQuoted } } #if compiler(>=6) -extension ServiceRouteLeg: Sendable {} +extension PubkySwapRouteQuote: Sendable {} #endif -extension ServiceRouteLeg: Equatable, Hashable { - public static func ==(lhs: ServiceRouteLeg, rhs: ServiceRouteLeg) -> Bool { - if lhs.service != rhs.service { +extension PubkySwapRouteQuote: Equatable, Hashable { + public static func ==(lhs: PubkySwapRouteQuote, rhs: PubkySwapRouteQuote) -> Bool { + if lhs.providerPubky != rhs.providerPubky { + return false + } + if lhs.quoteId != rhs.quoteId { return false } if lhs.endpoint != rhs.endpoint { @@ -12488,55 +12646,94 @@ extension ServiceRouteLeg: Equatable, Hashable { if lhs.deliveredSat != rhs.deliveredSat { return false } + if lhs.lockSat != rhs.lockSat { + return false + } if lhs.debitSat != rhs.debitSat { return false } + if lhs.serviceFeeSat != rhs.serviceFeeSat { + return false + } + if lhs.providerOnchainFeeSat != rhs.providerOnchainFeeSat { + return false + } + if lhs.claimFeeSat != rhs.claimFeeSat { + return false + } + if lhs.totalFeeSat != rhs.totalFeeSat { + return false + } if lhs.atomicity != rhs.atomicity { return false } if lhs.validUntilUnix != rhs.validUntilUnix { return false } + if lhs.providersQuoted != rhs.providersQuoted { + return false + } return true } public func hash(into hasher: inout Hasher) { - hasher.combine(service) + hasher.combine(providerPubky) + hasher.combine(quoteId) hasher.combine(endpoint) hasher.combine(deliveredSat) + hasher.combine(lockSat) hasher.combine(debitSat) + hasher.combine(serviceFeeSat) + hasher.combine(providerOnchainFeeSat) + hasher.combine(claimFeeSat) + hasher.combine(totalFeeSat) hasher.combine(atomicity) hasher.combine(validUntilUnix) + hasher.combine(providersQuoted) } } -extension ServiceRouteLeg: Codable {} +extension PubkySwapRouteQuote: Codable {} #if swift(>=5.8) @_documentation(visibility: private) #endif -public struct FfiConverterTypeServiceRouteLeg: FfiConverterRustBuffer { - public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ServiceRouteLeg { +public struct FfiConverterTypePubkySwapRouteQuote: FfiConverterRustBuffer { + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PubkySwapRouteQuote { return - try ServiceRouteLeg( - service: FfiConverterString.read(from: &buf), + try PubkySwapRouteQuote( + providerPubky: FfiConverterString.read(from: &buf), + quoteId: FfiConverterString.read(from: &buf), endpoint: FfiConverterTypePaykitEndpoint.read(from: &buf), deliveredSat: FfiConverterUInt64.read(from: &buf), + lockSat: FfiConverterUInt64.read(from: &buf), debitSat: FfiConverterUInt64.read(from: &buf), + serviceFeeSat: FfiConverterUInt64.read(from: &buf), + providerOnchainFeeSat: FfiConverterUInt64.read(from: &buf), + claimFeeSat: FfiConverterUInt64.read(from: &buf), + totalFeeSat: FfiConverterUInt64.read(from: &buf), atomicity: FfiConverterString.read(from: &buf), - validUntilUnix: FfiConverterUInt64.read(from: &buf) + validUntilUnix: FfiConverterUInt64.read(from: &buf), + providersQuoted: FfiConverterUInt32.read(from: &buf) ) } - public static func write(_ value: ServiceRouteLeg, into buf: inout [UInt8]) { - FfiConverterString.write(value.service, into: &buf) + public static func write(_ value: PubkySwapRouteQuote, into buf: inout [UInt8]) { + FfiConverterString.write(value.providerPubky, into: &buf) + FfiConverterString.write(value.quoteId, into: &buf) FfiConverterTypePaykitEndpoint.write(value.endpoint, into: &buf) FfiConverterUInt64.write(value.deliveredSat, into: &buf) + FfiConverterUInt64.write(value.lockSat, into: &buf) FfiConverterUInt64.write(value.debitSat, into: &buf) + FfiConverterUInt64.write(value.serviceFeeSat, into: &buf) + FfiConverterUInt64.write(value.providerOnchainFeeSat, into: &buf) + FfiConverterUInt64.write(value.claimFeeSat, into: &buf) + FfiConverterUInt64.write(value.totalFeeSat, into: &buf) FfiConverterString.write(value.atomicity, into: &buf) FfiConverterUInt64.write(value.validUntilUnix, into: &buf) + FfiConverterUInt32.write(value.providersQuoted, into: &buf) } } @@ -12544,66 +12741,530 @@ public struct FfiConverterTypeServiceRouteLeg: FfiConverterRustBuffer { #if swift(>=5.8) @_documentation(visibility: private) #endif -public func FfiConverterTypeServiceRouteLeg_lift(_ buf: RustBuffer) throws -> ServiceRouteLeg { - return try FfiConverterTypeServiceRouteLeg.lift(buf) +public func FfiConverterTypePubkySwapRouteQuote_lift(_ buf: RustBuffer) throws -> PubkySwapRouteQuote { + return try FfiConverterTypePubkySwapRouteQuote.lift(buf) } #if swift(>=5.8) @_documentation(visibility: private) #endif -public func FfiConverterTypeServiceRouteLeg_lower(_ value: ServiceRouteLeg) -> RustBuffer { - return FfiConverterTypeServiceRouteLeg.lower(value) +public func FfiConverterTypePubkySwapRouteQuote_lower(_ value: PubkySwapRouteQuote) -> RustBuffer { + return FfiConverterTypePubkySwapRouteQuote.lower(value) } -/** - * Result from querying a single Bitcoin address. - */ -public struct SingleAddressInfoResult { - /** - * The queried address - */ - public var address: String - /** - * Total confirmed balance in satoshis - */ - public var balance: UInt64 - /** - * UTXOs for this address - */ - public var utxos: [AccountUtxo] - /** - * Number of transactions involving this address - */ - public var transfers: UInt32 - /** - * Current blockchain tip height - */ - public var blockHeight: UInt32 +public struct PubkySwapRouteStatus { + public var swapId: String + public var state: PubkySwapRouteState + public var providerPubky: String + public var deliveredSat: UInt64 + public var destinationAddress: String // Default memberwise initializers are never public by default, so we // declare one manually. - public init( - /** - * The queried address - */address: String, - /** - * Total confirmed balance in satoshis - */balance: UInt64, - /** - * UTXOs for this address - */utxos: [AccountUtxo], - /** - * Number of transactions involving this address - */transfers: UInt32, - /** - * Current blockchain tip height - */blockHeight: UInt32) { - self.address = address - self.balance = balance - self.utxos = utxos - self.transfers = transfers - self.blockHeight = blockHeight + public init(swapId: String, state: PubkySwapRouteState, providerPubky: String, deliveredSat: UInt64, destinationAddress: String) { + self.swapId = swapId + self.state = state + self.providerPubky = providerPubky + self.deliveredSat = deliveredSat + self.destinationAddress = destinationAddress + } +} + +#if compiler(>=6) +extension PubkySwapRouteStatus: Sendable {} +#endif + + +extension PubkySwapRouteStatus: Equatable, Hashable { + public static func ==(lhs: PubkySwapRouteStatus, rhs: PubkySwapRouteStatus) -> Bool { + if lhs.swapId != rhs.swapId { + return false + } + if lhs.state != rhs.state { + return false + } + if lhs.providerPubky != rhs.providerPubky { + return false + } + if lhs.deliveredSat != rhs.deliveredSat { + return false + } + if lhs.destinationAddress != rhs.destinationAddress { + return false + } + return true + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(swapId) + hasher.combine(state) + hasher.combine(providerPubky) + hasher.combine(deliveredSat) + hasher.combine(destinationAddress) + } +} + +extension PubkySwapRouteStatus: Codable {} + + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypePubkySwapRouteStatus: FfiConverterRustBuffer { + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PubkySwapRouteStatus { + return + try PubkySwapRouteStatus( + swapId: FfiConverterString.read(from: &buf), + state: FfiConverterTypePubkySwapRouteState.read(from: &buf), + providerPubky: FfiConverterString.read(from: &buf), + deliveredSat: FfiConverterUInt64.read(from: &buf), + destinationAddress: FfiConverterString.read(from: &buf) + ) + } + + public static func write(_ value: PubkySwapRouteStatus, into buf: inout [UInt8]) { + FfiConverterString.write(value.swapId, into: &buf) + FfiConverterTypePubkySwapRouteState.write(value.state, into: &buf) + FfiConverterString.write(value.providerPubky, into: &buf) + FfiConverterUInt64.write(value.deliveredSat, into: &buf) + FfiConverterString.write(value.destinationAddress, into: &buf) + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypePubkySwapRouteStatus_lift(_ buf: RustBuffer) throws -> PubkySwapRouteStatus { + return try FfiConverterTypePubkySwapRouteStatus.lift(buf) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypePubkySwapRouteStatus_lower(_ value: PubkySwapRouteStatus) -> RustBuffer { + return FfiConverterTypePubkySwapRouteStatus.lower(value) +} + + +/** + * A Lightning payment the wallet's node sent, which `pubky_swaps_restore` matches to a listed + * swap by its hash. + */ +public struct PubkySwapSentPayment { + public var paymentHashHex: String + /** + * What the payment paid the provider, routing fees excluded. + */ + public var amountSat: UInt64 + /** + * Whether the payment settled, so the provider holds the preimage. A pending payment is + * still in flight. + */ + public var settled: Bool + + // Default memberwise initializers are never public by default, so we + // declare one manually. + public init(paymentHashHex: String, + /** + * What the payment paid the provider, routing fees excluded. + */amountSat: UInt64, + /** + * Whether the payment settled, so the provider holds the preimage. A pending payment is + * still in flight. + */settled: Bool) { + self.paymentHashHex = paymentHashHex + self.amountSat = amountSat + self.settled = settled + } +} + +#if compiler(>=6) +extension PubkySwapSentPayment: Sendable {} +#endif + + +extension PubkySwapSentPayment: Equatable, Hashable { + public static func ==(lhs: PubkySwapSentPayment, rhs: PubkySwapSentPayment) -> Bool { + if lhs.paymentHashHex != rhs.paymentHashHex { + return false + } + if lhs.amountSat != rhs.amountSat { + return false + } + if lhs.settled != rhs.settled { + return false + } + return true + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(paymentHashHex) + hasher.combine(amountSat) + hasher.combine(settled) + } +} + +extension PubkySwapSentPayment: Codable {} + + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypePubkySwapSentPayment: FfiConverterRustBuffer { + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PubkySwapSentPayment { + return + try PubkySwapSentPayment( + paymentHashHex: FfiConverterString.read(from: &buf), + amountSat: FfiConverterUInt64.read(from: &buf), + settled: FfiConverterBool.read(from: &buf) + ) + } + + public static func write(_ value: PubkySwapSentPayment, into buf: inout [UInt8]) { + FfiConverterString.write(value.paymentHashHex, into: &buf) + FfiConverterUInt64.write(value.amountSat, into: &buf) + FfiConverterBool.write(value.settled, into: &buf) + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypePubkySwapSentPayment_lift(_ buf: RustBuffer) throws -> PubkySwapSentPayment { + return try FfiConverterTypePubkySwapSentPayment.lift(buf) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypePubkySwapSentPayment_lower(_ value: PubkySwapSentPayment) -> RustBuffer { + return FfiConverterTypePubkySwapSentPayment.lower(value) +} + + +/** + * Result of creating a reverse swap (Lightning -> onchain). + * + * The caller pays `invoice` from its Lightning node; once Boltz locks funds at + * `lockup_address`, the module claims them to the provided onchain address. + */ +public struct ReverseSwapResponse { + public var id: String + /** + * Hold invoice the caller must pay via Lightning. + */ + public var invoice: String + /** + * Address Boltz locks the onchain funds to. + */ + public var lockupAddress: String + /** + * Amount in satoshis that will be received onchain (after Boltz fees). + */ + public var onchainAmountSat: UInt64 + /** + * Onchain timeout height for the swap. + */ + public var timeoutBlockHeight: UInt64 + + // Default memberwise initializers are never public by default, so we + // declare one manually. + public init(id: String, + /** + * Hold invoice the caller must pay via Lightning. + */invoice: String, + /** + * Address Boltz locks the onchain funds to. + */lockupAddress: String, + /** + * Amount in satoshis that will be received onchain (after Boltz fees). + */onchainAmountSat: UInt64, + /** + * Onchain timeout height for the swap. + */timeoutBlockHeight: UInt64) { + self.id = id + self.invoice = invoice + self.lockupAddress = lockupAddress + self.onchainAmountSat = onchainAmountSat + self.timeoutBlockHeight = timeoutBlockHeight + } +} + +#if compiler(>=6) +extension ReverseSwapResponse: Sendable {} +#endif + + +extension ReverseSwapResponse: Equatable, Hashable { + public static func ==(lhs: ReverseSwapResponse, rhs: ReverseSwapResponse) -> Bool { + if lhs.id != rhs.id { + return false + } + if lhs.invoice != rhs.invoice { + return false + } + if lhs.lockupAddress != rhs.lockupAddress { + return false + } + if lhs.onchainAmountSat != rhs.onchainAmountSat { + return false + } + if lhs.timeoutBlockHeight != rhs.timeoutBlockHeight { + return false + } + return true + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(id) + hasher.combine(invoice) + hasher.combine(lockupAddress) + hasher.combine(onchainAmountSat) + hasher.combine(timeoutBlockHeight) + } +} + +extension ReverseSwapResponse: Codable {} + + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypeReverseSwapResponse: FfiConverterRustBuffer { + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ReverseSwapResponse { + return + try ReverseSwapResponse( + id: FfiConverterString.read(from: &buf), + invoice: FfiConverterString.read(from: &buf), + lockupAddress: FfiConverterString.read(from: &buf), + onchainAmountSat: FfiConverterUInt64.read(from: &buf), + timeoutBlockHeight: FfiConverterUInt64.read(from: &buf) + ) + } + + public static func write(_ value: ReverseSwapResponse, into buf: inout [UInt8]) { + FfiConverterString.write(value.id, into: &buf) + FfiConverterString.write(value.invoice, into: &buf) + FfiConverterString.write(value.lockupAddress, into: &buf) + FfiConverterUInt64.write(value.onchainAmountSat, into: &buf) + FfiConverterUInt64.write(value.timeoutBlockHeight, into: &buf) + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeReverseSwapResponse_lift(_ buf: RustBuffer) throws -> ReverseSwapResponse { + return try FfiConverterTypeReverseSwapResponse.lift(buf) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeReverseSwapResponse_lower(_ value: ReverseSwapResponse) -> RustBuffer { + return FfiConverterTypeReverseSwapResponse.lower(value) +} + + +/** + * A one-leg route through a service the wallet holds a balance on, such as a Spark withdrawal + * to the contact's on-chain address. The app quotes it and runs it. + */ +public struct ServiceRouteLeg { + /** + * The service, such as `spark`. + */ + public var service: String + /** + * The contact endpoint the service delivers to. It must be one the contact published. + */ + public var endpoint: PaykitEndpoint + /** + * What the contact receives. + */ + public var deliveredSat: UInt64 + /** + * What the wallet's balance on the service is debited. + */ + public var debitSat: UInt64 + /** + * Who the wallet trusts to complete the leg: `trusted` for Spark's operators. + */ + public var atomicity: String + /** + * When the quote stops holding, or 0 when it does not expire. + */ + public var validUntilUnix: UInt64 + + // Default memberwise initializers are never public by default, so we + // declare one manually. + public init( + /** + * The service, such as `spark`. + */service: String, + /** + * The contact endpoint the service delivers to. It must be one the contact published. + */endpoint: PaykitEndpoint, + /** + * What the contact receives. + */deliveredSat: UInt64, + /** + * What the wallet's balance on the service is debited. + */debitSat: UInt64, + /** + * Who the wallet trusts to complete the leg: `trusted` for Spark's operators. + */atomicity: String, + /** + * When the quote stops holding, or 0 when it does not expire. + */validUntilUnix: UInt64) { + self.service = service + self.endpoint = endpoint + self.deliveredSat = deliveredSat + self.debitSat = debitSat + self.atomicity = atomicity + self.validUntilUnix = validUntilUnix + } +} + +#if compiler(>=6) +extension ServiceRouteLeg: Sendable {} +#endif + + +extension ServiceRouteLeg: Equatable, Hashable { + public static func ==(lhs: ServiceRouteLeg, rhs: ServiceRouteLeg) -> Bool { + if lhs.service != rhs.service { + return false + } + if lhs.endpoint != rhs.endpoint { + return false + } + if lhs.deliveredSat != rhs.deliveredSat { + return false + } + if lhs.debitSat != rhs.debitSat { + return false + } + if lhs.atomicity != rhs.atomicity { + return false + } + if lhs.validUntilUnix != rhs.validUntilUnix { + return false + } + return true + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(service) + hasher.combine(endpoint) + hasher.combine(deliveredSat) + hasher.combine(debitSat) + hasher.combine(atomicity) + hasher.combine(validUntilUnix) + } +} + +extension ServiceRouteLeg: Codable {} + + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypeServiceRouteLeg: FfiConverterRustBuffer { + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ServiceRouteLeg { + return + try ServiceRouteLeg( + service: FfiConverterString.read(from: &buf), + endpoint: FfiConverterTypePaykitEndpoint.read(from: &buf), + deliveredSat: FfiConverterUInt64.read(from: &buf), + debitSat: FfiConverterUInt64.read(from: &buf), + atomicity: FfiConverterString.read(from: &buf), + validUntilUnix: FfiConverterUInt64.read(from: &buf) + ) + } + + public static func write(_ value: ServiceRouteLeg, into buf: inout [UInt8]) { + FfiConverterString.write(value.service, into: &buf) + FfiConverterTypePaykitEndpoint.write(value.endpoint, into: &buf) + FfiConverterUInt64.write(value.deliveredSat, into: &buf) + FfiConverterUInt64.write(value.debitSat, into: &buf) + FfiConverterString.write(value.atomicity, into: &buf) + FfiConverterUInt64.write(value.validUntilUnix, into: &buf) + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeServiceRouteLeg_lift(_ buf: RustBuffer) throws -> ServiceRouteLeg { + return try FfiConverterTypeServiceRouteLeg.lift(buf) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeServiceRouteLeg_lower(_ value: ServiceRouteLeg) -> RustBuffer { + return FfiConverterTypeServiceRouteLeg.lower(value) +} + + +/** + * Result from querying a single Bitcoin address. + */ +public struct SingleAddressInfoResult { + /** + * The queried address + */ + public var address: String + /** + * Total confirmed balance in satoshis + */ + public var balance: UInt64 + /** + * UTXOs for this address + */ + public var utxos: [AccountUtxo] + /** + * Number of transactions involving this address + */ + public var transfers: UInt32 + /** + * Current blockchain tip height + */ + public var blockHeight: UInt32 + + // Default memberwise initializers are never public by default, so we + // declare one manually. + public init( + /** + * The queried address + */address: String, + /** + * Total confirmed balance in satoshis + */balance: UInt64, + /** + * UTXOs for this address + */utxos: [AccountUtxo], + /** + * Number of transactions involving this address + */transfers: UInt32, + /** + * Current blockchain tip height + */blockHeight: UInt32) { + self.address = address + self.balance = balance + self.utxos = utxos + self.transfers = transfers + self.blockHeight = blockHeight } } @@ -12948,6 +13609,192 @@ public func FfiConverterTypeSupportedHardwareWallet_lower(_ value: SupportedHard } +/** + * A `swap/1` edge from a provider's offer, in Paykit Capabilities terms: the payment endpoint + * the owner pays from, the endpoint the route delivers to, its bounds and its indicative fee. + */ +public struct SwapRouteEdge { + public var providerPubky: String + public var offerId: String + /** + * `reverse` (Lightning to on-chain) or `submarine` (on-chain to Lightning). + */ + public var direction: String + /** + * Payment Endpoint Identifier the owner pays with, such as `btc-lightning-bolt11`. + */ + public var fromEndpoint: String + /** + * Payment Endpoint Identifier the route delivers to, such as `btc-regtest-p2wpkh`. + */ + public var toEndpoint: String + /** + * The minimum the provider enforces, not its configured floor. + */ + public var minSat: UInt64 + public var maxSat: UInt64 + public var baseFeeSat: UInt64 + public var feePpm: UInt64 + public var onchainFeeSat: UInt64 + /** + * Atomicity class of the edge. Pubky Swaps legs are always `hash`. + */ + public var atomicity: String + public var fundWithinSecs: UInt64 + + // Default memberwise initializers are never public by default, so we + // declare one manually. + public init(providerPubky: String, offerId: String, + /** + * `reverse` (Lightning to on-chain) or `submarine` (on-chain to Lightning). + */direction: String, + /** + * Payment Endpoint Identifier the owner pays with, such as `btc-lightning-bolt11`. + */fromEndpoint: String, + /** + * Payment Endpoint Identifier the route delivers to, such as `btc-regtest-p2wpkh`. + */toEndpoint: String, + /** + * The minimum the provider enforces, not its configured floor. + */minSat: UInt64, maxSat: UInt64, baseFeeSat: UInt64, feePpm: UInt64, onchainFeeSat: UInt64, + /** + * Atomicity class of the edge. Pubky Swaps legs are always `hash`. + */atomicity: String, fundWithinSecs: UInt64) { + self.providerPubky = providerPubky + self.offerId = offerId + self.direction = direction + self.fromEndpoint = fromEndpoint + self.toEndpoint = toEndpoint + self.minSat = minSat + self.maxSat = maxSat + self.baseFeeSat = baseFeeSat + self.feePpm = feePpm + self.onchainFeeSat = onchainFeeSat + self.atomicity = atomicity + self.fundWithinSecs = fundWithinSecs + } +} + +#if compiler(>=6) +extension SwapRouteEdge: Sendable {} +#endif + + +extension SwapRouteEdge: Equatable, Hashable { + public static func ==(lhs: SwapRouteEdge, rhs: SwapRouteEdge) -> Bool { + if lhs.providerPubky != rhs.providerPubky { + return false + } + if lhs.offerId != rhs.offerId { + return false + } + if lhs.direction != rhs.direction { + return false + } + if lhs.fromEndpoint != rhs.fromEndpoint { + return false + } + if lhs.toEndpoint != rhs.toEndpoint { + return false + } + if lhs.minSat != rhs.minSat { + return false + } + if lhs.maxSat != rhs.maxSat { + return false + } + if lhs.baseFeeSat != rhs.baseFeeSat { + return false + } + if lhs.feePpm != rhs.feePpm { + return false + } + if lhs.onchainFeeSat != rhs.onchainFeeSat { + return false + } + if lhs.atomicity != rhs.atomicity { + return false + } + if lhs.fundWithinSecs != rhs.fundWithinSecs { + return false + } + return true + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(providerPubky) + hasher.combine(offerId) + hasher.combine(direction) + hasher.combine(fromEndpoint) + hasher.combine(toEndpoint) + hasher.combine(minSat) + hasher.combine(maxSat) + hasher.combine(baseFeeSat) + hasher.combine(feePpm) + hasher.combine(onchainFeeSat) + hasher.combine(atomicity) + hasher.combine(fundWithinSecs) + } +} + +extension SwapRouteEdge: Codable {} + + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypeSwapRouteEdge: FfiConverterRustBuffer { + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwapRouteEdge { + return + try SwapRouteEdge( + providerPubky: FfiConverterString.read(from: &buf), + offerId: FfiConverterString.read(from: &buf), + direction: FfiConverterString.read(from: &buf), + fromEndpoint: FfiConverterString.read(from: &buf), + toEndpoint: FfiConverterString.read(from: &buf), + minSat: FfiConverterUInt64.read(from: &buf), + maxSat: FfiConverterUInt64.read(from: &buf), + baseFeeSat: FfiConverterUInt64.read(from: &buf), + feePpm: FfiConverterUInt64.read(from: &buf), + onchainFeeSat: FfiConverterUInt64.read(from: &buf), + atomicity: FfiConverterString.read(from: &buf), + fundWithinSecs: FfiConverterUInt64.read(from: &buf) + ) + } + + public static func write(_ value: SwapRouteEdge, into buf: inout [UInt8]) { + FfiConverterString.write(value.providerPubky, into: &buf) + FfiConverterString.write(value.offerId, into: &buf) + FfiConverterString.write(value.direction, into: &buf) + FfiConverterString.write(value.fromEndpoint, into: &buf) + FfiConverterString.write(value.toEndpoint, into: &buf) + FfiConverterUInt64.write(value.minSat, into: &buf) + FfiConverterUInt64.write(value.maxSat, into: &buf) + FfiConverterUInt64.write(value.baseFeeSat, into: &buf) + FfiConverterUInt64.write(value.feePpm, into: &buf) + FfiConverterUInt64.write(value.onchainFeeSat, into: &buf) + FfiConverterString.write(value.atomicity, into: &buf) + FfiConverterUInt64.write(value.fundWithinSecs, into: &buf) + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeSwapRouteEdge_lift(_ buf: RustBuffer) throws -> SwapRouteEdge { + return try FfiConverterTypeSwapRouteEdge.lift(buf) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeSwapRouteEdge_lower(_ value: SwapRouteEdge) -> RustBuffer { + return FfiConverterTypeSwapRouteEdge.lower(value) +} + + public struct SweepResult { /** * The transaction ID of the sweep transaction @@ -25197,6 +26044,11 @@ public enum PaykitRoute { */ case service(leg: ServiceRouteLeg ) + /** + * The wallet pays over Lightning and a Pubky Swaps provider delivers on-chain. + */ + case swap(quote: PubkySwapRouteQuote + ) /** * Nothing can pay this contact. `reason` is English detail for logs; the app shows its own * localized text. @@ -25226,7 +26078,10 @@ public struct FfiConverterTypePaykitRoute: FfiConverterRustBuffer { case 2: return .service(leg: try FfiConverterTypeServiceRouteLeg.read(from: &buf) ) - case 3: return .none(reason: try FfiConverterString.read(from: &buf) + case 3: return .swap(quote: try FfiConverterTypePubkySwapRouteQuote.read(from: &buf) + ) + + case 4: return .none(reason: try FfiConverterString.read(from: &buf) ) default: throw UniffiInternalError.unexpectedEnumCase @@ -25247,8 +26102,13 @@ public struct FfiConverterTypePaykitRoute: FfiConverterRustBuffer { FfiConverterTypeServiceRouteLeg.write(leg, into: &buf) + case let .swap(quote): + writeInt(&buf, Int32(3)) + FfiConverterTypePubkySwapRouteQuote.write(quote, into: &buf) + + case let .none(reason): - writeInt(&buf, Int32(3)) + writeInt(&buf, Int32(4)) FfiConverterString.write(reason, into: &buf) } @@ -25666,13 +26526,305 @@ public struct FfiConverterTypePubkyAuthKind: FfiConverterRustBuffer { switch value { - case .signin: - writeInt(&buf, Int32(1)) + case .signin: + writeInt(&buf, Int32(1)) + + + case .signup: + writeInt(&buf, Int32(2)) + + } + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypePubkyAuthKind_lift(_ buf: RustBuffer) throws -> PubkyAuthKind { + return try FfiConverterTypePubkyAuthKind.lift(buf) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypePubkyAuthKind_lower(_ value: PubkyAuthKind) -> RustBuffer { + return FfiConverterTypePubkyAuthKind.lower(value) +} + + +extension PubkyAuthKind: Equatable, Hashable {} + +extension PubkyAuthKind: Codable {} + + + + + + + +public enum PubkyError: Swift.Error { + + + + case InvalidCapabilities(reason: String + ) + case AuthFailed(reason: String + ) + case NoActiveFlow + case ResolutionFailed(reason: String + ) + case FetchFailed(reason: String + ) + case ProfileNotFound + case ProfileParseFailed(reason: String + ) + case KeyError(reason: String + ) + case WriteFailed(reason: String + ) +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypePubkyError: FfiConverterRustBuffer { + typealias SwiftType = PubkyError + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PubkyError { + let variant: Int32 = try readInt(&buf) + switch variant { + + + + + case 1: return .InvalidCapabilities( + reason: try FfiConverterString.read(from: &buf) + ) + case 2: return .AuthFailed( + reason: try FfiConverterString.read(from: &buf) + ) + case 3: return .NoActiveFlow + case 4: return .ResolutionFailed( + reason: try FfiConverterString.read(from: &buf) + ) + case 5: return .FetchFailed( + reason: try FfiConverterString.read(from: &buf) + ) + case 6: return .ProfileNotFound + case 7: return .ProfileParseFailed( + reason: try FfiConverterString.read(from: &buf) + ) + case 8: return .KeyError( + reason: try FfiConverterString.read(from: &buf) + ) + case 9: return .WriteFailed( + reason: try FfiConverterString.read(from: &buf) + ) + + default: throw UniffiInternalError.unexpectedEnumCase + } + } + + public static func write(_ value: PubkyError, into buf: inout [UInt8]) { + switch value { + + + + + + case let .InvalidCapabilities(reason): + writeInt(&buf, Int32(1)) + FfiConverterString.write(reason, into: &buf) + + + case let .AuthFailed(reason): + writeInt(&buf, Int32(2)) + FfiConverterString.write(reason, into: &buf) + + + case .NoActiveFlow: + writeInt(&buf, Int32(3)) + + + case let .ResolutionFailed(reason): + writeInt(&buf, Int32(4)) + FfiConverterString.write(reason, into: &buf) + + + case let .FetchFailed(reason): + writeInt(&buf, Int32(5)) + FfiConverterString.write(reason, into: &buf) + + + case .ProfileNotFound: + writeInt(&buf, Int32(6)) + + + case let .ProfileParseFailed(reason): + writeInt(&buf, Int32(7)) + FfiConverterString.write(reason, into: &buf) + + + case let .KeyError(reason): + writeInt(&buf, Int32(8)) + FfiConverterString.write(reason, into: &buf) + + + case let .WriteFailed(reason): + writeInt(&buf, Int32(9)) + FfiConverterString.write(reason, into: &buf) + + } + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypePubkyError_lift(_ buf: RustBuffer) throws -> PubkyError { + return try FfiConverterTypePubkyError.lift(buf) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypePubkyError_lower(_ value: PubkyError) -> RustBuffer { + return FfiConverterTypePubkyError.lower(value) +} + + +extension PubkyError: Equatable, Hashable {} + +extension PubkyError: Codable {} + + + + +extension PubkyError: Foundation.LocalizedError { + public var errorDescription: String? { + String(reflecting: self) + } +} + + + + + +/** + * Errors surfaced by the Pubky Swaps route module. + */ +public enum PubkySwapError: Swift.Error { + + + + case InvalidInput(errorDetails: String + ) + case Transport(errorDetails: String + ) + /** + * The provider refused the request with one of its closed refusal codes. + */ + case Refused(code: String, reason: String + ) + /** + * The provider's quote, contract or invoice did not match what was asked for. + */ + case Validation(errorDetails: String + ) + case Chain(errorDetails: String + ) + case Storage(errorDetails: String + ) + case NotFound(errorDetails: String + ) +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypePubkySwapError: FfiConverterRustBuffer { + typealias SwiftType = PubkySwapError + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PubkySwapError { + let variant: Int32 = try readInt(&buf) + switch variant { + + + + + case 1: return .InvalidInput( + errorDetails: try FfiConverterString.read(from: &buf) + ) + case 2: return .Transport( + errorDetails: try FfiConverterString.read(from: &buf) + ) + case 3: return .Refused( + code: try FfiConverterString.read(from: &buf), + reason: try FfiConverterString.read(from: &buf) + ) + case 4: return .Validation( + errorDetails: try FfiConverterString.read(from: &buf) + ) + case 5: return .Chain( + errorDetails: try FfiConverterString.read(from: &buf) + ) + case 6: return .Storage( + errorDetails: try FfiConverterString.read(from: &buf) + ) + case 7: return .NotFound( + errorDetails: try FfiConverterString.read(from: &buf) + ) + + default: throw UniffiInternalError.unexpectedEnumCase + } + } + + public static func write(_ value: PubkySwapError, into buf: inout [UInt8]) { + switch value { + + + + + + case let .InvalidInput(errorDetails): + writeInt(&buf, Int32(1)) + FfiConverterString.write(errorDetails, into: &buf) + + + case let .Transport(errorDetails): + writeInt(&buf, Int32(2)) + FfiConverterString.write(errorDetails, into: &buf) + + + case let .Refused(code,reason): + writeInt(&buf, Int32(3)) + FfiConverterString.write(code, into: &buf) + FfiConverterString.write(reason, into: &buf) + + + case let .Validation(errorDetails): + writeInt(&buf, Int32(4)) + FfiConverterString.write(errorDetails, into: &buf) + + case let .Chain(errorDetails): + writeInt(&buf, Int32(5)) + FfiConverterString.write(errorDetails, into: &buf) + - case .signup: - writeInt(&buf, Int32(2)) + case let .Storage(errorDetails): + writeInt(&buf, Int32(6)) + FfiConverterString.write(errorDetails, into: &buf) + + case let .NotFound(errorDetails): + writeInt(&buf, Int32(7)) + FfiConverterString.write(errorDetails, into: &buf) + } } } @@ -25681,141 +26833,124 @@ public struct FfiConverterTypePubkyAuthKind: FfiConverterRustBuffer { #if swift(>=5.8) @_documentation(visibility: private) #endif -public func FfiConverterTypePubkyAuthKind_lift(_ buf: RustBuffer) throws -> PubkyAuthKind { - return try FfiConverterTypePubkyAuthKind.lift(buf) +public func FfiConverterTypePubkySwapError_lift(_ buf: RustBuffer) throws -> PubkySwapError { + return try FfiConverterTypePubkySwapError.lift(buf) } #if swift(>=5.8) @_documentation(visibility: private) #endif -public func FfiConverterTypePubkyAuthKind_lower(_ value: PubkyAuthKind) -> RustBuffer { - return FfiConverterTypePubkyAuthKind.lower(value) +public func FfiConverterTypePubkySwapError_lower(_ value: PubkySwapError) -> RustBuffer { + return FfiConverterTypePubkySwapError.lower(value) } -extension PubkyAuthKind: Equatable, Hashable {} +extension PubkySwapError: Equatable, Hashable {} -extension PubkyAuthKind: Codable {} +extension PubkySwapError: Codable {} +extension PubkySwapError: Foundation.LocalizedError { + public var errorDescription: String? { + String(reflecting: self) + } +} + -public enum PubkyError: Swift.Error { +// Note that we don't yet support `indirect` for enums. +// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion. +public enum PubkySwapRouteState { - - case InvalidCapabilities(reason: String - ) - case AuthFailed(reason: String - ) - case NoActiveFlow - case ResolutionFailed(reason: String - ) - case FetchFailed(reason: String + /** + * Waiting for the hold invoice to be paid. + */ + case awaitingPayment + /** + * Paid; waiting for the provider's on-chain lockup, or for its confirmations. + */ + case awaitingLockup(confirmations: UInt32, required: UInt32 ) - case ProfileNotFound - case ProfileParseFailed(reason: String + /** + * The claim to the contact's address is broadcast but not confirmed yet. The provider settles + * the invoice once it sees the preimage; keep calling until the claim confirms. + */ + case claimBroadcast(txid: String ) - case KeyError(reason: String + /** + * The claim to the contact's address is confirmed. + */ + case claimed(txid: String ) - case WriteFailed(reason: String + case failed(reason: String ) } +#if compiler(>=6) +extension PubkySwapRouteState: Sendable {} +#endif + #if swift(>=5.8) @_documentation(visibility: private) #endif -public struct FfiConverterTypePubkyError: FfiConverterRustBuffer { - typealias SwiftType = PubkyError +public struct FfiConverterTypePubkySwapRouteState: FfiConverterRustBuffer { + typealias SwiftType = PubkySwapRouteState - public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PubkyError { + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PubkySwapRouteState { let variant: Int32 = try readInt(&buf) switch variant { - - + case 1: return .awaitingPayment - case 1: return .InvalidCapabilities( - reason: try FfiConverterString.read(from: &buf) - ) - case 2: return .AuthFailed( - reason: try FfiConverterString.read(from: &buf) - ) - case 3: return .NoActiveFlow - case 4: return .ResolutionFailed( - reason: try FfiConverterString.read(from: &buf) - ) - case 5: return .FetchFailed( - reason: try FfiConverterString.read(from: &buf) - ) - case 6: return .ProfileNotFound - case 7: return .ProfileParseFailed( - reason: try FfiConverterString.read(from: &buf) - ) - case 8: return .KeyError( - reason: try FfiConverterString.read(from: &buf) - ) - case 9: return .WriteFailed( - reason: try FfiConverterString.read(from: &buf) - ) - - default: throw UniffiInternalError.unexpectedEnumCase + case 2: return .awaitingLockup(confirmations: try FfiConverterUInt32.read(from: &buf), required: try FfiConverterUInt32.read(from: &buf) + ) + + case 3: return .claimBroadcast(txid: try FfiConverterString.read(from: &buf) + ) + + case 4: return .claimed(txid: try FfiConverterString.read(from: &buf) + ) + + case 5: return .failed(reason: try FfiConverterString.read(from: &buf) + ) + + default: throw UniffiInternalError.unexpectedEnumCase } } - public static func write(_ value: PubkyError, into buf: inout [UInt8]) { + public static func write(_ value: PubkySwapRouteState, into buf: inout [UInt8]) { switch value { - - - - case let .InvalidCapabilities(reason): + case .awaitingPayment: writeInt(&buf, Int32(1)) - FfiConverterString.write(reason, into: &buf) - - case let .AuthFailed(reason): + + case let .awaitingLockup(confirmations,required): writeInt(&buf, Int32(2)) - FfiConverterString.write(reason, into: &buf) + FfiConverterUInt32.write(confirmations, into: &buf) + FfiConverterUInt32.write(required, into: &buf) - case .NoActiveFlow: + case let .claimBroadcast(txid): writeInt(&buf, Int32(3)) + FfiConverterString.write(txid, into: &buf) + - - case let .ResolutionFailed(reason): + case let .claimed(txid): writeInt(&buf, Int32(4)) - FfiConverterString.write(reason, into: &buf) + FfiConverterString.write(txid, into: &buf) - case let .FetchFailed(reason): + case let .failed(reason): writeInt(&buf, Int32(5)) FfiConverterString.write(reason, into: &buf) - - case .ProfileNotFound: - writeInt(&buf, Int32(6)) - - - case let .ProfileParseFailed(reason): - writeInt(&buf, Int32(7)) - FfiConverterString.write(reason, into: &buf) - - - case let .KeyError(reason): - writeInt(&buf, Int32(8)) - FfiConverterString.write(reason, into: &buf) - - - case let .WriteFailed(reason): - writeInt(&buf, Int32(9)) - FfiConverterString.write(reason, into: &buf) - } } } @@ -25824,30 +26959,23 @@ public struct FfiConverterTypePubkyError: FfiConverterRustBuffer { #if swift(>=5.8) @_documentation(visibility: private) #endif -public func FfiConverterTypePubkyError_lift(_ buf: RustBuffer) throws -> PubkyError { - return try FfiConverterTypePubkyError.lift(buf) +public func FfiConverterTypePubkySwapRouteState_lift(_ buf: RustBuffer) throws -> PubkySwapRouteState { + return try FfiConverterTypePubkySwapRouteState.lift(buf) } #if swift(>=5.8) @_documentation(visibility: private) #endif -public func FfiConverterTypePubkyError_lower(_ value: PubkyError) -> RustBuffer { - return FfiConverterTypePubkyError.lower(value) +public func FfiConverterTypePubkySwapRouteState_lower(_ value: PubkySwapRouteState) -> RustBuffer { + return FfiConverterTypePubkySwapRouteState.lower(value) } -extension PubkyError: Equatable, Hashable {} - -extension PubkyError: Codable {} - +extension PubkySwapRouteState: Equatable, Hashable {} +extension PubkySwapRouteState: Codable {} -extension PubkyError: Foundation.LocalizedError { - public var errorDescription: String? { - String(reflecting: self) - } -} @@ -30683,6 +31811,31 @@ fileprivate struct FfiConverterSequenceTypePubkyProfileLink: FfiConverterRustBuf } } +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +fileprivate struct FfiConverterSequenceTypePubkySwapSentPayment: FfiConverterRustBuffer { + typealias SwiftType = [PubkySwapSentPayment] + + public static func write(_ value: [PubkySwapSentPayment], into buf: inout [UInt8]) { + let len = Int32(value.count) + writeInt(&buf, len) + for item in value { + FfiConverterTypePubkySwapSentPayment.write(item, into: &buf) + } + } + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [PubkySwapSentPayment] { + let len: Int32 = try readInt(&buf) + var seq = [PubkySwapSentPayment]() + seq.reserveCapacity(Int(len)) + for _ in 0 ..< len { + seq.append(try FfiConverterTypePubkySwapSentPayment.read(from: &buf)) + } + return seq + } +} + #if swift(>=5.8) @_documentation(visibility: private) #endif @@ -30733,6 +31886,31 @@ fileprivate struct FfiConverterSequenceTypeSupportedHardwareWallet: FfiConverter } } +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +fileprivate struct FfiConverterSequenceTypeSwapRouteEdge: FfiConverterRustBuffer { + typealias SwiftType = [SwapRouteEdge] + + public static func write(_ value: [SwapRouteEdge], into buf: inout [UInt8]) { + let len = Int32(value.count) + writeInt(&buf, len) + for item in value { + FfiConverterTypeSwapRouteEdge.write(item, into: &buf) + } + } + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [SwapRouteEdge] { + let len: Int32 = try readInt(&buf) + var seq = [SwapRouteEdge]() + seq.reserveCapacity(Int(len)) + for _ in 0 ..< len { + seq.append(try FfiConverterTypeSwapRouteEdge.read(from: &buf)) + } + return seq + } +} + #if swift(>=5.8) @_documentation(visibility: private) #endif @@ -33311,6 +34489,108 @@ public func pubkySignUp(secretKeyHex: String, homeserverPublicKeyZ32: String, si errorHandler: FfiConverterTypePubkyError_lift ) } +/** + * Advance a committed route: once the provider's lockup has its confirmations, claim it to the + * contact's address. Call after paying the hold invoice, until it reports `Claimed`. + */ +public func pubkySwapsAdvance(swapId: String, mnemonic: String, bip39Passphrase: String?)async throws -> PubkySwapRouteStatus { + return + try await uniffiRustCallAsync( + rustFutureFunc: { + uniffi_bitkitcore_fn_func_pubky_swaps_advance(FfiConverterString.lower(swapId),FfiConverterString.lower(mnemonic),FfiConverterOptionString.lower(bip39Passphrase) + ) + }, + pollFunc: ffi_bitkitcore_rust_future_poll_rust_buffer, + completeFunc: ffi_bitkitcore_rust_future_complete_rust_buffer, + freeFunc: ffi_bitkitcore_rust_future_free_rust_buffer, + liftFunc: FfiConverterTypePubkySwapRouteStatus_lift, + errorHandler: FfiConverterTypePubkySwapError_lift + ) +} +/** + * Commit to a routed quote and get the hold invoice to pay. The provider's contract and invoice + * are checked against the quote and the wallet's own keys before they are returned. + */ +public func pubkySwapsCommitRoute(quoteId: String, electrumUrl: String, mnemonic: String, bip39Passphrase: String?)async throws -> PubkySwapRoutePayment { + return + try await uniffiRustCallAsync( + rustFutureFunc: { + uniffi_bitkitcore_fn_func_pubky_swaps_commit_route(FfiConverterString.lower(quoteId),FfiConverterString.lower(electrumUrl),FfiConverterString.lower(mnemonic),FfiConverterOptionString.lower(bip39Passphrase) + ) + }, + pollFunc: ffi_bitkitcore_rust_future_poll_rust_buffer, + completeFunc: ffi_bitkitcore_rust_future_complete_rust_buffer, + freeFunc: ffi_bitkitcore_rust_future_free_rust_buffer, + liftFunc: FfiConverterTypePubkySwapRoutePayment_lift, + errorHandler: FfiConverterTypePubkySwapError_lift + ) +} +/** + * The `swap/1` edges a Pubky Swaps provider advertises right now, read from its live offer + * over iroh. The wallet's swap identity is derived from `mnemonic`. + */ +public func pubkySwapsProviderEdges(providerPubky: String, mnemonic: String, bip39Passphrase: String?)async throws -> [SwapRouteEdge] { + return + try await uniffiRustCallAsync( + rustFutureFunc: { + uniffi_bitkitcore_fn_func_pubky_swaps_provider_edges(FfiConverterString.lower(providerPubky),FfiConverterString.lower(mnemonic),FfiConverterOptionString.lower(bip39Passphrase) + ) + }, + pollFunc: ffi_bitkitcore_rust_future_poll_rust_buffer, + completeFunc: ffi_bitkitcore_rust_future_complete_rust_buffer, + freeFunc: ffi_bitkitcore_rust_future_free_rust_buffer, + liftFunc: FfiConverterSequenceTypeSwapRouteEdge.lift, + errorHandler: FfiConverterTypePubkySwapError_lift + ) +} +/** + * Rebuild the swaps this wallet started, for a wallet restored from its seed. Each of + * `providers` that supports it lists the swaps it holds for the wallet's swap identity, and the + * wallet derives their keys from the seed and checks them against each contract. A swap gets a + * record only when `sent_payments`, the Lightning payments the wallet's node sent and whether + * each settled, holds its hash for no more than its lockup plus the most fees the wallet accepts. The contact's address is not + * in the listing, so a restored swap claims to `payout_address`, the wallet's own. Drive each + * restored and known swap with `pubky_swaps_advance`; restore again for an incomplete provider. + */ +public func pubkySwapsRestore(providers: [String], sentPayments: [PubkySwapSentPayment], electrumUrl: String, payoutAddress: String, feeRateSatVb: UInt64, network: Network, mnemonic: String, bip39Passphrase: String?)async throws -> PubkySwapRestoreReport { + return + try await uniffiRustCallAsync( + rustFutureFunc: { + uniffi_bitkitcore_fn_func_pubky_swaps_restore(FfiConverterSequenceString.lower(providers),FfiConverterSequenceTypePubkySwapSentPayment.lower(sentPayments),FfiConverterString.lower(electrumUrl),FfiConverterString.lower(payoutAddress),FfiConverterUInt64.lower(feeRateSatVb),FfiConverterTypeNetwork_lower(network),FfiConverterString.lower(mnemonic),FfiConverterOptionString.lower(bip39Passphrase) + ) + }, + pollFunc: ffi_bitkitcore_rust_future_poll_rust_buffer, + completeFunc: ffi_bitkitcore_rust_future_complete_rust_buffer, + freeFunc: ffi_bitkitcore_rust_future_free_rust_buffer, + liftFunc: FfiConverterTypePubkySwapRestoreReport_lift, + errorHandler: FfiConverterTypePubkySwapError_lift + ) +} +/** + * Pick how to pay a Paykit contact. Returns `Direct` when a balance the wallet holds reaches + * one of the contact's endpoints, otherwise the cheaper of the request's service legs and the + * trusted Pubky Swaps providers' firm quotes, or `None` with a reason. The user never picks + * the route. + * + * Each candidate in `request.providers`, at most 30, is asked for its offer over iroh. iroh finds + * a candidate's address through n0's discovery servers, so n0 sees the keys looked up from the + * wallet's swap identity and IP: pass candidates the user expects to route through, not every + * contact, where that matters. + */ +public func pubkySwapsRoutePaykitPayment(request: PaykitRouteRequest, network: Network, mnemonic: String, bip39Passphrase: String?)async throws -> PaykitRoute { + return + try await uniffiRustCallAsync( + rustFutureFunc: { + uniffi_bitkitcore_fn_func_pubky_swaps_route_paykit_payment(FfiConverterTypePaykitRouteRequest_lower(request),FfiConverterTypeNetwork_lower(network),FfiConverterString.lower(mnemonic),FfiConverterOptionString.lower(bip39Passphrase) + ) + }, + pollFunc: ffi_bitkitcore_rust_future_poll_rust_buffer, + completeFunc: ffi_bitkitcore_rust_future_complete_rust_buffer, + freeFunc: ffi_bitkitcore_rust_future_free_rust_buffer, + liftFunc: FfiConverterTypePaykitRoute_lift, + errorHandler: FfiConverterTypePubkySwapError_lift + ) +} /** * Persist a successful outgoing RBF result, including its replacement fee rate, in one transaction. * Call after the node has returned the replacement txid; this function does not broadcast anything. @@ -34955,6 +36235,21 @@ private let initializationResult: InitializationResult = { if (uniffi_bitkitcore_checksum_func_pubky_sign_up() != 61692) { return InitializationResult.apiChecksumMismatch } + if (uniffi_bitkitcore_checksum_func_pubky_swaps_advance() != 27871) { + return InitializationResult.apiChecksumMismatch + } + if (uniffi_bitkitcore_checksum_func_pubky_swaps_commit_route() != 4882) { + return InitializationResult.apiChecksumMismatch + } + if (uniffi_bitkitcore_checksum_func_pubky_swaps_provider_edges() != 4359) { + return InitializationResult.apiChecksumMismatch + } + if (uniffi_bitkitcore_checksum_func_pubky_swaps_restore() != 44531) { + return InitializationResult.apiChecksumMismatch + } + if (uniffi_bitkitcore_checksum_func_pubky_swaps_route_paykit_payment() != 45030) { + return InitializationResult.apiChecksumMismatch + } if (uniffi_bitkitcore_checksum_func_record_rbf_boost() != 15433) { return InitializationResult.apiChecksumMismatch } diff --git a/bindings/ios/bitkitcoreFFI.h b/bindings/ios/bitkitcoreFFI.h index cdbede1d..d3e08292 100644 --- a/bindings/ios/bitkitcoreFFI.h +++ b/bindings/ios/bitkitcoreFFI.h @@ -1576,6 +1576,31 @@ uint64_t uniffi_bitkitcore_fn_func_pubky_sign_in(RustBuffer secret_key_hex uint64_t uniffi_bitkitcore_fn_func_pubky_sign_up(RustBuffer secret_key_hex, RustBuffer homeserver_public_key_z32, RustBuffer signup_code ); #endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_SWAPS_ADVANCE +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_SWAPS_ADVANCE +uint64_t uniffi_bitkitcore_fn_func_pubky_swaps_advance(RustBuffer swap_id, RustBuffer mnemonic, RustBuffer bip39_passphrase +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_SWAPS_COMMIT_ROUTE +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_SWAPS_COMMIT_ROUTE +uint64_t uniffi_bitkitcore_fn_func_pubky_swaps_commit_route(RustBuffer quote_id, RustBuffer electrum_url, RustBuffer mnemonic, RustBuffer bip39_passphrase +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_SWAPS_PROVIDER_EDGES +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_SWAPS_PROVIDER_EDGES +uint64_t uniffi_bitkitcore_fn_func_pubky_swaps_provider_edges(RustBuffer provider_pubky, RustBuffer mnemonic, RustBuffer bip39_passphrase +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_SWAPS_RESTORE +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_SWAPS_RESTORE +uint64_t uniffi_bitkitcore_fn_func_pubky_swaps_restore(RustBuffer providers, RustBuffer sent_payments, RustBuffer electrum_url, RustBuffer payout_address, uint64_t fee_rate_sat_vb, RustBuffer network, RustBuffer mnemonic, RustBuffer bip39_passphrase +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_SWAPS_ROUTE_PAYKIT_PAYMENT +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_SWAPS_ROUTE_PAYKIT_PAYMENT +uint64_t uniffi_bitkitcore_fn_func_pubky_swaps_route_paykit_payment(RustBuffer request, RustBuffer network, RustBuffer mnemonic, RustBuffer bip39_passphrase +); +#endif #ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_RECORD_RBF_BOOST #define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_RECORD_RBF_BOOST void uniffi_bitkitcore_fn_func_record_rbf_boost(RustBuffer wallet_id, RustBuffer original_activity_id, RustBuffer replacement_tx_id, uint64_t fee_rate, RustCallStatus *_Nonnull out_status @@ -3186,6 +3211,36 @@ uint16_t uniffi_bitkitcore_checksum_func_pubky_sign_in(void #define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_SIGN_UP uint16_t uniffi_bitkitcore_checksum_func_pubky_sign_up(void +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_SWAPS_ADVANCE +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_SWAPS_ADVANCE +uint16_t uniffi_bitkitcore_checksum_func_pubky_swaps_advance(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_SWAPS_COMMIT_ROUTE +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_SWAPS_COMMIT_ROUTE +uint16_t uniffi_bitkitcore_checksum_func_pubky_swaps_commit_route(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_SWAPS_PROVIDER_EDGES +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_SWAPS_PROVIDER_EDGES +uint16_t uniffi_bitkitcore_checksum_func_pubky_swaps_provider_edges(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_SWAPS_RESTORE +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_SWAPS_RESTORE +uint16_t uniffi_bitkitcore_checksum_func_pubky_swaps_restore(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_SWAPS_ROUTE_PAYKIT_PAYMENT +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_SWAPS_ROUTE_PAYKIT_PAYMENT +uint16_t uniffi_bitkitcore_checksum_func_pubky_swaps_route_paykit_payment(void + ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_RECORD_RBF_BOOST diff --git a/src/lib.rs b/src/lib.rs index fec78d90..2acecc48 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -54,6 +54,10 @@ pub use crate::modules::jade::{ JadeTransportReadResult, JadeTransportResult, JadeVersionInfo, JadeXpubResponse, }; use crate::modules::pubky::{PubkyAuthDetails, PubkyAuthKind, PubkyError, PubkyProfile}; +use crate::modules::pubky_swaps::{ + self as pubky_swaps, PubkySwapError, PubkySwapRestoreReport, PubkySwapRoutePayment, + PubkySwapRouteStatus, PubkySwapSentPayment, SwapRouteEdge, +}; use crate::modules::trezor::account_type_to_script_type; pub use crate::modules::trezor::{ get_transport_callback, trezor_is_ble_available, trezor_set_transport_callback, @@ -517,6 +521,9 @@ pub fn init_db(base_path: String) -> Result { let blocktank_db = rt .block_on(async { BlocktankDB::new(&format!("{}/blocktank.db", base_path), None).await })?; let boltz_db = rt.block_on(async { BoltzDB::new(&format!("{}/boltz.db", base_path)).await })?; + modules::pubky_swaps::init(&base_path).map_err(|e| DbError::InitializationError { + error_details: e.to_string(), + })?; // Initialize sync database { @@ -2113,6 +2120,11 @@ pub async fn wipe_all_databases() -> Result { .await .unwrap()?; + // Wipe pubky swaps records + modules::pubky_swaps::wipe_all().map_err(|e| DbError::InitializationError { + error_details: format!("Failed to wipe pubky swaps records: {}", e), + })?; + Ok("All databases wiped successfully".to_string()) } @@ -3774,6 +3786,124 @@ pub async fn boltz_stop_swap_updates() { .await; } +// ============================================================================ +// Pubky Swaps as Paykit routes +// ============================================================================ + +fn pubky_swaps_runtime_err(e: tokio::task::JoinError) -> PubkySwapError { + PubkySwapError::Transport { + error_details: format!("Runtime error: {}", e), + } +} + +/// The `swap/1` edges a Pubky Swaps provider advertises right now, read from its live offer +/// over iroh. The wallet's swap identity is derived from `mnemonic`. +#[uniffi::export] +pub async fn pubky_swaps_provider_edges( + provider_pubky: String, + mnemonic: String, + bip39_passphrase: Option, +) -> Result, PubkySwapError> { + let rt = ensure_runtime(); + rt.spawn(async move { + pubky_swaps::provider_edges(provider_pubky, mnemonic, bip39_passphrase).await + }) + .await + .unwrap_or_else(|e| Err(pubky_swaps_runtime_err(e))) +} + +/// Pick how to pay a Paykit contact. Returns `Direct` when a balance the wallet holds reaches +/// one of the contact's endpoints, otherwise the cheaper of the request's service legs and the +/// trusted Pubky Swaps providers' firm quotes, or `None` with a reason. The user never picks +/// the route. +/// +/// Each candidate in `request.providers`, at most 30, is asked for its offer over iroh. iroh finds +/// a candidate's address through n0's discovery servers, so n0 sees the keys looked up from the +/// wallet's swap identity and IP: pass candidates the user expects to route through, not every +/// contact, where that matters. +#[uniffi::export] +pub async fn pubky_swaps_route_paykit_payment( + request: PaykitRouteRequest, + network: Network, + mnemonic: String, + bip39_passphrase: Option, +) -> Result { + let rt = ensure_runtime(); + rt.spawn(async move { + pubky_swaps::route_paykit_payment(request, network.into(), mnemonic, bip39_passphrase).await + }) + .await + .unwrap_or_else(|e| Err(pubky_swaps_runtime_err(e))) +} + +/// Commit to a routed quote and get the hold invoice to pay. The provider's contract and invoice +/// are checked against the quote and the wallet's own keys before they are returned. +#[uniffi::export] +pub async fn pubky_swaps_commit_route( + quote_id: String, + electrum_url: String, + mnemonic: String, + bip39_passphrase: Option, +) -> Result { + let rt = ensure_runtime(); + rt.spawn(async move { + pubky_swaps::commit_route(quote_id, electrum_url, mnemonic, bip39_passphrase).await + }) + .await + .unwrap_or_else(|e| Err(pubky_swaps_runtime_err(e))) +} + +/// Advance a committed route: once the provider's lockup has its confirmations, claim it to the +/// contact's address. Call after paying the hold invoice, until it reports `Claimed`. +#[uniffi::export] +pub async fn pubky_swaps_advance( + swap_id: String, + mnemonic: String, + bip39_passphrase: Option, +) -> Result { + let rt = ensure_runtime(); + rt.spawn(async move { pubky_swaps::advance_swap(swap_id, mnemonic, bip39_passphrase).await }) + .await + .unwrap_or_else(|e| Err(pubky_swaps_runtime_err(e))) +} + +/// Rebuild the swaps this wallet started, for a wallet restored from its seed. Each of +/// `providers` that supports it lists the swaps it holds for the wallet's swap identity, and the +/// wallet derives their keys from the seed and checks them against each contract. A swap gets a +/// record only when `sent_payments`, the Lightning payments the wallet's node sent and whether +/// each settled, holds its hash for no more than its lockup plus the most fees the wallet accepts. The contact's address is not +/// in the listing, so a restored swap claims to `payout_address`, the wallet's own. Drive each +/// restored and known swap with `pubky_swaps_advance`; restore again for an incomplete provider. +#[uniffi::export] +#[allow(clippy::too_many_arguments)] +pub async fn pubky_swaps_restore( + providers: Vec, + sent_payments: Vec, + electrum_url: String, + payout_address: String, + fee_rate_sat_vb: u64, + network: Network, + mnemonic: String, + bip39_passphrase: Option, +) -> Result { + let rt = ensure_runtime(); + rt.spawn(async move { + pubky_swaps::restore_swaps( + providers, + sent_payments, + electrum_url, + payout_address, + fee_rate_sat_vb, + network.into(), + mnemonic, + bip39_passphrase, + ) + .await + }) + .await + .unwrap_or_else(|e| Err(pubky_swaps_runtime_err(e))) +} + /// Pick how to pay a Paykit contact: `Direct` when a balance the wallet holds reaches one of the /// contact's endpoints, otherwise the cheapest of the request's service legs, or `None` with a /// reason. The user never picks the route. @@ -3924,4 +4054,25 @@ mod tests { std::fs::remove_dir_all(&base_path).ok(); } + + #[tokio::test] + async fn test_wipe_all_databases_removes_swap_records() { + let base_path = std::env::temp_dir().join(format!( + "bitkitcore_wipe_all_test_{}", + rand::random::() + )); + std::fs::create_dir_all(&base_path).unwrap(); + init_db(base_path.to_string_lossy().into_owned()).unwrap(); + + let swap_dir = base_path.join("pubky_swaps"); + let test_swap_file = swap_dir.join("test_swap_123.json"); + std::fs::write(&test_swap_file, b"{\"swap_id\":\"test_swap_123\"}").unwrap(); + assert!(test_swap_file.exists()); + + let result = wipe_all_databases().await; + assert!(result.is_ok()); + assert!(!test_swap_file.exists()); + + std::fs::remove_dir_all(&base_path).ok(); + } } diff --git a/src/modules/mod.rs b/src/modules/mod.rs index f7533a66..42c1f76d 100644 --- a/src/modules/mod.rs +++ b/src/modules/mod.rs @@ -7,6 +7,7 @@ pub mod lnurl; pub mod onchain; pub mod paykit_route; pub mod pubky; +pub mod pubky_swaps; pub mod scanner; pub mod seedqr; pub mod trezor; diff --git a/src/modules/paykit_route/mod.rs b/src/modules/paykit_route/mod.rs index a90c3a75..98b441db 100644 --- a/src/modules/paykit_route/mod.rs +++ b/src/modules/paykit_route/mod.rs @@ -6,4 +6,5 @@ mod types; pub use errors::PaykitRouteError; pub use router::route_payment; +pub(crate) use router::{network_label, onchain_endpoint}; pub use types::{PaykitEndpoint, PaykitRoute, PaykitRouteRequest, ServiceRouteLeg}; diff --git a/src/modules/paykit_route/router.rs b/src/modules/paykit_route/router.rs index b0fb6cd0..b55a58ac 100644 --- a/src/modules/paykit_route/router.rs +++ b/src/modules/paykit_route/router.rs @@ -16,7 +16,7 @@ const ONCHAIN_PREFERENCE: [&str; 4] = ["p2tr", "p2wpkh", "p2sh", "p2pkh"]; /// The rail segment of an on-chain Payment Endpoint Identifier, as the apps publish it. The /// spec has no Testnet4 rail, so a Testnet4 wallet routes nothing on chain. -fn network_label(network: bitcoin::Network) -> Option<&'static str> { +pub(crate) fn network_label(network: bitcoin::Network) -> Option<&'static str> { match network { bitcoin::Network::Bitcoin => Some("bitcoin"), bitcoin::Network::Regtest => Some("regtest"), @@ -99,7 +99,7 @@ fn lightning_endpoint( }) } -fn onchain_endpoint( +pub(crate) fn onchain_endpoint( endpoints: &[PaykitEndpoint], network: bitcoin::Network, ) -> Option<&PaykitEndpoint> { @@ -230,6 +230,8 @@ mod tests { lightning_spendable_sat: lightning, onchain_spendable_sat: onchain, service_legs: legs, + providers: vec![], + fee_rate_sat_vb: 2, } } diff --git a/src/modules/paykit_route/types.rs b/src/modules/paykit_route/types.rs index 1cf062fa..2667d307 100644 --- a/src/modules/paykit_route/types.rs +++ b/src/modules/paykit_route/types.rs @@ -1,5 +1,7 @@ use serde::{Deserialize, Serialize}; +use crate::modules::pubky_swaps::PubkySwapRouteQuote; + /// A Payment Endpoint the contact published: its Payment Endpoint Identifier, such as /// `btc-lightning-bolt11` or `btc-bitcoin-p2tr`, and the value a payer pays to. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, uniffi::Record)] @@ -24,6 +26,11 @@ pub struct PaykitRouteRequest { /// Legs through services the wallet holds a balance on, such as a Spark withdrawal to the /// contact's on-chain address, each already quoted by the app's engine for that service. pub service_legs: Vec, + /// Candidate Pubky Swaps providers as pubkys, usually the user's contacts. Only + /// `pubky_swaps_route_paykit_payment` asks them; a contact that runs no provider is skipped. + pub providers: Vec, + /// Fee rate for the wallet's own claim transaction on a swap route. + pub fee_rate_sat_vb: u64, } /// A one-leg route through a service the wallet holds a balance on, such as a Spark withdrawal @@ -51,6 +58,8 @@ pub enum PaykitRoute { Direct { endpoint: PaykitEndpoint }, /// A service the wallet holds a balance on delivers to the contact. The app runs the leg. Service { leg: ServiceRouteLeg }, + /// The wallet pays over Lightning and a Pubky Swaps provider delivers on-chain. + Swap { quote: PubkySwapRouteQuote }, /// Nothing can pay this contact. `reason` is English detail for logs; the app shows its own /// localized text. None { reason: String }, diff --git a/src/modules/pubky/mod.rs b/src/modules/pubky/mod.rs index b52063ac..d16c5d5f 100644 --- a/src/modules/pubky/mod.rs +++ b/src/modules/pubky/mod.rs @@ -10,6 +10,7 @@ mod tests; pub use auth::*; pub use errors::*; pub use keys::*; +pub(crate) use profile::fetch_public_file_if_any; pub use profile::*; pub use resolve::*; pub use session::*; diff --git a/src/modules/pubky/profile.rs b/src/modules/pubky/profile.rs index 3e9f5024..76681969 100644 --- a/src/modules/pubky/profile.rs +++ b/src/modules/pubky/profile.rs @@ -49,6 +49,27 @@ fn is_not_found(err: &impl std::fmt::Display) -> bool { msg.contains("404") || msg.to_lowercase().contains("not found") } +/// Read a public file at `addr` (`/pub/…`), or `None` when it is not published. +pub(crate) async fn fetch_public_file_if_any(addr: &str) -> Result>, PubkyError> { + let pubky = get_pubky()?; + let response = match pubky.public_storage().get(addr).await { + Ok(response) => response, + Err(e) if is_not_found(&e) => return Ok(None), + Err(e) => { + return Err(PubkyError::FetchFailed { + reason: e.to_string(), + }) + } + }; + let bytes = response + .bytes() + .await + .map_err(|e| PubkyError::FetchFailed { + reason: e.to_string(), + })?; + Ok(Some(bytes.to_vec())) +} + /// Fetch and parse a user's `profile.json` by their public key (z32-encoded). pub async fn fetch_pubky_profile(public_key: String) -> Result { let pubky = get_pubky()?; diff --git a/src/modules/pubky_swaps/README.md b/src/modules/pubky_swaps/README.md new file mode 100644 index 00000000..33bdb475 --- /dev/null +++ b/src/modules/pubky_swaps/README.md @@ -0,0 +1,118 @@ +# Pubky Swaps Module + +Routes a Paykit payment through a [Pubky Swaps](https://github.com/coreyphillips/pubky-swap) +provider when no balance the wallet holds reaches an endpoint the contact published. The user +never picks the swap: the router does, and the review screen shows the route. + +The first route is a reverse swap: the wallet pays over Lightning, the provider locks bitcoin on +chain, and this module claims it straight to the contact's on-chain address. The contact receives +exactly the amount asked for (`exact_out`): the lock covers the wallet's own claim fee. + +## Flow + +| Step | Paykit Capabilities | pubky-swap message | Owner | +|------|---------------------|--------------------|-------| +| Pick a route | router (§9.1) | `OfferRequest` → `Offer` | `pubky_swaps_route_paykit_payment` | +| Ask for a price | `rfq` → `quote` | `paykit-cap.rfq` → signed `paykit-cap.quote` | same call, up to 3 providers | +| Commit | `commit` → `contract` | `paykit-cap.commit` → signed `paykit-cap.contract` | `pubky_swaps_commit_route` | +| Fund | funding is the acceptance | hold invoice | **App** pays the invoice from spending | +| Claim | evidence from the rail | claim with the preimage | `pubky_swaps_advance` | + +`pubky_swaps_route_paykit_payment` returns `Direct` when a balance reaches one of the contact's +endpoints, so the app only swaps when it must. + +## Service routes + +The direct-pay check and the service legs live in the `paykit_route` module +(`paykit_route_payment`). `pubky_swaps_route_paykit_payment` runs the same check first; when no +balance reaches the contact, it asks the providers for a swap quote and returns whichever of the +cheapest live service leg and the swap costs less in fees. A swap wins a tie, since a hash lock +needs no one's trust. + +## Signed terms + +Only providers whose offer lists `paykit-cap-v1` and `direct-rpc-v1` are quoted. Quotes and +contracts are signed (Paykit Capabilities §10), and swap-common's `CapClient` checks each one: the +quote's `terms_hash` binds this wallet, the provider, the request and the quote; the contract's +`commit_hash` binds it to this wallet's commit; and the invoice arrives sealed under a hash the +contract signs. A reply must be signed by the provider's own key or by the capability signing key +its published records delegate to (§5): the identity-signed Noise Key Authorization, then the +routing key's delegation for the same generation. Any other signer, and any unsigned reply to a +signed request, is refused. The commit carries the signed quote, so a provider that forgot it can +still honour it, and a provider that holds the swap without its signed contract gets the commit +again. The contract is kept in the swap record. + +The offer itself is unsigned, so it only says who to ask; the signed quote is what the route is +priced on. A restore reads providers' plain listings and checks them against the wallet's own +keys and payments instead. + +Before the invoice reaches the app, the module checks the quote against the request +(`validate_quote`), the contract against the quote and the chain tip (`validate_accept`), rebuilds +the HTLC from its own keys (`verify_contract`), and binds the hold invoice to the quote and the +payment hash (`validate_hold_invoice`). These checks are pubky-swap's own `swap-common`. + +## Transport + +Requests travel over iroh `pubky-swap/direct/1`. The provider authenticates the request by the +connection's key, so neither side needs a homeserver. iroh does need n0's infrastructure: it finds +each candidate's address through n0's discovery servers and publishes the wallet's own there, so +for each payment that needs a swap, n0 sees up to 30 candidate keys looked up from one swap identity +and IP. The caller's candidate list sets that exposure. Published Capability Descriptors +(coreyphillips/pubky-swap#104) would let the router ask only providers, not every contact. Paykit Capabilities §13.1 allows the same +payloads over this carrier. + +## Keys and storage + +- The wallet's identity towards providers derives from the seed. Each swap's claim key and preimage + derive from the seed and a random 32-byte index, with HMAC-SHA512 under their own domain strings, + so a restored wallet or a second device on the same seed never repeats a preimage an earlier + claim published. The keys never collide with the Boltz module's keys, and the identity is not the + user's Pubky identity. +- The index is not secret: the swap request carries it as `owner_ref`, which the provider keeps and + lists back (`swap-list-v1`). +- `/pubky_swaps/.json` holds the contract, the index and the signed claim, whose + witness carries the preimage before the claim is broadcast; it is synced before the invoice + reaches the app, and the claim before it is broadcast. + +## Restore + +`pubky_swaps_restore` rebuilds the swaps a wallet started when it has only its seed. The providers +that advertise `swap-list-v1`, asked at once, list the swaps they hold for the wallet's swap +identity; the wallet derives each swap's keys from the index in its `owner_ref` and checks the +network, the payment hash and the contract against them. The listing is the provider's word, so the +amount is checked against what the wallet holds: a swap gets a record only when the app's +`sent_payments` holds its hash, for no more than the lockup plus the most fees the wallet accepts, +and no other record holds that hash. + +The listing does not carry the contact's address, so a restored swap claims to a payout address the +app passes, the wallet's own. A claim the provider says it saw counts only once the chain shows it +with the preimage in its witness. Until then it counts only when the app's payment for it is +`settled`, so the preimage is public: the wallet then claims again once the lockup has its +confirmations, past the window too. With the payment pending, the listing counts for nothing. Finished swaps, other wallets' swaps and swaps without this wallet's `owner_ref` +get no record. The report names the swaps restored, those already on record, those finished, and +the providers whose list was not read in full, for a later restore. `pubky_swaps_advance` then +drives each restored and known swap. + +## Claim + +`pubky_swaps_advance` claims the lockup once it has its confirmations and while the timeout is more +than 6 blocks away, then reports `ClaimBroadcast` once a server took the claim, until it confirms, +and `Claimed` after. Each call checks the HTLC's history: a claim that dropped out of the mempool is +broadcast again, and a spend without the preimage in its witness (the provider's refund) or a +lockup that never came before the timeout ends in `Failed`. The claim's fee is +fixed when the route is quoted and is never bumped, so swap routes are refused on mainnet. + +## What it does not do yet + +- **Discovery:** candidates come from the caller, usually the user's contacts. Each is asked for + its live offer over iroh; nothing reads published Capability Descriptors yet (§6, §7). +- **Paykit transport:** no `paykit-cap.*` messages over Encrypted Links. paykit-rs has no API to + send extension kinds yet (§17). +- **Signed offers and restores:** offers and restore listings are unsigned; nothing reads the + signed `swap/1` descriptor yet. Messages carry no `key_generation` until the §8.1 envelope lands, + so a delegated signer is checked against the generation published now. +- **Submarine routes** (savings to a Lightning-only contact) and USDT. Pubky Swaps is Bitcoin and + Lightning only. +- **Refunds and recovery:** a reverse swap needs no wallet refund (the provider cancels its hold + invoice). A restore rebuilds swaps from providers' listings, within their retention window, and + claims them to the wallet's own address; swap records are not in the wallet backup. diff --git a/src/modules/pubky_swaps/cap.rs b/src/modules/pubky_swaps/cap.rs new file mode 100644 index 00000000..f01af895 --- /dev/null +++ b/src/modules/pubky_swaps/cap.rs @@ -0,0 +1,446 @@ +//! Signed `swap/1` negotiation (`paykit-cap.*`, Paykit Capabilities §10) with one provider. +//! +//! swap-common's `CapClient` checks every reply: the quote's `terms_hash` and signature against +//! the RFQ and both parties, the contract's `commit_hash` against the commit, its own hash and +//! signature, and the invoice blob. This session adds the signer rule: a reply must be signed by +//! the provider's own key or by the capability signing key its records delegate to (§5), and +//! anything unsigned is refused. + +use std::time::Duration; + +use swap_common::messages::{QuoteRequest, SwapMessage}; +use swap_common::paykit_cap::{ + reply_signer, CapClient, CapError, CapMessage, Parties, SignedQuote, +}; + +use super::delegation; +use super::errors::PubkySwapError; +use super::transport::{bare_pubky, provider_endpoint_id, DirectClient}; + +/// How long a provider's published signing key may take to read. +const DELEGATION_TIMEOUT: Duration = Duration::from_secs(20); + +pub(crate) struct CapSession<'a> { + client: &'a DirectClient, + provider: String, + cap: CapClient, + /// The delegated key this session accepted, if the provider signs with one. + delegated_signer: Option, + /// The commit request of this session, sent again when the provider has the swap but not its + /// signed contract. + commit: Option, +} + +fn cap_error(error: CapError) -> PubkySwapError { + PubkySwapError::validation(format!("provider reply: {error}")) +} + +/// The checker for replies to `owner` from `provider`: the parties every signed quote must name, +/// and the provider's own key as the only signer until a delegation is followed. Never built +/// without an expected signer, which would accept any. +fn checker(owner: &str, provider: &str) -> Result { + let provider = bare_pubky(provider).to_string(); + let root = *provider_endpoint_id(&provider)?.as_bytes(); + let parties = Parties { + owner: bare_pubky(owner).to_string(), + provider, + }; + Ok(CapClient::new(Some(root), parties)) +} + +impl<'a> CapSession<'a> { + /// A session as `owner` (the wallet's bare swap identity) with `provider`, accepting replies + /// signed by the provider's own key. + pub(crate) fn new( + client: &'a DirectClient, + owner: &str, + provider: &str, + ) -> Result { + Ok(Self { + client, + provider: bare_pubky(provider).to_string(), + cap: checker(owner, provider)?, + delegated_signer: None, + commit: None, + }) + } + + /// The delegated key this session accepted, to carry to a later session. + pub(crate) fn delegated_signer(&self) -> Option { + self.delegated_signer.clone() + } + + /// Accept a delegated key a previous session already followed from the provider's records. + pub(crate) fn allow_delegated_signer(&mut self, signer: Option) { + if let Some(signer) = signer { + self.cap.allow_signer(signer.clone()); + self.delegated_signer = Some(signer); + } + } + + /// Check a quote an earlier session received again, so this session can commit to it. + pub(crate) fn remember_quote( + &mut self, + request: &QuoteRequest, + signed: SignedQuote, + ) -> Result<(), PubkySwapError> { + self.cap + .reply( + &SwapMessage::QuoteRequest(request.clone()), + CapMessage::Quote(signed), + ) + .map(|_| ()) + .map_err(cap_error) + } + + /// Send `request` in its signed form and return the checked reply in plain form, with the + /// signed reply it came from. Offers and lists have no signed form and are refused here. + pub(crate) async fn ask( + &mut self, + request: &SwapMessage, + ) -> Result<(SwapMessage, CapMessage), PubkySwapError> { + let message = self.cap.request(request).ok_or_else(|| { + PubkySwapError::validation("this request has no signed form, or no signed quote") + })?; + if matches!(request, SwapMessage::SwapRequest(_)) { + self.commit = Some(request.clone()); + } + let reply = self.client.request_cap(&self.provider, &message).await?; + self.accept_signer(&reply).await; + match self.cap.reply(request, reply.clone()) { + Ok(plain) => Ok((plain, reply)), + // The provider has the swap but no signed contract for it: sending the same commit + // again has it sign and store one. + Err(CapError::MissingContract(commit)) => { + let commit_request = self + .commit + .clone() + .ok_or_else(|| cap_error(CapError::MissingContract(commit.clone())))?; + let reply = self + .client + .request_cap(&self.provider, &CapMessage::Commit(*commit)) + .await?; + self.accept_signer(&reply).await; + let plain = self + .cap + .reply(&commit_request, reply.clone()) + .map_err(cap_error)?; + Ok((plain, reply)) + } + Err(e) => Err(cap_error(e)), + } + } + + /// When a reply is signed by a key other than the provider's own, follow the provider's + /// published records (§5) and accept that key only if they delegate to it. Failing that, the + /// key stays refused and the reply with it. + async fn accept_signer(&mut self, reply: &CapMessage) { + let Some(signer) = reply_signer(reply).map(str::to_string) else { + return; + }; + if self.cap.allows(&signer) { + return; + } + match tokio::time::timeout(DELEGATION_TIMEOUT, delegation::resolve(&self.provider)).await { + Ok(Ok(Some(delegated))) if delegated == signer => { + self.cap.allow_signer(delegated.clone()); + self.delegated_signer = Some(delegated); + } + Ok(Ok(Some(_))) => log::warn!( + "pubky swaps: {} signed with a key its records do not delegate to", + self.provider + ), + Ok(Ok(None)) => log::warn!( + "pubky swaps: {} signed with another key and publishes no delegation", + self.provider + ), + Ok(Err(e)) => log::warn!("pubky swaps: {}'s signing key: {e}", self.provider), + Err(_) => log::warn!("pubky swaps: {}'s signing key took too long", self.provider), + } + } +} + +#[cfg(test)] +mod tests { + use swap_common::messages::{Quote, SwapAccept, SwapRequest, SwapScript, SwapStatusRequest}; + use swap_common::paykit_cap::{ + sign_contract, sign_quote, CommitBody, Ed25519Signer, RfqConstraints, Status, + }; + use swap_common::{NetworkSpec, SwapDirection, SwapState, SwapStatusSnapshot}; + use uuid::Uuid; + + use super::*; + + const PROVIDER_SECRET: [u8; 32] = [1; 32]; + const OWNER_SECRET: [u8; 32] = [2; 32]; + + fn z32(secret: &[u8; 32]) -> String { + pubky::Keypair::from_secret(secret).public_key().to_z32() + } + + fn parties() -> Parties { + Parties { + owner: z32(&OWNER_SECRET), + provider: z32(&PROVIDER_SECRET), + } + } + + fn quote_request() -> QuoteRequest { + QuoteRequest { + request_id: Some(Uuid::from_bytes([3; 16])), + offer_id: Uuid::from_bytes([4; 16]), + client_pkarr: z32(&OWNER_SECRET), + direction: SwapDirection::Reverse, + amount_sat: 20_300, + protocol_version: 0, + features: vec![], + } + } + + fn quote() -> Quote { + Quote { + request_id: None, + quote_id: Uuid::from_bytes([5; 16]), + offer_id: Uuid::from_bytes([4; 16]), + direction: SwapDirection::Reverse, + amount_sat: 20_300, + fee_sat: 300, + service_fee_sat: 150, + onchain_fee_sat: 150, + fee_rate_sat_vb: 2, + total_sat: 20_600, + htlc_timeout_blocks: 144, + required_confirmations: 1, + valid_until_unix: 4_000_000_000, + fund_within_secs: 60, + protocol_version: 0, + } + } + + fn constraints() -> RfqConstraints { + let request = quote_request(); + RfqConstraints { + offer_id: request.offer_id, + direction: request.direction, + amount_sat: request.amount_sat, + } + } + + fn signed_by(secret: &[u8; 32]) -> SignedQuote { + sign_quote( + &Ed25519Signer::from_secret(secret), + &parties(), + &constraints(), + "e(), + ) + .unwrap() + } + + fn swap_request() -> SwapRequest { + SwapRequest { + script_type: SwapScript::P2wsh, + quote_id: quote().quote_id, + client_pkarr: z32(&OWNER_SECRET), + direction: SwapDirection::Reverse, + payment_hash_hex: "aa".repeat(32), + client_claim_pubkey_hex: Some("02".to_string() + &"bb".repeat(32)), + client_refund_pubkey_hex: None, + invoice: None, + owner_ref: Some("ref".into()), + } + } + + fn accept() -> SwapAccept { + SwapAccept { + script_type: SwapScript::P2wsh, + swap_tree: None, + quote_id: quote().quote_id, + swap_id: Uuid::from_bytes([6; 16]), + direction: SwapDirection::Reverse, + htlc_script_hex: String::new(), + htlc_address: String::new(), + onchain_amount_sat: 20_300, + timeout_block_height: 1_144, + provider_pubkey_hex: "03".to_string() + &"cc".repeat(32), + invoice: Some("lnbcrt-hold-invoice".into()), + } + } + + /// A checker that holds the signed quote, and the commit it sends for it. + fn committed() -> (CapClient, SwapMessage) { + let mut cap = checker(&z32(&OWNER_SECRET), &z32(&PROVIDER_SECRET)).unwrap(); + cap.reply( + &SwapMessage::QuoteRequest(quote_request()), + CapMessage::Quote(signed_by(&PROVIDER_SECRET)), + ) + .unwrap(); + let request = SwapMessage::SwapRequest(swap_request()); + assert!(matches!(cap.request(&request), Some(CapMessage::Commit(_)))); + (cap, request) + } + + fn contract_over(terms_hash: &str, commit: &CommitBody) -> ContractReplyFixture { + sign_contract( + &Ed25519Signer::from_secret(&PROVIDER_SECRET), + terms_hash, + commit, + &accept(), + ) + .unwrap() + } + + type ContractReplyFixture = swap_common::paykit_cap::ContractReply; + + fn our_contract() -> ContractReplyFixture { + contract_over( + &signed_by(&PROVIDER_SECRET).terms_hash, + &CommitBody::from_request(&swap_request()), + ) + } + + #[test] + fn takes_a_quote_signed_by_the_provider() { + let mut cap = checker(&z32(&OWNER_SECRET), &z32(&PROVIDER_SECRET)).unwrap(); + let reply = cap.reply( + &SwapMessage::QuoteRequest(quote_request()), + CapMessage::Quote(signed_by(&PROVIDER_SECRET)), + ); + assert!(matches!(reply, Ok(SwapMessage::Quote(q)) if q.quote_id == quote().quote_id)); + } + + #[test] + fn refuses_a_quote_signed_by_another_key_until_it_is_delegated() { + let other = [9; 32]; + let request = SwapMessage::QuoteRequest(quote_request()); + let mut cap = checker(&z32(&OWNER_SECRET), &z32(&PROVIDER_SECRET)).unwrap(); + assert!(matches!( + cap.reply(&request, CapMessage::Quote(signed_by(&other))), + Err(CapError::UnexpectedSigner) + )); + // Only a key the provider's records delegate to is added. + cap.allow_signer(hex::encode( + ed25519_dalek::SigningKey::from_bytes(&other) + .verifying_key() + .to_bytes(), + )); + assert!(cap + .reply(&request, CapMessage::Quote(signed_by(&other))) + .is_ok()); + } + + #[test] + fn refuses_a_tampered_quote() { + let request = SwapMessage::QuoteRequest(quote_request()); + let mut cheaper = signed_by(&PROVIDER_SECRET); + cheaper.quote.total_sat -= 1; + let mut renamed = signed_by(&PROVIDER_SECRET); + renamed.terms_hash = "00".repeat(32); + for tampered in [cheaper, renamed] { + let mut cap = checker(&z32(&OWNER_SECRET), &z32(&PROVIDER_SECRET)).unwrap(); + assert!(cap.reply(&request, CapMessage::Quote(tampered)).is_err()); + } + // A quote issued to another wallet does not name this one. + let mut cap = checker(&z32(&[8; 32]), &z32(&PROVIDER_SECRET)).unwrap(); + assert!(cap + .reply(&request, CapMessage::Quote(signed_by(&PROVIDER_SECRET))) + .is_err()); + } + + #[test] + fn takes_a_contract_signed_over_this_commit() { + let (mut cap, request) = committed(); + let reply = cap.reply(&request, CapMessage::Contract(our_contract())); + assert!(matches!( + reply, + Ok(SwapMessage::SwapAccept(a)) if a.invoice.as_deref() == Some("lnbcrt-hold-invoice") + )); + } + + #[test] + fn refuses_a_contract_over_another_commit_or_tampered() { + let terms_hash = signed_by(&PROVIDER_SECRET).terms_hash; + let mut other_commit = CommitBody::from_request(&swap_request()); + other_commit.payment_hash_hex = "dd".repeat(32); + let mut tampered = our_contract(); + tampered.signed.contract.accept.onchain_amount_sat -= 1; + let mut other_blob = our_contract(); + other_blob.invoice_blob = contract_over(&terms_hash, &other_commit).invoice_blob; + other_blob.invoice_blob.as_mut().unwrap().ciphertext = "00".repeat(40); + for contract in [ + contract_over(&terms_hash, &other_commit), + tampered, + other_blob, + ] { + let (mut cap, request) = committed(); + assert!(cap.reply(&request, CapMessage::Contract(contract)).is_err()); + } + } + + #[test] + fn refuses_a_contract_before_a_signed_quote() { + let mut cap = checker(&z32(&OWNER_SECRET), &z32(&PROVIDER_SECRET)).unwrap(); + let request = SwapMessage::SwapRequest(swap_request()); + // No signed quote, so no signed form to send and nothing to check a contract against. + assert!(cap.request(&request).is_none()); + assert!(cap + .reply(&request, CapMessage::Contract(our_contract())) + .is_err()); + } + + fn status(snapshot_accept: SwapAccept, contract: Option) -> CapMessage { + CapMessage::Status(Box::new(Status { + request_id: None, + swap_id: Some(snapshot_accept.swap_id), + quote_id: Some(snapshot_accept.quote_id), + state: "lockup_confirmed".into(), + reference: None, + snapshot: Some(SwapStatusSnapshot { + request_id: None, + accept: SwapAccept { + invoice: None, + ..snapshot_accept + }, + network: NetworkSpec::Regtest, + state: SwapState::LockupConfirmed, + funding_txid_hex: None, + funding_vout: None, + spend_txid_hex: None, + claim_observed_txid_hex: None, + required_confirmations: 1, + updated_at_unix: 0, + observed_at_unix: 0, + created_at_unix: 0, + payment_hash_hex: "aa".repeat(32), + owner_ref: None, + claimable: false, + }), + contract, + })) + } + + #[test] + fn checks_a_status_against_the_contract_over_this_commit() { + let request = SwapMessage::SwapStatusRequest(SwapStatusRequest { + request_id: None, + swap_id: None, + quote_id: Some(quote().quote_id), + }); + let (mut cap, _) = committed(); + assert!(cap + .reply(&request, status(accept(), Some(our_contract()))) + .is_ok()); + // A snapshot that differs from what the contract signed. + let mut moved = accept(); + moved.onchain_amount_sat -= 1; + let (mut cap, _) = committed(); + assert!(cap + .reply(&request, status(moved, Some(our_contract()))) + .is_err()); + // No contract for a committed swap: the session sends the commit again. + let (mut cap, _) = committed(); + assert!(matches!( + cap.reply(&request, status(accept(), None)), + Err(CapError::MissingContract(_)) + )); + } +} diff --git a/src/modules/pubky_swaps/claim.rs b/src/modules/pubky_swaps/claim.rs new file mode 100644 index 00000000..86d4b558 --- /dev/null +++ b/src/modules/pubky_swaps/claim.rs @@ -0,0 +1,457 @@ +//! What `pubky_swaps_advance` does next for a reverse swap, decided from the HTLC's script history +//! (mempool included) and the chain tip, so the claim path can be checked without a chain. + +use bitcoin::{OutPoint, ScriptBuf, Transaction}; +use swap_common::onchain::extract_preimage; +use swap_common::timelock::claim_start_is_safe; + +use super::types::PubkySwapRouteState; + +/// The contract as the wallet rebuilt it from its own keys. +pub(crate) struct Contract<'a> { + pub htlc_spk: &'a ScriptBuf, + pub lock_sat: u64, + /// The hash the claim's witness reveals the preimage of. Only the claim path carries it, so it + /// tells our claim from the provider's refund whatever either pays. + pub payment_hash: &'a [u8; 32], + pub timeout: u32, + pub required_confirmations: u32, +} + +#[derive(Debug, PartialEq)] +pub(crate) enum Step { + /// Report this state; nothing to do. + Report(PubkySwapRouteState), + /// Our claim spends the lockup; record `txid` if the record names another, and report. + Claimed { + txid: String, + state: PubkySwapRouteState, + }, + /// The saved claim is not in the history: broadcast it again, or a new claim of this lockup + /// when the record holds none (a restored swap whose claim the provider listed). Once a claim + /// was published its preimage is public, so it goes out whatever the window; before that, only + /// inside it. + Rebroadcast { + outpoint: OutPoint, + confirmations: u32, + }, + /// Build, save and broadcast the claim of this lockup. + Claim { + outpoint: OutPoint, + confirmations: u32, + }, +} + +/// A claim the record holds, and whether its preimage ever left the wallet. +pub(crate) struct SavedClaim { + pub published: bool, +} + +/// `listed_claim`: the provider listed a claim of this swap that the history does not show, and the +/// wallet's node shows the payment settled, so the preimage is public. +pub(crate) fn next_step( + contract: &Contract, + saved_claim: Option, + listed_claim: bool, + tip: u32, + history: &[(i32, Transaction)], +) -> Step { + let confirmations_at = |height: i32| { + if height > 0 { + tip.saturating_sub(height as u32) + 1 + } else { + 0 + } + }; + let lockup = history.iter().find_map(|(height, tx)| { + let vout = tx.output.iter().position(|out| { + out.script_pubkey == *contract.htlc_spk && out.value.to_sat() == contract.lock_sat + })?; + Some(( + OutPoint::new(tx.compute_txid(), vout as u32), + confirmations_at(*height), + )) + }); + let Some((outpoint, confirmations)) = lockup else { + return Step::Report(if tip >= contract.timeout { + PubkySwapRouteState::Failed { + reason: "The provider never locked funds before the timeout. Its hold invoice is \ + cancelled and the payment returns." + .into(), + } + } else { + PubkySwapRouteState::AwaitingLockup { + confirmations: 0, + required: contract.required_confirmations, + } + }); + }; + + let spend = history.iter().find(|(_, tx)| { + tx.input + .iter() + .any(|input| input.previous_output == outpoint) + }); + if let Some((height, tx)) = spend { + // A claim reveals the preimage in its witness and a refund cannot, so this holds for a + // claim sent from another device too, whatever it pays. + if extract_preimage(tx, &outpoint, contract.payment_hash).is_none() { + return Step::Report(PubkySwapRouteState::Failed { + reason: "The provider refunded its lockup instead of the claim.".into(), + }); + } + let txid = tx.compute_txid().to_string(); + let state = if confirmations_at(*height) > 0 { + PubkySwapRouteState::Claimed { txid: txid.clone() } + } else { + PubkySwapRouteState::ClaimBroadcast { txid: txid.clone() } + }; + return Step::Claimed { txid, state }; + } + + let safe_to_reveal = claim_start_is_safe(tip, contract.timeout); + if let Some(claim) = saved_claim { + // A claim never sent still keeps its preimage: like a new one, it waits for the lockup's + // confirmations, which a reorganization can take back after the claim was saved. + if claim.published || (safe_to_reveal && confirmations >= contract.required_confirmations) { + return Step::Rebroadcast { + outpoint, + confirmations, + }; + } + } + // A listed claim whose payment settled gets no early reveal either: the lockup could still be + // replaced. Once it has its confirmations, the claim goes out whatever the window, as the + // settled payment shows the preimage is public. A listing with the payment pending counts for + // nothing, since past the window a claim would hand the provider the preimage and its refund. + if listed_claim { + if confirmations < contract.required_confirmations { + return Step::Report(PubkySwapRouteState::AwaitingLockup { + confirmations, + required: contract.required_confirmations, + }); + } + return Step::Rebroadcast { + outpoint, + confirmations, + }; + } + if !safe_to_reveal { + return Step::Report(PubkySwapRouteState::Failed { + reason: format!( + "The lockup times out at block {}, too close to claim safely at block {tip}. \ + The provider's refund returns the payment.", + contract.timeout + ), + }); + } + if confirmations < contract.required_confirmations { + return Step::Report(PubkySwapRouteState::AwaitingLockup { + confirmations, + required: contract.required_confirmations, + }); + } + Step::Claim { + outpoint, + confirmations, + } +} + +#[cfg(test)] +mod tests { + use bitcoin::absolute::LockTime; + use bitcoin::hashes::{sha256, Hash}; + use bitcoin::transaction::Version; + use bitcoin::{Amount, Sequence, TxIn, TxOut, Witness}; + + use super::*; + + const LOCK: u64 = 20_200; + const TIMEOUT: u32 = 1_144; + const PREIMAGE: [u8; 32] = [5; 32]; + + fn spk(byte: u8) -> ScriptBuf { + ScriptBuf::from_bytes(vec![0x00, 0x14].into_iter().chain([byte; 20]).collect()) + } + + fn tx(inputs: Vec, witness: Witness, outputs: Vec<(ScriptBuf, u64)>) -> Transaction { + Transaction { + version: Version::TWO, + lock_time: LockTime::ZERO, + input: inputs + .into_iter() + .map(|previous_output| TxIn { + previous_output, + script_sig: ScriptBuf::new(), + sequence: Sequence::ENABLE_RBF_NO_LOCKTIME, + witness: witness.clone(), + }) + .collect(), + output: outputs + .into_iter() + .map(|(script_pubkey, sats)| TxOut { + value: Amount::from_sat(sats), + script_pubkey, + }) + .collect(), + } + } + + /// A claim's witness: signature, preimage, script. A refund's: signature, empty, script. + fn witness(second: &[u8]) -> Witness { + Witness::from_slice(&[vec![0x30; 71], second.to_vec(), vec![0x63; 90]]) + } + + struct Fixture { + htlc: ScriptBuf, + payment_hash: [u8; 32], + lockup: Transaction, + } + + impl Fixture { + fn new() -> Self { + let htlc = spk(1); + let lockup = tx( + vec![OutPoint::null()], + Witness::new(), + vec![(spk(9), 5_000), (htlc.clone(), LOCK)], + ); + Self { + htlc, + payment_hash: sha256::Hash::hash(&PREIMAGE).to_byte_array(), + lockup, + } + } + + fn contract(&self) -> Contract<'_> { + Contract { + htlc_spk: &self.htlc, + lock_sat: LOCK, + payment_hash: &self.payment_hash, + timeout: TIMEOUT, + required_confirmations: 1, + } + } + + fn outpoint(&self) -> OutPoint { + OutPoint::new(self.lockup.compute_txid(), 1) + } + + /// A claim to the contact. + fn claim(&self) -> Transaction { + self.claim_to(spk(2)) + } + + fn claim_to(&self, destination: ScriptBuf) -> Transaction { + tx( + vec![self.outpoint()], + witness(&PREIMAGE), + vec![(destination, 20_000)], + ) + } + + fn refund_to(&self, outputs: Vec<(ScriptBuf, u64)>) -> Transaction { + tx(vec![self.outpoint()], witness(&[]), outputs) + } + + fn refund(&self) -> Transaction { + self.refund_to(vec![(spk(3), 20_000)]) + } + + /// A saved claim that already reached the server. + fn step(&self, saved: Option<&str>, tip: u32, history: &[(i32, Transaction)]) -> Step { + let saved = saved.map(|_| SavedClaim { published: true }); + next_step(&self.contract(), saved, false, tip, history) + } + + fn step_unpublished(&self, tip: u32, history: &[(i32, Transaction)]) -> Step { + let saved = SavedClaim { published: false }; + next_step(&self.contract(), Some(saved), false, tip, history) + } + + /// A restored swap whose claim the provider listed, unproven. + fn step_listed(&self, tip: u32, history: &[(i32, Transaction)]) -> Step { + next_step(&self.contract(), None, true, tip, history) + } + + fn rebroadcast(&self, confirmations: u32) -> Step { + Step::Rebroadcast { + outpoint: self.outpoint(), + confirmations, + } + } + + fn claim_step(&self, confirmations: u32) -> Step { + Step::Claim { + outpoint: self.outpoint(), + confirmations, + } + } + } + + fn is_failed(step: Step) -> bool { + matches!(step, Step::Report(PubkySwapRouteState::Failed { .. })) + } + + #[test] + fn waits_for_a_lockup_until_the_timeout_then_fails() { + let f = Fixture::new(); + assert_eq!( + f.step(None, TIMEOUT - 1, &[]), + Step::Report(PubkySwapRouteState::AwaitingLockup { + confirmations: 0, + required: 1 + }) + ); + assert!(is_failed(f.step(None, TIMEOUT, &[]))); + } + + #[test] + fn waits_for_the_lockup_confirmations() { + let f = Fixture::new(); + assert_eq!( + f.step(None, 1_000, &[(0, f.lockup.clone())]), + Step::Report(PubkySwapRouteState::AwaitingLockup { + confirmations: 0, + required: 1 + }) + ); + assert_eq!( + f.step(None, 1_000, &[(1_000, f.lockup.clone())]), + f.claim_step(1) + ); + } + + #[test] + fn leaves_a_lockup_too_close_to_the_timeout_to_the_refund() { + let f = Fixture::new(); + let history = [(1_000, f.lockup.clone())]; + assert_eq!(f.step(None, TIMEOUT - 7, &history), f.claim_step(138)); + assert!(is_failed(f.step(None, TIMEOUT - 6, &history))); + } + + #[test] + fn reports_the_claim_as_broadcast_until_it_confirms() { + let f = Fixture::new(); + let claim = f.claim(); + let txid = claim.compute_txid().to_string(); + let lockup = (1_000, f.lockup.clone()); + assert_eq!( + f.step(Some(&txid), 1_001, &[lockup.clone(), (0, claim.clone())]), + Step::Claimed { + txid: txid.clone(), + state: PubkySwapRouteState::ClaimBroadcast { txid: txid.clone() } + } + ); + assert_eq!( + f.step(Some(&txid), 1_002, &[lockup, (1_002, claim)]), + Step::Claimed { + txid: txid.clone(), + state: PubkySwapRouteState::Claimed { txid } + } + ); + } + + #[test] + fn fails_when_the_provider_refunds_even_after_the_claim_went_out() { + let f = Fixture::new(); + let history = [(1_000, f.lockup.clone()), (1_200, f.refund())]; + let saved = f.claim().compute_txid().to_string(); + for saved in [None, Some(saved.as_str())] { + assert!(is_failed(f.step(saved, 1_200, &history))); + } + } + + #[test] + fn broadcasts_a_saved_claim_again_once_it_left_the_mempool() { + let f = Fixture::new(); + let saved = f.claim().compute_txid().to_string(); + // Also past the claim window: the preimage is public, so the claim must go out. + assert_eq!( + f.step(Some(&saved), TIMEOUT - 1, &[(1_000, f.lockup.clone())]), + f.rebroadcast(144) + ); + } + + #[test] + fn claims_a_listed_claim_again_only_once_the_lockup_confirmed() { + let f = Fixture::new(); + // Unconfirmed: a provider could have listed any txid to get the preimage revealed early. + assert_eq!( + f.step_listed(1_000, &[(0, f.lockup.clone())]), + Step::Report(PubkySwapRouteState::AwaitingLockup { + confirmations: 0, + required: 1 + }) + ); + // Confirmed: the listed claim may have made the preimage public, so claim past the window. + assert_eq!( + f.step_listed(TIMEOUT + 5, &[(1_000, f.lockup.clone())]), + f.rebroadcast(150) + ); + } + + #[test] + fn records_a_claim_from_another_device_whatever_it_pays() { + let f = Fixture::new(); + // The original device claimed to the contact, whose address a restored record lacks. + let claim = f.claim_to(spk(7)); + let txid = claim.compute_txid().to_string(); + for listed in [false, true] { + assert_eq!( + next_step( + &f.contract(), + None, + listed, + 1_001, + &[(1_000, f.lockup.clone()), (0, claim.clone())] + ), + Step::Claimed { + txid: txid.clone(), + state: PubkySwapRouteState::ClaimBroadcast { txid: txid.clone() } + } + ); + } + } + + #[test] + fn keeps_an_unpublished_claim_private_once_the_window_closed() { + let f = Fixture::new(); + let history = [(1_000, f.lockup.clone())]; + assert_eq!( + f.step_unpublished(TIMEOUT - 7, &history), + f.rebroadcast(138) + ); + assert!(is_failed(f.step_unpublished(TIMEOUT + 5, &history))); + // A reorganization left the lockup unconfirmed: the unsent claim waits for it again. + assert_eq!( + f.step_unpublished(1_000, &[(0, f.lockup.clone())]), + Step::Report(PubkySwapRouteState::AwaitingLockup { + confirmations: 0, + required: 1 + }) + ); + } + + #[test] + fn reports_a_refund_that_pays_the_contact_as_failed() { + let f = Fixture::new(); + let history = |refund| [(1_000, f.lockup.clone()), (TIMEOUT as i32 + 1, refund)]; + // Dust to the contact, or exactly what the claim would have paid: neither is our claim. + let dust = f.refund_to(vec![(spk(3), 19_000), (spk(2), 546)]); + let exact = f.refund_to(vec![(spk(2), 20_000)]); + let saved = exact.compute_txid().to_string(); + assert!(is_failed(f.step(None, TIMEOUT + 5, &history(dust)))); + assert!(is_failed(f.step( + Some(&saved), + TIMEOUT + 5, + &history(exact) + ))); + } + + #[test] + fn fails_an_unconfirmed_lockup_past_the_timeout() { + let f = Fixture::new(); + assert!(is_failed(f.step(None, 2_000, &[(0, f.lockup.clone())]))); + } +} diff --git a/src/modules/pubky_swaps/client.rs b/src/modules/pubky_swaps/client.rs new file mode 100644 index 00000000..1ae502d5 --- /dev/null +++ b/src/modules/pubky_swaps/client.rs @@ -0,0 +1,1588 @@ +//! The `swap/1` flow for a Paykit payment: route, commit, claim. +//! +//! Message mapping (Paykit Capabilities §13.1): `rfq` is pubky-swap's `QuoteRequest`, `quote` +//! is `Quote`, `commit` is `SwapRequest`, `contract` is `SwapAccept`, `refusal` is `Reject`. +//! Here they travel over iroh `direct/1`, which §13.1 allows for the same payloads. + +use std::collections::HashMap; +use std::str::FromStr; +use std::sync::Mutex; +use std::time::{SystemTime, UNIX_EPOCH}; + +use bitcoin::{Address, OutPoint, ScriptBuf}; +use electrum_client::{Client as ElectrumClient, ConfigBuilder, ElectrumApi}; +use once_cell::sync::Lazy; +use swap_common::htlc::build_htlc_script; +use swap_common::messages::{ + OfferRequest, Quote, QuoteRequest, Reject, SwapAccept, SwapListRequest, SwapMessage, SwapOffer, + SwapRequest, SwapScript, SwapStatusRequest, SwapStatusSnapshot, PAYKIT_CAP_FEATURE, + PROTOCOL_VERSION, SWAP_LIST_FEATURE, +}; +use swap_common::onchain::{build_claim_tx, estimate_spend_fee, spend_vsize}; +use swap_common::paykit_cap::{CapMessage, ContractReply, SignedQuote}; +use swap_common::timelock::TimelockParams; +use swap_common::validate::{ + min_reverse_lockup_sat, validate_accept, validate_hold_invoice, validate_quote, + verify_contract, ClientPolicy, DecodedHoldInvoice, +}; +use swap_common::SwapDirection; +use uuid::Uuid; + +use super::cap::CapSession; +use super::claim; +use super::errors::PubkySwapError; +use super::keys; +use super::router; +use super::store::{self, SwapRecord}; +use super::transport::{bare_pubky, DirectClient}; +use super::types::*; +use crate::modules::paykit_route; + +/// The offer feature for requests over `direct/1`, which signed negotiation needs beside +/// `paykit-cap-v1`. swap-common names no constant for it. +const DIRECT_RPC_FEATURE: &str = "direct-rpc-v1"; +/// How long a candidate provider has to answer an offer request. +const OFFER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20); +/// Most candidates asked for an offer per payment: each is a connection and an address lookup +/// through iroh's n0 discovery, which sees which keys the wallet looks up. +const MAX_CANDIDATES: usize = 30; +const ELECTRUM_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); +/// How long the wallet keeps asking about a swap request the provider is still admitting. +const PENDING_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60); +const PENDING_POLL: std::time::Duration = std::time::Duration::from_secs(2); +/// Most pages read from one provider's swap list on restore. +const MAX_LIST_PAGES: usize = 100; + +/// Quotes the router fetched, kept until the wallet commits to one of them. +static QUOTES: Lazy>> = Lazy::new(Default::default); + +#[derive(Clone)] +struct CachedQuote { + route: PubkySwapRouteQuote, + quote: Quote, + network: bitcoin::Network, + /// The signed quote and the request it answered, which the commit carries and is checked + /// against. + request: QuoteRequest, + signed: SignedQuote, + /// The delegated key the quote was signed by, if not the provider's own. + delegated_signer: Option, +} + +/// A quote whose signature checked out, with what committing to it needs. +struct SignedRoute { + quote: Quote, + request: QuoteRequest, + signed: SignedQuote, + delegated_signer: Option, +} + +fn now_unix() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +fn policy(network: bitcoin::Network) -> ClientPolicy { + ClientPolicy::for_network(network, TimelockParams::default()) +} + +fn refused(reject: Reject) -> PubkySwapError { + PubkySwapError::Refused { + code: reject.code.unwrap_or_else(|| "unknown".into()), + reason: reject.reason, + } +} + +fn unexpected(what: &str, got: &SwapMessage) -> PubkySwapError { + PubkySwapError::transport(format!("expected {what}, got {got:?}")) +} + +fn identity_pubky(secret: &[u8; 32]) -> String { + pubky::Keypair::from_secret(secret).public_key().to_z32() +} + +fn parse_address(address: &str, network: bitcoin::Network) -> Result { + Address::from_str(address) + .map_err(|e| PubkySwapError::invalid(format!("address: {e}")))? + .require_network(network) + .map_err(|e| PubkySwapError::invalid(format!("address: {e}"))) +} + +/// The wallet's fee for claiming the provider's lockup to `destination`. +fn claim_fee(destination: &ScriptBuf, fee_rate_sat_vb: u64) -> Result { + // Only the shape matters for the size: a real contract has the same lengths. + let key = keys::swap_keys( + "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", + None, + &[0; 32], + )?; + let script = build_htlc_script(&[0; 32], &key.claim_pubkey, &key.claim_pubkey, 1_000_000); + Ok(estimate_spend_fee( + fee_rate_sat_vb.max(1), + spend_vsize(&script, destination, true), + )) +} + +async fn fetch_offer(client: &DirectClient, provider: &str) -> Result { + let request = SwapMessage::OfferRequest(OfferRequest { + request_id: Some(Uuid::new_v4()), + }); + match client.request(provider, &request).await? { + SwapMessage::Offer(offer) => Ok(offer), + SwapMessage::Reject(reject) => Err(refused(reject)), + other => Err(unexpected("Offer", &other)), + } +} + +/// The `swap/1` edges a provider advertises right now. +pub async fn provider_edges( + provider: String, + mnemonic: String, + bip39_passphrase: Option, +) -> Result, PubkySwapError> { + let secret = keys::identity_secret(&mnemonic, bip39_passphrase.as_deref())?; + let client = DirectClient::bind(secret).await?; + let offer = fetch_offer(&client, bare_pubky(&provider)).await; + client.close().await; + Ok(router::edges_from_offer(&offer?)) +} + +/// A signed quote for `lock_sat` from `offer`'s provider (`paykit-cap.rfq`), refused unless it +/// is signed by the provider's key or the key it delegates to, and binds this wallet, the +/// provider and the request. +async fn quote_edge( + client: &DirectClient, + identity: &str, + offer: &SwapOffer, + lock_sat: u64, + network: bitcoin::Network, +) -> Result { + let request = QuoteRequest { + request_id: Some(Uuid::new_v4()), + offer_id: offer.offer_id, + client_pkarr: identity.to_string(), + direction: SwapDirection::Reverse, + amount_sat: lock_sat, + protocol_version: PROTOCOL_VERSION, + features: vec![], + }; + let mut session = CapSession::new(client, identity, &offer.provider_pkarr)?; + let (reply, signed) = session + .ask(&SwapMessage::QuoteRequest(request.clone())) + .await?; + let (quote, signed) = match (reply, signed) { + (SwapMessage::Quote(quote), CapMessage::Quote(signed)) => (quote, signed), + (SwapMessage::Reject(reject), _) => return Err(refused(reject)), + (other, _) => return Err(unexpected("Quote", &other)), + }; + validate_quote("e, &request, now_unix(), &policy(network)) + .map_err(PubkySwapError::validation)?; + Ok(SignedRoute { + quote, + request, + signed, + delegated_signer: session.delegated_signer(), + }) +} + +/// Whether an offer takes signed negotiation over `direct/1`. Others are skipped: their quotes +/// and contracts would be unsigned. +fn negotiates_signed(offer: &SwapOffer) -> bool { + [PAYKIT_CAP_FEATURE, DIRECT_RPC_FEATURE] + .iter() + .all(|feature| offer.features.iter().any(|f| f == feature)) +} + +/// Pick the route for a Paykit payment. The user never picks a swap: one is used only when no +/// rail the wallet holds reaches an endpoint the contact published. +pub async fn route_paykit_payment( + request: PaykitRouteRequest, + network: bitcoin::Network, + mnemonic: String, + bip39_passphrase: Option, +) -> Result { + let service = match paykit_route::route_payment(&request, network, now_unix()) + .map_err(PubkySwapError::invalid)? + { + PaykitRoute::Service { leg } => Some(leg), + PaykitRoute::None { .. } => None, + route => return Ok(route), + }; + let onchain = paykit_route::onchain_endpoint(&request.contact_endpoints, network).cloned(); + let swap = match &onchain { + Some(onchain) if !request.providers.is_empty() => { + match best_swap_route( + &request, + onchain.clone(), + network, + &mnemonic, + bip39_passphrase.as_deref(), + ) + .await + { + Ok(swap) => swap, + Err(e) if service.is_some() => { + log::warn!("pubky swaps: no swap route, paying through a service: {e}"); + None + } + Err(e) => return Err(e), + } + } + _ => None, + }; + Ok( + router::cheaper_route(service, swap).unwrap_or_else(|| PaykitRoute::None { + reason: if onchain.is_none() { + "No balance can reach an endpoint this contact accepts." + } else if request.providers.is_empty() { + "No swap provider is set up." + } else if network == bitcoin::Network::Bitcoin { + "Swap routes are not available on mainnet yet." + } else { + "No swap provider can route this payment right now." + } + .into(), + }), + ) +} + +/// The cheapest firm quote from the trusted Pubky Swaps providers for delivering the request's +/// amount to `onchain`, cached for `commit_route`. +async fn best_swap_route( + request: &PaykitRouteRequest, + onchain: PaykitEndpoint, + network: bitcoin::Network, + mnemonic: &str, + bip39_passphrase: Option<&str>, +) -> Result, PubkySwapError> { + // The claim is broadcast at one fee and only rebroadcast, never bumped: until it can be, a + // claim stuck below the market could lose the whole debit, so mainnet takes no swap route. + // Service legs still route there. + if network == bitcoin::Network::Bitcoin { + return Ok(None); + } + let amount = request.amount_sat; + let destination = parse_address(&onchain.value, network)?.script_pubkey(); + let claim_fee_sat = claim_fee(&destination, request.fee_rate_sat_vb)?; + let lock_sat = amount + claim_fee_sat; + + let secret = keys::identity_secret(mnemonic, bip39_passphrase)?; + let identity = identity_pubky(&secret); + let client = DirectClient::bind(secret).await?; + + let mut offers = HashMap::new(); + let mut edges = vec![]; + // Candidates are usually the user's contacts, and most of them run no provider: ask them all at + // once and give each a short window to answer. + let mut probes = tokio::task::JoinSet::new(); + // In the caller's order, so the cap keeps configured providers listed first. + let mut seen = std::collections::HashSet::new(); + let candidates: Vec = request + .providers + .iter() + .map(|p| bare_pubky(p).to_string()) + .filter(|p| seen.insert(p.clone())) + .take(MAX_CANDIDATES) + .collect(); + for provider in candidates { + let client = client.clone(); + probes.spawn(async move { + let offer = tokio::time::timeout(OFFER_TIMEOUT, fetch_offer(&client, &provider)).await; + (provider, offer) + }); + } + while let Some(probe) = probes.join_next().await { + let Ok((provider, offer)) = probe else { + continue; + }; + match offer { + Ok(Ok(offer)) if bare_pubky(&offer.provider_pkarr) != provider => { + log::warn!("pubky swaps: {provider} answered with another provider's offer") + } + Ok(Ok(offer)) if !negotiates_signed(&offer) => { + log::warn!("pubky swaps: {provider} does not sign its quotes; skipping it") + } + Ok(Ok(offer)) if offer.network.to_bitcoin_network() == network => { + edges.extend(router::edges_from_offer(&offer)); + offers.insert(offer.provider_pkarr.clone(), offer); + } + Ok(Ok(_)) => log::warn!("pubky swaps: provider {provider} is on another network"), + Ok(Err(e)) => log::debug!("pubky swaps: no offer from {provider}: {e}"), + Err(_) => log::debug!("pubky swaps: {provider} did not answer in time"), + } + } + let ranked = router::rank_reverse_edges( + edges, + &onchain.method_id, + lock_sat, + request.lightning_spendable_sat, + policy(network).max_fee_bps, + ); + let asked = ranked.len() as u32; + + let mut best: Option<(SignedRoute, String)> = None; + for edge in &ranked { + let Some(offer) = offers.get(&edge.provider_pubky) else { + continue; + }; + match quote_edge(&client, &identity, offer, lock_sat, network).await { + Ok(signed) if signed.quote.total_sat <= request.lightning_spendable_sat => { + if best + .as_ref() + .is_none_or(|(b, _)| signed.quote.total_sat < b.quote.total_sat) + { + best = Some((signed, edge.provider_pubky.clone())); + } + } + Ok(_) => {} + Err(e) => log::warn!("pubky swaps: no quote from {}: {e}", edge.provider_pubky), + } + } + client.close().await; + + let Some((signed, provider)) = best else { + return Ok(None); + }; + let quote = signed.quote.clone(); + let route = PubkySwapRouteQuote { + provider_pubky: provider, + // The wallet's own id for this route: two providers may pick the same quote id. + quote_id: Uuid::new_v4().to_string(), + endpoint: onchain, + delivered_sat: amount, + lock_sat, + debit_sat: quote.total_sat, + service_fee_sat: quote.service_fee_sat, + provider_onchain_fee_sat: quote.onchain_fee_sat, + claim_fee_sat, + total_fee_sat: quote.total_sat.saturating_sub(amount), + atomicity: "hash".into(), + valid_until_unix: quote.valid_until_unix, + providers_quoted: asked, + }; + let mut quotes = QUOTES.lock().unwrap(); + let now = now_unix(); + quotes.retain(|_, cached| !cached.quote.is_expired(now)); + quotes.insert( + route.quote_id.clone(), + CachedQuote { + route: route.clone(), + quote, + network, + request: signed.request, + signed: signed.signed, + delegated_signer: signed.delegated_signer, + }, + ); + Ok(Some(route)) +} + +fn is_pending(reply: &Result<(SwapMessage, CapMessage), PubkySwapError>) -> bool { + matches!(reply, Ok((SwapMessage::Reject(reject), _)) if reject.code.as_deref() == Some("pending")) +} + +/// Commit to a signed quote (`paykit-cap.commit`) and return the acceptance from the signed +/// contract, with that contract. The quote is checked again first, and the contract must be +/// signed by the same keys, over this commit. +#[allow(clippy::too_many_arguments)] +async fn signed_commit( + client: &DirectClient, + identity: &str, + provider: &str, + quote_request: &QuoteRequest, + signed: SignedQuote, + delegated_signer: Option, + request: SwapRequest, +) -> Result<(SwapAccept, ContractReply), PubkySwapError> { + let quote_id = request.quote_id; + let mut session = CapSession::new(client, identity, provider)?; + session.allow_delegated_signer(delegated_signer); + session.remember_quote(quote_request, signed)?; + let mut reply = session.ask(&SwapMessage::SwapRequest(request)).await; + // `pending` means the provider is still admitting it, never a decline: keep asking until it + // accepts or refuses. Past the deadline the wallet gives up without paying anything. + let deadline = tokio::time::Instant::now() + PENDING_TIMEOUT; + while is_pending(&reply) && tokio::time::Instant::now() < deadline { + tokio::time::sleep(PENDING_POLL).await; + let status = SwapMessage::SwapStatusRequest(SwapStatusRequest { + request_id: Some(Uuid::new_v4()), + swap_id: None, + quote_id: Some(quote_id), + }); + reply = session.ask(&status).await; + } + match reply? { + (SwapMessage::SwapAccept(accept), CapMessage::Contract(contract)) => Ok((accept, contract)), + (SwapMessage::SwapStatusSnapshot(snapshot), CapMessage::Status(status)) => { + // A status the session checked carries the contract signed over this commit. + let contract = status + .contract + .ok_or_else(|| PubkySwapError::validation("status without a signed contract"))?; + Ok((snapshot.accept, contract)) + } + (SwapMessage::Reject(reject), _) => Err(refused(reject)), + (other, _) => Err(unexpected("SwapAccept", &other)), + } +} + +fn decode_hold_invoice(invoice: &str) -> Result { + let invoice = lightning_invoice::Bolt11Invoice::from_str(invoice) + .map_err(|e| PubkySwapError::validation(format!("hold invoice: {e}")))?; + let amount_msat = invoice.amount_milli_satoshis(); + let expires_at = invoice + .expires_at() + .map(|d| d.as_secs()) + .unwrap_or_default(); + Ok(DecodedHoldInvoice { + payment_hash: *invoice.payment_hash().as_ref(), + amount_msat: amount_msat.unwrap_or_default(), + amount_is_explicit: amount_msat.is_some(), + expires_at_unix: expires_at, + }) +} + +/// An Electrum client whose reads time out, so a connection that dies silently cannot hold a swap. +fn electrum(url: &str) -> Result { + electrum_with_retries(url, 1) +} + +fn electrum_with_retries(url: &str, retries: u8) -> Result { + let config = ConfigBuilder::new() + .timeout(Some(ELECTRUM_TIMEOUT)) + .retry(retries) + .build(); + Ok(ElectrumClient::from_config(url, config)?) +} + +fn chain_tip(electrum_url: &str) -> Result { + let client = electrum(electrum_url)?; + Ok(client.block_headers_subscribe()?.height as u32) +} + +/// Commit to a routed quote. Returns the hold invoice the wallet pays over Lightning; nothing +/// is funded before that payment. +pub async fn commit_route( + quote_id: String, + electrum_url: String, + mnemonic: String, + bip39_passphrase: Option, +) -> Result { + let cached = QUOTES + .lock() + .unwrap() + .get("e_id) + .cloned() + .ok_or_else(|| PubkySwapError::NotFound { + error_details: format!("quote {quote_id}"), + })?; + let CachedQuote { + route, + quote, + network, + request: quote_request, + signed, + delegated_signer, + } = cached; + if network == bitcoin::Network::Bitcoin { + return Err(PubkySwapError::invalid( + "Swap routes are not available on mainnet yet.", + )); + } + if quote.is_expired(now_unix()) { + return Err(PubkySwapError::Refused { + code: "quote_expired".into(), + reason: "The quote expired. Route the payment again.".into(), + }); + } + let passphrase = bip39_passphrase.as_deref(); + let secret = keys::identity_secret(&mnemonic, passphrase)?; + let index = keys::new_index(); + let swap_keys = keys::swap_keys(&mnemonic, passphrase, &index)?; + let request = SwapRequest { + script_type: SwapScript::P2wsh, + quote_id: quote.quote_id, + client_pkarr: identity_pubky(&secret), + direction: SwapDirection::Reverse, + payment_hash_hex: hex::encode(swap_keys.payment_hash), + client_claim_pubkey_hex: Some(swap_keys.claim_pubkey.to_string()), + client_refund_pubkey_hex: None, + invoice: None, + owner_ref: Some(keys::owner_ref(&index)), + }; + + let client = DirectClient::bind(secret).await?; + let committed = signed_commit( + &client, + &identity_pubky(&secret), + &route.provider_pubky, + "e_request, + signed, + delegated_signer, + request, + ) + .await; + client.close().await; + let (accept, contract) = committed?; + // `advance` watches and spends only the P2WSH contract the request asked for. + if accept.script_type != SwapScript::P2wsh { + return Err(PubkySwapError::validation(format!( + "the provider answered with a {:?} contract, not P2WSH", + accept.script_type + ))); + } + + let tip = { + let url = electrum_url.clone(); + tokio::task::spawn_blocking(move || chain_tip(&url)) + .await + .map_err(PubkySwapError::chain)?? + }; + let policy = policy(network); + validate_accept(&accept, "e, Some(tip), &policy).map_err(PubkySwapError::validation)?; + let htlc_spk = verify_contract( + &accept, + SwapDirection::Reverse, + &swap_keys.payment_hash, + &swap_keys.claim_pubkey, + network, + ) + .map_err(PubkySwapError::validation)?; + let invoice = accept + .invoice + .clone() + .ok_or_else(|| PubkySwapError::validation("the contract has no hold invoice"))?; + validate_hold_invoice( + &decode_hold_invoice(&invoice)?, + "e, + &swap_keys.payment_hash, + now_unix(), + &policy, + ) + .map_err(PubkySwapError::validation)?; + let htlc_address = Address::from_script(&htlc_spk, network) + .map_err(PubkySwapError::validation)? + .to_string(); + + let record = SwapRecord { + swap_id: accept.swap_id.to_string(), + key_index: hex::encode(index), + provider_pubky: route.provider_pubky.clone(), + network, + electrum_url, + required_confirmations: quote.required_confirmations, + quote: Some(quote), + accept: accept.clone(), + destination_address: route.endpoint.value.clone(), + delivered_sat: route.delivered_sat, + claim_fee_sat: route.claim_fee_sat, + claim_txid: None, + claim_tx_hex: None, + claim_published: false, + claim_seen: false, + claim_listed: false, + contract: Some(contract), + created_at_unix: now_unix(), + }; + store::create(&record)?; + QUOTES.lock().unwrap().remove("e_id); + + Ok(PubkySwapRoutePayment { + swap_id: record.swap_id, + invoice, + debit_sat: route.debit_sat, + delivered_sat: route.delivered_sat, + destination_address: route.endpoint.value, + htlc_address, + timeout_block_height: accept.timeout_block_height, + }) +} + +fn status_of(record: &SwapRecord, state: PubkySwapRouteState) -> PubkySwapRouteStatus { + PubkySwapRouteStatus { + swap_id: record.swap_id.clone(), + state, + provider_pubky: record.provider_pubky.clone(), + delivered_sat: record.delivered_sat, + destination_address: record.destination_address.clone(), + } +} + +/// Find the provider's lockup and, once it has its confirmations, claim it straight to the +/// contact's address. Call again until it reports `Claimed`: until the claim confirms, each call +/// checks it is still in the mempool and broadcasts it again if it dropped out. +fn advance_blocking( + mut record: SwapRecord, + mnemonic: &str, + passphrase: Option<&str>, +) -> Result { + let index: [u8; 32] = hex::decode(&record.key_index) + .ok() + .and_then(|index| index.try_into().ok()) + .ok_or_else(|| PubkySwapError::storage("invalid key index"))?; + let keys = keys::swap_keys(mnemonic, passphrase, &index)?; + let provider = record + .accept + .provider_pubkey_hex + .parse() + .map_err(PubkySwapError::validation)?; + let timeout = record.accept.timeout_block_height; + let redeem_script = + build_htlc_script(&keys.payment_hash, &keys.claim_pubkey, &provider, timeout); + let htlc_spk = ScriptBuf::new_p2wsh(&redeem_script.wscript_hash()); + let destination = parse_address(&record.destination_address, record.network)?.script_pubkey(); + let contract = claim::Contract { + htlc_spk: &htlc_spk, + lock_sat: record.accept.onchain_amount_sat, + payment_hash: &keys.payment_hash, + timeout, + required_confirmations: policy(record.network) + .effective_confirmations(record.required_confirmations), + }; + + let electrum = electrum(&record.electrum_url)?; + let tip = electrum.block_headers_subscribe()?.height as u32; + let mut history = vec![]; + for item in electrum.script_get_history(&htlc_spk)? { + history.push((item.height, electrum.transaction_get(&item.tx_hash)?)); + } + + let saved = record.claim_txid.as_ref().map(|_| claim::SavedClaim { + published: record.claim_published, + }); + let required = contract.required_confirmations; + let state = match claim::next_step(&contract, saved, record.claim_listed, tip, &history) { + claim::Step::Report(state) => state, + claim::Step::Claimed { txid, state } => { + if record.claim_txid.as_deref() != Some(txid.as_str()) || !record.claim_seen { + record.claim_txid = Some(txid); + record.claim_published = true; + record.claim_seen = true; + store::save(&record)?; + } + state + } + claim::Step::Rebroadcast { + outpoint, + confirmations, + } => { + match record.claim_tx_hex.clone() { + // The saved claim spends the lockup found now. A lockup the provider replaced + // after a reorganization has another outpoint, so the claim is built again. + Some(claim) if claim_spends(&claim, outpoint) => { + publish_claim(&mut record, &claim)? + } + Some(_) => { + claim_lockup(&mut record, outpoint, &redeem_script, &destination, &keys)? + } + // A restored swap whose claim the provider listed holds no claim of its own. Its + // preimage may be public, so a claim of our own goes out whatever the window. + None => claim_lockup(&mut record, outpoint, &redeem_script, &destination, &keys)?, + } + claim_state(&record, confirmations, required) + } + claim::Step::Claim { + outpoint, + confirmations, + } => { + claim_lockup(&mut record, outpoint, &redeem_script, &destination, &keys)?; + claim_state(&record, confirmations, required) + } + }; + Ok(status_of(&record, state)) +} + +/// Whether the saved claim spends `outpoint`. An unreadable one does not. +fn claim_spends(claim_hex: &str, outpoint: OutPoint) -> bool { + bitcoin::consensus::encode::deserialize_hex::(claim_hex).is_ok_and( + |claim| { + claim + .input + .iter() + .any(|input| input.previous_output == outpoint) + }, + ) +} + +/// `ClaimBroadcast` once a server took the claim; until then the lockup is still waiting on it. +fn claim_state(record: &SwapRecord, confirmations: u32, required: u32) -> PubkySwapRouteState { + match (&record.claim_txid, record.claim_seen) { + (Some(txid), true) => PubkySwapRouteState::ClaimBroadcast { txid: txid.clone() }, + _ => PubkySwapRouteState::AwaitingLockup { + confirmations, + required, + }, + } +} + +/// Build the claim of `outpoint` to the contact, save it, then broadcast it. +fn claim_lockup( + record: &mut SwapRecord, + outpoint: OutPoint, + redeem_script: &ScriptBuf, + destination: &ScriptBuf, + keys: &keys::SwapKeys, +) -> Result<(), PubkySwapError> { + let claim = build_claim_tx( + outpoint, + record.accept.onchain_amount_sat, + redeem_script, + destination.clone(), + record.claim_fee_sat, + keys.preimage, + &keys.claim_key, + ) + .map_err(PubkySwapError::chain)?; + let txid = claim.compute_txid().to_string(); + let claim = bitcoin::consensus::encode::serialize_hex(&claim); + // Saved before the broadcast, so a restart in between finds and sends the same claim. + record.claim_txid = Some(txid); + record.claim_tx_hex = Some(claim.clone()); + store::save(record)?; + publish_claim(record, &claim) +} + +/// Send a saved claim. It is recorded as published before it goes out: once a broadcast was +/// attempted its preimage may have left the wallet, even if the reply is lost. Only an explicit +/// refusal of the first attempt marks it private again, and a failure is only logged, so the app +/// keeps polling and the next call sends it again. +fn publish_claim(record: &mut SwapRecord, claim: &str) -> Result<(), PubkySwapError> { + let claim = bitcoin::consensus::encode::deserialize_hex::(claim) + .map_err(PubkySwapError::storage)?; + // No automatic resend: a refusal must answer the one attempt this call made, not a retry that + // hides an earlier attempt whose reply was lost. + let sender = match electrum_with_retries(&record.electrum_url, 0) { + Ok(sender) => sender, + Err(e) => { + log::warn!("pubky swaps: no Electrum connection for the claim, retrying: {e}"); + return Ok(()); + } + }; + // Only a refusal of the very first attempt proves the preimage never left: an earlier attempt + // may have reached the server even if its reply was lost. + let first_attempt = !record.claim_published; + if first_attempt { + record.claim_published = true; + store::save(record)?; + } + match sender.transaction_broadcast(&claim) { + Ok(_) if !record.claim_seen => { + record.claim_seen = true; + store::save(record) + } + Ok(_) => Ok(()), + Err(e) => { + log::warn!("pubky swaps: claim broadcast failed, retrying on the next advance: {e}"); + if first_attempt && is_refusal(&e) { + record.claim_published = false; + store::save(record)?; + } + Ok(()) + } + } +} + +/// Whether the server answered and refused, rather than the reply being lost. Only a bare server +/// error counts, from a client that sends once. +fn is_refusal(error: &electrum_client::Error) -> bool { + matches!(error, electrum_client::Error::Protocol(_)) +} + +/// One advance at a time per swap, so two overlapping calls cannot save a stale record over the +/// claim, while a slow call for one swap does not hold up the others. +static ADVANCING: Lazy>>>> = + Lazy::new(Default::default); + +fn advancing_lock(swap_id: &str) -> std::sync::Arc> { + ADVANCING + .lock() + .unwrap() + .entry(swap_id.to_string()) + .or_default() + .clone() +} + +/// A swap on record whose claim the provider lists, and whose payment the wallet's node now +/// shows settled, has a public preimage: mark it so `advance` claims past the window too. A +/// restore that ran while the payment was in flight wrote the record without it. +fn promote_listed_claim( + snapshot: &SwapStatusSnapshot, + wallet: &Restoring, +) -> Result<(), PubkySwapError> { + let hash = snapshot.payment_hash_hex.to_lowercase(); + let settled = wallet + .paid + .get(&hash) + .is_some_and(|payment| payment.settled); + if snapshot.claim_observed_txid_hex.is_none() || !settled { + return Ok(()); + } + let swap_id = snapshot.accept.swap_id.to_string(); + let lock = advancing_lock(&swap_id); + let _advancing = lock.lock().unwrap(); + let mut record = store::load(&swap_id)?; + // The listed hash must be the record's own, derived from the wallet's keys. + if record.claim_listed + || record_payment_hash(&record, wallet.mnemonic, wallet.passphrase)? != hash + { + return Ok(()); + } + record.claim_listed = true; + store::save(&record) +} + +/// Rebuild the records of reverse swaps this wallet started, for a wallet restored from its seed: +/// each provider that advertises `swap-list-v1` lists the swaps it holds for the wallet's swap +/// identity, the wallet derives each swap's keys from the index in its `owner_ref`, and checks +/// them against the listed contract before writing a record. +/// +/// The listing is the provider's word, so a record is written only for a swap whose hash the +/// wallet's own Lightning node paid (`sent_payments`), whose lockup is no smaller than that payment +/// less the policy's most fees, and whose hash no other record holds. Finished swaps, other +/// wallets' swaps and contracts that do not match get no record. The contact's address is not in +/// the listing, so a restored swap claims to `payout_address`, the wallet's own. +#[allow(clippy::too_many_arguments)] +pub async fn restore_swaps( + providers: Vec, + sent_payments: Vec, + electrum_url: String, + payout_address: String, + fee_rate_sat_vb: u64, + network: bitcoin::Network, + mnemonic: String, + bip39_passphrase: Option, +) -> Result { + let payout = parse_address(&payout_address, network)?.script_pubkey(); + let claim_fee_sat = claim_fee(&payout, fee_rate_sat_vb)?; + let secret = keys::identity_secret(&mnemonic, bip39_passphrase.as_deref())?; + let client = DirectClient::bind(secret).await?; + + // Providers are asked at once, as an older one never answers a list request and each costs a + // request timeout. + // Providers past the cap, and any whose list task fails, are reported incomplete so the app + // restores them in a later call. + let mut seen = std::collections::HashSet::new(); + let unique: Vec = providers + .iter() + .map(|p| bare_pubky(p).to_string()) + .filter(|p| seen.insert(p.clone())) + .collect(); + let mut report = PubkySwapRestoreReport::default(); + let mut pending: std::collections::HashSet = + unique.iter().take(MAX_CANDIDATES).cloned().collect(); + report + .incomplete_providers + .extend(unique.iter().skip(MAX_CANDIDATES).cloned()); + let mut lists = tokio::task::JoinSet::new(); + for provider in pending.iter().cloned() { + let client = client.clone(); + lists.spawn(async move { + let listing = provider_swaps(&client, &provider).await; + (provider, listing) + }); + } + let mut listings = vec![]; + while let Some(list) = lists.join_next().await { + let Ok((provider, listing)) = list else { + continue; + }; + pending.remove(&provider); + if !listing.complete { + report.incomplete_providers.push(provider.clone()); + } + listings.push((provider, listing.snapshots)); + } + report.incomplete_providers.extend(pending); + client.close().await; + + let paid: HashMap = sent_payments + .into_iter() + .map(|p| (p.payment_hash_hex.to_lowercase(), p)) + .collect(); + // One record per hash: a second listing of the same swap under a new id gets none. + let mut hashes = std::collections::HashSet::new(); + for record in store::list()? { + if let Ok(hash) = record_payment_hash(&record, &mnemonic, bip39_passphrase.as_deref()) { + hashes.insert(hash); + } + } + let wallet = Restoring { + electrum_url: &electrum_url, + payout_address: &payout_address, + claim_fee_sat, + network, + mnemonic: &mnemonic, + passphrase: bip39_passphrase.as_deref(), + paid: &paid, + }; + for (provider, snapshots) in listings { + for snapshot in snapshots { + let swap_id = snapshot.accept.swap_id.to_string(); + match store::load(&swap_id) { + Ok(_) => { + if let Err(e) = promote_listed_claim(&snapshot, &wallet) { + log::warn!("pubky swaps: could not update swap {swap_id}: {e}"); + } + report.known.push(swap_id); + continue; + } + Err(PubkySwapError::NotFound { .. }) => {} + Err(e) => { + log::warn!("pubky swaps: could not read swap {swap_id}, not restoring it: {e}"); + continue; + } + } + if snapshot.state.is_terminal() { + report.finished.push(swap_id); + continue; + } + let Some(record) = restored_record(&snapshot, &provider, &wallet) else { + continue; + }; + if !hashes.insert(snapshot.payment_hash_hex.to_lowercase()) { + log::warn!("pubky swaps: {provider} listed hash of swap {swap_id} twice"); + continue; + } + // One swap that cannot be saved must not cost the user the others. + if let Err(e) = store::create(&record) { + log::warn!("pubky swaps: could not save restored swap {swap_id}: {e}"); + continue; + } + report.restored.push(swap_id); + } + } + Ok(report) +} + +fn record_payment_hash( + record: &SwapRecord, + mnemonic: &str, + passphrase: Option<&str>, +) -> Result { + let index: [u8; 32] = hex::decode(&record.key_index) + .ok() + .and_then(|index| index.try_into().ok()) + .ok_or_else(|| PubkySwapError::storage("invalid key index"))?; + Ok(hex::encode( + keys::swap_keys(mnemonic, passphrase, &index)?.payment_hash, + )) +} + +/// A provider's list of this wallet's swaps, and whether it was read to the end. +struct Listing { + snapshots: Vec, + complete: bool, +} + +/// The swaps a provider that advertises `swap-list-v1` lists for this wallet's identity. +async fn provider_swaps(client: &DirectClient, provider: &str) -> Listing { + let offer = tokio::time::timeout(OFFER_TIMEOUT, fetch_offer(client, provider)).await; + match offer { + Ok(Ok(offer)) if offer.features.iter().any(|f| f == SWAP_LIST_FEATURE) => { + list_swaps(client, provider).await + } + Ok(Ok(_)) => { + log::debug!("pubky swaps: {provider} cannot list swaps"); + Listing { + snapshots: vec![], + complete: true, + } + } + Ok(Err(e)) => { + log::warn!("pubky swaps: no offer from {provider}: {e}"); + Listing { + snapshots: vec![], + complete: false, + } + } + Err(_) => { + log::warn!("pubky swaps: {provider} did not answer in time"); + Listing { + snapshots: vec![], + complete: false, + } + } + } +} + +/// Every swap a provider lists for this wallet's identity, page by page. A provider that keeps +/// sending cursors stops at [`MAX_LIST_PAGES`] or at a cursor it sent before, so it cannot hold up +/// the restore of the other providers. A page that fails keeps the pages read before it. +async fn list_swaps(client: &DirectClient, provider: &str) -> Listing { + let mut snapshots = vec![]; + let mut cursor = None; + let mut cursors_seen = std::collections::HashSet::new(); + for _ in 0..MAX_LIST_PAGES { + let request = SwapMessage::SwapListRequest(SwapListRequest { + request_id: Some(Uuid::new_v4()), + cursor: cursor.take(), + limit: None, + active_only: false, + }); + let page = match client.request(provider, &request).await { + Ok(SwapMessage::SwapList(page)) => page, + reply => { + let error = match reply { + Ok(SwapMessage::Reject(reject)) => refused(reject), + Ok(other) => unexpected("SwapList", &other), + Err(e) => e, + }; + log::warn!("pubky swaps: swap list from {provider} stopped: {error}"); + return Listing { + snapshots, + complete: false, + }; + } + }; + snapshots.extend(page.snapshots); + match page.next_cursor { + Some(next) if cursors_seen.insert(next.clone()) => cursor = Some(next), + Some(next) => { + log::warn!("pubky swaps: {provider} sent cursor {next} again; ending its list"); + return Listing { + snapshots, + complete: false, + }; + } + None => { + return Listing { + snapshots, + complete: true, + } + } + } + } + log::warn!("pubky swaps: {provider} listed more than {MAX_LIST_PAGES} pages; ending its list"); + Listing { + snapshots, + complete: false, + } +} + +/// What a restore checks listed swaps against: the wallet's seed, network and payments. +struct Restoring<'a> { + electrum_url: &'a str, + payout_address: &'a str, + claim_fee_sat: u64, + network: bitcoin::Network, + mnemonic: &'a str, + passphrase: Option<&'a str>, + /// What the wallet's Lightning node paid, by payment hash in lowercase hex. + paid: &'a HashMap, +} + +/// The record for a listed reverse swap on the wallet's network whose keys this wallet derives +/// from its `owner_ref` and whose hash its node paid for at least the lockup plus the most fees +/// the policy allows, or `None`. +fn restored_record( + snapshot: &SwapStatusSnapshot, + provider: &str, + wallet: &Restoring, +) -> Option { + let accept = &snapshot.accept; + let swap_id = accept.swap_id; + if accept.direction != SwapDirection::Reverse + || accept.script_type != SwapScript::P2wsh + || snapshot.network.to_bitcoin_network() != wallet.network + { + return None; + } + let index = keys::index_from_owner_ref(snapshot.owner_ref.as_deref()?)?; + let keys = keys::swap_keys(wallet.mnemonic, wallet.passphrase, &index).ok()?; + let hash = hex::encode(keys.payment_hash); + if hash != snapshot.payment_hash_hex.to_lowercase() { + return None; + } + verify_contract( + accept, + SwapDirection::Reverse, + &keys.payment_hash, + &keys.claim_pubkey, + wallet.network, + ) + .ok()?; + // The listing names the lockup amount, so it is checked against the payment the wallet's own + // node sent: a smaller lockup would let the provider keep the difference. + let Some(payment) = wallet.paid.get(&hash) else { + log::warn!("pubky swaps: no payment for swap {swap_id} from {provider}; not restoring it"); + return None; + }; + let paid_sat = payment.amount_sat; + // The least a quote within the fee bound could lock for this payment. + let min_lock_sat = min_reverse_lockup_sat( + paid_sat.saturating_mul(1_000), + policy(wallet.network).max_fee_bps, + ); + if accept.onchain_amount_sat < min_lock_sat { + log::warn!( + "pubky swaps: swap {swap_id} from {provider} locks {} sat for a {paid_sat} sat \ + payment; not restoring it", + accept.onchain_amount_sat + ); + return None; + } + let delivered_sat = accept + .onchain_amount_sat + .checked_sub(wallet.claim_fee_sat)?; + Some(SwapRecord { + swap_id: swap_id.to_string(), + key_index: hex::encode(index), + provider_pubky: provider.to_string(), + network: wallet.network, + electrum_url: wallet.electrum_url.to_string(), + quote: None, + required_confirmations: snapshot.required_confirmations, + accept: accept.clone(), + destination_address: wallet.payout_address.to_string(), + delivered_sat, + claim_fee_sat: wallet.claim_fee_sat, + // The provider's word that a claim went out is no proof: `advance` finds it in the chain's + // history by its preimage, or claims again once the lockup has its confirmations. + claim_txid: None, + claim_tx_hex: None, + claim_published: false, + claim_seen: false, + // A listed claim counts only once the payment settled: until then the provider has shown + // nothing, and a claim past the window would hand it the preimage and its refund. + claim_listed: snapshot.claim_observed_txid_hex.is_some() && payment.settled, + contract: None, + created_at_unix: snapshot.created_at_unix, + }) +} + +pub async fn advance_swap( + swap_id: String, + mnemonic: String, + bip39_passphrase: Option, +) -> Result { + tokio::task::spawn_blocking(move || { + let lock = advancing_lock(&swap_id); + let _advancing = lock.lock().unwrap(); + let record = store::load(&swap_id)?; + advance_blocking(record, &mnemonic, bip39_passphrase.as_deref()) + }) + .await + .map_err(PubkySwapError::chain)? +} + +#[cfg(test)] +mod tests { + use super::*; + + const SEED: &str = + "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; + const OTHER_SEED: &str = + "legal winner thank year wave sausage worth useful legal winner thank yellow"; + const PAYOUT: &str = "bcrt1qdp8zwu9xk08p3dvkz4qyavmfaadkr4lnvwfah2"; + + fn listed_swap(mnemonic: &str, owner_ref: Option) -> SwapStatusSnapshot { + let index = owner_ref + .as_deref() + .and_then(keys::index_from_owner_ref) + .unwrap_or([7; 32]); + let keys = keys::swap_keys(mnemonic, None, &index).unwrap(); + let provider_secret = bitcoin::secp256k1::SecretKey::from_slice(&[9; 32]).unwrap(); + let provider = bitcoin::PublicKey::new( + provider_secret.public_key(&bitcoin::secp256k1::Secp256k1::new()), + ); + SwapStatusSnapshot { + request_id: None, + accept: swap_common::messages::SwapAccept { + script_type: SwapScript::P2wsh, + swap_tree: None, + quote_id: Uuid::new_v4(), + swap_id: Uuid::new_v4(), + direction: SwapDirection::Reverse, + htlc_script_hex: String::new(), + htlc_address: String::new(), + onchain_amount_sat: 20_300, + timeout_block_height: 1_144, + provider_pubkey_hex: provider.to_string(), + invoice: None, + }, + network: swap_common::NetworkSpec::Regtest, + state: swap_common::SwapState::LockupConfirmed, + funding_txid_hex: None, + funding_vout: None, + spend_txid_hex: None, + claim_observed_txid_hex: None, + required_confirmations: 1, + updated_at_unix: 0, + observed_at_unix: 0, + created_at_unix: 1_000, + payment_hash_hex: hex::encode(keys.payment_hash), + owner_ref, + claimable: false, + } + } + + /// Restore as a wallet whose node paid `paid_sat` for the snapshot's hash, still pending. + fn restore_paid(snapshot: &SwapStatusSnapshot, paid_sat: u64) -> Option { + restore_payment(snapshot, paid_sat, false) + } + + fn restore_payment( + snapshot: &SwapStatusSnapshot, + paid_sat: u64, + settled: bool, + ) -> Option { + let paid = HashMap::from([( + snapshot.payment_hash_hex.clone(), + PubkySwapSentPayment { + payment_hash_hex: snapshot.payment_hash_hex.clone(), + amount_sat: paid_sat, + settled, + }, + )]); + let wallet = Restoring { + electrum_url: "tcp://127.0.0.1:60001", + payout_address: PAYOUT, + claim_fee_sat: 300, + network: bitcoin::Network::Regtest, + mnemonic: SEED, + passphrase: None, + paid: &paid, + }; + restored_record(snapshot, "provider", &wallet) + } + + fn restore(snapshot: &SwapStatusSnapshot) -> Option { + restore_paid(snapshot, 20_500) + } + + #[test] + fn restores_a_listed_swap_from_the_index_in_its_owner_ref() { + let index = keys::new_index(); + let snapshot = listed_swap(SEED, Some(keys::owner_ref(&index))); + let record = restore(&snapshot).expect("restored"); + assert_eq!(record.key_index, hex::encode(index)); + assert_eq!(record.destination_address, PAYOUT); + assert_eq!(record.delivered_sat, 20_000); + assert_eq!(record.required_confirmations, 1); + assert!(record.quote.is_none() && record.claim_txid.is_none()); + } + + #[test] + fn skips_swaps_this_wallet_cannot_rebuild() { + let other_wallets = listed_swap(OTHER_SEED, Some(keys::owner_ref(&keys::new_index()))); + assert!(restore(&other_wallets).is_none()); + assert!(restore(&listed_swap(SEED, None)).is_none()); + assert!(restore(&listed_swap(SEED, Some("someone-else:1".into()))).is_none()); + let mut other_network = listed_swap(SEED, Some(keys::owner_ref(&keys::new_index()))); + other_network.network = swap_common::NetworkSpec::Signet; + assert!(restore(&other_network).is_none()); + } + + #[test] + fn restores_only_a_lockup_the_wallet_paid_for() { + let snapshot = listed_swap(SEED, Some(keys::owner_ref(&keys::new_index()))); + // Locks 20,300 sat; a quote may charge 5% of the lockup in fees. + assert!(restore_paid(&snapshot, 21_315).is_some()); + assert!(restore_paid(&snapshot, 21_316).is_none()); + let paid = HashMap::new(); + let wallet = Restoring { + electrum_url: "", + payout_address: PAYOUT, + claim_fee_sat: 300, + network: bitcoin::Network::Regtest, + mnemonic: SEED, + passphrase: None, + paid: &paid, + }; + assert!(restored_record(&snapshot, "provider", &wallet).is_none()); + } + + #[test] + fn does_not_take_a_listed_claim_as_published() { + let mut snapshot = listed_swap(SEED, Some(keys::owner_ref(&keys::new_index()))); + snapshot.claim_observed_txid_hex = Some("ab".repeat(32)); + let record = restore_payment(&snapshot, 20_500, true).expect("restored"); + assert!(record.claim_listed); + assert!(record.claim_txid.is_none() && !record.claim_published && !record.claim_seen); + } + + #[test] + fn refuses_a_new_swap_that_reuses_a_saved_swap_id() { + let dir = std::env::temp_dir().join(format!("pubky-swaps-{}", Uuid::new_v4())); + store::init(dir.to_str().unwrap()).unwrap(); + let snapshot = listed_swap(SEED, Some(keys::owner_ref(&keys::new_index()))); + let first = restore(&snapshot).expect("restored"); + store::create(&first).unwrap(); + // A provider's acceptance names the swap id, so a later one may reuse an earlier swap's. + let mut second = first.clone(); + second.key_index = hex::encode(keys::new_index()); + second.destination_address = PAYOUT.to_string(); + + assert!(store::create(&second).is_err()); + assert_eq!( + store::load(&first.swap_id).unwrap().key_index, + first.key_index + ); + } + + #[test] + fn marks_a_known_swap_once_its_payment_settles() { + let dir = std::env::temp_dir().join(format!("pubky-swaps-{}", Uuid::new_v4())); + store::init(dir.to_str().unwrap()).unwrap(); + let mut snapshot = listed_swap(SEED, Some(keys::owner_ref(&keys::new_index()))); + snapshot.claim_observed_txid_hex = Some("ab".repeat(32)); + // Restored while the payment was in flight. + let record = restore(&snapshot).expect("restored"); + assert!(!record.claim_listed); + store::save(&record).unwrap(); + let wallet = |settled| { + HashMap::from([( + snapshot.payment_hash_hex.clone(), + PubkySwapSentPayment { + payment_hash_hex: snapshot.payment_hash_hex.clone(), + amount_sat: 20_500, + settled, + }, + )]) + }; + let restoring = |paid| Restoring { + electrum_url: "", + payout_address: PAYOUT, + claim_fee_sat: 300, + network: bitcoin::Network::Regtest, + mnemonic: SEED, + passphrase: None, + paid, + }; + let pending = wallet(false); + promote_listed_claim(&snapshot, &restoring(&pending)).unwrap(); + assert!(!store::load(&record.swap_id).unwrap().claim_listed); + let settled = wallet(true); + promote_listed_claim(&snapshot, &restoring(&settled)).unwrap(); + assert!(store::load(&record.swap_id).unwrap().claim_listed); + } + + #[test] + fn ignores_a_listed_claim_while_the_payment_is_pending() { + // Past the window, claiming on a bare listing would hand the provider the preimage and + // its refund: only a settled payment shows the preimage is public. + let mut snapshot = listed_swap(SEED, Some(keys::owner_ref(&keys::new_index()))); + snapshot.claim_observed_txid_hex = Some("ab".repeat(32)); + assert!(!restore(&snapshot).expect("restored").claim_listed); + } + + #[test] + fn rebuilds_a_saved_claim_of_a_replaced_lockup() { + let spent = OutPoint::new("11".repeat(32).parse().unwrap(), 0); + let replaced = OutPoint::new("22".repeat(32).parse().unwrap(), 0); + let claim = bitcoin::Transaction { + version: bitcoin::transaction::Version::TWO, + lock_time: bitcoin::absolute::LockTime::ZERO, + input: vec![bitcoin::TxIn { + previous_output: spent, + ..Default::default() + }], + output: vec![], + }; + let claim = bitcoin::consensus::encode::serialize_hex(&claim); + assert!(claim_spends(&claim, spent)); + assert!(!claim_spends(&claim, replaced)); + assert!(!claim_spends("not a transaction", spent)); + } + + #[test] + fn only_an_answer_from_the_server_counts_as_a_refusal() { + use electrum_client::Error; + let refused = || Error::Protocol(serde_json::json!({"message": "min relay fee not met"})); + let lost = || Error::IOError(std::io::Error::from(std::io::ErrorKind::TimedOut)); + assert!(is_refusal(&refused())); + assert!(!is_refusal(&lost())); + // A transport error after the single attempt, or retries that hid an earlier one. + assert!(!is_refusal(&Error::AllAttemptsErrored(vec![]))); + assert!(!is_refusal(&Error::AllAttemptsErrored(vec![ + lost(), + refused() + ]))); + } + + const MNEMONIC: &str = + "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; + + fn onchain_contact() -> PaykitEndpoint { + PaykitEndpoint { + method_id: "btc-regtest-p2wpkh".into(), + value: "bcrt1qdp8zwu9xk08p3dvkz4qyavmfaadkr4lnvwfah2".into(), + } + } + + fn request(service_legs: Vec) -> PaykitRouteRequest { + PaykitRouteRequest { + amount_sat: 20_000, + contact_endpoints: vec![onchain_contact()], + lightning_spendable_sat: 0, + onchain_spendable_sat: 0, + providers: vec![], + fee_rate_sat_vb: 2, + service_legs, + } + } + + async fn route(request: PaykitRouteRequest) -> PaykitRoute { + route_paykit_payment(request, bitcoin::Network::Regtest, MNEMONIC.into(), None) + .await + .unwrap() + } + + #[tokio::test] + async fn routes_an_onchain_contact_through_a_service_without_providers() { + let leg = ServiceRouteLeg { + service: "spark".into(), + endpoint: onchain_contact(), + delivered_sat: 20_000, + debit_sat: 20_300, + atomicity: "trusted".into(), + valid_until_unix: 0, + }; + let PaykitRoute::Service { leg: picked } = route(request(vec![leg.clone()])).await else { + panic!("expected a service route"); + }; + assert_eq!(picked, leg); + } + + #[tokio::test] + async fn routes_through_a_service_on_mainnet_where_swaps_are_refused() { + let mainnet_contact = PaykitEndpoint { + method_id: "btc-bitcoin-p2wpkh".into(), + value: "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu".into(), + }; + let leg = ServiceRouteLeg { + service: "spark".into(), + endpoint: mainnet_contact.clone(), + delivered_sat: 20_000, + debit_sat: 20_300, + atomicity: "trusted".into(), + valid_until_unix: 0, + }; + let mut request = request(vec![leg.clone()]); + request.contact_endpoints = vec![mainnet_contact]; + request.providers = vec!["pubky-provider".into()]; + let route = + route_paykit_payment(request, bitcoin::Network::Bitcoin, MNEMONIC.into(), None).await; + assert!(matches!(route, Ok(PaykitRoute::Service { leg: picked }) if picked == leg)); + } + + #[tokio::test] + async fn explains_why_nothing_routes_without_providers_or_services() { + let PaykitRoute::None { reason } = route(request(vec![])).await else { + panic!("expected no route"); + }; + assert_eq!(reason, "No swap provider is set up."); + } +} + +#[cfg(test)] +mod live_tests { + //! Against a running regtest provider: + //! `PUBKY_SWAPS_PROVIDER=[,…] PUBKY_SWAPS_ELECTRUM=tcp://127.0.0.1:60001 + //! PUBKY_SWAPS_DESTINATION= cargo test --lib pubky_swaps::client::live_tests -- --ignored` + use super::*; + + const MNEMONIC: &str = + "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; + + #[tokio::test(flavor = "multi_thread")] + #[ignore = "needs a running regtest Pubky Swaps provider"] + async fn routes_an_onchain_contact_through_the_provider_and_commits() { + let provider = std::env::var("PUBKY_SWAPS_PROVIDER").unwrap(); + let electrum = std::env::var("PUBKY_SWAPS_ELECTRUM").unwrap(); + let destination = std::env::var("PUBKY_SWAPS_DESTINATION").unwrap(); + let dir = std::env::temp_dir().join(format!("pubky-swaps-{}", Uuid::new_v4())); + store::init(dir.to_str().unwrap()).unwrap(); + + let mut providers: Vec = provider.split(',').map(str::to_string).collect(); + let provider = providers[0].clone(); + let edges = provider_edges(provider.clone(), MNEMONIC.into(), None) + .await + .unwrap(); + assert!(edges.iter().any(|e| e.direction == "reverse"), "{edges:?}"); + + let request = PaykitRouteRequest { + amount_sat: 20_000, + contact_endpoints: vec![PaykitEndpoint { + method_id: "btc-regtest-p2wpkh".into(), + value: destination.clone(), + }], + lightning_spendable_sat: 500_000, + onchain_spendable_sat: 0, + providers: std::mem::take(&mut providers), + fee_rate_sat_vb: 2, + service_legs: vec![], + }; + let route = route_paykit_payment(request, bitcoin::Network::Regtest, MNEMONIC.into(), None) + .await + .unwrap(); + let PaykitRoute::Swap { quote } = route else { + panic!("expected a swap route, got {route:?}"); + }; + assert_eq!(quote.delivered_sat, 20_000); + assert_eq!(quote.lock_sat, 20_000 + quote.claim_fee_sat); + assert!(quote.debit_sat > quote.lock_sat); + + let payment = commit_route(quote.quote_id.clone(), electrum, MNEMONIC.into(), None) + .await + .unwrap(); + assert_eq!(payment.destination_address, destination); + assert!(payment.invoice.starts_with("lnbcrt"), "{}", payment.invoice); + let status = advance_swap(payment.swap_id.clone(), MNEMONIC.into(), None) + .await + .unwrap(); + assert!(matches!( + status.state, + PubkySwapRouteState::AwaitingLockup { .. } + )); + log::info!("quote {quote:?}\npayment {payment:?}"); + + // The rest of the journey, with `PUBKY_SWAPS_PAY_CMD` paying the hold invoice it is given + // from a Lightning-only node, and `PUBKY_SWAPS_MINE_CMD` mining a block. + let (Ok(pay), Ok(mine)) = ( + std::env::var("PUBKY_SWAPS_PAY_CMD"), + std::env::var("PUBKY_SWAPS_MINE_CMD"), + ) else { + return; + }; + let sh = |cmd: &str| { + std::process::Command::new("sh") + .arg("-c") + .arg(cmd) + .spawn() + .unwrap() + }; + // The payment settles only once the claim reveals the preimage, so it runs alongside. + let mut paying = sh(&format!("{pay} {}", payment.invoice)); + let txid = loop { + tokio::time::sleep(std::time::Duration::from_secs(5)).await; + assert!(sh(&mine).wait().unwrap().success()); + let status = advance_swap(payment.swap_id.clone(), MNEMONIC.into(), None) + .await + .unwrap(); + log::info!("{:?}", status.state); + match status.state { + PubkySwapRouteState::Claimed { txid } => break txid, + PubkySwapRouteState::Failed { reason } => panic!("{reason}"), + _ => {} + } + }; + assert!( + paying.wait().unwrap().success(), + "the payment did not settle" + ); + let claim = electrum_with_retries(&std::env::var("PUBKY_SWAPS_ELECTRUM").unwrap(), 3) + .unwrap() + .transaction_get(&txid.parse().unwrap()) + .unwrap(); + let contact = parse_address(&destination, bitcoin::Network::Regtest) + .unwrap() + .script_pubkey(); + assert!(claim + .output + .iter() + .any(|out| out.script_pubkey == contact && out.value.to_sat() == 20_000)); + log::info!("claimed {txid}: 20000 sat to {destination}"); + } +} diff --git a/src/modules/pubky_swaps/delegation.rs b/src/modules/pubky_swaps/delegation.rs new file mode 100644 index 00000000..a3a58b74 --- /dev/null +++ b/src/modules/pubky_swaps/delegation.rs @@ -0,0 +1,223 @@ +//! A provider's capability signing key, followed from its published records (Paykit +//! Capabilities §5): its identity key authorizes a routing key per key generation (paykit-rs's +//! Noise Key Authorization), and the routing key delegates to the capability signing key that +//! signs its `paykit-cap.*` quotes and contracts. +//! +//! This reads the same records and checks the same bytes as pubky-swap's +//! `paykit_identity::resolve_signing_key`, on the pubky client bitkit-core already has. The tests +//! hold records upstream's code wrote. + +use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; +use base64::Engine; +use ed25519_dalek::{Signature, VerifyingKey}; +use serde::{Deserialize, Serialize}; + +use super::errors::PubkySwapError; +use crate::modules::pubky::fetch_public_file_if_any; + +const AUTHORIZATION_PATH: &str = "/pub/paykit-authority/v0/current-key.json"; +const AUTHORIZATION_KIND: &str = "paykit.noise_key_authorization"; +const AUTHORIZATION_DOMAIN: &[u8] = b"paykit.noise_key_authorization/v1\0"; +const DELEGATION_PATH: &str = "/pub/paykit/ext/capabilities/v1/signing-key.json"; +const DELEGATION_KIND: &str = "paykit-cap.signing_key"; +const DELEGATION_DOMAIN: &[u8] = b"paykit-cap/subkey/v1"; +const MAX_BYTES: usize = 4096; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Authorization { + version: u8, + kind: String, + owner: String, + noise_public_key: String, + noise_static_public_key: String, + key_generation: u64, + signature: String, +} + +/// The delegation as written. Fields are in JCS order and hold only ASCII strings and safe +/// integers, so `serde_json` writes the bytes the routing key signed. +#[derive(Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Delegation { + key_generation: u64, + kind: String, + owner: String, + #[serde(skip_serializing_if = "Option::is_none")] + sig: Option, + signing_key: String, + version: u64, +} + +fn invalid(what: &str) -> PubkySwapError { + PubkySwapError::validation(format!("provider signing key: {what}")) +} + +fn z32_key(z32: &str) -> Result { + let key = pubky::PublicKey::try_from_z32(z32).map_err(|_| invalid("a key is not a pubky"))?; + VerifyingKey::from_bytes(&key.to_bytes()).map_err(|_| invalid("a key is not Ed25519")) +} + +/// The capability signing key, as hex, that `owner`'s records name: the authorization signed by +/// `owner`, then the delegation for the same owner and generation signed by the routing key it +/// authorizes. A delegation for another generation is refused. +pub(crate) fn verify_chain( + owner: &str, + authorization: &[u8], + delegation: &[u8], +) -> Result { + if authorization.len() > MAX_BYTES || delegation.len() > MAX_BYTES { + return Err(invalid("a record is too large")); + } + let auth: Authorization = + serde_json::from_slice(authorization).map_err(|_| invalid("unreadable authorization"))?; + if auth.version != 1 || auth.kind != AUTHORIZATION_KIND || auth.key_generation == 0 { + return Err(invalid("not a version 1 Noise Key Authorization")); + } + if auth.owner != owner { + return Err(invalid("the authorization is for another identity")); + } + let owner_key = z32_key(&auth.owner)?; + let routing_key = z32_key(&auth.noise_public_key)?; + let noise_static: [u8; 32] = hex::decode(&auth.noise_static_public_key) + .ok() + .and_then(|key| key.try_into().ok()) + .ok_or_else(|| invalid("the authorization's static key is malformed"))?; + let signature: [u8; 64] = STANDARD + .decode(&auth.signature) + .ok() + .and_then(|sig| sig.try_into().ok()) + .ok_or_else(|| invalid("the authorization's signature is malformed"))?; + let signed = [ + AUTHORIZATION_DOMAIN, + owner_key.as_bytes(), + routing_key.as_bytes(), + &noise_static, + &auth.key_generation.to_be_bytes(), + ] + .concat(); + owner_key + .verify_strict(&signed, &Signature::from_bytes(&signature)) + .map_err(|_| invalid("the authorization is not signed by its owner"))?; + + let wire: Delegation = + serde_json::from_slice(delegation).map_err(|_| invalid("unreadable delegation"))?; + if wire.version != 1 || wire.kind != DELEGATION_KIND { + return Err(invalid("not a version 1 delegation")); + } + if wire.owner != auth.owner { + return Err(invalid("the delegation is for another identity")); + } + if wire.key_generation != auth.key_generation { + return Err(invalid("the delegation is for another key generation")); + } + let signing_key: [u8; 32] = URL_SAFE_NO_PAD + .decode(&wire.signing_key) + .ok() + .and_then(|key| key.try_into().ok()) + .ok_or_else(|| invalid("the delegated key is malformed"))?; + VerifyingKey::from_bytes(&signing_key) + .map_err(|_| invalid("the delegated key is not Ed25519"))?; + let signature: [u8; 64] = wire + .sig + .as_deref() + .and_then(|sig| URL_SAFE_NO_PAD.decode(sig).ok()) + .and_then(|sig| sig.try_into().ok()) + .ok_or_else(|| invalid("the delegation's signature is malformed"))?; + let mut signed = DELEGATION_DOMAIN.to_vec(); + signed.push(0); + signed.extend(serde_json::to_vec(&Delegation { + sig: None, + ..wire.clone() + })?); + routing_key + .verify_strict(&signed, &Signature::from_bytes(&signature)) + .map_err(|_| invalid("the delegation is not signed by the authorized routing key"))?; + Ok(hex::encode(signing_key)) +} + +/// The capability signing key `provider` (bare z32) publishes, or `None` when it publishes no +/// authorization or delegation. An error when a published record does not verify. +pub(crate) async fn resolve(provider: &str) -> Result, PubkySwapError> { + let fetch = |path: &str| { + let addr = format!("{provider}{path}"); + async move { + fetch_public_file_if_any(&addr) + .await + .map_err(PubkySwapError::transport) + } + }; + let Some(authorization) = fetch(AUTHORIZATION_PATH).await? else { + return Ok(None); + }; + let Some(delegation) = fetch(DELEGATION_PATH).await? else { + return Ok(None); + }; + verify_chain(provider, &authorization, &delegation).map(Some) +} + +#[cfg(test)] +mod tests { + use super::*; + + // Written by pubky-swap's `paykit_identity` at f45e204 and paykit-rs at 01de5dd, for Pubky + // secret `[7; 32]`. `DELEGATION_1` is upstream's golden vector. + const OWNER: &str = "7jfgaa9nutjyixzikb7tgmsf9gkwq7iqz498zr1nd5ig1fng4esy"; + const AUTHORIZATION_1: &str = r#"{"version":1,"kind":"paykit.noise_key_authorization","owner":"7jfgaa9nutjyixzikb7tgmsf9gkwq7iqz498zr1nd5ig1fng4esy","noise_public_key":"yr51em3ri9u7yeos61bu3fa1smuepmigxigjceixykbm76j93wjo","noise_static_public_key":"22441e724551e9f183ce9d7dc0cc3879351dff59f04ad989ca8529c540aeca1b","key_generation":1,"signature":"FjpeQWA/dA7C4+IoiNzX3WU/p1dXEKxVBS1M8XRRs0bBZ7if3nvxD/keZ+pOge1TDdzNH6RH/kSGxg3O4j/YCw=="}"#; + const DELEGATION_1: &str = r#"{"key_generation":1,"kind":"paykit-cap.signing_key","owner":"7jfgaa9nutjyixzikb7tgmsf9gkwq7iqz498zr1nd5ig1fng4esy","sig":"Sj9Xps4rjkmNrqYv4EU8OuD7gyN4LGNb1SyAbjv0p9PEEg7HekF6unysSnkPRXDn_k9XOBHmll3-Xdo2xkrtAQ","signing_key":"7TrkHFnQPW67doNM4TipjT9CmZygnHHbriRjgBb4Ry8","version":1}"#; + const SIGNER_1: &str = "ed3ae41c59d03d6ebb76834ce138a98d3f42999ca09c71dbae24638016f8472f"; + const AUTHORIZATION_2: &str = r#"{"version":1,"kind":"paykit.noise_key_authorization","owner":"7jfgaa9nutjyixzikb7tgmsf9gkwq7iqz498zr1nd5ig1fng4esy","noise_public_key":"h9968eqdmsz5fcrfjrfdssmrpyc35mdazxjd1wcxf7dfspaz3kmo","noise_static_public_key":"b41fd37e6772a4efc6475d7c57ce8197264aff7209785c25ca71c1051d167220","key_generation":2,"signature":"PpXMWkTx9Y0+0Yt99dqdKAL99GEzMVPQnYCYVlxTIqkKt6wnVCTUczHZFuJMSgym5FS/8Lb0M6jd6+l/UXInDA=="}"#; + const DELEGATION_2: &str = r#"{"key_generation":2,"kind":"paykit-cap.signing_key","owner":"7jfgaa9nutjyixzikb7tgmsf9gkwq7iqz498zr1nd5ig1fng4esy","sig":"6M_pzVhuKJiBpPwTTd15LQu89Asth_k1iLgsDn4XvgBd-MtTPtsmTCSMiNL4LAOEALtCrjEphJ0VffYE16A1Dw","signing_key":"oaDkbPRgoLq6pWzuAwpr8xCrflZjn47MRHG7aJxwLMY","version":1}"#; + const SIGNER_2: &str = "a1a0e46cf460a0babaa56cee030a6bf310ab7e56639f8ecc4471bb689c702cc6"; + + fn chain(authorization: &str, delegation: &str) -> Result { + verify_chain(OWNER, authorization.as_bytes(), delegation.as_bytes()) + } + + fn edit(json: &str, field: &str, value: serde_json::Value) -> String { + let mut record: serde_json::Value = serde_json::from_str(json).unwrap(); + record[field] = value; + serde_json::to_string(&record).unwrap() + } + + #[test] + fn follows_upstream_records_to_the_delegated_key() { + assert_eq!(chain(AUTHORIZATION_1, DELEGATION_1).unwrap(), SIGNER_1); + assert_eq!(chain(AUTHORIZATION_2, DELEGATION_2).unwrap(), SIGNER_2); + } + + #[test] + fn refuses_a_delegation_for_another_generation() { + assert!(chain(AUTHORIZATION_2, DELEGATION_1).is_err()); + assert!(chain(AUTHORIZATION_1, DELEGATION_2).is_err()); + } + + #[test] + fn refuses_records_for_another_identity() { + let other = "yr51em3ri9u7yeos61bu3fa1smuepmigxigjceixykbm76j93wjo"; + assert!(verify_chain(other, AUTHORIZATION_1.as_bytes(), DELEGATION_1.as_bytes()).is_err()); + } + + #[test] + fn refuses_tampered_records() { + let signer_2_b64 = URL_SAFE_NO_PAD.encode(hex::decode(SIGNER_2).unwrap()); + // Another delegated key under the same signature, or another routing key. + assert!(chain( + AUTHORIZATION_1, + &edit(DELEGATION_1, "signing_key", signer_2_b64.into()) + ) + .is_err()); + let routing_2 = "h9968eqdmsz5fcrfjrfdssmrpyc35mdazxjd1wcxf7dfspaz3kmo"; + assert!(chain( + &edit(AUTHORIZATION_1, "noise_public_key", routing_2.into()), + DELEGATION_1 + ) + .is_err()); + assert!(chain( + AUTHORIZATION_1, + &edit(DELEGATION_1, "sig", serde_json::Value::Null) + ) + .is_err()); + assert!(chain(AUTHORIZATION_1, &edit(DELEGATION_1, "extra", 1.into())).is_err()); + } +} diff --git a/src/modules/pubky_swaps/errors.rs b/src/modules/pubky_swaps/errors.rs new file mode 100644 index 00000000..3657d5f6 --- /dev/null +++ b/src/modules/pubky_swaps/errors.rs @@ -0,0 +1,78 @@ +use thiserror::Error; + +/// Errors surfaced by the Pubky Swaps route module. +#[derive(uniffi::Error, Debug, Error)] +pub enum PubkySwapError { + #[error("Invalid input: {error_details}")] + InvalidInput { error_details: String }, + + #[error("Provider unreachable: {error_details}")] + Transport { error_details: String }, + + /// The provider refused the request with one of its closed refusal codes. + #[error("Provider refused ({code}): {reason}")] + Refused { code: String, reason: String }, + + /// The provider's quote, contract or invoice did not match what was asked for. + #[error("Validation failed: {error_details}")] + Validation { error_details: String }, + + #[error("Chain error: {error_details}")] + Chain { error_details: String }, + + #[error("Storage error: {error_details}")] + Storage { error_details: String }, + + #[error("Swap not found: {error_details}")] + NotFound { error_details: String }, +} + +impl PubkySwapError { + pub(crate) fn invalid(details: impl ToString) -> Self { + Self::InvalidInput { + error_details: details.to_string(), + } + } + + pub(crate) fn transport(details: impl ToString) -> Self { + Self::Transport { + error_details: details.to_string(), + } + } + + pub(crate) fn validation(details: impl ToString) -> Self { + Self::Validation { + error_details: details.to_string(), + } + } + + pub(crate) fn chain(details: impl ToString) -> Self { + Self::Chain { + error_details: details.to_string(), + } + } + + pub(crate) fn storage(details: impl ToString) -> Self { + Self::Storage { + error_details: details.to_string(), + } + } +} + +impl From for PubkySwapError { + fn from(err: serde_json::Error) -> Self { + Self::storage(err) + } +} + +impl From for PubkySwapError { + fn from(err: std::io::Error) -> Self { + Self::storage(err) + } +} + +impl From for PubkySwapError { + fn from(err: electrum_client::Error) -> Self { + Self::chain(err) + } +} diff --git a/src/modules/pubky_swaps/keys.rs b/src/modules/pubky_swaps/keys.rs new file mode 100644 index 00000000..76b1bc2b --- /dev/null +++ b/src/modules/pubky_swaps/keys.rs @@ -0,0 +1,144 @@ +//! Swap keys derived from the wallet seed and a random per-swap index, so a swap can be rebuilt +//! from the seed and the index. +//! +//! The provider sees only public keys and the payment hash. Each key is +//! HMAC-SHA512(seed, domain || index), truncated to 32 bytes, under its own domain string, so +//! nothing here can collide with the Boltz module's BIP85 keys or with each other. +//! +//! The index is 32 random bytes, so a restored wallet or a second device on the same seed never +//! repeats a preimage an earlier claim published. It is not secret: the wallet sends it to the +//! provider as the swap's `owner_ref`, which the provider keeps and lists back (`swap-list-v1`), so +//! a wallet restored from its seed reads the index and derives the keys again. + +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use base64::Engine; +use bitcoin::hashes::{hmac, sha256, sha512, Hash, HashEngine}; +use bitcoin::secp256k1::{Secp256k1, SecretKey}; + +use super::errors::PubkySwapError; + +const IDENTITY_DOMAIN: &[u8] = b"bitkit/pubky-swaps/identity/v1"; +const CLAIM_DOMAIN: &[u8] = b"bitkit/pubky-swaps/claim/v4/"; +const PREIMAGE_DOMAIN: &[u8] = b"bitkit/pubky-swaps/preimage/v4/"; +/// Marks an `owner_ref` this wallet wrote: the version of the key scheme, then the index in +/// unpadded base64url, 58 characters in all. +const OWNER_REF_PREFIX: &str = "bitkit-swap-v4:"; + +pub(crate) struct SwapKeys { + pub claim_key: SecretKey, + pub claim_pubkey: bitcoin::PublicKey, + pub preimage: [u8; 32], + pub payment_hash: [u8; 32], +} + +fn seed(mnemonic: &str, passphrase: Option<&str>) -> Result<[u8; 64], PubkySwapError> { + let mnemonic = bip39::Mnemonic::parse(mnemonic) + .map_err(|e| PubkySwapError::invalid(format!("mnemonic: {e}")))?; + Ok(mnemonic.to_seed(passphrase.unwrap_or(""))) +} + +fn derive(seed: &[u8; 64], domain: &[u8], suffix: &[u8]) -> [u8; 32] { + let mut engine = hmac::HmacEngine::::new(seed); + engine.input(domain); + engine.input(suffix); + let out = hmac::Hmac::::from_engine(engine).to_byte_array(); + let mut key = [0u8; 32]; + key.copy_from_slice(&out[..32]); + key +} + +/// The Ed25519 secret the wallet uses as its identity towards swap providers. It is not the +/// user's Pubky identity, so providers cannot link swaps to the user's profile. +pub(crate) fn identity_secret( + mnemonic: &str, + passphrase: Option<&str>, +) -> Result<[u8; 32], PubkySwapError> { + Ok(derive(&seed(mnemonic, passphrase)?, IDENTITY_DOMAIN, &[])) +} + +/// A fresh random index for a new swap's keys. +pub(crate) fn new_index() -> [u8; 32] { + rand::random() +} + +/// The `owner_ref` that carries `index` to the provider. +pub(crate) fn owner_ref(index: &[u8; 32]) -> String { + format!("{OWNER_REF_PREFIX}{}", URL_SAFE_NO_PAD.encode(index)) +} + +/// The index in an `owner_ref` this wallet wrote, or `None` for anything else. +pub(crate) fn index_from_owner_ref(owner_ref: &str) -> Option<[u8; 32]> { + URL_SAFE_NO_PAD + .decode(owner_ref.strip_prefix(OWNER_REF_PREFIX)?) + .ok()? + .try_into() + .ok() +} + +pub(crate) fn swap_keys( + mnemonic: &str, + passphrase: Option<&str>, + index: &[u8; 32], +) -> Result { + let seed = seed(mnemonic, passphrase)?; + let claim_key = SecretKey::from_slice(&derive(&seed, CLAIM_DOMAIN, index)) + .map_err(|e| PubkySwapError::invalid(format!("claim key: {e}")))?; + let claim_pubkey = bitcoin::PublicKey::new(claim_key.public_key(&Secp256k1::new())); + let preimage = derive(&seed, PREIMAGE_DOMAIN, index); + let payment_hash = sha256::Hash::hash(&preimage).to_byte_array(); + Ok(SwapKeys { + claim_key, + claim_pubkey, + preimage, + payment_hash, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + const MNEMONIC: &str = + "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"; + + #[test] + fn keys_are_deterministic_and_distinct_per_index() { + let a = swap_keys(MNEMONIC, None, &[0; 32]).unwrap(); + let again = swap_keys(MNEMONIC, None, &[0; 32]).unwrap(); + let b = swap_keys(MNEMONIC, None, &[1; 32]).unwrap(); + assert_eq!(a.claim_key, again.claim_key); + assert_eq!(a.preimage, again.preimage); + assert_ne!(a.claim_key, b.claim_key); + assert_ne!(a.preimage, b.preimage); + assert_ne!(a.preimage[..], a.claim_key.secret_bytes()[..]); + } + + #[test] + fn passphrase_changes_every_key() { + let plain = swap_keys(MNEMONIC, None, &[0; 32]).unwrap(); + let with = swap_keys(MNEMONIC, Some("x"), &[0; 32]).unwrap(); + assert_ne!(plain.claim_key, with.claim_key); + assert_ne!( + identity_secret(MNEMONIC, None).unwrap(), + identity_secret(MNEMONIC, Some("x")).unwrap() + ); + } + + #[test] + fn fresh_indexes_never_repeat_a_preimage() { + let a = swap_keys(MNEMONIC, None, &new_index()).unwrap(); + let b = swap_keys(MNEMONIC, None, &new_index()).unwrap(); + assert_ne!(a.payment_hash, b.payment_hash); + } + + #[test] + fn the_index_round_trips_through_an_owner_ref_the_provider_keeps() { + let index = new_index(); + let owner_ref = owner_ref(&index); + assert!(swap_common::messages::owner_ref_is_valid(&owner_ref)); + assert_eq!(index_from_owner_ref(&owner_ref), Some(index)); + assert_eq!(owner_ref.len(), 58); + assert_eq!(index_from_owner_ref("someone-else:00"), None); + assert_eq!(index_from_owner_ref("bitkit-swap-v4:zz"), None); + } +} diff --git a/src/modules/pubky_swaps/mod.rs b/src/modules/pubky_swaps/mod.rs new file mode 100644 index 00000000..42625764 --- /dev/null +++ b/src/modules/pubky_swaps/mod.rs @@ -0,0 +1,19 @@ +//! Pubky Swaps as Paykit routes: when no rail the wallet holds reaches an endpoint a Paykit +//! contact published, route the payment through a Pubky Swaps provider (`swap/1`). +//! See README.md. + +mod cap; +mod claim; +mod client; +mod delegation; +mod errors; +mod keys; +mod router; +mod store; +mod transport; +mod types; + +pub use client::{advance_swap, commit_route, provider_edges, restore_swaps, route_paykit_payment}; +pub use errors::PubkySwapError; +pub(crate) use store::{init, wipe_all}; +pub use types::*; diff --git a/src/modules/pubky_swaps/router.rs b/src/modules/pubky_swaps/router.rs new file mode 100644 index 00000000..785089db --- /dev/null +++ b/src/modules/pubky_swaps/router.rs @@ -0,0 +1,228 @@ +//! Wallet-local route selection for a Paykit payment (Paykit Capabilities §9.1, one `swap/1` +//! leg at most). +//! +//! A contact the wallet can pay from its own balance is paid directly. Otherwise the router +//! turns each trusted provider's offer into `swap/1` edges, keeps the edges that connect a rail +//! the wallet holds to an endpoint the contact published, pre-ranks them by indicative fee, +//! asks the best few for a firm quote, and picks the one that debits the wallet least for the +//! exact amount the contact must receive. + +use swap_common::messages::SwapOffer; +use swap_common::SwapDirection; + +use crate::modules::paykit_route::network_label; + +use super::types::{PaykitRoute, PubkySwapRouteQuote, ServiceRouteLeg, SwapRouteEdge}; + +pub(crate) const LIGHTNING_BOLT11: &str = "btc-lightning-bolt11"; +/// Providers asked for a firm quote per payment (§9.1 `fanout_budget`). +pub(crate) const FANOUT_BUDGET: usize = 3; + +/// On-chain address types in the order Bitkit prefers to pay them. +const ONCHAIN_PREFERENCE: [&str; 4] = ["p2tr", "p2wpkh", "p2sh", "p2pkh"]; + +/// The `swap/1` edges an offer advertises (Paykit Capabilities §13.1), one per on-chain Payment +/// Endpoint Identifier the provider pays or accepts. The fee, minimum and `fund_within_secs` are +/// offer-wide, so every edge carries the same numbers. +pub(crate) fn edges_from_offer(offer: &SwapOffer) -> Vec { + let Some(network) = network_label(offer.network.to_bitcoin_network()) else { + return vec![]; + }; + let mut edges = vec![]; + for direction in &offer.directions { + for kind in ONCHAIN_PREFERENCE { + let onchain = format!("btc-{network}-{kind}"); + let (dir, from, to) = match direction { + SwapDirection::Reverse => ("reverse", LIGHTNING_BOLT11.to_string(), onchain), + SwapDirection::Submarine => ("submarine", onchain, LIGHTNING_BOLT11.to_string()), + }; + edges.push(SwapRouteEdge { + provider_pubky: offer.provider_pkarr.clone(), + offer_id: offer.offer_id.to_string(), + direction: dir.to_string(), + from_endpoint: from, + to_endpoint: to, + min_sat: offer.effective_min_amount_sat(), + max_sat: offer.max_amount_sat, + base_fee_sat: offer.base_fee_sat, + fee_ppm: offer.fee_ppm, + onchain_fee_sat: offer.onchain_fee_sat, + atomicity: "hash".to_string(), + fund_within_secs: offer.fund_within_secs, + }); + } + } + edges +} + +/// Indicative fee of an edge for `amount_sat`: base + ppm + on-chain (§6.2). +pub(crate) fn indicative_fee(edge: &SwapRouteEdge, amount_sat: u64) -> u64 { + let proportional = (u128::from(amount_sat) * u128::from(edge.fee_ppm) / 1_000_000) as u64; + edge.base_fee_sat + .saturating_add(proportional) + .saturating_add(edge.onchain_fee_sat) +} + +/// Reverse edges that deliver to `endpoint`, can lock `lock_sat`, stay within the client's fee +/// cap (swap-common refuses a quote above it) and that the wallet can afford over Lightning, +/// cheapest first, at most [`FANOUT_BUDGET`]. +pub(crate) fn rank_reverse_edges( + edges: Vec, + endpoint: &str, + lock_sat: u64, + lightning_spendable_sat: u64, + max_fee_bps: u16, +) -> Vec { + let max_fee = (u128::from(lock_sat) * u128::from(max_fee_bps) / 10_000) as u64; + let mut usable: Vec<_> = edges + .into_iter() + .filter(|e| e.direction == "reverse" && e.to_endpoint == endpoint) + .filter(|e| lock_sat >= e.min_sat && lock_sat <= e.max_sat) + .filter(|e| indicative_fee(e, lock_sat) <= max_fee) + .filter(|e| lock_sat.saturating_add(indicative_fee(e, lock_sat)) <= lightning_spendable_sat) + .collect(); + usable.sort_by_key(|e| indicative_fee(e, lock_sat)); + usable.truncate(FANOUT_BUDGET); + usable +} + +/// The route that costs the wallet less in fees. A hash-locked swap wins a tie: the wallet +/// trusts no one to complete it. +pub(crate) fn cheaper_route( + service: Option, + swap: Option, +) -> Option { + match (service, swap) { + (Some(leg), Some(quote)) if quote.total_fee_sat <= leg.debit_sat - leg.delivered_sat => { + Some(PaykitRoute::Swap { quote }) + } + (Some(leg), _) => Some(PaykitRoute::Service { leg }), + (None, Some(quote)) => Some(PaykitRoute::Swap { quote }), + (None, None) => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::modules::paykit_route::PaykitEndpoint; + + fn edge(provider: &str, direction: &str, base: u64, min: u64, max: u64) -> SwapRouteEdge { + SwapRouteEdge { + provider_pubky: provider.into(), + offer_id: "o".into(), + direction: direction.into(), + from_endpoint: LIGHTNING_BOLT11.into(), + to_endpoint: "btc-regtest-p2wpkh".into(), + min_sat: min, + max_sat: max, + base_fee_sat: base, + fee_ppm: 2500, + onchain_fee_sat: 500, + atomicity: "hash".into(), + fund_within_secs: 300, + } + } + + fn endpoint(method_id: &str) -> PaykitEndpoint { + PaykitEndpoint { + method_id: method_id.into(), + value: "v".into(), + } + } + + #[test] + fn ranks_reverse_edges_by_fee_within_bounds_and_budget() { + let edges = vec![ + edge("expensive", "reverse", 900, 10_000, 1_000_000), + edge("cheap", "reverse", 100, 10_000, 1_000_000), + edge("submarine", "submarine", 0, 10_000, 1_000_000), + edge("too-small", "reverse", 0, 10_000, 15_000), + edge("min-too-high", "reverse", 0, 50_000, 1_000_000), + ]; + let ranked = rank_reverse_edges(edges, "btc-regtest-p2wpkh", 20_000, 1_000_000, 10_000); + let names: Vec<_> = ranked.iter().map(|e| e.provider_pubky.as_str()).collect(); + assert_eq!(names, ["cheap", "expensive"]); + } + + #[test] + fn drops_edges_the_wallet_cannot_afford() { + let edges = vec![edge("p", "reverse", 100, 10_000, 1_000_000)]; + // 20,000 locked + 100 + 50 + 500 fee = 20,650. + let rank = |spendable| { + rank_reverse_edges(edges.clone(), "btc-regtest-p2wpkh", 20_000, spendable, 500) + }; + assert!(rank(20_649).is_empty()); + assert_eq!(rank(20_650).len(), 1); + } + + #[test] + fn indicative_fee_matches_the_offer_formula() { + let e = edge("p", "reverse", 100, 0, u64::MAX); + assert_eq!(indicative_fee(&e, 100_000), 100 + 250 + 500); + } + + fn leg( + service: &str, + method_id: &str, + delivered: u64, + debit: u64, + until: u64, + ) -> ServiceRouteLeg { + ServiceRouteLeg { + service: service.into(), + endpoint: endpoint(method_id), + delivered_sat: delivered, + debit_sat: debit, + atomicity: "trusted".into(), + valid_until_unix: until, + } + } + + fn swap_quote(total_fee_sat: u64) -> PubkySwapRouteQuote { + PubkySwapRouteQuote { + provider_pubky: "p".into(), + quote_id: "q".into(), + endpoint: endpoint("btc-regtest-p2wpkh"), + delivered_sat: 20_000, + lock_sat: 20_200, + debit_sat: 20_000 + total_fee_sat, + service_fee_sat: 0, + provider_onchain_fee_sat: 0, + claim_fee_sat: 200, + total_fee_sat, + atomicity: "hash".into(), + valid_until_unix: 0, + providers_quoted: 1, + } + } + + #[test] + fn picks_the_route_with_the_lower_fee_and_the_swap_on_a_tie() { + let service = leg("spark", "btc-regtest-p2wpkh", 20_000, 20_500, 0); + let pick = |swap_fee| cheaper_route(Some(service.clone()), Some(swap_quote(swap_fee))); + assert!(matches!(pick(499), Some(PaykitRoute::Swap { .. }))); + assert!(matches!(pick(500), Some(PaykitRoute::Swap { .. }))); + assert!(matches!(pick(501), Some(PaykitRoute::Service { .. }))); + assert!(matches!( + cheaper_route(Some(service), None), + Some(PaykitRoute::Service { .. }) + )); + assert!(cheaper_route(None, None).is_none()); + } + + #[test] + fn drops_edges_above_the_client_fee_cap_and_other_endpoints() { + // 100 + 50 + 500 = 650 sats on 20,000 is 3.25%: under the 5% cap, over a 3% one. + let edges = vec![edge("p", "reverse", 100, 10_000, 1_000_000)]; + assert_eq!( + rank_reverse_edges(edges.clone(), "btc-regtest-p2wpkh", 20_000, 1_000_000, 500).len(), + 1 + ); + assert!( + rank_reverse_edges(edges.clone(), "btc-regtest-p2wpkh", 20_000, 1_000_000, 300) + .is_empty() + ); + assert!(rank_reverse_edges(edges, "btc-regtest-p2tr", 20_000, 1_000_000, 500).is_empty()); + } +} diff --git a/src/modules/pubky_swaps/store.rs b/src/modules/pubky_swaps/store.rs new file mode 100644 index 00000000..bcd69f36 --- /dev/null +++ b/src/modules/pubky_swaps/store.rs @@ -0,0 +1,230 @@ +//! One JSON file per swap under `/pubky_swaps/`. +//! +//! A record holds the swap's key index, not its keys, which come from the seed and the index. Its +//! saved claim does carry the preimage, before the claim is broadcast too. The contract is synced +//! to disk before the invoice is handed to the app. + +use std::fs; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, RwLock}; + +use serde::{Deserialize, Serialize}; +use swap_common::messages::{Quote, SwapAccept}; +use swap_common::paykit_cap::ContractReply; + +use super::errors::PubkySwapError; + +/// The current base path; `init_db` may move it, like every other store it opens. +static BASE: RwLock> = RwLock::new(None); +static LOCK: Mutex<()> = Mutex::new(()); + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(crate) struct SwapRecord { + pub swap_id: String, + /// Hex of the random index the swap's claim key and preimage derive from (see `keys`). + pub key_index: String, + pub provider_pubky: String, + pub network: bitcoin::Network, + pub electrum_url: String, + /// The quote this wallet committed to; absent for a swap rebuilt from a provider's listing. + #[serde(default)] + pub quote: Option, + /// Lockup confirmations the provider requires before the claim. + pub required_confirmations: u32, + pub accept: SwapAccept, + pub destination_address: String, + pub delivered_sat: u64, + pub claim_fee_sat: u64, + pub claim_txid: Option, + /// The signed claim, kept so it can be broadcast again while it is unconfirmed. + #[serde(default)] + pub claim_tx_hex: Option, + /// Whether a broadcast of the claim was ever attempted, so its preimage may be public. + #[serde(default)] + pub claim_published: bool, + /// Whether the server accepted the claim or it showed up in the chain's history. + #[serde(default)] + pub claim_seen: bool, + /// A restored swap whose provider listed a claim it saw, which the chain has not shown, and + /// whose payment the wallet's node shows settled. Its preimage is public, so the wallet claims + /// once the lockup has its confirmations, whatever the window. + #[serde(default)] + pub claim_listed: bool, + /// The contract the provider signed over this wallet's commit; absent for a swap rebuilt + /// from a provider's listing. + #[serde(default)] + pub contract: Option, + pub created_at_unix: u64, +} + +pub(crate) fn init(base_path: &str) -> Result<(), PubkySwapError> { + let dir = Path::new(base_path).join("pubky_swaps"); + fs::create_dir_all(&dir)?; + *BASE.write().unwrap() = Some(dir); + Ok(()) +} + +fn dir() -> Result { + BASE.read() + .unwrap() + .clone() + .ok_or_else(|| PubkySwapError::storage("Database not initialized. Call init_db first.")) +} + +fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), PubkySwapError> { + let tmp = path.with_extension("tmp"); + let mut file = fs::File::create(&tmp)?; + file.write_all(bytes)?; + file.sync_all()?; + fs::rename(tmp, path)?; + if let Some(parent) = path.parent() { + fs::File::open(parent)?.sync_all()?; + } + Ok(()) +} + +pub(crate) fn save(record: &SwapRecord) -> Result<(), PubkySwapError> { + let _guard = LOCK.lock().unwrap(); + let path = dir()?.join(format!("{}.json", record.swap_id)); + write_atomic(&path, &serde_json::to_vec_pretty(record)?) +} + +/// Saves a new swap, refusing an id already on file: the provider names the id, so an acceptance +/// that reused an earlier swap's would otherwise replace its contract, key index and saved claim. +pub(crate) fn create(record: &SwapRecord) -> Result<(), PubkySwapError> { + let _guard = LOCK.lock().unwrap(); + let path = dir()?.join(format!("{}.json", record.swap_id)); + if path.try_exists()? { + return Err(PubkySwapError::storage(format!( + "swap {} is already on file", + record.swap_id + ))); + } + write_atomic(&path, &serde_json::to_vec_pretty(record)?) +} + +/// Every record on file. A file that cannot be read is skipped with a warning. +pub(crate) fn list() -> Result, PubkySwapError> { + let mut records = vec![]; + for entry in fs::read_dir(dir()?)? { + let path = entry?.path(); + if path.extension().is_some_and(|ext| ext == "json") { + match fs::read(&path) + .map_err(PubkySwapError::from) + .and_then(|bytes| Ok(serde_json::from_slice(&bytes)?)) + { + Ok(record) => records.push(record), + Err(e) => log::warn!("pubky swaps: skipping {}: {e}", path.display()), + } + } + } + Ok(records) +} + +pub(crate) fn load(swap_id: &str) -> Result { + let path = dir()?.join(format!("{swap_id}.json")); + match fs::read(&path) { + Ok(bytes) => Ok(serde_json::from_slice(&bytes)?), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Err(PubkySwapError::NotFound { + error_details: swap_id.to_string(), + }), + Err(e) => Err(e.into()), + } +} + +/// Removes every swap record from disk. +pub(crate) fn wipe_all() -> Result<(), PubkySwapError> { + let _guard = LOCK.lock().unwrap(); + let dir = dir()?; + if dir.exists() { + for entry in fs::read_dir(&dir)? { + let entry = entry?; + let path = entry.path(); + if path.is_file() { + fs::remove_file(&path)?; + } else if path.is_dir() { + fs::remove_dir_all(&path)?; + } + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use swap_common::messages::SwapScript; + use swap_common::SwapDirection; + use uuid::Uuid; + + fn sample_record(swap_id: &str) -> SwapRecord { + let provider_secret = bitcoin::secp256k1::SecretKey::from_slice(&[9; 32]).unwrap(); + let provider = bitcoin::PublicKey::new( + provider_secret.public_key(&bitcoin::secp256k1::Secp256k1::new()), + ); + SwapRecord { + swap_id: swap_id.to_string(), + key_index: hex::encode([7; 32]), + provider_pubky: "pk:test_provider".to_string(), + network: bitcoin::Network::Regtest, + electrum_url: "tcp://127.0.0.1:60001".to_string(), + quote: None, + required_confirmations: 1, + accept: SwapAccept { + script_type: SwapScript::P2wsh, + swap_tree: None, + quote_id: Uuid::new_v4(), + swap_id: Uuid::new_v4(), + direction: SwapDirection::Reverse, + htlc_script_hex: String::new(), + htlc_address: String::new(), + onchain_amount_sat: 20_000, + timeout_block_height: 1_200, + provider_pubkey_hex: provider.to_string(), + invoice: None, + }, + destination_address: "bcrt1qtest".to_string(), + delivered_sat: 20_000, + claim_fee_sat: 200, + claim_txid: None, + claim_tx_hex: None, + claim_published: false, + claim_seen: false, + claim_listed: false, + contract: None, + created_at_unix: 1_700_000_000, + } + } + + #[test] + fn test_store_wipe_all() { + let temp_dir = + std::env::temp_dir().join(format!("pubky_swaps_store_test_{}", rand::random::())); + std::fs::create_dir_all(&temp_dir).unwrap(); + init(temp_dir.to_str().unwrap()).unwrap(); + + let rec1 = sample_record("swap-1"); + let rec2 = sample_record("swap-2"); + create(&rec1).unwrap(); + create(&rec2).unwrap(); + + let listed = list().unwrap(); + assert_eq!(listed.len(), 2); + assert!(load("swap-1").is_ok()); + assert!(load("swap-2").is_ok()); + + wipe_all().unwrap(); + + let listed_after = list().unwrap(); + assert_eq!(listed_after.len(), 0); + assert!(load("swap-1").is_err()); + assert!(load("swap-2").is_err()); + + // Can create again after wipe + create(&rec1).unwrap(); + assert_eq!(list().unwrap().len(), 1); + + let _ = std::fs::remove_dir_all(&temp_dir); + } +} diff --git a/src/modules/pubky_swaps/transport.rs b/src/modules/pubky_swaps/transport.rs new file mode 100644 index 00000000..475e9294 --- /dev/null +++ b/src/modules/pubky_swaps/transport.rs @@ -0,0 +1,150 @@ +//! Requests to a Pubky Swaps provider over iroh `pubky-swap/direct/1`. +//! +//! The provider authenticates the request by the connection's key, so this needs no +//! homeserver on either side. Each request opens a stream, writes `{"message": …}`, and reads +//! the provider's reply: one `SwapMessage`, or one signed `paykit-cap.*` message. + +use std::time::Duration; + +use iroh::endpoint::presets; +use iroh::{Endpoint, PublicKey as EndpointId, SecretKey}; +use serde::Serialize; +use serde_json::json; +use swap_common::messages::SwapMessage; +use swap_common::paykit_cap::{is_cap_message, CapMessage}; + +use super::errors::PubkySwapError; + +const DIRECT_ALPN: &[u8] = b"pubky-swap/direct/1"; +const MAX_REPLY_BYTES: usize = 64 * 1024; +const CONNECT_TIMEOUT: Duration = Duration::from_secs(20); +const REQUEST_TIMEOUT: Duration = Duration::from_secs(60); +const ONLINE_TIMEOUT: Duration = Duration::from_secs(10); + +#[derive(Clone)] +pub(crate) struct DirectClient { + endpoint: Endpoint, +} + +impl DirectClient { + /// Bind an endpoint whose id is the wallet's swap identity. + pub(crate) async fn bind(identity_secret: [u8; 32]) -> Result { + let endpoint = Endpoint::builder(presets::N0) + .secret_key(SecretKey::from_bytes(&identity_secret)) + .bind() + .await + .map_err(PubkySwapError::transport)?; + // Reaching a provider needs a home relay; without one the first connects all time out. + if tokio::time::timeout(ONLINE_TIMEOUT, endpoint.online()) + .await + .is_err() + { + log::warn!("pubky swaps: no home relay after {ONLINE_TIMEOUT:?}"); + } + Ok(Self { endpoint }) + } + + /// Send one plain request to `provider_pubky` and return its reply. + pub(crate) async fn request( + &self, + provider_pubky: &str, + message: &SwapMessage, + ) -> Result { + let reply = self.round_trip(provider_pubky, message).await?; + serde_json::from_slice(&reply) + .map_err(|e| PubkySwapError::transport(format!("unreadable reply: {e}"))) + } + + /// Send one `paykit-cap.*` request. Any reply that is not a `paykit-cap.*` message is refused, + /// so a provider cannot answer a signed request with an unsigned one. + pub(crate) async fn request_cap( + &self, + provider_pubky: &str, + message: &CapMessage, + ) -> Result { + cap_reply(&self.round_trip(provider_pubky, message).await?) + } + + async fn round_trip( + &self, + provider_pubky: &str, + message: &impl Serialize, + ) -> Result, PubkySwapError> { + let provider = provider_endpoint_id(provider_pubky)?; + let body = serde_json::to_vec(&json!({ "message": message }))?; + let conn = tokio::time::timeout( + CONNECT_TIMEOUT, + self.endpoint.connect(provider, DIRECT_ALPN), + ) + .await + .map_err(|_| PubkySwapError::transport("timed out connecting to the provider"))? + .map_err(PubkySwapError::transport)?; + let reply = tokio::time::timeout(REQUEST_TIMEOUT, async { + let (mut send, mut recv) = conn.open_bi().await.map_err(PubkySwapError::transport)?; + send.write_all(&body) + .await + .map_err(PubkySwapError::transport)?; + send.finish().map_err(PubkySwapError::transport)?; + recv.read_to_end(MAX_REPLY_BYTES) + .await + .map_err(PubkySwapError::transport) + }) + .await + .map_err(|_| PubkySwapError::transport("timed out waiting for the provider"))??; + conn.close(0u32.into(), b"done"); + Ok(reply) + } + + pub(crate) async fn close(self) { + self.endpoint.close().await; + } +} + +/// A reply to a `paykit-cap.*` request, refused unless it is one too. +fn cap_reply(reply: &[u8]) -> Result { + let value: serde_json::Value = serde_json::from_slice(reply) + .map_err(|e| PubkySwapError::transport(format!("unreadable reply: {e}")))?; + if !is_cap_message(&value) { + return Err(PubkySwapError::validation( + "the provider answered a signed request with an unsigned reply", + )); + } + serde_json::from_value(value) + .map_err(|e| PubkySwapError::transport(format!("unreadable reply: {e}"))) +} + +/// A pubky and an iroh endpoint id are the same Ed25519 key. +pub(crate) fn provider_endpoint_id(provider_pubky: &str) -> Result { + let bare = bare_pubky(provider_pubky); + let key = pubky::PublicKey::try_from_z32(bare) + .map_err(|e| PubkySwapError::invalid(format!("provider pubky: {e}")))?; + EndpointId::from_bytes(&key.to_bytes()) + .map_err(|e| PubkySwapError::invalid(format!("provider pubky: {e}"))) +} + +/// The 52-character z-base-32 key, with any `pubky://` or `pubky` display prefix removed. +pub(crate) fn bare_pubky(pubky: &str) -> &str { + let pubky = pubky.trim(); + let pubky = pubky.strip_prefix("pubky://").unwrap_or(pubky); + match pubky.strip_prefix("pubky") { + Some(rest) if rest.len() == 52 => rest, + _ => pubky, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn refuses_an_unsigned_reply_to_a_signed_request() { + let plain = br#"{"type":"swap_accept","quote_id":"00000000-0000-0000-0000-000000000000"}"#; + assert!(matches!( + cap_reply(plain), + Err(PubkySwapError::Validation { .. }) + )); + let refusal = + br#"{"kind":"paykit-cap.refusal","body":{"code":"offer_stale","reason":"r"}}"#; + assert!(matches!(cap_reply(refusal), Ok(CapMessage::Refusal(_)))); + } +} diff --git a/src/modules/pubky_swaps/types.rs b/src/modules/pubky_swaps/types.rs new file mode 100644 index 00000000..81f78bef --- /dev/null +++ b/src/modules/pubky_swaps/types.rs @@ -0,0 +1,123 @@ +use serde::{Deserialize, Serialize}; + +pub use crate::modules::paykit_route::{ + PaykitEndpoint, PaykitRoute, PaykitRouteRequest, ServiceRouteLeg, +}; + +/// A `swap/1` edge from a provider's offer, in Paykit Capabilities terms: the payment endpoint +/// the owner pays from, the endpoint the route delivers to, its bounds and its indicative fee. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, uniffi::Record)] +pub struct SwapRouteEdge { + pub provider_pubky: String, + pub offer_id: String, + /// `reverse` (Lightning to on-chain) or `submarine` (on-chain to Lightning). + pub direction: String, + /// Payment Endpoint Identifier the owner pays with, such as `btc-lightning-bolt11`. + pub from_endpoint: String, + /// Payment Endpoint Identifier the route delivers to, such as `btc-regtest-p2wpkh`. + pub to_endpoint: String, + /// The minimum the provider enforces, not its configured floor. + pub min_sat: u64, + pub max_sat: u64, + pub base_fee_sat: u64, + pub fee_ppm: u64, + pub onchain_fee_sat: u64, + /// Atomicity class of the edge. Pubky Swaps legs are always `hash`. + pub atomicity: String, + pub fund_within_secs: u64, +} + +/// A firm `swap/1` quote for one route, with everything the review screen shows. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, uniffi::Record)] +pub struct PubkySwapRouteQuote { + pub provider_pubky: String, + /// The wallet's id for this route, which `pubky_swaps_commit_route` takes. The provider's own + /// quote id stays inside bitkit-core. + pub quote_id: String, + /// The contact endpoint the swap delivers to. + pub endpoint: PaykitEndpoint, + /// What the contact receives. + pub delivered_sat: u64, + /// What the provider locks on chain: the delivered amount plus the wallet's claim fee. + pub lock_sat: u64, + /// What the wallet pays over Lightning. + pub debit_sat: u64, + pub service_fee_sat: u64, + pub provider_onchain_fee_sat: u64, + pub claim_fee_sat: u64, + /// `debit_sat - delivered_sat`. + pub total_fee_sat: u64, + pub atomicity: String, + pub valid_until_unix: u64, + /// How many providers were asked for a quote. + pub providers_quoted: u32, +} + +/// A committed swap: the hold invoice the wallet pays to start it. +#[derive(Debug, Clone, uniffi::Record)] +pub struct PubkySwapRoutePayment { + pub swap_id: String, + pub invoice: String, + pub debit_sat: u64, + pub delivered_sat: u64, + pub destination_address: String, + pub htlc_address: String, + pub timeout_block_height: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq, uniffi::Enum)] +pub enum PubkySwapRouteState { + /// Waiting for the hold invoice to be paid. + AwaitingPayment, + /// Paid; waiting for the provider's on-chain lockup, or for its confirmations. + AwaitingLockup { + confirmations: u32, + required: u32, + }, + /// The claim to the contact's address is broadcast but not confirmed yet. The provider settles + /// the invoice once it sees the preimage; keep calling until the claim confirms. + ClaimBroadcast { + txid: String, + }, + /// The claim to the contact's address is confirmed. + Claimed { + txid: String, + }, + Failed { + reason: String, + }, +} + +/// A Lightning payment the wallet's node sent, which `pubky_swaps_restore` matches to a listed +/// swap by its hash. +#[derive(Debug, Clone, uniffi::Record)] +pub struct PubkySwapSentPayment { + pub payment_hash_hex: String, + /// What the payment paid the provider, routing fees excluded. + pub amount_sat: u64, + /// Whether the payment settled, so the provider holds the preimage. A pending payment is + /// still in flight. + pub settled: bool, +} + +/// What `pubky_swaps_restore` found, by swap id. +#[derive(Debug, Clone, Default, uniffi::Record)] +pub struct PubkySwapRestoreReport { + /// Swaps rebuilt now; drive each with `pubky_swaps_advance`. + pub restored: Vec, + /// Swaps already on record, listed again; drive the unfinished ones with `pubky_swaps_advance`. + pub known: Vec, + /// Swaps the provider lists as finished, which get no record. + pub finished: Vec, + /// Providers whose list was not read in full; restore again later to finish it. + pub incomplete_providers: Vec, +} + +#[derive(Debug, Clone, uniffi::Record)] +pub struct PubkySwapRouteStatus { + pub swap_id: String, + pub state: PubkySwapRouteState, + pub provider_pubky: String, + pub delivered_sat: u64, + pub destination_address: String, +}