Create an Ethereum Wallet | Creating Ether Wallet Using Spring Boot

Creating an Ethereum Wallet Using Spring Boot

Posted by : himanshu.bhatt | 27-Dec-2019

  • Create an Ethereum Wallet

    In this blog, we have explained how to create an ethereum wallet using spring boot. To build an ether wallet, we will need a blockchain network URL in some testnet network, which may be either ropsten or rinkedby. Also, you can configure your local machine for the ether test network.

    We will use the web3j library to connect with the Ethereum network and perform operations on the blockchain.

    Steps to Create an Ethereum Wallet

      • We will make a domain class for saving the user’s wallet details in the database. We will save the user’s wallet address, balance, and the private key, which is the JSON file. Here is the following code snippet:

     

    @Entity
    public class UserWallet extends BaseEntity{
    	@Id
    	@GeneratedValue(strategy = GenerationType.AUTO)
    	private Long id;
    	
    	private Long userId;
    	
    	@Column(nullable = false,columnDefinition ="mediumtext")    
    	private String address;
    	
    	@Column(columnDefinition ="mediumtext")    
    	private String fileName;
    	
    	@Column(columnDefinition="mediumtext")
    	private String password;
    	
    	@Column(columnDefinition="mediumtext")
    	private String passwordKey;
    
    	@DecimalMin("0")
    	@Column(precision = 20, scale = 8)
    	private BigDecimal balance;
    
    	@Enumerated(EnumType.STRING)
    	private CoinType coinType;
    	
    	public UserWallet()
    	{
    		
    	}
    

    Getters and setters are omitted for better readability.

    • We will make a connection class, which will connect to the ethereum network, and here, the URL of the blockchain will be the URL of your blockchain network. Here is the code snippet:

     

    @Configuration
    public class EthereumConnectionConfig {
        private static Logger LOGGER = LoggerFactory.getLogger(EthereumConnectionConfig.class);
    
    
        @Value("${ethereum.service.url}")
        private String url;
    
        @Bean
        Web3j getEthereumCononnection() throws IOException {
    
            String serverIp = url;
            LOGGER.info("Ethereum sync serverIp : " + serverIp);
            Web3j web3 = Web3j.build(new HttpService(serverIp));
            LOGGER.info("connected to ethereum server 123" + web3);
            Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().send();
            String clientVersion = web3ClientVersion.getWeb3ClientVersion();
            LOGGER.info("Ethereum client version" + clientVersion);
            return web3;
    
        }
    }
    
    • Now we will make the controller class, in which we will make the restend points.

     

    @RestController
    public class UserWalletController {
        private static final Logger logger = LoggerFactory.getLogger(EthereumListener.class);
        @Autowired
        private WalletService walletService;
    
      
        @PostMapping(CREATE_WALLET)
        public ResponseEntity<Object> setUsersWallet() {
                    return ResponseHandler.response(walletService.createEtherWallet(),
                            LocaleService.toLocale("wallet.created"));
    }            
    }
    
    • Now we will create a service class where the logic for the creation of a user’s wallet will take place.

     

     public Map<String, Object> createEtherWallet() {
         
                Map<String, Object> map = new HashMap<>();
                map = createCredentials();
                Object jsonFile = map.get("jsonFile");
                Credentials credentials = (Credentials) map.get("credentials");
                String passwordKey = (String) map.get("passwordKey");
                String encPwd = (String) map.get("encPwd");
                UserWallet userWallet = new UserWallet(userId, credentials.getAddress(), jsonFile.toString(), encPwd, passwordKey, ETHEREUM);
                userWalletRepository.save(userWallet);
                result.put("address", credentials.getAddress());
            }
            return result;
        }
    
    private Map<String, Object> createCredentials() {
            Map<String, Object> map = new HashMap<>();
            try {
                File file = new File(ethWalletLocation);
                String fileName;
                String password = UUID.randomUUID().toString().replaceAll("-", "");
                fileName = WalletUtils.generateFullNewWalletFile(password, file);
                logger.info("wallet file name {} ", fileName);
                String passwordKey = CryptoUtil.getSecretKey();
                logger.debug("wallet file passwordKey: {}", passwordKey);
                String encPwd = CryptoUtil.encrypt(password, passwordKey);
                logger.debug("wallet file encPwd: {}", encPwd);
                File jsonFile = new File(file + File.separator + fileName);
                logger.debug("wallet file jsonFile: {}", jsonFile.toString());
                Credentials credentials = WalletUtils.loadCredentials(password, jsonFile);
                logger.debug("wallet address: {}", credentials.getAddress());
                map.put("jsonFile", jsonFile);
                map.put("credentials", credentials);
                map.put("encPwd", encPwd);
                map.put("passwordKey", passwordKey);
            } catch (IOException | NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException
                    | CipherException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException
                    | BadPaddingException e) {
                e.printStackTrace();
    
            }
            return map;
        }
    

    Now, we have successfully created a user’s wallet on the Ethereum’s test network. You can verify your address in etherscan.io by giving your address.

    Also Read  Enterprise Ethereum: A Platform for Private Blockchain Solutions


Leave a Comment

Name is required

Comment is required

No Comments Yet.

About Author

himanshu.bhatt (Writer)

More From Oodles

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.