IS3101 Cryptocurrency & Blockchain
Lecture 6 Mechanics of Bitcoin
Recap: Bitcoin consensus
Copyright By PowCoder代写 加微信 powcoder
Bitcoin consensus gives us:
● Append-only ledger
● Decentralized consensus
● Miners to validate transactions
assuming a currency exists to motivate miners!
Bitcoin transactions
An account
based ledger (
might need to scan backwards until genesis!
Create 25 coins and credit to AliceASSERTED BY MINERS
Transfer 17 coins from Alice to BobSIGNED(Alice)
Transfer 8 coins from Bob to CarolSIGNED(Bob)
Transfer 5 coins from Carol to AliceSIGNED(Carol)
Transfer 15 coins from Alice to DavidSIGNED(Alice)
is this valid?
SIMPLIFICATION: only one transaction per block
A transaction
based ledger (Bitcoin)
Inputs: Ø Outputs: 25.0→Alice
change 2 Inputs: 1[0] address
Outputs: 17.0→Bob, 8.0→ IGNED(Alice)
Inputs: 2[0]
Outputs: 8.0→Carol, 9.0→ IGNED(Bob)
Inputs: 2[1]
Outputs: 6.0→David, 2.0→ IGNED(Alice)
finite scan to check for validity
is this valid?
SIMPLIFICATION: only one transaction per block
we implement this with hash pointers
Merging value
Inputs: …
Outputs: 17.0→Bob, 8.0→Alice
SIGNED(Alice)
Outputs: 6.0→Carol, 2.0→Bob ..
Inputs: 1[1]
SIGNED(Alice)
Inputs: 1[0], 2[1] Outputs: 19.0→ IGNED(Bob)
SIMPLIFICATION: only one transaction per block
Joint payments
Inputs: …
Outputs: 17.0→Bob, 8.0→Alice
SIGNED(Alice)
Outputs: 6.0→Carol, 2.0→Bob ..
Inputs: 1[1]
SIGNED(Alice)
Inputs: 2[0], 2[1] Outputs: 8.0→David
two signatures!
SIGNED(Carol), SIGNED(Bob)
SIMPLIFICATION: only one transaction per block
a Bitcoin transaction
“hash”:”5a42590fbe0a90ee8e8747244d6c84f0db1a3a24e8f1b95b10c9e050990b8b6b”, “ver”:1,
“vin_sz”:2,
“vout_sz”:1,
“lock_time”:0,
“size”:404,
{ “prev_out”:{
“hash”:”3be4ac9728a0823cf5e2deb2e86fc0bd2aa503a91d307b42ba76117d79280260″,
“scriptSig”:”30440…” },
{ “prev_out”:{
“hash”:”7508e6ab259b4df0fd5147bab0c949d81473db4518f81afc5c3f52f91ff6b34e”,
“scriptSig”:”3f3a4ce81….” }
“value”:”10.12287097″,
“scriptPubKey”:”OP_DUP OP_HASH160 69e02e18b5705a05dd6b28ed517716c894b3d42e OP_EQUALVERIFY OP_CHECKSIG” }
transaction hash housekeeping
“not valid before” housekeeping
“ver”:1, “vin_sz”:2, “vout_sz”:1, “lock_time”:0, “size”:404,
more on this later…
transaction metadata
“hash”:”5a42590…b8b6b”,
previous transaction
signature (more inputs)
“prev_out”:{ “hash”:”3be4…80260″, “n”:0
transaction inputs
“scriptSig”:”30440….3f3a4ce81″
output value
recipient address??
(more outputs) … ]
“value”:”10.12287097″,
“scriptPubKey”:”OP_DUP OP_HASH160 69e…3d42e OP_EQUALVERIFY OP_CHECKSIG”
transaction outputs
more on this soon…
Bitcoin scripts
Output “addresses” are really
How to redeem a coin?
OP_HASH160
69e02e18…
OP_EQUALVERIFY OP_CHECKSIG
https://en.bitcoin.it/wiki/Script
Input “addresses” are
30440220…
Bob’s signature 0467d2c9… Bob’s public key
OP_HASH160
69e02e18…
OP_EQUALVERIFY OP_CHECKSIG
Hash of Bob’s public key = address
scriptPubKey
TO VERIFY: Concatenated script must execute completely with no errors
Bitcoin scripting language (“Script”)
Design goals
● Built for Bitcoin (inspired by Forth) ● Simple, compact
● Support for cryptography
● Stack-based (LIFO)
● Limits on time/memory ● No looping
b✓KeyHash?> pbuKbeKyeH
Bitcoin script execution example
Review Bitcoin script execution
Bitcoin script instructions
256 opcodes total (15 disabled, 75 reserved)
● Arithmetic
● Logic/data handling ● Crypto!
○ Signature verification
○ Multi-signature verification
OP_CHECKMULTISIG
Built-in support for joint signatures Specify n public keys
Verification requires t signatures
BUG ALERT: Extra data value popped from the stack and ignored
Bitcoin scripts in practice
● Most nodes whitelist known scripts ● 99.9% are simple signature checks
● ~0.01% are MULTISIG
● ~0.01% are Pay-to-Script-Hash
● Remainder are errors, proof-of-burn
More on this soon
nothing’s going to redeem that ☹
OP_RETURN
Applications of Bitcoin scripts
1: Escrow transactions
(normal case) (disputed case)
Pay x to x to IGNED(ALICE, BOB)
SIGNED(ALICE, JUDY)
PROBLEM: Alice wants to buy online from Bob. Pay x to 2-of-3 of Alice, Bob, Judy (MULTISIG)
Alice doesn’t want to pay until after BoSIbGNEsDh(AiLpICsE).
To: : doesn’t want to ship until after Alice pays.
It’s me, Alice! Could you make out a green payment to Bob?
Faraday cage
Example 2: Green addresses
004 days since last double spend!
x to Bob, y to Bank No double spend SIGNED(BANK)
ROBLEM: Alice wants to pay Bob.
Bob can’t wait 6 verifications to guard against double-spends, or is offline completely.
Example 3: Efficient micro
What if Bob never signs??
A.l.i.ce demands a timed refund transaction before starting
Input: x; Pay 42 to Bob, 58 to SIIGNED((ALIICE))_S_IG_N__E_D_(B_O__B_)
all of these could be double- spends!
I’ll publish!
Input: x; Pay 04 to Bob, 96 to : x; Pay 100 to Alice, LOCK until time t
SIGNED(ALICE)___________ SIGNED(ALICE) SIGNED(BOB)
Input: x; Pay 03 to Bob, 97 to IGNED(ALICE)___________
Input: x; Pay 02 to Bob, 98 to IGNED(ALICE)___________
Input: x; Pay 01 to Bob, 99 to IGNED(ALICE)___________
PROBLEM: Alice wants to pay Bob for each
minute of phone service. She doesn’t want to Input: y; Pay 100 to Bob/Alice (MULTISIG)
SIGNED(ALICE) incur a transaction fee every minute.
“hash”:”5a42590…b8b6b”,
“vin_sz”:2, “vout_sz”:1, “lock_time”:315415, “size”:404,
this transaction can’t be published till the Block index or real-world timestamp reached
More advanced scripts
● Multiplayer lotteries
● Hash pre-image challenges
● Coin-swapping protocols
● Don’t miss the lecture on anonymity!
“Smart contracts”
Bitcoin blocks
Why bundle transactions together? ● Single unit of work for miners
● Limit length of hash-chain of blocks ○ Faster to verify history
Bitcoin blocks
Bitcoin block structure
Hash chain of blocks
prev: H( )
trans: H( )
prev: H( )
trans: H( )
prev: H( )
trans: H( )
Hash tree (Merkle tree) of transactions in each block
H() H() H() H()
transaction transaction transaction transaction
“hash”:”00000000000000001aad2…”, “ver”:2, “prev_block”:”00000000000000003043…”, “time”:1391279636,
“bits”:419558700,
“nonce”:459459841, “mrkl_root”:”89776…”,
“n_tx”:354,
“size”:181520,
“mrkl_tree”:[ “6bd5eb25…”, … “89776cdb…”
a Bitcoin block
block header
transaction data
mining puzzle information
“hash”:”00000000000000001aad2…”, “ver”:2, “prev_block”:”00000000000000003043…”, “time”:1391279636,
“bits”:419558700,
“nonce”:459459841, “mrkl_root”:”89776…”,
hashed during mining
a Bitcoin block header
not hashed
redeeming nothing
}, First ever coinbase parameter: “coinbase”:”…” “The Times 03/Jan/2009 Chancellor
“prev_out”:{ “hash”:”000000…..0000000″, “n”:4294967295
transaction
Null hash pointer
}, “out”:[
on brink of second bailout for banks”
block reward
“value”:”6.25.03371419″, “scriptPubKey”:”OPDUP OPHASH160 … ”
transaction fees
See for yourself!
https://www.blockchain.com/explorer (and many other sites)
Smart Contract III
Solidity Data Structure
• 1 Ether = 1018 Wei
• Price for a Tx = gas X gas price
• Unit conversation:
– 1 wei = 1 wei (0.000000000000000001 ether)
– 1 Gwei = 1e9 wei (1,000,000,000) or (0.000000001 ether) – 1 szabo = 1e12 wei (1012 = 1,000,000,000,000)
– 1 finney = 1e15 wei (1015 =1,000,000,000,000,000)
– 1 ether = 1e18 wei (= ?wei)
Recap: Cost of Gas
Data Structures (Part 1) (BallotV1 Demo)
• Explain the syntax and usage of arrays, enum and struct data types of Solidity.
• Illustrate the use of time units pre-defined in Solidity.
Ballot Smart Contract:
1. The creator is the chairperson who gets a weight of 2 for her vote, others get a weightage of 1 for their 1 vote.
2. Each voter has to be registered first, by the chairperson, before they can vote.
3. They can vote only once.
Ballot Class Diagram
struct voter
struct Voter {
uint weight; bool voted; uint8 vote;
Let’s code in Remix IDE
1. Home>Solidity
2. File> >type filename 3. Begin coding→
Possible Errors
• pragmasolidity^0.5.9;
• Current compiler is 9.8.7+
• invalidBigNumberstringis (argument=”value”, value=””, code=INVALID_ARGUMENT, version=bignumber/5.5.0
View function modifier
• Function winningProposal() public view returns(…)
• A constant/view function is included to enable the client
applications to call to obtain the result.
• The constant/view modifier of the function prevents it from changing any state of the smart contract.
• This call comes directly to the smart contract and not via a transaction, so it is not recorded on the blockchain.
Data Structures (Part 2) (StateTransV2 Demo)
• Time units –
• now/Block.timestamp • Enum
Unix Epoch Time
www.epochconverter.com
• Used in timestamping the block time when a block is added to the blockchain.
• All the transactions confirmed by the block also have the block time as their confirmation time.
• A variable called “now” defined by Solidity returns the block timestamp. This variable is often used for evaluating time-related conditions.
• Unit: seconds, minutes, hours, days, weeks, and years
block.timestamp
• If (now >= creationTime + 1 day) = Stage.RegDone;
• If (now <= voteStartTime + 60 minutes) ... then allow to vote
Example: now
• Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums.
• With the use of enums it is possible to reduce the number of bugs in your code.
• For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to small, medium, and large. This would make sure that it would not allow anyone to order any size other than small, medium, or large.
https://www.tutorialspoint.com/solidity/solidity_enums.htm
Example: Enum
• Enumeratordatatype(Enum).
• Definingstatesorphasesofasmartcontract.
Init Start Reg +1 Vote +1 Done time Minute Minute
Example: StateTransV2.sol, BallotWithStages.sol
• Struct types are used to represent a record. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book −
https://www.tutorialspoint.com/solidity/solidity_structs.htm
Accessing a Struct and its variable
• To access any member of a structure, we use the member access operator “.”
• The member access operator is coded as a period between the structure variable name and the structure member that we wish to access.
• You would use the struct to define variables of structure type. https://www.tutorialspoint.com/solidity/solidity_structs.htm
• Explaintheuseoffunctionmodifiers • Explain“require”clause
• Illustrateassertdeclaration
• Discuss revert() function.
unction modifiers
• Modifierscanchangebehaviorofafunction. • AlsoknownasFunctionModifiers.
– add a prerequisite to a function.
modifier and require clauses:
– Define modifier for clause “onlyBy(chairperson)”
– Adding the special notation (_;) to the modifier definition
– Using the modifier clause in the register() function header
constructor (...){ chairperson = msg.sender; ...}
modifier onlyBy(address _account){ require(chairperson == _account);
function register(address toVoter) public onlyBy(chairperson) {
If (voters[toVoter].voted) revert(); voters[toVoter].weight = 1; voters[toVoter].voted = false;}
: modifier
() & require()
function register(address toVoter) public onlyBy (chairperson) {
if (voters[toVoter].voted) revert (); voters[toVoter].weight =1; voters[toVoter].voted = false;
function payoff (address better) public {
/* compute & payoff all the betters */
assert (bank.balance >10000);
/* revert the call and any state transitions if bank
balance falls below a reserve of 10,000 */
Execution order
Function Header
Input arguments validation using “require”
(Tx revertible)
Function Code
Assertion (Tx revertible)
Rules, laws, policies, governance coded as modifier
Function guard conditions
Modifiers (Tx revertible) referenced in the function header
Example: Execution order
function buy(..) payable atLeast5sellers..returns(..)
Buyer has enough money to buy the selected item?
Function code: collect money and transfer digital item
Assertion (itemTransferred);
Rules: at least 5 sellers have registered
modifiers atLeast5Sellers{ require(numSellers>=5);
Functions and addresses declared payable can receive ether into the contract
• functionmodifiers: • require()
• revert()
• assert()
History of payment systems and the road to Bitcoin
1. Narayanan et al. Ch3
2. Solidity Document
3. Remix IDE Document
4. https://www.tutorialspoint.com/solidity/
References:
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com