Intro BlockChain

A brief introduction to blockchain.

“Bitcoin is exciting because it shows how cheap it can be. Bitcoin is better than currency in that you don’t have to be physically in the same place and, of course, for large transactions, currency can get pretty inconvenient,” Bill Gates, Co-founder of Microsoft, investor and philanthropist.

Applications

  • Goods transfer
    • Supply chain ?
  • Digital media transfer
    • Sale of art
  • Remote services delivery
    • Travel and tourism ?
  • Platform for decentralized business logic
    • Moving computing to data sources ?
  • Distributed intelligence
    • Education credentialing
  • Distributed resources
    • Power generation and distribution(I worked for a this kind of private chain)
  • Crowd funding
    • Startup fund raising
  • Crowd operations
    • Electronic voting
  • Identity management
    • One ID for all your life’s functions
  • Government public records and open governing
  • Inclusive economy
    • Enable a person in a remote corner of the world to partake in a democratic process.

Two major contributions of cryptocurrency Bitcoin

  • A continuously working digital currency system
  • A model for autonomous decentralized application technology called the blockchain.

What is a blockchain?

Blockchain is about enabling peer to peer transaction in a decentralized network. Establishing trust among unknown peers. Recording the transaction in an immutable distributed ledger.

How do we establish trust among the peers in a decentralized system?

  • Validation, Verification, Consensus, and Immutable Recording.
  • Record the transaction in a distributed ledger of blocks.
    • I’m lending Amy $10,000. This is one single peer to peer transaction. We both make a note of it on a ledger. What if I change my entry from 10,000 to 11,000? Alternatively, Amy changes hers from 10,000 to 1,000. To prevent this trust violation, we need to seek the help of people around us, Lisa, Allison, and Francis. Provide all of them a valid copy of this ledger.
  • Create a tamper-proof record of blocks, chain of blocks.
  • Implement a consensus protocol for agreement on the block to be added to the chain.

https://bitcoin.org/bitcoin.pdf

Structure of a blockchain

  • Transaction: The basic element of the Bitcoin Blockchain. Transactions are validated and broadcast.
  • Block: Many transactions form a block.
  • Chain: Many blocks form a chain through a digital data link.
  • Consensus: Blocks go through a consensus process, to select the next block that will be added to the chain. Chosen block is verified, and added to the current chain.
  • Miner: Validation and consensus process are carried out by special peer nodes called miners. These are powerful computers executing software defined by the blockchain protocol.

UTXO / Transaction / Block / Wallet

Unspent Transaction Output
The set of all UTXOs in a bitcoin network collectively defined the state of the Bitcoin Blockchain.
UTXO’s are referenced as inputs in a transaction. UTXO’s those are also outputs generated by a transaction. All of that UTXO’s is in a system, are stored by the participant nodes in a database.

  • The structure of a given UTXO
    • A unique identifier of the transaction that created this UTXO
    • An index or the position of the UTXO in the transaction output list
    • A value or the amount
    • An optional script, the condition under which the output can be spent
  • The structure of transaction (Tx): UTXO defines the inputs and outputs of a transaction.
    • A reference number of the current transaction
    • References to one no more input UTXOs
    • References to one or more output UTXOs newly generated by the current transaction
    • The total input amount and output amount
  • The structure of block
    • A header of information about the block
      • Current block hash (block hash computation)
      • The previous block hash (the link between the blocks)
      • The Nonce
      • The next block hash (if exists)
    • A set of valid transaction (a block is verified an algorithmic-ally agreed upon by the miners)

      Wallet: Walletapplications provide the basic interface to transfer value through the Bitcoin blockchain.

Scripts for conditional transfer of values

Bitcoin supports an optional and special feature called scripts for conditional transfer of values.
Ethereum Blockchain extended the scripting feature into a full-blown code execution framework called smart contract.

A smart contract provide capability of code execution for embedding business logic on the blockchain.

  • Type one deals with the coins in cryptocurrency currency chain. Example, Bitcoin.
  • Type two supports cryptocurrency and a business logic layer supported by code execution. Example, ethereum.
  • Type three involves no currency but supports software execution for business logic. Example, The Linux Foundation’s Hyperledger.

The classification blockchains based on access limits

With the addition of code execution, comes the serious consideration about public access to the blockchain

  • Public blockchain
    • Bitcoin is a fantastic example. Transaction blocks and the blockchain are publicly observable even though participants are anonymous. It is open-source. You can also create new coin digital currency by modifying the Bitcoin code.
  • Private blockchain
    • Access to the blockchain is limited to selected participants for example, those participants within an organization.
    • This restriction helps in simplifying the normal operations such as block creation and contingence model.
  • Permissioned blockchain, also called consortium blockchain. It is meant for a consortium of collaborating parties to transact on a blockchain for ease of governance, provenance, and accountability for example, a consortium of all automobile companies or healthcare organizations. Permissioned blockchain has the benefits of a public blockchain with allowing only users with permission to collaborate and transact.

Operations of bitcoin blockchain

Operations in the decentralized network are the responsibility of the peer participants and their respective computational nodes.
For example, laptop, desktop, and server racks.
These operations include:

  • Validation transactions
  • Gathering the transactions for a block
  • Broadcasting the ballot transactions in the block
  • Consensus on the next block creation
  • Chaining the blocks to form an immutable record.

Two major roles for the participants.

  • Participants that initiate transfer of value by creating a transaction.
  • Miners (additional participants): Who pick on added work or computation to:
    • Broadcast transaction
    • Verify transactions
      • Transaction validation is carried out independently by all miners.
      • The process involves validation of more than 20 criteria, including size, syntax, et cetera. Some of these criteria are:
        • Referenced Input UTXOs are valid
        • Reference output UTXOs are correct
        • Reference input amount and output amount matched sufficiently
      • (Rejected Txs) Invalid transactions are rejected and will not be broadcast
      • (Valid Tx – Pool of unconfirmed Txs) All the valid transactions are added to a pool of transactions
      • Miners select a set of transaction from this pool to create a block (This creates a challenge. If every miner adds the block to the chain, there will be many branches to the chain, resulting in inconsistent state. As the blockchain is a single consistent linked chain of flux. We need a system to overcome this challenge)
    • Compete to claim the right to create a block
      • Miners compete to solving a puzzle to determine who earn the right to create the next block (Once a miner solves the puzzle, the announcement is broadcast to the network and the block is also broadcast to the network)
    • Work on reaching consensus by validating the block
      • The algorithm for consensus is called proof of work protocol
      • Transaction zero: Index zero of the confirmed block is created by the miner of the block. It has a special UTXO and does not have any input UTXO. It is called the coinbase transaction that generates a minor’s fees for the block creation
      • Other participant verify the new block. Participants reach a consensus to add a new block to the chain. This new block is added to their local copy of the blockchain. Thus, a new set of transactions are recorded and confirmed
    • Broadcasting the newly created block
    • Confirming transactions

Ethereum supports smart contracts and of virtual machine on which smart contracts execute.
Smart contracts in turn enable decentralized application that accomplish more than a transfer of value.
Efficient automation of decentralized application such as supply chain.

Smart Contract: A piece of code deployed in the blockchain node.

  • Smart contracts add a layer of logic and computation to the trust infrastructure supported by the blockchain.

    An EVM provides a run anywhere obstruction layer for the contract code.

  • A smart contract is translated into EVM byte code, and then, deployed on the Ethereum Virtual Machine, EVM. Every node will host the same smart contract codes on the EVM.

Ethereum Structure

Account: The originator and the target of a transaction

  • A transaction directly updates the account balances as opposed to maintaining the state such as in the bitcoin UTXOs.
  • It allows for transmit of value and messages and data between the accounts that may result in the state transitions.
  • These transfers are implemented using transactions
  • Every account has a coin balance

Two types of accounts:

  • Externally Owned Accounts (EOA)
    • Controlled by private keys
    • An EOA is needed to participate in the Ethereum network
    • It interacts with the blockchain using transactions
  • Contract Accounts (CA)
    • Controlled by the Code
    • Can be activated only by an EOA
    • A CA represents a smart contract

Ethereum Transaction structure:

  • Recipient: The recipient of the message
  • Digital signature of sender authorizing transfer
  • Amount of Wei (to transfer)
  • Message to a contract: An optional data field or payload that contains a message to a contract
  • STARTGAS A value representing the maximum number of computational steps the transaction is allowed.
  • Gas Price: A value representing the fee sender is willing to pay for the computations.

Ethereum Block structure:

  • header
  • Transaction
  • runner-up block headers

Ethereum Operations

The participant node can send transaction for Ether transfer or it can send transaction to invoke a smart contract code or both

  • Ethereum Node: A computational system representing a business entity or an individual participant

  • Ethereum full node: Hosts the software needed for transaction initiation, validation, mining, block creation, smart contract execution and the Ethereum Virtual Machine, EVM

  • Miner Node: Receive, verify, gather and execute transactions

    • The in-work smart contract code are executed by all miners
    • Validated transactions are broadcast and gathered for block creation
    • The consensus protocol used is a memory-based rather than a CPU-based proof of work
  • When the target address in a transaction is a smart contract, the execution code corresponding to the smart contract is activated and executed on the EVM

  • (Input) needed for this execution is extracted from the (payload field of the transaction)

  • (Current state of the smart contract) is the values of the variables defined in it. The state of the smart contract may be updated by this execution

  • (Receipts) Results of this execution is told in the receipts

A blockchain maintains both the state hash and the receipt hash

  • (Transaction validation) involves checking the time-stamp and the nonce combination to be valid and the availability of sufficient fees for execution

Incentive Model

transaction

One ether = 1,000,000,000,000,000,000 wei (1018). The smallest denomination of cryptocurrency.

Gas Points: are used to specify the fees inside of Ether, for ease of computation using standard values

  • Gas points allow for cryptocurrency independent valuation of the transaction fee and computation fees
  • Ethereum has specified gas points for each type of operation
  • Mining process computes gas points required for execution of a transaction
  • If the fee specified and the gas point in the transaction are not sufficient, it is rejected (This is similar to mailing a letter with insufficient postage)
  • If there is any amount left over after the execution of a transaction, it is returned to the originating account

block

Gas Limit: The amount of gas points available for a block to spend
$\frac{Gas Limit}{Tx Fee} = nTx$; (plain Ether transactions)
If we add smart contract transactions also into this block, that usually requires more gas, and the number of transactions for this block will likely be lower
Gas spent is the actual amount of gas spent at the completion of the block creation

miner

The proof of work puzzle winner, miner that creates a new block, is incentivized with:

  • The base fees of three Ethers, The transaction fees in Ethereum blockchain
  • The fees, gas points for execution of a smart contract transactions
    Ommers: Miners solve the puzzle, but didn’t win the block
  • The blocks created by them are called Ommer Blocks
  • These are added as Ommer Blocks, or side blocks, to the main chain.
  • Ommer miners also get a small percentage of the total gas points as a consolation and for network security

Public-Key Cryptography

Key Pair

Symmetric Key

  • Ceasar Encryption

    Symmetric Key Issues:

  • It is easy to derive the secret key from the encrypted data
  • The key distribution, how do you pass the key to the participant transacting

A popular implementation of public key, private key is the Rivest Shamir Adleman (RSA) algorithm
Elliptic Curve Cryptography, ECC family of algorithms is used in the bitcoin as well as an Ethereum block chain for generating the key pair

Hashing

What is hashing? A hash function or hashing transforms and maps an arbitrary length of input data value to a unique fixed length value

  • Input data can be a document, tree data, or a block data

Two basic requirements of a hash function:

  • The algorithm chosen for the hash function should be a one-way function (no one can derive the original items hashed from the hash value)
  • It should be collision free, or exhibit extremely low probability of collision (To make sure that the hash value uniquely represents the original items hashed)
    • Choosing a strong algorithm such as secure hash (The common functions are SHA-3, SHA-256 and Keccak.)
    • Using appropriately large number of bits in the hash value (most common hash size now is 256 bits)

Hash value space: ex: how good is 256 bits hash

When is a simple hash used? When we have a fixed number of items to be hashed, such as the items in a block header, and we are verifying the composite block integrity and not the individual item integrity.

When the number of items differ from block to block, for example, number of transactions, number of states, number of receipts, we use the tree structure for computing the hash

  • Note that the state is a variable that may be modified by a smart contract execution, and the result of the execution may be returned in a receipt
  • Tree structure helps the efficiency of repeated operations, such as transaction modification and the state changes from one block to the next
  • Mekle tree hash

Merkle tree hash is also used for computing the state root hash, since only the hash of the chained states from block to block have to be re-computed

  • Smart contract execution in Ethereum results in state transitions. Every state change requires state root hash re-computation. Instead of computing hash for the entire set of states, only the affected path in the Merkle tree needs to be re-computed.

    It is also used for receipt hash root:

  • If any transaction is to be verified, only one path to the tree has to be checked. You don’t have to go through the entire set of transactions

In Ethereum, hashing functions are used for:

  • Generating account addresses
  • Digital signatures
  • Transaction hash
  • State hash
  • Receipt hash
  • Block header hash

Transaction Integrity

To manage the integrity of a transaction we need:

  • Secure a unique account address. We need a standard approach to uniquely identify the participants in the decentralized network
  • Authorization of the transaction by the sender through digital signing
  • Three, verification that the content of that transaction is not modified

The address of the accounts

  • A 256-bit random number is generated, and designated as the private key. Kept secure and locked using a passphrase
  • An ECC algorithm is applied to the private key, to get a unique public key. This is the private public key pair
  • Then a hashing function is applied to the public key to obtain account address. The address is shorter in size, only 20 bytes or 160 bits

Transaction Verification

  • Find the hash of the data fields of the transaction
  • Encrypt that hash using the private key of the participant originating the transaction. Thus, digitally signing the transaction to authorize and making the transaction non-repudiable
  • This hash just added to the transaction. It can be verified by others decryiptng it using the public key of the sender of the transaction, and recomputing the hash of the transaction. Then, compare the computed hash, and the hash received at the digital signature
  • If that is a match, accept the transaction. Otherwise, reject it
  • For the complete transaction verification, the timestamp, nons, account balances, and sufficiency of fees are also verified

Versatile Hash

  • First, compute the hash of the block header elements that is a fixed value, and a nonce that is a variable
  • If hash value is less than 2 par 128 for bitcoin, and less than function of difficulty for ethereum, the puzzle has been solved
  • If it has not been solved, repeat the process after changing the nonce value

Exception Satisfactorily Handling

Double Spending

Double spending is reusing digital assets intentionally or inadvertently
Ex:

  • More than one miner solves the consensus puzzle where it close in time to each other
    • BTC:
      • Bitcoin protocol allows this chain split or two chains for the next cycle. One led by each of the competing blocks
      • The probability that the next block will happen at the same time in both these chains is extremely low
      • So the winner of the next cycle for block creation consolidates one of the chains and that chain becomes the accepted chain
      • In this case, the newest block is added to the main chain. Now this chain is the longest and the valid main chain
      • The transaction in the other blocks are returned to the unconfirmed pool
    • ETH:
      • That are Runner-up blocks are maintained for six more blocks after they were added
      • Ex: a blockchain with two blocks one at the height, 4567, another one at a height, 4557
      • The one deeper inside the chain is more trustworthy than the one newly added
  • More than one transaction references as input the same digital asset
    • BTC: Allow the first transaction that reference the digital asset and reject the rest of the transaction that reference the same digital asset
    • Ethereum: A combination of account number and a global nonce is used to address the doublet spending issue
      • Every time a transaction is initiated by an account, a global nonce is included in the transaction
      • After that, the nonce is incremented. Time stamp on the nonce in the transaction should be unique and verified to prevent any double use of digital asset

Fork

DAO: Decentralized Autonomous Organization
EIP: Ethereum Improvement Proposals

Author: Yuzu
Link: https://kamisu66.com/2022/06/12/Intro-BlockChain/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.