Module 1 Introduction To Blockchain
Module 1 Introduction To Blockchain
Instructions:
1. Ensure that the task is completed on the very same day it is assigned. If you face
any problem, do share it with us in the group at the same moment, so that the doubts
are cleared at the earliest.
2. Every week we will complete one module. Each module is further divided into 5
days. We have kept the weekends free so you can catch up on the work over the
weekend and attend the doubts session/workshops which will be organised.
3. If you are not able to complete the task, ensure that they are covered in the very
week so that the process is not delayed much.
4. We will have live workshops every week. The schedule of the same will be shared
at the start of the week and the same is added to your weekly curriculum. Do ensure
you are attending these workshops as they are live sessions by industry experts. It is
going to help you only in your journey. If by any reason you are not able to attend,
inform the team beforehand.
6. Please update your daily progress by posting on twitter and sending a message on
the group When posting on your twitter accounts please tag us @blockchainedind
and @Polkadot, along with the use of following hashtags:
#60DaysofCode #BuildInPublic #Polkadotdevbootcamp
If you have any questions or doubts, please reach out to us on the group or email us
at [email protected] and [email protected].
Content
Workshop Details
Advanced Topics (optional)
2
Module 1: Introduction to blockchain
Day 1
The first blockchain started as a research project. Satoshi Nakamoto wrote the paper
Bitcoin: ‘A Peer to Peer Electronic Cash System in 2009’ in which he described a way
of transferring value from one person to another without the need for physical
currency or bank. Bitcoin itself is a very simple blockchain. At its core, it’s just a list
of accounts and the value held within them.
In 2014 people realized that blockchains could be used to run small programs and a
way to transfer money safely.
The Bitcoin protocol isn’t particularly well equipped for programs, so in 2015 Vitalik
Buterin co-created Ethereum which allowed developers to create smart contracts on
a blockchain. Ethereum vastly improved the usability of blockchains and attracted
the attention of companies like Microsoft, Bank of America, and Google.
3
iii) So what exactly is blockchain?
ii) “With shared-state” means that the state stored on this machine is shared
and open to everyone.
(Ex: A valid transaction obtained from singleton machine is stored in all the members
of blockchain)
Think of a firewall of sorts. They make it nearly impossible to cheat the system.
(e.g. create fake transactions, erase transactions, etc.)
4
iv) Blockchain vs Centralized server:
Blockchain networks look like regular networks, with a group of computers all
connected. However, they differ in the way that programs and applications run. On a
regular network when a user wants to find the results of an application, they send the
request to a particular server who runs a program and returns the answer to the user.
An issue with this process is that there isn’t any way to verify that the response the
user got from the server is correct, or that the program the server ran was the
program the user requested.
On a blockchain network when a request is sent from the user to the network, all the
computers run the program and agree on the answer before sending it back to the
user. This way the user can verify that the answer is the correct answer and that the
correct program was run in the first place. Calling a program is referred to as a
transaction. All transactions are saved in a database and shared with all the other
computers on the blockchain network. Because of this, users can prove that they
performed a certain action.
https://www.youtube.com/watch?v=8fbhI1qVj0c&ab_channel=TEDxTalks
https://www.youtube.com/watch?v=SSo_EIwHSd4&ab_channel=SimplyExplained
5
Let’s split the definition to understand better using a fictional cryptocurrency as
Example:
Ledger - A ledger can be considered as a digital register/Database which can store
any content. Assume a new transaction detail “Trump paid 10 paise to Kim jung Un”
is stored in the digital database or ‘ledger’ present in north korea.
Assume countries like India, China, Northkorea, and the United States also have
ledgers with them. To achieve ‘distributed’ status all the above countries copies/
syncs the same transaction - ‘Trump paid 10 paise to Kim jung Un’ into their ledgers.
Why Synchronization?
Hence the transaction which abided by the universal rule and is shared/Replicated
within all the ledgers constitutes a distributed ledger.
6
But wait! How can we ensure that the person who is writing the transaction is
following the universally acceptable rule?
You might say that as it is universally acceptable , so we can ask other countries
whether the particular transaction is valid or not. If a country didn’t follow the
universal rule the validity of other countries can help reject the transaction.
You must have heard about DDOS attack i.e distributed denial of service , generally
this occurs when millions of fake requests generated by malicious bots hit the
website and the website loses its control and crashes In this case the genuine
requests cannot survive as the fake requests have destroyed the System Now if we
don’t want that to repeat in our use case , let us punish malicious dude !
In this case each country needs to put some of their valuable men at stake to prove
their
Seriously, if they made a faulty transaction , the UN can jail those valuable men they
kept at stake !
https://hackernoon.com/wtf-is-the-blockchain-1da89ba19348
7
Day 2
There are basically two types of blockchain network related to access control.
1. Public Blockchain
2. Private(and consortium) Blockchain
Public Blockchain
Public Blockchain is accessible to everyone – anyone who wants to read, write can
join the blockchain and can perform respective operations. The information once
validated in the network cannot be changed and no single entity can have control
over the network. Bitcoin is one of the first public blockchain networks to prove the
value can be moved anywhere around the world without banks or other third parties.
Take the example of Bitcoins, which are traded on such peer-to-peer networks. This
cryptocurrency can be quite practical when the idea is to dissimulate criminal
activities, since it’s virtual, meaning that it can travel across borders in a seemingly
anonymous way. “Seemingly” because we cannot discard what the benefits of a
Blockchain, public or not, are: Every single transaction is recorded across all nodes of
the network, which provides a complete transaction history accessible by anybody.
Now, it’s not a routing number and a bank account number that are recorded but
rather an (unusable because just made-up) I'D like this one:
1BsghtSLRHtKNngkdBEengR76b53CHAtpyT. The trick is then to convert Bitcoins
into fiat currencies since it must be done via a centralized exchange platform like
Coinbase/Binance. And transactions from Coinbase to a bank account can be
flagged.
8
Private Blockchain
These blockchains work in the same way as public blockchain but with restricted
access. The restriction is applied to the users who are authorized to join the network
and operate. They may have one or more entities that control the network.
Consortium Blockchain:
9
organizations are made public, while others remain private.
To ensure proper functionality, the consortium has a validator node that can do two
functions, validate transactions, and also initiate or receive transactions. In
comparison, the member node can receive or initiate transactions.
Example: Let’s take an Oil & Gas consortium made of twenty companies for
example. Each company operates one node on the network. In a consortium
Blockchain, a percentage of the consortium’s participants must sign every block in
the chain before the block can be validated. So, it could be ten or fifteen companies
required to validate a transaction, before the same transaction is validated
throughout the network for all participants. A federated Blockchain is less
decentralized than a public Blockchain and less centralized than a private Blockchain
in regard to write permissions.--Harshil
10
Public Blockchain Private Blockchain Consortium or Federated
Blockchain
11
Day 3
Currently if you have to transfer funds to someone, one of the possible ways is by
giving cash or alternatively use a trusted intermediary (example, a bank). Both the
mechanisms, whether it be physical cash (with the central bank of the country as the
guarantor) or electronic transfer, involve an intermediary (in the later case, a bank or
another financial institution). When intermediaries are involved, there are transaction
costs.
This cryptographic trust is built into Bitcoin through a wallet, a public key and a
private key in the program.
12
Anyone can create a Bitcoin wallet for free by downloading the Bitcoin program.
Each wallet contains a public key and a private key.
The public key is like an address or an account number via which any person can
receive Bitcoins.
A private key is like a digital signature via which a person can send Bitcoins. The
name suggests that private keys should be only held and known by the owner and
public keys can be shared with anyone for receiving Bitcoins. That is where you
would have heard in the news about Bitcoins being lost either due to a private key
not being accessible or stolen by hackers.
Owners of Bitcoin addresses are not explicitly identified, but all transactions on the
blockchain are public.
Since the inception of Bitcoin in 2009, each and every transaction that has occurred
is stored in a ledger, which is considered immutable, non-tamperable and irreversible.
Mining in Bitcoin
Mining refers to the process of validating and recording transactions on the Bitcoin
network. The primary purpose of Bitcoin mining is twofold: validating transactions to
prevent fraud and adding new blocks to the blockchain, thereby creating new
Bitcoins in a decentralized manner.
The process of bitcoin mining involves the verification of new transactions against
the Bitcoin network, which results in the production of new bitcoins.
13
Miners validate new transactions and record them on the global ledger (blockchain).
On average, a block (the structure containing transactions) is mined every 10
minutes. Miners compete to solve a difficult mathematical problem based on a
cryptographic hash algorithm. The solution found is called the Proof-Of-Work. This
proof proves that a miner did spend a lot of time and resources to solve the problem.
When a block is 'solved', the transactions contained are considered confirmed, and
the bitcoin concerned in the transactions can be spent. So, if you receive some
bitcoin on your wallet, it will take approximately 10 minutes for your transaction to be
confirmed.
Miners receive a reward when they solve the complex mathematical problem. There
are two types of rewards: new bitcoins or transaction fees. The amount of bitcoins
created decreases every 4 years (every 210,000 blocks to be precise). Today, a newly
created block creates 12.5 bitcoins. This number will keep going down until no more
bitcoin will be issued. This will happen around 2140, when around 21 millions
bitcoins will have been created. After this date, no more bitcoin will be issued.
Miners can also receive rewards in the form of transaction fees. The winning miner
can 'keep the change' on the block's transactions. As the amount of bitcoin created
with each block diminishes, the transactions fees received by the miner will increase.
After 2140, the winning miner will only receive transaction fees as his reward.
14
In a picture, mining is:
As you can see, mining is like a lottery. There is no way to predict which nonce will
solve the problem.
In the case of Bitcoin, the hash function used is called SHA256. A hash algorithm
always produces the same arbitrary length data given the same inputs. It is
impossible to compute the same hash with two different inputs (collision). It is also
impossible to predict the output of any given data in advance.
SHA256 always produces an output 256 bits long. Mining is finding the nonce, the
only input that changes every time we run the hash function. It is very easy to prove
that the nonce found indeed produces a valid hash. All the information is available,
everyone can run the hash function and confirm if the hash is valid or not. Because it
15
is also impossible to predict what the nonce will be, it also acts as a proof that the
miner worked to get a valid hash (Hence => Proof-of-Work).
16
Day 4
“The adoption of Ethereum by the corporate world,” says CNBC, “means it could
eventually be bigger than its early stage rival.” That means it’s time to get to know the
Ethereum platform, including its features and applications, and what makes
Ethereum different from Bitcoin.
What is Ethereum?
Ethereum Features
17
● Ethereum Virtual Machine: Ethereum provides the underlying
technology—the architecture and the software—that understands smart
contracts and allows you to interact with it.
● Decentralized applications (Dapps): A decentralized application is called a
Dapp (also spelled DAPP, App, or DApp) for short. Ethereum allows you to
create consolidated applications, called decentralized applications.
● Decentralized autonomous organizations (DAOs): Ethereum allows you to
create these for democratic decision-making.
These are Ethereum’s essential features. Before going deep into the Ethereum
tutorial, let’s discuss each of these features in more detail.
1. Ether
Ether (ETH) is Ethereum’s cryptocurrency. It is the fuel that runs the network. It is
used to pay for the computational resources and the transaction fees for any
transaction executed on the Ethereum network. Like Bitcoins, ether is a peer-to-peer
currency. Apart from being used to pay for transactions, ether is also used to buy
gas, which is used to pay for the computation of any transaction made on the
Ethereum network.
Also, if you want to deploy a contract on Ethereum, you will need gas, and you would
have to pay for that gas in ether. So gas is the execution fee paid by a user for
running a transaction in Ethereum. Ether can be utilized for building decentralized
applications, building smart contracts, and making regular peer-to-peer payments.
2. Smart Contracts
Smart contracts are revolutionizing how traditional contracts work, which is why you
need to use the tutorial to become more familiar with them. A smart contract is a
simple computer program that facilitates the exchange of any asset between two
18
parties. It could be money, shares, property, or any other digital asset that you want
to exchange. Anyone on the Ethereum network can create these contracts. The
contract consists primarily of the terms and conditions mutually agreed on between
the parties (peers).
The smart contract’s primary feature is that once it is executed, it cannot be altered,
and any transaction done on top of a smart contract is registered permanently—it is
immutable. So even if you modify the smart contract in the future, the transactions
correlated with the original contract will not get altered; you cannot edit them.
The verification process for the smart contracts is carried out by anonymous parties
in the network without the need for a centralized authority, and that’s what makes
any smart contract execution on Ethereum a decentralized execution.
In conventional contract systems, you sign an agreement, then you trust and hire a
third party for its execution. The problem is that in this type of process, data
tampering is possible. With smart contracts, the agreement is coded in a program.
A centralized authority does not verify the result; it is confirmed by the participants
on the Ethereum blockchain-based network. Once a contract is executed, the
transaction is registered and cannot be altered or tampered, so it removes the risk of
any data manipulation or alteration.
19
Let’s take an example in which someone named Zack has given a contract of $500 to
someone named Elsa for developing his company’s website. The developers code
the agreement of the smart contract using Ethereum’s programming language.
The smart contract has all the conditions (requirements) for building the website.
Once the code is written, it is uploaded and deployed on the Ethereum Virtual
Machine (EVM).
EVM is a runtime compiler to execute a smart contract. Once the code is deployed
on the EVM, every participant on the network has a copy of the contract. When Elsa
submits the work on Ethereum for evaluation, each node on the Ethereum network
will evaluate and confirm whether the result given by Elsa has been done as per the
coding requirements.
Once the result is approved and verified, the contract worth $500 will be
self-executed, and the payment will be paid to Elsa in ether. Zack’s account will be
automatically debited, and Elsa will be credited with $500 in ether.
20
3. Ethereum Virtual Machine
Any programming language in the smart contract is compiled into the bytecode,
which the EVM understands. This bytecode can be read and executed using the
EVM. Solidity is one of the most popular languages for writing a smart contract.
Once you write your smart contract in Solidity, that contract gets converted into the
bytecode and gets deployed on the EVM, thereby guaranteeing security from
cyberattacks.
Suppose person A wants to pay person B 10 ethers. The transaction will be sent to
the EVM using a smart contract for a fund transfer from A to B. To validate the
transaction; the Ethereum network will perform the proof-of-work consensus
algorithm.
The miner nodes on Ethereum will validate this transaction—whether the identity of A
exists or not, and if A has the requested amount to transfer. Once the transaction is
confirmed, the ether will be debited from A’s wallet and will be credited to B’s wallet,
and during this process, the miners will charge a fee to validate this transaction and
will earn a reward.
21
All the nodes on the Ethereum network execute smart contracts using their
respective EVMs.
b) Proof of Work
The goal of the miners on the Ethereum network is to validate the blocks. For each
block of a transaction, miners use their computational power and resources to get
the appropriate hash value by varying the nonce. The miners will vary the nonce and
pass it through a hashing algorithm—in Ethereum, it is the Ethash algorithm.
This produces a hash value that should be less than the predefined target as per the
proof-of-work consensus. If the hash value generated is less than the target value,
then the block is considered to be verified, and the miner gets rewarded.
When the proof of work is solved, the result is broadcast and shared with all the
other nodes to update their ledger. If other nodes accept the hashed block as valid,
then the block gets added to the Ethereum main blockchain, and as a result, the
miner receives a reward, which as of today stands at three ethers. Plus, the miner
gets the transaction fees that have been generated for verifying the block. All the
transactions that are aggregated in the block—the cumulative transaction fees
associated with all the transactions are also rewarded to the miner.
22
c) Proof of Stake
So, based on the accumulation of crypto coins the miner has beforehand, he or she
has a higher probability of mining the block. However, proof of stake is not widely
used as of now compared to proof of work.
d) Gas
Just like we need fuel to run a car, we need gas to run applications on the Ethereum
network. To perform any transaction within the Ethereum network, a user must make
a payment, in this case paying out ethers, to get a transaction done, and the
intermediary monetary value is called gas.
On the Ethereum network, gas is a unit that measures the computational power
required to run a smart contract or a transaction. So, if you must do a transaction
that updates the blockchain, you would have to shell out gas, and that gas costs
ethers.
In Ethereum, the transaction fees are calculated using a formula (see screenshot
below). For every transaction, there is gas and its correlated gas price. The
transaction fees equal the amount of gas required to execute a transaction
multiplied by the gas price. “Gas limit” refers to the amount of gas used for the
computation and the amount of ether a user is required to pay for the gas.
23
To understand the gas limit and price, let’s consider an example using a car. Suppose
your vehicle has a mileage of 10 kilometers per liter and petrol costs $1 per liter.
Under these parameters, driving a car for 50 kilometers would cost you five liters of
petrol, which is worth $5. Similarly, to perform an operation or to run code on
Ethereum, you need to obtain a certain amount of gas, like petrol, and the gas has a
per-unit price, called gas price.
If the user provides less than the amount of gas to run an operation, then the process
will fail, and the user will be given the message “out of gas.” And Gwei, as noted
above, is the lowest denomination of ether used for measuring a unit of a gas price.
24
e) How is Ethereum Mining Different from Bitcoin Mining?
25
otherwise reject it. Each node has its own transaction pool that it maintains. All the
transactions that are valid are placed inside the transaction pool.
In blockchain at a given point of time, it is not necessary for all the nodes to have the
same transactions in their transaction pool. There could be various reasons for this
to happen such as network latency, broken connection, less computational power
etc. Bitcoin blockchain also defines the frequency at which blocks should be created
inside the network which is set to 10 minutes in the current Bitcoin system.
The miner node takes the unconfirmed transactions in the mining pool and creates a
block. Once a block is created, it gets flooded across the network using the gossip
protocol. All the nodes receive the block and first validate the block if the block
passes the validation they add it to their respective blockchain otherwise not.
Before going through the validation process we will have a look at the Block
Anatomy.
26
A Blocks Header is Comprised of the Following
Components:
i) Merkle root - aggregation of all the hash values of the transactions into a single
hash value.
Now you must be thinking what the block body contains, So it contains the Merkle
Tree.
27
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. If there is an odd number of transactions, the last hash will be duplicated
once to create an even number of leaf nodes.
The above example is the most common and simple form of a Merkle tree, i.e.,
Binary Merkle Tree. There are four transactions in a block: TX1, TX2, TX3, and TX4.
Here you can see, there is a top hash which is the hash of the entire tree, known as
the Root Hash, or the Merkle Root. Each of these is repeatedly hashed, and stored in
each leaf node, resulting in Hash 0, 1, 2, and 3. Consecutive pairs of leaf nodes are
then summarized in a parent node by hashing Hash0 and Hash1, resulting in Hash01,
and separately hashing Hash2 and Hash3, resulting in Hash23. The two hashes
(Hash01 and Hash23) are then hashed again to produce the Root Hash or the Merkle
Root.
28
Day 5
This is the most common alternative to PoW. Ethereum is shifting from PoW to PoS
consensus. In this type of consensus algorithm, instead of investing in expensive
hardware to solve a complex puzzle, validators invest in the coins of the system by
locking up some of their coins as stake. After that, all the validators will start
validating the blocks. Validators will validate blocks by placing a bet on it if they
discover a block which they think can be added to the chain. Based on the actual
blocks added in the Blockchain, all the validators get a reward proportionate to their
bets and their stake increases accordingly.
In the end, a validator is chosen to generate a new block based on their economic
stake in the network. Thus, PoS encourages validators through an incentive
mechanism to reach an agreement.
With PoB, instead of investing into expensive hardware equipment, validators ‘burn’
coins by sending them to an address from where they are irretrievable. By
committing the coins to an unreachable address, validators earn a privilege to mine
on the system based on a random selection process. Thus, burning coins here
means that validators have a long-term commitment in exchange for their short-term
loss.
Depending on how the PoB is implemented, miners may burn the native currency of
the Blockchain application or the currency of an alternative chain, such as bitcoin.
The more coins they burn, the better are their chances of being selected to mine the
next block.
While PoB is an interesting alternative to PoW, the protocol still wastes resources
needlessly. And it is also questioned that mining power simply goes to those who are
willing to burn more money.
3. Proof of Capacity:
In the Proof of Capacity consensus, validators are supposed to invest their hard drive
space instead of investing in expensive hardware or burning coins. The more hard
drive space validators have, the better are their chances of getting selected for
mining the next block and earning the block reward.
29
4. Proof of Elapsed Time:
PoET is one of the fairest consensus algorithms which chooses the next miner using
fair means only. It is mainly used in a permissioned Blockchain network where
permission is required for accessing the network.
In this, every individual on the network is supposed to wait for a random amount of
time. The participant who has finished waiting for the given set of time will get a
chance to be on the ledger to create a new block.
5. Proof of Activity:
There also exist other consensus algorithms like Proof of Activity, Proof of Weight,
Proof of Importance, Leased Proof of Stake, etc. It is therefore important to wisely
choose one as per the business network requirement because Blockchain networks
cannot function properly without the consensus algorithms to verify each and every
transaction that is being committed.
https://medium.com/hackernoon/consensuspedia-an-encyclopedia-of-29-consensu
s-algorithms-e9c4b4b7d08f
30
Do you actually need a blockchain?
https://medium.com/swlh/hyperledger-chapter-3-when-to-use-the-blockchain-techno
logy-a5c414221bdf
31
Blockchain Terms: Block, Gas, Gas Price, Merkle
Patricia Tree
5. Miners - specific nodes which perform the block verification process before
adding anything to the blockchain structure
7. Gas - Gas is the unit of calculation that indicates the fee for a particular action or
transaction. For example, if your transaction is to simply add two numbers, that is 3
units of work. If it is multiplication, that would be 5 units of work and so on. This unit
of work is called gas.
8. Gas Price - The Gas Limit is the maximum amount of Gas that a user is willing to
pay for performing this action or confirming a transaction. For example, you can say
"I am willing to pay 3 Gwei per gas" for my transaction. If your transaction takes
100000 gas and you set the gas price to 3 Gwei, you end up paying 300000 Gwei for
your transaction.
9. Gas Limit - The price of Gas (Gas Price) is the amount that the user is willing to
spend on each unit of Gas. As a developer, you don't want to blindly execute a
transaction and realize your transaction took hundreds of dollars worth of Ether. To
avoid this situation, you can specify a gas limit which indicates the maximum
amount of gas you are willing to buy to execute your transaction.
Don't confuse this with the Block gas limit. Block gas limit is the maximum cap
applied to each block in Ethereum. Currently, a block can only include transactions
whose total sum of gas is less than 8 million. The reason you have a limit for each
block is to prevent someone from just writing an infinite loop in which case the
32
transaction wouldn't complete it's execution resulting in the block not getting mined.
Gas Explained:
To better understand how gas works in Ethereum, let’s use an analogy. Suppose you
are going on a road trip. Before you do so you go through these steps:
● You go to the gas station and specify how much gas you want to fill up in
your car.
● You get that gas filled up in your car.
● You pay the gas station the amount of money you owe them for the gas.
Driving the car is the operation that you want to execute, like executing a function of
a smart contract.
All the operations that users want to execute in ethereum must provide gas for the
following:
10. Nonce - Nonce is the central part of this Proof of Work. The Nonce is a random
whole number, which is a 32-bit (4 byte) field, which is adjusted by the miners, so that
it becomes a valid number to be used for hashing the value of block. Nonce is the
number which can be used only once. Once the perfect Nonce is found, it is added to
the hashed block. Along with this number, the hash value of that block will get
33
Workshop Details
10th June: Live workshop on “How Blockchain
34
Optional: If you want to go deeper in understanding cryptography you can go
through the study material (not important for the bootcamp)
Advance Topics
Cryptography
35
Symmetric cryptography
To get a better idea of how this works, we have created a visualization of the process
below. First of all the sender encrypts a message with the shared key, the sender
then sends the message without having to worry that anybody without the shared
key is able to read the message. The receiver then receives the encrypted message
and decrypts it (with the same shared key).
The main downside of this cryptography method is that the key needs to be shared
with everyone who needs to access the data, which can often be quite hard.
Asymmetric Cryptography
Now you are familiar with symmetric cryptography, let’s dive into asymmetric
cryptography. Asymmetric cryptography is similar to symmetric cryptography, but is
a bit more complex and also has a solution to the main downside of symmetric
cryptography.
36
The main distinction from symmetric cryptography is the usage of keypairs.
Asymmetric cryptography uses keypairs, instead of a shared key, in order to encrypt
and decrypt data.
In the graphic below you can see how these keys work in practice, when sending a
message to somebody securely. First of all the sender encrypts the message with
the public key of the receiver, the sender can then send the (encrypted) message
safely, as the only way to view the message is to decrypt it with the corresponding
private key which only the receiver has. The receiver then receives the message and
is able to decrypt it using the private key.
37
receive it. These keypairs also allow themselves to be used for authentication
purposes, which we will talk more about below.
Digital Signatures
Digital signatures are essentially signatures that provide integrity using asymmetric
cryptography. They are widely used in many protocols for authentication purposes
and have already proven to be both very useful and secure.
Digital signatures are incorruptible and easily verifiable thanks to their usage of
asymmetric cryptography. Since they use asymmetric cryptography (and a private
key is only linked to a single person) digital signatures also have the quality of
non-repudiation, meaning they can be as legally binding as a normal signature. But
how can you verify the integrity of certain messages, or how could you ensure others
are able to verify the integrity of your message?
The answer to these questions is rather simple and can be explained with the image
above. The lock in the image above has 2 keys, the public key, which can only turn
counterclockwise, and a private key, which can only turn clockwise. We assume the
public key of each lock is widely available.
Let’s say Alice wants to send an unencrypted message to Bob, but Bob wants to
ensure Alice has sent the message. Alice puts the message in a box and then puts
the lock on the box. She then locks the lock using her own private key (from B to C).
After locking the box she sends it to Bob. Bob then receives the box and can verify
the integrity (and sender) of the message using Alice’s public key. If Alice’s public key
38
does not open the box the integrity of the message and box should be considered
violated.
If you encrypt (“lock”) something with your private key, anyone can decrypt it
(“unlock”), but this serves as a proof you encrypted it: it’s “digitally signed” by
you. — Panayotis Vryonis
If Alice wants to send an encrypted message to Bob, and only Bob should be able to
both decrypt the message and verify the identity of the sender, she would have to
take some extra steps. First of all Alice puts the message in a box and puts a lock on
the box, she then locks the box using her own private key (from B to C). She then
puts the (locked) box in a new box and puts a new lock on the box. She locks the new
lock using Bob’s public key (from B to A). After Alice is done she sends the box to
Bob. Once Bob receives the box he can open the otterbox with his private key, he can
then open the inner box with Alice’s public key. If the inner box can not be opened
with Alice’s public key the the integrity of the message and box should, yet again, be
considered violated.
Note that in reality both a signature generation algorithm, which takes a key and
data, and a signature verification algorithm, which takes a message and signature,
are needed to do the things explained above.
39
The usage in blockchains
While both asymmetric cryptography and digital signatures have been popular ever
since they were invented, they are probably most known for their implementations in
blockchains. Since blockchains are essentially widely distributed ledgers, it is of the
essence that the cryptography used is both reliable and functional.
Digital signatures are also widely used in cryptocurrencies. They can be used to sign
transactions more safely (offline) and are also used in multisignature contracts and
wallets. These multisignature contracts and wallets require digital signatures from
multiple (different) private keys before any action can be executed.
40
SHA-256
Presently SHA-256 is the most secure hashing function. This function expresses the
possible combinations or values that results from the given input data. SHA stands
for Secure Hashing Function, and 256 expresses the numerical quantity of the fixed
bit length. This means that the target is correct 256 bit, and as mentioned, Bitcoin
uses a 65-hexadecimal hash value.
Using the SHA-256 function makes it (nearly) impossible to duplicate a hash. That’s
because there are just too many combinations to try and process. Therefore, a
significant amount of computational work is required. So much so that Bitcoins are
no longer mined with personal computers. Presently, to mine, you need to rely on
Application-Specific Integrated Circuits or ASICs. Achieving this target has a
probability of 2^256. If you remember your exponents, you will deduce this is an
incredibly difficult variable to hit.
Furthermore, using this hash function means that such a hash is intentionally
computationally impractical to reverse. The intentional result is that it requires a
random or brute-force method to solve for the input.
A Case in Point
A hash rate is then the speed at which hashing operations take place during the
mining process. If the hash rate gets too high and miners solve the target too quickly,
this increases the potential for a collision. When that happens, the difficulty of the
hash needs adjusting accordingly. For example, at present, a Bitcoin is
mined/hashed about every 10 minutes.
Collision Resistance
Due to the complexity and sensitivity of SHA-256, reversing the hash sequence in an
effort to find the original input data is basically impossible. The difficulty of meeting
SHA-256 means that this hash is extremely secure because it is“collision resistant.”
Collision resistance expresses the likelihood of two different networks solving the
same hash at the same chance is minuscule.
41
Therefore, given the possible permutations of SHA-256, the probability of a collision
is negligible. Below is a comparison of two different hash outcomes. The first only
uses the single hash function (SHA-1), while the second uses the double hash
function (SHA-256). And as you can see, the double hash function produces a much
more complicated hash and as a consequence is far more collision resistant.
Here are a few examples of other cryptographic hash functions and when collision
resistance broke, and it will become evident why SHA-256 is currently the favored
hash:
If you want to more deep down into how SHA-256 works then you can explore the
below link
https://medium.com/bugbountywriteup/breaking-down-sha-256-algorithm-2ce61d86
f7a3
42
ECDSA
Elliptic Curve Digital Signature Algorithm or ECDSA is a cryptographic algorithm used
by Bitcoin to ensure that funds can only be spent by their rightful owners.
i) Private Key: A secret number, known only to the person that generated it. A
private key is essentially a randomly generated number. In Bitcoin, someone with the
private key that corresponds to funds on the block chain can spend the funds. In
Bitcoin, a private key is a single unsigned 256 bit integer (32 bytes).
ii) Public Key: A number that corresponds to a private key, but does not need to be
kept secret. A public key can be calculated from a private key, but not vice versa. A
public key can be used to determine if a signature is genuine (in other words,
produced with the proper key) without requiring the private key to be divulged. In
Bitcoin, public keys are either compressed or uncompressed. Compressed public
keys are 33 bytes, consisting of a prefix either 0x02 or 0x03, and a 256-bit integer
called x. The older uncompressed keys are 65 bytes, consisting of constant prefix
(0x04), followed by two 256-bit integers called x and y (2 * 32 bytes). The prefix of a
compressed key allows for the y value to be derived from the x value.
iii) Signature: A number that proves that a signing operation took place. A
signature is mathematically generated from a hash of something to be signed, plus a
private key. The signature itself is two numbers known as r and s. With the public key,
a mathematical algorithm can be used on the signature to determine that it was
originally produced from the hash and the private key, without needing to know the
private key. Resulting signatures are either 73, 72, or 71 bytes long (with approximate
probabilities of 25%, 50%, and 25%, respectively--although sizes even smaller than
that are possible with exponentially decreasing probability).
What is double-spending?
As the term suggests, double-spending means spending the same money twice.
With physical cash such as coins and notes, this simply isn’t possible and therefore
isn’t an issue.
43
Let’s look at this example: You go to Dmart and buy groceries worth Rs.100. You pay
in cash and hand over a Rs.100 note. As soon as the cashier puts the cash in the
register, you can’t re-spend it unless you physically steal it.
Digital money is different from cash. When you make a transaction with digital cash,
you are broadcasting the transaction to all the ‘nodes’ in the network (nodes are
computers that run the software on which the currency is supported). These nodes
need to receive and confirm the transaction, which takes time. Hence the problem:
what’s to stop someone copying a transaction and rebroadcasting it before it’s been
confirmed on the network?
To prove that no attempts to double-spend have occurred, the blockchain provides a
way for all nodes to be aware of every transaction. With bitcoin, all transactions are
publicly announced to all nodes. They can then agree on a single history of the order
in which they were received. Bitcoin’s solution to double-spending is that if the
majority of the nodes agree on which transaction was first to be received, later
attempts to double-spend are irrelevant.
Let us suppose you have 1 BTC and try to spend it twice. You made the 1 BTC
transaction to Alice. Again, you sign and send the same 1 BTC transaction to Bob.
Both transactions go into the pool of unconfirmed transactions where many
unconfirmed transactions are stored already. The unconfirmed transactions are
44
transactions which are not picked by anyone. Now, whichever transaction first got
confirmations and was verified by miners, will be valid. Another transaction which
could not get enough confirmations will be pulled out from the network. In this
example, transaction T1 is valid, and Alice will receive the bitcoin.
45