Backup and Restore Bitcoin HD Wallet From Seed
Posted By : S. Ajit | 14-May-2017
You can easily backup and restore Bitcoin HD Wallet with seed and creation Time. Seed is a set of Words which are derived from wallet. Each wallet has their own seed which can be like this: celery avocado walk sketch spring park burden uncover want puzzle picture erosion. So when you create a new wallet you need to save two things in database:
1. Seed
2. Wallet creation Time
Below written code shows how to get seed and creationTime from HD wallet:
SecureRandom random = new SecureRandom();
DeterministicKeyChain determinstickeychain = new DeterministicKeyChain(random, bits);
DeterministicSeed seed = determinstickeychain.getSeed();
Wallet wallet = Wallet.fromSeed(TestNet3Params.get(), seed);
long creationTime = wallet.getEarliestKeyCreationTime()
String seedCode=seed.getMnemonicCode().toString();
seedCode=seedCode.replace(",","").replace("[","").replace("]","");
System.out.println("Here is the seed:"+seedCode +" and creation time:"+creationTime);
Now we will create a object of DeterministicSeed class using seed, blank passphrase and creation time. This DeterministicSeed object along with network parameter is passed to fromSeed static method of Wallet class to create a object of Wallet, Below is the code:
import java.io.File;
import java.io.IOException;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.Wallet;
import org.bitcoinj.params.TestNet3Params;
import org.bitcoinj.store.UnreadableWalletException;
import org.bitcoinj.wallet.DeterministicSeed;
public class RestoreWalletFromSeed {
public static void main(String[] args) {
NetworkParameters params = TestNet3Params.get();
String seed = "Your Wallet Seed Code";
String passphrase = "";
Long time = 1438070601L; // wallet creation time
try {
DeterministicSeed seed = new DeterministicSeed(seed,null,passphrase,time);
Wallet wallet = Wallet.fromSeed(params, seed);
saveWallet(wallet);
System.out.println("Address=" + wallet.currentReceiveAddress());
} catch (UnreadableWalletException e) {
e.printStackTrace();
}
}
public static void saveWallet(Wallet wallet) {
try {
File file = new File("/opt/restoredWallet.dat");
wallet.saveToFile(file);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
S. Ajit
Ajit is a software developer who loves solving problems and programming in C, C++, Java. He also has a passion to learn new technologies.