Digital Currencies & Blockchain

Lecture 2

david@fumbi.network

  • Blocks
     
  • Transactions
     
  • Bitcoin Script

Bitcoin Protocol 

  • 40% of Grade
  • Deadline: 30.11. 2021

  • Smart Contract Platform Comparisons
    • Major protocols, interoperability, languages, scalability,

  • Hard money vs "modern" money - your opinion on it

  • Bitcoin vs Ethereum (comparison from tech perspective)

  • Analysis of a DeFi protocol of your choice
    • Aave, Compound, Uniswap


Assignment Topics:

  • How does Bitcoin transaction work?
     
  • How mining works?
     
  • What is UTXO?

Questions:

Blocks

Number of transactions: How many transactions the block contains
Height: The number of the block in the blockchain
Block Reward: The amount rewarded to the miner for computing the block
Timestamp: The time the block was added
Mined by: Who mined the block (Can appear anonymous)
Merkle Root: The combined hash of all the transactions in this block
Previous Block: The previous block’s hash
Difficulty: A value used to calculate how difficult the block is to solve (This value is adjusted every 2016 blocks to aim for » 10 minutes computation time)
Size: The total size of the block
Version: Signals to the rest of the network about intentions to update
Nonce: A value that is changed to find a solution for the block

 

Blocks II.

Block header

Genesis Block

Coinbase Transaction

Transactions

  • The fundamental building block of a bitcoin transaction is a transaction output.
  • UTXO --> indivisible chunks of bitcoin currency
  • UTXO set - The collection of all UTXOs
    • grows as new UTXO is created and shrinks when UTXO is consumed.
  • To receive bitcoins mean:
    • wallet has detected a UTXO that can be spent with one of the keys controlled by that wallet
  • Wallet calculates balance by scanning blockchain and aggregating the value of any UTXO the wallet can spend .
    • via DB service to store a quick reference set of all the UTXO they can spend with the keys they control.

Transactions I.

  • A transaction consumes previously recorded unspent transaction outputs and creates new transaction outputs that can be consumed by a future transaction.
  • This way, chunks of bitcoin value move forward from owner to owner in a chain of transac‐ tions consuming and creating UTXO
  • Only exception is COINBASE transaction --> first transaction in each block.
    • placed there by the “winning” miner and creates brand-new bitcoin payable to that miner as a reward for mining.
    • does not consume UTXO; instead, it has a special type of input called the “coinbase.”
    • This is how bitcoin’s money supply is created during the mining process
      • ​What comes first - Input or Output? Chicken or Egg?

Transactions II.

UTXO


Unspent Transaction Output
 

  • An amount of bitcoin, denominated in satoshis, the smallest bitcoin unit
  • A cryptographic puzzle that determines the conditions required to spend the output
    • a.k.a locking script, a witness script, or a scriptPubKey

UTXO consists of:

"vout":
[ {
"value": 0.01500000,
"scriptPubKey": "OP_DUP OP_HASH160 ab68025513c3dbd2f7b92a94e0581f5d50f654e7 OP_EQUALVERIFY
        OP_CHECKSIG"
}, 
{
"value": 0.08450000,
"scriptPubKey": "OP_DUP OP_HASH160 7f9b1a7fb68d60c536c2fd8aeaa53a8f3cc025a8 OP_EQUALVERIFY OP_CHECKSIG",
} ]

UTXO - Advantages 

  • Simplicity: Spending a UTXO is all or nothing. Since UTXOs are uniquely referenced and completely consumed upon spending, there is no chance for a transaction to be replayed.
     
  • Transactions can be trivially verified in parallel. It is impossible for two transactions to affect the same UTXO. This is due to the stateless nature of UTXO transactions. Transactions do not refer to any input outside of the UTXOs consumed and corresponding signatures.
     
  • Privacy-preserving behavior is encouraged in the UTXO model. Users are encouraged to generate a new address for every incoming transaction including change addresses. By using a new address each time, it is difficult to definitively link different coins to a single owner.

UTXO - Disadvantages 

  • UI/UX considerations are tricky. Users tend to think of accounts when they conceptualize their money. Since there is no concept of an account within Bitcoin, it is up to the wallet provider to manage a potential set of addresses and sum the corresponding balances. Doing so in a privacy-preserving way may require running a local node.
     
  • Smart contract abilities are quite limited in a UTXO model. Each UTXO has spending criteria that dictates spending conditions. This can require signatures from multiple parties, but there is little ability to reference outside the state such as oracles.

 

Transacations

Transacations II.

Transacations III.

Transacations IV.

Transacations V.

  • Compensate the bitcoin miners for securing the network
    • making it economically infeasible for attackers to flood the network with transactions
       
  • Fees also serve as a security mechanism themselves
  • Most wallets calculate and include transaction fees automatically
    • more inputs --> higher fee
  • Calculated based on the size of the transaction in kilobytes, not the value of the transaction in bitcoin
  • Fee market

Transaction fees:

  • Bitcoin Script: 
    • A (simple) programming language
    • "script": an executable program - a list of instructions
    • A transaction is validated if the respective script is successfully executed
       
  • The constituents of each script can be distinguished into two basic types:
    • Opcodes (commands/functions): begin with prefix 'OP_', e.g., 'OP_HASH160'
    • Data: store data related to transactions - appear within '<.>', e.g., '<pubKeyHash>'

Bitcoin Script

  • Script is a Forth-like reverse polish notation, stack-based execution language, which is not Turing-complete and does not include loops.
     
  • Forth is an imperative stack-based computer programming language and environment.
     
  • Some applications of Forth
     
  • Small ebook that helps you learn Forth.

Bitcoin Script II.

  • uses a data structure called a stack.
  • very simple data structure that can be visualized as a stack of cards.
  • A stack allows two operations:
    • Push adds an item on top of the stack.
    • Pop removes the top item from the stack.
  • Operations on a stack can only act on the topmost item on the stack.
  • A stack data structure is also called a Last-In-First-Out, or “LIFO” queue.

Bitcoin Script III.

  • Turing complete or computationally universal if it can be used to simulate any Turing machine

  • The bitcoin transaction script language contains many operators, but is deliberately limited in one important way—there are no loops or complex flow control capabili‐ ties other than conditional flow control. This ensures that the language is not Turing Complete, meaning that scripts have limited complexity and predictable execution times. Script is not a general-purpose language. These limitations ensure that the lan‐ guage cannot be used to create an infinite loop or other form of “logic bomb” that could be embedded in a transaction in a way that causes a denial-of-service attack against the bitcoin network.

  • Every Bitcoin Script will terminate in finite steps.

Turing incomplete

  • The bitcoin transaction script language is stateless
  • There is no state prior to execution of the script, or state saved after execution of the script.
  • Therefore, all the information needed to execute a script is contained within the script.
  • A script will predictably execute the same way on any system. If your system verifies a script, you can be sure that every other system in the bitcoin network will also verify the script, meaning that a valid transaction is valid for everyone and everyone knows this.
  • This predictability of outcomes is an essential benefit of the bitcoin system.

Stateless Verification

  • P2PKH: Pay To Public Key Hash
    • Public Key Hash refers to a bitcoin address
    • In other words, “send funds to this bitcoin address”
  • Typical TX: Sender (S) sends some BTC to Receiver (R)
    • The underlying script for this transaction consists of two scripts:
      • scriptSig: <sig> <pubKey>
      • scriptPubKey: OP_DUP OP_HASH160 <pubKeyHash> OP_EQUALVERIFY OP_CHECKSIG
    • S needs a private key, a public key and an address created from the public key (scriptSig)
    • Then, S creates a scriptPubKey using R's address
  • The transaction is completed once the overall script is successfully evaluated
    • Overall script: concatenation of scriptSig and scriptPubKey
    • Successfully evaluated: 'True'

Most Common TXs

  • Locking script:
    • spending condition placed on an output
    • it specifies the conditions that must be met to spend the output in the future
    • Called also scriptPubKey, because it usually contained a public key or bitcoin address (public key hash)
  • Unlocking script
    • a script that “solves,” or satisfies, the conditions placed on an output
    • called also scriptSig because usually contains a digital signature produced by the user’s wallet
    • part of every transaction input

Script Construction (Lock +Unlock)

  • Every  node validates transactions by executing the locking and unlocking scripts together.
  • Each input contains an unlocking script and refers to a previously existing UTXO.
  • The validation software will copy the unlocking script, retrieve the UTXO referenced by the input, and copy the locking script from that UTXO.
  • The unlocking and locking script are then executed in sequence.
  • The input is valid if the unlocking script satisfies the locking script conditions
  • All the inputs are validated independently, as part of the overall validation of the transaction

Script Verification 

  • Initially, P2PK - Pay to Public Key
     
  • Now - P2PKH - Pay to Public key hash = bitcoin address
     
  • An output locked by a P2PKH script can be unlocked (spent) by presenting a public key and a digital signature created by the corresponding private key

BTC Address

Public Key to BTC Address

  • P2PK - Pay To Public Key
    • ​Original format
    • Privacy issues and waste of blockspace
  • P2PKH - Pay to Public Key Hash
    • ​addresses that start with "1"
    • when spending from this address sender needs to reveal PK
  • P2SH - Pay to Script Hash
    • An elegant solution for more complex unlocking scripts (timelock, multisig)
    • hides script (created by the receiver), saves space & fees,
    • Addresses that start with "3"
  • Bech32
    • ​Native Segwit - the latest form of addresses
    • saves block space
    • start with "bc1"

Evolution of BTC addressess



 

  • OP_DUP - Duplicates the top stack item
  • OP_HASH160 - The input is hashed twice: first with SHA-256 and then with RIPEMD-160
  • OP_EQUALVERIFY -Same as OP_EQUAL, but runs OP_VERIFY afterward
  • OP_EQUAL - Returns 1 if the inputs are exactly equal, 0 otherwise
  • OP_CHECKSIG -The entire transaction's outputs, inputs, and script are hashed. The signature used by OP_CHECKSIG must be a valid signature for this hash and public key. If it is, 1 is returned, 0 otherwise

Transaction locking script

OP_DUP OP_HASH160 <Cafe Public Key Hash> OP_EQUALVERIFY OP_CHECKSIG

Alice --> Bob's cafe

 

 

Two scripts together:

 

   

Unlocking script

    <Cafe Signature> <Cafe Public Key> OP_DUP OP_HASH160
    <Cafe Public Key Hash> OP_EQUALVERIFY OP_CHECKSIG
<Cafe Signature> <Cafe Public Key>

Text

  • When executed, this combined script will evaluate to TRUE if, and only if, the unlocking script matches the conditions set by the locking script.
  • In other words, the result will be TRUE if the unlocking script has a valid signature from the cafe’s private key that corresponds to the public key hash set as an encumbrance.

Bitcoin Script Resources:

  • Elliptic Curve Digital Signature Algorithm
     
  • A digital signature is a mathematical scheme that consists of two parts. The first part is an algorithm for creating a signature, using a private key (the signing key), from a message (the transaction). The second part is an algorithm that allows anyone to ver‐ ify the signature, given also the message and a public key.

Digital Signatures (ECDSA)

 ECDSA - Secp256k1

  • Proves that the owner of the private key, who is by implication the owner of the funds, has authorized the spending of those funds.
     
  • The proof of authorization is undeniable (nonrepudiation).
     
  • The signature proves that the transaction (or specific parts of the transaction) have not and cannot be modified by anyone after it has been signed.

Digital Signatures (ECDSA) II.

3 key functions:

Transaction details

Balance

  •  There is no concept of a “balance” --> values are constructed by the blockchain explorer
  • “Total Received” --> explorer first decodes the Base58Check encoding of the bitcoin address to retrieve the 160-bit hash of Bob’s public key that is encoded within the address.
  • Then, it searches through the database of transactions, looking for outputs with P2PKH locking scripts that contain Bob’s public key hash.
    • -->summing up the value of all the outputs

Reading:

 

 

Extras

EUBA L2 (Bitcoin Protocol)

By David Stancel

EUBA L2 (Bitcoin Protocol)

Bitcoin: Blocks, Transactions & Script

  • 671