This commit is contained in:
John Smith 2023-05-15 11:33:32 -04:00
parent 5f9fec0b18
commit cbdbd34af8
11 changed files with 436 additions and 203 deletions

View File

@ -1,4 +1,5 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
@ -97,11 +98,11 @@ class _MyAppState extends State<MyApp> with UiLoggy {
if (update is VeilidLog) { if (update is VeilidLog) {
await processLog(update); await processLog(update);
} else if (update is VeilidAppMessage) { } else if (update is VeilidAppMessage) {
loggy.info("AppMessage: ${update.json}"); loggy.info("AppMessage: ${jsonEncode(update)}");
} else if (update is VeilidAppCall) { } else if (update is VeilidAppCall) {
loggy.info("AppCall: ${update.json}"); loggy.info("AppCall: ${jsonEncode(update)}");
} else { } else {
loggy.trace("Update: ${update.json}"); loggy.trace("Update: ${jsonEncode(update)}");
} }
} }
} }

View File

@ -14,7 +14,7 @@ void veilidInit() {
logsInConsole: false), logsInConsole: false),
api: VeilidWASMConfigLoggingApi( api: VeilidWASMConfigLoggingApi(
enabled: true, level: VeilidConfigLogLevel.info))); enabled: true, level: VeilidConfigLogLevel.info)));
Veilid.instance.initializeVeilidCore(platformConfig.json); Veilid.instance.initializeVeilidCore(platformConfig.toJson());
} else { } else {
var platformConfig = VeilidFFIConfig( var platformConfig = VeilidFFIConfig(
logging: VeilidFFIConfigLogging( logging: VeilidFFIConfigLogging(
@ -29,6 +29,6 @@ void veilidInit() {
serviceName: "VeilidExample"), serviceName: "VeilidExample"),
api: VeilidFFIConfigLoggingApi( api: VeilidFFIConfigLoggingApi(
enabled: true, level: VeilidConfigLogLevel.info))); enabled: true, level: VeilidConfigLogLevel.info)));
Veilid.instance.initializeVeilidCore(platformConfig.json); Veilid.instance.initializeVeilidCore(platformConfig.toJson());
} }
} }

View File

@ -33,7 +33,7 @@ abstract class DHTSchema {
} }
} }
} }
Map<String, dynamic> get json; Map<String, dynamic> toJson();
} }
class DHTSchemaDFLT implements DHTSchema { class DHTSchemaDFLT implements DHTSchema {
@ -49,7 +49,7 @@ class DHTSchemaDFLT implements DHTSchema {
} }
@override @override
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'kind': "DFLT", 'kind': "DFLT",
'o_cnt': oCnt, 'o_cnt': oCnt,
@ -71,7 +71,7 @@ class DHTSchemaMember {
} }
} }
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'm_key': mKey, 'm_key': mKey,
'm_cnt': mCnt, 'm_cnt': mCnt,
@ -97,11 +97,11 @@ class DHTSchemaSMPL implements DHTSchema {
} }
} }
@override @override
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'kind': "SMPL", 'kind': "SMPL",
'o_cnt': oCnt, 'o_cnt': oCnt,
'members': members.map((p) => p.json).toList(), 'members': members.map((p) => p.toJson()).toList(),
}; };
} }
} }
@ -122,12 +122,12 @@ class DHTRecordDescriptor {
required this.schema, required this.schema,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'key': key.toString(), 'key': key.toString(),
'owner': owner, 'owner': owner,
'owner_secret': ownerSecret, 'owner_secret': ownerSecret,
'schema': schema.json, 'schema': schema.toJson(),
}; };
} }
@ -168,7 +168,7 @@ class ValueSubkeyRange {
} }
} }
List<dynamic> get json { List<dynamic> toJson() {
return [low, high]; return [low, high];
} }
} }
@ -192,7 +192,7 @@ class ValueData {
data = base64UrlNoPadDecode(json['data']), data = base64UrlNoPadDecode(json['data']),
writer = json['writer']; writer = json['writer'];
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return {'seq': seq, 'data': base64UrlNoPadEncode(data), 'writer': writer}; return {'seq': seq, 'data': base64UrlNoPadEncode(data), 'writer': writer};
} }
} }
@ -205,7 +205,7 @@ enum Stability {
} }
extension StabilityExt on Stability { extension StabilityExt on Stability {
String get json { String toJson() {
return name.toPascalCase(); return name.toPascalCase();
} }
} }
@ -224,7 +224,7 @@ enum Sequencing {
} }
extension SequencingExt on Sequencing { extension SequencingExt on Sequencing {
String get json { String toJson() {
return name.toPascalCase(); return name.toPascalCase();
} }
} }
@ -245,7 +245,7 @@ class RouteBlob {
: routeId = json['route_id'], : routeId = json['route_id'],
blob = base64UrlNoPadDecode(json['blob']); blob = base64UrlNoPadDecode(json['blob']);
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return {'route_id': routeId, 'blob': base64UrlNoPadEncode(blob)}; return {'route_id': routeId, 'blob': base64UrlNoPadEncode(blob)};
} }
} }

View File

@ -36,16 +36,29 @@ Object? veilidApiToEncodable(Object? value) {
return value; return value;
} }
switch (value.runtimeType) { switch (value.runtimeType) {
case AttachmentState: // case KeyPair:
return (value as AttachmentState).json; // return (value as KeyPair).json;
case VeilidLogLevel:
return (value as VeilidLogLevel).json;
case VeilidConfigLogLevel:
return (value as VeilidConfigLogLevel).json;
} }
throw UnsupportedError('Cannot convert to JSON: $value'); throw UnsupportedError('Cannot convert to JSON: $value');
} }
T? Function(dynamic) optFromJson<T>(T Function(dynamic) jsonConstructor) {
return (dynamic j) {
if (j == null) {
return null;
} else {
return jsonConstructor(j);
}
};
}
List<T> Function(dynamic) jsonListConstructor<T>(
T Function(dynamic) jsonConstructor) {
return (dynamic j) {
return (j as List<dynamic>).map((e) => jsonConstructor(e)).toList();
};
}
////////////////////////////////////// //////////////////////////////////////
/// VeilidVersion /// VeilidVersion
@ -71,8 +84,7 @@ class Timestamp {
Timestamp.fromString(String s) : value = BigInt.parse(s); Timestamp.fromString(String s) : value = BigInt.parse(s);
Timestamp.fromJson(dynamic json) : this.fromString(json as String); Timestamp.fromJson(dynamic json) : this.fromString(json as String);
String toJson() {
String get json {
return toString(); return toString();
} }
@ -97,8 +109,7 @@ class TimestampDuration {
TimestampDuration.fromString(String s) : value = BigInt.parse(s); TimestampDuration.fromString(String s) : value = BigInt.parse(s);
TimestampDuration.fromJson(dynamic json) : this.fromString(json as String); TimestampDuration.fromJson(dynamic json) : this.fromString(json as String);
String toJson() {
String get json {
return toString(); return toString();
} }

View File

@ -20,7 +20,7 @@ enum VeilidConfigLogLevel {
} }
extension VeilidConfigLogLevelExt on VeilidConfigLogLevel { extension VeilidConfigLogLevelExt on VeilidConfigLogLevel {
String get json { String toJson() {
return name.toPascalCase(); return name.toPascalCase();
} }
} }
@ -45,7 +45,7 @@ class VeilidConfigHTTPS {
this.url, this.url,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'enabled': enabled, 'enabled': enabled,
'listen_address': listenAddress, 'listen_address': listenAddress,
@ -76,7 +76,7 @@ class VeilidConfigHTTP {
this.url, this.url,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'enabled': enabled, 'enabled': enabled,
'listen_address': listenAddress, 'listen_address': listenAddress,
@ -103,10 +103,10 @@ class VeilidConfigApplication {
required this.http, required this.http,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'https': https.json, 'https': https.toJson(),
'http': http.json, 'http': http.toJson(),
}; };
} }
@ -129,7 +129,7 @@ class VeilidConfigUDP {
required this.listenAddress, required this.listenAddress,
this.publicAddress}); this.publicAddress});
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'enabled': enabled, 'enabled': enabled,
'socket_pool_size': socketPoolSize, 'socket_pool_size': socketPoolSize,
@ -161,7 +161,7 @@ class VeilidConfigTCP {
required this.listenAddress, required this.listenAddress,
this.publicAddress}); this.publicAddress});
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'connect': connect, 'connect': connect,
'listen': listen, 'listen': listen,
@ -197,7 +197,7 @@ class VeilidConfigWS {
required this.path, required this.path,
this.url}); this.url});
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'connect': connect, 'connect': connect,
'listen': listen, 'listen': listen,
@ -235,7 +235,7 @@ class VeilidConfigWSS {
required this.path, required this.path,
this.url}); this.url});
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'connect': connect, 'connect': connect,
'listen': listen, 'listen': listen,
@ -270,12 +270,12 @@ class VeilidConfigProtocol {
required this.wss, required this.wss,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'udp': udp.json, 'udp': udp.toJson(),
'tcp': tcp.json, 'tcp': tcp.toJson(),
'ws': ws.json, 'ws': ws.toJson(),
'wss': wss.json, 'wss': wss.toJson(),
}; };
} }
@ -299,7 +299,7 @@ class VeilidConfigTLS {
required this.connectionInitialTimeoutMs, required this.connectionInitialTimeoutMs,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'certificate_path': certificatePath, 'certificate_path': certificatePath,
'private_key_path': privateKeyPath, 'private_key_path': privateKeyPath,
@ -357,7 +357,7 @@ class VeilidConfigDHT {
required this.remoteMaxSubkeyCacheMemoryMb, required this.remoteMaxSubkeyCacheMemoryMb,
required this.remoteMaxStorageSpaceMb}); required this.remoteMaxStorageSpaceMb});
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'max_find_node_count': maxFindNodeCount, 'max_find_node_count': maxFindNodeCount,
'resolve_node_timeout_ms': resolveNodeTimeoutMs, 'resolve_node_timeout_ms': resolveNodeTimeoutMs,
@ -425,7 +425,7 @@ class VeilidConfigRPC {
required this.maxRouteHopCount, required this.maxRouteHopCount,
required this.defaultRouteHopCount}); required this.defaultRouteHopCount});
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'concurrency': concurrency, 'concurrency': concurrency,
'queue_size': queueSize, 'queue_size': queueSize,
@ -470,10 +470,10 @@ class VeilidConfigRoutingTable {
required this.limitAttachedWeak, required this.limitAttachedWeak,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'node_id': nodeId.map((p) => p.json).toList(), 'node_id': nodeId.map((p) => p.toJson()).toList(),
'node_id_secret': nodeIdSecret.map((p) => p.json).toList(), 'node_id_secret': nodeIdSecret.map((p) => p.toJson()).toList(),
'bootstrap': bootstrap.map((p) => p).toList(), 'bootstrap': bootstrap.map((p) => p).toList(),
'limit_over_attached': limitOverAttached, 'limit_over_attached': limitOverAttached,
'limit_fully_attached': limitFullyAttached, 'limit_fully_attached': limitFullyAttached,
@ -539,7 +539,7 @@ class VeilidConfigNetwork {
required this.protocol, required this.protocol,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'connection_initial_timeout_ms': connectionInitialTimeoutMs, 'connection_initial_timeout_ms': connectionInitialTimeoutMs,
'connection_inactivity_timeout_ms': connectionInactivityTimeoutMs, 'connection_inactivity_timeout_ms': connectionInactivityTimeoutMs,
@ -550,15 +550,15 @@ class VeilidConfigNetwork {
'client_whitelist_timeout_ms': clientWhitelistTimeoutMs, 'client_whitelist_timeout_ms': clientWhitelistTimeoutMs,
'reverse_connection_receipt_time_ms': reverseConnectionReceiptTimeMs, 'reverse_connection_receipt_time_ms': reverseConnectionReceiptTimeMs,
'hole_punch_receipt_time_ms': holePunchReceiptTimeMs, 'hole_punch_receipt_time_ms': holePunchReceiptTimeMs,
'routing_table': routingTable.json, 'routing_table': routingTable.toJson(),
'rpc': rpc.json, 'rpc': rpc.toJson(),
'dht': dht.json, 'dht': dht.toJson(),
'upnp': upnp, 'upnp': upnp,
'detect_address_changes': detectAddressChanges, 'detect_address_changes': detectAddressChanges,
'restricted_nat_retries': restrictedNatRetries, 'restricted_nat_retries': restrictedNatRetries,
'tls': tls.json, 'tls': tls.toJson(),
'application': application.json, 'application': application.toJson(),
'protocol': protocol.json, 'protocol': protocol.toJson(),
}; };
} }
@ -597,7 +597,7 @@ class VeilidConfigTableStore {
required this.delete, required this.delete,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return {'directory': directory, 'delete': delete}; return {'directory': directory, 'delete': delete};
} }
@ -617,7 +617,7 @@ class VeilidConfigBlockStore {
required this.delete, required this.delete,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return {'directory': directory, 'delete': delete}; return {'directory': directory, 'delete': delete};
} }
@ -641,7 +641,7 @@ class VeilidConfigProtectedStore {
required this.delete, required this.delete,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'allow_insecure_fallback': allowInsecureFallback, 'allow_insecure_fallback': allowInsecureFallback,
'always_use_insecure_storage': alwaysUseInsecureStorage, 'always_use_insecure_storage': alwaysUseInsecureStorage,
@ -678,7 +678,7 @@ class VeilidConfigCapabilities {
required this.protocolAcceptWSS, required this.protocolAcceptWSS,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'protocol_udp': protocolUDP, 'protocol_udp': protocolUDP,
'protocol_connect_tcp': protocolConnectTCP, 'protocol_connect_tcp': protocolConnectTCP,
@ -721,15 +721,15 @@ class VeilidConfig {
required this.network, required this.network,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'program_name': programName, 'program_name': programName,
'namespace': namespace, 'namespace': namespace,
'capabilities': capabilities.json, 'capabilities': capabilities.toJson(),
'protected_store': protectedStore.json, 'protected_store': protectedStore.toJson(),
'table_store': tableStore.json, 'table_store': tableStore.toJson(),
'block_store': blockStore.json, 'block_store': blockStore.toJson(),
'network': network.json 'network': network.toJson()
}; };
} }

View File

@ -55,7 +55,7 @@ class Typed<V extends EncodedString> {
value = EncodedString.fromString<V>(parts.sublist(1).join(":")); value = EncodedString.fromString<V>(parts.sublist(1).join(":"));
} }
String get json { String toJson() {
return toString(); return toString();
} }
@ -83,7 +83,7 @@ class KeyPair {
secret = PublicKey(parts[1]); secret = PublicKey(parts[1]);
} }
String get json { String toJson() {
return toString(); return toString();
} }
@ -114,7 +114,7 @@ class TypedKeyPair {
secret = PublicKey(parts[2]); secret = PublicKey(parts[2]);
} }
String get json { String toJson() {
return toString(); return toString();
} }

View File

@ -70,7 +70,7 @@ class FixedEncodedString32 extends EncodedString {
return 24; return 24;
} }
String get json { String toJson() {
return toString(); return toString();
} }
@ -89,7 +89,7 @@ class FixedEncodedString43 extends EncodedString {
return 32; return 32;
} }
String get json { String toJson() {
return toString(); return toString();
} }
@ -108,7 +108,7 @@ class FixedEncodedString86 extends EncodedString {
return 64; return 64;
} }
String get json { String toJson() {
return toString(); return toString();
} }

View File

@ -22,10 +22,10 @@ class VeilidFFIConfigLoggingTerminal {
required this.level, required this.level,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'enabled': enabled, 'enabled': enabled,
'level': level.json, 'level': level.toJson(),
}; };
} }
@ -47,10 +47,10 @@ class VeilidFFIConfigLoggingOtlp {
required this.serviceName, required this.serviceName,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'enabled': enabled, 'enabled': enabled,
'level': level.json, 'level': level.toJson(),
'grpc_endpoint': grpcEndpoint, 'grpc_endpoint': grpcEndpoint,
'service_name': serviceName, 'service_name': serviceName,
}; };
@ -72,10 +72,10 @@ class VeilidFFIConfigLoggingApi {
required this.level, required this.level,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'enabled': enabled, 'enabled': enabled,
'level': level.json, 'level': level.toJson(),
}; };
} }
@ -92,11 +92,11 @@ class VeilidFFIConfigLogging {
VeilidFFIConfigLogging( VeilidFFIConfigLogging(
{required this.terminal, required this.otlp, required this.api}); {required this.terminal, required this.otlp, required this.api});
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'terminal': terminal.json, 'terminal': terminal.toJson(),
'otlp': otlp.json, 'otlp': otlp.toJson(),
'api': api.json, 'api': api.toJson(),
}; };
} }
@ -113,9 +113,9 @@ class VeilidFFIConfig {
required this.logging, required this.logging,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'logging': logging.json, 'logging': logging.toJson(),
}; };
} }
@ -221,9 +221,9 @@ typedef _RoutingContextSetDHTValueDart = void Function(
int, int, Pointer<Utf8>, int, Pointer<Utf8>); int, int, Pointer<Utf8>, int, Pointer<Utf8>);
// fn routing_context_watch_dht_values(port: i64, id: u32, key: FfiStr, subkeys: FfiStr, expiration: FfiStr, count: u32) // fn routing_context_watch_dht_values(port: i64, id: u32, key: FfiStr, subkeys: FfiStr, expiration: FfiStr, count: u32)
typedef _RoutingContextWatchDHTValuesC = Void Function( typedef _RoutingContextWatchDHTValuesC = Void Function(
Int64, Uint32, Pointer<Utf8>, Pointer<Utf8>, Pointer<Utf8>, Uint32); Int64, Uint32, Pointer<Utf8>, Pointer<Utf8>, Uint64, Uint32);
typedef _RoutingContextWatchDHTValuesDart = void Function( typedef _RoutingContextWatchDHTValuesDart = void Function(
int, int, Pointer<Utf8>, Pointer<Utf8>, Pointer<Utf8>, int); int, int, Pointer<Utf8>, Pointer<Utf8>, int, int);
// fn routing_context_cancel_dht_watch(port: i64, id: u32, key: FfiStr, subkeys: FfiStr) // fn routing_context_cancel_dht_watch(port: i64, id: u32, key: FfiStr, subkeys: FfiStr)
typedef _RoutingContextCancelDHTWatchC = Void Function( typedef _RoutingContextCancelDHTWatchC = Void Function(
Int64, Uint32, Pointer<Utf8>, Pointer<Utf8>); Int64, Uint32, Pointer<Utf8>, Pointer<Utf8>);
@ -652,14 +652,14 @@ class VeilidRoutingContextFFI implements VeilidRoutingContext {
@override @override
VeilidRoutingContextFFI withCustomPrivacy(Stability stability) { VeilidRoutingContextFFI withCustomPrivacy(Stability stability) {
final newId = _ctx.ffi._routingContextWithCustomPrivacy( final newId = _ctx.ffi._routingContextWithCustomPrivacy(
_ctx.id, stability.json.toNativeUtf8()); _ctx.id, jsonEncode(stability).toNativeUtf8());
return VeilidRoutingContextFFI._(_Ctx(newId, _ctx.ffi)); return VeilidRoutingContextFFI._(_Ctx(newId, _ctx.ffi));
} }
@override @override
VeilidRoutingContextFFI withSequencing(Sequencing sequencing) { VeilidRoutingContextFFI withSequencing(Sequencing sequencing) {
final newId = _ctx.ffi final newId = _ctx.ffi._routingContextWithSequencing(
._routingContextWithSequencing(_ctx.id, sequencing.json.toNativeUtf8()); _ctx.id, jsonEncode(sequencing).toNativeUtf8());
return VeilidRoutingContextFFI._(_Ctx(newId, _ctx.ffi)); return VeilidRoutingContextFFI._(_Ctx(newId, _ctx.ffi));
} }
@ -677,7 +677,7 @@ class VeilidRoutingContextFFI implements VeilidRoutingContext {
} }
@override @override
Future<void> appMessage(String target, Uint8List message) async { Future<void> appMessage(String target, Uint8List message) {
final nativeEncodedTarget = target.toNativeUtf8(); final nativeEncodedTarget = target.toNativeUtf8();
final nativeEncodedMessage = base64UrlNoPadEncode(message).toNativeUtf8(); final nativeEncodedMessage = base64UrlNoPadEncode(message).toNativeUtf8();
@ -687,6 +687,111 @@ class VeilidRoutingContextFFI implements VeilidRoutingContext {
nativeEncodedTarget, nativeEncodedMessage); nativeEncodedTarget, nativeEncodedMessage);
return processFutureVoid(recvPort.first); return processFutureVoid(recvPort.first);
} }
@override
Future<DHTRecordDescriptor> createDHTRecord(
CryptoKind kind, DHTSchema schema) async {
final nativeSchema = jsonEncode(schema).toNativeUtf8();
final recvPort = ReceivePort("routing_context_create_dht_record");
final sendPort = recvPort.sendPort;
_ctx.ffi._routingContextCreateDHTRecord(
sendPort.nativePort, _ctx.id, kind, nativeSchema);
final dhtRecordDescriptor =
await processFutureJson(DHTRecordDescriptor.fromJson, recvPort.first);
return dhtRecordDescriptor;
}
@override
Future<DHTRecordDescriptor> openDHTRecord(
TypedKey key, KeyPair? writer) async {
final nativeKey = jsonEncode(key).toNativeUtf8();
final nativeWriter =
writer != null ? jsonEncode(key).toNativeUtf8() : nullptr;
final recvPort = ReceivePort("routing_context_open_dht_record");
final sendPort = recvPort.sendPort;
_ctx.ffi._routingContextOpenDHTRecord(
sendPort.nativePort, _ctx.id, nativeKey, nativeWriter);
final dhtRecordDescriptor =
await processFutureJson(DHTRecordDescriptor.fromJson, recvPort.first);
return dhtRecordDescriptor;
}
@override
Future<void> closeDHTRecord(TypedKey key) {
final nativeKey = jsonEncode(key).toNativeUtf8();
final recvPort = ReceivePort("routing_context_close_dht_record");
final sendPort = recvPort.sendPort;
_ctx.ffi
._routingContextCloseDHTRecord(sendPort.nativePort, _ctx.id, nativeKey);
return processFutureVoid(recvPort.first);
}
@override
Future<void> deleteDHTRecord(TypedKey key) {
final nativeKey = jsonEncode(key).toNativeUtf8();
final recvPort = ReceivePort("routing_context_delete_dht_record");
final sendPort = recvPort.sendPort;
_ctx.ffi._routingContextDeleteDHTRecord(
sendPort.nativePort, _ctx.id, nativeKey);
return processFutureVoid(recvPort.first);
}
@override
Future<ValueData?> getDHTValue(
TypedKey key, int subkey, bool forceRefresh) async {
final nativeKey = jsonEncode(key).toNativeUtf8();
final recvPort = ReceivePort("routing_context_get_dht_value");
final sendPort = recvPort.sendPort;
_ctx.ffi._routingContextGetDHTValue(
sendPort.nativePort, _ctx.id, nativeKey, subkey, forceRefresh);
final valueData = await processFutureJson(
optFromJson(ValueData.fromJson), recvPort.first);
return valueData;
}
@override
Future<ValueData?> setDHTValue(
TypedKey key, int subkey, Uint8List data) async {
final nativeKey = jsonEncode(key).toNativeUtf8();
final nativeData = base64UrlNoPadEncode(data).toNativeUtf8();
final recvPort = ReceivePort("routing_context_set_dht_value");
final sendPort = recvPort.sendPort;
_ctx.ffi._routingContextSetDHTValue(
sendPort.nativePort, _ctx.id, nativeKey, subkey, nativeData);
final valueData = await processFutureJson(
optFromJson(ValueData.fromJson), recvPort.first);
return valueData;
}
@override
Future<Timestamp> watchDHTValues(TypedKey key, ValueSubkeyRange subkeys,
Timestamp expiration, int count) async {
final nativeKey = jsonEncode(key).toNativeUtf8();
final nativeSubkeys = jsonEncode(subkeys).toNativeUtf8();
final nativeExpiration = expiration.value.toInt();
final recvPort = ReceivePort("routing_context_watch_dht_values");
final sendPort = recvPort.sendPort;
_ctx.ffi._routingContextWatchDHTValues(sendPort.nativePort, _ctx.id,
nativeKey, nativeSubkeys, nativeExpiration, count);
final actualExpiration = Timestamp(
value: BigInt.from(await processFuturePlain<int>(recvPort.first)));
return actualExpiration;
}
@override
Future<bool> cancelDHTWatch(TypedKey key, ValueSubkeyRange subkeys) async {
final nativeKey = jsonEncode(key).toNativeUtf8();
final nativeSubkeys = jsonEncode(subkeys).toNativeUtf8();
final recvPort = ReceivePort("routing_context_cancel_dht_watch");
final sendPort = recvPort.sendPort;
_ctx.ffi._routingContextCancelDHTWatch(
sendPort.nativePort, _ctx.id, nativeKey, nativeSubkeys);
final cancelled = await processFuturePlain<bool>(recvPort.first);
return cancelled;
}
} }
class _TDBT { class _TDBT {
@ -853,6 +958,56 @@ class VeilidTableDBFFI extends VeilidTableDB {
} }
} }
// FFI implementation of VeilidCryptoSystem
class VeilidCryptoSystemFFI implements VeilidCryptoSystem {
final CryptoKind _kind;
VeilidCryptoSystemFFI._(this._kind);
@override
CryptoKind kind() {
return _kind;
}
@override
Future<SharedSecret> cachedDH(PublicKey key, SecretKey secret) {}
@override
Future<SharedSecret> computeDH(PublicKey key, SecretKey secret) {}
@override
Future<Nonce> randomNonce() {}
@override
Future<SharedSecret> randomSharedSecret() {}
@override
Future<KeyPair> generateKeyPair() {}
@override
Future<HashDigest> generateHash(Uint8List data) {}
@override
Future<HashDigest> generateHashReader(Stream<List<int>> reader) {}
@override
Future<bool> validateKeyPair(PublicKey key, SecretKey secret) {}
@override
Future<bool> validateHash(Uint8List data, HashDigest hash) {}
@override
Future<bool> validateHashReader(Stream<List<int>> reader, HashDigest hash) {}
@override
Future<CryptoKeyDistance> distance(CryptoKey key1, CryptoKey key2) {}
@override
Future<Signature> sign(PublicKey key, SecretKey secret, Uint8List data) {}
@override
Future<void> verify(PublicKey key, Uint8List data, Signature signature) {}
@override
Future<int> aeadOverhead() {}
@override
Future<Uint8List> decryptAead(Uint8List body, Nonce nonce,
SharedSecret sharedSecret, Uint8List? associatedData) {}
@override
Future<Uint8List> encryptAead(Uint8List body, Nonce nonce,
SharedSecret sharedSecret, Uint8List? associatedData) {}
@override
Future<Uint8List> cryptNoAuth(
Uint8List body, Nonce nonce, SharedSecret sharedSecret) {}
}
// FFI implementation of high level Veilid API // FFI implementation of high level Veilid API
class VeilidFFI implements Veilid { class VeilidFFI implements Veilid {
// veilid_core shared library // veilid_core shared library
@ -1054,31 +1209,63 @@ class VeilidFFI implements Veilid {
_tableDbTransactionDelete = dylib.lookupFunction< _tableDbTransactionDelete = dylib.lookupFunction<
_TableDbTransactionDeleteC, _TableDbTransactionDeleteC,
_TableDbTransactionDeleteDart>('table_db_transaction_delete'), _TableDbTransactionDeleteDart>('table_db_transaction_delete'),
_validCryptoKinds =
xxx dylib.lookupFunction<_ValidCryptoKindsC, _ValidCryptoKindsDart>(
final _ValidCryptoKindsDart _validCryptoKinds; 'valid_crypto_kinds'),
final _BestCryptoKindDart _bestCryptoKind; _bestCryptoKind =
final _VerifySignaturesDart _verifySignatures; dylib.lookupFunction<_BestCryptoKindC, _BestCryptoKindDart>(
final _GenerateSignaturesDart _generateSignatures; 'best_crypto_kind'),
final _GenerateKeyPairDart _generateKeyPair; _verifySignatures =
dylib.lookupFunction<_VerifySignaturesC, _VerifySignaturesDart>(
final _CryptoCachedDHDart _cryptoCachedDH; 'verify_signatures'),
final _CryptoComputeDHDart _cryptoComputeDH; _generateSignatures =
final _CryptoRandomNonceDart _cryptoRandomNonce; dylib.lookupFunction<_GenerateSignaturesC, _GenerateSignaturesDart>(
final _CryptoRandomSharedSecretDart _cryptoRandomSharedSecret; 'generate_signatures'),
final _CryptoGenerateKeyPairDart _cryptoGenerateKeyPair; _generateKeyPair =
final _CryptoGenerateHashDart _cryptoGenerateHash; dylib.lookupFunction<_GenerateKeyPairC, _GenerateKeyPairDart>(
final _CryptoValidateKeyPairDart _cryptoValidateKeyPair; 'generate_key_pair'),
final _CryptoValidateHashDart _cryptoValidateHash; _cryptoCachedDH =
final _CryptoDistanceDart _cryptoDistance; dylib.lookupFunction<_CryptoCachedDHC, _CryptoCachedDHDart>(
final _CryptoSignDart _cryptoSign; 'crypto_cached_dh'),
final _CryptoVerifyDart _cryptoVerify; _cryptoComputeDH =
final _CryptoAeadOverheadDart _cryptoAeadOverhead; dylib.lookupFunction<_CryptoComputeDHC, _CryptoComputeDHDart>(
final _CryptoDecryptAeadDart _cryptoDecryptAead; 'crypto_compute_dh'),
final _CryptoEncryptAeadDart _cryptoEncryptAead; _cryptoRandomNonce =
final _CryptoCryptNoAuthDart _cryptoCryptNoAuth; dylib.lookupFunction<_CryptoRandomNonceC, _CryptoRandomNonceDart>(
'crypto_random_nonce'),
_cryptoRandomSharedSecret = dylib.lookupFunction<
_CryptoRandomSharedSecretC,
_CryptoRandomSharedSecretDart>('crypto_random_shared_secret'),
_cryptoGenerateKeyPair = dylib.lookupFunction<_CryptoGenerateKeyPairC,
_CryptoGenerateKeyPairDart>('crypto_generate_key_pair'),
_cryptoGenerateHash =
dylib.lookupFunction<_CryptoGenerateHashC, _CryptoGenerateHashDart>(
'crypto_generate_hash'),
_cryptoValidateKeyPair = dylib.lookupFunction<_CryptoValidateKeyPairC,
_CryptoValidateKeyPairDart>('crypto_validate_key_pair'),
_cryptoValidateHash =
dylib.lookupFunction<_CryptoValidateHashC, _CryptoValidateHashDart>(
'crypto_validate_hash'),
_cryptoDistance =
dylib.lookupFunction<_CryptoDistanceC, _CryptoDistanceDart>(
'crypto_distance'),
_cryptoSign =
dylib.lookupFunction<_CryptoSignC, _CryptoSignDart>('crypto_sign'),
_cryptoVerify = dylib
.lookupFunction<_CryptoVerifyC, _CryptoVerifyDart>('crypto_verify'),
_cryptoAeadOverhead =
dylib.lookupFunction<_CryptoAeadOverheadC, _CryptoAeadOverheadDart>(
'crypto_aead_overhead'),
_cryptoDecryptAead =
dylib.lookupFunction<_CryptoDecryptAeadC, _CryptoDecryptAeadDart>(
'crypto_decrypt_aead'),
_cryptoEncryptAead =
dylib.lookupFunction<_CryptoEncryptAeadC, _CryptoEncryptAeadDart>(
'crypto_encrypt_aead'),
_cryptoCryptNoAuth =
dylib.lookupFunction<_CryptoCryptNoAuthC, _CryptoCryptNoAuthDart>(
'crypto_crypt_no_auth'),
_now = dylib.lookupFunction<_NowC, _NowDart>('now'),
_debug = dylib.lookupFunction<_DebugC, _DebugDart>('debug'), _debug = dylib.lookupFunction<_DebugC, _DebugDart>('debug'),
_veilidVersionString = dylib.lookupFunction<_VeilidVersionStringC, _veilidVersionString = dylib.lookupFunction<_VeilidVersionStringC,
_VeilidVersionStringDart>('veilid_version_string'), _VeilidVersionStringDart>('veilid_version_string'),
@ -1094,9 +1281,7 @@ xxx
@override @override
void initializeVeilidCore(Map<String, dynamic> platformConfigJson) { void initializeVeilidCore(Map<String, dynamic> platformConfigJson) {
var nativePlatformConfig = var nativePlatformConfig = jsonEncode(platformConfigJson).toNativeUtf8();
jsonEncode(platformConfigJson, toEncodable: veilidApiToEncodable)
.toNativeUtf8();
_initializeVeilidCore(nativePlatformConfig); _initializeVeilidCore(nativePlatformConfig);
@ -1105,9 +1290,7 @@ xxx
@override @override
void changeLogLevel(String layer, VeilidConfigLogLevel logLevel) { void changeLogLevel(String layer, VeilidConfigLogLevel logLevel) {
var nativeLogLevel = var nativeLogLevel = jsonEncode(logLevel).toNativeUtf8();
jsonEncode(logLevel.json, toEncodable: veilidApiToEncodable)
.toNativeUtf8();
var nativeLayer = layer.toNativeUtf8(); var nativeLayer = layer.toNativeUtf8();
_changeLogLevel(nativeLayer, nativeLogLevel); _changeLogLevel(nativeLayer, nativeLogLevel);
malloc.free(nativeLayer); malloc.free(nativeLayer);
@ -1116,9 +1299,7 @@ xxx
@override @override
Future<Stream<VeilidUpdate>> startupVeilidCore(VeilidConfig config) { Future<Stream<VeilidUpdate>> startupVeilidCore(VeilidConfig config) {
var nativeConfig = var nativeConfig = jsonEncode(config).toNativeUtf8();
jsonEncode(config.json, toEncodable: veilidApiToEncodable)
.toNativeUtf8();
final recvStreamPort = ReceivePort("veilid_api_stream"); final recvStreamPort = ReceivePort("veilid_api_stream");
final sendStreamPort = recvStreamPort.sendPort; final sendStreamPort = recvStreamPort.sendPort;
final recvPort = ReceivePort("startup_veilid_core"); final recvPort = ReceivePort("startup_veilid_core");
@ -1185,8 +1366,10 @@ xxx
Stability stability, Sequencing sequencing) async { Stability stability, Sequencing sequencing) async {
final recvPort = ReceivePort("new_custom_private_route"); final recvPort = ReceivePort("new_custom_private_route");
final sendPort = recvPort.sendPort; final sendPort = recvPort.sendPort;
_newCustomPrivateRoute(sendPort.nativePort, stability.json.toNativeUtf8(), _newCustomPrivateRoute(
sequencing.json.toNativeUtf8()); sendPort.nativePort,
jsonEncode(stability).toNativeUtf8(),
jsonEncode(sequencing).toNativeUtf8());
final routeBlob = final routeBlob =
await processFutureJson(RouteBlob.fromJson, recvPort.first); await processFutureJson(RouteBlob.fromJson, recvPort.first);
return routeBlob; return routeBlob;
@ -1240,6 +1423,48 @@ xxx
return deleted; return deleted;
} }
@override
List<CryptoKind> validCryptoKinds() {
final vckString = _validCryptoKinds();
final vck = jsonDecode(vckString.toDartString());
_freeString(vckString);
return vck;
}
@override
Future<VeilidCryptoSystem> getCryptoSystem(CryptoKind kind) async {
if (!validCryptoKinds().contains(kind)) {
throw VeilidAPIExceptionGeneric("unsupported cryptosystem");
}
return VeilidCryptoSystemFFI._(kind);
}
@override
Future<VeilidCryptoSystem> bestCryptoSystem() async {
return VeilidCryptoSystemFFI._(_bestCryptoKind());
}
@override
Future<List<TypedKey>> verifySignatures(
List<TypedKey> nodeIds, Uint8List data, List<TypedSignature> signatures) {
final nativeNodeIds = jsonEncode(nodeIds).toNativeUtf8();
final nativeData = base64UrlNoPadEncode(data).toNativeUtf8();
final nativeSignatures = jsonEncode(signatures).toNativeUtf8();
final recvPort = ReceivePort("app_call_reply");
final sendPort = recvPort.sendPort;
_verifySignatures(
sendPort.nativePort, nativeNodeIds, nativeData, nativeSignatures);
return processFutureJson(
jsonListConstructor<TypedKey>(TypedKey.fromJson), recvPort.first);
}
xxx
@override
Future<List<TypedSignature>> generateSignatures(
Uint8List data, List<TypedKeyPair> keyPairs) {}
@override
Future<TypedKeyPair> generateKeyPair(CryptoKind kind) {}
@override @override
Future<String> debug(String command) async { Future<String> debug(String command) async {
var nativeCommand = command.toNativeUtf8(); var nativeCommand = command.toNativeUtf8();

View File

@ -25,10 +25,10 @@ class VeilidWASMConfigLoggingPerformance {
required this.logsInConsole, required this.logsInConsole,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'enabled': enabled, 'enabled': enabled,
'level': level.json, 'level': level.toJson(),
'logs_in_timings': logsInTimings, 'logs_in_timings': logsInTimings,
'logs_in_console': logsInConsole, 'logs_in_console': logsInConsole,
}; };
@ -50,10 +50,10 @@ class VeilidWASMConfigLoggingApi {
required this.level, required this.level,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'enabled': enabled, 'enabled': enabled,
'level': level.json, 'level': level.toJson(),
}; };
} }
@ -68,10 +68,10 @@ class VeilidWASMConfigLogging {
VeilidWASMConfigLogging({required this.performance, required this.api}); VeilidWASMConfigLogging({required this.performance, required this.api});
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'performance': performance.json, 'performance': performance.toJson(),
'api': api.json, 'api': api.toJson(),
}; };
} }
@ -88,9 +88,9 @@ class VeilidWASMConfig {
required this.logging, required this.logging,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'logging': logging.json, 'logging': logging.toJson(),
}; };
} }
@ -137,15 +137,17 @@ class VeilidRoutingContextJS implements VeilidRoutingContext {
@override @override
VeilidRoutingContextJS withCustomPrivacy(Stability stability) { VeilidRoutingContextJS withCustomPrivacy(Stability stability) {
final newId = js_util.callMethod( final newId = js_util.callMethod(
wasm, "routing_context_with_custom_privacy", [_ctx.id, stability.json]); wasm,
"routing_context_with_custom_privacy",
[_ctx.id, jsonEncode(stability)]);
return VeilidRoutingContextJS._(_Ctx(newId, _ctx.js)); return VeilidRoutingContextJS._(_Ctx(newId, _ctx.js));
} }
@override @override
VeilidRoutingContextJS withSequencing(Sequencing sequencing) { VeilidRoutingContextJS withSequencing(Sequencing sequencing) {
final newId = js_util.callMethod( final newId = js_util.callMethod(wasm, "routing_context_with_sequencing",
wasm, "routing_context_with_sequencing", [_ctx.id, sequencing.json]); [_ctx.id, jsonEncode(sequencing)]);
return VeilidRoutingContextJS._(_Ctx(newId, _ctx.js)); return VeilidRoutingContextJS._(_Ctx(newId, _ctx.js));
} }
@ -292,16 +294,14 @@ class VeilidTableDBJS extends VeilidTableDB {
class VeilidJS implements Veilid { class VeilidJS implements Veilid {
@override @override
void initializeVeilidCore(Map<String, dynamic> platformConfigJson) { void initializeVeilidCore(Map<String, dynamic> platformConfigJson) {
var platformConfigJsonString = var platformConfigJsonString = jsonEncode(platformConfigJson);
jsonEncode(platformConfigJson, toEncodable: veilidApiToEncodable);
js_util js_util
.callMethod(wasm, "initialize_veilid_core", [platformConfigJsonString]); .callMethod(wasm, "initialize_veilid_core", [platformConfigJsonString]);
} }
@override @override
void changeLogLevel(String layer, VeilidConfigLogLevel logLevel) { void changeLogLevel(String layer, VeilidConfigLogLevel logLevel) {
var logLevelJsonString = var logLevelJsonString = jsonEncode(logLevel);
jsonEncode(logLevel.json, toEncodable: veilidApiToEncodable);
js_util.callMethod(wasm, "change_log_level", [layer, logLevelJsonString]); js_util.callMethod(wasm, "change_log_level", [layer, logLevelJsonString]);
} }
@ -318,10 +318,8 @@ class VeilidJS implements Veilid {
} }
} }
await _wrapApiPromise(js_util.callMethod(wasm, "startup_veilid_core", [ await _wrapApiPromise(js_util.callMethod(wasm, "startup_veilid_core",
js.allowInterop(updateCallback), [js.allowInterop(updateCallback), jsonEncode(config)]));
jsonEncode(config.json, toEncodable: veilidApiToEncodable)
]));
return streamController.stream; return streamController.stream;
} }
@ -365,10 +363,8 @@ class VeilidJS implements Veilid {
@override @override
Future<RouteBlob> newCustomPrivateRoute( Future<RouteBlob> newCustomPrivateRoute(
Stability stability, Sequencing sequencing) async { Stability stability, Sequencing sequencing) async {
var stabilityString = var stabilityString = jsonEncode(stability);
jsonEncode(stability, toEncodable: veilidApiToEncodable); var sequencingString = jsonEncode(sequencing);
var sequencingString =
jsonEncode(sequencing, toEncodable: veilidApiToEncodable);
Map<String, dynamic> blobJson = jsonDecode(await _wrapApiPromise(js_util Map<String, dynamic> blobJson = jsonDecode(await _wrapApiPromise(js_util
.callMethod( .callMethod(

View File

@ -20,7 +20,7 @@ enum AttachmentState {
} }
extension AttachmentStateExt on AttachmentState { extension AttachmentStateExt on AttachmentState {
String get json { String toJson() {
return name.toPascalCase(); return name.toPascalCase();
} }
} }
@ -41,7 +41,7 @@ enum VeilidLogLevel {
} }
extension VeilidLogLevelExt on VeilidLogLevel { extension VeilidLogLevelExt on VeilidLogLevel {
String get json { String toJson() {
return name.toPascalCase(); return name.toPascalCase();
} }
} }
@ -63,11 +63,11 @@ class LatencyStats {
required this.slowest, required this.slowest,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'fastest': fastest.json, 'fastest': fastest.toJson(),
'average': average.json, 'average': average.toJson(),
'slowest': slowest.json, 'slowest': slowest.toJson(),
}; };
} }
@ -92,7 +92,7 @@ class TransferStats {
required this.minimum, required this.minimum,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'total': total.toString(), 'total': total.toString(),
'maximum': maximum.toString(), 'maximum': maximum.toString(),
@ -119,10 +119,10 @@ class TransferStatsDownUp {
required this.up, required this.up,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'down': down.json, 'down': down.toJson(),
'up': up.json, 'up': up.toJson(),
}; };
} }
@ -154,14 +154,14 @@ class RPCStats {
required this.failedToSend, required this.failedToSend,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'messages_sent': messagesSent, 'messages_sent': messagesSent,
'messages_rcvd': messagesRcvd, 'messages_rcvd': messagesRcvd,
'questions_in_flight': questionsInFlight, 'questions_in_flight': questionsInFlight,
'last_question': lastQuestion?.json, 'last_question': lastQuestion?.toJson(),
'last_seen_ts': lastSeenTs?.json, 'last_seen_ts': lastSeenTs?.toJson(),
'first_consecutive_seen_ts': firstConsecutiveSeenTs?.json, 'first_consecutive_seen_ts': firstConsecutiveSeenTs?.toJson(),
'recent_lost_answers': recentLostAnswers, 'recent_lost_answers': recentLostAnswers,
'failed_to_send': failedToSend, 'failed_to_send': failedToSend,
}; };
@ -199,12 +199,12 @@ class PeerStats {
required this.transfer, required this.transfer,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'time_added': timeAdded.json, 'time_added': timeAdded.toJson(),
'rpc_stats': rpcStats.json, 'rpc_stats': rpcStats.toJson(),
'latency': latency?.json, 'latency': latency?.toJson(),
'transfer': transfer.json, 'transfer': transfer.toJson(),
}; };
} }
@ -230,11 +230,11 @@ class PeerTableData {
required this.peerStats, required this.peerStats,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'node_ids': nodeIds.map((p) => p.json).toList(), 'node_ids': nodeIds.map((p) => p.toJson()).toList(),
'peer_address': peerAddress.json, 'peer_address': peerAddress.toJson(),
'peer_stats': peerStats.json, 'peer_stats': peerStats.toJson(),
}; };
} }
@ -256,7 +256,7 @@ enum ProtocolType {
} }
extension ProtocolTypeExt on ProtocolType { extension ProtocolTypeExt on ProtocolType {
String get json { String toJson() {
return name.toUpperCase(); return name.toUpperCase();
} }
} }
@ -276,9 +276,9 @@ class PeerAddress {
required this.socketAddress, required this.socketAddress,
}); });
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'protocol_type': protocolType.json, 'protocol_type': protocolType.toJson(),
'socket_address': socketAddress, 'socket_address': socketAddress,
}; };
} }
@ -347,7 +347,7 @@ abstract class VeilidUpdate {
} }
} }
} }
Map<String, dynamic> get json; Map<String, dynamic> toJson();
} }
class VeilidLog implements VeilidUpdate { class VeilidLog implements VeilidUpdate {
@ -362,10 +362,10 @@ class VeilidLog implements VeilidUpdate {
}); });
@override @override
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'kind': "Log", 'kind': "Log",
'log_level': logLevel.json, 'log_level': logLevel.toJson(),
'message': message, 'message': message,
'backtrace': backtrace 'backtrace': backtrace
}; };
@ -383,7 +383,7 @@ class VeilidAppMessage implements VeilidUpdate {
}); });
@override @override
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'kind': "AppMessage", 'kind': "AppMessage",
'sender': sender, 'sender': sender,
@ -405,7 +405,7 @@ class VeilidAppCall implements VeilidUpdate {
}); });
@override @override
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'kind': "AppMessage", 'kind': "AppMessage",
'sender': sender, 'sender': sender,
@ -421,8 +421,8 @@ class VeilidUpdateAttachment implements VeilidUpdate {
VeilidUpdateAttachment({required this.state}); VeilidUpdateAttachment({required this.state});
@override @override
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
var jsonRep = state.json; var jsonRep = state.toJson();
jsonRep['kind'] = "Attachment"; jsonRep['kind'] = "Attachment";
return jsonRep; return jsonRep;
} }
@ -434,8 +434,8 @@ class VeilidUpdateNetwork implements VeilidUpdate {
VeilidUpdateNetwork({required this.state}); VeilidUpdateNetwork({required this.state});
@override @override
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
var jsonRep = state.json; var jsonRep = state.toJson();
jsonRep['kind'] = "Network"; jsonRep['kind'] = "Network";
return jsonRep; return jsonRep;
} }
@ -447,8 +447,8 @@ class VeilidUpdateConfig implements VeilidUpdate {
VeilidUpdateConfig({required this.state}); VeilidUpdateConfig({required this.state});
@override @override
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
var jsonRep = state.json; var jsonRep = state.toJson();
jsonRep['kind'] = "Config"; jsonRep['kind'] = "Config";
return jsonRep; return jsonRep;
} }
@ -464,7 +464,7 @@ class VeilidUpdateRouteChange implements VeilidUpdate {
}); });
@override @override
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'dead_routes': deadRoutes.map((p) => p).toList(), 'dead_routes': deadRoutes.map((p) => p).toList(),
'dead_remote_routes': deadRemoteRoutes.map((p) => p).toList() 'dead_remote_routes': deadRemoteRoutes.map((p) => p).toList()
@ -487,12 +487,12 @@ class VeilidUpdateValueChange implements VeilidUpdate {
}); });
@override @override
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'key': key.json, 'key': key.toJson(),
'subkeys': subkeys.map((p) => p.json).toList(), 'subkeys': subkeys.map((p) => p.toJson()).toList(),
'count': count, 'count': count,
'value_data': valueData.json, 'value_data': valueData.toJson(),
}; };
} }
} }
@ -513,9 +513,9 @@ class VeilidStateAttachment {
publicInternetReady = json['public_internet_ready'], publicInternetReady = json['public_internet_ready'],
localNetworkReady = json['local_network_ready']; localNetworkReady = json['local_network_ready'];
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'state': state.json, 'state': state.toJson(),
'public_internet_ready': publicInternetReady, 'public_internet_ready': publicInternetReady,
'local_network_ready': localNetworkReady, 'local_network_ready': localNetworkReady,
}; };
@ -544,12 +544,12 @@ class VeilidStateNetwork {
peers = List<PeerTableData>.from( peers = List<PeerTableData>.from(
json['peers'].map((j) => PeerTableData.fromJson(j))); json['peers'].map((j) => PeerTableData.fromJson(j)));
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'started': started, 'started': started,
'bps_down': bpsDown.toString(), 'bps_down': bpsDown.toString(),
'bps_up': bpsUp.toString(), 'bps_up': bpsUp.toString(),
'peers': peers.map((p) => p.json).toList(), 'peers': peers.map((p) => p.toJson()).toList(),
}; };
} }
} }
@ -566,7 +566,7 @@ class VeilidStateConfig {
VeilidStateConfig.fromJson(dynamic json) : config = json['config']; VeilidStateConfig.fromJson(dynamic json) : config = json['config'];
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return {'config': config}; return {'config': config};
} }
} }
@ -584,11 +584,11 @@ class VeilidState {
network = VeilidStateNetwork.fromJson(json['network']), network = VeilidStateNetwork.fromJson(json['network']),
config = VeilidStateConfig.fromJson(json['config']); config = VeilidStateConfig.fromJson(json['config']);
Map<String, dynamic> get json { Map<String, dynamic> toJson() {
return { return {
'attachment': attachment.json, 'attachment': attachment.toJson(),
'network': network.json, 'network': network.toJson(),
'config': config.json 'config': config.toJson()
}; };
} }
} }

View File

@ -606,10 +606,10 @@ pub extern "C" fn routing_context_set_dht_value(port: i64, id: u32, key: FfiStr,
#[no_mangle] #[no_mangle]
pub extern "C" fn routing_context_watch_dht_values(port: i64, id: u32, key: FfiStr, subkeys: FfiStr, expiration: FfiStr, count: u32) { pub extern "C" fn routing_context_watch_dht_values(port: i64, id: u32, key: FfiStr, subkeys: FfiStr, expiration: u64, count: u32) {
let key: veilid_core::TypedKey = veilid_core::deserialize_opt_json(key.into_opt_string()).unwrap(); let key: veilid_core::TypedKey = veilid_core::deserialize_opt_json(key.into_opt_string()).unwrap();
let subkeys: veilid_core::ValueSubkeyRangeSet = veilid_core::deserialize_opt_json(subkeys.into_opt_string()).unwrap(); let subkeys: veilid_core::ValueSubkeyRangeSet = veilid_core::deserialize_opt_json(subkeys.into_opt_string()).unwrap();
let expiration = veilid_core::Timestamp::from_str(expiration.as_opt_str().unwrap()).unwrap(); let expiration = veilid_core::Timestamp::from(expiration);
DartIsolateWrapper::new(port).spawn_result(async move { DartIsolateWrapper::new(port).spawn_result(async move {
let routing_context = { let routing_context = {
@ -620,7 +620,7 @@ pub extern "C" fn routing_context_watch_dht_values(port: i64, id: u32, key: FfiS
routing_context.clone() routing_context.clone()
}; };
let res = routing_context.watch_dht_values(key, subkeys, expiration, count).await?; let res = routing_context.watch_dht_values(key, subkeys, expiration, count).await?;
APIResult::Ok(res.to_string()) APIResult::Ok(res.as_u64())
}); });
} }