The Blockchain in your Java application

short foreword

This article discusses the integration of blockchain mechanisms into Java applications. It is important to clarify that the focus is not on prices or individual cryptocurrencies overall. Throughout the article, I mention various blockchain networks, but I want to emphasize that this is not investment advice or promotional material for these networks or their cryptocurrencies. Instead, the article provides a technical explanation of how to incorporate blockchain technology into Java applications using Web3j.

Blockchain

The fundamental idea of distributed systems with shared data storage and collaborative management has existed for a very long time. The first white paper on Bitcoin – currently the most prominent and widely known blockchain network – was published on November 1, 2008 via a mailing list under the pseudonym Satoshi Nakamoto and can still be viewed online today. A miner successfully mined the first block, known as the Genesis Block, on January 3, 2009. This event marked the official launch of the Bitcoin network.

Blockchain is a distributed ledger technology managed by a peer-to-peer network. Essentially, it is a decentralized or distributed database that allows all participants to access and verify data, ensuring a trustworthy and transparent exchange of information. This decentralized approach is in contrast to traditional, centralized systems, where control over the database resides with a signle entity.

As the term “blockchain” suggests, it consists of the words “block” and “chain”. A block contains various data – most often represented through transactions in most blockchain networks. A block is created when a certain number of transactions, along with specific data such as difficulty level, block number, and block hash, are grouped together. The chain comes into play when each new block references the previous one via its hash, creating a secure, sequential link between blocks (see following figure).

Blockchain_hash_explained

Much like the internet facilitates the free exchange of information, blockchain enables the almost unrestricted exchange of digital values. However, unlike the internet, access to the blockchain network alone is not enough – it also requires a digital wallet, specifically a private key, to initiate new transactions. Using this private key, a participant can sign a message for the network. This digital signature verifies the legitimacy and origin of the message, allowing others to trust its authenticity.

Blockchain has fundamentally revolutionized and influenced the financial sector by enabling secure, transparent, and efficient transactions. Over time, its application has expanded to numerous other fields, including real estate, supply chain management, voting systems, and intellectual property protection.

Smart Contracts

A smart contract is a self-executing digital agreement that functions as a distinct entity within a blockchain network. It has its own blockchain address and can receive, manage, and send digital assets such as tokens. The execution of a smart contract’s functions occurs autonomously across multiple nodes in the network, ensuring that all participants obtain the same, unaltered result. Like standard blockchain transactions, smart contracts are transparent, tamper-proof, and immutable.

An illustrative example, which I encountered at the Linux Foundation Decentralized Trust initiative, is a vending machine. You deposit something – such as 2 euros or a cryptocurrency share – into the machine, which then dispenses a specific item in return, like a bottle of water or a financial instrument such as a share.

In summary, smart contracts offer an innovative, efficient, and secure method of automating contractual agreements by leveraging the advantages of blockchain technology.

pragma solidity 0.8.15;

contract HelloWorld {
 
    function getHelloWorld() public pure returns (string memory) {
        return "Hello World";
    }
}

Web3j Library

A transaction in the Ethereum network, for example, can appear very complex at first glance. There are the possibilities of a transfer of ether (the currency within Ethereum), a smart contract deployment or a smart contract function call. All of these processes are transactions within the blockchain. The following illustration shows such a schematic representation of a transaction.

Ethereum Blockchain Transaktion - Web3j

However, when we consider a standard HTTPS call, we encounter different levels and a process involving the exchange of certificates during the SSL handshake. At its core, this idea is quite similar, with only a different implementation.

After compiling a transaction, the sender signs it using their private key. To ensure security, the application should generate this signature locally, so that private keys are not transmitted and remain exclusively in the possession of the user. Without using a dedicated library, you must implement the entire process of creating and signing the transaction manually in your Java application.

The Web3j library simplifies this complexity and provides an abstraction. The following figure visualizes this abstraction and illustrates the simplification.

Web3j_network

The developer can now focus on building the actual Java application and its use cases. A detailed understanding of smart contracts and transaction execution is not strictly necessary at this stage. The following section also provide a Java example to illustrate this.

Integration in Java with Maven

To include Web3j in your Java project, add the corresponding Maven repository as a dependency in your pom.xml.

<dependency>
    <groupId>org.web3j</groupId>
    <artifactId>core</artifactId>
    <version>${web3j-core.version}</version>
</dependency>

For better integration, include the Web3j Maven plugin as a build plugin in your project’s pom.xml

<build>
    <plugins>
        <plugin>
            <groupId>org.web3j</groupId>
            <artifactId>web3j-maven-plugin</artifactId>
            <version>${web3j-maven-plugin.version}</version>
            <configuration>
                <soliditySourceFiles/>
            </configuration>
        </plugin>
    </plugins>
</build>

For a detailed description of the parameterization, refer to the official Web3j Docs page. Using this setup, you can generate Java wrapper classes from Smart Contracts. The command to perform the generation is as follows:

mvn web3j:generate-sources

Here is an example of a Java wrapper class generated for the Solidity Smart Contract described above:

public class HelloWorld extends Contract {
 
    public RemoteFunctionCall<String> getHelloWorld() {...}
 
    public static HelloWorld load(....) {...}
    public static RemoteCall<HelloWorld> deploy(....) {...}
}

These generated classes always contain the “load” and “deploy” functions and all possible external (public or external) function calls. The load function loads the structure of a smart contract and stores its address. The deploy function packages and publishes a new contract on the blockchain – similar to a constructor or an HTTP POST request.

<contract name>.<function name>([param1, ...., paramN]).[send() | sendAsync()];

Buildung on our example from the Smart Contract section, a typical scenario for using the generated Java code is as follows:

Web3j web3j = Web3j.build(new HttpService("someAddress.de"));
Credentials credentials = WalletUtils.loadCredentials("password", keyFile);
DefaultGasProvider gasProvider = new DefaultGasProvider();
 
HelloWorld helloWorld = HelloWorld.deploy(web3j, credentials, gasProvider).send();
helloWorld.getHelloWorld().send();
 
> "Hello World"

The above code also manages the connection to a blockchain node, handles credentials (address, public key & private key) for signing transactions and sets the transaction fees (GasFee). The “HelloWorld” smart contract is then called up and deployed as a Java object. After deployment, the “getHelloWorld” call follows. This function call returns a string that can be further used and utilized in the Java application.

Difficulties of integration

That’s how easy it is to integrate the blockchain in Java with Web3j – well, almost. Of course we still need a suitable wallet file, connection to a blockchain node and tokens to be able to pay for our transactions.

Some blockchain systems mitigate these challenges by offering alternative cost models or by enabling other parties to cover transaction fees. Additionally, some service providers offer interfaces that simplify access to the network. But do we still need blockchain if we have to trust the service provider to carry out our transaction as expected? If we want full sovereignty over our transactions, we should create them ourselves. Only then can we be sure that the transactions arrive as intended and act in our best interests. However, there are already ideas to address these issues by verifying signatures within smart contracts and executing transactions only after successful verification.

Example project

This is another project from my personal GitHub account, linked here. In this project, I cominded the integration of the Web3j library with automated Java code generation. Is also includes a wallet with sufficient test network currency to experiment with. If there are any problems or difficulties, I’ll be happy to help.

Example from practice

In practice, many companies brand themselves with terms related to blockchain, NFTs, smart contracts and similar concepts. However, we rarely see the actual underlying technologies behind these claims.

A positive example of this is an open standard from DZ BANK AG, which asserts to have traded financial products via smart contracts in a legally binding manner. One such financial product is the so-called Smart Derivative Contract, for which further publications – including technical descriptions and initial reference implementations – are available.

Conclusion

Many Java developers are probably wondering at this point whether they could also work on blockchain projects.

Of course, there are hurdles when it comes to integrating blockchain with Java using Web3j. However, Web3j’s abstraction significantly simplifies this process, allowing Java developers to familiarize themselves very well with the topic.
A certain level of prior knowledge is not always mandatory—the specific tasks ultimately determine the learning curve. Nevertheless, interest and enthusiasm—as in many other areas—can make it easier to get started and build a solid understanding of the concepts.

Once familiar, developers can learn a great deal about blockchain technology and its various applications through relevant projects.

A minimal example can be implemented quickly and provides a clear introduction, as demonstrated in the Java example above.

With this in mind, don’t be afraid, play around and explore the world of blockchain. Or to quote Simon Seiter in the closing words of a conference panel discussion: “sail the ships […] leave your island and discover the free world of public chains”

Total
0
Shares
Previous Post

How Coupled Are Your Microservices?

Next Post

Why AI Agents Need a Protocol-Flexible Event Bus

Related Posts