<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Olelewexpressrules on Medium]]></title>
        <description><![CDATA[Stories by Olelewexpressrules on Medium]]></description>
        <link>https://medium.com/@olelewexpressrules?source=rss-a5a9390e2cbe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*rF_8t3s_3b3uQcTB</url>
            <title>Stories by Olelewexpressrules on Medium</title>
            <link>https://medium.com/@olelewexpressrules?source=rss-a5a9390e2cbe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 10:02:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@olelewexpressrules/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Creating a simple Bitcoin wallet service using the Bitcoin Java library — BitcoinJ]]></title>
            <link>https://medium.com/@olelewexpressrules/creating-a-simple-bitcoin-wallet-service-using-the-bitcoin-java-library-bitcoinj-2cebb82ac08d?source=rss-a5a9390e2cbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cebb82ac08d</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[bitcoinjs-lib]]></category>
            <category><![CDATA[wallet]]></category>
            <dc:creator><![CDATA[Olelewexpressrules]]></dc:creator>
            <pubDate>Sun, 04 Feb 2024 21:24:40 GMT</pubDate>
            <atom:updated>2024-02-04T21:24:40.726Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating a simple Bitcoin wallet service using the Bitcoin Java library — BitcoinJ</h3><h3>Introduction</h3><p>Creating a Bitcoin wallet has never been easier for Java developers all thanks to the BitcoinJ java library. BitcoinJ is a Java library for working with the Bitcoin cryptocurrency. It provides tools for working with Bitcoin transactions, managing wallets, and interacting with the Bitcoin network. <br>In this article, we aim to build a simple wallet service that exposes two API(s), create a wallet, and restore a wallet.</p><p>Full source code can be accessed on GitHub (<a href="https://github.com/darlington-olelewe/bitcon-j-wallet-java.git">https://github.com/darlington-olelewe/bitcon-j-wallet-java.git</a>)</p><p>To follow along you will need Java 8 and above, Maven 3.0 and above, and any IDE of choice.</p><h3><strong>Project Setup and Structure</strong></h3><p>To begin a new Spring Boot application with Lombok and Spring Web dependencies, visit <a href="https://start.spring.io/">https://start.spring.io/</a>. Select Java and Maven as your preferred build tools. Customize the Group, Artifact, Name, Description, and Package Name according to your preferences. Afterward, download the generated zip file, extract its contents, and open the project in your preferred Integrated Development Environment (IDE). Upon completion, your project should exhibit a fundamental file structure similar to the following.</p><figure><img alt="wallet application file structure" src="https://cdn-images-1.medium.com/max/1024/1*QdeC3Fy7mS12PWOOjulMxA.png" /><figcaption>Basic File Structure after unzipping</figcaption></figure><p>For ease of follow-up, I will rename the BitcoinJWalletApplication.Java class to App.Java. This is the application’s entry point.</p><p>On the pom.xml file, I will add BitcoinJ dependency to the list of dependencies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed5b13dc3bbec2e070f9ed0bfe54a919/href">https://medium.com/media/ed5b13dc3bbec2e070f9ed0bfe54a919/href</a></iframe><h3><strong>Add other Files / Classes</strong></h3><p>Creating a well-organized application structure adhering to the Object-Oriented Programming (OOP) model involves the inclusion of files such as WalletModel.java, WalletService.java, WalletServiceImpl.java, and Controller.java. This approach ensures a coherent and systematic design for our application.</p><figure><img alt="Image showing new classes and interfaces added to our wallet service." src="https://cdn-images-1.medium.com/max/615/1*OrqaYCo5mb3OjEr8vhcxfg.png" /></figure><h3><strong>WalletModel.Java</strong></h3><pre>package com.btrust.bitcoin.bitcoinjwallet;<br><br>import lombok.AllArgsConstructor;<br>import lombok.Getter;<br>import lombok.NoArgsConstructor;<br>import lombok.ToString;<br><br>import java.util.List;<br><br>@NoArgsConstructor<br>@AllArgsConstructor<br>@ToString<br>@Getter<br>public class WalletModel {<br>    private String publicAddress;<br>    private String privateKey;<br>    private List&lt;String&gt; mnemonicCode;<br>}</pre><p>The Wallet Model encompasses essential properties: publicAddress, privateKey, and mnemonicCode, which serve as the blueprint for our wallet representation. The public address, a string, functions as the destination for fund receptions. The privateKey, a key indicating ownership, is pivotal for transaction authorization. The mnemonicCode, consisting of a human-readable list of typically 12 strings, plays a crucial role in wallet recovery.</p><h3><strong>WalletService.Java</strong></h3><pre>package com.btrust.bitcoin.bitcoinjwallet;<br>import org.bitcoinj.crypto.MnemonicException;<br>import java.util.ArrayList;<br><br><br>public interface WalletService {<br>    WalletModel createWallet() throws MnemonicException.MnemonicLengthException;<br>    WalletModel restoreWallet(ArrayList&lt;String&gt; mnemonicCode);<br>}</pre><p>The WalletService functions as an interface, outlining the actions to be performed without delving into specific implementations. It defines two crucial methods: createWallet(), responsible for initiating a new wallet, and restoreWallet(List&lt;String&gt; mnemonicCode), designed for the restoration of a wallet based on a provided mnemonic code list. The interface sets the groundwork for these actions without prescribing the exact details of their execution.</p><p>Contoller.Java</p><pre>package com.btrust.bitcoin.bitcoinjwallet;<br><br>import lombok.RequiredArgsConstructor;<br>import org.bitcoinj.crypto.MnemonicException;<br>import org.springframework.http.MediaType;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.PostMapping;<br>import org.springframework.web.bind.annotation.RequestBody;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RestController;<br><br>import java.util.ArrayList;<br><br>@RestController<br>@RequiredArgsConstructor<br>@RequestMapping(&quot;api/v1/&quot;)<br>public class controller {<br><br>    private final WalletService walletService;<br><br>    @PostMapping(&quot;create-wallet&quot;)<br>    public ResponseEntity&lt;WalletModel&gt; createAndSaveWallet()<br>            throws MnemonicException.MnemonicLengthException {<br>        return ResponseEntity.ok(walletService.createWallet());<br>    }<br><br>    @PostMapping(value=&quot;restore-wallet&quot;)<br>    public ResponseEntity&lt;WalletModel&gt; recoverWallet(@RequestBody ArrayList&lt;String&gt; mnemonicCode){<br>        return ResponseEntity.ok(walletService.restoreWallet(mnemonicCode));<br>    }<br><br>}</pre><p>The controller serves as the interface for two APIs, namely create-wallet and restore-wallet, both of which delegate their functionalities to the WalletService. Lacking any application-specific logic, the controller focuses on managing the API endpoints. Further examination will delve into the intricacies of the WalletServiceImpl, which was injected through constructor injection, elucidating the underlying implementation details.</p><p>WalletServiceImpl.Java</p><pre>package com.btrust.bitcoin.bitcoinjwallet;<br>import org.bitcoinj.core.Address;<br>import org.bitcoinj.core.ECKey;<br>import org.bitcoinj.core.LegacyAddress;<br>import org.bitcoinj.core.NetworkParameters;<br>import org.bitcoinj.crypto.MnemonicCode;<br>import org.bitcoinj.crypto.MnemonicException;<br>import org.bitcoinj.params.TestNet3Params;<br>import org.bitcoinj.wallet.DeterministicSeed;<br>import org.bitcoinj.wallet.Wallet;<br>import org.springframework.stereotype.Service;<br>import java.security.SecureRandom;<br>import java.util.ArrayList;<br>import java.util.List;<br><br>@Service<br>public class WalletServiceImpl implements WalletService{<br>    private final NetworkParameters networkParameters = TestNet3Params.get();<br>    @Override<br>    public WalletModel createWallet() throws MnemonicException.MnemonicLengthException {<br>        /**<br>         * Secure random: this gives us a random numbers, it returns a byte array,<br>         * 1 byte = 8bits<br>         * 16 bytes = 128<br>         *  dividing 128 by 12 will give you 12 mnemonic codes<br>         *  it is also called entropy<br>         */<br>        byte[] randomness = SecureRandom.getSeed(16 );<br>        /**<br>         * From the documentation of toMnemonic,<br>         * it picks the words from mnemonic/wordlist/english.txt in the bitcoinj j file<br>         */<br>        List&lt;String&gt; mnemonicCode = MnemonicCode.INSTANCE.toMnemonic(randomness);<br>        /**<br>         * At this point an Enlongation Algorithm is employed to make it up to 512bits<br>         */<br>        DeterministicSeed seed = new DeterministicSeed(mnemonicCode, null, &quot;&quot;, System.currentTimeMillis());<br>        /**<br>         * Here a wallet is created from the seed<br>         * a P2PKHWallet is always created when .formseed() method is used<br>         */<br>        Wallet wallet = Wallet.fromSeed(networkParameters, seed);<br>        /**<br>         * Get the first key in the wallet (you can generate more keys as needed)<br>         */<br>        ECKey key = wallet.freshReceiveKey();<br><br>        // Create a P2PKH address using the public key<br>        Address address = LegacyAddress.fromKey(networkParameters, key);<br><br>        // Get the private key in Wallet Import Format (WIF)<br>        String privateKeyWIF = key.getPrivateKeyEncoded(networkParameters).toBase58();<br><br>        return new WalletModel(address.toString(),privateKeyWIF,mnemonicCode);<br>    }<br><br><br><br>    @Override<br>    public WalletModel restoreWallet(ArrayList&lt;String&gt; mnemonicCode) {<br>        DeterministicSeed seed = new DeterministicSeed(mnemonicCode, null, &quot;&quot;, System.currentTimeMillis());<br>        Wallet wallet = Wallet.fromSeed(networkParameters, seed);<br>        ECKey key = wallet.freshReceiveKey();<br>        Address address = LegacyAddress.fromKey(networkParameters, key);<br>        String privateKeyWIF = key.getPrivateKeyEncoded(networkParameters).toBase58();<br>        return new WalletModel(address.toString(),privateKeyWIF,mnemonicCode);<br>    }<br><br>}</pre><p>randomness (byte[]) is created via java.security.SecureRandom. <br>This provides an entropy that is unique each time.</p><p>MenmonicCodes (List&lt;String&gt;) is generated using this process below.</p><pre>public List&lt;String&gt; toMnemonic(byte[] entropy) throws MnemonicException.MnemonicLengthException {<br>    if (entropy.length % 4 &gt; 0) {<br>        throw new MnemonicException.MnemonicLengthException(&quot;Entropy length not multiple of 32 bits.&quot;);<br>    } else if (entropy.length == 0) {<br>        throw new MnemonicException.MnemonicLengthException(&quot;Entropy is empty.&quot;);<br>    } else {<br>        byte[] hash = Sha256Hash.hash(entropy);<br>        boolean[] hashBits = bytesToBits(hash);<br>        boolean[] entropyBits = bytesToBits(entropy);<br>        int checksumLengthBits = entropyBits.length / 32;<br>        boolean[] concatBits = new boolean[entropyBits.length + checksumLengthBits];<br>        System.arraycopy(entropyBits, 0, concatBits, 0, entropyBits.length);<br>        System.arraycopy(hashBits, 0, concatBits, entropyBits.length, checksumLengthBits);<br>        ArrayList&lt;String&gt; words = new ArrayList();<br>        int nwords = concatBits.length / 11;<br><br>        for(int i = 0; i &lt; nwords; ++i) {<br>            int index = 0;<br><br>            for(int j = 0; j &lt; 11; ++j) {<br>                index &lt;&lt;= 1;<br>                if (concatBits[i * 11 + j]) {<br>                    index |= 1;<br>                }<br>            }<br><br>            words.add(this.wordList.get(index));<br>        }<br><br>        return words;<br>    }<br>}</pre><h4>Deterministic Seed Creation:</h4><p>The deterministic seed is created using an elongation algorithm. The mnemonic code, consisting of 12 strings, is converted into 128 bits. The elongation algorithm incorporates a salt, constructed by concatenating a “mnemonic” with a user-defined string or empty string. This elongation results in a 512bit data.</p><h4>Wallet Creation:</h4><ul><li>The resulting seed is utilized to create a wallet.</li><li>The wallet provides methods for generating addresses and public keys.</li><li>Since it is a deterministic wallet, multiple addresses can be created from it, allowing for versatility and ease of use.</li></ul><h4>Restore Wallet:</h4><ul><li>The restoration process mirrors the creation of a wallet, with the notable exception of omitting the randomness step.</li><li>Instead of relying on random entropy, the restoration utilizes the human-readable equivalent provided by the 12 mnemonic strings.</li><li>The mnemonic code serves as a substitute for the entropy, enabling the recreation of the deterministic seed and, consequently, the wallet.</li></ul><h4>Testing on Postman:</h4><p>To execute a Spring Boot Maven project using Postman, follow these steps:</p><ol><li>Open the terminal in the root directory of your Spring Boot Maven project.</li><li>Run the following command to start the application:</li></ol><pre>mvn spring-boot:run</pre><ol><li>This command will build and run your Spring Boot application. The application will start, and you should see an output indicating that the application has started successfully.</li><li>Once the application is running, open Postman.</li><li>In Postman, you can now send HTTP requests to the endpoints provided by your Spring Boot application. The base URL would typically be http://localhost:8080 unless you have configured a different port.</li><li>For example, if your Spring Boot application has an endpoint for creating a wallet and the endpoint is /create-wallet, you would send a POST request to http://localhost:8080/api/v1create-wallet in Postman.</li><li>Similarly, if you have an endpoint for restoring a wallet, you can send a request to http://localhost:8080/api/v1/restore-wallet with the appropriate parameters.</li><li>After testing, you can stop the Spring Boot application by going back to the terminal where it is running and pressing Ctrl + C.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*qLwfZMFhxkC7q-6XFMdozw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*S4RjXKDefG4ATOXCRXFxEg.png" /><figcaption>Image showing postman calls</figcaption></figure><p>postman collection has been provided on the codebase on ./src/main/resource/postman-collection.json.</p><p><strong><em>HAPPY CODING</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cebb82ac08d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>