@functionland/react-native-fula 1.35.0 → 1.36.0

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,1473 +1,1509 @@
1
- package land.fx.fula;
2
-
3
- import android.util.Log;
4
-
5
- import androidx.annotation.NonNull;
6
-
7
- import com.facebook.react.bridge.Promise;
8
- import com.facebook.react.bridge.ReactApplicationContext;
9
- import com.facebook.react.bridge.ReactContextBaseJavaModule;
10
- import com.facebook.react.bridge.ReactMethod;
11
- import com.facebook.react.bridge.WritableMap;
12
- import com.facebook.react.bridge.WritableNativeMap;
13
- import com.facebook.react.module.annotations.ReactModule;
14
- import com.facebook.react.bridge.Arguments;
15
- import com.facebook.react.bridge.WritableArray;
16
- import com.facebook.react.bridge.ReadableArray;
17
-
18
-
19
- import org.apache.commons.io.FileUtils;
20
- import org.jetbrains.annotations.Contract;
21
-
22
- import java.io.File;
23
- import java.io.IOException;
24
- import java.nio.charset.StandardCharsets;
25
- import java.security.GeneralSecurityException;
26
- import java.security.InvalidAlgorithmParameterException;
27
- import java.security.InvalidKeyException;
28
- import java.security.NoSuchAlgorithmException;
29
- import java.security.MessageDigest;
30
- import java.util.Arrays;
31
- import java.util.ArrayList;
32
-
33
- import javax.crypto.BadPaddingException;
34
- import javax.crypto.IllegalBlockSizeException;
35
- import javax.crypto.NoSuchPaddingException;
36
- import javax.crypto.SecretKey;
37
-
38
- import java.util.concurrent.Executors;
39
- import java.util.concurrent.ScheduledExecutorService;
40
- import java.util.concurrent.TimeUnit;
41
- import java.util.concurrent.atomic.AtomicBoolean;
42
- import java.util.concurrent.Future;
43
- import java.util.concurrent.TimeoutException;
44
-
45
- import fulamobile.Config;
46
- import fulamobile.Fulamobile;
47
-
48
- import land.fx.wnfslib.Fs;
49
-
50
- @ReactModule(name = FulaModule.NAME)
51
- public class FulaModule extends ReactContextBaseJavaModule {
52
-
53
-
54
- @Override
55
- public void initialize() {
56
- System.loadLibrary("wnfslib");
57
- System.loadLibrary("gojni");
58
- }
59
-
60
-
61
- public static final String NAME = "FulaModule";
62
- fulamobile.Client fula;
63
-
64
- Client client;
65
- Config fulaConfig;
66
-
67
- String appName;
68
- String appDir;
69
- String fulaStorePath;
70
- land.fx.wnfslib.Config rootConfig;
71
- SharedPreferenceHelper sharedPref;
72
- SecretKey secretKeyGlobal;
73
- String identityEncryptedGlobal;
74
- static String PRIVATE_KEY_STORE_PEERID = "PRIVATE_KEY";
75
-
76
- public static class Client implements land.fx.wnfslib.Datastore {
77
-
78
- private final fulamobile.Client internalClient;
79
-
80
- Client(fulamobile.Client clientInput) {
81
- this.internalClient = clientInput;
82
- }
83
-
84
- @NonNull
85
- @Override
86
- public byte[] get(@NonNull byte[] cid) {
87
- try {
88
- Log.d("ReactNative", Arrays.toString(cid));
89
- return this.internalClient.get(cid);
90
- } catch (Exception e) {
91
- e.printStackTrace();
92
- }
93
- Log.d("ReactNative","Error get");
94
- return cid;
95
- }
96
-
97
- @NonNull
98
- @Override
99
- public byte[] put(@NonNull byte[] cid, byte[] data) {
100
- try {
101
- long codec = (long)cid[1] & 0xFF;
102
- byte[] put_cid = this.internalClient.put(data, codec);
103
- //Log.d("ReactNative", "data="+ Arrays.toString(data) +" ;codec="+codec);
104
- return put_cid;
105
- } catch (Exception e) {
106
- Log.d("ReactNative", "put Error="+e.getMessage());
107
- e.printStackTrace();
108
- }
109
- Log.d("ReactNative","Error put");
110
- return data;
111
- }
112
- }
113
-
114
- public FulaModule(ReactApplicationContext reactContext) {
115
- super(reactContext);
116
- appName = reactContext.getPackageName();
117
- appDir = reactContext.getFilesDir().toString();
118
- fulaStorePath = appDir + "/fula";
119
- File storeDir = new File(fulaStorePath);
120
- sharedPref = SharedPreferenceHelper.getInstance(reactContext.getApplicationContext());
121
- boolean success = true;
122
- if (!storeDir.exists()) {
123
- success = storeDir.mkdirs();
124
- }
125
- if (success) {
126
- Log.d("ReactNative", "Fula store folder created for " + appName + " at " + fulaStorePath);
127
- } else {
128
- Log.d("ReactNative", "Unable to create fula store folder for " + appName + " at " + fulaStorePath);
129
- }
130
- }
131
-
132
- @Override
133
- @NonNull
134
- public java.lang.String getName() {
135
- return NAME;
136
- }
137
-
138
-
139
- private byte[] toByte(@NonNull String input) {
140
- return input.getBytes(StandardCharsets.UTF_8);
141
- }
142
-
143
- private byte[] decToByte(@NonNull String input) {
144
- String[] parts = input.split(",");
145
- byte[] output = new byte[parts.length];
146
- for (int i = 0; i < parts.length; i++) {
147
- output[i] = Byte.parseByte(parts[i]);
148
- }
149
- return output;
150
- }
151
-
152
- @NonNull
153
- @Contract("_ -> new")
154
- public String toString(byte[] input) {
155
- return new String(input, StandardCharsets.UTF_8);
156
- }
157
-
158
- @NonNull
159
- private static int[] stringArrToIntArr(@NonNull String[] s) {
160
- int[] result = new int[s.length];
161
- for (int i = 0; i < s.length; i++) {
162
- result[i] = Integer.parseInt(s[i]);
163
- }
164
- return result;
165
- }
166
-
167
- @NonNull
168
- @Contract(pure = true)
169
- private static byte[] convertIntToByte(@NonNull int[] input) {
170
- byte[] result = new byte[input.length];
171
- for (int i = 0; i < input.length; i++) {
172
- byte b = (byte) input[i];
173
- result[i] = b;
174
- }
175
- return result;
176
- }
177
-
178
- @NonNull
179
- private byte[] convertStringToByte(@NonNull String data) {
180
- String[] keyInt_S = data.split(",");
181
- int[] keyInt = stringArrToIntArr(keyInt_S);
182
-
183
- return convertIntToByte(keyInt);
184
- }
185
-
186
- @ReactMethod
187
- public void checkConnection(int timeout, Promise promise) {
188
- Log.d("ReactNative", "checkConnection started");
189
- ThreadUtils.runOnExecutor(() -> {
190
- if (this.fula != null) {
191
- try {
192
- boolean connectionStatus = this.checkConnectionInternal(timeout);
193
- Log.d("ReactNative", "checkConnection ended " + connectionStatus);
194
- promise.resolve(connectionStatus);
195
- }
196
- catch (Exception e) {
197
- Log.d("ReactNative", "checkConnection failed with Error: " + e.getMessage());
198
- promise.resolve(false);
199
- }
200
- } else {
201
- Log.d("ReactNative", "checkConnection failed with Error: " + "fula is null");
202
- promise.resolve(false);
203
- }
204
- });
205
- }
206
-
207
- @ReactMethod
208
- public void newClient(String identityString, String storePath, String bloxAddr, String exchange, boolean autoFlush, boolean useRelay, boolean refresh, Promise promise) {
209
- Log.d("ReactNative", "newClient started");
210
- ThreadUtils.runOnExecutor(() -> {
211
- try {
212
- Log.d("ReactNative", "newClient storePath= " + storePath + " bloxAddr= " + bloxAddr + " exchange= " + exchange + " autoFlush= " + autoFlush + " useRelay= " + useRelay + " refresh= " + refresh);
213
- byte[] identity = toByte(identityString);
214
- Log.d("ReactNative", "newClient identity= " + identityString);
215
- this.newClientInternal(identity, storePath, bloxAddr, exchange, autoFlush, useRelay, refresh);
216
- //String objString = Arrays.toString(obj);
217
- String peerId = this.fula.id();
218
- Log.d("ReactNative", "newClient peerId= " + peerId);
219
- promise.resolve(peerId);
220
- } catch (Exception e) {
221
- Log.d("ReactNative", "newClient failed with Error: " + e.getMessage());
222
- promise.reject("Error", e.getMessage());
223
- }
224
- });
225
- }
226
-
227
- @ReactMethod
228
- public void isReady(boolean filesystemCheck, Promise promise) {
229
- Log.d("ReactNative", "isReady started");
230
- ThreadUtils.runOnExecutor(() -> {
231
- boolean initialized = false;
232
- try {
233
- if (this.fula != null && this.fula.id() != null) {
234
- if (filesystemCheck) {
235
- if (this.client != null && this.rootConfig != null && !this.rootConfig.getCid().isEmpty()) {
236
- initialized = true;
237
- Log.d("ReactNative", "isReady is true with filesystem check");
238
- }
239
- } else {
240
- Log.d("ReactNative", "isReady is true without filesystem check");
241
- initialized = true;
242
- }
243
- }
244
- promise.resolve(initialized);
245
- } catch (Exception e) {
246
- Log.d("ReactNative", "isReady failed with Error: " + e.getMessage());
247
- promise.reject("Error", e.getMessage());
248
- }
249
- });
250
- }
251
-
252
- @ReactMethod
253
- public void initFula(String identityString, String storePath, String bloxAddr, String exchange, boolean autoFlush, String rootConfig, boolean useRelay, boolean refresh, Promise promise) {
254
- Log.d("ReactNative", "init started");
255
- ThreadUtils.runOnExecutor(() -> {
256
- try {
257
- WritableMap resultData = new WritableNativeMap();
258
- Log.d("ReactNative", "init storePath= " + storePath);
259
- byte[] identity = toByte(identityString);
260
- Log.d("ReactNative", "init identity= " + identityString);
261
- String[] obj = this.initInternal(identity, storePath, bloxAddr, exchange, autoFlush, rootConfig, useRelay, refresh);
262
- Log.d("ReactNative", "init object created: [ " + obj[0] + ", " + obj[1] + " ]");
263
- resultData.putString("peerId", obj[0]);
264
- resultData.putString("rootCid", obj[1]);
265
- promise.resolve(resultData);
266
- } catch (Exception e) {
267
- Log.d("ReactNative", "init failed with Error: " + e.getMessage());
268
- promise.reject("Error", e.getMessage());
269
- }
270
- });
271
- }
272
-
273
- @ReactMethod
274
- public void logout(String identityString, String storePath, Promise promise) {
275
- Log.d("ReactNative", "logout started");
276
- ThreadUtils.runOnExecutor(() -> {
277
- try {
278
- byte[] identity = toByte(identityString);
279
- boolean obj = this.logoutInternal(identity, storePath);
280
- Log.d("ReactNative", "logout completed");
281
- promise.resolve(obj);
282
- } catch (Exception e) {
283
- Log.d("ReactNative", "logout failed with Error: " + e.getMessage());
284
- promise.reject("Error", e.getMessage());
285
- }
286
- });
287
- }
288
-
289
- private boolean checkConnectionInternal(int timeout) throws Exception {
290
- try {
291
- Log.d("ReactNative", "checkConnectionInternal started");
292
- if (this.fula != null) {
293
- try {
294
- Log.d("ReactNative", "connectToBlox started");
295
-
296
- AtomicBoolean connectionStatus = new AtomicBoolean(false);
297
- ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
298
- Future<?> future = executor.submit(() -> {
299
- try {
300
- this.fula.connectToBlox();
301
- connectionStatus.set(true);
302
- Log.d("ReactNative", "checkConnectionInternal succeeded ");
303
- } catch (Exception e) {
304
- Log.d("ReactNative", "checkConnectionInternal failed with Error: " + e.getMessage());
305
- }
306
- });
307
-
308
- try {
309
- future.get(timeout, TimeUnit.SECONDS);
310
- } catch (TimeoutException te) {
311
- // If the timeout occurs, shut down the executor and return false
312
- executor.shutdownNow();
313
- return false;
314
- } finally {
315
- // If the future task is done, we can shut down the executor
316
- if (future.isDone()) {
317
- executor.shutdown();
318
- }
319
- }
320
-
321
- return connectionStatus.get();
322
- } catch (Exception e) {
323
- Log.d("ReactNative", "checkConnectionInternal failed with Error: " + e.getMessage());
324
- return false;
325
- }
326
- } else {
327
- Log.d("ReactNative", "checkConnectionInternal failed because fula is not initialized ");
328
- return false;
329
- }
330
- } catch (Exception e) {
331
- Log.d("ReactNative", "checkConnectionInternal failed with Error: " + e.getMessage());
332
- throw (e);
333
- }
334
- }
335
-
336
- @ReactMethod
337
- public void checkFailedActions(boolean retry, int timeout, Promise promise) throws Exception {
338
- try {
339
- if (this.fula != null) {
340
- if (!retry) {
341
- Log.d("ReactNative", "checkFailedActions without retry");
342
- fulamobile.LinkIterator failedLinks = this.fula.listFailedPushes();
343
- if (failedLinks.hasNext()) {
344
- Log.d("ReactNative", "checkFailedActions found: "+Arrays.toString(failedLinks.next()));
345
- promise.resolve(true);
346
- } else {
347
- promise.resolve(false);
348
- }
349
- } else {
350
- Log.d("ReactNative", "checkFailedActions with retry");
351
- boolean retryResults = this.retryFailedActionsInternal(timeout);
352
- promise.resolve(!retryResults);
353
- }
354
- } else {
355
- throw new Exception("Fula is not initialized");
356
- }
357
- } catch (Exception e) {
358
- Log.d("ReactNative", "checkFailedActions failed with Error: " + e.getMessage());
359
- throw (e);
360
- }
361
- }
362
-
363
- @ReactMethod
364
- private void listFailedActions(ReadableArray cids, Promise promise) throws Exception {
365
- try {
366
- if (this.fula != null) {
367
- Log.d("ReactNative", "listFailedActions");
368
- fulamobile.StringIterator failedLinks = this.fula.listFailedPushesAsString();
369
- ArrayList<String> failedLinksList = new ArrayList<>();
370
- while (failedLinks.hasNext()) {
371
- failedLinksList.add(failedLinks.next());
372
- }
373
- if (cids.size() > 0) {
374
- // If cids array is provided, filter the failedLinksList
375
- ArrayList<String> cidsList = new ArrayList<>();
376
- for (int i = 0; i < cids.size(); i++) {
377
- cidsList.add(cids.getString(i));
378
- }
379
- cidsList.retainAll(failedLinksList); // Keep only the elements in both cidsList and failedLinksList
380
- if (!cidsList.isEmpty()) {
381
- // If there are any matching cids, return them
382
- WritableArray cidsArray = Arguments.createArray();
383
- for (String cid : cidsList) {
384
- cidsArray.pushString(cid);
385
- }
386
- promise.resolve(cidsArray);
387
- } else {
388
- // If there are no matching cids, return false
389
- promise.resolve(false);
390
- }
391
- } else if (!failedLinksList.isEmpty()) {
392
- // If cids array is not provided, return the whole list
393
- Log.d("ReactNative", "listFailedActions found: "+ failedLinksList);
394
- WritableArray failedLinksArray = Arguments.createArray();
395
- for (String link : failedLinksList) {
396
- failedLinksArray.pushString(link);
397
- }
398
- promise.resolve(failedLinksArray);
399
- } else {
400
- promise.resolve(false);
401
- }
402
- } else {
403
- throw new Exception("listFailedActions: Fula is not initialized");
404
- }
405
- } catch (Exception e) {
406
- Log.d("ReactNative", "listFailedActions failed with Error: " + e.getMessage());
407
- throw (e);
408
- }
409
- }
410
-
411
-
412
-
413
-
414
- private boolean retryFailedActionsInternal(int timeout) throws Exception {
415
- try {
416
- Log.d("ReactNative", "retryFailedActionsInternal started");
417
- if (this.fula != null) {
418
- //Fula is initialized
419
- try {
420
- boolean connectionCheck = this.checkConnectionInternal(timeout);
421
- if(connectionCheck) {
422
- try {
423
- Log.d("ReactNative", "retryFailedPushes started");
424
- this.fula.retryFailedPushes();
425
- Log.d("ReactNative", "flush started");
426
- this.fula.flush();
427
- return true;
428
- }
429
- catch (Exception e) {
430
- this.fula.flush();
431
- Log.d("ReactNative", "retryFailedActionsInternal failed with Error: " + e.getMessage());
432
- return false;
433
- }
434
- //Blox online
435
- /*fulamobile.LinkIterator failedLinks = this.fula.listFailedPushes();
436
- if (failedLinks.hasNext()) {
437
- Log.d("ReactNative", "Failed links");
438
- //Failed list is not empty. iterate in the list
439
- while (failedLinks.hasNext()) {
440
- //Get the missing key
441
- byte[] failedNode = failedLinks.next();
442
- try {
443
- //Push to Blox
444
- Log.d("ReactNative", "Pushing Failed links "+Arrays.toString(failedNode));
445
- this.pushInternal(failedNode);
446
- Log.d("ReactNative", "Failed links pushed");
447
- }
448
- catch (Exception e) {
449
- Log.d("ReactNative", "retryFailedActionsInternal failed with Error: " + e.getMessage());
450
- }
451
- }
452
- //check if list is empty now and all are pushed
453
- Log.d("ReactNative", "Pushing finished");
454
- fulamobile.LinkIterator failedLinks_after = this.fula.listFailedPushes();
455
- if(failedLinks_after.hasNext()) {
456
- //Some pushes failed
457
- byte[] first_failed = failedLinks_after.next();
458
- Log.d("ReactNative", "Failed links are not empty "+Arrays.toString(first_failed));
459
- return false;
460
- } else {
461
- //All pushes successful
462
- return true;
463
- }
464
- } else {
465
- Log.d("ReactNative", "No Failed links");
466
- //Failed list is empty
467
- return true;
468
- }*/
469
- } else {
470
- Log.d("ReactNative", "retryFailedActionsInternal failed because blox is offline");
471
- //Blox Offline
472
- return false;
473
- }
474
- }
475
- catch (Exception e) {
476
- Log.d("ReactNative", "retryFailedActionsInternal failed with Error: " + e.getMessage());
477
- return false;
478
- }
479
- } else {
480
- Log.d("ReactNative", "retryFailedActionsInternal failed because fula is not initialized");
481
- //Fula is not initialized
482
- return false;
483
- }
484
- } catch (Exception e) {
485
- Log.d("ReactNative", "retryFailedActionsInternal failed with Error: " + e.getMessage());
486
- throw (e);
487
- }
488
- }
489
-
490
- @NonNull
491
- private byte[] createPeerIdentity(byte[] identity) throws GeneralSecurityException, IOException {
492
- try {
493
- // 1: First: create public key from provided private key
494
- // 2: Should read the local keychain store (if it is key-value, key is public key above,
495
- // 3: if found, decrypt using the private key
496
- // 4: If not found or decryption not successful, generate an identity
497
- // 5: then encrypt and store in keychain
498
- byte[] libp2pId;
499
- String encryptedLibp2pId = sharedPref.getValue(PRIVATE_KEY_STORE_PEERID);
500
- byte[] encryptionPair;
501
- SecretKey encryptionSecretKey;
502
- try {
503
- encryptionSecretKey = Cryptography.generateKey(identity);
504
- Log.d("ReactNative", "encryptionSecretKey generated from privateKey");
505
- } catch (Exception e) {
506
- Log.d("ReactNative", "Failed to generate key for encryption: " + e.getMessage());
507
- throw new GeneralSecurityException("Failed to generate key encryption", e);
508
- }
509
-
510
- if (encryptedLibp2pId == null || !encryptedLibp2pId.startsWith("FULA_" +
511
- "ENC_V4:")) {
512
- Log.d("ReactNative", "encryptedLibp2pId is not correct. creating new one " + encryptedLibp2pId);
513
-
514
- try {
515
- libp2pId = Fulamobile.generateEd25519KeyFromString(toString(identity));
516
- } catch (Exception e) {
517
- Log.d("ReactNative", "Failed to generate libp2pId: " + e.getMessage());
518
- throw new GeneralSecurityException("Failed to generate libp2pId", e);
519
- }
520
- encryptedLibp2pId = "FULA_ENC_V4:" + Cryptography.encryptMsg(StaticHelper.bytesToBase64(libp2pId), encryptionSecretKey, null);
521
- sharedPref.add(PRIVATE_KEY_STORE_PEERID, encryptedLibp2pId);
522
- } else {
523
- Log.d("ReactNative", "encryptedLibp2pId is correct. decrypting " + encryptedLibp2pId);
524
- }
525
-
526
- try {
527
- String decryptedLibp2pId = Cryptography.decryptMsg(encryptedLibp2pId.replace("FULA_ENC_V4:", ""), encryptionSecretKey);
528
-
529
- return StaticHelper.base64ToBytes(decryptedLibp2pId);
530
- } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException e) {
531
- Log.d("ReactNative", "createPeerIdentity decryptMsg failed with Error: " + e.getMessage());
532
- throw (e);
533
- }
534
-
535
- } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException e) {
536
- Log.d("ReactNative", "createPeerIdentity failed with Error: " + e.getMessage());
537
- throw (e);
538
- }
539
- }
540
-
541
- private void createNewRootConfig(FulaModule.Client iClient, byte[] identity) throws Exception {
542
- byte[] hash32 = getSHA256Hash(identity);
543
- this.rootConfig = Fs.init(iClient, hash32);
544
- Log.d("ReactNative", "rootConfig is created " + this.rootConfig.getCid());
545
- if (this.fula != null) {
546
- this.fula.flush();
547
- }
548
- this.encrypt_and_store_config();
549
- }
550
-
551
- public static byte[] getSHA256Hash(byte[] input) throws NoSuchAlgorithmException {
552
- MessageDigest md = MessageDigest.getInstance("SHA-256");
553
- return md.digest(input);
554
- }
555
-
556
- private static String bytesToHex(byte[] bytes) {
557
- StringBuilder result = new StringBuilder();
558
- for (byte b : bytes) {
559
- result.append(String.format("%02x", b));
560
- }
561
- return result.toString();
562
- }
563
-
564
- private void reloadFS(FulaModule.Client iClient, byte[] wnfsKey, String rootCid) throws Exception {
565
- Log.d("ReactNative", "reloadFS called: rootCid=" + rootCid);
566
- byte[] hash32 = getSHA256Hash(wnfsKey);
567
- Log.d("ReactNative", "wnfsKey=" + bytesToHex(wnfsKey) + "; hash32 = " + bytesToHex(hash32));
568
- Fs.loadWithWNFSKey(iClient, hash32, rootCid);
569
- Log.d("ReactNative", "reloadFS completed");
570
- }
571
-
572
- private boolean encrypt_and_store_config() throws Exception {
573
- try {
574
- if(this.identityEncryptedGlobal != null && !this.identityEncryptedGlobal.isEmpty()) {
575
- Log.d("ReactNative", "encrypt_and_store_config started");
576
-
577
- String cid_encrypted = Cryptography.encryptMsg(this.rootConfig.getCid(), this.secretKeyGlobal, null);
578
-
579
- sharedPref.add("FULA_ENC_V4:cid_encrypted_" + this.identityEncryptedGlobal, cid_encrypted);
580
- return true;
581
- } else {
582
- Log.d("ReactNative", "encrypt_and_store_config failed because identityEncryptedGlobal is empty");
583
- return false;
584
- }
585
- } catch (Exception e) {
586
- Log.d("ReactNative", "encrypt_and_store_config failed with Error: " + e.getMessage());
587
- throw (e);
588
- }
589
- }
590
-
591
- private boolean logoutInternal(byte[] identity, String storePath) throws Exception {
592
- try {
593
- if (this.fula != null) {
594
- this.fula.flush();
595
- }
596
- SecretKey secretKey = Cryptography.generateKey(identity);
597
- byte[] iv = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B };
598
- String identity_encrypted = Cryptography.encryptMsg(Arrays.toString(identity), secretKey, iv);
599
- sharedPref.remove("FULA_ENC_V4:cid_encrypted_"+ identity_encrypted);
600
-
601
- //TODO: Should also remove peerid @Mahdi
602
-
603
- sharedPref.remove("FULA_ENC_V4:cid_encrypted_"+ identity_encrypted);
604
-
605
- this.rootConfig = null;
606
- this.secretKeyGlobal = null;
607
- this.identityEncryptedGlobal = null;
608
-
609
- if (storePath == null || storePath.trim().isEmpty()) {
610
- storePath = this.fulaStorePath;
611
- }
612
-
613
- File file = new File(storePath);
614
- FileUtils.deleteDirectory(file);
615
- return true;
616
-
617
- } catch (Exception e) {
618
- Log.d("ReactNative", "logout internal failed with Error: " + e.getMessage());
619
- throw (e);
620
- }
621
- }
622
-
623
- public fulamobile.Client getFulaClient() {
624
- return this.fula;
625
- }
626
-
627
- @NonNull
628
- private byte[] newClientInternal(byte[] identity, String storePath, String bloxAddr, String exchange, boolean autoFlush, boolean useRelay, boolean refresh) throws GeneralSecurityException, IOException {
629
- byte[] peerIdentity = null;
630
- try {
631
- fulaConfig = new Config();
632
- if (storePath == null || storePath.trim().isEmpty()) {
633
- fulaConfig.setStorePath(this.fulaStorePath);
634
- } else {
635
- fulaConfig.setStorePath(storePath);
636
- }
637
- Log.d("ReactNative", "newClientInternal storePath is set: " + fulaConfig.getStorePath());
638
-
639
- peerIdentity = this.createPeerIdentity(identity);
640
- fulaConfig.setIdentity(peerIdentity);
641
- Log.d("ReactNative", "peerIdentity is set: " + toString(fulaConfig.getIdentity()));
642
- fulaConfig.setBloxAddr(bloxAddr);
643
- Log.d("ReactNative", "bloxAddr is set: " + fulaConfig.getBloxAddr());
644
- fulaConfig.setExchange(exchange);
645
- fulaConfig.setSyncWrites(autoFlush);
646
- if (useRelay) {
647
- fulaConfig.setAllowTransientConnection(true);
648
- fulaConfig.setForceReachabilityPrivate(true);
649
- }
650
- if (this.fula == null || refresh) {
651
- Log.d("ReactNative", "Creating a new Fula instance");
652
- try {
653
- shutdownInternal();
654
- Log.d("ReactNative", "Creating a new Fula instance with config");
655
- this.fula = Fulamobile.newClient(fulaConfig);
656
- if (this.fula != null) {
657
- this.fula.flush();
658
- }
659
- } catch (Exception e) {
660
- Log.d("ReactNative", "Failed to create new Fula instance: " + e.getMessage());
661
- throw new IOException("Failed to create new Fula instance", e);
662
- }
663
- }
664
- } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException e) {
665
- Log.d("ReactNative", "newclientInternal failed with Error: " + e.getMessage());
666
- throw (e);
667
- }
668
- return peerIdentity;
669
- }
670
-
671
-
672
- @NonNull
673
- private String[] initInternal(byte[] identity, String storePath, String bloxAddr, String exchange, boolean autoFlush, String rootCid, boolean useRelay, boolean refresh) throws Exception {
674
- try {
675
- if (this.fula == null || refresh) {
676
- this.newClientInternal(identity, storePath, bloxAddr, exchange, autoFlush, useRelay, refresh);
677
- }
678
- if(this.client == null || refresh) {
679
- this.client = new Client(this.fula);
680
- Log.d("ReactNative", "fula initialized: " + this.fula.id());
681
- }
682
-
683
- SecretKey secretKey = Cryptography.generateKey(identity);
684
- Log.d("ReactNative", "secretKey generated: " + secretKey.toString());
685
- byte[] iv = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B };
686
- String identity_encrypted =Cryptography.encryptMsg(Arrays.toString(identity), secretKey, iv);
687
- Log.d("ReactNative", "identity_encrypted generated: " + identity_encrypted + " for identity: " + Arrays.toString(identity));
688
- this.identityEncryptedGlobal = identity_encrypted;
689
- this.secretKeyGlobal = secretKey;
690
-
691
- if ( this.rootConfig == null || this.rootConfig.getCid().isEmpty() ) {
692
- Log.d("ReactNative", "this.rootCid is empty.");
693
- //Load from keystore
694
-
695
- String cid_encrypted_fetched = sharedPref.getValue("FULA_ENC_V4:cid_encrypted_"+ identity_encrypted);
696
- Log.d("ReactNative", "Here1");
697
- String cid = "";
698
- if(cid_encrypted_fetched != null && !cid_encrypted_fetched.isEmpty()) {
699
- Log.d("ReactNative", "decrypting cid="+cid_encrypted_fetched+" with secret="+secretKey.toString());
700
- cid = Cryptography.decryptMsg(cid_encrypted_fetched, secretKey);
701
- }
702
-
703
- Log.d("ReactNative", "Here2");
704
- //Log.d("ReactNative", "Attempted to fetch cid from keystore; cid="+cid);
705
- if(cid == null || cid.isEmpty()) {
706
- Log.d("ReactNative", "cid was not found");
707
- if(rootCid != null && !rootCid.isEmpty()){
708
- Log.d("ReactNative", "Re-setting cid from input: "+rootCid);
709
- cid = rootCid;
710
- this.rootConfig = new land.fx.wnfslib.Config(cid);
711
- this.reloadFS(this.client, identity, cid);
712
- this.encrypt_and_store_config();
713
- }
714
- if(cid == null || cid.isEmpty()) {
715
- Log.d("ReactNative", "Tried to recover cid but was not successful. Creating new ones");
716
- this.createNewRootConfig(this.client, identity);
717
- } else {
718
- this.rootConfig = new land.fx.wnfslib.Config(cid);
719
- this.reloadFS(this.client, identity, cid);
720
- this.encrypt_and_store_config();
721
- }
722
- } else {
723
- Log.d("ReactNative", "Recovered cid and private ref from keychain store. cid="+cid +" and cid from input was: "+rootCid);
724
- this.rootConfig = new land.fx.wnfslib.Config(cid);
725
- this.reloadFS(this.client, identity, cid);
726
- this.encrypt_and_store_config();
727
- }
728
-
729
- Log.d("ReactNative", "creating rootConfig completed");
730
-
731
- Log.d("ReactNative", "rootConfig is created: cid=" + this.rootConfig.getCid());
732
- } else {
733
- Log.d("ReactNative", "rootConfig existed: cid=" + this.rootConfig.getCid());
734
- }
735
- String peerId = this.fula.id();
736
- String[] obj = new String[2];
737
- obj[0] = peerId;
738
- obj[1] = this.rootConfig.getCid();
739
- Log.d("ReactNative", "initInternal is completed successfully");
740
- if (this.fula != null) {
741
- this.fula.flush();
742
- }
743
- return obj;
744
- } catch (Exception e) {
745
- Log.d("ReactNative", "init internal failed with Error: " + e.getMessage());
746
- throw (e);
747
- }
748
- }
749
-
750
- @ReactMethod
751
- public void mkdir(String path, Promise promise) {
752
- ThreadUtils.runOnExecutor(() -> {
753
- Log.d("ReactNative", "mkdir started with: path = " + path + " rootConfig.getCid() = " + this.rootConfig.getCid());
754
- try {
755
- land.fx.wnfslib.Config config = Fs.mkdir(this.client, this.rootConfig.getCid(), path);
756
- if(config != null) {
757
- this.rootConfig = config;
758
- this.encrypt_and_store_config();
759
- if (this.fula != null) {
760
- this.fula.flush();
761
- }
762
- String rootCid = this.rootConfig.getCid();
763
- Log.d("ReactNative", "mkdir completed successfully with rootCid = " + rootCid);
764
- promise.resolve(rootCid);
765
- } else {
766
- Log.d("ReactNative", "mkdir Error: config is null");
767
- promise.reject(new Exception("mkdir Error: config is null"));
768
- }
769
- } catch (Exception e) {
770
- Log.d("get", e.getMessage());
771
- promise.reject(e);
772
- }
773
- });
774
- }
775
-
776
- @ReactMethod
777
- public void writeFile(String fulaTargetFilename, String localFilename, Promise promise) {
778
- /*
779
- // reads content of the file form localFilename (should include full absolute path to local file with read permission
780
- // writes content to the specified location by fulaTargetFilename in Fula filesystem
781
- // fulaTargetFilename: a string including full path and filename of target file on Fula (e.g. root/pictures/cat.jpg)
782
- // localFilename: a string containing full path and filename of local file on hte device (e.g /usr/bin/cat.jpg)
783
- // Returns: new cid of the root after this file is placed in the tree
784
- */
785
- ThreadUtils.runOnExecutor(() -> {
786
- Log.d("ReactNative", "writeFile to : path = " + fulaTargetFilename + ", from: " + localFilename);
787
- try {
788
- if (this.client != null) {
789
- Log.d("ReactNative", "writeFileFromPath started: this.rootConfig.getCid=" + this.rootConfig.getCid()+ ", fulaTargetFilename="+fulaTargetFilename + ", localFilename="+localFilename);
790
- land.fx.wnfslib.Config config = Fs.writeFileStreamFromPath(this.client, this.rootConfig.getCid(), fulaTargetFilename, localFilename);
791
- if(config != null) {
792
- this.rootConfig = config;
793
- this.encrypt_and_store_config();
794
- if (this.fula != null) {
795
- this.fula.flush();
796
- String rootCid = this.rootConfig.getCid();
797
- Log.d("ReactNative", "writeFileFromPath completed: this.rootConfig.getCid=" + rootCid);
798
- promise.resolve(rootCid);
799
- } else {
800
- Log.d("ReactNative", "writeFile Error: fula is null");
801
- promise.reject(new Exception("writeFile Error: fula is null"));
802
- }
803
- } else {
804
- Log.d("ReactNative", "writeFile Error: config is null");
805
- promise.reject(new Exception("writeFile Error: config is null"));
806
- }
807
- } else {
808
- Log.d("ReactNative", "writeFile Error: client is null");
809
- promise.reject(new Exception("writeFile Error: client is null"));
810
- }
811
- } catch (Exception e) {
812
- Log.d("get", e.getMessage());
813
- promise.reject(e);
814
- }
815
- });
816
- }
817
-
818
- @ReactMethod
819
- public void writeFileContent(String path, String contentString, Promise promise) {
820
- ThreadUtils.runOnExecutor(() -> {
821
- Log.d("ReactNative", "writeFile: contentString = " + contentString);
822
- Log.d("ReactNative", "writeFile: path = " + path);
823
- try {
824
- byte[] content = this.convertStringToByte(contentString);
825
- land.fx.wnfslib.Config config = Fs.writeFile(this.client, this.rootConfig.getCid(), path, content);
826
- this.rootConfig = config;
827
- this.encrypt_and_store_config();
828
- if (this.fula != null) {
829
- this.fula.flush();
830
- }
831
- promise.resolve(config.getCid());
832
- } catch (Exception e) {
833
- Log.d("get", e.getMessage());
834
- promise.reject(e);
835
- }
836
- });
837
- }
838
-
839
- @ReactMethod
840
- public void ls(String path, Promise promise) {
841
- ThreadUtils.runOnExecutor(() -> {
842
- Log.d("ReactNative", "ls: path = " + path + "rootCid= " + this.rootConfig.getCid());
843
- try {
844
- byte[] res = Fs.ls(this.client, this.rootConfig.getCid(), path);
845
-
846
- String s = new String(res, StandardCharsets.UTF_8);
847
- Log.d("ReactNative", "ls: res = " + s);
848
- promise.resolve(s);
849
- } catch (Exception e) {
850
- Log.d("ReactNative", e.getMessage());
851
- promise.reject(e);
852
- }
853
- });
854
- }
855
-
856
- @ReactMethod
857
- public void rm(String path, Promise promise) {
858
- ThreadUtils.runOnExecutor(() -> {
859
- Log.d("ReactNative", "rm: path = " + path + ", beginning rootCid=" + this.rootConfig.getCid());
860
- try {
861
- land.fx.wnfslib.Config config = Fs.rm(this.client, this.rootConfig.getCid(), path);
862
- if(config != null) {
863
- this.rootConfig = config;
864
- this.encrypt_and_store_config();
865
- if (this.fula != null) {
866
- this.fula.flush();
867
- }
868
- String rootCid = config.getCid();
869
- Log.d("ReactNative", "rm: returned rootCid = " + rootCid);
870
- promise.resolve(rootCid);
871
- } else {
872
- Log.d("ReactNative", "rm Error: config is null");
873
- promise.reject(new Exception("rm Error: config is null"));
874
- }
875
- } catch (Exception e) {
876
- Log.d("ReactNative", e.getMessage());
877
- promise.reject(e);
878
- }
879
- });
880
- }
881
-
882
- @ReactMethod
883
- public void cp(String sourcePath, String targetPath, Promise promise) {
884
- ThreadUtils.runOnExecutor(() -> {
885
- Log.d("ReactNative", "rm: sourcePath = " + sourcePath);
886
- try {
887
- land.fx.wnfslib.Config config = Fs.cp(this.client, this.rootConfig.getCid(), sourcePath, targetPath);
888
- if(config != null) {
889
- this.rootConfig = config;
890
- this.encrypt_and_store_config();
891
- if (this.fula != null) {
892
- this.fula.flush();
893
- }
894
- promise.resolve(config.getCid());
895
- } else {
896
- Log.d("ReactNative", "cp Error: config is null");
897
- promise.reject(new Exception("cp Error: config is null"));
898
- }
899
- } catch (Exception e) {
900
- Log.d("ReactNative", e.getMessage());
901
- promise.reject(e);
902
- }
903
- });
904
- }
905
-
906
- @ReactMethod
907
- public void mv(String sourcePath, String targetPath, Promise promise) {
908
- ThreadUtils.runOnExecutor(() -> {
909
- Log.d("ReactNative", "rm: sourcePath = " + sourcePath);
910
- try {
911
- land.fx.wnfslib.Config config = Fs.mv(this.client, this.rootConfig.getCid(), sourcePath, targetPath);
912
- if(config != null) {
913
- this.rootConfig = config;
914
- this.encrypt_and_store_config();
915
- if (this.fula != null) {
916
- this.fula.flush();
917
- }
918
- promise.resolve(config.getCid());
919
- } else {
920
- Log.d("ReactNative", "mv Error: config is null");
921
- promise.reject(new Exception("mv Error: config is null"));
922
- }
923
- } catch (Exception e) {
924
- Log.d("ReactNative", e.getMessage());
925
- promise.reject(e);
926
- }
927
- });
928
- }
929
-
930
- @ReactMethod
931
- public void readFile(String fulaTargetFilename, String localFilename, Promise promise) {
932
- /*
933
- // reads content of the file form localFilename (should include full absolute path to local file with read permission
934
- // writes content to the specified location by fulaTargetFilename in Fula filesystem
935
- // fulaTargetFilename: a string including full path and filename of target file on Fula (e.g. root/pictures/cat.jpg)
936
- // localFilename: a string containing full path and filename of local file on hte device (e.g /usr/bin/cat.jpg)
937
- // Returns: new cid of the root after this file is placed in the tree
938
- */
939
- ThreadUtils.runOnExecutor(() -> {
940
- Log.d("ReactNative", "readFile: fulaTargetFilename = " + fulaTargetFilename);
941
- try {
942
- Log.d("ReactNative", "readFile: localFilename = " + localFilename + " fulaTargetFilename = " + fulaTargetFilename + " beginning rootCid = " + this.rootConfig.getCid());
943
- String path = Fs.readFilestreamToPath(this.client, this.rootConfig.getCid(), fulaTargetFilename, localFilename);
944
- promise.resolve(path);
945
- } catch (Exception e) {
946
- Log.d("ReactNative", e.getMessage());
947
- promise.reject(e);
948
- }
949
- });
950
- }
951
-
952
- @ReactMethod
953
- public void readFileContent(String path, Promise promise) {
954
- ThreadUtils.runOnExecutor(() -> {
955
- Log.d("ReactNative", "readFileContent: path = " + path);
956
- try {
957
- byte[] res = Fs.readFile(this.client, this.rootConfig.getCid(), path);
958
- String resString = toString(res);
959
- promise.resolve(resString);
960
- } catch (Exception e) {
961
- Log.d("ReactNative", e.getMessage());
962
- promise.reject(e);
963
- }
964
- });
965
- }
966
-
967
- @ReactMethod
968
- public void get(String keyString, Promise promise) {
969
- ThreadUtils.runOnExecutor(() -> {
970
- Log.d("ReactNative", "get: keyString = " + keyString);
971
- try {
972
- byte[] key = this.convertStringToByte(keyString);
973
- byte[] value = this.getInternal(key);
974
- String valueString = toString(value);
975
- promise.resolve(valueString);
976
- } catch (Exception e) {
977
- Log.d("ReactNative", e.getMessage());
978
- promise.reject(e);
979
- }
980
- });
981
- }
982
-
983
- @NonNull
984
- private byte[] getInternal(byte[] key) throws Exception {
985
- try {
986
- Log.d("ReactNative", "getInternal: key.toString() = " + toString(key));
987
- Log.d("ReactNative", "getInternal: key.toString().bytes = " + Arrays.toString(key));
988
- byte[] value = this.fula.get(key);
989
- Log.d("ReactNative", "getInternal: value.toString() = " + toString(value));
990
- return value;
991
- } catch (Exception e) {
992
- Log.d("ReactNative", "getInternal: error = " + e.getMessage());
993
- Log.d("getInternal", e.getMessage());
994
- throw (e);
995
- }
996
- }
997
-
998
- @ReactMethod
999
- public void has(String keyString, Promise promise) {
1000
- ThreadUtils.runOnExecutor(() -> {
1001
- Log.d("ReactNative", "has: keyString = " + keyString);
1002
- try {
1003
- byte[] key = this.convertStringToByte(keyString);
1004
- boolean result = this.hasInternal(key);
1005
- promise.resolve(result);
1006
- } catch (Exception e) {
1007
- Log.d("ReactNative", e.getMessage());
1008
- promise.reject(e);
1009
- }
1010
- });
1011
- }
1012
-
1013
- private boolean hasInternal(byte[] key) throws Exception {
1014
- try {
1015
- boolean res = this.fula.has(key);
1016
- return res;
1017
- } catch (Exception e) {
1018
- Log.d("ReactNative", e.getMessage());
1019
- throw (e);
1020
- }
1021
- }
1022
-
1023
- private void pullInternal(byte[] key) throws Exception {
1024
- try {
1025
- this.fula.pull(key);
1026
- } catch (Exception e) {
1027
- Log.d("ReactNative", e.getMessage());
1028
- throw (e);
1029
- }
1030
- }
1031
-
1032
- @ReactMethod
1033
- public void push(Promise promise) {
1034
- ThreadUtils.runOnExecutor(() -> {
1035
- Log.d("ReactNative", "push started");
1036
- try {
1037
- this.pushInternal(this.convertStringToByte(this.rootConfig.getCid()));
1038
- promise.resolve(this.rootConfig.getCid());
1039
- } catch (Exception e) {
1040
- Log.d("ReactNative", e.getMessage());
1041
- promise.reject(e);
1042
- }
1043
- });
1044
- }
1045
-
1046
- private void pushInternal(byte[] key) throws Exception {
1047
- try {
1048
- if (this.fula != null && this.fula.has(key)) {
1049
- this.fula.push(key);
1050
- this.fula.flush();
1051
- } else {
1052
- Log.d("ReactNative", "pushInternal error: key wasn't found or fula is not initialized");
1053
- throw new Exception("key wasn't found in local storage");
1054
- }
1055
- } catch (Exception e) {
1056
- Log.d("ReactNative", "pushInternal"+ e.getMessage());
1057
- throw (e);
1058
- }
1059
- }
1060
-
1061
- @ReactMethod
1062
- public void put(String valueString, String codecString, Promise promise) {
1063
- ThreadUtils.runOnExecutor(() -> {
1064
- Log.d("ReactNative", "put: codecString = " + codecString);
1065
- Log.d("ReactNative", "put: valueString = " + valueString);
1066
- try {
1067
- //byte[] codec = this.convertStringToByte(CodecString);
1068
- long codec = Long.parseLong(codecString);
1069
-
1070
-
1071
- Log.d("ReactNative", "put: codec = " + codec);
1072
- byte[] value = toByte(valueString);
1073
-
1074
- Log.d("ReactNative", "put: value.toString() = " + toString(value));
1075
- byte[] key = this.putInternal(value, codec);
1076
- Log.d("ReactNative", "put: key.toString() = " + toString(key));
1077
- promise.resolve(toString(key));
1078
- } catch (Exception e) {
1079
- Log.d("ReactNative", "put: error = " + e.getMessage());
1080
- promise.reject(e);
1081
- }
1082
- });
1083
- }
1084
-
1085
- @NonNull
1086
- private byte[] putInternal(byte[] value, long codec) throws Exception {
1087
- try {
1088
- if(this.fula != null) {
1089
- byte[] key = this.fula.put(value, codec);
1090
- this.fula.flush();
1091
- return key;
1092
- } else {
1093
- Log.d("ReactNative", "putInternal Error: fula is not initialized");
1094
- throw (new Exception("putInternal Error: fula is not initialized"));
1095
- }
1096
- } catch (Exception e) {
1097
- Log.d("ReactNative", "putInternal"+ e.getMessage());
1098
- throw (e);
1099
- }
1100
- }
1101
-
1102
- @ReactMethod
1103
- public void setAuth(String peerIdString, boolean allow, Promise promise) {
1104
- ThreadUtils.runOnExecutor(() -> {
1105
- Log.d("ReactNative", "setAuth: peerIdString = " + peerIdString);
1106
- try {
1107
- if (this.fula != null && this.fula.id() != null && this.fulaConfig != null && this.fulaConfig.getBloxAddr() != null) {
1108
- String bloxAddr = this.fulaConfig.getBloxAddr();
1109
- Log.d("ReactNative", "setAuth: bloxAddr = '" + bloxAddr+"'"+ " peerIdString = '" + peerIdString+"'");
1110
- int index = bloxAddr.lastIndexOf("/");
1111
- String bloxPeerId = bloxAddr.substring(index + 1);
1112
- this.fula.setAuth(bloxPeerId, peerIdString, allow);
1113
- promise.resolve(true);
1114
- } else {
1115
- Log.d("ReactNative", "setAuth error: fula is not initialized");
1116
- throw new Exception("fula is not initialized");
1117
- }
1118
- promise.resolve(false);
1119
- } catch (Exception e) {
1120
- Log.d("ReactNative", e.getMessage());
1121
- promise.reject(e);
1122
- }
1123
- });
1124
- }
1125
-
1126
- private void shutdownInternal() throws Exception {
1127
- try {
1128
- if(this.fula != null) {
1129
- this.fula.shutdown();
1130
- this.fula = null;
1131
- this.client = null;
1132
- Log.d("ReactNative", "shutdownInternal done");
1133
-
1134
- }
1135
- } catch (Exception e) {
1136
- Log.d("ReactNative", "shutdownInternal"+ e.getMessage());
1137
- throw (e);
1138
- }
1139
- }
1140
-
1141
- @ReactMethod
1142
- public void shutdown(Promise promise) {
1143
- ThreadUtils.runOnExecutor(() -> {
1144
- try {
1145
- shutdownInternal();
1146
- promise.resolve(true);
1147
- } catch (Exception e) {
1148
- promise.reject(e);
1149
- Log.d("ReactNative", "shutdown"+ e.getMessage());
1150
- }
1151
- });
1152
- }
1153
-
1154
- ///////////////////////////////////////////////////////////
1155
- ///////////////////////////////////////////////////////////
1156
- ///////////////////////////////////////////////////////////
1157
- ///////////////////////////////////////////////////////////
1158
- //////////////////////ANYTHING BELOW IS FOR BLOCKCHAIN/////
1159
- ///////////////////////////////////////////////////////////
1160
- @ReactMethod
1161
- public void getAccount(Promise promise) {
1162
- ThreadUtils.runOnExecutor(() -> {
1163
- Log.d("ReactNative", "getAccount called ");
1164
- try {
1165
- byte[] result = this.fula.getAccount();
1166
- String resultString = toString(result);
1167
- promise.resolve(resultString);
1168
- } catch (Exception e) {
1169
- Log.d("ReactNative", e.getMessage());
1170
- promise.reject(e);
1171
- }
1172
- });
1173
- }
1174
-
1175
- @ReactMethod
1176
- public void assetsBalance(String account, String assetId, String classId, Promise promise) {
1177
- ThreadUtils.runOnExecutor(() -> {
1178
- Log.d("ReactNative", "assetsBalance called ");
1179
- try {
1180
- byte[] result = this.fula.assetsBalance(account, assetId, classId);
1181
- String resultString = toString(result);
1182
- promise.resolve(resultString);
1183
- } catch (Exception e) {
1184
- Log.d("ReactNative", e.getMessage());
1185
- promise.reject(e);
1186
- }
1187
- });
1188
- }
1189
-
1190
- @ReactMethod
1191
- public void transferToFula(String amount, String wallet, String chain, Promise promise) {
1192
- ThreadUtils.runOnExecutor(() -> {
1193
- Log.d("ReactNative", "transferToFula called ");
1194
- try {
1195
- byte[] result = this.fula.transferToFula(amount, wallet, chain);
1196
- String resultString = toString(result);
1197
- promise.resolve(resultString);
1198
- } catch (Exception e) {
1199
- Log.d("ReactNative", e.getMessage());
1200
- promise.reject(e);
1201
- }
1202
- });
1203
- }
1204
-
1205
- @ReactMethod
1206
- public void checkAccountExists(String accountString, Promise promise) {
1207
- ThreadUtils.runOnExecutor(() -> {
1208
- Log.d("ReactNative", "checkAccountExists: accountString = " + accountString);
1209
- try {
1210
- byte[] result = this.fula.accountExists(accountString);
1211
- String resultString = toString(result);
1212
- promise.resolve(resultString);
1213
- } catch (Exception e) {
1214
- Log.d("ReactNative", e.getMessage());
1215
- promise.reject(e);
1216
- }
1217
- });
1218
- }
1219
-
1220
- @ReactMethod
1221
- public void listPools(Promise promise) {
1222
- ThreadUtils.runOnExecutor(() -> {
1223
- Log.d("ReactNative", "listPools");
1224
- try {
1225
- byte[] result = this.fula.poolList();
1226
- String resultString = toString(result);
1227
- promise.resolve(resultString);
1228
- } catch (Exception e) {
1229
- Log.d("ReactNative", e.getMessage());
1230
- promise.reject(e);
1231
- }
1232
- });
1233
- }
1234
-
1235
- @ReactMethod
1236
- public void joinPool(String poolID, Promise promise) {
1237
- ThreadUtils.runOnExecutor(() -> {
1238
- long poolIdLong = Long.parseLong(poolID);
1239
- Log.d("ReactNative", "joinPool: poolID = " + poolIdLong);
1240
- try {
1241
- byte[] result = this.fula.poolJoin(poolIdLong);
1242
- String resultString = toString(result);
1243
- promise.resolve(resultString);
1244
- } catch (Exception e) {
1245
- Log.d("ReactNative", e.getMessage());
1246
- promise.reject(e);
1247
- }
1248
- });
1249
- }
1250
-
1251
- @ReactMethod
1252
- public void cancelPoolJoin(long poolID, Promise promise) {
1253
- ThreadUtils.runOnExecutor(() -> {
1254
- Log.d("ReactNative", "cancelPoolJoin: poolID = " + poolID);
1255
- try {
1256
- byte[] result = this.fula.poolCancelJoin(poolID);
1257
- String resultString = toString(result);
1258
- promise.resolve(resultString);
1259
- } catch (Exception e) {
1260
- Log.d("ReactNative", e.getMessage());
1261
- promise.reject(e);
1262
- }
1263
- });
1264
- }
1265
-
1266
- @ReactMethod
1267
- public void listPoolJoinRequests(long poolID, Promise promise) {
1268
- ThreadUtils.runOnExecutor(() -> {
1269
- Log.d("ReactNative", "listPoolJoinRequests: poolID = " + poolID);
1270
- try {
1271
- byte[] result = this.fula.poolRequests(poolID);
1272
- String resultString = toString(result);
1273
- promise.resolve(resultString);
1274
- } catch (Exception e) {
1275
- Log.d("ReactNative", e.getMessage());
1276
- promise.reject(e);
1277
- }
1278
- });
1279
- }
1280
-
1281
- @ReactMethod
1282
- public void leavePool(long poolID, Promise promise) {
1283
- ThreadUtils.runOnExecutor(() -> {
1284
- Log.d("ReactNative", "leavePool: poolID = " + poolID);
1285
- try {
1286
- byte[] result = this.fula.poolLeave(poolID);
1287
- String resultString = toString(result);
1288
- promise.resolve(resultString);
1289
- } catch (Exception e) {
1290
- Log.d("ReactNative", e.getMessage());
1291
- promise.reject(e);
1292
- }
1293
- });
1294
- }
1295
-
1296
- @ReactMethod
1297
- public void listAvailableReplicationRequests(long poolID, Promise promise) {
1298
- ThreadUtils.runOnExecutor(() -> {
1299
- Log.d("ReactNative", "listAvailableReplicationRequests: poolID = " + poolID);
1300
- try {
1301
- byte[] result = this.fula.manifestAvailable(poolID);
1302
- String resultString = toString(result);
1303
- promise.resolve(resultString);
1304
- } catch (Exception e) {
1305
- Log.d("ReactNative", e.getMessage());
1306
- promise.reject(e);
1307
- }
1308
- });
1309
- }
1310
-
1311
- @ReactMethod
1312
- private void listRecentCidsAsString(Promise promise) throws Exception {
1313
- ThreadUtils.runOnExecutor(() -> {
1314
- try {
1315
- if (this.fula != null) {
1316
- Log.d("ReactNative", "ListRecentCidsAsString");
1317
- fulamobile.StringIterator recentLinks = this.fula.listRecentCidsAsString();
1318
- ArrayList<String> recentLinksList = new ArrayList<>();
1319
- while (recentLinks.hasNext()) {
1320
- recentLinksList.add(recentLinks.next());
1321
- }
1322
- if (!recentLinksList.isEmpty()) {
1323
- // return the whole list
1324
- Log.d("ReactNative", "ListRecentCidsAsString found: "+ recentLinksList);
1325
- WritableArray recentLinksArray = Arguments.createArray();
1326
- for (String link : recentLinksList) {
1327
- recentLinksArray.pushString(link);
1328
- }
1329
- promise.resolve(recentLinksArray);
1330
- } else {
1331
- promise.resolve(false);
1332
- }
1333
- } else {
1334
- throw new Exception("ListRecentCidsAsString: Fula is not initialized");
1335
- }
1336
- } catch (Exception e) {
1337
- Log.d("ReactNative", "ListRecentCidsAsString failed with Error: " + e.getMessage());
1338
- try {
1339
- throw (e);
1340
- } catch (Exception ex) {
1341
- throw new RuntimeException(ex);
1342
- }
1343
- }
1344
- });
1345
- }
1346
-
1347
- @ReactMethod
1348
- public void clearCidsFromRecent(ReadableArray cidArray, Promise promise) {
1349
- ThreadUtils.runOnExecutor(() -> {
1350
- try {
1351
- if (this.fula != null) {
1352
- StringBuilder cidStrBuilder = new StringBuilder();
1353
- for (int i = 0; i < cidArray.size(); i++) {
1354
- if (i > 0) {
1355
- cidStrBuilder.append("|");
1356
- }
1357
- cidStrBuilder.append(cidArray.getString(i));
1358
- }
1359
-
1360
- byte[] cidsBytes = cidStrBuilder.toString().getBytes(StandardCharsets.UTF_8);
1361
- this.fula.clearCidsFromRecent(cidsBytes);
1362
- promise.resolve(true); // Indicate success
1363
- } else {
1364
- throw new Exception("clearCidsFromRecent: Fula is not initialized");
1365
- }
1366
- } catch (Exception e) {
1367
- Log.d("ReactNative", "clearCidsFromRecent failed with Error: " + e.getMessage());
1368
- promise.reject("Error", e.getMessage());
1369
- }
1370
- });
1371
- }
1372
-
1373
-
1374
- ////////////////////////////////////////////////////////////////
1375
- ///////////////// Blox Hardware Methods ////////////////////////
1376
- ////////////////////////////////////////////////////////////////
1377
-
1378
- @ReactMethod
1379
- public void bloxFreeSpace(Promise promise) {
1380
- ThreadUtils.runOnExecutor(() -> {
1381
- Log.d("ReactNative", "bloxFreeSpace");
1382
- try {
1383
- byte[] result = this.fula.bloxFreeSpace();
1384
- String resultString = toString(result);
1385
- Log.d("ReactNative", "result string="+resultString);
1386
- promise.resolve(resultString);
1387
- } catch (Exception e) {
1388
- Log.d("ReactNative", e.getMessage());
1389
- promise.reject(e);
1390
- }
1391
- });
1392
- }
1393
-
1394
- @ReactMethod
1395
- public void wifiRemoveall(Promise promise) {
1396
- ThreadUtils.runOnExecutor(() -> {
1397
- Log.d("ReactNative", "wifiRemoveall");
1398
- try {
1399
- byte[] result = this.fula.wifiRemoveall();
1400
- String resultString = toString(result);
1401
- Log.d("ReactNative", "result string="+resultString);
1402
- promise.resolve(resultString);
1403
- } catch (Exception e) {
1404
- Log.d("ReactNative", e.getMessage());
1405
- promise.reject(e);
1406
- }
1407
- });
1408
- }
1409
-
1410
- @ReactMethod
1411
- public void reboot(Promise promise) {
1412
- ThreadUtils.runOnExecutor(() -> {
1413
- Log.d("ReactNative", "reboot");
1414
- try {
1415
- byte[] result = this.fula.reboot();
1416
- String resultString = toString(result);
1417
- Log.d("ReactNative", "result string="+resultString);
1418
- promise.resolve(resultString);
1419
- } catch (Exception e) {
1420
- Log.d("ReactNative", e.getMessage());
1421
- promise.reject(e);
1422
- }
1423
- });
1424
- }
1425
-
1426
- @ReactMethod
1427
- public void eraseBlData(Promise promise) {
1428
- ThreadUtils.runOnExecutor(() -> {
1429
- Log.d("ReactNative", "eraseBlData");
1430
- try {
1431
- byte[] result = this.fula.eraseBlData();
1432
- String resultString = toString(result);
1433
- Log.d("ReactNative", "result string="+resultString);
1434
- promise.resolve(resultString);
1435
- } catch (Exception e) {
1436
- Log.d("ReactNative", e.getMessage());
1437
- promise.reject(e);
1438
- }
1439
- });
1440
- }
1441
-
1442
- @ReactMethod
1443
- public void testData(String identityString, String bloxAddr, Promise promise) {
1444
- try {
1445
- byte[] identity = toByte(identityString);
1446
- byte[] peerIdByte = this.newClientInternal(identity, "", bloxAddr, "", true, true, true);
1447
-
1448
- String peerIdReturned = Arrays.toString(peerIdByte);
1449
- Log.d("ReactNative", "newClient peerIdReturned= " + peerIdReturned);
1450
- String peerId = this.fula.id();
1451
- Log.d("ReactNative", "newClient peerId= " + peerId);
1452
- byte[] bytes = {1, 85, 18, 32, 11, -31, 75, -78, -109, 11, -111, 97, -47, -78, -22, 84, 39, -117, -64, -70, -91, 55, -23, -80, 116, -123, -97, -26, 126, -70, -76, 35, 54, -106, 55, -9};
1453
-
1454
- byte[] key = this.fula.put(bytes, 85);
1455
- Log.d("ReactNative", "testData put result string="+Arrays.toString(key));
1456
-
1457
- byte[] value = this.fula.get(key);
1458
- Log.d("ReactNative", "testData get result string="+Arrays.toString(value));
1459
-
1460
- this.fula.push(key);
1461
- //this.fula.flush();
1462
-
1463
- byte[] fetchedVal = this.fula.get(key);
1464
- this.fula.pull(key);
1465
-
1466
- promise.resolve(Arrays.toString(fetchedVal));
1467
- } catch (Exception e) {
1468
- Log.d("ReactNative", "ERROR:" + e.getMessage());
1469
- promise.reject(e);
1470
- }
1471
- }
1472
-
1473
- }
1
+ package land.fx.fula;
2
+
3
+ import android.util.Log;
4
+
5
+ import androidx.annotation.NonNull;
6
+
7
+ import com.facebook.react.bridge.Promise;
8
+ import com.facebook.react.bridge.ReactApplicationContext;
9
+ import com.facebook.react.bridge.ReactContextBaseJavaModule;
10
+ import com.facebook.react.bridge.ReactMethod;
11
+ import com.facebook.react.bridge.WritableMap;
12
+ import com.facebook.react.bridge.WritableNativeMap;
13
+ import com.facebook.react.module.annotations.ReactModule;
14
+ import com.facebook.react.bridge.Arguments;
15
+ import com.facebook.react.bridge.WritableArray;
16
+ import com.facebook.react.bridge.ReadableArray;
17
+
18
+
19
+ import org.apache.commons.io.FileUtils;
20
+ import org.jetbrains.annotations.Contract;
21
+
22
+ import java.io.File;
23
+ import java.io.IOException;
24
+ import java.nio.charset.StandardCharsets;
25
+ import java.security.GeneralSecurityException;
26
+ import java.security.InvalidAlgorithmParameterException;
27
+ import java.security.InvalidKeyException;
28
+ import java.security.NoSuchAlgorithmException;
29
+ import java.security.MessageDigest;
30
+ import java.util.Arrays;
31
+ import java.util.ArrayList;
32
+
33
+ import javax.crypto.BadPaddingException;
34
+ import javax.crypto.IllegalBlockSizeException;
35
+ import javax.crypto.NoSuchPaddingException;
36
+ import javax.crypto.SecretKey;
37
+
38
+ import java.util.concurrent.Executors;
39
+ import java.util.concurrent.ScheduledExecutorService;
40
+ import java.util.concurrent.TimeUnit;
41
+ import java.util.concurrent.atomic.AtomicBoolean;
42
+ import java.util.concurrent.Future;
43
+ import java.util.concurrent.TimeoutException;
44
+
45
+ import fulamobile.Config;
46
+ import fulamobile.Fulamobile;
47
+
48
+ import land.fx.wnfslib.Fs;
49
+
50
+ @ReactModule(name = FulaModule.NAME)
51
+ public class FulaModule extends ReactContextBaseJavaModule {
52
+
53
+
54
+ @Override
55
+ public void initialize() {
56
+ System.loadLibrary("wnfslib");
57
+ System.loadLibrary("gojni");
58
+ }
59
+
60
+
61
+ public static final String NAME = "FulaModule";
62
+ fulamobile.Client fula;
63
+
64
+ Client client;
65
+ Config fulaConfig;
66
+
67
+ String appName;
68
+ String appDir;
69
+ String fulaStorePath;
70
+ land.fx.wnfslib.Config rootConfig;
71
+ SharedPreferenceHelper sharedPref;
72
+ SecretKey secretKeyGlobal;
73
+ String identityEncryptedGlobal;
74
+ static String PRIVATE_KEY_STORE_PEERID = "PRIVATE_KEY";
75
+
76
+ public static class Client implements land.fx.wnfslib.Datastore {
77
+
78
+ private final fulamobile.Client internalClient;
79
+
80
+ Client(fulamobile.Client clientInput) {
81
+ this.internalClient = clientInput;
82
+ }
83
+
84
+ @NonNull
85
+ @Override
86
+ public byte[] get(@NonNull byte[] cid) {
87
+ try {
88
+ Log.d("ReactNative", Arrays.toString(cid));
89
+ return this.internalClient.get(cid);
90
+ } catch (Exception e) {
91
+ e.printStackTrace();
92
+ }
93
+ Log.d("ReactNative","Error get");
94
+ return cid;
95
+ }
96
+
97
+ @NonNull
98
+ @Override
99
+ public byte[] put(@NonNull byte[] cid, byte[] data) {
100
+ try {
101
+ long codec = (long)cid[1] & 0xFF;
102
+ byte[] put_cid = this.internalClient.put(data, codec);
103
+ //Log.d("ReactNative", "data="+ Arrays.toString(data) +" ;codec="+codec);
104
+ return put_cid;
105
+ } catch (Exception e) {
106
+ Log.d("ReactNative", "put Error="+e.getMessage());
107
+ e.printStackTrace();
108
+ }
109
+ Log.d("ReactNative","Error put");
110
+ return data;
111
+ }
112
+ }
113
+
114
+ public FulaModule(ReactApplicationContext reactContext) {
115
+ super(reactContext);
116
+ appName = reactContext.getPackageName();
117
+ appDir = reactContext.getFilesDir().toString();
118
+ fulaStorePath = appDir + "/fula";
119
+ File storeDir = new File(fulaStorePath);
120
+ sharedPref = SharedPreferenceHelper.getInstance(reactContext.getApplicationContext());
121
+ boolean success = true;
122
+ if (!storeDir.exists()) {
123
+ success = storeDir.mkdirs();
124
+ }
125
+ if (success) {
126
+ Log.d("ReactNative", "Fula store folder created for " + appName + " at " + fulaStorePath);
127
+ } else {
128
+ Log.d("ReactNative", "Unable to create fula store folder for " + appName + " at " + fulaStorePath);
129
+ }
130
+ }
131
+
132
+ @Override
133
+ @NonNull
134
+ public java.lang.String getName() {
135
+ return NAME;
136
+ }
137
+
138
+
139
+ private byte[] toByte(@NonNull String input) {
140
+ return input.getBytes(StandardCharsets.UTF_8);
141
+ }
142
+
143
+ private byte[] decToByte(@NonNull String input) {
144
+ String[] parts = input.split(",");
145
+ byte[] output = new byte[parts.length];
146
+ for (int i = 0; i < parts.length; i++) {
147
+ output[i] = Byte.parseByte(parts[i]);
148
+ }
149
+ return output;
150
+ }
151
+
152
+ @NonNull
153
+ @Contract("_ -> new")
154
+ public String toString(byte[] input) {
155
+ return new String(input, StandardCharsets.UTF_8);
156
+ }
157
+
158
+ @NonNull
159
+ private static int[] stringArrToIntArr(@NonNull String[] s) {
160
+ int[] result = new int[s.length];
161
+ for (int i = 0; i < s.length; i++) {
162
+ result[i] = Integer.parseInt(s[i]);
163
+ }
164
+ return result;
165
+ }
166
+
167
+ @NonNull
168
+ @Contract(pure = true)
169
+ private static byte[] convertIntToByte(@NonNull int[] input) {
170
+ byte[] result = new byte[input.length];
171
+ for (int i = 0; i < input.length; i++) {
172
+ byte b = (byte) input[i];
173
+ result[i] = b;
174
+ }
175
+ return result;
176
+ }
177
+
178
+ @NonNull
179
+ private byte[] convertStringToByte(@NonNull String data) {
180
+ String[] keyInt_S = data.split(",");
181
+ int[] keyInt = stringArrToIntArr(keyInt_S);
182
+
183
+ return convertIntToByte(keyInt);
184
+ }
185
+
186
+ @ReactMethod
187
+ public void checkConnection(int timeout, Promise promise) {
188
+ Log.d("ReactNative", "checkConnection started");
189
+ ThreadUtils.runOnExecutor(() -> {
190
+ if (this.fula != null) {
191
+ try {
192
+ boolean connectionStatus = this.checkConnectionInternal(timeout);
193
+ Log.d("ReactNative", "checkConnection ended " + connectionStatus);
194
+ promise.resolve(connectionStatus);
195
+ }
196
+ catch (Exception e) {
197
+ Log.d("ReactNative", "checkConnection failed with Error: " + e.getMessage());
198
+ promise.resolve(false);
199
+ }
200
+ } else {
201
+ Log.d("ReactNative", "checkConnection failed with Error: " + "fula is null");
202
+ promise.resolve(false);
203
+ }
204
+ });
205
+ }
206
+
207
+ @ReactMethod
208
+ public void newClient(String identityString, String storePath, String bloxAddr, String exchange, boolean autoFlush, boolean useRelay, boolean refresh, Promise promise) {
209
+ Log.d("ReactNative", "newClient started");
210
+ ThreadUtils.runOnExecutor(() -> {
211
+ try {
212
+ Log.d("ReactNative", "newClient storePath= " + storePath + " bloxAddr= " + bloxAddr + " exchange= " + exchange + " autoFlush= " + autoFlush + " useRelay= " + useRelay + " refresh= " + refresh);
213
+ byte[] identity = toByte(identityString);
214
+ Log.d("ReactNative", "newClient identity= " + identityString);
215
+ this.newClientInternal(identity, storePath, bloxAddr, exchange, autoFlush, useRelay, refresh);
216
+ //String objString = Arrays.toString(obj);
217
+ String peerId = this.fula.id();
218
+ Log.d("ReactNative", "newClient peerId= " + peerId);
219
+ promise.resolve(peerId);
220
+ } catch (Exception e) {
221
+ Log.d("ReactNative", "newClient failed with Error: " + e.getMessage());
222
+ promise.reject("Error", e.getMessage());
223
+ }
224
+ });
225
+ }
226
+
227
+ @ReactMethod
228
+ public void isReady(boolean filesystemCheck, Promise promise) {
229
+ Log.d("ReactNative", "isReady started");
230
+ ThreadUtils.runOnExecutor(() -> {
231
+ boolean initialized = false;
232
+ try {
233
+ if (this.fula != null && this.fula.id() != null) {
234
+ if (filesystemCheck) {
235
+ if (this.client != null && this.rootConfig != null && !this.rootConfig.getCid().isEmpty()) {
236
+ initialized = true;
237
+ Log.d("ReactNative", "isReady is true with filesystem check");
238
+ }
239
+ } else {
240
+ Log.d("ReactNative", "isReady is true without filesystem check");
241
+ initialized = true;
242
+ }
243
+ }
244
+ promise.resolve(initialized);
245
+ } catch (Exception e) {
246
+ Log.d("ReactNative", "isReady failed with Error: " + e.getMessage());
247
+ promise.reject("Error", e.getMessage());
248
+ }
249
+ });
250
+ }
251
+
252
+ @ReactMethod
253
+ public void initFula(String identityString, String storePath, String bloxAddr, String exchange, boolean autoFlush, String rootConfig, boolean useRelay, boolean refresh, Promise promise) {
254
+ Log.d("ReactNative", "init started");
255
+ ThreadUtils.runOnExecutor(() -> {
256
+ try {
257
+ WritableMap resultData = new WritableNativeMap();
258
+ Log.d("ReactNative", "init storePath= " + storePath);
259
+ byte[] identity = toByte(identityString);
260
+ Log.d("ReactNative", "init identity= " + identityString);
261
+ String[] obj = this.initInternal(identity, storePath, bloxAddr, exchange, autoFlush, rootConfig, useRelay, refresh);
262
+ Log.d("ReactNative", "init object created: [ " + obj[0] + ", " + obj[1] + " ]");
263
+ resultData.putString("peerId", obj[0]);
264
+ resultData.putString("rootCid", obj[1]);
265
+ promise.resolve(resultData);
266
+ } catch (Exception e) {
267
+ Log.d("ReactNative", "init failed with Error: " + e.getMessage());
268
+ promise.reject("Error", e.getMessage());
269
+ }
270
+ });
271
+ }
272
+
273
+ @ReactMethod
274
+ public void logout(String identityString, String storePath, Promise promise) {
275
+ Log.d("ReactNative", "logout started");
276
+ ThreadUtils.runOnExecutor(() -> {
277
+ try {
278
+ byte[] identity = toByte(identityString);
279
+ boolean obj = this.logoutInternal(identity, storePath);
280
+ Log.d("ReactNative", "logout completed");
281
+ promise.resolve(obj);
282
+ } catch (Exception e) {
283
+ Log.d("ReactNative", "logout failed with Error: " + e.getMessage());
284
+ promise.reject("Error", e.getMessage());
285
+ }
286
+ });
287
+ }
288
+
289
+ private boolean checkConnectionInternal(int timeout) throws Exception {
290
+ try {
291
+ Log.d("ReactNative", "checkConnectionInternal started");
292
+ if (this.fula != null) {
293
+ try {
294
+ Log.d("ReactNative", "connectToBlox started");
295
+
296
+ AtomicBoolean connectionStatus = new AtomicBoolean(false);
297
+ ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
298
+ Future<?> future = executor.submit(() -> {
299
+ try {
300
+ this.fula.connectToBlox();
301
+ connectionStatus.set(true);
302
+ Log.d("ReactNative", "checkConnectionInternal succeeded ");
303
+ } catch (Exception e) {
304
+ Log.d("ReactNative", "checkConnectionInternal failed with Error: " + e.getMessage());
305
+ }
306
+ });
307
+
308
+ try {
309
+ future.get(timeout, TimeUnit.SECONDS);
310
+ } catch (TimeoutException te) {
311
+ // If the timeout occurs, shut down the executor and return false
312
+ executor.shutdownNow();
313
+ return false;
314
+ } finally {
315
+ // If the future task is done, we can shut down the executor
316
+ if (future.isDone()) {
317
+ executor.shutdown();
318
+ }
319
+ }
320
+
321
+ return connectionStatus.get();
322
+ } catch (Exception e) {
323
+ Log.d("ReactNative", "checkConnectionInternal failed with Error: " + e.getMessage());
324
+ return false;
325
+ }
326
+ } else {
327
+ Log.d("ReactNative", "checkConnectionInternal failed because fula is not initialized ");
328
+ return false;
329
+ }
330
+ } catch (Exception e) {
331
+ Log.d("ReactNative", "checkConnectionInternal failed with Error: " + e.getMessage());
332
+ throw (e);
333
+ }
334
+ }
335
+
336
+ @ReactMethod
337
+ public void checkFailedActions(boolean retry, int timeout, Promise promise) throws Exception {
338
+ try {
339
+ if (this.fula != null) {
340
+ if (!retry) {
341
+ Log.d("ReactNative", "checkFailedActions without retry");
342
+ fulamobile.LinkIterator failedLinks = this.fula.listFailedPushes();
343
+ if (failedLinks.hasNext()) {
344
+ Log.d("ReactNative", "checkFailedActions found: "+Arrays.toString(failedLinks.next()));
345
+ promise.resolve(true);
346
+ } else {
347
+ promise.resolve(false);
348
+ }
349
+ } else {
350
+ Log.d("ReactNative", "checkFailedActions with retry");
351
+ boolean retryResults = this.retryFailedActionsInternal(timeout);
352
+ promise.resolve(!retryResults);
353
+ }
354
+ } else {
355
+ throw new Exception("Fula is not initialized");
356
+ }
357
+ } catch (Exception e) {
358
+ Log.d("ReactNative", "checkFailedActions failed with Error: " + e.getMessage());
359
+ throw (e);
360
+ }
361
+ }
362
+
363
+ @ReactMethod
364
+ private void listFailedActions(ReadableArray cids, Promise promise) throws Exception {
365
+ try {
366
+ if (this.fula != null) {
367
+ Log.d("ReactNative", "listFailedActions");
368
+ fulamobile.StringIterator failedLinks = this.fula.listFailedPushesAsString();
369
+ ArrayList<String> failedLinksList = new ArrayList<>();
370
+ while (failedLinks.hasNext()) {
371
+ failedLinksList.add(failedLinks.next());
372
+ }
373
+ if (cids.size() > 0) {
374
+ // If cids array is provided, filter the failedLinksList
375
+ ArrayList<String> cidsList = new ArrayList<>();
376
+ for (int i = 0; i < cids.size(); i++) {
377
+ cidsList.add(cids.getString(i));
378
+ }
379
+ cidsList.retainAll(failedLinksList); // Keep only the elements in both cidsList and failedLinksList
380
+ if (!cidsList.isEmpty()) {
381
+ // If there are any matching cids, return them
382
+ WritableArray cidsArray = Arguments.createArray();
383
+ for (String cid : cidsList) {
384
+ cidsArray.pushString(cid);
385
+ }
386
+ promise.resolve(cidsArray);
387
+ } else {
388
+ // If there are no matching cids, return false
389
+ promise.resolve(false);
390
+ }
391
+ } else if (!failedLinksList.isEmpty()) {
392
+ // If cids array is not provided, return the whole list
393
+ Log.d("ReactNative", "listFailedActions found: "+ failedLinksList);
394
+ WritableArray failedLinksArray = Arguments.createArray();
395
+ for (String link : failedLinksList) {
396
+ failedLinksArray.pushString(link);
397
+ }
398
+ promise.resolve(failedLinksArray);
399
+ } else {
400
+ promise.resolve(false);
401
+ }
402
+ } else {
403
+ throw new Exception("listFailedActions: Fula is not initialized");
404
+ }
405
+ } catch (Exception e) {
406
+ Log.d("ReactNative", "listFailedActions failed with Error: " + e.getMessage());
407
+ throw (e);
408
+ }
409
+ }
410
+
411
+
412
+
413
+
414
+ private boolean retryFailedActionsInternal(int timeout) throws Exception {
415
+ try {
416
+ Log.d("ReactNative", "retryFailedActionsInternal started");
417
+ if (this.fula != null) {
418
+ //Fula is initialized
419
+ try {
420
+ boolean connectionCheck = this.checkConnectionInternal(timeout);
421
+ if(connectionCheck) {
422
+ try {
423
+ Log.d("ReactNative", "retryFailedPushes started");
424
+ this.fula.retryFailedPushes();
425
+ Log.d("ReactNative", "flush started");
426
+ this.fula.flush();
427
+ return true;
428
+ }
429
+ catch (Exception e) {
430
+ this.fula.flush();
431
+ Log.d("ReactNative", "retryFailedActionsInternal failed with Error: " + e.getMessage());
432
+ return false;
433
+ }
434
+ //Blox online
435
+ /*fulamobile.LinkIterator failedLinks = this.fula.listFailedPushes();
436
+ if (failedLinks.hasNext()) {
437
+ Log.d("ReactNative", "Failed links");
438
+ //Failed list is not empty. iterate in the list
439
+ while (failedLinks.hasNext()) {
440
+ //Get the missing key
441
+ byte[] failedNode = failedLinks.next();
442
+ try {
443
+ //Push to Blox
444
+ Log.d("ReactNative", "Pushing Failed links "+Arrays.toString(failedNode));
445
+ this.pushInternal(failedNode);
446
+ Log.d("ReactNative", "Failed links pushed");
447
+ }
448
+ catch (Exception e) {
449
+ Log.d("ReactNative", "retryFailedActionsInternal failed with Error: " + e.getMessage());
450
+ }
451
+ }
452
+ //check if list is empty now and all are pushed
453
+ Log.d("ReactNative", "Pushing finished");
454
+ fulamobile.LinkIterator failedLinks_after = this.fula.listFailedPushes();
455
+ if(failedLinks_after.hasNext()) {
456
+ //Some pushes failed
457
+ byte[] first_failed = failedLinks_after.next();
458
+ Log.d("ReactNative", "Failed links are not empty "+Arrays.toString(first_failed));
459
+ return false;
460
+ } else {
461
+ //All pushes successful
462
+ return true;
463
+ }
464
+ } else {
465
+ Log.d("ReactNative", "No Failed links");
466
+ //Failed list is empty
467
+ return true;
468
+ }*/
469
+ } else {
470
+ Log.d("ReactNative", "retryFailedActionsInternal failed because blox is offline");
471
+ //Blox Offline
472
+ return false;
473
+ }
474
+ }
475
+ catch (Exception e) {
476
+ Log.d("ReactNative", "retryFailedActionsInternal failed with Error: " + e.getMessage());
477
+ return false;
478
+ }
479
+ } else {
480
+ Log.d("ReactNative", "retryFailedActionsInternal failed because fula is not initialized");
481
+ //Fula is not initialized
482
+ return false;
483
+ }
484
+ } catch (Exception e) {
485
+ Log.d("ReactNative", "retryFailedActionsInternal failed with Error: " + e.getMessage());
486
+ throw (e);
487
+ }
488
+ }
489
+
490
+ @NonNull
491
+ private byte[] createPeerIdentity(byte[] identity) throws GeneralSecurityException, IOException {
492
+ try {
493
+ // 1: First: create public key from provided private key
494
+ // 2: Should read the local keychain store (if it is key-value, key is public key above,
495
+ // 3: if found, decrypt using the private key
496
+ // 4: If not found or decryption not successful, generate an identity
497
+ // 5: then encrypt and store in keychain
498
+ byte[] libp2pId;
499
+ String encryptedLibp2pId = sharedPref.getValue(PRIVATE_KEY_STORE_PEERID);
500
+ byte[] encryptionPair;
501
+ SecretKey encryptionSecretKey;
502
+ try {
503
+ encryptionSecretKey = Cryptography.generateKey(identity);
504
+ Log.d("ReactNative", "encryptionSecretKey generated from privateKey");
505
+ } catch (Exception e) {
506
+ Log.d("ReactNative", "Failed to generate key for encryption: " + e.getMessage());
507
+ throw new GeneralSecurityException("Failed to generate key encryption", e);
508
+ }
509
+
510
+ if (encryptedLibp2pId == null || !encryptedLibp2pId.startsWith("FULA_" +
511
+ "ENC_V4:")) {
512
+ Log.d("ReactNative", "encryptedLibp2pId is not correct or empty. creating new one " + encryptedLibp2pId);
513
+ encryptedLibp2pId = createEncryptedLibp2pId(identity, encryptionSecretKey);
514
+ } else {
515
+ Log.d("ReactNative", "encryptedLibp2pId is correct. decrypting " + encryptedLibp2pId);
516
+ }
517
+
518
+ try {
519
+ String decryptedLibp2pId = decryptLibp2pIdentity(encryptedLibp2pId, encryptionSecretKey);
520
+ return StaticHelper.base64ToBytes(decryptedLibp2pId);
521
+ } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException e) {
522
+ Log.d("ReactNative", "createPeerIdentity decryptMsg failed with Error: " + e.getMessage());
523
+ Log.d("ReactNative", "creating new encrpyted identity");
524
+ try {
525
+ encryptedLibp2pId = createEncryptedLibp2pId(identity, encryptionSecretKey);
526
+ String decryptedLibp2pId = decryptLibp2pIdentity(encryptedLibp2pId, encryptionSecretKey);
527
+ return StaticHelper.base64ToBytes(decryptedLibp2pId);
528
+ } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException e2) {
529
+ Log.d("ReactNative", "createPeerIdentity decryptMsg failed with Error: " + e2.getMessage());
530
+ Log.d("ReactNative", "creating new encrpyted identity");
531
+ throw(e2);
532
+ }
533
+ }
534
+
535
+ } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException e) {
536
+ Log.d("ReactNative", "createPeerIdentity failed with Error: " + e.getMessage());
537
+ throw (e);
538
+ } catch (Exception e) {
539
+ throw new RuntimeException(e);
540
+ }
541
+ }
542
+
543
+ private String decryptLibp2pIdentity(String encryptedLibp2pId, SecretKey encryptionSecretKey) throws Exception {
544
+ try {
545
+ String decryptedLibp2pId = Cryptography.decryptMsg(encryptedLibp2pId.replace("FULA_ENC_V4:", ""), encryptionSecretKey);
546
+
547
+ return decryptedLibp2pId;
548
+ } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException e) {
549
+ Log.d("ReactNative", "createPeerIdentity decryptMsg failed with Error: " + e.getMessage());
550
+ Log.d("ReactNative", "creating new encrpyted identity");
551
+ throw new GeneralSecurityException("decryptLibp2pIdentity Failed to decrypt libp2pId", e);
552
+ }
553
+ }
554
+
555
+ private String createEncryptedLibp2pId(byte[] identity, SecretKey encryptionSecretKey) throws Exception {
556
+ byte[] libp2pId;
557
+ String encryptedLibp2pId;
558
+ try {
559
+ Log.d("ReactNative", "createEncryptedLibp2pId started");
560
+
561
+ try {
562
+ libp2pId = Fulamobile.generateEd25519KeyFromString(toString(identity));
563
+ } catch (Exception e) {
564
+ Log.d("ReactNative", " createEncryptedLibp2pId Failed to generate libp2pId: " + e.getMessage());
565
+ throw new GeneralSecurityException("createEncryptedLibp2pId Failed to generate libp2pId", e);
566
+ }
567
+ encryptedLibp2pId = "FULA_ENC_V4:" + Cryptography.encryptMsg(StaticHelper.bytesToBase64(libp2pId), encryptionSecretKey, null);
568
+ sharedPref.add(PRIVATE_KEY_STORE_PEERID, encryptedLibp2pId);
569
+ return encryptedLibp2pId;
570
+ }
571
+ catch (Exception e) {
572
+ Log.d("ReactNative", "createEncryptedLibp2pId failed with Error: " + e.getMessage());
573
+ throw new GeneralSecurityException("createEncryptedLibp2pId Failed to generate libp2pId at hte first level", e);
574
+ }
575
+ }
576
+
577
+ private void createNewRootConfig(FulaModule.Client iClient, byte[] identity) throws Exception {
578
+ byte[] hash32 = getSHA256Hash(identity);
579
+ this.rootConfig = Fs.init(iClient, hash32);
580
+ Log.d("ReactNative", "rootConfig is created " + this.rootConfig.getCid());
581
+ if (this.fula != null) {
582
+ this.fula.flush();
583
+ }
584
+ this.encrypt_and_store_config();
585
+ }
586
+
587
+ public static byte[] getSHA256Hash(byte[] input) throws NoSuchAlgorithmException {
588
+ MessageDigest md = MessageDigest.getInstance("SHA-256");
589
+ return md.digest(input);
590
+ }
591
+
592
+ private static String bytesToHex(byte[] bytes) {
593
+ StringBuilder result = new StringBuilder();
594
+ for (byte b : bytes) {
595
+ result.append(String.format("%02x", b));
596
+ }
597
+ return result.toString();
598
+ }
599
+
600
+ private void reloadFS(FulaModule.Client iClient, byte[] wnfsKey, String rootCid) throws Exception {
601
+ Log.d("ReactNative", "reloadFS called: rootCid=" + rootCid);
602
+ byte[] hash32 = getSHA256Hash(wnfsKey);
603
+ Log.d("ReactNative", "wnfsKey=" + bytesToHex(wnfsKey) + "; hash32 = " + bytesToHex(hash32));
604
+ Fs.loadWithWNFSKey(iClient, hash32, rootCid);
605
+ Log.d("ReactNative", "reloadFS completed");
606
+ }
607
+
608
+ private boolean encrypt_and_store_config() throws Exception {
609
+ try {
610
+ if(this.identityEncryptedGlobal != null && !this.identityEncryptedGlobal.isEmpty()) {
611
+ Log.d("ReactNative", "encrypt_and_store_config started");
612
+
613
+ String cid_encrypted = Cryptography.encryptMsg(this.rootConfig.getCid(), this.secretKeyGlobal, null);
614
+
615
+ sharedPref.add("FULA_ENC_V4:cid_encrypted_" + this.identityEncryptedGlobal, cid_encrypted);
616
+ return true;
617
+ } else {
618
+ Log.d("ReactNative", "encrypt_and_store_config failed because identityEncryptedGlobal is empty");
619
+ return false;
620
+ }
621
+ } catch (Exception e) {
622
+ Log.d("ReactNative", "encrypt_and_store_config failed with Error: " + e.getMessage());
623
+ throw (e);
624
+ }
625
+ }
626
+
627
+ private boolean logoutInternal(byte[] identity, String storePath) throws Exception {
628
+ try {
629
+ if (this.fula != null) {
630
+ this.fula.flush();
631
+ }
632
+ SecretKey secretKey = Cryptography.generateKey(identity);
633
+ byte[] iv = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B };
634
+ String identity_encrypted = Cryptography.encryptMsg(Arrays.toString(identity), secretKey, iv);
635
+ sharedPref.remove("FULA_ENC_V4:cid_encrypted_"+ identity_encrypted);
636
+
637
+ //TODO: Should also remove peerid @Mahdi
638
+
639
+ sharedPref.remove("FULA_ENC_V4:cid_encrypted_"+ identity_encrypted);
640
+
641
+ this.rootConfig = null;
642
+ this.secretKeyGlobal = null;
643
+ this.identityEncryptedGlobal = null;
644
+
645
+ if (storePath == null || storePath.trim().isEmpty()) {
646
+ storePath = this.fulaStorePath;
647
+ }
648
+
649
+ File file = new File(storePath);
650
+ FileUtils.deleteDirectory(file);
651
+ return true;
652
+
653
+ } catch (Exception e) {
654
+ Log.d("ReactNative", "logout internal failed with Error: " + e.getMessage());
655
+ throw (e);
656
+ }
657
+ }
658
+
659
+ public fulamobile.Client getFulaClient() {
660
+ return this.fula;
661
+ }
662
+
663
+ @NonNull
664
+ private byte[] newClientInternal(byte[] identity, String storePath, String bloxAddr, String exchange, boolean autoFlush, boolean useRelay, boolean refresh) throws GeneralSecurityException, IOException {
665
+ byte[] peerIdentity = null;
666
+ try {
667
+ fulaConfig = new Config();
668
+ if (storePath == null || storePath.trim().isEmpty()) {
669
+ fulaConfig.setStorePath(this.fulaStorePath);
670
+ } else {
671
+ fulaConfig.setStorePath(storePath);
672
+ }
673
+ Log.d("ReactNative", "newClientInternal storePath is set: " + fulaConfig.getStorePath());
674
+
675
+ peerIdentity = this.createPeerIdentity(identity);
676
+ fulaConfig.setIdentity(peerIdentity);
677
+ Log.d("ReactNative", "peerIdentity is set: " + toString(fulaConfig.getIdentity()));
678
+ fulaConfig.setBloxAddr(bloxAddr);
679
+ Log.d("ReactNative", "bloxAddr is set: " + fulaConfig.getBloxAddr());
680
+ fulaConfig.setExchange(exchange);
681
+ fulaConfig.setSyncWrites(autoFlush);
682
+ if (useRelay) {
683
+ fulaConfig.setAllowTransientConnection(true);
684
+ fulaConfig.setForceReachabilityPrivate(true);
685
+ }
686
+ if (this.fula == null || refresh) {
687
+ Log.d("ReactNative", "Creating a new Fula instance");
688
+ try {
689
+ shutdownInternal();
690
+ Log.d("ReactNative", "Creating a new Fula instance with config");
691
+ this.fula = Fulamobile.newClient(fulaConfig);
692
+ if (this.fula != null) {
693
+ this.fula.flush();
694
+ }
695
+ } catch (Exception e) {
696
+ Log.d("ReactNative", "Failed to create new Fula instance: " + e.getMessage());
697
+ throw new IOException("Failed to create new Fula instance", e);
698
+ }
699
+ }
700
+ } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException e) {
701
+ Log.d("ReactNative", "newclientInternal failed with Error: " + e.getMessage());
702
+ throw (e);
703
+ }
704
+ return peerIdentity;
705
+ }
706
+
707
+
708
+ @NonNull
709
+ private String[] initInternal(byte[] identity, String storePath, String bloxAddr, String exchange, boolean autoFlush, String rootCid, boolean useRelay, boolean refresh) throws Exception {
710
+ try {
711
+ if (this.fula == null || refresh) {
712
+ this.newClientInternal(identity, storePath, bloxAddr, exchange, autoFlush, useRelay, refresh);
713
+ }
714
+ if(this.client == null || refresh) {
715
+ this.client = new Client(this.fula);
716
+ Log.d("ReactNative", "fula initialized: " + this.fula.id());
717
+ }
718
+
719
+ SecretKey secretKey = Cryptography.generateKey(identity);
720
+ Log.d("ReactNative", "secretKey generated: " + secretKey.toString());
721
+ byte[] iv = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B };
722
+ String identity_encrypted =Cryptography.encryptMsg(Arrays.toString(identity), secretKey, iv);
723
+ Log.d("ReactNative", "identity_encrypted generated: " + identity_encrypted + " for identity: " + Arrays.toString(identity));
724
+ this.identityEncryptedGlobal = identity_encrypted;
725
+ this.secretKeyGlobal = secretKey;
726
+
727
+ if ( this.rootConfig == null || this.rootConfig.getCid().isEmpty() ) {
728
+ Log.d("ReactNative", "this.rootCid is empty.");
729
+ //Load from keystore
730
+
731
+ String cid_encrypted_fetched = sharedPref.getValue("FULA_ENC_V4:cid_encrypted_"+ identity_encrypted);
732
+ Log.d("ReactNative", "Here1");
733
+ String cid = "";
734
+ if(cid_encrypted_fetched != null && !cid_encrypted_fetched.isEmpty()) {
735
+ Log.d("ReactNative", "decrypting cid="+cid_encrypted_fetched+" with secret="+secretKey.toString());
736
+ cid = Cryptography.decryptMsg(cid_encrypted_fetched, secretKey);
737
+ }
738
+
739
+ Log.d("ReactNative", "Here2");
740
+ //Log.d("ReactNative", "Attempted to fetch cid from keystore; cid="+cid);
741
+ if(cid == null || cid.isEmpty()) {
742
+ Log.d("ReactNative", "cid was not found");
743
+ if(rootCid != null && !rootCid.isEmpty()){
744
+ Log.d("ReactNative", "Re-setting cid from input: "+rootCid);
745
+ cid = rootCid;
746
+ this.rootConfig = new land.fx.wnfslib.Config(cid);
747
+ this.reloadFS(this.client, identity, cid);
748
+ this.encrypt_and_store_config();
749
+ }
750
+ if(cid == null || cid.isEmpty()) {
751
+ Log.d("ReactNative", "Tried to recover cid but was not successful. Creating new ones");
752
+ this.createNewRootConfig(this.client, identity);
753
+ } else {
754
+ this.rootConfig = new land.fx.wnfslib.Config(cid);
755
+ this.reloadFS(this.client, identity, cid);
756
+ this.encrypt_and_store_config();
757
+ }
758
+ } else {
759
+ Log.d("ReactNative", "Recovered cid and private ref from keychain store. cid="+cid +" and cid from input was: "+rootCid);
760
+ this.rootConfig = new land.fx.wnfslib.Config(cid);
761
+ this.reloadFS(this.client, identity, cid);
762
+ this.encrypt_and_store_config();
763
+ }
764
+
765
+ Log.d("ReactNative", "creating rootConfig completed");
766
+
767
+ Log.d("ReactNative", "rootConfig is created: cid=" + this.rootConfig.getCid());
768
+ } else {
769
+ Log.d("ReactNative", "rootConfig existed: cid=" + this.rootConfig.getCid());
770
+ }
771
+ String peerId = this.fula.id();
772
+ String[] obj = new String[2];
773
+ obj[0] = peerId;
774
+ obj[1] = this.rootConfig.getCid();
775
+ Log.d("ReactNative", "initInternal is completed successfully");
776
+ if (this.fula != null) {
777
+ this.fula.flush();
778
+ }
779
+ return obj;
780
+ } catch (Exception e) {
781
+ Log.d("ReactNative", "init internal failed with Error: " + e.getMessage());
782
+ throw (e);
783
+ }
784
+ }
785
+
786
+ @ReactMethod
787
+ public void mkdir(String path, Promise promise) {
788
+ ThreadUtils.runOnExecutor(() -> {
789
+ Log.d("ReactNative", "mkdir started with: path = " + path + " rootConfig.getCid() = " + this.rootConfig.getCid());
790
+ try {
791
+ land.fx.wnfslib.Config config = Fs.mkdir(this.client, this.rootConfig.getCid(), path);
792
+ if(config != null) {
793
+ this.rootConfig = config;
794
+ this.encrypt_and_store_config();
795
+ if (this.fula != null) {
796
+ this.fula.flush();
797
+ }
798
+ String rootCid = this.rootConfig.getCid();
799
+ Log.d("ReactNative", "mkdir completed successfully with rootCid = " + rootCid);
800
+ promise.resolve(rootCid);
801
+ } else {
802
+ Log.d("ReactNative", "mkdir Error: config is null");
803
+ promise.reject(new Exception("mkdir Error: config is null"));
804
+ }
805
+ } catch (Exception e) {
806
+ Log.d("get", e.getMessage());
807
+ promise.reject(e);
808
+ }
809
+ });
810
+ }
811
+
812
+ @ReactMethod
813
+ public void writeFile(String fulaTargetFilename, String localFilename, Promise promise) {
814
+ /*
815
+ // reads content of the file form localFilename (should include full absolute path to local file with read permission
816
+ // writes content to the specified location by fulaTargetFilename in Fula filesystem
817
+ // fulaTargetFilename: a string including full path and filename of target file on Fula (e.g. root/pictures/cat.jpg)
818
+ // localFilename: a string containing full path and filename of local file on hte device (e.g /usr/bin/cat.jpg)
819
+ // Returns: new cid of the root after this file is placed in the tree
820
+ */
821
+ ThreadUtils.runOnExecutor(() -> {
822
+ Log.d("ReactNative", "writeFile to : path = " + fulaTargetFilename + ", from: " + localFilename);
823
+ try {
824
+ if (this.client != null) {
825
+ Log.d("ReactNative", "writeFileFromPath started: this.rootConfig.getCid=" + this.rootConfig.getCid()+ ", fulaTargetFilename="+fulaTargetFilename + ", localFilename="+localFilename);
826
+ land.fx.wnfslib.Config config = Fs.writeFileStreamFromPath(this.client, this.rootConfig.getCid(), fulaTargetFilename, localFilename);
827
+ if(config != null) {
828
+ this.rootConfig = config;
829
+ this.encrypt_and_store_config();
830
+ if (this.fula != null) {
831
+ this.fula.flush();
832
+ String rootCid = this.rootConfig.getCid();
833
+ Log.d("ReactNative", "writeFileFromPath completed: this.rootConfig.getCid=" + rootCid);
834
+ promise.resolve(rootCid);
835
+ } else {
836
+ Log.d("ReactNative", "writeFile Error: fula is null");
837
+ promise.reject(new Exception("writeFile Error: fula is null"));
838
+ }
839
+ } else {
840
+ Log.d("ReactNative", "writeFile Error: config is null");
841
+ promise.reject(new Exception("writeFile Error: config is null"));
842
+ }
843
+ } else {
844
+ Log.d("ReactNative", "writeFile Error: client is null");
845
+ promise.reject(new Exception("writeFile Error: client is null"));
846
+ }
847
+ } catch (Exception e) {
848
+ Log.d("get", e.getMessage());
849
+ promise.reject(e);
850
+ }
851
+ });
852
+ }
853
+
854
+ @ReactMethod
855
+ public void writeFileContent(String path, String contentString, Promise promise) {
856
+ ThreadUtils.runOnExecutor(() -> {
857
+ Log.d("ReactNative", "writeFile: contentString = " + contentString);
858
+ Log.d("ReactNative", "writeFile: path = " + path);
859
+ try {
860
+ byte[] content = this.convertStringToByte(contentString);
861
+ land.fx.wnfslib.Config config = Fs.writeFile(this.client, this.rootConfig.getCid(), path, content);
862
+ this.rootConfig = config;
863
+ this.encrypt_and_store_config();
864
+ if (this.fula != null) {
865
+ this.fula.flush();
866
+ }
867
+ promise.resolve(config.getCid());
868
+ } catch (Exception e) {
869
+ Log.d("get", e.getMessage());
870
+ promise.reject(e);
871
+ }
872
+ });
873
+ }
874
+
875
+ @ReactMethod
876
+ public void ls(String path, Promise promise) {
877
+ ThreadUtils.runOnExecutor(() -> {
878
+ Log.d("ReactNative", "ls: path = " + path + "rootCid= " + this.rootConfig.getCid());
879
+ try {
880
+ byte[] res = Fs.ls(this.client, this.rootConfig.getCid(), path);
881
+
882
+ String s = new String(res, StandardCharsets.UTF_8);
883
+ Log.d("ReactNative", "ls: res = " + s);
884
+ promise.resolve(s);
885
+ } catch (Exception e) {
886
+ Log.d("ReactNative", e.getMessage());
887
+ promise.reject(e);
888
+ }
889
+ });
890
+ }
891
+
892
+ @ReactMethod
893
+ public void rm(String path, Promise promise) {
894
+ ThreadUtils.runOnExecutor(() -> {
895
+ Log.d("ReactNative", "rm: path = " + path + ", beginning rootCid=" + this.rootConfig.getCid());
896
+ try {
897
+ land.fx.wnfslib.Config config = Fs.rm(this.client, this.rootConfig.getCid(), path);
898
+ if(config != null) {
899
+ this.rootConfig = config;
900
+ this.encrypt_and_store_config();
901
+ if (this.fula != null) {
902
+ this.fula.flush();
903
+ }
904
+ String rootCid = config.getCid();
905
+ Log.d("ReactNative", "rm: returned rootCid = " + rootCid);
906
+ promise.resolve(rootCid);
907
+ } else {
908
+ Log.d("ReactNative", "rm Error: config is null");
909
+ promise.reject(new Exception("rm Error: config is null"));
910
+ }
911
+ } catch (Exception e) {
912
+ Log.d("ReactNative", e.getMessage());
913
+ promise.reject(e);
914
+ }
915
+ });
916
+ }
917
+
918
+ @ReactMethod
919
+ public void cp(String sourcePath, String targetPath, Promise promise) {
920
+ ThreadUtils.runOnExecutor(() -> {
921
+ Log.d("ReactNative", "rm: sourcePath = " + sourcePath);
922
+ try {
923
+ land.fx.wnfslib.Config config = Fs.cp(this.client, this.rootConfig.getCid(), sourcePath, targetPath);
924
+ if(config != null) {
925
+ this.rootConfig = config;
926
+ this.encrypt_and_store_config();
927
+ if (this.fula != null) {
928
+ this.fula.flush();
929
+ }
930
+ promise.resolve(config.getCid());
931
+ } else {
932
+ Log.d("ReactNative", "cp Error: config is null");
933
+ promise.reject(new Exception("cp Error: config is null"));
934
+ }
935
+ } catch (Exception e) {
936
+ Log.d("ReactNative", e.getMessage());
937
+ promise.reject(e);
938
+ }
939
+ });
940
+ }
941
+
942
+ @ReactMethod
943
+ public void mv(String sourcePath, String targetPath, Promise promise) {
944
+ ThreadUtils.runOnExecutor(() -> {
945
+ Log.d("ReactNative", "rm: sourcePath = " + sourcePath);
946
+ try {
947
+ land.fx.wnfslib.Config config = Fs.mv(this.client, this.rootConfig.getCid(), sourcePath, targetPath);
948
+ if(config != null) {
949
+ this.rootConfig = config;
950
+ this.encrypt_and_store_config();
951
+ if (this.fula != null) {
952
+ this.fula.flush();
953
+ }
954
+ promise.resolve(config.getCid());
955
+ } else {
956
+ Log.d("ReactNative", "mv Error: config is null");
957
+ promise.reject(new Exception("mv Error: config is null"));
958
+ }
959
+ } catch (Exception e) {
960
+ Log.d("ReactNative", e.getMessage());
961
+ promise.reject(e);
962
+ }
963
+ });
964
+ }
965
+
966
+ @ReactMethod
967
+ public void readFile(String fulaTargetFilename, String localFilename, Promise promise) {
968
+ /*
969
+ // reads content of the file form localFilename (should include full absolute path to local file with read permission
970
+ // writes content to the specified location by fulaTargetFilename in Fula filesystem
971
+ // fulaTargetFilename: a string including full path and filename of target file on Fula (e.g. root/pictures/cat.jpg)
972
+ // localFilename: a string containing full path and filename of local file on hte device (e.g /usr/bin/cat.jpg)
973
+ // Returns: new cid of the root after this file is placed in the tree
974
+ */
975
+ ThreadUtils.runOnExecutor(() -> {
976
+ Log.d("ReactNative", "readFile: fulaTargetFilename = " + fulaTargetFilename);
977
+ try {
978
+ Log.d("ReactNative", "readFile: localFilename = " + localFilename + " fulaTargetFilename = " + fulaTargetFilename + " beginning rootCid = " + this.rootConfig.getCid());
979
+ String path = Fs.readFilestreamToPath(this.client, this.rootConfig.getCid(), fulaTargetFilename, localFilename);
980
+ promise.resolve(path);
981
+ } catch (Exception e) {
982
+ Log.d("ReactNative", e.getMessage());
983
+ promise.reject(e);
984
+ }
985
+ });
986
+ }
987
+
988
+ @ReactMethod
989
+ public void readFileContent(String path, Promise promise) {
990
+ ThreadUtils.runOnExecutor(() -> {
991
+ Log.d("ReactNative", "readFileContent: path = " + path);
992
+ try {
993
+ byte[] res = Fs.readFile(this.client, this.rootConfig.getCid(), path);
994
+ String resString = toString(res);
995
+ promise.resolve(resString);
996
+ } catch (Exception e) {
997
+ Log.d("ReactNative", e.getMessage());
998
+ promise.reject(e);
999
+ }
1000
+ });
1001
+ }
1002
+
1003
+ @ReactMethod
1004
+ public void get(String keyString, Promise promise) {
1005
+ ThreadUtils.runOnExecutor(() -> {
1006
+ Log.d("ReactNative", "get: keyString = " + keyString);
1007
+ try {
1008
+ byte[] key = this.convertStringToByte(keyString);
1009
+ byte[] value = this.getInternal(key);
1010
+ String valueString = toString(value);
1011
+ promise.resolve(valueString);
1012
+ } catch (Exception e) {
1013
+ Log.d("ReactNative", e.getMessage());
1014
+ promise.reject(e);
1015
+ }
1016
+ });
1017
+ }
1018
+
1019
+ @NonNull
1020
+ private byte[] getInternal(byte[] key) throws Exception {
1021
+ try {
1022
+ Log.d("ReactNative", "getInternal: key.toString() = " + toString(key));
1023
+ Log.d("ReactNative", "getInternal: key.toString().bytes = " + Arrays.toString(key));
1024
+ byte[] value = this.fula.get(key);
1025
+ Log.d("ReactNative", "getInternal: value.toString() = " + toString(value));
1026
+ return value;
1027
+ } catch (Exception e) {
1028
+ Log.d("ReactNative", "getInternal: error = " + e.getMessage());
1029
+ Log.d("getInternal", e.getMessage());
1030
+ throw (e);
1031
+ }
1032
+ }
1033
+
1034
+ @ReactMethod
1035
+ public void has(String keyString, Promise promise) {
1036
+ ThreadUtils.runOnExecutor(() -> {
1037
+ Log.d("ReactNative", "has: keyString = " + keyString);
1038
+ try {
1039
+ byte[] key = this.convertStringToByte(keyString);
1040
+ boolean result = this.hasInternal(key);
1041
+ promise.resolve(result);
1042
+ } catch (Exception e) {
1043
+ Log.d("ReactNative", e.getMessage());
1044
+ promise.reject(e);
1045
+ }
1046
+ });
1047
+ }
1048
+
1049
+ private boolean hasInternal(byte[] key) throws Exception {
1050
+ try {
1051
+ boolean res = this.fula.has(key);
1052
+ return res;
1053
+ } catch (Exception e) {
1054
+ Log.d("ReactNative", e.getMessage());
1055
+ throw (e);
1056
+ }
1057
+ }
1058
+
1059
+ private void pullInternal(byte[] key) throws Exception {
1060
+ try {
1061
+ this.fula.pull(key);
1062
+ } catch (Exception e) {
1063
+ Log.d("ReactNative", e.getMessage());
1064
+ throw (e);
1065
+ }
1066
+ }
1067
+
1068
+ @ReactMethod
1069
+ public void push(Promise promise) {
1070
+ ThreadUtils.runOnExecutor(() -> {
1071
+ Log.d("ReactNative", "push started");
1072
+ try {
1073
+ this.pushInternal(this.convertStringToByte(this.rootConfig.getCid()));
1074
+ promise.resolve(this.rootConfig.getCid());
1075
+ } catch (Exception e) {
1076
+ Log.d("ReactNative", e.getMessage());
1077
+ promise.reject(e);
1078
+ }
1079
+ });
1080
+ }
1081
+
1082
+ private void pushInternal(byte[] key) throws Exception {
1083
+ try {
1084
+ if (this.fula != null && this.fula.has(key)) {
1085
+ this.fula.push(key);
1086
+ this.fula.flush();
1087
+ } else {
1088
+ Log.d("ReactNative", "pushInternal error: key wasn't found or fula is not initialized");
1089
+ throw new Exception("key wasn't found in local storage");
1090
+ }
1091
+ } catch (Exception e) {
1092
+ Log.d("ReactNative", "pushInternal"+ e.getMessage());
1093
+ throw (e);
1094
+ }
1095
+ }
1096
+
1097
+ @ReactMethod
1098
+ public void put(String valueString, String codecString, Promise promise) {
1099
+ ThreadUtils.runOnExecutor(() -> {
1100
+ Log.d("ReactNative", "put: codecString = " + codecString);
1101
+ Log.d("ReactNative", "put: valueString = " + valueString);
1102
+ try {
1103
+ //byte[] codec = this.convertStringToByte(CodecString);
1104
+ long codec = Long.parseLong(codecString);
1105
+
1106
+
1107
+ Log.d("ReactNative", "put: codec = " + codec);
1108
+ byte[] value = toByte(valueString);
1109
+
1110
+ Log.d("ReactNative", "put: value.toString() = " + toString(value));
1111
+ byte[] key = this.putInternal(value, codec);
1112
+ Log.d("ReactNative", "put: key.toString() = " + toString(key));
1113
+ promise.resolve(toString(key));
1114
+ } catch (Exception e) {
1115
+ Log.d("ReactNative", "put: error = " + e.getMessage());
1116
+ promise.reject(e);
1117
+ }
1118
+ });
1119
+ }
1120
+
1121
+ @NonNull
1122
+ private byte[] putInternal(byte[] value, long codec) throws Exception {
1123
+ try {
1124
+ if(this.fula != null) {
1125
+ byte[] key = this.fula.put(value, codec);
1126
+ this.fula.flush();
1127
+ return key;
1128
+ } else {
1129
+ Log.d("ReactNative", "putInternal Error: fula is not initialized");
1130
+ throw (new Exception("putInternal Error: fula is not initialized"));
1131
+ }
1132
+ } catch (Exception e) {
1133
+ Log.d("ReactNative", "putInternal"+ e.getMessage());
1134
+ throw (e);
1135
+ }
1136
+ }
1137
+
1138
+ @ReactMethod
1139
+ public void setAuth(String peerIdString, boolean allow, Promise promise) {
1140
+ ThreadUtils.runOnExecutor(() -> {
1141
+ Log.d("ReactNative", "setAuth: peerIdString = " + peerIdString);
1142
+ try {
1143
+ if (this.fula != null && this.fula.id() != null && this.fulaConfig != null && this.fulaConfig.getBloxAddr() != null) {
1144
+ String bloxAddr = this.fulaConfig.getBloxAddr();
1145
+ Log.d("ReactNative", "setAuth: bloxAddr = '" + bloxAddr+"'"+ " peerIdString = '" + peerIdString+"'");
1146
+ int index = bloxAddr.lastIndexOf("/");
1147
+ String bloxPeerId = bloxAddr.substring(index + 1);
1148
+ this.fula.setAuth(bloxPeerId, peerIdString, allow);
1149
+ promise.resolve(true);
1150
+ } else {
1151
+ Log.d("ReactNative", "setAuth error: fula is not initialized");
1152
+ throw new Exception("fula is not initialized");
1153
+ }
1154
+ promise.resolve(false);
1155
+ } catch (Exception e) {
1156
+ Log.d("ReactNative", e.getMessage());
1157
+ promise.reject(e);
1158
+ }
1159
+ });
1160
+ }
1161
+
1162
+ private void shutdownInternal() throws Exception {
1163
+ try {
1164
+ if(this.fula != null) {
1165
+ this.fula.shutdown();
1166
+ this.fula = null;
1167
+ this.client = null;
1168
+ Log.d("ReactNative", "shutdownInternal done");
1169
+
1170
+ }
1171
+ } catch (Exception e) {
1172
+ Log.d("ReactNative", "shutdownInternal"+ e.getMessage());
1173
+ throw (e);
1174
+ }
1175
+ }
1176
+
1177
+ @ReactMethod
1178
+ public void shutdown(Promise promise) {
1179
+ ThreadUtils.runOnExecutor(() -> {
1180
+ try {
1181
+ shutdownInternal();
1182
+ promise.resolve(true);
1183
+ } catch (Exception e) {
1184
+ promise.reject(e);
1185
+ Log.d("ReactNative", "shutdown"+ e.getMessage());
1186
+ }
1187
+ });
1188
+ }
1189
+
1190
+ ///////////////////////////////////////////////////////////
1191
+ ///////////////////////////////////////////////////////////
1192
+ ///////////////////////////////////////////////////////////
1193
+ ///////////////////////////////////////////////////////////
1194
+ //////////////////////ANYTHING BELOW IS FOR BLOCKCHAIN/////
1195
+ ///////////////////////////////////////////////////////////
1196
+ @ReactMethod
1197
+ public void getAccount(Promise promise) {
1198
+ ThreadUtils.runOnExecutor(() -> {
1199
+ Log.d("ReactNative", "getAccount called ");
1200
+ try {
1201
+ byte[] result = this.fula.getAccount();
1202
+ String resultString = toString(result);
1203
+ promise.resolve(resultString);
1204
+ } catch (Exception e) {
1205
+ Log.d("ReactNative", e.getMessage());
1206
+ promise.reject(e);
1207
+ }
1208
+ });
1209
+ }
1210
+
1211
+ @ReactMethod
1212
+ public void assetsBalance(String account, String assetId, String classId, Promise promise) {
1213
+ ThreadUtils.runOnExecutor(() -> {
1214
+ Log.d("ReactNative", "assetsBalance called ");
1215
+ try {
1216
+ byte[] result = this.fula.assetsBalance(account, assetId, classId);
1217
+ String resultString = toString(result);
1218
+ promise.resolve(resultString);
1219
+ } catch (Exception e) {
1220
+ Log.d("ReactNative", e.getMessage());
1221
+ promise.reject(e);
1222
+ }
1223
+ });
1224
+ }
1225
+
1226
+ @ReactMethod
1227
+ public void transferToFula(String amount, String wallet, String chain, Promise promise) {
1228
+ ThreadUtils.runOnExecutor(() -> {
1229
+ Log.d("ReactNative", "transferToFula called ");
1230
+ try {
1231
+ byte[] result = this.fula.transferToFula(amount, wallet, chain);
1232
+ String resultString = toString(result);
1233
+ promise.resolve(resultString);
1234
+ } catch (Exception e) {
1235
+ Log.d("ReactNative", e.getMessage());
1236
+ promise.reject(e);
1237
+ }
1238
+ });
1239
+ }
1240
+
1241
+ @ReactMethod
1242
+ public void checkAccountExists(String accountString, Promise promise) {
1243
+ ThreadUtils.runOnExecutor(() -> {
1244
+ Log.d("ReactNative", "checkAccountExists: accountString = " + accountString);
1245
+ try {
1246
+ byte[] result = this.fula.accountExists(accountString);
1247
+ String resultString = toString(result);
1248
+ promise.resolve(resultString);
1249
+ } catch (Exception e) {
1250
+ Log.d("ReactNative", e.getMessage());
1251
+ promise.reject(e);
1252
+ }
1253
+ });
1254
+ }
1255
+
1256
+ @ReactMethod
1257
+ public void listPools(Promise promise) {
1258
+ ThreadUtils.runOnExecutor(() -> {
1259
+ Log.d("ReactNative", "listPools");
1260
+ try {
1261
+ byte[] result = this.fula.poolList();
1262
+ String resultString = toString(result);
1263
+ promise.resolve(resultString);
1264
+ } catch (Exception e) {
1265
+ Log.d("ReactNative", e.getMessage());
1266
+ promise.reject(e);
1267
+ }
1268
+ });
1269
+ }
1270
+
1271
+ @ReactMethod
1272
+ public void joinPool(String poolID, Promise promise) {
1273
+ ThreadUtils.runOnExecutor(() -> {
1274
+ long poolIdLong = Long.parseLong(poolID);
1275
+ Log.d("ReactNative", "joinPool: poolID = " + poolIdLong);
1276
+ try {
1277
+ byte[] result = this.fula.poolJoin(poolIdLong);
1278
+ String resultString = toString(result);
1279
+ promise.resolve(resultString);
1280
+ } catch (Exception e) {
1281
+ Log.d("ReactNative", e.getMessage());
1282
+ promise.reject(e);
1283
+ }
1284
+ });
1285
+ }
1286
+
1287
+ @ReactMethod
1288
+ public void cancelPoolJoin(long poolID, Promise promise) {
1289
+ ThreadUtils.runOnExecutor(() -> {
1290
+ Log.d("ReactNative", "cancelPoolJoin: poolID = " + poolID);
1291
+ try {
1292
+ byte[] result = this.fula.poolCancelJoin(poolID);
1293
+ String resultString = toString(result);
1294
+ promise.resolve(resultString);
1295
+ } catch (Exception e) {
1296
+ Log.d("ReactNative", e.getMessage());
1297
+ promise.reject(e);
1298
+ }
1299
+ });
1300
+ }
1301
+
1302
+ @ReactMethod
1303
+ public void listPoolJoinRequests(long poolID, Promise promise) {
1304
+ ThreadUtils.runOnExecutor(() -> {
1305
+ Log.d("ReactNative", "listPoolJoinRequests: poolID = " + poolID);
1306
+ try {
1307
+ byte[] result = this.fula.poolRequests(poolID);
1308
+ String resultString = toString(result);
1309
+ promise.resolve(resultString);
1310
+ } catch (Exception e) {
1311
+ Log.d("ReactNative", e.getMessage());
1312
+ promise.reject(e);
1313
+ }
1314
+ });
1315
+ }
1316
+
1317
+ @ReactMethod
1318
+ public void leavePool(long poolID, Promise promise) {
1319
+ ThreadUtils.runOnExecutor(() -> {
1320
+ Log.d("ReactNative", "leavePool: poolID = " + poolID);
1321
+ try {
1322
+ byte[] result = this.fula.poolLeave(poolID);
1323
+ String resultString = toString(result);
1324
+ promise.resolve(resultString);
1325
+ } catch (Exception e) {
1326
+ Log.d("ReactNative", e.getMessage());
1327
+ promise.reject(e);
1328
+ }
1329
+ });
1330
+ }
1331
+
1332
+ @ReactMethod
1333
+ public void listAvailableReplicationRequests(long poolID, Promise promise) {
1334
+ ThreadUtils.runOnExecutor(() -> {
1335
+ Log.d("ReactNative", "listAvailableReplicationRequests: poolID = " + poolID);
1336
+ try {
1337
+ byte[] result = this.fula.manifestAvailable(poolID);
1338
+ String resultString = toString(result);
1339
+ promise.resolve(resultString);
1340
+ } catch (Exception e) {
1341
+ Log.d("ReactNative", e.getMessage());
1342
+ promise.reject(e);
1343
+ }
1344
+ });
1345
+ }
1346
+
1347
+ @ReactMethod
1348
+ private void listRecentCidsAsString(Promise promise) throws Exception {
1349
+ ThreadUtils.runOnExecutor(() -> {
1350
+ try {
1351
+ if (this.fula != null) {
1352
+ Log.d("ReactNative", "ListRecentCidsAsString");
1353
+ fulamobile.StringIterator recentLinks = this.fula.listRecentCidsAsString();
1354
+ ArrayList<String> recentLinksList = new ArrayList<>();
1355
+ while (recentLinks.hasNext()) {
1356
+ recentLinksList.add(recentLinks.next());
1357
+ }
1358
+ if (!recentLinksList.isEmpty()) {
1359
+ // return the whole list
1360
+ Log.d("ReactNative", "ListRecentCidsAsString found: "+ recentLinksList);
1361
+ WritableArray recentLinksArray = Arguments.createArray();
1362
+ for (String link : recentLinksList) {
1363
+ recentLinksArray.pushString(link);
1364
+ }
1365
+ promise.resolve(recentLinksArray);
1366
+ } else {
1367
+ promise.resolve(false);
1368
+ }
1369
+ } else {
1370
+ throw new Exception("ListRecentCidsAsString: Fula is not initialized");
1371
+ }
1372
+ } catch (Exception e) {
1373
+ Log.d("ReactNative", "ListRecentCidsAsString failed with Error: " + e.getMessage());
1374
+ try {
1375
+ throw (e);
1376
+ } catch (Exception ex) {
1377
+ throw new RuntimeException(ex);
1378
+ }
1379
+ }
1380
+ });
1381
+ }
1382
+
1383
+ @ReactMethod
1384
+ public void clearCidsFromRecent(ReadableArray cidArray, Promise promise) {
1385
+ ThreadUtils.runOnExecutor(() -> {
1386
+ try {
1387
+ if (this.fula != null) {
1388
+ StringBuilder cidStrBuilder = new StringBuilder();
1389
+ for (int i = 0; i < cidArray.size(); i++) {
1390
+ if (i > 0) {
1391
+ cidStrBuilder.append("|");
1392
+ }
1393
+ cidStrBuilder.append(cidArray.getString(i));
1394
+ }
1395
+
1396
+ byte[] cidsBytes = cidStrBuilder.toString().getBytes(StandardCharsets.UTF_8);
1397
+ this.fula.clearCidsFromRecent(cidsBytes);
1398
+ promise.resolve(true); // Indicate success
1399
+ } else {
1400
+ throw new Exception("clearCidsFromRecent: Fula is not initialized");
1401
+ }
1402
+ } catch (Exception e) {
1403
+ Log.d("ReactNative", "clearCidsFromRecent failed with Error: " + e.getMessage());
1404
+ promise.reject("Error", e.getMessage());
1405
+ }
1406
+ });
1407
+ }
1408
+
1409
+
1410
+ ////////////////////////////////////////////////////////////////
1411
+ ///////////////// Blox Hardware Methods ////////////////////////
1412
+ ////////////////////////////////////////////////////////////////
1413
+
1414
+ @ReactMethod
1415
+ public void bloxFreeSpace(Promise promise) {
1416
+ ThreadUtils.runOnExecutor(() -> {
1417
+ Log.d("ReactNative", "bloxFreeSpace");
1418
+ try {
1419
+ byte[] result = this.fula.bloxFreeSpace();
1420
+ String resultString = toString(result);
1421
+ Log.d("ReactNative", "result string="+resultString);
1422
+ promise.resolve(resultString);
1423
+ } catch (Exception e) {
1424
+ Log.d("ReactNative", e.getMessage());
1425
+ promise.reject(e);
1426
+ }
1427
+ });
1428
+ }
1429
+
1430
+ @ReactMethod
1431
+ public void wifiRemoveall(Promise promise) {
1432
+ ThreadUtils.runOnExecutor(() -> {
1433
+ Log.d("ReactNative", "wifiRemoveall");
1434
+ try {
1435
+ byte[] result = this.fula.wifiRemoveall();
1436
+ String resultString = toString(result);
1437
+ Log.d("ReactNative", "result string="+resultString);
1438
+ promise.resolve(resultString);
1439
+ } catch (Exception e) {
1440
+ Log.d("ReactNative", e.getMessage());
1441
+ promise.reject(e);
1442
+ }
1443
+ });
1444
+ }
1445
+
1446
+ @ReactMethod
1447
+ public void reboot(Promise promise) {
1448
+ ThreadUtils.runOnExecutor(() -> {
1449
+ Log.d("ReactNative", "reboot");
1450
+ try {
1451
+ byte[] result = this.fula.reboot();
1452
+ String resultString = toString(result);
1453
+ Log.d("ReactNative", "result string="+resultString);
1454
+ promise.resolve(resultString);
1455
+ } catch (Exception e) {
1456
+ Log.d("ReactNative", e.getMessage());
1457
+ promise.reject(e);
1458
+ }
1459
+ });
1460
+ }
1461
+
1462
+ @ReactMethod
1463
+ public void eraseBlData(Promise promise) {
1464
+ ThreadUtils.runOnExecutor(() -> {
1465
+ Log.d("ReactNative", "eraseBlData");
1466
+ try {
1467
+ byte[] result = this.fula.eraseBlData();
1468
+ String resultString = toString(result);
1469
+ Log.d("ReactNative", "result string="+resultString);
1470
+ promise.resolve(resultString);
1471
+ } catch (Exception e) {
1472
+ Log.d("ReactNative", e.getMessage());
1473
+ promise.reject(e);
1474
+ }
1475
+ });
1476
+ }
1477
+
1478
+ @ReactMethod
1479
+ public void testData(String identityString, String bloxAddr, Promise promise) {
1480
+ try {
1481
+ byte[] identity = toByte(identityString);
1482
+ byte[] peerIdByte = this.newClientInternal(identity, "", bloxAddr, "", true, true, true);
1483
+
1484
+ String peerIdReturned = Arrays.toString(peerIdByte);
1485
+ Log.d("ReactNative", "newClient peerIdReturned= " + peerIdReturned);
1486
+ String peerId = this.fula.id();
1487
+ Log.d("ReactNative", "newClient peerId= " + peerId);
1488
+ byte[] bytes = {1, 85, 18, 32, 11, -31, 75, -78, -109, 11, -111, 97, -47, -78, -22, 84, 39, -117, -64, -70, -91, 55, -23, -80, 116, -123, -97, -26, 126, -70, -76, 35, 54, -106, 55, -9};
1489
+
1490
+ byte[] key = this.fula.put(bytes, 85);
1491
+ Log.d("ReactNative", "testData put result string="+Arrays.toString(key));
1492
+
1493
+ byte[] value = this.fula.get(key);
1494
+ Log.d("ReactNative", "testData get result string="+Arrays.toString(value));
1495
+
1496
+ this.fula.push(key);
1497
+ //this.fula.flush();
1498
+
1499
+ byte[] fetchedVal = this.fula.get(key);
1500
+ this.fula.pull(key);
1501
+
1502
+ promise.resolve(Arrays.toString(fetchedVal));
1503
+ } catch (Exception e) {
1504
+ Log.d("ReactNative", "ERROR:" + e.getMessage());
1505
+ promise.reject(e);
1506
+ }
1507
+ }
1508
+
1509
+ }