@functionland/react-native-fula 1.54.9 → 1.54.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,49 +1,59 @@
1
1
  import Foundation
2
- import CommonCrypto
3
2
  import CryptoSwift
4
3
  import os.log
5
4
 
6
-
7
-
8
- public class Cryptography: NSObject {
9
- public static func encryptMsg(_ message: Array<UInt8>, _ secretKey: Array<UInt8>)
10
- throws -> String {
11
- OSLog.viewCycle.info("ReactNative encryptMsg started for \(message)")
12
- let aes = try! AES(key: secretKey, blockMode: ECB(), padding: .pkcs5)
13
- OSLog.viewCycle.info("ReactNative encryptMsg aes")
14
- let encrypted = try! aes.encrypt(message)
15
- OSLog.viewCycle.info("ReactNative encryptMsg encrypted")
16
- do{
17
- let data = Data(encrypted).base64EncodedString()
18
- OSLog.viewCycle.info("ReactNative encryptMsg: \(data)")
19
- return data
20
- } catch let error {
21
- OSLog.viewCycle.info("ReactNative encryptMsg error: \(error.localizedDescription)")
22
- throw error
5
+ public class Cryptography {
6
+ // AES/GCM Encryption with IV handling
7
+ public static func encryptMsg(_ message: [UInt8], _ secretKey: [UInt8], _ providedIv: [UInt8]? = nil) throws -> String {
8
+ var iv = providedIv ?? [UInt8](repeating: 0, count: 12) // Default IV value
9
+ if iv.isEmpty {
10
+ iv = AES.randomIV(12) // Generate a random IV if not provided or if empty
23
11
  }
12
+
13
+ let gcm = GCM(iv: iv, mode: .combined)
14
+ let aes = try AES(key: secretKey, blockMode: gcm, padding: .noPadding)
15
+
16
+ let encrypted = try aes.encrypt(message)
17
+ let encryptedDataWithIv = Data(iv + encrypted) // Prepend IV to the encrypted data
18
+ return encryptedDataWithIv.base64EncodedString()
24
19
  }
25
20
 
26
- public static func decryptMsg(_ cipherText: String, _ secretKey: Array<UInt8>)
27
- throws -> Array<UInt8> {
28
- let aes = try! AES(key: secretKey, blockMode: ECB(), padding: .pkcs5)
29
- let data = cipherText.fromBase64()!
30
- return try! aes.decrypt(data.bytes)
31
-
21
+ // AES/GCM Decryption with IV extracted from the beginning of the cipherText
22
+ public static func decryptMsg(_ cipherText: String, _ secretKey: [UInt8]) throws -> [UInt8] {
23
+ guard let encryptedDataWithIv = Data(base64Encoded: cipherText) else {
24
+ throw NSError(domain: "DecryptionError", code: -1, userInfo: nil)
25
+ }
26
+ let iv = Array(encryptedDataWithIv.prefix(12)) // Extract IV (first 12 bytes)
27
+ let encryptedData = Array(encryptedDataWithIv.dropFirst(12)) // The rest is the encrypted data
28
+
29
+ let gcm = GCM(iv: iv, mode: .combined)
30
+ let aes = try AES(key: secretKey, blockMode: gcm, padding: .noPadding)
31
+
32
+ let decrypted = try aes.decrypt(encryptedData)
33
+ return decrypted
32
34
  }
33
35
 
34
- public static func generateKey(_ salt: Data)
35
- throws -> Array<UInt8> {
36
- let password: [UInt8] = Array("".utf8)
37
- let salt: [UInt8] = salt.bytes
38
-
39
- //TODO: Generate a key from a salt and an empty password
40
- let key = try PKCS5.PBKDF2(
41
- password: password,
42
- salt: salt,
43
- iterations: 4096,
44
- keyLength: 16, /* AES-128 */
45
- variant: .sha2(SHA2.Variant.sha256)
46
- ).calculate()
47
- return key
36
+ // Key Generation matching Java's logic
37
+ public static func generateKey(_ identity: Data) throws -> Data {
38
+ // Transform identity to base64 string to mimic Java's behavior
39
+ let passwordString = identity.base64EncodedString()
40
+ let passwordData = Array(passwordString.utf8) // Convert to byte array
41
+
42
+ // Use identity itself as salt for simplicity to mimic Java behavior
43
+ let salt = Array(identity)
44
+
45
+ do {
46
+ let key = try PKCS5.PBKDF2(
47
+ password: passwordData,
48
+ salt: salt,
49
+ iterations: 1000, // Adjust the iteration count as needed
50
+ keyLength: 16, // AES-128
51
+ variant: .sha256
52
+ ).calculate()
53
+
54
+ return Data(key)
55
+ } catch {
56
+ throw error // Propagate error
57
+ }
48
58
  }
49
59
  }
package/ios/Fula.mm CHANGED
@@ -190,7 +190,8 @@ RCT_EXTERN_METHOD(getFolderSize:(NSString *)folderPath
190
190
  withResolver:(RCTPromiseResolveBlock)resolve
191
191
  withRejecter:(RCTPromiseRejectBlock)reject)
192
192
 
193
- RCT_EXTERN_METHOD(getDatastoreSize:(RCTPromiseResolveBlock)resolve withRejecter:(RCTPromiseRejectBlock)reject)
193
+ RCT_EXTERN_METHOD(getDatastoreSize:(RCTPromiseResolveBlock)resolve
194
+ rejecter:(RCTPromiseRejectBlock)reject)
194
195
 
195
196
  + (BOOL)requiresMainQueueSetup
196
197
  {
package/ios/Fula.swift CHANGED
@@ -149,7 +149,7 @@ class FulaModule: NSObject {
149
149
  // Attempt to shut down Fula cleanly (similar to onHostDestroy)
150
150
  os_log("Application will terminate - shutting down Fula", log: OSLog.viewCycle, type: .info)
151
151
  do {
152
- if let fulaClient = fula {
152
+ if let fulaClient = self.fula {
153
153
  try fulaClient.shutdown()
154
154
  os_log("Fula shutdown successfully.", log: OSLog.viewCycle, type: .info)
155
155
  }
@@ -188,23 +188,23 @@ class FulaModule: NSObject {
188
188
 
189
189
  @objc(checkConnection:withResolver:withRejecter:)
190
190
  func checkConnection(timeout: NSNumber, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
191
- OSLog.viewCycle.info("ReactNative checkConnection started with timeout=\(timeout)")
191
+ NSLog("ReactNative checkConnection started with timeout=\(timeout)")
192
192
 
193
193
  if let timeoutInt = timeout as? Int {
194
- if fula != nil {
194
+ if self.fula != nil {
195
195
  DispatchQueue.global(qos: .default).async {
196
196
  do {
197
197
  let connectionStatus = try self.checkConnectionInternal(timeout: timeoutInt)
198
- OSLog.viewCycle.info("ReactNative checkConnection ended \(connectionStatus)")
198
+ NSLog("ReactNative checkConnection ended \(connectionStatus)")
199
199
  resolve(connectionStatus)
200
200
  }
201
201
  catch let error {
202
- OSLog.viewCycle.info("ReactNative checkConnection failed with Error: \(error.localizedDescription)")
202
+ NSLog("ReactNative checkConnection failed with Error: \(error.localizedDescription)")
203
203
  resolve(false)
204
204
  }
205
205
  }
206
206
  } else {
207
- OSLog.viewCycle.info("ReactNative checkConnection fula is null")
207
+ NSLog("ReactNative checkConnection fula is null")
208
208
  resolve(false)
209
209
  }
210
210
  } else {
@@ -216,13 +216,13 @@ class FulaModule: NSObject {
216
216
 
217
217
  @objc(newClient:withStorePath:withBloxAddr:withExchange:withAutoFlush:withUseRelay:withRefresh:withResolver:withRejecter:)
218
218
  func newClient(identityString: String, storePath: String, bloxAddr: String, exchange: String, autoFlush: Bool, useRelay: Bool, refresh: Bool, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
219
- print("ReactNative", "newClient storePath= " , storePath , " bloxAddr= " , bloxAddr , " exchange= " , exchange , " autoFlush= " , autoFlush , " useRelay= " , useRelay , " refresh= " , refresh);
219
+ print("ReactNative", "newClient storePath= " , storePath , " bloxAddr= " , bloxAddr , " exchange= " , exchange , " autoFlush= " , autoFlush , " useRelay= " , useRelay , " refresh= " , refresh)
220
220
  do {
221
221
  print("ReactNative", "newClient storePath= ", storePath)
222
222
  let identity = toByte(identityString)
223
223
  print("ReactNative", "newClient identity= ", identityString)
224
224
  try newClientInternal(identity: identity, storePath: storePath, bloxAddr: bloxAddr, exchange: exchange, autoFlush: autoFlush, useRelay: useRelay, refresh: refresh)
225
- let peerId = fula?.id_()
225
+ let peerId = self.fula?.id_()
226
226
  resolve(peerId)
227
227
  } catch let error {
228
228
  print("ReactNative", "newClient failed with Error: ", error.localizedDescription)
@@ -236,9 +236,9 @@ class FulaModule: NSObject {
236
236
  print("ReactNative", "isReady started")
237
237
  var initialized = false
238
238
  do {
239
- if (fula != nil && !fula!.id_().isEmpty) {
239
+ if (self.fula != nil && !self.fula!.id_().isEmpty) {
240
240
  if (filesystemCheck) {
241
- if (client != nil && rootCid != nil && !rootCid!.isEmpty) {
241
+ if (self.client != nil && rootCid != nil && !rootCid!.isEmpty) {
242
242
  initialized = true
243
243
  }
244
244
  } else {
@@ -257,23 +257,23 @@ class FulaModule: NSObject {
257
257
  @objc(initFula:withStorePath:withBloxAddr:withExchange:withAutoFlush:withRootConfig:withUseRelay:withRefresh:withResolver:withRejecter:)
258
258
  func initFula(identityString: String, storePath: String, bloxAddr: String, exchange: String, autoFlush: Bool, rootConfig: String, useRelay: Bool, refresh: Bool, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
259
259
 
260
- OSLog.viewCycle.info("ReactNative - init started")
260
+ NSLog("ReactNative - init started")
261
261
 
262
262
  do {
263
263
 
264
264
  var resultData = Dictionary<String, String>()
265
- OSLog.viewCycle.info("ReactNative init storePath= \(storePath)")
265
+ NSLog("ReactNative init storePath= \(storePath)")
266
266
  let identity = self.toByte(identityString)
267
- OSLog.viewCycle.info("ReactNative init identity= \(identityString)")
267
+ NSLog("ReactNative init identity= \(identityString)")
268
268
  let obj = try initInternal(identity: identity, storePath: storePath, bloxAddr: bloxAddr, exchange: exchange, autoFlush: autoFlush, _rootCid: rootConfig, useRelay: useRelay, refresh: refresh)
269
- OSLog.viewCycle.info("ReactNative init object created: [ \(obj[0]), \(obj[1]), \(obj[2]) ]")
269
+ NSLog("ReactNative init object created: [ \(obj[0]), \(obj[1]), \(obj[2]) ]")
270
270
  resultData["peerId"] = obj[0]
271
271
  resultData["rootCid"] = obj[1]
272
272
  resultData["wnfs_key"] = obj[2]
273
273
  resolve(resultData as NSDictionary)
274
274
 
275
275
  } catch let error {
276
- OSLog.viewCycle.info("ReactNative init failed with Error: \(error.localizedDescription)")
276
+ NSLog("ReactNative init failed with Error: \(error.localizedDescription)")
277
277
  reject("ERR_FULA", "init failed", error)
278
278
  }
279
279
 
@@ -297,7 +297,7 @@ class FulaModule: NSObject {
297
297
  }
298
298
 
299
299
  func checkConnectionInternal(timeout: Int) throws -> Bool {
300
- OSLog.viewCycle.info("ReactNative checkConnectionInternal started with timeout: \(timeout)")
300
+ NSLog("ReactNative checkConnectionInternal started with timeout: \(timeout)")
301
301
  var connectionStatus = false
302
302
 
303
303
  if let fula = self.fula {
@@ -306,13 +306,13 @@ class FulaModule: NSObject {
306
306
 
307
307
  queue.async {
308
308
  do {
309
- OSLog.viewCycle.info("ReactNative connectToBlox started")
309
+ NSLog("ReactNative connectToBlox started")
310
310
  try fula.connectToBlox()
311
311
  connectionStatus = true
312
- OSLog.viewCycle.info("ReactNative checkConnectionInternal succeeded")
312
+ NSLog("ReactNative checkConnectionInternal succeeded")
313
313
  semaphore.signal()
314
314
  } catch let error {
315
- OSLog.viewCycle.info("ReactNative checkConnectionInternal failed with Error: \(error.localizedDescription)")
315
+ NSLog("ReactNative checkConnectionInternal failed with Error: \(error.localizedDescription)")
316
316
  semaphore.signal()
317
317
  }
318
318
  }
@@ -320,13 +320,13 @@ class FulaModule: NSObject {
320
320
  let timeoutResult = semaphore.wait(timeout: .now() + .seconds(timeout))
321
321
  switch timeoutResult {
322
322
  case .timedOut:
323
- OSLog.viewCycle.info("ReactNative checkConnectionInternal timed out")
323
+ NSLog("ReactNative checkConnectionInternal timed out")
324
324
  return false
325
325
  case .success:
326
326
  return connectionStatus
327
327
  }
328
328
  } else {
329
- OSLog.viewCycle.info("ReactNative checkConnectionInternal failed because fula is not initialized")
329
+ NSLog("ReactNative checkConnectionInternal failed because fula is not initialized")
330
330
  return false
331
331
  }
332
332
  }
@@ -334,29 +334,29 @@ class FulaModule: NSObject {
334
334
  @objc(checkFailedActions:withTimeout:withResolver:withRejecter:)
335
335
  func checkFailedActions(retry: Bool, timeout: Int, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) -> Void {
336
336
  do {
337
- guard let fula = fula else {
337
+ guard let fula = self.fula else {
338
338
  throw NSError(domain: "ERR_FULA", code: 1001, userInfo: [NSLocalizedDescriptionKey: "Fula is not initialized"])
339
339
  }
340
340
 
341
341
  if !retry {
342
- OSLog.viewCycle.info("ReactNative checkFailedActions without retry")
342
+ NSLog("ReactNative checkFailedActions without retry")
343
343
  let failedLinks = try fula.listFailedPushes()
344
344
 
345
345
  let nextFailedLink = try failedLinks.next()
346
346
  if nextFailedLink != nil {
347
347
  // Assuming nextFailedLink is of type Data; replace `toHex()` with an appropriate method to convert Data to a hex string
348
- OSLog.viewCycle.info("ReactNative checkFailedActions found")
348
+ NSLog("ReactNative checkFailedActions found")
349
349
  resolve(true)
350
350
  } else {
351
351
  resolve(false)
352
352
  }
353
353
  } else {
354
- OSLog.viewCycle.info("ReactNative checkFailedActions with retry")
354
+ NSLog("ReactNative checkFailedActions with retry")
355
355
  let retryResults = try retryFailedActionsInternal(timeout: timeout) // Ensure retryFailedActionsInternal accepts a timeout parameter
356
356
  resolve(!retryResults)
357
357
  }
358
358
  } catch let error {
359
- OSLog.viewCycle.info("ReactNative checkFailedActions failed with Error: \(error.localizedDescription)")
359
+ NSLog("ReactNative checkFailedActions failed with Error: \(error.localizedDescription)")
360
360
  reject("ERR_FULA", "CheckFailedActions failed", error)
361
361
  }
362
362
  }
@@ -364,10 +364,10 @@ class FulaModule: NSObject {
364
364
 
365
365
 
366
366
  func retryFailedActionsInternal(timeout: Int) throws -> Bool {
367
- OSLog.viewCycle.info("ReactNative retryFailedActionsInternal started")
367
+ NSLog("ReactNative retryFailedActionsInternal started")
368
368
 
369
- guard let fula = fula else {
370
- OSLog.viewCycle.info("ReactNative retryFailedActionsInternal failed because fula is not initialized")
369
+ guard let fula = self.fula else {
370
+ NSLog("ReactNative retryFailedActionsInternal failed because fula is not initialized")
371
371
  return false
372
372
  }
373
373
 
@@ -376,79 +376,107 @@ class FulaModule: NSObject {
376
376
 
377
377
  if connectionCheck {
378
378
  do {
379
- OSLog.viewCycle.info("ReactNative retryFailedPushes started")
379
+ NSLog("ReactNative retryFailedPushes started")
380
380
  try fula.retryFailedPushes()
381
- OSLog.viewCycle.info("ReactNative flush started")
381
+ NSLog("ReactNative flush started")
382
382
  try fula.flush()
383
383
  return true
384
384
  } catch let error {
385
385
  try fula.flush()
386
- OSLog.viewCycle.info("ReactNative retryFailedActionsInternal failed with Error: \(error.localizedDescription)")
386
+ NSLog("ReactNative retryFailedActionsInternal failed with Error: \(error.localizedDescription)")
387
387
  return false
388
388
  }
389
389
  } else {
390
- OSLog.viewCycle.info("ReactNative retryFailedActionsInternal failed because blox is offline")
390
+ NSLog("ReactNative retryFailedActionsInternal failed because blox is offline")
391
391
  return false
392
392
  }
393
393
  } catch let error {
394
- OSLog.viewCycle.info("ReactNative retryFailedActionsInternal failed with Error: \(error.localizedDescription)")
394
+ NSLog("ReactNative retryFailedActionsInternal failed with Error: \(error.localizedDescription)")
395
395
  return false
396
396
  }
397
397
  }
398
398
 
399
-
400
-
401
399
  func createPeerIdentity(privateKey: Data) throws -> Data {
402
- do {
403
- // 1: First: create public key from provided private key
404
- // 2: Should read the local keychain store (if it is key-value, key is public key above,
405
- // 3: if found, decrypt using the private key
406
- // 4: If not found or decryption not successful, generate an identity
407
- // 5: then encrypt and store in keychain
408
- // TODO: recheck error handling
409
- var encryptedKey = userDataHelper.getValue(FulaModule.PRIVATE_KEY_STORE_ID)
410
- let secretKey = try Cryptography.generateKey(privateKey)
411
- if (encryptedKey == nil) {
412
- var error: NSError?
413
- let autoGeneratedIdentity = FulamobileGenerateEd25519Key(&error)
414
- if error != nil {
415
- throw error!
416
- }
417
- encryptedKey = try Cryptography.encryptMsg(autoGeneratedIdentity!.toUint8Array(), secretKey)
418
- userDataHelper.add(FulaModule.PRIVATE_KEY_STORE_ID, encryptedKey!)
400
+ let secretKey = try Cryptography.generateKey(privateKey)
401
+
402
+ var encryptedKey: String? = userDataHelper.getValue(FulaModule.PRIVATE_KEY_STORE_ID)
403
+ NSLog("ReactNative createPeerIdentity encryptedKey=\(encryptedKey ?? "nil")")
404
+ if encryptedKey == nil {
405
+ let privateKeyString = String(data: privateKey, encoding: .utf8) ?? ""
406
+
407
+ guard !privateKeyString.isEmpty else {
408
+ throw NSError(domain: "KeyGenerationError", code: -1, userInfo: [NSLocalizedDescriptionKey: "Private key string conversion failed"])
409
+ }
410
+ var error: NSError?
411
+ guard let autoGeneratedIdentity = FulamobileGenerateEd25519KeyFromString(privateKeyString, &error)?.toUint8Array() else {
412
+ throw error ?? NSError(domain: "KeyGenerationError", code: -1, userInfo: nil)
419
413
  }
420
- return try Cryptography.decryptMsg(encryptedKey!, secretKey).toData()
414
+ encryptedKey = try Cryptography.encryptMsg([UInt8](autoGeneratedIdentity), [UInt8](secretKey))
415
+ NSLog("ReactNative createPeerIdentity encryptedKey2=\(encryptedKey)")
416
+ userDataHelper.add(FulaModule.PRIVATE_KEY_STORE_ID, encryptedKey ?? "")
417
+ }
418
+
419
+ // Assuming decryptMsg returns Data or throws an error if decryption fails
420
+ guard let encryptedKeyData = encryptedKey, !encryptedKeyData.isEmpty else {
421
+ throw NSError(domain: "DecryptionError", code: -1, userInfo: [NSLocalizedDescriptionKey: "Encrypted key is empty"])
422
+ }
423
+ let decryptedData = try Cryptography.decryptMsg(encryptedKeyData, Array(secretKey))
424
+ let hexString = decryptedData.map { String(format: "%02hhx", $0) }.joined()
425
+ NSLog("ReactNative createPeerIdentity decryptedData=\(hexString)")
426
+ return Data(decryptedData)
427
+ }
428
+
429
+ func decryptLibp2pIdentity(_ encryptedLibp2pId: String, with encryptionSecretKey: Data) throws -> String {
430
+ // Convert Data to [UInt8]
431
+ let secretKeyBytes = [UInt8](encryptionSecretKey)
432
+
433
+ // Attempt decryption
434
+ guard let decryptedBytes = try? Cryptography.decryptMsg(encryptedLibp2pId, secretKeyBytes) else {
435
+ throw NSError(domain: "DecryptionError", code: 1, userInfo: [NSLocalizedDescriptionKey: "Failed to decrypt Libp2p ID"])
436
+ }
437
+
438
+ // Assuming decryptedBytes is an array of UInt8
439
+ return String(decoding: decryptedBytes, as: UTF8.self)
440
+ }
421
441
 
422
- } catch let error {
423
- print("ReactNative", "createPeerIdentity failed with Error: ", error.localizedDescription)
424
- throw error
442
+ func createEncryptedLibp2pId(from identity: Data, with encryptionSecretKey: Data) throws -> String {
443
+ var error: NSError?
444
+ guard let autoGeneratedIdentity = FulamobileGenerateEd25519Key(&error) else {
445
+ throw error ?? NSError(domain: "KeyGenerationError", code: -1, userInfo: nil)
425
446
  }
447
+ let encryptedLibp2pId = try Cryptography.encryptMsg(Array(autoGeneratedIdentity), Array(encryptionSecretKey))
448
+ userDataHelper.add(FulaModule.PRIVATE_KEY_STORE_ID, encryptedLibp2pId)
449
+ return encryptedLibp2pId
426
450
  }
427
451
 
428
452
  func createNewrootCid(identity: Data) throws -> Void {
429
453
  let hash32 = identity.sha256()
430
- print("ReactNative", "wnfsKey=" , identity.toHex() , "; hash32 = " , hash32.toHex());
431
- if (fula != nil) {
432
- try fula?.flush()
454
+ NSLog("ReactNative createNewrootCid wnfsKey= \(identity.toHex()) , hash32 = \(hash32.toHex())")
455
+ if (self.fula != nil) {
456
+ NSLog("ReactNative createNewrootCid self.fula not null")
457
+ try self.fula?.flush()
433
458
  }
434
- rootCid = try wnfs?.Init(wnfsKey: hash32)
435
- print("ReactNative", "privateForest is created: ", rootCid!)
459
+ NSLog("ReactNative fula flushed")
460
+ rootCid = try self.wnfs?.Init(wnfsKey: hash32)
461
+ NSLog("ReactNative privateForest is created: \(rootCid!)")
436
462
  wnfsKey = identity
437
- print("ReactNative", "rootCid is created: cid=", rootCid!, " ; wnfs_key=", wnfsKey!.toHex(), "; hash32=", hash32)
463
+ NSLog("ReactNative rootCid is created: cid= \(rootCid!) wnfs_key= \(wnfsKey!.toHex()), hash32=\(hash32)")
438
464
  try encryptAndStoreConfig()
439
465
  }
440
466
 
441
467
  func loadWnfs(_ _wnfsKey: Data , _ _rootCid: String) throws {
442
- OSLog.viewCycle.info("ReactNative loadWnfs called: rootCid=\(_rootCid)")
468
+ NSLog("ReactNative loadWnfs called: _rootCid=\(_rootCid)")
443
469
  let hash32 = _wnfsKey.sha256()
444
- OSLog.viewCycle.info("ReactNative wnfsKey= \(_wnfsKey.toHex()) ; hash32 = \(hash32.toHex())");
445
- try wnfs?.LoadWithWNFSKey(wnfsKey: hash32, cid: _rootCid)
470
+ NSLog("ReactNative wnfsKey= \(_wnfsKey.toHex()) ; hash32 = \(hash32.toHex())")
471
+ try self.wnfs?.LoadWithWNFSKey(wnfsKey: hash32, cid: _rootCid)
472
+ NSLog("ReactNative loadWnfs LoadWithWNFSKey")
446
473
  rootCid = _rootCid
447
474
  wnfsKey = _wnfsKey
448
- if (fula != nil) {
449
- try fula?.flush()
475
+ NSLog("ReactNative loadWnfs called: rootCid=\(rootCid)")
476
+ if (self.fula != nil) {
477
+ try self.fula?.flush()
450
478
  }
451
- OSLog.viewCycle.info("ReactNative loadWnfs completed")
479
+ NSLog("ReactNative loadWnfs completed")
452
480
  try encryptAndStoreConfig()
453
481
  }
454
482
 
@@ -456,37 +484,38 @@ class FulaModule: NSObject {
456
484
  func encryptAndStoreConfig() throws {
457
485
  do {
458
486
  if let identityEncryptedGlobalUnwrapped = identityEncryptedGlobal {
459
- OSLog.viewCycle.info("ReactNative encryptAndStoreConfig started")
487
+ NSLog("ReactNative encryptAndStoreConfig started")
460
488
 
461
489
  if let rootCidUnwrapped = rootCid, let wnfsKeyUnwrapped = wnfsKey, let secretKeyGlobalUnwrapped = secretKeyGlobal {
462
- OSLog.viewCycle.info("ReactNative encryptAndStoreConfig started with rootCid: \(rootCidUnwrapped.toUint8Array()) and wnfsKey:\(wnfsKeyUnwrapped)")
490
+ NSLog("ReactNative encryptAndStoreConfig started with rootCid: \(rootCidUnwrapped.toUint8Array()) and wnfsKey:\(wnfsKeyUnwrapped)")
463
491
 
464
492
  let cid_encrypted = try Cryptography.encryptMsg(rootCidUnwrapped.toUint8Array(), secretKeyGlobalUnwrapped)
465
- OSLog.viewCycle.info("ReactNative encryptAndStoreConfig cid_encrypted: \(cid_encrypted)")
493
+ NSLog("ReactNative encryptAndStoreConfig cid_encrypted: \(cid_encrypted)")
466
494
 
467
495
  let wnfs_key_encrypted = try Cryptography.encryptMsg(wnfsKeyUnwrapped.toUint8Array(), secretKeyGlobalUnwrapped)
468
- OSLog.viewCycle.info("ReactNative encryptAndStoreConfig wnfs_key_encrypted: \(wnfs_key_encrypted)")
496
+ NSLog("ReactNative encryptAndStoreConfig wnfs_key_encrypted: \(wnfs_key_encrypted)")
469
497
 
470
498
  userDataHelper.add("cid_encrypted_" + identityEncryptedGlobalUnwrapped, cid_encrypted)
471
499
  userDataHelper.add("wnfs_key_encrypted_" + identityEncryptedGlobalUnwrapped, wnfs_key_encrypted)
472
500
  } else {
473
501
  // Handle the case where rootCid, wnfsKey, or secretKeyGlobal is nil
474
- OSLog.viewCycle.info("ReactNative encryptAndStoreConfig failed because one of the values is nil")
502
+ NSLog("ReactNative encryptAndStoreConfig failed because one of the values is nil")
475
503
  }
476
504
  }
477
505
  } catch let error {
478
- OSLog.viewCycle.info("ReactNative encryptAndStoreConfig failed with Error: \(error.localizedDescription)")
506
+ NSLog("ReactNative encryptAndStoreConfig failed with Error: \(error.localizedDescription)")
479
507
  throw error
480
508
  }
481
509
  }
482
510
 
483
511
  func logoutInternal(identity: Data, _storePath: String?) throws {
484
512
  do {
485
- if (fula != nil) {
486
- try fula?.flush()
513
+ if (self.fula != nil) {
514
+ try self.fula?.flush()
487
515
  }
488
516
  let secretKey = try Cryptography.generateKey(identity)
489
- let identity_encrypted: String = try Cryptography.encryptMsg(identity.toUint8Array(), secretKey)
517
+ let identity_encrypted: String = try Cryptography.encryptMsg(identity.toUint8Array(), [UInt8](secretKey))
518
+
490
519
  userDataHelper.remove("cid_encrypted_"+identity_encrypted)
491
520
 
492
521
  //TODO: Should also remove peerid @Mahdi
@@ -514,48 +543,59 @@ class FulaModule: NSObject {
514
543
  }
515
544
 
516
545
  func getFulaClient() -> FulamobileClient? {
517
- return fula
546
+ return self.fula
518
547
  }
519
548
 
520
- func newClientInternal(identity: Data, storePath: String?, bloxAddr: String, exchange: String, autoFlush: Bool, useRelay: Bool, refresh: Bool) throws -> Data {
549
+ func newClientInternal(identity: Data, storePath: String?, bloxAddr: String, exchange: String, autoFlush: Bool, useRelay: Bool, refresh: Bool) throws -> Void {
521
550
  do {
522
- OSLog.viewCycle.info("ReactNative fula newClientInternal refresh=\(refresh)")
551
+ NSLog("ReactNative fula newClientInternal refresh=\(refresh)")
523
552
  fulaConfig = FulamobileConfig()
524
- print("ReactNative", "cofig is set: ")
553
+ NSLog("ReactNative: cofig is set")
525
554
  if (storePath == nil || storePath!.isEmpty) {
526
555
  fulaConfig!.storePath = fulaStorePath
527
556
  } else {
528
557
  fulaConfig!.storePath = storePath!
529
558
  }
530
- print("ReactNative", "storePath is set: " + fulaConfig!.storePath)
559
+ NSLog("ReactNative storePath is set: \(fulaConfig!.storePath)")
531
560
 
532
561
  let peerIdentity = try createPeerIdentity(privateKey: identity)
533
562
  fulaConfig!.identity = peerIdentity
534
- print("ReactNative", "peerIdentity is set: " + fulaConfig!.identity!.toHex())
563
+ NSLog("ReactNative peerIdentity is set: \(fulaConfig!.identity!.toHex())")
535
564
  fulaConfig!.bloxAddr = bloxAddr
536
- print("ReactNative", "bloxAddr is set: " + fulaConfig!.bloxAddr)
565
+ NSLog("ReactNative bloxAddr is set: \(fulaConfig!.bloxAddr)")
537
566
  fulaConfig!.exchange = exchange
538
567
  fulaConfig!.syncWrites = autoFlush
539
568
  if (useRelay) {
540
569
  fulaConfig!.allowTransientConnection = true
541
570
  fulaConfig!.forceReachabilityPrivate = true
542
571
  }
543
- if (fula == nil || refresh) {
544
- print("ReactNative", "Creating a new Fula instance");
572
+ if (self.fula == nil || refresh) {
573
+ NSLog("ReactNative Creating a new Fula instance")
545
574
  do {
546
- try shutdownInternal();
547
- fula = FulamobileClient(fulaConfig)
548
- if (fula != nil) {
549
- try fula?.flush();
550
- }
575
+ try shutdownInternal()
576
+ NSLog("ReactNative Creating a new Fula instance shutdown done")
577
+ var error: NSError?
578
+ let client = FulamobileNewClient(fulaConfig, &error)
579
+ if let error = error {
580
+ throw error
581
+ }
582
+
583
+ self.fula = client
584
+ NSLog("ReactNative FulamobileClient created")
585
+ if (self.fula != nil) {
586
+ NSLog("ReactNative Creating a new Fula instance fula is not null, flushing")
587
+ try self.fula?.flush()
588
+ } else {
589
+ NSLog("** ReactNative Creating a new Fula instance fula failed **")
590
+ }
551
591
  } catch let error {
552
- print("ReactNative", "Failed to create new Fula instance: " , error.localizedDescription);
553
- throw MyError.runtimeError("Failed to create new Fula instance")
592
+ NSLog("ReactNative Failed to create new Fula instance: \(error.localizedDescription)")
593
+ throw MyError.runtimeError("ReactNative Failed to create new Fula instance")
554
594
  }
555
595
  }
556
- return peerIdentity
596
+ NSLog("ReactNative peerIdentity returned: \(peerIdentity)")
557
597
  } catch let error {
558
- print("ReactNative", "newclientInternal failed with Error: ", error.localizedDescription)
598
+ NSLog("ReactNative newclientInternal failed with Error: \(error.localizedDescription)")
559
599
  throw error
560
600
  }
561
601
  }
@@ -563,62 +603,79 @@ class FulaModule: NSObject {
563
603
  func initInternal(identity: Data, storePath: String, bloxAddr: String, exchange: String, autoFlush: Bool, _rootCid: String, useRelay: Bool, refresh: Bool) throws -> [String] {
564
604
 
565
605
  do {
566
- OSLog.viewCycle.info("ReactNative fula initInternal=\(refresh)")
567
- if (fula == nil || refresh) {
606
+ os_log("ReactNative: This is an info message.", log: OSLog.viewCycle, type: .info)
607
+ NSLog("ReactNative: This is a simple log message.")
608
+
609
+ NSLog("ReactNative fula initInternal=\(refresh)")
610
+ if (self.fula == nil || refresh) {
611
+ NSLog("ReactNative fula self.fula is null or refresh is set")
568
612
  try newClientInternal(identity: identity, storePath: storePath, bloxAddr: bloxAddr, exchange: exchange, autoFlush: autoFlush, useRelay: useRelay, refresh: refresh)
569
- OSLog.viewCycle.info("ReactNative fula initialized: \(self.fula!.id_())")
613
+ NSLog("ReactNative fula initialized")
614
+ if (self.fula == nil) {
615
+ NSLog("ReactNative: fula is not initialized")
616
+ }
617
+ guard let fulaId = self.fula?.id_() else {
618
+ NSLog("ReactNative error: fula is not initialized")
619
+ throw MyError.runtimeError("ReactNative: fula client not ready")
620
+ }
621
+ NSLog("ReactNative fula initialized: \(fulaId)")
570
622
  }
571
- if(client == nil || refresh) {
572
- client = Client(clientInput: fula!)
573
- wnfs = Wnfs(putFn: { cid, data in
623
+ if(self.client == nil || self.wnfs == nil || refresh) {
624
+ NSLog("ReactNative fula self.client is null or refresh is set")
625
+ self.client = Client(clientInput: self.fula!)
626
+ self.wnfs = Wnfs(putFn: { cid, data in
574
627
  guard let c = self.client else {
575
- throw MyError.runtimeError("wnfs: fula client not ready")
628
+ NSLog("ReactNative wnfs put: fula client not ready")
629
+ throw MyError.runtimeError("ReactNative wnfs: fula client not ready")
576
630
  }
577
631
  try c.put(cid, data)
578
632
  }, getFn: { cid in
579
633
  guard let c = self.client else {
580
- throw MyError.runtimeError("wnfs: fula client not ready")
634
+ NSLog("ReactNative wnfs get: fula client not ready")
635
+ throw MyError.runtimeError("ReactNative wnfs: fula client not ready")
581
636
  }
582
637
  return try c.get(cid)
583
638
  })
584
- OSLog.viewCycle.info("ReactNative wnfs initialized")
639
+ NSLog("ReactNative wnfs initialized")
585
640
  }
586
641
 
587
642
  let secretKey = try Cryptography.generateKey(identity)
588
- let identity_encrypted = try Cryptography.encryptMsg(identity.toUint8Array(), secretKey)
643
+ let identity_encrypted = try Cryptography.encryptMsg(identity.toUint8Array(), [UInt8](secretKey))
644
+
589
645
  identityEncryptedGlobal = identity_encrypted
590
- secretKeyGlobal = secretKey
646
+ secretKeyGlobal = [UInt8](secretKey)
591
647
 
592
648
  if (rootCid == nil || rootCid!.isEmpty) {
593
- OSLog.viewCycle.info("ReactNative rootCid is empty.")
649
+ NSLog("ReactNative rootCid is empty.")
594
650
  //Load from keystore
595
651
 
596
652
  let cid_encrypted_fetched = userDataHelper.getValue("cid_encrypted_"+identity_encrypted)
597
- OSLog.viewCycle.info("ReactNative Here1")
653
+ NSLog("ReactNative Here1")
598
654
  var cid: Array<UInt8>? = nil
599
655
  if(cid_encrypted_fetched != nil && !cid_encrypted_fetched!.isEmpty) {
600
- OSLog.viewCycle.info("ReactNative decrypting cid= \(cid_encrypted_fetched!) with secret \(secretKey.toHex())")
601
- cid = try Cryptography.decryptMsg(cid_encrypted_fetched!, secretKey)
656
+ NSLog("ReactNative decrypting cid= \(cid_encrypted_fetched!) with secret \(secretKey.toHex())")
657
+ cid = try Cryptography.decryptMsg(cid_encrypted_fetched!, [UInt8](secretKey))
658
+
602
659
  }
603
- print("ReactNative", "Here2")
660
+ NSLog("ReactNative Here2")
604
661
  //print("ReactNative", "Attempted to fetch cid from keystore cid="+cid+" & wnfs_key="+wnfs_key)
605
662
  if(cid == nil || cid!.isEmpty){
606
- OSLog.viewCycle.info("ReactNative cid or wnfs key was not found")
663
+ NSLog("ReactNative cid or wnfs key was not found")
607
664
  if(!_rootCid.isEmpty){
608
- OSLog.viewCycle.info("ReactNative Re-setting cid from input: \(_rootCid)")
665
+ NSLog("ReactNative Re-setting cid from input: \(_rootCid)")
609
666
  cid = _rootCid.toUint8Array()
610
667
  }
611
668
 
612
669
  }
613
670
  if(cid == nil || cid!.isEmpty){
614
- OSLog.viewCycle.info("ReactNative Tried to recover cid but was not successful. Creating ones")
671
+ NSLog("ReactNative Tried to recover cid but was not successful. Creating ones")
615
672
  try createNewrootCid(identity: identity)
616
673
  } else {
617
- OSLog.viewCycle.info("ReactNative Found cid and wnfs key in keychain store")
618
- OSLog.viewCycle.info("ReactNative Recovered cid and private ref from keychain store. cid=\(cid!) & wnfs_key=\(identity)")
674
+ NSLog("ReactNative Found cid and wnfs key in keychain store")
675
+ NSLog("ReactNative Recovered cid and private ref from keychain store. cid=\(cid!) & wnfs_key=\(identity)")
619
676
  try loadWnfs(identity, cid!.toData().toUTF8String()!)
620
677
  }
621
- OSLog.viewCycle.info("ReactNative creating/reloading rootCid completed")
678
+ NSLog("ReactNative creating/reloading rootCid completed")
622
679
 
623
680
  /*
624
681
  byte[] testbyte = convertStringToByte("-104,40,24,-93,24,100,24,114,24,111,24,111,24,116,24,-126,24,-126,0,0,24,-128,24,103,24,118,24,101,24,114,24,115,24,105,24,111,24,110,24,101,24,48,24,46,24,49,24,46,24,48,24,105,24,115,24,116,24,114,24,117,24,99,24,116,24,117,24,114,24,101,24,100,24,104,24,97,24,109,24,116")
@@ -631,22 +688,26 @@ class FulaModule: NSObject {
631
688
  */
632
689
 
633
690
 
634
- OSLog.viewCycle.info("ReactNative rootCid is created: cid=\(self.rootCid!) & wnfs_key=\(self.wnfsKey!.toHex())")
691
+ NSLog("ReactNative rootCid is created: cid=\(self.rootCid!) & wnfs_key=\(self.wnfsKey!.toHex())")
635
692
  } else {
636
- OSLog.viewCycle.info("ReactNative rootCid existed: cid=\(self.rootCid!) & wnfs_key=\(self.wnfsKey!.toHex())")
693
+ NSLog("ReactNative rootCid existed: cid=\(self.rootCid!) & wnfs_key=\(self.wnfsKey!.toHex())")
694
+ }
695
+ guard let peerId = self.fula?.id_() else {
696
+ NSLog("ReactNative error: fula is not initialized")
697
+ throw MyError.runtimeError("ReactNative: fula client not ready")
637
698
  }
638
- let peerId = fula!.id_()
699
+ NSLog("ReactNative fula peerId initialized: \(peerId)")
639
700
  var obj = [String]()
640
701
  obj.append(peerId)
641
702
  obj.append(rootCid!)
642
703
  obj.append(wnfsKey!.toHex())
643
- OSLog.viewCycle.info("ReactNative initInternal is completed successfully")
644
- if (fula != nil) {
645
- try fula?.flush()
704
+ NSLog("ReactNative initInternal is completed successfully")
705
+ if (self.fula != nil) {
706
+ try self.fula?.flush()
646
707
  }
647
708
  return obj
648
709
  } catch let error {
649
- OSLog.viewCycle.info("ReactNative init internal failed with Error: \(error.localizedDescription)")
710
+ NSLog("ReactNative init internal failed with Error: \(error.localizedDescription)")
650
711
  throw error
651
712
  }
652
713
  }
@@ -654,18 +715,18 @@ class FulaModule: NSObject {
654
715
 
655
716
  @objc(mkdir:withResolver:withRejecter:)
656
717
  func mkdir(path: String, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
657
- print("ReactNative", "mkdir: path = " + path)
718
+ NSLog("ReactNative mkdir: path = \(path)")
658
719
  do {
659
- let cid = try wnfs?.MkDir(cid: rootCid!, remotePath: path)
720
+ let cid = try self.wnfs?.MkDir(cid: rootCid!, remotePath: path)
660
721
  if(cid != nil) {
661
722
  rootCid = cid
662
723
  try encryptAndStoreConfig()
663
- if (fula != nil) {
664
- try fula?.flush()
724
+ if (self.fula != nil) {
725
+ try self.fula?.flush()
665
726
  }
666
727
  resolve(rootCid)
667
728
  } else {
668
- print("ReactNative", "mkdir Error: config is nil")
729
+ NSLog("ReactNative mkdir Error: config is nil")
669
730
  reject("ERR_WNFS", "Can't make dir", nil)
670
731
  }
671
732
 
@@ -684,18 +745,18 @@ class FulaModule: NSObject {
684
745
  // localFilename: a string containing full path and filename of local file on hte device (e.g /usr/bin/cat.jpg)
685
746
  // Returns: new cid of the root after this file is placed in the tree
686
747
  */
687
- print("ReactNative", "writeFile to : path = " + fulaTargetFilename + ", from: " + localFilename)
748
+ NSLog("ReactNative writeFile to : path = \(fulaTargetFilename) + from: \(localFilename)")
688
749
  do {
689
- let cid = try wnfs?.WriteFileFromPath(cid: rootCid!, remotePath: fulaTargetFilename, fileUrl: URL.init(string: localFilename)!)
750
+ let cid = try self.wnfs?.WriteFileFromPath(cid: rootCid!, remotePath: fulaTargetFilename, fileUrl: URL.init(string: localFilename)!)
690
751
  if(cid != nil) {
691
752
  rootCid = cid
692
753
  try encryptAndStoreConfig()
693
- if (fula != nil) {
694
- try fula?.flush()
754
+ if (self.fula != nil) {
755
+ try self.fula?.flush()
695
756
  }
696
757
  resolve(rootCid)
697
758
  } else {
698
- print("ReactNative", "writeFile Error: config is nil")
759
+ NSLog("ReactNative writeFile Error: config is nil")
699
760
  reject("ERR_WNFS", "writeFile Error: config is nil", nil)
700
761
  }
701
762
  } catch let error {
@@ -707,15 +768,15 @@ class FulaModule: NSObject {
707
768
  @objc(writeFileContent:withContentString:withResolver:withRejecter:)
708
769
  func writeFileContent(path: String, contentString: String, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
709
770
 
710
- print("ReactNative", "writeFile: contentString = " + contentString)
711
- print("ReactNative", "writeFile: path = " + path)
771
+ NSLog("ReactNative writeFile: contentString = \(contentString)")
772
+ NSLog("ReactNative writeFile: path = \(path)")
712
773
  do {
713
774
  let content = convertStringToByte(contentString)
714
- let cid = try wnfs?.WriteFile(cid: rootCid!, remotePath: path, data: content.toData())
775
+ let cid = try self.wnfs?.WriteFile(cid: rootCid!, remotePath: path, data: content.toData())
715
776
  rootCid = cid
716
777
  try encryptAndStoreConfig()
717
- if (fula != nil) {
718
- try fula?.flush()
778
+ if (self.fula != nil) {
779
+ try self.fula?.flush()
719
780
  }
720
781
  resolve(rootCid)
721
782
  } catch let error {
@@ -727,15 +788,15 @@ class FulaModule: NSObject {
727
788
 
728
789
  @objc(ls:withResolver:withRejecter:)
729
790
  func ls(path: String, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
730
- print("ReactNative", "ls: path = " + path)
791
+ NSLog("ReactNative ls: path = \(path)")
731
792
  do {
732
- let res = try wnfs?.Ls(cid: rootCid!, remotePath: path)
793
+ let res = try self.wnfs?.Ls(cid: rootCid!, remotePath: path)
733
794
 
734
795
  //JSONArray jsonArray = new JSONArray(res)
735
796
  guard let s = res?.toUTF8String() else {
736
- throw MyError.runtimeError("converting bytes to utf8 string")
797
+ throw MyError.runtimeError("ReactNative converting bytes to utf8 string")
737
798
  }
738
- print("ReactNative", "ls: res = " + s)
799
+ NSLog("ReactNative ls: res = \(s)")
739
800
  resolve(s)
740
801
  } catch let error {
741
802
  print("ls", error.localizedDescription)
@@ -749,12 +810,12 @@ class FulaModule: NSObject {
749
810
 
750
811
  print("ReactNative", "rm: path = " + path)
751
812
  do {
752
- let cid = try wnfs?.Rm(cid: rootCid!, remotePath: path)
813
+ let cid = try self.wnfs?.Rm(cid: rootCid!, remotePath: path)
753
814
  if(cid != nil) {
754
815
  rootCid = cid
755
816
  try encryptAndStoreConfig()
756
- if (fula != nil) {
757
- try fula?.flush()
817
+ if (self.fula != nil) {
818
+ try self.fula?.flush()
758
819
  }
759
820
  resolve(rootCid)
760
821
  } else {
@@ -773,12 +834,12 @@ class FulaModule: NSObject {
773
834
 
774
835
  print("ReactNative", "rm: sourcePath = " + sourcePath)
775
836
  do {
776
- let cid = try wnfs?.Cp(cid: rootCid!, remotePathFrom: sourcePath, remotePathTo: targetPath)
837
+ let cid = try self.wnfs?.Cp(cid: rootCid!, remotePathFrom: sourcePath, remotePathTo: targetPath)
777
838
  if(cid != nil) {
778
839
  rootCid = cid
779
840
  try encryptAndStoreConfig()
780
- if (fula != nil) {
781
- try fula?.flush()
841
+ if (self.fula != nil) {
842
+ try self.fula?.flush()
782
843
  }
783
844
  resolve(rootCid)
784
845
  } else {
@@ -796,12 +857,12 @@ class FulaModule: NSObject {
796
857
  func mv(sourcePath: String, targetPath: String, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
797
858
  print("ReactNative", "rm: sourcePath = " + sourcePath)
798
859
  do {
799
- let cid = try wnfs?.Mv(cid: rootCid!, remotePathFrom: sourcePath, remotePathTo: targetPath)
860
+ let cid = try self.wnfs?.Mv(cid: rootCid!, remotePathFrom: sourcePath, remotePathTo: targetPath)
800
861
  if(cid != nil) {
801
862
  rootCid = cid
802
863
  try encryptAndStoreConfig()
803
- if (fula != nil) {
804
- try fula?.flush()
864
+ if (self.fula != nil) {
865
+ try self.fula?.flush()
805
866
  }
806
867
  resolve(rootCid)
807
868
  } else {
@@ -826,7 +887,7 @@ class FulaModule: NSObject {
826
887
  */
827
888
  print("ReactNative", "readFile: fulaTargetFilename = " + fulaTargetFilename)
828
889
  do {
829
- let path = try wnfs?.ReadFileToPath(cid: rootCid!, remotePath: fulaTargetFilename, fileUrl: URL.init(string: localFilename)!)
890
+ let path = try self.wnfs?.ReadFileToPath(cid: rootCid!, remotePath: fulaTargetFilename, fileUrl: URL.init(string: localFilename)!)
830
891
  resolve(path)
831
892
  } catch let error {
832
893
  print("readFile", error.localizedDescription)
@@ -841,9 +902,9 @@ class FulaModule: NSObject {
841
902
  print("ReactNative", "readFileContent: path = " + path)
842
903
  do {
843
904
  // FIXME: dhouldn't we output an NSData object instead?
844
- let res = try wnfs?.ReadFile(cid: rootCid!, remotePath: path)
905
+ let res = try self.wnfs?.ReadFile(cid: rootCid!, remotePath: path)
845
906
  guard let resString = res?.toUTF8String() else{
846
- throw MyError.runtimeError("converting bytes to utf8 string")
907
+ throw MyError.runtimeError(" ReactNative converting bytes to utf8 string")
847
908
  }
848
909
  resolve(resString)
849
910
  } catch let error {
@@ -873,7 +934,7 @@ class FulaModule: NSObject {
873
934
  do {
874
935
  print("ReactNative", "getInternal: key.toUTF8String() = " , key.toUTF8String()!)
875
936
  print("ReactNative", "getInternal: key.toHex().bytes = " , key.toHex())
876
- let value = try fula!.get(key)
937
+ let value = try self.fula!.get(key)
877
938
  print("ReactNative", "getInternal: value.toHex() = " , value.toHex())
878
939
  return value
879
940
  } catch let error {
@@ -901,7 +962,7 @@ class FulaModule: NSObject {
901
962
  func hasInternal(_ key: Data) throws -> Bool {
902
963
  do {
903
964
  let ret = UnsafeMutablePointer<ObjCBool>.allocate(capacity: 1)
904
- try fula?.has(key, ret0_: ret)
965
+ try self.fula?.has(key, ret0_: ret)
905
966
  let res = ret.pointee.boolValue
906
967
  ret.deallocate()
907
968
  return res
@@ -913,7 +974,7 @@ class FulaModule: NSObject {
913
974
 
914
975
  func pullInternal(key: Data) throws -> Void {
915
976
  do {
916
- try fula!.pull(key)
977
+ try self.fula!.pull(key)
917
978
  } catch let error {
918
979
  print("pullInternal", error.localizedDescription)
919
980
  throw error
@@ -935,12 +996,12 @@ class FulaModule: NSObject {
935
996
  func pushInternal(key: Data) throws -> Void {
936
997
  do {
937
998
  let hasIt = try hasInternal(key)
938
- if (fula != nil && hasIt) {
939
- try fula?.push(key)
940
- try fula?.flush()
999
+ if (self.fula != nil && hasIt) {
1000
+ try self.fula?.push(key)
1001
+ try self.fula?.flush()
941
1002
  } else {
942
1003
  print("ReactNative", "pushInternal error: key wasn't found or fula is not initialized")
943
- throw MyError.runtimeError("pushInternal error: key wasn't found or fula is not initialized")
1004
+ throw MyError.runtimeError("ReactNative pushInternal error: key wasn't found or fula is not initialized")
944
1005
  }
945
1006
  } catch let error {
946
1007
  print("ReactNative", "pushInternal", error.localizedDescription)
@@ -976,13 +1037,13 @@ class FulaModule: NSObject {
976
1037
  // FIXME: unused codec arg
977
1038
  func putInternal(value: Data, codec: Int) throws -> Data {
978
1039
  do {
979
- if(fula != nil) {
980
- let key: Data = try fula!.put(value, codec: Int64(FulaModule.CODEC_DAG_CBOR))
981
- try fula?.flush()
1040
+ if(self.fula != nil) {
1041
+ let key: Data = try self.fula!.put(value, codec: Int64(FulaModule.CODEC_DAG_CBOR))
1042
+ try self.fula?.flush()
982
1043
  return key
983
1044
  } else {
984
1045
  print("ReactNative", "putInternal Error: fula is not initialized")
985
- throw MyError.runtimeError("putInternal Error: fula is not initialized")
1046
+ throw MyError.runtimeError("ReactNative putInternal Error: fula is not initialized")
986
1047
  }
987
1048
  } catch let error {
988
1049
  print("ReactNative", "putInternal", error.localizedDescription)
@@ -995,15 +1056,15 @@ class FulaModule: NSObject {
995
1056
 
996
1057
  print("ReactNative", "setAuth: peerIdString = " + peerIdString)
997
1058
  do {
998
- if (fula != nil && !(fula?.id_().isEmpty)! && fulaConfig != nil && !fulaConfig!.bloxAddr.isEmpty) {
1059
+ if (self.fula != nil && !(self.fula?.id_().isEmpty)! && fulaConfig != nil && !fulaConfig!.bloxAddr.isEmpty) {
999
1060
  let bloxAddr = fulaConfig!.bloxAddr
1000
1061
  print("ReactNative", "setAuth: bloxAddr = '",bloxAddr,"'"," peerIdString = '",peerIdString,"'")
1001
1062
  let parts = bloxAddr.split(separator: "/").map(String.init)
1002
- try fula?.setAuth(parts.last, subject: peerIdString, allow: allow)
1063
+ try self.fula?.setAuth(parts.last, subject: peerIdString, allow: allow)
1003
1064
  resolve(true)
1004
1065
  } else {
1005
1066
  print("ReactNative", "setAuth error: fula is not initialized")
1006
- throw MyError.runtimeError("fula is not initialized")
1067
+ throw MyError.runtimeError("ReactNative fula is not initialized")
1007
1068
  }
1008
1069
  resolve(false)
1009
1070
  } catch let error {
@@ -1018,14 +1079,14 @@ class FulaModule: NSObject {
1018
1079
  DispatchQueue.global(qos: .default).async {
1019
1080
  do {
1020
1081
  guard let fulaClient = self.fula else {
1021
- throw MyError.runtimeError("Fula client is not initialized")
1082
+ throw MyError.runtimeError("ReactNative Fula client is not initialized")
1022
1083
  }
1023
1084
 
1024
1085
  // Concatenate all CID strings into a single string separated by "|"
1025
1086
  let concatenatedCids = (cidArray as? [String])?.joined(separator: "|")
1026
1087
 
1027
1088
  guard let cidsData = concatenatedCids?.data(using: .utf8) else {
1028
- throw MyError.runtimeError("Unable to encode CIDs as data")
1089
+ throw MyError.runtimeError("ReactNative Unable to encode CIDs as data")
1029
1090
  }
1030
1091
 
1031
1092
  try fulaClient.clearCids(fromRecent: cidsData)
@@ -1043,7 +1104,7 @@ class FulaModule: NSObject {
1043
1104
  DispatchQueue.global(qos: .default).async {
1044
1105
  do {
1045
1106
  guard let fulaClient = self.fula else {
1046
- throw MyError.runtimeError("Fula client is not initialized")
1107
+ throw MyError.runtimeError("ReactNative Fula client is not initialized")
1047
1108
  }
1048
1109
 
1049
1110
  let recentLinksIterator = try fulaClient.listRecentCidsAsString()
@@ -1078,7 +1139,7 @@ class FulaModule: NSObject {
1078
1139
  DispatchQueue.global(qos: .default).async {
1079
1140
  do {
1080
1141
  guard let fulaClient = self.fula else {
1081
- throw MyError.runtimeError("Fula client is not initialized")
1142
+ throw MyError.runtimeError("ReactNative Fula client is not initialized")
1082
1143
  }
1083
1144
 
1084
1145
  let recentLinksIterator = try fulaClient.listRecentCidsAsStringWithChildren()
@@ -1113,7 +1174,7 @@ class FulaModule: NSObject {
1113
1174
  DispatchQueue.global(qos: .default).async {
1114
1175
  do {
1115
1176
  guard let fulaClient = self.fula else {
1116
- throw MyError.runtimeError("Fula client is not initialized")
1177
+ throw MyError.runtimeError("ReactNative Fula client is not initialized")
1117
1178
  }
1118
1179
  guard let poolID = Int64(poolIDStr) else {
1119
1180
  let error = NSError(domain: "FULAErrorDomain", code: 1001, userInfo: [NSLocalizedDescriptionKey: "Invalid poolID - not a valid number: \(poolIDStr)"])
@@ -1132,7 +1193,7 @@ class FulaModule: NSObject {
1132
1193
  let concatenatedCids = (cidArray as? [String])?.joined(separator: "|")
1133
1194
 
1134
1195
  guard let cidsData = concatenatedCids?.data(using: .utf8) else {
1135
- throw MyError.runtimeError("Unable to encode CIDs as data")
1196
+ throw MyError.runtimeError("ReactNative Unable to encode CIDs as data")
1136
1197
  }
1137
1198
 
1138
1199
  // Adjusted call to match the expected method signature and argument types
@@ -1153,18 +1214,21 @@ class FulaModule: NSObject {
1153
1214
  try shutdownInternal()
1154
1215
  resolve(true)
1155
1216
  } catch let error {
1156
- print("ReactNative", "shutdown", error.localizedDescription)
1217
+ NSLog("ReactNative shutdown \(error.localizedDescription)")
1157
1218
  reject("ERR_FULA", "shutdown", error)
1158
1219
  }
1159
1220
 
1160
1221
  }
1161
1222
 
1162
1223
  func shutdownInternal() throws {
1163
- if(fula != nil) {
1164
- try fula?.shutdown()
1165
- fula = nil
1166
- client = nil
1167
- wnfs = nil
1224
+ NSLog("ReactNative shutdownInternal")
1225
+ if(self.fula != nil) {
1226
+ NSLog("ReactNative shutdownInternal fula is not null")
1227
+ try self.fula?.shutdown()
1228
+ NSLog("ReactNative shutdownInternal fula.shutdown called")
1229
+ self.fula = nil
1230
+ self.client = nil
1231
+ self.wnfs = nil
1168
1232
  }
1169
1233
  }
1170
1234
 
@@ -1179,7 +1243,7 @@ class FulaModule: NSObject {
1179
1243
  func checkAccountExists(accountString: String, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
1180
1244
  print("ReactNative", "checkAccountExists: accountString = ", accountString)
1181
1245
  do {
1182
- let result = try fula!.accountExists(accountString)
1246
+ let result = try self.fula!.accountExists(accountString)
1183
1247
  let resultString = result.toUTF8String()!
1184
1248
  resolve(resultString)
1185
1249
  } catch let error {
@@ -1193,7 +1257,7 @@ class FulaModule: NSObject {
1193
1257
  func accountFund(accountString: String, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
1194
1258
  print("ReactNative", "accountFund: accountString = ", accountString)
1195
1259
  do {
1196
- let result = try fula!.accountFund(accountString)
1260
+ let result = try self.fula!.accountFund(accountString)
1197
1261
  let resultString = result.toUTF8String()!
1198
1262
  resolve(resultString)
1199
1263
  } catch let error {
@@ -1207,7 +1271,7 @@ class FulaModule: NSObject {
1207
1271
  func listPools( resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
1208
1272
  print("ReactNative", "listPools")
1209
1273
  do {
1210
- let result = try fula!.poolList()
1274
+ let result = try self.fula!.poolList()
1211
1275
  let resultString = result.toUTF8String()!
1212
1276
  resolve(resultString)
1213
1277
  } catch let error {
@@ -1223,7 +1287,7 @@ class FulaModule: NSObject {
1223
1287
  do {
1224
1288
  if let poolID = Int64(poolIDStr), let intPoolID = Int(exactly: poolID) {
1225
1289
  // Conversion to Int successful - use intPoolID
1226
- let result = try fula!.poolRequests(intPoolID)
1290
+ let result = try self.fula!.poolRequests(intPoolID)
1227
1291
  let resultString = result.toUTF8String()!
1228
1292
  resolve(resultString)
1229
1293
  } else {
@@ -1251,7 +1315,7 @@ class FulaModule: NSObject {
1251
1315
  reject("ERR_FULA", "Invalid poolID - not a valid number: \(poolIDStr)", error)
1252
1316
  return
1253
1317
  }
1254
- let result = try fula!.manifestAvailable(intPoolID)
1318
+ let result = try self.fula!.manifestAvailable(intPoolID)
1255
1319
  guard let resultString = result.toUTF8String() else {
1256
1320
  let error = NSError(domain: "FULAErrorDomain",
1257
1321
  code: 1005, // Use appropriate error code
@@ -1271,7 +1335,7 @@ class FulaModule: NSObject {
1271
1335
  func bloxFreeSpace( resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
1272
1336
  print("ReactNative", "bloxFreeSpace")
1273
1337
  do {
1274
- let result = try fula!.bloxFreeSpace()
1338
+ let result = try self.fula!.bloxFreeSpace()
1275
1339
  let resultString = result.toUTF8String()!
1276
1340
  resolve(resultString)
1277
1341
  } catch let error {
@@ -1300,7 +1364,7 @@ class FulaModule: NSObject {
1300
1364
  @objc(getAccount:withRejecter:)
1301
1365
  func getAccount(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
1302
1366
  do {
1303
- let account = try fula!.getAccount()
1367
+ let account = try self.fula!.getAccount()
1304
1368
  let accountString = String(data: account, encoding: .utf8)
1305
1369
  resolve(accountString)
1306
1370
  } catch let error {
@@ -1316,7 +1380,7 @@ class FulaModule: NSObject {
1316
1380
  }
1317
1381
 
1318
1382
  do {
1319
- let balance = try fula!.assetsBalance(account, assetId: assetIdInt, classId: classIdInt)
1383
+ let balance = try self.fula!.assetsBalance(account, assetId: assetIdInt, classId: classIdInt)
1320
1384
  let balanceString = String(data: balance, encoding: .utf8)
1321
1385
  resolve(balanceString)
1322
1386
  } catch let error {
@@ -1331,7 +1395,7 @@ class FulaModule: NSObject {
1331
1395
  guard let poolIdInt = Int(poolID) else {
1332
1396
  throw NSError(domain: "Invalid poolID", code: 0, userInfo: nil)
1333
1397
  }
1334
- let result = try fula!.poolJoin(poolIdInt)
1398
+ let result = try self.fula!.poolJoin(poolIdInt)
1335
1399
  let resultString = String(data: result, encoding: .utf8)
1336
1400
  resolve(resultString)
1337
1401
  } catch let error {
@@ -1345,7 +1409,7 @@ class FulaModule: NSObject {
1345
1409
  guard let poolIdInt = Int(poolID) else {
1346
1410
  throw NSError(domain: "Invalid poolID", code: 0, userInfo: nil)
1347
1411
  }
1348
- let result = try fula!.poolCancelJoin(poolIdInt)
1412
+ let result = try self.fula!.poolCancelJoin(poolIdInt)
1349
1413
  let resultString = String(data: result, encoding: .utf8)
1350
1414
  resolve(resultString)
1351
1415
  } catch let error {
@@ -1360,7 +1424,7 @@ class FulaModule: NSObject {
1360
1424
  guard let poolIdInt = Int(poolID) else {
1361
1425
  throw NSError(domain: "Invalid poolID", code: 0, userInfo: nil)
1362
1426
  }
1363
- let result = try fula!.poolLeave(poolIdInt)
1427
+ let result = try self.fula!.poolLeave(poolIdInt)
1364
1428
  let resultString = String(data: result, encoding: .utf8)
1365
1429
  resolve(resultString)
1366
1430
  } catch let error {
@@ -1372,7 +1436,7 @@ class FulaModule: NSObject {
1372
1436
  @objc(eraseBlData:withRejecter:)
1373
1437
  func eraseBlData(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
1374
1438
  do {
1375
- let result = try fula!.eraseBlData()
1439
+ let result = try self.fula!.eraseBlData()
1376
1440
  let resultString = String(data: result, encoding: .utf8)
1377
1441
  resolve(resultString)
1378
1442
  } catch let error {
@@ -1383,7 +1447,7 @@ class FulaModule: NSObject {
1383
1447
  @objc(reboot:withRejecter:)
1384
1448
  func reboot(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
1385
1449
  do {
1386
- let result = try fula!.reboot()
1450
+ let result = try self.fula!.reboot()
1387
1451
  let resultString = result.toUTF8String()!
1388
1452
  resolve(resultString)
1389
1453
  } catch let error {
@@ -1395,7 +1459,7 @@ class FulaModule: NSObject {
1395
1459
  @objc(partition:withRejecter:)
1396
1460
  func partition(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
1397
1461
  do {
1398
- let result = try fula!.partition()
1462
+ let result = try self.fula!.partition()
1399
1463
  let resultString = result.toUTF8String()!
1400
1464
  resolve(resultString)
1401
1465
  } catch let error {
@@ -1407,7 +1471,7 @@ class FulaModule: NSObject {
1407
1471
  @objc(wifiRemoveall:withRejecter:)
1408
1472
  func wifiRemoveall(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
1409
1473
  do {
1410
- let result = try fula!.wifiRemoveall()
1474
+ let result = try self.fula!.wifiRemoveall()
1411
1475
  let resultString = result.toUTF8String()!
1412
1476
  resolve(resultString)
1413
1477
  } catch let error {
@@ -1420,7 +1484,7 @@ class FulaModule: NSObject {
1420
1484
  func fetchContainerLogs(containerName: String, tailCount: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
1421
1485
  do {
1422
1486
  // Since fetchContainerLogs expects a String for tailCount, pass it directly
1423
- let result = try fula!.fetchContainerLogs(containerName, tailCount: tailCount)
1487
+ let result = try self.fula!.fetchContainerLogs(containerName, tailCount: tailCount)
1424
1488
  guard let resultString = result.toUTF8String() else {
1425
1489
  // Handle the case where result.toUTF8String() returns nil
1426
1490
  let error = NSError(domain: "FULAErrorDomain",
@@ -1441,7 +1505,7 @@ class FulaModule: NSObject {
1441
1505
  @objc(getFolderSize:withResolver:withRejecter:)
1442
1506
  func getFolderSize(folderPath: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
1443
1507
  do {
1444
- let result = try fula!.getFolderSize(folderPath)
1508
+ let result = try self.fula!.getFolderSize(folderPath)
1445
1509
  let resultString = result.toUTF8String()!
1446
1510
  resolve(resultString)
1447
1511
  } catch let error {
@@ -1450,19 +1514,33 @@ class FulaModule: NSObject {
1450
1514
  }
1451
1515
  }
1452
1516
 
1453
- @objc(getDatastoreSizeWithResolver:withRejecter:)
1454
- func getDatastoreSize(resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) -> Void {
1455
- do {
1456
- let result = try fula!.getDatastoreSize()
1457
- let resultString = result.toUTF8String()!
1458
- resolve(resultString)
1459
- } catch let error {
1460
- print("getDatastoreSize", error.localizedDescription)
1461
- let nsError = error as NSError
1462
- reject("ERR_FULA", "Failed to get datastore size", nsError)
1517
+ @objc
1518
+ func getDatastoreSize(_ resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
1519
+ DispatchQueue.global(qos: .background).async {
1520
+ // Safely unwrap `self.fula` using `guard let`
1521
+ guard let fulaClient = self.fula else {
1522
+ let error = NSError(domain: "FulaModuleError", code: 0, userInfo: [NSLocalizedDescriptionKey: "Fula client is not initialized"])
1523
+ DispatchQueue.main.async {
1524
+ reject("ERR_FULA_NOT_INITIALIZED", "Fula client is not initialized", error)
1525
+ }
1526
+ return
1527
+ }
1528
+
1529
+ do {
1530
+ let result = try fulaClient.getDatastoreSize()
1531
+ let resultString = String(decoding: result, as: UTF8.self)
1532
+ DispatchQueue.main.async {
1533
+ resolve(resultString)
1534
+ }
1535
+ } catch let error {
1536
+ DispatchQueue.main.async {
1537
+ reject("ERR_FULA", "Failed to get datastore size: \(error.localizedDescription)", error)
1538
+ }
1539
+ }
1463
1540
  }
1464
1541
  }
1465
1542
 
1543
+
1466
1544
  //Add Replicate In Pool (replicateInPool)
1467
1545
 
1468
1546
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@functionland/react-native-fula",
3
- "version": "1.54.9",
3
+ "version": "1.54.11",
4
4
  "description": "This package is a bridge to use the Fula libp2p protocols in the react-native which is using wnfs",
5
5
  "main": "lib/commonjs/index",
6
6
  "module": "lib/module/index",