在Android客戶端使用Web3j建立錢包、匯入錢包時都可能會產生OOM,相關issue在Github上已經有所提及:https://github.com/web3j/web3j/issues/299 。這個問題在Web3j 3.0版本以前是沒有的,由於 新版的Web3j使用spongycastle庫替換了lambdaworks庫,雖然在效率上提升了速度,但存在Android端的相容性問題。
本專案程式碼地址:https://github.com/uncleleonfan/WalletOOM.git
建立錢包OOM解決
在建立錢包時,如果建立一個Full Wallet,則會導致OOM:
public void onCreateFullWallet(View view) {
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/full";
File file = new File(filePath);
file.mkdirs();
try {
WalletUtils.generateFullNewWalletFile("a12345678", file);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (CipherException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
複製程式碼
Log如下:
"Caused by: java.lang.OutOfMemoryError: Failed to allocate a 1036 byte allocation with 16777216 free bytes and 48MB until OOM; failed due to fragmentation (required continguous free 16384 bytes for a new buffer where largest contiguous free 8192 bytes)",
"\tat org.spongycastle.util.Arrays.clone(Arrays.java:602)",
"\tat org.spongycastle.crypto.generators.SCrypt.SMix(SCrypt.java:126)",
"\tat org.spongycastle.crypto.generators.SCrypt.MFcrypt(SCrypt.java:87)",
"\tat org.spongycastle.crypto.generators.SCrypt.generate(SCrypt.java:66)",
"\tat org.web3j.crypto.Wallet.generateDerivedScryptKey(Wallet.java:136)",
"\tat org.web3j.crypto.Wallet.create(Wallet.java:74)",
"\tat org.web3j.crypto.Wallet.createStandard(Wallet.java:93)",
"\tat org.web3j.crypto.WalletUtils.generateWalletFile(WalletUtils.java:61)"
複製程式碼
generateFullNewWalletFile裡面會呼叫createStandard建立錢包,使用N_STANDARD,P_STANDARD來配置加密強度,直接影響需使用的記憶體大小,最終導致OOM的發生。
public static WalletFile createStandard(String password, ECKeyPair ecKeyPair)
throws CipherException {
return create(password, ecKeyPair, N_STANDARD, P_STANDARD);
}
複製程式碼
解決方法非常簡單,建立一個Light Wallet即可:
public void onCreateLightWallet(View view) {
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/light";
File file = new File(filePath);
file.mkdirs();
try {
WalletUtils.generateLightNewWalletFile("a12345678", file);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (CipherException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
複製程式碼
generateLightNewWalletFile會呼叫createLight來建立一個輕錢包,使用N_LIGHT,P_LIGHT,他們在數值上相對較小,所以 不會OOM。
public static WalletFile createLight(String password, ECKeyPair ecKeyPair)
throws CipherException {
return create(password, ecKeyPair, N_LIGHT, P_LIGHT);
}
複製程式碼
我們可以對比一下N_STANDARD和P_STANDARD, N_LIGHT和P_LIGHT的大小:
private static final int N_LIGHT = 1 << 12;
private static final int P_LIGHT = 6;
private static final int N_STANDARD = 1 << 18;
private static final int P_STANDARD = 1;
複製程式碼
匯入錢包OOM解決
當我們匯入一個輕錢包時,不會產生OOM,但匯入不是一個輕錢包時,則有可能產生OOM。例如,我們使用Imtoken建立一個錢包並匯出Keystore, Keystore如下:
{"address":"9a2e2419f3af050d4730f80e7a65b9f8deb5e16f","crypto":{"cipher":"aes-128-ctr","cipherparams":{"iv":"eaccea79c27a91e307f24988186ef21a"},"ciphertext":"a163e532edf2d76beaee5c26fd2c2fab071a9cb37627aa185ac89e223e41ab97","kdf":"scrypt","kdfparams":{"dklen":32,"n":65536,"p":1,"r":8,"salt":"6a847392a029553f4152dea7bb0b6fb0ac9eec29f55e572fe94603182f5ed7f1"},"mac":"3fad2a31e18c611b10df84db9ae368ce2e189b5c35e9f111e40ca4b4bfb02491"},"id":"032c47c2-c7b7-46f8-a3f7-f526580f6f09","version":3}
複製程式碼
可以看到,其中n為65536,p為1,而輕錢包的n為1<<12,即2的12次方,4096,所以這不是一個輕錢包。 我們將該Keystore作為一個json檔案push到SD卡中,然後使用Web3j進行匯入:
public void onImportWallet(View view) {
try {
//需提前將assets目錄下的keystore.json檔案推送到手機SD裡面
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/keystore.json";
File file = new File(filePath);
WalletUtils.loadCredentials("a12345678", file);
} catch (IOException e) {
e.printStackTrace();
} catch (CipherException e) {
e.printStackTrace();
}
}
複製程式碼
發現同樣會OOM:
Caused by: java.lang.OutOfMemoryError: Failed to allocate a 1036 byte allocation with 13588800 free bytes and 12MB until OOM; failed due to fragmentation (required continguous free 16384 bytes for a new buffer where largest contiguous free 12288 bytes)
at org.spongycastle.util.Arrays.clone(Arrays.java:602)
at org.spongycastle.crypto.generators.SCrypt.SMix(SCrypt.java:126)
at org.spongycastle.crypto.generators.SCrypt.MFcrypt(SCrypt.java:87)
at org.spongycastle.crypto.generators.SCrypt.generate(SCrypt.java:66)
at org.web3j.crypto.Wallet.generateDerivedScryptKey(Wallet.java:136)
at org.web3j.crypto.Wallet.decrypt(Wallet.java:214)
at org.web3j.crypto.WalletUtils.loadCredentials(WalletUtils.java:112)
複製程式碼
通過log可以看出來,這裡和建立錢包的OOM是一樣的,都是最後呼叫generateDerivedScryptKey後導致:
private static byte[] generateDerivedScryptKey(
byte[] password, byte[] salt, int n, int r, int p, int dkLen) throws CipherException {
return SCrypt.generate(password, salt, n, r, p, dkLen);
}
複製程式碼
建立錢包可以建立一個輕錢包,匯入錢包總不能讓使用者換一個輕錢包來匯入吧。這裡,我們只能還是換回lambda庫來完成keystore的編解碼, 即我們可以自己寫一個generateDerivedScryptKey方法,將spongycastle的SCrypt換成lambda的SCrypt。我們使用MyWalletUtils和MyWallet 共同完成該任務。
public void onImportWallet(View view) {
try {
//需提前將assets目錄下的keystore.json檔案推送到手機SD裡面
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/keystore.json";
File file = new File(filePath);
Credentials credentials = MyWalletUtils.loadCredentials("a12345678", file);
Log.d(TAG, "address:" + credentials.getAddress());
} catch (IOException e) {
e.printStackTrace();
} catch (CipherException e) {
e.printStackTrace();
}
}
public class MyWalletUtils {
public static Credentials loadCredentials(String password, File source)
throws IOException, CipherException {
WalletFile walletFile = objectMapper.readValue(source, WalletFile.class);
return Credentials.create(MyWallet.decrypt(password, walletFile));
}
}
public class MyWallet {
private static final int CURRENT_VERSION = 3;
private static final String CIPHER = "aes-128-ctr";
static final String AES_128_CTR = "pbkdf2";
static final String SCRYPT = "scrypt";
private static byte[] generateDerivedScryptKey(
byte[] password, byte[] salt, int n, int r, int p, int dkLen) {
try {
return SCrypt.scrypt(password, salt, n, r, p, dkLen);
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
return null;
}
}
複製程式碼
按照以上方法處理之後,就可以解決OOM,但是使用者等待的時間會稍微長一點,另外,最好還是新增一下Android平臺的libscrpt.so庫,大家可在本專案的jniLibs中找到。