Ethereum (Android) Wallet series 2 – Import account and account management has been updated, please go to the original read
This is how to develop an Ethereum wallet (Android) series part 2, how to import accounts. Sometimes users may already have an account, this article will introduce how to implement the import of the user’s existing account.
Import account knowledge
In terms of users’ needs, it is necessary to import users’ existing accounts. However, for security reasons, if you have previously used an unofficial, non-open source wallet product (especially a niche wallet), or if you have not been careful to save your private key, mnemonic, or Keysotre files before. The correct approach is to prompt the user:
- Create a new wallet account in the new wallet and secure the backup (because the previous one may not be secure);
- Then transfer all the coins from the old wallet to the new account.
There are three methods for importing an account:
- Import using a private key
- Import from KeyStore
- By mnemonic import
Import an account using a private key
The key is to use the user input to the private key secret key to create an ellipse curve, and then use the secret key to create the purse, the code is as follows: (the code in the code base app/SRC/pro/upchain/wallet/utils/ETHWalletUtils Java file)
public static ETHWallet loadWalletByPrivateKey(String privateKey, String pwd) {
Credentials credentials = null;
ECKeyPair ecKeyPair = ECKeyPair.create(Numeric.toBigInt(privateKey));
return generateWallet(generateNewWalletName(), pwd, ecKeyPair);
}
Copy the code
Return statement generateWallet(), described in series 1- Creating an account by mnemonic, creating a wallet by elliptic curve secret key pair.
The second parameter of loadWalletByPrivateKey() is the password PWD, which is not needed to generate the account for the private key. It is used to encrypt the private key, i.e. to generate the keystore file.
Import the account through the KeyStore file
About KeyStore file, you can read the account KeyStore file import and export.
Key steps:
- KeyStore text content parsing WalletFile instance;
- Use the password to decode WalletFile to generate elliptic curve secret key pairs to create a wallet.
/ * * *@paramKeystore Content of the original JSON file *@paramPWD keystore Decryption password *@return* /
public static ETHWallet loadWalletByKeystore(String keystore, String pwd) {
try {
WalletFile walletFile = null;
walletFile = objectMapper.readValue(keystore, WalletFile.class);
return generateWallet(generateNewWalletName(), pwd, Wallet.decrypt(pwd, walletFile));
} catch (IOException e) {
} catch (CipherException e) {
}
return null;
}
Copy the code
Import an account using a mnemonic
Import is very similar to the creation in the previous article, except that the seed is generated by a user-supplied mnemonic.
When importing an account using a mnemonic, the user also needs to select (or enter) a push path (see BIP44). The key steps are:
- Create random number seeds through mnemonic words;
- Generate private key through seed + path derivation to create wallet;
/** * Import wallet ** by importing mnemonic **@paramPath Bip44 Path *@paramList of mnemonics *@paramThe PWD password *@return* /
public static ETHWallet importMnemonic(String path, String mnemonic, String pwd) {
List<String> list = Arrays.asList(mnemonic.split(""));if(! path.startsWith("m") && !path.startsWith("M")) {
// The parameter is invalid
return null;
}
String[] pathArray = path.split("/");
if (pathArray.length <= 1) {
// The content is incorrect
return null;
}
String passphrase = "";
long creationTimeSeconds = System.currentTimeMillis() / 1000;
DeterministicSeed ds = new DeterministicSeed(list, null, passphrase, creationTimeSeconds);
return generateWalletByMnemonic(generateNewWalletName(), ds, pathArray, pwd);
}
Copy the code
General Walletbymnemonic was introduced in the last article,
Account storage (save to database)
As many of you must have noticed, no matter how an account is constructed, it will eventually be constructed as an ETHWallet object, which is defined as follows:
@Entity
public class ETHWallet {
@Id(autoincrement = true)
private Long id;
public String address;
private String name;
private String password; // Encrypted PWD
private String keystorePath;
private String mnemonic;
private boolean isCurrent; // Is the currently selected wallet
private boolean isBackup; // Whether the backup has been performed
}
Copy the code
ETHWallet exists only in the content. After the application exits, this data will be lost, so we need to serialize it to the serialized database for storage, and load the database to restore the account at the next time we enter the application.
greenDAO
GreenDAO is a lightweight and fast ORM solution for mapping objects to SQLite databases. Here’s a diagram of what greenDAO does:
Here we also use greenDAO to map an ETHWallet object to the SQLite database. The usage of greenDAO is explained briefly here, but not in detail. You can follow the official introduction and how-to-get-started.
Object map save
To map ETHWallet to the database, add the @Entity annotation to the class. In this way, greenDAO will generate several classes: DaoMaster, DaoSession, and ETHWalletDao to help us build the database table.
Before using ETHWalletDao inserted into a database need to an initialization, often initialization in the application portal, such as: pro. Upchain. Wallet. UpChainWalletApp of onCreate (), the initialization code is as follows:
protected void init(a) {
DaoMaster.DevOpenHelper mHelper = new DaoMaster.DevOpenHelper(this."wallet".null);
SQLiteDatabase db = mHelper.getWritableDatabase();
DaoSession daoSession = new DaoMaster(db).newSession();
ETHWalletDao ethWalletDao = daoSession.getETHWalletDao();
}
Copy the code
With the helper classes generated for us by greenDAO, inserting into the database is simple, with one line of code:
ethWalletDao.insert(ethWallet); //
Copy the code
EthWallet is an instance of ethWallet, which is constructed for both newly created and imported accounts.
Multiple Account Management
Considering that the user may create multiple accounts, it is necessary to determine a currently selected account. In general, the newly created account of the user should be used as the currently selected account, while other accounts should be unselected. We will improve the account storage logic as follows: (code in the code base app/SRC/pro/upchain/wallet/utils/WalletDaoUtils Java file)
/** * Insert the newly created wallet **@paramEthWallet money * /
public static void insertNewWallet(ETHWallet ethWallet) {
updateCurrent(-1); // Deselect other site accounts
ethWallet.setCurrent(true);
ethWalletDao.insert(ethWallet);
}
/** * Update the selected wallet **@paramId Wallet ID */
public static ETHWallet updateCurrent(long id) {
// Load all wallet accounts
List<ETHWallet> ethWallets = ethWalletDao.loadAll();
ETHWallet currentWallet = null;
for (ETHWallet ethwallet : ethWallets) {
if(id ! = -1 && ethwallet.getId() == id) {
ethwallet.setCurrent(true);
currentWallet = ethwallet;
} else {
ethwallet.setCurrent(false);
}
ethWalletDao.update(ethwallet);
}
return currentWallet;
}
Copy the code
Enable account creation and saving
To save through the private key import account for example, the creation of accounts and save accounts through, here we use responsive programming ReactiveX, this part as a subscriber welfare, published in my small column, while still not price, quickly subscribe, super value!
Learning materials
- RxAndroid learn more about responsive programming
- GreenDAO introduction and How-to -get-started
I created a special discussion of wallet development wechat group, add wechat: xlbxiong Note: wallet.
Join The Planet of Knowledge and learn with a group of outstanding blockchain practitioners. Blockchain in Simple terms – systematic learning of blockchain to create the best blockchain technology blog.