Ethereum Blockchain “Hello World” Smart Contract with JAVA

Thushara Jayasinghe
Coinmonks
19 min readJun 20, 2018

--

Ethereum

This tutorial cover the complete set of steps needed to develop your first smart contract in a private Ethereum node using web3j Java framework.

Blockchain is disrupting software industry. The term blockchain has become a popular topic. Everyone is talking about blockchain and its usages in decentralized applications. But most of the time the underline concept of a blockchain is misinterpreted. Let us try to understand it in simple terms. Blockchain can be considered as a database technology which is used to store data in a distributed manner. It uses hashing algorithms to maintain the integrity of data which is very much similar to Git. Every node in block chain will have its own copy of the data store. The manipulation of records in the data store is prevented by a proof of work algorithm.Processing nodes are connected peer-to-peer and will work autonomously. This enable the elimination of third party player such as banking system the middle of a transaction to manage the risk. Cryptocurrency such as Bitcoin is an example usage of blockchain technology. But it is not limited to Cryptocurrency.

Blockchain

The purpose of the blockchain technology is to eliminate the need of having a middle man to facilitate financial transactions. In a typical payment system a bank or a financial institution will minimize the risk of the transaction by acting as a middle man.

Typical transaction flow

Blockchain technology facilitates payments without a middle player. For example you can transfer digital money from your account to your supplier account without the help of paypal or any other third party payment provider functionalities. So blockchain is simple as that.

Direct peer-to-peer transaction

Definition : A blockchain is a peer-to-peer distributed ledger forged by consensus, combined with a system for “smart contracts” and other assistive technologies. Rememner blockchain is not a single technology. It is a collection of technologies.

Blockchain Technology

Lets try to understand these technologies.

DLT : Distributed ledgers use independent computers (referred to as nodes) to record, share and synchronize transactions in their respective electronic ledgers (instead of keeping data centralized as in a traditional ledger). Blockchain organizes data into blocks, which are chained together in an append only mode.

Blockchain is a specific form or subset of distributed ledger technologies. It is the way that the data is stored in the DLT. But the term Blockchain has become the buzz word for the entire technology stack.

Peer-to-peer : Nodes in a blockchain are connected peer-to-peer. You can connect a local node running in your laptop to the blockchain network seamlessly.

Decentralized : In a decentralized system each node is running autonomously. The main difference with a distributed system is that in a distributed system there are dedicates set of nodes to control other nodes. But in a decentralized system no one takes commands from each other. No concept of client server of master slave. Every one has equal decision power.

Decentralized

Cryptographically secure: Blockchain uses digital signature (SHA256) algorithm to maintain/verify integrity of the data.

Digital Signature

Anonymous: In blockchain an account with a key pair ( public key & private key) is used a wallet for submitting transactions. There is no way of identifying a user or any other personal information by looking at a transaction. It is completely anonymous. For example if you go to etherscan.io which is the central application to view Ethereum blockchain transactions then the from account and to account would be something like below.

Anonymous

We will talk about these technologies in more details later. Lets have a look at the history of blockchain.

My other publications :

Java “Hello world” Microservice with Vert.X, Docker and Kubernetes

Oracle JDK is no longer free !!

Java Code Convention Simplified

Create your own Cryptocurrency in Ethereum Blockchain

Ethereum Blockchain “Hello World” Smart Contract with JAVA

Git in Real Life — GitFlow Branching model

Continuous Integration (CI) toolchain for JAVA

Java Web Services with RESTEasy, JSON, TestNG, Mockito & Maven

History : Blockchain technology has found a solution for the Byzantine generals problem as illustrated in below article.

Image result for blockchain byzantine
Byzantine generals problem

Types of Blockchains: Mainly there are two types of blockchain implementations. Open/Public and enterprise. In an open and public blockchain such as BitCoin or Ethereum anyone can join as a node to the main network. But in an enterprise blockchain such as Hyperledger fabric only authorized nodes can enter into the network.

Types of blockchains

There are many implementations of blockchain technology. We will be discussing about Ethereum.

Blockchain Implementations

BitCoin : October 31st of 2008, a white paper has been submitted by an unknown person called Satoshi Nakamoto on performing electronic transactions without the need of a middle party. This is the origin of BitCoin. The whole purpose of the BitCoin technology was to transfer money between two parties in a peer-to-peer manner in contract to current financial transactions which are performed with the help of an intermediary (like a Bank).

BitCoin
https://bitcoin.org/bitcoin.pdf

Ethereum : December 2013 , Vitalik Buterin wrote a white paper on extending the blockchain technology beyond the financial transactions and the idea of Smart Contracts. This is the origin of Ethereum.

https://github.com/ethereum/wiki/wiki/White-Paper

http://web.archive.org/web/20131228111141/http://vbuterin.com/ethereum.html

https://blockchainreview.io/wp-content/uploads/2018/03/02.01._final_Ethereum-White-Paper-Made-Simple.pdf

Vitalik Buterin : Co-founder of Ethereum
Main components of Ethereum

Ethereum is written using Go programming language. Geth is the command line tool/interface for running a full ethereum node. You have the option of connecting to main ethereum network or create your own private network. If you are connected to main network then entire block chain data (~45GB) will be downloaded to your machine. Therefore we are going to setup our own network with one node.

Ethereum

Smart Contract in ethereum is a piece of code that can be deployed and executed to perform business functions. The compiled code is run on every node using ethereum JVM. Contract has its own account address. The caller should pay ether to deploy and execute smart contracts in nodes. A token (Currency) is also a smart contract. These contracts are written using Solidity language. You can define your own currency as a smart contract.

Account in ethereum is a combination of account address, a public key and a private key. Address is used to when performing transactions such as fund transfer. Account address is derived from public key. Private key is used to sign the transactions.

There are couple of test ethereum networks available in addition to main ethereum network. Ropsten, Kovan & Rinkeby can be used to test your application before moving into production main network.

Accounts

Wallet is used to create/manage your accounts. Wallet can have multiple accounts.

MetaMask is a wallet manager app which can be downloaded as a Chrome extension. You will have to trust them to keep your private key.

Remix is an online IDE for solidity language. Remix runs it own ethereum node for testing purposes.

web3js is a java script framework which can be used to interact with the ethereum node

web3j is a java API which can be used to interact with the node

Mist is a browser to browse dApps hosted in cloud. It can be used as a wallet manage as well.

Geth is the command line tool which is used to interact with the blockchain

Transaction is the fundamental message structure in blockchain.

Ethereum blockchain consists of multiple nodes. Each node will have its own copy of blocks. Nodes are communicated peer-to-peer using a gossip protocol.

Transaction
Transaction

A block contains multiple transactions.

Block
Node

Blockchain is a link list of Blocks which are connected with Hash values similar to Git. Changing the content of one block will result in change of Hash values in the chain.

Blockchain

Set of transactions (Block) will be selected by a node for validations. Each transaction is digitally singed with the private key of the user. The public key is embedded in the transaction so that nodes can use the public key to validate the signatures. Once signatures are validated, the node tries to find the next valid block by solving a hashing puzzle. The puzzle is to find a number called Nonse so that the resulting hash of the block will start from given number of leading zeros. For example in below block Node will iterate Nonse = 0 to n so that when n = 139358, the block Hash contains five leading zeros. This is called mining. Once the correct Nonse is found the Node will send this block for other Nodes for confirmation. After a certain number of confirmations the block is accepted as the next block in the chain. The Node is rewarded with some amount of Ether for finding the Nonse. This is where the computing power matters.

Mining

A chain of blocks is created by using Hash of the previous block in newly Mined block. The Hash of the previous block is an input for the current block. If the previous block is modified then the Hash of the previous block is changed. This will have a chain reaction in entire block chain. Because changing of previous Hash will impact the next block Hash and the next block Hash and it continues…

Mining

This is how blockchain maintains integrity of the data. There is an interactive tutorial on this in https://anders.com/blockchain/tokens.html

Submitting a transaction from Wallet

Submit Transaction

Interfacing with Ethereum : It is possible to interact with ethereum blockchain using web3js java script API.

Interfacing with ethereum

Lets create our own private network with one node.

Download & install Geth: Download windows version of Geth from below URL and install it. Geth is the command line interface for the blockchain.

https://geth.ethereum.org/downloads/

Create genesis block & data folder : You need to create your initial block (genesis block) to start the block chain protocol. Create a new folder in your hard drive and save below content as genesis.json. Change the chainId value from 1 to a different number to avoid connecting to main network. chainId=1 is reserved for the main network.

Create an empty folder called chaindata to store the blocks. Final state will be as follows.

genesis.json & data folder

Open your command prompt from this folder and use below command to initiate blockchain protocol. This will not start any node.

Initiate block chain

Start your private node : Now you can start your private node using below command.

Start private node

Download & install wallet manager app : Wallet manager app can be used to create ethereum accounts. An account is a keystore in ethereum with private and public key pair. Keys will be saved in chaindata folder by default. The private key is used to encrypt/sign transactions when submitting to block chain. This key will be loaded by web3j as well. You can use Mist as a wallet manager and to browse ehereum app store. On the other hand wallet manager can be installed as a standalone application as well. https://github.com/ethereum/mist/releases?after=0.4.0

We will create two testing accounts using wallet manager app. Download and install wallet manager app from below location.

  1. Install wallet manager app
https://github.com/ethereum/mist/releases

2. Launch wallet manager app : Remix wallet manager app will connect to your private node by default. You can see it in below screenshot under “PRIVATE NET” red color label.

No need to wait for the sync activity with main network, we are just running our local node. Press the launch application button.

Wallet Manager

3. Create two accounts : we will do a simple money transfer transaction using wallet manager app. Two different accounts are needed for that. You can create account using wallet manager app. Go to File menu and press new account. Specify your wallet password. This will create your keystore file with private key and public key. Same process can be repeated to create another account for money transfer transaction. The first account will be identified as the main account by default.

Create new account

This is your identity and it should be protected in a safe place. You can locate your kestore files under chaindata/keystore folder.

Keystore files

What is in your keystore file : https://medium.com/@julien.maffre/what-is-an-ethereum-keystore-file-86c8c5917b97

In a real world scenario MetaMask will act as your keystore manager. The MetaMask chrome browser extension will manage your keys and will use the private key stored in your browsers data store to sign the transactions.

https://ethereum.stackexchange.com/questions/39954/does-metamask-store-private-key-on-server-or-anywhere-else

4. Start Mining : There is not point of having an account without real money (Ether). We can get some free ether to our main account by starting mining process using Geth console. Below is the command.

You can navigate to wallet manager app to see how ether is added to your account in real time. Ether will be added to your main account.

5. Transfer Ether

Press the SEND button in wallet manager to transfer ether from one account to another. Select the FROM account. Copy and paste the address of destination account to TO field. Specify the amount. A fee should be paid for the minors to perform this transaction. You can select your fee under SELECT FEE section and press the SEND button. You will be prompt to enter the keystore password of the source account. Once submitted miners ( we have one miner will start the mining process.

Transfer Ether

Please make sure that your node has started mining. If not use miner.start(); command in geth console to start it. It is possible to see the status of your last transaction in wallet manager app. 12 confirmations are required to complete the transaction. Once transaction is completed check your account balances to confirm the money transfer effect. Next we will do the same money transfer transaction using web3j library.

Lets start coding with web3j

web3j is a lightweight, highly modular, reactive, type safe Java and Android library for working with Smart Contracts and integrating with clients (nodes) on the Ethereum network.

web3j

Create an empty maven project and add below dependency. Complete pom.xml file is as follows.

  1. Transfer ether using web3j

Notes: You can use the same accounts created by wallet application in web3j code. The actual file name of the keystore file should be mentioned in the code. It will not work if you specify the folder name and not the file name. Use valid destination account address in to parameter. Once above code is executed you can validate the transferred amount in wallet manager app. Miner should be running in your geth console to complete the transaction.

Code

Output

Transfer Ether

Write your first smart contact in solidity language

Smart contract is piece of software developed using Solidity language to perform custom business functionalities. Smart contract will be installed in all nodes in the network. Installation is a one time operation and it has to be submitted as a transaction to the network by spending ether for the miners. Once installed you cannot modify it. It is like a stored procedure in a rational database. You can call functions in the contract by submitting transactions. You can use the Remix browser application to write the smart contract. Remix has an inbuilt ethereum node where you can deploy the contract and test it. Navigate to https://remix.ethereum.org in your browser and write below code.

HelloWorld.sol

Deploy & test your contract in Remix.

Compile your contact using Compile option. Then navigate to Run tab and press Deploy button to deploy it. Your contract will be deployed as a Transaction. Therefore you need to specify the source account address and a Gas limit (amount of ether paid for miners for the execution of this transaction). Once deployed contract will have its own address. This address can be used to call methods in the transaction.

Deployed contract

You can execute functions in the contract by pressing add, subtract and getCounter buttons. Press the add button and then press the getCounter button to check the value of your counter.

Execute the contract

Now we will be deploying the contract using web3j instead of Remix. First we need to compile the contract. The compiled output of the Smart Contract has two parts. The binary file ( which will be executed in ethereum JVM once deployed) and the application binary interface (ABI) which is a human readable definition of the contract represented in JSON format. These output is required to generate the wrapper class uisng web3j. The wrapper class will hide all the complexities of connecting & executing your smart contract. It will act as an interface for the smart contract.

Compile Contract
  1. Compile the contact

We will be using solc compiler to compile the contract. You can download the windows version of it.

https://github.com/ethereum/solidity/releases

solc compiler

Download and extract the zip file into your hard disk. Then save your contract to a file called HelloWorld.sol and save it to solc compile folder for easy access.

solc file

Open new terminal and use below command to compile it.

https://web3j.readthedocs.io/en/latest/smart_contracts.html

This command will generate binary file and ABI file as the output.

Compiled output of the contract

Lets use the output of the compiled smart contract to generate the HelloWorld.java wrapper class. This wrapper class is used to interact with the Smart Contract. All complexities will be hidden from the end user.

Generate Wrapper class
Interact with the Smart Contract

web3j comes with a command line utility to generate the wrapper class. where you can download it from below location. Once the tool is copied to your hard disk, you need to copy the binary file and ABI generated in above step to the same folder where the web3j.bat file is present.

web3j

Extract the folder into your hard disk. Copy abi file and binary file created in above solidity compilation step into bin folder.

Generate Wrapper class

Run below command to generate the wrapper class.

Parameter p should be the java packaging structure for the generated class.

Hint : https://stackoverflow.com/questions/44662197/web3j-solidity-generate-command-not-working

New class will be generated in org.web3j.sample folder.

Part of the generated HelloWorld.java

Copy this file to your application folder structure.

Application package structure

Lets deploy and use Smart Contract from our your application.

Deploy and use smart contract

Complete code

Output

Output

Woooow!!, It is working ….

Application of Blockchain technology : Blockchain technology can be used not only for Cryptocurrencies. The primary building blocks of blockchain technology can be used in enterprise applications such as immutability, anonymity & security. For an example a land registration system can be easily build using Smart Contracts in Ethereum. Any application built using blockchain will leverage one or more capabilities of blockchain.

Conclusion

web3j is an effective method of interfacing with Ethereum blockchain using Java language.

I just started writing my next article in creating your own Currency (Token) using smart contract. It will cover all steps needed to publish your currency in private network and use it for transactions.

As promised my article on creating you own currency token has been released.

https://medium.com/coinmonks/create-your-own-cryptocurrency-in-ethereum-blockchain-40865db8a29f

I am planning to an article on initial coin offering as well. This is called Crowdsale. Hope to see you soon.

I’ll will be sharing more articles on future so don’t forget to follow, clap and comment. Thanks for reading.

Please feel free to contact me on:

Email : email.thusharaj[at]gmail.com

Linkedin : https://www.linkedin.com/in/thusharaj/

References: Special Thanx to Stepen Gridder : Udemy.com for his wonderful materials on Ethereum. I have reused some of his original work in my article.

https://skillsmatter.com/skillscasts/11141-java-and-the-blockchain-building-java-applications-on-ethereum-with-web3j-3-0
https://www.ccn.com/bitcoin-transaction-really-works/

https://codeburst.io/build-your-first-ethereum-smart-contract-with-solidity-tutorial-94171d6b1c4b
https://www.youtube.com/watch?v=UmCEdcRjaz0&pbjreload=10
https://www.youtube.com/watch?v=1fKnjMGmB2U
https://medium.com/@mvmurthy/full-stack-hello-world-voting-ethereum-dapp-tutorial-part-1-40d2d0d807c2
https://medium.com/taipei-ethereum-meetup/beginners-guide-to-ethereum-2-run-multiple-nodes-on-a-private-network-in-5-lines-c97a4d78a590
https://hackernoon.com/setup-your-own-private-proof-of-authority-ethereum-network-with-geth-9a0a3750cda8
https://arvanaghi.com/blog/how-to-set-up-a-private-ethereum-blockchain-using-geth/
https://blog.zeppelin.solutions/designing-the-architecture-for-your-ethereum-application-9cec086f8317
https://medium.com/@merunasgrincalaitis/the-ultimate-end-to-end-tutorial-to-create-and-deploy-a-fully-descentralized-dapp-in-ethereum-18f0cf6d7e0e
https://www.codeooze.com/blockchain/solc-hello-world/

Join Coinmonks Telegram Channel and Youtube Channel get daily Crypto News

Also, Read

--

--