代写代考 IS3101 Cryptocurrency & Blockchain

IS3101 Cryptocurrency & Blockchain
Lecture 8 Bitcoin Network

• The Bitcoin Network

Copyright By PowCoder代写 加微信 powcoder

• LimitationsandImprovements
• Smart Contract IV: Ballot version 2 & version 3 • IndividualAssignment10%

The Bitcoin network
● Ad-hoc protocol (runs on TCP port 8333) ● Ad-hoc network with random topology ● All nodes are equal
● New nodes can join at any time
● Forget non-responding nodes after 3 hr

Joining the Bitcoin P2P network
1 getaddr() 8
getaddr() getaddr()
Hello World! I’m ready to Bitcoin!

Transaction propagation (flooding)
A→B Newtx! A→B
Already heard that!

Should I relay a proposed transaction?
● Transaction valid with current block chain ● (default) script matches a whitelist
○ Avoid unusual scripts ● Haven’t seen before
○ Avoid infinite loops
● Doesn’t conflict with others I’ve relayed
○ Avoid double-spends
Sanity checks only…
Some nodes may ignore them!

Nodes may differ on transaction pool

Race conditions
Transactions or blocks may conflict
● Default behavior: accept what you hear first ● Network position matters
● Miners may implement other logic!
Stay tune for our lecture on mining!

Block propagation nearly identical
Relay a new block when you hear it if: ● Block meets the hash target
● Block has all valid transactions
○ Run all scripts, even if you wouldn’t relay
● Block builds on current longest chain ○ Avoid forks
Sanity check
Also may be ignored…

Source: and : “Accelerating Bitcoin’s Transaction Processing” 2014

How big is the network?
● Impossible to measure exactly
● Estimates-up to 1M IP addresses/month ● Only about 5-10k “full nodes”
○ Permanently connected
○ Fully-validate
● This number is very stable!
https://bitnodes.io/ https://www.bitrawr.com/bitcoin-node-map

Can 51% Attack destroy Bitcoin?
● Non-mining full nodes cannot prevent a 51% attack, but they are essential in preventing other attacks.
● Full nodes are what keep miners honest.

Fully-validating nodes
● Permanently connected
● Store entire block chain
● Hear and forward every node/transaction

Storage costs
https://blockchair.com/compare

Tracking the UTXO set
● Unspent Transaction Output
○ Everything else can be stored on disk
● Currently ~72 M UTXOs ● =~7.2GB
● Can still fit into 16GB RAM
● (Min. requirement is 2GB RAM)
https://bitcoin.org/en/full-node#initial-block-downloadibd
https://www.blockchain.com/charts/utxo-count

Thin/SPV clients (not fully-validating)
Idea: don’t store everything
● Store block headers only
● Request transactions as needed
● To verify incoming payment ● Trust fully-validating nodes
5000x cost savings! (350 GB→~70MB)

Software diversity
● About 90% of nodes run “Core Bitcoin” (C++)
● Also known as “Satoshi client”
● Some nodes are running out of date versions ● Other implementations running successfully
○ BitcoinJ (Java)
○ Libbitcoin (C++)
○ btcd (Go) https://bitcoincore.org/
https://github.com/bitcoin/bitcoin

Limitations & improvements
• Hard-coded
• Throughput
• Cryptographic • Forking

Hard-coded limits in Bitcoin
● 10 min. average creation time per block
● 1 M bytes in a block
● 20,000 signature operations per block
● 100 M satoshis per bitcoin
● 23M total bitcoins maximum
● 50,25,12.5… bitcoin mining reward
These affect economic balance of power too much to change now

Throughput limits in Bitcoin
● 1 M bytes/block (10 min) ● >250 bytes/transaction ● 7 transactions/sec ☹
Compare to:
● VISA: 2,000-10,000 transactions/sec ● PayPal: 50-100 transaction/sec

Cryptographic limits in Bitcoin
● Only 1 signature algorithm (ECDSA/P256) ● Hard-coded hash functions
Crypto primitives might break by 2040…

“Hard-forking” changes to Bitcoin
That’s crazy talk!!
I found a nifty new block!
BBlloocckk2234
That’s crazy talk!!
PROBLEM: Old nodes will never catch up

Soft forks
Observation: we can add new features which only limit the set of valid transactions
Need majority of nodes to enforce new rules
Old nodes will approve
RISK: Old nodes might mine now-invalid blocks

Soft fork example: pay-to-script-hash

< OP_CHECKSIG>
OP_HASH160
OP_EQUAL
Old nodes will just approve the hash, not run the embedded script

Soft fork possibilities
● New signature schemes
● Extra per-block metadata
○ Shove in the coinbase parameter
○ Commit to UTXO tree in each block

● New op codes
● Changes to size limits ● Changes to mining rate ● Many small bug fixes
Hard forks
Currently seem very unlikely to happen Stay tuned for our lecture on altcoins!

Smart Contracts IV
• Putting It All Together: Developing Smart Contracts

Learning Objectives
• Write a smart contract
• Analyze a problem statement to design & implement
a smart contract
• ProgramsmartcontractsusingSoliditylanguageand Remix IDE
• Add features to the ballot smart contract code

Problem statement
1. Analyze problem
2. Use class diagram to represent design
3. Define the visibility for the state variables and functions
4. Define access modifiers for the functions
5. Define validations for input variables of the functions
6. Define conditions that must hold true
7. Express conditions that were discovered

• Constructor
• Register
• ClientApplication

Ballot smart contract

Time Elements (Part 1)
Init •Created Reg •Registered Vote •Voted Done •Start time •+10 days •+ 1 day

Time Element (Part 2) Ballot V2 Demo

Storage vs Memory in Solidity
• Storage and Memory keywords in Solidity are analogous to Computer’s hard drive and Computer’s RAM.
• Much like RAM, Memory in Solidity is a temporary place to store data whereas Storage holds data between function calls.
• The Solidity Smart Contract can use any amount of memory during the execution but once the execution stops, the Memory is completely wiped off for the next execution.
• Whereas Storage on the other hand is persistent, each execution of the Smart contract has access to the data previously stored on the storage area.
• Every transaction on Ethereum Virtual Machine costs us some amount of Gas.
• The lower the Gas consumption the better is your Solidity code.
• The Gas consumption of Memory is not very significant as compared to the gas consumption of Storage.
• Therefore, it is always better to use Memory for intermediate calculations and store the final result in Storage.
• State variables and Local Variables of structs, array are always stored in storage by default.
• Function arguments are in memory.
• Whenever a new instance of an array is created using the keyword ‘memory’, a new copy of that variable is created. Changing the array value of the new instance does not affect the original array.

Deploy Error?
• creation of Ballot errored: Error encoding arguments: Error: invalid BigNumber string (argument=”value”, value=””, code=INVALID_ARGUMENT, version=bignumber/5.0.8)
• You forget to give an initial value!

Time Elements (Part 3)
• enum Stage {Init, Reg, Vote, Done}
• Stage public stage = Stage.Init;
• function register(address toVoter) public {
• if(stage!=Stage.Reg) {return;}
• function vote(uint toProposal) public {
• if (stage != Stage.Vote) {return;}

Common questions:
• Can we reject transaction if it doesn’t conform to rules?
• Can we separate the validation from the code that is executed?
• Can we specify the problem-specific rules and conditions so they can be independently specified and audited?

Validation & Test
• Explain reverting a transaction
• Use revert declaration
• Applyfunctionmodifier,requireand assert

Example: modifier
Function Modifier
modifier validStage(Stage requiredStage)..;
Function Header
Function vote(uint8 toProposal) public voteStage{
//function code…} Stage requiredStage
modifier validStage(Stage requiredStage) {require(stage == requiredStage);

Ballotv3.sol
//modifiers
modifier validStage(Stage reqStage) {require(stage == reqStage);
function register(address toVoter) public validStage(Stage.Reg) {
// if(stage!=Stage.Reg) {return;}

• Invalidstage
• assert(winningVoteCount>0) • Atie?

Client Applications
• Concept of events:
• Defining an event and pushing an event
to a subscribed listeners.
• Illustrate the event using. The Ballot example.

Event Definition
• event nameOfEvent(parameters);
• Example:
event votingCompleted(); …
In function done()…
if (block.timestamp > (startTime + 30 seconds)) {stage = Stage.Done; emit votingCompleted();}

Event logging
• The application can listen to the events pushed, using a listener code, to:
• Track transaction
• Receiveresults
• Initiate a pull request to receive information from a smart contract

Individual assignment 10%
• Due date: 11:59 p.m. Mar 27, 2022 (Sunday)
• iAssg_template.sol
• Screenshots of some test run results

What is ++?
• donorIdCount++;
– Means donorIdCount =
donorIdCount + 1 – Increment by 1

/ Division
• Uint answer = uint(a) / uint(b)
• Since the type of the result of an operation is always the type of one of the operands, division on integers always results in an integer.
• In Solidity, division rounds towards zero.
• This mean that uint(5) / uint(2) == uint(2) but not == 2.5

% Modulus or Remainder
• uint answer = uint(a) % uint(b)
• This operation returns the remainder result of the process of division of two numbers.
• In Modulus Operation all the variables must be Integers of the Same Bits Length.
• Modulus with zero causes a failing assert

How to draw a random number?
• uint randomIndex = (block.number / currentGift.giftTokens.length) % currentGift.giftTokens.length;
– Solidity Not come with a random function
– Block.number means current block number,
we use it as the random seed
– You could use Now or other non-fixed number
– We try to scramble it a bit more by /
– % will set the maximum number of results to match the total number of bids
https://docs.soliditylang.org/en/v0.5.11/types.html#modulo

Why use for loop?
• To record the bided token(s) in a selected gift, each token will bring the donor ONE luck draw chance.
– for (initialize loop counter; check and test the counter; increase the value of counter;)
– { Execute multiple instructions here }
– for(uint i=0; i<_tokens; i++) – {bidGift.giftTokens.push(tokenDetails[msg. sender].donorId);} History of payment systems and the road to Bitcoin Narayanan et al. Ch. 4 Solidity Document Remix IDE Document https://www.tutorialspoint.com/solidity/ References: 程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com