-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathFulaModule.java
More file actions
executable file
·1477 lines (1346 loc) · 55.4 KB
/
FulaModule.java
File metadata and controls
executable file
·1477 lines (1346 loc) · 55.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package land.fx.fula;
import android.util.Log;
import androidx.annotation.NonNull;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.ReadableArray;
import org.apache.commons.io.FileUtils;
import org.jetbrains.annotations.Contract;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.ArrayList;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import fulamobile.Config;
import fulamobile.Fulamobile;
import land.fx.wnfslib.Fs;
@ReactModule(name = FulaModule.NAME)
public class FulaModule extends ReactContextBaseJavaModule {
@Override
public void initialize() {
System.loadLibrary("wnfslib");
System.loadLibrary("gojni");
}
public static final String NAME = "FulaModule";
fulamobile.Client fula;
Client client;
Config fulaConfig;
String appName;
String appDir;
String fulaStorePath;
land.fx.wnfslib.Config rootConfig;
SharedPreferenceHelper sharedPref;
SecretKey secretKeyGlobal;
String identityEncryptedGlobal;
static String PRIVATE_KEY_STORE_PEERID = "PRIVATE_KEY";
public static class Client implements land.fx.wnfslib.Datastore {
private final fulamobile.Client internalClient;
Client(fulamobile.Client clientInput) {
this.internalClient = clientInput;
}
@NonNull
@Override
public byte[] get(@NonNull byte[] cid) {
try {
Log.d("ReactNative", Arrays.toString(cid));
return this.internalClient.get(cid);
} catch (Exception e) {
e.printStackTrace();
}
Log.d("ReactNative","Error get");
return cid;
}
@NonNull
@Override
public byte[] put(@NonNull byte[] cid, byte[] data) {
try {
long codec = (long)cid[1] & 0xFF;
byte[] put_cid = this.internalClient.put(data, codec);
//Log.d("ReactNative", "data="+ Arrays.toString(data) +" ;codec="+codec);
return put_cid;
} catch (Exception e) {
Log.d("ReactNative", "put Error="+e.getMessage());
e.printStackTrace();
}
Log.d("ReactNative","Error put");
return data;
}
}
public FulaModule(ReactApplicationContext reactContext) {
super(reactContext);
appName = reactContext.getPackageName();
appDir = reactContext.getFilesDir().toString();
fulaStorePath = appDir + "/fula";
File storeDir = new File(fulaStorePath);
sharedPref = SharedPreferenceHelper.getInstance(reactContext.getApplicationContext());
boolean success = true;
if (!storeDir.exists()) {
success = storeDir.mkdirs();
}
if (success) {
Log.d("ReactNative", "Fula store folder created for " + appName + " at " + fulaStorePath);
} else {
Log.d("ReactNative", "Unable to create fula store folder for " + appName + " at " + fulaStorePath);
}
}
@Override
@NonNull
public java.lang.String getName() {
return NAME;
}
private byte[] toByte(@NonNull String input) {
return input.getBytes(StandardCharsets.UTF_8);
}
private byte[] decToByte(@NonNull String input) {
String[] parts = input.split(",");
byte[] output = new byte[parts.length];
for (int i = 0; i < parts.length; i++) {
output[i] = Byte.parseByte(parts[i]);
}
return output;
}
@NonNull
@Contract("_ -> new")
public String toString(byte[] input) {
return new String(input, StandardCharsets.UTF_8);
}
@NonNull
private static int[] stringArrToIntArr(@NonNull String[] s) {
int[] result = new int[s.length];
for (int i = 0; i < s.length; i++) {
result[i] = Integer.parseInt(s[i]);
}
return result;
}
@NonNull
@Contract(pure = true)
private static byte[] convertIntToByte(@NonNull int[] input) {
byte[] result = new byte[input.length];
for (int i = 0; i < input.length; i++) {
byte b = (byte) input[i];
result[i] = b;
}
return result;
}
@NonNull
private byte[] convertStringToByte(@NonNull String data) {
String[] keyInt_S = data.split(",");
int[] keyInt = stringArrToIntArr(keyInt_S);
return convertIntToByte(keyInt);
}
@ReactMethod
public void checkConnection(int timeout, Promise promise) {
Log.d("ReactNative", "checkConnection started");
ThreadUtils.runOnExecutor(() -> {
if (this.fula != null) {
try {
boolean connectionStatus = this.checkConnectionInternal(timeout);
Log.d("ReactNative", "checkConnection ended " + connectionStatus);
promise.resolve(connectionStatus);
}
catch (Exception e) {
Log.d("ReactNative", "checkConnection failed with Error: " + e.getMessage());
promise.resolve(false);
}
} else {
Log.d("ReactNative", "checkConnection failed with Error: " + "fula is null");
promise.resolve(false);
}
});
}
@ReactMethod
public void newClient(String identityString, String storePath, String bloxAddr, String exchange, boolean autoFlush, boolean useRelay, boolean refresh, Promise promise) {
Log.d("ReactNative", "newClient started");
ThreadUtils.runOnExecutor(() -> {
try {
Log.d("ReactNative", "newClient storePath= " + storePath + " bloxAddr= " + bloxAddr + " exchange= " + exchange + " autoFlush= " + autoFlush + " useRelay= " + useRelay + " refresh= " + refresh);
byte[] identity = toByte(identityString);
Log.d("ReactNative", "newClient identity= " + identityString);
this.newClientInternal(identity, storePath, bloxAddr, exchange, autoFlush, useRelay, refresh);
//String objString = Arrays.toString(obj);
String peerId = this.fula.id();
Log.d("ReactNative", "newClient peerId= " + peerId);
promise.resolve(peerId);
} catch (Exception e) {
Log.d("ReactNative", "newClient failed with Error: " + e.getMessage());
promise.reject("Error", e.getMessage());
}
});
}
@ReactMethod
public void isReady(boolean filesystemCheck, Promise promise) {
Log.d("ReactNative", "isReady started");
ThreadUtils.runOnExecutor(() -> {
boolean initialized = false;
try {
if (this.fula != null && this.fula.id() != null) {
if (filesystemCheck) {
if (this.client != null && this.rootConfig != null && !this.rootConfig.getCid().isEmpty()) {
initialized = true;
Log.d("ReactNative", "isReady is true with filesystem check");
}
} else {
Log.d("ReactNative", "isReady is true without filesystem check");
initialized = true;
}
}
promise.resolve(initialized);
} catch (Exception e) {
Log.d("ReactNative", "isReady failed with Error: " + e.getMessage());
promise.reject("Error", e.getMessage());
}
});
}
@ReactMethod
public void init(String identityString, String storePath, String bloxAddr, String exchange, boolean autoFlush, String rootConfig, boolean useRelay, boolean refresh, Promise promise) {
Log.d("ReactNative", "init started");
ThreadUtils.runOnExecutor(() -> {
try {
WritableMap resultData = new WritableNativeMap();
Log.d("ReactNative", "init storePath= " + storePath);
byte[] identity = toByte(identityString);
Log.d("ReactNative", "init identity= " + identityString);
String[] obj = this.initInternal(identity, storePath, bloxAddr, exchange, autoFlush, rootConfig, useRelay, refresh);
Log.d("ReactNative", "init object created: [ " + obj[0] + ", " + obj[1] + " ]");
resultData.putString("peerId", obj[0]);
resultData.putString("rootCid", obj[1]);
promise.resolve(resultData);
} catch (Exception e) {
Log.d("ReactNative", "init failed with Error: " + e.getMessage());
promise.reject("Error", e.getMessage());
}
});
}
@ReactMethod
public void logout(String identityString, String storePath, Promise promise) {
Log.d("ReactNative", "logout started");
ThreadUtils.runOnExecutor(() -> {
try {
byte[] identity = toByte(identityString);
boolean obj = this.logoutInternal(identity, storePath);
Log.d("ReactNative", "logout completed");
promise.resolve(obj);
} catch (Exception e) {
Log.d("ReactNative", "logout failed with Error: " + e.getMessage());
promise.reject("Error", e.getMessage());
}
});
}
private boolean checkConnectionInternal(int timeout) throws Exception {
try {
Log.d("ReactNative", "checkConnectionInternal started");
if (this.fula != null) {
try {
Log.d("ReactNative", "connectToBlox started");
AtomicBoolean connectionStatus = new AtomicBoolean(false);
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
Future<?> future = executor.submit(() -> {
try {
this.fula.connectToBlox();
connectionStatus.set(true);
Log.d("ReactNative", "checkConnectionInternal succeeded ");
} catch (Exception e) {
Log.d("ReactNative", "checkConnectionInternal failed with Error: " + e.getMessage());
}
});
try {
future.get(timeout, TimeUnit.SECONDS);
} catch (TimeoutException te) {
// If the timeout occurs, shut down the executor and return false
executor.shutdownNow();
return false;
} finally {
// If the future task is done, we can shut down the executor
if (future.isDone()) {
executor.shutdown();
}
}
return connectionStatus.get();
} catch (Exception e) {
Log.d("ReactNative", "checkConnectionInternal failed with Error: " + e.getMessage());
return false;
}
} else {
Log.d("ReactNative", "checkConnectionInternal failed because fula is not initialized ");
return false;
}
} catch (Exception e) {
Log.d("ReactNative", "checkConnectionInternal failed with Error: " + e.getMessage());
throw (e);
}
}
@ReactMethod
public void checkFailedActions(boolean retry, int timeout, Promise promise) throws Exception {
try {
if (this.fula != null) {
if (!retry) {
Log.d("ReactNative", "checkFailedActions without retry");
fulamobile.LinkIterator failedLinks = this.fula.listFailedPushes();
if (failedLinks.hasNext()) {
Log.d("ReactNative", "checkFailedActions found: "+Arrays.toString(failedLinks.next()));
promise.resolve(true);
} else {
promise.resolve(false);
}
} else {
Log.d("ReactNative", "checkFailedActions with retry");
boolean retryResults = this.retryFailedActionsInternal(timeout);
promise.resolve(!retryResults);
}
} else {
throw new Exception("Fula is not initialized");
}
} catch (Exception e) {
Log.d("ReactNative", "checkFailedActions failed with Error: " + e.getMessage());
throw (e);
}
}
@ReactMethod
private void listFailedActions(ReadableArray cids, Promise promise) throws Exception {
try {
if (this.fula != null) {
Log.d("ReactNative", "listFailedActions");
fulamobile.StringIterator failedLinks = this.fula.listFailedPushesAsString();
ArrayList<String> failedLinksList = new ArrayList<>();
while (failedLinks.hasNext()) {
failedLinksList.add(failedLinks.next());
}
if (cids.size() > 0) {
// If cids array is provided, filter the failedLinksList
ArrayList<String> cidsList = new ArrayList<>();
for (int i = 0; i < cids.size(); i++) {
cidsList.add(cids.getString(i));
}
cidsList.retainAll(failedLinksList); // Keep only the elements in both cidsList and failedLinksList
if (!cidsList.isEmpty()) {
// If there are any matching cids, return them
WritableArray cidsArray = Arguments.createArray();
for (String cid : cidsList) {
cidsArray.pushString(cid);
}
promise.resolve(cidsArray);
} else {
// If there are no matching cids, return false
promise.resolve(false);
}
} else if (!failedLinksList.isEmpty()) {
// If cids array is not provided, return the whole list
Log.d("ReactNative", "listFailedActions found: "+ failedLinksList);
WritableArray failedLinksArray = Arguments.createArray();
for (String link : failedLinksList) {
failedLinksArray.pushString(link);
}
promise.resolve(failedLinksArray);
} else {
promise.resolve(false);
}
} else {
throw new Exception("listFailedActions: Fula is not initialized");
}
} catch (Exception e) {
Log.d("ReactNative", "listFailedActions failed with Error: " + e.getMessage());
throw (e);
}
}
private boolean retryFailedActionsInternal(int timeout) throws Exception {
try {
Log.d("ReactNative", "retryFailedActionsInternal started");
if (this.fula != null) {
//Fula is initialized
try {
boolean connectionCheck = this.checkConnectionInternal(timeout);
if(connectionCheck) {
try {
Log.d("ReactNative", "retryFailedPushes started");
this.fula.retryFailedPushes();
Log.d("ReactNative", "flush started");
this.fula.flush();
return true;
}
catch (Exception e) {
this.fula.flush();
Log.d("ReactNative", "retryFailedActionsInternal failed with Error: " + e.getMessage());
return false;
}
//Blox online
/*fulamobile.LinkIterator failedLinks = this.fula.listFailedPushes();
if (failedLinks.hasNext()) {
Log.d("ReactNative", "Failed links");
//Failed list is not empty. iterate in the list
while (failedLinks.hasNext()) {
//Get the missing key
byte[] failedNode = failedLinks.next();
try {
//Push to Blox
Log.d("ReactNative", "Pushing Failed links "+Arrays.toString(failedNode));
this.pushInternal(failedNode);
Log.d("ReactNative", "Failed links pushed");
}
catch (Exception e) {
Log.d("ReactNative", "retryFailedActionsInternal failed with Error: " + e.getMessage());
}
}
//check if list is empty now and all are pushed
Log.d("ReactNative", "Pushing finished");
fulamobile.LinkIterator failedLinks_after = this.fula.listFailedPushes();
if(failedLinks_after.hasNext()) {
//Some pushes failed
byte[] first_failed = failedLinks_after.next();
Log.d("ReactNative", "Failed links are not empty "+Arrays.toString(first_failed));
return false;
} else {
//All pushes successful
return true;
}
} else {
Log.d("ReactNative", "No Failed links");
//Failed list is empty
return true;
}*/
} else {
Log.d("ReactNative", "retryFailedActionsInternal failed because blox is offline");
//Blox Offline
return false;
}
}
catch (Exception e) {
Log.d("ReactNative", "retryFailedActionsInternal failed with Error: " + e.getMessage());
return false;
}
} else {
Log.d("ReactNative", "retryFailedActionsInternal failed because fula is not initialized");
//Fula is not initialized
return false;
}
} catch (Exception e) {
Log.d("ReactNative", "retryFailedActionsInternal failed with Error: " + e.getMessage());
throw (e);
}
}
@NonNull
private byte[] createPeerIdentity(byte[] identity) throws GeneralSecurityException, IOException {
try {
// 1: First: create public key from provided private key
// 2: Should read the local keychain store (if it is key-value, key is public key above,
// 3: if found, decrypt using the private key
// 4: If not found or decryption not successful, generate an identity
// 5: then encrypt and store in keychain
byte[] libp2pId;
String encryptedLibp2pId = sharedPref.getValue(PRIVATE_KEY_STORE_PEERID);
byte[] encryptionPair;
SecretKey encryptionSecretKey;
try {
encryptionSecretKey = Cryptography.generateKey(identity);
Log.d("ReactNative", "encryptionSecretKey generated from privateKey");
} catch (Exception e) {
Log.d("ReactNative", "Failed to generate key for encryption: " + e.getMessage());
throw new GeneralSecurityException("Failed to generate key encryption", e);
}
if (encryptedLibp2pId == null || !encryptedLibp2pId.startsWith("FULA_" +
"ENC_V4:")) {
Log.d("ReactNative", "encryptedLibp2pId is not correct. creating new one " + encryptedLibp2pId);
try {
libp2pId = Fulamobile.generateEd25519KeyFromString(toString(identity));
} catch (Exception e) {
Log.d("ReactNative", "Failed to generate libp2pId: " + e.getMessage());
throw new GeneralSecurityException("Failed to generate libp2pId", e);
}
encryptedLibp2pId = "FULA_ENC_V4:" + Cryptography.encryptMsg(StaticHelper.bytesToBase64(libp2pId), encryptionSecretKey, null);
sharedPref.add(PRIVATE_KEY_STORE_PEERID, encryptedLibp2pId);
} else {
Log.d("ReactNative", "encryptedLibp2pId is correct. decrypting " + encryptedLibp2pId);
}
try {
String decryptedLibp2pId = Cryptography.decryptMsg(encryptedLibp2pId.replace("FULA_ENC_V4:", ""), encryptionSecretKey);
return StaticHelper.base64ToBytes(decryptedLibp2pId);
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException e) {
Log.d("ReactNative", "createPeerIdentity decryptMsg failed with Error: " + e.getMessage());
throw (e);
}
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException e) {
Log.d("ReactNative", "createPeerIdentity failed with Error: " + e.getMessage());
throw (e);
}
}
private void createNewRootConfig(FulaModule.Client iClient, byte[] identity) throws Exception {
byte[] hash32 = getSHA256Hash(identity);
this.rootConfig = Fs.init(iClient, hash32);
Log.d("ReactNative", "rootConfig is created " + this.rootConfig.getCid());
if (this.fula != null) {
this.fula.flush();
}
this.encrypt_and_store_config();
}
public static byte[] getSHA256Hash(byte[] input) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
return md.digest(input);
}
private static String bytesToHex(byte[] bytes) {
StringBuilder result = new StringBuilder();
for (byte b : bytes) {
result.append(String.format("%02x", b));
}
return result.toString();
}
private void reloadFS(FulaModule.Client iClient, byte[] wnfsKey, String rootCid) throws Exception {
Log.d("ReactNative", "reloadFS called: rootCid=" + rootCid);
byte[] hash32 = getSHA256Hash(wnfsKey);
Log.d("ReactNative", "wnfsKey=" + bytesToHex(wnfsKey) + "; hash32 = " + bytesToHex(hash32));
Fs.loadWithWNFSKey(iClient, hash32, rootCid);
Log.d("ReactNative", "reloadFS completed");
}
private boolean encrypt_and_store_config() throws Exception {
try {
if(this.identityEncryptedGlobal != null && !this.identityEncryptedGlobal.isEmpty()) {
Log.d("ReactNative", "encrypt_and_store_config started");
String cid_encrypted = Cryptography.encryptMsg(this.rootConfig.getCid(), this.secretKeyGlobal, null);
sharedPref.add("FULA_ENC_V4:cid_encrypted_" + this.identityEncryptedGlobal, cid_encrypted);
return true;
} else {
Log.d("ReactNative", "encrypt_and_store_config failed because identityEncryptedGlobal is empty");
return false;
}
} catch (Exception e) {
Log.d("ReactNative", "encrypt_and_store_config failed with Error: " + e.getMessage());
throw (e);
}
}
private boolean logoutInternal(byte[] identity, String storePath) throws Exception {
try {
if (this.fula != null) {
this.fula.flush();
}
SecretKey secretKey = Cryptography.generateKey(identity);
byte[] iv = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B };
String identity_encrypted = Cryptography.encryptMsg(Arrays.toString(identity), secretKey, iv);
sharedPref.remove("FULA_ENC_V4:cid_encrypted_"+ identity_encrypted);
//TODO: Should also remove peerid @Mahdi
sharedPref.remove("FULA_ENC_V4:cid_encrypted_"+ identity_encrypted);
this.rootConfig = null;
this.secretKeyGlobal = null;
this.identityEncryptedGlobal = null;
if (storePath == null || storePath.trim().isEmpty()) {
storePath = this.fulaStorePath;
}
File file = new File(storePath);
FileUtils.deleteDirectory(file);
return true;
} catch (Exception e) {
Log.d("ReactNative", "logout internal failed with Error: " + e.getMessage());
throw (e);
}
}
public fulamobile.Client getFulaClient() {
return this.fula;
}
@NonNull
private byte[] newClientInternal(byte[] identity, String storePath, String bloxAddr, String exchange, boolean autoFlush, boolean useRelay, boolean refresh) throws GeneralSecurityException, IOException {
byte[] peerIdentity = null;
try {
fulaConfig = new Config();
if (storePath == null || storePath.trim().isEmpty()) {
fulaConfig.setStorePath(this.fulaStorePath);
} else {
fulaConfig.setStorePath(storePath);
}
Log.d("ReactNative", "newClientInternal storePath is set: " + fulaConfig.getStorePath());
peerIdentity = this.createPeerIdentity(identity);
fulaConfig.setIdentity(peerIdentity);
Log.d("ReactNative", "peerIdentity is set: " + toString(fulaConfig.getIdentity()));
fulaConfig.setBloxAddr(bloxAddr);
Log.d("ReactNative", "bloxAddr is set: " + fulaConfig.getBloxAddr());
fulaConfig.setExchange(exchange);
fulaConfig.setSyncWrites(autoFlush);
if (useRelay) {
fulaConfig.setAllowTransientConnection(true);
fulaConfig.setForceReachabilityPrivate(true);
}
if (this.fula == null || refresh) {
Log.d("ReactNative", "Creating a new Fula instance");
try {
shutdownInternal();
this.fula = Fulamobile.newClient(fulaConfig);
if (this.fula != null) {
this.fula.flush();
}
} catch (Exception e) {
Log.d("ReactNative", "Failed to create new Fula instance: " + e.getMessage());
throw new IOException("Failed to create new Fula instance", e);
}
}
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException e) {
Log.d("ReactNative", "newclientInternal failed with Error: " + e.getMessage());
throw (e);
}
return peerIdentity;
}
@NonNull
private String[] initInternal(byte[] identity, String storePath, String bloxAddr, String exchange, boolean autoFlush, String rootCid, boolean useRelay, boolean refresh) throws Exception {
try {
if (this.fula == null || refresh) {
this.newClientInternal(identity, storePath, bloxAddr, exchange, autoFlush, useRelay, refresh);
}
if(this.client == null || refresh) {
this.client = new Client(this.fula);
Log.d("ReactNative", "fula initialized: " + this.fula.id());
}
SecretKey secretKey = Cryptography.generateKey(identity);
Log.d("ReactNative", "secretKey generated: " + secretKey.toString());
byte[] iv = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B };
String identity_encrypted =Cryptography.encryptMsg(Arrays.toString(identity), secretKey, iv);
Log.d("ReactNative", "identity_encrypted generated: " + identity_encrypted + " for identity: " + Arrays.toString(identity));
this.identityEncryptedGlobal = identity_encrypted;
this.secretKeyGlobal = secretKey;
if ( this.rootConfig == null || this.rootConfig.getCid().isEmpty() ) {
Log.d("ReactNative", "this.rootCid is empty.");
//Load from keystore
String cid_encrypted_fetched = sharedPref.getValue("FULA_ENC_V4:cid_encrypted_"+ identity_encrypted);
Log.d("ReactNative", "Here1");
String cid = "";
if(cid_encrypted_fetched != null && !cid_encrypted_fetched.isEmpty()) {
Log.d("ReactNative", "decrypting cid="+cid_encrypted_fetched+" with secret="+secretKey.toString());
cid = Cryptography.decryptMsg(cid_encrypted_fetched, secretKey);
}
Log.d("ReactNative", "Here2");
//Log.d("ReactNative", "Attempted to fetch cid from keystore; cid="+cid);
if(cid == null || cid.isEmpty()) {
Log.d("ReactNative", "cid was not found");
if(rootCid != null && !rootCid.isEmpty()){
Log.d("ReactNative", "Re-setting cid from input: "+rootCid);
cid = rootCid;
}
if(cid == null || cid.isEmpty()) {
Log.d("ReactNative", "Tried to recover cid but was not successful. Creating new ones");
this.createNewRootConfig(this.client, identity);
}
} else {
Log.d("ReactNative", "Recovered cid and private ref from keychain store. cid="+cid +" and cid from input was: "+rootCid);
this.rootConfig = new land.fx.wnfslib.Config(cid);
this.reloadFS(this.client, identity, cid);
this.encrypt_and_store_config();
}
Log.d("ReactNative", "creating rootConfig completed");
Log.d("ReactNative", "rootConfig is created: cid=" + this.rootConfig.getCid());
} else {
Log.d("ReactNative", "rootConfig existed: cid=" + this.rootConfig.getCid());
}
String peerId = this.fula.id();
String[] obj = new String[2];
obj[0] = peerId;
obj[1] = this.rootConfig.getCid();
Log.d("ReactNative", "initInternal is completed successfully");
if (this.fula != null) {
this.fula.flush();
}
return obj;
} catch (Exception e) {
Log.d("ReactNative", "init internal failed with Error: " + e.getMessage());
throw (e);
}
}
@ReactMethod
public void mkdir(String path, Promise promise) {
ThreadUtils.runOnExecutor(() -> {
Log.d("ReactNative", "mkdir started with: path = " + path + " rootConfig.getCid() = " + this.rootConfig.getCid());
try {
land.fx.wnfslib.Config config = Fs.mkdir(this.client, this.rootConfig.getCid(), path);
if(config != null) {
this.rootConfig = config;
this.encrypt_and_store_config();
if (this.fula != null) {
this.fula.flush();
}
String rootCid = this.rootConfig.getCid();
Log.d("ReactNative", "mkdir completed successfully with rootCid = " + rootCid);
promise.resolve(rootCid);
} else {
Log.d("ReactNative", "mkdir Error: config is null");
promise.reject(new Exception("mkdir Error: config is null"));
}
} catch (Exception e) {
Log.d("get", e.getMessage());
promise.reject(e);
}
});
}
@ReactMethod
public void writeFile(String fulaTargetFilename, String localFilename, Promise promise) {
/*
// reads content of the file form localFilename (should include full absolute path to local file with read permission
// writes content to the specified location by fulaTargetFilename in Fula filesystem
// fulaTargetFilename: a string including full path and filename of target file on Fula (e.g. root/pictures/cat.jpg)
// localFilename: a string containing full path and filename of local file on hte device (e.g /usr/bin/cat.jpg)
// Returns: new cid of the root after this file is placed in the tree
*/
ThreadUtils.runOnExecutor(() -> {
Log.d("ReactNative", "writeFile to : path = " + fulaTargetFilename + ", from: " + localFilename);
try {
if (this.client != null) {
Log.d("ReactNative", "writeFileFromPath started: this.rootConfig.getCid=" + this.rootConfig.getCid()+ ", fulaTargetFilename="+fulaTargetFilename + ", localFilename="+localFilename);
land.fx.wnfslib.Config config = Fs.writeFileStreamFromPath(this.client, this.rootConfig.getCid(), fulaTargetFilename, localFilename);
if(config != null) {
this.rootConfig = config;
this.encrypt_and_store_config();
if (this.fula != null) {
this.fula.flush();
String rootCid = this.rootConfig.getCid();
Log.d("ReactNative", "writeFileFromPath completed: this.rootConfig.getCid=" + rootCid);
promise.resolve(rootCid);
} else {
Log.d("ReactNative", "writeFile Error: fula is null");
promise.reject(new Exception("writeFile Error: fula is null"));
}
} else {
Log.d("ReactNative", "writeFile Error: config is null");
promise.reject(new Exception("writeFile Error: config is null"));
}
} else {
Log.d("ReactNative", "writeFile Error: client is null");
promise.reject(new Exception("writeFile Error: client is null"));
}
} catch (Exception e) {
Log.d("get", e.getMessage());
promise.reject(e);
}
});
}
@ReactMethod
public void writeFileContent(String path, String contentString, Promise promise) {
ThreadUtils.runOnExecutor(() -> {
Log.d("ReactNative", "writeFile: contentString = " + contentString);
Log.d("ReactNative", "writeFile: path = " + path);
try {
byte[] content = this.convertStringToByte(contentString);
land.fx.wnfslib.Config config = Fs.writeFile(this.client, this.rootConfig.getCid(), path, content);
this.rootConfig = config;
this.encrypt_and_store_config();
if (this.fula != null) {
this.fula.flush();
}
promise.resolve(config.getCid());
} catch (Exception e) {
Log.d("get", e.getMessage());
promise.reject(e);
}
});
}
@ReactMethod
public void ls(String path, Promise promise) {
ThreadUtils.runOnExecutor(() -> {
Log.d("ReactNative", "ls: path = " + path);
try {
byte[] res = Fs.ls(this.client, this.rootConfig.getCid(), path);
String s = new String(res, StandardCharsets.UTF_8);
Log.d("ReactNative", "ls: res = " + s);
promise.resolve(s);
} catch (Exception e) {
Log.d("get", e.getMessage());
promise.reject(e);
}
});
}
@ReactMethod
public void rm(String path, Promise promise) {
ThreadUtils.runOnExecutor(() -> {
Log.d("ReactNative", "rm: path = " + path + ", beginning rootCid=" + this.rootConfig.getCid());
try {
land.fx.wnfslib.Config config = Fs.rm(this.client, this.rootConfig.getCid(), path);
if(config != null) {
this.rootConfig = config;
this.encrypt_and_store_config();
if (this.fula != null) {
this.fula.flush();
}
String rootCid = config.getCid();
Log.d("ReactNative", "rm: returned rootCid = " + rootCid);
promise.resolve(rootCid);
} else {
Log.d("ReactNative", "rm Error: config is null");
promise.reject(new Exception("rm Error: config is null"));
}
} catch (Exception e) {
Log.d("get", e.getMessage());
promise.reject(e);
}
});
}
@ReactMethod
public void cp(String sourcePath, String targetPath, Promise promise) {
ThreadUtils.runOnExecutor(() -> {
Log.d("ReactNative", "rm: sourcePath = " + sourcePath);
try {
land.fx.wnfslib.Config config = Fs.cp(this.client, this.rootConfig.getCid(), sourcePath, targetPath);
if(config != null) {
this.rootConfig = config;
this.encrypt_and_store_config();
if (this.fula != null) {
this.fula.flush();
}
promise.resolve(config.getCid());
} else {
Log.d("ReactNative", "cp Error: config is null");
promise.reject(new Exception("cp Error: config is null"));
}
} catch (Exception e) {
Log.d("get", e.getMessage());
promise.reject(e);
}
});
}
@ReactMethod
public void mv(String sourcePath, String targetPath, Promise promise) {
ThreadUtils.runOnExecutor(() -> {
Log.d("ReactNative", "rm: sourcePath = " + sourcePath);
try {
land.fx.wnfslib.Config config = Fs.mv(this.client, this.rootConfig.getCid(), sourcePath, targetPath);
if(config != null) {
this.rootConfig = config;
this.encrypt_and_store_config();
if (this.fula != null) {
this.fula.flush();
}
promise.resolve(config.getCid());
} else {
Log.d("ReactNative", "mv Error: config is null");
promise.reject(new Exception("mv Error: config is null"));
}
} catch (Exception e) {
Log.d("get", e.getMessage());
promise.reject(e);
}
});
}
@ReactMethod
public void readFile(String fulaTargetFilename, String localFilename, Promise promise) {
/*
// reads content of the file form localFilename (should include full absolute path to local file with read permission
// writes content to the specified location by fulaTargetFilename in Fula filesystem
// fulaTargetFilename: a string including full path and filename of target file on Fula (e.g. root/pictures/cat.jpg)
// localFilename: a string containing full path and filename of local file on hte device (e.g /usr/bin/cat.jpg)
// Returns: new cid of the root after this file is placed in the tree
*/
ThreadUtils.runOnExecutor(() -> {
Log.d("ReactNative", "readFile: fulaTargetFilename = " + fulaTargetFilename);
try {
Log.d("ReactNative", "readFile: localFilename = " + localFilename + " fulaTargetFilename = " + fulaTargetFilename + " beginning rootCid = " + this.rootConfig.getCid());
String path = Fs.readFilestreamToPath(this.client, this.rootConfig.getCid(), fulaTargetFilename, localFilename);
promise.resolve(path);
} catch (Exception e) {
Log.d("get", e.getMessage());
promise.reject(e);
}
});
}
@ReactMethod
public void readFileContent(String path, Promise promise) {
ThreadUtils.runOnExecutor(() -> {
Log.d("ReactNative", "readFileContent: path = " + path);
try {
byte[] res = Fs.readFile(this.client, this.rootConfig.getCid(), path);
String resString = toString(res);
promise.resolve(resString);
} catch (Exception e) {
Log.d("get", e.getMessage());
promise.reject(e);
}
});
}
@ReactMethod
public void get(String keyString, Promise promise) {
ThreadUtils.runOnExecutor(() -> {
Log.d("ReactNative", "get: keyString = " + keyString);
try {
byte[] key = this.convertStringToByte(keyString);
byte[] value = this.getInternal(key);
String valueString = toString(value);
promise.resolve(valueString);
} catch (Exception e) {
Log.d("get", e.getMessage());
promise.reject(e);
}
});
}
@NonNull
private byte[] getInternal(byte[] key) throws Exception {
try {
Log.d("ReactNative", "getInternal: key.toString() = " + toString(key));
Log.d("ReactNative", "getInternal: key.toString().bytes = " + Arrays.toString(key));
byte[] value = this.fula.get(key);
Log.d("ReactNative", "getInternal: value.toString() = " + toString(value));
return value;
} catch (Exception e) {
Log.d("ReactNative", "getInternal: error = " + e.getMessage());
Log.d("getInternal", e.getMessage());
throw (e);
}
}
@ReactMethod
public void has(String keyString, Promise promise) {
ThreadUtils.runOnExecutor(() -> {
Log.d("ReactNative", "has: keyString = " + keyString);
try {
byte[] key = this.convertStringToByte(keyString);
boolean result = this.hasInternal(key);
promise.resolve(result);
} catch (Exception e) {
Log.d("get", e.getMessage());
promise.reject(e);