Maximilian Stark (mail@dakror.de), SS2020
Stand: 18.07.2020
Blockchain-based Systems Engineering
Definition of Blockchain
- technical definition: distributed write-only database
- functional definition: trust-free consensus on shared facts
- intermediary-free trust-free transaction of digital non-copyable goods
- decentralized immutable secure transactions
- automated programmable contracts for compliance assurance
Use cases
- Fintech
- Automotive
- Pharma, Medical
- Energy
- Documentation / Legal proofs
- Digital identity
- IP Management
- Sharing Economy
Reputation Problem
- Power consumption
- Shady business
- Casino economy
- Gap between expectations and technological maturity
Smart contract
- Domain specific programming language code
- Immaturity through blockchain
- "persistent scripts"
Ledger
- Account based: Global tracking of account balances
- Transaction-based: list of in- & outgoing funds
- Bitcoin
- Requirement: All or no coins of transaction referenced must be consumed
- Sending of money to own address ("change address")
- List of available funds: Tracking of unspent transaction outputs (UXTO)
Bitcoin
Core Properties
- Trust-free
- Tamper-proof
- Transparent
- Maximum of 21 mil coints
- Halving of block reward every 210k blocks
Roles in Bitcoin
- Wallet Owner (User)
- Identity as hash of public key
- Light node
- transaction relay
- Gateway between wallet owner and network
- Verification of wallet owner transaction
- Almost irrelevant today
- Full node
- Copy of full blockchain
- Full transaction & block validation
- Relaying of transaction and blocks
- Miner
- Full node + block creation
Bitcoin Transactions
- Max Block size: 1MB
- Inputs: reference to previous output
- Outputs: amount and receiver
- Verification scripts
- Input scripts for signature of referenced outputs
- Output scripts for conditional redeeming of funds
- Difference of sum of input and sum of output is miner fee
Bitcoin script
- Definition of script by sender
- Scripting language verifying output addresses
- Stack based execution
- Code: Concat of input script (scriptSig) and output script (scriptPubKey)
- Use Cases
- Escrow / Money-Goods exchange
- Creation of N/M Multisig address
- Requirement of at least N and at most M signatures
- Depositing of money at multisig address, showing credibility
- Shipping of goods
- Retrieval of funds by signing
- Micropayments
- Continuous chain of multisig transactions at consumer
- After termination of service contract, single validation by producer to retrieve funds
- Requirement of lock-time incorporation to ensure payment cancellation
- Locking of output funds until time passed and output is unspent
- Proof of Burn / Data storage
OP_RETURN
: throws error, making money inaccessible
- Bootstrap for new chain
- Storage of arbitrary data after command
- P2SH: Pay to script hash
- payment to hashed script instead of hashed public key
- Receiver defined script
Distributed consensus
- Byzantine Generals Problem: Impossible of consensus if $\geq 33%$ malicious
- No consistent notion of time
- Bitcoin Approach
- Probabilistic consensus: ongoing
- Randomness: random node as new block proposer
- Incentives: Payment for creating blocks in the longest chain
- Flow of events
- Transaction Broadcast
- Block Building
- Random node selection
- Block validation by network
- Block acceptance by network through building blocks based on it
- Double spending attack
- Forking of blocks to avoid spending transaction to get processed
- Attack avoidance by waiting for several confirmations on transaction reception
Random node selection
- Proof of Work
- Bitcoin uses double sha-256 for mining puzzle
- Different puzzle for every miner since reward address (in $TX_0$) is unique to them
- Average puzzle time 10 mins
- Difficulty increase every 2016 blocks ($\approx 2 ~\text{weeks}$)
- Measurement of mining speed $T$ for last 2016 blocks
- Calculation speed factor $F = 2 ~\text{weeks} / T$
- Difficulty increase $F > 1$ up to 4x, decrease if $F < 1$, max 0.25x
- Incentives
- Block reward, start at 50 BTC, halved every 210k blocks
- Upper limit of 21 mil BTC issued
- Transaction fee: diff of input-output
- Mining hardware
- CPUs
- GPUs
- FPGAs
- ASICs
- Mining Pools
- PoW / Near-solutions to show work within pool
- Reward shares distributed among members
- Proof of Stake
- Rich get richer
- Depositing of coins to acquire rights to mine
Network Evolution
- Bitcoin Improvement Proposals (BIP) = RFC
- Protocol update process
- Design proposal (fork)
- Signaling: Voting of miner community
- Voting of miners by inclusion of voting flag in block header
- Selection of bit in version field and timeframe for voting per BIP
- Majority threshold 95% (1916 blocks) of 2016 blocks
- Application of rules after another 2016 blocks
- Simultaneous voting for up to 29 BIPs possible
- Results: Split, Merge, Reject
- Bitcoin Cash
- Bitcoin Gold
Attacks
- 51% attack
- selfish mining attack
- not yet observed in practice
- abusing of chance of double-proposing
- Withholding of mined block until child found and double publishing, making mainstream chain not longest, wasting power
- Hashing power of 25% needed for 50% chance of success
Statistics
- Max of 576k transactions per day
- Growth of Blockchain by 1MB every 10 mins
- Visa throughput: 150mil/day
- Energy consumption
- Difficult estimate based on speed of network and Antminer S9
- 10.4 GW
- 895 kWh per transaction
Ethereum
- Account-Based ledger
- Private-key based accounts: Default user accounts
- Smart contract accounts, controlled by their code
- Can act as entities
- Can't issue transactions
- Persistent internal storage
- Account properties
- nonce: increasing number, preventing double spending and replay
- balance
- contract code
- storage
- Blockchain as single computer
- Transactions as commands / interactions
- Cost for code execution: "Gas"
- Assigning of priority by entering high gas price as sender
- Prices per instruction
- No price of reading contract state data
- Ethereum Virtual Machine (EVM)
- Execution model for state change of the Blockchain
- Transactions: Wallet to Smart Contract, mineable
- Messages: Between Contracts, virtual
- ASIC-proof PoW: Ethash
- Difficulty adjustment after each block
- No block size limit
- No orphaning, but block uncles
- Blocks in uncle blocks considered invalid
- Open source node specification
- Multiple implementations available
Smart Contract
- Set of functions
- Bound to address
- Special security care required
- No modification after public deployment
- No access to external resources outside of Blockchain
- No RNG -> Prevention of nondeterministic computation
- Oracles
- Only way of integration of external data
- Verification services for external source data
- Writing of external data into special contract by oracle
- Use Cases
- Token systems: Shares
- Identity systems
- Decentralized Autonomous Organization (DAO): Multi-signature Wallets
- Election / Voting systems
Solidity
- Scripting language
- Bytecode
- OOP, statically typed
- special unit literals for ether
- special type for address
- 20 byte hex
- Downcast into Contract possible
- Low level function calls
- global variable to access sender triggering function call
- global variable to access last mined block
- global variable to access transaction triggering function call
- C3 linearization (BFS)
- Contract structure
- state variables
- function modifiers
- sequential resolution, l2r
- placement of method code using "
_;
"
- constructor
- functions
- visibility types
- view functions: read-only
- pure function: no state interactions
- fallback function: when no matching function for request
- paypable function: consumer of ether
- Idioms
- Access restrictions (modifiers)
- Secure ether transfer: pull over push
- safe math (overflow protection)
- Patterns
- Oracle
- synchronous: periodic data push
- asynchronous
- request for fresh data triggered by contract access
- callback through external method
- Requirement of limiting of forwarded gas on message sending to prevent malicious usage
- Randomness
- Implementation via Oracle
- RNG based on block hash
- Commit-Reveal scheme
- Commit of hashes containing secret and random value by two users
- Reveal of both users numbers
- Calculation of final value $(r_a + r_b) % 2$ decides winner
- Evolution Support
- Replacement of old contract with newer version
- Challenge of migrating contract state and linking to new contract address
- Approaches
- Data segregation: split into data and code contracts
- Proxy: Separation of business logic from application-facing logic
- Test Networks
- Ropsten: PoW
- Koban: Proof of Authority (PoA)
- Rinkeby: PoA
Tokens
- Smart contracts with standardized interface
- Virtual asset buyable with Currency
- Use-Cases
- ICOs & crowd-funding
- Gaming
- Classes
- Fungible: Indistinguishable with same values
- Non-fungible: uniquely identifiable
- Standards
- ERC20
- fungible
- allowance and balance management of users
- transfer approvals through token owner
- ERC721
- based on ERC20
- non-fungible
- usable for individual assets
dApps
- Decentralized application UI ontop of Smart contracts
- Core data stored on blockchain
- Core data changing functions executed on blockchain
- Benefits
- Trust
- Payment
- Accounts
- Storage
- Drawbacks
- Costs
- Time
- Availability
- Transparency: Code inspection only through 3rd party tools
- Web based dApps
- Use cases
- ICOs
- Games
- Gambling
- Exchanges
- Architecture
- Communication of priv key manager with blockchain over JSON RPC 2.0
- Communication of client with priv key manager and Web server for other data
- Browser Plugin MetaMask for client-based private key manager
Hyperledger
Corda
- No mining
- No central ledger
- Individual vaults between parties
- Subset of network ledger information
- SQL database with table of shared facts
- Permissioned network
- legally identifiable entities behind nodes
- Permissioning service as network operator, signing participation certificates
- No transaction broadcast, only direct communication
- Smart contracts only as pure transaction validation functions
- JVM-based (Kotlin)
- Goal: Seamless interoperability with other systems
- Corda Applications (CorDapps) as network-interaction-glue
- Flows invoked by nodes upon consensus-reaching using RPC
- Manual installation of CorDapps on nodes
- Components
- State objects
- Contracts
- Flows
- Transactions
- APIs & UI
- Examples
- Token minting
- Healthcare
- Energy
- Government
- UTXO-based ledger
- Flow: P2P algorithm for ledger update & sync
- Notary cluster
- Network service
- Notarising of transactions through signing or rejection
- Consensus on transaction validity
- Validity consensus
- Signatures
- Acceptance by all contracts
- Uniqueness consensus
- UTXO-checks
- Provided by notaries
- Global corda network
- Components
- Network paramenters (consensus guidelines, global compatibility)
- Identity framework
- Recommendations for notary pools
- Oracles
- Facilitation of digital tokens
- Reliance on open governance
- Network map service
- Notary service
- Benefits
- Privacy by design: Only transaction-specified parties aware of transaction
- Parallel execution
- Strong developer ecosystem
- Use of proven technology (SQL, JVM)
- Niche industry
Hyperledger
- Group of projects by Linux Foundation
- Burrow: Smart contract machine, interoperable with Ethereum
- Tendermint consensus engine
- Permissioned EVM, supplying Ethereum smart contracts with random Gas amount due to no currency
- API Gateway for REST and JSON-RPC
- Fabric: Modular Base for modular systems with plug and play support
- Grid: Supply-Chain focused Blockchain & Smart contract development package
- High-level access through strong abstraction
- Web-Assembly based
- Indy: Distributed ledger with focus on distributed identity
- Permissioned public Blockchain
- Author-controlled data-sharing for full control over own data
- Zero-Knowledge proofs for identity management
- Iroha: Modular blockchain platform
- Focus on high Byzantine fault tolerance
- Sophisticated account & permission system
- Integrated asset management
- Yet Another Consensus (YAC)
- Sawtooth: Modular blockchain with Proof of Elapsed Time, minimal resource consumption
- Focus on security and transaction throughput
- On-chain governance (voting on-chain)
- Parallel transaction execution
- Dynamic consensus algorithm
- Caliper: Blockchain benchmark tool
- Cello: Blockchain management & creation tool
- Composer: Smart contract collaboration tool
- Explorer: Blockchain explorer
- Quilt: Ledger interoperability with value transfer
- Ursa: Shared cryptographic library
Hyperledger Fabric
- Permissioned network, Membership Service Provider (MSP) for new joining nodes
- Channels and multi-ledger
- Chaincode
- network operator and developer business logic for whole channels or single transactions
- Container of group of related smart contracts for installation and instantiation
- Programming paradigms
- Native Fabric (Golang)
- Hyperloedger Composer (testing & PoC)
- Ordering service: Enforcement of network policies and consensus-based transaction collection
- SOLO: Single node, development
- Kafka: blocks map to topics
- SBFT: Simple byzantine fault tolerance
- Peers (=full node)
- Validation of transactions and endorsement responses to Ordering service
- Committing peer: Committing of transactions and verification of endorsements and transaction results
- Endorsing peer: Extension of Committing peer + processing of transaction proposals for endorsement creation
- Handling and processing of chaincode-emitted events (pub-sub)
- Transaction flow
- Enrollment at MSP
- Submission of tx proposal to endorsment peer
- Execution of chaincode and return of endorsement (signed read/write set on the ledger)
- Submittion of tx to Ordering service
- Consensus-based ordering
- Batch delivery to committer peer
- Validation and commit
- Software architectures
- Order-Execution (classic blockchain)
- Sequential execution on all peers
- No non-deterministic code
- confidentiality of execution
- Execution-Order-Validate: Parallel execution of unrelated operations
- Ledger database
- Google LevelDB
- Apache CouchCB