100% found this document useful (2 votes)
7 views

Introducing Blockchain with Java: Program, Implement, and Extend Blockchains with Java 1st Edition Spiro Buzharovski pdf download

The document introduces 'Introducing Blockchain with Java' by Spiro Buzharovski, which is aimed at individuals with basic Java and SQL knowledge, providing a comprehensive guide to understanding and implementing blockchain technology. It includes step-by-step instructions for creating a cryptocurrency and a user interface using JavaFX, along with supplemental materials available on GitHub. The book emphasizes a hands-on approach to learning, encouraging readers to actively engage with the code as they progress through the chapters.

Uploaded by

aynethnafkha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
7 views

Introducing Blockchain with Java: Program, Implement, and Extend Blockchains with Java 1st Edition Spiro Buzharovski pdf download

The document introduces 'Introducing Blockchain with Java' by Spiro Buzharovski, which is aimed at individuals with basic Java and SQL knowledge, providing a comprehensive guide to understanding and implementing blockchain technology. It includes step-by-step instructions for creating a cryptocurrency and a user interface using JavaFX, along with supplemental materials available on GitHub. The book emphasizes a hands-on approach to learning, encouraging readers to actively engage with the code as they progress through the chapters.

Uploaded by

aynethnafkha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

Introducing Blockchain with Java: Program,

Implement, and Extend Blockchains with Java 1st


Edition Spiro Buzharovski install download

https://ebookmeta.com/product/introducing-blockchain-with-java-
program-implement-and-extend-blockchains-with-java-1st-edition-
spiro-buzharovski/

Download more ebook from https://ebookmeta.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!

Introducing Blockchain with Java: Program, Implement,


and Extend Blockchains with Java 1st Edition Spiro
Buzharovski

https://ebookmeta.com/product/introducing-blockchain-with-java-
program-implement-and-extend-blockchains-with-java-1st-edition-
spiro-buzharovski/

Introducing Blockchain with Lisp: Implement and Extend


Blockchains with the Racket Language 1st Edition Boro
Sitnikovski

https://ebookmeta.com/product/introducing-blockchain-with-lisp-
implement-and-extend-blockchains-with-the-racket-language-1st-
edition-boro-sitnikovski/

Learn Java with Math 1st Edition Ron Dai

https://ebookmeta.com/product/learn-java-with-math-1st-edition-
ron-dai/

Humans in the Siberian Landscapes Ethnocultural


Dynamics and Interaction with Nature and Space 1st
Edition Vladimir N. Bocharnikov

https://ebookmeta.com/product/humans-in-the-siberian-landscapes-
ethnocultural-dynamics-and-interaction-with-nature-and-space-1st-
edition-vladimir-n-bocharnikov/
Thinking with Stephen J. Ball : Lines of Flight in
Education 1st Edition Maria Tamboukou

https://ebookmeta.com/product/thinking-with-stephen-j-ball-lines-
of-flight-in-education-1st-edition-maria-tamboukou/

Violence Against Women and Criminal Justice in Africa


Volume I Legislation Limitations and Culture 1st
Edition Emma Charlene Lubaale

https://ebookmeta.com/product/violence-against-women-and-
criminal-justice-in-africa-volume-i-legislation-limitations-and-
culture-1st-edition-emma-charlene-lubaale/

Advanced Optical and Wireless Communications Systems,


2nd Edition Ivan B. Djordjevic

https://ebookmeta.com/product/advanced-optical-and-wireless-
communications-systems-2nd-edition-ivan-b-djordjevic/

PTSD and Coping with Trauma Information for Teens Teen


Health Series 1st Edition Angela L. Williams

https://ebookmeta.com/product/ptsd-and-coping-with-trauma-
information-for-teens-teen-health-series-1st-edition-angela-l-
williams/

Heart Of A Wolf Crescent Pack 2 1st Edition Jennifer


Snyder

https://ebookmeta.com/product/heart-of-a-wolf-crescent-
pack-2-1st-edition-jennifer-snyder/
Capturing Christmas A Bratva Age Gap Captive Romance A
Filthy Dirty Christmas 1st Edition Jagger Cole

https://ebookmeta.com/product/capturing-christmas-a-bratva-age-
gap-captive-romance-a-filthy-dirty-christmas-1st-edition-jagger-
cole/
Spiro Buzharovski

Introducing Blockchain with Java


Program, Implement, and Extend Blockchains with
Java
Spiro Buzharovski
Skopje, North Macedonia

ISBN 978-1-4842-7926-7 e-ISBN 978-1-4842-7927-4


https://doi.org/10.1007/978-1-4842-7927-4

© Spiro Buzharovski 2022

This work is subject to copyright. All rights are solely and exclusively
licensed by the Publisher, whether the whole or part of the material is
concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in
any other physical way, and transmission or information storage and
retrieval, electronic adaptation, computer software, or by similar or
dissimilar methodology now known or hereafter developed.

The use of general descriptive names, registered names, trademarks,


service marks, etc. in this publication does not imply, even in the
absence of a specific statement, that such names are exempt from the
relevant protective laws and regulations and therefore free for general
use.

The publisher, the authors and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.

This Apress imprint is published by the registered company APress


Media, LLC part of Springer Nature.
The registered company address is: 1 New York Plaza, New York, NY
10004, U.S.A.
Dedicated to my friends.
Preface
This book is for anyone with at least entry-level knowledge of Java or a
similar OOP language, entry-level knowledge of FXML or HTML or
similar markup languages, and entry-level knowledge of SQL. The book
will provide a solid understanding of blockchains and a great portfolio
project for those seeking employment as a developer in the blockchain
space or other IT sectors. It is great for developers who want to learn
by doing.
Chapter 1 is an excerpt from Introducing Blockchain with Lisp:
Implement and Extend Blockchains with the Racket Language by Boro
Sitnikovski. I am most grateful to Boro for allowing me to reuse his first
chapter here. It explains the theoretical part with excellent clarity, and I
feel very fortunate to have it included in my book. The rest of the book
will offer a step-by-step guide of how to create your own crypto coin by
implementing Blockchain technology in Java. This book contains a
completely unique implementation of a blockchain in the Java language.
Also, it will teach you how to create a basic user interface using JavaFX
and how to implement an SQLite database using a JDBC driver for our
blockchain. These topics will greatly help in visualizing the final
product and provide you with a solid set of transferable technical skills.
The recommended approach for the book is to follow along with
each chapter and write the code as it’s being explained instead of
reading passively. This way you will get the most from this book. All of
the source code is available for download from
https://github.com/5pir3x/e-coin. You should look at this
book as a guide to the why and how of the codebase found in the
repository.
Feel free to contact me at [email protected] for
any questions you might have, and I will do my best to answer.
Finally, thank you for purchasing this book! I hope this book will
dispel a lot of the mysteries surrounding the blockchain and that it will
spark some more interest in Java and blockchain technology.
Any source code or other supplementary material referenced by the
author in this book is available to readers on GitHub
(https://github.com/Apress). For more detailed information, please
visit http://www.apress.com/source-code.
Table of Contents
Chapter 1:​Introduction to Blockchain
1.​1 Motivation and Basic Definitions
1.​2 Encryption
1.​2.​1 Functions
1.​2.​2 Symmetric-Key Algorithm
1.​2.​3 Asymmetric-Key Algorithm
1.​3 Hashing
1.​4 Smart Contracts
1.​5 Bitcoin
1.​6 Example Workflows
1.​7 Summary
Chapter 2:​Model:​Blockchain Core
2.​1 Block.​java
2.​2 Transaction.​java
2.​3 Wallet.​java
2.​4 Summary
Chapter 3:​Database Setup
3.​1 SQLite Database Browser Setup
3.​2 Blockchain.​db
3.​3 Wallet.​db
3.​4 JDBC Driver for SQLite Setup
3.​5 Writing Your App init( ) Method
3.​6 Summary
Chapter 4:​Building the UI
4.​1 Scene Builder Quick Setup
4.​2 Creating Your Views
4.​2.​1 MainWindow.​fxml
4.​2.​2 AddNewTransactio​nWindow.​fxml
4.​3 Creating Your View Controllers
4.​3.​1 MainWindowContro​ller
4.​3.​2 AddNewTransactio​nController
4.​4 Summary
Chapter 5:​Setting Up the Network and Multithreading
5.​1 UI Thread
5.​2 Mining Thread
5.​3 P2P Network Threads
5.​3.​1 PeerClient Thread
5.​3.​2 PeerServer Thread
5.​4 PeerRequestThrea​d
5.​5 Summary
Chapter 6:​Service Layer
6.​1 WalletData
6.​2 BlockchainData
6.​2.​1 Blockchain Consensus Protocol
6.​3 Summary
Chapter 7:​Extras
7.​1 Running the Application
7.​2 Topics for Future Improvements
7.​3 Conclusion
Index
About the Author
Spiro Buzharovski
is a full-stack software developer in the IT sector. He has a degree in
mechanical engineering and has worked as an engineer in the oil and
gas sector for more than six years. His interests include Java
frameworks, blockchain, and the latest high-tech trends. Inspiration for
this book came while working as a technical reviewer on an Apress
book by Boro Sitnikovski, Introducing Blockchain with Lisp: Implement
and Extend Blockchains with the Racket Language.
About the Technical Reviewer
Filip Tanurovski
is a senior software engineer with more than eight years of experience.
He has a degree in informatics and computer engineering. During the
first five years of his career, he primarily worked as a web developer
using the Java technology stack, although, lately, he has switched his
focus to other technologies like Node.js, Python, and Ruby, to name a
few. For two years, he was a course instructor for a five-week
introductory course to Java. He became passionate about writing clean
and maintainable code after reading the works of Robert Martin (Uncle
Bob). He is a highly motivated individual who is constantly looking for
ways to improve himself. In his spare time, he likes to spend time with
his wife, family, and friends, to travel, and train kickboxing.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer
Nature 2022
S. Buzharovski, Introducing Blockchain with Java
https://doi.org/10.1007/978-1-4842-7927-4_1

1. Introduction to Blockchain
Spiro Buzharovski1
(1) Skopje, North Macedonia

The entirety of this chapter is comprised of an excerpt from


Introducing Blockchain with Lisp: Implement and Extend
Blockchains with the Racket Language by Boro Sitnikovski, and it
is reused here with the author’s permission.
“Chained” by Filip Rizov
In this chapter, we will see some definitions and examples for
blockchain. We will see what properties a blockchain has, what it allows
us to do, and what it is good for.

Definition 1-1 Blockchain is a system in which a record of


transactions is maintained across several computers that are linked
in a peer-to-peer network.1

We will give an example that will serve as motivation, as well as define


what encryption and hashing techniques are and how they will help us
with our system.
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.

1.1 Motivation and Basic Definitions


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.

Figure 1-1 A ledger and a set of connected friends (peers)

Definition 1-2 A ledger is a book that contains a record of


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.
We want to design the system such that it functions similarly to a
regular bank account. A holder of a wallet (bank account) should be
able to only send money from their wallet to other wallets. Thus, every
person in the system will have a wallet of a kind, which can also be used
to determine the balance for them. Note that with the current setup
using a ledger, we have to go through all the existing records to
determine the balance of a specific wallet.
If we want to avoid going through all the existing records, there is a
way we can optimize this with unspent transaction outputs (UTXOs), as
we will see later in Chapter 3.
A problem that may arise is the double-spending problem , where
Bob can try to send all of his money to Alice and you at the same time,
thus effectively doubling the money he sends in relation to what he
owned. 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 digital signature is a way to verify the


authenticity of digital messages or documents.

For signing and verifying transactions we will rely on digital signatures


(Figure 1-2). For now, let’s assume that anyone who adds information
to the ledger also adds a signature with each record, and others have no
way to modify the signature, but only to verify it. We will cover the
technical details in the “Encryption” section.

Figure 1-2 Our ledger now contains signatures


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


more computers are connected to each other.

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.
In contrast, in a peer-to-peer network, which represents a
decentralized system, the distinction between a client and a server is
blurred. Every peer is both a client and a server at the same time.
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.
Figure 1-3 A decentralized ledger

Definition 1-5 A proof of work is data that is time-consuming


to calculate and easy for others to verify.

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.
In addition to all this, we want the transactions to have an order, so
every record will also contain a link to the previous record. This
represents the actual blockchain, depicted in Figure 1-4.
Figure 1-4 A chain of blocks: blockchain
If everybody agreed to use this ledger as a source of truth, there
would be no need to exchange physical money at all. Everybody can just
use the ledger to put in or retrieve money from it.
To understand the technical bits of digital signatures and proof of
work, we will be looking at encryption and hashing, respectively.
Fortunately for us, the programming language that we will be using has
built-in functionalities for encryption and hashing. We don’t have to dig
too deep into how hashing and encryption and decryption work, but a
basic understanding of them will be sufficient.
Observe how we started with a simple definition of a ledger and
gradually built up to a complex system. We will use the same approach
in programming.

1.2 Encryption
We will start with the following definition.

Definition 1-6 Encryption is a method of encoding values such


that only authorized people can view the original content.
Decryption is a method of decoding encrypted values.

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.
Before we talk about encryption, we first have to recall what
functions are, since the encoding/decoding values are achieved with
the usage of them.

1.2.1 Functions

Figure 1-5 A function

Definition 1-7 Functions are mathematical entities that assign


unique outputs to given inputs.

For example, you might have a function that accepts as input a person
and as output returns the person’s age or name. Another example is the
function f (x) = x + 1. There are many inputs this function can accept: 1,
2, 3.14. For example, when we input 2, it gives us an output of 3, since f
(2) = 2 + 1 = 3.
One simple way to think of functions is in the form of tables. For a
function f (x) accepting a single argument x, we have a two-column
table where the first column is the input, and the second column is the
output. For a function f (x, y) accepting two arguments x and y, we have
a three-column table where the first and second columns represent the
input, and the third column is the output. Thus, to display the function
discussed earlier in the form of a table, it would look like this:
x f (x)
1 2
2 3
… …
1.2.2 Symmetric-Key Algorithm
We can assume that there exist functions E(x) and D(x) for encryption
and decryption, respectively. We want these functions to have the
following properties:
E(x) ≠ x, meaning that the encrypted value should not be the
same as the original value
E(x) ≠ D(x), meaning that the encryption and decryption
functions produce different values
D(E(x)) = x, meaning that the decryption of an encrypted value
should return the original value
For example, let’s assume there’s some kind of an encryption
scheme, say E("Boro") = 426f726f. We can “safely” communicate
the value 426f726f without actually exposing our original value, and
only those who know the decryption scheme D(x) will be able to see
that D(426f726f) = "Boro".
Another example of encryption scheme is for E(x) to shift every
character in x forward, and for D(x) to shift every character in x
backward. 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".
However, the scheme described makes a symmetric algorithm
(Figure 1-6), meaning that we have to share the functions E and D with
the parties involved, and as such, they may be open to attacks.

Figure 1-6 Symmetric-key algorithm

1.2.3 Asymmetric-Key Algorithm


To solve the problems that arise with symmetric-key algorithms, we
will use what is called an asymmetric algorithm or public-key
cryptography (Figure 1-7). In this scheme, we have two kinds of keys:
public and private. We share the public key with the world and keep the
private one to ourselves.

Figure 1-7 Asymmetric-key algorithm

This algorithm scheme has a neat property where only the private
key can decode a message, and the public key can encode a message.
We have two functions that should have the same properties as
those for the symmetric-key algorithm.
E(x, p), which encrypts a message x given a public key p
D(x′ , s), which decrypts an encrypted message x′ given a
private (secret) key s
In our example, we will rely on the modulo operation. Recall that a
mod b represents the remainder when a is divided by b. For example, 4
mod 2 = 0 because there is no remainder when dividing 4 by 2;
however, 5 mod 2 = 1.
Here’s one example of a basic encryption algorithm based on
addition and modulo operations:
1. Pick one random number, for example 100. This will represent a
common, publicly available key.

2. Pick another random number in the range (1, 100), for example 97.
This will represent the private key s.

3. The public key p is obtained by subtracting the common key from


the private: 100 − 97 = 3.
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.

For example, suppose we want to encrypt 5. Then E(5, 3) = (5


+ 3) mod 100 = 8. To decrypt 8, we have D(8, 97) = (8 +
97) mod 100 = 105 mod 100 = 5.
This example uses a very simple generation pair of (x + y) mod
c. But, in practice, the pair generation algorithm is much more complex
and harder to break by attackers. After all, the complexity of the
algorithm’s computation is what makes it hard to break it.
We can use a similar algorithm for digital signatures:
S(x, s), which signs a message x given a private key s
(encryption)
V (x′ , sig, p), which verifies a signed message x′ , given
signature sig and public key p (decryption)
As we said earlier, each record will also include a special number (or
a hash). This hash will be what is produced by S(x, s) (encryption).
A hash can be verified by using the verify function to confirm a record’s
ownership (decryption).
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
Come up with a table of functions such that:
1. The input is a number, and the output is a number

2. The input is a number, and the output is the name of an


employee in a company given that number

EXERCISE 1-2
Check the three properties for a symmetric-key algorithm to ensure
the Caesar cipher is compatible with them.

EXERCISE 1-3
Come up with an encryption scheme, based on mathematical
substitution.

EXERCISE 1-4
Use the asymmetric-key algorithm we defined to sign a message and
verify it.

Hint This is similar to the encryption/decryption example shown


earlier.

1.3 Hashing

Definition 1-8 Hashing is a one-way function in that it


encodes text without a way to retrieve the original value.

Hashing is simpler than the previously described encryption schemes.


One example of a hashing function is to return the length of characters
as in H ("abc") = 3, but also H ("bcd") = 3. This means we
don’t have a way to retrieve the original value just by using the return
value 3.
As we mentioned earlier, the reason to use such a technique is that
it has some interesting properties, such as providing us with the proof
of work.

Definition 1-9 Mining is the process of validating transactions.


For this effort, successful miners obtain money as a reward.

Hashcash is one kind of a proof-of-work system.3 We will use it to


implement mining. We will see how this algorithm works in detail in
the later chapters where we will implement it.
Hashing functions have another useful property that allows
connecting two or more distinct blocks by having the information about
the current block’s hash (current hash) and previous block’s hash
(previous hash) in each block. For example, block-1 may have a hash
such as 123456, and block-2 may have a hash such as 345678. Now,
block-2’s previous-hash will be block-1’s current hash, that is, 123456.
Here, we linked these two blocks, thus effectively creating a linked list
of blocks containing ledgers with transactions. Figure 1-4 depicts this
linking.
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.
Two or more blocks (or transactions) that are connected form a
blockchain. The validity of the blockchain will depend on the validity of
each transaction.

EXERCISE 1-5
Come up with your own hashing function.

EXERCISE 1-6
In which way can the linked list depicted in Figure 1-4 be traversed?
What are the implications of this property?

1.4 Smart Contracts


Definition 1-10 A smart contract is a self-executing contract
with the conditions of an agreement between a buyer and a seller
being directly written into lines of code.

A blockchain is programmable if the transactions themselves can be


programmed by users. For example, users (not necessarily
programmers) can write a script to add additional requirements that
must be satisfied before sending money. It could look something like
this:

1 if (user has more than 10 money)


2 then approve transaction
3 else reject transaction

Smart contracts are implemented as a computation that takes place


on the blockchain.

1.5 Bitcoin
Bitcoin was the world’s first implementation of a blockchain. In
November 2008, a link to a paper authored by Satoshi Nakamoto titled
“Bitcoin: A Peer-to-Peer Electronic Cash System” was published on a
cryptography mailing list. Bitcoin’s white paper consists of nine pages;
however, it is a mostly theoretical explanation of the design and as such
may be a bit overwhelming to newcomers.
The Bitcoin software is open source code and was released in
January 2009 on SourceForge. The design of a Bitcoin includes a
decentralized network (peer-to-peer network), block (mining),
blockchain, transactions, and wallets, each of which we will look at in
detail in this book.
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.

1.6 Example Workflows


We will list a few important workflows that our system will use, among
others.
Mining a block creates a new block, using Hashcash to calculate the
current hash of the block. It also contains the previous hash that is a
link to the previous block in the blockchain.
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.
Adding a block to a blockchain consists of sending money from A to
B. One prerequisite is that A has enough money; we check this using the
wallet balance workflow. We proceed by creating a transaction (sender
= A, receiver = B) and signing it. Then we mine a block using this
transaction and update the UTXO with the rewards.

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.
Here’s what we learned in this chapter, briefly:
The core entity of the system is a block.
A block contains (among other data) transactions.
We have a ledger that is an ordered list of all valid blocks
(blockchain.)
Every peer involved with the ledger has a wallet.
Every record in the ledger is signed by the owner and can be verified
by the public (digital signatures).
The ledger is in a decentralized location; that is, everybody has a
copy of it.
Trust is based upon proof of work (mining).

Footnotes
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.

2 An ASCII table is a table that assigns a unique number to each character (such as !,
@, a, Z, etc.).

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.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer
Nature 2022
S. Buzharovski, Introducing Blockchain with Java
https://doi.org/10.1007/978-1-4842-7927-4_2

2. Model: Blockchain Core


Spiro Buzharovski1
(1) Skopje, North Macedonia
“Block” by Filip Rizov
Now that we have explained in theory what a blockchain is and how it is
useful, the next obvious step is to start implementing it in Java. In this
chapter, we will start by creating the model classes that represent the most
elementary building blocks for our application. You can either look at the
code snippets provided or download the complete repository from
https://github.com/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;
2
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

Next we move on to our class declaration and fields, as shown in our


next code snippet:

13 public class Block implements Serializable {


14
15 private byte[] prevHash;
16 private byte[] currHash;
17 private String timeStamp;
18 private byte[] minedBy;
19 private Integer ledgerId = 1;
20 private Integer miningPoints = 0;
21 private Double luck = 0.0;
22
23 private ArrayList<Transaction>
transactionLedger = new ArrayList<>();
The first thing we recognize on line 13 is that this class implements the
interface Serializable . Since all the blocks for our blockchain will be
created using this class, we need them to be serializable so that we can
share our blockchain through our network.
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. 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.”
In the following snippet, we can see the three constructors starting on
line 26, line 38, and line 45:

25 //This constructor is used when we retrieve it


from the db
26 public Block(byte[] prevHash, byte[] currHash,
String timeStamp, byte[] minedBy,Integer
ledgerId,
27 Integer miningPoints, Double luck,
ArrayList<Transaction>
transactionLedger) {
28 this.prevHash = prevHash;
29 this.currHash = currHash;
30 this.timeStamp = timeStamp;
31 this.minedBy = minedBy;
32 this.ledgerId = ledgerId;
33 this.transactionLedger =
transactionLedger;
34 this.miningPoints = miningPoints;
35 this.luck = luck;
36 }
37 //This constructor is used when we initiate it
after
retrieve.
38 public Block(LinkedList<Block>
currentBlockChain) {
39 Block lastBlock =
currentBlockChain.getLast();
40 prevHash = lastBlock.getCurrHash();
41 ledgerId = lastBlock.getLedgerId() + 1;
42 luck = Math.random() * 1000000;
43 }
44 //This constructor is used only for creating
the first block in the blockchain.
45 public Block() {
46 prevHash = new byte[]{0};
47 }
48
The first constructor is used when we retrieve our blockchain from the
database. Here we retrieve all the blocks completely finalized, and this
constructor helps us instantiate the block with all of the fields properly set
up. The second constructor is used while the application is running and is
used to create a completely new block (in other words, the head of the
blockchain) for us to work on. We will go over the details of how this is
achieved in Chapter 6. Our third constructor on line 45 will be used only
once by our init() method to create our first block.
Our next snippet showcases the isVerified method :
48
49 public Boolean isVerified(Signature signing)
50 throws InvalidKeyException,
SignatureException {
51 signing.initVerify(new
DSAPublicKeyImpl(this.minedBy));
52 signing.update(this.toString().getBytes());
53 return signing.verify(this.currHash);
54 }
55
We accept an object from the Signature class as a parameter. The
Signature class is actually a class from the java security package
java.security.Signature. It is a helper singleton class that allows us
to encrypt/decrypt data using different algorithms. On line 51 we initiate
the signing parameter by using the public key from the minedBy field of
this class. We will use this key to verify the data in this class against the
signature stored in the currHash. On line 52 we insert the data that we
want to verify, which in our case is the contents of the toString method.
On line 53 we return the Boolean result after verifying the data contained
in this class against its currHash.
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
57 public boolean equals(Object o) {
58 if (this == o) return true;
59 if (!(o instanceof Block)) return false;
60 Block block = (Block) o;
61 return Arrays.equals(getPrevHash(),
block.getPrevHash());
62 }
63
64 @Override
65 public int hashCode() {
66 return Arrays.hashCode(getPrevHash());
67 }
68
69 public byte[] getPrevHash() { return prevHash;
}
70 public byte[] getCurrHash() { return currHash;
}
71
72 public void setPrevHash(byte[] prevHash) {
this.prevHash = prevHash; }
73 public void setCurrHash(byte[] currHash) {
this.currHash = currHash; }
74
75 public ArrayList<Transaction>
getTransactionLedger() {
return transactionLedger; }
76 public void setTransactionLedger(
ArrayList<Transaction> transactionLedger)
{
77 this.transactionLedger =
transactionLedger;
78 }
79
80 public String getTimeStamp() { return
timeStamp; }
81 public void setMinedBy(byte[] minedBy) {
this.minedBy = minedBy; }
82
83 public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp; }
84
85 public byte[] getMinedBy() { return minedBy; }
86
87 public Integer getMiningPoints() { return
miningPoints; }
88 public void setMiningPoints(Integer
miningPoints) {
this.miningPoints = miningPoints; }
89 public Double getLuck() { return luck; }
90 public void setLuck(Double luck) { this.luck =
luck; }
91
92 public Integer getLedgerId() { return
ledgerId; }
93 public void setLedgerId(Integer ledgerId) {
this.ledgerId = ledgerId; }
94
95 @Override
96 public String toString() {
97 return "Block{" +
98 "prevHash=" +
Arrays.toString(prevHash) +
99 ", timeStamp='" + timeStamp + '\''
+
100 ", minedBy=" +
Arrays.toString(minedBy) +
101 ", ledgerId=" + ledgerId +
102 ", miningPoints=" + miningPoints +
103 ", luck=" + luck +
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 current hash/signature of the block is just the encrypted


version of the data contained in the block.
The miner’s private key is used to encrypt the block’s data, which
creates the signature.

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 we use the toString() method throughout this class


to prep our data conveniently for comparison.

Note how all of the essential fields that make certain the block is
unique are included in the toString() method.

2.2 Transaction.java
We briefly mentioned that we keep an array list of transactions in our
Block class in the previous section, and now it’s time to explain in detail
what our Transaction.java class contains. First we’ll start with the
imports found in the following code snippet:

1 package com.company.Model;
2
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

Next let’s go over the class declaration and its fields, as shown in the
next code snippet:
13 public class Transaction implements Serializable {
14
15 private byte[] from;
16 private String fromFX;
17 private byte[] to;
18 private String toFX;
19 private Integer value;
20 private String timestamp;
21 private byte[] signature;
22 private String signatureFX;
23 private Integer ledgerId;
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:

26 //Constructor for loading with existing


signature
27 public Transaction(byte[] from, byte[] to,
Integer value,
byte[] signature, Integer ledgerId,
28 String timeStamp) {
29 Base64.Encoder encoder = Base64.getEncoder();
30 this.from = from;
31 this.fromFX = encoder.encodeToString(from);
32 this.to = to;
33 this.toFX = encoder.encodeToString(to);
34 this.value = value;
35 this.signature = signature;
36 this.signatureFX =
encoder.encodeToString(signature);
37 this.ledgerId = ledgerId;
38 this.timestamp = timeStamp;
39 }
40 //Constructor for creating a new transaction and
signing it.
41 public Transaction (Wallet fromWallet, byte[]
toAddress,
Integer value, Integer ledgerId,
42 Signature signing) throws
InvalidKeyException,
SignatureException {
43 Base64.Encoder encoder = Base64.getEncoder();
44 this.from =
fromWallet.getPublicKey().getEncoded();
45 this.fromFX = encoder.encodeToString(
fromWallet.getPublicKey().getEncoded());
46 this.to = toAddress;
47 this.toFX =
encoder.encodeToString(toAddress);
48 this.value = value;
49 this.ledgerId = ledgerId;
50 this.timestamp =
LocalDateTime.now().toString();
51 signing.initSign(fromWallet.getPrivateKey());
52 String sr = this.toString();
53 signing.update(sr.getBytes());
54 this.signature = signing.sign();
55 this.signatureFX =
encoder.encodeToString(this.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 .
The second constructor is a bit more complex, so we will explain it in
more detail piece by piece. First let’s look at the constructor parameters
that are different: Wallet fromWallet and Signature signing. We
will explain the Wallet class in more detail in the next section, for now we
should just note that the fromWallet parameter contains the public and
private keys of the sender/maker of the transaction. We use the same
Signature class as in our Block isVerified method mentioned in
the previous section.
Next let’s explain the body of the constructor so we understand how
encrypting data works in our case. The signature creation phase shown in
Figure 2-1 offers an overview of what we are trying to accomplish.

Figure 2-1 Signature creation

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 we
are putting all the data we want to encrypt in a single String object by
using the toString() method . On line 53 we are feeding all the data we
want to encrypt to the signing object, and on line 54 we are actually
encrypting the data and assigning it to our signature field.
Next is our method for the verification of transactions, as shown in the
following snippet:

58 public Boolean isVerified(Signature signing)


59 throws InvalidKeyException,
SignatureException {
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.

Figure 2-2 Verification phase

The workflow of the schematic is quite simple; we need to compare the


hash of the signature and the hash of the data contained in our class using
the public key.
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.
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
66 public String toString() {
67 return "Transaction{" +
68 "from=" + Arrays.toString(from) +
69 ", to=" + Arrays.toString(to) +
70 ", value=" + value +
71 ", timeStamp= " + timestamp +
72 ", ledgerId=" + ledgerId +
73 '}';
74 }
75
76 public byte[] getFrom() { return from; }
77 public void setFrom(byte[] from) { this.from =
from; }
78
79 public byte[] getTo() { return to; }
80 public void setTo(byte[] to) { this.to = to; }
81
82 public Integer getValue() { return value; }
83 public void setValue(Integer value) {
this.value = value; }
84 public byte[] getSignature() { return
signature; }
85
86 public Integer getLedgerId() { return ledgerId;
}
87 public void setLedgerId(Integer ledgerId) {
this.ledgerId = ledgerId; }
88
89 public String getTimestamp() { return
timestamp; }
90
91 public String getFromFX() { return fromFX; }
92 public String getToFX() { return toFX; }
93 public String getSignatureFX() { return
signatureFX; }
94
95
96 @Override
97 public boolean equals(Object o) {
98 if (this == o) return true;
99 if (!(o instanceof Transaction)) return
false;
100 Transaction that = (Transaction) o;
101 return Arrays.equals(getSignature(),
that.getSignature());
102 }
103
104 @Override
105 public int hashCode() {
106 return Arrays.hashCode(getSignature());
107 }
108
109}

Important!

Note how we use the toString() method throughout this class


to prep our data conveniently for comparison.

Note how all the essential fields that make certain the transaction
is unique are included in the toString() method.

EXERCISE 2-1
If we fail to include a timestamp as part of the verification process in our
transaction object, can you think of a way to exploit this vulnerability?

2.3 Wallet.java
Let’s start as always with the imports for this class located in the following
snippet:

1 package com.company.Model;
2
3 import java.io.Serializable;
4 import java.security.*;
5

In the following snippet, observe the class declaration and fields:

6 public class Wallet implements Serializable {


7
8 private KeyPair keyPair;
9

Since we would like to be able to store and export/import our wallet


from/to a database, we will also implement the Serializable interface.
This class will contain a single field that will be an object of the KeyPair
class. This class is part of the java.security package and contains the
public key and private key that we mentioned in the previous sections.

Important!

Note how our blockchain wallet doesn’t require any information


regarding the wallet holder. This is the basis of the wallet holder’s
anonymity.

Our blockchain wallet also won’t contain any field containing the
current balance of the wallet. We will explain how we obtain our
wallet balance in Chapter 6.
Let’s look at our first two constructors on our next snippet, which will be
used when we want to create a new wallet and assign a new key pair to it:

10 //Constructors for generating new KeyPair


11 public Wallet() throws NoSuchAlgorithmException
{
12 this(2048,
KeyPairGenerator.getInstance("DSA"));
13 }
14 public Wallet(Integer keySize, KeyPairGenerator
keyPairGen) {
15 keyPairGen.initialize(keySize);
16 this.keyPair = keyPairGen.generateKeyPair();
17 }

The first no parameters constructor will call the second constructor


with a default keySize and a KeyPairGenerator instance set to
generate keys using the DSA algorithm. The second constructor receives
these input parameters either from the first or from other parts of the
application and simply sets the size of the keys on line 15 and generates the
keys themselves on line 16.
Our third constructor will be used to create our wallet once we have
imported an already existing key pair from our database. We can observe it
in the following snippet:

18
19 //Constructor for importing Keys only
20 public Wallet(PublicKey publicKey, PrivateKey
privateKey) {
21 this.keyPair = new
KeyPair(publicKey,privateKey);
22 }

The code here simply receives public and private key objects and
creates a new KeyPair object with them.
Finally, we finish up this class and chapter by including the generic
getters and setters in the following snippet:
23
24 public KeyPair getKeyPair() { return keyPair; }
25
26 public PublicKey getPublicKey() { return
keyPair.getPublic(); }
27 public PrivateKey getPrivateKey() {
return keyPair.getPrivate(); }
28}

2.4 Summary
In this chapter, we covered the creation of our model layer of the
application. These classes and their methods will be used as basic building
blocks throughout the rest of the application. Therefore, having nice grasp
of them now will greatly benefit you in understanding the more complex
logic in the upcoming chapters. This is a small recap of what concepts we
covered so far:
Representation of a single block of the blockchain by implementing our
Block.java class
Java implementation of importing blocks from an existing blockchain and
creation of the head block of the blockchain
Representation of a blockchain transaction by implementing our
Transaction.java class
Java implementation for importing transactions and creating new
transactions
Java implementation of encryption and verification (creating signatures
and verifying them)
Representation of a blockchain wallet by implementing our
Wallet.java class
Answer to Exercise 2-1: Someone can copy and paste a signed
transaction, and it will pass the validation checks since there is no way to
make sure the transaction is unique in time.
Other documents randomly have
different content
1 813 107
2 706 61
3 645 46
4 599 33
5 566 30
6 536 20
7 516 11
8 505 9
9 496 7
10 489 6
11 483 5
12 478 5
13 473 6
14 467 6
15 461 6
16 455 7
17 448 6
18 442 6
19 436 6
20 430 5
21 425 5
22 420 5
23 415 6
24 409 6
25 403 6
26 397 6
27 391 7
28 384 7
29 377 7
30 370 6
31 364 6
32 358 5
33 353 6
34 347 7
35 340 8
36 332 8
37 324 8
38 316 9
39 307 9
40 298 8
41 290 7
42 283 6
43 277 6
44 271 7
45 264 8
46 256 9
47 247 9
48 238 9
49 229 9
50 220 8
51 212 7
52 205 7
53 198 7
54 191 7
55 184 8
56 176 8
57 168 9
58 159 8
59 151 8
60 143 7
61 136 7
62 129 6
63 123 7
64 116 7
65 109 8
66 101 8
67 93 8
68 85 7
69 78 7
70 71 6
71 65 5
72 60 5
73 55 4
74 51 4
75 47 5
76 42 5
77 37 5
78 32 5
79 27 4
80 23 3
81 20 2
82 18 2
83 16 2
84 14 2
85 12 2
86 10 2
87 8 2
88 6 2
89 4 1
90 3 1
91 2 1
92 1 1

Shewing the Probabilities of Life at Berlin. Formed from the Bills


from Four Years, from 1752 to 1755. Given by Mr. Susmilch, in
his Gottliche Ordnung. Contains 134,000 Inhabitants. Half die
under Three Years of Age.
Ages. Persons living. Decr. of life.
0 1427 524
1 903 151
2 752 61
3 691 73
4 618 45
5 573 21
6 552 16
7 536 13
8 523 9
9 514 7
10 507 5
11 502 4
12 498 4
13 494 4
14 490 4
15 486 4
16 482 5
17 477 5
18 472 5
19 467 6
20 461 6
21 455 6
22 449 6
23 443 7
24 436 8
25 428 7
26 421 9
27 412 9
28 403 9
29 394 9
30 385 9
31 376 8
32 368 7
33 361 7
34 354 7
35 347 8
36 339 9
37 330 10
33 320 10
39 310 10
40 300 10
41 290 9
42 281 8
43 273 7
44 266 7
45 259 7
46 252 7
47 245 7
48 238 7
49 231 7
50 224 7
51 217 7
52 210 7
53 203 8
54 195 8
55 187 8
56 179 8
57 171 8
58 163 9
59 154 9
60 145 8
61 137 7
62 130 6
63 124 6
64 118 6
65 112 6
66 106 7
67 99 7
68 92 6
69 86 6
70 80 6
71 74 6
72 68 6
73 62 5
74 57 5
75 52 5
76 47 5
77 42 5
78 37 5
79 32 4
80 28 4
81 24 3
82 21 2
83 19 2
84 17 2
85 15 2
86 13 2
87 11 2
88 9 2
89 7 1
90 6 1
91 5 1
92 4 1

Dr. Short’s Table, from January 1st, 1728, to 1743; a Period of


Fifteen Years. Died by the London Bills, at all Ages, taken at an
Annual Medium, in the following Proportions.
Years of Age. Died.
Under ——— 2 9910
{2 to 5 2411
{5 ——— 10 980
{10 ——— 20 851
{20 ——— 30 2060
{30 ——— 40 2471
From {40 ——— 50 2510
{50 ——— 60 2231
{60 ——— 70 1675
{70 ——— 80 1200
{80 ——— 90 634
{90 ——— 100 117
———
Total Annual Medium of Deaths in this Period }—27,058

A Table of Thirty Years, taken from the London Bills, beginning with
1728, and ending with 1757; shewing the Total Number of
Deaths and Decrease in this Period, at every Age.
Years of Age. Died.
Under ——— 2 272903
{2 to 5 64745
{5 ——— 10 25912
{ 10 ——— 20 22891
{ 20 ——— 30 58474
{ 30 ——— 40 71502
From { 40 ——— 50 73258
{ 50 ——— 60 59872
{ 60 ——— 70 47269
{ 70 ——— 80 33679
{ 80 ——— 90 16948
{ 90 ——— 100 2496
{100 ——— 138 242
———
Total Deaths in this Period, at all Ages } 750,191

Shewing the Probabilities of Life in a Country Parish in Brandenburg.


Formed from the Bills for Fifty Years, from 1710 to 1759, as
given by Mr. Susmilch, in his Gottliche Ordnung. One Half born
lived to 25 Years of Age.

Ages. Persons living. Decr. of life.


0 1000 225
1 775 57
2 718 31
3 687 23
4 664 22
5 642 20
6 622 15
7 607 12
8 595 10
9 585 8
10 577 7
11 570 6
12 564 5
13 559 5
14 554 5
15 549 5
16 544 5
17 539 4
18 535 4
19 531 4
20 527 5
21 522 5
22 517 5
23 512 5
24 507 5
25 502 4
26 498 3
27 495 3
28 492 3
29 489 3
30 486 4
31 482 5
32 477 5
33 472 5
34 467 5
35 462 6
36 456 6
37 450 6
38 444 6
39 438 6
40 432 5
41 427 5
42 422 5
43 417 5
44 412 6
45 406 6
46 400 6
47 394 6
48 388 7
49 381 7
50 374 7
51 367 8
52 359 8
53 351 8
54 343 9
55 334 10
56 324 10
57 314 10
58 304 11
59 293 11
60 282 11
61 271 11
62 260 12
63 248 12
64 236 12
65 224 11
66 213 11
67 202 12
68 190 12
69 178 12
70 166 13
71 153 15
72 138 16
73 122 15
74 107 14
75 93 13
76 80 12
77 68 9
78 59 8
79 51 7
80 44 6
81 38 6
82 32 6
83 26 6
84 20 5
85 15 4
86 11 3
87 8 2
88 6 2
89 4 1
90 3 1
91 2 1
92 1 1

Shewing the Probabilities of Life in the Parish of Holy Cross, near


Shrewsbury, in England. Formed from a Register kept by the
Rev. Mr. Gorsuch for Twenty Years, from 1750 to 1770. One Half
born lived to 27 Years of Age.
Ages. Persons living. Decr. of life.
0 1000 189
1 811 49
2 762 45
3 717 35
4 682 23
5 659 23
6 636 18
7 618 14
8 604 9
9 595 6
10 589 4
11 585 4
12 581 4
13 577 4
14 573 4
15 569 4
16 565 5
17 560 5
18 555 5
19 550 5
20 545 6
21 539 7
22 532 7
23 525 7
24 518 6
25 512 6
26 506 5
27 501 5
28 496 5
29 491 5
30 486 5
31 481 5
32 476 5
33 471 5
34 466 6
35 460 6
36 454 7
37 447 7
38 440 7
39 433 7
40 426 8
41 418 8
42 410 9
43 401 8
44 393 7
45 386 7
46 379 7
47 372 7
48 365 6
49 359 6
50 353 6
51 347 7
52 340 7
53 333 7
54 326 8
55 318 8
56 310 9
57 301 9
58 292 9
59 283 10
60 273 10
61 263 10
62 253 10
63 243 10
64 233 10
65 223 10
66 213 10
67 203 10
68 193 11
69 182 11
70 171 10
71 161 10
72 151 9
73 142 8
74 134 8
75 126 7
76 119 7
77 112 7
78 105 7
79 98 8
80 90 9
81 81 10
82 71 10
83 61 10
84 51 10
85 41 9
86 32 8
87 24 7
88 17 6
89 11 4
90 7 2
91 5 1
92 4 1

Shewing the Probabilities of Life in the Country District of Vaud, in


Switzerland, from the Registers of Forty-three Parishes. Given by
Mr. Muret, in the First Part of the Bern Memoirs for the Year
1766. In this Country Province were 112,951 Inhabitants; and
one Half born lived to the Age of 41.
Ages. Persons living. Decr. of life.
0 1000 189
1 811 46
2 765 30
3 735 20
4 715 14
5 701 13
6 688 11
7 677 10
8 667 8
9 659 6
10 653 5
11 648 5
12 643 4
13 639 4
14 635 4
15 631 5
16 626 4
17 622 4
18 618 4
19 614 4
20 610 4
21 606 4
22 602 5
23 597 5
24 592 5
25 587 5
26 582 5
27 577 5
28 572 5
29 567 4
30 563 5
31 558 5
32 553 5
33 548 4
34 544 5
35 539 6
36 533 6
37 527 7
38 520 7
39 513 7
40 506 6
41 500 6
42 494 6
43 488 6
44 482 6
45 476 7
46 469 8
47 461 10
48 451 10
49 441 10
50 431 9
51 422 8
52 414 8
53 406 9
54 397 9
55 388 11
56 377 13
57 364 16
58 348 17
59 331 17
60 314 15
61 299 13
62 286 12
63 274 12
64 262 12
65 250 14
66 236 16
67 220 18
68 202 18
69 184 16
70 168 15
71 153 13
72 140 11
73 129 10
74 119 10
75 109 11
76 98 13
77 85 14
78 71 13
79 58 12
80 46 10
81 36 7
82 29 5
83 24 4
84 20 3
85 17 3
86 14 3
87 11 2
88 9 2
89 7 2
90 5 1

The two following Tables are taken from Dr. Price. I have however
omitted the fractions, for reasons which shall be explained when
treating of the inaccuracy of the public registers. The expectations of
life are here rated a few years inferior to the standard of most other
authors.
The probable Expectations or Prospects of Life in
Country Holy Cross, Pais de
Ages. London. Vienna. Berlin. parish of near Vaud, in
Brandenburg. Shrewsbury. Switzerland.
At
18 yrs. 17 yrs. 18 yrs. 33 yrs. 33 yrs. 37 yrs.
birth
Age 12 34 36 36 44 44 44
25 26 28 27 36 35 35
30 24 26 25 32 32 31
35 22 23 24 26 28 28
40 20 21 21 25 26 24
45 18 18 19 22 23 21
50 16 16 16 18 20 18
55 14 14 14 15 17 15
60 13 12 13 12 15 12
65 11 10 11 10 12 10
70 9 9 9 8 10 8
75 7 7 7 6 8 6
80 5 6 6 5 5 5
The Odds or Probability of living one Year in
Country Holy Cross, Pais de
Ages. London. Vienna. Berlin. parish of near Vaud, in
Brandenburg. Shrewsbury. Switzerland.
At
2 to 1 2 to 1 2 to 1 4 to 1 5 to 1 5 to 1
birth
Age 12 75 to 1 84 to 1 123 to 1 112 to 1 144 to 1 160 to 1
25 56 to 1 66 to 1 50 to 1 110 to 1 100 to 1 117 to 1
30 45 to 1 56 to 1 44 to 1 107 to 1 96 to 1 111 to 1
40 31 to 1 36 to 1 32 to 1 78 to 1 55 to 1 83 to 1
50 24 to 1 27 to 1 30 to 1 50 to 1 50 to 1 49 to 1
60 18 to 1 19 to 1 18 to 1 25 to 1 26 to 1 23 to 1
70 12 to 1 11 to 1 12 to 1 11 to 1 16 to 1 10 to 1
80 7 to 1 7 to 1 7 to 1 6 to 1 8 to 1 4 to 1
Having in the preceding part endeavoured to establish the mortality
of the human species at different ages, I am now to attempt a more
arduous task; to ascertain the mortality by different diseases. I
propose therefore, in imitation of the geographers, to spread out and
to review, in one general Chart, the enormous host of diseases which
disgorge their virulence over the earth, and, with frightful rapacity,
wage incessant hostilities with mankind. By this means, we shall, to
use a military phrase, reconnoitre more distinctly our enemies
arranged in hostile front; and be warned to make the best disposition
and preparation for defence where the greatest danger is
apprehended, and the most formidable assaults to be sustained.
Armed with diseases, the grim King of Terrors appears in the most
hideous aspect. Under all these predatory disguises and morbifick
forms, I shall track him grappling with mankind, and with his
tremendous scythe mowing down generations. The learned Sauvages
thus expresses himself: “Utinam numerus respectivus diversorum
morborum a nostratibus inquirarentur.” It is, in some measure, from
ignorance in this subject, that the streams of medical inquiries, of
academick rudiments, and of charitable donations to poverty in
disease, have not yet been pointedly directed to publick utility.
I could easily have exhibited tables of the Diseases and Casualties in
London during the greater part of the last century. But, compared to
its present magnitude, the British metropolis was then insignificant in
size: 23 new parishes have been since gradually added to the London
bills: there is also a chasm of 10 years in which the registers are lost.
Again, until 1665 and 6, London was infested with the plague; which
disease, previous to that date, seems to have been one primary
object of the registers: and to adopt Graunt and Short’s sentiments,
these records, from various political and religious obstacles, were
then very negligently managed. During the early part of this interval,
the kingdom was distracted with civil war; and after the great
pestilence in 1665, London must have required some years to recruit.
Besides, had I attempted to form tables for even the latter part of the
last century, the reader would have been fruitlesly embarrassed; and
such an attempt must ever prove abortive. For example, under one
and the same title, in the annual bills of mortality, are often
confounded flox, small pox, and measles: consumptions and tissick:
cancer, canker, and thrush: wolf, cancer, gangrene, and fistula:
cancer, gangrene, fistula, and mortification: gout and sciatica:
vapours and water in the head: quinsey and thrush: teeth and
worms: sores, ulcers, bruised and broken limbs: cough, cold, and
chincough, &c. These are a few specimens of Nosological absurdity in
the superintendents of the publick registers.
Notwithstanding this rabble of diseases in commenting upon the
London bills and diseases of the present century, I constantly refer
back, and contrast them with the bills of the last thirty years of the
preceding century; so that, as near as the imperfection of the
materials will admit, the mortality and diseases of 105 years in
London is presented at one view; and comprehends the various acute
and chronic diseases, by which about two million and a half of the
human species have been destroyed. The few authors who have
written on bills of mortality, have obscured their works in a cloud of
figures and calculation: the reader must have no small portion of
phlegm and resolution to follow them throughout with attention: they
often tax the memory and patience with a numerical superfluity, even
to a nuisance.
For the above, and many other reasons, I have compressed into one
chart, the London Diseases and Casualties of seventy-five years in
the present century: each disease and casualty arranged in a
progressive series of fifteen years mortality; in a fifth column is
added together the mortality of the preceding five divisions. During
this period, London has been more populous and stationary in
numbers: and by this means, the actual and comparative magnitude,
rise, and declension of different diseases, will be more conspicuous in
each period or interval: and by measuring the mortality with the
population, we are enabled, with certain precautions and exceptions,
to make the diseases and casualties of London serve as a morbid
barometer to the whole nation. The important reason which
determined me in forming an arrangement of fifteen years, in
preference to any other number or period, was, that the annual
havock by similar diseases and casualties, throughout this and the
neighbouring island, might be computed with some probability by
each fifteen years of the London bills; and thereby to elicite a new,
curious, and comprehensive proportion in medicine. For instance, if
we suppose the standing number, on an average, of the London
inhabitants at six hundred thousand; and the total inhabitants in
Britain and Ireland at nine million; and if the same diseases and
casualties were equally diffused and fatal to this whole community,
then, in such case, the London bills would serve as a scale or index of
mortality to both kingdoms: as many would die annually of every
disease and casualty throughout nine million, as are cut off in fifteen
years in London; for six hundred thousand multiplied by fifteen,
amounts to nine million.
But to supply the probable deficiency in the annual mortality of
London by different diseases and casualties, we must make an
addition to each of one third or fourth. To the mortality of Small-Pox,
in London, during fifteen years, and rated at thirty thousand, we
should add one third or fourth more to raise it to its just standard;
that is, to about thirty-eight thousand; which would be the annual
mortality amongst nine million in Britain and Ireland, supposing
small-pox equally universal, one time or other, and destructive. By
the same hypothesis, amongst two hundred million in Europe
Variolous mortality annually, would amount to four hundred
thousand; and, amongst eight hundred million; that is, the whole
human race would exceed three million annually. On this simple
principle, a gross estimate may be formed of the annual havock by
every other disease and casualty; taking the precaution, however, to
attend to the subsequent criticisms on the London bills.
Another curious corollary may be grounded on the above hypothesis;
which is, to form a probable conjecture of the numbers who are
annually Sick, or afflicted with different diseases. Example: if one of
every seven die of the Small Pox, and the variolous deaths
throughout Britain and Ireland are rated at thirty-eight thousand
annually, this number, multiplied by seven, amounts to two hundred
and sixty-six thousand annually, infected with variolous contagion.
Apply the same rule to Childbed mortality; rate the annual havock by
parturition in the two islands at four thousand: it will hereafter be
shewn, that in London one of seventy-four women die in childbed:
multiply therefore 4,000 by 74, the product is 296,000, which, in
reality, cannot be very distant from the total annual procreation in
both islands. And in these two examples, I have suggested what may
be termed an inverse proof of both propositions. From these tables
and commentaries, we are likewise furnished with a key to the
comparative mortality of each disease amongst a community:
whether its devastation is in the proportion of a fifth, tenth,
twentieth, or hundredth. Gentlemen who have not particularly
attended to the subject of morbid calculations (and very few of the
medical profession have) will, on better information, be astonished at
the flagrant errors daily committed by authors when treating of these
topicks. Out of the many examples which might be enumerated, I
shall merely select one in proof. Baron Dimsdale, in a Treatise on
Inoculation, dedicated to the present Empress of Russia, calculated
that, at least, two million were annually destroyed by Small Pox alone
in the Russian empire; and it was not until after the publication of my
Observations on his different Inoculating Essays, that this error and
others were erased.
I would request the reader’s particular attention to another
circumstance: which is, that on comparing the gradations of mortality
in the following chart, we are not to estimate the relative number,
frequency, or proportion of certain diseases, compared to others by
the absolute mortality of each. For instance, Apoplexy kills rather
more annually in London than Measles; but yet the latter disease is
infinitely more universal and diffused amongst the community, and
consequently less dangerous to life: Cancerous and Venereal cases
are widely different in the annual number afflicted with each,
although the deaths are not far distant from an equality. The same
observations will apply to Rheumatism, compared to the Dropsy, and
to many other diseases.
There are between eighty and ninety diseases and casualties
enumerated in the London bills, which, in the subsequent comments,
I have disentangled into their separate genera. But, to prevent the
possibility of aberration, after the chart of London diseases, I have
added a correct Medical Chart of all the principal diseases and
casualties with which mankind, in every part of the earth and ocean,
are afflicted or harrassed. This will operate as a check and correction
to the public registers; and by this, the defects and errors in the
London bills will be apparent; and it will serve as an index to our
future commentaries. But objections and difficulties occur in our
researches for collateral information and illustration from hospital
records. The reasons are glaring, why, in the latter, diseases should
be less fatal; and in this respect, cities should have the advantage of
the country. We cannot therefore apply hospital registers as a general
criterion to a nation. Whenever authentic and systematic records of
diseases, recovery, and mortality, are kept in hospitals, domestick as
well as military, and annually published, whatever may be alledged
respecting the importance and demerits of such institutions, the
community, at all events, will derive much useful information.

A CHART of all the Fatal Diseases and


Casualties in London, during 75 Years;
Beginning from 1701, and ending with 1776.
Collected from the London Bills of Mortality, and arranged into Five
separate progressive Periods of Fifteen Years each.
The Total Amount of the Five Periods, or Seventy-five Years Mortality,
is added together in the Sixth Column.
DISEASES AND Fifteen From From From From Total
CASUALTIES. Years, 1717 to 1732 to 1747 1762 Amount
from 1732. 1747. to to of
1701 1762. 1777. Seventy-
to five
1717. Years
Mortality,
from
1701 to
1777.
Ague 80 198 82 99 109 574
Fevers. Malignant,
Spotted, Scarlet,
and Purple 50,955 53,330 57,995 45,621 48,594 256,085

Small Pox 22,219 34,448 29,462 29,165 36,276 151,570


Measles 1,972 2,618 2,858 3,099 3,319 13,866
Quincy, Sore Throat 226 169 287 306 309 1,297
Pleurisy 384 602 811 407 321 3,525
Rheumatism 368 447 310 175 128 1,468
Gout 313 645 769 803 1,010 3,236

Consumption 42,541 49,680 66,009 61,749 68,949 288,928


Chin Cough,
Hooping Cough, 116 632 1,692 2,755 4,252 9,573
Cough
Asthma and Tissick 5,090 7,938 9,460 5,699 6,154 34,341
Apoplexy and
Suddenly 2,228 3,013 3,287 3,271 3,353 15,152
Palsy 332 550 621 1,021 1,020 3,544
Lethargy 105 126 116 105 74 526
Meagrims 13 10 — — — 23
Headach 21 32 6 18 — 77
Lunatick 412 513 777 1,126 1,048 3,876
Spleen and Vapours 53 52 20 — — 125
Rising of the Lights 1,219 1,239 197 30 10 2,074
Stoppage of the
Stomach 4,139 2,557 2,286 304 179 9,465
Vomiting and
820 682 248 134 120 2,004
Looseness
Cholic, Gripes, and
13,668 11,032 3,739 1,475 796 29,710
Twisting of the Guts
Flux 178 200 — 252 341 971
Bloody Flux 133 248 167 94 93 745
Worms 697 662 161 115 56 1,691
Jaundice 1,261 1,798 2,032 1,729 2,089 8,909
Gravel, Stone, and
789 868 700 421 429 3,205
Strangury
Diabetes 37 48 19 16 5 125
Dropsy and
Tympany 11,626 15,430 16,036 13,410 14,038 70,506
Livergrown 76 95 75 23 — 269

French Pox 917 1,372 1,663 997 1,016 5,965


Scurvy 63 28 14 59 42 226
Evil 1,020 519 426 197 198 2,360
Leprosy 19 53 69 39 15 1,915
Rash 77 128 47 59 24 341
Itch — — 42 31 11 84

Childbed 3,560 3,894 3,412 3,005 3,186 17,057


Abortion, and
8,746 10,231 8,793 8,820 10,241 46,831
Stillborn
Chrisoms and
850 315 606 — — 1,771
Infants
Miscarriage — — 47 56 49 152

Convulsions 91,660 114,718 111,966 85,196 89,221 492,761


Headmold-shot, and
609 2,374 2,013 1,022 337 6,355
Water in the Head
Teeth 18,478 25,199 20,274 13,978 11,918 89,847
Thrush 839 1,191 1,512 1,391 1,101 6,034
Scald Head 9 15 29 22 — 75
Rickets 3,916 1,383 954 112 104 6,569

Inflammation 8 67 698 894 1,394 3,061


Imposthume 790 694 387 191 84 2,130
St. Anthony’s Fire — 73 36 63 69 241
Gangrene and
1,071 2,857 3,362 3,083 3,023 13,438
Mortification
Canker 138 181 123 77 61 580
Cancer 1,041 1,059 774 682 719 2,475
Sores and Ulcers 695 485 402 253 236 2,071
Fistula 360 202 210 134 119 1,025
Bursten and
310 309 304 163 140 1,226
Ruptures
Swelling and Wen 6 — 47 49 37 139
Killed by Falls,
Bruises, Fractures,
and other Accidents 828 917 926 1,084 1,065 4,820
Self-Murder 445 667 693 555 509 2,869
Murdered 135 109 147 71 77 539
Stabbed, Killed,
15 32 13 — — 60
Wounded, Shot, &c.

Executed — — 495 495 1,020


Drowned 907 1,193 1,444 1,718 1,781 7,043
Burnt 90 54 90 127 132 493
Scalded 19 36 45 51 40 191
Stifled, Suffocated,
13 34 62 90 68 276
and Smothered
Overlaid 817 1,180 1,293 414 95 3,799
Found dead 388 557 668 336 133 2,082
Grief — 267 — 87 77 421
Frightened 8 14 8 13 2 45
Surfeits 685 131 59 31 27 933
Starved — 17 96 53 57 223
Excessive Drinking 19 267 678 189 69 1,222
Bleeding 87 69 57 70 114 397
Poisoned 2 7 7 24 10 40
Bit by Mad Dogs
— 3 14 15 6 38
and Cats

Bedridden — 104 — 56 105 265


Aged 27,341 34,708 30,058 25,109 22,032 139,248

A MEDICAL CATALOGUE of all the principal Diseases and Casualties


by which the Human Species are destroyed or annoyed.

Fevers. Intermittent, quotidian, tertian, quartan, species and varieties.


—— Remittent, Continued, and Eruptive; remittent, and the species,
nervous and putrid, miliary, inflammatory, small pox natural and
inoculated, measles, scarlet fever, some cutaneous eruptions,
mixed and anomalous fevers, plague, sweating sickness.
Fevers with topical inflammation of the brain, of the fauces, including
angina inflammatory and putrid, pleurisy, and peripneumony,
inflammations of the heart, diaphragm, liver, spleen, stomach,
intestines, kidneys and ureters, bladder, peritoneum, erysipelas,
acute and chronic rheumatism, regular and irregular gout.
Internal suppuration and gangrene.
Injured respiration and coughs, catarrh, pulmonary hæmorrhage,
pulmonary consumption, hectick, atrophy and tabes, asthma,
hooping cough, croup.
Natal hemorrhage, headach, nightmare, lethargy, vertigo, apoplexy,
epilepsy, fainting, resemblance of death from drowning, foul air,
&c. palpitation of the heart, internal polypus and aneurism,
tetanus and locked jaw, catalepsy, spasm, cramp, Saint Vitus’s

You might also like