程序代写 IS3101 Cryptocurrency & Blockchain

IS3101 Cryptocurrency & Blockchain
Lecture 5 Decentralization II & Smart Contract II

• HowBitcoinAchievesDecentralizationII • SmartContractII

Copyright By PowCoder代写 加微信 powcoder

Incentives and
• Bitcoinconsensusalgorithm
• 6 confirmations
• And clever incentive engineering

Assumption of honesty is problematic
Can we give nodes incentives for behaving honestly?
Can we reward nodes
that created these blocks?
Can we penalize the node that created this block?
Everything so far is just a distributed consensus protocol But now we utilize the fact that the currency has value

Incentive 1: block reward
Creator of the block gets to
• include special coin-creation transaction in the block
• choose recipient address of this transaction
Value is fixed: currently, 6.25 BTC, halves every 4 years
Block creator gets to “collect” the reward only if the block ends up on the long-term consensus branch!

There’s a finite supply of bitcoins
First inflection point:
reward halved from 50BTC to 25BTC
Total supply: 21 million
Block reward is how
new bitcoins are created
Runs out in 2040. No new bitcoins unless rules change
Total bitcoins in circulation

Incentive 2: transaction fees
• Creator of transaction can choose to make
• output value less than input value
• Remainder is a transaction fee and goes to block creator
• Purely voluntary, like a tip

Remaining problems
1. How to pick a random node?
2. How to avoid a free-for-all due to rewards? 3. How to prevent Sybil attacks?

Proof of work
To approximate selecting a random node: select nodes in proportion to a resource that no one can monopolize (we hope)
• In proportion to computing power: proof-of-work
• In proportion to ownership: proof-of-stake

Equivalent views of proof of work
1. Select nodes in proportion to computing power
2. Let nodes compete for right to create block
3. Make it moderately hard to create new identities

Hash puzzles
To create a block, find nonce s.t.
H(nonce ‖ prev_hash ‖ tx ‖ … ‖ tx) is very small

Output space of hash
Target space
If hash function is secure:
only way to succeed is to try enough nonces until you get lucky

PoW property 1: difficult to compute
As of Aug 2014: about 1020 hashes/block
• Only some nodes bother to compete — miners

PoW property 2: parameterizable cost
• Nodes automatically re-calculate the target every two weeks
• Goal: average time between blocks = 10 minutes
Prob (Alice wins next block) = fraction of global hash power she controls

Key security assumption
• Attacks infeasible if the majority of miners weighted by hash power follow the protocol

Solving hash puzzles is probabilistic
10 minutes
Time to next block (entire network)
Probability density

PoW property 3: trivial to verify
• The nonce must be published as part of the block
• Other miners simply verify that
• H(nonce ‖ prev_hash ‖ tx ‖ … ‖ tx) < target Putting it all together • Miningeconomics • Blockreward:6.25Bitcoins • Profitable for a miner to mine? Mining economics If mining reward (block reward + Tx fees) hardware + electricity cost Complications: • fixed vs. variable costs • reward depends on global hash rate • Identities • Transactions • P2P network • Block chain & consensus • Hash puzzles & mining Bitcoin has three types of consensus • Value • State • Rules Bitcoin is bootstrapped security of block chain health of mining ecosystem value of currency What can a “51% attacker” do? Steal coins from existing address? ✗ Suppress some transactions? • From the block chain ✓ • From the P2P network ✗ Change the block reward? ✗ Destroy confidence in Bitcoin? ✓✓ Remaining questions • How do we get from consensus to currency? • What else can we do with consensus? SMART CONTRACTS PART II Learning Objectives: • Processing Smart Contracts (Compile Artifacts) • DeployingSmartContracts • Illustratedatatypes,anddatastructures,functions, modifiers, and events • Design, develop, deploy, and test a smart contract. Compile Artifacts Demo Smart Contract Remix compile process Contract Bytecode WebDeploy script Gas estimates Function hashes Instance bytecode Deploy Process Smart Contract Smart Contract Compile Process Web3 Deploy Script Account Address AC Function Hashes Gas Estimate Summary: Compile Artifacts • Name of the contract • Bytecode executed for the contract “creation” on the EVM • ABI: Application Binary Interface, details functions, parameters and return value • Web3 deploy module that provides the script code for invoking the smart contract from a web application • Gas estimates for the execution of the functions • Actual runtime bytecode of the smart contract Solidity: Structure • Remix supports test environments • JavaScriptVM, • Injected Web3 (e.g., Metamask) • Web3Provider,(Ethereumnode) Detailed Structure Detailed Structure 1. Data or state variables 2. User-defined types in struct and enums 3. Modifiers 4. Events 5. Functions: – Constructor – Fallback – Private – Internal – External Data or state • State variables – Permanently stored • Local variables – Present till the function is executing • Global variables – Special variables exists – Msg.data, msg.sender, msg.sig, now, tx.gasprice • Struct types – Represent a record – Restrict a variable to have only a few predefined values defined types in struct and Function Modifiers • modify the behavior of a function – E.g., add a prerequisite • Special symbol _; – If condition is not satisfied, an exception is thrown • Visibility and accessibility modifiers: • external, public, internal, private • allows a contract to log a change of state to the blockchain • E.g.,transactionlogs – Constructor: initialize – View: read-only – Public: accessible from outside – Private: accessible only with the current contract – Internal: accessible inside and inherited contracts – External: accessed only from outside contract More special ones: Fallback: is executed if no functions match or no data was provided Pure: ensure not read or modified the state • function header {function code} • Function header: – As simple as an anonymous, no-name function to a complex function header loaded with a lot of details • Function code: – Contains the local data and statements to process the data and returns the results of the processing definition Inheritance 1) contract StandardPolicies {...} 2) contract MYPolicies is StandardPolicies { //plus other policies... Basic Data Types & Statements (Smart Contract Demo: Bidder.sol) • Understand the cost of gas mechanism • Explain the basic data types and Solidity • Explain the use of access modifier “public” • Illustrate the basic definition of functions • Apply the basic data types and functions in constructing a smart contract Cost of Gas • Gas or crypto-fuel that is paid for transaction execution and an operation step, as set by Ethereum Protocol • 1 Ether = 1018 Wei • Price for a Tx = gas X gas price 1. assert(1 wei == 1); 2. assert(1 szabo == 1e12); 3. assert(1 finney == 1e15); 4. assert(1 ether == 1e18); Solidity Basic Data Types • bool: that supports logic true and false value • int: integer positive and negative value accepted 256 bits • string: string of characters • uint: unsigned int of 256 bits BidderData Solidity Specific Data Types (Smart Contract Demo: Coin.sol) • Explainimportantdatastructuresof Solidity: – address – mapping – message • Explain Solidity events that logs events and pushes data to an application level listener Address data type •

.balance(uint256)
• Balance of the Address in Wei

.transfer(uint256amount)
• Transfer given amount of Wei to Address

Mapping data type
1) mapping (uint => string) phoneToName;
2) struct customer { uint idNum;
string name;
uint bidAmount;}
mapping (address => customer) custData;

Message data type
• Complexdatatype
1. address adr = msg.sender 2. uint amt = msg.value

• Impossible to enumerate every possible language element of solidity
• Conceptofaddress,mapping,andmessage
• Alwaysdesignbeforeyoucode
• Explore the coding examples by uploading them to the remix

References:
History of payment systems and the road to Bitcoin
1. Narayanan et al. Ch2
2. Haber and Stornetta, 1991, “How to Time-Stamp a Digital Document.”
3. Nakamoto, 2008, “Bitcoin: A Peer-to-Peer Electronic Cash System.”
4. Solidity Document
5. Remix IDE Document

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com