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

 

 

 

 

About Author

Author Image
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.

Request for Proposal

Name is required

Comment is required

Sending message..