diff --git a/Cargo.lock b/Cargo.lock index 70e2f79..f33b537 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1333,7 +1333,7 @@ dependencies = [ ] [[package]] -name = "pubkymobile" +name = "pubkycore" version = "0.1.0" dependencies = [ "base64", diff --git a/Cargo.toml b/Cargo.toml index 6000e8e..89a1de6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,12 +1,12 @@ [package] -name = "pubkymobile" +name = "pubkycore" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [lib] -crate_type = ["cdylib", "rlib"] -name = "pubkymobile" +crate_type = ["cdylib"] +name = "pubkycore" [[bin]] name = "testing" diff --git a/README.md b/README.md index f53b9c3..05dacbf 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,11 @@ The Pubky Core Mobile SDK provides native bindings for iOS and Android platforms ./build.sh android ``` +### To build only Python bindings: +``` +./build.sh python +``` + ## Run Tests: ``` cargo test -- --test-threads=1 @@ -29,19 +34,18 @@ cargo test -- --test-threads=1 ### Installation 1. Add the XCFramework to your Xcode project: - - Drag bindings/ios/PubkyMobile.xcframework into your Xcode project + - Drag bindings/ios/PubkyCore.xcframework into your Xcode project Ensure "Copy items if needed" is checked Add the framework to your target 2. Copy the Swift bindings: - - Add bindings/ios/pubkymobile.swift to your project + - Add bindings/ios/pubkycore.swift to your project ### Basic Usage ```swift -import PubkyMobile -import PubkyMobile +import PubkyCore class PubkyManager { // Generate a new secret key @@ -125,14 +129,14 @@ class ViewController: UIViewController { 2. Add the Kotlin bindings: - - Copy bindings/android/pubkymobile.kt to your project's source directory + - Copy bindings/android/pubkycore.kt to your project's source directory ### Basic Usage ```kotlin class PubkyManager { init { // Initialize the library - System.loadLibrary("pubkymobile") + System.loadLibrary("pubkycore") } fun generateNewAccount(): String { diff --git a/bindings/android/jniLibs/arm64-v8a/libpubkymobile.so b/bindings/android/jniLibs/arm64-v8a/libpubkymobile.so deleted file mode 100755 index 74b48df..0000000 Binary files a/bindings/android/jniLibs/arm64-v8a/libpubkymobile.so and /dev/null differ diff --git a/bindings/android/jniLibs/armeabi-v7a/libpubkymobile.so b/bindings/android/jniLibs/armeabi-v7a/libpubkymobile.so deleted file mode 100755 index 8142071..0000000 Binary files a/bindings/android/jniLibs/armeabi-v7a/libpubkymobile.so and /dev/null differ diff --git a/bindings/android/jniLibs/x86/libpubkymobile.so b/bindings/android/jniLibs/x86/libpubkymobile.so deleted file mode 100755 index 01f9e43..0000000 Binary files a/bindings/android/jniLibs/x86/libpubkymobile.so and /dev/null differ diff --git a/bindings/android/jniLibs/x86_64/libpubkymobile.so b/bindings/android/jniLibs/x86_64/libpubkymobile.so deleted file mode 100755 index b87eb33..0000000 Binary files a/bindings/android/jniLibs/x86_64/libpubkymobile.so and /dev/null differ diff --git a/bindings/android/pubkymobile.kt b/bindings/android/pubkymobile.kt deleted file mode 100644 index 94bf55b..0000000 --- a/bindings/android/pubkymobile.kt +++ /dev/null @@ -1,1327 +0,0 @@ -// This file was autogenerated by some hot garbage in the `uniffi` crate. -// Trust me, you don't want to mess with it! - -@file:Suppress("NAME_SHADOWING") - -package uniffi.pubkymobile; - -// Common helper code. -// -// Ideally this would live in a separate .kt file where it can be unittested etc -// in isolation, and perhaps even published as a re-useable package. -// -// However, it's important that the details of how this helper code works (e.g. the -// way that different builtin types are passed across the FFI) exactly match what's -// expected by the Rust code on the other side of the interface. In practice right -// now that means coming from the exact some version of `uniffi` that was used to -// compile the Rust component. The easiest way to ensure this is to bundle the Kotlin -// helpers directly inline like we're doing here. - -import com.sun.jna.Library -import com.sun.jna.IntegerType -import com.sun.jna.Native -import com.sun.jna.Pointer -import com.sun.jna.Structure -import com.sun.jna.Callback -import com.sun.jna.ptr.* -import java.nio.ByteBuffer -import java.nio.ByteOrder -import java.nio.CharBuffer -import java.nio.charset.CodingErrorAction -import java.util.concurrent.ConcurrentHashMap -import java.util.concurrent.atomic.AtomicBoolean -import java.util.concurrent.atomic.AtomicLong -import java.util.concurrent.locks.ReentrantLock -import kotlin.concurrent.withLock - -// This is a helper for safely working with byte buffers returned from the Rust code. -// A rust-owned buffer is represented by its capacity, its current length, and a -// pointer to the underlying data. - -@Structure.FieldOrder("capacity", "len", "data") -open class RustBuffer : Structure() { - @JvmField var capacity: Int = 0 - @JvmField var len: Int = 0 - @JvmField var data: Pointer? = null - - class ByValue: RustBuffer(), Structure.ByValue - class ByReference: RustBuffer(), Structure.ByReference - - companion object { - internal fun alloc(size: Int = 0) = rustCall() { status -> - _UniFFILib.INSTANCE.ffi_pubkymobile_rustbuffer_alloc(size, status) - }.also { - if(it.data == null) { - throw RuntimeException("RustBuffer.alloc() returned null data pointer (size=${size})") - } - } - - internal fun create(capacity: Int, len: Int, data: Pointer?): RustBuffer.ByValue { - var buf = RustBuffer.ByValue() - buf.capacity = capacity - buf.len = len - buf.data = data - return buf - } - - internal fun free(buf: RustBuffer.ByValue) = rustCall() { status -> - _UniFFILib.INSTANCE.ffi_pubkymobile_rustbuffer_free(buf, status) - } - } - - @Suppress("TooGenericExceptionThrown") - fun asByteBuffer() = - this.data?.getByteBuffer(0, this.len.toLong())?.also { - it.order(ByteOrder.BIG_ENDIAN) - } -} - -/** - * The equivalent of the `*mut RustBuffer` type. - * Required for callbacks taking in an out pointer. - * - * Size is the sum of all values in the struct. - */ -class RustBufferByReference : ByReference(16) { - /** - * Set the pointed-to `RustBuffer` to the given value. - */ - fun setValue(value: RustBuffer.ByValue) { - // NOTE: The offsets are as they are in the C-like struct. - val pointer = getPointer() - pointer.setInt(0, value.capacity) - pointer.setInt(4, value.len) - pointer.setPointer(8, value.data) - } - - /** - * Get a `RustBuffer.ByValue` from this reference. - */ - fun getValue(): RustBuffer.ByValue { - val pointer = getPointer() - val value = RustBuffer.ByValue() - value.writeField("capacity", pointer.getInt(0)) - value.writeField("len", pointer.getInt(4)) - value.writeField("data", pointer.getPointer(8)) - - return value - } -} - -// This is a helper for safely passing byte references into the rust code. -// It's not actually used at the moment, because there aren't many things that you -// can take a direct pointer to in the JVM, and if we're going to copy something -// then we might as well copy it into a `RustBuffer`. But it's here for API -// completeness. - -@Structure.FieldOrder("len", "data") -open class ForeignBytes : Structure() { - @JvmField var len: Int = 0 - @JvmField var data: Pointer? = null - - class ByValue : ForeignBytes(), Structure.ByValue -} -// The FfiConverter interface handles converter types to and from the FFI -// -// All implementing objects should be public to support external types. When a -// type is external we need to import it's FfiConverter. -public interface FfiConverter { - // Convert an FFI type to a Kotlin type - fun lift(value: FfiType): KotlinType - - // Convert an Kotlin type to an FFI type - fun lower(value: KotlinType): FfiType - - // Read a Kotlin type from a `ByteBuffer` - fun read(buf: ByteBuffer): KotlinType - - // Calculate bytes to allocate when creating a `RustBuffer` - // - // This must return at least as many bytes as the write() function will - // write. It can return more bytes than needed, for example when writing - // Strings we can't know the exact bytes needed until we the UTF-8 - // encoding, so we pessimistically allocate the largest size possible (3 - // bytes per codepoint). Allocating extra bytes is not really a big deal - // because the `RustBuffer` is short-lived. - fun allocationSize(value: KotlinType): Int - - // Write a Kotlin type to a `ByteBuffer` - fun write(value: KotlinType, buf: ByteBuffer) - - // Lower a value into a `RustBuffer` - // - // This method lowers a value into a `RustBuffer` rather than the normal - // FfiType. It's used by the callback interface code. Callback interface - // returns are always serialized into a `RustBuffer` regardless of their - // normal FFI type. - fun lowerIntoRustBuffer(value: KotlinType): RustBuffer.ByValue { - val rbuf = RustBuffer.alloc(allocationSize(value)) - try { - val bbuf = rbuf.data!!.getByteBuffer(0, rbuf.capacity.toLong()).also { - it.order(ByteOrder.BIG_ENDIAN) - } - write(value, bbuf) - rbuf.writeField("len", bbuf.position()) - return rbuf - } catch (e: Throwable) { - RustBuffer.free(rbuf) - throw e - } - } - - // Lift a value from a `RustBuffer`. - // - // This here mostly because of the symmetry with `lowerIntoRustBuffer()`. - // It's currently only used by the `FfiConverterRustBuffer` class below. - fun liftFromRustBuffer(rbuf: RustBuffer.ByValue): KotlinType { - val byteBuf = rbuf.asByteBuffer()!! - try { - val item = read(byteBuf) - if (byteBuf.hasRemaining()) { - throw RuntimeException("junk remaining in buffer after lifting, something is very wrong!!") - } - return item - } finally { - RustBuffer.free(rbuf) - } - } -} - -// FfiConverter that uses `RustBuffer` as the FfiType -public interface FfiConverterRustBuffer: FfiConverter { - override fun lift(value: RustBuffer.ByValue) = liftFromRustBuffer(value) - override fun lower(value: KotlinType) = lowerIntoRustBuffer(value) -} -// A handful of classes and functions to support the generated data structures. -// This would be a good candidate for isolating in its own ffi-support lib. -// Error runtime. -@Structure.FieldOrder("code", "error_buf") -internal open class RustCallStatus : Structure() { - @JvmField var code: Byte = 0 - @JvmField var error_buf: RustBuffer.ByValue = RustBuffer.ByValue() - - class ByValue: RustCallStatus(), Structure.ByValue - - fun isSuccess(): Boolean { - return code == 0.toByte() - } - - fun isError(): Boolean { - return code == 1.toByte() - } - - fun isPanic(): Boolean { - return code == 2.toByte() - } -} - -class InternalException(message: String) : Exception(message) - -// Each top-level error class has a companion object that can lift the error from the call status's rust buffer -interface CallStatusErrorHandler { - fun lift(error_buf: RustBuffer.ByValue): E; -} - -// Helpers for calling Rust -// In practice we usually need to be synchronized to call this safely, so it doesn't -// synchronize itself - -// Call a rust function that returns a Result<>. Pass in the Error class companion that corresponds to the Err -private inline fun rustCallWithError(errorHandler: CallStatusErrorHandler, callback: (RustCallStatus) -> U): U { - var status = RustCallStatus(); - val return_value = callback(status) - checkCallStatus(errorHandler, status) - return return_value -} - -// Check RustCallStatus and throw an error if the call wasn't successful -private fun checkCallStatus(errorHandler: CallStatusErrorHandler, status: RustCallStatus) { - if (status.isSuccess()) { - return - } else if (status.isError()) { - throw errorHandler.lift(status.error_buf) - } else if (status.isPanic()) { - // when the rust code sees a panic, it tries to construct a rustbuffer - // with the message. but if that code panics, then it just sends back - // an empty buffer. - if (status.error_buf.len > 0) { - throw InternalException(FfiConverterString.lift(status.error_buf)) - } else { - throw InternalException("Rust panic") - } - } else { - throw InternalException("Unknown rust call status: $status.code") - } -} - -// CallStatusErrorHandler implementation for times when we don't expect a CALL_ERROR -object NullCallStatusErrorHandler: CallStatusErrorHandler { - override fun lift(error_buf: RustBuffer.ByValue): InternalException { - RustBuffer.free(error_buf) - return InternalException("Unexpected CALL_ERROR") - } -} - -// Call a rust function that returns a plain value -private inline fun rustCall(callback: (RustCallStatus) -> U): U { - return rustCallWithError(NullCallStatusErrorHandler, callback); -} - -// IntegerType that matches Rust's `usize` / C's `size_t` -public class USize(value: Long = 0) : IntegerType(Native.SIZE_T_SIZE, value, true) { - // This is needed to fill in the gaps of IntegerType's implementation of Number for Kotlin. - override fun toByte() = toInt().toByte() - // Needed until https://youtrack.jetbrains.com/issue/KT-47902 is fixed. - @Deprecated("`toInt().toChar()` is deprecated") - override fun toChar() = toInt().toChar() - override fun toShort() = toInt().toShort() - - fun writeToBuffer(buf: ByteBuffer) { - // Make sure we always write usize integers using native byte-order, since they may be - // casted to pointer values - buf.order(ByteOrder.nativeOrder()) - try { - when (Native.SIZE_T_SIZE) { - 4 -> buf.putInt(toInt()) - 8 -> buf.putLong(toLong()) - else -> throw RuntimeException("Invalid SIZE_T_SIZE: ${Native.SIZE_T_SIZE}") - } - } finally { - buf.order(ByteOrder.BIG_ENDIAN) - } - } - - companion object { - val size: Int - get() = Native.SIZE_T_SIZE - - fun readFromBuffer(buf: ByteBuffer) : USize { - // Make sure we always read usize integers using native byte-order, since they may be - // casted from pointer values - buf.order(ByteOrder.nativeOrder()) - try { - return when (Native.SIZE_T_SIZE) { - 4 -> USize(buf.getInt().toLong()) - 8 -> USize(buf.getLong()) - else -> throw RuntimeException("Invalid SIZE_T_SIZE: ${Native.SIZE_T_SIZE}") - } - } finally { - buf.order(ByteOrder.BIG_ENDIAN) - } - } - } -} - - -// Map handles to objects -// -// This is used when the Rust code expects an opaque pointer to represent some foreign object. -// Normally we would pass a pointer to the object, but JNA doesn't support getting a pointer from an -// object reference , nor does it support leaking a reference to Rust. -// -// Instead, this class maps USize values to objects so that we can pass a pointer-sized type to -// Rust when it needs an opaque pointer. -// -// TODO: refactor callbacks to use this class -internal class UniFfiHandleMap { - private val map = ConcurrentHashMap() - // Use AtomicInteger for our counter, since we may be on a 32-bit system. 4 billion possible - // values seems like enough. If somehow we generate 4 billion handles, then this will wrap - // around back to zero and we can assume the first handle generated will have been dropped by - // then. - private val counter = java.util.concurrent.atomic.AtomicInteger(0) - - val size: Int - get() = map.size - - fun insert(obj: T): USize { - val handle = USize(counter.getAndAdd(1).toLong()) - map.put(handle, obj) - return handle - } - - fun get(handle: USize): T? { - return map.get(handle) - } - - fun remove(handle: USize): T? { - return map.remove(handle) - } -} - -// FFI type for Rust future continuations -internal interface UniFffiRustFutureContinuationCallbackType : com.sun.jna.Callback { - fun callback(continuationHandle: USize, pollResult: Short); -} - -// Contains loading, initialization code, -// and the FFI Function declarations in a com.sun.jna.Library. -@Synchronized -private fun findLibraryName(componentName: String): String { - val libOverride = System.getProperty("uniffi.component.$componentName.libraryOverride") - if (libOverride != null) { - return libOverride - } - return "pubkymobile" -} - -private inline fun loadIndirect( - componentName: String -): Lib { - return Native.load(findLibraryName(componentName), Lib::class.java) -} - -// A JNA Library to expose the extern-C FFI definitions. -// This is an implementation detail which will be called internally by the public API. - -internal interface _UniFFILib : Library { - companion object { - internal val INSTANCE: _UniFFILib by lazy { - loadIndirect<_UniFFILib>(componentName = "pubkymobile") - .also { lib: _UniFFILib -> - uniffiCheckContractApiVersion(lib) - uniffiCheckApiChecksums(lib) - FfiConverterTypeEventListener.register(lib) - } - } - } - - fun uniffi_pubkymobile_fn_free_eventnotifier(`ptr`: Pointer,_uniffi_out_err: RustCallStatus, - ): Unit - fun uniffi_pubkymobile_fn_init_callback_eventlistener(`callbackStub`: ForeignCallback,_uniffi_out_err: RustCallStatus, - ): Unit - fun uniffi_pubkymobile_fn_func_auth(`url`: RustBuffer.ByValue,`secretKey`: RustBuffer.ByValue,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun uniffi_pubkymobile_fn_func_create_recovery_file(`secretKey`: RustBuffer.ByValue,`passphrase`: RustBuffer.ByValue,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun uniffi_pubkymobile_fn_func_decrypt_recovery_file(`recoveryFile`: RustBuffer.ByValue,`passphrase`: RustBuffer.ByValue,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun uniffi_pubkymobile_fn_func_delete_file(`url`: RustBuffer.ByValue,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun uniffi_pubkymobile_fn_func_generate_secret_key(_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun uniffi_pubkymobile_fn_func_get(`url`: RustBuffer.ByValue,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun uniffi_pubkymobile_fn_func_get_public_key_from_secret_key(`secretKey`: RustBuffer.ByValue,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun uniffi_pubkymobile_fn_func_list(`url`: RustBuffer.ByValue,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun uniffi_pubkymobile_fn_func_parse_auth_url(`url`: RustBuffer.ByValue,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun uniffi_pubkymobile_fn_func_publish(`recordName`: RustBuffer.ByValue,`recordContent`: RustBuffer.ByValue,`secretKey`: RustBuffer.ByValue,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun uniffi_pubkymobile_fn_func_publish_https(`recordName`: RustBuffer.ByValue,`target`: RustBuffer.ByValue,`secretKey`: RustBuffer.ByValue,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun uniffi_pubkymobile_fn_func_put(`url`: RustBuffer.ByValue,`content`: RustBuffer.ByValue,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun uniffi_pubkymobile_fn_func_remove_event_listener(_uniffi_out_err: RustCallStatus, - ): Unit - fun uniffi_pubkymobile_fn_func_resolve(`publicKey`: RustBuffer.ByValue,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun uniffi_pubkymobile_fn_func_resolve_https(`publicKey`: RustBuffer.ByValue,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun uniffi_pubkymobile_fn_func_session(`pubky`: RustBuffer.ByValue,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun uniffi_pubkymobile_fn_func_set_event_listener(`listener`: Long,_uniffi_out_err: RustCallStatus, - ): Unit - fun uniffi_pubkymobile_fn_func_sign_in(`secretKey`: RustBuffer.ByValue,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun uniffi_pubkymobile_fn_func_sign_out(`secretKey`: RustBuffer.ByValue,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun uniffi_pubkymobile_fn_func_sign_up(`secretKey`: RustBuffer.ByValue,`homeserver`: RustBuffer.ByValue,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun uniffi_pubkymobile_fn_func_switch_network(`useTestnet`: Byte,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun ffi_pubkymobile_rustbuffer_alloc(`size`: Int,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun ffi_pubkymobile_rustbuffer_from_bytes(`bytes`: ForeignBytes.ByValue,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun ffi_pubkymobile_rustbuffer_free(`buf`: RustBuffer.ByValue,_uniffi_out_err: RustCallStatus, - ): Unit - fun ffi_pubkymobile_rustbuffer_reserve(`buf`: RustBuffer.ByValue,`additional`: Int,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun ffi_pubkymobile_rust_future_continuation_callback_set(`callback`: UniFffiRustFutureContinuationCallbackType, - ): Unit - fun ffi_pubkymobile_rust_future_poll_u8(`handle`: Pointer,`uniffiCallback`: USize, - ): Unit - fun ffi_pubkymobile_rust_future_cancel_u8(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_free_u8(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_complete_u8(`handle`: Pointer,_uniffi_out_err: RustCallStatus, - ): Byte - fun ffi_pubkymobile_rust_future_poll_i8(`handle`: Pointer,`uniffiCallback`: USize, - ): Unit - fun ffi_pubkymobile_rust_future_cancel_i8(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_free_i8(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_complete_i8(`handle`: Pointer,_uniffi_out_err: RustCallStatus, - ): Byte - fun ffi_pubkymobile_rust_future_poll_u16(`handle`: Pointer,`uniffiCallback`: USize, - ): Unit - fun ffi_pubkymobile_rust_future_cancel_u16(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_free_u16(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_complete_u16(`handle`: Pointer,_uniffi_out_err: RustCallStatus, - ): Short - fun ffi_pubkymobile_rust_future_poll_i16(`handle`: Pointer,`uniffiCallback`: USize, - ): Unit - fun ffi_pubkymobile_rust_future_cancel_i16(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_free_i16(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_complete_i16(`handle`: Pointer,_uniffi_out_err: RustCallStatus, - ): Short - fun ffi_pubkymobile_rust_future_poll_u32(`handle`: Pointer,`uniffiCallback`: USize, - ): Unit - fun ffi_pubkymobile_rust_future_cancel_u32(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_free_u32(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_complete_u32(`handle`: Pointer,_uniffi_out_err: RustCallStatus, - ): Int - fun ffi_pubkymobile_rust_future_poll_i32(`handle`: Pointer,`uniffiCallback`: USize, - ): Unit - fun ffi_pubkymobile_rust_future_cancel_i32(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_free_i32(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_complete_i32(`handle`: Pointer,_uniffi_out_err: RustCallStatus, - ): Int - fun ffi_pubkymobile_rust_future_poll_u64(`handle`: Pointer,`uniffiCallback`: USize, - ): Unit - fun ffi_pubkymobile_rust_future_cancel_u64(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_free_u64(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_complete_u64(`handle`: Pointer,_uniffi_out_err: RustCallStatus, - ): Long - fun ffi_pubkymobile_rust_future_poll_i64(`handle`: Pointer,`uniffiCallback`: USize, - ): Unit - fun ffi_pubkymobile_rust_future_cancel_i64(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_free_i64(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_complete_i64(`handle`: Pointer,_uniffi_out_err: RustCallStatus, - ): Long - fun ffi_pubkymobile_rust_future_poll_f32(`handle`: Pointer,`uniffiCallback`: USize, - ): Unit - fun ffi_pubkymobile_rust_future_cancel_f32(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_free_f32(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_complete_f32(`handle`: Pointer,_uniffi_out_err: RustCallStatus, - ): Float - fun ffi_pubkymobile_rust_future_poll_f64(`handle`: Pointer,`uniffiCallback`: USize, - ): Unit - fun ffi_pubkymobile_rust_future_cancel_f64(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_free_f64(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_complete_f64(`handle`: Pointer,_uniffi_out_err: RustCallStatus, - ): Double - fun ffi_pubkymobile_rust_future_poll_pointer(`handle`: Pointer,`uniffiCallback`: USize, - ): Unit - fun ffi_pubkymobile_rust_future_cancel_pointer(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_free_pointer(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_complete_pointer(`handle`: Pointer,_uniffi_out_err: RustCallStatus, - ): Pointer - fun ffi_pubkymobile_rust_future_poll_rust_buffer(`handle`: Pointer,`uniffiCallback`: USize, - ): Unit - fun ffi_pubkymobile_rust_future_cancel_rust_buffer(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_free_rust_buffer(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_complete_rust_buffer(`handle`: Pointer,_uniffi_out_err: RustCallStatus, - ): RustBuffer.ByValue - fun ffi_pubkymobile_rust_future_poll_void(`handle`: Pointer,`uniffiCallback`: USize, - ): Unit - fun ffi_pubkymobile_rust_future_cancel_void(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_free_void(`handle`: Pointer, - ): Unit - fun ffi_pubkymobile_rust_future_complete_void(`handle`: Pointer,_uniffi_out_err: RustCallStatus, - ): Unit - fun uniffi_pubkymobile_checksum_func_auth( - ): Short - fun uniffi_pubkymobile_checksum_func_create_recovery_file( - ): Short - fun uniffi_pubkymobile_checksum_func_decrypt_recovery_file( - ): Short - fun uniffi_pubkymobile_checksum_func_delete_file( - ): Short - fun uniffi_pubkymobile_checksum_func_generate_secret_key( - ): Short - fun uniffi_pubkymobile_checksum_func_get( - ): Short - fun uniffi_pubkymobile_checksum_func_get_public_key_from_secret_key( - ): Short - fun uniffi_pubkymobile_checksum_func_list( - ): Short - fun uniffi_pubkymobile_checksum_func_parse_auth_url( - ): Short - fun uniffi_pubkymobile_checksum_func_publish( - ): Short - fun uniffi_pubkymobile_checksum_func_publish_https( - ): Short - fun uniffi_pubkymobile_checksum_func_put( - ): Short - fun uniffi_pubkymobile_checksum_func_remove_event_listener( - ): Short - fun uniffi_pubkymobile_checksum_func_resolve( - ): Short - fun uniffi_pubkymobile_checksum_func_resolve_https( - ): Short - fun uniffi_pubkymobile_checksum_func_session( - ): Short - fun uniffi_pubkymobile_checksum_func_set_event_listener( - ): Short - fun uniffi_pubkymobile_checksum_func_sign_in( - ): Short - fun uniffi_pubkymobile_checksum_func_sign_out( - ): Short - fun uniffi_pubkymobile_checksum_func_sign_up( - ): Short - fun uniffi_pubkymobile_checksum_func_switch_network( - ): Short - fun uniffi_pubkymobile_checksum_method_eventlistener_on_event_occurred( - ): Short - fun ffi_pubkymobile_uniffi_contract_version( - ): Int - -} - -private fun uniffiCheckContractApiVersion(lib: _UniFFILib) { - // Get the bindings contract version from our ComponentInterface - val bindings_contract_version = 24 - // Get the scaffolding contract version by calling the into the dylib - val scaffolding_contract_version = lib.ffi_pubkymobile_uniffi_contract_version() - if (bindings_contract_version != scaffolding_contract_version) { - throw RuntimeException("UniFFI contract version mismatch: try cleaning and rebuilding your project") - } -} - -@Suppress("UNUSED_PARAMETER") -private fun uniffiCheckApiChecksums(lib: _UniFFILib) { - if (lib.uniffi_pubkymobile_checksum_func_auth() != 61378.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } - if (lib.uniffi_pubkymobile_checksum_func_create_recovery_file() != 55903.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } - if (lib.uniffi_pubkymobile_checksum_func_decrypt_recovery_file() != 59688.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } - if (lib.uniffi_pubkymobile_checksum_func_delete_file() != 57905.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } - if (lib.uniffi_pubkymobile_checksum_func_generate_secret_key() != 63116.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } - if (lib.uniffi_pubkymobile_checksum_func_get() != 21596.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } - if (lib.uniffi_pubkymobile_checksum_func_get_public_key_from_secret_key() != 23603.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } - if (lib.uniffi_pubkymobile_checksum_func_list() != 8522.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } - if (lib.uniffi_pubkymobile_checksum_func_parse_auth_url() != 29088.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } - if (lib.uniffi_pubkymobile_checksum_func_publish() != 20156.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } - if (lib.uniffi_pubkymobile_checksum_func_publish_https() != 14705.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } - if (lib.uniffi_pubkymobile_checksum_func_put() != 51107.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } - if (lib.uniffi_pubkymobile_checksum_func_remove_event_listener() != 6794.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } - if (lib.uniffi_pubkymobile_checksum_func_resolve() != 18303.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } - if (lib.uniffi_pubkymobile_checksum_func_resolve_https() != 34593.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } - if (lib.uniffi_pubkymobile_checksum_func_session() != 65177.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } - if (lib.uniffi_pubkymobile_checksum_func_set_event_listener() != 19468.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } - if (lib.uniffi_pubkymobile_checksum_func_sign_in() != 21006.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } - if (lib.uniffi_pubkymobile_checksum_func_sign_out() != 59116.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } - if (lib.uniffi_pubkymobile_checksum_func_sign_up() != 58756.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } - if (lib.uniffi_pubkymobile_checksum_func_switch_network() != 14054.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } - if (lib.uniffi_pubkymobile_checksum_method_eventlistener_on_event_occurred() != 39865.toShort()) { - throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } -} - -// Async support - -// Public interface members begin here. - - -public object FfiConverterBoolean: FfiConverter { - override fun lift(value: Byte): Boolean { - return value.toInt() != 0 - } - - override fun read(buf: ByteBuffer): Boolean { - return lift(buf.get()) - } - - override fun lower(value: Boolean): Byte { - return if (value) 1.toByte() else 0.toByte() - } - - override fun allocationSize(value: Boolean) = 1 - - override fun write(value: Boolean, buf: ByteBuffer) { - buf.put(lower(value)) - } -} - -public object FfiConverterString: FfiConverter { - // Note: we don't inherit from FfiConverterRustBuffer, because we use a - // special encoding when lowering/lifting. We can use `RustBuffer.len` to - // store our length and avoid writing it out to the buffer. - override fun lift(value: RustBuffer.ByValue): String { - try { - val byteArr = ByteArray(value.len) - value.asByteBuffer()!!.get(byteArr) - return byteArr.toString(Charsets.UTF_8) - } finally { - RustBuffer.free(value) - } - } - - override fun read(buf: ByteBuffer): String { - val len = buf.getInt() - val byteArr = ByteArray(len) - buf.get(byteArr) - return byteArr.toString(Charsets.UTF_8) - } - - fun toUtf8(value: String): ByteBuffer { - // Make sure we don't have invalid UTF-16, check for lone surrogates. - return Charsets.UTF_8.newEncoder().run { - onMalformedInput(CodingErrorAction.REPORT) - encode(CharBuffer.wrap(value)) - } - } - - override fun lower(value: String): RustBuffer.ByValue { - val byteBuf = toUtf8(value) - // Ideally we'd pass these bytes to `ffi_bytebuffer_from_bytes`, but doing so would require us - // to copy them into a JNA `Memory`. So we might as well directly copy them into a `RustBuffer`. - val rbuf = RustBuffer.alloc(byteBuf.limit()) - rbuf.asByteBuffer()!!.put(byteBuf) - return rbuf - } - - // We aren't sure exactly how many bytes our string will be once it's UTF-8 - // encoded. Allocate 3 bytes per UTF-16 code unit which will always be - // enough. - override fun allocationSize(value: String): Int { - val sizeForLength = 4 - val sizeForString = value.length * 3 - return sizeForLength + sizeForString - } - - override fun write(value: String, buf: ByteBuffer) { - val byteBuf = toUtf8(value) - buf.putInt(byteBuf.limit()) - buf.put(byteBuf) - } -} - - -// Interface implemented by anything that can contain an object reference. -// -// Such types expose a `destroy()` method that must be called to cleanly -// dispose of the contained objects. Failure to call this method may result -// in memory leaks. -// -// The easiest way to ensure this method is called is to use the `.use` -// helper method to execute a block and destroy the object at the end. -interface Disposable { - fun destroy() - companion object { - fun destroy(vararg args: Any?) { - args.filterIsInstance() - .forEach(Disposable::destroy) - } - } -} - -inline fun T.use(block: (T) -> R) = - try { - block(this) - } finally { - try { - // N.B. our implementation is on the nullable type `Disposable?`. - this?.destroy() - } catch (e: Throwable) { - // swallow - } - } - -// The base class for all UniFFI Object types. -// -// This class provides core operations for working with the Rust `Arc` pointer to -// the live Rust struct on the other side of the FFI. -// -// There's some subtlety here, because we have to be careful not to operate on a Rust -// struct after it has been dropped, and because we must expose a public API for freeing -// the Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: -// -// * Each `FFIObject` instance holds an opaque pointer to the underlying Rust struct. -// Method calls need to read this pointer from the object's state and pass it in to -// the Rust FFI. -// -// * When an `FFIObject` is no longer needed, its pointer should be passed to a -// special destructor function provided by the Rust FFI, which will drop the -// underlying Rust struct. -// -// * Given an `FFIObject` instance, calling code is expected to call the special -// `destroy` method in order to free it after use, either by calling it explicitly -// or by using a higher-level helper like the `use` method. Failing to do so will -// leak the underlying Rust struct. -// -// * We can't assume that calling code will do the right thing, and must be prepared -// to handle Kotlin method calls executing concurrently with or even after a call to -// `destroy`, and to handle multiple (possibly concurrent!) calls to `destroy`. -// -// * We must never allow Rust code to operate on the underlying Rust struct after -// the destructor has been called, and must never call the destructor more than once. -// Doing so may trigger memory unsafety. -// -// If we try to implement this with mutual exclusion on access to the pointer, there is the -// possibility of a race between a method call and a concurrent call to `destroy`: -// -// * Thread A starts a method call, reads the value of the pointer, but is interrupted -// before it can pass the pointer over the FFI to Rust. -// * Thread B calls `destroy` and frees the underlying Rust struct. -// * Thread A resumes, passing the already-read pointer value to Rust and triggering -// a use-after-free. -// -// One possible solution would be to use a `ReadWriteLock`, with each method call taking -// a read lock (and thus allowed to run concurrently) and the special `destroy` method -// taking a write lock (and thus blocking on live method calls). However, we aim not to -// generate methods with any hidden blocking semantics, and a `destroy` method that might -// block if called incorrectly seems to meet that bar. -// -// So, we achieve our goals by giving each `FFIObject` an associated `AtomicLong` counter to track -// the number of in-flight method calls, and an `AtomicBoolean` flag to indicate whether `destroy` -// has been called. These are updated according to the following rules: -// -// * The initial value of the counter is 1, indicating a live object with no in-flight calls. -// The initial value for the flag is false. -// -// * At the start of each method call, we atomically check the counter. -// If it is 0 then the underlying Rust struct has already been destroyed and the call is aborted. -// If it is nonzero them we atomically increment it by 1 and proceed with the method call. -// -// * At the end of each method call, we atomically decrement and check the counter. -// If it has reached zero then we destroy the underlying Rust struct. -// -// * When `destroy` is called, we atomically flip the flag from false to true. -// If the flag was already true we silently fail. -// Otherwise we atomically decrement and check the counter. -// If it has reached zero then we destroy the underlying Rust struct. -// -// Astute readers may observe that this all sounds very similar to the way that Rust's `Arc` works, -// and indeed it is, with the addition of a flag to guard against multiple calls to `destroy`. -// -// The overall effect is that the underlying Rust struct is destroyed only when `destroy` has been -// called *and* all in-flight method calls have completed, avoiding violating any of the expectations -// of the underlying Rust code. -// -// In the future we may be able to replace some of this with automatic finalization logic, such as using -// the new "Cleaner" functionaility in Java 9. The above scheme has been designed to work even if `destroy` is -// invoked by garbage-collection machinery rather than by calling code (which by the way, it's apparently also -// possible for the JVM to finalize an object while there is an in-flight call to one of its methods [1], -// so there would still be some complexity here). -// -// Sigh...all of this for want of a robust finalization mechanism. -// -// [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 -// -abstract class FFIObject( - protected val pointer: Pointer -): Disposable, AutoCloseable { - - private val wasDestroyed = AtomicBoolean(false) - private val callCounter = AtomicLong(1) - - open protected fun freeRustArcPtr() { - // To be overridden in subclasses. - } - - override fun destroy() { - // Only allow a single call to this method. - // TODO: maybe we should log a warning if called more than once? - if (this.wasDestroyed.compareAndSet(false, true)) { - // This decrement always matches the initial count of 1 given at creation time. - if (this.callCounter.decrementAndGet() == 0L) { - this.freeRustArcPtr() - } - } - } - - @Synchronized - override fun close() { - this.destroy() - } - - internal inline fun callWithPointer(block: (ptr: Pointer) -> R): R { - // Check and increment the call counter, to keep the object alive. - // This needs a compare-and-set retry loop in case of concurrent updates. - do { - val c = this.callCounter.get() - if (c == 0L) { - throw IllegalStateException("${this.javaClass.simpleName} object has already been destroyed") - } - if (c == Long.MAX_VALUE) { - throw IllegalStateException("${this.javaClass.simpleName} call counter would overflow") - } - } while (! this.callCounter.compareAndSet(c, c + 1L)) - // Now we can safely do the method call without the pointer being freed concurrently. - try { - return block(this.pointer) - } finally { - // This decrement always matches the increment we performed above. - if (this.callCounter.decrementAndGet() == 0L) { - this.freeRustArcPtr() - } - } - } -} - -public interface EventNotifierInterface { - - companion object -} - -class EventNotifier( - pointer: Pointer -) : FFIObject(pointer), EventNotifierInterface { - - /** - * Disconnect the object from the underlying Rust object. - * - * It can be called more than once, but once called, interacting with the object - * causes an `IllegalStateException`. - * - * Clients **must** call this method once done with the object, or cause a memory leak. - */ - override protected fun freeRustArcPtr() { - rustCall() { status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_free_eventnotifier(this.pointer, status) - } - } - - - - - companion object - -} - -public object FfiConverterTypeEventNotifier: FfiConverter { - override fun lower(value: EventNotifier): Pointer = value.callWithPointer { it } - - override fun lift(value: Pointer): EventNotifier { - return EventNotifier(value) - } - - override fun read(buf: ByteBuffer): EventNotifier { - // The Rust code always writes pointers as 8 bytes, and will - // fail to compile if they don't fit. - return lift(Pointer(buf.getLong())) - } - - override fun allocationSize(value: EventNotifier) = 8 - - override fun write(value: EventNotifier, buf: ByteBuffer) { - // The Rust code always expects pointers written as 8 bytes, - // and will fail to compile if they don't fit. - buf.putLong(Pointer.nativeValue(lower(value))) - } -} - - - - -internal typealias Handle = Long -internal class ConcurrentHandleMap( - private val leftMap: MutableMap = mutableMapOf(), - private val rightMap: MutableMap = mutableMapOf() -) { - private val lock = java.util.concurrent.locks.ReentrantLock() - private val currentHandle = AtomicLong(0L) - private val stride = 1L - - fun insert(obj: T): Handle = - lock.withLock { - rightMap[obj] ?: - currentHandle.getAndAdd(stride) - .also { handle -> - leftMap[handle] = obj - rightMap[obj] = handle - } - } - - fun get(handle: Handle) = lock.withLock { - leftMap[handle] - } - - fun delete(handle: Handle) { - this.remove(handle) - } - - fun remove(handle: Handle): T? = - lock.withLock { - leftMap.remove(handle)?.let { obj -> - rightMap.remove(obj) - obj - } - } -} - -interface ForeignCallback : com.sun.jna.Callback { - public fun callback(handle: Handle, method: Int, argsData: Pointer, argsLen: Int, outBuf: RustBufferByReference): Int -} - -// Magic number for the Rust proxy to call using the same mechanism as every other method, -// to free the callback once it's dropped by Rust. -internal const val IDX_CALLBACK_FREE = 0 -// Callback return codes -internal const val UNIFFI_CALLBACK_SUCCESS = 0 -internal const val UNIFFI_CALLBACK_ERROR = 1 -internal const val UNIFFI_CALLBACK_UNEXPECTED_ERROR = 2 - -public abstract class FfiConverterCallbackInterface( - protected val foreignCallback: ForeignCallback -): FfiConverter { - private val handleMap = ConcurrentHandleMap() - - // Registers the foreign callback with the Rust side. - // This method is generated for each callback interface. - internal abstract fun register(lib: _UniFFILib) - - fun drop(handle: Handle): RustBuffer.ByValue { - return handleMap.remove(handle).let { RustBuffer.ByValue() } - } - - override fun lift(value: Handle): CallbackInterface { - return handleMap.get(value) ?: throw InternalException("No callback in handlemap; this is a Uniffi bug") - } - - override fun read(buf: ByteBuffer) = lift(buf.getLong()) - - override fun lower(value: CallbackInterface) = - handleMap.insert(value).also { - assert(handleMap.get(it) === value) { "Handle map is not returning the object we just placed there. This is a bug in the HandleMap." } - } - - override fun allocationSize(value: CallbackInterface) = 8 - - override fun write(value: CallbackInterface, buf: ByteBuffer) { - buf.putLong(lower(value)) - } -} - -// Declaration and FfiConverters for EventListener Callback Interface - -public interface EventListener { - fun `onEventOccurred`(`eventData`: String) - - companion object -} - -// The ForeignCallback that is passed to Rust. -internal class ForeignCallbackTypeEventListener : ForeignCallback { - @Suppress("TooGenericExceptionCaught") - override fun callback(handle: Handle, method: Int, argsData: Pointer, argsLen: Int, outBuf: RustBufferByReference): Int { - val cb = FfiConverterTypeEventListener.lift(handle) - return when (method) { - IDX_CALLBACK_FREE -> { - FfiConverterTypeEventListener.drop(handle) - // Successful return - // See docs of ForeignCallback in `uniffi_core/src/ffi/foreigncallbacks.rs` - UNIFFI_CALLBACK_SUCCESS - } - 1 -> { - // Call the method, write to outBuf and return a status code - // See docs of ForeignCallback in `uniffi_core/src/ffi/foreigncallbacks.rs` for info - try { - this.`invokeOnEventOccurred`(cb, argsData, argsLen, outBuf) - } catch (e: Throwable) { - // Unexpected error - try { - // Try to serialize the error into a string - outBuf.setValue(FfiConverterString.lower(e.toString())) - } catch (e: Throwable) { - // If that fails, then it's time to give up and just return - } - UNIFFI_CALLBACK_UNEXPECTED_ERROR - } - } - - else -> { - // An unexpected error happened. - // See docs of ForeignCallback in `uniffi_core/src/ffi/foreigncallbacks.rs` - try { - // Try to serialize the error into a string - outBuf.setValue(FfiConverterString.lower("Invalid Callback index")) - } catch (e: Throwable) { - // If that fails, then it's time to give up and just return - } - UNIFFI_CALLBACK_UNEXPECTED_ERROR - } - } - } - - - @Suppress("UNUSED_PARAMETER") - private fun `invokeOnEventOccurred`(kotlinCallbackInterface: EventListener, argsData: Pointer, argsLen: Int, outBuf: RustBufferByReference): Int { - val argsBuf = argsData.getByteBuffer(0, argsLen.toLong()).also { - it.order(ByteOrder.BIG_ENDIAN) - } - fun makeCall() : Int { - kotlinCallbackInterface.`onEventOccurred`( - FfiConverterString.read(argsBuf) - ) - return UNIFFI_CALLBACK_SUCCESS - } - fun makeCallAndHandleError() : Int = makeCall() - - return makeCallAndHandleError() - } - -} - -// The ffiConverter which transforms the Callbacks in to Handles to pass to Rust. -public object FfiConverterTypeEventListener: FfiConverterCallbackInterface( - foreignCallback = ForeignCallbackTypeEventListener() -) { - override fun register(lib: _UniFFILib) { - rustCall() { status -> - lib.uniffi_pubkymobile_fn_init_callback_eventlistener(this.foreignCallback, status) - } - } -} - - - - -public object FfiConverterSequenceString: FfiConverterRustBuffer> { - override fun read(buf: ByteBuffer): List { - val len = buf.getInt() - return List(len) { - FfiConverterString.read(buf) - } - } - - override fun allocationSize(value: List): Int { - val sizeForLength = 4 - val sizeForItems = value.map { FfiConverterString.allocationSize(it) }.sum() - return sizeForLength + sizeForItems - } - - override fun write(value: List, buf: ByteBuffer) { - buf.putInt(value.size) - value.forEach { - FfiConverterString.write(it, buf) - } - } -} - -fun `auth`(`url`: String, `secretKey`: String): List { - return FfiConverterSequenceString.lift( - rustCall() { _status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_func_auth(FfiConverterString.lower(`url`),FfiConverterString.lower(`secretKey`),_status) -}) -} - - -fun `createRecoveryFile`(`secretKey`: String, `passphrase`: String): List { - return FfiConverterSequenceString.lift( - rustCall() { _status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_func_create_recovery_file(FfiConverterString.lower(`secretKey`),FfiConverterString.lower(`passphrase`),_status) -}) -} - - -fun `decryptRecoveryFile`(`recoveryFile`: String, `passphrase`: String): List { - return FfiConverterSequenceString.lift( - rustCall() { _status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_func_decrypt_recovery_file(FfiConverterString.lower(`recoveryFile`),FfiConverterString.lower(`passphrase`),_status) -}) -} - - -fun `deleteFile`(`url`: String): List { - return FfiConverterSequenceString.lift( - rustCall() { _status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_func_delete_file(FfiConverterString.lower(`url`),_status) -}) -} - - -fun `generateSecretKey`(): List { - return FfiConverterSequenceString.lift( - rustCall() { _status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_func_generate_secret_key(_status) -}) -} - - -fun `get`(`url`: String): List { - return FfiConverterSequenceString.lift( - rustCall() { _status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_func_get(FfiConverterString.lower(`url`),_status) -}) -} - - -fun `getPublicKeyFromSecretKey`(`secretKey`: String): List { - return FfiConverterSequenceString.lift( - rustCall() { _status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_func_get_public_key_from_secret_key(FfiConverterString.lower(`secretKey`),_status) -}) -} - - -fun `list`(`url`: String): List { - return FfiConverterSequenceString.lift( - rustCall() { _status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_func_list(FfiConverterString.lower(`url`),_status) -}) -} - - -fun `parseAuthUrl`(`url`: String): List { - return FfiConverterSequenceString.lift( - rustCall() { _status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_func_parse_auth_url(FfiConverterString.lower(`url`),_status) -}) -} - - -fun `publish`(`recordName`: String, `recordContent`: String, `secretKey`: String): List { - return FfiConverterSequenceString.lift( - rustCall() { _status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_func_publish(FfiConverterString.lower(`recordName`),FfiConverterString.lower(`recordContent`),FfiConverterString.lower(`secretKey`),_status) -}) -} - - -fun `publishHttps`(`recordName`: String, `target`: String, `secretKey`: String): List { - return FfiConverterSequenceString.lift( - rustCall() { _status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_func_publish_https(FfiConverterString.lower(`recordName`),FfiConverterString.lower(`target`),FfiConverterString.lower(`secretKey`),_status) -}) -} - - -fun `put`(`url`: String, `content`: String): List { - return FfiConverterSequenceString.lift( - rustCall() { _status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_func_put(FfiConverterString.lower(`url`),FfiConverterString.lower(`content`),_status) -}) -} - - -fun `removeEventListener`() = - - rustCall() { _status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_func_remove_event_listener(_status) -} - - - -fun `resolve`(`publicKey`: String): List { - return FfiConverterSequenceString.lift( - rustCall() { _status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_func_resolve(FfiConverterString.lower(`publicKey`),_status) -}) -} - - -fun `resolveHttps`(`publicKey`: String): List { - return FfiConverterSequenceString.lift( - rustCall() { _status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_func_resolve_https(FfiConverterString.lower(`publicKey`),_status) -}) -} - - -fun `session`(`pubky`: String): List { - return FfiConverterSequenceString.lift( - rustCall() { _status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_func_session(FfiConverterString.lower(`pubky`),_status) -}) -} - - -fun `setEventListener`(`listener`: EventListener) = - - rustCall() { _status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_func_set_event_listener(FfiConverterTypeEventListener.lower(`listener`),_status) -} - - - -fun `signIn`(`secretKey`: String): List { - return FfiConverterSequenceString.lift( - rustCall() { _status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_func_sign_in(FfiConverterString.lower(`secretKey`),_status) -}) -} - - -fun `signOut`(`secretKey`: String): List { - return FfiConverterSequenceString.lift( - rustCall() { _status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_func_sign_out(FfiConverterString.lower(`secretKey`),_status) -}) -} - - -fun `signUp`(`secretKey`: String, `homeserver`: String): List { - return FfiConverterSequenceString.lift( - rustCall() { _status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_func_sign_up(FfiConverterString.lower(`secretKey`),FfiConverterString.lower(`homeserver`),_status) -}) -} - - -fun `switchNetwork`(`useTestnet`: Boolean): List { - return FfiConverterSequenceString.lift( - rustCall() { _status -> - _UniFFILib.INSTANCE.uniffi_pubkymobile_fn_func_switch_network(FfiConverterBoolean.lower(`useTestnet`),_status) -}) -} - - diff --git a/bindings/ios/PubkyMobile.xcframework/Info.plist b/bindings/ios/PubkyMobile.xcframework/Info.plist deleted file mode 100644 index bb3ac5e..0000000 --- a/bindings/ios/PubkyMobile.xcframework/Info.plist +++ /dev/null @@ -1,47 +0,0 @@ - - - - - AvailableLibraries - - - BinaryPath - libpubkymobile.a - HeadersPath - Headers - LibraryIdentifier - ios-arm64 - LibraryPath - libpubkymobile.a - SupportedArchitectures - - arm64 - - SupportedPlatform - ios - - - BinaryPath - libpubkymobile.a - HeadersPath - Headers - LibraryIdentifier - ios-arm64-simulator - LibraryPath - libpubkymobile.a - SupportedArchitectures - - arm64 - - SupportedPlatform - ios - SupportedPlatformVariant - simulator - - - CFBundlePackageType - XFWK - XCFrameworkFormatVersion - 1.0 - - diff --git a/bindings/ios/PubkyMobile.xcframework/ios-arm64-simulator/Headers/module.modulemap b/bindings/ios/PubkyMobile.xcframework/ios-arm64-simulator/Headers/module.modulemap deleted file mode 100644 index 09b533a..0000000 --- a/bindings/ios/PubkyMobile.xcframework/ios-arm64-simulator/Headers/module.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -// This file was autogenerated by some hot garbage in the `uniffi` crate. -// Trust me, you don't want to mess with it! -module pubkymobileFFI { - header "pubkymobileFFI.h" - export * -} \ No newline at end of file diff --git a/bindings/ios/PubkyMobile.xcframework/ios-arm64-simulator/Headers/pubkymobileFFI.h b/bindings/ios/PubkyMobile.xcframework/ios-arm64-simulator/Headers/pubkymobileFFI.h deleted file mode 100644 index 3694adc..0000000 --- a/bindings/ios/PubkyMobile.xcframework/ios-arm64-simulator/Headers/pubkymobileFFI.h +++ /dev/null @@ -1,297 +0,0 @@ -// This file was autogenerated by some hot garbage in the `uniffi` crate. -// Trust me, you don't want to mess with it! - -#pragma once - -#include -#include -#include - -// The following structs are used to implement the lowest level -// of the FFI, and thus useful to multiple uniffied crates. -// We ensure they are declared exactly once, with a header guard, UNIFFI_SHARED_H. -#ifdef UNIFFI_SHARED_H - // We also try to prevent mixing versions of shared uniffi header structs. - // If you add anything to the #else block, you must increment the version suffix in UNIFFI_SHARED_HEADER_V4 - #ifndef UNIFFI_SHARED_HEADER_V4 - #error Combining helper code from multiple versions of uniffi is not supported - #endif // ndef UNIFFI_SHARED_HEADER_V4 -#else -#define UNIFFI_SHARED_H -#define UNIFFI_SHARED_HEADER_V4 -// ⚠️ Attention: If you change this #else block (ending in `#endif // def UNIFFI_SHARED_H`) you *must* ⚠️ -// ⚠️ increment the version suffix in all instances of UNIFFI_SHARED_HEADER_V4 in this file. ⚠️ - -typedef struct RustBuffer -{ - int32_t capacity; - int32_t len; - uint8_t *_Nullable data; -} RustBuffer; - -typedef int32_t (*ForeignCallback)(uint64_t, int32_t, const uint8_t *_Nonnull, int32_t, RustBuffer *_Nonnull); - -// Task defined in Rust that Swift executes -typedef void (*UniFfiRustTaskCallback)(const void * _Nullable, int8_t); - -// Callback to execute Rust tasks using a Swift Task -// -// Args: -// executor: ForeignExecutor lowered into a size_t value -// delay: Delay in MS -// task: UniFfiRustTaskCallback to call -// task_data: data to pass the task callback -typedef int8_t (*UniFfiForeignExecutorCallback)(size_t, uint32_t, UniFfiRustTaskCallback _Nullable, const void * _Nullable); - -typedef struct ForeignBytes -{ - int32_t len; - const uint8_t *_Nullable data; -} ForeignBytes; - -// Error definitions -typedef struct RustCallStatus { - int8_t code; - RustBuffer errorBuf; -} RustCallStatus; - -// ⚠️ Attention: If you change this #else block (ending in `#endif // def UNIFFI_SHARED_H`) you *must* ⚠️ -// ⚠️ increment the version suffix in all instances of UNIFFI_SHARED_HEADER_V4 in this file. ⚠️ -#endif // def UNIFFI_SHARED_H - -// Continuation callback for UniFFI Futures -typedef void (*UniFfiRustFutureContinuation)(void * _Nonnull, int8_t); - -// Scaffolding functions -void uniffi_pubkymobile_fn_free_eventnotifier(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status -); -void uniffi_pubkymobile_fn_init_callback_eventlistener(ForeignCallback _Nonnull callback_stub, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_auth(RustBuffer url, RustBuffer secret_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_create_recovery_file(RustBuffer secret_key, RustBuffer passphrase, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_decrypt_recovery_file(RustBuffer recovery_file, RustBuffer passphrase, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_delete_file(RustBuffer url, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_generate_secret_key(RustCallStatus *_Nonnull out_status - -); -RustBuffer uniffi_pubkymobile_fn_func_get(RustBuffer url, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_get_public_key_from_secret_key(RustBuffer secret_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_list(RustBuffer url, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_parse_auth_url(RustBuffer url, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_publish(RustBuffer record_name, RustBuffer record_content, RustBuffer secret_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_publish_https(RustBuffer record_name, RustBuffer target, RustBuffer secret_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_put(RustBuffer url, RustBuffer content, RustCallStatus *_Nonnull out_status -); -void uniffi_pubkymobile_fn_func_remove_event_listener(RustCallStatus *_Nonnull out_status - -); -RustBuffer uniffi_pubkymobile_fn_func_resolve(RustBuffer public_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_resolve_https(RustBuffer public_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_session(RustBuffer pubky, RustCallStatus *_Nonnull out_status -); -void uniffi_pubkymobile_fn_func_set_event_listener(uint64_t listener, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_sign_in(RustBuffer secret_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_sign_out(RustBuffer secret_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_sign_up(RustBuffer secret_key, RustBuffer homeserver, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_switch_network(int8_t use_testnet, RustCallStatus *_Nonnull out_status -); -RustBuffer ffi_pubkymobile_rustbuffer_alloc(int32_t size, RustCallStatus *_Nonnull out_status -); -RustBuffer ffi_pubkymobile_rustbuffer_from_bytes(ForeignBytes bytes, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rustbuffer_free(RustBuffer buf, RustCallStatus *_Nonnull out_status -); -RustBuffer ffi_pubkymobile_rustbuffer_reserve(RustBuffer buf, int32_t additional, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_continuation_callback_set(UniFfiRustFutureContinuation _Nonnull callback -); -void ffi_pubkymobile_rust_future_poll_u8(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_u8(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_u8(void* _Nonnull handle -); -uint8_t ffi_pubkymobile_rust_future_complete_u8(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_i8(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_i8(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_i8(void* _Nonnull handle -); -int8_t ffi_pubkymobile_rust_future_complete_i8(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_u16(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_u16(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_u16(void* _Nonnull handle -); -uint16_t ffi_pubkymobile_rust_future_complete_u16(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_i16(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_i16(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_i16(void* _Nonnull handle -); -int16_t ffi_pubkymobile_rust_future_complete_i16(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_u32(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_u32(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_u32(void* _Nonnull handle -); -uint32_t ffi_pubkymobile_rust_future_complete_u32(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_i32(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_i32(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_i32(void* _Nonnull handle -); -int32_t ffi_pubkymobile_rust_future_complete_i32(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_u64(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_u64(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_u64(void* _Nonnull handle -); -uint64_t ffi_pubkymobile_rust_future_complete_u64(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_i64(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_i64(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_i64(void* _Nonnull handle -); -int64_t ffi_pubkymobile_rust_future_complete_i64(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_f32(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_f32(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_f32(void* _Nonnull handle -); -float ffi_pubkymobile_rust_future_complete_f32(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_f64(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_f64(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_f64(void* _Nonnull handle -); -double ffi_pubkymobile_rust_future_complete_f64(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_pointer(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_pointer(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_pointer(void* _Nonnull handle -); -void*_Nonnull ffi_pubkymobile_rust_future_complete_pointer(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_rust_buffer(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_rust_buffer(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_rust_buffer(void* _Nonnull handle -); -RustBuffer ffi_pubkymobile_rust_future_complete_rust_buffer(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_void(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_void(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_void(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_complete_void(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -uint16_t uniffi_pubkymobile_checksum_func_auth(void - -); -uint16_t uniffi_pubkymobile_checksum_func_create_recovery_file(void - -); -uint16_t uniffi_pubkymobile_checksum_func_decrypt_recovery_file(void - -); -uint16_t uniffi_pubkymobile_checksum_func_delete_file(void - -); -uint16_t uniffi_pubkymobile_checksum_func_generate_secret_key(void - -); -uint16_t uniffi_pubkymobile_checksum_func_get(void - -); -uint16_t uniffi_pubkymobile_checksum_func_get_public_key_from_secret_key(void - -); -uint16_t uniffi_pubkymobile_checksum_func_list(void - -); -uint16_t uniffi_pubkymobile_checksum_func_parse_auth_url(void - -); -uint16_t uniffi_pubkymobile_checksum_func_publish(void - -); -uint16_t uniffi_pubkymobile_checksum_func_publish_https(void - -); -uint16_t uniffi_pubkymobile_checksum_func_put(void - -); -uint16_t uniffi_pubkymobile_checksum_func_remove_event_listener(void - -); -uint16_t uniffi_pubkymobile_checksum_func_resolve(void - -); -uint16_t uniffi_pubkymobile_checksum_func_resolve_https(void - -); -uint16_t uniffi_pubkymobile_checksum_func_session(void - -); -uint16_t uniffi_pubkymobile_checksum_func_set_event_listener(void - -); -uint16_t uniffi_pubkymobile_checksum_func_sign_in(void - -); -uint16_t uniffi_pubkymobile_checksum_func_sign_out(void - -); -uint16_t uniffi_pubkymobile_checksum_func_sign_up(void - -); -uint16_t uniffi_pubkymobile_checksum_func_switch_network(void - -); -uint16_t uniffi_pubkymobile_checksum_method_eventlistener_on_event_occurred(void - -); -uint32_t ffi_pubkymobile_uniffi_contract_version(void - -); - diff --git a/bindings/ios/PubkyMobile.xcframework/ios-arm64-simulator/libpubkymobile.a b/bindings/ios/PubkyMobile.xcframework/ios-arm64-simulator/libpubkymobile.a deleted file mode 100644 index d26a9b7..0000000 Binary files a/bindings/ios/PubkyMobile.xcframework/ios-arm64-simulator/libpubkymobile.a and /dev/null differ diff --git a/bindings/ios/PubkyMobile.xcframework/ios-arm64/Headers/module.modulemap b/bindings/ios/PubkyMobile.xcframework/ios-arm64/Headers/module.modulemap deleted file mode 100644 index 09b533a..0000000 --- a/bindings/ios/PubkyMobile.xcframework/ios-arm64/Headers/module.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -// This file was autogenerated by some hot garbage in the `uniffi` crate. -// Trust me, you don't want to mess with it! -module pubkymobileFFI { - header "pubkymobileFFI.h" - export * -} \ No newline at end of file diff --git a/bindings/ios/PubkyMobile.xcframework/ios-arm64/Headers/pubkymobileFFI.h b/bindings/ios/PubkyMobile.xcframework/ios-arm64/Headers/pubkymobileFFI.h deleted file mode 100644 index 3694adc..0000000 --- a/bindings/ios/PubkyMobile.xcframework/ios-arm64/Headers/pubkymobileFFI.h +++ /dev/null @@ -1,297 +0,0 @@ -// This file was autogenerated by some hot garbage in the `uniffi` crate. -// Trust me, you don't want to mess with it! - -#pragma once - -#include -#include -#include - -// The following structs are used to implement the lowest level -// of the FFI, and thus useful to multiple uniffied crates. -// We ensure they are declared exactly once, with a header guard, UNIFFI_SHARED_H. -#ifdef UNIFFI_SHARED_H - // We also try to prevent mixing versions of shared uniffi header structs. - // If you add anything to the #else block, you must increment the version suffix in UNIFFI_SHARED_HEADER_V4 - #ifndef UNIFFI_SHARED_HEADER_V4 - #error Combining helper code from multiple versions of uniffi is not supported - #endif // ndef UNIFFI_SHARED_HEADER_V4 -#else -#define UNIFFI_SHARED_H -#define UNIFFI_SHARED_HEADER_V4 -// ⚠️ Attention: If you change this #else block (ending in `#endif // def UNIFFI_SHARED_H`) you *must* ⚠️ -// ⚠️ increment the version suffix in all instances of UNIFFI_SHARED_HEADER_V4 in this file. ⚠️ - -typedef struct RustBuffer -{ - int32_t capacity; - int32_t len; - uint8_t *_Nullable data; -} RustBuffer; - -typedef int32_t (*ForeignCallback)(uint64_t, int32_t, const uint8_t *_Nonnull, int32_t, RustBuffer *_Nonnull); - -// Task defined in Rust that Swift executes -typedef void (*UniFfiRustTaskCallback)(const void * _Nullable, int8_t); - -// Callback to execute Rust tasks using a Swift Task -// -// Args: -// executor: ForeignExecutor lowered into a size_t value -// delay: Delay in MS -// task: UniFfiRustTaskCallback to call -// task_data: data to pass the task callback -typedef int8_t (*UniFfiForeignExecutorCallback)(size_t, uint32_t, UniFfiRustTaskCallback _Nullable, const void * _Nullable); - -typedef struct ForeignBytes -{ - int32_t len; - const uint8_t *_Nullable data; -} ForeignBytes; - -// Error definitions -typedef struct RustCallStatus { - int8_t code; - RustBuffer errorBuf; -} RustCallStatus; - -// ⚠️ Attention: If you change this #else block (ending in `#endif // def UNIFFI_SHARED_H`) you *must* ⚠️ -// ⚠️ increment the version suffix in all instances of UNIFFI_SHARED_HEADER_V4 in this file. ⚠️ -#endif // def UNIFFI_SHARED_H - -// Continuation callback for UniFFI Futures -typedef void (*UniFfiRustFutureContinuation)(void * _Nonnull, int8_t); - -// Scaffolding functions -void uniffi_pubkymobile_fn_free_eventnotifier(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status -); -void uniffi_pubkymobile_fn_init_callback_eventlistener(ForeignCallback _Nonnull callback_stub, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_auth(RustBuffer url, RustBuffer secret_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_create_recovery_file(RustBuffer secret_key, RustBuffer passphrase, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_decrypt_recovery_file(RustBuffer recovery_file, RustBuffer passphrase, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_delete_file(RustBuffer url, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_generate_secret_key(RustCallStatus *_Nonnull out_status - -); -RustBuffer uniffi_pubkymobile_fn_func_get(RustBuffer url, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_get_public_key_from_secret_key(RustBuffer secret_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_list(RustBuffer url, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_parse_auth_url(RustBuffer url, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_publish(RustBuffer record_name, RustBuffer record_content, RustBuffer secret_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_publish_https(RustBuffer record_name, RustBuffer target, RustBuffer secret_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_put(RustBuffer url, RustBuffer content, RustCallStatus *_Nonnull out_status -); -void uniffi_pubkymobile_fn_func_remove_event_listener(RustCallStatus *_Nonnull out_status - -); -RustBuffer uniffi_pubkymobile_fn_func_resolve(RustBuffer public_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_resolve_https(RustBuffer public_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_session(RustBuffer pubky, RustCallStatus *_Nonnull out_status -); -void uniffi_pubkymobile_fn_func_set_event_listener(uint64_t listener, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_sign_in(RustBuffer secret_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_sign_out(RustBuffer secret_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_sign_up(RustBuffer secret_key, RustBuffer homeserver, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_switch_network(int8_t use_testnet, RustCallStatus *_Nonnull out_status -); -RustBuffer ffi_pubkymobile_rustbuffer_alloc(int32_t size, RustCallStatus *_Nonnull out_status -); -RustBuffer ffi_pubkymobile_rustbuffer_from_bytes(ForeignBytes bytes, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rustbuffer_free(RustBuffer buf, RustCallStatus *_Nonnull out_status -); -RustBuffer ffi_pubkymobile_rustbuffer_reserve(RustBuffer buf, int32_t additional, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_continuation_callback_set(UniFfiRustFutureContinuation _Nonnull callback -); -void ffi_pubkymobile_rust_future_poll_u8(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_u8(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_u8(void* _Nonnull handle -); -uint8_t ffi_pubkymobile_rust_future_complete_u8(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_i8(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_i8(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_i8(void* _Nonnull handle -); -int8_t ffi_pubkymobile_rust_future_complete_i8(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_u16(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_u16(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_u16(void* _Nonnull handle -); -uint16_t ffi_pubkymobile_rust_future_complete_u16(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_i16(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_i16(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_i16(void* _Nonnull handle -); -int16_t ffi_pubkymobile_rust_future_complete_i16(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_u32(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_u32(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_u32(void* _Nonnull handle -); -uint32_t ffi_pubkymobile_rust_future_complete_u32(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_i32(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_i32(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_i32(void* _Nonnull handle -); -int32_t ffi_pubkymobile_rust_future_complete_i32(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_u64(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_u64(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_u64(void* _Nonnull handle -); -uint64_t ffi_pubkymobile_rust_future_complete_u64(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_i64(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_i64(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_i64(void* _Nonnull handle -); -int64_t ffi_pubkymobile_rust_future_complete_i64(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_f32(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_f32(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_f32(void* _Nonnull handle -); -float ffi_pubkymobile_rust_future_complete_f32(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_f64(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_f64(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_f64(void* _Nonnull handle -); -double ffi_pubkymobile_rust_future_complete_f64(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_pointer(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_pointer(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_pointer(void* _Nonnull handle -); -void*_Nonnull ffi_pubkymobile_rust_future_complete_pointer(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_rust_buffer(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_rust_buffer(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_rust_buffer(void* _Nonnull handle -); -RustBuffer ffi_pubkymobile_rust_future_complete_rust_buffer(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_void(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_void(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_void(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_complete_void(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -uint16_t uniffi_pubkymobile_checksum_func_auth(void - -); -uint16_t uniffi_pubkymobile_checksum_func_create_recovery_file(void - -); -uint16_t uniffi_pubkymobile_checksum_func_decrypt_recovery_file(void - -); -uint16_t uniffi_pubkymobile_checksum_func_delete_file(void - -); -uint16_t uniffi_pubkymobile_checksum_func_generate_secret_key(void - -); -uint16_t uniffi_pubkymobile_checksum_func_get(void - -); -uint16_t uniffi_pubkymobile_checksum_func_get_public_key_from_secret_key(void - -); -uint16_t uniffi_pubkymobile_checksum_func_list(void - -); -uint16_t uniffi_pubkymobile_checksum_func_parse_auth_url(void - -); -uint16_t uniffi_pubkymobile_checksum_func_publish(void - -); -uint16_t uniffi_pubkymobile_checksum_func_publish_https(void - -); -uint16_t uniffi_pubkymobile_checksum_func_put(void - -); -uint16_t uniffi_pubkymobile_checksum_func_remove_event_listener(void - -); -uint16_t uniffi_pubkymobile_checksum_func_resolve(void - -); -uint16_t uniffi_pubkymobile_checksum_func_resolve_https(void - -); -uint16_t uniffi_pubkymobile_checksum_func_session(void - -); -uint16_t uniffi_pubkymobile_checksum_func_set_event_listener(void - -); -uint16_t uniffi_pubkymobile_checksum_func_sign_in(void - -); -uint16_t uniffi_pubkymobile_checksum_func_sign_out(void - -); -uint16_t uniffi_pubkymobile_checksum_func_sign_up(void - -); -uint16_t uniffi_pubkymobile_checksum_func_switch_network(void - -); -uint16_t uniffi_pubkymobile_checksum_method_eventlistener_on_event_occurred(void - -); -uint32_t ffi_pubkymobile_uniffi_contract_version(void - -); - diff --git a/bindings/ios/PubkyMobile.xcframework/ios-arm64/libpubkymobile.a b/bindings/ios/PubkyMobile.xcframework/ios-arm64/libpubkymobile.a deleted file mode 100644 index 89d6d34..0000000 Binary files a/bindings/ios/PubkyMobile.xcframework/ios-arm64/libpubkymobile.a and /dev/null differ diff --git a/bindings/ios/module.modulemap b/bindings/ios/module.modulemap index 09b533a..4d51af4 100644 --- a/bindings/ios/module.modulemap +++ b/bindings/ios/module.modulemap @@ -1,6 +1,6 @@ // This file was autogenerated by some hot garbage in the `uniffi` crate. // Trust me, you don't want to mess with it! -module pubkymobileFFI { - header "pubkymobileFFI.h" +module pubkycoreFFI { + header "pubkycoreFFI.h" export * } \ No newline at end of file diff --git a/bindings/ios/pubkymobile.swift b/bindings/ios/pubkymobile.swift deleted file mode 100644 index 98d384e..0000000 --- a/bindings/ios/pubkymobile.swift +++ /dev/null @@ -1,905 +0,0 @@ -// This file was autogenerated by some hot garbage in the `uniffi` crate. -// Trust me, you don't want to mess with it! -import Foundation - -// Depending on the consumer's build setup, the low-level FFI code -// might be in a separate module, or it might be compiled inline into -// this module. This is a bit of light hackery to work with both. -#if canImport(pubkymobileFFI) -import pubkymobileFFI -#endif - -fileprivate extension RustBuffer { - // Allocate a new buffer, copying the contents of a `UInt8` array. - init(bytes: [UInt8]) { - let rbuf = bytes.withUnsafeBufferPointer { ptr in - RustBuffer.from(ptr) - } - self.init(capacity: rbuf.capacity, len: rbuf.len, data: rbuf.data) - } - - static func from(_ ptr: UnsafeBufferPointer) -> RustBuffer { - try! rustCall { ffi_pubkymobile_rustbuffer_from_bytes(ForeignBytes(bufferPointer: ptr), $0) } - } - - // Frees the buffer in place. - // The buffer must not be used after this is called. - func deallocate() { - try! rustCall { ffi_pubkymobile_rustbuffer_free(self, $0) } - } -} - -fileprivate extension ForeignBytes { - init(bufferPointer: UnsafeBufferPointer) { - self.init(len: Int32(bufferPointer.count), data: bufferPointer.baseAddress) - } -} - -// For every type used in the interface, we provide helper methods for conveniently -// lifting and lowering that type from C-compatible data, and for reading and writing -// values of that type in a buffer. - -// Helper classes/extensions that don't change. -// Someday, this will be in a library of its own. - -fileprivate extension Data { - init(rustBuffer: RustBuffer) { - // TODO: This copies the buffer. Can we read directly from a - // Rust buffer? - self.init(bytes: rustBuffer.data!, count: Int(rustBuffer.len)) - } -} - -// Define reader functionality. Normally this would be defined in a class or -// struct, but we use standalone functions instead in order to make external -// types work. -// -// With external types, one swift source file needs to be able to call the read -// method on another source file's FfiConverter, but then what visibility -// should Reader have? -// - If Reader is fileprivate, then this means the read() must also -// be fileprivate, which doesn't work with external types. -// - If Reader is internal/public, we'll get compile errors since both source -// files will try define the same type. -// -// Instead, the read() method and these helper functions input a tuple of data - -fileprivate func createReader(data: Data) -> (data: Data, offset: Data.Index) { - (data: data, offset: 0) -} - -// Reads an integer at the current offset, in big-endian order, and advances -// the offset on success. Throws if reading the integer would move the -// offset past the end of the buffer. -fileprivate func readInt(_ reader: inout (data: Data, offset: Data.Index)) throws -> T { - let range = reader.offset...size - guard reader.data.count >= range.upperBound else { - throw UniffiInternalError.bufferOverflow - } - if T.self == UInt8.self { - let value = reader.data[reader.offset] - reader.offset += 1 - return value as! T - } - var value: T = 0 - let _ = withUnsafeMutableBytes(of: &value, { reader.data.copyBytes(to: $0, from: range)}) - reader.offset = range.upperBound - return value.bigEndian -} - -// Reads an arbitrary number of bytes, to be used to read -// raw bytes, this is useful when lifting strings -fileprivate func readBytes(_ reader: inout (data: Data, offset: Data.Index), count: Int) throws -> Array { - let range = reader.offset..<(reader.offset+count) - guard reader.data.count >= range.upperBound else { - throw UniffiInternalError.bufferOverflow - } - var value = [UInt8](repeating: 0, count: count) - value.withUnsafeMutableBufferPointer({ buffer in - reader.data.copyBytes(to: buffer, from: range) - }) - reader.offset = range.upperBound - return value -} - -// Reads a float at the current offset. -fileprivate func readFloat(_ reader: inout (data: Data, offset: Data.Index)) throws -> Float { - return Float(bitPattern: try readInt(&reader)) -} - -// Reads a float at the current offset. -fileprivate func readDouble(_ reader: inout (data: Data, offset: Data.Index)) throws -> Double { - return Double(bitPattern: try readInt(&reader)) -} - -// Indicates if the offset has reached the end of the buffer. -fileprivate func hasRemaining(_ reader: (data: Data, offset: Data.Index)) -> Bool { - return reader.offset < reader.data.count -} - -// Define writer functionality. Normally this would be defined in a class or -// struct, but we use standalone functions instead in order to make external -// types work. See the above discussion on Readers for details. - -fileprivate func createWriter() -> [UInt8] { - return [] -} - -fileprivate func writeBytes(_ writer: inout [UInt8], _ byteArr: S) where S: Sequence, S.Element == UInt8 { - writer.append(contentsOf: byteArr) -} - -// Writes an integer in big-endian order. -// -// Warning: make sure what you are trying to write -// is in the correct type! -fileprivate func writeInt(_ writer: inout [UInt8], _ value: T) { - var value = value.bigEndian - withUnsafeBytes(of: &value) { writer.append(contentsOf: $0) } -} - -fileprivate func writeFloat(_ writer: inout [UInt8], _ value: Float) { - writeInt(&writer, value.bitPattern) -} - -fileprivate func writeDouble(_ writer: inout [UInt8], _ value: Double) { - writeInt(&writer, value.bitPattern) -} - -// Protocol for types that transfer other types across the FFI. This is -// analogous go the Rust trait of the same name. -fileprivate protocol FfiConverter { - associatedtype FfiType - associatedtype SwiftType - - static func lift(_ value: FfiType) throws -> SwiftType - static func lower(_ value: SwiftType) -> FfiType - static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType - static func write(_ value: SwiftType, into buf: inout [UInt8]) -} - -// Types conforming to `Primitive` pass themselves directly over the FFI. -fileprivate protocol FfiConverterPrimitive: FfiConverter where FfiType == SwiftType { } - -extension FfiConverterPrimitive { - public static func lift(_ value: FfiType) throws -> SwiftType { - return value - } - - public static func lower(_ value: SwiftType) -> FfiType { - return value - } -} - -// Types conforming to `FfiConverterRustBuffer` lift and lower into a `RustBuffer`. -// Used for complex types where it's hard to write a custom lift/lower. -fileprivate protocol FfiConverterRustBuffer: FfiConverter where FfiType == RustBuffer {} - -extension FfiConverterRustBuffer { - public static func lift(_ buf: RustBuffer) throws -> SwiftType { - var reader = createReader(data: Data(rustBuffer: buf)) - let value = try read(from: &reader) - if hasRemaining(reader) { - throw UniffiInternalError.incompleteData - } - buf.deallocate() - return value - } - - public static func lower(_ value: SwiftType) -> RustBuffer { - var writer = createWriter() - write(value, into: &writer) - return RustBuffer(bytes: writer) - } -} -// An error type for FFI errors. These errors occur at the UniFFI level, not -// the library level. -fileprivate enum UniffiInternalError: LocalizedError { - case bufferOverflow - case incompleteData - case unexpectedOptionalTag - case unexpectedEnumCase - case unexpectedNullPointer - case unexpectedRustCallStatusCode - case unexpectedRustCallError - case unexpectedStaleHandle - case rustPanic(_ message: String) - - public var errorDescription: String? { - switch self { - case .bufferOverflow: return "Reading the requested value would read past the end of the buffer" - case .incompleteData: return "The buffer still has data after lifting its containing value" - case .unexpectedOptionalTag: return "Unexpected optional tag; should be 0 or 1" - case .unexpectedEnumCase: return "Raw enum value doesn't match any cases" - case .unexpectedNullPointer: return "Raw pointer value was null" - case .unexpectedRustCallStatusCode: return "Unexpected RustCallStatus code" - case .unexpectedRustCallError: return "CALL_ERROR but no errorClass specified" - case .unexpectedStaleHandle: return "The object in the handle map has been dropped already" - case let .rustPanic(message): return message - } - } -} - -fileprivate let CALL_SUCCESS: Int8 = 0 -fileprivate let CALL_ERROR: Int8 = 1 -fileprivate let CALL_PANIC: Int8 = 2 -fileprivate let CALL_CANCELLED: Int8 = 3 - -fileprivate extension RustCallStatus { - init() { - self.init( - code: CALL_SUCCESS, - errorBuf: RustBuffer.init( - capacity: 0, - len: 0, - data: nil - ) - ) - } -} - -private func rustCall(_ callback: (UnsafeMutablePointer) -> T) throws -> T { - try makeRustCall(callback, errorHandler: nil) -} - -private func rustCallWithError( - _ errorHandler: @escaping (RustBuffer) throws -> Error, - _ callback: (UnsafeMutablePointer) -> T) throws -> T { - try makeRustCall(callback, errorHandler: errorHandler) -} - -private func makeRustCall( - _ callback: (UnsafeMutablePointer) -> T, - errorHandler: ((RustBuffer) throws -> Error)? -) throws -> T { - uniffiEnsureInitialized() - var callStatus = RustCallStatus.init() - let returnedVal = callback(&callStatus) - try uniffiCheckCallStatus(callStatus: callStatus, errorHandler: errorHandler) - return returnedVal -} - -private func uniffiCheckCallStatus( - callStatus: RustCallStatus, - errorHandler: ((RustBuffer) throws -> Error)? -) throws { - switch callStatus.code { - case CALL_SUCCESS: - return - - case CALL_ERROR: - if let errorHandler = errorHandler { - throw try errorHandler(callStatus.errorBuf) - } else { - callStatus.errorBuf.deallocate() - throw UniffiInternalError.unexpectedRustCallError - } - - case CALL_PANIC: - // When the rust code sees a panic, it tries to construct a RustBuffer - // with the message. But if that code panics, then it just sends back - // an empty buffer. - if callStatus.errorBuf.len > 0 { - throw UniffiInternalError.rustPanic(try FfiConverterString.lift(callStatus.errorBuf)) - } else { - callStatus.errorBuf.deallocate() - throw UniffiInternalError.rustPanic("Rust panic") - } - - case CALL_CANCELLED: - throw CancellationError() - - default: - throw UniffiInternalError.unexpectedRustCallStatusCode - } -} - -// Public interface members begin here. - - -fileprivate struct FfiConverterBool : FfiConverter { - typealias FfiType = Int8 - typealias SwiftType = Bool - - public static func lift(_ value: Int8) throws -> Bool { - return value != 0 - } - - public static func lower(_ value: Bool) -> Int8 { - return value ? 1 : 0 - } - - public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Bool { - return try lift(readInt(&buf)) - } - - public static func write(_ value: Bool, into buf: inout [UInt8]) { - writeInt(&buf, lower(value)) - } -} - -fileprivate struct FfiConverterString: FfiConverter { - typealias SwiftType = String - typealias FfiType = RustBuffer - - public static func lift(_ value: RustBuffer) throws -> String { - defer { - value.deallocate() - } - if value.data == nil { - return String() - } - let bytes = UnsafeBufferPointer(start: value.data!, count: Int(value.len)) - return String(bytes: bytes, encoding: String.Encoding.utf8)! - } - - public static func lower(_ value: String) -> RustBuffer { - return value.utf8CString.withUnsafeBufferPointer { ptr in - // The swift string gives us int8_t, we want uint8_t. - ptr.withMemoryRebound(to: UInt8.self) { ptr in - // The swift string gives us a trailing null byte, we don't want it. - let buf = UnsafeBufferPointer(rebasing: ptr.prefix(upTo: ptr.count - 1)) - return RustBuffer.from(buf) - } - } - } - - public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> String { - let len: Int32 = try readInt(&buf) - return String(bytes: try readBytes(&buf, count: Int(len)), encoding: String.Encoding.utf8)! - } - - public static func write(_ value: String, into buf: inout [UInt8]) { - let len = Int32(value.utf8.count) - writeInt(&buf, len) - writeBytes(&buf, value.utf8) - } -} - - -public protocol EventNotifierProtocol { - -} - -public class EventNotifier: EventNotifierProtocol { - fileprivate let pointer: UnsafeMutableRawPointer - - // TODO: We'd like this to be `private` but for Swifty reasons, - // we can't implement `FfiConverter` without making this `required` and we can't - // make it `required` without making it `public`. - required init(unsafeFromRawPointer pointer: UnsafeMutableRawPointer) { - self.pointer = pointer - } - - deinit { - try! rustCall { uniffi_pubkymobile_fn_free_eventnotifier(pointer, $0) } - } - - - - - -} - -public struct FfiConverterTypeEventNotifier: FfiConverter { - typealias FfiType = UnsafeMutableRawPointer - typealias SwiftType = EventNotifier - - public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> EventNotifier { - let v: UInt64 = try readInt(&buf) - // The Rust code won't compile if a pointer won't fit in a UInt64. - // We have to go via `UInt` because that's the thing that's the size of a pointer. - let ptr = UnsafeMutableRawPointer(bitPattern: UInt(truncatingIfNeeded: v)) - if (ptr == nil) { - throw UniffiInternalError.unexpectedNullPointer - } - return try lift(ptr!) - } - - public static func write(_ value: EventNotifier, into buf: inout [UInt8]) { - // This fiddling is because `Int` is the thing that's the same size as a pointer. - // The Rust code won't compile if a pointer won't fit in a `UInt64`. - writeInt(&buf, UInt64(bitPattern: Int64(Int(bitPattern: lower(value))))) - } - - public static func lift(_ pointer: UnsafeMutableRawPointer) throws -> EventNotifier { - return EventNotifier(unsafeFromRawPointer: pointer) - } - - public static func lower(_ value: EventNotifier) -> UnsafeMutableRawPointer { - return value.pointer - } -} - - -public func FfiConverterTypeEventNotifier_lift(_ pointer: UnsafeMutableRawPointer) throws -> EventNotifier { - return try FfiConverterTypeEventNotifier.lift(pointer) -} - -public func FfiConverterTypeEventNotifier_lower(_ value: EventNotifier) -> UnsafeMutableRawPointer { - return FfiConverterTypeEventNotifier.lower(value) -} - -fileprivate extension NSLock { - func withLock(f: () throws -> T) rethrows -> T { - self.lock() - defer { self.unlock() } - return try f() - } -} - -fileprivate typealias UniFFICallbackHandle = UInt64 -fileprivate class UniFFICallbackHandleMap { - private var leftMap: [UniFFICallbackHandle: T] = [:] - private var counter: [UniFFICallbackHandle: UInt64] = [:] - private var rightMap: [ObjectIdentifier: UniFFICallbackHandle] = [:] - - private let lock = NSLock() - private var currentHandle: UniFFICallbackHandle = 0 - private let stride: UniFFICallbackHandle = 1 - - func insert(obj: T) -> UniFFICallbackHandle { - lock.withLock { - let id = ObjectIdentifier(obj as AnyObject) - let handle = rightMap[id] ?? { - currentHandle += stride - let handle = currentHandle - leftMap[handle] = obj - rightMap[id] = handle - return handle - }() - counter[handle] = (counter[handle] ?? 0) + 1 - return handle - } - } - - func get(handle: UniFFICallbackHandle) -> T? { - lock.withLock { - leftMap[handle] - } - } - - func delete(handle: UniFFICallbackHandle) { - remove(handle: handle) - } - - @discardableResult - func remove(handle: UniFFICallbackHandle) -> T? { - lock.withLock { - defer { counter[handle] = (counter[handle] ?? 1) - 1 } - guard counter[handle] == 1 else { return leftMap[handle] } - let obj = leftMap.removeValue(forKey: handle) - if let obj = obj { - rightMap.removeValue(forKey: ObjectIdentifier(obj as AnyObject)) - } - return obj - } - } -} - -// Magic number for the Rust proxy to call using the same mechanism as every other method, -// to free the callback once it's dropped by Rust. -private let IDX_CALLBACK_FREE: Int32 = 0 -// Callback return codes -private let UNIFFI_CALLBACK_SUCCESS: Int32 = 0 -private let UNIFFI_CALLBACK_ERROR: Int32 = 1 -private let UNIFFI_CALLBACK_UNEXPECTED_ERROR: Int32 = 2 - -// Declaration and FfiConverters for EventListener Callback Interface - -public protocol EventListener : AnyObject { - func onEventOccurred(eventData: String) - -} - -// The ForeignCallback that is passed to Rust. -fileprivate let foreignCallbackCallbackInterfaceEventListener : ForeignCallback = - { (handle: UniFFICallbackHandle, method: Int32, argsData: UnsafePointer, argsLen: Int32, out_buf: UnsafeMutablePointer) -> Int32 in - - - func invokeOnEventOccurred(_ swiftCallbackInterface: EventListener, _ argsData: UnsafePointer, _ argsLen: Int32, _ out_buf: UnsafeMutablePointer) throws -> Int32 { - var reader = createReader(data: Data(bytes: argsData, count: Int(argsLen))) - func makeCall() throws -> Int32 { - try swiftCallbackInterface.onEventOccurred( - eventData: try FfiConverterString.read(from: &reader) - ) - return UNIFFI_CALLBACK_SUCCESS - } - return try makeCall() - } - - - switch method { - case IDX_CALLBACK_FREE: - FfiConverterCallbackInterfaceEventListener.drop(handle: handle) - // Sucessful return - // See docs of ForeignCallback in `uniffi_core/src/ffi/foreigncallbacks.rs` - return UNIFFI_CALLBACK_SUCCESS - case 1: - let cb: EventListener - do { - cb = try FfiConverterCallbackInterfaceEventListener.lift(handle) - } catch { - out_buf.pointee = FfiConverterString.lower("EventListener: Invalid handle") - return UNIFFI_CALLBACK_UNEXPECTED_ERROR - } - do { - return try invokeOnEventOccurred(cb, argsData, argsLen, out_buf) - } catch let error { - out_buf.pointee = FfiConverterString.lower(String(describing: error)) - return UNIFFI_CALLBACK_UNEXPECTED_ERROR - } - - // This should never happen, because an out of bounds method index won't - // ever be used. Once we can catch errors, we should return an InternalError. - // https://github.com/mozilla/uniffi-rs/issues/351 - default: - // An unexpected error happened. - // See docs of ForeignCallback in `uniffi_core/src/ffi/foreigncallbacks.rs` - return UNIFFI_CALLBACK_UNEXPECTED_ERROR - } -} - -// FfiConverter protocol for callback interfaces -fileprivate struct FfiConverterCallbackInterfaceEventListener { - private static let initCallbackOnce: () = { - // Swift ensures this initializer code will once run once, even when accessed by multiple threads. - try! rustCall { (err: UnsafeMutablePointer) in - uniffi_pubkymobile_fn_init_callback_eventlistener(foreignCallbackCallbackInterfaceEventListener, err) - } - }() - - private static func ensureCallbackinitialized() { - _ = initCallbackOnce - } - - static func drop(handle: UniFFICallbackHandle) { - handleMap.remove(handle: handle) - } - - private static var handleMap = UniFFICallbackHandleMap() -} - -extension FfiConverterCallbackInterfaceEventListener : FfiConverter { - typealias SwiftType = EventListener - // We can use Handle as the FfiType because it's a typealias to UInt64 - typealias FfiType = UniFFICallbackHandle - - public static func lift(_ handle: UniFFICallbackHandle) throws -> SwiftType { - ensureCallbackinitialized(); - guard let callback = handleMap.get(handle: handle) else { - throw UniffiInternalError.unexpectedStaleHandle - } - return callback - } - - public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType { - ensureCallbackinitialized(); - let handle: UniFFICallbackHandle = try readInt(&buf) - return try lift(handle) - } - - public static func lower(_ v: SwiftType) -> UniFFICallbackHandle { - ensureCallbackinitialized(); - return handleMap.insert(obj: v) - } - - public static func write(_ v: SwiftType, into buf: inout [UInt8]) { - ensureCallbackinitialized(); - writeInt(&buf, lower(v)) - } -} - -fileprivate struct FfiConverterSequenceString: FfiConverterRustBuffer { - typealias SwiftType = [String] - - public static func write(_ value: [String], into buf: inout [UInt8]) { - let len = Int32(value.count) - writeInt(&buf, len) - for item in value { - FfiConverterString.write(item, into: &buf) - } - } - - public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [String] { - let len: Int32 = try readInt(&buf) - var seq = [String]() - seq.reserveCapacity(Int(len)) - for _ in 0 ..< len { - seq.append(try FfiConverterString.read(from: &buf)) - } - return seq - } -} - -public func auth(url: String, secretKey: String) -> [String] { - return try! FfiConverterSequenceString.lift( - try! rustCall() { - uniffi_pubkymobile_fn_func_auth( - FfiConverterString.lower(url), - FfiConverterString.lower(secretKey),$0) -} - ) -} - -public func createRecoveryFile(secretKey: String, passphrase: String) -> [String] { - return try! FfiConverterSequenceString.lift( - try! rustCall() { - uniffi_pubkymobile_fn_func_create_recovery_file( - FfiConverterString.lower(secretKey), - FfiConverterString.lower(passphrase),$0) -} - ) -} - -public func decryptRecoveryFile(recoveryFile: String, passphrase: String) -> [String] { - return try! FfiConverterSequenceString.lift( - try! rustCall() { - uniffi_pubkymobile_fn_func_decrypt_recovery_file( - FfiConverterString.lower(recoveryFile), - FfiConverterString.lower(passphrase),$0) -} - ) -} - -public func deleteFile(url: String) -> [String] { - return try! FfiConverterSequenceString.lift( - try! rustCall() { - uniffi_pubkymobile_fn_func_delete_file( - FfiConverterString.lower(url),$0) -} - ) -} - -public func generateSecretKey() -> [String] { - return try! FfiConverterSequenceString.lift( - try! rustCall() { - uniffi_pubkymobile_fn_func_generate_secret_key($0) -} - ) -} - -public func get(url: String) -> [String] { - return try! FfiConverterSequenceString.lift( - try! rustCall() { - uniffi_pubkymobile_fn_func_get( - FfiConverterString.lower(url),$0) -} - ) -} - -public func getPublicKeyFromSecretKey(secretKey: String) -> [String] { - return try! FfiConverterSequenceString.lift( - try! rustCall() { - uniffi_pubkymobile_fn_func_get_public_key_from_secret_key( - FfiConverterString.lower(secretKey),$0) -} - ) -} - -public func list(url: String) -> [String] { - return try! FfiConverterSequenceString.lift( - try! rustCall() { - uniffi_pubkymobile_fn_func_list( - FfiConverterString.lower(url),$0) -} - ) -} - -public func parseAuthUrl(url: String) -> [String] { - return try! FfiConverterSequenceString.lift( - try! rustCall() { - uniffi_pubkymobile_fn_func_parse_auth_url( - FfiConverterString.lower(url),$0) -} - ) -} - -public func publish(recordName: String, recordContent: String, secretKey: String) -> [String] { - return try! FfiConverterSequenceString.lift( - try! rustCall() { - uniffi_pubkymobile_fn_func_publish( - FfiConverterString.lower(recordName), - FfiConverterString.lower(recordContent), - FfiConverterString.lower(secretKey),$0) -} - ) -} - -public func publishHttps(recordName: String, target: String, secretKey: String) -> [String] { - return try! FfiConverterSequenceString.lift( - try! rustCall() { - uniffi_pubkymobile_fn_func_publish_https( - FfiConverterString.lower(recordName), - FfiConverterString.lower(target), - FfiConverterString.lower(secretKey),$0) -} - ) -} - -public func put(url: String, content: String) -> [String] { - return try! FfiConverterSequenceString.lift( - try! rustCall() { - uniffi_pubkymobile_fn_func_put( - FfiConverterString.lower(url), - FfiConverterString.lower(content),$0) -} - ) -} - -public func removeEventListener() { - try! rustCall() { - uniffi_pubkymobile_fn_func_remove_event_listener($0) -} -} - - - -public func resolve(publicKey: String) -> [String] { - return try! FfiConverterSequenceString.lift( - try! rustCall() { - uniffi_pubkymobile_fn_func_resolve( - FfiConverterString.lower(publicKey),$0) -} - ) -} - -public func resolveHttps(publicKey: String) -> [String] { - return try! FfiConverterSequenceString.lift( - try! rustCall() { - uniffi_pubkymobile_fn_func_resolve_https( - FfiConverterString.lower(publicKey),$0) -} - ) -} - -public func session(pubky: String) -> [String] { - return try! FfiConverterSequenceString.lift( - try! rustCall() { - uniffi_pubkymobile_fn_func_session( - FfiConverterString.lower(pubky),$0) -} - ) -} - -public func setEventListener(listener: EventListener) { - try! rustCall() { - uniffi_pubkymobile_fn_func_set_event_listener( - FfiConverterCallbackInterfaceEventListener.lower(listener),$0) -} -} - - - -public func signIn(secretKey: String) -> [String] { - return try! FfiConverterSequenceString.lift( - try! rustCall() { - uniffi_pubkymobile_fn_func_sign_in( - FfiConverterString.lower(secretKey),$0) -} - ) -} - -public func signOut(secretKey: String) -> [String] { - return try! FfiConverterSequenceString.lift( - try! rustCall() { - uniffi_pubkymobile_fn_func_sign_out( - FfiConverterString.lower(secretKey),$0) -} - ) -} - -public func signUp(secretKey: String, homeserver: String) -> [String] { - return try! FfiConverterSequenceString.lift( - try! rustCall() { - uniffi_pubkymobile_fn_func_sign_up( - FfiConverterString.lower(secretKey), - FfiConverterString.lower(homeserver),$0) -} - ) -} - -public func switchNetwork(useTestnet: Bool) -> [String] { - return try! FfiConverterSequenceString.lift( - try! rustCall() { - uniffi_pubkymobile_fn_func_switch_network( - FfiConverterBool.lower(useTestnet),$0) -} - ) -} - -private enum InitializationResult { - case ok - case contractVersionMismatch - case apiChecksumMismatch -} -// Use a global variables to perform the versioning checks. Swift ensures that -// the code inside is only computed once. -private var initializationResult: InitializationResult { - // Get the bindings contract version from our ComponentInterface - let bindings_contract_version = 24 - // Get the scaffolding contract version by calling the into the dylib - let scaffolding_contract_version = ffi_pubkymobile_uniffi_contract_version() - if bindings_contract_version != scaffolding_contract_version { - return InitializationResult.contractVersionMismatch - } - if (uniffi_pubkymobile_checksum_func_auth() != 61378) { - return InitializationResult.apiChecksumMismatch - } - if (uniffi_pubkymobile_checksum_func_create_recovery_file() != 55903) { - return InitializationResult.apiChecksumMismatch - } - if (uniffi_pubkymobile_checksum_func_decrypt_recovery_file() != 59688) { - return InitializationResult.apiChecksumMismatch - } - if (uniffi_pubkymobile_checksum_func_delete_file() != 57905) { - return InitializationResult.apiChecksumMismatch - } - if (uniffi_pubkymobile_checksum_func_generate_secret_key() != 63116) { - return InitializationResult.apiChecksumMismatch - } - if (uniffi_pubkymobile_checksum_func_get() != 21596) { - return InitializationResult.apiChecksumMismatch - } - if (uniffi_pubkymobile_checksum_func_get_public_key_from_secret_key() != 23603) { - return InitializationResult.apiChecksumMismatch - } - if (uniffi_pubkymobile_checksum_func_list() != 8522) { - return InitializationResult.apiChecksumMismatch - } - if (uniffi_pubkymobile_checksum_func_parse_auth_url() != 29088) { - return InitializationResult.apiChecksumMismatch - } - if (uniffi_pubkymobile_checksum_func_publish() != 20156) { - return InitializationResult.apiChecksumMismatch - } - if (uniffi_pubkymobile_checksum_func_publish_https() != 14705) { - return InitializationResult.apiChecksumMismatch - } - if (uniffi_pubkymobile_checksum_func_put() != 51107) { - return InitializationResult.apiChecksumMismatch - } - if (uniffi_pubkymobile_checksum_func_remove_event_listener() != 6794) { - return InitializationResult.apiChecksumMismatch - } - if (uniffi_pubkymobile_checksum_func_resolve() != 18303) { - return InitializationResult.apiChecksumMismatch - } - if (uniffi_pubkymobile_checksum_func_resolve_https() != 34593) { - return InitializationResult.apiChecksumMismatch - } - if (uniffi_pubkymobile_checksum_func_session() != 65177) { - return InitializationResult.apiChecksumMismatch - } - if (uniffi_pubkymobile_checksum_func_set_event_listener() != 19468) { - return InitializationResult.apiChecksumMismatch - } - if (uniffi_pubkymobile_checksum_func_sign_in() != 21006) { - return InitializationResult.apiChecksumMismatch - } - if (uniffi_pubkymobile_checksum_func_sign_out() != 59116) { - return InitializationResult.apiChecksumMismatch - } - if (uniffi_pubkymobile_checksum_func_sign_up() != 58756) { - return InitializationResult.apiChecksumMismatch - } - if (uniffi_pubkymobile_checksum_func_switch_network() != 14054) { - return InitializationResult.apiChecksumMismatch - } - if (uniffi_pubkymobile_checksum_method_eventlistener_on_event_occurred() != 39865) { - return InitializationResult.apiChecksumMismatch - } - - return InitializationResult.ok -} - -private func uniffiEnsureInitialized() { - switch initializationResult { - case .ok: - break - case .contractVersionMismatch: - fatalError("UniFFI contract version mismatch: try cleaning and rebuilding your project") - case .apiChecksumMismatch: - fatalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") - } -} \ No newline at end of file diff --git a/bindings/ios/pubkymobileFFI.h b/bindings/ios/pubkymobileFFI.h deleted file mode 100644 index 3694adc..0000000 --- a/bindings/ios/pubkymobileFFI.h +++ /dev/null @@ -1,297 +0,0 @@ -// This file was autogenerated by some hot garbage in the `uniffi` crate. -// Trust me, you don't want to mess with it! - -#pragma once - -#include -#include -#include - -// The following structs are used to implement the lowest level -// of the FFI, and thus useful to multiple uniffied crates. -// We ensure they are declared exactly once, with a header guard, UNIFFI_SHARED_H. -#ifdef UNIFFI_SHARED_H - // We also try to prevent mixing versions of shared uniffi header structs. - // If you add anything to the #else block, you must increment the version suffix in UNIFFI_SHARED_HEADER_V4 - #ifndef UNIFFI_SHARED_HEADER_V4 - #error Combining helper code from multiple versions of uniffi is not supported - #endif // ndef UNIFFI_SHARED_HEADER_V4 -#else -#define UNIFFI_SHARED_H -#define UNIFFI_SHARED_HEADER_V4 -// ⚠️ Attention: If you change this #else block (ending in `#endif // def UNIFFI_SHARED_H`) you *must* ⚠️ -// ⚠️ increment the version suffix in all instances of UNIFFI_SHARED_HEADER_V4 in this file. ⚠️ - -typedef struct RustBuffer -{ - int32_t capacity; - int32_t len; - uint8_t *_Nullable data; -} RustBuffer; - -typedef int32_t (*ForeignCallback)(uint64_t, int32_t, const uint8_t *_Nonnull, int32_t, RustBuffer *_Nonnull); - -// Task defined in Rust that Swift executes -typedef void (*UniFfiRustTaskCallback)(const void * _Nullable, int8_t); - -// Callback to execute Rust tasks using a Swift Task -// -// Args: -// executor: ForeignExecutor lowered into a size_t value -// delay: Delay in MS -// task: UniFfiRustTaskCallback to call -// task_data: data to pass the task callback -typedef int8_t (*UniFfiForeignExecutorCallback)(size_t, uint32_t, UniFfiRustTaskCallback _Nullable, const void * _Nullable); - -typedef struct ForeignBytes -{ - int32_t len; - const uint8_t *_Nullable data; -} ForeignBytes; - -// Error definitions -typedef struct RustCallStatus { - int8_t code; - RustBuffer errorBuf; -} RustCallStatus; - -// ⚠️ Attention: If you change this #else block (ending in `#endif // def UNIFFI_SHARED_H`) you *must* ⚠️ -// ⚠️ increment the version suffix in all instances of UNIFFI_SHARED_HEADER_V4 in this file. ⚠️ -#endif // def UNIFFI_SHARED_H - -// Continuation callback for UniFFI Futures -typedef void (*UniFfiRustFutureContinuation)(void * _Nonnull, int8_t); - -// Scaffolding functions -void uniffi_pubkymobile_fn_free_eventnotifier(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status -); -void uniffi_pubkymobile_fn_init_callback_eventlistener(ForeignCallback _Nonnull callback_stub, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_auth(RustBuffer url, RustBuffer secret_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_create_recovery_file(RustBuffer secret_key, RustBuffer passphrase, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_decrypt_recovery_file(RustBuffer recovery_file, RustBuffer passphrase, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_delete_file(RustBuffer url, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_generate_secret_key(RustCallStatus *_Nonnull out_status - -); -RustBuffer uniffi_pubkymobile_fn_func_get(RustBuffer url, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_get_public_key_from_secret_key(RustBuffer secret_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_list(RustBuffer url, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_parse_auth_url(RustBuffer url, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_publish(RustBuffer record_name, RustBuffer record_content, RustBuffer secret_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_publish_https(RustBuffer record_name, RustBuffer target, RustBuffer secret_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_put(RustBuffer url, RustBuffer content, RustCallStatus *_Nonnull out_status -); -void uniffi_pubkymobile_fn_func_remove_event_listener(RustCallStatus *_Nonnull out_status - -); -RustBuffer uniffi_pubkymobile_fn_func_resolve(RustBuffer public_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_resolve_https(RustBuffer public_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_session(RustBuffer pubky, RustCallStatus *_Nonnull out_status -); -void uniffi_pubkymobile_fn_func_set_event_listener(uint64_t listener, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_sign_in(RustBuffer secret_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_sign_out(RustBuffer secret_key, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_sign_up(RustBuffer secret_key, RustBuffer homeserver, RustCallStatus *_Nonnull out_status -); -RustBuffer uniffi_pubkymobile_fn_func_switch_network(int8_t use_testnet, RustCallStatus *_Nonnull out_status -); -RustBuffer ffi_pubkymobile_rustbuffer_alloc(int32_t size, RustCallStatus *_Nonnull out_status -); -RustBuffer ffi_pubkymobile_rustbuffer_from_bytes(ForeignBytes bytes, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rustbuffer_free(RustBuffer buf, RustCallStatus *_Nonnull out_status -); -RustBuffer ffi_pubkymobile_rustbuffer_reserve(RustBuffer buf, int32_t additional, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_continuation_callback_set(UniFfiRustFutureContinuation _Nonnull callback -); -void ffi_pubkymobile_rust_future_poll_u8(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_u8(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_u8(void* _Nonnull handle -); -uint8_t ffi_pubkymobile_rust_future_complete_u8(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_i8(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_i8(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_i8(void* _Nonnull handle -); -int8_t ffi_pubkymobile_rust_future_complete_i8(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_u16(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_u16(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_u16(void* _Nonnull handle -); -uint16_t ffi_pubkymobile_rust_future_complete_u16(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_i16(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_i16(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_i16(void* _Nonnull handle -); -int16_t ffi_pubkymobile_rust_future_complete_i16(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_u32(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_u32(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_u32(void* _Nonnull handle -); -uint32_t ffi_pubkymobile_rust_future_complete_u32(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_i32(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_i32(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_i32(void* _Nonnull handle -); -int32_t ffi_pubkymobile_rust_future_complete_i32(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_u64(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_u64(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_u64(void* _Nonnull handle -); -uint64_t ffi_pubkymobile_rust_future_complete_u64(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_i64(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_i64(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_i64(void* _Nonnull handle -); -int64_t ffi_pubkymobile_rust_future_complete_i64(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_f32(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_f32(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_f32(void* _Nonnull handle -); -float ffi_pubkymobile_rust_future_complete_f32(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_f64(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_f64(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_f64(void* _Nonnull handle -); -double ffi_pubkymobile_rust_future_complete_f64(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_pointer(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_pointer(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_pointer(void* _Nonnull handle -); -void*_Nonnull ffi_pubkymobile_rust_future_complete_pointer(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_rust_buffer(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_rust_buffer(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_rust_buffer(void* _Nonnull handle -); -RustBuffer ffi_pubkymobile_rust_future_complete_rust_buffer(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -void ffi_pubkymobile_rust_future_poll_void(void* _Nonnull handle, void* _Nonnull uniffi_callback -); -void ffi_pubkymobile_rust_future_cancel_void(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_free_void(void* _Nonnull handle -); -void ffi_pubkymobile_rust_future_complete_void(void* _Nonnull handle, RustCallStatus *_Nonnull out_status -); -uint16_t uniffi_pubkymobile_checksum_func_auth(void - -); -uint16_t uniffi_pubkymobile_checksum_func_create_recovery_file(void - -); -uint16_t uniffi_pubkymobile_checksum_func_decrypt_recovery_file(void - -); -uint16_t uniffi_pubkymobile_checksum_func_delete_file(void - -); -uint16_t uniffi_pubkymobile_checksum_func_generate_secret_key(void - -); -uint16_t uniffi_pubkymobile_checksum_func_get(void - -); -uint16_t uniffi_pubkymobile_checksum_func_get_public_key_from_secret_key(void - -); -uint16_t uniffi_pubkymobile_checksum_func_list(void - -); -uint16_t uniffi_pubkymobile_checksum_func_parse_auth_url(void - -); -uint16_t uniffi_pubkymobile_checksum_func_publish(void - -); -uint16_t uniffi_pubkymobile_checksum_func_publish_https(void - -); -uint16_t uniffi_pubkymobile_checksum_func_put(void - -); -uint16_t uniffi_pubkymobile_checksum_func_remove_event_listener(void - -); -uint16_t uniffi_pubkymobile_checksum_func_resolve(void - -); -uint16_t uniffi_pubkymobile_checksum_func_resolve_https(void - -); -uint16_t uniffi_pubkymobile_checksum_func_session(void - -); -uint16_t uniffi_pubkymobile_checksum_func_set_event_listener(void - -); -uint16_t uniffi_pubkymobile_checksum_func_sign_in(void - -); -uint16_t uniffi_pubkymobile_checksum_func_sign_out(void - -); -uint16_t uniffi_pubkymobile_checksum_func_sign_up(void - -); -uint16_t uniffi_pubkymobile_checksum_func_switch_network(void - -); -uint16_t uniffi_pubkymobile_checksum_method_eventlistener_on_event_occurred(void - -); -uint32_t ffi_pubkymobile_uniffi_contract_version(void - -); - diff --git a/bindings/python/README.md b/bindings/python/README.md new file mode 100644 index 0000000..7b2fd62 --- /dev/null +++ b/bindings/python/README.md @@ -0,0 +1,22 @@ +# Pubky Mobile Python Bindings + +Python bindings for the Pubky Mobile SDK. + +## Installation + +```bash +pip install . +``` + +## Usage + +```python +from pubkycore import * + +# Generate a new keypair +result = generate_secret_key() +if result[0] == "success": + print(f"Generated key: {result[1]}") +else: + print(f"Error: {result[1]}") +``` diff --git a/bindings/python/pubkycore/__init__.py b/bindings/python/pubkycore/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/bindings/python/pubkycore/libpubkycore.dylib b/bindings/python/pubkycore/libpubkycore.dylib new file mode 100755 index 0000000..ba9934e Binary files /dev/null and b/bindings/python/pubkycore/libpubkycore.dylib differ diff --git a/bindings/python/pubkycore/pubkycore.py b/bindings/python/pubkycore/pubkycore.py new file mode 100644 index 0000000..596a103 --- /dev/null +++ b/bindings/python/pubkycore/pubkycore.py @@ -0,0 +1,1440 @@ +# This file was autogenerated by some hot garbage in the `uniffi` crate. +# Trust me, you don't want to mess with it! + +# Common helper code. +# +# Ideally this would live in a separate .py file where it can be unittested etc +# in isolation, and perhaps even published as a re-useable package. +# +# However, it's important that the details of how this helper code works (e.g. the +# way that different builtin types are passed across the FFI) exactly match what's +# expected by the rust code on the other side of the interface. In practice right +# now that means coming from the exact some version of `uniffi` that was used to +# compile the rust component. The easiest way to ensure this is to bundle the Python +# helpers directly inline like we're doing here. + +import os +import sys +import ctypes +import enum +import struct +import contextlib +import datetime +import typing +import platform + +# Used for default argument values +_DEFAULT = object() + + +class _UniffiRustBuffer(ctypes.Structure): + _fields_ = [ + ("capacity", ctypes.c_int32), + ("len", ctypes.c_int32), + ("data", ctypes.POINTER(ctypes.c_char)), + ] + + @staticmethod + def alloc(size): + return _rust_call(_UniffiLib.ffi_pubkycore_rustbuffer_alloc, size) + + @staticmethod + def reserve(rbuf, additional): + return _rust_call(_UniffiLib.ffi_pubkycore_rustbuffer_reserve, rbuf, additional) + + def free(self): + return _rust_call(_UniffiLib.ffi_pubkycore_rustbuffer_free, self) + + def __str__(self): + return "_UniffiRustBuffer(capacity={}, len={}, data={})".format( + self.capacity, + self.len, + self.data[0:self.len] + ) + + @contextlib.contextmanager + def alloc_with_builder(*args): + """Context-manger to allocate a buffer using a _UniffiRustBufferBuilder. + + The allocated buffer will be automatically freed if an error occurs, ensuring that + we don't accidentally leak it. + """ + builder = _UniffiRustBufferBuilder() + try: + yield builder + except: + builder.discard() + raise + + @contextlib.contextmanager + def consume_with_stream(self): + """Context-manager to consume a buffer using a _UniffiRustBufferStream. + + The _UniffiRustBuffer will be freed once the context-manager exits, ensuring that we don't + leak it even if an error occurs. + """ + try: + s = _UniffiRustBufferStream.from_rust_buffer(self) + yield s + if s.remaining() != 0: + raise RuntimeError("junk data left in buffer at end of consume_with_stream") + finally: + self.free() + + @contextlib.contextmanager + def read_with_stream(self): + """Context-manager to read a buffer using a _UniffiRustBufferStream. + + This is like consume_with_stream, but doesn't free the buffer afterwards. + It should only be used with borrowed `_UniffiRustBuffer` data. + """ + s = _UniffiRustBufferStream.from_rust_buffer(self) + yield s + if s.remaining() != 0: + raise RuntimeError("junk data left in buffer at end of read_with_stream") + +class _UniffiForeignBytes(ctypes.Structure): + _fields_ = [ + ("len", ctypes.c_int32), + ("data", ctypes.POINTER(ctypes.c_char)), + ] + + def __str__(self): + return "_UniffiForeignBytes(len={}, data={})".format(self.len, self.data[0:self.len]) + + +class _UniffiRustBufferStream: + """ + Helper for structured reading of bytes from a _UniffiRustBuffer + """ + + def __init__(self, data, len): + self.data = data + self.len = len + self.offset = 0 + + @classmethod + def from_rust_buffer(cls, buf): + return cls(buf.data, buf.len) + + def remaining(self): + return self.len - self.offset + + def _unpack_from(self, size, format): + if self.offset + size > self.len: + raise InternalError("read past end of rust buffer") + value = struct.unpack(format, self.data[self.offset:self.offset+size])[0] + self.offset += size + return value + + def read(self, size): + if self.offset + size > self.len: + raise InternalError("read past end of rust buffer") + data = self.data[self.offset:self.offset+size] + self.offset += size + return data + + def read_i8(self): + return self._unpack_from(1, ">b") + + def read_u8(self): + return self._unpack_from(1, ">B") + + def read_i16(self): + return self._unpack_from(2, ">h") + + def read_u16(self): + return self._unpack_from(2, ">H") + + def read_i32(self): + return self._unpack_from(4, ">i") + + def read_u32(self): + return self._unpack_from(4, ">I") + + def read_i64(self): + return self._unpack_from(8, ">q") + + def read_u64(self): + return self._unpack_from(8, ">Q") + + def read_float(self): + v = self._unpack_from(4, ">f") + return v + + def read_double(self): + return self._unpack_from(8, ">d") + + def read_c_size_t(self): + return self._unpack_from(ctypes.sizeof(ctypes.c_size_t) , "@N") + +class _UniffiRustBufferBuilder: + """ + Helper for structured writing of bytes into a _UniffiRustBuffer. + """ + + def __init__(self): + self.rbuf = _UniffiRustBuffer.alloc(16) + self.rbuf.len = 0 + + def finalize(self): + rbuf = self.rbuf + self.rbuf = None + return rbuf + + def discard(self): + if self.rbuf is not None: + rbuf = self.finalize() + rbuf.free() + + @contextlib.contextmanager + def _reserve(self, num_bytes): + if self.rbuf.len + num_bytes > self.rbuf.capacity: + self.rbuf = _UniffiRustBuffer.reserve(self.rbuf, num_bytes) + yield None + self.rbuf.len += num_bytes + + def _pack_into(self, size, format, value): + with self._reserve(size): + # XXX TODO: I feel like I should be able to use `struct.pack_into` here but can't figure it out. + for i, byte in enumerate(struct.pack(format, value)): + self.rbuf.data[self.rbuf.len + i] = byte + + def write(self, value): + with self._reserve(len(value)): + for i, byte in enumerate(value): + self.rbuf.data[self.rbuf.len + i] = byte + + def write_i8(self, v): + self._pack_into(1, ">b", v) + + def write_u8(self, v): + self._pack_into(1, ">B", v) + + def write_i16(self, v): + self._pack_into(2, ">h", v) + + def write_u16(self, v): + self._pack_into(2, ">H", v) + + def write_i32(self, v): + self._pack_into(4, ">i", v) + + def write_u32(self, v): + self._pack_into(4, ">I", v) + + def write_i64(self, v): + self._pack_into(8, ">q", v) + + def write_u64(self, v): + self._pack_into(8, ">Q", v) + + def write_float(self, v): + self._pack_into(4, ">f", v) + + def write_double(self, v): + self._pack_into(8, ">d", v) + + def write_c_size_t(self, v): + self._pack_into(ctypes.sizeof(ctypes.c_size_t) , "@N", v) +# A handful of classes and functions to support the generated data structures. +# This would be a good candidate for isolating in its own ffi-support lib. + +class InternalError(Exception): + pass + +class _UniffiRustCallStatus(ctypes.Structure): + """ + Error runtime. + """ + _fields_ = [ + ("code", ctypes.c_int8), + ("error_buf", _UniffiRustBuffer), + ] + + # These match the values from the uniffi::rustcalls module + CALL_SUCCESS = 0 + CALL_ERROR = 1 + CALL_PANIC = 2 + + def __str__(self): + if self.code == _UniffiRustCallStatus.CALL_SUCCESS: + return "_UniffiRustCallStatus(CALL_SUCCESS)" + elif self.code == _UniffiRustCallStatus.CALL_ERROR: + return "_UniffiRustCallStatus(CALL_ERROR)" + elif self.code == _UniffiRustCallStatus.CALL_PANIC: + return "_UniffiRustCallStatus(CALL_PANIC)" + else: + return "_UniffiRustCallStatus()" + +def _rust_call(fn, *args): + # Call a rust function + return _rust_call_with_error(None, fn, *args) + +def _rust_call_with_error(error_ffi_converter, fn, *args): + # Call a rust function and handle any errors + # + # This function is used for rust calls that return Result<> and therefore can set the CALL_ERROR status code. + # error_ffi_converter must be set to the _UniffiConverter for the error class that corresponds to the result. + call_status = _UniffiRustCallStatus(code=_UniffiRustCallStatus.CALL_SUCCESS, error_buf=_UniffiRustBuffer(0, 0, None)) + + args_with_error = args + (ctypes.byref(call_status),) + result = fn(*args_with_error) + _uniffi_check_call_status(error_ffi_converter, call_status) + return result + +def _uniffi_check_call_status(error_ffi_converter, call_status): + if call_status.code == _UniffiRustCallStatus.CALL_SUCCESS: + pass + elif call_status.code == _UniffiRustCallStatus.CALL_ERROR: + if error_ffi_converter is None: + call_status.error_buf.free() + raise InternalError("_rust_call_with_error: CALL_ERROR, but error_ffi_converter is None") + else: + raise error_ffi_converter.lift(call_status.error_buf) + elif call_status.code == _UniffiRustCallStatus.CALL_PANIC: + # When the rust code sees a panic, it tries to construct a _UniffiRustBuffer + # with the message. But if that code panics, then it just sends back + # an empty buffer. + if call_status.error_buf.len > 0: + msg = _UniffiConverterString.lift(call_status.error_buf) + else: + msg = "Unknown rust panic" + raise InternalError(msg) + else: + raise InternalError("Invalid _UniffiRustCallStatus code: {}".format( + call_status.code)) + +# A function pointer for a callback as defined by UniFFI. +# Rust definition `fn(handle: u64, method: u32, args: _UniffiRustBuffer, buf_ptr: *mut _UniffiRustBuffer) -> int` +_UNIFFI_FOREIGN_CALLBACK_T = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_ulonglong, ctypes.c_ulong, ctypes.POINTER(ctypes.c_char), ctypes.c_int, ctypes.POINTER(_UniffiRustBuffer)) + +# UniFFI future continuation +_UNIFFI_FUTURE_CONTINUATION_T = ctypes.CFUNCTYPE(None, ctypes.c_size_t, ctypes.c_int8) + +class _UniffiPointerManagerCPython: + """ + Manage giving out pointers to Python objects on CPython + + This class is used to generate opaque pointers that reference Python objects to pass to Rust. + It assumes a CPython platform. See _UniffiPointerManagerGeneral for the alternative. + """ + + def new_pointer(self, obj): + """ + Get a pointer for an object as a ctypes.c_size_t instance + + Each call to new_pointer() must be balanced with exactly one call to release_pointer() + + This returns a ctypes.c_size_t. This is always the same size as a pointer and can be + interchanged with pointers for FFI function arguments and return values. + """ + # IncRef the object since we're going to pass a pointer to Rust + ctypes.pythonapi.Py_IncRef(ctypes.py_object(obj)) + # id() is the object address on CPython + # (https://docs.python.org/3/library/functions.html#id) + return id(obj) + + def release_pointer(self, address): + py_obj = ctypes.cast(address, ctypes.py_object) + obj = py_obj.value + ctypes.pythonapi.Py_DecRef(py_obj) + return obj + + def lookup(self, address): + return ctypes.cast(address, ctypes.py_object).value + +class _UniffiPointerManagerGeneral: + """ + Manage giving out pointers to Python objects on non-CPython platforms + + This has the same API as _UniffiPointerManagerCPython, but doesn't assume we're running on + CPython and is slightly slower. + + Instead of using real pointers, it maps integer values to objects and returns the keys as + c_size_t values. + """ + + def __init__(self): + self._map = {} + self._lock = threading.Lock() + self._current_handle = 0 + + def new_pointer(self, obj): + with self._lock: + handle = self._current_handle + self._current_handle += 1 + self._map[handle] = obj + return handle + + def release_pointer(self, handle): + with self._lock: + return self._map.pop(handle) + + def lookup(self, handle): + with self._lock: + return self._map[handle] + +# Pick an pointer manager implementation based on the platform +if platform.python_implementation() == 'CPython': + _UniffiPointerManager = _UniffiPointerManagerCPython # type: ignore +else: + _UniffiPointerManager = _UniffiPointerManagerGeneral # type: ignore +# Types conforming to `_UniffiConverterPrimitive` pass themselves directly over the FFI. +class _UniffiConverterPrimitive: + @classmethod + def check(cls, value): + return value + + @classmethod + def lift(cls, value): + return value + + @classmethod + def lower(cls, value): + return cls.lowerUnchecked(cls.check(value)) + + @classmethod + def lowerUnchecked(cls, value): + return value + + @classmethod + def write(cls, value, buf): + cls.write_unchecked(cls.check(value), buf) + +class _UniffiConverterPrimitiveInt(_UniffiConverterPrimitive): + @classmethod + def check(cls, value): + try: + value = value.__index__() + except Exception: + raise TypeError("'{}' object cannot be interpreted as an integer".format(type(value).__name__)) + if not isinstance(value, int): + raise TypeError("__index__ returned non-int (type {})".format(type(value).__name__)) + if not cls.VALUE_MIN <= value < cls.VALUE_MAX: + raise ValueError("{} requires {} <= value < {}".format(cls.CLASS_NAME, cls.VALUE_MIN, cls.VALUE_MAX)) + return super().check(value) + +class _UniffiConverterPrimitiveFloat(_UniffiConverterPrimitive): + @classmethod + def check(cls, value): + try: + value = value.__float__() + except Exception: + raise TypeError("must be real number, not {}".format(type(value).__name__)) + if not isinstance(value, float): + raise TypeError("__float__ returned non-float (type {})".format(type(value).__name__)) + return super().check(value) + +# Helper class for wrapper types that will always go through a _UniffiRustBuffer. +# Classes should inherit from this and implement the `read` and `write` static methods. +class _UniffiConverterRustBuffer: + @classmethod + def lift(cls, rbuf): + with rbuf.consume_with_stream() as stream: + return cls.read(stream) + + @classmethod + def lower(cls, value): + with _UniffiRustBuffer.alloc_with_builder() as builder: + cls.write(value, builder) + return builder.finalize() + +# Contains loading, initialization code, and the FFI Function declarations. +# Define some ctypes FFI types that we use in the library + +""" +ctypes type for the foreign executor callback. This is a built-in interface for scheduling +tasks + +Args: + executor: opaque c_size_t value representing the eventloop + delay: delay in ms + task: function pointer to the task callback + task_data: void pointer to the task callback data + +Normally we should call task(task_data) after the detail. +However, when task is NULL this indicates that Rust has dropped the ForeignExecutor and we should +decrease the EventLoop refcount. +""" +_UNIFFI_FOREIGN_EXECUTOR_CALLBACK_T = ctypes.CFUNCTYPE(ctypes.c_int8, ctypes.c_size_t, ctypes.c_uint32, ctypes.c_void_p, ctypes.c_void_p) + +""" +Function pointer for a Rust task, which a callback function that takes a opaque pointer +""" +_UNIFFI_RUST_TASK = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_int8) + +def _uniffi_future_callback_t(return_type): + """ + Factory function to create callback function types for async functions + """ + return ctypes.CFUNCTYPE(None, ctypes.c_size_t, return_type, _UniffiRustCallStatus) + +def _uniffi_load_indirect(): + """ + This is how we find and load the dynamic library provided by the component. + For now we just look it up by name. + """ + if sys.platform == "darwin": + libname = "lib{}.dylib" + elif sys.platform.startswith("win"): + # As of python3.8, ctypes does not seem to search $PATH when loading DLLs. + # We could use `os.add_dll_directory` to configure the search path, but + # it doesn't feel right to mess with application-wide settings. Let's + # assume that the `.dll` is next to the `.py` file and load by full path. + libname = os.path.join( + os.path.dirname(__file__), + "{}.dll", + ) + else: + # Anything else must be an ELF platform - Linux, *BSD, Solaris/illumos + libname = "lib{}.so" + + libname = libname.format("pubkycore") + path = os.path.join(os.path.dirname(__file__), libname) + lib = ctypes.cdll.LoadLibrary(path) + return lib + +def _uniffi_check_contract_api_version(lib): + # Get the bindings contract version from our ComponentInterface + bindings_contract_version = 24 + # Get the scaffolding contract version by calling the into the dylib + scaffolding_contract_version = lib.ffi_pubkycore_uniffi_contract_version() + if bindings_contract_version != scaffolding_contract_version: + raise InternalError("UniFFI contract version mismatch: try cleaning and rebuilding your project") + +def _uniffi_check_api_checksums(lib): + if lib.uniffi_pubkycore_checksum_func_auth() != 51826: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_pubkycore_checksum_func_create_recovery_file() != 48846: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_pubkycore_checksum_func_decrypt_recovery_file() != 26407: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_pubkycore_checksum_func_delete_file() != 9063: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_pubkycore_checksum_func_generate_secret_key() != 12800: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_pubkycore_checksum_func_get() != 6591: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_pubkycore_checksum_func_get_public_key_from_secret_key() != 40316: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_pubkycore_checksum_func_list() != 43198: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_pubkycore_checksum_func_parse_auth_url() != 27379: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_pubkycore_checksum_func_publish() != 48989: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_pubkycore_checksum_func_publish_https() != 5614: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_pubkycore_checksum_func_put() != 48150: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_pubkycore_checksum_func_remove_event_listener() != 23534: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_pubkycore_checksum_func_resolve() != 34317: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_pubkycore_checksum_func_resolve_https() != 17266: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_pubkycore_checksum_func_session() != 59795: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_pubkycore_checksum_func_set_event_listener() != 60071: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_pubkycore_checksum_func_sign_in() != 21584: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_pubkycore_checksum_func_sign_out() != 34903: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_pubkycore_checksum_func_sign_up() != 37999: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_pubkycore_checksum_func_switch_network() != 64215: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_pubkycore_checksum_method_eventlistener_on_event_occurred() != 11531: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + +# A ctypes library to expose the extern-C FFI definitions. +# This is an implementation detail which will be called internally by the public API. + +_UniffiLib = _uniffi_load_indirect() +_UniffiLib.uniffi_pubkycore_fn_free_eventnotifier.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_free_eventnotifier.restype = None +_UniffiLib.uniffi_pubkycore_fn_init_callback_eventlistener.argtypes = ( + _UNIFFI_FOREIGN_CALLBACK_T, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_init_callback_eventlistener.restype = None +_UniffiLib.uniffi_pubkycore_fn_func_auth.argtypes = ( + _UniffiRustBuffer, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_func_auth.restype = _UniffiRustBuffer +_UniffiLib.uniffi_pubkycore_fn_func_create_recovery_file.argtypes = ( + _UniffiRustBuffer, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_func_create_recovery_file.restype = _UniffiRustBuffer +_UniffiLib.uniffi_pubkycore_fn_func_decrypt_recovery_file.argtypes = ( + _UniffiRustBuffer, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_func_decrypt_recovery_file.restype = _UniffiRustBuffer +_UniffiLib.uniffi_pubkycore_fn_func_delete_file.argtypes = ( + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_func_delete_file.restype = _UniffiRustBuffer +_UniffiLib.uniffi_pubkycore_fn_func_generate_secret_key.argtypes = ( + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_func_generate_secret_key.restype = _UniffiRustBuffer +_UniffiLib.uniffi_pubkycore_fn_func_get.argtypes = ( + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_func_get.restype = _UniffiRustBuffer +_UniffiLib.uniffi_pubkycore_fn_func_get_public_key_from_secret_key.argtypes = ( + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_func_get_public_key_from_secret_key.restype = _UniffiRustBuffer +_UniffiLib.uniffi_pubkycore_fn_func_list.argtypes = ( + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_func_list.restype = _UniffiRustBuffer +_UniffiLib.uniffi_pubkycore_fn_func_parse_auth_url.argtypes = ( + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_func_parse_auth_url.restype = _UniffiRustBuffer +_UniffiLib.uniffi_pubkycore_fn_func_publish.argtypes = ( + _UniffiRustBuffer, + _UniffiRustBuffer, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_func_publish.restype = _UniffiRustBuffer +_UniffiLib.uniffi_pubkycore_fn_func_publish_https.argtypes = ( + _UniffiRustBuffer, + _UniffiRustBuffer, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_func_publish_https.restype = _UniffiRustBuffer +_UniffiLib.uniffi_pubkycore_fn_func_put.argtypes = ( + _UniffiRustBuffer, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_func_put.restype = _UniffiRustBuffer +_UniffiLib.uniffi_pubkycore_fn_func_remove_event_listener.argtypes = ( + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_func_remove_event_listener.restype = None +_UniffiLib.uniffi_pubkycore_fn_func_resolve.argtypes = ( + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_func_resolve.restype = _UniffiRustBuffer +_UniffiLib.uniffi_pubkycore_fn_func_resolve_https.argtypes = ( + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_func_resolve_https.restype = _UniffiRustBuffer +_UniffiLib.uniffi_pubkycore_fn_func_session.argtypes = ( + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_func_session.restype = _UniffiRustBuffer +_UniffiLib.uniffi_pubkycore_fn_func_set_event_listener.argtypes = ( + ctypes.c_uint64, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_func_set_event_listener.restype = None +_UniffiLib.uniffi_pubkycore_fn_func_sign_in.argtypes = ( + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_func_sign_in.restype = _UniffiRustBuffer +_UniffiLib.uniffi_pubkycore_fn_func_sign_out.argtypes = ( + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_func_sign_out.restype = _UniffiRustBuffer +_UniffiLib.uniffi_pubkycore_fn_func_sign_up.argtypes = ( + _UniffiRustBuffer, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_func_sign_up.restype = _UniffiRustBuffer +_UniffiLib.uniffi_pubkycore_fn_func_switch_network.argtypes = ( + ctypes.c_int8, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_pubkycore_fn_func_switch_network.restype = _UniffiRustBuffer +_UniffiLib.ffi_pubkycore_rustbuffer_alloc.argtypes = ( + ctypes.c_int32, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_pubkycore_rustbuffer_alloc.restype = _UniffiRustBuffer +_UniffiLib.ffi_pubkycore_rustbuffer_from_bytes.argtypes = ( + _UniffiForeignBytes, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_pubkycore_rustbuffer_from_bytes.restype = _UniffiRustBuffer +_UniffiLib.ffi_pubkycore_rustbuffer_free.argtypes = ( + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_pubkycore_rustbuffer_free.restype = None +_UniffiLib.ffi_pubkycore_rustbuffer_reserve.argtypes = ( + _UniffiRustBuffer, + ctypes.c_int32, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_pubkycore_rustbuffer_reserve.restype = _UniffiRustBuffer +_UniffiLib.ffi_pubkycore_rust_future_continuation_callback_set.argtypes = ( + _UNIFFI_FUTURE_CONTINUATION_T, +) +_UniffiLib.ffi_pubkycore_rust_future_continuation_callback_set.restype = None +_UniffiLib.ffi_pubkycore_rust_future_poll_u8.argtypes = ( + ctypes.c_void_p, + ctypes.c_size_t, +) +_UniffiLib.ffi_pubkycore_rust_future_poll_u8.restype = None +_UniffiLib.ffi_pubkycore_rust_future_cancel_u8.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_cancel_u8.restype = None +_UniffiLib.ffi_pubkycore_rust_future_free_u8.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_free_u8.restype = None +_UniffiLib.ffi_pubkycore_rust_future_complete_u8.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_pubkycore_rust_future_complete_u8.restype = ctypes.c_uint8 +_UniffiLib.ffi_pubkycore_rust_future_poll_i8.argtypes = ( + ctypes.c_void_p, + ctypes.c_size_t, +) +_UniffiLib.ffi_pubkycore_rust_future_poll_i8.restype = None +_UniffiLib.ffi_pubkycore_rust_future_cancel_i8.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_cancel_i8.restype = None +_UniffiLib.ffi_pubkycore_rust_future_free_i8.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_free_i8.restype = None +_UniffiLib.ffi_pubkycore_rust_future_complete_i8.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_pubkycore_rust_future_complete_i8.restype = ctypes.c_int8 +_UniffiLib.ffi_pubkycore_rust_future_poll_u16.argtypes = ( + ctypes.c_void_p, + ctypes.c_size_t, +) +_UniffiLib.ffi_pubkycore_rust_future_poll_u16.restype = None +_UniffiLib.ffi_pubkycore_rust_future_cancel_u16.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_cancel_u16.restype = None +_UniffiLib.ffi_pubkycore_rust_future_free_u16.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_free_u16.restype = None +_UniffiLib.ffi_pubkycore_rust_future_complete_u16.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_pubkycore_rust_future_complete_u16.restype = ctypes.c_uint16 +_UniffiLib.ffi_pubkycore_rust_future_poll_i16.argtypes = ( + ctypes.c_void_p, + ctypes.c_size_t, +) +_UniffiLib.ffi_pubkycore_rust_future_poll_i16.restype = None +_UniffiLib.ffi_pubkycore_rust_future_cancel_i16.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_cancel_i16.restype = None +_UniffiLib.ffi_pubkycore_rust_future_free_i16.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_free_i16.restype = None +_UniffiLib.ffi_pubkycore_rust_future_complete_i16.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_pubkycore_rust_future_complete_i16.restype = ctypes.c_int16 +_UniffiLib.ffi_pubkycore_rust_future_poll_u32.argtypes = ( + ctypes.c_void_p, + ctypes.c_size_t, +) +_UniffiLib.ffi_pubkycore_rust_future_poll_u32.restype = None +_UniffiLib.ffi_pubkycore_rust_future_cancel_u32.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_cancel_u32.restype = None +_UniffiLib.ffi_pubkycore_rust_future_free_u32.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_free_u32.restype = None +_UniffiLib.ffi_pubkycore_rust_future_complete_u32.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_pubkycore_rust_future_complete_u32.restype = ctypes.c_uint32 +_UniffiLib.ffi_pubkycore_rust_future_poll_i32.argtypes = ( + ctypes.c_void_p, + ctypes.c_size_t, +) +_UniffiLib.ffi_pubkycore_rust_future_poll_i32.restype = None +_UniffiLib.ffi_pubkycore_rust_future_cancel_i32.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_cancel_i32.restype = None +_UniffiLib.ffi_pubkycore_rust_future_free_i32.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_free_i32.restype = None +_UniffiLib.ffi_pubkycore_rust_future_complete_i32.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_pubkycore_rust_future_complete_i32.restype = ctypes.c_int32 +_UniffiLib.ffi_pubkycore_rust_future_poll_u64.argtypes = ( + ctypes.c_void_p, + ctypes.c_size_t, +) +_UniffiLib.ffi_pubkycore_rust_future_poll_u64.restype = None +_UniffiLib.ffi_pubkycore_rust_future_cancel_u64.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_cancel_u64.restype = None +_UniffiLib.ffi_pubkycore_rust_future_free_u64.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_free_u64.restype = None +_UniffiLib.ffi_pubkycore_rust_future_complete_u64.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_pubkycore_rust_future_complete_u64.restype = ctypes.c_uint64 +_UniffiLib.ffi_pubkycore_rust_future_poll_i64.argtypes = ( + ctypes.c_void_p, + ctypes.c_size_t, +) +_UniffiLib.ffi_pubkycore_rust_future_poll_i64.restype = None +_UniffiLib.ffi_pubkycore_rust_future_cancel_i64.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_cancel_i64.restype = None +_UniffiLib.ffi_pubkycore_rust_future_free_i64.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_free_i64.restype = None +_UniffiLib.ffi_pubkycore_rust_future_complete_i64.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_pubkycore_rust_future_complete_i64.restype = ctypes.c_int64 +_UniffiLib.ffi_pubkycore_rust_future_poll_f32.argtypes = ( + ctypes.c_void_p, + ctypes.c_size_t, +) +_UniffiLib.ffi_pubkycore_rust_future_poll_f32.restype = None +_UniffiLib.ffi_pubkycore_rust_future_cancel_f32.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_cancel_f32.restype = None +_UniffiLib.ffi_pubkycore_rust_future_free_f32.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_free_f32.restype = None +_UniffiLib.ffi_pubkycore_rust_future_complete_f32.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_pubkycore_rust_future_complete_f32.restype = ctypes.c_float +_UniffiLib.ffi_pubkycore_rust_future_poll_f64.argtypes = ( + ctypes.c_void_p, + ctypes.c_size_t, +) +_UniffiLib.ffi_pubkycore_rust_future_poll_f64.restype = None +_UniffiLib.ffi_pubkycore_rust_future_cancel_f64.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_cancel_f64.restype = None +_UniffiLib.ffi_pubkycore_rust_future_free_f64.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_free_f64.restype = None +_UniffiLib.ffi_pubkycore_rust_future_complete_f64.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_pubkycore_rust_future_complete_f64.restype = ctypes.c_double +_UniffiLib.ffi_pubkycore_rust_future_poll_pointer.argtypes = ( + ctypes.c_void_p, + ctypes.c_size_t, +) +_UniffiLib.ffi_pubkycore_rust_future_poll_pointer.restype = None +_UniffiLib.ffi_pubkycore_rust_future_cancel_pointer.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_cancel_pointer.restype = None +_UniffiLib.ffi_pubkycore_rust_future_free_pointer.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_free_pointer.restype = None +_UniffiLib.ffi_pubkycore_rust_future_complete_pointer.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_pubkycore_rust_future_complete_pointer.restype = ctypes.c_void_p +_UniffiLib.ffi_pubkycore_rust_future_poll_rust_buffer.argtypes = ( + ctypes.c_void_p, + ctypes.c_size_t, +) +_UniffiLib.ffi_pubkycore_rust_future_poll_rust_buffer.restype = None +_UniffiLib.ffi_pubkycore_rust_future_cancel_rust_buffer.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_cancel_rust_buffer.restype = None +_UniffiLib.ffi_pubkycore_rust_future_free_rust_buffer.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_free_rust_buffer.restype = None +_UniffiLib.ffi_pubkycore_rust_future_complete_rust_buffer.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_pubkycore_rust_future_complete_rust_buffer.restype = _UniffiRustBuffer +_UniffiLib.ffi_pubkycore_rust_future_poll_void.argtypes = ( + ctypes.c_void_p, + ctypes.c_size_t, +) +_UniffiLib.ffi_pubkycore_rust_future_poll_void.restype = None +_UniffiLib.ffi_pubkycore_rust_future_cancel_void.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_cancel_void.restype = None +_UniffiLib.ffi_pubkycore_rust_future_free_void.argtypes = ( + ctypes.c_void_p, +) +_UniffiLib.ffi_pubkycore_rust_future_free_void.restype = None +_UniffiLib.ffi_pubkycore_rust_future_complete_void.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_pubkycore_rust_future_complete_void.restype = None +_UniffiLib.uniffi_pubkycore_checksum_func_auth.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_func_auth.restype = ctypes.c_uint16 +_UniffiLib.uniffi_pubkycore_checksum_func_create_recovery_file.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_func_create_recovery_file.restype = ctypes.c_uint16 +_UniffiLib.uniffi_pubkycore_checksum_func_decrypt_recovery_file.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_func_decrypt_recovery_file.restype = ctypes.c_uint16 +_UniffiLib.uniffi_pubkycore_checksum_func_delete_file.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_func_delete_file.restype = ctypes.c_uint16 +_UniffiLib.uniffi_pubkycore_checksum_func_generate_secret_key.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_func_generate_secret_key.restype = ctypes.c_uint16 +_UniffiLib.uniffi_pubkycore_checksum_func_get.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_func_get.restype = ctypes.c_uint16 +_UniffiLib.uniffi_pubkycore_checksum_func_get_public_key_from_secret_key.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_func_get_public_key_from_secret_key.restype = ctypes.c_uint16 +_UniffiLib.uniffi_pubkycore_checksum_func_list.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_func_list.restype = ctypes.c_uint16 +_UniffiLib.uniffi_pubkycore_checksum_func_parse_auth_url.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_func_parse_auth_url.restype = ctypes.c_uint16 +_UniffiLib.uniffi_pubkycore_checksum_func_publish.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_func_publish.restype = ctypes.c_uint16 +_UniffiLib.uniffi_pubkycore_checksum_func_publish_https.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_func_publish_https.restype = ctypes.c_uint16 +_UniffiLib.uniffi_pubkycore_checksum_func_put.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_func_put.restype = ctypes.c_uint16 +_UniffiLib.uniffi_pubkycore_checksum_func_remove_event_listener.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_func_remove_event_listener.restype = ctypes.c_uint16 +_UniffiLib.uniffi_pubkycore_checksum_func_resolve.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_func_resolve.restype = ctypes.c_uint16 +_UniffiLib.uniffi_pubkycore_checksum_func_resolve_https.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_func_resolve_https.restype = ctypes.c_uint16 +_UniffiLib.uniffi_pubkycore_checksum_func_session.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_func_session.restype = ctypes.c_uint16 +_UniffiLib.uniffi_pubkycore_checksum_func_set_event_listener.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_func_set_event_listener.restype = ctypes.c_uint16 +_UniffiLib.uniffi_pubkycore_checksum_func_sign_in.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_func_sign_in.restype = ctypes.c_uint16 +_UniffiLib.uniffi_pubkycore_checksum_func_sign_out.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_func_sign_out.restype = ctypes.c_uint16 +_UniffiLib.uniffi_pubkycore_checksum_func_sign_up.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_func_sign_up.restype = ctypes.c_uint16 +_UniffiLib.uniffi_pubkycore_checksum_func_switch_network.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_func_switch_network.restype = ctypes.c_uint16 +_UniffiLib.uniffi_pubkycore_checksum_method_eventlistener_on_event_occurred.argtypes = ( +) +_UniffiLib.uniffi_pubkycore_checksum_method_eventlistener_on_event_occurred.restype = ctypes.c_uint16 +_UniffiLib.ffi_pubkycore_uniffi_contract_version.argtypes = ( +) +_UniffiLib.ffi_pubkycore_uniffi_contract_version.restype = ctypes.c_uint32 +_uniffi_check_contract_api_version(_UniffiLib) +_uniffi_check_api_checksums(_UniffiLib) + +# Async support + +# Public interface members begin here. + + +class _UniffiConverterBool(_UniffiConverterPrimitive): + @classmethod + def check(cls, value): + return not not value + + @classmethod + def read(cls, buf): + return cls.lift(buf.read_u8()) + + @classmethod + def write_unchecked(cls, value, buf): + buf.write_u8(value) + + @staticmethod + def lift(value): + return value != 0 + +class _UniffiConverterString: + @staticmethod + def check(value): + if not isinstance(value, str): + raise TypeError("argument must be str, not {}".format(type(value).__name__)) + return value + + @staticmethod + def read(buf): + size = buf.read_i32() + if size < 0: + raise InternalError("Unexpected negative string length") + utf8_bytes = buf.read(size) + return utf8_bytes.decode("utf-8") + + @staticmethod + def write(value, buf): + value = _UniffiConverterString.check(value) + utf8_bytes = value.encode("utf-8") + buf.write_i32(len(utf8_bytes)) + buf.write(utf8_bytes) + + @staticmethod + def lift(buf): + with buf.consume_with_stream() as stream: + return stream.read(stream.remaining()).decode("utf-8") + + @staticmethod + def lower(value): + value = _UniffiConverterString.check(value) + with _UniffiRustBuffer.alloc_with_builder() as builder: + builder.write(value.encode("utf-8")) + return builder.finalize() + + + +class EventNotifier: + _pointer: ctypes.c_void_p + + def __del__(self): + # In case of partial initialization of instances. + pointer = getattr(self, "_pointer", None) + if pointer is not None: + _rust_call(_UniffiLib.uniffi_pubkycore_fn_free_eventnotifier, pointer) + + # Used by alternative constructors or any methods which return this type. + @classmethod + def _make_instance_(cls, pointer): + # Lightly yucky way to bypass the usual __init__ logic + # and just create a new instance with the required pointer. + inst = cls.__new__(cls) + inst._pointer = pointer + return inst + + +class _UniffiConverterTypeEventNotifier: + @classmethod + def read(cls, buf): + ptr = buf.read_u64() + if ptr == 0: + raise InternalError("Raw pointer value was null") + return cls.lift(ptr) + + @classmethod + def write(cls, value, buf): + if not isinstance(value, EventNotifier): + raise TypeError("Expected EventNotifier instance, {} found".format(type(value).__name__)) + buf.write_u64(cls.lower(value)) + + @staticmethod + def lift(value): + return EventNotifier._make_instance_(value) + + @staticmethod + def lower(value): + return value._pointer + + + +import threading + +class ConcurrentHandleMap: + """ + A map where inserting, getting and removing data is synchronized with a lock. + """ + + def __init__(self): + # type Handle = int + self._left_map = {} # type: Dict[Handle, Any] + self._right_map = {} # type: Dict[Any, Handle] + + self._lock = threading.Lock() + self._current_handle = 0 + self._stride = 1 + + + def insert(self, obj): + with self._lock: + if obj in self._right_map: + return self._right_map[obj] + else: + handle = self._current_handle + self._current_handle += self._stride + self._left_map[handle] = obj + self._right_map[obj] = handle + return handle + + def get(self, handle): + with self._lock: + return self._left_map.get(handle) + + def remove(self, handle): + with self._lock: + if handle in self._left_map: + obj = self._left_map.pop(handle) + del self._right_map[obj] + return obj + +# Magic number for the Rust proxy to call using the same mechanism as every other method, +# to free the callback once it's dropped by Rust. +IDX_CALLBACK_FREE = 0 +# Return codes for callback calls +_UNIFFI_CALLBACK_SUCCESS = 0 +_UNIFFI_CALLBACK_ERROR = 1 +_UNIFFI_CALLBACK_UNEXPECTED_ERROR = 2 + +class _UniffiConverterCallbackInterface: + _handle_map = ConcurrentHandleMap() + + def __init__(self, cb): + self._foreign_callback = cb + + def drop(self, handle): + self.__class__._handle_map.remove(handle) + + @classmethod + def lift(cls, handle): + obj = cls._handle_map.get(handle) + if not obj: + raise InternalError("The object in the handle map has been dropped already") + + return obj + + @classmethod + def read(cls, buf): + handle = buf.read_u64() + cls.lift(handle) + + @classmethod + def lower(cls, cb): + handle = cls._handle_map.insert(cb) + return handle + + @classmethod + def write(cls, cb, buf): + buf.write_u64(cls.lower(cb)) + +# Declaration and _UniffiConverters for EventListener Callback Interface + +class EventListener: + def on_event_occurred(self, event_data: "str"): + raise NotImplementedError + + + +def py_foreignCallbackCallbackInterfaceEventListener(handle, method, args_data, args_len, buf_ptr): + + def invoke_on_event_occurred(python_callback, args_stream, buf_ptr): + def makeCall():return python_callback.on_event_occurred( + _UniffiConverterString.read(args_stream) + ) + + def makeCallAndHandleReturn(): + makeCall() + return _UNIFFI_CALLBACK_SUCCESS + return makeCallAndHandleReturn() + + + + cb = _UniffiConverterCallbackInterfaceEventListener.lift(handle) + if not cb: + raise InternalError("No callback in handlemap; this is a uniffi bug") + + if method == IDX_CALLBACK_FREE: + _UniffiConverterCallbackInterfaceEventListener.drop(handle) + # Successfull return + # See docs of ForeignCallback in `uniffi_core/src/ffi/foreigncallbacks.rs` + return _UNIFFI_CALLBACK_SUCCESS + + if method == 1: + # Call the method and handle any errors + # See docs of ForeignCallback in `uniffi_core/src/ffi/foreigncallbacks.rs` for details + try: + return invoke_on_event_occurred(cb, _UniffiRustBufferStream(args_data, args_len), buf_ptr) + except BaseException as e: + # Catch unexpected errors + try: + # Try to serialize the exception into a String + buf_ptr[0] = _UniffiConverterString.lower(repr(e)) + except: + # If that fails, just give up + pass + return _UNIFFI_CALLBACK_UNEXPECTED_ERROR + + + # This should never happen, because an out of bounds method index won't + # ever be used. Once we can catch errors, we should return an InternalException. + # https://github.com/mozilla/uniffi-rs/issues/351 + + # An unexpected error happened. + # See docs of ForeignCallback in `uniffi_core/src/ffi/foreigncallbacks.rs` + return _UNIFFI_CALLBACK_UNEXPECTED_ERROR + +# We need to keep this function reference alive: +# if they get GC'd while in use then UniFFI internals could attempt to call a function +# that is in freed memory. +# That would be...uh...bad. Yeah, that's the word. Bad. +foreignCallbackCallbackInterfaceEventListener = _UNIFFI_FOREIGN_CALLBACK_T(py_foreignCallbackCallbackInterfaceEventListener) +_rust_call(lambda err: _UniffiLib.uniffi_pubkycore_fn_init_callback_eventlistener(foreignCallbackCallbackInterfaceEventListener, err)) + +# The _UniffiConverter which transforms the Callbacks in to Handles to pass to Rust. +_UniffiConverterCallbackInterfaceEventListener = _UniffiConverterCallbackInterface(foreignCallbackCallbackInterfaceEventListener) + + + +class _UniffiConverterSequenceString(_UniffiConverterRustBuffer): + @classmethod + def write(cls, value, buf): + items = len(value) + buf.write_i32(items) + for item in value: + _UniffiConverterString.write(item, buf) + + @classmethod + def read(cls, buf): + count = buf.read_i32() + if count < 0: + raise InternalError("Unexpected negative sequence length") + + return [ + _UniffiConverterString.read(buf) for i in range(count) + ] + +def auth(url: "str",secret_key: "str") -> "typing.List[str]": + + + return _UniffiConverterSequenceString.lift(_rust_call(_UniffiLib.uniffi_pubkycore_fn_func_auth, + _UniffiConverterString.lower(url), + _UniffiConverterString.lower(secret_key))) + + +def create_recovery_file(secret_key: "str",passphrase: "str") -> "typing.List[str]": + + + return _UniffiConverterSequenceString.lift(_rust_call(_UniffiLib.uniffi_pubkycore_fn_func_create_recovery_file, + _UniffiConverterString.lower(secret_key), + _UniffiConverterString.lower(passphrase))) + + +def decrypt_recovery_file(recovery_file: "str",passphrase: "str") -> "typing.List[str]": + + + return _UniffiConverterSequenceString.lift(_rust_call(_UniffiLib.uniffi_pubkycore_fn_func_decrypt_recovery_file, + _UniffiConverterString.lower(recovery_file), + _UniffiConverterString.lower(passphrase))) + + +def delete_file(url: "str") -> "typing.List[str]": + + return _UniffiConverterSequenceString.lift(_rust_call(_UniffiLib.uniffi_pubkycore_fn_func_delete_file, + _UniffiConverterString.lower(url))) + + +def generate_secret_key() -> "typing.List[str]": + return _UniffiConverterSequenceString.lift(_rust_call(_UniffiLib.uniffi_pubkycore_fn_func_generate_secret_key,)) + + +def get(url: "str") -> "typing.List[str]": + + return _UniffiConverterSequenceString.lift(_rust_call(_UniffiLib.uniffi_pubkycore_fn_func_get, + _UniffiConverterString.lower(url))) + + +def get_public_key_from_secret_key(secret_key: "str") -> "typing.List[str]": + + return _UniffiConverterSequenceString.lift(_rust_call(_UniffiLib.uniffi_pubkycore_fn_func_get_public_key_from_secret_key, + _UniffiConverterString.lower(secret_key))) + + +def list(url: "str") -> "typing.List[str]": + + return _UniffiConverterSequenceString.lift(_rust_call(_UniffiLib.uniffi_pubkycore_fn_func_list, + _UniffiConverterString.lower(url))) + + +def parse_auth_url(url: "str") -> "typing.List[str]": + + return _UniffiConverterSequenceString.lift(_rust_call(_UniffiLib.uniffi_pubkycore_fn_func_parse_auth_url, + _UniffiConverterString.lower(url))) + + +def publish(record_name: "str",record_content: "str",secret_key: "str") -> "typing.List[str]": + + + + return _UniffiConverterSequenceString.lift(_rust_call(_UniffiLib.uniffi_pubkycore_fn_func_publish, + _UniffiConverterString.lower(record_name), + _UniffiConverterString.lower(record_content), + _UniffiConverterString.lower(secret_key))) + + +def publish_https(record_name: "str",target: "str",secret_key: "str") -> "typing.List[str]": + + + + return _UniffiConverterSequenceString.lift(_rust_call(_UniffiLib.uniffi_pubkycore_fn_func_publish_https, + _UniffiConverterString.lower(record_name), + _UniffiConverterString.lower(target), + _UniffiConverterString.lower(secret_key))) + + +def put(url: "str",content: "str") -> "typing.List[str]": + + + return _UniffiConverterSequenceString.lift(_rust_call(_UniffiLib.uniffi_pubkycore_fn_func_put, + _UniffiConverterString.lower(url), + _UniffiConverterString.lower(content))) + + +def remove_event_listener(): + _rust_call(_UniffiLib.uniffi_pubkycore_fn_func_remove_event_listener,) + + +def resolve(public_key: "str") -> "typing.List[str]": + + return _UniffiConverterSequenceString.lift(_rust_call(_UniffiLib.uniffi_pubkycore_fn_func_resolve, + _UniffiConverterString.lower(public_key))) + + +def resolve_https(public_key: "str") -> "typing.List[str]": + + return _UniffiConverterSequenceString.lift(_rust_call(_UniffiLib.uniffi_pubkycore_fn_func_resolve_https, + _UniffiConverterString.lower(public_key))) + + +def session(pubky: "str") -> "typing.List[str]": + + return _UniffiConverterSequenceString.lift(_rust_call(_UniffiLib.uniffi_pubkycore_fn_func_session, + _UniffiConverterString.lower(pubky))) + + +def set_event_listener(listener: "EventListener"): + + _rust_call(_UniffiLib.uniffi_pubkycore_fn_func_set_event_listener, + _UniffiConverterCallbackInterfaceEventListener.lower(listener)) + + +def sign_in(secret_key: "str") -> "typing.List[str]": + + return _UniffiConverterSequenceString.lift(_rust_call(_UniffiLib.uniffi_pubkycore_fn_func_sign_in, + _UniffiConverterString.lower(secret_key))) + + +def sign_out(secret_key: "str") -> "typing.List[str]": + + return _UniffiConverterSequenceString.lift(_rust_call(_UniffiLib.uniffi_pubkycore_fn_func_sign_out, + _UniffiConverterString.lower(secret_key))) + + +def sign_up(secret_key: "str",homeserver: "str") -> "typing.List[str]": + + + return _UniffiConverterSequenceString.lift(_rust_call(_UniffiLib.uniffi_pubkycore_fn_func_sign_up, + _UniffiConverterString.lower(secret_key), + _UniffiConverterString.lower(homeserver))) + + +def switch_network(use_testnet: "bool") -> "typing.List[str]": + + return _UniffiConverterSequenceString.lift(_rust_call(_UniffiLib.uniffi_pubkycore_fn_func_switch_network, + _UniffiConverterBool.lower(use_testnet))) + + +__all__ = [ + "InternalError", + "auth", + "create_recovery_file", + "decrypt_recovery_file", + "delete_file", + "generate_secret_key", + "get", + "get_public_key_from_secret_key", + "list", + "parse_auth_url", + "publish", + "publish_https", + "put", + "remove_event_listener", + "resolve", + "resolve_https", + "session", + "set_event_listener", + "sign_in", + "sign_out", + "sign_up", + "switch_network", + "EventNotifier", + "EventListener", +] + diff --git a/bindings/python/setup.py b/bindings/python/setup.py new file mode 100644 index 0000000..6ec530a --- /dev/null +++ b/bindings/python/setup.py @@ -0,0 +1,23 @@ +from setuptools import setup, find_packages + +setup( + name="pubkycore", + version="0.1.0", + packages=find_packages(), + package_data={ + "pubkycore": ["*.so", "*.dylib", "*.dll"], + }, + install_requires=[], + author="Pubky", + author_email="", + description="Python bindings for the Pubky Mobile SDK", + long_description=open("README.md").read(), + long_description_content_type="text/markdown", + url="", + classifiers=[ + "Programming Language :: Python :: 3", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", + ], + python_requires=">=3.6", +) diff --git a/build.sh b/build.sh index 733a7a0..3e2362b 100755 --- a/build.sh +++ b/build.sh @@ -8,11 +8,14 @@ case "$1" in "android") ./build_android.sh ;; + "python") + ./build_python.sh + ;; "all") - ./build_ios.sh && ./build_android.sh + ./build_ios.sh && ./build_android.sh && ./build_python.sh ;; *) - echo "Usage: $0 {ios|android|all}" + echo "Usage: $0 {ios|android|python|all}" exit 1 ;; esac \ No newline at end of file diff --git a/build_android.sh b/build_android.sh index b220be5..4694acd 100755 --- a/build_android.sh +++ b/build_android.sh @@ -55,7 +55,7 @@ cargo ndk \ # Generate Kotlin bindings echo "Generating Kotlin bindings..." -LIBRARY_PATH="./target/release/libpubkymobile.dylib" +LIBRARY_PATH="./target/release/libpubkycore.dylib" # Check if the library file exists if [ ! -f "$LIBRARY_PATH" ]; then @@ -76,7 +76,7 @@ cargo run --bin uniffi-bindgen generate \ # Move the Kotlin file from the nested directory to the final location echo "Moving Kotlin file to final location..." -find "$TMP_DIR" -name "pubkymobile.kt" -exec mv {} "$BASE_DIR/" \; +find "$TMP_DIR" -name "pubkycore.kt" -exec mv {} "$BASE_DIR/" \; # Clean up temp directory and any remaining uniffi directories echo "Cleaning up temporary files..." @@ -84,7 +84,7 @@ rm -rf "$TMP_DIR" rm -rf "$BASE_DIR/uniffi" # Verify the file was moved correctly -if [ ! -f "$BASE_DIR/pubkymobile.kt" ]; then +if [ ! -f "$BASE_DIR/pubkycore.kt" ]; then echo "Error: Kotlin bindings were not moved correctly" echo "Contents of $BASE_DIR:" ls -la "$BASE_DIR" diff --git a/build_ios.sh b/build_ios.sh index 7a2f6e0..c2b11a2 100755 --- a/build_ios.sh +++ b/build_ios.sh @@ -40,30 +40,30 @@ cargo build --release --target=aarch64-apple-ios # Generate Swift bindings echo "Generating Swift bindings..." # First, ensure any existing generated files are removed -rm -rf ./bindings/ios/pubkymobile.swift -rm -rf ./bindings/ios/pubkymobileFFI.h -rm -rf ./bindings/ios/pubkymobileFFI.modulemap +rm -rf ./bindings/ios/pubkycore.swift +rm -rf ./bindings/ios/pubkycoreFFI.h +rm -rf ./bindings/ios/pubkycoreFFI.modulemap rm -rf ./bindings/ios/Headers rm -rf ./bindings/ios/ios-arm64 rm -rf ./bindings/ios/ios-arm64-sim cargo run --bin uniffi-bindgen generate \ - --library ./target/release/libpubkymobile.dylib \ + --library ./target/release/libpubkycore.dylib \ --language swift \ --out-dir ./bindings/ios \ || { echo "Failed to generate Swift bindings"; exit 1; } # Handle modulemap file echo "Handling modulemap file..." -if [ -f bindings/ios/pubkymobileFFI.modulemap ]; then - mv bindings/ios/pubkymobileFFI.modulemap bindings/ios/module.modulemap +if [ -f bindings/ios/pubkycoreFFI.modulemap ]; then + mv bindings/ios/pubkycoreFFI.modulemap bindings/ios/module.modulemap else echo "Warning: modulemap file not found" fi # Clean up any existing XCFramework and temporary directories echo "Cleaning up existing XCFramework..." -rm -rf "bindings/ios/PubkyMobile.xcframework" +rm -rf "bindings/ios/PubkyCore.xcframework" rm -rf "bindings/ios/Headers" rm -rf "bindings/ios/ios-arm64" rm -rf "bindings/ios/ios-arm64-sim" @@ -75,17 +75,17 @@ mkdir -p "bindings/ios/ios-arm64-sim/Headers" # Copy headers to architecture-specific directories echo "Copying headers to architecture directories..." -cp bindings/ios/pubkymobileFFI.h "bindings/ios/ios-arm64/Headers/" +cp bindings/ios/pubkycoreFFI.h "bindings/ios/ios-arm64/Headers/" cp bindings/ios/module.modulemap "bindings/ios/ios-arm64/Headers/" -cp bindings/ios/pubkymobileFFI.h "bindings/ios/ios-arm64-sim/Headers/" +cp bindings/ios/pubkycoreFFI.h "bindings/ios/ios-arm64-sim/Headers/" cp bindings/ios/module.modulemap "bindings/ios/ios-arm64-sim/Headers/" # Create XCFramework echo "Creating XCFramework..." xcodebuild -create-xcframework \ - -library ./target/aarch64-apple-ios-sim/release/libpubkymobile.a -headers "bindings/ios/ios-arm64-sim/Headers" \ - -library ./target/aarch64-apple-ios/release/libpubkymobile.a -headers "bindings/ios/ios-arm64/Headers" \ - -output "bindings/ios/PubkyMobile.xcframework" \ + -library ./target/aarch64-apple-ios-sim/release/libpubkycore.a -headers "bindings/ios/ios-arm64-sim/Headers" \ + -library ./target/aarch64-apple-ios/release/libpubkycore.a -headers "bindings/ios/ios-arm64/Headers" \ + -output "bindings/ios/PubkyCore.xcframework" \ || { echo "Failed to create XCFramework"; exit 1; } # Clean up temporary directories diff --git a/build_python.sh b/build_python.sh new file mode 100755 index 0000000..08f672c --- /dev/null +++ b/build_python.sh @@ -0,0 +1,121 @@ +#!/bin/bash + +set -e # Exit immediately if a command exits with a non-zero status. + +echo "Starting Python build process..." + +# Define output directories +BASE_DIR="./bindings/python" +PACKAGE_DIR="$BASE_DIR/pubkycore" + +# Create output directories +mkdir -p "$BASE_DIR" +mkdir -p "$PACKAGE_DIR" + +# Remove previous build +echo "Removing previous build..." +# shellcheck disable=SC2115 +rm -rf "$PACKAGE_DIR"/* + +# Cargo Build +echo "Building Rust libraries..." +cargo build && cd pubky && cargo build && cd pubky && cargo build && cd ../ && cd pubky-common && cargo build && cd ../ && cd pubky-homeserver && cargo build && cd ../../ + +# Modify Cargo.toml to ensure correct crate type +echo "Updating Cargo.toml..." +sed -i '' 's/crate_type = .*/crate_type = ["cdylib"]/' Cargo.toml + +# Build release +echo "Building release version..." +cargo build --release + +# Generate Python bindings +echo "Generating Python bindings..." +LIBRARY_PATH="./target/release/libpubkycore.dylib" + +# Check if the library file exists +if [ ! -f "$LIBRARY_PATH" ]; then + echo "Error: Library file not found at $LIBRARY_PATH" + echo "Available files in target/release:" + ls -l ./target/release/ + exit 1 +fi + +# Generate the Python bindings +cargo run --bin uniffi-bindgen generate \ + --library "$LIBRARY_PATH" \ + --language python \ + --out-dir "$PACKAGE_DIR" + +# Create __init__.py +touch "$PACKAGE_DIR/__init__.py" + +# Create setup.py +cat > "$BASE_DIR/setup.py" << EOL +from setuptools import setup, find_packages + +setup( + name="pubkycore", + version="0.1.0", + packages=find_packages(), + package_data={ + "pubkycore": ["*.so", "*.dylib", "*.dll"], + }, + install_requires=[], + author="Pubky", + author_email="", + description="Python bindings for the Pubky Mobile SDK", + long_description=open("README.md").read(), + long_description_content_type="text/markdown", + url="", + classifiers=[ + "Programming Language :: Python :: 3", + "License :: OSI Approved :: MIT License", + "Operating System :: OS Independent", + ], + python_requires=">=3.6", +) +EOL + +# Create README.md +cat > "$BASE_DIR/README.md" << EOL +# Pubky Mobile Python Bindings + +Python bindings for the Pubky Mobile SDK. + +## Installation + +\`\`\`bash +pip install . +\`\`\` + +## Usage + +\`\`\`python +from pubkycore import * + +# Generate a new keypair +result = generate_secret_key() +if result[0] == "success": + print(f"Generated key: {result[1]}") +else: + print(f"Error: {result[1]}") +\`\`\` +EOL + +# Copy necessary library files +echo "Copying library files..." +case "$(uname)" in + "Darwin") + cp "$LIBRARY_PATH" "$PACKAGE_DIR/" + ;; + "Linux") + cp "./target/release/libpubkycore.so" "$PACKAGE_DIR/" + ;; + "MINGW"*|"MSYS"*|"CYGWIN"*) + cp "./target/release/pubkycore.dll" "$PACKAGE_DIR/" + ;; +esac + +echo "Python build process completed successfully!" +echo "To install the package, cd into $BASE_DIR and run: pip install ." \ No newline at end of file diff --git a/tests/lib_tests.rs b/tests/lib_tests.rs index 6af481a..b3ebfc0 100644 --- a/tests/lib_tests.rs +++ b/tests/lib_tests.rs @@ -1,4 +1,4 @@ -use pubkymobile::*; +use pubkycore::*; use tokio; use base64;