CHAPTER 10
Java Programming for Blockchain Applications

You can fool all the people some of the time and some of the people all the time, but you cannot fool all the people all the time.

—Abraham Lincoln

10.1 What Is Blockchain?

Blockchain is another one of the hottest buzzwords at the moment. What is blockchain, and what has it to do with Bitcoin? Well, blockchain is a technology that was invented in 2008 by the mysterious Satoshi Nakamoto, whose real identity is still unknown. (It is largely believed to be a person or a group of people living in Japan.) The original purpose of blockchain technology was to serve as the distributed, digital, public transaction ledger of the cryptocurrency Bitcoin to solve the double-spending problem. In digital currency, double-spending occurs when the same single digital token can be spent more than once. With a public ledger, when you try to spend the same digital token the second time, the transaction will not be validated. But today, blockchain has shown potential in many other areas, such as smart contracts, smart property, insurance, music, healthcare, manufacture, supply chain, arts, government, the Internet of Things (IoT), and so on. Blockchain is another digital technology that may revolutionize the way we live and work.

In the simplest terms, as illustrated in Figure 10.1, a blockchain is basically a chain of blocks, each of which contains some information—data. In the case of digital currency, this can be the amount of money transferred, the identities of the sender and receiver, the date and time, and so on. Each block also contains an index, the previous block's hash, a timestamp, a nonce value, and its own hash. Each block is connected to the previous block through the previous block's hash, so all blocks are connected like a daisy chain, which is where it gets the name blockchain. The first block in the chain, called the genesis, does not have a previous block, so the previous block's hash is NULL. The index is a unique number for each block. The index of the first block is 0, the second block is 1, the third block is 2, and so on. The timestamp is the date and time when the block is created, and the nonce is a 32-bit (4-byte) integer whose value controls the outcome of the calculated hash of the block.

Image described by caption and surrounding text.

Figure 10.1: The schematic diagram of a blockchain

Each block uses its index, the previous block's hash, its data, its timestamp, and its nonce value to feed into a hash function, such as SHA-256, to create its own hash, as shown in Figure 10.2. As described in Chapter 9, a hash function is a mathematical function that can map data of any size to fixed-size data. Unlike encryption, a hash cannot be reversed. If someone gets the hash of the current block, there is no way they can figure out the information in the block that was hashed.

Schematic flow diagram depicting index, previous hash, data, timestamp, and nonce to feed into a hash function, such as SHA-256, to calculate the current hash.

Figure 10.2: Each block uses its index, previous hash, data, timestamp, and nonce to feed into a hash function, such as SHA-256, to calculate the current hash.

10.2 How Do You Validate a Blockchain?

A blockchain is a record of a series of items of information, such as a series of transactions. After a blockchain is formed, it must be validated. To validate a blockchain, you must validate every single block on the chain, starting from the first block, the genesis.

Validating a block is not difficult; it takes just two steps. First, you need to test whether the previous hash is the same as the current hash of the previous block; you can skip this step for the first block. Second, you need to use the block's index, the previous block's hash, and the block's data, timestamp, and nonce to feed into a hash function (such as SHA-256) to calculate its hash, exactly as it was calculated in the first place, as shown in Figure 10.2, to see if the newly calculated hash is the same as the original current hash in the block. If both steps are successful, then this block is valid. If all the blocks on the chain are valid, then it is a valid blockchain.

Now, let us try to alter the data in block 2 of Figure 10.1 after the chain has been created. What will happen? When you alter the data, the block will become invalid, as the new hash will not match the existing hash. You can replace the existing hash with the new hash to make this block valid, but then block 3 will not be valid, as its previous hash no longer matches block 2's new hash. You can of course replace the previous hash in block 3 with block 2's new hash, but then you will need to recalculate block 3's hash to make block 3 valid again. Then you will have to repeat this for blocks 4, 5, 6, …, until the end of the chain. This is the beauty of using a hash in the blockchain; once the chain is created, nothing can be changed. The same will happen when you try to remove blocks from the chain or insert new blocks into it.

The only way you can make a change on the chain is to recalculate the hash for all the blocks after the changed block. But blockchain technology has a consensus mechanism to prevent this from happening. It is called proof of work, which requires you to mine the blocks.

10.3 How Do You Mine the Blocks?

The proof-of-work system in the blockchain technology means that when you calculate a hash, the hash needs to start with a certain number of zeros, described as its difficulty. More zeros means greater difficulty; fewer zeros means less difficulty. Blockchain uses difficulty to control the time of creating one block. If the difficulty value is 5, that means the hash must start with five zeros. Because all other information in the block, such as the index, previous hash, data, and timestamp, is fixed, the only thing you can change is the nonce, which is a 32-bit integer. By trying different nonce values, you repeatedly calculate the hash, until you get the hash starting with the desired number of zeros. This is called mining the block. Clearly, the higher the difficulty value, the longer it takes to mine the block. On average, it takes about 10 minutes to mine one block. If you have a long chain of blocks, it will take longer to mine all the blocks; and this is just for one chain. If there are millions of users, you will need to change millions of chains. The proof of work system makes it practically impossible to alter the information on a blockchain. This is what makes blockchain different from other technologies, and it is exactly why it is potentially useful in many applications.

10.4 How Does Blockchain Work?

To see how blockchain works, let's consider the transfer of money as an example. Traditionally, if person A wants to send some money to person B, A will use a bank, as both can trust the bank, see Figure 10.3 (left). This is a centralized approach, in which the bank behaves as a ledger. There are several issues with this approach. First, the bank will charge for the service. Especially for a large sum of money, this could become expensive. Second, transactions take time, especially international transactions. Finally, if the bank has a problem, as happened in the 2008 financial crisis, both person A and person B will suffer.

Schematic flow diagram depicting money transfer using the traditional centralized approach (left) and the blockchain distributed approach (right).

Figure 10.3: Money transfer using the traditional centralized approach (left) and the blockchain distributed approach (right)

Blockchain instead uses a distributed approach. In this case, if person A wants to send some money to person B, A will simply add a new block to the existing blockchain, see Figure 10.3 (right). The new block will contain information such as sender name, receiver name, and amount of money sent. The blockchain is then copied to every user on the network, called peers. Peers form a peer-to-peer network, and all the peers together behave as a form of distributed ledger. Therefore, there is no centralized ledger. This brings several benefits: it is free, it is fast, and it is transparent. Also different from the traditional bank-based approach is that person A did not actually send anything to B—there is no account, and there is no balance. There is only a blockchain shared by all the users, which is then used to work out who sent what, who received what, and what is the final balance. There is no currency item per se; digital currency is just the numbers existing in a record of a series of transactions.

If person B wants to commit fraud by altering the information on the chain, not only does he need to alter his own chain, he also needs to alter the majority of the chains among the users on the network, of which there could be millions. With the proof-of-work system, this is practically impossible.

The following are blockchain technology's key features and benefits:

  • Decentralization This is the core concept of blockchain technology and also its core benefit. There is no centralized ledger to record and validate transactions; instead, the users on the network collectively act as a distributed ledger. As a result, it is free, and it is fast. There is no central bank to charge for the service, and instead of days, a transaction could take just a few hours.
  • Immutability Once the block is created, it cannot be changed. You cannot add or remove blocks from the chain, nor alter any information inside the blocks. The only thing you can do is to add a new block at the end of the chain. This immutability is another key benefit of blockchain, which brings security and reliability.
  • Transparency Because the transaction records are shared with all the users in a peer-to-peer network, everything is transparent; there are no black boxes.
  • High Availability Also, because the transaction records are shared with all the users in a peer-to-peer network, there is no single point of failure; data is highly available.

Figure 10.4 shows an interesting blockchain virtual demo web site (https://blockchaindemo.io/), in which you can see the contents of a block, add new blocks to the chain, and add more peers.

Image described by caption and surrounding text.

Figure 10.4: A virtual blockchain demo

10.5 Uses of Blockchain

Blockchain technology can be used in many applications; here are some examples.

10.5.1 Bitcoin

The first and most important application is digital currency, also called cryptocurrency, as it is protected through encryption. There are many digital currencies; the most popular one is Bitcoin (BTC), symbol image. Bitcoin was invented by Satoshi Nakamoto and released as open-source software in 2009. Bitcoin can be transferred and exchanged for real currencies, products, and services. There are millions of Bitcoin users in the world, which generate millions of transactions every month. The price of a Bitcoin has been rising from a fraction of a dollar to several thousands of dollars. It reached a peak value of nearly $20,000 in December 2017. When trading, you don't need to buy one whole Bitcoin. The smallest Bitcoin unit you can buy and sell is called a satoshi, which is 100 millionth of a Bitcoin. Unlike real currency, which can be supplied unlimited, Bitcoin has limited supply. Bitcoin is created through a process called Bitcoin mining, as described in section 10.3. Bitcoin mining is basically a process that validates the recent transactions, adds new blocks to the chain, and gets rewards. Through Bitcoin mining new Bitcoins are created, but only a small amount can be created each hour, tightly controlled by its underlying algorithm. The new Bitcoins will be continuously created until they reach the maximum of 21 million. This limited supply makes Bitcoin a potential asset: as the demand increases, the value will also increase.

Figure 10.5 shows the structure inside a Bitcoin block. Each block has a header and a body. The header contains a hash of the previous block header, along with the timestamp, difficulty target, nonce, and Merkle root. Within the body are all the transactions. Each block contains about 500 transactions. Each transaction will have its own hash computed, and from all the hashes together a final hash will be computed. The final hash is stored in the Merkle root, or Tx_Root, as shown in Figure 10.5.

Flow diagram depicting structure of the Bitcoin block with Blocks 10 to 12 with Hash 01 and 23 from Tx0 to Tx3.

Figure 10.5: The structure of the Bitcoin block

Adapted from https://upload.wikimedia.org/wikipedia/commons/thumb/5/55/Bitcoin_Block_Data.svg/1200px-Bitcoin_Block_Data.svg.png

Figure 10.6 shows the three layers of the Bitcoin service architecture, adapted from the Luxsci web site. At the bottom is the peer-to-peer network; this is where all the nodes, or users, are connected together. In the middle is the decentralized ledger, where the blockchain technology is implemented. On the top is the applications layer, where application programs such as Bitcoin wallets are implemented.

Schematic diagram depicting three layers of the Bitcoin service architecture with Applications, Decentralized Ledger, and Peer-to-Peer Network.

Figure 10.6: The three layers of the Bitcoin architecture

Adapted from https://luxsci.com/blog/understanding-blockchains-and-bitcoin-technology.html

Several web sites allow you to look into the structure of a Bitcoin chain. Figure 10.7 shows an example from Block Explorer (https://www.blockchain.com/explorer), where you can see that the total number of blocks on the Bitcoin main chain (called its height) was at that time 539,602, the latest block was created about 6 minutes earlier (called the chain's age), it contains 652 transactions, the number of Bitcoins sent is 1,686.25, and the size of the block is 313.35 KB.

Image described by caption and surrounding text.

Figure 10.7: Cryptocurrency Bitcoin Block Explorer (top) and the structure of the latest block (bottom)

The following is another Bitcoin block explorer web site where you can view the latest transactions and the structure of Bitcoin blocks:

https://blockexplorer.com/

Another interesting web site is Learn Me a Bitcoin, at the following URL, where you can learn Bitcoin terminology and also visualize the details of Bitcoin blocks:

http://learnmeabitcoin.com/guide/

However, as its popularity increases, Bitcoin has shown several scalability issues: it uses 1 MB size blocks, it can have only seven transactions per second, and each transaction takes 10 minutes to process. This has led to the development of a new cryptocurrency: Bitcoin Cash (BCH), which is a different version of Bitcoin. This illustrates what is called a fork in software development, as Bitcoin and Bitcoin Cash are based on the same technology (the main branch), and Bitcoin Cash is forking out as a new subbranch. With Bitcoin Cash, it uses 8 MB size blocks, with an adjustable level of difficulty, and transactions take two minutes to process.

If you are interested in trying Bitcoin or other cryptocurrencies, such as Bitcoin Cash, Ether, Ripple, Litecoin, Peercoin, or Dogecoin, you can download and install one of the following popular cryptocurrency digital wallets:

  • Bitcoin Core Created by Satoshi Nakamoto for Bitcoin, it is also called the Satoshi client (https://bitcoin.org/en/bitcoin-core/).
  • Ethereum Ethereum is an open-source, public, blockchain-based distributed computing platform, which offers a cryptocurrency called Ether (https://www.ethereum.org/).
  • Ripple Ripple is a real-time payment system, based on a shared public XRP Ledger. It has been used by banks such as UniCredit, UBS, and Santander (https://ripple.com/).
  • Bitcoin Cash Bitcoin Cash is a hard fork of Bitcoin, only started in 2017. Bitcoin Cash claims to be faster and cheaper to use, with the maximum block size of 8MB (https://www.bitcoincash.org/).
  • Electrum Electrum is a lightweight Bitcoin client, which comes with both a hardware wallet and a software wallet. Hardware wallets allow users to store the Bitcoin information such as private keys in a hardware device, such as a USB memory stick. Unlike a software wallet, a hardware wallet can be physically secured and is immune from viruses, which are designed to steal from software wallets. (https://electrum.org/).
  • Coinbase Coinbase claims to be one of the most well-known and trusted apps to buy, sell, and manage your digital currency (https://www.coinbase.com/).
  • Blockchain Luxembourg This platform has a beautiful user interface that's easy to use and many useful features for cryptocurrency (https://www.blockchain.com/).

Figure 10.8 shows more cryptocurrency wallets from the bitcoin.org web site (https://bitcoin.org/en/choose-your-wallet). Figure 10.9 shows the Live Coin Watch web site, where you can find more details, such as price, market capitalization, volume, and trend, of each cryptocurrency (https://www.livecoinwatch.com/). According to Live Coin Watch, the top three most popular cryptocurrencies are BTC (Bitcoin), XRP (Ripple), and ETH (Ethereum), according to their Market Cap (market capitalization; that is, the total dollar market value). BTC is about $70B, XRP is about $15B, and ETH is about $12B, far ahead of the other cryptocurrencies.

Image described by caption and surrounding text.

Figure 10.8: Cryptocurrency wallets from Bitcoin.org

Image described by caption and surrounding text.

Figure 10.9: The Live Coin Watch web site

For more information, please read Satoshi Nakamoto's white paper, and visit the Bitcoin wiki and the Bitcoin.org pages.

https://bitcoin.org/bitcoin.pdf

https://en.bitcoin.it/wiki/Main_Page

https://bitcoin.org/en/

10.5.2 Smart Contracts

Smart contracts are self-executing contracts designed to enforce the terms of an agreement. Smart contracts are used to control the transfer of digital currencies or assets between parties under certain conditions. With smart contracts, you exchange money, property, shares, or anything of value without needing a middleman. Smart contracts not only define all the rules and all the penalties but also automatically enforce these obligations.

Buying a house, for example, usually involves buyer, seller, and multiple third parties such as real estate agents and lawyers. With a smart contract and digital currency, this can be done just between the buyer and the seller. Once all the conditions are met, the smart contract, which is essentially a software program, will automatically complete the transaction using digital currency. The process consists of the following steps:

  1. Buyer and seller agree on the house price in digital currency, and write the contract into the blockchain. The contract includes all the buyer's and seller's information and terms and conditions. Because the contract is in the public ledger, it therefore cannot be changed.
  2. When all the conditions are met and a trigger event occurs, such as expiration date, the contract will execute itself according to agreed terms.
  3. Seller gets the payment in digital currency and buyer gets the house, including all the legal documents such as land deed. All the clearing and settlement is automated, and the ownership is undisputed.

Figure 10.10 shows the operation of a smart contract, adapted from the BlockGeeks site.

Schematic flow diagram depicting operation of a smart contract from Sell House to Buy House with Digitize The Land Deed and Digitize Currency stages.

Figure 10.10: The operation of a smart contract

Adapted from https://blockgeeks.com/guides/smart-contracts/.

10.5.3 Healthcare

Personal health data can also be stored in the blockchain, protected by encryption, to allow access only by specific users, such as doctors and insurance providers. Doctors will have the full patient history and hence can provide better diagnosis. The medical records will be automatically shared with insurance providers to support claims. Blockchain can be used to verify the authenticity of drugs, to prevent counterfeit drugs and medical devices, and to improve the quality and reliability of clinical trials data.

10.5.4 Manufacture and Supply Chains

Blockchain technology can also be used in manufacturing and supply chains to record any exchange, agreements/contracts, tracking, and payment. Because every transaction is recorded on a block and across multiple copies of the ledger that are distributed among users, this recording method is highly transparent. It's also highly secure. It will be extremely efficient and scalable. You will be able to see the whole record of a product or a component, including where it comes from and where it has been. This is called traceability. Blockchain technology can increase the efficiency and transparency of supply chains. For example, multinational retailer Walmart has partnered with IBM to track food staples from supplier to shelf using its Hyperledger Fabric blockchain. The technology has also been used to track art works, antiques, jewelry, and other valuables for authentication and proof of ownership and to combat counterfeiting.

10.5.5 Internet of Things

With the Internet of Things (IoT), billions of devices will be interconnected. Securely storing the enormous amounts of data generated by the IoT systems presents a huge challenge. With blockchain technology's distributed ledger, IoT data can be stored distributed in a trustless fashion, and it can be better organized and analyzed to produce valuable insights. Blockchain is perfectly suited for both public- and private-sector IoT systems, because of its identification, verification, and data transfer abilities. Blockchain can build trust between parties and devices, can reduce cost by removing the middlemen, and can accelerate transactions by reducing the settlement time.

10.5.6 Government

Voting is one of the most important democratic processes for a government. With blockchain, voting can be more open, less costly, and less prone to fraud. Many kinds of government information and data can also be stored in blockchain, which will make it easier to access and make the government more transparent and reduce corruption. To learn more, see this site:

https://blockgeeks.com/guides/blockchain-applications/

10.6 Issues with Blockchain

Just like any other technology, blockchain also has some limitations.

  • Security Because blockchain relies on the users to store the record, if a majority of the users decide to alter a record, then that change of the record will be accepted. This is called a 51 percent attack. Satoshi Nakamoto highlighted this security flaw when bitcoin was launched. To minimize the possibility of this 51 percent attack, the network will need to be larger than a certain size so that no one or no one group can have more than 51 percent of the control. Hacking is also a common threat to digital currencies.
  • Complexity Blockchain is based on huge, complex technologies that involve sophisticated mathematics and huge amounts of software programming. The complexity of blockchain will make it difficult for anyone to understand how it works and what benefits it brings and therefore hinder its application.
  • Lack of Regulation Because blockchain technology is so new, there is little regulation. The lack of regulation creates a risky environment, where fraud, scams, and market manipulation are commonplace.
  • Quantum Readiness Blockchain is built on encryption, which is safe for today's computers. But with the emergence of technology such as quantum computing, computers could run 100 million times faster than they currently do, which will pose a significant threat to all the forms of encryption you are using today. To face this challenge, a quantum-resistant cryptographic system needs to be developed.
  • Scalability As the network grows, the processing of transaction on the blockchain can be slow and cumbersome because of the complexity, encrypted, and distributed nature. For example, popular blockchain platforms like Bitcoin and Ethereum can process around 7 to 15 transactions per second on average, while Visa currently processes around 5,000 to 8,000 transactions per second on average. More research is needed to improve scalability.

10.7 Java Blockchain Examples

Let us look at some examples of Java blockchain applications. Example 10.1 shows a simple Java blockchain demonstration program. It consists of two Java files, Block.java and BlockChainMain.java. The first, Block.java (Example 10.1A), has the task of creating a single block. In each block there are six attributes and three methods. The attributes are the same as explained earlier: index, timestamp, currentHash, previousHash, data, and nonce. The three methods are calculateHash(), mineBlock() and toString(). The calculateHash() method is for calculating the current hash of the block, mineBlock() is for mining the block according to the specified difficulty (the number of leading zeros), and toString() is for display the information of the block. To create a block you will need to provide information about index, previousHash, and data.

BlockChainMain.java (Example 10.1B) is the main program, which creates a blockchain and adds two blocks to the chain. Figure 10.11 shows the compilation and execution of BlockChainMain.java.

Screen capture depicting code of compilation and execution of BlockChainMain.java.

Figure 10.11: The compilation and execution of BlockChainMain.java

You can modify the BlockChainMain.java program to also validate the blocks, as shown in Example 10.1C, the BlockChainMain2.java program. It uses a new function named ValidateBlock(), which can validate a block based on its index, the previous hash, and the current hash. Figure 10.12 (top) shows the compilation and execution of BlockChainMain2.java. As you can see, both blocks added are valid.

Screen capture depicting code of compilation and execution of BlockChainMain2.java, with both blocks valid (top) and the second block not valid (bottom).

Figure 10.12: The compilation and execution of BlockChainMain2.java, with both blocks valid (top) and the second block not valid (bottom)

Now if you uncomment the following line in the program, the effect is equivalent to manually modifying the block after it is created:

//b2.data="My Third Block";

When you recompile and run the program, it will show that the second block is not valid, as shown in Figure 10.12 (bottom).

Example 10.1D (BlockChainMain3.java) shows how to validate the whole blockchain. To do that, you will need to validate all the blocks in the blockchain. The new ValidateChain() method uses a loop to go through all blocks on the chain and validate each block using the previous ValidateBlock() method. Figure 10.13 shows the compilation and execution of the BlockChainMain3.java program.

Screen capture depicting code of compilation and execution of BlockChainMain3.java.

Figure 10.13: The compilation and execution of BlockChainMain3.java

10.8 Java Blockchain Transaction Examples

Now you are ready to start doing something interesting with the blockchain. Example 10.2 shows how to use a blockchain record transaction. It contains four Java classes, Block2.java, Transaction.java, Wallet.java, and BlockChainMain4.java. The Block2.java program (Example 10.2A) is similar to the previous Block.java, but instead of using String data, it uses ArrayList<Transaction> transactions inside each block. The ArrayList is used to store several transactions.

Transaction.java (Example 10.2B) simply records a transaction, which includes information such as sender, recipient, and value.

Wallet.java (Example 10.2C) creates a digital wallet for a user. It uses generateKeyPair() to generate a public/private key pair for the user, getBalance() to get the user's balance, and send() to send some digital coins to another user using the public keys of the sender and recipient. The getBalance() method basically goes through the entire blockchain searching for transactions for the user. If a transaction is sending, the method deducts the transaction value from the balance; if receiving, it adds the value to the balance. For the sake of simplicity, each digital wallet contains 100 digital coins.

BlockChainMain4.java is the main program that uses Wallet.java for blockchain transactions. It simply creates two digital wallets and displays their balance, as illustrated in Figure 10.14.

Screen capture depicting code of compilation and execution of BlockChainMain4.java.

Figure 10.14: The compilation and execution of BlockChainMain4.java

Next, you can add some transactions. In Example 10.2E, two transactions were added: A sends 10 coins to B, and A sends 20 coins to B. You can also use the previous ValidateChain() to validate the whole blockchain. Figure 10.15 shows the output of the program. As you can see, both transactions went through, and the whole blockchain is valid.

Screen capture depicting code of compilation and execution of BlockChainMain5.java.

Figure 10.15: The compilation and execution of BlockChainMain5.java

If you change the second transaction to 200 (that is, A sends 200 coins to B), this exceeds the total balance of wallet A; therefore, the transaction is discarded, as shown in Figure 10.16.

Screen capture depicting code of compilation and execution of BlockChainMain5.java, where transaction is discarded.

Figure 10.16: The compilation and execution of BlockChainMain5.java

The most popular Blockchain libraries for Java developers are these:

10.9 Java BitcoinJ Example

BitcoinJ is an open source library for developing Java Bitcoin applications. BitcoinJ allows you to maintain a wallet and to send and receive transactions without needing a local copy of Bitcoin Core. To use BitcoinJ, first you will need to download the BitcoinJ JAR file bitcoinj-core-0.14.4-bundled.jar from its web site.

https://bitcoinj.github.io/getting-started-java

Alternatively, you can just directly download the JAR file from the following links:

https://search.maven.org/remotecontent?filepath=org/bitcoinj/bitcoinj-core/0.14.4/bitcoinj-core-0.14.4-bundled.jar

https://jar-download.com/artifacts/org.bitcoinj

Second, you will also need to download the Simple Logging Facade for Java (SLF4J) library from this site:

https://www.slf4j.org/download.html

Extract the downloaded file to a folder, and get a file named something like slf4j-simple-1.7.25.jar. Again, don't worry if your version number is slightly different.

Example 10.3 is a simple demonstration program, modified from the BitcoinJ example DumpWallet.java at this site:

https://github.com/bitcoinj/bitcoinj/blob/master/examples/src/main/java/org/bitcoinj/examples/DumpWallet.java

Put the DumpWallet1.java file, bitcoinj-core-0.14.4-bundled.jar, and slf4j-simple-1.7.25.jar all into one folder. Then you can compile and run the DumpWallet1.java program by typing the following commands:

javac -classpath ".;bitcoinj-core-0.14.4-bundled.jar;slf4j-simple-1.7.25.jar" DumpWallet1.java
java -classpath ".;bitcoinj-core-0.14.4-bundled.jar;slf4j-simple-1.7.25.jar" DumpWallet1

You will need a wallet file to make this program work. See section 10.10 to learn how to create a digital wallet file. For more BitcoinJ examples, you can download the entire source code from its Github web site here:

https://github.com/bitcoinj/bitcoinj

This site offers a simple tutorial on how to build a simple GUI wallet using BitcoinJ library:

https://bitcoinj.github.io/simple-gui-wallet

10.9.1 The Testnet

Before you run your program on real Bitcoin, it is always a good idea to test it in a simulated environment. The Bitcoin community provides a simulated Bitcoin network called the testnet. With the testnet, you can send and receive coins. The coins on the testnet have no value and can be obtained for free from testnet faucet sites like these:

https://testnet-faucet.mempool.co/

http://tpfaucet.appspot.com/ .

For more information about the BitcoinJ library, see the following:

https://bitcoinj.github.io/

https://github.com/bitcoinj/bitcoinj

10.10 Java Web3j Examples

Web3j is a lightweight Java library for integration with Ethereum clients. With Web3j you can create a digital wallet, manage the wallet, send Ether, the Ethereum digital cryptocurrency, and create a smart contract. The easiest way to use the Web3j library is to download its command line tools from the following GitHub site:

https://github.com/web3j/web3j/releases/tag/v4.0.1

There, look for a zip file named web3j-4.0.1.zip. More information about the Web3j command-line tools can be found here:

https://docs.web3j.io/command_line.html

Unzip the web3j-4.0.1.zip file to a folder, in this case E:web3j-4.0.1. The main command-line tool program is named web3j.bat in the E:web3j-4.0.1in folder. Open an MS-DOS terminal, go to the E: folder, and type in the following command to create a digital wallet, as shown in Figure 10.17:

Image described by caption and surrounding text.

Figure 10.17: The Web3j command to create a digital wallet (top) and using the type command to display the content of the wallet (bottom)

.web3j-4.0.1inweb3j wallet create

You will need to provide a password to your digital wallet; once you've done that, a wallet file with a filename like the following will be created:

UTC--2018-11-26T13-18-32.250132200Z--ccded263b9310c875d615bf66ba678e 121c26362.json

The default location for the digital wallet is shown next, where %USERPROFILE% is your user folder. For example, on my computer it is C:Usersxiaop.

%USERPROFILE%AppDataRoamingEthereum estnetkeystore But you can change it to another folder.

You can use the Windows type command (or any text editor) to display the content of the wallet file, as shown in the following output. The address in the wallet is your unique address, which can be used to send Ether or create a smart contract. The crypto in the wallet specifies the encryption algorithm you are using and your private key.

{
"address":"168d8513597cc0958f635a679a5b60ccd13d6ef1",
"id":"721b533c-c552-4f94-9860-5b70cb45497a",
"version":3,
"crypto":{"cipher":"aes-128-ctr",
"ciphertext":"1924aaf30e9b6ea7360caeeab7f1afac196aa9455fea022186642a6dc35c7cd7",
"cipherparams":{"iv":"70c135529198af334f952192f577f2b6"},
"kdf":"scrypt",
"kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"68a357b71dc0f3a92726a761125f9cabee2ed4a1d6d0ea183ee6c37d608c97e9"},
"mac":"6dab6ec9ee482c10556e26264c13047a6d9386f2c1ae4cea1c26e0bc5d662bab"}
}

You can use the Etherscan web site to display the transactions at your address; the URL is as follows:

https://etherscan.io/address/<your address>

Figure 10.18 shows the Etherscan web site of the address specified in the digital wallet (https://etherscan.io/address/0x168d8513597cc0958f635a679a5b60ccd13d6ef1). Because you have just started, there are no transactions at the moment.

Image described by caption and surrounding text.

Figure 10.18: The Etherscan web site can show the transactions for your address.

Before you can send anybody any Ether, you will need to get some Ether. You can get Ether either by mining it or by obtaining it from someone else. Once you have some Ether, you can use the following command to send it to someone:

.web3j-4.0.1inweb3j wallet send <walletfile> 0x<address>|<ensName>

It will ask you to enter the wallet password, confirm the receiver address, specify the amount of Ether you want to send, and specify the Ether unit (such as ether or wei).

For more details on smart contracts and Web3j examples, see the following web sites:

https://docs.web3j.io/smart_contracts.html

https://github.com/web3j/sample-project-gradle

https://github.com/web3j/examples

The following are Web3j official web sites:

https://web3j.io/

https://github.com/web3j/web3j

https://docs.web3j.io/

10.11 Java EthereumJ Examples

EthereumJ is a pure-Java implementation of the Ethereum protocol. The EthereumJ library allows you to interact with the Ethereum blockchain using Java. The easiest way to obtain and use EthereumJ is by using Git; see Appendix C for more details on how to download, install, and use Git.

In Windows, just run the Git Bash program, and from the Git Bash command line, type the following command to download and run a simple EthereumJ starter example:

git clone https://github.com/ether-camp/ethereumj.starter
cd ethereumj.starter
./gradlew run 

Please note that the ./gradlew run command will download quite a few files and may take several minutes. It will also configure and run a local REST server. To check the results, type the following command at the Git Bash command line, to view the information for the local blockchain:

curl -w "
" -X GET http://localhost:8080/bestBlock 

The following command will download, or clone, the entire EthereumJ project source:

git clone https://github.com/ethereum/ethereumj

After the download, you can change to the ethereumj subfolder and run an example program named TestNetSample, which is an example for Testnet (see section 10.9.1). Also shown here are the truncated results (the full results are too long):

cd ethereumj
./gradlew run -PmainClass=org.ethereum.samples.TestNetSample
Starting a Gradle Daemon, 1 incompatible Daemon could not be reused, use --status for details
Building version: 1.13.0-SNAPSHOT (from branch develop)
publishing if master || develop current branch: null
[buildinfo] Properties file path was not found! (Relevant only for builds running on a CI Server)
 
:ethereumj-core:processResources
This will be printed after the build task even if something else calls the build task
:ethereumj-core:classes
:ethereumj-core:run
20:09:17.397 INFO [sample]  Starting EthereumJ!
20:09:17.444 INFO [general]  Starting EthereumJ…
20:09:26.092 INFO [general]  External address identified: 59.72.70.14
20:09:26.170 INFO [discover]  Pinging discovery nodes…
 
20:09:26.339 INFO [general]  EthereumJ node started: enode://23b940843d8adf1fb0ccfe4a781e9e35850be7f3aaf6dd5e3b1f2371c1361cc2baaac2d8c95882c34b7ae5ff18bf8a504d50e99f22ad4ee60963fa4930d0c9e8@59.72.70.14:30303
20:09:26.355 INFO [general]  DB is empty - adding Genesis
20:09:26.424 INFO [general]  Genesis block loaded
20:09:26.439 INFO [ethash]  Kept caches: cnt: 1 epochs: 0…0
20:09:26.471 INFO [general]  Bind address wasn't set, Punching to identify it…
20:09:47.519 WARN [general]  Can't get bind IP. Fall back to 0.0.0.0: java.net.ConnectException: Connection timed out: connect
20:09:47.519 INFO [discover]  Discovery UDPListener started
20:09:47.688 INFO [net]  Listening for incoming connections, port: [30303]
20:09:47.688 INFO [net]  NodeId: [23b940843d8adf1fb0ccfe4a781e9e35850be7f3aaf6dd5e3b1f2371c1361cc2baaac2d8c95882c34b7ae5ff18bf8a504d50e99f22ad4ee60963fa4930d0c9e8]
20:09:47.741 INFO [discover]  Reading Node statistics from DB: 0 nodes.
20:09:48.085 INFO [discover]  Received response.
20:09:49.001 INFO [discover]  New peers discovered.
20:09:57.570 INFO [net]  TCP: Speed in/out 3Kb / 3Kb(sec), packets in/out 91/150, total in/out: 31Kb / 37Kb
20:09:57.570 INFO [net]  UDP: Speed in/out 8Kb / 6Kb(sec), packets in/out 438/465, total in/out: 81Kb / 63Kb
20:10:07.575 INFO [net]  TCP: Speed in/out 3Kb / 4Kb(sec), packets in/out 98/162, total in/out: 66Kb / 78Kb
20:10:07.575 INFO [net]  UDP: Speed in/out 4Kb / 2Kb(sec), packets in/out 178/192, total in/out: 123Kb / 89Kb
20:10:48.541 INFO [discover]  Write Node statistics to DB: 829 nodes.

You can also run other example programs, such as these:

./gradlew run -PmainClass=org.ethereum.samples.BasicSample
./gradlew run -PmainClass=org.ethereum.samples.FollowAccount
./gradlew run -PmainClass=org.ethereum.samples.PendingStateSample
./gradlew run -PmainClass=org.ethereum.samples.PriceFeedSample
./gradlew run -PmainClass=org.ethereum.samples.PrivateMinerSample
./gradlew run -PmainClass=org.ethereum.samples.TransactionBomb

For more details about EthereumJ, see this page:

https://github.com/ethereum/ethereumj

10.12 Java Ethereum Smart Contract Example

In the chapter's final Java example, you'll learn how to create an Ethereum Smart Contract. To that, you will need to use Solidity, the designated programming language for Ethereum Smart Contracts, which can be downloaded from the following web site:

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

(In this book, the Solidity downloaded is version 0.5.7.) For Windows, just look for an archive named solidity-windows.zip. Download it and unzip it to a local folder; in this example, you use E:solidity-windows. The solc.exe file in the folder is what you need to compile Solidity programs.

For other operating systems, just follow their instructions accordingly.

You will also need Web3j. Please see section 10.10 for download details. Again, you assume it is downloaded and unzipped into a local folder named E:web3j-4.0.1.

Create a folder named E:contractssolidity. Use a text editor to create a file named Greeter.sol in this folder, and save the content in Example 10.4 into the file. This is a simple Smart Contract application, which essentially has just one function, greet(), which just returns the value in a String variable named greeting.

From a Windows terminal, go to the E:contractssolidity folder, and type in the following command to compile the Solidity program:

E:solidity-windowssolc Greeter.sol --bin --abi --optimize -o ../build

This will create the following two .bin files and two .abi files in E:contractsuild folder:

E:contractsuildGreeter.bin
E:contractsuildGreeter.abi
E:contractsuildMortal.bin
E:contractsuildMortal.abi

For more information about Solidity programming, see the following site:

https://solidity.readthedocs.io/

Then, from the E:contractsuild folder, type in the following command to create a Java project for the Ethereum Smart Contract:

E:web3j-4.0.1inweb3j solidity generate ./greeter.bin ./greeter.abi -o ../../src/main/java 

This will create the Java project in the E:src folder, which has the following structure and contains a Java program called Greeter.java:

E: 
   src
       main
            java
                 Greeter.java

Example 10.5 is the generated Greeter.java program.

Next, use Web3j to create a digital wallet. The procedure is the same as illustrated in section 10.10. Enter the password when prompted, and save the wallet in a folder on your E: drive.

E:web3j-4.0.1inweb3j wallet create

The digital wallet will be something like the following, where d517e874a888b58d02dad75c26f2a7ddec14f07b is the wallet ID.

E:UTC--2019-04-12T03-47-43.931058900Z--d517e874a888b58d02dad75c26f2a7ddec14f07b.json

You will need this wallet password and ID later. Next go to the Infura (https://infura.io/) web site to register an account, create a new project, and copy out the secret key. Infura is an online platform that provides a wide variety of tools to connect your applications to Ethereum. For more information about using Infura with Web3j, see the following site:

https://docs.web3j.io/infura.html

Example 10.6 shows a Java program that can use the Greeter.java program to deploy the Smart Contract and execute the Smart Contract. In this program, the rinkebyKey is the project ID or token ID you got from Infura, and the walletFilePassword and walletId are what you have created using Web3j. Please update them with your own values.

You can compile and run the Greeting.java and Greeter.java programs by typing the following commands:

javac -classpath ".;E:\web3j-4.0.1\lib\*" Greeter.java Greeting.java
java -classpath ".;E:\web3j-4.0.1\lib\*" Greeting

If everything is correct, you should see a “Hello Smart Contract” message on the screen; otherwise, it will display an error message to explain what is going wrong. A common error is “insufficient funds for gas * price + value.” This is simply because you have not got enough Ether coin in your account. You can either get real Ether:

https://github.com/ethereum/wiki/wiki/Getting-Ether

https://www.ethereum.org/ether

or get Ether for testing:

https://faucet.rinkeby.io/

10.13 Go Further: Choosing a Blockchain Platform

If you want to go further with blockchain, whatever your applications might be—cryptocurrency, healthcare, manufacturing, supply chains, or the IoT—the next and most important step is to choose a suitable blockchain platform and then develop your own decentralized applications, known as DApps. Decentralized applications are different from traditional centralized applications, such as Google, Facebook, or Amazon, where the contents are owned by a central entity. For decentralized applications, the contents are owned by the users. The following is a list of popular blockchain platforms:

  • Bitcoin (https://bitcoin.org/en/) This is the first blockchain platform, where it all started. This platform is solely designed for one purpose only, which is for the crypocurrency Bitcoin (BTC). The software implementation of Bitcoin is called Bitcoin Core (https://bitcoincore.org/), also called Bitcoin client. Bitcoin Core is written in C++. Today, Bitcoin is the most successful digital currency, with billions of dollars invested in it around the world.
  • Ethereum (https://www.ethereum.org/) Ethereum was founded in November 2013, by Vitalik Buterin, a Russian-Canadian programmer, when he was only 19 years old! Unlike the Bitcoin platform, the Ethereum platform can do more than just cryptocurrency. Ethereum is written in a Turing-complete language, which includes seven different programming languages. Featuring smart contract functionality, Ethereum is an open source software platform that enables developers to build and deploy decentralized applications based on blockchain technology. Ethereum has its own cryptocurrency, Ether (ETH), and its own programming language, Solidity, a contract-oriented programming language for writing smart contracts.
  • Eris (https://monax.io/platform/) Built on the Ethereum blockchain, Eris is another free, open platform for building, testing, maintaining, and operating decentralized applications. Eris makes it easy and simple to implement smart contracts.
  • IBM Blockchain (https://www.ibm.com/blockchain) IBM Blockchain, which is based on the open source Hyperledger Fabric, is a public cloud service that aims for business customers to build secure blockchain networks. Hyperledger Fabric is different from traditional blockchain networks, which can't support private transactions or confidential contracts, which are key for businesses. Hyperledger Fabric addresses this issue by keeping private transactions private and keeping the specific data to be accessible only to who needs to know.
  • NEO (https://neo.org/) NEO is a nonprofit community-driven blockchain platform. It aims to create a “smart economy,” by utilizing digitize assets, digital identity, and smart contracts. Using a distributed network, Neo uses an interesting consensus mechanism that can improve its scalability.

10.14 Summary

This chapter introduced the concept of blockchains, as well as how to validate a blockchain and how to mine the blocks. Then you learned how blockchains work and what they can be used for. You also saw variations of a simple Java blockchain example, using the BitcoinJ, Web3j, and EthereumJ open source libraries. Finally, you looked at the platforms you'll need to choose from when you decide to go further and use blockchain in your own business. Blockchain is a fascinating technology. Although it still has some issues, it is nevertheless amazing and has the potential to fundamentally change the world.

10.15 Chapter Review Questions

Q10.1.When was blockchain invented, and who invented blockchain?
Q10.2.Use a suitable diagram to illustrate what is inside a block and what is the relationship between two adjacent blocks.
Q10.3.How do you validate a blockchain?
Q10.4.What is a blockchain consensus?
Q10.5.What does it mean to mine a blockchain? What is proof of work?
Q10.6.What can blockchains be used for?
Q10.7.What are the issues with blockchain technology?
Q10.8.What are Bitcoin and Bitcoin Cash? What is a fork in software development?
Q10.9.What is a smart contract?
Q10.10.What are the differences between the Bitcoin blockchain platform, the Ethereum platform, and the Hyperledger Fabric platform?
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset