diff --git a/AGENTS.md b/AGENTS.md index acc6fbc4..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, paykit_route, pubky_swaps, 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, paykit_route, pubky_swaps, 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/CHANGELOG.md b/CHANGELOG.md index 0793371f..608c2172 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,6 @@ ## Unreleased -- Remove the `pubky` module (breaking). Pubky auth goes through Paykit grant links. Removed exports: the legacy Pubky Ring auth `parse_pubky_auth_url` and `approve_pubky_auth`, plus the unused `resolve_pubky_url`, `fetch_pubky_file`, `fetch_pubky_file_string`, `start_pubky_auth`, `cancel_pubky_auth`, `complete_pubky_auth`, `fetch_pubky_profile`, `fetch_pubky_contacts`, `derive_pubky_secret_key`, `pubky_public_key_from_secret`, `pubky_sign_up`, `pubky_sign_in`, `pubky_session_put`, `pubky_session_delete`, `pubky_session_list` and `pubky_put_with_secret_key`. Removed types: the `PubkyProfile` and `PubkyProfileLink` records, `PubkyAuthDetails`, `PubkyAuthKind` and `PubkyError` (`PubkyException` on Android). Drop the `pubky-app-specs` dependency. Pubky Swaps reads a provider's published signing key records as before. - Decode BIP 321 `bitcoin:` URIs without an address. `bitcoin:?lightning=` (served over NFC by Numo point-of-sale terminals, and planned by Square, which serves `lightning:` today) returns `Scanner::Lightning`, and a segwit address in the `bc`, `tb` or `bcrt` parameter returns `Scanner::OnChain` with that address, keeping other instructions such as `lightning` in `params`. An address in the wrong parameter (`bc=tb1…`) returns `InvalidAddress`. `lno`, `sp` or `pay` alone returns `UnsupportedType`, and no payment instruction returns `InvalidAddress` as before. Any `req-` parameter, `req-pop` included, now returns `InvalidFormat`, because Bitkit handles none of them and BIP 321 forbids paying such a URI (breaking for callers that paid `req-pop` URIs). - Update `lightning` to 0.2.8. - `regtest_mine`, `regtest_deposit`, `regtest_pay`, `regtest_get_payment` and `regtest_close_channel` take an optional `auth` (`user:password`), sent as basic auth to Blocktank servers that protect the regtest routes; a 401 returns a clear error. diff --git a/Cargo.lock b/Cargo.lock index 3e2e98dc..75333b0b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1072,7 +1072,8 @@ dependencies = [ "once_cell", "openssl", "prost", - "pubky", + "pubky 0.6.0", + "pubky-app-specs", "r2d2", "r2d2_sqlite", "rand 0.8.5", @@ -1668,6 +1669,20 @@ dependencies = [ "version_check", ] +[[package]] +name = "cookie_store" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2eac901828f88a5241ee0600950ab981148a18f2f756900ffba1b125ca6a3ef9" +dependencies = [ + "cookie", + "document-features", + "idna", + "log", + "time", + "url", +] + [[package]] name = "cookie_store" version = "0.22.1" @@ -4214,6 +4229,12 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + [[package]] name = "minicbor" version = "2.3.0" @@ -5558,6 +5579,31 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "pubky" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f7fe978ba733fdb614320e9b1f3910cfecf0509530511c8ba12cc8d32f8bc8" +dependencies = [ + "anyhow", + "base64 0.22.1", + "bytes", + "cookie", + "cookie_store 0.21.1", + "flume", + "futures-lite", + "futures-util", + "log", + "pkarr", + "pubky-common 0.5.4", + "reqwest 0.12.28", + "thiserror 2.0.18", + "tokio", + "tracing", + "url", + "wasm-bindgen-futures", +] + [[package]] name = "pubky" version = "0.6.0" @@ -5572,7 +5618,7 @@ dependencies = [ "httpdate", "log", "pkarr", - "pubky-common", + "pubky-common 0.6.0", "reqwest 0.12.28", "thiserror 2.0.18", "tokio", @@ -5582,6 +5628,46 @@ dependencies = [ "web-time", ] +[[package]] +name = "pubky-app-specs" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "768489143c50693e617f2efd6b2498be0c8b0ac6280b4ba59067a3afc8b01477" +dependencies = [ + "base32", + "blake3", + "js-sys", + "mime", + "pubky 0.5.4", + "serde", + "serde-wasm-bindgen", + "serde_json", + "url", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "pubky-common" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f078584beadafe3bc8669bfd6b245f10f42b8bea24e7ccbff0e09886e310ba9b" +dependencies = [ + "argon2", + "base32", + "blake3", + "crypto_secretbox", + "ed25519-dalek 2.2.0", + "js-sys", + "once_cell", + "pkarr", + "postcard", + "pubky-timestamp", + "rand 0.9.2", + "serde", + "thiserror 2.0.18", +] + [[package]] name = "pubky-common" version = "0.6.0" @@ -5942,7 +6028,7 @@ dependencies = [ "base64 0.22.1", "bytes", "cookie", - "cookie_store", + "cookie_store 0.22.1", "futures-core", "http", "http-body", @@ -6683,6 +6769,17 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-wasm-bindgen" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8302e169f0eddcc139c70f139d19d6467353af16f9fce27e8c30158036a1e16b" +dependencies = [ + "js-sys", + "serde", + "wasm-bindgen", +] + [[package]] name = "serde-xml-rs" version = "0.8.2" diff --git a/Cargo.toml b/Cargo.toml index 3a95e72e..d069fed7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -47,6 +47,7 @@ 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" } diff --git a/bindings/ios/bitkitcore.swift b/bindings/ios/bitkitcore.swift index 5eac138e..6b646266 100644 --- a/bindings/ios/bitkitcore.swift +++ b/bindings/ios/bitkitcore.swift @@ -12019,6 +12019,303 @@ public func FfiConverterTypePubkyAuth_lower(_ value: PubkyAuth) -> RustBuffer { } +/** + * Details extracted from a `pubkyauth://` deep-link URL. + */ +public struct PubkyAuthDetails { + /** + * Whether this is a signin or signup flow. + */ + public var kind: PubkyAuthKind + /** + * Requested capabilities (e.g. `"/pub/pubky.app/:rw"`). + */ + public var capabilities: String + /** + * Relay URL used for the auth exchange. + */ + public var relay: String + /** + * Homeserver public key (z32-encoded). Present only for signup flows. + */ + public var homeserver: String? + /** + * Signup token. Present only for signup flows. + */ + public var signupToken: String? + + // Default memberwise initializers are never public by default, so we + // declare one manually. + public init( + /** + * Whether this is a signin or signup flow. + */kind: PubkyAuthKind, + /** + * Requested capabilities (e.g. `"/pub/pubky.app/:rw"`). + */capabilities: String, + /** + * Relay URL used for the auth exchange. + */relay: String, + /** + * Homeserver public key (z32-encoded). Present only for signup flows. + */homeserver: String?, + /** + * Signup token. Present only for signup flows. + */signupToken: String?) { + self.kind = kind + self.capabilities = capabilities + self.relay = relay + self.homeserver = homeserver + self.signupToken = signupToken + } +} + +#if compiler(>=6) +extension PubkyAuthDetails: Sendable {} +#endif + + +extension PubkyAuthDetails: Equatable, Hashable { + public static func ==(lhs: PubkyAuthDetails, rhs: PubkyAuthDetails) -> Bool { + if lhs.kind != rhs.kind { + return false + } + if lhs.capabilities != rhs.capabilities { + return false + } + if lhs.relay != rhs.relay { + return false + } + if lhs.homeserver != rhs.homeserver { + return false + } + if lhs.signupToken != rhs.signupToken { + return false + } + return true + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(kind) + hasher.combine(capabilities) + hasher.combine(relay) + hasher.combine(homeserver) + hasher.combine(signupToken) + } +} + +extension PubkyAuthDetails: Codable {} + + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypePubkyAuthDetails: FfiConverterRustBuffer { + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PubkyAuthDetails { + return + try PubkyAuthDetails( + kind: FfiConverterTypePubkyAuthKind.read(from: &buf), + capabilities: FfiConverterString.read(from: &buf), + relay: FfiConverterString.read(from: &buf), + homeserver: FfiConverterOptionString.read(from: &buf), + signupToken: FfiConverterOptionString.read(from: &buf) + ) + } + + public static func write(_ value: PubkyAuthDetails, into buf: inout [UInt8]) { + FfiConverterTypePubkyAuthKind.write(value.kind, into: &buf) + FfiConverterString.write(value.capabilities, into: &buf) + FfiConverterString.write(value.relay, into: &buf) + FfiConverterOptionString.write(value.homeserver, into: &buf) + FfiConverterOptionString.write(value.signupToken, into: &buf) + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypePubkyAuthDetails_lift(_ buf: RustBuffer) throws -> PubkyAuthDetails { + return try FfiConverterTypePubkyAuthDetails.lift(buf) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypePubkyAuthDetails_lower(_ value: PubkyAuthDetails) -> RustBuffer { + return FfiConverterTypePubkyAuthDetails.lower(value) +} + + +public struct PubkyProfile { + public var name: String + public var bio: String? + public var image: String? + public var links: [PubkyProfileLink]? + public var status: String? + + // Default memberwise initializers are never public by default, so we + // declare one manually. + public init(name: String, bio: String?, image: String?, links: [PubkyProfileLink]?, status: String?) { + self.name = name + self.bio = bio + self.image = image + self.links = links + self.status = status + } +} + +#if compiler(>=6) +extension PubkyProfile: Sendable {} +#endif + + +extension PubkyProfile: Equatable, Hashable { + public static func ==(lhs: PubkyProfile, rhs: PubkyProfile) -> Bool { + if lhs.name != rhs.name { + return false + } + if lhs.bio != rhs.bio { + return false + } + if lhs.image != rhs.image { + return false + } + if lhs.links != rhs.links { + return false + } + if lhs.status != rhs.status { + return false + } + return true + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(name) + hasher.combine(bio) + hasher.combine(image) + hasher.combine(links) + hasher.combine(status) + } +} + +extension PubkyProfile: Codable {} + + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypePubkyProfile: FfiConverterRustBuffer { + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PubkyProfile { + return + try PubkyProfile( + name: FfiConverterString.read(from: &buf), + bio: FfiConverterOptionString.read(from: &buf), + image: FfiConverterOptionString.read(from: &buf), + links: FfiConverterOptionSequenceTypePubkyProfileLink.read(from: &buf), + status: FfiConverterOptionString.read(from: &buf) + ) + } + + public static func write(_ value: PubkyProfile, into buf: inout [UInt8]) { + FfiConverterString.write(value.name, into: &buf) + FfiConverterOptionString.write(value.bio, into: &buf) + FfiConverterOptionString.write(value.image, into: &buf) + FfiConverterOptionSequenceTypePubkyProfileLink.write(value.links, into: &buf) + FfiConverterOptionString.write(value.status, into: &buf) + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypePubkyProfile_lift(_ buf: RustBuffer) throws -> PubkyProfile { + return try FfiConverterTypePubkyProfile.lift(buf) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypePubkyProfile_lower(_ value: PubkyProfile) -> RustBuffer { + return FfiConverterTypePubkyProfile.lower(value) +} + + +public struct PubkyProfileLink { + public var title: String + public var url: String + + // Default memberwise initializers are never public by default, so we + // declare one manually. + public init(title: String, url: String) { + self.title = title + self.url = url + } +} + +#if compiler(>=6) +extension PubkyProfileLink: Sendable {} +#endif + + +extension PubkyProfileLink: Equatable, Hashable { + public static func ==(lhs: PubkyProfileLink, rhs: PubkyProfileLink) -> Bool { + if lhs.title != rhs.title { + return false + } + if lhs.url != rhs.url { + return false + } + return true + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(title) + hasher.combine(url) + } +} + +extension PubkyProfileLink: Codable {} + + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypePubkyProfileLink: FfiConverterRustBuffer { + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PubkyProfileLink { + return + try PubkyProfileLink( + title: FfiConverterString.read(from: &buf), + url: FfiConverterString.read(from: &buf) + ) + } + + public static func write(_ value: PubkyProfileLink, into buf: inout [UInt8]) { + FfiConverterString.write(value.title, into: &buf) + FfiConverterString.write(value.url, into: &buf) + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypePubkyProfileLink_lift(_ buf: RustBuffer) throws -> PubkyProfileLink { + return try FfiConverterTypePubkyProfileLink.lift(buf) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypePubkyProfileLink_lower(_ value: PubkyProfileLink) -> RustBuffer { + return FfiConverterTypePubkyProfileLink.lower(value) +} + + /** * What `pubky_swaps_restore` found, by swap id. */ @@ -26190,99 +26487,324 @@ extension PsbtCompletionError: Foundation.LocalizedError { - +// Note that we don't yet support `indirect` for enums. +// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion. /** - * Errors surfaced by the Pubky Swaps route module. + * The type of a `pubkyauth://` deep-link flow. */ -public enum PubkySwapError: Swift.Error { +public enum PubkyAuthKind { - - 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 - ) + case signin + case signup } +#if compiler(>=6) +extension PubkyAuthKind: Sendable {} +#endif + #if swift(>=5.8) @_documentation(visibility: private) #endif -public struct FfiConverterTypePubkySwapError: FfiConverterRustBuffer { - typealias SwiftType = PubkySwapError +public struct FfiConverterTypePubkyAuthKind: FfiConverterRustBuffer { + typealias SwiftType = PubkyAuthKind - public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PubkySwapError { + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PubkyAuthKind { let variant: Int32 = try readInt(&buf) switch variant { - - + case 1: return .signin - 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 + case 2: return .signup + + default: throw UniffiInternalError.unexpectedEnumCase } } - public static func write(_ value: PubkySwapError, into buf: inout [UInt8]) { + public static func write(_ value: PubkyAuthKind, into buf: inout [UInt8]) { switch value { - - - - case let .InvalidInput(errorDetails): + case .signin: writeInt(&buf, Int32(1)) - FfiConverterString.write(errorDetails, into: &buf) - - case let .Transport(errorDetails): + + case .signup: 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) - + } + } +} + + +#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)) @@ -30641,6 +31163,30 @@ fileprivate struct FfiConverterOptionSequenceTypeIManualRefund: FfiConverterRust } } +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +fileprivate struct FfiConverterOptionSequenceTypePubkyProfileLink: FfiConverterRustBuffer { + typealias SwiftType = [PubkyProfileLink]? + + public static func write(_ value: SwiftType, into buf: inout [UInt8]) { + guard let value = value else { + writeInt(&buf, Int8(0)) + return + } + writeInt(&buf, Int8(1)) + FfiConverterSequenceTypePubkyProfileLink.write(value, into: &buf) + } + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType { + switch try readInt(&buf) as Int8 { + case 0: return nil + case 1: return try FfiConverterSequenceTypePubkyProfileLink.read(from: &buf) + default: throw UniffiInternalError.unexpectedOptionalTag + } + } +} + #if swift(>=5.8) @_documentation(visibility: private) #endif @@ -31240,6 +31786,31 @@ fileprivate struct FfiConverterSequenceTypePreActivityMetadata: FfiConverterRust } } +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +fileprivate struct FfiConverterSequenceTypePubkyProfileLink: FfiConverterRustBuffer { + typealias SwiftType = [PubkyProfileLink] + + public static func write(_ value: [PubkyProfileLink], into buf: inout [UInt8]) { + let len = Int32(value.count) + writeInt(&buf, len) + for item in value { + FfiConverterTypePubkyProfileLink.write(item, into: &buf) + } + } + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [PubkyProfileLink] { + let len: Int32 = try readInt(&buf) + var seq = [PubkyProfileLink]() + seq.reserveCapacity(Int(len)) + for _ in 0 ..< len { + seq.append(try FfiConverterTypePubkyProfileLink.read(from: &buf)) + } + return seq + } +} + #if swift(>=5.8) @_documentation(visibility: private) #endif @@ -32138,6 +32709,20 @@ public func addTags(walletId: String, activityId: String, tags: [String])throws ) } } +public func approvePubkyAuth(authUrl: String, secretKeyHex: String)async throws { + return + try await uniffiRustCallAsync( + rustFutureFunc: { + uniffi_bitkitcore_fn_func_approve_pubky_auth(FfiConverterString.lower(authUrl),FfiConverterString.lower(secretKeyHex) + ) + }, + pollFunc: ffi_bitkitcore_rust_future_poll_void, + completeFunc: ffi_bitkitcore_rust_future_complete_void, + freeFunc: ffi_bitkitcore_rust_future_free_void, + liftFunc: { $0 }, + errorHandler: FfiConverterTypePubkyError_lift + ) +} public func blocktankRemoveAllCjitEntries()async throws { return try await uniffiRustCallAsync( @@ -32428,6 +33013,20 @@ public func calculateChannelLiquidityOptions(params: ChannelLiquidityParams) -> ) }) } +public func cancelPubkyAuth()async throws { + return + try await uniffiRustCallAsync( + rustFutureFunc: { + uniffi_bitkitcore_fn_func_cancel_pubky_auth( + ) + }, + pollFunc: ffi_bitkitcore_rust_future_poll_void, + completeFunc: ffi_bitkitcore_rust_future_complete_void, + freeFunc: ffi_bitkitcore_rust_future_free_void, + liftFunc: { $0 }, + errorHandler: FfiConverterTypePubkyError_lift + ) +} public func checkSweepableBalances(mnemonicPhrase: String, network: Network?, bip39Passphrase: String?, electrumUrl: String)async throws -> SweepableBalances { return try await uniffiRustCallAsync( @@ -32463,6 +33062,20 @@ public func closedChannelsToJson(channels: [ClosedChannelDetails])throws -> Str ) }) } +public func completePubkyAuth()async throws -> String { + return + try await uniffiRustCallAsync( + rustFutureFunc: { + uniffi_bitkitcore_fn_func_complete_pubky_auth( + ) + }, + 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: FfiConverterString.lift, + errorHandler: FfiConverterTypePubkyError_lift + ) +} public func createChannelRequestUrl(k1: String, callback: String, localNodeId: String, isPrivate: Bool, cancel: Bool)throws -> String { return try FfiConverterString.lift(try rustCallWithError(FfiConverterTypeLnurlError_lift) { uniffi_bitkitcore_fn_func_create_channel_request_url( @@ -32613,6 +33226,13 @@ public func derivePrivateKey(mnemonicPhrase: String, derivationPathStr: String?, ) }) } +public func derivePubkySecretKey(seed: Data)throws -> String { + return try FfiConverterString.lift(try rustCallWithError(FfiConverterTypePubkyError_lift) { + uniffi_bitkitcore_fn_func_derive_pubky_secret_key( + FfiConverterData.lower(seed),$0 + ) +}) +} /** * Derive a stable, cross-platform `wallet_id` for a hardware (watch-only) wallet * from its account extended public keys. See `derive_wallet_id` in the activity @@ -32662,6 +33282,62 @@ public func estimateOrderFeeFull(lspBalanceSat: UInt64, channelExpiryWeeks: UInt errorHandler: FfiConverterTypeBlocktankError_lift ) } +public func fetchPubkyContacts(publicKey: String)async throws -> [String] { + return + try await uniffiRustCallAsync( + rustFutureFunc: { + uniffi_bitkitcore_fn_func_fetch_pubky_contacts(FfiConverterString.lower(publicKey) + ) + }, + 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: FfiConverterSequenceString.lift, + errorHandler: FfiConverterTypePubkyError_lift + ) +} +public func fetchPubkyFile(uri: String)async throws -> Data { + return + try await uniffiRustCallAsync( + rustFutureFunc: { + uniffi_bitkitcore_fn_func_fetch_pubky_file(FfiConverterString.lower(uri) + ) + }, + 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: FfiConverterData.lift, + errorHandler: FfiConverterTypePubkyError_lift + ) +} +public func fetchPubkyFileString(uri: String)async throws -> String { + return + try await uniffiRustCallAsync( + rustFutureFunc: { + uniffi_bitkitcore_fn_func_fetch_pubky_file_string(FfiConverterString.lower(uri) + ) + }, + 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: FfiConverterString.lift, + errorHandler: FfiConverterTypePubkyError_lift + ) +} +public func fetchPubkyProfile(publicKey: String)async throws -> PubkyProfile { + return + try await uniffiRustCallAsync( + rustFutureFunc: { + uniffi_bitkitcore_fn_func_fetch_pubky_profile(FfiConverterString.lower(publicKey) + ) + }, + 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: FfiConverterTypePubkyProfile_lift, + errorHandler: FfiConverterTypePubkyError_lift + ) +} /** * Combine and finalize a signed PSBT, then extract its broadcastable transaction. */ @@ -33640,6 +34316,13 @@ public func openChannel(orderId: String, connectionString: String)async throws errorHandler: FfiConverterTypeBlocktankError_lift ) } +public func parsePubkyAuthUrl(authUrl: String)throws -> PubkyAuthDetails { + return try FfiConverterTypePubkyAuthDetails_lift(try rustCallWithError(FfiConverterTypePubkyError_lift) { + uniffi_bitkitcore_fn_func_parse_pubky_auth_url( + FfiConverterString.lower(authUrl),$0 + ) +}) +} /** * Parse Passport's generic JSON account export from a decoded `ur:bytes` payload. * @@ -33715,6 +34398,97 @@ public func prepareSweepTransaction(mnemonicPhrase: String, network: Network?, b errorHandler: FfiConverterTypeSweepError_lift ) } +public func pubkyPublicKeyFromSecret(secretKeyHex: String)throws -> String { + return try FfiConverterString.lift(try rustCallWithError(FfiConverterTypePubkyError_lift) { + uniffi_bitkitcore_fn_func_pubky_public_key_from_secret( + FfiConverterString.lower(secretKeyHex),$0 + ) +}) +} +public func pubkyPutWithSecretKey(secretKeyHex: String, path: String, content: Data)async throws { + return + try await uniffiRustCallAsync( + rustFutureFunc: { + uniffi_bitkitcore_fn_func_pubky_put_with_secret_key(FfiConverterString.lower(secretKeyHex),FfiConverterString.lower(path),FfiConverterData.lower(content) + ) + }, + pollFunc: ffi_bitkitcore_rust_future_poll_void, + completeFunc: ffi_bitkitcore_rust_future_complete_void, + freeFunc: ffi_bitkitcore_rust_future_free_void, + liftFunc: { $0 }, + errorHandler: FfiConverterTypePubkyError_lift + ) +} +public func pubkySessionDelete(sessionSecret: String, path: String)async throws { + return + try await uniffiRustCallAsync( + rustFutureFunc: { + uniffi_bitkitcore_fn_func_pubky_session_delete(FfiConverterString.lower(sessionSecret),FfiConverterString.lower(path) + ) + }, + pollFunc: ffi_bitkitcore_rust_future_poll_void, + completeFunc: ffi_bitkitcore_rust_future_complete_void, + freeFunc: ffi_bitkitcore_rust_future_free_void, + liftFunc: { $0 }, + errorHandler: FfiConverterTypePubkyError_lift + ) +} +public func pubkySessionList(sessionSecret: String, dirPath: String)async throws -> [String] { + return + try await uniffiRustCallAsync( + rustFutureFunc: { + uniffi_bitkitcore_fn_func_pubky_session_list(FfiConverterString.lower(sessionSecret),FfiConverterString.lower(dirPath) + ) + }, + 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: FfiConverterSequenceString.lift, + errorHandler: FfiConverterTypePubkyError_lift + ) +} +public func pubkySessionPut(sessionSecret: String, path: String, content: Data)async throws { + return + try await uniffiRustCallAsync( + rustFutureFunc: { + uniffi_bitkitcore_fn_func_pubky_session_put(FfiConverterString.lower(sessionSecret),FfiConverterString.lower(path),FfiConverterData.lower(content) + ) + }, + pollFunc: ffi_bitkitcore_rust_future_poll_void, + completeFunc: ffi_bitkitcore_rust_future_complete_void, + freeFunc: ffi_bitkitcore_rust_future_free_void, + liftFunc: { $0 }, + errorHandler: FfiConverterTypePubkyError_lift + ) +} +public func pubkySignIn(secretKeyHex: String)async throws -> String { + return + try await uniffiRustCallAsync( + rustFutureFunc: { + uniffi_bitkitcore_fn_func_pubky_sign_in(FfiConverterString.lower(secretKeyHex) + ) + }, + 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: FfiConverterString.lift, + errorHandler: FfiConverterTypePubkyError_lift + ) +} +public func pubkySignUp(secretKeyHex: String, homeserverPublicKeyZ32: String, signupCode: String?)async throws -> String { + return + try await uniffiRustCallAsync( + rustFutureFunc: { + uniffi_bitkitcore_fn_func_pubky_sign_up(FfiConverterString.lower(secretKeyHex),FfiConverterString.lower(homeserverPublicKeyZ32),FfiConverterOptionString.lower(signupCode) + ) + }, + 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: FfiConverterString.lift, + 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`. @@ -33993,6 +34767,13 @@ public func resetPreActivityMetadataTags(walletId: String, paymentId: String)thr ) } } +public func resolvePubkyUrl(uri: String)throws -> String { + return try FfiConverterString.lift(try rustCallWithError(FfiConverterTypePubkyError_lift) { + uniffi_bitkitcore_fn_func_resolve_pubky_url( + FfiConverterString.lower(uri),$0 + ) +}) +} public func scanLegacyRnNativeSegwitRecoveryFunds(mnemonicPhrase: String, network: Network?, electrumUrl: String, indexLimit: UInt32, bip39Passphrase: String?)async throws -> LegacyRnCloseRecoveryScanResult { return try await uniffiRustCallAsync( @@ -34014,6 +34795,20 @@ public func serializedExtendedPubkey(xpub: String)throws -> Data { ) }) } +public func startPubkyAuth(caps: String)async throws -> String { + return + try await uniffiRustCallAsync( + rustFutureFunc: { + uniffi_bitkitcore_fn_func_start_pubky_auth(FfiConverterString.lower(caps) + ) + }, + 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: FfiConverterString.lift, + errorHandler: FfiConverterTypePubkyError_lift + ) +} public func testNotification(deviceToken: String, secretMessage: String, notificationType: String?, customUrl: String?)async throws -> String { return try await uniffiRustCallAsync( @@ -35047,6 +35842,9 @@ private let initializationResult: InitializationResult = { if (uniffi_bitkitcore_checksum_func_add_tags() != 61276) { return InitializationResult.apiChecksumMismatch } + if (uniffi_bitkitcore_checksum_func_approve_pubky_auth() != 22222) { + return InitializationResult.apiChecksumMismatch + } if (uniffi_bitkitcore_checksum_func_blocktank_remove_all_cjit_entries() != 40127) { return InitializationResult.apiChecksumMismatch } @@ -35095,6 +35893,9 @@ private let initializationResult: InitializationResult = { if (uniffi_bitkitcore_checksum_func_calculate_channel_liquidity_options() != 51013) { return InitializationResult.apiChecksumMismatch } + if (uniffi_bitkitcore_checksum_func_cancel_pubky_auth() != 61962) { + return InitializationResult.apiChecksumMismatch + } if (uniffi_bitkitcore_checksum_func_check_sweepable_balances() != 64201) { return InitializationResult.apiChecksumMismatch } @@ -35104,6 +35905,9 @@ private let initializationResult: InitializationResult = { if (uniffi_bitkitcore_checksum_func_closed_channels_to_json() != 54955) { return InitializationResult.apiChecksumMismatch } + if (uniffi_bitkitcore_checksum_func_complete_pubky_auth() != 48191) { + return InitializationResult.apiChecksumMismatch + } if (uniffi_bitkitcore_checksum_func_create_channel_request_url() != 9305) { return InitializationResult.apiChecksumMismatch } @@ -35149,6 +35953,9 @@ private let initializationResult: InitializationResult = { if (uniffi_bitkitcore_checksum_func_derive_private_key() != 25155) { return InitializationResult.apiChecksumMismatch } + if (uniffi_bitkitcore_checksum_func_derive_pubky_secret_key() != 36989) { + return InitializationResult.apiChecksumMismatch + } if (uniffi_bitkitcore_checksum_func_derive_wallet_id() != 30111) { return InitializationResult.apiChecksumMismatch } @@ -35161,6 +35968,18 @@ private let initializationResult: InitializationResult = { if (uniffi_bitkitcore_checksum_func_estimate_order_fee_full() != 13361) { return InitializationResult.apiChecksumMismatch } + if (uniffi_bitkitcore_checksum_func_fetch_pubky_contacts() != 18744) { + return InitializationResult.apiChecksumMismatch + } + if (uniffi_bitkitcore_checksum_func_fetch_pubky_file() != 24890) { + return InitializationResult.apiChecksumMismatch + } + if (uniffi_bitkitcore_checksum_func_fetch_pubky_file_string() != 47799) { + return InitializationResult.apiChecksumMismatch + } + if (uniffi_bitkitcore_checksum_func_fetch_pubky_profile() != 19709) { + return InitializationResult.apiChecksumMismatch + } if (uniffi_bitkitcore_checksum_func_finalize_psbt() != 37120) { return InitializationResult.apiChecksumMismatch } @@ -35389,6 +36208,9 @@ private let initializationResult: InitializationResult = { if (uniffi_bitkitcore_checksum_func_open_channel() != 21402) { return InitializationResult.apiChecksumMismatch } + if (uniffi_bitkitcore_checksum_func_parse_pubky_auth_url() != 56972) { + return InitializationResult.apiChecksumMismatch + } if (uniffi_bitkitcore_checksum_func_passport_parse_account_export() != 62096) { return InitializationResult.apiChecksumMismatch } @@ -35407,6 +36229,27 @@ private let initializationResult: InitializationResult = { if (uniffi_bitkitcore_checksum_func_prepare_sweep_transaction() != 18273) { return InitializationResult.apiChecksumMismatch } + if (uniffi_bitkitcore_checksum_func_pubky_public_key_from_secret() != 47481) { + return InitializationResult.apiChecksumMismatch + } + if (uniffi_bitkitcore_checksum_func_pubky_put_with_secret_key() != 36562) { + return InitializationResult.apiChecksumMismatch + } + if (uniffi_bitkitcore_checksum_func_pubky_session_delete() != 39070) { + return InitializationResult.apiChecksumMismatch + } + if (uniffi_bitkitcore_checksum_func_pubky_session_list() != 7225) { + return InitializationResult.apiChecksumMismatch + } + if (uniffi_bitkitcore_checksum_func_pubky_session_put() != 25203) { + return InitializationResult.apiChecksumMismatch + } + if (uniffi_bitkitcore_checksum_func_pubky_sign_in() != 26706) { + return InitializationResult.apiChecksumMismatch + } + if (uniffi_bitkitcore_checksum_func_pubky_sign_up() != 61692) { + return InitializationResult.apiChecksumMismatch + } if (uniffi_bitkitcore_checksum_func_pubky_swaps_advance() != 27871) { return InitializationResult.apiChecksumMismatch } @@ -35461,12 +36304,18 @@ private let initializationResult: InitializationResult = { if (uniffi_bitkitcore_checksum_func_reset_pre_activity_metadata_tags() != 49760) { return InitializationResult.apiChecksumMismatch } + if (uniffi_bitkitcore_checksum_func_resolve_pubky_url() != 43253) { + return InitializationResult.apiChecksumMismatch + } if (uniffi_bitkitcore_checksum_func_scan_legacy_rn_native_segwit_recovery_funds() != 52496) { return InitializationResult.apiChecksumMismatch } if (uniffi_bitkitcore_checksum_func_serialized_extended_pubkey() != 12807) { return InitializationResult.apiChecksumMismatch } + if (uniffi_bitkitcore_checksum_func_start_pubky_auth() != 18158) { + return InitializationResult.apiChecksumMismatch + } if (uniffi_bitkitcore_checksum_func_test_notification() != 32857) { return InitializationResult.apiChecksumMismatch } diff --git a/bindings/ios/bitkitcoreFFI.h b/bindings/ios/bitkitcoreFFI.h index 960f035d..10a0c056 100644 --- a/bindings/ios/bitkitcoreFFI.h +++ b/bindings/ios/bitkitcoreFFI.h @@ -870,6 +870,11 @@ void uniffi_bitkitcore_fn_func_add_pre_activity_metadata_tags(RustBuffer wallet_ void uniffi_bitkitcore_fn_func_add_tags(RustBuffer wallet_id, RustBuffer activity_id, RustBuffer tags, RustCallStatus *_Nonnull out_status ); #endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_APPROVE_PUBKY_AUTH +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_APPROVE_PUBKY_AUTH +uint64_t uniffi_bitkitcore_fn_func_approve_pubky_auth(RustBuffer auth_url, RustBuffer secret_key_hex +); +#endif #ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_BLOCKTANK_REMOVE_ALL_CJIT_ENTRIES #define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_BLOCKTANK_REMOVE_ALL_CJIT_ENTRIES uint64_t uniffi_bitkitcore_fn_func_blocktank_remove_all_cjit_entries(void @@ -954,6 +959,12 @@ uint64_t uniffi_bitkitcore_fn_func_broadcast_sweep_transaction(RustBuffer psbt, #ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_CALCULATE_CHANNEL_LIQUIDITY_OPTIONS #define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_CALCULATE_CHANNEL_LIQUIDITY_OPTIONS RustBuffer uniffi_bitkitcore_fn_func_calculate_channel_liquidity_options(RustBuffer params, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_CANCEL_PUBKY_AUTH +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_CANCEL_PUBKY_AUTH +uint64_t uniffi_bitkitcore_fn_func_cancel_pubky_auth(void + ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_CHECK_SWEEPABLE_BALANCES @@ -969,6 +980,12 @@ RustBuffer uniffi_bitkitcore_fn_func_closed_channels_from_json(RustBuffer json, #ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_CLOSED_CHANNELS_TO_JSON #define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_CLOSED_CHANNELS_TO_JSON RustBuffer uniffi_bitkitcore_fn_func_closed_channels_to_json(RustBuffer channels, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_COMPLETE_PUBKY_AUTH +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_COMPLETE_PUBKY_AUTH +uint64_t uniffi_bitkitcore_fn_func_complete_pubky_auth(void + ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_CREATE_CHANNEL_REQUEST_URL @@ -1046,6 +1063,11 @@ RustBuffer uniffi_bitkitcore_fn_func_derive_onchain_descriptor(RustBuffer mnemon RustBuffer uniffi_bitkitcore_fn_func_derive_private_key(RustBuffer mnemonic_phrase, RustBuffer derivation_path_str, RustBuffer network, RustBuffer bip39_passphrase, RustCallStatus *_Nonnull out_status ); #endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_DERIVE_PUBKY_SECRET_KEY +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_DERIVE_PUBKY_SECRET_KEY +RustBuffer uniffi_bitkitcore_fn_func_derive_pubky_secret_key(RustBuffer seed, RustCallStatus *_Nonnull out_status +); +#endif #ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_DERIVE_WALLET_ID #define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_DERIVE_WALLET_ID RustBuffer uniffi_bitkitcore_fn_func_derive_wallet_id(RustBuffer device_type, RustBuffer xpubs, RustCallStatus *_Nonnull out_status @@ -1066,6 +1088,26 @@ uint64_t uniffi_bitkitcore_fn_func_estimate_order_fee(uint64_t lsp_balance_sat, uint64_t uniffi_bitkitcore_fn_func_estimate_order_fee_full(uint64_t lsp_balance_sat, uint32_t channel_expiry_weeks, RustBuffer options ); #endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_FETCH_PUBKY_CONTACTS +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_FETCH_PUBKY_CONTACTS +uint64_t uniffi_bitkitcore_fn_func_fetch_pubky_contacts(RustBuffer public_key +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_FETCH_PUBKY_FILE +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_FETCH_PUBKY_FILE +uint64_t uniffi_bitkitcore_fn_func_fetch_pubky_file(RustBuffer uri +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_FETCH_PUBKY_FILE_STRING +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_FETCH_PUBKY_FILE_STRING +uint64_t uniffi_bitkitcore_fn_func_fetch_pubky_file_string(RustBuffer uri +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_FETCH_PUBKY_PROFILE +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_FETCH_PUBKY_PROFILE +uint64_t uniffi_bitkitcore_fn_func_fetch_pubky_profile(RustBuffer public_key +); +#endif #ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_FINALIZE_PSBT #define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_FINALIZE_PSBT RustBuffer uniffi_bitkitcore_fn_func_finalize_psbt(RustBuffer original_psbt, RustBuffer signed_psbt, RustCallStatus *_Nonnull out_status @@ -1464,6 +1506,11 @@ void uniffi_bitkitcore_fn_func_onchain_stop_watcher(RustBuffer watcher_id, RustC uint64_t uniffi_bitkitcore_fn_func_open_channel(RustBuffer order_id, RustBuffer connection_string ); #endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PARSE_PUBKY_AUTH_URL +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PARSE_PUBKY_AUTH_URL +RustBuffer uniffi_bitkitcore_fn_func_parse_pubky_auth_url(RustBuffer auth_url, RustCallStatus *_Nonnull out_status +); +#endif #ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PASSPORT_PARSE_ACCOUNT_EXPORT #define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PASSPORT_PARSE_ACCOUNT_EXPORT RustBuffer uniffi_bitkitcore_fn_func_passport_parse_account_export(RustBuffer data, RustCallStatus *_Nonnull out_status @@ -1494,6 +1541,41 @@ uint64_t uniffi_bitkitcore_fn_func_prepare_legacy_rn_native_segwit_recovery_swee uint64_t uniffi_bitkitcore_fn_func_prepare_sweep_transaction(RustBuffer mnemonic_phrase, RustBuffer network, RustBuffer bip39_passphrase, RustBuffer electrum_url, RustBuffer destination_address, RustBuffer fee_rate_sats_per_vbyte ); #endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_PUBLIC_KEY_FROM_SECRET +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_PUBLIC_KEY_FROM_SECRET +RustBuffer uniffi_bitkitcore_fn_func_pubky_public_key_from_secret(RustBuffer secret_key_hex, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_PUT_WITH_SECRET_KEY +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_PUT_WITH_SECRET_KEY +uint64_t uniffi_bitkitcore_fn_func_pubky_put_with_secret_key(RustBuffer secret_key_hex, RustBuffer path, RustBuffer content +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_SESSION_DELETE +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_SESSION_DELETE +uint64_t uniffi_bitkitcore_fn_func_pubky_session_delete(RustBuffer session_secret, RustBuffer path +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_SESSION_LIST +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_SESSION_LIST +uint64_t uniffi_bitkitcore_fn_func_pubky_session_list(RustBuffer session_secret, RustBuffer dir_path +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_SESSION_PUT +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_SESSION_PUT +uint64_t uniffi_bitkitcore_fn_func_pubky_session_put(RustBuffer session_secret, RustBuffer path, RustBuffer content +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_SIGN_IN +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_SIGN_IN +uint64_t uniffi_bitkitcore_fn_func_pubky_sign_in(RustBuffer secret_key_hex +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_SIGN_UP +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_PUBKY_SIGN_UP +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 @@ -1586,6 +1668,11 @@ void uniffi_bitkitcore_fn_func_remove_tags(RustBuffer wallet_id, RustBuffer acti void uniffi_bitkitcore_fn_func_reset_pre_activity_metadata_tags(RustBuffer wallet_id, RustBuffer payment_id, RustCallStatus *_Nonnull out_status ); #endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_RESOLVE_PUBKY_URL +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_RESOLVE_PUBKY_URL +RustBuffer uniffi_bitkitcore_fn_func_resolve_pubky_url(RustBuffer uri, RustCallStatus *_Nonnull out_status +); +#endif #ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_SCAN_LEGACY_RN_NATIVE_SEGWIT_RECOVERY_FUNDS #define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_SCAN_LEGACY_RN_NATIVE_SEGWIT_RECOVERY_FUNDS uint64_t uniffi_bitkitcore_fn_func_scan_legacy_rn_native_segwit_recovery_funds(RustBuffer mnemonic_phrase, RustBuffer network, RustBuffer electrum_url, uint32_t index_limit, RustBuffer bip39_passphrase @@ -1596,6 +1683,11 @@ uint64_t uniffi_bitkitcore_fn_func_scan_legacy_rn_native_segwit_recovery_funds(R RustBuffer uniffi_bitkitcore_fn_func_serialized_extended_pubkey(RustBuffer xpub, RustCallStatus *_Nonnull out_status ); #endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_START_PUBKY_AUTH +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_START_PUBKY_AUTH +uint64_t uniffi_bitkitcore_fn_func_start_pubky_auth(RustBuffer caps +); +#endif #ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_TEST_NOTIFICATION #define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_FN_FUNC_TEST_NOTIFICATION uint64_t uniffi_bitkitcore_fn_func_test_notification(RustBuffer device_token, RustBuffer secret_message, RustBuffer notification_type, RustBuffer custom_url @@ -2303,6 +2395,12 @@ uint16_t uniffi_bitkitcore_checksum_func_add_pre_activity_metadata_tags(void #define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_ADD_TAGS uint16_t uniffi_bitkitcore_checksum_func_add_tags(void +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_APPROVE_PUBKY_AUTH +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_APPROVE_PUBKY_AUTH +uint16_t uniffi_bitkitcore_checksum_func_approve_pubky_auth(void + ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_BLOCKTANK_REMOVE_ALL_CJIT_ENTRIES @@ -2399,6 +2497,12 @@ uint16_t uniffi_bitkitcore_checksum_func_broadcast_sweep_transaction(void #define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_CALCULATE_CHANNEL_LIQUIDITY_OPTIONS uint16_t uniffi_bitkitcore_checksum_func_calculate_channel_liquidity_options(void +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_CANCEL_PUBKY_AUTH +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_CANCEL_PUBKY_AUTH +uint16_t uniffi_bitkitcore_checksum_func_cancel_pubky_auth(void + ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_CHECK_SWEEPABLE_BALANCES @@ -2417,6 +2521,12 @@ uint16_t uniffi_bitkitcore_checksum_func_closed_channels_from_json(void #define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_CLOSED_CHANNELS_TO_JSON uint16_t uniffi_bitkitcore_checksum_func_closed_channels_to_json(void +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_COMPLETE_PUBKY_AUTH +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_COMPLETE_PUBKY_AUTH +uint16_t uniffi_bitkitcore_checksum_func_complete_pubky_auth(void + ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_CREATE_CHANNEL_REQUEST_URL @@ -2507,6 +2617,12 @@ uint16_t uniffi_bitkitcore_checksum_func_derive_onchain_descriptor(void #define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_DERIVE_PRIVATE_KEY uint16_t uniffi_bitkitcore_checksum_func_derive_private_key(void +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_DERIVE_PUBKY_SECRET_KEY +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_DERIVE_PUBKY_SECRET_KEY +uint16_t uniffi_bitkitcore_checksum_func_derive_pubky_secret_key(void + ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_DERIVE_WALLET_ID @@ -2531,6 +2647,30 @@ uint16_t uniffi_bitkitcore_checksum_func_estimate_order_fee(void #define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_ESTIMATE_ORDER_FEE_FULL uint16_t uniffi_bitkitcore_checksum_func_estimate_order_fee_full(void +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_FETCH_PUBKY_CONTACTS +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_FETCH_PUBKY_CONTACTS +uint16_t uniffi_bitkitcore_checksum_func_fetch_pubky_contacts(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_FETCH_PUBKY_FILE +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_FETCH_PUBKY_FILE +uint16_t uniffi_bitkitcore_checksum_func_fetch_pubky_file(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_FETCH_PUBKY_FILE_STRING +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_FETCH_PUBKY_FILE_STRING +uint16_t uniffi_bitkitcore_checksum_func_fetch_pubky_file_string(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_FETCH_PUBKY_PROFILE +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_FETCH_PUBKY_PROFILE +uint16_t uniffi_bitkitcore_checksum_func_fetch_pubky_profile(void + ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_FINALIZE_PSBT @@ -2987,6 +3127,12 @@ uint16_t uniffi_bitkitcore_checksum_func_onchain_stop_watcher(void #define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_OPEN_CHANNEL uint16_t uniffi_bitkitcore_checksum_func_open_channel(void +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PARSE_PUBKY_AUTH_URL +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PARSE_PUBKY_AUTH_URL +uint16_t uniffi_bitkitcore_checksum_func_parse_pubky_auth_url(void + ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PASSPORT_PARSE_ACCOUNT_EXPORT @@ -3023,6 +3169,48 @@ uint16_t uniffi_bitkitcore_checksum_func_prepare_legacy_rn_native_segwit_recover #define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PREPARE_SWEEP_TRANSACTION uint16_t uniffi_bitkitcore_checksum_func_prepare_sweep_transaction(void +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_PUBLIC_KEY_FROM_SECRET +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_PUBLIC_KEY_FROM_SECRET +uint16_t uniffi_bitkitcore_checksum_func_pubky_public_key_from_secret(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_PUT_WITH_SECRET_KEY +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_PUT_WITH_SECRET_KEY +uint16_t uniffi_bitkitcore_checksum_func_pubky_put_with_secret_key(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_SESSION_DELETE +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_SESSION_DELETE +uint16_t uniffi_bitkitcore_checksum_func_pubky_session_delete(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_SESSION_LIST +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_SESSION_LIST +uint16_t uniffi_bitkitcore_checksum_func_pubky_session_list(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_SESSION_PUT +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_SESSION_PUT +uint16_t uniffi_bitkitcore_checksum_func_pubky_session_put(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_SIGN_IN +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_SIGN_IN +uint16_t uniffi_bitkitcore_checksum_func_pubky_sign_in(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_PUBKY_SIGN_UP +#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 @@ -3131,6 +3319,12 @@ uint16_t uniffi_bitkitcore_checksum_func_remove_tags(void #define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_RESET_PRE_ACTIVITY_METADATA_TAGS uint16_t uniffi_bitkitcore_checksum_func_reset_pre_activity_metadata_tags(void +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_RESOLVE_PUBKY_URL +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_RESOLVE_PUBKY_URL +uint16_t uniffi_bitkitcore_checksum_func_resolve_pubky_url(void + ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_SCAN_LEGACY_RN_NATIVE_SEGWIT_RECOVERY_FUNDS @@ -3143,6 +3337,12 @@ uint16_t uniffi_bitkitcore_checksum_func_scan_legacy_rn_native_segwit_recovery_f #define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_SERIALIZED_EXTENDED_PUBKEY uint16_t uniffi_bitkitcore_checksum_func_serialized_extended_pubkey(void +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_START_PUBKY_AUTH +#define UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_START_PUBKY_AUTH +uint16_t uniffi_bitkitcore_checksum_func_start_pubky_auth(void + ); #endif #ifndef UNIFFI_FFIDEF_UNIFFI_BITKITCORE_CHECKSUM_FUNC_TEST_NOTIFICATION diff --git a/src/lib.rs b/src/lib.rs index 6b7187bb..af33b748 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -53,6 +53,7 @@ pub use crate::modules::jade::{ JadeState, JadeTransportCallback, JadeTransportErrorCode, JadeTransportKind, 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, @@ -2146,6 +2147,227 @@ pub fn get_default_lsp_balance(params: DefaultLspBalanceParams) -> u64 { crate::modules::blocktank::get_default_lsp_balance(params) } +// ============================================================================ +// Pubky Functions +// ============================================================================ + +#[uniffi::export] +pub fn resolve_pubky_url(uri: String) -> Result { + crate::modules::pubky::resolve_pubky_url(uri) +} + +#[uniffi::export] +pub async fn fetch_pubky_file(uri: String) -> Result, PubkyError> { + let rt = ensure_runtime(); + rt.spawn(async move { crate::modules::pubky::fetch_pubky_file(uri).await }) + .await + .unwrap_or_else(|e| { + Err(PubkyError::ResolutionFailed { + reason: format!("Runtime error: {}", e), + }) + }) +} + +#[uniffi::export] +pub async fn start_pubky_auth(caps: String) -> Result { + let rt = ensure_runtime(); + rt.spawn(async move { crate::modules::pubky::start_pubky_auth(caps).await }) + .await + .unwrap_or_else(|e| { + Err(PubkyError::AuthFailed { + reason: format!("Runtime error: {}", e), + }) + }) +} + +#[uniffi::export] +pub async fn cancel_pubky_auth() -> Result<(), PubkyError> { + let rt = ensure_runtime(); + rt.spawn(async move { crate::modules::pubky::cancel_pubky_auth().await }) + .await + .unwrap_or_else(|e| { + Err(PubkyError::AuthFailed { + reason: format!("Runtime error: {}", e), + }) + }) +} + +#[uniffi::export] +pub async fn complete_pubky_auth() -> Result { + let rt = ensure_runtime(); + rt.spawn(async move { crate::modules::pubky::complete_pubky_auth().await }) + .await + .unwrap_or_else(|e| { + Err(PubkyError::AuthFailed { + reason: format!("Runtime error: {}", e), + }) + }) +} + +#[uniffi::export] +pub fn parse_pubky_auth_url(auth_url: String) -> Result { + crate::modules::pubky::parse_pubky_auth_url(auth_url) +} + +#[uniffi::export] +pub async fn approve_pubky_auth( + auth_url: String, + secret_key_hex: String, +) -> Result<(), PubkyError> { + let rt = ensure_runtime(); + rt.spawn( + async move { crate::modules::pubky::approve_pubky_auth(auth_url, secret_key_hex).await }, + ) + .await + .unwrap_or_else(|e| { + Err(PubkyError::AuthFailed { + reason: format!("Runtime error: {}", e), + }) + }) +} + +#[uniffi::export] +pub async fn fetch_pubky_profile(public_key: String) -> Result { + let rt = ensure_runtime(); + rt.spawn(async move { crate::modules::pubky::fetch_pubky_profile(public_key).await }) + .await + .unwrap_or_else(|e| { + Err(PubkyError::FetchFailed { + reason: format!("Runtime error: {}", e), + }) + }) +} + +#[uniffi::export] +pub async fn fetch_pubky_contacts(public_key: String) -> Result, PubkyError> { + let rt = ensure_runtime(); + rt.spawn(async move { crate::modules::pubky::fetch_pubky_contacts(public_key).await }) + .await + .unwrap_or_else(|e| { + Err(PubkyError::FetchFailed { + reason: format!("Runtime error: {}", e), + }) + }) +} + +#[uniffi::export] +pub async fn fetch_pubky_file_string(uri: String) -> Result { + let rt = ensure_runtime(); + rt.spawn(async move { crate::modules::pubky::fetch_pubky_file_string(uri).await }) + .await + .unwrap_or_else(|e| { + Err(PubkyError::FetchFailed { + reason: format!("Runtime error: {}", e), + }) + }) +} + +#[uniffi::export] +pub fn derive_pubky_secret_key(seed: Vec) -> Result { + crate::modules::pubky::derive_pubky_secret_key(seed) +} + +#[uniffi::export] +pub fn pubky_public_key_from_secret(secret_key_hex: String) -> Result { + crate::modules::pubky::pubky_public_key_from_secret(secret_key_hex) +} + +#[uniffi::export] +pub async fn pubky_sign_up( + secret_key_hex: String, + homeserver_public_key_z32: String, + signup_code: Option, +) -> Result { + let rt = ensure_runtime(); + rt.spawn(async move { + crate::modules::pubky::pubky_sign_up(secret_key_hex, homeserver_public_key_z32, signup_code) + .await + }) + .await + .unwrap_or_else(|e| { + Err(PubkyError::AuthFailed { + reason: format!("Runtime error: {}", e), + }) + }) +} + +#[uniffi::export] +pub async fn pubky_sign_in(secret_key_hex: String) -> Result { + let rt = ensure_runtime(); + rt.spawn(async move { crate::modules::pubky::pubky_sign_in(secret_key_hex).await }) + .await + .unwrap_or_else(|e| { + Err(PubkyError::AuthFailed { + reason: format!("Runtime error: {}", e), + }) + }) +} + +#[uniffi::export] +pub async fn pubky_session_put( + session_secret: String, + path: String, + content: Vec, +) -> Result<(), PubkyError> { + let rt = ensure_runtime(); + rt.spawn(async move { + crate::modules::pubky::pubky_session_put(session_secret, path, content).await + }) + .await + .unwrap_or_else(|e| { + Err(PubkyError::WriteFailed { + reason: format!("Runtime error: {}", e), + }) + }) +} + +#[uniffi::export] +pub async fn pubky_session_delete(session_secret: String, path: String) -> Result<(), PubkyError> { + let rt = ensure_runtime(); + rt.spawn(async move { crate::modules::pubky::pubky_session_delete(session_secret, path).await }) + .await + .unwrap_or_else(|e| { + Err(PubkyError::WriteFailed { + reason: format!("Runtime error: {}", e), + }) + }) +} + +#[uniffi::export] +pub async fn pubky_put_with_secret_key( + secret_key_hex: String, + path: String, + content: Vec, +) -> Result<(), PubkyError> { + let rt = ensure_runtime(); + rt.spawn(async move { + crate::modules::pubky::pubky_put_with_secret_key(secret_key_hex, path, content).await + }) + .await + .unwrap_or_else(|e| { + Err(PubkyError::WriteFailed { + reason: format!("Runtime error: {}", e), + }) + }) +} + +#[uniffi::export] +pub async fn pubky_session_list( + session_secret: String, + dir_path: String, +) -> Result, PubkyError> { + let rt = ensure_runtime(); + rt.spawn( + async move { crate::modules::pubky::pubky_session_list(session_secret, dir_path).await }, + ) + .await + .unwrap_or_else(|e| { + Err(PubkyError::FetchFailed { + reason: format!("Runtime error: {}", e), + }) + }) +} + // ============================================================================ // Wake Functions // ============================================================================ diff --git a/src/modules/mod.rs b/src/modules/mod.rs index 27936cff..42c1f76d 100644 --- a/src/modules/mod.rs +++ b/src/modules/mod.rs @@ -6,6 +6,7 @@ pub mod jade; pub mod lnurl; pub mod onchain; pub mod paykit_route; +pub mod pubky; pub mod pubky_swaps; pub mod scanner; pub mod seedqr; diff --git a/src/modules/pubky/auth.rs b/src/modules/pubky/auth.rs new file mode 100644 index 00000000..92c9f8f9 --- /dev/null +++ b/src/modules/pubky/auth.rs @@ -0,0 +1,136 @@ +use once_cell::sync::OnceCell; +use pubky::deep_links::DeepLink; +use pubky::{AuthFlowKind, Capabilities, PubkyAuthFlow}; +use tokio::sync::Mutex as TokioMutex; + +use super::errors::PubkyError; +use super::keys::keypair_from_hex; +use super::resolve::get_pubky; + +static AUTH_FLOW: OnceCell>> = OnceCell::new(); + +fn auth_flow_slot() -> &'static TokioMutex> { + AUTH_FLOW.get_or_init(|| TokioMutex::new(None)) +} + +/// Start a Pubky auth flow and return the `pubkyauth://` deep-link URL. +pub async fn start_pubky_auth(caps: String) -> Result { + let capabilities = + Capabilities::try_from(caps.as_str()).map_err(|e| PubkyError::InvalidCapabilities { + reason: e.to_string(), + })?; + + let mut guard = auth_flow_slot().lock().await; + + if guard.is_some() { + return Err(PubkyError::AuthFailed { + reason: "An auth flow is already in progress".into(), + }); + } + + let flow = PubkyAuthFlow::start(&capabilities, AuthFlowKind::signin()).map_err(|e| { + PubkyError::AuthFailed { + reason: e.to_string(), + } + })?; + + let url = flow.authorization_url().to_string(); + *guard = Some(flow); + + Ok(url) +} + +/// Cancel an in-progress auth flow, freeing the slot for a new one. +pub async fn cancel_pubky_auth() -> Result<(), PubkyError> { + let mut guard = auth_flow_slot().lock().await; + guard.take().ok_or(PubkyError::NoActiveFlow)?; + Ok(()) +} + +/// Await Ring approval and return the session secret (`":"`). +pub async fn complete_pubky_auth() -> Result { + let flow = { + let mut guard = auth_flow_slot().lock().await; + guard.take().ok_or(PubkyError::NoActiveFlow)? + }; + + let session = flow + .await_approval() + .await + .map_err(|e| PubkyError::AuthFailed { + reason: e.to_string(), + })?; + + Ok(session.export_secret()) +} + +/// The type of a `pubkyauth://` deep-link flow. +#[derive(uniffi::Enum, Debug, Clone, PartialEq)] +pub enum PubkyAuthKind { + Signin, + Signup, +} + +/// Details extracted from a `pubkyauth://` deep-link URL. +#[derive(uniffi::Record, Debug, Clone)] +pub struct PubkyAuthDetails { + /// Whether this is a signin or signup flow. + pub kind: PubkyAuthKind, + /// Requested capabilities (e.g. `"/pub/pubky.app/:rw"`). + pub capabilities: String, + /// Relay URL used for the auth exchange. + pub relay: String, + /// Homeserver public key (z32-encoded). Present only for signup flows. + pub homeserver: Option, + /// Signup token. Present only for signup flows. + pub signup_token: Option, +} + +/// Parse a `pubkyauth://` URL and return its details for UI display. +pub fn parse_pubky_auth_url(auth_url: String) -> Result { + let deep_link: DeepLink = + auth_url + .parse() + .map_err( + |e: pubky::deep_links::DeepLinkParseError| PubkyError::AuthFailed { + reason: e.to_string(), + }, + )?; + + match deep_link { + DeepLink::Signin(signin) => Ok(PubkyAuthDetails { + kind: PubkyAuthKind::Signin, + capabilities: signin.capabilities().to_string(), + relay: signin.relay().to_string(), + homeserver: None, + signup_token: None, + }), + DeepLink::Signup(signup) => Ok(PubkyAuthDetails { + kind: PubkyAuthKind::Signup, + capabilities: signup.capabilities().to_string(), + relay: signup.relay().to_string(), + homeserver: Some(signup.homeserver().z32()), + signup_token: signup.signup_token(), + }), + DeepLink::SeedExport(_) => Err(PubkyError::AuthFailed { + reason: "seed_export deep links are not auth URLs".to_string(), + }), + } +} + +/// Approve a Pubky auth request by signing an AuthToken and posting it to the relay. +pub async fn approve_pubky_auth( + auth_url: String, + secret_key_hex: String, +) -> Result<(), PubkyError> { + let kp = keypair_from_hex(&secret_key_hex)?; + let pubky = get_pubky()?; + let signer = pubky.signer(kp); + + signer + .approve_auth(&auth_url) + .await + .map_err(|e| PubkyError::AuthFailed { + reason: e.to_string(), + }) +} diff --git a/src/modules/pubky/errors.rs b/src/modules/pubky/errors.rs new file mode 100644 index 00000000..2d9f7637 --- /dev/null +++ b/src/modules/pubky/errors.rs @@ -0,0 +1,30 @@ +#[derive(uniffi::Error, thiserror::Error, Debug)] +#[non_exhaustive] +pub enum PubkyError { + #[error("Invalid capabilities: {reason}")] + InvalidCapabilities { reason: String }, + + #[error("Auth flow failed: {reason}")] + AuthFailed { reason: String }, + + #[error("No active auth flow")] + NoActiveFlow, + + #[error("Resolution failed: {reason}")] + ResolutionFailed { reason: String }, + + #[error("Fetch failed: {reason}")] + FetchFailed { reason: String }, + + #[error("Profile not found")] + ProfileNotFound, + + #[error("Profile parse failed: {reason}")] + ProfileParseFailed { reason: String }, + + #[error("Key error: {reason}")] + KeyError { reason: String }, + + #[error("Write failed: {reason}")] + WriteFailed { reason: String }, +} diff --git a/src/modules/pubky/keys.rs b/src/modules/pubky/keys.rs new file mode 100644 index 00000000..95b14ede --- /dev/null +++ b/src/modules/pubky/keys.rs @@ -0,0 +1,40 @@ +use bitcoin::hashes::{hmac, sha256, Hash, HashEngine, HmacEngine}; +use pubky::Keypair; + +use super::errors::PubkyError; + +/// Reconstruct a [`Keypair`] from a hex-encoded 32-byte secret key. +pub(super) fn keypair_from_hex(secret_key_hex: &str) -> Result { + let bytes = hex::decode(secret_key_hex).map_err(|e| PubkyError::KeyError { + reason: e.to_string(), + })?; + + let secret: [u8; 32] = bytes + .try_into() + .map_err(|v: Vec| PubkyError::KeyError { + reason: format!("expected 32 bytes, got {}", v.len()), + })?; + + Ok(Keypair::from_secret(&secret)) +} + +/// Derive a Pubky Ed25519 secret key from a BIP39 seed using HMAC-SHA256. +pub fn derive_pubky_secret_key(seed: Vec) -> Result { + if seed.len() != 64 { + return Err(PubkyError::KeyError { + reason: format!("expected 64-byte BIP39 seed, got {}", seed.len()), + }); + } + + let mut engine = hmac::HmacEngine::::new(b"paykit/pubky"); + engine.input(&seed); + let result = hmac::Hmac::::from_engine(engine); + + Ok(hex::encode(result.to_byte_array())) +} + +/// Derive the z32-encoded public key from a hex-encoded secret key. +pub fn pubky_public_key_from_secret(secret_key_hex: String) -> Result { + let kp = keypair_from_hex(&secret_key_hex)?; + Ok(kp.public_key().z32()) +} diff --git a/src/modules/pubky/mod.rs b/src/modules/pubky/mod.rs new file mode 100644 index 00000000..d16c5d5f --- /dev/null +++ b/src/modules/pubky/mod.rs @@ -0,0 +1,16 @@ +mod auth; +mod errors; +mod keys; +mod profile; +mod resolve; +mod session; +#[cfg(test)] +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 new file mode 100644 index 00000000..76681969 --- /dev/null +++ b/src/modules/pubky/profile.rs @@ -0,0 +1,135 @@ +use pubky_app_specs::{PubkyAppUser, PubkyAppUserLink}; + +use super::errors::PubkyError; +use super::resolve::get_pubky; + +const PROFILE_PATH: &str = "/pub/pubky.app/profile.json"; +const FOLLOWS_PATH: &str = "/pub/pubky.app/follows/"; + +#[derive(uniffi::Record, Debug, Clone)] +pub struct PubkyProfileLink { + pub title: String, + pub url: String, +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct PubkyProfile { + pub name: String, + pub bio: Option, + pub image: Option, + pub links: Option>, + pub status: Option, +} + +impl From for PubkyProfileLink { + fn from(link: PubkyAppUserLink) -> Self { + PubkyProfileLink { + title: link.title, + url: link.url, + } + } +} + +impl From for PubkyProfile { + fn from(user: PubkyAppUser) -> Self { + PubkyProfile { + name: user.name, + bio: user.bio, + image: user.image, + links: user + .links + .map(|links| links.into_iter().map(PubkyProfileLink::from).collect()), + status: user.status, + } + } +} + +fn is_not_found(err: &impl std::fmt::Display) -> bool { + let msg = err.to_string(); + 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()?; + let addr = format!("{public_key}{PROFILE_PATH}"); + + let response = pubky.public_storage().get(&addr).await.map_err(|e| { + if is_not_found(&e) { + PubkyError::ProfileNotFound + } else { + PubkyError::FetchFailed { + reason: e.to_string(), + } + } + })?; + + let bytes = response + .bytes() + .await + .map_err(|e| PubkyError::FetchFailed { + reason: e.to_string(), + })?; + + let user: PubkyAppUser = + serde_json::from_slice(&bytes).map_err(|e| PubkyError::ProfileParseFailed { + reason: e.to_string(), + })?; + + Ok(PubkyProfile::from(user)) +} + +/// Fetch the followed public keys for a user. Returns an empty list if the user has no follows. +pub async fn fetch_pubky_contacts(public_key: String) -> Result, PubkyError> { + let pubky = get_pubky()?; + let addr = format!("{public_key}{FOLLOWS_PATH}"); + let storage = pubky.public_storage(); + + let list_builder = storage.list(&addr).map_err(|e| PubkyError::FetchFailed { + reason: e.to_string(), + })?; + + let entries = match list_builder.send().await { + Ok(entries) => entries, + Err(e) if is_not_found(&e) => return Ok(Vec::new()), + Err(e) => { + return Err(PubkyError::FetchFailed { + reason: e.to_string(), + }) + } + }; + + let mut contacts = Vec::new(); + for entry in entries { + let url_str = entry.to_pubky_url(); + if url_str.ends_with('/') { + continue; + } + if let Some(pk_str) = url_str.rsplit('/').next().filter(|s| !s.is_empty()) { + contacts.push(pk_str.to_string()); + } + } + + Ok(contacts) +} diff --git a/src/modules/pubky/resolve.rs b/src/modules/pubky/resolve.rs new file mode 100644 index 00000000..62b6aec8 --- /dev/null +++ b/src/modules/pubky/resolve.rs @@ -0,0 +1,52 @@ +use once_cell::sync::OnceCell; +use pubky::Pubky; + +use super::errors::PubkyError; + +static PUBKY_SDK: OnceCell = OnceCell::new(); + +pub(super) fn get_pubky() -> Result<&'static Pubky, PubkyError> { + PUBKY_SDK.get_or_try_init(|| { + Pubky::new().map_err(|e| PubkyError::ResolutionFailed { + reason: e.to_string(), + }) + }) +} + +/// Convert a `pubky://` URI to its `https://_pubky./…` transport URL. +pub fn resolve_pubky_url(uri: String) -> Result { + let url = pubky::resolve_pubky(&uri).map_err(|e| PubkyError::ResolutionFailed { + reason: e.to_string(), + })?; + Ok(url.to_string()) +} + +/// Fetch a public resource from a `pubky://` URI and return as a UTF-8 string. +pub async fn fetch_pubky_file_string(uri: String) -> Result { + let bytes = fetch_pubky_file(uri).await?; + String::from_utf8(bytes).map_err(|e| PubkyError::FetchFailed { + reason: e.to_string(), + }) +} + +/// Fetch a public resource from a `pubky://` URI and return its raw bytes. +pub async fn fetch_pubky_file(uri: String) -> Result, PubkyError> { + let pubky = get_pubky()?; + + let response = pubky + .public_storage() + .get(&uri) + .await + .map_err(|e| PubkyError::FetchFailed { + reason: e.to_string(), + })?; + + let bytes = response + .bytes() + .await + .map_err(|e| PubkyError::FetchFailed { + reason: e.to_string(), + })?; + + Ok(bytes.to_vec()) +} diff --git a/src/modules/pubky/session.rs b/src/modules/pubky/session.rs new file mode 100644 index 00000000..591ac34f --- /dev/null +++ b/src/modules/pubky/session.rs @@ -0,0 +1,136 @@ +use pubky::{PubkySession, PublicKey}; + +use super::errors::PubkyError; +use super::keys::keypair_from_hex; +use super::resolve::get_pubky; + +/// Sign up on a homeserver and return the session secret (`":"`). +pub async fn pubky_sign_up( + secret_key_hex: String, + homeserver_public_key_z32: String, + signup_code: Option, +) -> Result { + let kp = keypair_from_hex(&secret_key_hex)?; + + let homeserver_pk = + PublicKey::try_from_z32(&homeserver_public_key_z32).map_err(|e| PubkyError::KeyError { + reason: e.to_string(), + })?; + + let pubky = get_pubky()?; + let signer = pubky.signer(kp); + + let session = signer + .signup(&homeserver_pk, signup_code.as_deref()) + .await + .map_err(|e| PubkyError::AuthFailed { + reason: e.to_string(), + })?; + + Ok(session.export_secret()) +} + +/// Re-authenticate with an existing secret key and return a new session secret. +pub async fn pubky_sign_in(secret_key_hex: String) -> Result { + let kp = keypair_from_hex(&secret_key_hex)?; + + let pubky = get_pubky()?; + let signer = pubky.signer(kp); + + let session = signer.signin().await.map_err(|e| PubkyError::AuthFailed { + reason: e.to_string(), + })?; + + Ok(session.export_secret()) +} + +/// Write content to a path on the user's homeserver using their session. +pub async fn pubky_session_put( + session_secret: String, + path: String, + content: Vec, +) -> Result<(), PubkyError> { + let session = import_session(&session_secret).await?; + + session + .storage() + .put(path.as_str(), content) + .await + .map_err(|e| PubkyError::WriteFailed { + reason: e.to_string(), + })?; + + Ok(()) +} + +/// Delete a resource at path on the user's homeserver. +pub async fn pubky_session_delete(session_secret: String, path: String) -> Result<(), PubkyError> { + let session = import_session(&session_secret).await?; + + session + .storage() + .delete(path.as_str()) + .await + .map_err(|e| PubkyError::WriteFailed { + reason: format!("delete failed: {e}"), + })?; + + Ok(()) +} + +/// Sign in with a secret key and write content in one shot (e.g., redirect.json on old identity). +pub async fn pubky_put_with_secret_key( + secret_key_hex: String, + path: String, + content: Vec, +) -> Result<(), PubkyError> { + let kp = keypair_from_hex(&secret_key_hex)?; + + let pubky = get_pubky()?; + let signer = pubky.signer(kp); + + let session = signer.signin().await.map_err(|e| PubkyError::AuthFailed { + reason: e.to_string(), + })?; + + session + .storage() + .put(path.as_str(), content) + .await + .map_err(|e| PubkyError::WriteFailed { + reason: e.to_string(), + })?; + + Ok(()) +} + +/// List resources in a directory on the user's homeserver. `dir_path` must end with `/`. +pub async fn pubky_session_list( + session_secret: String, + dir_path: String, +) -> Result, PubkyError> { + let session = import_session(&session_secret).await?; + + let entries = session + .storage() + .list(dir_path.as_str()) + .map_err(|e| PubkyError::FetchFailed { + reason: e.to_string(), + })? + .send() + .await + .map_err(|e| PubkyError::FetchFailed { + reason: e.to_string(), + })?; + + Ok(entries.iter().map(|e| e.to_pubky_url()).collect()) +} + +/// Import a session from its secret token, validating it against the homeserver. +async fn import_session(session_secret: &str) -> Result { + PubkySession::import_secret(session_secret, None) + .await + .map_err(|e| PubkyError::AuthFailed { + reason: e.to_string(), + }) +} diff --git a/src/modules/pubky/tests.rs b/src/modules/pubky/tests.rs new file mode 100644 index 00000000..4c8daa1b --- /dev/null +++ b/src/modules/pubky/tests.rs @@ -0,0 +1,527 @@ +use super::*; + +// ============================================================================ +// Resolution tests +// ============================================================================ + +#[test] +fn resolve_pubky_uri() { + let pk = "operrr8wsbpr3ue9d4qj41ge1kcc6r7fdiy6o3ugjrrhi4y77rdo"; + let uri = format!("pubky://{pk}/pub/pubky.app/files/0034RC8872KNG"); + let result = resolve_pubky_url(uri).unwrap(); + assert_eq!( + result, + format!("https://_pubky.{pk}/pub/pubky.app/files/0034RC8872KNG") + ); +} + +#[test] +fn resolve_pubky_prefixed_form() { + let pk = "operrr8wsbpr3ue9d4qj41ge1kcc6r7fdiy6o3ugjrrhi4y77rdo"; + let uri = format!("pubky{pk}/pub/pubky.app/profile.json"); + let result = resolve_pubky_url(uri).unwrap(); + assert_eq!( + result, + format!("https://_pubky.{pk}/pub/pubky.app/profile.json") + ); +} + +#[test] +fn resolve_invalid_uri() { + let result = resolve_pubky_url("not-a-pubky-uri".into()); + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::ResolutionFailed { .. } => {} + other => panic!("expected ResolutionFailed, got: {other:?}"), + } +} + +// ============================================================================ +// Auth flow tests +// ============================================================================ + +#[tokio::test] +async fn complete_without_active_flow_returns_no_active_flow() { + let result = complete_pubky_auth().await; + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::NoActiveFlow => {} + other => panic!("expected NoActiveFlow, got: {other:?}"), + } +} + +#[tokio::test] +async fn cancel_without_active_flow_returns_no_active_flow() { + let result = cancel_pubky_auth().await; + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::NoActiveFlow => {} + other => panic!("expected NoActiveFlow, got: {other:?}"), + } +} + +// ============================================================================ +// File fetch tests +// ============================================================================ + +#[tokio::test] +async fn fetch_malformed_uri_returns_error() { + let result = fetch_pubky_file("totally-not-a-pubky-uri".into()).await; + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::FetchFailed { .. } => {} + other => panic!("expected FetchFailed, got: {other:?}"), + } +} + +// ============================================================================ +// Profile conversion tests +// ============================================================================ + +#[test] +fn profile_from_full_app_user() { + use pubky_app_specs::{PubkyAppUser, PubkyAppUserLink}; + + let user = PubkyAppUser::new( + "Alice".to_string(), + Some("Hello world".to_string()), + Some("https://example.com/avatar.png".to_string()), + Some(vec![PubkyAppUserLink::new( + "Website".to_string(), + "https://alice.example.com".to_string(), + )]), + Some("Online".to_string()), + ); + + let profile = PubkyProfile::from(user); + assert_eq!(profile.name, "Alice"); + assert_eq!(profile.bio.as_deref(), Some("Hello world")); + assert_eq!( + profile.image.as_deref(), + Some("https://example.com/avatar.png") + ); + assert_eq!(profile.status.as_deref(), Some("Online")); + + let links = profile.links.unwrap(); + assert_eq!(links.len(), 1); + assert_eq!(links[0].title, "Website"); + assert!(links[0].url.starts_with("https://alice.example.com")); +} + +#[test] +fn profile_from_minimal_app_user() { + use pubky_app_specs::PubkyAppUser; + + let user = PubkyAppUser::new("Bob".to_string(), None, None, None, None); + + let profile = PubkyProfile::from(user); + assert_eq!(profile.name, "Bob"); + assert!(profile.bio.is_none()); + assert!(profile.image.is_none()); + assert!(profile.links.is_none()); + assert!(profile.status.is_none()); +} + +#[test] +fn profile_from_user_with_empty_links() { + use pubky_app_specs::PubkyAppUser; + + let user = PubkyAppUser::new( + "Carol".to_string(), + Some("Bio".to_string()), + None, + Some(vec![]), + None, + ); + + let profile = PubkyProfile::from(user); + assert_eq!(profile.name, "Carol"); + let links = profile.links.unwrap(); + assert!(links.is_empty()); +} + +// ============================================================================ +// Profile JSON deserialization tests +// ============================================================================ + +#[test] +fn profile_deserialized_from_full_json() { + let json = r#"{ + "name": "Dave", + "bio": "Hello", + "image": "https://example.com/img.png", + "links": [ + {"title": "Blog", "url": "https://blog.example.com"}, + {"title": "GitHub", "url": "https://github.com/dave"} + ], + "status": "Away" + }"#; + + let user: pubky_app_specs::PubkyAppUser = serde_json::from_str(json).unwrap(); + let profile = PubkyProfile::from(user); + + assert_eq!(profile.name, "Dave"); + assert_eq!(profile.bio.as_deref(), Some("Hello")); + assert_eq!( + profile.image.as_deref(), + Some("https://example.com/img.png") + ); + assert_eq!(profile.status.as_deref(), Some("Away")); + let links = profile.links.unwrap(); + assert_eq!(links.len(), 2); + assert_eq!(links[0].title, "Blog"); + assert_eq!(links[1].title, "GitHub"); +} + +#[test] +fn profile_deserialized_from_name_only_json() { + let json = r#"{"name": "Eve"}"#; + let user: pubky_app_specs::PubkyAppUser = serde_json::from_str(json).unwrap(); + let profile = PubkyProfile::from(user); + + assert_eq!(profile.name, "Eve"); + assert!(profile.bio.is_none()); + assert!(profile.image.is_none()); + assert!(profile.links.is_none()); + assert!(profile.status.is_none()); +} + +#[test] +fn profile_missing_name_json_fails() { + let json = r#"{"bio": "no name field"}"#; + let result: Result = serde_json::from_str(json); + assert!(result.is_err()); +} + +#[test] +fn profile_invalid_json_fails() { + let json = r#"not valid json"#; + let result: Result = serde_json::from_str(json); + assert!(result.is_err()); +} + +// ============================================================================ +// Profile fetch error tests +// ============================================================================ + +#[tokio::test] +async fn fetch_profile_invalid_key_returns_fetch_failed() { + let result = fetch_pubky_profile("not-a-valid-public-key".into()).await; + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::FetchFailed { .. } | PubkyError::ProfileNotFound => {} + other => panic!("expected FetchFailed or ProfileNotFound, got: {other:?}"), + } +} + +#[tokio::test] +async fn fetch_profile_empty_key_returns_fetch_failed() { + let result = fetch_pubky_profile(String::new()).await; + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::FetchFailed { .. } | PubkyError::ProfileNotFound => {} + other => panic!("expected FetchFailed or ProfileNotFound, got: {other:?}"), + } +} + +// ============================================================================ +// Contacts fetch error tests +// ============================================================================ + +#[tokio::test] +async fn fetch_contacts_invalid_key_returns_fetch_failed() { + let result = fetch_pubky_contacts("not-a-valid-public-key".into()).await; + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::FetchFailed { .. } => {} + other => panic!("expected FetchFailed, got: {other:?}"), + } +} + +#[tokio::test] +async fn fetch_contacts_empty_key_returns_fetch_failed() { + let result = fetch_pubky_contacts(String::new()).await; + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::FetchFailed { .. } => {} + other => panic!("expected FetchFailed, got: {other:?}"), + } +} + +// ============================================================================ +// Key derivation tests +// ============================================================================ + +#[test] +fn derive_secret_key_returns_valid_hex() { + let seed = vec![0xABu8; 64]; + let hex_str = derive_pubky_secret_key(seed).unwrap(); + assert_eq!(hex_str.len(), 64); // 32 bytes = 64 hex chars + assert!(hex::decode(&hex_str).is_ok()); +} + +#[test] +fn derive_secret_key_is_deterministic() { + let seed = vec![0x42u8; 64]; + let key1 = derive_pubky_secret_key(seed.clone()).unwrap(); + let key2 = derive_pubky_secret_key(seed).unwrap(); + assert_eq!(key1, key2); +} + +#[test] +fn derive_secret_key_different_seeds_produce_different_keys() { + let key1 = derive_pubky_secret_key(vec![0x01u8; 64]).unwrap(); + let key2 = derive_pubky_secret_key(vec![0x02u8; 64]).unwrap(); + assert_ne!(key1, key2); +} + +#[test] +fn derive_secret_key_rejects_short_seed() { + let result = derive_pubky_secret_key(vec![0u8; 32]); + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::KeyError { .. } => {} + other => panic!("expected KeyError, got: {other:?}"), + } +} + +#[test] +fn derive_secret_key_rejects_empty_seed() { + let result = derive_pubky_secret_key(vec![]); + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::KeyError { .. } => {} + other => panic!("expected KeyError, got: {other:?}"), + } +} + +#[test] +fn public_key_from_derived_secret_roundtrips() { + let seed = vec![0xCDu8; 64]; + let secret = derive_pubky_secret_key(seed).unwrap(); + let pk1 = pubky_public_key_from_secret(secret.clone()).unwrap(); + let pk2 = pubky_public_key_from_secret(secret).unwrap(); + assert_eq!(pk1, pk2); + assert!(!pk1.is_empty()); + // z32-encoded public keys are 52 characters + assert_eq!(pk1.len(), 52); +} + +#[test] +fn public_key_from_invalid_hex_returns_error() { + let result = pubky_public_key_from_secret("not-valid-hex".into()); + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::KeyError { .. } => {} + other => panic!("expected KeyError, got: {other:?}"), + } +} + +#[test] +fn public_key_from_empty_hex_returns_error() { + let result = pubky_public_key_from_secret(String::new()); + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::KeyError { .. } => {} + other => panic!("expected KeyError, got: {other:?}"), + } +} + +#[test] +fn public_key_from_wrong_length_hex_returns_error() { + let result = pubky_public_key_from_secret("aabb".into()); // only 2 bytes, need 32 + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::KeyError { .. } => {} + other => panic!("expected KeyError, got: {other:?}"), + } +} + +// ============================================================================ +// Sign up / sign in error tests +// ============================================================================ + +#[tokio::test] +async fn sign_up_invalid_secret_key_returns_error() { + let result = pubky_sign_up("bad-hex".into(), "some-homeserver".into(), None).await; + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::KeyError { .. } => {} + other => panic!("expected KeyError, got: {other:?}"), + } +} + +#[tokio::test] +async fn sign_in_invalid_secret_key_returns_error() { + let result = pubky_sign_in("bad-hex".into()).await; + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::KeyError { .. } => {} + other => panic!("expected KeyError, got: {other:?}"), + } +} + +// ============================================================================ +// Put with secret key error tests +// ============================================================================ + +#[tokio::test] +async fn put_with_secret_key_invalid_key_returns_error() { + let result = pubky_put_with_secret_key("bad-hex".into(), "/pub/test".into(), vec![]).await; + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::KeyError { .. } => {} + other => panic!("expected KeyError, got: {other:?}"), + } +} + +// ============================================================================ +// Session operation error tests +// ============================================================================ + +#[tokio::test] +async fn session_put_invalid_session_returns_error() { + let result = pubky_session_put("bad-session".into(), "/pub/test".into(), vec![]).await; + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::AuthFailed { .. } => {} + other => panic!("expected AuthFailed, got: {other:?}"), + } +} + +#[tokio::test] +async fn session_delete_invalid_session_returns_error() { + let result = pubky_session_delete("bad-session".into(), "/pub/test".into()).await; + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::AuthFailed { .. } => {} + other => panic!("expected AuthFailed, got: {other:?}"), + } +} + +#[tokio::test] +async fn session_list_invalid_session_returns_error() { + let result = pubky_session_list("bad-session".into(), "/pub/test/".into()).await; + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::AuthFailed { .. } => {} + other => panic!("expected AuthFailed, got: {other:?}"), + } +} + +// ============================================================================ +// Approver auth tests +// ============================================================================ + +#[test] +fn parse_signin_auth_url() { + let url = "pubkyauth://signin?caps=/pub/pubky.app/:rw&secret=kqnceEMgrNQM_xi06oQXjA3cJHX_RQmw1BY6JE1bse8&relay=https://httprelay.pubky.app/link"; + let details = parse_pubky_auth_url(url.into()).unwrap(); + assert_eq!(details.kind, PubkyAuthKind::Signin); + assert_eq!(details.capabilities, "/pub/pubky.app/:rw"); + assert_eq!(details.relay, "https://httprelay.pubky.app/link"); + assert!(details.homeserver.is_none()); + assert!(details.signup_token.is_none()); +} + +#[test] +fn parse_signup_auth_url_with_token() { + let url = "pubkyauth://signup?caps=/pub/pubky.app/:rw&secret=kqnceEMgrNQM_xi06oQXjA3cJHX_RQmw1BY6JE1bse8&relay=https://httprelay.pubky.app/link&hs=5jsjx1o6fzu6aeeo697r3i5rx15zq41kikcye8wtwdqm4nb4tryo&st=1234567890"; + let details = parse_pubky_auth_url(url.into()).unwrap(); + assert_eq!(details.kind, PubkyAuthKind::Signup); + assert_eq!(details.capabilities, "/pub/pubky.app/:rw"); + assert_eq!(details.relay, "https://httprelay.pubky.app/link"); + assert_eq!( + details.homeserver.as_deref(), + Some("5jsjx1o6fzu6aeeo697r3i5rx15zq41kikcye8wtwdqm4nb4tryo") + ); + assert_eq!(details.signup_token.as_deref(), Some("1234567890")); +} + +#[test] +fn parse_signup_auth_url_without_token() { + let url = "pubkyauth://signup?caps=/pub/pubky.app/:rw&secret=kqnceEMgrNQM_xi06oQXjA3cJHX_RQmw1BY6JE1bse8&relay=https://httprelay.pubky.app/link&hs=5jsjx1o6fzu6aeeo697r3i5rx15zq41kikcye8wtwdqm4nb4tryo"; + let details = parse_pubky_auth_url(url.into()).unwrap(); + assert_eq!(details.kind, PubkyAuthKind::Signup); + assert_eq!( + details.homeserver.as_deref(), + Some("5jsjx1o6fzu6aeeo697r3i5rx15zq41kikcye8wtwdqm4nb4tryo") + ); + assert!(details.signup_token.is_none()); +} + +#[test] +fn parse_old_format_auth_url() { + let url = "pubkyauth:///?caps=/pub/pubky.app/:rw&secret=kqnceEMgrNQM_xi06oQXjA3cJHX_RQmw1BY6JE1bse8&relay=https://httprelay.pubky.app/link"; + let details = parse_pubky_auth_url(url.into()).unwrap(); + assert_eq!(details.kind, PubkyAuthKind::Signin); +} + +#[test] +fn parse_invalid_auth_url_returns_error() { + let result = parse_pubky_auth_url("not-a-valid-url".into()); + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::AuthFailed { .. } => {} + other => panic!("expected AuthFailed, got: {other:?}"), + } +} + +#[test] +fn parse_auth_url_missing_params_returns_error() { + // Missing secret and relay + let result = parse_pubky_auth_url("pubkyauth://signin?caps=/pub/pubky.app/:rw".into()); + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::AuthFailed { .. } => {} + other => panic!("expected AuthFailed, got: {other:?}"), + } +} + +#[test] +fn parse_seed_export_url_returns_error() { + let url = "pubkyauth://secret_export?secret=kqnceEMgrNQM_xi06oQXjA3cJHX_RQmw1BY6JE1bse8"; + let result = parse_pubky_auth_url(url.into()); + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::AuthFailed { .. } => {} + other => panic!("expected AuthFailed, got: {other:?}"), + } +} + +#[tokio::test] +async fn approve_auth_invalid_key_returns_error() { + let url = "pubkyauth://signin?caps=/pub/pubky.app/:rw&secret=kqnceEMgrNQM_xi06oQXjA3cJHX_RQmw1BY6JE1bse8&relay=https://httprelay.pubky.app/link"; + let result = approve_pubky_auth(url.into(), "bad-hex".into()).await; + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::KeyError { .. } => {} + other => panic!("expected KeyError, got: {other:?}"), + } +} + +#[tokio::test] +async fn approve_auth_invalid_url_returns_error() { + let seed = vec![0xABu8; 64]; + let secret = derive_pubky_secret_key(seed).unwrap(); + let result = approve_pubky_auth("not-a-url".into(), secret).await; + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::AuthFailed { .. } => {} + other => panic!("expected AuthFailed, got: {other:?}"), + } +} + +// ============================================================================ +// String fetch tests +// ============================================================================ + +#[tokio::test] +async fn fetch_file_string_malformed_uri_returns_error() { + let result = fetch_pubky_file_string("not-a-uri".into()).await; + assert!(result.is_err()); + match result.unwrap_err() { + PubkyError::FetchFailed { .. } => {} + other => panic!("expected FetchFailed, got: {other:?}"), + } +} diff --git a/src/modules/pubky_swaps/delegation.rs b/src/modules/pubky_swaps/delegation.rs index 1d65043b..a3a58b74 100644 --- a/src/modules/pubky_swaps/delegation.rs +++ b/src/modules/pubky_swaps/delegation.rs @@ -13,7 +13,7 @@ use ed25519_dalek::{Signature, VerifyingKey}; use serde::{Deserialize, Serialize}; use super::errors::PubkySwapError; -use super::homeserver::fetch_public_file_if_any; +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"; @@ -141,7 +141,11 @@ pub(crate) fn verify_chain( 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 } + async move { + fetch_public_file_if_any(&addr) + .await + .map_err(PubkySwapError::transport) + } }; let Some(authorization) = fetch(AUTHORIZATION_PATH).await? else { return Ok(None); diff --git a/src/modules/pubky_swaps/homeserver.rs b/src/modules/pubky_swaps/homeserver.rs deleted file mode 100644 index 75cf7c7f..00000000 --- a/src/modules/pubky_swaps/homeserver.rs +++ /dev/null @@ -1,61 +0,0 @@ -//! Public reads from a provider's Pubky homeserver. - -use once_cell::sync::OnceCell; -use pubky::Pubky; - -use super::errors::PubkySwapError; - -static PUBKY: OnceCell = OnceCell::new(); - -fn pubky() -> Result<&'static Pubky, PubkySwapError> { - PUBKY.get_or_try_init(|| { - Pubky::new().map_err(|e| PubkySwapError::transport(format!("Resolution failed: {e}"))) - }) -} - -fn is_not_found(err: &impl std::fmt::Display) -> bool { - let msg = err.to_string(); - msg.contains("404") || msg.to_lowercase().contains("not found") -} - -fn fetch_failed(err: impl std::fmt::Display) -> PubkySwapError { - PubkySwapError::transport(format!("Fetch failed: {err}")) -} - -/// Read a public file at `addr` (`/pub/…`), or `None` when it is not published. -pub(super) async fn fetch_public_file_if_any( - addr: &str, -) -> Result>, PubkySwapError> { - 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(fetch_failed(e)), - }; - let bytes = response.bytes().await.map_err(fetch_failed)?; - Ok(Some(bytes.to_vec())) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn not_found_matches_404_and_not_found() { - assert!(is_not_found(&"HTTP status client error (404 Not Found)")); - assert!(is_not_found(&"Resource Not Found")); - assert!(!is_not_found(&"connection refused")); - } - - #[tokio::test] - async fn malformed_address_is_a_transport_error() { - match fetch_public_file_if_any("totally-not-a-pubky-uri").await { - Err(PubkySwapError::Transport { error_details }) => { - assert!( - error_details.starts_with("Fetch failed: "), - "{error_details}" - ) - } - other => panic!("expected Transport, got: {other:?}"), - } - } -} diff --git a/src/modules/pubky_swaps/mod.rs b/src/modules/pubky_swaps/mod.rs index a5d8ea6e..1becdd95 100644 --- a/src/modules/pubky_swaps/mod.rs +++ b/src/modules/pubky_swaps/mod.rs @@ -7,7 +7,6 @@ mod claim; mod client; mod delegation; mod errors; -mod homeserver; mod keys; mod router; mod store;