Introducing Blockchain with Java: Program, Implement, and Extend Blockchains with Java 1st Edition Spiro Buzharovski - The complete ebook is available for download with one click
Introducing Blockchain with Java: Program, Implement, and Extend Blockchains with Java 1st Edition Spiro Buzharovski - The complete ebook is available for download with one click
com
https://ebookmeta.com/product/introducing-blockchain-with-
java-program-implement-and-extend-blockchains-with-java-1st-
edition-spiro-buzharovski-2/
OR CLICK HERE
DOWLOAD EBOOK
https://ebookmeta.com/product/introducing-blockchain-with-java-
program-implement-and-extend-blockchains-with-java-1st-edition-spiro-
buzharovski/
ebookmeta.com
https://ebookmeta.com/product/learn-java-with-math-1st-edition-ron-
dai/
ebookmeta.com
https://ebookmeta.com/product/statistics-of-earth-science-data-their-
distribution-in-time-space-and-orientation-2nd-edition-graham-j-
borradaile/
ebookmeta.com
Rethinking darkness cultures histories practices 1st
Edition Nick Dunn Editor Tim Edensor Editor
https://ebookmeta.com/product/rethinking-darkness-cultures-histories-
practices-1st-edition-nick-dunn-editor-tim-edensor-editor-2/
ebookmeta.com
https://ebookmeta.com/product/junkyard-blues-1st-edition-al-moye/
ebookmeta.com
https://ebookmeta.com/product/marketing-an-introduction-15th-global-
edition-gary-armstrong/
ebookmeta.com
https://ebookmeta.com/product/spectacular-sports-world-s-toughest-
races-understanding-fractions-saskia-lacey/
ebookmeta.com
https://ebookmeta.com/product/the-grey-eagles-of-chippewa-falls-1st-
edition-john-e-kinville/
ebookmeta.com
The Protocol of the Gods A Study of the Kasuga Cult in
Japanese History Allan G. Grapard
https://ebookmeta.com/product/the-protocol-of-the-gods-a-study-of-the-
kasuga-cult-in-japanese-history-allan-g-grapard/
ebookmeta.com
CHAPTER 1
Introduction
to Blockchain
https://doi.org/10.1007/978-1-4842-7927-4_1
Note that we will skip some of the technical bits in this chapter, as it
is only supposed to serve as introductory material. The technical bits
will be covered later when we start building the blockchain.
Let’s assume that you and your friends exchange money often, for
example, paying for dinner or drinks. It can be inconvenient to
exchange cash all the time.
One possible solution is to keep records of all the bills that you and
your friends have. This is called a ledger and is depicted in Figure 1-
1.
1 We will use this definition throughout the book, but note that there
are many different definitions on the Internet. By the end of this
book, you should be able to distinguish the slight nuances and
similarities in each definition.
transactions.
Further, at the end of every day, you all sit together and refer to the
ledger to do the calculations to settle up. Let’s imagine that there is a
pot that is the place where all of the money is kept. If you spent
more than you received, you put that money in the pot; otherwise,
you take that money out.
There are several ways this can be resolved, and the solution that we
will provide will be a simple check of the sum of the inputs and the
sum of the outputs.
A problem that might appear with this kind of system is that anyone
can add a transaction. For example, Bob can add a transaction where
Alice pays him a few dollars without Alice’s approval. We need to re-
think our system such that each transaction will have a way to be
verified/signed.
Definition 1-3 a
However, let’s assume that Bob is keeping the ledger to himself, and
everybody agrees to this. The ledger is now stored in what is a
centralized place. But in this case, if Bob is unavailable at the end of
the day when everybody gathers to settle up, nobody will be able to
refer to the ledger.
We need a way to decentralize the ledger, such that at any given time
any of the people can do a transaction. For this, every person
involved will keep a copy of the ledger to themselves, and when they
meet at the end of the day, they will sync their ledgers.
You are connected to your friends, and so are they to you. Informally,
this makes a peer-to-peer network.
Definition 1-4 a
peer-to-peer network is formed when two or
For example, when you are accessing a web page on the Internet
using a browser, your browser is the client, and the web page you’re
accessing is hosted by a server. This represents a centralized system
since every user is getting the information from a single place—the
server.
With the system (Figure 1-3), as the list of peers (people) grows, we
might run into a problem of trust. When everybody meets at the end
of the day to sync their ledgers, how can they believe the others that
the transactions listed in their ledgers are true? Even if everybody
trusts everybody else for their ledger, what if a new person wants to
join this network? It’s natural for existing users to ask this newcomer
to prove that they can be trusted. We need to modify our system to
support this kind of trust. One way to achieve that is through so-
called proof of work, which we introduce next.
5
Chapter 1 IntroduCtIon to BloCkChaIn
Definition 1-5 a
For each record we will also include a special number (or a hash) that
will represent proof of work, in that it will provide proof that the
transaction is valid. We will cover the technical details in the
“Hashing”
section.
At the end of the day, we agree that we will trust the ledger of the
person who has put most of the work in it. If Bob has some errands
to run, he can catch up the next day by trusting the rest of the peers
in the network.
1.2 Encryption
Note that in this section we will mostly talk about numbers, but
characters and letters can also be encrypted/decrypted with the same
methods, by using the ASCII2 values for the characters.
1.2.1 Functions
( x)
12
23
……
1.2.2 Symmetric-Key Algorithm
9
Chapter 1 IntroduCtIon to BloCkChaIn
This scheme is known as the Caesar cipher. To encrypt the text “abc”
we have E("abc") = "bcd", and to decrypt it we have D("bcd") =
"abc".
We share the public key with the world and keep the private one to
ourselves.
This algorithm scheme has a neat property where only the private
key can decode a message, and the public key can encode a
message.
10
public key p
1. Pick one random number, for example 100. This will represent a
common, publicly available key.
4. To encrypt data, add it to the public key and take modulo 100: E(x,
p) = (x + p) mod 100.
5. To decrypt data, we use the same logic but with our private key, so
D(x′ , s) = (x′ + s) mod 100.
11
The wallet will contain a pair of public and a private key. These keys
will be used to receive or send money. With the private key, it is
possible to write new blocks (or transactions) to the blockchain,
effectively spending money. With the public key, others can send
currency and verify signatures.
EXERCISE 1-1
EXERCISE 1-2
12
EXERCISE 1-3
EXERCISE 1-4
1.3 Hashing
13
The hash of the block is based on the block’s data itself, so to verify a
hash we can just hash the block’s data and compare it to current
hash.
EXERCISE 1-5
EXERCISE 1-6
In which way can the linked list depicted in Figure 1-4 be traversed?
What are the implications of this property?
3 Hashcash was initially targeted for limiting email spam and other
attacks.
However, recently it’s also become known for its usage in blockchains
as part of the mining process. Hashcash was proposed in 1997 by
Adam Backa.
14
Definition 1-10 a
1.5 Bitcoin
15
Chapter 1 IntroduCtIon to BloCkChaIn Although there are many
blockchain models and each one of them differs in implementation
details, the blockchain we will be building upon in this book will look
pretty similar to Bitcoin, with some parts simplified.
We will list a few important workflows that our system will use,
among others.
Checking a wallet balance for person A will first filter all blocks in the
blockchain (sender = A or receiver = A) and then sum them to
calculate the balance. The more our blockchain grows, the longer this
operation will take. For that purpose, we will use unspent transaction
outputs or the UTXO model. This model is a list of transactions
containing information about the owner and the amount of money.
Thus, every transaction will consume elements from this list.
1.7 Summary
The point of this chapter is to get a vague idea of how the system
that we will implement looks. Things will become much clearer in the
next chapter where we will be explicit about the definitions of every
entity.
16
17
CHAPTER 2
Model: Blockchain
Core
https://doi.org/10.1007/978-1-4842-7927-4_2
5pir3x/e- coin. The exercises included will offer insight and give you
ideas for you to modify my code to create alternative
implementations of various aspects of the application. I urge you to
try to complete as many of them as possible; my hope is that at the
end you will have not only a greater and deeper understanding of
blockchain technology but also with a great project for your portfolio
that’s an alternative to my implementation instead of a mere copy. I
have chosen to create a folder named Model inside my
src.com.company folder structure in my repository and keep my
model classes there. It is recommended that you choose the same
folder structure for your project to avoid any pathing or import
problems.
2.1 Block.java
We will start first by listing the imports in the following code snippet:
1 package com.company.Model;
3 import sun.security.provider.DSAPublicKeyImpl; 4
5 import java.io.Serializable;
6 import java.security.InvalidKeyException;
7 import java.security.Signature;
8 import java.security.SignatureException;
9 import java.util.ArrayList;
10 import java.util.Arrays;
11 import java.util.LinkedList;
12
20
14
The field prevHash will contain the signature or, in other words, the
encrypted data from the previous block. The currHash will contain the
signature or, in other words, the encrypted data from this block,
which will be encrypted with the private key of the miner that will get
to mine this block. The timeStamp obviously will contain a timestamp
of when this block was mined/finalized. The field minedBy will contain
the public key, which also doubles as the public address of the miner
that managed to mine this block. In the process of blockchain
verification, this public address/public key will be used to verify that
the currHash/signature of this block is the same as the hash of the
data presented by this block and secondary that this block was
indeed mined by this particular miner.
21
We will touch on this topic a bit later in this section when we explain
the isVerified method of this class. Next is our ledgerId field. Since
we intend to implement a database with separate Block and
Transaction tables, this field will help us retrieve the correct
corresponding ledger for this block. You can also look at this field as
the block number. Our next fields, miningPoints and luck, will be used
to form the network consensus in regard to choosing this block’s
miner.
We will get into the details of how these fields are used in Chapter 6.
The field transactionLedger is simply an arraylist of all the
transactions contained in this block. We will explain the Transaction
class in the section “Transaction.java.”
28 this.prevHash = prevHash;
29 this.currHash = currHash;
30 this.timeStamp = timeStamp;
31 this.minedBy = minedBy;
32 this.ledgerId = ledgerId;
35 this.luck = luck;
36 }
22
43 }
44 //This constructor is used only for creating the first block in the
blockchain.
45 public Block() {
48
48
51 signing.initVerify(new DSAPublicKeyImpl(this.minedBy)); 52
signing.update(this.toString().getBytes()); 53 return
signing.verify(this.currHash); 54 }
55
23
What’s left, as shown in our next snippet, are the equals and hash
methods, the generic getters and setters, and the toString() method,
which concludes our Block.java class:
55
56 @Override
62 }
63
64 @Override
66 return Arrays.hashCode(getPrevHash()); 67 }
68
71
24
prevHash; }
currHash; }
74
return transactionLedger; }
77 this.transactionLedger = transactionLedger; 78 }
79
80 public String getTimeStamp() { return timeStamp; }
this.minedBy = minedBy; }
82
this.timeStamp = timeStamp; }
84
86
this.miningPoints = miningPoints; }
91
this.ledgerId = ledgerId; }
94
25
Chapter 2 Model: BloCkChain Core
95 @Override
97 return "Block{" +
98 "prevHash=" + Arrays.toString(prevHash) +
104 '}';
105 }
106}
107
The first thing to note here is that the equals method compares the
previous hash of the block class. We’ll use this later in Chapter 6
when we explain the consensus algorithm further. The other thing of
note is the fields contained in the toString method. We include
everything that goes into verifying the block against the current hash.
Important!
• remember that a wallet’s public key is also the wallet’s public
address/account number.
• the miner’s private key is used to encrypt the block’s data, which
creates the signature.
26
• the miner’s public key is used for other peers to verify the block by
comparing the signature’s hash against the hash of the block’s data.
• note how all of the essential fields that make certain the block is
unique are included in the toString() method.
2.2 Transaction.java
1 package com.company.Model;
3 import sun.security.provider.DSAPublicKeyImpl; 4
5 import java.io.Serializable;
6 import java.security.InvalidKeyException;
7 import java.security.Signature;
8 import java.security.SignatureException;
9 import java.time.LocalDateTime;
10 import java.util.Arrays;
11 import java.util.Base64;
12
27
Next let’s go over the class declaration and its fields, as shown in the
next code snippet:
14
24
Since this class also creates objects from which we are building our
blockchain, it will implement the interface serializable so that it’s
shareable through the network.
The fields from and to will contain the public keys/addresses of the
account that sends and the account that receives the coins,
respectively.
The value is the amount of coins that will be sent, and timeStamp is
the time at which the transaction has occurred. Signature will contain
the encrypted information of all the fields, and it will be used to verify
the validity of the transaction (it will be used the same way the field
currHash was used in the previous class).The ledgerId serves the
same purpose as in the previous class. The fields with the FX suffix
are simple duplicates formatted to String instead of byte[]. We do
this so that we can easily display them on our front end.
In this class we also have two constructors; the first one is used
when we retrieve a transaction from the database, and the second
one is used when we want to create a new transaction within our
application. Let’s observe them in the following code snippet:
28
28 String timeStamp) {
35 this.signature = signature;
36 this.signatureFX = encoder.encodeToString(signature); 37
this.ledgerId = ledgerId;
38 this.timestamp = timeStamp;
39 }
49 this.ledgerId = ledgerId;
50 this.timestamp = LocalDateTime.now().toString(); 51
signing.initSign(fromWallet.getPrivateKey()); 29
Chapter 2 Model: BloCkChain Core
52 String sr = this.toString();
.signature);
56 }
57
The first constructor simply sets the class fields according to the
retrieved data from the database and uses the Base64.Encoder class
to convert the byte[] fields safely into String.
30
To achieve this, first we set up our data by initiating our class fields
from the parameters and add a timestamp as shown on lines 44 to
50. Now once we have our data that we would like to encrypt, we set
our private key to the signing object with the statement on line 51.
This tells the signing object, when encrypting, to use the private key
we provided. On line 52
60 signing.initVerify(new DSAPublicKeyImpl(this.
getFrom()));
61 signing.update(this.toString().getBytes()); 62 return
signing.verify(this.signature); 63 }
64
This method will be used by the other peers to verify that each
transaction is valid. Before explaining the code, let’s look at Figure 2-
2 and see what our method tries to accomplish.
31
Now let’s look back at our isVerified method and explain how the
workflow from the schematic is achieved. As parameters we are
getting the Transaction object that we want to verify and the
Signature helper class object, which pre-initialized to use SHA256
with DSA algorithm the same way as before. On line 60 we are
setting the public key with which we would like to decrypt our
signature. The new DSAPublicKeyImpl(byte[]
encoded) is just a wrapper from the sun.security.provider package
that will help convert our public key information from byte[] to
PublicKey object. On line 61 we set the transaction data that we want
to verify against the signature. Finally on line
Blockchaintransaction.java 62 we provide the signature, the process
of comparison/verification gets executed and a result is returned
automatically for us.
32
We finish up the rest of the class with generic getters, setters, and
our toString, equals, and hash methods, as shown in the following
snippet: 65 @Override
67 return "Transaction{" +
68 "from=" + Arrays.toString(from) +
73 '}';
74 }
75
II.
III.
IV.
V.
VI.
VII.
Good, to forgive;
Best, to forget!
Living, we fret;
Dying, we live.
Fretless and free,
Soul, clap thy pinion!
Earth have dominion,
Body, o’er thee!
II.
Wander at will,
Day after day,—
Wander away,
Wandering still—
Soul that canst soar!
Body may slumber:
Body shall cumber
Soul-flight no more
III.
This is the proem to “La Saisiaz,” one of the most remarkable of the
poet’s works, in which the doctrine of immortality is argued with a
profundity of thought that has perhaps never been surpassed, even
in language freed from the fetters of verse. It also appears as No.
III. of “Pisgah Sights” in the second English series of selections. Both
of these connections suggest the key-note.
Observe the progress in the thought. In the first stanza the soul is
“fretless and free”; in the second it moves onward and upward; in
the third it has reached the region of “Sunshine and Love, Sky-blue
and Spring!” Similarly as to the body—in the first stanza there is the
apparent victory of the grave, “dust to dust”; in the next comes the
thought that, after all, the body may only be slumbering; in the last,
there is the beautiful suggestion that it is only hiding where it is
tenderly cared for, till
“——with the morn those angel faces smile
Which we have loved long since, and lost awhile.”
TOUCH HIM NE’ER SO LIGHTLY.
Indeed?
Rock’s the song-soil rather, surface hard and bare:
Sun and dew their mildness, storm and frost their rage
Vainly both expend,—few flowers awaken there:
Quiet in its cleft broods—what the after age
Knows and names a pine, a nation’s heritage.
II.
III.
IV.
V.
VI.
VII.
VIII.
IX.
X.
XI.
XII.
XIII.
A PICTURE AT FANO.
I.
II.
III.
IV.
V.
VI.
VII.
VIII.
A GROUP BY WOOLNER.
II.
III.
And another would mount and march, like the excellent minion he
was,
Ay, another and yet another, one crowd but with many a crest,
Raising my rampired walls of gold as transparent as glass,
Eager to do and die, yield each his place to the rest:
For higher still and higher (as a runner tips with fire,
When a great illumination surprises a festal night—
Outlining round and round Rome’s dome from space to spire)
Up, the pinnacled glory reached, and the pride of my soul was in
sight.
IV.
V.
Nay more; for there wanted not who walked in the glare and glow,
Presences plain in the place; or, fresh from the Protoplast,
Furnished for ages to come, when a kindlier wind should blow,
Lured now to begin and live, in a house to their liking at last;
Or else the wonderful Dead who have passed through the body and
gone,
But were back once more to breathe in an old world worth their
new:
What never had been, was now; what was, as it shall be anon;
And what is,—shall I say, matched both? for I was made perfect
too.
VI.
VII.
But here is the finger of God, a flash of the will that can,
Existent behind all laws: that made them, and, lo, they are!
And I know not if, save in this, such gift be allowed to man,
That out of three sounds he frame, not a fourth sound, but a star.
Consider it well: each tone of our scale in itself is nought;
It is everywhere in the world—loud, soft, and all is said:
Give it to me to use! I mix it with two in my thought,
And, there! Ye have heard and seen: consider and bow the head!
VIII.
IX.
X.
All we have willed or hoped or dreamed of good, shall exist;
Not its semblance, but itself; no beauty, nor good, nor power
Whose voice has gone forth, but each survives for the melodist,
When eternity affirms the conception of an hour.
The high that proved too high, the heroic for earth too hard,
The passion that left the ground to lose itself in the sky,
Are music sent up to God by the lover and the bard;
Enough that he heard it once: we shall hear it by-and-by.
XI.
XII.