0% found this document useful (0 votes)
55 views46 pages

Notes UNIT-3 and 5

Uploaded by

soman77kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views46 pages

Notes UNIT-3 and 5

Uploaded by

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

Unit III Crypto Primitives, Securing and Interconnecting Public and

Private Block Chains


Syllabus
Hash Function and Merle Tree-Security Properties-Security Considerations for block chain-
Digital Signature-Public Key Cryptography-Bitcoin blockchain incentive structures- Nash
Equilibriums- evolutionary stable strategies,-and Pareto efficiency (game theory) Weaknesses
and news Points of Failure, Mitigation Methods, Redundancies and fall-back methods.

3.1 Hash Function and Merle Tree


Block
With blockchain technology, each page in a ledger of transactions forms a block. This block
has an impact on the next block or page through cryptographic hashing. In other words, when
a block is completed, it creates a unique secure code, which ties into the next page or block,
creating a chain of blocks or a blockchain.

Figure 3.1 Blockchain Diagram on how blocks are connected


Blockchain working model

Figure 3.2 Blockchain working model

85
Blockchain Diagram: Only when the transaction is verified and validated, values can be
transferred to another place.
Whenever a blockchain is introduced to a new blockchain transaction or any new block is to
be added to the blockchain, in general, numerous nodes within the same blockchain
implementation are required to execute algorithms to evaluate, verify and process the history
of the blockchain block. If most of the nodes authenticate the history and signature of the
block, the new block of blockchain transaction is accepted into the ledger and the new block
containing data is added to the blockchain. If a consensus is not achieved, the block is denied
being added to the blockchain. This distributed consensus model allows blockchains to
function as a distributed ledger without requiring any central or unifying authority to validate
the blockchain transactions. Thus, the blockchain transaction is extremely secure.
Blockchain Architecture
When we investigate the DNA of blockchain architecture for a better understanding,
we need to analyze several aspects that contribute to this disruptive technological marvel.
How does blockchain work? These aspects include the blockchain platform, nodes,
transactions that makeup blocks, security implementations, and the process of adding new
blocks to the chain. The blockchain architecture is undoubtedly complex, but once you get a
hold of it you will get acquainted with the same.

Figure 3.3 Basic architectural representation of a blockchain.

86
With blocks being connected with each other through their respective hash codes, the
whole blockchain ecosystem becomes a Fort Knox technically. Whenever a blockchain
transaction flag is raised, a blockchain consensus needs to be achieved to update the same in
the blockchain. Instead of relying on a third party to mediate transactions, member nodes in
the blockchain network stick to a blockchain consensus protocol to agree on the ledger
content and cryptographic hashes and digital signatures to ensure the integrity of transactions.
Once authenticated, these blockchain transactions are considered successful and irreversible.
Transactions rely a lot on hash values and hash functions. These hash functions are
mathematical processes that take input data of any size, perform required operations on it,
and return the output data of a fixed size. These functions can be used to take a string of any
length as input and return a sequence of letters of a fixed length. This functionality of hash
functions makes them apt for transaction processing. Regardless of the size of transactions,
the final output will always be fixed and untampered.

process that
helps differentiate between blocks. The process of hashing gives blocks in a blockchain a
unique identity. Technically, blocks in a blockchain are identified by their hash, which serves
the purposes of both identification and integrity verification. An identification string that also
provides its own integrity is called a self-certifying identifier. The hashing functions generate

Bitcoin uses SHA-256 hash function that produces a hash code of size 256 bits or 32 bytes.

Figure 3.4 Hash message

87
Blockchain Diagram: Bob, while placing an order with Lisa, creates a message which is
like the one shown above. This message is hashed through a hash function that produces a 32
bytes hash code. The beauty of the hash is that for all practical purposes it can be considered
unique for the contents of the message. If the message is modified, the hash value will
change. This makes it impossible to reconstruct the original message. Hacking, therefore, is a
distant dream with hash functions.
Cryptographic Keys and Digital Signatures
As the information on the blockchain is transferred over peer-to-peer (P2P) networks
across the globe, cryptographic keys are incorporated to send data throughout the network
without compromising the safety and integrity. These keys not only allow blockchains to
respect the privacy of users but also uphold the ownership of assets and secure the
information of blocks in the network. Cryptography is applied throughout the entire
blockchain onto all the information that is stored and transacted. This provides users with

asset on the blockchain. Cryptographic hashes also help a great deal as they ensure that even
the smallest change to a transaction will result in a different hash value being computed,
which will eventually indicate a clear change in the transactional history. While
cryptographic keys are necessary for safety and integrity, digital signatures provide
verification and authentication of ownership on the blockchain. Using cryptographic digital
signatures, a user can sign a transaction proving the ownership of that asset and anyone on
the blockchain can digitally verify the identity to be true.
Blockchain Nodes
In simple terms, every participant in a blockchain network is a node. Being a
decentralized network where a central authority is absent, there is great value for blockchain
nodes. There exist several types of blockchain nodes, and each of them requires specific
hardware configurations to get hosted or connected. Basically, there are two types of nodes:
full nodes and lightweight nodes. These types comprise a constellation of a variety of nodes
that are grouped under them.

Figure 3.4 Blockchain nodes

88
Full nodes act as a server in a decentralized network. Their main tasks include
maintaining the consensus between other nodes and verifying the transactions. They also
store a copy of the blockchain, thus being able to securely enable custom functions such as
instant send and private transactions. When making decisions for the future of a network, full
nodes are the ones that vote on proposals.
Pruned Full Nodes: The specific characteristic here is that these nodes begin to download
blocks from the beginning, and once they reach the set limit, the oldest ones are deleted,
retaining only their headers and chain placement.
Archival Full Nodes: These are what most people refer to when they talk about full nodes.
These nodes envision a server that hosts the full Blockchain in its database.
Compared to full nodes, Master nodes themselves cannot add blocks to the blockchain.
Their only purpose is to keep a record of transactions and validate them. Whether Mining or

Lightweight or Simple Payment Verification (SPV) nodes, on the other hand, are used in
day-to-day cryptocurrency operations. These nodes communicate with the blockchain while
relying on full nodes to provide them with necessary sets of information. They do not store a
copy of the blockchain but only query the current status for the last block. Also, they
broadcast transactions to other nodes in the network for processing.
Blockchain Consensus
The set of rules by which a blockchain network operates and validates the information of
consensus

Figure 3.5 Blockchain consensus

assume that complications are bound to arise when a decision needs to be taken. This is
where consensus comes in handy. While consensus must be achieved by a certain type of

89
nodes, in P2P networks any user can become a full node and thus gain supremacy over
others. When at least 51% nodes agree on to something, the decision is validated on behalf of
the whole of the blockchain. This 51% rule may result in threats even. The most common
threat to a blockchain is the 51% attack, where more than half of nodes are concentrated in
one entity. This paves the way for the entity to change consensus rules as it sees fit, which
could lead to a monopoly.
Blockchain Proof of Work
A popular consensus mechanism for blockchains, Proof of Work is a requirement
through which expensive computations, also called mining, can be performed in order to
facilitate transactions on the blockchain. Although it might be hard for nodes to generate a
valid
achieved through hash functions. Since hashes are quite sensitive to changes and even minute
modifications will result in a completely different hash output, they can be used to validate
and secure blocks.

Figure 3.6 Bitcoin mining


For a block to be confirmed as valid, miners are required to generate two hashes: a
hash of all the transactions in the block and one proving that they have expended the energy
required to generate the block by solving a special cryptographic puzzle with a pre-set level
of difficulty. The difficulty of solving the puzzle can be automatically adjusted in Proof of
Work systems to create a consistent time period for blocks that are to be added to the
blockchain. In summary, a miner creates a block of valid transactions. Further, the miner runs
a Proof of Work algorithm on it to find a valid hash. When a valid block is generated, the
block is added to the blockchain, and the miner receives network fees and the newly
created cryptocurrency.

90
Blockchain Protocols
As blockchains are being rolled out at an exponential rate for everything from cross-
border financial transactions to supply chain management, the lack of scalability has
remained a constant issue since the genesis of blockchains. As more computers join the P2P
network, the efficiency of the whole blockchain ecosystem typically deteriorates. Through
the process of sharding, a way of partitioning, blockchain miners can maintain a consistent
throughput throughout the network. Blockchain protocols, however, demand constant
attention for their efficient functioning.

Table 3.1 Blockchain Protocol Characteristics


Blockchain Each party maintains its own copy of the information, and all nodes must
Protocol validate updates collectively.
Characteristics The information could represent transactions, contracts, assets, identities, or
practically anything else that can be described in digital form.
Entries are permanent, transparent and searchable, which make it possible
for community members to view transaction histories in their entirety.
Each update is a new block added to the end of a chain. A protocol manages
how new edits or entries are initiated, validated, recorded, and distributed.
Cryptology replaces third-party intermediaries as the keeper of trust, with
all blockchain participants running complex algorithms to certify the
integrity of the whole.

Major blockchain protocols are listed below:


Bitcoin: The first application of blockchains, Bitcoin enables users to perform non-
reversible transactions trustlessly. This protocol includes technologies such as hash,
digital signature, public-key cryptography, P2P networking, Proof of Work and Proof of
Work mining.
Ethereum: Known for smart contracts, Ethereum features a native cryptocurrency,
namely Ether, and an Ethereum wallet. This protocol allows users to create decentralized
applications and democratic autonomous organizations.
Ripple: Ripple supports tokens that are used to represent fiat, other cryptocurrencies,
commodities, or other value units such as mobile minutes and frequent flyer miles.
Hyperledger: Developed by the Linux Foundation in 2015, Hyperledger supports
Python, endorsement policies for transactions and confidential channels for private
information sharing.

91
Openchain: A scalable and secure blockchain protocol, Openchain is suitable for
organizations that wish to issue and manage their digital assets.
IOTA:
infinitesimally small payments without charging extra fees.
Lisk: A relatively new blockchain protocol, Lisk allows the development of
decentralized applications in pure JavaScript.
BigchainDB: This open-source system starts with a big data distributed database and
then adds blockchain characteristics to the network including decentralized control and
digital asset transfers.
Blockchain Hashing
Hashing, or a hashing algorithm, is a one-way process that converts your input data of any
size into fixed-length enciphered data.

Figure 3.7 Hash message


A hash function is a one-way mapping.
That means that it can take an input (the input is usually a large sequence of bits;
It can be a movie, a song, an e-book, a picture, or any digital data) and produce a fixed-size
value as output, often much smaller than the input size.

92
However, if I change only one bit in this input, the output will be completely different.
hash functions are unidirectional.
output hash is a fixed-length random bit sequence.
hexadecimal format and looks alphanumeric.
Hash Properties
Fixed length
Unique
One-way function
Eg:- SHA256
Hash Example -1
SHA 256

Input
from: person1
to: person2
amount: 5000
Hash
A1BA93299F5836B8A58543CAD52B8818F0C95F12991635609B0F7CAAF6388A58

Hash Example -1
SHA 256
Input
from: person1
to: person2
amount: 5001
Hash
C677256A3CD1F73CD4476204BCA19050E0A11AB11FAEBF14CD7B37FB696F73C5
Characteristics of Hash Function
Ensure data integrity.
Serve as a check-sum
Hash digest changes completely when any of the email content gets modified after
being digitally signed
Secure against unauthorized modifications.

93
The smallest of changes to a message will result in the creation of an entirely new
hash value.
Protect stored passwords
Websites typically do is hash passwords to generate hash values.
Operate at different speeds to suit different purposes.
Different hash functions serve different purposes depending on their design and hash
speeds
Popular Hash Functions
Message Digest (MD) MD5
128-bit hash function.
provide assurance about integrity of transferred file.
Secure Hash Function (SHA)
160-bit hash function

Each block has the following key components: data, hash, previous hash and metadata
(timestamp, block number).
Data in a block could be a
transactions
Hash is a unique identifier for a block and is analogous to a fingerprint for a human
Previous Hash is the hash value of the previous block in the blockchain
Metadata is information about the data; e.g., block number, timestamp, etc.

Figure 3.8 Blockchain Data Structure


Hash is calculated by cryptographic algorithms employed in the blockchain. They take a
s hash.
Hash = function(data, previous hash, metadata)
A different unique hash value is generated for different combinations of previous hash value
and data. The demo available here [2] allows you to generate hash for different data sets. You

data and previous hash.

94
As illustrated below, blocks are cryptographically linked through hash; i.e., hash of a block is
same as the previous hash of the block succeeding it in the blockchain. The first block in a
previous hash is zero as there is no block
hash with the previous hash value of the next block is
mandatory for the blockchain to be considered valid.

Figure 3.9 Blocks in a blockchain linked cryptographically through hash


Key properties of Secure Hash Algorithms (SHA)
SHA-256 used in Bitcoin is one of the examples of a cryptographic hashing algorithm.
SHA-256 always generates a 256-character hash value irrespective of the input data size.
Secure hash algorithms used in blockchain should have the following properties:
Same hash value should always be generated for the same input

the hash
Even a slight change in the data should change the hash value completely
Algorithm should be able to compute the hash quickly
The same input data produces same hash but a single change completely changes the hash.
The result returned is the verifiable fingerprint. Bitcoin uses the SHA256 hash function that
returns a fixed 256-bit fingerprint.

Figure 3.10 Hash messages

95
Blockchain is called an immutable ledger because it stores a record of transactions in
blocks which cannot be changed, once created. New blocks can be added to the block chain
but data in the existing blocks cannot be changed. If a malicious actor alters the data in a
block, the hash of that block gets changed and it does not match with the previous hash value
of the next block. The blockchain system realizes this and makes the change in the data
invalid.
Data integrity
blockchain is distributed to all the peers in the blockchain network in real-time.
Blockchain solution looks for updates constantly and replicates the blockchain that is in

The immutable nature of blockchain combined with its decentralized framework


ensures data integrity because it is extremely difficult to tamper with the data in the entire
block chain in majority of the systems in a blockchain within seconds especially when there
are numerous entities in the blockchain. The only possibility of a malicious actor being
successful in tampering block chain is when that actors has more computational power than
the rest of the blockchain network combined. This is called 51% attack.
Use of Cryptographic Hashes
Proof-of-work
Block contains transactions to be validated and previous hash value.
Pick a nouce such that H(prev hash, nounce, Tx) < E. E is a variable that the

bits are zero. The work required is exponential in the number of zero bits required.
Verification is easy. But proof-of-work is hard.

Figure 3.11 Block

Merkle Tree
The concept was patented by Professor Ralph Merkle back in 1979. Now it helps to solve
problems in large decentralized networks.
A Merkle tree is a data structure that is used for secure verification of data in a large

96
content pool.
It is also efficient and consistent when it comes to verifying the data.
Ethereum and Bitcoin both utilize Merkle Trees.
Problem in blockchain :
Each data is copied among the nodes. So, it is a challenge to efficiently access data.
The challenge is also to make a copy of the data and share it among nodes. On top of
that, the shared data needs to be verified for each of the receiving nodes.
Solution :
Merkle Trees enable decentralized blockchains to share data, verify them, and make
them trustworthy.
Merkle trees are data structure trees where the non-leaf node is defined as a hash
value of its respective child nodes.
The Merkle tree is inverted down where the leaf nodes are the lowest node.
At the core of Merkle trees, we need to learn three important terms. They are as below:
Merkle Root
Leaf Nodes
Non-Leaf Nodes
It is an upside-down tree
The tree is capable of summarizing a whole set of transactions by itself. This
means that the user can verify if a transaction is part of the block or not.

Figure 3.12 Merkle Tree


Merkle tree is a complete data structure in the form of a tree, in the leaf vertices of
which there are hashes from data blocks, with the inner vertices containing hashes from

97
adding values in child vertices. This connects all the elements with information among
themselves. In the end, it looks like this.

Figure 3.13 Merkle Tree example

A hash is a result of converting a hash function. It is a function that converts an array of


input data of arbitrary length into an output string of a specified length in accordance with a
specific algorithm.
To make Merkle trees work, hasing is used. It simply does the hashing pairs of nodes
repeatedly until only one hash value is left.
The left hash value is known as Merkle Root or the Root Hash.
The tree is created from the bottom up using the individual transactions hashes.
The individual transaction hashes are also known as Transaction IDs.
The leaf nodes are the nodes that contain transactional data hashes.
In the case of the non-leaf nodes, they store the hash of the two previous hashes.
Another important property of Merkle trees is that it is binary in nature.
This means that it requires leaf nodes to be even for it works.
In case, if there is an odd number of leaf nodes, it will simply duplicate the last hash
and make it even.
Merkle Tree of odd number of transections

98
Figure 3.14 : Merkle tree using four data blocks D0, D1, D2, and D3

It is a data structure tree in which every leaf node labelled with the hash of a data
block.
A Merkle tree stores all the transactions in a block by producing a digital fingerprint
of the entire set of transactions.
It allows the user to verify whether a transaction can be included in a block or not.
Merkle trees are created by repeatedly calculating hashing pairs of nodes until there is
only one hash left.
This hash is called the Merkle Root, or the Root Hash.
The Merkle Trees are constructed in a bottom-up approach.
Every leaf node is a hash of transactional data, and the non-leaf node is a hash of its
previous hashes.
Merkle trees are in a binary tree, so it requires an even number of leaf nodes.

99
If there is an odd number of transactions, the last hash will be duplicated once to
create an even number of leaf nodes.

Figure 3.15 : Merkle tree

Merkle Root is stored in the block header. The block header is the part of the bitcoin
block which gets hash in the process of mining.
It contains the hash of the last block, a Nonce, and the Root Hash of all the
transactions in the current block in a Merkle Tree.
So having the Merkle root in block header makes the transaction tamper-proof.
As this Root Hash includes the hashes of all the transactions within the block, these
transactions may result in saving the disk space.

Figure 3.16 : Merkle tree with block

The Merkle Tree maintains the integrity of the data. If any single detail of transactions
or order of the transaction's changes, then these changes reflected in the hash of that
transaction.

100
This change would cascade up the Merkle Tree to the Merkle Root, changing the
value of the Merkle root and thus invalidating the block.
So everyone can see that Merkle tree allows for a quick and simple test of whether a
specific transaction is included in the set or not.

Merkle trees benefits


Validate the integrity of data: It can be effectively used to validate the integrity of the
data.
Takes little disk space: Merkle tree takes little disk space compared to other data
structures.
Tiny information across networks: Merkle trees can be divided into tiny information
for verification.
Efficient verification: The data structure is efficient and takes only a while to verify
the integrity of the data.
3.2 Security Considerations for block chain
The followings are the key security features of blockchain
Identity and access management.
Key management.
Data privacy.
Secure communication.
Smart contract security.
Transaction endorsement.
In the Bitcoin network, for instance, the proof of work is used for block validation. Any
node in the network can attempt to validate the block through a process called mining. Miners
are awarded in cryptocurrency for every successful validation of a new block.
Is blockchain secure?
Blockchains have a heterogeneous architecture made up of cryptographic algorithms and
mathematical models. The structure of the blocks plays a crucial role in enabling distributed
consensus and ensuring the security of the system.
Data which may include transaction records, contracts, or even IoT device
telemetry.
Hash value of the current block is generated to serve as a cryptographic image of
the block that can be verified by anyone.

101
Hash value of the previous block is an encrypted string used to link to the
previous block in order to form the chain.
Timestamp. A record of the time when the block was created.
Additional information including digital signatures, nonce value, etc.

Figure 3.17 : blockchain sample transaction

Survey shows that financial and manufacturing use cases are facing more targeted cyber-
attacks. According to an article in Fortune magazine, more than 4 million bitcoins are
missing. This number accounts for 17% to 23% of the total cryptocurrency, which worth
more than $8,500 each.

Blockchain has some other inherent properties that can provide additional security. Some
of the properties of Blockchain technology are:

1. Increased Capacity
The structure of the linked system of blockchain is more than capable of
increasing the capacity of an entire network.
2. Immutability
It means that once a transaction is done, it is impossible to erase it from the database.
3. Faster Settlements
banking transactions take time, but blockchain transaction save lot of time.
4. Encryption
Asymmetric-key algorithm and Hash function encryption.
5. Decentralization: collaborative manner.

102
Phishing
Phishing is one of the most common hacking techniques.
It can mimic the emails from trusted and reputed sources.
These emails are sent to the owners of digital wallets, asking them to fill their
personal information on the fake links.
As per a report of Chainalysis, more than $225 million were lost to phishing
scams in the first of 2017.
Sybil Attacks
Sybil attacks involve the use of multiple fake identities.
In other words, a single party can run a number of nodes at the same time, using
fake identities to disrupt the activities of the network by crashing it.
Routing Attack
The information of blockchains can be intercepted by hackers by compromising
ISPs.
The compromised Internet Service Providers can also be the cause of this type of
attack.
Direct Denial of Service
DDoS attacks are also a major security issue for blockchain applications.
In this attack, hackers flood the network with false requests consequently
increasing the traffic of the network and disrupting legitimate requests or they
target applications with the low and slow attacks to make these applications
unavailable for its users.
Some of the most common issues
51% vulnerability
Private key security
Exchange hacks
Social engineering
Double spending
Transaction privacy leakage.
51% vulnerability
consensus mechanism has a 51% security vulnerability that can be
exposed by malicious attackers in an attempt to control the network.

103
PoW - a 51% attack occurs when a single miner or a pool of miners own more than
50% of total hashing power.
PoS - a 51% attack can be performed by a single miner who owns more than 50% of
all the funds.
a 51% attack would be extremely expensive to undertake.
Smaller blockchains that have less hashing power are more vulnerable to such attacks.
Private key security (wallet security)
blockchains today, public and private keys are generated using the elliptical curve
digital signature algorithm (ECDSA).
The public key can be derived from the private key, but not vice-versa.
While the public key can be shared and used as the address for sending transactions,
the private key should always be kept safe, known only to the owner.
In spite of the blockchains being inherently secure structures, their security is directly
related to the private key.
private key will give an attacker ac blockchain wallet.
Once lost, private keys cannot be recovered.
If the private key is by any chance stolen by attackers, it will give them full access to
the associated blockchain account and the opportunity to initiate transactions
Since the blockchain is not controlled by any centralized authority, it is difficult to
track and recover the lost funds or information.
Exchange hacks
Exchange is considered as quick investment return.
For the exchange to work, the users are register their wallets in third party databases.
It is prone to attacks
The safest methods of storing cryptocurrency are either using hardware or paper
wallets.
These wallets are so-called cold storage wallets that have minimal exposure to
malicious online attacks.
Solution: perform trading on decentralized exchanges (DEX) as they communicate
directly with the cryptocurrency wallet.
Social engineering attack
Manipulate individuals into uncovering and sharing their private keys, passwords, and
other sensitive information that can be used for fraudulent purposes.

104
Identity theft - result in significant financial losses.
Phishing - the attacker impersonates a trustful resource and sends out messages,
notifications, and emails requiring the victims to click on malicious links, fill out
forms, and give out their sensitive information.
Scenario involves the attacker using the domain name similar to the legit one.
Social engineering attacks - Solutions
To avoid falling prey to a phishing scam, make sure to:
Never share login credentials or private keys.
Educate yourself and the people around you about common cases of social
engineering.
Never click on the email attachments, links, ads, or websites of unknown origin.
Use anti-malware software and keep the software applications and operating systems
updated.
Use multi-factor authentication solutions whenever possible.
Double spending attacks
Double-spending is a situation in which the same digital funds are spent multiple
times.
In the blockchain-based decentralized network, a reliable consensus mechanism has to
be put in place to prevent double-spending.
Bitcoin network, double spending attacks are prevented by evaluating and verifying

blockchain protocol.
Transaction privacy leakage
In public blockchain networks, transactions are open and transparent.
Their architecture makes every transaction traceable as well.
Transactions could contain sensitive information about their issuers.
In some blockchain applications, such as the internet of things or mobile
crowdsourcing, transaction privacy leakage is a critical issue.
Solution : mixing service (cryptocurrency tumbler).

The architecture of Blockchain.

105
Figure 3.18 The architecture of Blockchain.

Table 3.2 Security and Privacy Requirements, Properties

S&P requirements Corresponding S&P Corresponding S&P


Supported in bitcoin S&P properties techniques techniques

Consistency Consistency Consensus algorithms

Integrity Tamper-resistance Hash chained storage

Resistance to DDoS Consensus algorithms


Availability
attacks with Byzantine fault

Resistance to
Prevention of Signature and
double-spending
double-spending verification
attacks

Public key as
Anonymity Pseudonymity
pseudonyms

Mitigation Methods

Performing Static Analysis testing (SAST) - analyze the source code to identify
security loopholes.
Performing Dynamic Analysis testing (DAST) eliminate vulnerabilities during
software development

106
to test for security vulnerabilities in applications in the production environment.
Performing Interactive Application analysis/testing (IAST) to thoroughly test for
hidden inputs, hidden files, and configuration information, etc. in an application
running in real-time, in the development process, QA, or in production.
Performing Software Composition Analysis (SCA) to check for any vulnerable
outdated libraries, open-source components, and containers used in the development.
You can use thisOWASP dependency-check tool to do this.
Performing a detailed penetration testing for your Blockchain-based application to test
and discover security loopholes and vulnerability exploits using the hacker approach.
You can do this by using a variety of open-source tools that are available on the
Internet.

Figure 3.19 bitcoin mining process

Figure 3.20 Block

107
3.3 Public Key Cryptography

Public key cryptography uses a pair of a public key and a private key to perform
different tasks. Public keys are widely distributed, while private keys are kept secret. Using a

private key can decrypt and read it. Using a private key, a digital signature can be created so
that anyone with the corresponding public key can verify that the message was created by the
owner of the private key and was not modified since.

Figure 3.21 Digital signature flow diagram

Public-key algorithms are asymmetric algorithms and, therefore, are based on the use of two
different keys, instead of just one. In public-key cryptography, the two keys are called
the private key and the public key
Private key: This key must be know only by its owner.
Public key: This key is known to everyone (it is public)
Relation between both keys: What one key encrypts, the other one decrypts, and vice versa.
That means that if you encrypt something with my public key (which you would know,
because it's public :-), I would need my private key to decrypt the message.

A secure conversation using public-key cryptography

In a basic secure conversation using public-key cryptography, the sender encrypts the
message using the receiver's public key.
Remember that this key is known to everyone. The encrypted message is sent to the
receiving end, who will decrypt the message with his private key.

108
Only the receiver can decrypt the message because no one else has the private key.
Also, notice how the encryption algorithm is the same at both ends: what is encrypted
with one key is decrypted with the other key using the same algorithm.

Figure 3.21 secure conversation using public-key cryptography

Pros and Cons of public-key systems


Public-key systems have a clear advantage over symmetric algorithms: there is no
need to agree on a common key for both the sender and the receiver.
As seen in the previous example, if someone wants to receive an encrypted message,
the sender only needs to know the receiver's public key (which the receiver will
provide; publishing the public key in no way compromises the secure transmission).
As long as the receiver keeps the private key secret, no one but the receiver will be
able to decrypt the messages encrypted with the corresponding public key.
This is due to the fact that, in public-key systems, it is relatively easy to compute the
public key from the private key, but very hard to compute the private key from the
public key (which is the one everyone knows).
In fact, some algorithms need several months (and even years) of constant
computation to obtain the private key from the public key.

109
Figure 3.22 public-key cryptography
Another important advantage is that, unlike symmetric algorithms, public-key systems
can guarantee integrity and authentication, not only privacy. The basic communication seen
above only guarantees privacy. We will shortly see how integrity and authentication fit into
public-key systems. The main disadvantage of using public-key systems is that they are not
as fast as symmetric algorithms.
Digital signatures: Integrity in public-key systems
Integrity is guaranteed in public-key systems by using digital signatures.
A digital signature is a piece of data which is attached to a message and which can be used to
find out if the message was tampered with during the conversation (e.g. through the
intervention of a malicious user)

Figure 3.23 Digital signature for a message


The digital signature for a message is generated in two steps:
A message digest is generated. A message digest is a 'summary' of the message we are going
to transmit, and has two important properties: (1) It is always smaller than the message itself

110
and (2) Even the slightest change in the message produces a different digest. The message
digest is generated using a set of hashing algorithms.
The message digest is encrypted using the sender's private key. The resulting encrypted
message digest is the digital signature. The digital signature is attached to the message, and
sent to the receiver. The receiver then does the following:
Using the sender's public key, decrypts the digital signature to obtain the message
digest generated by the sender. Uses the same message digest algorithm used by the sender to
generate a message digest of the received message. Compares both message digests (the one
sent by the sender as a digital signature, and the one generated by the receiver). If they are
not exactly the same, the message has been tampered with by a third party. We can be sure
that the digital signature was sent by the sender (and not by a malicious user)
because only the sender's public key can decrypt the digital signature (which was encrypted
by the sender's private key; remember that what one key encrypts, the other one decrypts, and
vice versa). If decrypting using the public key renders a faulty message digest, this means
that either the message or the message digest are not exactly what the sender sent.
Using public-key cryptography in this manner ensures integrity, because we have a
way of knowing if the message we received is exactly what was sent by the sender. However,
notice how the above example guarantees only integrity. The message itself is sent
unencrypted. This is not necessarily a bad thing: in some cases we might not be interested in
keeping the data private, we simply want to make sure it isn't tampered with. To add privacy
to this conversation, we would simply need to encrypt the message as explained in the first
diagram.
Authentication in public-key systems
The above example does guarantee, to a certain extent, the authenticity of the sender.
Since only the sender's public key can decrypt the digital signature (encrypted with the
sender's private key). However, the only thing this guarantees is that whoever sent the
message has the private key corresponding to the public key we used to decrypt the digital
signature. Although this public key might have been advertised as belonging to the sender,
how can we be absolutely certain? Maybe the sender isn't really who he claims to be, but just
someone impersonating the sender. Some security scenarios might consider that the 'weak
authentication' shown in the previous example is sufficient. However, other scenarios might
require that there is absolutely no doubt about a user's identity. This is achieved with digital
certificates, which are explained in the next page.

111
3.4 Nash Equilibriums evolutionary stable strategies,and Pareto efficiency (game
theory)

Evolutionary game theory (EGT) is the application of game theory to evolving


populations in biology. It defines a framework of contests, strategies, and analytics into
which Darwinian competition can be modelled. The mathematical criteria that can be used to
predict the results of competing strategies.
What are market structures?

Figure 3.24 Market structure


The organization and fundamental characteristics of any market are called market
structure.
The market structures are differentiated based on many factors like a number of
producers, control over prices and barriers to entry. Based on these factors, there are
four different kinds of market structures:
Based on these factors, there are four different kinds of market structures:
Perfect Competition.
Monopoly.
Monopolistic Competition.
Oligopoly.
Perfect Competition
Perfect competition is a market place where it is easy for anyone to get into the

Think of mangoes. It is easy for anyone to get into the market, all that anyone has to
do is to grow mangoes.

mango for $10 then the buyer can simply buy it from someone who is selling
mangoes for $5.
Monopoly

112
A monopoly is the polar opposite of a perfect competition.
This is a market place which is dominated by one corporation and the barriers to entry
are so high that nobody else can enter it.
De beers diamonds are a great example of a monopolistic market.
Monopolistic Competition
This is a marketplace which has a lot of sellers and very low barriers. Their products
are similar but not really identical.
Think of the pizza delivery service. Now, dominoes and pizza hut have the same
product with subtle differences.
Obviously one can slightly price their product a little higher based on factors like
customer preferences. However, if dominoes price their pizzas way too high, then
people will simply go over to pizza hut.
Consequently, if dominoes and pizza hut both start overcharging, since the barriers to
entry is so low, another player can come in and take all the customers.
Oligopoly
Oligopolies are market places which are dominated by a few markets and the barriers
to entry are high.
One of the best examples of an oligopoly is the smartphone market. The market is
dominated by few number of companies like Samsung, Apple, and Huawei. Much
like monopolistic competitions, the products are similar but not identical.
If tomorrow, Apple decides to price their iPhones at $4000, apart from the Apple
fanatics, most will simply opt for an Android phone.
Obviously, they can always get together and decide as a group to mutually increase
illegal in many countries, including the
United States.

-
without changing the price.
How do they do that? They do so by changing the look and style of their products and
giving a unique experience. However, the most recognizable form of non-price
competition is advertising.
Advertising is one of the most effective ways of showing unique qualities of your
products and to introduce new products.

113
But then again, there is a problem. How many of the advertisements do you watch
actually stick? Chances are that you have been bombarded by tons of ads today itself,
how many of them do you actually remember? If you are a player in an oligopoly and
you keep blindly advertising, you are going to be spending a lot of money.
As a result of that, in order to make up all that money, you are going to invariably
have to increase the price of your products.
If that happens, your buyers are simply going to go to your competitors. So how do
you go about this? How do you advertise your products without losing out on your
customers?
You will have to basically take decisions based on the actions that your competitors
will take. In order to do that, you will have to use Game Theory.
What is the Game theory?
Game theory is the study of strategic decision making. This is how many corporations
make decisions while keeping in mind the actions that their competitors will take. Game
theory was devised by John Van Nuemann and Osker Morgenstern in 1944 and was
considered a breakthrough in the study of oligopoly markets. Since then the game theory has
found a life of its own and has seen widespread implementations in various other
technologies and fields.
A game theory model has at least 3 components:
Players: The decision makers. Eg. The managers in the firms.
Strategies: The decisions they want to take to further their companies.
Payoff: Outcome of the strategies.
In game theory, there are two types of games.
Zero sum game: It is a game in which the gain of one player comes at the expense of another
player.
Non zero sum game: A game where the gain of one
another player.

Suppose there are two firms A and B.


Table 3.3 Pay-off matrix

114
If Firm A and B both decide to advertise then the payoff for both of them is 4 and three
respectively.
B decides to advertise, then the payoff is 2 and 5.

Case 1: If Firm A advertises


Then
obviously, their best payoff lies in advertising.

case their best payoff lies in advertising.


Conclusion: Regardless of what Firm A does, Firm B should advertise.

Case 1: If Firm B advertises

again, their best payoff lies in advertising.

advertise. Once again, their best payoff lies in advertising.


Conclusion: Regardless

So, in this example, for both Firm A and Firm B, their most stable state will be if they both
advertise, which is: For both Firm A and Firm B, this is their dominant strategy. A dominant
strategy is the best course of action for a player regardless of what the opponent does. In this
example, (4,3) is also the Nash Equilibrium.

115
Nash Equilibrium

Figure 3.25 Nash Equilibrium

The Nash equilibrium is a solution to a game where each player chooses their optimal
strategy given the strategy was chosen by the other and they have nothing to gain by
shifting their strategy.
This was formulated by John F Nash who was portrayed by Russell Crowe in the

This has humongous implications in a distributed computer system like the


-
Nash Equilibrium.

Blockchain and Cryptocurrency Game Theory

A block is a series of blocks which contains individual transactions in it. Each block
also contains the hash of the previous block and this, in turn, links each subsequent block to
rough visual
representation of a blockchain.

116
Figure 3.25 Chain of blocks

Some terms:
Genesis block:
Proof of work: The amount of computational work required to create the block.
Parent block: The block that immediately precedes a block is the parent block of that
block. So in the diagram above, Block 50 is the parent block of Block 51.
Every block in the blockchain has a scoring function.
Score(genesis) = 0.
Score(Block) = Score (parent block) + Proof of work
The current state of the chain is the block with the highest score.
In a system based on blockchain bitcoin there are two players:
Users.
Miners.
Users, in bitcoin, have only two functions available to them:
Send coins.
Receive coins.
In order to do that they need two keys, the public, and the private key.
What miners do is that they authenticate the transactions AND they do the process of
mining.
Mining is how new blocks are discovered and added to the blockchain.
Block Mining
Through a series of computations, miners find a block and add it to the
blockchain.In Ethereum, adding the block gives the miner(s) a reward of 5 ether and
In bitcoin, the mining reward is 25 BTC (both as of writing).

117
Miners have a lot of power in the blockchain system and if they do choose to cheat for
their own personal gain, they can cause havoc in the system.
To mitigate that, the blockchain uses game theory mechanics to keep the system
bulletproof.

another peer-to-peer system which has allowed its users to, time and again, get away
with cheating.
Torrenting is one most popular peer to peer systems in the world.
While using torrents, users have two roles: downloading and seeding.
After downloading a file, they are supposed to share it the network via a method
called seeding.
However, they get no compensation for seeding the said file and hence more often
than not they refuse to do so.

How can miners cheat? Cryptocurrency Game Theory


They can include an invalid transaction and give themselves extra coins.
Add blocks randomly without worrying about Proof of work.
Mine on top of invalid blocks to get more BTC.
Mine on top of a sub-optimally scoring block.

Figure 3.26 Forking of chain

118
The blocks in blue are the main chain. Now suppose there is a miner who, in blue
block 51, spends 20 bitcoins to get 500 litecoins (hypothetically).
And now he wants to create a parallel chain with a new block 51 (red), where in he

In blue block 51 spends 20 bitcoins to get 500 litecoins.

the litecoin transaction.


In the end, he comes out with his original 20 BTC and 500 new litecoins.
ly now miners can,
theoretically, mine on top of the new red chain and keep double spending and mining
extra bitcoins.
As you can imagine, this can destroy the bitcoin system.
The blockchain was designed in a way that it is a self-enforcing Nash Equilibrium.
The reason why that happens is that mining has a recursive punishment system.

The Nash Equilibrium in mining and the punishment system.

rule that has been defined in blockchain mechanics.


Any block that is mined on top of an invalid block becomes an invalid block.
Using this rule, miners will simply ignore the invalid block and keep on mining on top
of the main chain aka the blue chain in the diagram.
This similar logic stands for sub-optimally scoring block. Look at the diagram again.
No miner will want to mine on Red Block 52 because the Blue Block 53 will have a
higher score than the red block.
Both of these scenarios get mitigated because miners., as a group will choose the most
stable state aka the state with a Nash Equilibrium.
Obviously, you can make all the miners mine on the red block and make it the new
blockchain.
As the co-ordination game states, if a majority of the people in the group are not
changing their state, the minority will not have any incentive to stay in the new state.
Seeing this, why will a miner spend all their computation power and risk ostracization
in a futile cause?

119
Why will users use the main chain instead of the other chain?

about the users? In the blockchain game, there are two players, miners, and users. Why will
users prefer the blue chain over the red chain? Once again, game theory mechanics come into
play. The first thing that you need to keep in mind is that cryptocurrency has value is because
the people give it value. So, why will a normal user assign a value to coins coming out of the
blue chain and not to the coins coming out of the red chain? The reason is simple. The main
chain is a Schelling point from the users perspective. They give it value because the main
chain seems natural and special to them.

Bounded Rationality: Another reason why users will value the main chain more is that they
are simply used to it. Like bounded rationality states, people will simply opt for the simplest
solution every time. Moving through a newer chain needlessly complicates things.

Vitalik Buterin gave a great example of the Takeover problem and we are going to
expand on it. Suppose, someone makes a hypothetical smart contract for an activity.
The terms of the contract go like this:
Any miner can join the activity by sending a very large deposit into the contract.
The miners must send shares of the partially completed blocks that they have mined
into the contract and the contract verifies it and also verifies that you are a miner and
that you have sufficient hash power.
Before 60% of the miners in the system join you can leave anytime you want.
After 60% of the miners join, you will be bound to the contract until the 20 blocks
have been added to the hard fork chain aka the red chain.
Yes, it is indeed very diabolical and you can see the problem that this attack can have.
Not only will the new chain grow bigger and longer, since 60% of the entire miners
are bound contractually to this new chain this will quickly make the original older
chain aka the blue chain irrelevant. This will make double spends all over the place
and the value of the currency will fall fast.

Now, you might be asking why miners will join in a takeover?

The possible reward at the end.

120
No risk of joining on their part.
What is their incentive to follow through with the contract?
The huge amount they have deposited in the beginning.
Once again, the possibility of a great reward.
Theoretically, a takeover like this can end any currency, but this is not that likely to

Longest Chain Rule

A blockchain is a list of blocks linked by hash values with each block containing a
batch of ordered transactions.
To make all participants agree on the same chain of blocks, NC leverages two
components: the Proof-of-Work (PoW) mechanism and the longest chain rule (LCR).
Each participant collects valid and unconfirmed transactions from the network, orders
and packs these transactions into a block.

Figure 3.26 Longest chain rule

In addition, a valid block needs to contain a proof of work, i.e., its owner needs to find
a value of the nonce (i.e., a changeable data field) such that the hash value of this
block has required leading zeros.
The length of leading zeros is also known as the mining difficulty, which can be tuned
by the system so that new blocks are mined every ten minutes on average.
In reality, two new blocks might be mined around the same time, leading to a fork in

To resolve such a fork, an honest miner always accepts the longest chain as the valid
one. See Fig. 1 for an illustration. Block B3 is a forking block, which will be
abandoned by the honest miners according to the longest chain rule.

121
In Bitcoin, a block miner will receive a block reward (if its block is eventually
included in the longest chain) as well as transaction fees as another type of reward.
In Bitcoin, the mining of blocks has two functionalities: (1) electing leaders (i.e., the
owners of valid blocks) by miners, and (2) ordering and verifying transactions.
Transaction fee is used to incentivize miners to include transactions in their blocks.
Therefore, the higher the transaction fee is, the more miners try to include the
transaction into the latest block.
The results show that about 77.8% transactions have a quite small fee (less than
0.0001 BTC).

3.5 Incentive Structure

Figure 3.27 Blockchain incentive structure

122
Selfish Mining
NC is designed to fairly reward miners according to their contributions to the system

the studies show that a selfish miner can gain more revenue than its fair share by
deviating from the protocol.
This mining attack is called selfish mining. In this attack, a selfish miner can keep its
newly generated blocks secret, mine on top of these blocks, and create forks on
purpose when necessary.
In particular, when some honest miner generates a new block, a selfish miner will
publish one secret block to match this honest block as a competition or publish two
blocks to override this honest block because honest miners follow LCR.

Figure 3.28 Selfish Mining

123
Forks
The Nakamoto consensus does not guarantee that the blockchains of all miners are the
same at all points in time.
Thus, some conflicting chains may form, known as forks.
When a fork occurs, these blocks are usually created by different creators, and these
creators are in competition; thus, only the creator in the longest chain can win the
reward.
In the Nakamoto consensus, miners only admit the blocks in the longest chain, and the
transactions in other forks are invalid.
In addition, when the longest chains are not unique, miners usually follow the highest
block they received first.

Figure 3.29 Block is added into the chain of network

The above figure shows an example of a blockchain with the Nakamoto consensus. In this
example, the longest chain is from the genesis block (A0) to the black leaf block (A8), and
other blocks in shorter forks are colored white. In this example, the miners follow block (A8).

Preventing Double-spending

The only way is to be aware of all transactions.


Each node (miner) verifies that this is the first spending of the Bitcoin by the payer.
Only when it is verified it generates the proof-of-work and attach it to the current
chain.

124
Bitcoin Network

Each P2P node runs the following algorithm:


New transactions are broadcast to all nodes.
Each node (miners) collects new transactions into a block.
Each node works on finding a proof-of-work for its block. (Hard to do.
Probabilistic. The one to finish early will probably win.)
When a node finds a proof-of-work, it broadcasts the block to all nodes.
Nodes accept the block only if all transactions in it are valid (digital signature
checking) and not already spent (check all the transactions).
Nodes express their acceptance by working on creating the next block in the
chain, using the hash of the accepted block as the previous hash.

Tie breaking

Two nodes may find a correct block simultaneously.


Keep both and work on the first one
If one grows longer than the other, take the longer one

Figure 3.30 blocks

3.6 Blockchain Security Mitigation Methods


Blockchain technology enforces distributed consensus and cryptographic transactions.
It is very difficult to compromise the integrity of its records without being noticed by an
entire network. Because of blockchai
transactions, and events to be recorded and stored publicly. Therefore, it can prevent online
frauds such as double spending and hacking.

125
Maliciousness on the Internet encompasses identity theft, fraud, and network or
system intrusions.

Figure 3.31 blockchain security threats


Maliciousness on the Internet encompasses identity theft, fraud, and network or
system intrusions. Blockchain can help in preventing frauds involving assets other than
currency and credit. Smart contracts used to ensure transacting parties comply with contracts,
reducing defaults by buyers or poor service by providers. blockchain technology can prevent
several types of malicious attacks and reduce many associated risks, it cannot eliminate all
attacks.
Blockchain technology: unavoidable attacks
The 51% Attack
Occur when a single minor node that is having more computational resources than the
rest of the network nodes.
In such a situation, this node dominates the verification and approval of transactions
and controls the content of a blockchain.

dominant node can outpace all other nodes.


Thus, it can manipulate the blockchain, insert fraudulent transactions, double-spend
funds, or even steal an asset from others.
Identity Theft
Although blockchain can preserve anonymity and privacy, the security of assets
depends on safety of the private key, a form of digital identity.

Illegal Activities
Blockchain technology can become a venue for illegality.

126
Crypto-currency that uses blockchain technology may also facilitate money
laundering.
Using Detection Technologies
blockchain technology prevents fraudulent behavior, it is not able to detect fraud by
itself.
Implementing innovative techniques and methods that are needed to detect attacks.
Use of machine learning and data-mining algorithms for creating new applications for
detecting fraud and intrusions in blockchain-based transactions.
Implementation of techniques such as profiling, monitoring, and detecting behavioral
patterns based on peo
Development of supervised machine learning approaches that can help in detecting
outlier behaviors.
Establishing Identity In Blockchain Technology
Loss of a key is equal to the loss of identity on the network.
Solution : building an identity and reputation system using a blockchain that can

This can also track life events such as the opening of bank accounts, car purchases,
etc.
It is difficult to steal because it is unforgetable, publicly monitored, and time-stamped.
Mitigating Denial-of-Service (DDoS) Attacks
A distributed denial-of-service attack occurs when a network is intentionally flooded
with unsustainable amounts of traffic or specific information that triggers a crash.
These attacks are typically not aimed at acquiring personal information or holding a
system for ransom
Attackers generally unleash such attacks simply to claim credit for the mayhem.
The IoT is a primary reason why DDoS attacks were up 91% last year.
BlockArmor Leveraging blockchain technology to increase network size and make
DDoS attacks more difficult.
The CIA security triad model, composed of three areas;
(1) Confidentiality,
(2) Integrity
(3) Availability

127
Authentication, Authorization and Audit (AAA), and Non Repudiation, fundamental
security aspects for protecting information and designing / managing new systems and
networks
Confidentiality
The property that sensitive information is not disclosed to unauthorized individuals,
entities, or processes.
Network Access
Data Access & Disclosure
Integrity
Integrity is defined as the
destruction, and includes ensuring information non-repudiation and authenticity
Immutability
The combination of sequential hashing and cryptography along with its decentralized
structure makes it very challenging for any party to tamper with it in contrast to a
standard database
Right to be Forgotten
Traceability
Smart Contracts
Data Quality
Availability
Ensuring timely and reliable access to and use of information.
No Single Point of Failure
Operational Resilience
Redundancies in blockchain Network
In a blockchain network, for every node to be processed, it has to traverse and process every
intermediate node independently to reach the target node. Thus, the redundancy involved in
blockchain technology affects its performance.

Table 3.4 Preview of Blockchain Weaknesses - (Cloud Security Alliance - CSA)

Name of weakness Description


API Exposure If an API is improperly exposed an attacker can attack it
Block Mining Race Attack A variation on the Finney attack
Block Mining Timejack By isolating a node the time signal can be manipulated

128
Attack getting the victim out of synchronization
Certain cryptographic operations such as using CBC
(Cipher Blocker Chaining) or ECB (Electronic
Block Reordering Attack
Codebook) incorrectly allow blocks to be re-ordered and
the results will still decrypt properly
By creating a large number of fake peers in a network
Blockchain Peer flooding (peer to peer or otherwise) an attacker can cause real
Attack nodes to slow down or become non responsive as they
attempt to connect to the newly announced peers.
Advantages of Blockchain
Blockchain Pros
Near-instant updating
Chronological and timestamped
Cryptographically sealed
Irreversible and auditable
Operates without trust
Fewer third parties
Weakness of Blockchain
Blockchain is not a Distributed Computing System
Scalability Is An Issue
transactions are completed depending on the network congestion.
Some Blockchain Solutions Consume Too Much Energy
high energy consumption is what makes these complex mathematical problems.
Blockchain Cannot Go Back Data is Immutable

Blockchains are Sometimes Inefficient


storage problems - ledger can e
Not Completely Secure
51% attack, Double-
Users Are Their Own Bank: Private Keys
Make sure that they do not share it with anyone else. If they fail to do so, their wallet
is in danger. Also, if they lose the private key, they will lose access to the wallet forever.
Cost And Implementation Struggle
Expertise Knowledge
Maturity

129
o It is only a decade old and it requires time to mature.
Interoperability
Legacy Systems
if they want to adopt blockchain technology, they need to completely get rid of their
systems and change to blockchain technology

130

You might also like