Skip to content

Commit

Permalink
Merge pull request #65 from functionland/directoy-not-found-resolve
Browse files Browse the repository at this point in the history
Changed wnfs-android version to match v1.8.0
  • Loading branch information
ehsan6sha authored Aug 2, 2023
2 parents d256f18 + 47937b2 commit aec16af
Show file tree
Hide file tree
Showing 5 changed files with 193 additions and 77 deletions.
2 changes: 1 addition & 1 deletion android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ dependencies {
//noinspection GradleDynamicVersion
implementation "com.facebook.react:react-native:+" // From node_modules
implementation 'com.github.functionland:fula-build-aar:1.13.1' // From jitpack.io
implementation 'com.github.functionland:wnfs-android:v1.7.3' // From jitpack.io
implementation 'com.github.functionland:wnfs-android:v1.8.0' // From jitpack.io
implementation 'commons-io:commons-io:20030203.000550'
implementation 'commons-codec:commons-codec:1.15'
// implementation files('mobile.aar')
Expand Down
44 changes: 33 additions & 11 deletions android/src/main/java/land/fx/fula/FulaModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.ArrayList;

Expand Down Expand Up @@ -62,6 +63,8 @@ public void initialize() {

Client client;
Config fulaConfig;

String appName;
String appDir;
String fulaStorePath;
land.fx.wnfslib.Config rootConfig;
Expand Down Expand Up @@ -110,6 +113,7 @@ public byte[] put(@NonNull byte[] cid, byte[] data) {

public FulaModule(ReactApplicationContext reactContext) {
super(reactContext);
appName = reactContext.getPackageName();
appDir = reactContext.getFilesDir().toString();
fulaStorePath = appDir + "/fula";
File storeDir = new File(fulaStorePath);
Expand All @@ -119,9 +123,9 @@ public FulaModule(ReactApplicationContext reactContext) {
success = storeDir.mkdirs();
}
if (success) {
Log.d(NAME, "Fula store folder created");
Log.d("ReactNative", "Fula store folder created for " + appName + " at " + fulaStorePath);
} else {
Log.d(NAME, "Unable to create fula store folder!");
Log.d("ReactNative", "Unable to create fula store folder for " + appName + " at " + fulaStorePath);
}
}

Expand Down Expand Up @@ -503,7 +507,8 @@ private byte[] createPeerIdentity(byte[] identity) throws GeneralSecurityExcepti
throw new GeneralSecurityException("Failed to generate key encryption", e);
}

if (encryptedLibp2pId == null || !encryptedLibp2pId.startsWith("FULA_ENC_V3:")) {
if (encryptedLibp2pId == null || !encryptedLibp2pId.startsWith("FULA_" +
"ENC_V4:")) {
Log.d("ReactNative", "encryptedLibp2pId is not correct. creating new one " + encryptedLibp2pId);

try {
Expand All @@ -512,14 +517,14 @@ private byte[] createPeerIdentity(byte[] identity) throws GeneralSecurityExcepti
Log.d("ReactNative", "Failed to generate libp2pId: " + e.getMessage());
throw new GeneralSecurityException("Failed to generate libp2pId", e);
}
encryptedLibp2pId = "FULA_ENC_V3:" + Cryptography.encryptMsg(StaticHelper.bytesToBase64(libp2pId), encryptionSecretKey, null);
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_V3:", ""), encryptionSecretKey);
String decryptedLibp2pId = Cryptography.decryptMsg(encryptedLibp2pId.replace("FULA_ENC_V4:", ""), encryptionSecretKey);

return StaticHelper.base64ToBytes(decryptedLibp2pId);
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException e) {
Expand All @@ -534,17 +539,33 @@ private byte[] createPeerIdentity(byte[] identity) throws GeneralSecurityExcepti
}

private void createNewRootConfig(FulaModule.Client iClient, byte[] identity) throws Exception {
this.rootConfig = Fs.init(iClient, identity);
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);
Fs.loadWithWNFSKey(iClient, wnfsKey, rootCid);
byte[] hash32 = getSHA256Hash(wnfsKey);
Log.d("ReactNative", "wnfsKey=" + bytesToHex(wnfsKey) + "; hash32 = " + bytesToHex(hash32));
Fs.loadWithWNFSKey(iClient, hash32, rootCid);
Log.d("ReactNative", "reloadFS completed");
}

Expand All @@ -555,7 +576,7 @@ private boolean encrypt_and_store_config() throws Exception {

String cid_encrypted = Cryptography.encryptMsg(this.rootConfig.getCid(), this.secretKeyGlobal, null);

sharedPref.add("FULA_ENC_V3:cid_encrypted_" + this.identityEncryptedGlobal, cid_encrypted);
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");
Expand All @@ -575,11 +596,11 @@ private boolean logoutInternal(byte[] identity, String storePath) throws Excepti
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_V3:cid_encrypted_"+ identity_encrypted);
sharedPref.remove("FULA_ENC_V4:cid_encrypted_"+ identity_encrypted);

//TODO: Should also remove peerid @Mahdi

sharedPref.remove("FULA_ENC_V3:cid_encrypted_"+ identity_encrypted);
sharedPref.remove("FULA_ENC_V4:cid_encrypted_"+ identity_encrypted);

this.rootConfig = null;
this.secretKeyGlobal = null;
Expand Down Expand Up @@ -670,7 +691,7 @@ private String[] initInternal(byte[] identity, String storePath, String bloxAddr
Log.d("ReactNative", "this.rootCid is empty.");
//Load from keystore

String cid_encrypted_fetched = sharedPref.getValue("FULA_ENC_V3:cid_encrypted_"+ identity_encrypted);
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()) {
Expand Down Expand Up @@ -904,6 +925,7 @@ public void readFile(String fulaTargetFilename, String localFilename, Promise pr
ThreadUtils.runOnExecutor(() -> {
Log.d("ReactNative", "readFile: fulaTargetFilename = " + fulaTargetFilename);
try {
Log.d("ReactNative", "readFile: localFilename = " + localFilename + " fulaTargetFilename = " + fulaTargetFilename + " cid = " + this.rootConfig.getCid() + " client = " + this.client);
String path = Fs.readFilestreamToPath(this.client, this.rootConfig.getCid(), fulaTargetFilename, localFilename);
promise.resolve(path);
} catch (Exception e) {
Expand Down
57 changes: 52 additions & 5 deletions example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,29 @@ const App = () => {
}}
color={inprogress ? 'green' : 'blue'}
/>
<Button
//12D3KooWMMt4C3FKui14ai4r1VWwznRw6DoP5DcgTfzx2D5VZoWx
title={
inprogress
? 'Putting & Getting...'
: 'set auth'
}
onPress={async () => {
try {
fula
.setAuth('12D3KooWMMt4C3FKui14ai4r1VWwznRw6DoP5DcgTfzx2D5VZoWx', true)
.then((res: any) => {
console.log('tested');
console.log(res);
})
.catch((e: any) => {
console.log('test failed');
console.log(e);
});
} catch (e) {}
}}
color={inprogress ? 'green' : 'blue'}
/>

<Button
title={
Expand Down Expand Up @@ -189,30 +212,35 @@ const App = () => {
<Button
title={inprogress ? 'Putting & Getting...' : 'Write WNFS'}
onPress={async () => {
const unixTimestamp: number = Math.floor(Date.now() / 1000);
try {
if (initComplete) {
console.log('initialization is completed. putting key/value');
var path = RNFS.DocumentDirectoryPath + '/test.txt';
RNFS.writeFile(path, 'test', 'utf8')
RNFS.writeFile(path, 'test ' + unixTimestamp, 'utf8')
.then((success: any) => {
console.log(
'FILE WRITTEN in ' +
RNFS.DocumentDirectoryPath +
'/test.txt'
'/test.txt with ' +
unixTimestamp
);
console.log(success);
fula
.writeFile(
'root/test.txt',
'root/test_' + unixTimestamp + '.txt',
RNFS.DocumentDirectoryPath + '/test.txt'
)
.then((res: any) => {
console.log('upload completed');
console.log(res);
fula
.readFile(
'root/test.txt',
RNFS.DocumentDirectoryPath + '/test2.txt'
'root/test_' + unixTimestamp + '.txt',
RNFS.DocumentDirectoryPath +
'/test_' +
unixTimestamp +
'.txt'
)
.then((res2: any) => {
console.log('read completed ' + res2);
Expand All @@ -231,6 +259,25 @@ const App = () => {
color={inprogress ? 'green' : 'blue'}
/>

<Button
title={inprogress ? 'List' : 'List'}
onPress={async () => {
try {
fula
.ls('root')
.then((res: any) => {
console.log('tested');
console.log(res);
})
.catch((e: any) => {
console.log('test failed');
console.log(e);
});
} catch (e) {}
}}
color={inprogress ? 'green' : 'blue'}
/>

<Button
title={inprogress ? 'Putting & Getting...' : 'Check Failes'}
onPress={async () => {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@functionland/react-native-fula",
"version": "1.13.1",
"version": "1.14.0",
"description": "This package is a bridge to use the Fula libp2p protocols in the react-native which is using wnfs",
"main": "lib/commonjs/index",
"module": "lib/module/index",
Expand Down
Loading

0 comments on commit aec16af

Please sign in to comment.