| 1 | import 'dart:ffi'; |
| 2 | import 'dart:io'; |
| 3 | import 'dart:typed_data'; |
| 4 | |
| 5 | import 'package:cw_mweb/generated_bindings.g.dart'; |
| 6 | import 'package:cw_mweb/print_verbose.dart'; |
| 7 | import 'package:ffi/ffi.dart'; |
| 8 | |
| 9 | String libPath = (() { |
| 10 | if (Platform.isWindows) return 'mweb.dll'; |
| 11 | if (Platform.isMacOS) return 'mweb.dylib'; |
| 12 | if (Platform.isIOS) return 'Mwebd.framework/Mwebd'; |
| 13 | if (Platform.isAndroid) return 'libmweb.so'; |
| 14 | return 'libmweb.so'; |
| 15 | })(); |
| 16 | |
| 17 | class MWebFfi { |
| 18 | late final MWebFlutter lib; |
| 19 | |
| 20 | MWebFfi() : lib = MWebFlutter(DynamicLibrary.open(libPath)); |
| 21 | |
| 22 | static MWebFfi instance = MWebFfi(); |
| 23 | |
| 24 | int start(String dataDir, String nodeUri) { |
| 25 | final chain = "".toNativeUtf8().cast<Char>(); |
| 26 | final dataDir_ = dataDir.toNativeUtf8().cast<Char>(); |
| 27 | final nodeUri_ = nodeUri.toNativeUtf8().cast<Char>(); |
| 28 | final errMsgPtr = calloc<Pointer<Char>>(); |
| 29 | |
| 30 | final port = lib.StartServer(chain, dataDir_, nodeUri_, errMsgPtr); |
| 31 | if (port == 0) { |
| 32 | final errMsg = errMsgPtr.value.cast<Utf8>().toDartString(); |
| 33 | printV('Error starting server: $errMsg'); |
| 34 | calloc.free(errMsgPtr.value); |
| 35 | } |
| 36 | |
| 37 | calloc.free(chain); |
| 38 | calloc.free(dataDir_); |
| 39 | calloc.free(nodeUri_); |
| 40 | calloc.free(errMsgPtr); |
| 41 | |
| 42 | return port; |
| 43 | } |
| 44 | |
| 45 | void stop() => lib.StopServer(); |
| 46 | |
| 47 | String addresses(Uint8List scanSecret, Uint8List spendPub, int fromIndex, int toIndex) { |
| 48 | final scanSecretPtr = malloc.allocate<Uint8>(scanSecret.length); |
| 49 | for (int k = 0; k < scanSecret.length; k++) { |
| 50 | scanSecretPtr[k] = scanSecret[k]; |
| 51 | } |
| 52 | |
| 53 | final spendPubKeyPtr = malloc.allocate<Uint8>(spendPub.length); |
| 54 | for (int k = 0; k < spendPub.length; k++) { |
| 55 | spendPubKeyPtr[k] = spendPub[k]; |
| 56 | } |
| 57 | |
| 58 | final Pointer<Char> resultPtr = lib.Addresses( |
| 59 | scanSecretPtr.cast(), |
| 60 | scanSecret.length, |
| 61 | spendPubKeyPtr.cast(), |
| 62 | spendPub.length, |
| 63 | fromIndex, |
| 64 | toIndex, |
| 65 | ); |
| 66 | |
| 67 | final result = resultPtr.cast<Utf8>().toDartString(); |
| 68 | |
| 69 | malloc.free(scanSecretPtr); |
| 70 | malloc.free(spendPubKeyPtr); |
| 71 | malloc.free(resultPtr); |
| 72 | |
| 73 | return result; |
| 74 | } |
| 75 | } |