@functionland/react-native-fula 1.37.0 → 1.39.1

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