Blockchain and Smart Contracts Design Thinking and Programming For
Blockchain and Smart Contracts Design Thinking and Programming For
Series Editor
David Lee Kuo Chuen (Singapore University of Social Sciences, Singapore)
Subject Editors
Guan Chong (Singapore University of Social Sciences, Singapore)
Ding Ding (Singapore University of Social Sciences, Singapore)
Published*
Vol. 1 AI & Quantum Computing for Finance & Insurance: Fortunes and
Challenges for China and America
by Paul Schulte and David Lee Kuo Chuen
For photocopying of material in this volume, please pay a copying fee through the Copyright Clearance
Center, Inc., 222 Rosewood Drive, Danvers, MA 01923, USA. In this case permission to photocopy
is not required from the publisher.
Printed in Singapore
v
b2530 International Strategic Relations and China’s National Security: World at the Crossroads
Preface
vii
December 24, 2020 14:18 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-fm page viii
viii Preface
Preface ix
x Preface
Dr. Xiao Feng, Chairman and CEO of Wanxiang Blockchain, giving a keynote
address at the Global Inclusive Blockchain Conference in 2018.
Ms. Hester Peirce, Commissioner of the U.S. Securities and Exchange Commis-
sion, delivering a keynote address at the SUSS Convergence Forum in 2019.
December 24, 2020 14:18 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-fm page xi
Preface xi
xii Preface
xiii
December 24, 2020 14:18 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-fm page xiv
xvii
December 24, 2020 14:18 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-fm page xviii
Acknowledgements
xxi
December 24, 2020 14:18 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-fm page xxii
xxii Acknowledgements
Contents
Preface vii
About the Authors xiii
About the Contributors xvii
Acknowledgements xxi
5. Cryptocurrency as an Alternative
Investment Class 155
xxiii
December 24, 2020 14:18 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-fm page xxiv
xxiv Contents
Index 351
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 1
Chapter 1
1.1 Introduction
In this chapter, we discuss the fundamentals of information security
and cryptography that undergird blockchain technology. Information
security and cryptography are highly intertwined fields of study.
Information security concerns the protection of data from unautho-
rised access or modification, while cryptography concerns the study
of mathematical techniques used to achieve information security
objectives when facing adversarial attacks.
We will begin by examining different objectives of information
security, and the concepts in modern cryptography that have evolved
to meet those objectives. We will then look at different cryptographic
techniques used to secure information in blockchain and financial
technology. These include hash function, digital signature, public
key infrastructure, encryption and privacy techniques. Throughout
our discussion, we will make references mainly to the Bitcoin
blockchain for application examples. We note that the usages of the
above cryptographic techniques in other blockchain are essentially to
achieve similar security objectives.
If we look up cryptography in the dictionary, a definition we are
likely to find is “the art of writing or solving codes”. This definition
accurately describes the historical evolution of classical cryptography
up until the 1970s and 1980s. Classical cryptography has been around
for millennia — the earliest known uses of codes have been recorded
1
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 2
1.2.1 Confidentiality
Confidentiality extends to both data confidentiality and user confi-
dentiality (also understood as user privacy):
1.2.2 Integrity
We cannot trust a message unless we know that its content has
been secured from the point that it leaves its origin to the point
that it reaches its destination. Data integrity is concerned with
ensuring that data are not tampered. Though often conflated with
confidentiality, integrity is a distinct objective. It is sometimes
assumed that encryption is sufficient to ensure data integrity, in the
sense that since encryption conceals the real content of a message,
the content cannot be modified in any meaningful way. This is a false
assumption as it is possible to manipulate a piece of encrypted data
in ways that simply invalidate its content. In this case, the recipient
has no idea if the encrypted data are received with errors or were
maliciously modified. We therefore need tools specific to integrity
protection to secure data from unauthorised modifications.
Integrity is achieved through the use of hash function, message
authentication codes and/or digital signature. Integrity is closely
associated with authentication and accountability — two security
objectives that have evolved above and beyond the traditional “CIA
triad”. It is important to be able to distinguish the subtle differences
among all three.
1.2.3 Availability
Data and online services are of no use if they are not available when
authorised users need them. Availability as a security objective is
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 5
1.2.4 Authentication
Authentication extends to both data authentication and user authen-
tication:
1.2.5 Accountability
Accountability aims to thwart a user from falsely denying that they
have sent or received a particular communication. It is analogous
with the concept of non-repudiation. Imagine that we have ensured
data integrity and authentication; that is, we have secured a piece of
data from tampering while in transit, and we have verified the origin
of the data. Accountability goes a step further by creating a digital
artefact that makes it impossible for the sender to deny having sent
the data. It draws an undeniable link between the data and the users
who have processed it, ensuring accountability for actions performed
on the data. This is achieved through the use of a digital signature.
With the rise of “deepfakes” and disinformation, and eroding public
trust in news media, ensuring accountability is increasingly becoming
a matter of social and political stability.
1.2.6 Attacks
Know thyself, know thy enemy, and in every battle you will be
victorious.
1.3 Cryptography
Earlier, we briefly discussed the idea of what is considered secure in
cryptography. We stated that cryptography is a suite of algorithms
based on the intractability of difficult problems that cannot be solved
in a reasonable amount of time. In this section, we will examine the
concept of security in cryptography in greater detail, and identify
the key properties of a secure cryptographic scheme.
c ← Enck (m)
c1 ← Enck (m1 )
c2 ← Enck (m2 )
1.4 Blockchain
The concept of a blockchain first appeared in 2008 in a white paper by
Bitcoin inventor Satoshi Nakamoto. In the paper, Nakamoto proposes
Bitcoin as a peer-to-peer payment system, and “a chain of blocks”
as the structure for recording Bitcoin transactions in an immutable
and transparent manner.
The idea of using digital currencies for decentralised peer-to-peer
payment is not new. However, before Bitcoin, it had never been
realised because without a trusted central authority (such as a bank)
to oversee transactions, there was no practical way to thwart three
possible acts by malicious users: spending without authorisation
(i.e., without ownership of the account), spending without having
enough balance and double-spending (i.e., sending the same amount
of digital currencies to more than one receiver without deduction in
the account balance).
Consider the banking system that we are familiar with. To
initiate a fund transfer, users first have to log in to their Internet
banking account. The act of logging in proves a user’s owner-
ship of the account. When the user requests a fund transfer,
this involves the bank checking, among others, if the user has
enough balance to perform the transaction. If so, the request
will be approved. Immediately after, the amount transferred will
be deducted from the balance, so double spending will not be
possible. If a user were to copy and resend the transaction confir-
mation, this would not result in multiple duplicate fund transfers
to the same receiver, because the bank would prohibit fraudulent
transactions.
At its introduction, Bitcoin blockchain was the first sound
design of an open and secure Distributed Ledger Technology (DLT )
that thwarts these three malicious acts without the need for a
central authority. DLT is a method of record-keeping whereby
every person involved in the record-keeping possesses a copy of
the ledger. Whenever a new record is created, it is updated in
each and every user’s ledger. DLT is straightforward to imple-
ment in a trusted setting, which assumes either a trusted central
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 11
h = Hash(m)
Hash functions have many uses, one of the most common being
the generation of hash tables for indexing data to enable efficient
data storage and retrieval. However, cryptographic hash functions
are different as they possess rigorous security definitions. Crypto-
graphic hash functions can be used for file integrity protection,
generation of one-time passwords and digital signature computa-
tion, to name a few. We are concerned only with the family of
cryptographic hash functions, and will use “cryptographic hash
function” and “hash function” interchangeably in the remainder
of this chapter. Some examples of hash functions are shown in
Figure 1.1.
You might have heard of a blockchain being described as an
immutable ledger. This immutability is a result of the use of
distributed ledger technology coupled with hash functions, which
do not allow any modification to a block and its transactions to
go undetected. Informally, a hash function possesses the properties
shown in Figure 1.2.
Figure 1.3: Number of pairs that can be formed out of four persons.
1
https://shattered.io/.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 16
Figure 1.5: An example of Merkle Hash Tree with data “P”, “Q”, “R” and “S”.
construction, where nodes at the bottom are called leaf nodes. Each
leaf node contains cryptographic hash of a piece of data and every
non-leaf node contains cryptographic hash of its children nodes. An
example is illustrated in Figure 1.5. Here, the data of each leaf node
are “P”, “Q”, “R” and “S”, respectively. Each leaf node thus contains
cryptographic hash of “P”, “Q”, “R” and “S”, i.e., hP , hQ , hR and
hS , respectively. The parent node (i.e., a non-leaf node) of “P” and
“Q” records the hash of hP and hQ , i.e., h2A = Hash(hP hQ ), where
“” denotes concatenation. Similarly, the parent node of “R” and
“S” records the hash of hR and hS , i.e., h2B = Hash(hR hS ). At this
juncture, we are left with only two nodes containing h2A and h2B ;
the parent of these nodes is called the Merkle Root and it records
Hash(h2A h2B ).
To take a closer look at how Merkle Hash Tree protects data
integrity, we notice how h2A is computed based on hP and hQ , how
h2B is computed based on hR and hS , and finally, how the Hash Root
is computed based on h2A and h2B . Consequently, any changes in
the data “P”, “Q”, “R” or “S” would always be reflected in the
Hash Root.
The construction of a Merkle Hash Tree allows efficient and secure
verification of data. If the Merkle Root, Hash Root, is published and
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 18
a lottery system among miners. Each miner can only vary the nonce,
recompute the block header hash and check if the block header
hash is valid. This effort constitutes proof of work. Each miner
has equal probability in finding a nonce that gives a valid block
header hash. When a valid block header hash is found, the miner
will broadcast the block in its entirety (referred to as “the solution”)
to the network. Other miners in the network will accept this block as
valid by checking that after hashing the solution, the resulting block
header hash satisfies the difficulty target. The value of a difficulty
target is part of the consensus rule globally accepted by miners in the
network.
To this end, we note that what constitutes a valid block header
hash is a hash value that satisfies the difficulty target. If the difficulty
target states that “A valid block header hash is one that starts with
at least four zeros in hexadecimal”, then, for a block Bi , any one of
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 21
• 00004a89fd89403a36e19c5d67ffcc9bba626cf8dc9a2109bcdbb2471
b952683
• 0000ed4bf83abd0f4b4ce53ed89fe59285f1016ccf85d738d0f6aa9924
e368d4
• 000002eb9ddb8b6d986196f3bf4a3958b2605e917e734c0d9e24d800
dc3cbb6b
• . . . and the list goes on.
In other words, for each element in Z∗N to have an inverse, the element
a ∈ Z∗N must satisfy gcd(a, N ) = 1. In fact, it turns out that for a
group Zp∗ , where p is a prime number, the set of group elements is
always {1, 2, . . . , p − 1}.
As an example, suppose N = 12. Recall that any number modulo
N will always result in a number between 0 (inclusive) and N , so we
start with Z12∗ = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}. Let us check each
in modular arithmetic, and this lays the basis of security for some
cryptographic schemes.
1.6.2 Scheme
A digital signature scheme comprises three algorithms:
(sk = d, pk = N, e ) ← KeyGen.RSA(1n )
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 29
Signing in RSA-PSS
S1. Given a message M , the signer performs a message encoding
process that takes as input M , padding1 , padding2 and salt:
a. Let M = padding1 |Hash(M )|salt
b. Let H = Hash(M )
c. Let DB = padding2 |salt
d. Using the mask generation function, transform H so that
|H| = |DB|
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 31
The resulting private and public keys are shown in Figures 1.11
and 1.12, respectively.
Figure 1.13 shows how we can sign using the RSA digital signature
scheme in Python. Here, the message is sent as input to the signing
algorithm in bytecode and the user’s private (signing) key is assumed
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 33
Figure 1.13: Python code for RSA digital signature signing algorithm.
Figure 1.14: The resulting RSA digital signature in bytecode (upper part) and
UTF-8 encoding (lower part).
different public key from the actual signer’s, the signature verification
will fail.
2
http://www.secg.org/sec2-v2.pdf.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 35
Verification
The counterpart of signature generation or computation is signature
verification. The receiver can easily verify the authenticity of the
message using the sender’s public key. Necessary inputs are the hash
value of the message, m, the public key P (corresponding to the
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 39
private key that is used to sign the message) and the signature s.
The verification process consists of the following steps3 :
1. To calculate the integer w = s−1 mod n.
2. To calculate the integer u1 = (m ∗ w) mod n.
3. To calculate the integer u2 = (r ∗ w) mod n.
4. To calculate point H = (u1 ∗ G + u2 ∗ P )mod n.
If the x-coordinate of point H equals r, the verification is successful
and the signature is in fact signed or computed using the private key,
meaning the message is authentic or valid. In a bitcoin transaction,
this means the sender is indeed the owner of the bitcoin amount.
The mathematic logic behind the verification ensures its validity
in the following way (Corbellini, 2015):
1. To replace the public key P with private key k from the previous
equation,
3
https://www.maximintegrated.com/en/design/technical-documents/tutorials/
5/5767.html.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 40
Alice, Bob, Charlie and Eve, and the flow of their fiat transactions
with each other is shown below.
to specify that she intends to pay Eve 4 btc, and pay herself 2 btc;
this is the concept of “change” in bitcoin (see Figure 1.20).
Notice a few things in the example above. First, a bitcoin
transaction can contain one or more inputs and one or more outputs.
Second, once a previous transaction (e.g., Alice-to-Bob) has been
recorded on the blockchain, it effectively transfers the ownership of
the 5 btc from Alice to Bob. Third, when Bob intends to spend the 5
btc he has gotten from Alice, he must specify the source of the 5 btc
in the “prev out” field and provide his proof of ownership of the 5 btc
by stating his public key and digital signature on this transaction.
In order for miners to validate whether Bob has ownership of the 5
btc, they will do the following checks:
1. Extract Bob’s public key from the “scriptSig” field in the Bob-to-
Charlie transaction.
2. Calculate the hash of Bob’s public key obtained in Step 1.
3. Find the transaction specified in the “prev out” field in the Bob-
to-Charlie transaction, i.e., the Alice-to-Bob transaction.
4. Verify that the hash calculated in Step 2 is equal to the recipient’s
public key hash specified in the “scriptPubKey” field of the Alice-
to-Bob transaction.
5. If they are equal, use the public key obtained in Step 1 to verify
Bob’s digital signature in the “scriptSig” field for the Bob-to-
Charlie transaction.
6. If verification succeeds, conclude that Bob has ownership of the
5 btc and thus can spend the 5 btc.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 45
The fourth point to note in this process is that Bob’s public key
is not disclosed until he creates the Bob-to-Charlie transaction and
announces his intention to spend the 5 btc in his wallet. The usage of
public key hash to specify the receiver utilises properties of the hash
function — an attacker could not pretend to be Bob because the
public key hash reveals nothing about the pre-image. Consequently,
only Bob can provide the correct public key that hashes to the public
key hash specified by Alice.
Finally, once the miners verified that the hash of Bob’s public key
is equal to the public key hash specified by Alice, the miners will use
Bob’s public key to verify his digital signature on the Bob-to-Charlie
transaction. When the verification succeeds, miners conclude that
Bob has ownership of the 5 btc in the wallet.
To this end, note the relationship between a user’s private key,
public key and wallet address. For security purposes, private keys
are truly random strings. From the private key, a user’s public key is
calculated using a one-way (irreversible) and predetermined manner.
The public key is then hashed and encoded to form the user’s bitcoin
wallet address. As such, the conclusion that “Bob has ownership
of the wallet containing the 5 btc if his digital signature on the
transaction can be verified using his public key” is based on the
fact that Bob can only provide the (correct) public key if and only if
he has the private key to create the digital signature. Consequently,
only Bob can give Alice the (correct) public key hash. The act of
specifying the receiver’s public key hash in a bitcoin transaction is a
mechanism called “Pay to Public Key Hash (P2PKH)”.
that by itself does not contain any identifiable information about its
owner.
This leaves a potential security loophole — how can a verifier
be sure that the public key belongs to the right signer? Without
a method of verification, an attacker could exploit this loophole
by intercepting the public key and replacing it with his own,
thereby compromising the objective of data authentication and
accountability in the digital signature. Therefore, there is a need
for us to ensure that a public key belongs to a specific user. Public
key infrastructure (PKI) solves this problem by providing a method
for associating a public key with a specific user in a secure manner.
As shown in Figure 1.21, the PKI framework comprises certificates,
certification authorities and certificate revocation.
A certificate is a digital document that serves as proof that
a particular public key belongs to a specific user (the subject).
A certificate contains the following information: version number,
serial number, type of digital signature scheme used, issuer’s name,
validity period, subject’s name, subject’s public key and issuer’s
signature. Aside from users, certificates can also state a website’s
information. A screenshot of Facebook’s certificate is shown in
Figure 1.22.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 47
4
https://www.mas.gov.sg/schemes-and-initiatives/project-ubin.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 49
1.9 Encryption
Encryption was an early component of classical cryptography and
continues to be an important part of modern cryptography, where it
is the means of achieving confidentiality. In this section, we will first
look at the concepts of perfect secrecy and computational secrecy,
and then discuss the distinctions between symmetric and asymmetric
encryption schemes.
Input Output
m k c
0 0 0
0 1 1
1 0 1
1 1 0
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 50
c=m⊕k
m 1 0 1 0 1 1 1 0 1 0
k 1 1 0 0 1 0 1 1 0 0
c 0 1 1 0 0 1 0 1 1 0
m =c⊕k
The receiver will use the same key k to compute the plaintext
m as
c 0 1 1 0 0 1 0 1 1 0
k 1 1 0 0 1 0 1 1 0 0
m 1 0 1 0 1 1 1 0 1 0
Figure 1.24: Vernam cipher decryption using the same secret key k used for
encryption.
Figure 1.26: Vernam cipher decryption using a different secret key k”.
k ← KeyGen.SE(1n )
m = L0 |R0
In each round of encryption, the DES round function swaps the right
and left sides, and applies a function fi (), also called a mangler
function, to one side. The mangler function uses a 48-bit subkey, also
called a round key, generated from a 56-bit master secret key. The
mangler function carries out four operations: expansion of the 32-bit
half-block to 48 bits; Exclusive-OR operation with the round key;
substitution using substitution boxes (S-boxes); and permutation.
Mathematically, we write this as
Li = Ri−1
Ri = Li−1 ⊕ fi (Ri−1 )
Ri−1 = Li
Li−1 = Ri ⊕ fi (Ri−1 )
Given A = B ⊕ C
A⊕C = B⊕C ⊕C = B⊕0 = B
B =A⊕C
Encryption Decryption
Input: m = L0 | R0 Input: c = L4 | R4
Output: c = L4 | R4 Output: m = L0 | R0
L0 R0 L0 = R1 ⊕f1(R0) R0 = L1
L1 = R0 R1 = L0 ⊕f1(R0) L1 = R2 ⊕f2(R1) R1 = L2
L2 = R1 R2 = L1 ⊕f2(R1) L2 = R3 ⊕f3(R2) R2 = L3
L3 = R2 R3 = L2 ⊕f3(R2) L3 = R4 ⊕f4(R3) R3 = L4
L4 = R3 R4 = L3 ⊕f4(R3) L4 R4
(as well as ransomware attacks) and Secure Sockets Layer (SSL) pro-
tocol for secure communication. As forms of symmetric encryption,
DES and AES can be used to encrypt large plaintexts efficiently and
possess shorter key lengths than asymmetric encryption. However,
the main drawback of symmetric encryption is that the sender and
receiver will need to share the secret key prior to any encryption.
To communicate with n number of peers, a user will also need n
number of secret keys. These inefficiencies can be addressed through
asymmetric encryption.
c ← Enc.AEpk (m)
m = Dec.AEsk (c)
(sk = d, pk = N, e ) ← KeyGen.RSA(1n )
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 60
Figure 1.30: Python code for hybrid encryption using RSA and AES.
Figure 1.31: The resulting ciphertexts from hybrid encryption using RSA and
AES.
Figure 1.32: Python code for hybrid decryption using RSA and AES.
1.10 Privacy
User privacy in a blockchain rests on the untraceability and unlink-
ability of transactions. To recap, untraceability means we should
be able to conceal the details of a transaction so that an observer
cannot follow the trail. Unlinkability, in general, means that two
events occurring under observation of an attacker should appear
unrelated to the observer. Earlier, we said that blockchain technology
is pseudonymous, as opposed to anonymous. By simply observing
the blockchain, there is no identifying information linked to the
wallet addresses or transactions. However, we are able to trace the
source of every transaction, and therefore, able to obtain a graphical
visualisation of transaction paths.Through prior knowledge or social
engineering, it is possible to link an identity to a wallet address. We
therefore need security schemes in place to protect user privacy.
Furthermore, suppose an attacker observes the following transac-
tion traces (Figure 1.33) at time t.
At time t+1, a new transaction as shown in Figure 1.34 takes
place.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 64
Figure 1.34: A new transaction that takes user inputs from three different
addresses may reveal user private information.
1.10.1 CoinJoin
CoinJoin is a trustless method that allows multiple bitcoin spenders
to come together and mix their input and output, so that observers
cannot easily trace how they are spending their bitcoin. Suppose
Alice has received 2 btc from Bob, which she now wants to spend.
But, Bob can easily track the 2 btc to see which addresses Alice pays
the amount to. For privacy, Alice decides to spend her 2 btc in a
CoinJoin transaction.
Alice finds at least one other user who agrees to spend the
common denomination of 2 btc. Among them, they identify a user
who will facilitate the transaction. They then provide their respective
input of 2 btc to the facilitator, as well as their respective public key
hashes specifying where their output should go. All the users then
sign the transaction and broadcast it to the network. This single
transaction spends the agreed common denomination of bitcoin from
each user at one go. Purely by observing the CoinJoin transaction,
other users, including Bob, will not be able to identify which
particular public key hash belongs to Alice. From that point onwards,
Bob will lose trace of Alice’s spending behaviour. In effect, CoinJoin
employs a mixing technique that gives users plausible deniability
regarding how they spend their bitcoin.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 66
5
https://bitcoinmagazine.com/articles/shuffling-coins-to-protect-privacy-and-f
ungibility-a-new-take-on-traditional-mixing-1465934826.
6
We use public key hash and wallet address interchangeably.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 67
R=r×G
Alice’s transaction:
R=r×G
XBob = Hash(r × P VBob ) × G + P SBob
...
Other info
Hash(pv × R ) × G + PS = X
Hash(pvBob × R) × G + PSBob
= Hash(pvBob × r × G) × G + PSBob
= Hash(r × PVBob ) × G + PSBob
= XBob
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch01 page 68
Thus, each time a user wants to send a new transaction, she will
choose a different r value, generating a unique stealth address. To an
observer, it will be computationally infeasible to work out which
addresses are meant for the same receiver, granting the receiver
untraceability.
However, suppose another user, Charlie, is also sending XMR to
Bob. On the blockchain, Alice’s and Charlie’s transactions to Bob
will not reveal that they are sending XMR to the same receiver.
But, if Alice and Charlie were to meet in real life and compare their
transaction details, it would be possible to deduce that both had
made transactions with Bob. To provide untraceability even in such
a scenario, Monero uses subaddresses. Bob can send different subad-
dresses to Alice and Charlie, which are not identifiable as belonging to
the same user. For more information about subaddresses, the reader
may refer to (SerHack and the Monero Community, 2018).
References
Corbellini, A. (2015). Elliptic Curve Cryptography: ECDH and ECDSA.
Retrieved from https://andrea.corbellini.name/2015/05/30/elliptic-curve-cr
yptography-ecdh-and-ecdsa/.
Electronic Coin Company. (2020). How it works | Zcash. Retrieved from Privacy
Protecting Digital Currencies | Zcash: https://z.cash/technology/.
Hopwood, D., Bowe, S., Hornby, T. and Wilcox, N. (2019). zips/protocol.pdf at
master. zcash/zips. Retrieved from GitHub: https://github.com/zcash/zips
/blob/master/protocol/protocol.pdf.
Khalique, A., Singh, K. and Sood, S. (2010). Implementation of Elliptic Curve
Digital Signature Algorithm, International Journal of Computer Applica-
tions, 2(2), 21–27.
Ostrom, E. (2015). Governing the Commons: The Evolution of Institutions for
Collective Actions (Canto Classics). Cambridge University Press.
Quisquater, J.-J., Quisquater, M., Quisquater, M., Quisquater, M., Guillou, L.,
Guillou, M.,... Guillou, S. (1989). How to Explain Zero-Knowledge Protocols
to Your Children. Advances in Cryptology — CRYPTO’ 89.
SerHack and the Monero Community (2018). Mastering Monero — The Future
of Private Transactions. LernoLibro LLC.
Stallings, W. (2017). Cryptography and Network Security: Principles and Practice,
(7th Global Edition). Pearson Education.
Sullivan, N. (2014). ECDSA: The Digital Signature Algorithm of a Better
Internet. Retrieved from https://blog.cloudflare.com/ecdsa-the-digital-sign
ature-algorithm-of-a-better-internet/.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch02 page 73
Chapter 2
73
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch02 page 74
• Proof-of-Work
• Block and transaction rules
Consensus Layer
• Difficulty
The data in the text file are then stored as a list in tx, with each
line as an element of the list (see Figure 2.4). To clean the transaction
data, we would like to store each row in different columns (similar to
Excel) and remove the line breaker “\n” at the end of each line. So,
we create a new list named tx list and leave it empty (“[]” refers to
a list). For each element t in tx, we delete the line breaker “\n” by
replacing it with an empty string. t.split will convert each line (t) in
transaction data (tx ) into different columns using the separator —
comma. Then, we store the separated line data in the list tx list with
each line as a list.
In the last line of Figure 2.4, we convert the list to dataframe
type by calling the pandas module, with the column names as “id”,
“content” and “tx fee” (here we use simplified transaction data;
the column names can be specified according to the data using
the following format). The transaction data are now well organised
with transaction id, transaction content and transaction fee data in
separate columns.
Next, with reference to Figure 2.5, we choose the transaction IDs
from the transaction data. The input() function allows users to use
the keyboard to key in data, which will be stored as strings. The
sentence in the parenthesis is what shows on the screen preceding
the cursor. The “\n” at the end of the line allows the user to key in
data in a new line. We can split the string input by space and get a
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch02 page 77
using the “for loop” (see Figure 2.5). The for loop and
tx data[tx data[‘id’] ==id] return only the rows in tx data where the
ID in tx data[‘id’] appears in the instr list (the list that stores the
transaction IDs selected). The print output will be the list of valid
transaction IDs selected and the corresponding transaction data.
Printing 30 equation symbols is just to make the layout nicer.
Then, we can have the transaction data imported and nicely
presented in Python. This is a demonstration of data files import and
data clean in Python. In the following sections, we will use a simple
four-transaction example to further elaborate the mining process.
2.4 Transaction
Before we proceed to deal with the transaction data in Python, let us
run through the information contained in a Bitcoin transaction and
how it works. As mentioned earlier, transaction data will be recorded
in the bitcoin blockchain. Like any other conventional transaction,
a bitcoin transaction needs information on the receiver, sender and
the amount of money. First, a sender needs to have a certain amount
of bitcoins to spend, and he can initiate a transaction by specifying
a bitcoin amount and a sender. This transaction will then go to a
transaction pool for miners to validate and be included in a block
with other transactions. The Bitcoin blockchain ensures that trans-
action data included in a block cannot be altered. How can it achieve
that? The answer is the bitcoin blockchain structure and information
included in the transaction. Whether the transaction data included in
a specific block have been tampered with can be easily verified using
the Merkle Hash Tree method in the cryptography. Understanding
transaction, transaction data and Merkle Hash Tree is important to
understand bitcoin mining and blockchain.
linked. In this way, it would be very effective and easy for miners to
verify whether the sender owns the bitcoins.
Furthermore, the receiver information, or the transaction output
in bitcoin, is different from conventional online transactions. In a
bank transfer, we can simply transfer the money to another account
with the rest remaining unchanged as long as the amount we are
trying to send is no more than the total amount available, while in
bitcoin, we need to include the bitcoins left as part of the transaction
output. For each transaction, if there are unspent bitcoins left, this
amount will be sent to the sender’s address again as an unspent
transaction output (UTXO), which refers to bitcoins from a previous
transaction that has not yet been spent (or unspent) and can be
the input of another transaction in the future (Figure 2.7). All
transaction inputs in bitcoin are UTXOs and can be linked to
previous transactions that indicate the source of unspent bitcoins.
In summary, a typical bitcoin transaction contains the following
information as shown in Figure 2.8:
and the output counter shows the number of outflows (where the
bitcoins go) with unspent amount transferred to the sender’s own
address.
2.6 Hash
Since there is a lot of information included in a transaction, bitcoin
adopts a more efficient way to incorporate the transaction data in
the mining while ensuring the integrity of the data at the same time.
Namely, the transaction information will then be taken into a hash
function and the generated hash value of the information will be used
as transaction ID that is used to identify the transaction. The hash
value of any input has the same length and any slight changes in the
input will cause the resulted hash value to be completely different
with no pattern. Such features of hash ensure that as long as we have
the same transaction ID, the data and information in a transaction
have not been tampered with.
What is hash and why is used in bitcoin transactions? Hash, or
hashing, refers to a function that takes data input of any length and
returns a value of fixed length (Sobti & Geetha, 2012). The value
returned by a hash function is also known as hashes, hash values, hash
codes or digests. We can create hashes of all kinds of digital content of
any length and form (e.g., numbers, letters, and symbols; documents,
images and music) and the output will be a value of fixed length, which
makes the calculation process neater and easier. The use of a hash
function can also easily suggest whether the transaction information
remains unchanged or not. This is because hashing the same input
will always generate the same hash values and any changes, even
the slightest, in the input will result in a totally different hash
value.
The hash function used in bitcoin is SHA-256, which returns a
fixed length of 256 bits (32 bytes). So, the transaction ID in bitcoin
would look like this:
B94d27b9934d3e08a52e52d7da7dabfac484efe37a5380
ee9088f7ace2efcde9
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch02 page 83
(or transaction data) with the same hash output (or hash values)
is extremely difficult with current computing power.
in the block header later. The above number for time is the Unix
epoch (or Unix time or POSIX time or Unix timestamp), which
is the number of seconds that have elapsed since January 1, 1970
(midnight UTC/GMT), not counting leap seconds (in ISO 8601:
1970-01-01T00:00:00Z). It is equivalent to 2019-07-07 08:08:08.
2.8 Mining
Mining refers to the process of finding a valid block to add to the
current blockchain and it follows certain rules or consensus rule,
which is Proof of Work (PoW) in bitcoin. Miners are the nodes
that do mining. Since there are no centralised parties like banks
or governments to control the issuance or validate the account
balance and transactions, the consensus rule, or PoW, is what the
bitcoin network relies on. The nodes in the bitcoin network reach
the consensus that a block is genuine through the block header’s
hash value — whether it satisfies a given condition or meets a given
target (Nguyen and Kim, 2018). Just like solving a math problem,
this condition is explicit and stated in the bitcoin protocol so that
everyone in the community must comply, which ensures trust among
the bitcoin community.
In Bitcoin’s Proof-of-Work mechanism, the blockchain that was
created with the greatest cumulative effort expended is the one
considered to be the latest and to which new blocks are attached.
That is to say, the longest blockchain in the system is the accepted
state of the bitcoin ledger as it requires the greatest effort to create.
Since the rest of the information included in the block header hash
value computation is more or less given, the most variable factor
is the nonce, so miners will keep trying different nonce values to
generate different hash values of the block header. That said, without
changing any other data in the block header (definitely not the
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch02 page 90
is the third and fourth digit in bits, so it is the second and third
element in the bits string since the number starts with 0 in a list and
bits[2:4] means the second and third in bits, which is 0x1e. bits[4:]
gets the 5th digit to the last digit in the bits value, which is 0x03a30c.
Then, we can calculate the target using the abovementioned formula.
While int(var) gives the integer of var in decimal, int(var, 16) tells
the program that this integer var is in hexadecimal.
The output will be as follows (see Figure 2.23). We can see that
the target in decimal is an extremely large number. It is much more
neatly expressed in hex strings, which is why hex strings are widely
used in the bitcoin blockchain. Without the zfill(64), the target would
be 000003a30c and the function fills the rest of the places so that the
final number is 64 digits.
the rest of the information into the header and start finding the
Golden Nonce in the mining process (see Figure 2.24).
The target value in bytes is stored in target byte for block mining
later (see Figure 2.25). We can also prepare the partial header using
the information we have now, including version, hash of previous
block header, Merkle Root that aggregates the transactions included
in this block and timestamp. struct.pack(“< L”, x) returns the input
x as little-endian ordered unsigned long value. As mentioned in the
transaction section, the endianness is a convention that determines
in which direction a sequence of bits is interpreted as a number: from
(Big-endian) left to right, or from (Little-endian) right to left. This
is to follow the rules in bitcoin network.
From the partial header (see Figure 2.25), we can see that among
the information included in a block header, all the rest of the data
are given and can be easily obtained except for the nonce. So, to
successfully mine a new block is equivalent to finding a correct nonce
that makes the hash value of the block header equal to or smaller
than the target. Any change to the block header input (such as the
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch02 page 95
time taken. We will show the nonce, hash of the block header and
the hash rate per second every 50,000 times the loop runs.
For every loop, we try a larger nonce value until the golden nonce
is found or nonce value reaches 4294967296 (can set to larger value
with smaller target). If the block header hash is smaller than the
target, the loop will be broken with a “Success!” message. The nonce
that satisfies the condition is the golden nonce.
This is an example of trying different nonce values to see if we
get a hash value that is smaller than the target given. Here, we start
with a small nonce and try a bigger nonce every time the loop runs.
Of course, it can be other methods to try out different nonce values,
such as to randomly select a nonce number in a range or to start
with a large number and try a smaller value in every round.
Once the target is met, miners can broadcast the new block
they find to the network. If recognised, more miners will use this
block as the latest block and calculate the hash value of the next
block to mine another new block. Successful miners can collect the
reward generated with the new block and the transaction fees via
the transactions included in and confirmed with the block. This
is the economic incentive for miners to keep the bitcoin network
running.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch02 page 98
References
Gordon, A. D. and Jeffrey, A. (2004). Types and effects for asymmetric
cryptographic protocols. Journal of Computer Security, 12(3–4), 435–483.
MacKenzie, D. (2019). Pick a nonce and try a hash. London Review of Books,
41(8), 35–38.
Merkle, R. C. (1980). Protocols for public key cryptosystems. In Proc. 1980
Symposium on Security and Privacy, IEEE Computer Society, (pp. 122–133).
Nakamoto, S. (2019). Bitcoin: A peer-to-peer electronic cash system. Manubot.
Nguyen, G. T. and Kim, K. (2018). A survey about consensus algorithms used in
blockchain. Journal of Information Processing Systems, 14(1), 101–128.
O’Dwyer, K. J. and Malone, D. (2014). Bitcoin mining and its energy footprint.
Conference working paper.
Sobti, R. and Geetha, G. (2012). Cryptographic hash functions: A review.
International Journal of Computer Science Issues (IJCSI), 9(2), 461.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch03 page 99
Chapter 3
3.1 Introduction
When a group arrive together at a decision and agree to support it,
the group would have achieved consensus among its members. The
decision is what is considered an acceptable resolution, a decision
that the group can support even if it is not the preferred option of
individuals in the group. A government election is one example of a
group coming together to make such a decision.
Consensus is an important concept for blockchain networks and
distributed ledgers as there is no central authority to provide the
source of truth. The network members have to arrive at a conclusion
about the state of the network by following some rules. These
rules are the consensus algorithms programmed into the blockchain
protocol. In Bitcoin, the consensus algorithm used is Proof of Work or
Bitcoin mining. Nodes on the Bitcoin blockchain can choose which
transactions to include into a block they are mining or validating.
They can also choose to ignore transactions that are broadcasted to
the network. When a block is mined, a majority of nodes on the
∗
Adjunct Senior Lecturer, National University of Singapore; Co Vice-Chairman,
Blockchain Association Singapore, Singapore.
99
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch03 page 100
A. All loyal generals will decide upon the same plan of action.
a. The loyal generals will all do what the set of rules says they
should, but the traitors may do anything they wish.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch03 page 103
A. All good nodes have to agree on the same plan of action (whether
a transaction is valid).
a. All good nodes will follow the rules set by the consensus
algorithm; check the ledger history to ensure that a transaction
is valid before putting on the ledger. Bad nodes can do what
they want such as work together to invalidate legitimate trans-
actions or validate double-spent transactions (by invalidating
the first transaction).
b. The consensus algorithm must guarantee A no matter what
the bad nodes do.
B. As long as the number of bad nodes is small enough, the good
nodes will not adopt an invalid transaction.
n ≥ 3m + 1,
Proof of Work
Proof of Work is the grandparent of trustless consensus in a
blockchain. PoW has been tried and tested since 2008 and is working
well. Bitcoin, Ethereum, Litecoin and Dodgecoin are some of the
cryptocurrency networks that have adopted PoW. Nodes on the
network can create blocks in the ledger when they participate in
PoW. PoW is competitive in nature as only one node can win the
mining reward for each block. The steps in PoW are as follows and
are described in Figure 3.3:
1. Receive new broadcasted transactions and check them against the
ledger to ensure that they are legitimate (sender has signed the
transaction and sender address has enough balance).
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch03 page 106
Proof of Stake
One of the first proposals as an alternative to address the issues with
PoW is Proof of Stake (PoS). One needs to have a stake (or hold some
coins) in the system to participate in PoS. In its simplest form, if you
own 5% of the total stake, your chance of mining the next block is
also 5%. In this way, not much computation (to solve a cryptography
puzzle) is needed. PoS is more energy efficient than PoW. PoS is also
competitive, only one staker can mine each block.
PoS is also not susceptible to economies of scale; a dollar is a
dollar. The chances of mining the block are the same for someone
with a hundred dollars’ worth of coins and a hundred persons with
a dollar each. Attacking a PoS is also more costly than PoW as you
will lose your stake if the network detects that you are malicious.
In PoW, you do not lose your coins or your mining hardware if you
launch a malicious attack.
However, the main issue in PoS is the “nothing at stake” problem.
In the event of a fork (where two miners create the next block at the
same time), PoW miners have to choose the block they wish to mine
on top of as their computing resources are limited. For a PoS miner,
there is nothing to lose if they stake on both forks. When a fork
occurs, the staker will have coins on both forks, allowing it to stake
on both sides. This leads to no resolution on what is the correct chain
(see Figure 3.4).
Different projects have made attempts at solving the “nothing
at stake” problem. Peercoin1 is one of the first cryptocurrencies
to use PoS. It used checkpoints which prevent a reorganisation of
the blockchain beyond the last known checkpoint. This was later
made optional as the blockchain network reached a suitable level of
1
https://docs.peercoin.net/#/proof-of-stake.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch03 page 108
2
https://nxtdocs.jelurida.com/Nxt Whitepaper#Nxt.E2.80.99s Proof of Stake
Model.
3
https://www.cardano.org/en/ouroboros/.
4
https://docs.ethhub.io/ethereum-roadmap/ethereum-2.0/proof-of-stake/.
5
https://eos.io/.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch03 page 109
Proof of Weight
Proof of Weight refers to a large class of consensus algorithms where
the chance of being chosen to validate or mine the next block is based
on a weighted score. This class of consensus usually aims to make it
more costly to lose the acquired weighted score, thus ensuring that
validators continue to be good. Proof of Weight is generally energy
efficient but incentive mechanism design is important, and it may be
hard to ensure that incentives are aligned to the outcomes. Proof of
Believability, Proof of Space and Proof of Importance are forms of
Proof of Weight.
Proof of Believability
Proof of Believability is used by IOST6 and utilises several factors
to compose a believability score. With Proof of Believability (PoB),
IOST aims to encourage decentralisation in the network. Central
to this is the reputation-based sub-token system called Servi. Servi
tokens serve as a measurement of a user’s contribution to the network
6
https://iost.io/.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch03 page 110
Proof of Space
Proof of Space (PoSpace) was first proposed by Dziembowski et al.
(2015). Also called Proof of Capacity (PoC), it dedicates a certain
amount of disk space in order to participate in validating a block.
It is similar to PoW as the miner needs to provide a mathematical
proof to demonstrate that the resources (computational power or
disk space) have been committed. This is implemented through the
use of hard-to-pebble graphs. The prover needs to build labelling
of a hard-to-pebble graph and commit to the labelling. To verify
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch03 page 111
Proof of Importance
Proof of Importance (PoI) is the consensus algorithm adopted by
NEM.7 It pays out to members participating in PoI based on their
importance which depends on various factors, such as notoriety
(based on purpose-designed framework), balance and the number
of transactions made to and from that position. This “importance”
calculation aims to measure the “helpfulness” of a network member.
Similar to PoS, to be eligible to participate in PoI, a network
member needs to have a minimum stake of coins (10,000 XEM).
Importance is calculated using a specific algorithm and determines
the chance one will win the PoI reward. It aims to be a fairer system
where anyone who contributes to the network gets to be rewarded.
Due to its construct, PoI is also resistant to arbitrary manipulation,
Sybil and loop attacks.
Proof of Burn
In Proof of Burn, you “burn” your coins by sending them to an
address where they are irretrievable. In exchange, you earn a privilege
to mine on the system based on a random selection process. In most
implementations, you “burn” cryptocurrency from an alternative
chain such as Bitcoin. The more you burn, the higher the chance
of being selected to mine the next block. Over time, this probability
declines, so you will need to keep burning more coins to retain the
same chance. Although the network itself does not exhaust much
energy to run Proof of Burn, the cryptocurrencies required to be
burnt also expand resources. This method also does not address the
7
https://docs.nem.io/ja/gen-info/what-is-poi.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch03 page 112
Proof of Authority
In Proof of Authority (PoA), validation is done by approved accounts
called validators. The validators validate the transactions and blocks
that are recorded on the blockchain. Validators run software that
automates this process and need not constantly monitor their
computers. However, the validators do need to ensure that their
computers are not compromised or attacked. The general conditions
to approve a node as a validator are as follows:
Proof of Reputation
Proof of Reputation (PoR) is similar to PoA; it depends on the
reputation of the participants to keep the network secure. A validator
risks financial or brand consequences if they attempt to be malicious.
Thus, the validator also needs to have a reputation important enough
such that the consequences are costly. To be admitted into the
network, a potential validator needs to pass verification and prove
their reputation. Existing validators may vote on the eligibility of the
new entrant or a weighted matrix may be used to decide. Other than
the method of choosing the validator, PoR operates like PoA once the
validators are admitted into the network. Due to its similar nature
to PoA, PoR is also more suitable for trusted and permissioned
blockchains. GoChain8 uses Proof of Reputation.
8
https://gochain.io/proof-of-reputation/.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch03 page 114
• The first node to wake up (with the shortest waiting time) gets to
mine the next block and commit it to the blockchain network.
• The same process repeats for the next block.
The PoET network consensus mechanism needs to ensure two
important factors:
• First, participating nodes must be given a waiting time that is
indeed random and not a shorter duration chosen purposely by
the participants in order to win.
• Second, the winner must complete the waiting time.
To achieve this, Intel utilises their SGX technology to execute
trusted code in a protected environment. This prevents any attempt
to alter the code and also ensures that the results are verifiable by
external parties. PoET is used by the Hyperledger Sawtooth project
which is led by Intel.
RAFT
RAFT9 is named after Reliable, Replicated, Redundant, and Fault-
Tolerant. RAFT is not Byzantine fault tolerant and is usually used
in permissioned networks. It is a way to ensure each node in the
network agrees upon the same transactions. It arrives at consensus
via an elected leader. Nodes in a RAFT network can be leader or
a follower. A follower can also be a candidate in the case that the
leader becomes unavailable. The leader replicates the ledger to the
followers. The followers know that the leader exists from a heartbeat
message sent by the leader. If no heartbeat is received in a stipulated
amount of time, the follower switches to a candidate and initiates a
leader election. RAFT is used in Quorum and in later versions of
Hyperledger Fabric.
9
http://thesecretlivesofdata.com/raft/.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch03 page 116
10
https://komodoplatform.com/security-delayed-proof-of-work-dpow/.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch03 page 117
Tangle
Tangle11 is the DAG consensus algorithm used by IOTA.12 Tangle
adopts a pay-it-forward type of consensus. In order to send a
transaction, one needs to validate two previous transactions. As more
transactions are added to the network, the validity of the transactions
is strengthened. Technically, if one has the ability to generate one-
third of the transactions on the network, it would be able to convince
the rest of the network that its invalid transactions are valid. Thus,
transaction volume needs to be large enough for it to be infeasible
to do so. IOTA has implemented a centralised node called “The
Coordinator” to double check all of the network’s transactions and
will remove it once the network is large enough.
Hashgraph
Hashgraph is a gossip protocol consensus developed by Baird (2016).
Known transactions are shared with other nodes at random such
that all transactions are eventually gossiped to every node. Hedera
Hashgraph13 is a public blockchain network that combines the hash-
graph gossip protocol with a Proof-of-Stake consensus and promises
a transaction rate of 10,000 transactions per second. Hashgraph
consensus protocol has also been implemented in permissioned
distributed ledgers.
SPECTRE
Serialisation of Proof-of-work Events: Confirming Transactions via
Recursive Elections or SPECTRE (Zohar, 2016) is a proposal to
scale Bitcoin that combines PoW and DAGs. Each block mined
in SPECTRE points to multiple parents such that the network
can support multiple blocks at the same time. SPECTRE is not
implemented yet in reality, but can be an interesting solution to
scaling cryptocurrency networks.
11
https://blog.iota.org/the-tangle-an-illustrated-introduction-4d5eae6fe8d4.
12
https://www.iota.org/.
13
https://www.hedera.com/.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch03 page 119
3.4 Conclusion
Consensus algorithms are an important part of ensuring consistency
and accuracy on a blockchain or distributed ledger. Developing an
understanding of how the types of consensus algorithms work would
give us an appreciation of blockchain-based applications, assets and
investments, and allow us to make informed decisions. Ultimately,
the choice of consensus depends on what the network implementer
wants to achieve. It could be for a decentralised public system which
needs to be self-governing or an enterprise consortium blockchain
which needs to handle sensitive transactions.
The area of consensus algorithms is still evolving as we learn
more about how network participants react to different incentives
(especially for cryptocurrencies). With a variety of use cases emerging
for blockchain, we would expect as much variety in the type of
consensus used. With the multitude of blockchain solutions, any
blockchain network may also be required to communicate with
several others; interoperability will become a key consideration.
References
Baird, L. (2016). The swirlds hashgraph consensus algorithm: Fair, fast, byzantine
fault tolerance. Swirlds, Inc. Technical Report SWIRLDS-TR-2016, 1.
Dziembowski, S., Faust, S., Kolmogorov, V., and Pietrzak, K. (2015). Proofs
of space. In Annual Cryptology Conference (pp. 585–605). Springer, Berlin,
Heidelberg.
Lamport, L., Shostak, R., and Pease, M. (2019). The Byzantine generals problem.
In Concurrency: The Works of Leslie Lamport (pp. 203–226).
Patel, R. (2020). Byzantine Fault Tolerance (BFT) and its significance
in Blockchain world. HCLTech. Retrieved from https://www.hcltech.
com/blogs/byzantine-fault-tolerance-bft-and-its-significance-blockchain-wor
ld#:∼:text=Byzantine%20fault%20tolerance%20is%2050,as%20network%20
latency%20approaches%20infinity.
Zilliqa (2017). The Zilliqa Design Story Piece by Piece: Part 2 (Consensus
Protocol). Retrieved from https://blog.zilliqa.com/the-zilliqa-design-story-
piece-by-piece-part-2-consensus-protocol-e38f6bf566e3.
Zohar, A. (2016). SPECTRE: Serialization of Proof-of-Work Events, Confirming
Transactions via Recursive Elections. Retrieved from https://medium.com/
@avivzohar/the-spectre-protocol-7dbbebb707b5.
b2530 International Strategic Relations and China’s National Security: World at the Crossroads
Chapter 4
4.1 Introduction
DeFi, or Decentralised Finance, has been viewed as the future of
finance. Bitcoin and the underlying blockchain technology have made
a decentralised, distributed and open system feasible. Bitcoin proto-
col, the very first form of crypto-token network with mass adoption,
has provided a potential solution to the lack of trust problem in
the traditional and centralised business world. The token economy
is an alternative to the centralised third-party trust economy. The
underlying financial instruments that drive the decentralised token
economy are crypto-tokens. What exactly is a crypto-token, and what
drives the value of these crypto-tokens?
Digital assets, currencies or tokens that use cryptography tech-
nology are called crypto-tokens. Cryptocurrency is a form of crypto-
token that possesses the monetary circulation property and value
measurement function. They can be used as a payment tool, just
like a currency. Other crypto-tokens without such features are called
non-currencies or non-payment tokens. A crypto-token is not only a
digitised representation of an object but it is also a cryptography-
generated trust carrier formed with consensus by a group of par-
ticipants in the peer-to-peer network. Goods and services, time and
anything of value can be tokenised. The tokenised objects or tokens
can be easily traded, and the value increases with the ability to
exchange for other objects with value.
121
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch04 page 122
1
https://en.wikipedia.org/wiki/Token economy.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch04 page 123
2
https://www.wisegeek.com/what-is-a-token-economy.htm.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch04 page 124
Processed
Digitalised Digitalised Digitalised
information
Information
No Some Yes
transparency
Type Detail
Utility Utility tokens facilitate transactions, and sometimes mean the ability
to use the platform itself
Operation Token is a determinant of important decisions related to operations
in the ecosystem
Profit Token holders get a portion of revenues or profits, like shares of a
company in some sense
Asset-backed Asset-backed tokens are linked to real-world or virtual assets such
as gold, fiat currency or property
and the latter uses only one token. Although a simple architecture
can be successful and have various use cases, there are concerns.
In the case of a single token, if people use it to exchange goods
or services in the platform or pay the transaction fees so that they
can access the platform, the value of the tokens will increase. On
one hand, it is desirable for the ecosystem because people would
have the incentive to join the network, own the tokens and pursue
good behaviours. On the other hand, some token holders, such as
investors and speculators who buy or earn the token, not for its utility
or function but the potential price increase, may sell the tokens in
exchange for profits. This speculative behaviour will cause the price
of tokens to drop, thus increasing the price volatility and destabilising
the financial utility of the token economy.
Therefore, the dual architecture offers a solution to the problem
where two tokens with different roles are introduced in the network.
This is to segregate the tokens into different functions and mitigate
the effect on the value of tokens. Under this scheme, two tokens
are performing different tasks. One example is the payment/utility
token that acts as a transaction fee to facilitate transactions and
gain platform access or resembles “currencies” that can be exchanged
for goods or services. Another token may function like security for
the store of value or collateral that can be exchanged with other
tokens (Brouwer, 2018). There is no reason to stop at two, and design
thinking is the key to solving whatever problems at hand. In the end,
the final design must address the pain points to have value acting for
payment, utility, security or other functions.
Figure 4.10 shows the main factors to consider when making
architecture decisions.
Successful token economics should incentivise not only desirable
behaviour but also be able to stabilise the network operation. In
contrast, inappropriate token economics may lead to a death spiral if
there is a perceived loss of value in the token economy. The following
shows both good and bad examples of token economics.
3
https://www.emerald.com/insight/content/doi/10.1108/JABES-12-2018-0107
/full/html.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch04 page 137
4
https://fas.org/sgp/crs/misc/R45427.pdf.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch04 page 138
with a relatively stable level of value over the years. The value of
gold may be due to gold’s naturally limited supply, which provides
gold with the ability to have intrinsic value that does not diminish
over time.
Cryptocurrencies often have finite supplies by design, such as in
the case of Bitcoin, where computer codes predetermined the upper
boundary of 21 million bitcoins. Hence, in terms of capping of supply,
Bitcoin may be akin to gold and it probably fulfils SOV in theory.
It was not surprising that bitcoin was a follow-through from bitgold
proposed by Nick Szabo (2005).5
The fair value of cryptocurrencies could be derived by calculating
the fair value of the price of the currency with SOV, by assuming that
the cryptocurrency would ultimately replace gold as the go-to store
of value for investors (Leilacher, 2019). For example, the value of
bitcoin could be derived by factoring the value of global gold bullion
and the ultimate number of bitcoins in circulation.
Total Global Gold Value
Value of bitcoin =
Total number of Bitcoin
$8 trillion
$380, 000 per bitcoin =
21 million BTC
There is no reason why cryptocurrencies cannot replace a portion of
the commodity market. In that case, one can add to the denominator
by the number of potential cryptocurrencies that will be liquid as
well as just taking a percentage of the commodity market that will
be replaced.
Total Global Commodity Value
Value of a token =
Total number of liquid tokens
$20 trillion ∗ 0.2
$x per token =
y billion tokens
5
https://nakamotoinstitute.org/bit-gold/.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch04 page 139
d. Token velocity
Wang (2014) proposes the token velocity theory to derive a value of
Bitcoins according to the fundamental macroeconomic equation of
exchange: M V = P Q. Specifically, P (price) was set to 1, resulting
in M being the total market capitalisation of the crypto asset, while
Q was defined as the amount of value that is transferred across the
network. V remains as the velocity. Substituting M by the market
capitalisation gives us the following equation:
Q
pb =
nb V
6
Wang (2014) assumed that velocity is proportional to the amount of bitcoins
that are saved and transacted, the likelihood of bitcoin saved being ls and the
likelihood of bitcoin transacted being lt . As such, the velocity for bitcoins saved
and spent is expressed as vs and vt , respectively. Another assumption made by
Wang (2014) was that the velocity of bitcoin transacted is significantly larger than
the velocity of bitcoin saved, vt vs , resulting in the value of vs being equal to 0.
The final assumption then states that velocity can be expressed as a linear
function of Q : V = lt ∗vt ∗ Q.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch04 page 141
As time advances, CUV and DEUV will take turns to drive the
price of cryptocurrency. This process works in this manner. Initially,
during the launch of the cryptocurrency asset, anticipation drives up
DEUV, causing it to be higher in relative percentage terms to CUV.
As time progresses, the initial anticipation dies down, while the cryp-
tocurrency asset delivers its true value. During this time, CUV will
be in a higher relative percentage to DEUV. Eventually, the market
cycle would be reached where both the CUV and the DEUV are
expanding. This process allows us to model and estimate the value of
a cryptocurrency asset to that of its maturity in a product life cycle.
It is worth highlighting that various factors, such as the velocity,
size of asset base, discount rate, adoption rate and supply of tokens,
are key considerations when factoring in the model for the utility
token INET (Burniske, 2017). As such, previous critics against
velocity still stand for the INET model.
f. Network value to transaction (NVT) ratio
The NVT is a valuation metric that attempts to study the rela-
tionship between the price of a cryptocurrency and its fundamentals
(Leilacher, 2019). NVT is very similar to the Price Earning (P/E)
ratio, which is typically used in traditional finance. The P/E ratio
provides a measuring stick for comparing if a stock is over or
undervalued at any point in time (Elmerraji, 2020), by comparing
the valuation of a company to their actual earnings.
While cryptocurrency does not have any earnings (some do have
yields from mining or staking) for measurement, one could argue
that a suitable fundamental proxy could be derived by assessing
the transaction volume of the particular cryptocurrency (Kalichkin,
2018). The principle behind NVT operates similarly as outlined in
the following formula:
network value
NVT =
daily transaction volume
Therefore, a high NVT for a cryptocurrency would suggest that
the cryptocurrency might be overvalued, hinting that the network
could be entering a bubble, or simply that the network is experiencing
a high growth phase.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch04 page 142
g. Metcalfe’s Law
demand (or when price bubbles appear), either the market price
will fall and/or the mining difficulty will increase to resolve the
discrepancy (Lee and Teo, 2020).
From a broader scale, the popularity of cryptocurrencies (or
investor attention), cryptocurrency market sentiment and factors
related to the associated blockchain networks such as incentives,
social scalability, consensus, utility and governance influence the
price of the tokens. There is no doubt that token valuation methods
will evolve with new designs beyond the income from mining, staking,
hedging against loss of trust, option for future payments, etc. Many
of the modified quantitative ideas from traditional finance will be
applicable with some ingenious twist and understanding of the
philosophy underlying the blockchain community. Below are some
qualitative methods that are compatible with scoring and ranking
valuation methods.
b. 3Cs
The 3Cs describe characteristics of an environment (geological or
institutional) that are ideal nurturing grounds for successful fintech
companies, and by extension, cryptocurrencies.
Community
The concept of clustering in economics describes how companies who
that in the same industry tend to gather together in geographical con-
centrations. This increases the general productivity of the industry
as a whole as it fosters productive competition among the industry
peers. Similarly, a strong community has a high tolerance for failure
and encourages innovative thinking which is extremely important for
a technology company or product like cryptocurrency to succeed.
Compassion
Another factor that spurs innovations in technologies is their com-
passion to failure. The mindset of people within these communities
is that failure is not the end of the world but rather a valuable lesson
for the next attempt. Such a mindset is important in the world of
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch04 page 146
Compliance Easy
Finally, providing services or products that are compliance easy
will minimise the risk of regulating bodies restricting their use and
jeopardising the prospects for a fintech startup. Changes in the
regulatory environment and compliance process may have major
influences on the costs of fintech companies and thus affect their
profitability and value.
d. 6Ds
Encompassing Interest of All and Beneficial to All. The idea was first
mentioned by Shen (2015).
Open
Openness refers to how open a project or company is. For example,
if the source code is open and publicly available, like Python and
Bitcoin, it becomes easier for developers to implement the codes,
build additional layers on it, revise it and develop it. Stakeholders
such as users and investors can also be more assured about the design
and function of the network.
Altruistic
The founding team and managing team of fintech companies should
also be altruistic. If they think only about themselves, it is difficult
to see if the stakeholders’ interests will be valued in the long run,
thus limiting the value of the firms.
Global
As mentioned earlier, the user base plays an important role in any
business’s success, more so for fintech companies. Digital services or
products that typical fintech companies provide do not have many
geographical restrictions as traditional ones, making going global an
easier target to achieve. The security and reliability of the system
depend on the number of people that use it, and the more, the
better. Hence, fintech companies should consider catering to a global
audience instead of merely focusing on their local jurisdiction.
Crowdsourcing Wisdom
Crowdsourcing wisdom will utilise the wisdom of the crowd or the
network. A little breakthrough from multiple sources will result in a
huge breakthrough when brought together.
Crowdsourcing Contribution
Similar to the above, a decentralised cryptocurrency can crowdsource
contributions to attain supercomputers like processing speeds and
power. Mesh technology, for example can lower average costs if more
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch04 page 150
4.5 Conclusion
To better understand the value of a token, the overall ecosystem and
underlying blockchain design thinking cannot be neglected. From
a business perspective, we can look at the governance, economic
incentives and scalability dimensions to continuously distribute trust
and increase the cost of hacking. Looking at one project or company
is not enough, as out of 100, 95 may just be loss ladders to build the
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch04 page 151
maximising the value for all. Also, the value of the tokens and stocks
shall not compete with each other, but supplement each other to
increase the values of both. In fact, shares that define voting rights
can be now tokenised as a governance token. How this can be achieved
is what we should focus on in the future and experiment in DeFi, also
known as decentralised finance, distributed finance or simply as open
finance.7
References
Aguilar, F. J. (1967). Scanning the Business Environment. Macmillan.
Alabi, K. (2017). Digital blockchain networks appear to be following Metcalfe’s
Law. Electronic Commerce Research and Applications, 24, 23–29.
Brouwer, A. J. (2018). The dual token structure thesis. Retrieved from https://
blog.goodaudience.com/the-dual-token-structure-thesis-c3a43ef54537.
Burniske, C. (2017). The crypto J-curve. Medium. Retrieved from https://mediu
m.com/@cburniske/the-crypto-j-curvebe5fdddafa26.
Cong, L. W., Li, Y., and Wang, N. (2020). Tokenomics: Dynamic adoption and
valuation (No. w27222). National Bureau of Economic Research.
Denault, J. F. (2018). The handbook of marketing strategy for life science
companies: Formulating the roadmap you need to navigate the market.
Routledge.
Elmerraji, J. (2020). 5 Must-Have metrics for value investors. Investopedia.
Retrieved from https://www.investopedia.com/articles/fundamental-analys
is/09/five-must-have-metrics-value-investors.asp.
Graham, A. (2017). TAM methodology: An explanation and example of total
addressable market analysis. Toptal. Retrieved from https://www.toptal.co
m/finance/market-sizing/total-addressable-market-example.
Hayes, A. (2016). Decentralised banking: Monetary technocracy in the digital age.
In Banking Beyond Banks and Money (pp. 121–131). Springer, Cham.
Hayes, A. S. (2019). Bitcoin price and its marginal cost of production: Support
for a fundamental value. Applied Economics Letters, 26(7).
He, H. (2018). The Death of FCoin: A tale of bad token design. Retrieved
from https://hackernoon.com/the-death-of-fcoin-a-tale-of-bad-token-desig
n-261d64a8116f.
Hlebiv, O. (2018). What Is Token Economics. Retrieved from https://applicatur
e.com/blog/blockchain-startups/what-is-token-economics.
Jain, N. (2019). How to Value a Fintech Startup. Retrieved from https://www.t
optal.com/finance/valuation/how-to-value-a-fintech-startup.
7
https://fintechnews.sg/37725/blockchain/how-defi-is-building-a-new-financial
-system/.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch04 page 153
Chapter 5
Cryptocurrency as an Alternative
Investment Class
Jointly written with Guo Li∗
5.1 Introduction
The surge of Bitcoin’s price and emerging applications of blockchain
technology had prompted heated discussions over cryptocurrencies.
Over 1,000 cryptocurrencies had been launched until early 2018,
and that number has gone up to over 7,000 during the past two
years, according to CoinGecko.com (see Figure 5.1). Hundreds of
billions worth of total market capitalisation (see Figure 5.2) indeed
poses great investment opportunities for investors, with one third, or
around US$90 billion, consisting of altcoins (cryptocurrencies other
than bitcoin; see Figure 5.3).
In a nutshell, the cryptocurrency market has the following
features: (i) attracting a large amount of funds, (ii) increasing number
of altcoins and (iii) altcoins playing an increasingly important role.
However, constructing an investment portfolio using cryptocurrencies
and how it performs compared to the mainstream asset classes
such as stocks, bonds and other alternatives (e.g., commodities and
REITs) are under-examined. Investing in cryptocurrencies means
∗
Assistant Professor, Fudan University; Academic Researcher, Shanghai Institute
of International Finance and Economics, Shanghai, People’s Republic of China.
155
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch05 page 156
5.2 Data
We collect cryptocurrency data from CoinGecko.com and data for
other traditional asset classes from Bloomberg. The whole sample
period spans from August 2014 to March 2017. Here, we use CRIX
(CRypto IndeX1 ) as a proxy for cryptocurrency market performance,
like S&P 500 for the stock market. It was established as early as
2014 and incorporated various numbers of constituents that can best
reflect the whole cryptocurrency markets based on both liquidity and
market value rules (Trimborn and Härdle, 2018). For the analysis, we
included the top ten cryptocurrencies that had been included most
frequently in the CRIX index, shown in Figure 5.4.
For the traditional assets, we include S&P 500, Gold, S&P GSCI
Commodity Index, Oil futures, private equity and REITs. If we plot
the cumulative returns of CRIX and traditional asset class, we can
1
https://thecrix.de/.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch05 page 158
see that the return of the CRIX index had increased a lot from
2015 to 2017, much higher when compared to the rest of the asset
classes (Figure 5.5). But, it seemed much more volatile than the
others in the meantime.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch05 page 159
Static Correlation
CRIX BTC XRP LTC DASH DOGE XMR BTS MAID NXT BCN
S&P 500 0.036 0.038 0.22 0.013 0.102 −0.001 0.084 0.044 0.058 0.057 0.044
T-Note −0.02 0.017 −0.01 0.006 −0.013 −0.037 −0.011 −0.04 0.058 −0.072 −0.035
Gold 0.036 0.069 −0.064 0.045 0.045 0.01 −0.053 0.02 0.018 0.041 0.047
Oil −0.065 −0.075 −0.006 −0.076 −0.03 −0.094 0.032 0.005 0.009 −0.021 −0.025
GSCI 0.015 0.03 0.004 0.031 0.043 0.029 −0.01 −0.033 0.028 0.003 −0.015
REITs −0.014 0.004 0.003 0.043 −0.025 −0.016 −0.045 −0.058 0.011 −0.036 −0.052
PE −0.037 −0.007 −0.02 −0.029 −0.039 −0.017 −0.02 −0.094 0.024 −0.079 −0.012
5.5 Conclusion
The cryptocurrency market has large investment potentials as it
brings many new investment opportunities. We have thousands
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch05 page 169
References
Berkman, H., Koch, P. D., Tuttle, L., and Zhang, Y. J. (2012). Paying attention:
Overnight returns and the hidden cost of buying at the open. Journal of
Financial and Quantitative Analysis, 47(4), 715–741.
Chen, S., Chen, C., Härdle, W. K., Lee, T. M., and Ong, B. (2016). A first
econometric analysis of the CRIX family. Working Paper.
Engle, R. (2002). Dynamic conditional correlation: A simple class of multivariate
generalized autoregressive conditional heteroskedasticity models. Journal of
Business & Economic Statistics, 20(3), 339–350.
Lee, D. K. C., Guo, L., and Wang, Y. (2017). Cryptocurrency: A new investment
opportunity? Journal of Alternative Investments, 20(3), 16–40.
Trimborn, S. and Härdle, W. K. (2018). CRIX an Index for cryptocurrencies.
Journal of Empirical Finance, 49, 107–122.
b2530 International Strategic Relations and China’s National Security: World at the Crossroads
Chapter 6
Ernie Teo∗
∗
Adjunct Senior Lecturer, National University of Singapore; Co Vice-Chairman,
Blockchain Association Singapore, Singapore.
171
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch06 page 172
1
https://cointelegraph.com/news/ethereum-classic-51-attack-the-reality-of-pro
of-of-work.
2
https://bravenewcoin.com/insights/etc-51-attack-what-happened-and-how-it-
was-stopped.
3
https://www.gate.io/article/16735.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch06 page 174
Four of them were created by the attacker and in total 54,200 ETC
was transferred. Gate.io further corroborated Coinbase’s findings
that the attack was not just an innocent deep-chain reorganisation.4
Revealing the attacker’s wallet addresses as well as other informa-
tion pertinent to the malicious transactions, Gate.io also explained
the attack had resulted in losses amounting to US$40,000 for the
exchange. However, the exchange said it would not pass on the
losses to its users. It also raised the confirmation number for
ETC transactions and called on the ETC developers to change the
consensus mechanism for the blockchain in order to avoid another
attack. Following the Gate.io revelation, more exchanges began to
either limit ETC trading activity on their platforms or increase the
confirmation limit. Some of these include CoinCheck and Bitflyer as
well as the mining pool Etherchain. Concurrently, ETC developers
finally confirmed the presence of a 51% attack, referencing a report
that a single party had been able to acquire over 50% of the network’s
hashrate.
On January 9, SlowMist published a report with in-depth analysis
of the attack.5 The firm found that the first attempted malicious
transaction was carried out on the trading platform, Bitrue. The
attacker executed a double spend worth US$14,000. Appearing to
confirm Coinbase’s estimate of US$1.1 million lost as a result of the
attack, Slow Mist said that the attacker halted its activities due to
the actions of exchange. “Based on continuous tracking, we found
that, in view of the increase in block confirmations and the ban on
malicious wallet addresses by exchanges, the attacker’s 51% attack
on ETC has stopped after that.”
Coinbase was able to protect its users by halting trading of
ETC. Given that ETC was one of the top 20 digital assets by
market capitalisation, the 51% attack reverberated throughout the
cryptocurrency community. It was easy for machines mining ETH to
4
This can happen in certain circumstances as the blockchain network is asyn-
chronous and some machines mine faster than others.
5
https://medium.com/@slowmist/the-analysis-of-etc-51-attack-from-slowmist-
team-728596d76ead.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch06 page 175
6
https://www.crypto51.app/.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch06 page 176
7
https://qz.com/1287701/bitcoin-golds-51-attack-is-every-cryptocurrencys-nig
htmare-scenario/.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch06 page 177
A Look at Security and Privacy 177
Number of nodes in Bitcoin Gold.
Source: https://status.bitcoingold.org.
Figure 6.3:
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch06 page 178
178 Blockchain and Smart Contracts
The number of nodes in Bitcoin.
Source: https://bitnodes.earn.com.
Figure 6.4:
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch06 page 179
8
https://cointelegraph.com/news/ethereum-is-under-ddos-attack-miners-are-al
erted.
9
https://blog.ethereum.org/2016/09/22/transaction-spam-attack-next-steps/.
10
https://blockgeeks.com/guides/ethereum/.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch06 page 180
The most famous exchange hack was that of Mt. Gox in 201411
where around 850,000 bitcoins, worth US$470 million (at that time),
were stolen by a hacker. Mt. Gox was the industry leader at that
time; they process about 70% of all bitcoin transactions. All the
affected users were unable to get their money back. Exchange hacks
were still prevalent, and hundreds of millions were stolen by hackers.
It is always good practice to transfer your crypto holdings to self-
managed secure wallets (such as a hardware device). If you have large
amounts of cryptocurrencies, consider using a custodian service with
high levels of security.
Although blockchain networks are secure by design, they can
still be vulnerable to bad actors such as in situations described
above. The risk of such attacks needs to be considered when trading
in cryptocurrencies and deploying a blockchain network. However,
security considerations go beyond hackers. In the next section, we
look at protecting user data privacy.
11
https://www.wired.com/2014/03/bitcoin-exchange/.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch06 page 182
Secure
Anonymous Homomorphic State
Coin Mixing Multiparty
Signatures Encryption Channels
Computing
Zero Trusted
Group
Knowledge Execution
Signatures Proofs Environments
Ring
Signatures
without any additional setup. Thus, such schemes are good for public
blockchains. Examples of public blockchains with ring signature
schemes are Monero and Ethereum.
Another important method to protect data privacy is homomor-
phic encryption. It is a cryptography method that allows certain
operations to be performed on encrypted data. This means one can
perform a calculation without having to decrypt the data. For exam-
ple, one can determine if a wallet has sufficient amount for a transfer
without knowing the actual amount of funds in the wallet. This
technique can be used to store data on blockchain without having to
change the properties of the blockchain. It allows public blockchains
to operate without having to store transactional data publicly.
Ethereum smart contracts can provide homomorphic encryption on
data stored on the Ethereum blockchain. Zero Knowledge Proofs are
one form of homomorphic encryption and are used by blockchains
such as ZCash.
Another widely discussed type of privacy protection technique
is Secure Multi-Party Computation (SMPC). This technique allows
multiple parties to each compute part of the input data in a way
which does not compromise on the privacy of the input. Many real-
world problems (where inputs need to remain anonymous) such as
voting and bidding can be solved with SMPC. SMPC eliminates the
need for a trusted authority to count votes or check bids. In 2015, a
decentralised (blockchain-based) SMPC platform called Enigma was
proposed. Enigma provides autonomous control and protection of
personal data while eliminating the necessity and dependency of a
trusted third party.
Enigma utilises a Trusted Execution Environment (TEE). TEE
is an isolated computing environment, where other applications
within the machine will not be able to access or tamper with the
computation. One notable type of TEE technology is the Intel
Software Guard eXtensions (SGX). It forms the basis for secure and
privacy-preserving smart contracts on Enigma. One use case is for a
decentralised credit-scoring algorithm. Multiple inputs for a person’s
credit score such as account information, transactions, payments
and credit history can be stored in an encrypted manner on the
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch06 page 184
One can mask the data by hiding parts of the data by replacing
it with random characters or other data. Data blurring is one form
of pseudonymisation. Pictures and videos containing faces can be
blurred out to protect the identity of individuals captured by the
camera. In pictures of identity documents such as passports, the
sensitive information can also be blurred out.
Encryption converts data to another form which is only readable
to someone who has access to a key or password. There are two
categories of encryption, symmetric and asymmetric. In symmetric
encryption, there is only one password and anyone with the password
can decrypt the data. In asymmetric encryption, there are sets of key
pairs (public and private key). The key pairs are required to encrypt
and decrypt the data. Asymmetric encryption is widely used in the
design of blockchain systems. Data should be encrypted while being
moved and also while in storage.
As data in a blockchain can be read by its network, we need
to consider two types of risks when storing sensitive data on a
blockchain. “Reversal risks” are the likelihood that the data can
be decrypted, such as when someone is able to gain access to the
keys. Reversal risks exist as long as the keys exist. Many encryption
techniques may one day be cracked. Thus, it is not sufficient to just
store encrypted data. “Linkability risks” occur when one can link the
data to an individual by analysing patterns.
Hashing techniques that are used in blockchain applications are
non-reversible. Whether personal data are hashed is widely debated.
It also comes down to whether there are potential reversibility and
linkability risks. It may be possible to reverse a hash using brute force if
the data come from a known set of possibilities (e.g., numbers from one
to a million). This can be mitigated by salting or peppering the data,
where extra data (that is only known to the generator of the hash) is
added before creating the hash. Transactional data on blockchain may
be linkable if you use an application to perform actions on your behalf
which is linked to your address. This can be mitigated by using the
anonymous signature schemes described above.
When designing a blockchain network which will store user data,
one needs to consider the following points (see Figure 6.7).
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch06 page 187
WHY is the
What is the
data being purpose?
stored?
Privacy by Design
Respect •Keep it
•Positive-sum, for user user-
not zero-sum privacy centric
Chapter 7
7.1 Introduction
The concept of smart contracts was first discussed in Nick Szabo’s
(1997) paper, “The Idea of Smart Contracts”. He proposed smart
contracts as a means to embed contractual clauses into digital assets.
For smart contracts to be useful for digital assets, there needs
to be transparency and trust between the contractual parties. The
emergence of Bitcoin reignited the discussion of smart contracts
as an application for blockchains. It serves as a system that aids
trustworthy execution of smart contract. They run exactly as
programmed without any possibility of downtime, censorship, fraud
or third-party interference. Instead of recording transfers of bitcoin
on the blockchain, smart contracts are stored (see Figure 7.1).
∗
Adjunct Senior Lecturer, National University of Singapore; Co Vice-Chairman,
Blockchain Association Singapore, Singapore.
189
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch07 page 190
7.2 Ethereum
Ethereum’s global computer (or the Ethereum virtual machine)
processes code in a decentralised way, relying on the resources of the
nodes on the blockchain network (see Figure 7.5). Invented in 2013,
the first version of Ethereum was released in 2016 (see Figure 7.6).
Before Ethereum was conceptualised, blockchains had limited
ability to process code. Ethereum is different; rather than giving
a set of limited operations, it allows developers to create whatever
operations they want. This means developers can build thousands
of different applications that go way beyond anything we have
3. Solidity
a. https://solidity.readthedocs.io/.
4. Web3
a. https://web3js.readthedocs.io/.
b. http://www.dappuniversity.com/articles/web3-js-intro.
contract MyFirstContract {
If the function returns some value, you will need to specify that
with the reserved word returns and then in regular brackets to
specify which type does function returns. In this case, it will be
string (because we return our variable message which is string).
If the function does not return any value, there is no need for
returns statement. It is common practice to write function arguments
with underscore syntax ( message). This convention came from
JavaScript, where private methods and variables start with .
Next, we test the contract. We compile (as described previously)
and deploy. To deploy, choose the Deploy and Run module (add the
module if it is not there). Choose JavaScript VM as the environment;
we are deploying the smart contract in your computer memory (see
Figure 7.16).
After deployment, you will see the deployed contract below where
you can test the functions. We can now see methods from our contract
(see Figure 7.17).
There are two buttons (get & set) for our two public functions
(private cannot be seen here).
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch07 page 201
Click the Get button for the EVM to execute the function. You
will see an empty string returned. Now, type a message in the “set”
field and click the Set button. Click the Get button again, and your
message will be returned.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch07 page 202
However, it does not say Hello world; we can initialise the message
with a constructor. You can write constructor in Solidity with
constructor() public {
// do something. . .
}
We have made the message public and removed the Get function.
If we make the state variables public, one can claim their values
from outside the contract. Solidity will make for each public state
variable a method with the same name which can be called as a
regular function. We do not need the get function once we do this.
This will reduce the size of the code and make it cheaper to deploy.
You can compile, deploy and test the updated code. A message
button now replaces the Get function; it will return the value of
message.
Next, we will create an ERC-20 contract. The token contract
consists of the following:
• ERC-20 Interface — The token rules or standard
• SafeMath Library — Add-on arithmetic operations
• Your customised token contract
ERC-20 tokens follow a list of rules so that they can be shared,
exchanged for other tokens or transferred to a crypto-wallet; these
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch07 page 203
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a); c = a - b; }function safeMul(uint a, uint b) public
pure returns (uint c) {c = a * b; require(a == 0 ||c / a == b); }function
safeDiv(uint a, uint b) public pure returns (uint c) {require(b >0);
c = a / b;
}
}
contract baseContract {
// base contract code...
}
contract inheritedContract is baseContract {
// inherited contract code...
}
constructor() public {
name = “TokenName”;
symbol = “XYZ”;
decimals = 18;
totalSupply = 100000000000000000000000000;
balances[msg.sender] = totalSupply;
}
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch07 page 206
You then call the event in the body of whatever function you
wish to cause to generate the event. You can do so using the emit
keyword:
constructor() public {
name = “TokenName”;
symbol = “XYZ”;
decimals = 18;
totalSupply = 100000000000000000000000000;
balances[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
}
We also need to add code for the six mandatory functions in our
main token contract:
1. totalSupply
Identifies the total number of ERC 20 tokens created. The purpose
of this method is to determine the total number of tokens floating
around the ecosystem.
2. balanceOf
Returns the number of tokens that a particular address has in
their account.
3. allowance
In order to carry out a transaction, one of the most important
data that the contract should know is the balance of the user. If
the user does not have the minimum required number of tokens,
the function cancels the transaction.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch07 page 208
4. approve
To give approval to the user to collect the required number of
tokens from the contract’s address. The approve function also
checks the transaction against the total supply of tokens to make
sure that there are none missing or extra. It makes sure that
counterfeiting or double spending is impossible.
5. transfer
This function lets the owner of the contract send a given
amount of the tokens to another address just like a conventional
cryptocurrency transaction.
6. transferFrom
transferFrom() allows you to automate payment transfers to a
specific account.
*
* Initializes contract with initial supply tokens to the creator
of the contract
*/
constructor() public {
name = “TokenName”;
symbol = “XYZ”;
decimals = 18;
totalSupply = 100000000000000000000000000;
balances[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
function totalSupply() public view returns (uint) {
return totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public view returns
(uint balance) {
return balances[tokenOwner];
}
function allowance(address tokenOwner, address spender)
public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approve(address spender, uint tokens) public returns
(bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transfer(address to, uint tokens) public returns (bool
success) {
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch07 page 212
balances[msg.sender] = safeSub(balances[msg.sender],
tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens)
public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.
sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
}
You can now compile, deploy and test your contracts. The next
step is to deploy to the testnet. To do so, change the environment to
“Injected Web3” (see Figure 7.18).
Before you click Deploy, make sure that your Metamask wallet is
set to a testnet wallet with enough token balance (If your Metamask
wallet is connected to the Main Ethereum Network instead, your
wallet will be charged real ETH and the contract will be deployed
into the live network). Once you click Deploy, Metamask will prompt
you to approve the payment for the transaction fee (see Figure 7.19).
Once the transaction is complete, you can see a green tick in the
console box. You can also click on the link to check the transaction
on Etherscan (an Ethereum blockchain explorer). You can find your
wallet address (creator), the smart contract address and the token
details on Etherscan (see Figure 7.20).
Clicking on the token link will bring you to the Token page (see
Figure 7.21).
You can add the token to your Metamask wallet by following the
steps below (see Figure 7.22).
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch07 page 213
7.5 ERC-20
The key use of the ERC-20 contracts has been for raising funds
through a mechanism called ICOs. Thus, Ethereum is also known
as the ICO crowdfunding machine. One of the easiest applications
of Ethereum’s smart contract system is to create a simple token which
can be transacted on the Ethereum blockchain instead of ether. This
kind of contract was standardised with ERC-20. Ethereum became
the host of a wide scope of ICOs.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch07 page 215
Chapter 8
∗
Founder, Sentinel Chain.
†
School of Business, Singapore University of Social Sciences, Singapore.
217
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch08 page 218
division was commanded by its own general, and all the generals
could communicate with one another only by messenger. The generals
needed to have a coordinated plan of action in order to take down the
enemy fort. However, some of the generals could be traitors and they
would try to present an agreement to be reached. The generals must
have an algorithm to guarantee that (A) all loyal generals decide
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch08 page 220
upon the same plan of action, and (B) a small number of traitors
cannot cause the loyal generals to adopt a bad plan.
The Byzantine Generals Problem assumes that there will be an
unknown number of participants that are expected to misbehave and
attempt to subvert the network; hence, it is often used as an analogy
in computer science to describe the challenges faced by distributed
systems in achieving consensus over unreliable communication
links.
Solving the Byzantine Generals Problem requires complicated
algorithms, and such algorithms did not exist until the 1970s. They
only worked in lab-like environments, however, and they can only be
deployed in large-scale and expensive developments, such as Boeing
airplanes or submarines, where every component within the entire
system has to work with a very tight margin of error (see Figure 8.5).
Bitcoin and Boeing 777 share the similarity that both solve
the Byzantine Generals Problem, but Bitcoin solves it with cheap
hardware. The trade-off is that the confirmation in the Bitcoin (or
some other cryptocurrencies) network takes place in a different way:
the network needs time to collect votes and reach consensus. In
essence, time is the price (or rather, a unique feature) that the Bitcoin
network pays to reach consensus in a decentralised setup.
between peers. Other metadata will also be passed on, such as block
size and configuration of time needed to arrive at consensus.
8.2.3 Cryptography
A hash function is a function that maps data of arbitrary size to fixed-
size values, and it is in one direction only. Symmetric cryptography
means the same key is used for verifying the authenticity of data.
Asymmetric cryptography is used extensively in blockchain, and it
involves using pairs of related keys — a public key to process the
data and a private key to validate it. On the contrary, in the Digital
Signature Algorithm (DSA), data are signed with a private key but
can be verified with the public key. Public keys may be disseminated
widely, but private keys are known only to the owners.
One type of the asymmetric cryptography is elliptic-curve cryp-
tography (ECC), an approach based on the algebraic structure of
elliptic curves over finite fields (see Figure 8.9).
Base58Check
16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM
unlocking script, based on her private key) in the new transaction (see
Figure 8.39). This ScriptSig is combined with the ScriptPubKey (the
locking script, based on her public key) in the previous transactions
and executed. If the returned result is TRUE, it proves that Alice
does indeed own the private key paired with the public key, and the
spending is successfully executed.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch08 page 243
(1) OP DUP
(2) OP HASH160
(3) pubkeyHash
(4) OP EQUALVERIFY
(5) OP CHECKSIG
(1) sig
(2) pubkey
Step 7: Once Step 5 returns true, the last operator [OP CheckSig]
will be pushed onto the stack. It verifies if the public key
is generated by the private key which is used to sign the
signature.
If the returned result from Step 6 is true, the spending is
successfully executed.
A list of commonly used script opcodes are shown in Figure 8.43.
With these opcodes, functions other than spending can be achieved.
For example, instead of sending a transaction to a wallet address,
one can publish a transaction on the network and send bitcoins to
anyone who can return a certain hash value. Any user who can return
such a hash value will be able to unlock the transaction and receive
the bitcoins.
Given in Figure 8.51 are the three executable files needed during
the setup and use of multichain. The two main configuration files
should be set before the chain is created and running. Some hidden
folders will be created while setting up the blockchain.
Multichain-util is used to create a blockchain and kick off the
process (see Figure 8.52).
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch08 page 250
permissions for other nodes, and the administrator has the highest
power to change all permissions for any address.
• Check that both peers are on a blockchain with the same name.
• If necessary, download the blockchain parameters from the other
side; otherwise, check that both are using identical parameters.
• Each node identifies a public address which has connection per-
missions and for which it has the private key.
• Each node sends a challenge message to the other node which it
must sign using the private key corresponding to the address it
presented.
assets are issued by addresses, and the word “native” means that
the logic for validating such assets is embedded within the protocol.
There can be many different assets in multichain, but only one native
currency.
Bitcoin 2.0 is a concept that refers to leveraging the Bitcoin
protocol above and beyond its native currency bitcoin, such as
securing and validating external transactions that do not originate
on the main chain (see Figure 8.67). A related term is “colored
coins”, which describes a class of methods for representing and
managing real-world assets on top of the Bitcoin blockchain. Earlier,
we discussed that the Bitcoin Script language allows it to store
small amounts of metadata on the blockchain, which can be used
to represent such asset manipulation instructions. However, the
presence of such non-native assets encoded in the metadata is not
subjected to network-level verification, because Bitcoin nodes cannot
read the metadata and also because neither Bitcoin nodes nor Bitcoin
tracks such non-native assets. The only way to validate the balance
of such non-native assets is to download the full history of bitcoin
transactions.
MultiChain assets, on the contrary, are built into the protocol and
validated at the network level (Figure 8.68). It encodes the identifiers
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch08 page 260
Figure 8.67: Difference between multichain assets and bitcoin 2.0 protocols.
output may be less than the input, with the difference collected as a
fee by miners).
1
https://azure.microsoft.com/.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch08 page 263
Overview
Below are the steps for setting up Node 1 and Node 2 and establishing
a connection (see Figure 8.74):
Figure 8.74: Steps 1–4, establishing connections between Node 1 and Node 2.
Figure 8.85: Verify consensus settings for admin on Node 1 and Node 2.
Step 1: Node 1 grants itself the permission to issue, send and receive.
Step 2: Node 2 grants itself the permission to receive.
Step 3: Node 1 issues an asset called “asset1” to its own wallet; the
total quantity is 10,000, and the smallest denomination is
0.01.
Step 4: Node 1 sends a quantity of 100 asset1 to Node 2.
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch08 page 281
party will suffer a loss and it could also cause a chain of effects (see
Figure 8.127).
For exchange-traded products, there is a trusted third party
(clearing house) to lower the counterparty risks among participants,
but concentration risk is significantly increased (see Figure 8.128).
December 24, 2020 14:17 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch08 page 295
Step 4: Node 2 combines his unlocking script with the locking script
from Node 2, and asks for 1 unit of asset5.
Step 5: Node 2 sends the combined script onto the blockchain.
unit of asset2), and adds on what he asks for: 1 unit of asset5 (see
Figure 8.138).
If the transaction is constructed successfully, i.e., the asset names
and quantities between the two nodes match each other, the output
from appendrawexchange will show a complete field set to true (see
Figure 8.139).
If both nodes check their asset balance now, they will not
see the balance change due to the transaction. This is because
the transaction is not confirmed yet on the blockchain (see
Figure 8.142).
Node 2 then calls sendrawtransaction to broadcast this trans-
action to the network. It returns the txid for the transaction. The
transaction goes through once it is confirmed by the blockchain (see
Figure 8.143).
Both nodes will see the balance change due to the transaction
(see Figure 8.144).
Blockchain native assets, data stream management and atomic
exchange transactions are just a few instances of the extended
functionality of MultiChain. The ease of deployment and customi-
sation also make it one of the popular choices when it comes to
private permissioned blockchain for industrial use.
Reference
Lamport, L., Shostak, R., and Pease, M. (1982). The Byzantine generals problem.
ACM Transactions on Programming Languages and Systems 4(3), 382–401.
December 24, 2020 14:18 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch09 page 305
Chapter 9
9.1 Introduction
The intent of this guide is to allow individuals to have a physical
interaction running a bitcoin node in a more sustainable manner
through affordable devices like a Raspberry Pi (Linux) according
to an easy-to-follow coding instruction. The hands-on tutorial will
cover running a bitcoin core, which is key to understanding Bitcoin
and experiencing what it is like to be running a node, completely
decentralised and not relying on any centralised cloud-hosted nodes.
This tutorial will take a step further by extending beyond the
underlying protocol in overcoming the scalability issue, as seen in
layer-1 bitcoin, by implementing a layer-2 application known as the
lightning solution, which is an almost instant confirmation in bitcoin
peer-to-peer transactions with a minimal fee and increased privacy
simultaneously. In preservation of Cyberpunk’s work, individuals
running their own node can verify and trust their own node, which
is a fairly inexpensive investment that lends an extensive benefit
overall.
∗
Founder of HelloDime.
305
December 24, 2020 14:18 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch09 page 306
to see the yellow blinking light and the red LED light indicating
that it is turning on.
6. Here, the raspberry pi will have an IP assigned to it. We need to
make this IP static.
7. Enter your router settings or your default internet gateway via
an external device; key in both the admin and the password to
access this. Check with the administrator if you do not have it.
8. Find the device name “Raspberry Pi” and under DHCP server,
enable the Raspberry Pi to have its IP address static.
9. Configure port forwarding to allow our device to reach the
Bitcoin networks. Set up in the following manner with the
internal IP as above in point 8.
a. Bitcoin Mainnet, External Port 8333, Internal Port 8333,
Protocol both TCP & UDP.
b. Bitcoin Testnet, External Port 18333, Internal Port 18333,
Protocol both TCP & UDP.
10. For Windows users, please use PUTTY for the SSH connection.
For Mac users, you can use the built-in native terminal for SSH.
I will be using Mac and so it will be in the terminal and the
codes will be the same for Windows users accessing via PUTTY.
Next, we can enter into the pi IP address that we retrieve from
the gateway above in point 8. By default, your raspberry pi will
have a username as pi and password as raspberry. In the example
here, I logged in with “pi” as my username and this results in
the command starting with the username as shown in Figure 9.4.
SSH is enabled and the default password for the “pi” user has
not been changed.
This is a security risk — please log in as the “pi” user and type
“passwd” to set a new password.
Let us now set up some internal raspberry pi configurations using
the code “sudo raspi-config” shown in Figure 9.5.
While in “sudo raspi-config”, these are the commands to perform.
The numbers are shown in Figure 9.6 in the menu order.
December 24, 2020 14:18 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch09 page 313
Let us now get the latest updates and upgrades for the device
using “sudo apt-get update” and “sudo apt-get upgrade” for this
purpose.
We will now add an admin user using the code “sudo adduser
admin”, change password to your desired password for the admin
using the command “sudo passwd root” and reboot it using command
“sudo shutdown-r now”. Once it is back up, you may log in to the
admin user.
Then we will add another user name “bitcoin” as follows:
We will now mount the HDD you have attached to the pi and
format it into the right format. All data will be deleted during this
phase.
Getting the name and details of the hard disk attached, Figure 9.7
shows us that the raspberry pi has identified the HDD.
Format the hard disk by locating the name in the previous line;
in my case it is “sda” as the name shows.
pi@Pi:∼ $ sudo mkfs.ext4 /dev/[NAME OF HDD]
pi@Pi:∼ $ sudo nano /etc/fstab [This will lead you into an editor
screen shown in Figure 9.8]
Edit the “fstab” file and add the following as a new line (replace
UUID=your own HDD UUID) at the end as shown in Figure 9.8 and
below.
rw,nosuid,dev,noexec,noatime,nodiratime,auto,nouser,async,
nofail 0 2
As shown in Figure 9.9, make a new directory folder and add the
HDD.
We then mount the HDD and check if it is mounted correctly in
the following line.
Let us attach an owner to the HDD using the command
“Chown-R”.
If you are able to see your HDD mounted, you are doing well.
December 24, 2020 14:18 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch09 page 315
Figure 9.9: Screenshot to show that the HDD has been mounted.
Figure 9.10: Making a new directory called bitcoin within the HDD.
We can change the user to bitcoin now, change directory to the HDD
and make a bitcoin folder and exit it (see Figure 9.10).
We will create the swap file to shift it to the HDD instead of the
Internal memory card as shown in Figure 9.11. Log in as ADMIN
to do this. We will delete the old files using “swapoff” and uninstall
it. We will then edit the config file and replace it with the following
configuration:
“CONF SWAPFILE=/mnt/hdd/swapfile”
You will need to remove the default CONF SWAPSIZE line.
December 24, 2020 14:18 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch09 page 316
We will then create a new swap file and turn it on with swapon.
Figure 9.16: Linkage pointing to the correct directory which is the bitcoin
folder in the HDD.
PIDFile=/home/bitcoin/.bitcoin/bitcoind.pid
User =bitcoin
Group=bitcoin
Type=forking
KillMode=process
December 24, 2020 14:18 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch09 page 322
Restart=always
TimeoutSec=120
RestartSec=30
[Install]
WantedBy=multi-user.target
Save and exit. We will now activate (see Figure 9.21) and enable
the configuration file above.
We will copy a copy of the following configuration to the admin
user.
We will now restart the device to see if the daemon will autostart
as per our configuration.
Once the red and green LED stop blinking, you may enter into
the admin account and check the status of the services. Ensure that
it is active and running as shown in Figure 9.22.
Now, we are done with the configuration and the setup. We will
now wait for the testnet to be fully synced.
In the meantime, do check out some bitcoin command lines to
call while we wait for the testnet to finish its validation progress. It
is good to have a few of the common commands in hands. Once the
node is synchronised, all you need to do is call certain functions to
check the status of your node.
December 24, 2020 14:18 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch09 page 323
others as it will not be visible from the outside. You are required to
remove nat=true, your node will constantly try to connect but will
be unable to and will not start till it finds a network.
December 24, 2020 14:18 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch09 page 327
CP1
Now, we enable the lightning network, start it and unlock it. We
shall wait for testnet to finish synchronisation with the network (see
Figure 9.39).
Once you see the screen moving quickly with lots of logs (see
Figure 9.40), you have successfully got it to boot automatically.
December 24, 2020 14:18 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch09 page 333
Figure 9.40: Success of auto boot once I unlock the LND wallet.
Now that my transaction has been sent from a sender to me, this
is what I got (see Figure 9.45). It still remains unconfirmed.
After 10 minutes, I check again and this is what we have. Now
that it is a confirmed transaction (see Figure 9.46), UTXO, I can
spend it by sending it out if I want to.
Acinq, another company experimenting with Lightning imple-
mentation, has done a cool site for testing lightning transactions
over payment of coffee. Please try getting yourself a nice cold Frappe
for all the effort and determination through the entire process. Wait,
remember, you are on testnet. If you want to get yourself a real treat
December 24, 2020 14:18 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch09 page 335
Chapter 10
10.1 Introduction
The world is gradually starting to understand blockchain and
understand its benefits; more people and enterprises are discovering
and experimenting on use cases. The most well-known Bitcoin use
case for peer-to-peer payments has grown into an expanded world of
decentralised finance: stable coins, decentralised exchanges, lending
platforms, prediction markets and more. In the world of traditional
finance, banks have gone beyond cryptocurrencies and have deployed
solutions that are using blockchain for trade finance (letters of credit
in particular); central banks such as the Monetary Authority of
Singapore have experimented with interbank clearing and settlement.
The use cases for blockchain are not restricted to the finance space;
there are government and enterprise efforts in the areas of identity,
personal records, retail, trade and manufacturing (see Figure 10.1).
An emerging technology as blockchain is, it is exciting to think
about implementing blockchain in your business or use case. How-
ever, it is important to remember that not all problems can be solved
∗
Adjunct Senior Lecturer, National University of Singapore; Co Vice-Chairman,
Blockchain Association Singapore, Singapore.
337
December 24, 2020 14:18 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch10 page 338
• Asset Registration
Govt Tech • Citizen Identity
• Medical Records
• Underwriting
• Claims processing
Insurance • Asset usage history
• Fraud Detection
3. User actions include the ability to transact and hold assets. Does
this ability depend on their role?
4. How would they usually interact with the system (e.g., mobile
phones or laptops)?
Another important consideration is the identity (or account) of
the user. There are two types of identity to consider. First, consider
if a blockchain-based identity or account is needed. When users
are assigned a blockchain account (or address), they can transact
and hold assets. If this is needed, the other consideration is the
management of user keys. Are your users technically savvy enough
to manage their own private keys (i.e., manage their own blockchain
wallet)? Do you need a mechanism for key recovery? Is it better to
run a key management service? In this case, what are the security
considerations?
The second type of identity to consider is a user’s profile. This
is the connection to a user’s real-world identity. Should your users
transact only with their blockchain accounts? Pseudo-anonymous
blockchains like Bitcoin do not require user identities to be verified.
In most business use cases, some form of identity is required;
there may be legal or business considerations. If there is a need for
this, you also need to consider how you will verify their identity
and what types of identity information is required. Does it include
name, email, identity documents or more? In private or permissioned
blockchains, a gateway or controller ensures that identity is verified
before credentials are issued to the user. Once this information is
collected, you will need to store and manage the user data in a secure
manner. If you are using a public blockchain, you can also collect the
users’ identity on your servers and link them to blockchain accounts.
Exchanges that are legally required to store KYC information are an
example. Other alternatives in public blockchains are identity oracles
that are linked to a trusted database. These sources can come from
governments, financial institutions or utility providers. An example of
this is Uport, which worked with the city of Zug to issue government-
verified identities on the Ethereum blockchain.
December 24, 2020 14:18 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-ch10 page 342
Certificate
Certificate
Issue Issuing
School
Application
Certificate
Student
Issue
Result Verify
Verify
Verify
Employer
Web Cert
Application Hashes
Result
Result
Smart Contract
Blockchain
Index
351
December 24, 2020 14:18 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-index page 352
352 Index
Index 353
G interoperability, 119
gas, 195 intrinsic value, 122
gateways, 343 investor sentiment, 162–163, 168–169
General Data Protection Regulation
(GDPR), 184 K
Go language, 179 key management service, 341
gossip protocol, 118
greatest common divisor, 24 L
group, 25 LASIC principles, 146
group signatures, 182 Last In, First Out (LIFO), 241
leaf, 83
H leapfrog, 144
handshake, 222 Lightning Labs Daemon, 323
hard fork, 180, 236 lightning network, 323
Hardware Security Modules (HSM), Linkability risks, 186
225 LND, 323
hash, 12–13, 82, 86–88, 90, 92, 94–97, locktime, 81
186 low margins, 146
hash codes, 82
hash function, 82, 84, 223 M
hash value, 82–85, 88–90, 94, 97 main chain, 172
hashgraph, 118 mainnet, 306
hash rate, 97, 172 malicious validator, 110
hashrate for hire, 175 marginal cost of production, 143
hex, 85, 90, 96 mechanism design, 347
hex target, 91 mechanism design of the network,
hexadecimal, 85, 87, 90–91, 93, 224 101
homomorphic encryption, 183 medium of exchange, 137
hybrid encryption, 60 Merkle Path, 18
Hyperledger, 114–115, 344 Merkle Proof, 231
Hyperledger Fabric, 115 Merkle Hash Tree, 16–18, 78, 83, 86,
231
I Merkle root, 83, 86–88, 93–94, 231
identity, 48 mesh technology, 149
immutable, 339 Metadata, 238
immutable ledger, 13 Metcalfe’s Law, 142–143
incentive mechanism design, 109 miner, 172, 257
information ratio, 166 Mining Diversity, 256
Initial Coin Offerings (ICOs), 133, mining pool, 174
151, 192 mispricing, 162, 164
input counter, 79–81 modular arithmetic, 24
inputs, 237 Monero, 66
intangible digital assets, 342 multichain, 224, 344
integrity, 4 multiple contracts, 204
Internet economy, 124 multiplicative group, 26
December 24, 2020 14:18 Blockchain and Smart Contracts: Design Thinking. . . 9in x 6in b4043-index page 354
354 Index
Index 355
Forthcoming Titles
The Digital Transformation of Property in Greater China: Finance, 5G, AI, and
Blockchain
Paul Schulte, Dean Sun and Roman Shemakov