From 8f96994d53b7fd94ec2423cdb5339f78a11baef9 Mon Sep 17 00:00:00 2001 From: Christian Decker Date: Wed, 13 May 2026 17:52:57 +0200 Subject: [PATCH 1/2] sdk: Add stable numeric error codes with i18n interpolation values Replace tuple-style error variants with named-field variants carrying code (i32), message (String), and values (HashMap). This allows host-language callers to look up translated error strings by numeric code and interpolate structured values, rather than parsing English messages. Error code ranges: 1000-1099 node identity, 1100-1199 credentials, 2000-2099 RPC, 3000-3099 input validation, 9000-9099 generic. Co-Authored-By: Claude Opus 4.6 (1M context) --- libs/gl-sdk/bindings/glsdk.py | 2388 +++++++++++++++++++++++++++++++++ libs/gl-sdk/glsdk/glsdk.py | 787 ++++++++++- libs/gl-sdk/src/lib.rs | 131 +- libs/gl-sdk/src/node.rs | 16 +- libs/gl-sdk/src/scheduler.rs | 12 +- libs/gl-sdk/src/signer.rs | 6 +- 6 files changed, 3265 insertions(+), 75 deletions(-) create mode 100644 libs/gl-sdk/bindings/glsdk.py diff --git a/libs/gl-sdk/bindings/glsdk.py b/libs/gl-sdk/bindings/glsdk.py new file mode 100644 index 000000000..c59b1cff4 --- /dev/null +++ b/libs/gl-sdk/bindings/glsdk.py @@ -0,0 +1,2388 @@ + + +# 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. + +from __future__ import annotations +import os +import sys +import ctypes +import enum +import struct +import contextlib +import datetime +import threading +import itertools +import traceback +import typing +import platform + +# Used for default argument values +_DEFAULT = object() # type: typing.Any + + +class _UniffiRustBuffer(ctypes.Structure): + _fields_ = [ + ("capacity", ctypes.c_uint64), + ("len", ctypes.c_uint64), + ("data", ctypes.POINTER(ctypes.c_char)), + ] + + @staticmethod + def default(): + return _UniffiRustBuffer(0, 0, None) + + @staticmethod + def alloc(size): + return _uniffi_rust_call(_UniffiLib.ffi_glsdk_rustbuffer_alloc, size) + + @staticmethod + def reserve(rbuf, additional): + return _uniffi_rust_call(_UniffiLib.ffi_glsdk_rustbuffer_reserve, rbuf, additional) + + def free(self): + return _uniffi_rust_call(_UniffiLib.ffi_glsdk_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") + +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_UNEXPECTED_ERROR = 2 + + @staticmethod + def default(): + return _UniffiRustCallStatus(code=_UniffiRustCallStatus.CALL_SUCCESS, error_buf=_UniffiRustBuffer.default()) + + 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_UNEXPECTED_ERROR: + return "_UniffiRustCallStatus(CALL_UNEXPECTED_ERROR)" + else: + return "_UniffiRustCallStatus()" + +def _uniffi_rust_call(fn, *args): + # Call a rust function + return _uniffi_rust_call_with_error(None, fn, *args) + +def _uniffi_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.default() + + 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("_uniffi_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_UNEXPECTED_ERROR: + # 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)) + +def _uniffi_trait_interface_call(call_status, make_call, write_return_value): + try: + return write_return_value(make_call()) + except Exception as e: + call_status.code = _UniffiRustCallStatus.CALL_UNEXPECTED_ERROR + call_status.error_buf = _UniffiConverterString.lower(repr(e)) + +def _uniffi_trait_interface_call_with_error(call_status, make_call, write_return_value, error_type, lower_error): + try: + try: + return write_return_value(make_call()) + except error_type as e: + call_status.code = _UniffiRustCallStatus.CALL_ERROR + call_status.error_buf = lower_error(e) + except Exception as e: + call_status.code = _UniffiRustCallStatus.CALL_UNEXPECTED_ERROR + call_status.error_buf = _UniffiConverterString.lower(repr(e)) +class _UniffiHandleMap: + """ + A map where inserting, getting and removing data is synchronized with a lock. + """ + + def __init__(self): + # type Handle = int + self._map = {} # type: Dict[Handle, Any] + self._lock = threading.Lock() + self._counter = itertools.count() + + def insert(self, obj): + with self._lock: + handle = next(self._counter) + self._map[handle] = obj + return handle + + def get(self, handle): + try: + with self._lock: + return self._map[handle] + except KeyError: + raise InternalError("_UniffiHandleMap.get: Invalid handle") + + def remove(self, handle): + try: + with self._lock: + return self._map.pop(handle) + except KeyError: + raise InternalError("_UniffiHandleMap.remove: Invalid handle") + + def __len__(self): + return len(self._map) +# Types conforming to `_UniffiConverterPrimitive` pass themselves directly over the FFI. +class _UniffiConverterPrimitive: + @classmethod + def lift(cls, value): + return value + + @classmethod + def lower(cls, value): + return value + +class _UniffiConverterPrimitiveInt(_UniffiConverterPrimitive): + @classmethod + def check_lower(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)) + +class _UniffiConverterPrimitiveFloat(_UniffiConverterPrimitive): + @classmethod + def check_lower(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__)) + +# 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 + +""" +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_uint64, 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("glsdk") + 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 = 29 + # Get the scaffolding contract version by calling the into the dylib + scaffolding_contract_version = lib.ffi_glsdk_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_glsdk_checksum_method_credentials_save() != 26677: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_method_handle_stop() != 36432: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_method_node_onchain_receive() != 21676: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_method_node_onchain_send() != 51884: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_method_node_receive() != 24722: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_method_node_send() != 30141: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_method_node_stop() != 20186: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_method_scheduler_recover() != 55514: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_method_scheduler_register() != 20821: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_method_signer_authenticate() != 55935: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_method_signer_node_id() != 43931: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_method_signer_start() != 9404: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_constructor_credentials_load() != 25306: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_constructor_node_new() != 7003: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_constructor_scheduler_new() != 15239: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_constructor_signer_new() != 62159: + 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() +_UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK = ctypes.CFUNCTYPE(None,ctypes.c_uint64,ctypes.c_int8, +) +_UNIFFI_FOREIGN_FUTURE_FREE = ctypes.CFUNCTYPE(None,ctypes.c_uint64, +) +_UNIFFI_CALLBACK_INTERFACE_FREE = ctypes.CFUNCTYPE(None,ctypes.c_uint64, +) +class _UniffiForeignFuture(ctypes.Structure): + _fields_ = [ + ("handle", ctypes.c_uint64), + ("free", _UNIFFI_FOREIGN_FUTURE_FREE), + ] +class _UniffiForeignFutureStructU8(ctypes.Structure): + _fields_ = [ + ("return_value", ctypes.c_uint8), + ("call_status", _UniffiRustCallStatus), + ] +_UNIFFI_FOREIGN_FUTURE_COMPLETE_U8 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiForeignFutureStructU8, +) +class _UniffiForeignFutureStructI8(ctypes.Structure): + _fields_ = [ + ("return_value", ctypes.c_int8), + ("call_status", _UniffiRustCallStatus), + ] +_UNIFFI_FOREIGN_FUTURE_COMPLETE_I8 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiForeignFutureStructI8, +) +class _UniffiForeignFutureStructU16(ctypes.Structure): + _fields_ = [ + ("return_value", ctypes.c_uint16), + ("call_status", _UniffiRustCallStatus), + ] +_UNIFFI_FOREIGN_FUTURE_COMPLETE_U16 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiForeignFutureStructU16, +) +class _UniffiForeignFutureStructI16(ctypes.Structure): + _fields_ = [ + ("return_value", ctypes.c_int16), + ("call_status", _UniffiRustCallStatus), + ] +_UNIFFI_FOREIGN_FUTURE_COMPLETE_I16 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiForeignFutureStructI16, +) +class _UniffiForeignFutureStructU32(ctypes.Structure): + _fields_ = [ + ("return_value", ctypes.c_uint32), + ("call_status", _UniffiRustCallStatus), + ] +_UNIFFI_FOREIGN_FUTURE_COMPLETE_U32 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiForeignFutureStructU32, +) +class _UniffiForeignFutureStructI32(ctypes.Structure): + _fields_ = [ + ("return_value", ctypes.c_int32), + ("call_status", _UniffiRustCallStatus), + ] +_UNIFFI_FOREIGN_FUTURE_COMPLETE_I32 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiForeignFutureStructI32, +) +class _UniffiForeignFutureStructU64(ctypes.Structure): + _fields_ = [ + ("return_value", ctypes.c_uint64), + ("call_status", _UniffiRustCallStatus), + ] +_UNIFFI_FOREIGN_FUTURE_COMPLETE_U64 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiForeignFutureStructU64, +) +class _UniffiForeignFutureStructI64(ctypes.Structure): + _fields_ = [ + ("return_value", ctypes.c_int64), + ("call_status", _UniffiRustCallStatus), + ] +_UNIFFI_FOREIGN_FUTURE_COMPLETE_I64 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiForeignFutureStructI64, +) +class _UniffiForeignFutureStructF32(ctypes.Structure): + _fields_ = [ + ("return_value", ctypes.c_float), + ("call_status", _UniffiRustCallStatus), + ] +_UNIFFI_FOREIGN_FUTURE_COMPLETE_F32 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiForeignFutureStructF32, +) +class _UniffiForeignFutureStructF64(ctypes.Structure): + _fields_ = [ + ("return_value", ctypes.c_double), + ("call_status", _UniffiRustCallStatus), + ] +_UNIFFI_FOREIGN_FUTURE_COMPLETE_F64 = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiForeignFutureStructF64, +) +class _UniffiForeignFutureStructPointer(ctypes.Structure): + _fields_ = [ + ("return_value", ctypes.c_void_p), + ("call_status", _UniffiRustCallStatus), + ] +_UNIFFI_FOREIGN_FUTURE_COMPLETE_POINTER = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiForeignFutureStructPointer, +) +class _UniffiForeignFutureStructRustBuffer(ctypes.Structure): + _fields_ = [ + ("return_value", _UniffiRustBuffer), + ("call_status", _UniffiRustCallStatus), + ] +_UNIFFI_FOREIGN_FUTURE_COMPLETE_RUST_BUFFER = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiForeignFutureStructRustBuffer, +) +class _UniffiForeignFutureStructVoid(ctypes.Structure): + _fields_ = [ + ("call_status", _UniffiRustCallStatus), + ] +_UNIFFI_FOREIGN_FUTURE_COMPLETE_VOID = ctypes.CFUNCTYPE(None,ctypes.c_uint64,_UniffiForeignFutureStructVoid, +) +_UniffiLib.uniffi_glsdk_fn_clone_credentials.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_clone_credentials.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_free_credentials.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_free_credentials.restype = None +_UniffiLib.uniffi_glsdk_fn_constructor_credentials_load.argtypes = ( + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_constructor_credentials_load.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_method_credentials_save.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_credentials_save.restype = _UniffiRustBuffer +_UniffiLib.uniffi_glsdk_fn_clone_handle.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_clone_handle.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_free_handle.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_free_handle.restype = None +_UniffiLib.uniffi_glsdk_fn_method_handle_stop.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_handle_stop.restype = None +_UniffiLib.uniffi_glsdk_fn_clone_node.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_clone_node.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_free_node.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_free_node.restype = None +_UniffiLib.uniffi_glsdk_fn_constructor_node_new.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_constructor_node_new.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_method_node_onchain_receive.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_node_onchain_receive.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_method_node_onchain_send.argtypes = ( + ctypes.c_void_p, + _UniffiRustBuffer, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_node_onchain_send.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_method_node_receive.argtypes = ( + ctypes.c_void_p, + _UniffiRustBuffer, + _UniffiRustBuffer, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_node_receive.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_method_node_send.argtypes = ( + ctypes.c_void_p, + _UniffiRustBuffer, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_node_send.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_method_node_stop.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_node_stop.restype = None +_UniffiLib.uniffi_glsdk_fn_clone_onchainreceiveresponse.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_clone_onchainreceiveresponse.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_free_onchainreceiveresponse.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_free_onchainreceiveresponse.restype = None +_UniffiLib.uniffi_glsdk_fn_clone_onchainsendresponse.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_clone_onchainsendresponse.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_free_onchainsendresponse.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_free_onchainsendresponse.restype = None +_UniffiLib.uniffi_glsdk_fn_clone_receiveresponse.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_clone_receiveresponse.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_free_receiveresponse.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_free_receiveresponse.restype = None +_UniffiLib.uniffi_glsdk_fn_clone_scheduler.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_clone_scheduler.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_free_scheduler.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_free_scheduler.restype = None +_UniffiLib.uniffi_glsdk_fn_constructor_scheduler_new.argtypes = ( + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_constructor_scheduler_new.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_method_scheduler_recover.argtypes = ( + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_scheduler_recover.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_method_scheduler_register.argtypes = ( + ctypes.c_void_p, + ctypes.c_void_p, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_scheduler_register.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_clone_sendresponse.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_clone_sendresponse.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_free_sendresponse.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_free_sendresponse.restype = None +_UniffiLib.uniffi_glsdk_fn_clone_signer.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_clone_signer.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_free_signer.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_free_signer.restype = None +_UniffiLib.uniffi_glsdk_fn_constructor_signer_new.argtypes = ( + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_constructor_signer_new.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_method_signer_authenticate.argtypes = ( + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_signer_authenticate.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_method_signer_node_id.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_signer_node_id.restype = _UniffiRustBuffer +_UniffiLib.uniffi_glsdk_fn_method_signer_start.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_signer_start.restype = ctypes.c_void_p +_UniffiLib.ffi_glsdk_rustbuffer_alloc.argtypes = ( + ctypes.c_uint64, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_glsdk_rustbuffer_alloc.restype = _UniffiRustBuffer +_UniffiLib.ffi_glsdk_rustbuffer_from_bytes.argtypes = ( + _UniffiForeignBytes, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_glsdk_rustbuffer_from_bytes.restype = _UniffiRustBuffer +_UniffiLib.ffi_glsdk_rustbuffer_free.argtypes = ( + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_glsdk_rustbuffer_free.restype = None +_UniffiLib.ffi_glsdk_rustbuffer_reserve.argtypes = ( + _UniffiRustBuffer, + ctypes.c_uint64, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_glsdk_rustbuffer_reserve.restype = _UniffiRustBuffer +_UniffiLib.ffi_glsdk_rust_future_poll_u8.argtypes = ( + ctypes.c_uint64, + _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK, + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_poll_u8.restype = None +_UniffiLib.ffi_glsdk_rust_future_cancel_u8.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_cancel_u8.restype = None +_UniffiLib.ffi_glsdk_rust_future_free_u8.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_free_u8.restype = None +_UniffiLib.ffi_glsdk_rust_future_complete_u8.argtypes = ( + ctypes.c_uint64, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_glsdk_rust_future_complete_u8.restype = ctypes.c_uint8 +_UniffiLib.ffi_glsdk_rust_future_poll_i8.argtypes = ( + ctypes.c_uint64, + _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK, + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_poll_i8.restype = None +_UniffiLib.ffi_glsdk_rust_future_cancel_i8.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_cancel_i8.restype = None +_UniffiLib.ffi_glsdk_rust_future_free_i8.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_free_i8.restype = None +_UniffiLib.ffi_glsdk_rust_future_complete_i8.argtypes = ( + ctypes.c_uint64, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_glsdk_rust_future_complete_i8.restype = ctypes.c_int8 +_UniffiLib.ffi_glsdk_rust_future_poll_u16.argtypes = ( + ctypes.c_uint64, + _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK, + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_poll_u16.restype = None +_UniffiLib.ffi_glsdk_rust_future_cancel_u16.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_cancel_u16.restype = None +_UniffiLib.ffi_glsdk_rust_future_free_u16.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_free_u16.restype = None +_UniffiLib.ffi_glsdk_rust_future_complete_u16.argtypes = ( + ctypes.c_uint64, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_glsdk_rust_future_complete_u16.restype = ctypes.c_uint16 +_UniffiLib.ffi_glsdk_rust_future_poll_i16.argtypes = ( + ctypes.c_uint64, + _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK, + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_poll_i16.restype = None +_UniffiLib.ffi_glsdk_rust_future_cancel_i16.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_cancel_i16.restype = None +_UniffiLib.ffi_glsdk_rust_future_free_i16.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_free_i16.restype = None +_UniffiLib.ffi_glsdk_rust_future_complete_i16.argtypes = ( + ctypes.c_uint64, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_glsdk_rust_future_complete_i16.restype = ctypes.c_int16 +_UniffiLib.ffi_glsdk_rust_future_poll_u32.argtypes = ( + ctypes.c_uint64, + _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK, + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_poll_u32.restype = None +_UniffiLib.ffi_glsdk_rust_future_cancel_u32.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_cancel_u32.restype = None +_UniffiLib.ffi_glsdk_rust_future_free_u32.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_free_u32.restype = None +_UniffiLib.ffi_glsdk_rust_future_complete_u32.argtypes = ( + ctypes.c_uint64, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_glsdk_rust_future_complete_u32.restype = ctypes.c_uint32 +_UniffiLib.ffi_glsdk_rust_future_poll_i32.argtypes = ( + ctypes.c_uint64, + _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK, + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_poll_i32.restype = None +_UniffiLib.ffi_glsdk_rust_future_cancel_i32.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_cancel_i32.restype = None +_UniffiLib.ffi_glsdk_rust_future_free_i32.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_free_i32.restype = None +_UniffiLib.ffi_glsdk_rust_future_complete_i32.argtypes = ( + ctypes.c_uint64, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_glsdk_rust_future_complete_i32.restype = ctypes.c_int32 +_UniffiLib.ffi_glsdk_rust_future_poll_u64.argtypes = ( + ctypes.c_uint64, + _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK, + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_poll_u64.restype = None +_UniffiLib.ffi_glsdk_rust_future_cancel_u64.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_cancel_u64.restype = None +_UniffiLib.ffi_glsdk_rust_future_free_u64.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_free_u64.restype = None +_UniffiLib.ffi_glsdk_rust_future_complete_u64.argtypes = ( + ctypes.c_uint64, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_glsdk_rust_future_complete_u64.restype = ctypes.c_uint64 +_UniffiLib.ffi_glsdk_rust_future_poll_i64.argtypes = ( + ctypes.c_uint64, + _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK, + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_poll_i64.restype = None +_UniffiLib.ffi_glsdk_rust_future_cancel_i64.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_cancel_i64.restype = None +_UniffiLib.ffi_glsdk_rust_future_free_i64.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_free_i64.restype = None +_UniffiLib.ffi_glsdk_rust_future_complete_i64.argtypes = ( + ctypes.c_uint64, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_glsdk_rust_future_complete_i64.restype = ctypes.c_int64 +_UniffiLib.ffi_glsdk_rust_future_poll_f32.argtypes = ( + ctypes.c_uint64, + _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK, + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_poll_f32.restype = None +_UniffiLib.ffi_glsdk_rust_future_cancel_f32.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_cancel_f32.restype = None +_UniffiLib.ffi_glsdk_rust_future_free_f32.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_free_f32.restype = None +_UniffiLib.ffi_glsdk_rust_future_complete_f32.argtypes = ( + ctypes.c_uint64, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_glsdk_rust_future_complete_f32.restype = ctypes.c_float +_UniffiLib.ffi_glsdk_rust_future_poll_f64.argtypes = ( + ctypes.c_uint64, + _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK, + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_poll_f64.restype = None +_UniffiLib.ffi_glsdk_rust_future_cancel_f64.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_cancel_f64.restype = None +_UniffiLib.ffi_glsdk_rust_future_free_f64.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_free_f64.restype = None +_UniffiLib.ffi_glsdk_rust_future_complete_f64.argtypes = ( + ctypes.c_uint64, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_glsdk_rust_future_complete_f64.restype = ctypes.c_double +_UniffiLib.ffi_glsdk_rust_future_poll_pointer.argtypes = ( + ctypes.c_uint64, + _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK, + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_poll_pointer.restype = None +_UniffiLib.ffi_glsdk_rust_future_cancel_pointer.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_cancel_pointer.restype = None +_UniffiLib.ffi_glsdk_rust_future_free_pointer.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_free_pointer.restype = None +_UniffiLib.ffi_glsdk_rust_future_complete_pointer.argtypes = ( + ctypes.c_uint64, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_glsdk_rust_future_complete_pointer.restype = ctypes.c_void_p +_UniffiLib.ffi_glsdk_rust_future_poll_rust_buffer.argtypes = ( + ctypes.c_uint64, + _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK, + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_poll_rust_buffer.restype = None +_UniffiLib.ffi_glsdk_rust_future_cancel_rust_buffer.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_cancel_rust_buffer.restype = None +_UniffiLib.ffi_glsdk_rust_future_free_rust_buffer.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_free_rust_buffer.restype = None +_UniffiLib.ffi_glsdk_rust_future_complete_rust_buffer.argtypes = ( + ctypes.c_uint64, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_glsdk_rust_future_complete_rust_buffer.restype = _UniffiRustBuffer +_UniffiLib.ffi_glsdk_rust_future_poll_void.argtypes = ( + ctypes.c_uint64, + _UNIFFI_RUST_FUTURE_CONTINUATION_CALLBACK, + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_poll_void.restype = None +_UniffiLib.ffi_glsdk_rust_future_cancel_void.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_cancel_void.restype = None +_UniffiLib.ffi_glsdk_rust_future_free_void.argtypes = ( + ctypes.c_uint64, +) +_UniffiLib.ffi_glsdk_rust_future_free_void.restype = None +_UniffiLib.ffi_glsdk_rust_future_complete_void.argtypes = ( + ctypes.c_uint64, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.ffi_glsdk_rust_future_complete_void.restype = None +_UniffiLib.uniffi_glsdk_checksum_method_credentials_save.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_credentials_save.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_method_handle_stop.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_handle_stop.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_method_node_onchain_receive.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_node_onchain_receive.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_method_node_onchain_send.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_node_onchain_send.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_method_node_receive.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_node_receive.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_method_node_send.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_node_send.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_method_node_stop.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_node_stop.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_method_scheduler_recover.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_scheduler_recover.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_method_scheduler_register.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_scheduler_register.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_method_signer_authenticate.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_signer_authenticate.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_method_signer_node_id.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_signer_node_id.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_method_signer_start.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_signer_start.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_constructor_credentials_load.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_constructor_credentials_load.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_constructor_node_new.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_constructor_node_new.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_constructor_scheduler_new.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_constructor_scheduler_new.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_constructor_signer_new.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_constructor_signer_new.restype = ctypes.c_uint16 +_UniffiLib.ffi_glsdk_uniffi_contract_version.argtypes = ( +) +_UniffiLib.ffi_glsdk_uniffi_contract_version.restype = ctypes.c_uint32 + +_uniffi_check_contract_api_version(_UniffiLib) +# _uniffi_check_api_checksums(_UniffiLib) + +# Public interface members begin here. + + +class _UniffiConverterInt32(_UniffiConverterPrimitiveInt): + CLASS_NAME = "i32" + VALUE_MIN = -2**31 + VALUE_MAX = 2**31 + + @staticmethod + def read(buf): + return buf.read_i32() + + @staticmethod + def write(value, buf): + buf.write_i32(value) + +class _UniffiConverterUInt64(_UniffiConverterPrimitiveInt): + CLASS_NAME = "u64" + VALUE_MIN = 0 + VALUE_MAX = 2**64 + + @staticmethod + def read(buf): + return buf.read_u64() + + @staticmethod + def write(value, buf): + buf.write_u64(value) + +class _UniffiConverterString: + @staticmethod + def check_lower(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): + 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): + with _UniffiRustBuffer.alloc_with_builder() as builder: + builder.write(value.encode("utf-8")) + return builder.finalize() + +class _UniffiConverterBytes(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + size = buf.read_i32() + if size < 0: + raise InternalError("Unexpected negative byte string length") + return buf.read(size) + + @staticmethod + def check_lower(value): + try: + memoryview(value) + except TypeError: + raise TypeError("a bytes-like object is required, not {!r}".format(type(value).__name__)) + + @staticmethod + def write(value, buf): + buf.write_i32(len(value)) + buf.write(value) + + + + + + + + + + + + + + + + + + + + +# Error +# We want to define each variant as a nested class that's also a subclass, +# which is tricky in Python. To accomplish this we're going to create each +# class separately, then manually add the child classes to the base class's +# __dict__. All of this happens in dummy class to avoid polluting the module +# namespace. +class Error(Exception): + pass + +_UniffiTempError = Error + +class Error: # type: ignore + class DuplicateNode(_UniffiTempError): + def __init__(self, code, message, values): + super().__init__(", ".join([ + "code={!r}".format(code), + "message={!r}".format(message), + "values={!r}".format(values), + ])) + self.code = code + self.message = message + self.values = values + + def __repr__(self): + return "Error.DuplicateNode({})".format(str(self)) + _UniffiTempError.DuplicateNode = DuplicateNode # type: ignore + class NoSuchNode(_UniffiTempError): + def __init__(self, code, message, values): + super().__init__(", ".join([ + "code={!r}".format(code), + "message={!r}".format(message), + "values={!r}".format(values), + ])) + self.code = code + self.message = message + self.values = values + + def __repr__(self): + return "Error.NoSuchNode({})".format(str(self)) + _UniffiTempError.NoSuchNode = NoSuchNode # type: ignore + class UnparseableCreds(_UniffiTempError): + def __init__(self, code, message, values): + super().__init__(", ".join([ + "code={!r}".format(code), + "message={!r}".format(message), + "values={!r}".format(values), + ])) + self.code = code + self.message = message + self.values = values + + def __repr__(self): + return "Error.UnparseableCreds({})".format(str(self)) + _UniffiTempError.UnparseableCreds = UnparseableCreds # type: ignore + class PhraseCorrupted(_UniffiTempError): + def __init__(self, code, message, values): + super().__init__(", ".join([ + "code={!r}".format(code), + "message={!r}".format(message), + "values={!r}".format(values), + ])) + self.code = code + self.message = message + self.values = values + + def __repr__(self): + return "Error.PhraseCorrupted({})".format(str(self)) + _UniffiTempError.PhraseCorrupted = PhraseCorrupted # type: ignore + class Rpc(_UniffiTempError): + def __init__(self, code, message, values): + super().__init__(", ".join([ + "code={!r}".format(code), + "message={!r}".format(message), + "values={!r}".format(values), + ])) + self.code = code + self.message = message + self.values = values + + def __repr__(self): + return "Error.Rpc({})".format(str(self)) + _UniffiTempError.Rpc = Rpc # type: ignore + class Argument(_UniffiTempError): + def __init__(self, code, message, values): + super().__init__(", ".join([ + "code={!r}".format(code), + "message={!r}".format(message), + "values={!r}".format(values), + ])) + self.code = code + self.message = message + self.values = values + + def __repr__(self): + return "Error.Argument({})".format(str(self)) + _UniffiTempError.Argument = Argument # type: ignore + class Other(_UniffiTempError): + def __init__(self, code, message, values): + super().__init__(", ".join([ + "code={!r}".format(code), + "message={!r}".format(message), + "values={!r}".format(values), + ])) + self.code = code + self.message = message + self.values = values + + def __repr__(self): + return "Error.Other({})".format(str(self)) + _UniffiTempError.Other = Other # type: ignore + +Error = _UniffiTempError # type: ignore +del _UniffiTempError + + +class _UniffiConverterTypeError(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + variant = buf.read_i32() + if variant == 1: + return Error.DuplicateNode( + _UniffiConverterInt32.read(buf), + _UniffiConverterString.read(buf), + _UniffiConverterMapStringString.read(buf), + ) + if variant == 2: + return Error.NoSuchNode( + _UniffiConverterInt32.read(buf), + _UniffiConverterString.read(buf), + _UniffiConverterMapStringString.read(buf), + ) + if variant == 3: + return Error.UnparseableCreds( + _UniffiConverterInt32.read(buf), + _UniffiConverterString.read(buf), + _UniffiConverterMapStringString.read(buf), + ) + if variant == 4: + return Error.PhraseCorrupted( + _UniffiConverterInt32.read(buf), + _UniffiConverterString.read(buf), + _UniffiConverterMapStringString.read(buf), + ) + if variant == 5: + return Error.Rpc( + _UniffiConverterInt32.read(buf), + _UniffiConverterString.read(buf), + _UniffiConverterMapStringString.read(buf), + ) + if variant == 6: + return Error.Argument( + _UniffiConverterInt32.read(buf), + _UniffiConverterString.read(buf), + _UniffiConverterMapStringString.read(buf), + ) + if variant == 7: + return Error.Other( + _UniffiConverterInt32.read(buf), + _UniffiConverterString.read(buf), + _UniffiConverterMapStringString.read(buf), + ) + raise InternalError("Raw enum value doesn't match any cases") + + @staticmethod + def check_lower(value): + if isinstance(value, Error.DuplicateNode): + _UniffiConverterInt32.check_lower(value.code) + _UniffiConverterString.check_lower(value.message) + _UniffiConverterMapStringString.check_lower(value.values) + return + if isinstance(value, Error.NoSuchNode): + _UniffiConverterInt32.check_lower(value.code) + _UniffiConverterString.check_lower(value.message) + _UniffiConverterMapStringString.check_lower(value.values) + return + if isinstance(value, Error.UnparseableCreds): + _UniffiConverterInt32.check_lower(value.code) + _UniffiConverterString.check_lower(value.message) + _UniffiConverterMapStringString.check_lower(value.values) + return + if isinstance(value, Error.PhraseCorrupted): + _UniffiConverterInt32.check_lower(value.code) + _UniffiConverterString.check_lower(value.message) + _UniffiConverterMapStringString.check_lower(value.values) + return + if isinstance(value, Error.Rpc): + _UniffiConverterInt32.check_lower(value.code) + _UniffiConverterString.check_lower(value.message) + _UniffiConverterMapStringString.check_lower(value.values) + return + if isinstance(value, Error.Argument): + _UniffiConverterInt32.check_lower(value.code) + _UniffiConverterString.check_lower(value.message) + _UniffiConverterMapStringString.check_lower(value.values) + return + if isinstance(value, Error.Other): + _UniffiConverterInt32.check_lower(value.code) + _UniffiConverterString.check_lower(value.message) + _UniffiConverterMapStringString.check_lower(value.values) + return + + @staticmethod + def write(value, buf): + if isinstance(value, Error.DuplicateNode): + buf.write_i32(1) + _UniffiConverterInt32.write(value.code, buf) + _UniffiConverterString.write(value.message, buf) + _UniffiConverterMapStringString.write(value.values, buf) + if isinstance(value, Error.NoSuchNode): + buf.write_i32(2) + _UniffiConverterInt32.write(value.code, buf) + _UniffiConverterString.write(value.message, buf) + _UniffiConverterMapStringString.write(value.values, buf) + if isinstance(value, Error.UnparseableCreds): + buf.write_i32(3) + _UniffiConverterInt32.write(value.code, buf) + _UniffiConverterString.write(value.message, buf) + _UniffiConverterMapStringString.write(value.values, buf) + if isinstance(value, Error.PhraseCorrupted): + buf.write_i32(4) + _UniffiConverterInt32.write(value.code, buf) + _UniffiConverterString.write(value.message, buf) + _UniffiConverterMapStringString.write(value.values, buf) + if isinstance(value, Error.Rpc): + buf.write_i32(5) + _UniffiConverterInt32.write(value.code, buf) + _UniffiConverterString.write(value.message, buf) + _UniffiConverterMapStringString.write(value.values, buf) + if isinstance(value, Error.Argument): + buf.write_i32(6) + _UniffiConverterInt32.write(value.code, buf) + _UniffiConverterString.write(value.message, buf) + _UniffiConverterMapStringString.write(value.values, buf) + if isinstance(value, Error.Other): + buf.write_i32(7) + _UniffiConverterInt32.write(value.code, buf) + _UniffiConverterString.write(value.message, buf) + _UniffiConverterMapStringString.write(value.values, buf) + + + + + +class Network(enum.Enum): + BITCOIN = 0 + + REGTEST = 1 + + + +class _UniffiConverterTypeNetwork(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + variant = buf.read_i32() + if variant == 1: + return Network.BITCOIN + if variant == 2: + return Network.REGTEST + raise InternalError("Raw enum value doesn't match any cases") + + @staticmethod + def check_lower(value): + if value == Network.BITCOIN: + return + if value == Network.REGTEST: + return + raise ValueError(value) + + @staticmethod + def write(value, buf): + if value == Network.BITCOIN: + buf.write_i32(1) + if value == Network.REGTEST: + buf.write_i32(2) + + + + + + + +class PayStatus(enum.Enum): + COMPLETE = 0 + + PENDING = 1 + + FAILED = 2 + + + +class _UniffiConverterTypePayStatus(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + variant = buf.read_i32() + if variant == 1: + return PayStatus.COMPLETE + if variant == 2: + return PayStatus.PENDING + if variant == 3: + return PayStatus.FAILED + raise InternalError("Raw enum value doesn't match any cases") + + @staticmethod + def check_lower(value): + if value == PayStatus.COMPLETE: + return + if value == PayStatus.PENDING: + return + if value == PayStatus.FAILED: + return + raise ValueError(value) + + @staticmethod + def write(value, buf): + if value == PayStatus.COMPLETE: + buf.write_i32(1) + if value == PayStatus.PENDING: + buf.write_i32(2) + if value == PayStatus.FAILED: + buf.write_i32(3) + + + + + +class _UniffiConverterOptionalUInt64(_UniffiConverterRustBuffer): + @classmethod + def check_lower(cls, value): + if value is not None: + _UniffiConverterUInt64.check_lower(value) + + @classmethod + def write(cls, value, buf): + if value is None: + buf.write_u8(0) + return + + buf.write_u8(1) + _UniffiConverterUInt64.write(value, buf) + + @classmethod + def read(cls, buf): + flag = buf.read_u8() + if flag == 0: + return None + elif flag == 1: + return _UniffiConverterUInt64.read(buf) + else: + raise InternalError("Unexpected flag byte for optional type") + + + +class _UniffiConverterOptionalString(_UniffiConverterRustBuffer): + @classmethod + def check_lower(cls, value): + if value is not None: + _UniffiConverterString.check_lower(value) + + @classmethod + def write(cls, value, buf): + if value is None: + buf.write_u8(0) + return + + buf.write_u8(1) + _UniffiConverterString.write(value, buf) + + @classmethod + def read(cls, buf): + flag = buf.read_u8() + if flag == 0: + return None + elif flag == 1: + return _UniffiConverterString.read(buf) + else: + raise InternalError("Unexpected flag byte for optional type") + + + +class _UniffiConverterMapStringString(_UniffiConverterRustBuffer): + @classmethod + def check_lower(cls, items): + for (key, value) in items.items(): + _UniffiConverterString.check_lower(key) + _UniffiConverterString.check_lower(value) + + @classmethod + def write(cls, items, buf): + buf.write_i32(len(items)) + for (key, value) in items.items(): + _UniffiConverterString.write(key, buf) + _UniffiConverterString.write(value, buf) + + @classmethod + def read(cls, buf): + count = buf.read_i32() + if count < 0: + raise InternalError("Unexpected negative map size") + + # It would be nice to use a dict comprehension, + # but in Python 3.7 and before the evaluation order is not according to spec, + # so we we're reading the value before the key. + # This loop makes the order explicit: first reading the key, then the value. + d = {} + for i in range(count): + key = _UniffiConverterString.read(buf) + val = _UniffiConverterString.read(buf) + d[key] = val + return d + +# objects. +class CredentialsProtocol(typing.Protocol): + """ + `Credentials` is a container for `node_id`, the mTLS client + certificate used to authenticate a client against a node, as well + as the seed secret if present. If no seed is present in the + credentials, then the `Client` will not start a signer in the + background. + """ + + def save(self, ): + raise NotImplementedError +# Credentials is a Rust-only trait - it's a wrapper around a Rust implementation. +class Credentials(): + """ + `Credentials` is a container for `node_id`, the mTLS client + certificate used to authenticate a client against a node, as well + as the seed secret if present. If no seed is present in the + credentials, then the `Client` will not start a signer in the + background. + """ + + _pointer: ctypes.c_void_p + + def __init__(self, *args, **kwargs): + raise ValueError("This class has no default constructor") + + def __del__(self): + # In case of partial initialization of instances. + pointer = getattr(self, "_pointer", None) + if pointer is not None: + _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_free_credentials, pointer) + + def _uniffi_clone_pointer(self): + return _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_clone_credentials, self._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 + @classmethod + def load(cls, raw: "bytes"): + _UniffiConverterBytes.check_lower(raw) + + # Call the (fallible) function before creating any half-baked object instances. + pointer = _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_constructor_credentials_load, + _UniffiConverterBytes.lower(raw)) + return cls._make_instance_(pointer) + + + + def save(self, ) -> "bytes": + return _UniffiConverterBytes.lift( + _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_credentials_save,self._uniffi_clone_pointer(),) + ) + + + + + + +class _UniffiConverterTypeCredentials: + + @staticmethod + def lift(value: int): + return Credentials._make_instance_(value) + + @staticmethod + def check_lower(value: Credentials): + if not isinstance(value, Credentials): + raise TypeError("Expected Credentials instance, {} found".format(type(value).__name__)) + + @staticmethod + def lower(value: CredentialsProtocol): + if not isinstance(value, Credentials): + raise TypeError("Expected Credentials instance, {} found".format(type(value).__name__)) + return value._uniffi_clone_pointer() + + @classmethod + def read(cls, buf: _UniffiRustBuffer): + ptr = buf.read_u64() + if ptr == 0: + raise InternalError("Raw pointer value was null") + return cls.lift(ptr) + + @classmethod + def write(cls, value: CredentialsProtocol, buf: _UniffiRustBuffer): + buf.write_u64(cls.lower(value)) +class HandleProtocol(typing.Protocol): + """ + A handle to interact with a signer loop running and processing + requests in the background. Used primarily to stop the loop and + exiting the signer. + """ + + def stop(self, ): + raise NotImplementedError +# Handle is a Rust-only trait - it's a wrapper around a Rust implementation. +class Handle(): + """ + A handle to interact with a signer loop running and processing + requests in the background. Used primarily to stop the loop and + exiting the signer. + """ + + _pointer: ctypes.c_void_p + + def __init__(self, *args, **kwargs): + raise ValueError("This class has no default constructor") + + def __del__(self): + # In case of partial initialization of instances. + pointer = getattr(self, "_pointer", None) + if pointer is not None: + _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_free_handle, pointer) + + def _uniffi_clone_pointer(self): + return _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_clone_handle, self._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 + + + def stop(self, ) -> None: + _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_method_handle_stop,self._uniffi_clone_pointer(),) + + + + + + + +class _UniffiConverterTypeHandle: + + @staticmethod + def lift(value: int): + return Handle._make_instance_(value) + + @staticmethod + def check_lower(value: Handle): + if not isinstance(value, Handle): + raise TypeError("Expected Handle instance, {} found".format(type(value).__name__)) + + @staticmethod + def lower(value: HandleProtocol): + if not isinstance(value, Handle): + raise TypeError("Expected Handle instance, {} found".format(type(value).__name__)) + return value._uniffi_clone_pointer() + + @classmethod + def read(cls, buf: _UniffiRustBuffer): + ptr = buf.read_u64() + if ptr == 0: + raise InternalError("Raw pointer value was null") + return cls.lift(ptr) + + @classmethod + def write(cls, value: HandleProtocol, buf: _UniffiRustBuffer): + buf.write_u64(cls.lower(value)) +class NodeProtocol(typing.Protocol): + """ + The `Node` is an RPC stub representing the node running in the + cloud. It is the main entrypoint to interact with the node. + """ + + def onchain_receive(self, ): + raise NotImplementedError + def onchain_send(self, destination: "str",amount_or_all: "str"): + raise NotImplementedError + def receive(self, label: "str",description: "str",amount_msat: "typing.Optional[int]"): + """ + Receive an off-chain payment. + + This method generates a request for a payment, also called an + invoice, that encodes all the information, including amount + and destination, for a prospective sender to send a lightning + payment. The invoice includes negotiation of an LSPS2 / JIT + channel, meaning that if there is no channel sufficient to + receive the requested funds, the node will negotiate an + opening, and when/if executed the payment will cause a channel + to be created, and the incoming payment to be forwarded. + """ + + raise NotImplementedError + def send(self, invoice: "str",amount_msat: "typing.Optional[int]"): + raise NotImplementedError + def stop(self, ): + """ + Stop the node if it is currently running. + """ + + raise NotImplementedError +# Node is a Rust-only trait - it's a wrapper around a Rust implementation. +class Node(): + """ + The `Node` is an RPC stub representing the node running in the + cloud. It is the main entrypoint to interact with the node. + """ + + _pointer: ctypes.c_void_p + def __init__(self, credentials: "Credentials"): + _UniffiConverterTypeCredentials.check_lower(credentials) + + self._pointer = _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_constructor_node_new, + _UniffiConverterTypeCredentials.lower(credentials)) + + def __del__(self): + # In case of partial initialization of instances. + pointer = getattr(self, "_pointer", None) + if pointer is not None: + _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_free_node, pointer) + + def _uniffi_clone_pointer(self): + return _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_clone_node, self._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 + + + def onchain_receive(self, ) -> "OnchainReceiveResponse": + return _UniffiConverterTypeOnchainReceiveResponse.lift( + _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_node_onchain_receive,self._uniffi_clone_pointer(),) + ) + + + + + + def onchain_send(self, destination: "str",amount_or_all: "str") -> "OnchainSendResponse": + _UniffiConverterString.check_lower(destination) + + _UniffiConverterString.check_lower(amount_or_all) + + return _UniffiConverterTypeOnchainSendResponse.lift( + _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_node_onchain_send,self._uniffi_clone_pointer(), + _UniffiConverterString.lower(destination), + _UniffiConverterString.lower(amount_or_all)) + ) + + + + + + def receive(self, label: "str",description: "str",amount_msat: "typing.Optional[int]") -> "ReceiveResponse": + """ + Receive an off-chain payment. + + This method generates a request for a payment, also called an + invoice, that encodes all the information, including amount + and destination, for a prospective sender to send a lightning + payment. The invoice includes negotiation of an LSPS2 / JIT + channel, meaning that if there is no channel sufficient to + receive the requested funds, the node will negotiate an + opening, and when/if executed the payment will cause a channel + to be created, and the incoming payment to be forwarded. + """ + + _UniffiConverterString.check_lower(label) + + _UniffiConverterString.check_lower(description) + + _UniffiConverterOptionalUInt64.check_lower(amount_msat) + + return _UniffiConverterTypeReceiveResponse.lift( + _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_node_receive,self._uniffi_clone_pointer(), + _UniffiConverterString.lower(label), + _UniffiConverterString.lower(description), + _UniffiConverterOptionalUInt64.lower(amount_msat)) + ) + + + + + + def send(self, invoice: "str",amount_msat: "typing.Optional[int]") -> "SendResponse": + _UniffiConverterString.check_lower(invoice) + + _UniffiConverterOptionalUInt64.check_lower(amount_msat) + + return _UniffiConverterTypeSendResponse.lift( + _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_node_send,self._uniffi_clone_pointer(), + _UniffiConverterString.lower(invoice), + _UniffiConverterOptionalUInt64.lower(amount_msat)) + ) + + + + + + def stop(self, ) -> None: + """ + Stop the node if it is currently running. + """ + + _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_node_stop,self._uniffi_clone_pointer(),) + + + + + + + +class _UniffiConverterTypeNode: + + @staticmethod + def lift(value: int): + return Node._make_instance_(value) + + @staticmethod + def check_lower(value: Node): + if not isinstance(value, Node): + raise TypeError("Expected Node instance, {} found".format(type(value).__name__)) + + @staticmethod + def lower(value: NodeProtocol): + if not isinstance(value, Node): + raise TypeError("Expected Node instance, {} found".format(type(value).__name__)) + return value._uniffi_clone_pointer() + + @classmethod + def read(cls, buf: _UniffiRustBuffer): + ptr = buf.read_u64() + if ptr == 0: + raise InternalError("Raw pointer value was null") + return cls.lift(ptr) + + @classmethod + def write(cls, value: NodeProtocol, buf: _UniffiRustBuffer): + buf.write_u64(cls.lower(value)) +class OnchainReceiveResponseProtocol(typing.Protocol): + pass +# OnchainReceiveResponse is a Rust-only trait - it's a wrapper around a Rust implementation. +class OnchainReceiveResponse(): + _pointer: ctypes.c_void_p + + def __init__(self, *args, **kwargs): + raise ValueError("This class has no default constructor") + + def __del__(self): + # In case of partial initialization of instances. + pointer = getattr(self, "_pointer", None) + if pointer is not None: + _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_free_onchainreceiveresponse, pointer) + + def _uniffi_clone_pointer(self): + return _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_clone_onchainreceiveresponse, self._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 _UniffiConverterTypeOnchainReceiveResponse: + + @staticmethod + def lift(value: int): + return OnchainReceiveResponse._make_instance_(value) + + @staticmethod + def check_lower(value: OnchainReceiveResponse): + if not isinstance(value, OnchainReceiveResponse): + raise TypeError("Expected OnchainReceiveResponse instance, {} found".format(type(value).__name__)) + + @staticmethod + def lower(value: OnchainReceiveResponseProtocol): + if not isinstance(value, OnchainReceiveResponse): + raise TypeError("Expected OnchainReceiveResponse instance, {} found".format(type(value).__name__)) + return value._uniffi_clone_pointer() + + @classmethod + def read(cls, buf: _UniffiRustBuffer): + ptr = buf.read_u64() + if ptr == 0: + raise InternalError("Raw pointer value was null") + return cls.lift(ptr) + + @classmethod + def write(cls, value: OnchainReceiveResponseProtocol, buf: _UniffiRustBuffer): + buf.write_u64(cls.lower(value)) +class OnchainSendResponseProtocol(typing.Protocol): + pass +# OnchainSendResponse is a Rust-only trait - it's a wrapper around a Rust implementation. +class OnchainSendResponse(): + _pointer: ctypes.c_void_p + + def __init__(self, *args, **kwargs): + raise ValueError("This class has no default constructor") + + def __del__(self): + # In case of partial initialization of instances. + pointer = getattr(self, "_pointer", None) + if pointer is not None: + _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_free_onchainsendresponse, pointer) + + def _uniffi_clone_pointer(self): + return _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_clone_onchainsendresponse, self._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 _UniffiConverterTypeOnchainSendResponse: + + @staticmethod + def lift(value: int): + return OnchainSendResponse._make_instance_(value) + + @staticmethod + def check_lower(value: OnchainSendResponse): + if not isinstance(value, OnchainSendResponse): + raise TypeError("Expected OnchainSendResponse instance, {} found".format(type(value).__name__)) + + @staticmethod + def lower(value: OnchainSendResponseProtocol): + if not isinstance(value, OnchainSendResponse): + raise TypeError("Expected OnchainSendResponse instance, {} found".format(type(value).__name__)) + return value._uniffi_clone_pointer() + + @classmethod + def read(cls, buf: _UniffiRustBuffer): + ptr = buf.read_u64() + if ptr == 0: + raise InternalError("Raw pointer value was null") + return cls.lift(ptr) + + @classmethod + def write(cls, value: OnchainSendResponseProtocol, buf: _UniffiRustBuffer): + buf.write_u64(cls.lower(value)) +class ReceiveResponseProtocol(typing.Protocol): + pass +# ReceiveResponse is a Rust-only trait - it's a wrapper around a Rust implementation. +class ReceiveResponse(): + _pointer: ctypes.c_void_p + + def __init__(self, *args, **kwargs): + raise ValueError("This class has no default constructor") + + def __del__(self): + # In case of partial initialization of instances. + pointer = getattr(self, "_pointer", None) + if pointer is not None: + _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_free_receiveresponse, pointer) + + def _uniffi_clone_pointer(self): + return _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_clone_receiveresponse, self._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 _UniffiConverterTypeReceiveResponse: + + @staticmethod + def lift(value: int): + return ReceiveResponse._make_instance_(value) + + @staticmethod + def check_lower(value: ReceiveResponse): + if not isinstance(value, ReceiveResponse): + raise TypeError("Expected ReceiveResponse instance, {} found".format(type(value).__name__)) + + @staticmethod + def lower(value: ReceiveResponseProtocol): + if not isinstance(value, ReceiveResponse): + raise TypeError("Expected ReceiveResponse instance, {} found".format(type(value).__name__)) + return value._uniffi_clone_pointer() + + @classmethod + def read(cls, buf: _UniffiRustBuffer): + ptr = buf.read_u64() + if ptr == 0: + raise InternalError("Raw pointer value was null") + return cls.lift(ptr) + + @classmethod + def write(cls, value: ReceiveResponseProtocol, buf: _UniffiRustBuffer): + buf.write_u64(cls.lower(value)) +class SchedulerProtocol(typing.Protocol): + def recover(self, signer: "Signer"): + raise NotImplementedError + def register(self, signer: "Signer",code: "typing.Optional[str]"): + raise NotImplementedError +# Scheduler is a Rust-only trait - it's a wrapper around a Rust implementation. +class Scheduler(): + _pointer: ctypes.c_void_p + def __init__(self, network: "Network"): + """ + Create a `Scheduler` instance configured with the Greenlight + production service pre-configured. + """ + + _UniffiConverterTypeNetwork.check_lower(network) + + self._pointer = _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_constructor_scheduler_new, + _UniffiConverterTypeNetwork.lower(network)) + + def __del__(self): + # In case of partial initialization of instances. + pointer = getattr(self, "_pointer", None) + if pointer is not None: + _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_free_scheduler, pointer) + + def _uniffi_clone_pointer(self): + return _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_clone_scheduler, self._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 + + + def recover(self, signer: "Signer") -> "Credentials": + _UniffiConverterTypeSigner.check_lower(signer) + + return _UniffiConverterTypeCredentials.lift( + _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_scheduler_recover,self._uniffi_clone_pointer(), + _UniffiConverterTypeSigner.lower(signer)) + ) + + + + + + def register(self, signer: "Signer",code: "typing.Optional[str]") -> "Credentials": + _UniffiConverterTypeSigner.check_lower(signer) + + _UniffiConverterOptionalString.check_lower(code) + + return _UniffiConverterTypeCredentials.lift( + _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_scheduler_register,self._uniffi_clone_pointer(), + _UniffiConverterTypeSigner.lower(signer), + _UniffiConverterOptionalString.lower(code)) + ) + + + + + + +class _UniffiConverterTypeScheduler: + + @staticmethod + def lift(value: int): + return Scheduler._make_instance_(value) + + @staticmethod + def check_lower(value: Scheduler): + if not isinstance(value, Scheduler): + raise TypeError("Expected Scheduler instance, {} found".format(type(value).__name__)) + + @staticmethod + def lower(value: SchedulerProtocol): + if not isinstance(value, Scheduler): + raise TypeError("Expected Scheduler instance, {} found".format(type(value).__name__)) + return value._uniffi_clone_pointer() + + @classmethod + def read(cls, buf: _UniffiRustBuffer): + ptr = buf.read_u64() + if ptr == 0: + raise InternalError("Raw pointer value was null") + return cls.lift(ptr) + + @classmethod + def write(cls, value: SchedulerProtocol, buf: _UniffiRustBuffer): + buf.write_u64(cls.lower(value)) +class SendResponseProtocol(typing.Protocol): + pass +# SendResponse is a Rust-only trait - it's a wrapper around a Rust implementation. +class SendResponse(): + _pointer: ctypes.c_void_p + + def __init__(self, *args, **kwargs): + raise ValueError("This class has no default constructor") + + def __del__(self): + # In case of partial initialization of instances. + pointer = getattr(self, "_pointer", None) + if pointer is not None: + _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_free_sendresponse, pointer) + + def _uniffi_clone_pointer(self): + return _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_clone_sendresponse, self._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 _UniffiConverterTypeSendResponse: + + @staticmethod + def lift(value: int): + return SendResponse._make_instance_(value) + + @staticmethod + def check_lower(value: SendResponse): + if not isinstance(value, SendResponse): + raise TypeError("Expected SendResponse instance, {} found".format(type(value).__name__)) + + @staticmethod + def lower(value: SendResponseProtocol): + if not isinstance(value, SendResponse): + raise TypeError("Expected SendResponse instance, {} found".format(type(value).__name__)) + return value._uniffi_clone_pointer() + + @classmethod + def read(cls, buf: _UniffiRustBuffer): + ptr = buf.read_u64() + if ptr == 0: + raise InternalError("Raw pointer value was null") + return cls.lift(ptr) + + @classmethod + def write(cls, value: SendResponseProtocol, buf: _UniffiRustBuffer): + buf.write_u64(cls.lower(value)) +class SignerProtocol(typing.Protocol): + def authenticate(self, creds: "Credentials"): + raise NotImplementedError + def node_id(self, ): + raise NotImplementedError + def start(self, ): + raise NotImplementedError +# Signer is a Rust-only trait - it's a wrapper around a Rust implementation. +class Signer(): + _pointer: ctypes.c_void_p + def __init__(self, phrase: "str"): + _UniffiConverterString.check_lower(phrase) + + self._pointer = _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_constructor_signer_new, + _UniffiConverterString.lower(phrase)) + + def __del__(self): + # In case of partial initialization of instances. + pointer = getattr(self, "_pointer", None) + if pointer is not None: + _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_free_signer, pointer) + + def _uniffi_clone_pointer(self): + return _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_clone_signer, self._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 + + + def authenticate(self, creds: "Credentials") -> "Signer": + _UniffiConverterTypeCredentials.check_lower(creds) + + return _UniffiConverterTypeSigner.lift( + _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_signer_authenticate,self._uniffi_clone_pointer(), + _UniffiConverterTypeCredentials.lower(creds)) + ) + + + + + + def node_id(self, ) -> "bytes": + return _UniffiConverterBytes.lift( + _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_method_signer_node_id,self._uniffi_clone_pointer(),) + ) + + + + + + def start(self, ) -> "Handle": + return _UniffiConverterTypeHandle.lift( + _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_signer_start,self._uniffi_clone_pointer(),) + ) + + + + + + +class _UniffiConverterTypeSigner: + + @staticmethod + def lift(value: int): + return Signer._make_instance_(value) + + @staticmethod + def check_lower(value: Signer): + if not isinstance(value, Signer): + raise TypeError("Expected Signer instance, {} found".format(type(value).__name__)) + + @staticmethod + def lower(value: SignerProtocol): + if not isinstance(value, Signer): + raise TypeError("Expected Signer instance, {} found".format(type(value).__name__)) + return value._uniffi_clone_pointer() + + @classmethod + def read(cls, buf: _UniffiRustBuffer): + ptr = buf.read_u64() + if ptr == 0: + raise InternalError("Raw pointer value was null") + return cls.lift(ptr) + + @classmethod + def write(cls, value: SignerProtocol, buf: _UniffiRustBuffer): + buf.write_u64(cls.lower(value)) + +# Async support + +__all__ = [ + "InternalError", + "Error", + "Network", + "PayStatus", + "Credentials", + "Handle", + "Node", + "OnchainReceiveResponse", + "OnchainSendResponse", + "ReceiveResponse", + "Scheduler", + "SendResponse", + "Signer", +] + diff --git a/libs/gl-sdk/glsdk/glsdk.py b/libs/gl-sdk/glsdk/glsdk.py index 78a9bef28..c59b1cff4 100644 --- a/libs/gl-sdk/glsdk/glsdk.py +++ b/libs/gl-sdk/glsdk/glsdk.py @@ -460,8 +460,20 @@ def _uniffi_check_contract_api_version(lib): raise InternalError("UniFFI contract version mismatch: try cleaning and rebuilding your project") def _uniffi_check_api_checksums(lib): + if lib.uniffi_glsdk_checksum_method_credentials_save() != 26677: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_method_handle_stop() != 36432: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_method_node_onchain_receive() != 21676: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_method_node_onchain_send() != 51884: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_method_node_receive() != 24722: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_method_node_send() != 30141: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + if lib.uniffi_glsdk_checksum_method_node_stop() != 20186: + raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_method_scheduler_recover() != 55514: raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project") if lib.uniffi_glsdk_checksum_method_scheduler_register() != 20821: @@ -601,6 +613,11 @@ class _UniffiForeignFutureStructVoid(ctypes.Structure): ctypes.POINTER(_UniffiRustCallStatus), ) _UniffiLib.uniffi_glsdk_fn_constructor_credentials_load.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_method_credentials_save.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_credentials_save.restype = _UniffiRustBuffer _UniffiLib.uniffi_glsdk_fn_clone_handle.argtypes = ( ctypes.c_void_p, ctypes.POINTER(_UniffiRustCallStatus), @@ -631,6 +648,68 @@ class _UniffiForeignFutureStructVoid(ctypes.Structure): ctypes.POINTER(_UniffiRustCallStatus), ) _UniffiLib.uniffi_glsdk_fn_constructor_node_new.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_method_node_onchain_receive.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_node_onchain_receive.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_method_node_onchain_send.argtypes = ( + ctypes.c_void_p, + _UniffiRustBuffer, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_node_onchain_send.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_method_node_receive.argtypes = ( + ctypes.c_void_p, + _UniffiRustBuffer, + _UniffiRustBuffer, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_node_receive.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_method_node_send.argtypes = ( + ctypes.c_void_p, + _UniffiRustBuffer, + _UniffiRustBuffer, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_node_send.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_method_node_stop.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_method_node_stop.restype = None +_UniffiLib.uniffi_glsdk_fn_clone_onchainreceiveresponse.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_clone_onchainreceiveresponse.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_free_onchainreceiveresponse.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_free_onchainreceiveresponse.restype = None +_UniffiLib.uniffi_glsdk_fn_clone_onchainsendresponse.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_clone_onchainsendresponse.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_free_onchainsendresponse.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_free_onchainsendresponse.restype = None +_UniffiLib.uniffi_glsdk_fn_clone_receiveresponse.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_clone_receiveresponse.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_free_receiveresponse.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_free_receiveresponse.restype = None _UniffiLib.uniffi_glsdk_fn_clone_scheduler.argtypes = ( ctypes.c_void_p, ctypes.POINTER(_UniffiRustCallStatus), @@ -659,6 +738,16 @@ class _UniffiForeignFutureStructVoid(ctypes.Structure): ctypes.POINTER(_UniffiRustCallStatus), ) _UniffiLib.uniffi_glsdk_fn_method_scheduler_register.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_clone_sendresponse.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_clone_sendresponse.restype = ctypes.c_void_p +_UniffiLib.uniffi_glsdk_fn_free_sendresponse.argtypes = ( + ctypes.c_void_p, + ctypes.POINTER(_UniffiRustCallStatus), +) +_UniffiLib.uniffi_glsdk_fn_free_sendresponse.restype = None _UniffiLib.uniffi_glsdk_fn_clone_signer.argtypes = ( ctypes.c_void_p, ctypes.POINTER(_UniffiRustCallStatus), @@ -958,9 +1047,27 @@ class _UniffiForeignFutureStructVoid(ctypes.Structure): ctypes.POINTER(_UniffiRustCallStatus), ) _UniffiLib.ffi_glsdk_rust_future_complete_void.restype = None +_UniffiLib.uniffi_glsdk_checksum_method_credentials_save.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_credentials_save.restype = ctypes.c_uint16 _UniffiLib.uniffi_glsdk_checksum_method_handle_stop.argtypes = ( ) _UniffiLib.uniffi_glsdk_checksum_method_handle_stop.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_method_node_onchain_receive.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_node_onchain_receive.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_method_node_onchain_send.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_node_onchain_send.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_method_node_receive.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_node_receive.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_method_node_send.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_node_send.restype = ctypes.c_uint16 +_UniffiLib.uniffi_glsdk_checksum_method_node_stop.argtypes = ( +) +_UniffiLib.uniffi_glsdk_checksum_method_node_stop.restype = ctypes.c_uint16 _UniffiLib.uniffi_glsdk_checksum_method_scheduler_recover.argtypes = ( ) _UniffiLib.uniffi_glsdk_checksum_method_scheduler_recover.restype = ctypes.c_uint16 @@ -998,6 +1105,32 @@ class _UniffiForeignFutureStructVoid(ctypes.Structure): # Public interface members begin here. +class _UniffiConverterInt32(_UniffiConverterPrimitiveInt): + CLASS_NAME = "i32" + VALUE_MIN = -2**31 + VALUE_MAX = 2**31 + + @staticmethod + def read(buf): + return buf.read_i32() + + @staticmethod + def write(value, buf): + buf.write_i32(value) + +class _UniffiConverterUInt64(_UniffiConverterPrimitiveInt): + CLASS_NAME = "u64" + VALUE_MIN = 0 + VALUE_MAX = 2**64 + + @staticmethod + def read(buf): + return buf.read_u64() + + @staticmethod + def write(value, buf): + buf.write_u64(value) + class _UniffiConverterString: @staticmethod def check_lower(value): @@ -1061,6 +1194,14 @@ def write(value, buf): + + + + + + + + # Error # We want to define each variant as a nested class that's also a subclass, # which is tricky in Python. To accomplish this we're going to create each @@ -1074,60 +1215,99 @@ class Error(Exception): class Error: # type: ignore class DuplicateNode(_UniffiTempError): - def __init__(self, *values): - if len(values) != 1: - raise TypeError(f"Expected 1 arguments, found {len(values)}") - if not isinstance(values[0], str): - raise TypeError(f"unexpected type for tuple element 0 - expected 'str', got '{type(values[0])}'") - super().__init__(", ".join(map(repr, values))) - self._values = values - - def __getitem__(self, index): - return self._values[index] + def __init__(self, code, message, values): + super().__init__(", ".join([ + "code={!r}".format(code), + "message={!r}".format(message), + "values={!r}".format(values), + ])) + self.code = code + self.message = message + self.values = values def __repr__(self): return "Error.DuplicateNode({})".format(str(self)) _UniffiTempError.DuplicateNode = DuplicateNode # type: ignore class NoSuchNode(_UniffiTempError): - def __init__(self, *values): - if len(values) != 1: - raise TypeError(f"Expected 1 arguments, found {len(values)}") - if not isinstance(values[0], str): - raise TypeError(f"unexpected type for tuple element 0 - expected 'str', got '{type(values[0])}'") - super().__init__(", ".join(map(repr, values))) - self._values = values - - def __getitem__(self, index): - return self._values[index] + def __init__(self, code, message, values): + super().__init__(", ".join([ + "code={!r}".format(code), + "message={!r}".format(message), + "values={!r}".format(values), + ])) + self.code = code + self.message = message + self.values = values def __repr__(self): return "Error.NoSuchNode({})".format(str(self)) _UniffiTempError.NoSuchNode = NoSuchNode # type: ignore class UnparseableCreds(_UniffiTempError): - def __init__(self): - pass + def __init__(self, code, message, values): + super().__init__(", ".join([ + "code={!r}".format(code), + "message={!r}".format(message), + "values={!r}".format(values), + ])) + self.code = code + self.message = message + self.values = values def __repr__(self): return "Error.UnparseableCreds({})".format(str(self)) _UniffiTempError.UnparseableCreds = UnparseableCreds # type: ignore class PhraseCorrupted(_UniffiTempError): - def __init__(self): - pass + def __init__(self, code, message, values): + super().__init__(", ".join([ + "code={!r}".format(code), + "message={!r}".format(message), + "values={!r}".format(values), + ])) + self.code = code + self.message = message + self.values = values def __repr__(self): return "Error.PhraseCorrupted({})".format(str(self)) _UniffiTempError.PhraseCorrupted = PhraseCorrupted # type: ignore - class Other(_UniffiTempError): - def __init__(self, *values): - if len(values) != 1: - raise TypeError(f"Expected 1 arguments, found {len(values)}") - if not isinstance(values[0], str): - raise TypeError(f"unexpected type for tuple element 0 - expected 'str', got '{type(values[0])}'") - super().__init__(", ".join(map(repr, values))) - self._values = values + class Rpc(_UniffiTempError): + def __init__(self, code, message, values): + super().__init__(", ".join([ + "code={!r}".format(code), + "message={!r}".format(message), + "values={!r}".format(values), + ])) + self.code = code + self.message = message + self.values = values - def __getitem__(self, index): - return self._values[index] + def __repr__(self): + return "Error.Rpc({})".format(str(self)) + _UniffiTempError.Rpc = Rpc # type: ignore + class Argument(_UniffiTempError): + def __init__(self, code, message, values): + super().__init__(", ".join([ + "code={!r}".format(code), + "message={!r}".format(message), + "values={!r}".format(values), + ])) + self.code = code + self.message = message + self.values = values + + def __repr__(self): + return "Error.Argument({})".format(str(self)) + _UniffiTempError.Argument = Argument # type: ignore + class Other(_UniffiTempError): + def __init__(self, code, message, values): + super().__init__(", ".join([ + "code={!r}".format(code), + "message={!r}".format(message), + "values={!r}".format(values), + ])) + self.code = code + self.message = message + self.values = values def __repr__(self): return "Error.Other({})".format(str(self)) @@ -1143,55 +1323,123 @@ def read(buf): variant = buf.read_i32() if variant == 1: return Error.DuplicateNode( + _UniffiConverterInt32.read(buf), _UniffiConverterString.read(buf), + _UniffiConverterMapStringString.read(buf), ) if variant == 2: return Error.NoSuchNode( + _UniffiConverterInt32.read(buf), _UniffiConverterString.read(buf), + _UniffiConverterMapStringString.read(buf), ) if variant == 3: return Error.UnparseableCreds( + _UniffiConverterInt32.read(buf), + _UniffiConverterString.read(buf), + _UniffiConverterMapStringString.read(buf), ) if variant == 4: return Error.PhraseCorrupted( + _UniffiConverterInt32.read(buf), + _UniffiConverterString.read(buf), + _UniffiConverterMapStringString.read(buf), ) if variant == 5: + return Error.Rpc( + _UniffiConverterInt32.read(buf), + _UniffiConverterString.read(buf), + _UniffiConverterMapStringString.read(buf), + ) + if variant == 6: + return Error.Argument( + _UniffiConverterInt32.read(buf), + _UniffiConverterString.read(buf), + _UniffiConverterMapStringString.read(buf), + ) + if variant == 7: return Error.Other( + _UniffiConverterInt32.read(buf), _UniffiConverterString.read(buf), + _UniffiConverterMapStringString.read(buf), ) raise InternalError("Raw enum value doesn't match any cases") @staticmethod def check_lower(value): if isinstance(value, Error.DuplicateNode): - _UniffiConverterString.check_lower(value._values[0]) + _UniffiConverterInt32.check_lower(value.code) + _UniffiConverterString.check_lower(value.message) + _UniffiConverterMapStringString.check_lower(value.values) return if isinstance(value, Error.NoSuchNode): - _UniffiConverterString.check_lower(value._values[0]) + _UniffiConverterInt32.check_lower(value.code) + _UniffiConverterString.check_lower(value.message) + _UniffiConverterMapStringString.check_lower(value.values) return if isinstance(value, Error.UnparseableCreds): + _UniffiConverterInt32.check_lower(value.code) + _UniffiConverterString.check_lower(value.message) + _UniffiConverterMapStringString.check_lower(value.values) return if isinstance(value, Error.PhraseCorrupted): + _UniffiConverterInt32.check_lower(value.code) + _UniffiConverterString.check_lower(value.message) + _UniffiConverterMapStringString.check_lower(value.values) + return + if isinstance(value, Error.Rpc): + _UniffiConverterInt32.check_lower(value.code) + _UniffiConverterString.check_lower(value.message) + _UniffiConverterMapStringString.check_lower(value.values) + return + if isinstance(value, Error.Argument): + _UniffiConverterInt32.check_lower(value.code) + _UniffiConverterString.check_lower(value.message) + _UniffiConverterMapStringString.check_lower(value.values) return if isinstance(value, Error.Other): - _UniffiConverterString.check_lower(value._values[0]) + _UniffiConverterInt32.check_lower(value.code) + _UniffiConverterString.check_lower(value.message) + _UniffiConverterMapStringString.check_lower(value.values) return @staticmethod def write(value, buf): if isinstance(value, Error.DuplicateNode): buf.write_i32(1) - _UniffiConverterString.write(value._values[0], buf) + _UniffiConverterInt32.write(value.code, buf) + _UniffiConverterString.write(value.message, buf) + _UniffiConverterMapStringString.write(value.values, buf) if isinstance(value, Error.NoSuchNode): buf.write_i32(2) - _UniffiConverterString.write(value._values[0], buf) + _UniffiConverterInt32.write(value.code, buf) + _UniffiConverterString.write(value.message, buf) + _UniffiConverterMapStringString.write(value.values, buf) if isinstance(value, Error.UnparseableCreds): buf.write_i32(3) + _UniffiConverterInt32.write(value.code, buf) + _UniffiConverterString.write(value.message, buf) + _UniffiConverterMapStringString.write(value.values, buf) if isinstance(value, Error.PhraseCorrupted): buf.write_i32(4) - if isinstance(value, Error.Other): + _UniffiConverterInt32.write(value.code, buf) + _UniffiConverterString.write(value.message, buf) + _UniffiConverterMapStringString.write(value.values, buf) + if isinstance(value, Error.Rpc): buf.write_i32(5) - _UniffiConverterString.write(value._values[0], buf) + _UniffiConverterInt32.write(value.code, buf) + _UniffiConverterString.write(value.message, buf) + _UniffiConverterMapStringString.write(value.values, buf) + if isinstance(value, Error.Argument): + buf.write_i32(6) + _UniffiConverterInt32.write(value.code, buf) + _UniffiConverterString.write(value.message, buf) + _UniffiConverterMapStringString.write(value.values, buf) + if isinstance(value, Error.Other): + buf.write_i32(7) + _UniffiConverterInt32.write(value.code, buf) + _UniffiConverterString.write(value.message, buf) + _UniffiConverterMapStringString.write(value.values, buf) @@ -1233,6 +1481,79 @@ def write(value, buf): + + +class PayStatus(enum.Enum): + COMPLETE = 0 + + PENDING = 1 + + FAILED = 2 + + + +class _UniffiConverterTypePayStatus(_UniffiConverterRustBuffer): + @staticmethod + def read(buf): + variant = buf.read_i32() + if variant == 1: + return PayStatus.COMPLETE + if variant == 2: + return PayStatus.PENDING + if variant == 3: + return PayStatus.FAILED + raise InternalError("Raw enum value doesn't match any cases") + + @staticmethod + def check_lower(value): + if value == PayStatus.COMPLETE: + return + if value == PayStatus.PENDING: + return + if value == PayStatus.FAILED: + return + raise ValueError(value) + + @staticmethod + def write(value, buf): + if value == PayStatus.COMPLETE: + buf.write_i32(1) + if value == PayStatus.PENDING: + buf.write_i32(2) + if value == PayStatus.FAILED: + buf.write_i32(3) + + + + + +class _UniffiConverterOptionalUInt64(_UniffiConverterRustBuffer): + @classmethod + def check_lower(cls, value): + if value is not None: + _UniffiConverterUInt64.check_lower(value) + + @classmethod + def write(cls, value, buf): + if value is None: + buf.write_u8(0) + return + + buf.write_u8(1) + _UniffiConverterUInt64.write(value, buf) + + @classmethod + def read(cls, buf): + flag = buf.read_u8() + if flag == 0: + return None + elif flag == 1: + return _UniffiConverterUInt64.read(buf) + else: + raise InternalError("Unexpected flag byte for optional type") + + + class _UniffiConverterOptionalString(_UniffiConverterRustBuffer): @classmethod def check_lower(cls, value): @@ -1258,6 +1579,39 @@ def read(cls, buf): else: raise InternalError("Unexpected flag byte for optional type") + + +class _UniffiConverterMapStringString(_UniffiConverterRustBuffer): + @classmethod + def check_lower(cls, items): + for (key, value) in items.items(): + _UniffiConverterString.check_lower(key) + _UniffiConverterString.check_lower(value) + + @classmethod + def write(cls, items, buf): + buf.write_i32(len(items)) + for (key, value) in items.items(): + _UniffiConverterString.write(key, buf) + _UniffiConverterString.write(value, buf) + + @classmethod + def read(cls, buf): + count = buf.read_i32() + if count < 0: + raise InternalError("Unexpected negative map size") + + # It would be nice to use a dict comprehension, + # but in Python 3.7 and before the evaluation order is not according to spec, + # so we we're reading the value before the key. + # This loop makes the order explicit: first reading the key, then the value. + d = {} + for i in range(count): + key = _UniffiConverterString.read(buf) + val = _UniffiConverterString.read(buf) + d[key] = val + return d + # objects. class CredentialsProtocol(typing.Protocol): """ @@ -1268,7 +1622,8 @@ class CredentialsProtocol(typing.Protocol): background. """ - pass + def save(self, ): + raise NotImplementedError # Credentials is a Rust-only trait - it's a wrapper around a Rust implementation. class Credentials(): """ @@ -1312,6 +1667,15 @@ def load(cls, raw: "bytes"): + def save(self, ) -> "bytes": + return _UniffiConverterBytes.lift( + _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_credentials_save,self._uniffi_clone_pointer(),) + ) + + + + + class _UniffiConverterTypeCredentials: @@ -1423,7 +1787,33 @@ class NodeProtocol(typing.Protocol): cloud. It is the main entrypoint to interact with the node. """ - pass + def onchain_receive(self, ): + raise NotImplementedError + def onchain_send(self, destination: "str",amount_or_all: "str"): + raise NotImplementedError + def receive(self, label: "str",description: "str",amount_msat: "typing.Optional[int]"): + """ + Receive an off-chain payment. + + This method generates a request for a payment, also called an + invoice, that encodes all the information, including amount + and destination, for a prospective sender to send a lightning + payment. The invoice includes negotiation of an LSPS2 / JIT + channel, meaning that if there is no channel sufficient to + receive the requested funds, the node will negotiate an + opening, and when/if executed the payment will cause a channel + to be created, and the incoming payment to be forwarded. + """ + + raise NotImplementedError + def send(self, invoice: "str",amount_msat: "typing.Optional[int]"): + raise NotImplementedError + def stop(self, ): + """ + Stop the node if it is currently running. + """ + + raise NotImplementedError # Node is a Rust-only trait - it's a wrapper around a Rust implementation. class Node(): """ @@ -1457,6 +1847,88 @@ def _make_instance_(cls, pointer): return inst + def onchain_receive(self, ) -> "OnchainReceiveResponse": + return _UniffiConverterTypeOnchainReceiveResponse.lift( + _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_node_onchain_receive,self._uniffi_clone_pointer(),) + ) + + + + + + def onchain_send(self, destination: "str",amount_or_all: "str") -> "OnchainSendResponse": + _UniffiConverterString.check_lower(destination) + + _UniffiConverterString.check_lower(amount_or_all) + + return _UniffiConverterTypeOnchainSendResponse.lift( + _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_node_onchain_send,self._uniffi_clone_pointer(), + _UniffiConverterString.lower(destination), + _UniffiConverterString.lower(amount_or_all)) + ) + + + + + + def receive(self, label: "str",description: "str",amount_msat: "typing.Optional[int]") -> "ReceiveResponse": + """ + Receive an off-chain payment. + + This method generates a request for a payment, also called an + invoice, that encodes all the information, including amount + and destination, for a prospective sender to send a lightning + payment. The invoice includes negotiation of an LSPS2 / JIT + channel, meaning that if there is no channel sufficient to + receive the requested funds, the node will negotiate an + opening, and when/if executed the payment will cause a channel + to be created, and the incoming payment to be forwarded. + """ + + _UniffiConverterString.check_lower(label) + + _UniffiConverterString.check_lower(description) + + _UniffiConverterOptionalUInt64.check_lower(amount_msat) + + return _UniffiConverterTypeReceiveResponse.lift( + _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_node_receive,self._uniffi_clone_pointer(), + _UniffiConverterString.lower(label), + _UniffiConverterString.lower(description), + _UniffiConverterOptionalUInt64.lower(amount_msat)) + ) + + + + + + def send(self, invoice: "str",amount_msat: "typing.Optional[int]") -> "SendResponse": + _UniffiConverterString.check_lower(invoice) + + _UniffiConverterOptionalUInt64.check_lower(amount_msat) + + return _UniffiConverterTypeSendResponse.lift( + _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_node_send,self._uniffi_clone_pointer(), + _UniffiConverterString.lower(invoice), + _UniffiConverterOptionalUInt64.lower(amount_msat)) + ) + + + + + + def stop(self, ) -> None: + """ + Stop the node if it is currently running. + """ + + _uniffi_rust_call_with_error(_UniffiConverterTypeError,_UniffiLib.uniffi_glsdk_fn_method_node_stop,self._uniffi_clone_pointer(),) + + + + + + class _UniffiConverterTypeNode: @@ -1485,6 +1957,174 @@ def read(cls, buf: _UniffiRustBuffer): @classmethod def write(cls, value: NodeProtocol, buf: _UniffiRustBuffer): buf.write_u64(cls.lower(value)) +class OnchainReceiveResponseProtocol(typing.Protocol): + pass +# OnchainReceiveResponse is a Rust-only trait - it's a wrapper around a Rust implementation. +class OnchainReceiveResponse(): + _pointer: ctypes.c_void_p + + def __init__(self, *args, **kwargs): + raise ValueError("This class has no default constructor") + + def __del__(self): + # In case of partial initialization of instances. + pointer = getattr(self, "_pointer", None) + if pointer is not None: + _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_free_onchainreceiveresponse, pointer) + + def _uniffi_clone_pointer(self): + return _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_clone_onchainreceiveresponse, self._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 _UniffiConverterTypeOnchainReceiveResponse: + + @staticmethod + def lift(value: int): + return OnchainReceiveResponse._make_instance_(value) + + @staticmethod + def check_lower(value: OnchainReceiveResponse): + if not isinstance(value, OnchainReceiveResponse): + raise TypeError("Expected OnchainReceiveResponse instance, {} found".format(type(value).__name__)) + + @staticmethod + def lower(value: OnchainReceiveResponseProtocol): + if not isinstance(value, OnchainReceiveResponse): + raise TypeError("Expected OnchainReceiveResponse instance, {} found".format(type(value).__name__)) + return value._uniffi_clone_pointer() + + @classmethod + def read(cls, buf: _UniffiRustBuffer): + ptr = buf.read_u64() + if ptr == 0: + raise InternalError("Raw pointer value was null") + return cls.lift(ptr) + + @classmethod + def write(cls, value: OnchainReceiveResponseProtocol, buf: _UniffiRustBuffer): + buf.write_u64(cls.lower(value)) +class OnchainSendResponseProtocol(typing.Protocol): + pass +# OnchainSendResponse is a Rust-only trait - it's a wrapper around a Rust implementation. +class OnchainSendResponse(): + _pointer: ctypes.c_void_p + + def __init__(self, *args, **kwargs): + raise ValueError("This class has no default constructor") + + def __del__(self): + # In case of partial initialization of instances. + pointer = getattr(self, "_pointer", None) + if pointer is not None: + _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_free_onchainsendresponse, pointer) + + def _uniffi_clone_pointer(self): + return _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_clone_onchainsendresponse, self._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 _UniffiConverterTypeOnchainSendResponse: + + @staticmethod + def lift(value: int): + return OnchainSendResponse._make_instance_(value) + + @staticmethod + def check_lower(value: OnchainSendResponse): + if not isinstance(value, OnchainSendResponse): + raise TypeError("Expected OnchainSendResponse instance, {} found".format(type(value).__name__)) + + @staticmethod + def lower(value: OnchainSendResponseProtocol): + if not isinstance(value, OnchainSendResponse): + raise TypeError("Expected OnchainSendResponse instance, {} found".format(type(value).__name__)) + return value._uniffi_clone_pointer() + + @classmethod + def read(cls, buf: _UniffiRustBuffer): + ptr = buf.read_u64() + if ptr == 0: + raise InternalError("Raw pointer value was null") + return cls.lift(ptr) + + @classmethod + def write(cls, value: OnchainSendResponseProtocol, buf: _UniffiRustBuffer): + buf.write_u64(cls.lower(value)) +class ReceiveResponseProtocol(typing.Protocol): + pass +# ReceiveResponse is a Rust-only trait - it's a wrapper around a Rust implementation. +class ReceiveResponse(): + _pointer: ctypes.c_void_p + + def __init__(self, *args, **kwargs): + raise ValueError("This class has no default constructor") + + def __del__(self): + # In case of partial initialization of instances. + pointer = getattr(self, "_pointer", None) + if pointer is not None: + _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_free_receiveresponse, pointer) + + def _uniffi_clone_pointer(self): + return _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_clone_receiveresponse, self._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 _UniffiConverterTypeReceiveResponse: + + @staticmethod + def lift(value: int): + return ReceiveResponse._make_instance_(value) + + @staticmethod + def check_lower(value: ReceiveResponse): + if not isinstance(value, ReceiveResponse): + raise TypeError("Expected ReceiveResponse instance, {} found".format(type(value).__name__)) + + @staticmethod + def lower(value: ReceiveResponseProtocol): + if not isinstance(value, ReceiveResponse): + raise TypeError("Expected ReceiveResponse instance, {} found".format(type(value).__name__)) + return value._uniffi_clone_pointer() + + @classmethod + def read(cls, buf: _UniffiRustBuffer): + ptr = buf.read_u64() + if ptr == 0: + raise InternalError("Raw pointer value was null") + return cls.lift(ptr) + + @classmethod + def write(cls, value: ReceiveResponseProtocol, buf: _UniffiRustBuffer): + buf.write_u64(cls.lower(value)) class SchedulerProtocol(typing.Protocol): def recover(self, signer: "Signer"): raise NotImplementedError @@ -1578,6 +2218,62 @@ def read(cls, buf: _UniffiRustBuffer): @classmethod def write(cls, value: SchedulerProtocol, buf: _UniffiRustBuffer): buf.write_u64(cls.lower(value)) +class SendResponseProtocol(typing.Protocol): + pass +# SendResponse is a Rust-only trait - it's a wrapper around a Rust implementation. +class SendResponse(): + _pointer: ctypes.c_void_p + + def __init__(self, *args, **kwargs): + raise ValueError("This class has no default constructor") + + def __del__(self): + # In case of partial initialization of instances. + pointer = getattr(self, "_pointer", None) + if pointer is not None: + _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_free_sendresponse, pointer) + + def _uniffi_clone_pointer(self): + return _uniffi_rust_call(_UniffiLib.uniffi_glsdk_fn_clone_sendresponse, self._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 _UniffiConverterTypeSendResponse: + + @staticmethod + def lift(value: int): + return SendResponse._make_instance_(value) + + @staticmethod + def check_lower(value: SendResponse): + if not isinstance(value, SendResponse): + raise TypeError("Expected SendResponse instance, {} found".format(type(value).__name__)) + + @staticmethod + def lower(value: SendResponseProtocol): + if not isinstance(value, SendResponse): + raise TypeError("Expected SendResponse instance, {} found".format(type(value).__name__)) + return value._uniffi_clone_pointer() + + @classmethod + def read(cls, buf: _UniffiRustBuffer): + ptr = buf.read_u64() + if ptr == 0: + raise InternalError("Raw pointer value was null") + return cls.lift(ptr) + + @classmethod + def write(cls, value: SendResponseProtocol, buf: _UniffiRustBuffer): + buf.write_u64(cls.lower(value)) class SignerProtocol(typing.Protocol): def authenticate(self, creds: "Credentials"): raise NotImplementedError @@ -1678,10 +2374,15 @@ def write(cls, value: SignerProtocol, buf: _UniffiRustBuffer): "InternalError", "Error", "Network", + "PayStatus", "Credentials", "Handle", "Node", + "OnchainReceiveResponse", + "OnchainSendResponse", + "ReceiveResponse", "Scheduler", + "SendResponse", "Signer", ] diff --git a/libs/gl-sdk/src/lib.rs b/libs/gl-sdk/src/lib.rs index 1e9aba787..1e0a8a97b 100644 --- a/libs/gl-sdk/src/lib.rs +++ b/libs/gl-sdk/src/lib.rs @@ -1,27 +1,128 @@ +use std::collections::HashMap; + uniffi::setup_scaffolding!(); #[derive(uniffi::Error, thiserror::Error, Debug)] pub enum Error { - #[error("There is already a node for node_id={0}, maybe you want to recover?")] - DuplicateNode(String), + #[error("{message}")] + DuplicateNode { + code: i32, + message: String, + values: HashMap, + }, + + #[error("{message}")] + NoSuchNode { + code: i32, + message: String, + values: HashMap, + }, + + #[error("{message}")] + UnparseableCreds { + code: i32, + message: String, + values: HashMap, + }, + + #[error("{message}")] + PhraseCorrupted { + code: i32, + message: String, + values: HashMap, + }, + + #[error("{message}")] + Rpc { + code: i32, + message: String, + values: HashMap, + }, + + #[error("{message}")] + Argument { + code: i32, + message: String, + values: HashMap, + }, + + #[error("{message}")] + Other { + code: i32, + message: String, + values: HashMap, + }, +} + +impl Error { + pub fn duplicate_node(node_id: impl Into) -> Self { + let node_id = node_id.into(); + Error::DuplicateNode { + code: 1000, + message: format!( + "There is already a node for node_id={node_id}, maybe you want to recover?" + ), + values: HashMap::from([("node_id".into(), node_id)]), + } + } + + pub fn no_such_node(node_id: impl Into) -> Self { + let node_id = node_id.into(); + Error::NoSuchNode { + code: 1001, + message: format!( + "There is no node with node_id={node_id}, maybe you need to register first?" + ), + values: HashMap::from([("node_id".into(), node_id)]), + } + } - #[error("There is no node with node_id={0}, maybe you need to register first?")] - NoSuchNode(String), + pub fn unparseable_creds() -> Self { + Error::UnparseableCreds { + code: 1100, + message: "The provided credentials could not be parsed, please recover.".into(), + values: HashMap::new(), + } + } - #[error("The provided credentials could not be parsed, please recover.")] - UnparseableCreds(), + pub fn phrase_corrupted() -> Self { + Error::PhraseCorrupted { + code: 1101, + message: "The passphrase you provided fails the checksum".into(), + values: HashMap::new(), + } + } - #[error("The passphrase you provided fails the checksum")] - PhraseCorrupted(), + pub fn rpc(detail: impl Into) -> Self { + let detail = detail.into(); + Error::Rpc { + code: 2000, + message: format!("Error calling the rpc: {detail}"), + values: HashMap::from([("detail".into(), detail)]), + } + } - #[error("Error calling the rpc: {0}")] - Rpc(String), + pub fn argument(arg_name: impl Into, arg_value: impl Into) -> Self { + let arg_name = arg_name.into(); + let arg_value = arg_value.into(); + Error::Argument { + code: 3000, + message: format!("Invalid argument: {arg_name}={arg_value}"), + values: HashMap::from([ + ("arg_name".into(), arg_name), + ("arg_value".into(), arg_value), + ]), + } + } - #[error("Invalid argument: {0}={1}")] - Argument(String, String), - - #[error("Generic error: {0}")] - Other(String), + pub fn other(detail: impl Into) -> Self { + let detail = detail.into(); + Error::Other { + code: 9000, + message: format!("Generic error: {detail}"), + values: HashMap::from([("detail".into(), detail)]), + } + } } mod credentials; mod node; diff --git a/libs/gl-sdk/src/node.rs b/libs/gl-sdk/src/node.rs index e44a8ef2d..5842a28fa 100644 --- a/libs/gl-sdk/src/node.rs +++ b/libs/gl-sdk/src/node.rs @@ -22,7 +22,7 @@ impl Node { let node_id = credentials .inner .node_id() - .map_err(|_e| Error::UnparseableCreds())?; + .map_err(|_e| Error::unparseable_creds())?; let inner = ClientNode::new(node_id, credentials.inner.clone()) .expect("infallible client instantiation"); @@ -74,7 +74,7 @@ impl Node { token: "".to_owned(), }; let res = exec(gl_client.lsp_invoice(req)) - .map_err(|s| Error::Rpc(s.to_string()))? + .map_err(|s| Error::rpc(s.to_string()))? .into_inner(); Ok(ReceiveResponse { bolt11: res.bolt11 }) } @@ -101,7 +101,7 @@ impl Node { riskfactor: None, }; exec(cln_client.pay(req)) - .map_err(|e| Error::Rpc(e.to_string())) + .map_err(|e| Error::rpc(e.to_string())) .map(|r| r.into_inner().into()) } @@ -141,7 +141,7 @@ impl Node { (0, "all") => clnpb::AmountOrAll { value: Some(clnpb::amount_or_all::Value::All(true)), }, - (_, _) => return Err(Error::Argument("amount_or_all".to_owned(), amount_or_all)), + (_, _) => return Err(Error::argument("amount_or_all", amount_or_all)), }; let req = clnpb::WithdrawRequest { @@ -153,7 +153,7 @@ impl Node { }; exec(cln_client.withdraw(req)) - .map_err(|e| Error::Rpc(e.to_string())) + .map_err(|e| Error::rpc(e.to_string())) .map(|r| r.into_inner().into()) } @@ -165,7 +165,7 @@ impl Node { }; let res = exec(cln_client.new_addr(req)) - .map_err(|e| Error::Rpc(e.to_string()))? + .map_err(|e| Error::rpc(e.to_string()))? .into_inner(); Ok(res.into()) } @@ -178,7 +178,7 @@ impl Node { self.gl_client .get_or_try_init(|| async { inner.schedule::().await }) .await - .map_err(|e| Error::Rpc(e.to_string())) + .map_err(|e| Error::rpc(e.to_string())) } async fn get_cln_client<'a>(&'a self) -> Result<&'a ClnClient, Error> { @@ -187,7 +187,7 @@ impl Node { self.cln_client .get_or_try_init(|| async { inner.schedule::().await }) .await - .map_err(|e| Error::Rpc(e.to_string())) + .map_err(|e| Error::rpc(e.to_string())) } } diff --git a/libs/gl-sdk/src/scheduler.rs b/libs/gl-sdk/src/scheduler.rs index 172c406d4..97d1a1e07 100644 --- a/libs/gl-sdk/src/scheduler.rs +++ b/libs/gl-sdk/src/scheduler.rs @@ -30,14 +30,14 @@ impl Scheduler { gl_client::credentials::Nobody::new(), ) .await - .map_err(|e| Error::Other(e.to_string()))?; + .map_err(|e| Error::other(e.to_string()))?; let res = inner .register(&signer.inner, code) .await - .map_err(|e| Error::Other(e.to_string().clone()))?; + .map_err(|e| Error::other(e.to_string()))?; - Credentials::load(res.creds).map_err(|_e| Error::UnparseableCreds()) + Credentials::load(res.creds).map_err(|_e| Error::unparseable_creds()) }) } @@ -48,14 +48,14 @@ impl Scheduler { gl_client::credentials::Nobody::new(), ) .await - .map_err(|e| Error::Other(e.to_string()))?; + .map_err(|e| Error::other(e.to_string()))?; let res = inner .recover(&signer.inner) .await - .map_err(|e| Error::Other(e.to_string()))?; + .map_err(|e| Error::other(e.to_string()))?; - Credentials::load(res.creds).map_err(|_e| Error::UnparseableCreds()) + Credentials::load(res.creds).map_err(|_e| Error::unparseable_creds()) }) } } diff --git a/libs/gl-sdk/src/signer.rs b/libs/gl-sdk/src/signer.rs index b9da527f5..8399a7d20 100644 --- a/libs/gl-sdk/src/signer.rs +++ b/libs/gl-sdk/src/signer.rs @@ -14,7 +14,7 @@ pub struct Signer { impl Signer { #[uniffi::constructor()] fn new(phrase: String) -> Result { - let phrase = Mnemonic::from_str(phrase.as_str()).map_err(|_e| Error::PhraseCorrupted())?; + let phrase = Mnemonic::from_str(phrase.as_str()).map_err(|_e| Error::phrase_corrupted())?; let seed = phrase.to_seed_normalized(&"").to_vec(); // FIXME: We may need to give the signer real credentials to @@ -26,7 +26,7 @@ impl Signer { gl_client::bitcoin::Network::Bitcoin, credentials, ) - .map_err(|e| Error::Other(e.to_string()))?; + .map_err(|e| Error::other(e.to_string()))?; let credentials = None; Ok(Signer { seed, @@ -43,7 +43,7 @@ impl Signer { gl_client::bitcoin::Network::Bitcoin, creds.inner.clone(), ) - .map_err(|e| Error::Other(e.to_string()))?; + .map_err(|e| Error::other(e.to_string()))?; Ok(Signer { inner, From cfce6c1473d2a42e2f9ac7e5cdda72972a36238d Mon Sep 17 00:00:00 2001 From: Christian Decker Date: Wed, 13 May 2026 18:13:15 +0200 Subject: [PATCH 2/2] sdk: Regenerate Kotlin, Swift, and Ruby bindings Co-Authored-By: Claude Opus 4.6 (1M context) --- libs/gl-sdk/bindings/glsdk.rb | 1662 ++++++++ libs/gl-sdk/bindings/glsdk.swift | 2188 +++++++++++ libs/gl-sdk/bindings/glsdkFFI.h | 806 ++++ libs/gl-sdk/bindings/glsdkFFI.modulemap | 7 + libs/gl-sdk/bindings/uniffi/glsdk/glsdk.kt | 4059 ++++++++++++++++++++ 5 files changed, 8722 insertions(+) create mode 100644 libs/gl-sdk/bindings/glsdk.rb create mode 100644 libs/gl-sdk/bindings/glsdk.swift create mode 100644 libs/gl-sdk/bindings/glsdkFFI.h create mode 100644 libs/gl-sdk/bindings/glsdkFFI.modulemap create mode 100644 libs/gl-sdk/bindings/uniffi/glsdk/glsdk.kt diff --git a/libs/gl-sdk/bindings/glsdk.rb b/libs/gl-sdk/bindings/glsdk.rb new file mode 100644 index 000000000..cf0111603 --- /dev/null +++ b/libs/gl-sdk/bindings/glsdk.rb @@ -0,0 +1,1662 @@ +# 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 .rb 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 Ruby +# helpers directly inline like we're doing here. + +require 'ffi' + + +module Glsdk + def self.uniffi_in_range(i, type_name, min, max) + raise TypeError, "no implicit conversion of #{i} into Integer" unless i.respond_to?(:to_int) + i = i.to_int + raise RangeError, "#{type_name} requires #{min} <= value < #{max}" unless (min <= i && i < max) + i +end + +def self.uniffi_utf8(v) + raise TypeError, "no implicit conversion of #{v} into String" unless v.respond_to?(:to_str) + v = v.to_str.encode(Encoding::UTF_8) + raise Encoding::InvalidByteSequenceError, "not a valid UTF-8 encoded string" unless v.valid_encoding? + v +end + +def self.uniffi_bytes(v) + raise TypeError, "no implicit conversion of #{v} into String" unless v.respond_to?(:to_str) + v.to_str +end + + class RustBuffer < FFI::Struct + layout :capacity, :uint64, + :len, :uint64, + :data, :pointer + + def self.alloc(size) + return Glsdk.rust_call(:ffi_glsdk_rustbuffer_alloc, size) + end + + def self.reserve(rbuf, additional) + return Glsdk.rust_call(:ffi_glsdk_rustbuffer_reserve, rbuf, additional) + end + + def free + Glsdk.rust_call(:ffi_glsdk_rustbuffer_free, self) + end + + def capacity + self[:capacity] + end + + def len + self[:len] + end + + def len=(value) + self[:len] = value + end + + def data + self[:data] + end + + def to_s + "RustBuffer(capacity=#{capacity}, len=#{len}, data=#{data.read_bytes len})" + end + + # The allocated buffer will be automatically freed if an error occurs, ensuring that + # we don't accidentally leak it. + def self.allocWithBuilder + builder = RustBufferBuilder.new + + begin + yield builder + rescue => e + builder.discard + raise e + end + end + + # The RustBuffer will be freed once the context-manager exits, ensuring that we don't + # leak it even if an error occurs. + def consumeWithStream + stream = RustBufferStream.new self + + yield stream + + raise RuntimeError, 'junk data left in buffer after consuming' if stream.remaining != 0 + ensure + free + end# The primitive String type. + + def self.allocFromString(value) + RustBuffer.allocWithBuilder do |builder| + builder.write value.encode('utf-8') + return builder.finalize + end + end + + def consumeIntoString + consumeWithStream do |stream| + return stream.read(stream.remaining).force_encoding(Encoding::UTF_8) + end + end + + # The primitive Bytes type. + + def self.allocFromBytes(value) + RustBuffer.allocWithBuilder do |builder| + builder.write_Bytes(value) + return builder.finalize + end + end + + def consumeIntoBytes + consumeWithStream do |stream| + return stream.readBytes + end + end + + + + # The Enum type Network. + + def self.check_lower_TypeNetwork(v) + end + + def self.alloc_from_TypeNetwork(v) + RustBuffer.allocWithBuilder do |builder| + builder.write_TypeNetwork(v) + return builder.finalize + end + end + + def consumeIntoTypeNetwork + consumeWithStream do |stream| + return stream.readTypeNetwork + end + end + + + # The Enum type PayStatus. + + def self.check_lower_TypePayStatus(v) + end + + def self.alloc_from_TypePayStatus(v) + RustBuffer.allocWithBuilder do |builder| + builder.write_TypePayStatus(v) + return builder.finalize + end + end + + def consumeIntoTypePayStatus + consumeWithStream do |stream| + return stream.readTypePayStatus + end + end + + + # The Optional type for u64. + + def self.check_lower_Optionalu64(v) + if not v.nil? + + end + end + + def self.alloc_from_Optionalu64(v) + RustBuffer.allocWithBuilder do |builder| + builder.write_Optionalu64(v) + return builder.finalize() + end + end + + def consumeIntoOptionalu64 + consumeWithStream do |stream| + return stream.readOptionalu64 + end + end + + # The Optional type for string. + + def self.check_lower_Optionalstring(v) + if not v.nil? + + end + end + + def self.alloc_from_Optionalstring(v) + RustBuffer.allocWithBuilder do |builder| + builder.write_Optionalstring(v) + return builder.finalize() + end + end + + def consumeIntoOptionalstring + consumeWithStream do |stream| + return stream.readOptionalstring + end + end + + # The Map type for string. + + def self.check_lower_MapStringString(v) + v.each do |k, v| + + + end + end + + def self.alloc_from_MapStringString(v) + RustBuffer.allocWithBuilder do |builder| + builder.write_MapStringString(v) + return builder.finalize + end + end + + def consumeIntoMapStringString + consumeWithStream do |stream| + return stream.readMapStringString + end + end +end + +module UniFFILib + class ForeignBytes < FFI::Struct + layout :len, :int32, + :data, :pointer + + def len + self[:len] + end + + def data + self[:data] + end + + def to_s + "ForeignBytes(len=#{len}, data=#{data.read_bytes(len)})" + end + end +end + +private_constant :UniFFILib + +# Helper for structured reading of values from a RustBuffer. +class RustBufferStream + + def initialize(rbuf) + @rbuf = rbuf + @offset = 0 + end + + def remaining + @rbuf.len - @offset + end + + def read(size) + raise InternalError, 'read past end of rust buffer' if @offset + size > @rbuf.len + + data = @rbuf.data.get_bytes @offset, size + + @offset += size + + data + end + + def readI32 + unpack_from 4, 'l>' + end + + def readU64 + unpack_from 8, 'Q>' + end + + def readString + size = unpack_from 4, 'l>' + + raise InternalError, 'Unexpected negative string length' if size.negative? + + read(size).force_encoding(Encoding::UTF_8) + end + + def readBytes + size = unpack_from 4, 'l>' + + raise InternalError, 'Unexpected negative byte string length' if size.negative? + + read(size).force_encoding(Encoding::BINARY) + end + + # The Object type Credentials. + + def readTypeCredentials + pointer = FFI::Pointer.new unpack_from 8, 'Q>' + return Credentials.uniffi_allocate(pointer) + end + + # The Object type Handle. + + def readTypeHandle + pointer = FFI::Pointer.new unpack_from 8, 'Q>' + return Handle.uniffi_allocate(pointer) + end + + # The Object type Node. + + def readTypeNode + pointer = FFI::Pointer.new unpack_from 8, 'Q>' + return Node.uniffi_allocate(pointer) + end + + # The Object type OnchainReceiveResponse. + + def readTypeOnchainReceiveResponse + pointer = FFI::Pointer.new unpack_from 8, 'Q>' + return OnchainReceiveResponse.uniffi_allocate(pointer) + end + + # The Object type OnchainSendResponse. + + def readTypeOnchainSendResponse + pointer = FFI::Pointer.new unpack_from 8, 'Q>' + return OnchainSendResponse.uniffi_allocate(pointer) + end + + # The Object type ReceiveResponse. + + def readTypeReceiveResponse + pointer = FFI::Pointer.new unpack_from 8, 'Q>' + return ReceiveResponse.uniffi_allocate(pointer) + end + + # The Object type Scheduler. + + def readTypeScheduler + pointer = FFI::Pointer.new unpack_from 8, 'Q>' + return Scheduler.uniffi_allocate(pointer) + end + + # The Object type SendResponse. + + def readTypeSendResponse + pointer = FFI::Pointer.new unpack_from 8, 'Q>' + return SendResponse.uniffi_allocate(pointer) + end + + # The Object type Signer. + + def readTypeSigner + pointer = FFI::Pointer.new unpack_from 8, 'Q>' + return Signer.uniffi_allocate(pointer) + end + + + + + + # The Error type Error + + def readTypeError + variant = unpack_from 4, 'l>' + + if variant == 1 + return Error::DuplicateNode.new( + readI32(), + readString(), + readMapStringString() + ) + end + if variant == 2 + return Error::NoSuchNode.new( + readI32(), + readString(), + readMapStringString() + ) + end + if variant == 3 + return Error::UnparseableCreds.new( + readI32(), + readString(), + readMapStringString() + ) + end + if variant == 4 + return Error::PhraseCorrupted.new( + readI32(), + readString(), + readMapStringString() + ) + end + if variant == 5 + return Error::Rpc.new( + readI32(), + readString(), + readMapStringString() + ) + end + if variant == 6 + return Error::Argument.new( + readI32(), + readString(), + readMapStringString() + ) + end + if variant == 7 + return Error::Other.new( + readI32(), + readString(), + readMapStringString() + ) + end + + raise InternalError, 'Unexpected variant tag for TypeError' + end + + + + + # The Enum type Network. + + def readTypeNetwork + variant = unpack_from 4, 'l>' + + if variant == 1 + return Network::BITCOIN + end + if variant == 2 + return Network::REGTEST + end + + raise InternalError, 'Unexpected variant tag for TypeNetwork' + end + + + + + + # The Enum type PayStatus. + + def readTypePayStatus + variant = unpack_from 4, 'l>' + + if variant == 1 + return PayStatus::COMPLETE + end + if variant == 2 + return PayStatus::PENDING + end + if variant == 3 + return PayStatus::FAILED + end + + raise InternalError, 'Unexpected variant tag for TypePayStatus' + end + + + + # The Optional type for u64. + + def readOptionalu64 + flag = unpack_from 1, 'c' + + if flag == 0 + return nil + elsif flag == 1 + return readU64 + else + raise InternalError, 'Unexpected flag byte for Optionalu64' + end + end + + # The Optional type for string. + + def readOptionalstring + flag = unpack_from 1, 'c' + + if flag == 0 + return nil + elsif flag == 1 + return readString + else + raise InternalError, 'Unexpected flag byte for Optionalstring' + end + end + + # The Map type for string. + + def readMapStringString + count = unpack_from 4, 'l>' + raise InternalError, 'Unexpected negative map size' if count.negative? + + items = {} + count.times do + key = readString + items[key] = readString + end + + items + end + + def unpack_from(size, format) + raise InternalError, 'read past end of rust buffer' if @offset + size > @rbuf.len + + value = @rbuf.data.get_bytes(@offset, size).unpack format + + @offset += size + + # TODO: verify this + raise 'more than one element!!!' if value.size > 1 + + value[0] + end +end + +private_constant :RustBufferStream + +# Helper for structured writing of values into a RustBuffer. +class RustBufferBuilder + def initialize + @rust_buf = RustBuffer.alloc 16 + @rust_buf.len = 0 + end + + def finalize + rbuf = @rust_buf + + @rust_buf = nil + + rbuf + end + + def discard + return if @rust_buf.nil? + + rbuf = finalize + rbuf.free + end + + def write(value) + reserve(value.bytes.size) do + @rust_buf.data.put_array_of_char @rust_buf.len, value.bytes + end + end + + def write_I32(v) + v = Glsdk::uniffi_in_range(v, "i32", -2**31, 2**31) + pack_into(4, 'l>', v) + end + + def write_U64(v) + v = Glsdk::uniffi_in_range(v, "u64", 0, 2**64) + pack_into(8, 'Q>', v) + end + + def write_String(v) + v = Glsdk::uniffi_utf8(v) + pack_into 4, 'l>', v.bytes.size + write v + end + + def write_Bytes(v) + v = Glsdk::uniffi_bytes(v) + pack_into 4, 'l>', v.bytes.size + write v + end + + # The Object type Credentials. + + def write_TypeCredentials(obj) + pointer = Credentials.uniffi_lower obj + pack_into(8, 'Q>', pointer.address) + end + + # The Object type Handle. + + def write_TypeHandle(obj) + pointer = Handle.uniffi_lower obj + pack_into(8, 'Q>', pointer.address) + end + + # The Object type Node. + + def write_TypeNode(obj) + pointer = Node.uniffi_lower obj + pack_into(8, 'Q>', pointer.address) + end + + # The Object type OnchainReceiveResponse. + + def write_TypeOnchainReceiveResponse(obj) + pointer = OnchainReceiveResponse.uniffi_lower obj + pack_into(8, 'Q>', pointer.address) + end + + # The Object type OnchainSendResponse. + + def write_TypeOnchainSendResponse(obj) + pointer = OnchainSendResponse.uniffi_lower obj + pack_into(8, 'Q>', pointer.address) + end + + # The Object type ReceiveResponse. + + def write_TypeReceiveResponse(obj) + pointer = ReceiveResponse.uniffi_lower obj + pack_into(8, 'Q>', pointer.address) + end + + # The Object type Scheduler. + + def write_TypeScheduler(obj) + pointer = Scheduler.uniffi_lower obj + pack_into(8, 'Q>', pointer.address) + end + + # The Object type SendResponse. + + def write_TypeSendResponse(obj) + pointer = SendResponse.uniffi_lower obj + pack_into(8, 'Q>', pointer.address) + end + + # The Object type Signer. + + def write_TypeSigner(obj) + pointer = Signer.uniffi_lower obj + pack_into(8, 'Q>', pointer.address) + end + + + + # The Enum type Network. + + def write_TypeNetwork(v) + pack_into(4, 'l>', v) + end + + + # The Enum type PayStatus. + + def write_TypePayStatus(v) + pack_into(4, 'l>', v) + end + + + # The Optional type for u64. + + def write_Optionalu64(v) + if v.nil? + pack_into(1, 'c', 0) + else + pack_into(1, 'c', 1) + self.write_U64(v) + end + end + + # The Optional type for string. + + def write_Optionalstring(v) + if v.nil? + pack_into(1, 'c', 0) + else + pack_into(1, 'c', 1) + self.write_String(v) + end + end + + # The Map type for string. + + def write_MapStringString(items) + pack_into(4, 'l>', items.size) + + items.each do |k, v| + write_String(k) + self.write_String(v) + end + end + + private + + def reserve(num_bytes) + if @rust_buf.len + num_bytes > @rust_buf.capacity + @rust_buf = RustBuffer.reserve(@rust_buf, num_bytes) + end + + yield + + @rust_buf.len += num_bytes + end + + def pack_into(size, format, value) + reserve(size) do + @rust_buf.data.put_array_of_char @rust_buf.len, [value].pack(format).bytes + end + end +end + +private_constant :RustBufferBuilder + + # Error definitions + class RustCallStatus < FFI::Struct + layout :code, :int8, + :error_buf, RustBuffer + + def code + self[:code] + end + + def error_buf + self[:error_buf] + end + + def to_s + "RustCallStatus(code=#{self[:code]})" + end +end + +# These match the values from the uniffi::rustcalls module +CALL_SUCCESS = 0 +CALL_ERROR = 1 +CALL_PANIC = 2 + + +module Error + class DuplicateNode < StandardError + def initialize(code, message, values) + @code = code + @message = message + @values = values + super() + end + + attr_reader :code, :message, :values + + + def to_s + "#{self.class.name}(code=#{@code.inspect}, message=#{@message.inspect}, values=#{@values.inspect})" + end + end + class NoSuchNode < StandardError + def initialize(code, message, values) + @code = code + @message = message + @values = values + super() + end + + attr_reader :code, :message, :values + + + def to_s + "#{self.class.name}(code=#{@code.inspect}, message=#{@message.inspect}, values=#{@values.inspect})" + end + end + class UnparseableCreds < StandardError + def initialize(code, message, values) + @code = code + @message = message + @values = values + super() + end + + attr_reader :code, :message, :values + + + def to_s + "#{self.class.name}(code=#{@code.inspect}, message=#{@message.inspect}, values=#{@values.inspect})" + end + end + class PhraseCorrupted < StandardError + def initialize(code, message, values) + @code = code + @message = message + @values = values + super() + end + + attr_reader :code, :message, :values + + + def to_s + "#{self.class.name}(code=#{@code.inspect}, message=#{@message.inspect}, values=#{@values.inspect})" + end + end + class Rpc < StandardError + def initialize(code, message, values) + @code = code + @message = message + @values = values + super() + end + + attr_reader :code, :message, :values + + + def to_s + "#{self.class.name}(code=#{@code.inspect}, message=#{@message.inspect}, values=#{@values.inspect})" + end + end + class Argument < StandardError + def initialize(code, message, values) + @code = code + @message = message + @values = values + super() + end + + attr_reader :code, :message, :values + + + def to_s + "#{self.class.name}(code=#{@code.inspect}, message=#{@message.inspect}, values=#{@values.inspect})" + end + end + class Other < StandardError + def initialize(code, message, values) + @code = code + @message = message + @values = values + super() + end + + attr_reader :code, :message, :values + + + def to_s + "#{self.class.name}(code=#{@code.inspect}, message=#{@message.inspect}, values=#{@values.inspect})" + end + end + +end + + + + +# Map error modules to the RustBuffer method name that reads them +ERROR_MODULE_TO_READER_METHOD = { + + Error => :readTypeError, + + + +} + +private_constant :ERROR_MODULE_TO_READER_METHOD, :CALL_SUCCESS, :CALL_ERROR, :CALL_PANIC, + :RustCallStatus + +def self.consume_buffer_into_error(error_module, rust_buffer) + rust_buffer.consumeWithStream do |stream| + reader_method = ERROR_MODULE_TO_READER_METHOD[error_module] + return stream.send(reader_method) + end +end + +class InternalError < StandardError +end + +def self.rust_call(fn_name, *args) + # Call a rust function + rust_call_with_error(nil, fn_name, *args) +end + +def self.rust_call_with_error(error_module, fn_name, *args) + # Call a rust function and handle errors + # + # Use this when the rust function returns a Result<>. error_module must be the error_module that corresponds to that Result. + + + # Note: RustCallStatus.new zeroes out the struct, which is exactly what we + # want to pass to Rust (code=0, error_buf=RustBuffer(len=0, capacity=0, + # data=NULL)) + status = RustCallStatus.new + args << status + + result = UniFFILib.public_send(fn_name, *args) + + case status.code + when CALL_SUCCESS + result + when CALL_ERROR + if error_module.nil? + status.error_buf.free + raise InternalError, "CALL_ERROR with no error_module set" + else + raise consume_buffer_into_error(error_module, status.error_buf) + end + when 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 status.error_buf.len > 0 + raise InternalError, status.error_buf.consumeIntoString() + else + raise InternalError, "Rust panic" + end + else + raise InternalError, "Unknown call status: #{status.code}" + end +end + +private_class_method :consume_buffer_into_error + + # This is how we find and load the dynamic library provided by the component. +# For now we just look it up by name. +module UniFFILib + extend FFI::Library + + + ffi_lib 'glsdk' + + + attach_function :uniffi_glsdk_fn_clone_credentials, + [:pointer, RustCallStatus.by_ref], + :pointer + attach_function :uniffi_glsdk_fn_free_credentials, + [:pointer, RustCallStatus.by_ref], + :void + attach_function :uniffi_glsdk_fn_constructor_credentials_load, + [RustBuffer.by_value, RustCallStatus.by_ref], + :pointer + attach_function :uniffi_glsdk_fn_method_credentials_save, + [:pointer, RustCallStatus.by_ref], + RustBuffer.by_value + attach_function :uniffi_glsdk_fn_clone_handle, + [:pointer, RustCallStatus.by_ref], + :pointer + attach_function :uniffi_glsdk_fn_free_handle, + [:pointer, RustCallStatus.by_ref], + :void + attach_function :uniffi_glsdk_fn_method_handle_stop, + [:pointer, RustCallStatus.by_ref], + :void + attach_function :uniffi_glsdk_fn_clone_node, + [:pointer, RustCallStatus.by_ref], + :pointer + attach_function :uniffi_glsdk_fn_free_node, + [:pointer, RustCallStatus.by_ref], + :void + attach_function :uniffi_glsdk_fn_constructor_node_new, + [:pointer, RustCallStatus.by_ref], + :pointer + attach_function :uniffi_glsdk_fn_method_node_onchain_receive, + [:pointer, RustCallStatus.by_ref], + :pointer + attach_function :uniffi_glsdk_fn_method_node_onchain_send, + [:pointer, RustBuffer.by_value, RustBuffer.by_value, RustCallStatus.by_ref], + :pointer + attach_function :uniffi_glsdk_fn_method_node_receive, + [:pointer, RustBuffer.by_value, RustBuffer.by_value, RustBuffer.by_value, RustCallStatus.by_ref], + :pointer + attach_function :uniffi_glsdk_fn_method_node_send, + [:pointer, RustBuffer.by_value, RustBuffer.by_value, RustCallStatus.by_ref], + :pointer + attach_function :uniffi_glsdk_fn_method_node_stop, + [:pointer, RustCallStatus.by_ref], + :void + attach_function :uniffi_glsdk_fn_clone_onchainreceiveresponse, + [:pointer, RustCallStatus.by_ref], + :pointer + attach_function :uniffi_glsdk_fn_free_onchainreceiveresponse, + [:pointer, RustCallStatus.by_ref], + :void + attach_function :uniffi_glsdk_fn_clone_onchainsendresponse, + [:pointer, RustCallStatus.by_ref], + :pointer + attach_function :uniffi_glsdk_fn_free_onchainsendresponse, + [:pointer, RustCallStatus.by_ref], + :void + attach_function :uniffi_glsdk_fn_clone_receiveresponse, + [:pointer, RustCallStatus.by_ref], + :pointer + attach_function :uniffi_glsdk_fn_free_receiveresponse, + [:pointer, RustCallStatus.by_ref], + :void + attach_function :uniffi_glsdk_fn_clone_scheduler, + [:pointer, RustCallStatus.by_ref], + :pointer + attach_function :uniffi_glsdk_fn_free_scheduler, + [:pointer, RustCallStatus.by_ref], + :void + attach_function :uniffi_glsdk_fn_constructor_scheduler_new, + [RustBuffer.by_value, RustCallStatus.by_ref], + :pointer + attach_function :uniffi_glsdk_fn_method_scheduler_recover, + [:pointer, :pointer, RustCallStatus.by_ref], + :pointer + attach_function :uniffi_glsdk_fn_method_scheduler_register, + [:pointer, :pointer, RustBuffer.by_value, RustCallStatus.by_ref], + :pointer + attach_function :uniffi_glsdk_fn_clone_sendresponse, + [:pointer, RustCallStatus.by_ref], + :pointer + attach_function :uniffi_glsdk_fn_free_sendresponse, + [:pointer, RustCallStatus.by_ref], + :void + attach_function :uniffi_glsdk_fn_clone_signer, + [:pointer, RustCallStatus.by_ref], + :pointer + attach_function :uniffi_glsdk_fn_free_signer, + [:pointer, RustCallStatus.by_ref], + :void + attach_function :uniffi_glsdk_fn_constructor_signer_new, + [RustBuffer.by_value, RustCallStatus.by_ref], + :pointer + attach_function :uniffi_glsdk_fn_method_signer_authenticate, + [:pointer, :pointer, RustCallStatus.by_ref], + :pointer + attach_function :uniffi_glsdk_fn_method_signer_node_id, + [:pointer, RustCallStatus.by_ref], + RustBuffer.by_value + attach_function :uniffi_glsdk_fn_method_signer_start, + [:pointer, RustCallStatus.by_ref], + :pointer + attach_function :ffi_glsdk_rustbuffer_alloc, + [:uint64, RustCallStatus.by_ref], + RustBuffer.by_value + attach_function :ffi_glsdk_rustbuffer_from_bytes, + [ForeignBytes, RustCallStatus.by_ref], + RustBuffer.by_value + attach_function :ffi_glsdk_rustbuffer_free, + [RustBuffer.by_value, RustCallStatus.by_ref], + :void + attach_function :ffi_glsdk_rustbuffer_reserve, + [RustBuffer.by_value, :uint64, RustCallStatus.by_ref], + RustBuffer.by_value + attach_function :uniffi_glsdk_checksum_method_credentials_save, + [RustCallStatus.by_ref], + :uint16 + attach_function :uniffi_glsdk_checksum_method_handle_stop, + [RustCallStatus.by_ref], + :uint16 + attach_function :uniffi_glsdk_checksum_method_node_onchain_receive, + [RustCallStatus.by_ref], + :uint16 + attach_function :uniffi_glsdk_checksum_method_node_onchain_send, + [RustCallStatus.by_ref], + :uint16 + attach_function :uniffi_glsdk_checksum_method_node_receive, + [RustCallStatus.by_ref], + :uint16 + attach_function :uniffi_glsdk_checksum_method_node_send, + [RustCallStatus.by_ref], + :uint16 + attach_function :uniffi_glsdk_checksum_method_node_stop, + [RustCallStatus.by_ref], + :uint16 + attach_function :uniffi_glsdk_checksum_method_scheduler_recover, + [RustCallStatus.by_ref], + :uint16 + attach_function :uniffi_glsdk_checksum_method_scheduler_register, + [RustCallStatus.by_ref], + :uint16 + attach_function :uniffi_glsdk_checksum_method_signer_authenticate, + [RustCallStatus.by_ref], + :uint16 + attach_function :uniffi_glsdk_checksum_method_signer_node_id, + [RustCallStatus.by_ref], + :uint16 + attach_function :uniffi_glsdk_checksum_method_signer_start, + [RustCallStatus.by_ref], + :uint16 + attach_function :uniffi_glsdk_checksum_constructor_credentials_load, + [RustCallStatus.by_ref], + :uint16 + attach_function :uniffi_glsdk_checksum_constructor_node_new, + [RustCallStatus.by_ref], + :uint16 + attach_function :uniffi_glsdk_checksum_constructor_scheduler_new, + [RustCallStatus.by_ref], + :uint16 + attach_function :uniffi_glsdk_checksum_constructor_signer_new, + [RustCallStatus.by_ref], + :uint16 + attach_function :ffi_glsdk_uniffi_contract_version, + [RustCallStatus.by_ref], + :uint32 + +end + + # Public interface members begin here. + + + + + + +class Network + BITCOIN = 1 + REGTEST = 2 + +end + + + + + + +class PayStatus + COMPLETE = 1 + PENDING = 2 + FAILED = 3 + +end + + + + + + + + class Credentials + + # A private helper for initializing instances of the class from a raw pointer, + # bypassing any initialization logic and ensuring they are GC'd properly. + def self.uniffi_allocate(pointer) + pointer.autorelease = false + inst = allocate + inst.instance_variable_set :@pointer, pointer + ObjectSpace.define_finalizer(inst, uniffi_define_finalizer_by_pointer(pointer, inst.object_id)) + return inst + end + + # A private helper for registering an object finalizer. + # N.B. it's important that this does not capture a reference + # to the actual instance, only its underlying pointer. + def self.uniffi_define_finalizer_by_pointer(pointer, object_id) + Proc.new do |_id| + Glsdk.rust_call( + :uniffi_glsdk_fn_free_credentials, + pointer + ) + end + end + + # A private helper for lowering instances into a raw pointer. + # This does an explicit typecheck, because accidentally lowering a different type of + # object in a place where this type is expected, could lead to memory unsafety. + def self.uniffi_check_lower(inst) + if not inst.is_a? self + raise TypeError.new "Expected a Credentials instance, got #{inst}" + end + end + + def uniffi_clone_pointer() + return Glsdk.rust_call( + :uniffi_glsdk_fn_clone_credentials, + @pointer + ) + end + + def self.uniffi_lower(inst) + return inst.uniffi_clone_pointer() + end + + def self.load(raw) + raw = Glsdk::uniffi_bytes(raw) + + # Call the (fallible) function before creating any half-baked object instances. + # Lightly yucky way to bypass the usual "initialize" logic + # and just create a new instance with the required pointer. + return uniffi_allocate(Glsdk.rust_call_with_error(Error,:uniffi_glsdk_fn_constructor_credentials_load,RustBuffer.allocFromBytes(raw))) + end + + + def save() + result = Glsdk.rust_call_with_error(Error,:uniffi_glsdk_fn_method_credentials_save,uniffi_clone_pointer(),) + return result.consumeIntoBytes + end + +end + + class Handle + + # A private helper for initializing instances of the class from a raw pointer, + # bypassing any initialization logic and ensuring they are GC'd properly. + def self.uniffi_allocate(pointer) + pointer.autorelease = false + inst = allocate + inst.instance_variable_set :@pointer, pointer + ObjectSpace.define_finalizer(inst, uniffi_define_finalizer_by_pointer(pointer, inst.object_id)) + return inst + end + + # A private helper for registering an object finalizer. + # N.B. it's important that this does not capture a reference + # to the actual instance, only its underlying pointer. + def self.uniffi_define_finalizer_by_pointer(pointer, object_id) + Proc.new do |_id| + Glsdk.rust_call( + :uniffi_glsdk_fn_free_handle, + pointer + ) + end + end + + # A private helper for lowering instances into a raw pointer. + # This does an explicit typecheck, because accidentally lowering a different type of + # object in a place where this type is expected, could lead to memory unsafety. + def self.uniffi_check_lower(inst) + if not inst.is_a? self + raise TypeError.new "Expected a Handle instance, got #{inst}" + end + end + + def uniffi_clone_pointer() + return Glsdk.rust_call( + :uniffi_glsdk_fn_clone_handle, + @pointer + ) + end + + def self.uniffi_lower(inst) + return inst.uniffi_clone_pointer() + end + + + + def stop() + Glsdk.rust_call(:uniffi_glsdk_fn_method_handle_stop,uniffi_clone_pointer(),) + end + + +end + + class Node + + # A private helper for initializing instances of the class from a raw pointer, + # bypassing any initialization logic and ensuring they are GC'd properly. + def self.uniffi_allocate(pointer) + pointer.autorelease = false + inst = allocate + inst.instance_variable_set :@pointer, pointer + ObjectSpace.define_finalizer(inst, uniffi_define_finalizer_by_pointer(pointer, inst.object_id)) + return inst + end + + # A private helper for registering an object finalizer. + # N.B. it's important that this does not capture a reference + # to the actual instance, only its underlying pointer. + def self.uniffi_define_finalizer_by_pointer(pointer, object_id) + Proc.new do |_id| + Glsdk.rust_call( + :uniffi_glsdk_fn_free_node, + pointer + ) + end + end + + # A private helper for lowering instances into a raw pointer. + # This does an explicit typecheck, because accidentally lowering a different type of + # object in a place where this type is expected, could lead to memory unsafety. + def self.uniffi_check_lower(inst) + if not inst.is_a? self + raise TypeError.new "Expected a Node instance, got #{inst}" + end + end + + def uniffi_clone_pointer() + return Glsdk.rust_call( + :uniffi_glsdk_fn_clone_node, + @pointer + ) + end + + def self.uniffi_lower(inst) + return inst.uniffi_clone_pointer() + end + def initialize(credentials) + credentials = credentials + (Credentials.uniffi_check_lower credentials) + pointer = Glsdk.rust_call_with_error(Error,:uniffi_glsdk_fn_constructor_node_new,(Credentials.uniffi_lower credentials)) + @pointer = pointer + ObjectSpace.define_finalizer(self, self.class.uniffi_define_finalizer_by_pointer(pointer, self.object_id)) + end + + + + def onchain_receive() + result = Glsdk.rust_call_with_error(Error,:uniffi_glsdk_fn_method_node_onchain_receive,uniffi_clone_pointer(),) + return OnchainReceiveResponse.uniffi_allocate(result) + end + def onchain_send(destination, amount_or_all) + destination = Glsdk::uniffi_utf8(destination) + + amount_or_all = Glsdk::uniffi_utf8(amount_or_all) + + result = Glsdk.rust_call_with_error(Error,:uniffi_glsdk_fn_method_node_onchain_send,uniffi_clone_pointer(),RustBuffer.allocFromString(destination),RustBuffer.allocFromString(amount_or_all)) + return OnchainSendResponse.uniffi_allocate(result) + end + def receive(label, description, amount_msat) + label = Glsdk::uniffi_utf8(label) + + description = Glsdk::uniffi_utf8(description) + + amount_msat = (amount_msat ? Glsdk::uniffi_in_range(amount_msat, "u64", 0, 2**64) : nil) + RustBuffer.check_lower_Optionalu64(amount_msat) + result = Glsdk.rust_call_with_error(Error,:uniffi_glsdk_fn_method_node_receive,uniffi_clone_pointer(),RustBuffer.allocFromString(label),RustBuffer.allocFromString(description),RustBuffer.alloc_from_Optionalu64(amount_msat)) + return ReceiveResponse.uniffi_allocate(result) + end + def send(invoice, amount_msat) + invoice = Glsdk::uniffi_utf8(invoice) + + amount_msat = (amount_msat ? Glsdk::uniffi_in_range(amount_msat, "u64", 0, 2**64) : nil) + RustBuffer.check_lower_Optionalu64(amount_msat) + result = Glsdk.rust_call_with_error(Error,:uniffi_glsdk_fn_method_node_send,uniffi_clone_pointer(),RustBuffer.allocFromString(invoice),RustBuffer.alloc_from_Optionalu64(amount_msat)) + return SendResponse.uniffi_allocate(result) + end + def stop() + Glsdk.rust_call_with_error(Error,:uniffi_glsdk_fn_method_node_stop,uniffi_clone_pointer(),) + end + + +end + + class OnchainReceiveResponse + + # A private helper for initializing instances of the class from a raw pointer, + # bypassing any initialization logic and ensuring they are GC'd properly. + def self.uniffi_allocate(pointer) + pointer.autorelease = false + inst = allocate + inst.instance_variable_set :@pointer, pointer + ObjectSpace.define_finalizer(inst, uniffi_define_finalizer_by_pointer(pointer, inst.object_id)) + return inst + end + + # A private helper for registering an object finalizer. + # N.B. it's important that this does not capture a reference + # to the actual instance, only its underlying pointer. + def self.uniffi_define_finalizer_by_pointer(pointer, object_id) + Proc.new do |_id| + Glsdk.rust_call( + :uniffi_glsdk_fn_free_onchainreceiveresponse, + pointer + ) + end + end + + # A private helper for lowering instances into a raw pointer. + # This does an explicit typecheck, because accidentally lowering a different type of + # object in a place where this type is expected, could lead to memory unsafety. + def self.uniffi_check_lower(inst) + if not inst.is_a? self + raise TypeError.new "Expected a OnchainReceiveResponse instance, got #{inst}" + end + end + + def uniffi_clone_pointer() + return Glsdk.rust_call( + :uniffi_glsdk_fn_clone_onchainreceiveresponse, + @pointer + ) + end + + def self.uniffi_lower(inst) + return inst.uniffi_clone_pointer() + end + + + + +end + + class OnchainSendResponse + + # A private helper for initializing instances of the class from a raw pointer, + # bypassing any initialization logic and ensuring they are GC'd properly. + def self.uniffi_allocate(pointer) + pointer.autorelease = false + inst = allocate + inst.instance_variable_set :@pointer, pointer + ObjectSpace.define_finalizer(inst, uniffi_define_finalizer_by_pointer(pointer, inst.object_id)) + return inst + end + + # A private helper for registering an object finalizer. + # N.B. it's important that this does not capture a reference + # to the actual instance, only its underlying pointer. + def self.uniffi_define_finalizer_by_pointer(pointer, object_id) + Proc.new do |_id| + Glsdk.rust_call( + :uniffi_glsdk_fn_free_onchainsendresponse, + pointer + ) + end + end + + # A private helper for lowering instances into a raw pointer. + # This does an explicit typecheck, because accidentally lowering a different type of + # object in a place where this type is expected, could lead to memory unsafety. + def self.uniffi_check_lower(inst) + if not inst.is_a? self + raise TypeError.new "Expected a OnchainSendResponse instance, got #{inst}" + end + end + + def uniffi_clone_pointer() + return Glsdk.rust_call( + :uniffi_glsdk_fn_clone_onchainsendresponse, + @pointer + ) + end + + def self.uniffi_lower(inst) + return inst.uniffi_clone_pointer() + end + + + + +end + + class ReceiveResponse + + # A private helper for initializing instances of the class from a raw pointer, + # bypassing any initialization logic and ensuring they are GC'd properly. + def self.uniffi_allocate(pointer) + pointer.autorelease = false + inst = allocate + inst.instance_variable_set :@pointer, pointer + ObjectSpace.define_finalizer(inst, uniffi_define_finalizer_by_pointer(pointer, inst.object_id)) + return inst + end + + # A private helper for registering an object finalizer. + # N.B. it's important that this does not capture a reference + # to the actual instance, only its underlying pointer. + def self.uniffi_define_finalizer_by_pointer(pointer, object_id) + Proc.new do |_id| + Glsdk.rust_call( + :uniffi_glsdk_fn_free_receiveresponse, + pointer + ) + end + end + + # A private helper for lowering instances into a raw pointer. + # This does an explicit typecheck, because accidentally lowering a different type of + # object in a place where this type is expected, could lead to memory unsafety. + def self.uniffi_check_lower(inst) + if not inst.is_a? self + raise TypeError.new "Expected a ReceiveResponse instance, got #{inst}" + end + end + + def uniffi_clone_pointer() + return Glsdk.rust_call( + :uniffi_glsdk_fn_clone_receiveresponse, + @pointer + ) + end + + def self.uniffi_lower(inst) + return inst.uniffi_clone_pointer() + end + + + + +end + + class Scheduler + + # A private helper for initializing instances of the class from a raw pointer, + # bypassing any initialization logic and ensuring they are GC'd properly. + def self.uniffi_allocate(pointer) + pointer.autorelease = false + inst = allocate + inst.instance_variable_set :@pointer, pointer + ObjectSpace.define_finalizer(inst, uniffi_define_finalizer_by_pointer(pointer, inst.object_id)) + return inst + end + + # A private helper for registering an object finalizer. + # N.B. it's important that this does not capture a reference + # to the actual instance, only its underlying pointer. + def self.uniffi_define_finalizer_by_pointer(pointer, object_id) + Proc.new do |_id| + Glsdk.rust_call( + :uniffi_glsdk_fn_free_scheduler, + pointer + ) + end + end + + # A private helper for lowering instances into a raw pointer. + # This does an explicit typecheck, because accidentally lowering a different type of + # object in a place where this type is expected, could lead to memory unsafety. + def self.uniffi_check_lower(inst) + if not inst.is_a? self + raise TypeError.new "Expected a Scheduler instance, got #{inst}" + end + end + + def uniffi_clone_pointer() + return Glsdk.rust_call( + :uniffi_glsdk_fn_clone_scheduler, + @pointer + ) + end + + def self.uniffi_lower(inst) + return inst.uniffi_clone_pointer() + end + def initialize(network) + network = network + RustBuffer.check_lower_TypeNetwork(network) + pointer = Glsdk.rust_call_with_error(Error,:uniffi_glsdk_fn_constructor_scheduler_new,RustBuffer.alloc_from_TypeNetwork(network)) + @pointer = pointer + ObjectSpace.define_finalizer(self, self.class.uniffi_define_finalizer_by_pointer(pointer, self.object_id)) + end + + + + def recover(signer) + signer = signer + (Signer.uniffi_check_lower signer) + result = Glsdk.rust_call_with_error(Error,:uniffi_glsdk_fn_method_scheduler_recover,uniffi_clone_pointer(),(Signer.uniffi_lower signer)) + return Credentials.uniffi_allocate(result) + end + def register(signer, code) + signer = signer + (Signer.uniffi_check_lower signer) + code = (code ? Glsdk::uniffi_utf8(code) : nil) + RustBuffer.check_lower_Optionalstring(code) + result = Glsdk.rust_call_with_error(Error,:uniffi_glsdk_fn_method_scheduler_register,uniffi_clone_pointer(),(Signer.uniffi_lower signer),RustBuffer.alloc_from_Optionalstring(code)) + return Credentials.uniffi_allocate(result) + end + +end + + class SendResponse + + # A private helper for initializing instances of the class from a raw pointer, + # bypassing any initialization logic and ensuring they are GC'd properly. + def self.uniffi_allocate(pointer) + pointer.autorelease = false + inst = allocate + inst.instance_variable_set :@pointer, pointer + ObjectSpace.define_finalizer(inst, uniffi_define_finalizer_by_pointer(pointer, inst.object_id)) + return inst + end + + # A private helper for registering an object finalizer. + # N.B. it's important that this does not capture a reference + # to the actual instance, only its underlying pointer. + def self.uniffi_define_finalizer_by_pointer(pointer, object_id) + Proc.new do |_id| + Glsdk.rust_call( + :uniffi_glsdk_fn_free_sendresponse, + pointer + ) + end + end + + # A private helper for lowering instances into a raw pointer. + # This does an explicit typecheck, because accidentally lowering a different type of + # object in a place where this type is expected, could lead to memory unsafety. + def self.uniffi_check_lower(inst) + if not inst.is_a? self + raise TypeError.new "Expected a SendResponse instance, got #{inst}" + end + end + + def uniffi_clone_pointer() + return Glsdk.rust_call( + :uniffi_glsdk_fn_clone_sendresponse, + @pointer + ) + end + + def self.uniffi_lower(inst) + return inst.uniffi_clone_pointer() + end + + + + +end + + class Signer + + # A private helper for initializing instances of the class from a raw pointer, + # bypassing any initialization logic and ensuring they are GC'd properly. + def self.uniffi_allocate(pointer) + pointer.autorelease = false + inst = allocate + inst.instance_variable_set :@pointer, pointer + ObjectSpace.define_finalizer(inst, uniffi_define_finalizer_by_pointer(pointer, inst.object_id)) + return inst + end + + # A private helper for registering an object finalizer. + # N.B. it's important that this does not capture a reference + # to the actual instance, only its underlying pointer. + def self.uniffi_define_finalizer_by_pointer(pointer, object_id) + Proc.new do |_id| + Glsdk.rust_call( + :uniffi_glsdk_fn_free_signer, + pointer + ) + end + end + + # A private helper for lowering instances into a raw pointer. + # This does an explicit typecheck, because accidentally lowering a different type of + # object in a place where this type is expected, could lead to memory unsafety. + def self.uniffi_check_lower(inst) + if not inst.is_a? self + raise TypeError.new "Expected a Signer instance, got #{inst}" + end + end + + def uniffi_clone_pointer() + return Glsdk.rust_call( + :uniffi_glsdk_fn_clone_signer, + @pointer + ) + end + + def self.uniffi_lower(inst) + return inst.uniffi_clone_pointer() + end + def initialize(phrase) + phrase = Glsdk::uniffi_utf8(phrase) + + pointer = Glsdk.rust_call_with_error(Error,:uniffi_glsdk_fn_constructor_signer_new,RustBuffer.allocFromString(phrase)) + @pointer = pointer + ObjectSpace.define_finalizer(self, self.class.uniffi_define_finalizer_by_pointer(pointer, self.object_id)) + end + + + + def authenticate(creds) + creds = creds + (Credentials.uniffi_check_lower creds) + result = Glsdk.rust_call_with_error(Error,:uniffi_glsdk_fn_method_signer_authenticate,uniffi_clone_pointer(),(Credentials.uniffi_lower creds)) + return Signer.uniffi_allocate(result) + end + def node_id() + result = Glsdk.rust_call(:uniffi_glsdk_fn_method_signer_node_id,uniffi_clone_pointer(),) + return result.consumeIntoBytes + end + def start() + result = Glsdk.rust_call_with_error(Error,:uniffi_glsdk_fn_method_signer_start,uniffi_clone_pointer(),) + return Handle.uniffi_allocate(result) + end + +end + +end + diff --git a/libs/gl-sdk/bindings/glsdk.swift b/libs/gl-sdk/bindings/glsdk.swift new file mode 100644 index 000000000..e12721555 --- /dev/null +++ b/libs/gl-sdk/bindings/glsdk.swift @@ -0,0 +1,2188 @@ +// This file was autogenerated by some hot garbage in the `uniffi` crate. +// Trust me, you don't want to mess with it! + +// swiftlint:disable all +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(glsdkFFI) +import glsdkFFI +#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 empty() -> RustBuffer { + RustBuffer(capacity: 0, len:0, data: nil) + } + + static func from(_ ptr: UnsafeBufferPointer) -> RustBuffer { + try! rustCall { ffi_glsdk_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_glsdk_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) { + self.init( + bytesNoCopy: rustBuffer.data!, + count: Int(rustBuffer.len), + deallocator: .none + ) + } +} + +// 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 to 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 { +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public static func lift(_ value: FfiType) throws -> SwiftType { + return value + } + +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + 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 { +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + 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 + } + +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + 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 extension NSLock { + func withLock(f: () throws -> T) rethrows -> T { + self.lock() + defer { self.unlock() } + return try f() + } +} + +fileprivate let CALL_SUCCESS: Int8 = 0 +fileprivate let CALL_ERROR: Int8 = 1 +fileprivate let CALL_UNEXPECTED_ERROR: 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 { + let neverThrow: ((RustBuffer) throws -> Never)? = nil + return try makeRustCall(callback, errorHandler: neverThrow) +} + +private func rustCallWithError( + _ errorHandler: @escaping (RustBuffer) throws -> E, + _ callback: (UnsafeMutablePointer) -> T) throws -> T { + try makeRustCall(callback, errorHandler: errorHandler) +} + +private func makeRustCall( + _ callback: (UnsafeMutablePointer) -> T, + errorHandler: ((RustBuffer) throws -> E)? +) throws -> T { + uniffiEnsureGlsdkInitialized() + var callStatus = RustCallStatus.init() + let returnedVal = callback(&callStatus) + try uniffiCheckCallStatus(callStatus: callStatus, errorHandler: errorHandler) + return returnedVal +} + +private func uniffiCheckCallStatus( + callStatus: RustCallStatus, + errorHandler: ((RustBuffer) throws -> E)? +) 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_UNEXPECTED_ERROR: + // 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: + fatalError("Cancellation not supported yet") + + default: + throw UniffiInternalError.unexpectedRustCallStatusCode + } +} + +private func uniffiTraitInterfaceCall( + callStatus: UnsafeMutablePointer, + makeCall: () throws -> T, + writeReturn: (T) -> () +) { + do { + try writeReturn(makeCall()) + } catch let error { + callStatus.pointee.code = CALL_UNEXPECTED_ERROR + callStatus.pointee.errorBuf = FfiConverterString.lower(String(describing: error)) + } +} + +private func uniffiTraitInterfaceCallWithError( + callStatus: UnsafeMutablePointer, + makeCall: () throws -> T, + writeReturn: (T) -> (), + lowerError: (E) -> RustBuffer +) { + do { + try writeReturn(makeCall()) + } catch let error as E { + callStatus.pointee.code = CALL_ERROR + callStatus.pointee.errorBuf = lowerError(error) + } catch { + callStatus.pointee.code = CALL_UNEXPECTED_ERROR + callStatus.pointee.errorBuf = FfiConverterString.lower(String(describing: error)) + } +} +fileprivate final class UniffiHandleMap: @unchecked Sendable { + // All mutation happens with this lock held, which is why we implement @unchecked Sendable. + private let lock = NSLock() + private var map: [UInt64: T] = [:] + private var currentHandle: UInt64 = 1 + + func insert(obj: T) -> UInt64 { + lock.withLock { + let handle = currentHandle + currentHandle += 1 + map[handle] = obj + return handle + } + } + + func get(handle: UInt64) throws -> T { + try lock.withLock { + guard let obj = map[handle] else { + throw UniffiInternalError.unexpectedStaleHandle + } + return obj + } + } + + @discardableResult + func remove(handle: UInt64) throws -> T { + try lock.withLock { + guard let obj = map.removeValue(forKey: handle) else { + throw UniffiInternalError.unexpectedStaleHandle + } + return obj + } + } + + var count: Int { + get { + map.count + } + } +} + + +// Public interface members begin here. + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +fileprivate struct FfiConverterInt32: FfiConverterPrimitive { + typealias FfiType = Int32 + typealias SwiftType = Int32 + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Int32 { + return try lift(readInt(&buf)) + } + + public static func write(_ value: Int32, into buf: inout [UInt8]) { + writeInt(&buf, lower(value)) + } +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +fileprivate struct FfiConverterUInt64: FfiConverterPrimitive { + typealias FfiType = UInt64 + typealias SwiftType = UInt64 + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> UInt64 { + return try lift(readInt(&buf)) + } + + public static func write(_ value: SwiftType, into buf: inout [UInt8]) { + writeInt(&buf, lower(value)) + } +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +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) + } +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +fileprivate struct FfiConverterData: FfiConverterRustBuffer { + typealias SwiftType = Data + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Data { + let len: Int32 = try readInt(&buf) + return Data(try readBytes(&buf, count: Int(len))) + } + + public static func write(_ value: Data, into buf: inout [UInt8]) { + let len = Int32(value.count) + writeInt(&buf, len) + writeBytes(&buf, value) + } +} + + + + +/** + * `Credentials` is a container for `node_id`, the mTLS client + * certificate used to authenticate a client against a node, as well + * as the seed secret if present. If no seed is present in the + * credentials, then the `Client` will not start a signer in the + * background. + */ +public protocol CredentialsProtocol: AnyObject, Sendable { + + func save() throws -> Data + +} +/** + * `Credentials` is a container for `node_id`, the mTLS client + * certificate used to authenticate a client against a node, as well + * as the seed secret if present. If no seed is present in the + * credentials, then the `Client` will not start a signer in the + * background. + */ +open class Credentials: CredentialsProtocol, @unchecked Sendable { + fileprivate let pointer: UnsafeMutableRawPointer! + + /// Used to instantiate a [FFIObject] without an actual pointer, for fakes in tests, mostly. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public struct NoPointer { + public init() {} + } + + // 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`. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + required public init(unsafeFromRawPointer pointer: UnsafeMutableRawPointer) { + self.pointer = pointer + } + + // This constructor can be used to instantiate a fake object. + // - Parameter noPointer: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject]. + // + // - Warning: + // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing [Pointer] the FFI lower functions will crash. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public init(noPointer: NoPointer) { + self.pointer = nil + } + +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public func uniffiClonePointer() -> UnsafeMutableRawPointer { + return try! rustCall { uniffi_glsdk_fn_clone_credentials(self.pointer, $0) } + } + // No primary constructor declared for this class. + + deinit { + guard let pointer = pointer else { + return + } + + try! rustCall { uniffi_glsdk_fn_free_credentials(pointer, $0) } + } + + +public static func load(raw: Data)throws -> Credentials { + return try FfiConverterTypeCredentials_lift(try rustCallWithError(FfiConverterTypeError_lift) { + uniffi_glsdk_fn_constructor_credentials_load( + FfiConverterData.lower(raw),$0 + ) +}) +} + + + +open func save()throws -> Data { + return try FfiConverterData.lift(try rustCallWithError(FfiConverterTypeError_lift) { + uniffi_glsdk_fn_method_credentials_save(self.uniffiClonePointer(),$0 + ) +}) +} + + +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypeCredentials: FfiConverter { + + typealias FfiType = UnsafeMutableRawPointer + typealias SwiftType = Credentials + + public static func lift(_ pointer: UnsafeMutableRawPointer) throws -> Credentials { + return Credentials(unsafeFromRawPointer: pointer) + } + + public static func lower(_ value: Credentials) -> UnsafeMutableRawPointer { + return value.uniffiClonePointer() + } + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Credentials { + 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: Credentials, 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))))) + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeCredentials_lift(_ pointer: UnsafeMutableRawPointer) throws -> Credentials { + return try FfiConverterTypeCredentials.lift(pointer) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeCredentials_lower(_ value: Credentials) -> UnsafeMutableRawPointer { + return FfiConverterTypeCredentials.lower(value) +} + + + + + + +/** + * A handle to interact with a signer loop running and processing + * requests in the background. Used primarily to stop the loop and + * exiting the signer. + */ +public protocol HandleProtocol: AnyObject, Sendable { + + func stop() + +} +/** + * A handle to interact with a signer loop running and processing + * requests in the background. Used primarily to stop the loop and + * exiting the signer. + */ +open class Handle: HandleProtocol, @unchecked Sendable { + fileprivate let pointer: UnsafeMutableRawPointer! + + /// Used to instantiate a [FFIObject] without an actual pointer, for fakes in tests, mostly. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public struct NoPointer { + public init() {} + } + + // 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`. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + required public init(unsafeFromRawPointer pointer: UnsafeMutableRawPointer) { + self.pointer = pointer + } + + // This constructor can be used to instantiate a fake object. + // - Parameter noPointer: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject]. + // + // - Warning: + // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing [Pointer] the FFI lower functions will crash. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public init(noPointer: NoPointer) { + self.pointer = nil + } + +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public func uniffiClonePointer() -> UnsafeMutableRawPointer { + return try! rustCall { uniffi_glsdk_fn_clone_handle(self.pointer, $0) } + } + // No primary constructor declared for this class. + + deinit { + guard let pointer = pointer else { + return + } + + try! rustCall { uniffi_glsdk_fn_free_handle(pointer, $0) } + } + + + + +open func stop() {try! rustCall() { + uniffi_glsdk_fn_method_handle_stop(self.uniffiClonePointer(),$0 + ) +} +} + + +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypeHandle: FfiConverter { + + typealias FfiType = UnsafeMutableRawPointer + typealias SwiftType = Handle + + public static func lift(_ pointer: UnsafeMutableRawPointer) throws -> Handle { + return Handle(unsafeFromRawPointer: pointer) + } + + public static func lower(_ value: Handle) -> UnsafeMutableRawPointer { + return value.uniffiClonePointer() + } + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Handle { + 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: Handle, 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))))) + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeHandle_lift(_ pointer: UnsafeMutableRawPointer) throws -> Handle { + return try FfiConverterTypeHandle.lift(pointer) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeHandle_lower(_ value: Handle) -> UnsafeMutableRawPointer { + return FfiConverterTypeHandle.lower(value) +} + + + + + + +/** + * The `Node` is an RPC stub representing the node running in the + * cloud. It is the main entrypoint to interact with the node. + */ +public protocol NodeProtocol: AnyObject, Sendable { + + func onchainReceive() throws -> OnchainReceiveResponse + + func onchainSend(destination: String, amountOrAll: String) throws -> OnchainSendResponse + + /** + * Receive an off-chain payment. + * + * This method generates a request for a payment, also called an + * invoice, that encodes all the information, including amount + * and destination, for a prospective sender to send a lightning + * payment. The invoice includes negotiation of an LSPS2 / JIT + * channel, meaning that if there is no channel sufficient to + * receive the requested funds, the node will negotiate an + * opening, and when/if executed the payment will cause a channel + * to be created, and the incoming payment to be forwarded. + */ + func receive(label: String, description: String, amountMsat: UInt64?) throws -> ReceiveResponse + + func send(invoice: String, amountMsat: UInt64?) throws -> SendResponse + + /** + * Stop the node if it is currently running. + */ + func stop() throws + +} +/** + * The `Node` is an RPC stub representing the node running in the + * cloud. It is the main entrypoint to interact with the node. + */ +open class Node: NodeProtocol, @unchecked Sendable { + fileprivate let pointer: UnsafeMutableRawPointer! + + /// Used to instantiate a [FFIObject] without an actual pointer, for fakes in tests, mostly. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public struct NoPointer { + public init() {} + } + + // 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`. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + required public init(unsafeFromRawPointer pointer: UnsafeMutableRawPointer) { + self.pointer = pointer + } + + // This constructor can be used to instantiate a fake object. + // - Parameter noPointer: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject]. + // + // - Warning: + // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing [Pointer] the FFI lower functions will crash. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public init(noPointer: NoPointer) { + self.pointer = nil + } + +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public func uniffiClonePointer() -> UnsafeMutableRawPointer { + return try! rustCall { uniffi_glsdk_fn_clone_node(self.pointer, $0) } + } +public convenience init(credentials: Credentials)throws { + let pointer = + try rustCallWithError(FfiConverterTypeError_lift) { + uniffi_glsdk_fn_constructor_node_new( + FfiConverterTypeCredentials_lower(credentials),$0 + ) +} + self.init(unsafeFromRawPointer: pointer) +} + + deinit { + guard let pointer = pointer else { + return + } + + try! rustCall { uniffi_glsdk_fn_free_node(pointer, $0) } + } + + + + +open func onchainReceive()throws -> OnchainReceiveResponse { + return try FfiConverterTypeOnchainReceiveResponse_lift(try rustCallWithError(FfiConverterTypeError_lift) { + uniffi_glsdk_fn_method_node_onchain_receive(self.uniffiClonePointer(),$0 + ) +}) +} + +open func onchainSend(destination: String, amountOrAll: String)throws -> OnchainSendResponse { + return try FfiConverterTypeOnchainSendResponse_lift(try rustCallWithError(FfiConverterTypeError_lift) { + uniffi_glsdk_fn_method_node_onchain_send(self.uniffiClonePointer(), + FfiConverterString.lower(destination), + FfiConverterString.lower(amountOrAll),$0 + ) +}) +} + + /** + * Receive an off-chain payment. + * + * This method generates a request for a payment, also called an + * invoice, that encodes all the information, including amount + * and destination, for a prospective sender to send a lightning + * payment. The invoice includes negotiation of an LSPS2 / JIT + * channel, meaning that if there is no channel sufficient to + * receive the requested funds, the node will negotiate an + * opening, and when/if executed the payment will cause a channel + * to be created, and the incoming payment to be forwarded. + */ +open func receive(label: String, description: String, amountMsat: UInt64?)throws -> ReceiveResponse { + return try FfiConverterTypeReceiveResponse_lift(try rustCallWithError(FfiConverterTypeError_lift) { + uniffi_glsdk_fn_method_node_receive(self.uniffiClonePointer(), + FfiConverterString.lower(label), + FfiConverterString.lower(description), + FfiConverterOptionUInt64.lower(amountMsat),$0 + ) +}) +} + +open func send(invoice: String, amountMsat: UInt64?)throws -> SendResponse { + return try FfiConverterTypeSendResponse_lift(try rustCallWithError(FfiConverterTypeError_lift) { + uniffi_glsdk_fn_method_node_send(self.uniffiClonePointer(), + FfiConverterString.lower(invoice), + FfiConverterOptionUInt64.lower(amountMsat),$0 + ) +}) +} + + /** + * Stop the node if it is currently running. + */ +open func stop()throws {try rustCallWithError(FfiConverterTypeError_lift) { + uniffi_glsdk_fn_method_node_stop(self.uniffiClonePointer(),$0 + ) +} +} + + +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypeNode: FfiConverter { + + typealias FfiType = UnsafeMutableRawPointer + typealias SwiftType = Node + + public static func lift(_ pointer: UnsafeMutableRawPointer) throws -> Node { + return Node(unsafeFromRawPointer: pointer) + } + + public static func lower(_ value: Node) -> UnsafeMutableRawPointer { + return value.uniffiClonePointer() + } + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Node { + 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: Node, 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))))) + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeNode_lift(_ pointer: UnsafeMutableRawPointer) throws -> Node { + return try FfiConverterTypeNode.lift(pointer) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeNode_lower(_ value: Node) -> UnsafeMutableRawPointer { + return FfiConverterTypeNode.lower(value) +} + + + + + + +public protocol OnchainReceiveResponseProtocol: AnyObject, Sendable { + +} +open class OnchainReceiveResponse: OnchainReceiveResponseProtocol, @unchecked Sendable { + fileprivate let pointer: UnsafeMutableRawPointer! + + /// Used to instantiate a [FFIObject] without an actual pointer, for fakes in tests, mostly. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public struct NoPointer { + public init() {} + } + + // 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`. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + required public init(unsafeFromRawPointer pointer: UnsafeMutableRawPointer) { + self.pointer = pointer + } + + // This constructor can be used to instantiate a fake object. + // - Parameter noPointer: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject]. + // + // - Warning: + // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing [Pointer] the FFI lower functions will crash. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public init(noPointer: NoPointer) { + self.pointer = nil + } + +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public func uniffiClonePointer() -> UnsafeMutableRawPointer { + return try! rustCall { uniffi_glsdk_fn_clone_onchainreceiveresponse(self.pointer, $0) } + } + // No primary constructor declared for this class. + + deinit { + guard let pointer = pointer else { + return + } + + try! rustCall { uniffi_glsdk_fn_free_onchainreceiveresponse(pointer, $0) } + } + + + + + +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypeOnchainReceiveResponse: FfiConverter { + + typealias FfiType = UnsafeMutableRawPointer + typealias SwiftType = OnchainReceiveResponse + + public static func lift(_ pointer: UnsafeMutableRawPointer) throws -> OnchainReceiveResponse { + return OnchainReceiveResponse(unsafeFromRawPointer: pointer) + } + + public static func lower(_ value: OnchainReceiveResponse) -> UnsafeMutableRawPointer { + return value.uniffiClonePointer() + } + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> OnchainReceiveResponse { + 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: OnchainReceiveResponse, 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))))) + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeOnchainReceiveResponse_lift(_ pointer: UnsafeMutableRawPointer) throws -> OnchainReceiveResponse { + return try FfiConverterTypeOnchainReceiveResponse.lift(pointer) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeOnchainReceiveResponse_lower(_ value: OnchainReceiveResponse) -> UnsafeMutableRawPointer { + return FfiConverterTypeOnchainReceiveResponse.lower(value) +} + + + + + + +public protocol OnchainSendResponseProtocol: AnyObject, Sendable { + +} +open class OnchainSendResponse: OnchainSendResponseProtocol, @unchecked Sendable { + fileprivate let pointer: UnsafeMutableRawPointer! + + /// Used to instantiate a [FFIObject] without an actual pointer, for fakes in tests, mostly. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public struct NoPointer { + public init() {} + } + + // 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`. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + required public init(unsafeFromRawPointer pointer: UnsafeMutableRawPointer) { + self.pointer = pointer + } + + // This constructor can be used to instantiate a fake object. + // - Parameter noPointer: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject]. + // + // - Warning: + // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing [Pointer] the FFI lower functions will crash. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public init(noPointer: NoPointer) { + self.pointer = nil + } + +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public func uniffiClonePointer() -> UnsafeMutableRawPointer { + return try! rustCall { uniffi_glsdk_fn_clone_onchainsendresponse(self.pointer, $0) } + } + // No primary constructor declared for this class. + + deinit { + guard let pointer = pointer else { + return + } + + try! rustCall { uniffi_glsdk_fn_free_onchainsendresponse(pointer, $0) } + } + + + + + +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypeOnchainSendResponse: FfiConverter { + + typealias FfiType = UnsafeMutableRawPointer + typealias SwiftType = OnchainSendResponse + + public static func lift(_ pointer: UnsafeMutableRawPointer) throws -> OnchainSendResponse { + return OnchainSendResponse(unsafeFromRawPointer: pointer) + } + + public static func lower(_ value: OnchainSendResponse) -> UnsafeMutableRawPointer { + return value.uniffiClonePointer() + } + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> OnchainSendResponse { + 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: OnchainSendResponse, 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))))) + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeOnchainSendResponse_lift(_ pointer: UnsafeMutableRawPointer) throws -> OnchainSendResponse { + return try FfiConverterTypeOnchainSendResponse.lift(pointer) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeOnchainSendResponse_lower(_ value: OnchainSendResponse) -> UnsafeMutableRawPointer { + return FfiConverterTypeOnchainSendResponse.lower(value) +} + + + + + + +public protocol ReceiveResponseProtocol: AnyObject, Sendable { + +} +open class ReceiveResponse: ReceiveResponseProtocol, @unchecked Sendable { + fileprivate let pointer: UnsafeMutableRawPointer! + + /// Used to instantiate a [FFIObject] without an actual pointer, for fakes in tests, mostly. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public struct NoPointer { + public init() {} + } + + // 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`. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + required public init(unsafeFromRawPointer pointer: UnsafeMutableRawPointer) { + self.pointer = pointer + } + + // This constructor can be used to instantiate a fake object. + // - Parameter noPointer: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject]. + // + // - Warning: + // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing [Pointer] the FFI lower functions will crash. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public init(noPointer: NoPointer) { + self.pointer = nil + } + +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public func uniffiClonePointer() -> UnsafeMutableRawPointer { + return try! rustCall { uniffi_glsdk_fn_clone_receiveresponse(self.pointer, $0) } + } + // No primary constructor declared for this class. + + deinit { + guard let pointer = pointer else { + return + } + + try! rustCall { uniffi_glsdk_fn_free_receiveresponse(pointer, $0) } + } + + + + + +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypeReceiveResponse: FfiConverter { + + typealias FfiType = UnsafeMutableRawPointer + typealias SwiftType = ReceiveResponse + + public static func lift(_ pointer: UnsafeMutableRawPointer) throws -> ReceiveResponse { + return ReceiveResponse(unsafeFromRawPointer: pointer) + } + + public static func lower(_ value: ReceiveResponse) -> UnsafeMutableRawPointer { + return value.uniffiClonePointer() + } + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ReceiveResponse { + 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: ReceiveResponse, 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))))) + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeReceiveResponse_lift(_ pointer: UnsafeMutableRawPointer) throws -> ReceiveResponse { + return try FfiConverterTypeReceiveResponse.lift(pointer) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeReceiveResponse_lower(_ value: ReceiveResponse) -> UnsafeMutableRawPointer { + return FfiConverterTypeReceiveResponse.lower(value) +} + + + + + + +public protocol SchedulerProtocol: AnyObject, Sendable { + + func recover(signer: Signer) throws -> Credentials + + func register(signer: Signer, code: String?) throws -> Credentials + +} +open class Scheduler: SchedulerProtocol, @unchecked Sendable { + fileprivate let pointer: UnsafeMutableRawPointer! + + /// Used to instantiate a [FFIObject] without an actual pointer, for fakes in tests, mostly. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public struct NoPointer { + public init() {} + } + + // 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`. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + required public init(unsafeFromRawPointer pointer: UnsafeMutableRawPointer) { + self.pointer = pointer + } + + // This constructor can be used to instantiate a fake object. + // - Parameter noPointer: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject]. + // + // - Warning: + // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing [Pointer] the FFI lower functions will crash. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public init(noPointer: NoPointer) { + self.pointer = nil + } + +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public func uniffiClonePointer() -> UnsafeMutableRawPointer { + return try! rustCall { uniffi_glsdk_fn_clone_scheduler(self.pointer, $0) } + } + /** + * Create a `Scheduler` instance configured with the Greenlight + * production service pre-configured. + */ +public convenience init(network: Network)throws { + let pointer = + try rustCallWithError(FfiConverterTypeError_lift) { + uniffi_glsdk_fn_constructor_scheduler_new( + FfiConverterTypeNetwork_lower(network),$0 + ) +} + self.init(unsafeFromRawPointer: pointer) +} + + deinit { + guard let pointer = pointer else { + return + } + + try! rustCall { uniffi_glsdk_fn_free_scheduler(pointer, $0) } + } + + + + +open func recover(signer: Signer)throws -> Credentials { + return try FfiConverterTypeCredentials_lift(try rustCallWithError(FfiConverterTypeError_lift) { + uniffi_glsdk_fn_method_scheduler_recover(self.uniffiClonePointer(), + FfiConverterTypeSigner_lower(signer),$0 + ) +}) +} + +open func register(signer: Signer, code: String?)throws -> Credentials { + return try FfiConverterTypeCredentials_lift(try rustCallWithError(FfiConverterTypeError_lift) { + uniffi_glsdk_fn_method_scheduler_register(self.uniffiClonePointer(), + FfiConverterTypeSigner_lower(signer), + FfiConverterOptionString.lower(code),$0 + ) +}) +} + + +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypeScheduler: FfiConverter { + + typealias FfiType = UnsafeMutableRawPointer + typealias SwiftType = Scheduler + + public static func lift(_ pointer: UnsafeMutableRawPointer) throws -> Scheduler { + return Scheduler(unsafeFromRawPointer: pointer) + } + + public static func lower(_ value: Scheduler) -> UnsafeMutableRawPointer { + return value.uniffiClonePointer() + } + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Scheduler { + 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: Scheduler, 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))))) + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeScheduler_lift(_ pointer: UnsafeMutableRawPointer) throws -> Scheduler { + return try FfiConverterTypeScheduler.lift(pointer) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeScheduler_lower(_ value: Scheduler) -> UnsafeMutableRawPointer { + return FfiConverterTypeScheduler.lower(value) +} + + + + + + +public protocol SendResponseProtocol: AnyObject, Sendable { + +} +open class SendResponse: SendResponseProtocol, @unchecked Sendable { + fileprivate let pointer: UnsafeMutableRawPointer! + + /// Used to instantiate a [FFIObject] without an actual pointer, for fakes in tests, mostly. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public struct NoPointer { + public init() {} + } + + // 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`. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + required public init(unsafeFromRawPointer pointer: UnsafeMutableRawPointer) { + self.pointer = pointer + } + + // This constructor can be used to instantiate a fake object. + // - Parameter noPointer: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject]. + // + // - Warning: + // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing [Pointer] the FFI lower functions will crash. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public init(noPointer: NoPointer) { + self.pointer = nil + } + +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public func uniffiClonePointer() -> UnsafeMutableRawPointer { + return try! rustCall { uniffi_glsdk_fn_clone_sendresponse(self.pointer, $0) } + } + // No primary constructor declared for this class. + + deinit { + guard let pointer = pointer else { + return + } + + try! rustCall { uniffi_glsdk_fn_free_sendresponse(pointer, $0) } + } + + + + + +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypeSendResponse: FfiConverter { + + typealias FfiType = UnsafeMutableRawPointer + typealias SwiftType = SendResponse + + public static func lift(_ pointer: UnsafeMutableRawPointer) throws -> SendResponse { + return SendResponse(unsafeFromRawPointer: pointer) + } + + public static func lower(_ value: SendResponse) -> UnsafeMutableRawPointer { + return value.uniffiClonePointer() + } + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SendResponse { + 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: SendResponse, 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))))) + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeSendResponse_lift(_ pointer: UnsafeMutableRawPointer) throws -> SendResponse { + return try FfiConverterTypeSendResponse.lift(pointer) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeSendResponse_lower(_ value: SendResponse) -> UnsafeMutableRawPointer { + return FfiConverterTypeSendResponse.lower(value) +} + + + + + + +public protocol SignerProtocol: AnyObject, Sendable { + + func authenticate(creds: Credentials) throws -> Signer + + func nodeId() -> Data + + func start() throws -> Handle + +} +open class Signer: SignerProtocol, @unchecked Sendable { + fileprivate let pointer: UnsafeMutableRawPointer! + + /// Used to instantiate a [FFIObject] without an actual pointer, for fakes in tests, mostly. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public struct NoPointer { + public init() {} + } + + // 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`. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + required public init(unsafeFromRawPointer pointer: UnsafeMutableRawPointer) { + self.pointer = pointer + } + + // This constructor can be used to instantiate a fake object. + // - Parameter noPointer: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject]. + // + // - Warning: + // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing [Pointer] the FFI lower functions will crash. +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public init(noPointer: NoPointer) { + self.pointer = nil + } + +#if swift(>=5.8) + @_documentation(visibility: private) +#endif + public func uniffiClonePointer() -> UnsafeMutableRawPointer { + return try! rustCall { uniffi_glsdk_fn_clone_signer(self.pointer, $0) } + } +public convenience init(phrase: String)throws { + let pointer = + try rustCallWithError(FfiConverterTypeError_lift) { + uniffi_glsdk_fn_constructor_signer_new( + FfiConverterString.lower(phrase),$0 + ) +} + self.init(unsafeFromRawPointer: pointer) +} + + deinit { + guard let pointer = pointer else { + return + } + + try! rustCall { uniffi_glsdk_fn_free_signer(pointer, $0) } + } + + + + +open func authenticate(creds: Credentials)throws -> Signer { + return try FfiConverterTypeSigner_lift(try rustCallWithError(FfiConverterTypeError_lift) { + uniffi_glsdk_fn_method_signer_authenticate(self.uniffiClonePointer(), + FfiConverterTypeCredentials_lower(creds),$0 + ) +}) +} + +open func nodeId() -> Data { + return try! FfiConverterData.lift(try! rustCall() { + uniffi_glsdk_fn_method_signer_node_id(self.uniffiClonePointer(),$0 + ) +}) +} + +open func start()throws -> Handle { + return try FfiConverterTypeHandle_lift(try rustCallWithError(FfiConverterTypeError_lift) { + uniffi_glsdk_fn_method_signer_start(self.uniffiClonePointer(),$0 + ) +}) +} + + +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypeSigner: FfiConverter { + + typealias FfiType = UnsafeMutableRawPointer + typealias SwiftType = Signer + + public static func lift(_ pointer: UnsafeMutableRawPointer) throws -> Signer { + return Signer(unsafeFromRawPointer: pointer) + } + + public static func lower(_ value: Signer) -> UnsafeMutableRawPointer { + return value.uniffiClonePointer() + } + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Signer { + 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: Signer, 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))))) + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeSigner_lift(_ pointer: UnsafeMutableRawPointer) throws -> Signer { + return try FfiConverterTypeSigner.lift(pointer) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeSigner_lower(_ value: Signer) -> UnsafeMutableRawPointer { + return FfiConverterTypeSigner.lower(value) +} + + + + +public enum Error: Swift.Error { + + + + case DuplicateNode(code: Int32, message: String, values: [String: String] + ) + case NoSuchNode(code: Int32, message: String, values: [String: String] + ) + case UnparseableCreds(code: Int32, message: String, values: [String: String] + ) + case PhraseCorrupted(code: Int32, message: String, values: [String: String] + ) + case Rpc(code: Int32, message: String, values: [String: String] + ) + case Argument(code: Int32, message: String, values: [String: String] + ) + case Other(code: Int32, message: String, values: [String: String] + ) +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypeError: FfiConverterRustBuffer { + typealias SwiftType = Error + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Error { + let variant: Int32 = try readInt(&buf) + switch variant { + + + + + case 1: return .DuplicateNode( + code: try FfiConverterInt32.read(from: &buf), + message: try FfiConverterString.read(from: &buf), + values: try FfiConverterDictionaryStringString.read(from: &buf) + ) + case 2: return .NoSuchNode( + code: try FfiConverterInt32.read(from: &buf), + message: try FfiConverterString.read(from: &buf), + values: try FfiConverterDictionaryStringString.read(from: &buf) + ) + case 3: return .UnparseableCreds( + code: try FfiConverterInt32.read(from: &buf), + message: try FfiConverterString.read(from: &buf), + values: try FfiConverterDictionaryStringString.read(from: &buf) + ) + case 4: return .PhraseCorrupted( + code: try FfiConverterInt32.read(from: &buf), + message: try FfiConverterString.read(from: &buf), + values: try FfiConverterDictionaryStringString.read(from: &buf) + ) + case 5: return .Rpc( + code: try FfiConverterInt32.read(from: &buf), + message: try FfiConverterString.read(from: &buf), + values: try FfiConverterDictionaryStringString.read(from: &buf) + ) + case 6: return .Argument( + code: try FfiConverterInt32.read(from: &buf), + message: try FfiConverterString.read(from: &buf), + values: try FfiConverterDictionaryStringString.read(from: &buf) + ) + case 7: return .Other( + code: try FfiConverterInt32.read(from: &buf), + message: try FfiConverterString.read(from: &buf), + values: try FfiConverterDictionaryStringString.read(from: &buf) + ) + + default: throw UniffiInternalError.unexpectedEnumCase + } + } + + public static func write(_ value: Error, into buf: inout [UInt8]) { + switch value { + + + + + + case let .DuplicateNode(code,message,values): + writeInt(&buf, Int32(1)) + FfiConverterInt32.write(code, into: &buf) + FfiConverterString.write(message, into: &buf) + FfiConverterDictionaryStringString.write(values, into: &buf) + + + case let .NoSuchNode(code,message,values): + writeInt(&buf, Int32(2)) + FfiConverterInt32.write(code, into: &buf) + FfiConverterString.write(message, into: &buf) + FfiConverterDictionaryStringString.write(values, into: &buf) + + + case let .UnparseableCreds(code,message,values): + writeInt(&buf, Int32(3)) + FfiConverterInt32.write(code, into: &buf) + FfiConverterString.write(message, into: &buf) + FfiConverterDictionaryStringString.write(values, into: &buf) + + + case let .PhraseCorrupted(code,message,values): + writeInt(&buf, Int32(4)) + FfiConverterInt32.write(code, into: &buf) + FfiConverterString.write(message, into: &buf) + FfiConverterDictionaryStringString.write(values, into: &buf) + + + case let .Rpc(code,message,values): + writeInt(&buf, Int32(5)) + FfiConverterInt32.write(code, into: &buf) + FfiConverterString.write(message, into: &buf) + FfiConverterDictionaryStringString.write(values, into: &buf) + + + case let .Argument(code,message,values): + writeInt(&buf, Int32(6)) + FfiConverterInt32.write(code, into: &buf) + FfiConverterString.write(message, into: &buf) + FfiConverterDictionaryStringString.write(values, into: &buf) + + + case let .Other(code,message,values): + writeInt(&buf, Int32(7)) + FfiConverterInt32.write(code, into: &buf) + FfiConverterString.write(message, into: &buf) + FfiConverterDictionaryStringString.write(values, into: &buf) + + } + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeError_lift(_ buf: RustBuffer) throws -> Error { + return try FfiConverterTypeError.lift(buf) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeError_lower(_ value: Error) -> RustBuffer { + return FfiConverterTypeError.lower(value) +} + + +extension Error: Equatable, Hashable {} + + + + +extension Error: Foundation.LocalizedError { + public var errorDescription: String? { + String(reflecting: self) + } +} + + + + +// Note that we don't yet support `indirect` for enums. +// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion. + +public enum Network { + + case bitcoin + case regtest +} + + +#if compiler(>=6) +extension Network: Sendable {} +#endif + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypeNetwork: FfiConverterRustBuffer { + typealias SwiftType = Network + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Network { + let variant: Int32 = try readInt(&buf) + switch variant { + + case 1: return .bitcoin + + case 2: return .regtest + + default: throw UniffiInternalError.unexpectedEnumCase + } + } + + public static func write(_ value: Network, into buf: inout [UInt8]) { + switch value { + + + case .bitcoin: + writeInt(&buf, Int32(1)) + + + case .regtest: + writeInt(&buf, Int32(2)) + + } + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeNetwork_lift(_ buf: RustBuffer) throws -> Network { + return try FfiConverterTypeNetwork.lift(buf) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypeNetwork_lower(_ value: Network) -> RustBuffer { + return FfiConverterTypeNetwork.lower(value) +} + + +extension Network: Equatable, Hashable {} + + + + + + +// Note that we don't yet support `indirect` for enums. +// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion. + +public enum PayStatus { + + case complete + case pending + case failed +} + + +#if compiler(>=6) +extension PayStatus: Sendable {} +#endif + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public struct FfiConverterTypePayStatus: FfiConverterRustBuffer { + typealias SwiftType = PayStatus + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PayStatus { + let variant: Int32 = try readInt(&buf) + switch variant { + + case 1: return .complete + + case 2: return .pending + + case 3: return .failed + + default: throw UniffiInternalError.unexpectedEnumCase + } + } + + public static func write(_ value: PayStatus, into buf: inout [UInt8]) { + switch value { + + + case .complete: + writeInt(&buf, Int32(1)) + + + case .pending: + writeInt(&buf, Int32(2)) + + + case .failed: + writeInt(&buf, Int32(3)) + + } + } +} + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypePayStatus_lift(_ buf: RustBuffer) throws -> PayStatus { + return try FfiConverterTypePayStatus.lift(buf) +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +public func FfiConverterTypePayStatus_lower(_ value: PayStatus) -> RustBuffer { + return FfiConverterTypePayStatus.lower(value) +} + + +extension PayStatus: Equatable, Hashable {} + + + + + + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +fileprivate struct FfiConverterOptionUInt64: FfiConverterRustBuffer { + typealias SwiftType = UInt64? + + public static func write(_ value: SwiftType, into buf: inout [UInt8]) { + guard let value = value else { + writeInt(&buf, Int8(0)) + return + } + writeInt(&buf, Int8(1)) + FfiConverterUInt64.write(value, into: &buf) + } + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType { + switch try readInt(&buf) as Int8 { + case 0: return nil + case 1: return try FfiConverterUInt64.read(from: &buf) + default: throw UniffiInternalError.unexpectedOptionalTag + } + } +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +fileprivate struct FfiConverterOptionString: FfiConverterRustBuffer { + typealias SwiftType = String? + + public static func write(_ value: SwiftType, into buf: inout [UInt8]) { + guard let value = value else { + writeInt(&buf, Int8(0)) + return + } + writeInt(&buf, Int8(1)) + FfiConverterString.write(value, into: &buf) + } + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType { + switch try readInt(&buf) as Int8 { + case 0: return nil + case 1: return try FfiConverterString.read(from: &buf) + default: throw UniffiInternalError.unexpectedOptionalTag + } + } +} + +#if swift(>=5.8) +@_documentation(visibility: private) +#endif +fileprivate struct FfiConverterDictionaryStringString: FfiConverterRustBuffer { + public static func write(_ value: [String: String], into buf: inout [UInt8]) { + let len = Int32(value.count) + writeInt(&buf, len) + for (key, value) in value { + FfiConverterString.write(key, into: &buf) + FfiConverterString.write(value, into: &buf) + } + } + + public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [String: String] { + let len: Int32 = try readInt(&buf) + var dict = [String: String]() + dict.reserveCapacity(Int(len)) + for _ in 0.. +#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 +{ + uint64_t capacity; + uint64_t len; + uint8_t *_Nullable data; +} RustBuffer; + +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 +#ifndef UNIFFI_FFIDEF_RUST_FUTURE_CONTINUATION_CALLBACK +#define UNIFFI_FFIDEF_RUST_FUTURE_CONTINUATION_CALLBACK +typedef void (*UniffiRustFutureContinuationCallback)(uint64_t, int8_t + ); + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_FREE +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_FREE +typedef void (*UniffiForeignFutureFree)(uint64_t + ); + +#endif +#ifndef UNIFFI_FFIDEF_CALLBACK_INTERFACE_FREE +#define UNIFFI_FFIDEF_CALLBACK_INTERFACE_FREE +typedef void (*UniffiCallbackInterfaceFree)(uint64_t + ); + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE +#define UNIFFI_FFIDEF_FOREIGN_FUTURE +typedef struct UniffiForeignFuture { + uint64_t handle; + UniffiForeignFutureFree _Nonnull free; +} UniffiForeignFuture; + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_U8 +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_U8 +typedef struct UniffiForeignFutureStructU8 { + uint8_t returnValue; + RustCallStatus callStatus; +} UniffiForeignFutureStructU8; + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U8 +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U8 +typedef void (*UniffiForeignFutureCompleteU8)(uint64_t, UniffiForeignFutureStructU8 + ); + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_I8 +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_I8 +typedef struct UniffiForeignFutureStructI8 { + int8_t returnValue; + RustCallStatus callStatus; +} UniffiForeignFutureStructI8; + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I8 +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I8 +typedef void (*UniffiForeignFutureCompleteI8)(uint64_t, UniffiForeignFutureStructI8 + ); + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_U16 +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_U16 +typedef struct UniffiForeignFutureStructU16 { + uint16_t returnValue; + RustCallStatus callStatus; +} UniffiForeignFutureStructU16; + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U16 +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U16 +typedef void (*UniffiForeignFutureCompleteU16)(uint64_t, UniffiForeignFutureStructU16 + ); + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_I16 +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_I16 +typedef struct UniffiForeignFutureStructI16 { + int16_t returnValue; + RustCallStatus callStatus; +} UniffiForeignFutureStructI16; + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I16 +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I16 +typedef void (*UniffiForeignFutureCompleteI16)(uint64_t, UniffiForeignFutureStructI16 + ); + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_U32 +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_U32 +typedef struct UniffiForeignFutureStructU32 { + uint32_t returnValue; + RustCallStatus callStatus; +} UniffiForeignFutureStructU32; + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U32 +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U32 +typedef void (*UniffiForeignFutureCompleteU32)(uint64_t, UniffiForeignFutureStructU32 + ); + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_I32 +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_I32 +typedef struct UniffiForeignFutureStructI32 { + int32_t returnValue; + RustCallStatus callStatus; +} UniffiForeignFutureStructI32; + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I32 +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I32 +typedef void (*UniffiForeignFutureCompleteI32)(uint64_t, UniffiForeignFutureStructI32 + ); + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_U64 +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_U64 +typedef struct UniffiForeignFutureStructU64 { + uint64_t returnValue; + RustCallStatus callStatus; +} UniffiForeignFutureStructU64; + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U64 +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_U64 +typedef void (*UniffiForeignFutureCompleteU64)(uint64_t, UniffiForeignFutureStructU64 + ); + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_I64 +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_I64 +typedef struct UniffiForeignFutureStructI64 { + int64_t returnValue; + RustCallStatus callStatus; +} UniffiForeignFutureStructI64; + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I64 +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_I64 +typedef void (*UniffiForeignFutureCompleteI64)(uint64_t, UniffiForeignFutureStructI64 + ); + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_F32 +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_F32 +typedef struct UniffiForeignFutureStructF32 { + float returnValue; + RustCallStatus callStatus; +} UniffiForeignFutureStructF32; + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_F32 +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_F32 +typedef void (*UniffiForeignFutureCompleteF32)(uint64_t, UniffiForeignFutureStructF32 + ); + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_F64 +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_F64 +typedef struct UniffiForeignFutureStructF64 { + double returnValue; + RustCallStatus callStatus; +} UniffiForeignFutureStructF64; + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_F64 +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_F64 +typedef void (*UniffiForeignFutureCompleteF64)(uint64_t, UniffiForeignFutureStructF64 + ); + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_POINTER +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_POINTER +typedef struct UniffiForeignFutureStructPointer { + void*_Nonnull returnValue; + RustCallStatus callStatus; +} UniffiForeignFutureStructPointer; + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_POINTER +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_POINTER +typedef void (*UniffiForeignFutureCompletePointer)(uint64_t, UniffiForeignFutureStructPointer + ); + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_RUST_BUFFER +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_RUST_BUFFER +typedef struct UniffiForeignFutureStructRustBuffer { + RustBuffer returnValue; + RustCallStatus callStatus; +} UniffiForeignFutureStructRustBuffer; + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_RUST_BUFFER +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_RUST_BUFFER +typedef void (*UniffiForeignFutureCompleteRustBuffer)(uint64_t, UniffiForeignFutureStructRustBuffer + ); + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_VOID +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_STRUCT_VOID +typedef struct UniffiForeignFutureStructVoid { + RustCallStatus callStatus; +} UniffiForeignFutureStructVoid; + +#endif +#ifndef UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_VOID +#define UNIFFI_FFIDEF_FOREIGN_FUTURE_COMPLETE_VOID +typedef void (*UniffiForeignFutureCompleteVoid)(uint64_t, UniffiForeignFutureStructVoid + ); + +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CLONE_CREDENTIALS +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CLONE_CREDENTIALS +void*_Nonnull uniffi_glsdk_fn_clone_credentials(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_FREE_CREDENTIALS +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_FREE_CREDENTIALS +void uniffi_glsdk_fn_free_credentials(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CONSTRUCTOR_CREDENTIALS_LOAD +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CONSTRUCTOR_CREDENTIALS_LOAD +void*_Nonnull uniffi_glsdk_fn_constructor_credentials_load(RustBuffer raw, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_CREDENTIALS_SAVE +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_CREDENTIALS_SAVE +RustBuffer uniffi_glsdk_fn_method_credentials_save(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CLONE_HANDLE +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CLONE_HANDLE +void*_Nonnull uniffi_glsdk_fn_clone_handle(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_FREE_HANDLE +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_FREE_HANDLE +void uniffi_glsdk_fn_free_handle(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_HANDLE_STOP +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_HANDLE_STOP +void uniffi_glsdk_fn_method_handle_stop(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CLONE_NODE +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CLONE_NODE +void*_Nonnull uniffi_glsdk_fn_clone_node(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_FREE_NODE +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_FREE_NODE +void uniffi_glsdk_fn_free_node(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CONSTRUCTOR_NODE_NEW +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CONSTRUCTOR_NODE_NEW +void*_Nonnull uniffi_glsdk_fn_constructor_node_new(void*_Nonnull credentials, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_NODE_ONCHAIN_RECEIVE +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_NODE_ONCHAIN_RECEIVE +void*_Nonnull uniffi_glsdk_fn_method_node_onchain_receive(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_NODE_ONCHAIN_SEND +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_NODE_ONCHAIN_SEND +void*_Nonnull uniffi_glsdk_fn_method_node_onchain_send(void*_Nonnull ptr, RustBuffer destination, RustBuffer amount_or_all, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_NODE_RECEIVE +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_NODE_RECEIVE +void*_Nonnull uniffi_glsdk_fn_method_node_receive(void*_Nonnull ptr, RustBuffer label, RustBuffer description, RustBuffer amount_msat, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_NODE_SEND +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_NODE_SEND +void*_Nonnull uniffi_glsdk_fn_method_node_send(void*_Nonnull ptr, RustBuffer invoice, RustBuffer amount_msat, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_NODE_STOP +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_NODE_STOP +void uniffi_glsdk_fn_method_node_stop(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CLONE_ONCHAINRECEIVERESPONSE +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CLONE_ONCHAINRECEIVERESPONSE +void*_Nonnull uniffi_glsdk_fn_clone_onchainreceiveresponse(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_FREE_ONCHAINRECEIVERESPONSE +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_FREE_ONCHAINRECEIVERESPONSE +void uniffi_glsdk_fn_free_onchainreceiveresponse(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CLONE_ONCHAINSENDRESPONSE +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CLONE_ONCHAINSENDRESPONSE +void*_Nonnull uniffi_glsdk_fn_clone_onchainsendresponse(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_FREE_ONCHAINSENDRESPONSE +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_FREE_ONCHAINSENDRESPONSE +void uniffi_glsdk_fn_free_onchainsendresponse(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CLONE_RECEIVERESPONSE +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CLONE_RECEIVERESPONSE +void*_Nonnull uniffi_glsdk_fn_clone_receiveresponse(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_FREE_RECEIVERESPONSE +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_FREE_RECEIVERESPONSE +void uniffi_glsdk_fn_free_receiveresponse(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CLONE_SCHEDULER +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CLONE_SCHEDULER +void*_Nonnull uniffi_glsdk_fn_clone_scheduler(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_FREE_SCHEDULER +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_FREE_SCHEDULER +void uniffi_glsdk_fn_free_scheduler(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CONSTRUCTOR_SCHEDULER_NEW +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CONSTRUCTOR_SCHEDULER_NEW +void*_Nonnull uniffi_glsdk_fn_constructor_scheduler_new(RustBuffer network, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_SCHEDULER_RECOVER +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_SCHEDULER_RECOVER +void*_Nonnull uniffi_glsdk_fn_method_scheduler_recover(void*_Nonnull ptr, void*_Nonnull signer, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_SCHEDULER_REGISTER +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_SCHEDULER_REGISTER +void*_Nonnull uniffi_glsdk_fn_method_scheduler_register(void*_Nonnull ptr, void*_Nonnull signer, RustBuffer code, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CLONE_SENDRESPONSE +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CLONE_SENDRESPONSE +void*_Nonnull uniffi_glsdk_fn_clone_sendresponse(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_FREE_SENDRESPONSE +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_FREE_SENDRESPONSE +void uniffi_glsdk_fn_free_sendresponse(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CLONE_SIGNER +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CLONE_SIGNER +void*_Nonnull uniffi_glsdk_fn_clone_signer(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_FREE_SIGNER +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_FREE_SIGNER +void uniffi_glsdk_fn_free_signer(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CONSTRUCTOR_SIGNER_NEW +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_CONSTRUCTOR_SIGNER_NEW +void*_Nonnull uniffi_glsdk_fn_constructor_signer_new(RustBuffer phrase, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_SIGNER_AUTHENTICATE +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_SIGNER_AUTHENTICATE +void*_Nonnull uniffi_glsdk_fn_method_signer_authenticate(void*_Nonnull ptr, void*_Nonnull creds, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_SIGNER_NODE_ID +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_SIGNER_NODE_ID +RustBuffer uniffi_glsdk_fn_method_signer_node_id(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_SIGNER_START +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_FN_METHOD_SIGNER_START +void*_Nonnull uniffi_glsdk_fn_method_signer_start(void*_Nonnull ptr, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUSTBUFFER_ALLOC +#define UNIFFI_FFIDEF_FFI_GLSDK_RUSTBUFFER_ALLOC +RustBuffer ffi_glsdk_rustbuffer_alloc(uint64_t size, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUSTBUFFER_FROM_BYTES +#define UNIFFI_FFIDEF_FFI_GLSDK_RUSTBUFFER_FROM_BYTES +RustBuffer ffi_glsdk_rustbuffer_from_bytes(ForeignBytes bytes, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUSTBUFFER_FREE +#define UNIFFI_FFIDEF_FFI_GLSDK_RUSTBUFFER_FREE +void ffi_glsdk_rustbuffer_free(RustBuffer buf, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUSTBUFFER_RESERVE +#define UNIFFI_FFIDEF_FFI_GLSDK_RUSTBUFFER_RESERVE +RustBuffer ffi_glsdk_rustbuffer_reserve(RustBuffer buf, uint64_t additional, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_U8 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_U8 +void ffi_glsdk_rust_future_poll_u8(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_U8 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_U8 +void ffi_glsdk_rust_future_cancel_u8(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_U8 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_U8 +void ffi_glsdk_rust_future_free_u8(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_U8 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_U8 +uint8_t ffi_glsdk_rust_future_complete_u8(uint64_t handle, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_I8 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_I8 +void ffi_glsdk_rust_future_poll_i8(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_I8 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_I8 +void ffi_glsdk_rust_future_cancel_i8(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_I8 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_I8 +void ffi_glsdk_rust_future_free_i8(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_I8 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_I8 +int8_t ffi_glsdk_rust_future_complete_i8(uint64_t handle, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_U16 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_U16 +void ffi_glsdk_rust_future_poll_u16(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_U16 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_U16 +void ffi_glsdk_rust_future_cancel_u16(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_U16 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_U16 +void ffi_glsdk_rust_future_free_u16(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_U16 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_U16 +uint16_t ffi_glsdk_rust_future_complete_u16(uint64_t handle, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_I16 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_I16 +void ffi_glsdk_rust_future_poll_i16(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_I16 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_I16 +void ffi_glsdk_rust_future_cancel_i16(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_I16 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_I16 +void ffi_glsdk_rust_future_free_i16(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_I16 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_I16 +int16_t ffi_glsdk_rust_future_complete_i16(uint64_t handle, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_U32 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_U32 +void ffi_glsdk_rust_future_poll_u32(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_U32 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_U32 +void ffi_glsdk_rust_future_cancel_u32(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_U32 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_U32 +void ffi_glsdk_rust_future_free_u32(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_U32 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_U32 +uint32_t ffi_glsdk_rust_future_complete_u32(uint64_t handle, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_I32 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_I32 +void ffi_glsdk_rust_future_poll_i32(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_I32 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_I32 +void ffi_glsdk_rust_future_cancel_i32(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_I32 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_I32 +void ffi_glsdk_rust_future_free_i32(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_I32 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_I32 +int32_t ffi_glsdk_rust_future_complete_i32(uint64_t handle, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_U64 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_U64 +void ffi_glsdk_rust_future_poll_u64(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_U64 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_U64 +void ffi_glsdk_rust_future_cancel_u64(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_U64 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_U64 +void ffi_glsdk_rust_future_free_u64(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_U64 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_U64 +uint64_t ffi_glsdk_rust_future_complete_u64(uint64_t handle, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_I64 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_I64 +void ffi_glsdk_rust_future_poll_i64(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_I64 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_I64 +void ffi_glsdk_rust_future_cancel_i64(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_I64 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_I64 +void ffi_glsdk_rust_future_free_i64(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_I64 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_I64 +int64_t ffi_glsdk_rust_future_complete_i64(uint64_t handle, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_F32 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_F32 +void ffi_glsdk_rust_future_poll_f32(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_F32 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_F32 +void ffi_glsdk_rust_future_cancel_f32(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_F32 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_F32 +void ffi_glsdk_rust_future_free_f32(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_F32 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_F32 +float ffi_glsdk_rust_future_complete_f32(uint64_t handle, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_F64 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_F64 +void ffi_glsdk_rust_future_poll_f64(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_F64 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_F64 +void ffi_glsdk_rust_future_cancel_f64(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_F64 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_F64 +void ffi_glsdk_rust_future_free_f64(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_F64 +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_F64 +double ffi_glsdk_rust_future_complete_f64(uint64_t handle, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_POINTER +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_POINTER +void ffi_glsdk_rust_future_poll_pointer(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_POINTER +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_POINTER +void ffi_glsdk_rust_future_cancel_pointer(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_POINTER +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_POINTER +void ffi_glsdk_rust_future_free_pointer(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_POINTER +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_POINTER +void*_Nonnull ffi_glsdk_rust_future_complete_pointer(uint64_t handle, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_RUST_BUFFER +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_RUST_BUFFER +void ffi_glsdk_rust_future_poll_rust_buffer(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_RUST_BUFFER +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_RUST_BUFFER +void ffi_glsdk_rust_future_cancel_rust_buffer(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_RUST_BUFFER +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_RUST_BUFFER +void ffi_glsdk_rust_future_free_rust_buffer(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_RUST_BUFFER +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_RUST_BUFFER +RustBuffer ffi_glsdk_rust_future_complete_rust_buffer(uint64_t handle, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_VOID +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_POLL_VOID +void ffi_glsdk_rust_future_poll_void(uint64_t handle, UniffiRustFutureContinuationCallback _Nonnull callback, uint64_t callback_data +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_VOID +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_CANCEL_VOID +void ffi_glsdk_rust_future_cancel_void(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_VOID +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_FREE_VOID +void ffi_glsdk_rust_future_free_void(uint64_t handle +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_VOID +#define UNIFFI_FFIDEF_FFI_GLSDK_RUST_FUTURE_COMPLETE_VOID +void ffi_glsdk_rust_future_complete_void(uint64_t handle, RustCallStatus *_Nonnull out_status +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_CREDENTIALS_SAVE +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_CREDENTIALS_SAVE +uint16_t uniffi_glsdk_checksum_method_credentials_save(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_HANDLE_STOP +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_HANDLE_STOP +uint16_t uniffi_glsdk_checksum_method_handle_stop(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_NODE_ONCHAIN_RECEIVE +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_NODE_ONCHAIN_RECEIVE +uint16_t uniffi_glsdk_checksum_method_node_onchain_receive(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_NODE_ONCHAIN_SEND +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_NODE_ONCHAIN_SEND +uint16_t uniffi_glsdk_checksum_method_node_onchain_send(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_NODE_RECEIVE +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_NODE_RECEIVE +uint16_t uniffi_glsdk_checksum_method_node_receive(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_NODE_SEND +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_NODE_SEND +uint16_t uniffi_glsdk_checksum_method_node_send(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_NODE_STOP +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_NODE_STOP +uint16_t uniffi_glsdk_checksum_method_node_stop(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_SCHEDULER_RECOVER +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_SCHEDULER_RECOVER +uint16_t uniffi_glsdk_checksum_method_scheduler_recover(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_SCHEDULER_REGISTER +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_SCHEDULER_REGISTER +uint16_t uniffi_glsdk_checksum_method_scheduler_register(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_SIGNER_AUTHENTICATE +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_SIGNER_AUTHENTICATE +uint16_t uniffi_glsdk_checksum_method_signer_authenticate(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_SIGNER_NODE_ID +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_SIGNER_NODE_ID +uint16_t uniffi_glsdk_checksum_method_signer_node_id(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_SIGNER_START +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_METHOD_SIGNER_START +uint16_t uniffi_glsdk_checksum_method_signer_start(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_CONSTRUCTOR_CREDENTIALS_LOAD +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_CONSTRUCTOR_CREDENTIALS_LOAD +uint16_t uniffi_glsdk_checksum_constructor_credentials_load(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_CONSTRUCTOR_NODE_NEW +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_CONSTRUCTOR_NODE_NEW +uint16_t uniffi_glsdk_checksum_constructor_node_new(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_CONSTRUCTOR_SCHEDULER_NEW +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_CONSTRUCTOR_SCHEDULER_NEW +uint16_t uniffi_glsdk_checksum_constructor_scheduler_new(void + +); +#endif +#ifndef UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_CONSTRUCTOR_SIGNER_NEW +#define UNIFFI_FFIDEF_UNIFFI_GLSDK_CHECKSUM_CONSTRUCTOR_SIGNER_NEW +uint16_t uniffi_glsdk_checksum_constructor_signer_new(void + +); +#endif +#ifndef UNIFFI_FFIDEF_FFI_GLSDK_UNIFFI_CONTRACT_VERSION +#define UNIFFI_FFIDEF_FFI_GLSDK_UNIFFI_CONTRACT_VERSION +uint32_t ffi_glsdk_uniffi_contract_version(void + +); +#endif + diff --git a/libs/gl-sdk/bindings/glsdkFFI.modulemap b/libs/gl-sdk/bindings/glsdkFFI.modulemap new file mode 100644 index 000000000..666bf137b --- /dev/null +++ b/libs/gl-sdk/bindings/glsdkFFI.modulemap @@ -0,0 +1,7 @@ +module glsdkFFI { + header "glsdkFFI.h" + export * + use "Darwin" + use "_Builtin_stdbool" + use "_Builtin_stdint" +} \ No newline at end of file diff --git a/libs/gl-sdk/bindings/uniffi/glsdk/glsdk.kt b/libs/gl-sdk/bindings/uniffi/glsdk/glsdk.kt new file mode 100644 index 000000000..2f952869f --- /dev/null +++ b/libs/gl-sdk/bindings/uniffi/glsdk/glsdk.kt @@ -0,0 +1,4059 @@ +// 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.glsdk + +// 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.atomic.AtomicLong +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicBoolean + +// 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. + +/** + * @suppress + */ +@Structure.FieldOrder("capacity", "len", "data") +open class RustBuffer : Structure() { + // Note: `capacity` and `len` are actually `ULong` values, but JVM only supports signed values. + // When dealing with these fields, make sure to call `toULong()`. + @JvmField var capacity: Long = 0 + @JvmField var len: Long = 0 + @JvmField var data: Pointer? = null + + class ByValue: RustBuffer(), Structure.ByValue + class ByReference: RustBuffer(), Structure.ByReference + + internal fun setValue(other: RustBuffer) { + capacity = other.capacity + len = other.len + data = other.data + } + + companion object { + internal fun alloc(size: ULong = 0UL) = uniffiRustCall() { status -> + // Note: need to convert the size to a `Long` value to make this work with JVM. + UniffiLib.INSTANCE.ffi_glsdk_rustbuffer_alloc(size.toLong(), status) + }.also { + if(it.data == null) { + throw RuntimeException("RustBuffer.alloc() returned null data pointer (size=${size})") + } + } + + internal fun create(capacity: ULong, len: ULong, data: Pointer?): RustBuffer.ByValue { + var buf = RustBuffer.ByValue() + buf.capacity = capacity.toLong() + buf.len = len.toLong() + buf.data = data + return buf + } + + internal fun free(buf: RustBuffer.ByValue) = uniffiRustCall() { status -> + UniffiLib.INSTANCE.ffi_glsdk_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. + * + * @suppress + */ +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.setLong(0, value.capacity) + pointer.setLong(8, value.len) + pointer.setPointer(16, value.data) + } + + /** + * Get a `RustBuffer.ByValue` from this reference. + */ + fun getValue(): RustBuffer.ByValue { + val pointer = getPointer() + val value = RustBuffer.ByValue() + value.writeField("capacity", pointer.getLong(0)) + value.writeField("len", pointer.getLong(8)) + value.writeField("data", pointer.getLong(16)) + + 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") +internal 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. + * + * @suppress + */ +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): ULong + + // 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).also { + it.order(ByteOrder.BIG_ENDIAN) + } + write(value, bbuf) + rbuf.writeField("len", bbuf.position().toLong()) + 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 + * + * @suppress + */ +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. + +internal const val UNIFFI_CALL_SUCCESS = 0.toByte() +internal const val UNIFFI_CALL_ERROR = 1.toByte() +internal const val UNIFFI_CALL_UNEXPECTED_ERROR = 2.toByte() + +@Structure.FieldOrder("code", "error_buf") +internal open class UniffiRustCallStatus : Structure() { + @JvmField var code: Byte = 0 + @JvmField var error_buf: RustBuffer.ByValue = RustBuffer.ByValue() + + class ByValue: UniffiRustCallStatus(), Structure.ByValue + + fun isSuccess(): Boolean { + return code == UNIFFI_CALL_SUCCESS + } + + fun isError(): Boolean { + return code == UNIFFI_CALL_ERROR + } + + fun isPanic(): Boolean { + return code == UNIFFI_CALL_UNEXPECTED_ERROR + } + + companion object { + fun create(code: Byte, errorBuf: RustBuffer.ByValue): UniffiRustCallStatus.ByValue { + val callStatus = UniffiRustCallStatus.ByValue() + callStatus.code = code + callStatus.error_buf = errorBuf + return callStatus + } + } +} + +class InternalException(message: String) : kotlin.Exception(message) + +/** + * Each top-level error class has a companion object that can lift the error from the call status's rust buffer + * + * @suppress + */ +interface UniffiRustCallStatusErrorHandler { + 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 uniffiRustCallWithError(errorHandler: UniffiRustCallStatusErrorHandler, callback: (UniffiRustCallStatus) -> U): U { + var status = UniffiRustCallStatus() + val return_value = callback(status) + uniffiCheckCallStatus(errorHandler, status) + return return_value +} + +// Check UniffiRustCallStatus and throw an error if the call wasn't successful +private fun uniffiCheckCallStatus(errorHandler: UniffiRustCallStatusErrorHandler, status: UniffiRustCallStatus) { + 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") + } +} + +/** + * UniffiRustCallStatusErrorHandler implementation for times when we don't expect a CALL_ERROR + * + * @suppress + */ +object UniffiNullRustCallStatusErrorHandler: UniffiRustCallStatusErrorHandler { + 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 uniffiRustCall(callback: (UniffiRustCallStatus) -> U): U { + return uniffiRustCallWithError(UniffiNullRustCallStatusErrorHandler, callback) +} + +internal inline fun uniffiTraitInterfaceCall( + callStatus: UniffiRustCallStatus, + makeCall: () -> T, + writeReturn: (T) -> Unit, +) { + try { + writeReturn(makeCall()) + } catch(e: kotlin.Exception) { + callStatus.code = UNIFFI_CALL_UNEXPECTED_ERROR + callStatus.error_buf = FfiConverterString.lower(e.toString()) + } +} + +internal inline fun uniffiTraitInterfaceCallWithError( + callStatus: UniffiRustCallStatus, + makeCall: () -> T, + writeReturn: (T) -> Unit, + lowerError: (E) -> RustBuffer.ByValue +) { + try { + writeReturn(makeCall()) + } catch(e: kotlin.Exception) { + if (e is E) { + callStatus.code = UNIFFI_CALL_ERROR + callStatus.error_buf = lowerError(e) + } else { + callStatus.code = UNIFFI_CALL_UNEXPECTED_ERROR + callStatus.error_buf = FfiConverterString.lower(e.toString()) + } + } +} +// Map handles to objects +// +// This is used pass an opaque 64-bit handle representing a foreign object to the Rust code. +internal class UniffiHandleMap { + private val map = ConcurrentHashMap() + private val counter = java.util.concurrent.atomic.AtomicLong(0) + + val size: Int + get() = map.size + + // Insert a new object into the handle map and get a handle for it + fun insert(obj: T): Long { + val handle = counter.getAndAdd(1) + map.put(handle, obj) + return handle + } + + // Get an object from the handle map + fun get(handle: Long): T { + return map.get(handle) ?: throw InternalException("UniffiHandleMap.get: Invalid handle") + } + + // Remove an entry from the handlemap and get the Kotlin object back + fun remove(handle: Long): T { + return map.remove(handle) ?: throw InternalException("UniffiHandleMap: Invalid handle") + } +} + +// 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 "glsdk" +} + +private inline fun loadIndirect( + componentName: String +): Lib { + return Native.load(findLibraryName(componentName), Lib::class.java) +} + +// Define FFI callback types +internal interface UniffiRustFutureContinuationCallback : com.sun.jna.Callback { + fun callback(`data`: Long,`pollResult`: Byte,) +} +internal interface UniffiForeignFutureFree : com.sun.jna.Callback { + fun callback(`handle`: Long,) +} +internal interface UniffiCallbackInterfaceFree : com.sun.jna.Callback { + fun callback(`handle`: Long,) +} +@Structure.FieldOrder("handle", "free") +internal open class UniffiForeignFuture( + @JvmField internal var `handle`: Long = 0.toLong(), + @JvmField internal var `free`: UniffiForeignFutureFree? = null, +) : Structure() { + class UniffiByValue( + `handle`: Long = 0.toLong(), + `free`: UniffiForeignFutureFree? = null, + ): UniffiForeignFuture(`handle`,`free`,), Structure.ByValue + + internal fun uniffiSetValue(other: UniffiForeignFuture) { + `handle` = other.`handle` + `free` = other.`free` + } + +} +@Structure.FieldOrder("returnValue", "callStatus") +internal open class UniffiForeignFutureStructU8( + @JvmField internal var `returnValue`: Byte = 0.toByte(), + @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), +) : Structure() { + class UniffiByValue( + `returnValue`: Byte = 0.toByte(), + `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), + ): UniffiForeignFutureStructU8(`returnValue`,`callStatus`,), Structure.ByValue + + internal fun uniffiSetValue(other: UniffiForeignFutureStructU8) { + `returnValue` = other.`returnValue` + `callStatus` = other.`callStatus` + } + +} +internal interface UniffiForeignFutureCompleteU8 : com.sun.jna.Callback { + fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructU8.UniffiByValue,) +} +@Structure.FieldOrder("returnValue", "callStatus") +internal open class UniffiForeignFutureStructI8( + @JvmField internal var `returnValue`: Byte = 0.toByte(), + @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), +) : Structure() { + class UniffiByValue( + `returnValue`: Byte = 0.toByte(), + `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), + ): UniffiForeignFutureStructI8(`returnValue`,`callStatus`,), Structure.ByValue + + internal fun uniffiSetValue(other: UniffiForeignFutureStructI8) { + `returnValue` = other.`returnValue` + `callStatus` = other.`callStatus` + } + +} +internal interface UniffiForeignFutureCompleteI8 : com.sun.jna.Callback { + fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructI8.UniffiByValue,) +} +@Structure.FieldOrder("returnValue", "callStatus") +internal open class UniffiForeignFutureStructU16( + @JvmField internal var `returnValue`: Short = 0.toShort(), + @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), +) : Structure() { + class UniffiByValue( + `returnValue`: Short = 0.toShort(), + `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), + ): UniffiForeignFutureStructU16(`returnValue`,`callStatus`,), Structure.ByValue + + internal fun uniffiSetValue(other: UniffiForeignFutureStructU16) { + `returnValue` = other.`returnValue` + `callStatus` = other.`callStatus` + } + +} +internal interface UniffiForeignFutureCompleteU16 : com.sun.jna.Callback { + fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructU16.UniffiByValue,) +} +@Structure.FieldOrder("returnValue", "callStatus") +internal open class UniffiForeignFutureStructI16( + @JvmField internal var `returnValue`: Short = 0.toShort(), + @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), +) : Structure() { + class UniffiByValue( + `returnValue`: Short = 0.toShort(), + `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), + ): UniffiForeignFutureStructI16(`returnValue`,`callStatus`,), Structure.ByValue + + internal fun uniffiSetValue(other: UniffiForeignFutureStructI16) { + `returnValue` = other.`returnValue` + `callStatus` = other.`callStatus` + } + +} +internal interface UniffiForeignFutureCompleteI16 : com.sun.jna.Callback { + fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructI16.UniffiByValue,) +} +@Structure.FieldOrder("returnValue", "callStatus") +internal open class UniffiForeignFutureStructU32( + @JvmField internal var `returnValue`: Int = 0, + @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), +) : Structure() { + class UniffiByValue( + `returnValue`: Int = 0, + `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), + ): UniffiForeignFutureStructU32(`returnValue`,`callStatus`,), Structure.ByValue + + internal fun uniffiSetValue(other: UniffiForeignFutureStructU32) { + `returnValue` = other.`returnValue` + `callStatus` = other.`callStatus` + } + +} +internal interface UniffiForeignFutureCompleteU32 : com.sun.jna.Callback { + fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructU32.UniffiByValue,) +} +@Structure.FieldOrder("returnValue", "callStatus") +internal open class UniffiForeignFutureStructI32( + @JvmField internal var `returnValue`: Int = 0, + @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), +) : Structure() { + class UniffiByValue( + `returnValue`: Int = 0, + `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), + ): UniffiForeignFutureStructI32(`returnValue`,`callStatus`,), Structure.ByValue + + internal fun uniffiSetValue(other: UniffiForeignFutureStructI32) { + `returnValue` = other.`returnValue` + `callStatus` = other.`callStatus` + } + +} +internal interface UniffiForeignFutureCompleteI32 : com.sun.jna.Callback { + fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructI32.UniffiByValue,) +} +@Structure.FieldOrder("returnValue", "callStatus") +internal open class UniffiForeignFutureStructU64( + @JvmField internal var `returnValue`: Long = 0.toLong(), + @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), +) : Structure() { + class UniffiByValue( + `returnValue`: Long = 0.toLong(), + `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), + ): UniffiForeignFutureStructU64(`returnValue`,`callStatus`,), Structure.ByValue + + internal fun uniffiSetValue(other: UniffiForeignFutureStructU64) { + `returnValue` = other.`returnValue` + `callStatus` = other.`callStatus` + } + +} +internal interface UniffiForeignFutureCompleteU64 : com.sun.jna.Callback { + fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructU64.UniffiByValue,) +} +@Structure.FieldOrder("returnValue", "callStatus") +internal open class UniffiForeignFutureStructI64( + @JvmField internal var `returnValue`: Long = 0.toLong(), + @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), +) : Structure() { + class UniffiByValue( + `returnValue`: Long = 0.toLong(), + `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), + ): UniffiForeignFutureStructI64(`returnValue`,`callStatus`,), Structure.ByValue + + internal fun uniffiSetValue(other: UniffiForeignFutureStructI64) { + `returnValue` = other.`returnValue` + `callStatus` = other.`callStatus` + } + +} +internal interface UniffiForeignFutureCompleteI64 : com.sun.jna.Callback { + fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructI64.UniffiByValue,) +} +@Structure.FieldOrder("returnValue", "callStatus") +internal open class UniffiForeignFutureStructF32( + @JvmField internal var `returnValue`: Float = 0.0f, + @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), +) : Structure() { + class UniffiByValue( + `returnValue`: Float = 0.0f, + `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), + ): UniffiForeignFutureStructF32(`returnValue`,`callStatus`,), Structure.ByValue + + internal fun uniffiSetValue(other: UniffiForeignFutureStructF32) { + `returnValue` = other.`returnValue` + `callStatus` = other.`callStatus` + } + +} +internal interface UniffiForeignFutureCompleteF32 : com.sun.jna.Callback { + fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructF32.UniffiByValue,) +} +@Structure.FieldOrder("returnValue", "callStatus") +internal open class UniffiForeignFutureStructF64( + @JvmField internal var `returnValue`: Double = 0.0, + @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), +) : Structure() { + class UniffiByValue( + `returnValue`: Double = 0.0, + `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), + ): UniffiForeignFutureStructF64(`returnValue`,`callStatus`,), Structure.ByValue + + internal fun uniffiSetValue(other: UniffiForeignFutureStructF64) { + `returnValue` = other.`returnValue` + `callStatus` = other.`callStatus` + } + +} +internal interface UniffiForeignFutureCompleteF64 : com.sun.jna.Callback { + fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructF64.UniffiByValue,) +} +@Structure.FieldOrder("returnValue", "callStatus") +internal open class UniffiForeignFutureStructPointer( + @JvmField internal var `returnValue`: Pointer = Pointer.NULL, + @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), +) : Structure() { + class UniffiByValue( + `returnValue`: Pointer = Pointer.NULL, + `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), + ): UniffiForeignFutureStructPointer(`returnValue`,`callStatus`,), Structure.ByValue + + internal fun uniffiSetValue(other: UniffiForeignFutureStructPointer) { + `returnValue` = other.`returnValue` + `callStatus` = other.`callStatus` + } + +} +internal interface UniffiForeignFutureCompletePointer : com.sun.jna.Callback { + fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructPointer.UniffiByValue,) +} +@Structure.FieldOrder("returnValue", "callStatus") +internal open class UniffiForeignFutureStructRustBuffer( + @JvmField internal var `returnValue`: RustBuffer.ByValue = RustBuffer.ByValue(), + @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), +) : Structure() { + class UniffiByValue( + `returnValue`: RustBuffer.ByValue = RustBuffer.ByValue(), + `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), + ): UniffiForeignFutureStructRustBuffer(`returnValue`,`callStatus`,), Structure.ByValue + + internal fun uniffiSetValue(other: UniffiForeignFutureStructRustBuffer) { + `returnValue` = other.`returnValue` + `callStatus` = other.`callStatus` + } + +} +internal interface UniffiForeignFutureCompleteRustBuffer : com.sun.jna.Callback { + fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructRustBuffer.UniffiByValue,) +} +@Structure.FieldOrder("callStatus") +internal open class UniffiForeignFutureStructVoid( + @JvmField internal var `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), +) : Structure() { + class UniffiByValue( + `callStatus`: UniffiRustCallStatus.ByValue = UniffiRustCallStatus.ByValue(), + ): UniffiForeignFutureStructVoid(`callStatus`,), Structure.ByValue + + internal fun uniffiSetValue(other: UniffiForeignFutureStructVoid) { + `callStatus` = other.`callStatus` + } + +} +internal interface UniffiForeignFutureCompleteVoid : com.sun.jna.Callback { + fun callback(`callbackData`: Long,`result`: UniffiForeignFutureStructVoid.UniffiByValue,) +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +// For large crates we prevent `MethodTooLargeException` (see #2340) +// N.B. the name of the extension is very misleading, since it is +// rather `InterfaceTooLargeException`, caused by too many methods +// in the interface for large crates. +// +// By splitting the otherwise huge interface into two parts +// * UniffiLib +// * IntegrityCheckingUniffiLib (this) +// we allow for ~2x as many methods in the UniffiLib interface. +// +// The `ffi_uniffi_contract_version` method and all checksum methods are put +// into `IntegrityCheckingUniffiLib` and these methods are called only once, +// when the library is loaded. +internal interface IntegrityCheckingUniffiLib : Library { + // Integrity check functions only + fun uniffi_glsdk_checksum_method_credentials_save( +): Short +fun uniffi_glsdk_checksum_method_handle_stop( +): Short +fun uniffi_glsdk_checksum_method_node_onchain_receive( +): Short +fun uniffi_glsdk_checksum_method_node_onchain_send( +): Short +fun uniffi_glsdk_checksum_method_node_receive( +): Short +fun uniffi_glsdk_checksum_method_node_send( +): Short +fun uniffi_glsdk_checksum_method_node_stop( +): Short +fun uniffi_glsdk_checksum_method_scheduler_recover( +): Short +fun uniffi_glsdk_checksum_method_scheduler_register( +): Short +fun uniffi_glsdk_checksum_method_signer_authenticate( +): Short +fun uniffi_glsdk_checksum_method_signer_node_id( +): Short +fun uniffi_glsdk_checksum_method_signer_start( +): Short +fun uniffi_glsdk_checksum_constructor_credentials_load( +): Short +fun uniffi_glsdk_checksum_constructor_node_new( +): Short +fun uniffi_glsdk_checksum_constructor_scheduler_new( +): Short +fun uniffi_glsdk_checksum_constructor_signer_new( +): Short +fun ffi_glsdk_uniffi_contract_version( +): Int + +} + +// 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 { + val componentName = "glsdk" + // For large crates we prevent `MethodTooLargeException` (see #2340) + // N.B. the name of the extension is very misleading, since it is + // rather `InterfaceTooLargeException`, caused by too many methods + // in the interface for large crates. + // + // By splitting the otherwise huge interface into two parts + // * UniffiLib (this) + // * IntegrityCheckingUniffiLib + // And all checksum methods are put into `IntegrityCheckingUniffiLib` + // we allow for ~2x as many methods in the UniffiLib interface. + // + // Thus we first load the library with `loadIndirect` as `IntegrityCheckingUniffiLib` + // so that we can (optionally!) call `uniffiCheckApiChecksums`... + loadIndirect(componentName) + .also { lib: IntegrityCheckingUniffiLib -> + uniffiCheckContractApiVersion(lib) + uniffiCheckApiChecksums(lib) + } + // ... and then we load the library as `UniffiLib` + // N.B. we cannot use `loadIndirect` once and then try to cast it to `UniffiLib` + // => results in `java.lang.ClassCastException: com.sun.proxy.$Proxy cannot be cast to ...` + // error. So we must call `loadIndirect` twice. For crates large enough + // to trigger this issue, the performance impact is negligible, running on + // a macOS M1 machine the `loadIndirect` call takes ~50ms. + val lib = loadIndirect(componentName) + // No need to check the contract version and checksums, since + // we already did that with `IntegrityCheckingUniffiLib` above. + // Loading of library with integrity check done. + lib + } + + // The Cleaner for the whole library + internal val CLEANER: UniffiCleaner by lazy { + UniffiCleaner.create() + } + } + + // FFI functions + fun uniffi_glsdk_fn_clone_credentials(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun uniffi_glsdk_fn_free_credentials(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Unit +fun uniffi_glsdk_fn_constructor_credentials_load(`raw`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun uniffi_glsdk_fn_method_credentials_save(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): RustBuffer.ByValue +fun uniffi_glsdk_fn_clone_handle(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun uniffi_glsdk_fn_free_handle(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Unit +fun uniffi_glsdk_fn_method_handle_stop(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Unit +fun uniffi_glsdk_fn_clone_node(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun uniffi_glsdk_fn_free_node(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Unit +fun uniffi_glsdk_fn_constructor_node_new(`credentials`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun uniffi_glsdk_fn_method_node_onchain_receive(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun uniffi_glsdk_fn_method_node_onchain_send(`ptr`: Pointer,`destination`: RustBuffer.ByValue,`amountOrAll`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun uniffi_glsdk_fn_method_node_receive(`ptr`: Pointer,`label`: RustBuffer.ByValue,`description`: RustBuffer.ByValue,`amountMsat`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun uniffi_glsdk_fn_method_node_send(`ptr`: Pointer,`invoice`: RustBuffer.ByValue,`amountMsat`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun uniffi_glsdk_fn_method_node_stop(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Unit +fun uniffi_glsdk_fn_clone_onchainreceiveresponse(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun uniffi_glsdk_fn_free_onchainreceiveresponse(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Unit +fun uniffi_glsdk_fn_clone_onchainsendresponse(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun uniffi_glsdk_fn_free_onchainsendresponse(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Unit +fun uniffi_glsdk_fn_clone_receiveresponse(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun uniffi_glsdk_fn_free_receiveresponse(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Unit +fun uniffi_glsdk_fn_clone_scheduler(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun uniffi_glsdk_fn_free_scheduler(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Unit +fun uniffi_glsdk_fn_constructor_scheduler_new(`network`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun uniffi_glsdk_fn_method_scheduler_recover(`ptr`: Pointer,`signer`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun uniffi_glsdk_fn_method_scheduler_register(`ptr`: Pointer,`signer`: Pointer,`code`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun uniffi_glsdk_fn_clone_sendresponse(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun uniffi_glsdk_fn_free_sendresponse(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Unit +fun uniffi_glsdk_fn_clone_signer(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun uniffi_glsdk_fn_free_signer(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Unit +fun uniffi_glsdk_fn_constructor_signer_new(`phrase`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun uniffi_glsdk_fn_method_signer_authenticate(`ptr`: Pointer,`creds`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun uniffi_glsdk_fn_method_signer_node_id(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): RustBuffer.ByValue +fun uniffi_glsdk_fn_method_signer_start(`ptr`: Pointer,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun ffi_glsdk_rustbuffer_alloc(`size`: Long,uniffi_out_err: UniffiRustCallStatus, +): RustBuffer.ByValue +fun ffi_glsdk_rustbuffer_from_bytes(`bytes`: ForeignBytes.ByValue,uniffi_out_err: UniffiRustCallStatus, +): RustBuffer.ByValue +fun ffi_glsdk_rustbuffer_free(`buf`: RustBuffer.ByValue,uniffi_out_err: UniffiRustCallStatus, +): Unit +fun ffi_glsdk_rustbuffer_reserve(`buf`: RustBuffer.ByValue,`additional`: Long,uniffi_out_err: UniffiRustCallStatus, +): RustBuffer.ByValue +fun ffi_glsdk_rust_future_poll_u8(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, +): Unit +fun ffi_glsdk_rust_future_cancel_u8(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_free_u8(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_complete_u8(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, +): Byte +fun ffi_glsdk_rust_future_poll_i8(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, +): Unit +fun ffi_glsdk_rust_future_cancel_i8(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_free_i8(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_complete_i8(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, +): Byte +fun ffi_glsdk_rust_future_poll_u16(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, +): Unit +fun ffi_glsdk_rust_future_cancel_u16(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_free_u16(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_complete_u16(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, +): Short +fun ffi_glsdk_rust_future_poll_i16(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, +): Unit +fun ffi_glsdk_rust_future_cancel_i16(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_free_i16(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_complete_i16(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, +): Short +fun ffi_glsdk_rust_future_poll_u32(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, +): Unit +fun ffi_glsdk_rust_future_cancel_u32(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_free_u32(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_complete_u32(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, +): Int +fun ffi_glsdk_rust_future_poll_i32(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, +): Unit +fun ffi_glsdk_rust_future_cancel_i32(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_free_i32(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_complete_i32(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, +): Int +fun ffi_glsdk_rust_future_poll_u64(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, +): Unit +fun ffi_glsdk_rust_future_cancel_u64(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_free_u64(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_complete_u64(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, +): Long +fun ffi_glsdk_rust_future_poll_i64(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, +): Unit +fun ffi_glsdk_rust_future_cancel_i64(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_free_i64(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_complete_i64(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, +): Long +fun ffi_glsdk_rust_future_poll_f32(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, +): Unit +fun ffi_glsdk_rust_future_cancel_f32(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_free_f32(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_complete_f32(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, +): Float +fun ffi_glsdk_rust_future_poll_f64(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, +): Unit +fun ffi_glsdk_rust_future_cancel_f64(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_free_f64(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_complete_f64(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, +): Double +fun ffi_glsdk_rust_future_poll_pointer(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, +): Unit +fun ffi_glsdk_rust_future_cancel_pointer(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_free_pointer(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_complete_pointer(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, +): Pointer +fun ffi_glsdk_rust_future_poll_rust_buffer(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, +): Unit +fun ffi_glsdk_rust_future_cancel_rust_buffer(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_free_rust_buffer(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_complete_rust_buffer(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, +): RustBuffer.ByValue +fun ffi_glsdk_rust_future_poll_void(`handle`: Long,`callback`: UniffiRustFutureContinuationCallback,`callbackData`: Long, +): Unit +fun ffi_glsdk_rust_future_cancel_void(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_free_void(`handle`: Long, +): Unit +fun ffi_glsdk_rust_future_complete_void(`handle`: Long,uniffi_out_err: UniffiRustCallStatus, +): Unit + +} + +private fun uniffiCheckContractApiVersion(lib: IntegrityCheckingUniffiLib) { + // Get the bindings contract version from our ComponentInterface + val bindings_contract_version = 29 + // Get the scaffolding contract version by calling the into the dylib + val scaffolding_contract_version = lib.ffi_glsdk_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: IntegrityCheckingUniffiLib) { + if (lib.uniffi_glsdk_checksum_method_credentials_save() != 26677.toShort()) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } + if (lib.uniffi_glsdk_checksum_method_handle_stop() != 36432.toShort()) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } + if (lib.uniffi_glsdk_checksum_method_node_onchain_receive() != 21676.toShort()) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } + if (lib.uniffi_glsdk_checksum_method_node_onchain_send() != 51884.toShort()) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } + if (lib.uniffi_glsdk_checksum_method_node_receive() != 24722.toShort()) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } + if (lib.uniffi_glsdk_checksum_method_node_send() != 30141.toShort()) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } + if (lib.uniffi_glsdk_checksum_method_node_stop() != 20186.toShort()) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } + if (lib.uniffi_glsdk_checksum_method_scheduler_recover() != 55514.toShort()) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } + if (lib.uniffi_glsdk_checksum_method_scheduler_register() != 20821.toShort()) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } + if (lib.uniffi_glsdk_checksum_method_signer_authenticate() != 55935.toShort()) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } + if (lib.uniffi_glsdk_checksum_method_signer_node_id() != 43931.toShort()) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } + if (lib.uniffi_glsdk_checksum_method_signer_start() != 9404.toShort()) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } + if (lib.uniffi_glsdk_checksum_constructor_credentials_load() != 25306.toShort()) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } + if (lib.uniffi_glsdk_checksum_constructor_node_new() != 7003.toShort()) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } + if (lib.uniffi_glsdk_checksum_constructor_scheduler_new() != 15239.toShort()) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } + if (lib.uniffi_glsdk_checksum_constructor_signer_new() != 62159.toShort()) { + throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project") + } +} + +/** + * @suppress + */ +public fun uniffiEnsureInitialized() { + UniffiLib.INSTANCE +} + +// Async support + +// Public interface members begin here. + + +// 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?) { + for (arg in args) { + when (arg) { + is Disposable -> arg.destroy() + is ArrayList<*> -> { + for (idx in arg.indices) { + val element = arg[idx] + if (element is Disposable) { + element.destroy() + } + } + } + is Map<*, *> -> { + for (element in arg.values) { + if (element is Disposable) { + element.destroy() + } + } + } + is Iterable<*> -> { + for (element in arg) { + if (element is Disposable) { + element.destroy() + } + } + } + } + } + } + } +} + +/** + * @suppress + */ +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 + } + } + +/** + * Used to instantiate an interface without an actual pointer, for fakes in tests, mostly. + * + * @suppress + * */ +object NoPointer +/** + * The cleaner interface for Object finalization code to run. + * This is the entry point to any implementation that we're using. + * + * The cleaner registers objects and returns cleanables, so now we are + * defining a `UniffiCleaner` with a `UniffiClenaer.Cleanable` to abstract the + * different implmentations available at compile time. + * + * @suppress + */ +interface UniffiCleaner { + interface Cleanable { + fun clean() + } + + fun register(value: Any, cleanUpTask: Runnable): UniffiCleaner.Cleanable + + companion object +} + +// The fallback Jna cleaner, which is available for both Android, and the JVM. +private class UniffiJnaCleaner : UniffiCleaner { + private val cleaner = com.sun.jna.internal.Cleaner.getCleaner() + + override fun register(value: Any, cleanUpTask: Runnable): UniffiCleaner.Cleanable = + UniffiJnaCleanable(cleaner.register(value, cleanUpTask)) +} + +private class UniffiJnaCleanable( + private val cleanable: com.sun.jna.internal.Cleaner.Cleanable, +) : UniffiCleaner.Cleanable { + override fun clean() = cleanable.clean() +} + + +// We decide at uniffi binding generation time whether we were +// using Android or not. +// There are further runtime checks to chose the correct implementation +// of the cleaner. +private fun UniffiCleaner.Companion.create(): UniffiCleaner = + try { + // For safety's sake: if the library hasn't been run in android_cleaner = true + // mode, but is being run on Android, then we still need to think about + // Android API versions. + // So we check if java.lang.ref.Cleaner is there, and use that… + java.lang.Class.forName("java.lang.ref.Cleaner") + JavaLangRefCleaner() + } catch (e: ClassNotFoundException) { + // … otherwise, fallback to the JNA cleaner. + UniffiJnaCleaner() + } + +private class JavaLangRefCleaner : UniffiCleaner { + val cleaner = java.lang.ref.Cleaner.create() + + override fun register(value: Any, cleanUpTask: Runnable): UniffiCleaner.Cleanable = + JavaLangRefCleanable(cleaner.register(value, cleanUpTask)) +} + +private class JavaLangRefCleanable( + val cleanable: java.lang.ref.Cleaner.Cleanable +) : UniffiCleaner.Cleanable { + override fun clean() = cleanable.clean() +} + +/** + * @suppress + */ +public object FfiConverterInt: FfiConverter { + override fun lift(value: Int): Int { + return value + } + + override fun read(buf: ByteBuffer): Int { + return buf.getInt() + } + + override fun lower(value: Int): Int { + return value + } + + override fun allocationSize(value: Int) = 4UL + + override fun write(value: Int, buf: ByteBuffer) { + buf.putInt(value) + } +} + +/** + * @suppress + */ +public object FfiConverterULong: FfiConverter { + override fun lift(value: Long): ULong { + return value.toULong() + } + + override fun read(buf: ByteBuffer): ULong { + return lift(buf.getLong()) + } + + override fun lower(value: ULong): Long { + return value.toLong() + } + + override fun allocationSize(value: ULong) = 8UL + + override fun write(value: ULong, buf: ByteBuffer) { + buf.putLong(value.toLong()) + } +} + +/** + * @suppress + */ +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.toInt()) + 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().toULong()) + 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): ULong { + val sizeForLength = 4UL + val sizeForString = value.length.toULong() * 3UL + return sizeForLength + sizeForString + } + + override fun write(value: String, buf: ByteBuffer) { + val byteBuf = toUtf8(value) + buf.putInt(byteBuf.limit()) + buf.put(byteBuf) + } +} + +/** + * @suppress + */ +public object FfiConverterByteArray: FfiConverterRustBuffer { + override fun read(buf: ByteBuffer): ByteArray { + val len = buf.getInt() + val byteArr = ByteArray(len) + buf.get(byteArr) + return byteArr + } + override fun allocationSize(value: ByteArray): ULong { + return 4UL + value.size.toULong() + } + override fun write(value: ByteArray, buf: ByteBuffer) { + buf.putInt(value.size) + buf.put(value) + } +} + + +// This template implements a class for working with a Rust struct via a Pointer/Arc +// to the live Rust struct on the other side of the FFI. +// +// Each instance implements core operations for working with the Rust `Arc` and the +// Kotlin Pointer to work with 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 +// theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: +// +// * Each 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 instance 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 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 risks +// leaking 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. +// +// * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` +// is implemented to call the destructor when the Kotlin object becomes unreachable. +// This is done in a background thread. This is not a panacea, and client code should be aware that +// 1. the thread may starve if some there are objects that have poorly performing +// `drop` methods or do significant work in their `drop` methods. +// 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, +// or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). +// +// 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 instance 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. +// +// This makes a cleaner a better alternative to _not_ calling `destroy()` as +// and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` +// method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner +// thread may be starved, and the app will leak memory. +// +// In this case, `destroy`ing manually may be a better solution. +// +// The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects +// with Rust peers are reclaimed: +// +// 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: +// 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: +// 3. The memory is reclaimed when the process terminates. +// +// [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 +// + + +/** + * `Credentials` is a container for `node_id`, the mTLS client + * certificate used to authenticate a client against a node, as well + * as the seed secret if present. If no seed is present in the + * credentials, then the `Client` will not start a signer in the + * background. + */ +public interface CredentialsInterface { + + fun `save`(): kotlin.ByteArray + + companion object +} + +/** + * `Credentials` is a container for `node_id`, the mTLS client + * certificate used to authenticate a client against a node, as well + * as the seed secret if present. If no seed is present in the + * credentials, then the `Client` will not start a signer in the + * background. + */ +open class Credentials: Disposable, AutoCloseable, CredentialsInterface +{ + + constructor(pointer: Pointer) { + this.pointer = pointer + this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) + } + + /** + * This constructor can be used to instantiate a fake object. Only used for tests. Any + * attempt to actually use an object constructed this way will fail as there is no + * connected Rust object. + */ + @Suppress("UNUSED_PARAMETER") + constructor(noPointer: NoPointer) { + this.pointer = null + this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) + } + + protected val pointer: Pointer? + protected val cleanable: UniffiCleaner.Cleanable + + private val wasDestroyed = AtomicBoolean(false) + private val callCounter = AtomicLong(1) + + 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) { + cleanable.clean() + } + } + } + + @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.uniffiClonePointer()) + } finally { + // This decrement always matches the increment we performed above. + if (this.callCounter.decrementAndGet() == 0L) { + cleanable.clean() + } + } + } + + // Use a static inner class instead of a closure so as not to accidentally + // capture `this` as part of the cleanable's action. + private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { + override fun run() { + pointer?.let { ptr -> + uniffiRustCall { status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_free_credentials(ptr, status) + } + } + } + } + + fun uniffiClonePointer(): Pointer { + return uniffiRustCall() { status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_clone_credentials(pointer!!, status) + } + } + + + @Throws(Exception::class)override fun `save`(): kotlin.ByteArray { + return FfiConverterByteArray.lift( + callWithPointer { + uniffiRustCallWithError(Exception) { _status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_method_credentials_save( + it, _status) +} + } + ) + } + + + + + + companion object { + + @Throws(Exception::class) fun `load`(`raw`: kotlin.ByteArray): Credentials { + return FfiConverterTypeCredentials.lift( + uniffiRustCallWithError(Exception) { _status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_constructor_credentials_load( + FfiConverterByteArray.lower(`raw`),_status) +} + ) + } + + + + } + +} + +/** + * @suppress + */ +public object FfiConverterTypeCredentials: FfiConverter { + + override fun lower(value: Credentials): Pointer { + return value.uniffiClonePointer() + } + + override fun lift(value: Pointer): Credentials { + return Credentials(value) + } + + override fun read(buf: ByteBuffer): Credentials { + // 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: Credentials) = 8UL + + override fun write(value: Credentials, 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))) + } +} + + +// This template implements a class for working with a Rust struct via a Pointer/Arc +// to the live Rust struct on the other side of the FFI. +// +// Each instance implements core operations for working with the Rust `Arc` and the +// Kotlin Pointer to work with 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 +// theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: +// +// * Each 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 instance 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 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 risks +// leaking 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. +// +// * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` +// is implemented to call the destructor when the Kotlin object becomes unreachable. +// This is done in a background thread. This is not a panacea, and client code should be aware that +// 1. the thread may starve if some there are objects that have poorly performing +// `drop` methods or do significant work in their `drop` methods. +// 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, +// or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). +// +// 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 instance 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. +// +// This makes a cleaner a better alternative to _not_ calling `destroy()` as +// and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` +// method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner +// thread may be starved, and the app will leak memory. +// +// In this case, `destroy`ing manually may be a better solution. +// +// The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects +// with Rust peers are reclaimed: +// +// 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: +// 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: +// 3. The memory is reclaimed when the process terminates. +// +// [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 +// + + +/** + * A handle to interact with a signer loop running and processing + * requests in the background. Used primarily to stop the loop and + * exiting the signer. + */ +public interface HandleInterface { + + fun `stop`() + + companion object +} + +/** + * A handle to interact with a signer loop running and processing + * requests in the background. Used primarily to stop the loop and + * exiting the signer. + */ +open class Handle: Disposable, AutoCloseable, HandleInterface +{ + + constructor(pointer: Pointer) { + this.pointer = pointer + this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) + } + + /** + * This constructor can be used to instantiate a fake object. Only used for tests. Any + * attempt to actually use an object constructed this way will fail as there is no + * connected Rust object. + */ + @Suppress("UNUSED_PARAMETER") + constructor(noPointer: NoPointer) { + this.pointer = null + this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) + } + + protected val pointer: Pointer? + protected val cleanable: UniffiCleaner.Cleanable + + private val wasDestroyed = AtomicBoolean(false) + private val callCounter = AtomicLong(1) + + 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) { + cleanable.clean() + } + } + } + + @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.uniffiClonePointer()) + } finally { + // This decrement always matches the increment we performed above. + if (this.callCounter.decrementAndGet() == 0L) { + cleanable.clean() + } + } + } + + // Use a static inner class instead of a closure so as not to accidentally + // capture `this` as part of the cleanable's action. + private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { + override fun run() { + pointer?.let { ptr -> + uniffiRustCall { status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_free_handle(ptr, status) + } + } + } + } + + fun uniffiClonePointer(): Pointer { + return uniffiRustCall() { status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_clone_handle(pointer!!, status) + } + } + + override fun `stop`() + = + callWithPointer { + uniffiRustCall() { _status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_method_handle_stop( + it, _status) +} + } + + + + + + + + companion object + +} + +/** + * @suppress + */ +public object FfiConverterTypeHandle: FfiConverter { + + override fun lower(value: Handle): Pointer { + return value.uniffiClonePointer() + } + + override fun lift(value: Pointer): Handle { + return Handle(value) + } + + override fun read(buf: ByteBuffer): Handle { + // 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: Handle) = 8UL + + override fun write(value: Handle, 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))) + } +} + + +// This template implements a class for working with a Rust struct via a Pointer/Arc +// to the live Rust struct on the other side of the FFI. +// +// Each instance implements core operations for working with the Rust `Arc` and the +// Kotlin Pointer to work with 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 +// theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: +// +// * Each 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 instance 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 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 risks +// leaking 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. +// +// * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` +// is implemented to call the destructor when the Kotlin object becomes unreachable. +// This is done in a background thread. This is not a panacea, and client code should be aware that +// 1. the thread may starve if some there are objects that have poorly performing +// `drop` methods or do significant work in their `drop` methods. +// 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, +// or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). +// +// 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 instance 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. +// +// This makes a cleaner a better alternative to _not_ calling `destroy()` as +// and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` +// method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner +// thread may be starved, and the app will leak memory. +// +// In this case, `destroy`ing manually may be a better solution. +// +// The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects +// with Rust peers are reclaimed: +// +// 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: +// 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: +// 3. The memory is reclaimed when the process terminates. +// +// [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 +// + + +/** + * The `Node` is an RPC stub representing the node running in the + * cloud. It is the main entrypoint to interact with the node. + */ +public interface NodeInterface { + + fun `onchainReceive`(): OnchainReceiveResponse + + fun `onchainSend`(`destination`: kotlin.String, `amountOrAll`: kotlin.String): OnchainSendResponse + + /** + * Receive an off-chain payment. + * + * This method generates a request for a payment, also called an + * invoice, that encodes all the information, including amount + * and destination, for a prospective sender to send a lightning + * payment. The invoice includes negotiation of an LSPS2 / JIT + * channel, meaning that if there is no channel sufficient to + * receive the requested funds, the node will negotiate an + * opening, and when/if executed the payment will cause a channel + * to be created, and the incoming payment to be forwarded. + */ + fun `receive`(`label`: kotlin.String, `description`: kotlin.String, `amountMsat`: kotlin.ULong?): ReceiveResponse + + fun `send`(`invoice`: kotlin.String, `amountMsat`: kotlin.ULong?): SendResponse + + /** + * Stop the node if it is currently running. + */ + fun `stop`() + + companion object +} + +/** + * The `Node` is an RPC stub representing the node running in the + * cloud. It is the main entrypoint to interact with the node. + */ +open class Node: Disposable, AutoCloseable, NodeInterface +{ + + constructor(pointer: Pointer) { + this.pointer = pointer + this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) + } + + /** + * This constructor can be used to instantiate a fake object. Only used for tests. Any + * attempt to actually use an object constructed this way will fail as there is no + * connected Rust object. + */ + @Suppress("UNUSED_PARAMETER") + constructor(noPointer: NoPointer) { + this.pointer = null + this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) + } + constructor(`credentials`: Credentials) : + this( + uniffiRustCallWithError(Exception) { _status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_constructor_node_new( + FfiConverterTypeCredentials.lower(`credentials`),_status) +} + ) + + protected val pointer: Pointer? + protected val cleanable: UniffiCleaner.Cleanable + + private val wasDestroyed = AtomicBoolean(false) + private val callCounter = AtomicLong(1) + + 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) { + cleanable.clean() + } + } + } + + @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.uniffiClonePointer()) + } finally { + // This decrement always matches the increment we performed above. + if (this.callCounter.decrementAndGet() == 0L) { + cleanable.clean() + } + } + } + + // Use a static inner class instead of a closure so as not to accidentally + // capture `this` as part of the cleanable's action. + private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { + override fun run() { + pointer?.let { ptr -> + uniffiRustCall { status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_free_node(ptr, status) + } + } + } + } + + fun uniffiClonePointer(): Pointer { + return uniffiRustCall() { status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_clone_node(pointer!!, status) + } + } + + + @Throws(Exception::class)override fun `onchainReceive`(): OnchainReceiveResponse { + return FfiConverterTypeOnchainReceiveResponse.lift( + callWithPointer { + uniffiRustCallWithError(Exception) { _status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_method_node_onchain_receive( + it, _status) +} + } + ) + } + + + + @Throws(Exception::class)override fun `onchainSend`(`destination`: kotlin.String, `amountOrAll`: kotlin.String): OnchainSendResponse { + return FfiConverterTypeOnchainSendResponse.lift( + callWithPointer { + uniffiRustCallWithError(Exception) { _status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_method_node_onchain_send( + it, FfiConverterString.lower(`destination`),FfiConverterString.lower(`amountOrAll`),_status) +} + } + ) + } + + + + /** + * Receive an off-chain payment. + * + * This method generates a request for a payment, also called an + * invoice, that encodes all the information, including amount + * and destination, for a prospective sender to send a lightning + * payment. The invoice includes negotiation of an LSPS2 / JIT + * channel, meaning that if there is no channel sufficient to + * receive the requested funds, the node will negotiate an + * opening, and when/if executed the payment will cause a channel + * to be created, and the incoming payment to be forwarded. + */ + @Throws(Exception::class)override fun `receive`(`label`: kotlin.String, `description`: kotlin.String, `amountMsat`: kotlin.ULong?): ReceiveResponse { + return FfiConverterTypeReceiveResponse.lift( + callWithPointer { + uniffiRustCallWithError(Exception) { _status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_method_node_receive( + it, FfiConverterString.lower(`label`),FfiConverterString.lower(`description`),FfiConverterOptionalULong.lower(`amountMsat`),_status) +} + } + ) + } + + + + @Throws(Exception::class)override fun `send`(`invoice`: kotlin.String, `amountMsat`: kotlin.ULong?): SendResponse { + return FfiConverterTypeSendResponse.lift( + callWithPointer { + uniffiRustCallWithError(Exception) { _status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_method_node_send( + it, FfiConverterString.lower(`invoice`),FfiConverterOptionalULong.lower(`amountMsat`),_status) +} + } + ) + } + + + + /** + * Stop the node if it is currently running. + */ + @Throws(Exception::class)override fun `stop`() + = + callWithPointer { + uniffiRustCallWithError(Exception) { _status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_method_node_stop( + it, _status) +} + } + + + + + + + + companion object + +} + +/** + * @suppress + */ +public object FfiConverterTypeNode: FfiConverter { + + override fun lower(value: Node): Pointer { + return value.uniffiClonePointer() + } + + override fun lift(value: Pointer): Node { + return Node(value) + } + + override fun read(buf: ByteBuffer): Node { + // 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: Node) = 8UL + + override fun write(value: Node, 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))) + } +} + + +// This template implements a class for working with a Rust struct via a Pointer/Arc +// to the live Rust struct on the other side of the FFI. +// +// Each instance implements core operations for working with the Rust `Arc` and the +// Kotlin Pointer to work with 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 +// theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: +// +// * Each 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 instance 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 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 risks +// leaking 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. +// +// * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` +// is implemented to call the destructor when the Kotlin object becomes unreachable. +// This is done in a background thread. This is not a panacea, and client code should be aware that +// 1. the thread may starve if some there are objects that have poorly performing +// `drop` methods or do significant work in their `drop` methods. +// 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, +// or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). +// +// 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 instance 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. +// +// This makes a cleaner a better alternative to _not_ calling `destroy()` as +// and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` +// method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner +// thread may be starved, and the app will leak memory. +// +// In this case, `destroy`ing manually may be a better solution. +// +// The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects +// with Rust peers are reclaimed: +// +// 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: +// 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: +// 3. The memory is reclaimed when the process terminates. +// +// [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 +// + + +public interface OnchainReceiveResponseInterface { + + companion object +} + +open class OnchainReceiveResponse: Disposable, AutoCloseable, OnchainReceiveResponseInterface +{ + + constructor(pointer: Pointer) { + this.pointer = pointer + this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) + } + + /** + * This constructor can be used to instantiate a fake object. Only used for tests. Any + * attempt to actually use an object constructed this way will fail as there is no + * connected Rust object. + */ + @Suppress("UNUSED_PARAMETER") + constructor(noPointer: NoPointer) { + this.pointer = null + this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) + } + + protected val pointer: Pointer? + protected val cleanable: UniffiCleaner.Cleanable + + private val wasDestroyed = AtomicBoolean(false) + private val callCounter = AtomicLong(1) + + 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) { + cleanable.clean() + } + } + } + + @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.uniffiClonePointer()) + } finally { + // This decrement always matches the increment we performed above. + if (this.callCounter.decrementAndGet() == 0L) { + cleanable.clean() + } + } + } + + // Use a static inner class instead of a closure so as not to accidentally + // capture `this` as part of the cleanable's action. + private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { + override fun run() { + pointer?.let { ptr -> + uniffiRustCall { status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_free_onchainreceiveresponse(ptr, status) + } + } + } + } + + fun uniffiClonePointer(): Pointer { + return uniffiRustCall() { status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_clone_onchainreceiveresponse(pointer!!, status) + } + } + + + + + + companion object + +} + +/** + * @suppress + */ +public object FfiConverterTypeOnchainReceiveResponse: FfiConverter { + + override fun lower(value: OnchainReceiveResponse): Pointer { + return value.uniffiClonePointer() + } + + override fun lift(value: Pointer): OnchainReceiveResponse { + return OnchainReceiveResponse(value) + } + + override fun read(buf: ByteBuffer): OnchainReceiveResponse { + // 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: OnchainReceiveResponse) = 8UL + + override fun write(value: OnchainReceiveResponse, 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))) + } +} + + +// This template implements a class for working with a Rust struct via a Pointer/Arc +// to the live Rust struct on the other side of the FFI. +// +// Each instance implements core operations for working with the Rust `Arc` and the +// Kotlin Pointer to work with 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 +// theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: +// +// * Each 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 instance 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 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 risks +// leaking 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. +// +// * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` +// is implemented to call the destructor when the Kotlin object becomes unreachable. +// This is done in a background thread. This is not a panacea, and client code should be aware that +// 1. the thread may starve if some there are objects that have poorly performing +// `drop` methods or do significant work in their `drop` methods. +// 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, +// or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). +// +// 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 instance 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. +// +// This makes a cleaner a better alternative to _not_ calling `destroy()` as +// and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` +// method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner +// thread may be starved, and the app will leak memory. +// +// In this case, `destroy`ing manually may be a better solution. +// +// The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects +// with Rust peers are reclaimed: +// +// 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: +// 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: +// 3. The memory is reclaimed when the process terminates. +// +// [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 +// + + +public interface OnchainSendResponseInterface { + + companion object +} + +open class OnchainSendResponse: Disposable, AutoCloseable, OnchainSendResponseInterface +{ + + constructor(pointer: Pointer) { + this.pointer = pointer + this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) + } + + /** + * This constructor can be used to instantiate a fake object. Only used for tests. Any + * attempt to actually use an object constructed this way will fail as there is no + * connected Rust object. + */ + @Suppress("UNUSED_PARAMETER") + constructor(noPointer: NoPointer) { + this.pointer = null + this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) + } + + protected val pointer: Pointer? + protected val cleanable: UniffiCleaner.Cleanable + + private val wasDestroyed = AtomicBoolean(false) + private val callCounter = AtomicLong(1) + + 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) { + cleanable.clean() + } + } + } + + @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.uniffiClonePointer()) + } finally { + // This decrement always matches the increment we performed above. + if (this.callCounter.decrementAndGet() == 0L) { + cleanable.clean() + } + } + } + + // Use a static inner class instead of a closure so as not to accidentally + // capture `this` as part of the cleanable's action. + private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { + override fun run() { + pointer?.let { ptr -> + uniffiRustCall { status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_free_onchainsendresponse(ptr, status) + } + } + } + } + + fun uniffiClonePointer(): Pointer { + return uniffiRustCall() { status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_clone_onchainsendresponse(pointer!!, status) + } + } + + + + + + companion object + +} + +/** + * @suppress + */ +public object FfiConverterTypeOnchainSendResponse: FfiConverter { + + override fun lower(value: OnchainSendResponse): Pointer { + return value.uniffiClonePointer() + } + + override fun lift(value: Pointer): OnchainSendResponse { + return OnchainSendResponse(value) + } + + override fun read(buf: ByteBuffer): OnchainSendResponse { + // 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: OnchainSendResponse) = 8UL + + override fun write(value: OnchainSendResponse, 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))) + } +} + + +// This template implements a class for working with a Rust struct via a Pointer/Arc +// to the live Rust struct on the other side of the FFI. +// +// Each instance implements core operations for working with the Rust `Arc` and the +// Kotlin Pointer to work with 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 +// theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: +// +// * Each 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 instance 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 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 risks +// leaking 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. +// +// * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` +// is implemented to call the destructor when the Kotlin object becomes unreachable. +// This is done in a background thread. This is not a panacea, and client code should be aware that +// 1. the thread may starve if some there are objects that have poorly performing +// `drop` methods or do significant work in their `drop` methods. +// 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, +// or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). +// +// 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 instance 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. +// +// This makes a cleaner a better alternative to _not_ calling `destroy()` as +// and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` +// method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner +// thread may be starved, and the app will leak memory. +// +// In this case, `destroy`ing manually may be a better solution. +// +// The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects +// with Rust peers are reclaimed: +// +// 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: +// 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: +// 3. The memory is reclaimed when the process terminates. +// +// [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 +// + + +public interface ReceiveResponseInterface { + + companion object +} + +open class ReceiveResponse: Disposable, AutoCloseable, ReceiveResponseInterface +{ + + constructor(pointer: Pointer) { + this.pointer = pointer + this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) + } + + /** + * This constructor can be used to instantiate a fake object. Only used for tests. Any + * attempt to actually use an object constructed this way will fail as there is no + * connected Rust object. + */ + @Suppress("UNUSED_PARAMETER") + constructor(noPointer: NoPointer) { + this.pointer = null + this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) + } + + protected val pointer: Pointer? + protected val cleanable: UniffiCleaner.Cleanable + + private val wasDestroyed = AtomicBoolean(false) + private val callCounter = AtomicLong(1) + + 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) { + cleanable.clean() + } + } + } + + @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.uniffiClonePointer()) + } finally { + // This decrement always matches the increment we performed above. + if (this.callCounter.decrementAndGet() == 0L) { + cleanable.clean() + } + } + } + + // Use a static inner class instead of a closure so as not to accidentally + // capture `this` as part of the cleanable's action. + private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { + override fun run() { + pointer?.let { ptr -> + uniffiRustCall { status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_free_receiveresponse(ptr, status) + } + } + } + } + + fun uniffiClonePointer(): Pointer { + return uniffiRustCall() { status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_clone_receiveresponse(pointer!!, status) + } + } + + + + + + companion object + +} + +/** + * @suppress + */ +public object FfiConverterTypeReceiveResponse: FfiConverter { + + override fun lower(value: ReceiveResponse): Pointer { + return value.uniffiClonePointer() + } + + override fun lift(value: Pointer): ReceiveResponse { + return ReceiveResponse(value) + } + + override fun read(buf: ByteBuffer): ReceiveResponse { + // 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: ReceiveResponse) = 8UL + + override fun write(value: ReceiveResponse, 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))) + } +} + + +// This template implements a class for working with a Rust struct via a Pointer/Arc +// to the live Rust struct on the other side of the FFI. +// +// Each instance implements core operations for working with the Rust `Arc` and the +// Kotlin Pointer to work with 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 +// theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: +// +// * Each 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 instance 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 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 risks +// leaking 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. +// +// * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` +// is implemented to call the destructor when the Kotlin object becomes unreachable. +// This is done in a background thread. This is not a panacea, and client code should be aware that +// 1. the thread may starve if some there are objects that have poorly performing +// `drop` methods or do significant work in their `drop` methods. +// 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, +// or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). +// +// 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 instance 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. +// +// This makes a cleaner a better alternative to _not_ calling `destroy()` as +// and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` +// method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner +// thread may be starved, and the app will leak memory. +// +// In this case, `destroy`ing manually may be a better solution. +// +// The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects +// with Rust peers are reclaimed: +// +// 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: +// 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: +// 3. The memory is reclaimed when the process terminates. +// +// [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 +// + + +public interface SchedulerInterface { + + fun `recover`(`signer`: Signer): Credentials + + fun `register`(`signer`: Signer, `code`: kotlin.String?): Credentials + + companion object +} + +open class Scheduler: Disposable, AutoCloseable, SchedulerInterface +{ + + constructor(pointer: Pointer) { + this.pointer = pointer + this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) + } + + /** + * This constructor can be used to instantiate a fake object. Only used for tests. Any + * attempt to actually use an object constructed this way will fail as there is no + * connected Rust object. + */ + @Suppress("UNUSED_PARAMETER") + constructor(noPointer: NoPointer) { + this.pointer = null + this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) + } + /** + * Create a `Scheduler` instance configured with the Greenlight + * production service pre-configured. + */ + constructor(`network`: Network) : + this( + uniffiRustCallWithError(Exception) { _status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_constructor_scheduler_new( + FfiConverterTypeNetwork.lower(`network`),_status) +} + ) + + protected val pointer: Pointer? + protected val cleanable: UniffiCleaner.Cleanable + + private val wasDestroyed = AtomicBoolean(false) + private val callCounter = AtomicLong(1) + + 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) { + cleanable.clean() + } + } + } + + @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.uniffiClonePointer()) + } finally { + // This decrement always matches the increment we performed above. + if (this.callCounter.decrementAndGet() == 0L) { + cleanable.clean() + } + } + } + + // Use a static inner class instead of a closure so as not to accidentally + // capture `this` as part of the cleanable's action. + private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { + override fun run() { + pointer?.let { ptr -> + uniffiRustCall { status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_free_scheduler(ptr, status) + } + } + } + } + + fun uniffiClonePointer(): Pointer { + return uniffiRustCall() { status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_clone_scheduler(pointer!!, status) + } + } + + + @Throws(Exception::class)override fun `recover`(`signer`: Signer): Credentials { + return FfiConverterTypeCredentials.lift( + callWithPointer { + uniffiRustCallWithError(Exception) { _status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_method_scheduler_recover( + it, FfiConverterTypeSigner.lower(`signer`),_status) +} + } + ) + } + + + + @Throws(Exception::class)override fun `register`(`signer`: Signer, `code`: kotlin.String?): Credentials { + return FfiConverterTypeCredentials.lift( + callWithPointer { + uniffiRustCallWithError(Exception) { _status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_method_scheduler_register( + it, FfiConverterTypeSigner.lower(`signer`),FfiConverterOptionalString.lower(`code`),_status) +} + } + ) + } + + + + + + + companion object + +} + +/** + * @suppress + */ +public object FfiConverterTypeScheduler: FfiConverter { + + override fun lower(value: Scheduler): Pointer { + return value.uniffiClonePointer() + } + + override fun lift(value: Pointer): Scheduler { + return Scheduler(value) + } + + override fun read(buf: ByteBuffer): Scheduler { + // 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: Scheduler) = 8UL + + override fun write(value: Scheduler, 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))) + } +} + + +// This template implements a class for working with a Rust struct via a Pointer/Arc +// to the live Rust struct on the other side of the FFI. +// +// Each instance implements core operations for working with the Rust `Arc` and the +// Kotlin Pointer to work with 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 +// theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: +// +// * Each 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 instance 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 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 risks +// leaking 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. +// +// * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` +// is implemented to call the destructor when the Kotlin object becomes unreachable. +// This is done in a background thread. This is not a panacea, and client code should be aware that +// 1. the thread may starve if some there are objects that have poorly performing +// `drop` methods or do significant work in their `drop` methods. +// 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, +// or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). +// +// 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 instance 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. +// +// This makes a cleaner a better alternative to _not_ calling `destroy()` as +// and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` +// method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner +// thread may be starved, and the app will leak memory. +// +// In this case, `destroy`ing manually may be a better solution. +// +// The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects +// with Rust peers are reclaimed: +// +// 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: +// 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: +// 3. The memory is reclaimed when the process terminates. +// +// [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 +// + + +public interface SendResponseInterface { + + companion object +} + +open class SendResponse: Disposable, AutoCloseable, SendResponseInterface +{ + + constructor(pointer: Pointer) { + this.pointer = pointer + this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) + } + + /** + * This constructor can be used to instantiate a fake object. Only used for tests. Any + * attempt to actually use an object constructed this way will fail as there is no + * connected Rust object. + */ + @Suppress("UNUSED_PARAMETER") + constructor(noPointer: NoPointer) { + this.pointer = null + this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) + } + + protected val pointer: Pointer? + protected val cleanable: UniffiCleaner.Cleanable + + private val wasDestroyed = AtomicBoolean(false) + private val callCounter = AtomicLong(1) + + 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) { + cleanable.clean() + } + } + } + + @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.uniffiClonePointer()) + } finally { + // This decrement always matches the increment we performed above. + if (this.callCounter.decrementAndGet() == 0L) { + cleanable.clean() + } + } + } + + // Use a static inner class instead of a closure so as not to accidentally + // capture `this` as part of the cleanable's action. + private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { + override fun run() { + pointer?.let { ptr -> + uniffiRustCall { status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_free_sendresponse(ptr, status) + } + } + } + } + + fun uniffiClonePointer(): Pointer { + return uniffiRustCall() { status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_clone_sendresponse(pointer!!, status) + } + } + + + + + + companion object + +} + +/** + * @suppress + */ +public object FfiConverterTypeSendResponse: FfiConverter { + + override fun lower(value: SendResponse): Pointer { + return value.uniffiClonePointer() + } + + override fun lift(value: Pointer): SendResponse { + return SendResponse(value) + } + + override fun read(buf: ByteBuffer): SendResponse { + // 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: SendResponse) = 8UL + + override fun write(value: SendResponse, 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))) + } +} + + +// This template implements a class for working with a Rust struct via a Pointer/Arc +// to the live Rust struct on the other side of the FFI. +// +// Each instance implements core operations for working with the Rust `Arc` and the +// Kotlin Pointer to work with 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 +// theq Kotlin wrapper object in lieu of reliable finalizers. The core requirements are: +// +// * Each 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 instance 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 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 risks +// leaking 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. +// +// * To mitigate many of the risks of leaking memory and use-after-free unsafety, a `Cleaner` +// is implemented to call the destructor when the Kotlin object becomes unreachable. +// This is done in a background thread. This is not a panacea, and client code should be aware that +// 1. the thread may starve if some there are objects that have poorly performing +// `drop` methods or do significant work in their `drop` methods. +// 2. the thread is shared across the whole library. This can be tuned by using `android_cleaner = true`, +// or `android = true` in the [`kotlin` section of the `uniffi.toml` file](https://mozilla.github.io/uniffi-rs/kotlin/configuration.html). +// +// 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 instance 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. +// +// This makes a cleaner a better alternative to _not_ calling `destroy()` as +// and when the object is finished with, but the abstraction is not perfect: if the Rust object's `drop` +// method is slow, and/or there are many objects to cleanup, and it's on a low end Android device, then the cleaner +// thread may be starved, and the app will leak memory. +// +// In this case, `destroy`ing manually may be a better solution. +// +// The cleaner can live side by side with the manual calling of `destroy`. In the order of responsiveness, uniffi objects +// with Rust peers are reclaimed: +// +// 1. By calling the `destroy` method of the object, which calls `rustObject.free()`. If that doesn't happen: +// 2. When the object becomes unreachable, AND the Cleaner thread gets to call `rustObject.free()`. If the thread is starved then: +// 3. The memory is reclaimed when the process terminates. +// +// [1] https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope/24380219 +// + + +public interface SignerInterface { + + fun `authenticate`(`creds`: Credentials): Signer + + fun `nodeId`(): kotlin.ByteArray + + fun `start`(): Handle + + companion object +} + +open class Signer: Disposable, AutoCloseable, SignerInterface +{ + + constructor(pointer: Pointer) { + this.pointer = pointer + this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) + } + + /** + * This constructor can be used to instantiate a fake object. Only used for tests. Any + * attempt to actually use an object constructed this way will fail as there is no + * connected Rust object. + */ + @Suppress("UNUSED_PARAMETER") + constructor(noPointer: NoPointer) { + this.pointer = null + this.cleanable = UniffiLib.CLEANER.register(this, UniffiCleanAction(pointer)) + } + constructor(`phrase`: kotlin.String) : + this( + uniffiRustCallWithError(Exception) { _status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_constructor_signer_new( + FfiConverterString.lower(`phrase`),_status) +} + ) + + protected val pointer: Pointer? + protected val cleanable: UniffiCleaner.Cleanable + + private val wasDestroyed = AtomicBoolean(false) + private val callCounter = AtomicLong(1) + + 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) { + cleanable.clean() + } + } + } + + @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.uniffiClonePointer()) + } finally { + // This decrement always matches the increment we performed above. + if (this.callCounter.decrementAndGet() == 0L) { + cleanable.clean() + } + } + } + + // Use a static inner class instead of a closure so as not to accidentally + // capture `this` as part of the cleanable's action. + private class UniffiCleanAction(private val pointer: Pointer?) : Runnable { + override fun run() { + pointer?.let { ptr -> + uniffiRustCall { status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_free_signer(ptr, status) + } + } + } + } + + fun uniffiClonePointer(): Pointer { + return uniffiRustCall() { status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_clone_signer(pointer!!, status) + } + } + + + @Throws(Exception::class)override fun `authenticate`(`creds`: Credentials): Signer { + return FfiConverterTypeSigner.lift( + callWithPointer { + uniffiRustCallWithError(Exception) { _status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_method_signer_authenticate( + it, FfiConverterTypeCredentials.lower(`creds`),_status) +} + } + ) + } + + + override fun `nodeId`(): kotlin.ByteArray { + return FfiConverterByteArray.lift( + callWithPointer { + uniffiRustCall() { _status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_method_signer_node_id( + it, _status) +} + } + ) + } + + + + @Throws(Exception::class)override fun `start`(): Handle { + return FfiConverterTypeHandle.lift( + callWithPointer { + uniffiRustCallWithError(Exception) { _status -> + UniffiLib.INSTANCE.uniffi_glsdk_fn_method_signer_start( + it, _status) +} + } + ) + } + + + + + + + companion object + +} + +/** + * @suppress + */ +public object FfiConverterTypeSigner: FfiConverter { + + override fun lower(value: Signer): Pointer { + return value.uniffiClonePointer() + } + + override fun lift(value: Pointer): Signer { + return Signer(value) + } + + override fun read(buf: ByteBuffer): Signer { + // 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: Signer) = 8UL + + override fun write(value: Signer, 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))) + } +} + + + + + +sealed class Exception: kotlin.Exception() { + + class DuplicateNode( + + val `code`: kotlin.Int, + + val `message`: kotlin.String, + + val `values`: Map + ) : Exception() { + override val message + get() = "code=${ `code` }, message=${ `message` }, values=${ `values` }" + } + + class NoSuchNode( + + val `code`: kotlin.Int, + + val `message`: kotlin.String, + + val `values`: Map + ) : Exception() { + override val message + get() = "code=${ `code` }, message=${ `message` }, values=${ `values` }" + } + + class UnparseableCreds( + + val `code`: kotlin.Int, + + val `message`: kotlin.String, + + val `values`: Map + ) : Exception() { + override val message + get() = "code=${ `code` }, message=${ `message` }, values=${ `values` }" + } + + class PhraseCorrupted( + + val `code`: kotlin.Int, + + val `message`: kotlin.String, + + val `values`: Map + ) : Exception() { + override val message + get() = "code=${ `code` }, message=${ `message` }, values=${ `values` }" + } + + class Rpc( + + val `code`: kotlin.Int, + + val `message`: kotlin.String, + + val `values`: Map + ) : Exception() { + override val message + get() = "code=${ `code` }, message=${ `message` }, values=${ `values` }" + } + + class Argument( + + val `code`: kotlin.Int, + + val `message`: kotlin.String, + + val `values`: Map + ) : Exception() { + override val message + get() = "code=${ `code` }, message=${ `message` }, values=${ `values` }" + } + + class Other( + + val `code`: kotlin.Int, + + val `message`: kotlin.String, + + val `values`: Map + ) : Exception() { + override val message + get() = "code=${ `code` }, message=${ `message` }, values=${ `values` }" + } + + + companion object ErrorHandler : UniffiRustCallStatusErrorHandler { + override fun lift(error_buf: RustBuffer.ByValue): Exception = FfiConverterTypeError.lift(error_buf) + } + + +} + +/** + * @suppress + */ +public object FfiConverterTypeError : FfiConverterRustBuffer { + override fun read(buf: ByteBuffer): Exception { + + + return when(buf.getInt()) { + 1 -> Exception.DuplicateNode( + FfiConverterInt.read(buf), + FfiConverterString.read(buf), + FfiConverterMapStringString.read(buf), + ) + 2 -> Exception.NoSuchNode( + FfiConverterInt.read(buf), + FfiConverterString.read(buf), + FfiConverterMapStringString.read(buf), + ) + 3 -> Exception.UnparseableCreds( + FfiConverterInt.read(buf), + FfiConverterString.read(buf), + FfiConverterMapStringString.read(buf), + ) + 4 -> Exception.PhraseCorrupted( + FfiConverterInt.read(buf), + FfiConverterString.read(buf), + FfiConverterMapStringString.read(buf), + ) + 5 -> Exception.Rpc( + FfiConverterInt.read(buf), + FfiConverterString.read(buf), + FfiConverterMapStringString.read(buf), + ) + 6 -> Exception.Argument( + FfiConverterInt.read(buf), + FfiConverterString.read(buf), + FfiConverterMapStringString.read(buf), + ) + 7 -> Exception.Other( + FfiConverterInt.read(buf), + FfiConverterString.read(buf), + FfiConverterMapStringString.read(buf), + ) + else -> throw RuntimeException("invalid error enum value, something is very wrong!!") + } + } + + override fun allocationSize(value: Exception): ULong { + return when(value) { + is Exception.DuplicateNode -> ( + // Add the size for the Int that specifies the variant plus the size needed for all fields + 4UL + + FfiConverterInt.allocationSize(value.`code`) + + FfiConverterString.allocationSize(value.`message`) + + FfiConverterMapStringString.allocationSize(value.`values`) + ) + is Exception.NoSuchNode -> ( + // Add the size for the Int that specifies the variant plus the size needed for all fields + 4UL + + FfiConverterInt.allocationSize(value.`code`) + + FfiConverterString.allocationSize(value.`message`) + + FfiConverterMapStringString.allocationSize(value.`values`) + ) + is Exception.UnparseableCreds -> ( + // Add the size for the Int that specifies the variant plus the size needed for all fields + 4UL + + FfiConverterInt.allocationSize(value.`code`) + + FfiConverterString.allocationSize(value.`message`) + + FfiConverterMapStringString.allocationSize(value.`values`) + ) + is Exception.PhraseCorrupted -> ( + // Add the size for the Int that specifies the variant plus the size needed for all fields + 4UL + + FfiConverterInt.allocationSize(value.`code`) + + FfiConverterString.allocationSize(value.`message`) + + FfiConverterMapStringString.allocationSize(value.`values`) + ) + is Exception.Rpc -> ( + // Add the size for the Int that specifies the variant plus the size needed for all fields + 4UL + + FfiConverterInt.allocationSize(value.`code`) + + FfiConverterString.allocationSize(value.`message`) + + FfiConverterMapStringString.allocationSize(value.`values`) + ) + is Exception.Argument -> ( + // Add the size for the Int that specifies the variant plus the size needed for all fields + 4UL + + FfiConverterInt.allocationSize(value.`code`) + + FfiConverterString.allocationSize(value.`message`) + + FfiConverterMapStringString.allocationSize(value.`values`) + ) + is Exception.Other -> ( + // Add the size for the Int that specifies the variant plus the size needed for all fields + 4UL + + FfiConverterInt.allocationSize(value.`code`) + + FfiConverterString.allocationSize(value.`message`) + + FfiConverterMapStringString.allocationSize(value.`values`) + ) + } + } + + override fun write(value: Exception, buf: ByteBuffer) { + when(value) { + is Exception.DuplicateNode -> { + buf.putInt(1) + FfiConverterInt.write(value.`code`, buf) + FfiConverterString.write(value.`message`, buf) + FfiConverterMapStringString.write(value.`values`, buf) + Unit + } + is Exception.NoSuchNode -> { + buf.putInt(2) + FfiConverterInt.write(value.`code`, buf) + FfiConverterString.write(value.`message`, buf) + FfiConverterMapStringString.write(value.`values`, buf) + Unit + } + is Exception.UnparseableCreds -> { + buf.putInt(3) + FfiConverterInt.write(value.`code`, buf) + FfiConverterString.write(value.`message`, buf) + FfiConverterMapStringString.write(value.`values`, buf) + Unit + } + is Exception.PhraseCorrupted -> { + buf.putInt(4) + FfiConverterInt.write(value.`code`, buf) + FfiConverterString.write(value.`message`, buf) + FfiConverterMapStringString.write(value.`values`, buf) + Unit + } + is Exception.Rpc -> { + buf.putInt(5) + FfiConverterInt.write(value.`code`, buf) + FfiConverterString.write(value.`message`, buf) + FfiConverterMapStringString.write(value.`values`, buf) + Unit + } + is Exception.Argument -> { + buf.putInt(6) + FfiConverterInt.write(value.`code`, buf) + FfiConverterString.write(value.`message`, buf) + FfiConverterMapStringString.write(value.`values`, buf) + Unit + } + is Exception.Other -> { + buf.putInt(7) + FfiConverterInt.write(value.`code`, buf) + FfiConverterString.write(value.`message`, buf) + FfiConverterMapStringString.write(value.`values`, buf) + Unit + } + }.let { /* this makes the `when` an expression, which ensures it is exhaustive */ } + } + +} + + + + +enum class Network { + + BITCOIN, + REGTEST; + companion object +} + + +/** + * @suppress + */ +public object FfiConverterTypeNetwork: FfiConverterRustBuffer { + override fun read(buf: ByteBuffer) = try { + Network.values()[buf.getInt() - 1] + } catch (e: IndexOutOfBoundsException) { + throw RuntimeException("invalid enum value, something is very wrong!!", e) + } + + override fun allocationSize(value: Network) = 4UL + + override fun write(value: Network, buf: ByteBuffer) { + buf.putInt(value.ordinal + 1) + } +} + + + + + + +enum class PayStatus { + + COMPLETE, + PENDING, + FAILED; + companion object +} + + +/** + * @suppress + */ +public object FfiConverterTypePayStatus: FfiConverterRustBuffer { + override fun read(buf: ByteBuffer) = try { + PayStatus.values()[buf.getInt() - 1] + } catch (e: IndexOutOfBoundsException) { + throw RuntimeException("invalid enum value, something is very wrong!!", e) + } + + override fun allocationSize(value: PayStatus) = 4UL + + override fun write(value: PayStatus, buf: ByteBuffer) { + buf.putInt(value.ordinal + 1) + } +} + + + + + + +/** + * @suppress + */ +public object FfiConverterOptionalULong: FfiConverterRustBuffer { + override fun read(buf: ByteBuffer): kotlin.ULong? { + if (buf.get().toInt() == 0) { + return null + } + return FfiConverterULong.read(buf) + } + + override fun allocationSize(value: kotlin.ULong?): ULong { + if (value == null) { + return 1UL + } else { + return 1UL + FfiConverterULong.allocationSize(value) + } + } + + override fun write(value: kotlin.ULong?, buf: ByteBuffer) { + if (value == null) { + buf.put(0) + } else { + buf.put(1) + FfiConverterULong.write(value, buf) + } + } +} + + + + +/** + * @suppress + */ +public object FfiConverterOptionalString: FfiConverterRustBuffer { + override fun read(buf: ByteBuffer): kotlin.String? { + if (buf.get().toInt() == 0) { + return null + } + return FfiConverterString.read(buf) + } + + override fun allocationSize(value: kotlin.String?): ULong { + if (value == null) { + return 1UL + } else { + return 1UL + FfiConverterString.allocationSize(value) + } + } + + override fun write(value: kotlin.String?, buf: ByteBuffer) { + if (value == null) { + buf.put(0) + } else { + buf.put(1) + FfiConverterString.write(value, buf) + } + } +} + + + + +/** + * @suppress + */ +public object FfiConverterMapStringString: FfiConverterRustBuffer> { + override fun read(buf: ByteBuffer): Map { + val len = buf.getInt() + return buildMap(len) { + repeat(len) { + val k = FfiConverterString.read(buf) + val v = FfiConverterString.read(buf) + this[k] = v + } + } + } + + override fun allocationSize(value: Map): ULong { + val spaceForMapSize = 4UL + val spaceForChildren = value.map { (k, v) -> + FfiConverterString.allocationSize(k) + + FfiConverterString.allocationSize(v) + }.sum() + return spaceForMapSize + spaceForChildren + } + + override fun write(value: Map, buf: ByteBuffer) { + buf.putInt(value.size) + // The parens on `(k, v)` here ensure we're calling the right method, + // which is important for compatibility with older android devices. + // Ref https://blog.danlew.net/2017/03/16/kotlin-puzzler-whose-line-is-it-anyways/ + value.forEach { (k, v) -> + FfiConverterString.write(k, buf) + FfiConverterString.write(v, buf) + } + } +} +