Module-3 Bit Coin Introduction
Module-3 Bit Coin Introduction
Dr. Poornima B V
Assistant Professor,
Computer Science and Engineering,
Sahyadri College of Engineering and Management,
Adyar, Mangalore-575007.
Email: [email protected]
1
Introducing Bitcoin
• Bitcoin is the first application of blockchain technology.
• In 2008, Bitcoin was introduced through a paper called, Bitcoin: A Peer-to-Peer
Electronic Cash System.
• Bitcoin is built on decades of cryptographic research such as the research in Merkle
trees, hash functions, public key cryptography, and digital signatures.
• The original idea behind Bitcoin was to develop an e-cash system which requires no
trusted third party and users can be anonymous.
• If regulations require Know Your Customer (KYC) checks and detailed information
about business transactions to facilitate regulatory process then it might be too
much information to share and as a result Bitcoin may not be attractive anymore to
some.
3
Bitcoin definition
• Bitcoin can be defined in various ways; it's a protocol, a digital currency, and a
platform.
• It is a combination of peer-to-peer network, protocols, software that facilitate
the creation and usage of the digital currency named bitcoin.
• Nodes in this peer-to-peer network talk to each other using the Bitcoin protocol.
• Note that Bitcoin with a capital B is used to refer to the Bitcoin protocol, whereas
bitcoin with a lowercase b is used to refer to bitcoin, the currency.
7
• Decentralization of currency was made possible for the first time with the
invention of bitcoin.
• Double spending problem arises when, for example, a user sends coins to two
different users at the same time and they are verified independently as valid
transactions.
• The double spending problem is resolved in Bitcoin by using a distributed ledger
(blockchain) where every transaction is recorded permanently and by
implementing transaction validation and confirmation mechanism.
Bitcoin – a bird's-eye view
First, let us see that what the main components of a Bitcoin network are. Bitcoin is
composed of the elements listed here.
1. Digital keys
2. Addresses
3. Transactions
4. Blockchain
5. Miners
6. The Bitcoin network
7. Wallets (client software)
12
Sending a payment to someone (Example)
• First, either the payment is requested from a user by sending his Bitcoin
address to the sender via email or some other means such as SMS, chat
applications or in fact any appropriate communication mechanism.
• The sender can also initiate a transfer to send money to another user. In both
cases, the address of beneficiary is required. As an example, the Blockchain
wallet is shown here where a payment request is created:
14
15
• The sender either enters the receiver's address or scans the QR code that has
the Bitcoin address, amount and optional description encoded in it.
• The wallet application recognizes this QR code and decodes it into something
like Please send <Amount> BTC to the Bitcoin address <receiver's Bitcoin
address>.
• This will look like as shown here with values: Please send 0.00033324 BTC to
the Bitcoin address 1JzouJCVmMQBmTcd8K4Y5BP36gEFNn1ZJ3.
16
• This is also shown in the screenshot presented here:
17
• This transaction is digitally signed using the private key of the sender
before broadcasting it. From a user's point of view, once the QR code is
decoded the transaction will appear similar to what is shown in the
following screenshot:
18
19
• At this stage, the transaction has been constructed, signed and sent out to the
Bitcoin network.
• This transaction will be picked up by miners to be verified and included in the
block.
• Also note that in the preceding screenshot, confirmation is pending for this
transaction.
• These confirmations will start to appear as soon as the transaction is verified,
included in the block, and mined.
20
21
Transaction flow visualization (Blockchain.info)
22
The payment transaction in the Bitcoin network can be divided into the following steps:
23
Summary
27
Private keys in Bitcoin
• Private keys are required to be kept safe and normally resides only on the owner's
side. Private keys are used to digitally sign the transactions proving the ownership of
the bitcoins.
• Private keys are fundamentally 256-bit numbers randomly chosen in the range.
• Any randomly chosen 256-bit number from 0x1 to 0xFFFF FFFF FFFF FFFF FFFF
FFFF FFFF FFFE BAAE DCE6 AF48 A03B BFD2 5E8C D036 4140 is a valid
private key.
• Private keys are usually encoded using Wallet Import Format (WIF) in order to
make them easier to copy and use. It is a way to represent the full size private key in a
different format. WIF can be converted into a private key and vice versa.
28
• The following is an example of a private key:
A3ED7EC8A03667180D01FB4251A546C2B9F2FE33507C68B7D9D4E1FA571419520
1
• When it is converted into WIF format it looks like this:
L2iN7umV7kbr6LuCmgM27rBnptGbDVc8g4ZBm6EbgTPQXnj1RCZP
29
Public keys in Bitcoin
• Public keys exist on the blockchain and all network participants can see it.
• Public keys are derived from private keys due to their special mathematical
relationship with the private keys.
• Once a transaction signed with the private key is broadcasted on the Bitcoin
network, public keys are used by the nodes to verify that the transaction has indeed
been signed with the corresponding private key. This process of verification proves
the ownership of the bitcoin.
• A public key is 256-bits in length. Public keys can be represented in an uncompressed
or compressed format.
• Public keys are fundamentally x and y coordinates on an elliptic curve.
30
Addresses in Bitcoin
• A bitcoin address is created by taking the corresponding public key of a private key
and hashing it twice, first with the SHA-256 algorithm and then with RIPEMD-160.
• The resultant 160-bit hash is then prefixed with a version number and finally encoded
with a Base58Check encoding scheme.
• The bitcoin addresses are 26-35 characters long and begin with digit 1 or 3.
• A typical bitcoin address looks like a string shown here:
1ANAguGG8bikEv2fYsTBnRUmx7QUcK58wt
31
• A Bitcoin address is a unique identifier used to receive Bitcoin payments. It acts
like a bank account number but is generated cryptographically.
• Format: A Bitcoin address is typically 26-35 characters long and consists of letters
and numbers.
Types of Addresses:
• P2PKH (Pay-to-PubKey Hash): Starts with 1 (e.g.,
1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa).
• P2SH (Pay-to-Script Hash): Starts with 3 (e.g.,
3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy).Bech32 (SegWit Address):
• Starts with bc1 (e.g., bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf0hl0).
• Private & Public Keys: A Bitcoin address is derived from a public key, which in turn
is generated from a private key. The private key must be kept secure, as it allows
access to the Bitcoin associated with that address.
• Use: A Bitcoin address is used to send and receive BTC. Once used, it’s
recommended to generate a new address for better privacy.
• This is also commonly encoded in a QR code for easy distribution. The QR code of
the preceding bitcoin address is shown in the following screenshot:
34
Vanity addresses
• As bitcoin addresses are based on base-58 encoding, it is possible to generate
addresses that contain human readable messages. An example is shown as
follows:
A vanity address in Bitcoin is a type of Bitcoin address that includes a custom, user-defined pattern or
text at the beginning of the address. This pattern can be anything you choose, like a name, word, or any
combination of characters, making the address more recognizable or personalized.
• Vanity addresses are generated using a purely brute-force method.
• An example of a paper wallet with vanity address is shown in the following
screenshot:
Multi-signature addresses
• As the name implies, these addresses require multiple private keys. In practical
terms, it means that in order to release the coins a certain set of signatures is
required. This is also known as M-of-N MultiSig.
• Here M represents threshold or the minimum number of signatures required
from N number of keys to release the bitcoins.
38
• Inputs can be thought of as coins being spent that have been created in a
previous transaction and outputs as coins being created.
• If a transaction is to send coins to some other user (a bitcoin address), then it
needs to be signed by the sender with their private key and a reference is also
required to the previous transaction in order to show the origin of the coins.
• Transactions are not encrypted and are publicly visible in the blockchain. Blocks
are made up of transactions and these can be viewed using any online
blockchain explorer.
The transaction life cycle
1. A user/sender sends a transaction using wallet software or some other
interface.
2. The wallet software signs the transaction using the sender's private key.
3. The transaction is broadcasted to the Bitcoin network using a flooding algorithm.
40
4. Mining nodes (miners) who are listening for the transactions verify and include
this transaction in the next block to be mined. Just before the transactions are
placed in the block they are placed in a special memory buffer called transaction
pool.
5. Mining starts, which is a process by which the blockchain is secured and new
coins are generated as a reward for the miners who spend appropriate
computational resources.
6. Once a miner solves the PoW problem it broadcasts the newly mined block to
the network.
• The nodes verify the block and propagate the block further, and confirmations
start to generate.
• Finally, the confirmations start to appear in the receiver's wallet and after
approximately three confirmations, the transaction is considered finalized and
confirmed.
• However, three to six is just a recommended number; the transaction can be
considered final even after the first confirmation.
• The key idea behind waiting for six confirmations is that the probability of
double spending is virtually eliminated after three confirmations.
42
Transaction life-cycle in Blockchain
43
Transaction fee
• The fee charged is dependent upon the size and weight of the transaction.
• Transaction fees are calculated by subtracting the sum of the inputs and the sum of the
outputs.
45
• A transaction with a higher fee will be picked up sooner by the miners.
• There are different rules based on which fee is calculated for various types of actions,
such as sending transactions, inclusion in blocks, and relaying by nodes.
• Fees are not fixed by the Bitcoin protocol and are not mandatory; even a transaction
with no fee will be processed in due course but may take a very long time.
• This is however no longer practical due to the high volume of transactions and
competing investors on the Bitcoin network, therefore it is advisable to provide a fee
always.
46
• The time for transaction confirmation usually ranges from 10 minutes to over 12
hours in some cases.
• If the network is very busy then naturally transactions will take longer to process and
if you pay a higher fee then your transaction is more likely to be picked by miners first
due to additional incentive of the higher fee.
47
Transaction pools
• Also known as memory pools, these pools are basically created in local memory
(computer RAM) by nodes in order to maintain a temporary list of transactions
that are not yet confirmed in a block.
• Transactions are included in a block after passing verification and based on their
priority.
The transaction data structure
• A transaction at a high level contains metadata, inputs, and outputs. Transactions
are combined to create a block.
The script language
• Bitcoin uses a simple stack-based language called script to describe how bitcoins
can be spent and transferred.
• It is not Turing complete and has no loops to avoid any undesirable effects of
long-running/hung scripts on the Bitcoin network.
• This scripting language is based on a Forth programming language like syntax and
uses a reverse polish notation in which every operand is followed by its
operators. It is evaluated from the left to the right using a Last In, First Out (LIFO)
stack.
• Scripts use various opcodes or instructions to define their operation. Opcodes are
also known as words, commands, or functions.
Types of transactions
Types of transactions
• Standard transactions are evaluated using IsStandard() and IsStandardTx() tests
and only standard transactions that pass the test are generally allowed to be
mined or broadcasted on the Bitcoin network.
• Pay to Public Key Hash (P2PKH): P2PKH is the most commonly used transaction
type and is used to send transactions to the bitcoin addresses. The format of the
transaction is shown as follows:
ScriptPubKey: OP_DUP OP_HASH160 <pubKeyHash>
OP_EQUALVERIFY OP_CHECKSIG
ScriptSig: <sig> <pubKey>
• The ScriptPubKey and ScriptSig parameters are concatenated together and
executed.
54
• MultiSig (Pay to MultiSig): M-of-N MultiSig transaction script is a complex type of
script where it is possible to construct a script that required multiple signatures to
be valid in order to redeem a transaction. Various complex transactions such as
escrow and deposits can be built using this script.
The template is shown here:
ScriptPubKey: <m> <pubKey> [<pubKey> . . . ] <n> OP_CHECKMULTISIG
ScriptSig: 0 [<sig > . . . <sign>]
• Pay to Pubkey: This script is a very simple script that is commonly used in coin
base transactions. It is now obsolete and was used in an old version of bitcoin. The
public key is stored within the script in this case, and the unlocking script is
required to sign the transaction with the private key.
The template is shown as follows:
<PubKey> OP_CHECKSIG
55
• Null data/OP_RETURN: This script is used to store arbitrary data on the blockchain for a
fee. The limit of the message is 40 bytes. The output of this script is unredeemable
because OP_RETURN will fail the validation in any case. ScriptSig is not required in this
case.
The template is very simple and is shown as follows:
OP_RETURN <data>
56
A P2PKH script execution
57
Coinbase transactions
• As defined in the Bitcoin core developer guide, contracts are basically transactions that
use the Bitcoin system to enforce a financial agreement.
• This is a simple definition but has far-reaching consequences as it allows users to design
complex contracts that can be used in many real-world scenarios.
• Contracts allow the development of a completely decentralized, independent, and
reduced risk platform.
• Various contracts, such as escrow, arbitration, and micropayment channels, can be built
using the Bitcoin scripting language.
The structure of a block
• As shown in the following diagram, blockchain is a chain of blocks where each
block is linked to its previous block by referencing the previous block header's
hash.
• This linking makes sure that no transaction can be modified unless the block that
records it and all blocks that follow it are also modified.
• The first block is not linked to any previous block and is known as the genesis
block
A visualization of the blockchain, block, block header, transactions and scripts
• The preceding diagram shows a high-level overview of the Bitcoin blockchain.
• On the left-hand side blocks are shown starting from top to bottom. Each block
contains transactions and block headers which are further magnified on the right-
hand side.
• On the top, first, block header is expanded to show various elements within the
block header.
• Then on the right-hand side the Merkle root element of the block header is
shown in magnified view which shows that how Merkle root is calculated.
The genesis block
70
71
72
Mining
73
74
Proof of Work (PoW)
• This is a proof that enough computational resources have been spent in order to
build a valid block.
• PoW is based on the idea that a random node is selected every time to create a new
block.
• In this model, nodes compete with each other in order to be selected in proportion
to their computing capacity. The following equation sums up the PoW requirement in
bitcoin:
• H ( N || P_hash || Tx || Tx || . . . Tx) < Target
• Where N is a nonce, P_hash is a hash of the previous block, Tx represents
transactions in the block, and Target is the target network difficulty value. This
means that the hash of the previously mentioned concatenated fields should be less
than the target hash value.
75
The Bitcoin network
• The Bitcoin network is a peer-to-peer network where nodes exchange transactions and
blocks.
• There are different types of nodes on the network. There are two main types of nodes,
full nodes and SPV nodes.
• Full nodes, as the name implies, are implementations of Bitcoin core clients performing
the wallet, miner, full blockchain storage, and network routing functions.
• Simple Payment Verification (SPV) nodes or lightweight clients perform only wallet and
network routing functionality.
• The latest version of Bitcoin protocol is 70015 and was introduced with Bitcoin core
client 0.13.2.
76
• The Bitcoin network is identified by its different magic values. A list is shown as
follows:
85
• Bitcoin wallets are the tools that allow you to interact with the Bitcoin blockchain.
They are essential for:
• Storing Bitcoin securely.
• Sending and receiving Bitcoin by signing transactions.
• Managing multiple addresses for privacy.
• Tracking balances and transaction history.
• Providing security for your private keys.
• Backing up and recovering your wallet in case of device loss or damage.
Non-deterministic wallets
• These wallets contain randomly generated private keys and are also called just a bunch
of key wallets.
• The Bitcoin core client generates some keys when first started and generates keys as and
when required.
• Managing a large number of keys is very difficult and an error-prone process can lead to
theft and loss of coins.
• Non-deterministic wallet is a type of cryptocurrency wallet that generates a new
private key each time a transaction is made.
• This adds an extra layer of security, as the private keys are not reused, making it harder
for hackers to gain access to the wallet.
• When a user creates a non-deterministic wallet, a random number generator is used to
generate private keys. Each time a new transaction is initiated, a new private key is
created, providing additional security for the user’s funds.
87
Deterministic wallets
In this type of wallet, keys are derived out of a seed value via hash functions.
This seed number is generated randomly and is commonly represented by human-
readable mnemonic code words.
Mnemonic code words are defined in BIP 39, a Bitcoin improvement proposal for
mnemonic code for generating deterministic keys. This BIP is available at
https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki.
This phrase can be used to recover all keys and makes private key management
comparatively easier.
Hierarchical Deterministic wallets
89
Hardware wallets
90
Brain wallets
• The master private key can also be derived from the hash of passwords that are
memorized.
• The key idea is that this passphrase is used to derive the private key and if used in HD
wallets, this can result in a full HD wallet that is derived from a single memorized
password
• This method is prone to password guessing and brute force attacks but techniques such as
key stretching can be used to slow down the progress made by the attacker.
91
Online wallets
• Online wallets, as the name implies, are stored entirely online and are provided as a
service usually via the cloud.
• They provide a web interface to the users to manage their wallets and perform various
functions such as making and receiving payments.
• They are easy to use but imply that the user trusts the online wallet service provider.
• An example of online wallet is GreenAddress
92
Mobile wallets
93
94
Wallet Type Description Security Backup Example
96
Generally, these solutions work by following these steps:
1.The sales person enters the amount of money to be charged in currency, for example,
US Dollars
2.Once the value is entered in the system the terminal prints a receipt with QR code on it
and other relevant information such as amount.
3.The customer can then scan this QR code using their mobile Bitcoin wallet to send the
payment to the Bitcoin address of the seller embedded within the QR code
4.Once the payment is received on the designated Bitcoin address, a receipt is printed out
as a physical evidence of sale
97
Innovation in Bitcoin
Bitcoin has undergone many changes and still evolving into a more and more
robust and better system by addressing various weaknesses in the system.
These improvement proposals are usually made in the form of BIPs or
fundamentally new versions of Bitcoin protocols resulting in a new network
altogether.
Bitcoin Improvement Proposals (BIPs)
• Standard BIP: Used to describe the major changes that have a major impact on the
Bitcoin system, for example, block size changes, network protocol changes, or
transaction verification changes.
• Process BIP: A major difference between standard and process BIPs is that standard
BIPs cover protocol changes, whereas process BIPs usually deal with proposing a
change in a process that is outside the core Bitcoin protocol. These are implemented
only after a consensus among bitcoin users.
• Informational BIP: These are usually used to just advise or record some
information about the Bitcoin ecosystem, such as design issues.
99
Advanced protocols
• what are the various advanced protocols that have been suggested or
implemented for improving the Bitcoin protocol.
• Transaction throughput is one of the critical issues that need to be addressed.
Inherently, the Bitcoin network can only process from approximately 3 to 7
transactions per second which is a tiny number as compared to other financial
networks, such as Visa which can process approximately, on average, 24,000
transactions per second.
• PayPal can process approximately 200 transactions per second whereas Ethereum
can process up to on average 20.
• As Bitcoin Network grew exponentially over the last few years, these issues
started to grow even further.
• The difference of processing speed is also shown below in a graph which shows
the scale of difference between Bitcoin and other networks' transaction speeds.
Bitcoin investment and buying and selling bitcoins
• There are many online exchanges where users can buy and sell bitcoins.
• This is a big business on the internet now and it offers bitcoin trading, spread betting,
margin trading, and various other choices.
• Traders can buy bitcoins or trade by opening long or short positions to make a profit
when bitcoin's price goes up or down.
• Several other features, such as exchanging bitcoins for other virtual currencies, are also
possible, and many online bitcoin exchanges provide this function.
• Advanced market data, trading strategies, charts, and relevant data to support traders
is also available.
• An example is shown from CEX (https://cex.io) here. Other exchanges offer similar types
of services.
Bitcoin installation
106
Setting up a Bitcoin node
107
• Bitcoin-qt
108
Setting up a Bitcoin node
Setting up the source code
• The Bitcoin source code can be downloaded and compiled if users wish to
participate in the Bitcoin code or for learning purpose. The git command can be
used to download the Bitcoin source code:
$ sudo apt-get install git
$ mkdir bcsource
$ cd bcsource
$ git clone https://github.com/bitcoin/bitcoin.git
Cloning into 'bitcoin'...
remote: Counting objects: 78960, done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 78960 (delta 0), reused 0 (delta 0), pack-reused 78957
Receiving objects: 100% (78960/78960), 72.53 MiB | 1.85 MiB/s, done.
Resolving deltas: 100% (57908/57908), done.
Checking connectivity... done.
111
• Change the directory to bitcoin:
$ cd bitcoin
• After the preceding steps are completed, the code can be compiled:
$ ./autogen.sh
$ ./configure.sh
$ make
$ sudo make install
112
Starting up a node in testnet
• The bitcoin node can be started in the testnet mode if you want to test the Bitcoin
network and run an experiment. The command line to start up testnet is as follows:
bitcoind --testnet -daemon
bitcoin-cli –testnet <command>
bitcoin-qt --testnet
113
Starting up a node in regtest
• Bitcoin programming is a very rich field now. The Bitcoin Core client exposes
various JSON RPC commands that can be used to construct raw transactions and
perform other functions via custom scripts or programs.
• Also, the command-line tool, Bitcoin-cli, is available, which makes use of the
JSON-RPC interface and provides a rich toolset to work with Bitcoin.
• Various libraries are available for bitcoin programming.
1.Libbitcoin: Available at https://libbitcoin.dyne.org/ and provides powerful
command-line utilities and clients
2.Pycoin: Available at https://github.com/richardkiss/pycoin, is a library for
Python
3.Bitcoinj: This library is available at https://bitcoinj.github.io/ and is
implemented in Java
118