Week 1
Bitcoin and Block Chain Bitcoin Whitepaper, Bitcoin's Academic Pedigree, What is
Blockchain Technology? A Step-by-Step Guide For Beginners, Blockchain: The
Invisible Technology That's Changing the World
Welcome to the first course of the blockchain specialization titled
blockchain basics.
Let's start by asking ourselves, what is a blockchain?
Why should you care about it?
Unlike traditional methods, blockchain enables
peer to peer transfer of digital assets without any intermediaries.
It was a technology originally created to support the famous cryptocurrency,
BitCoin.
The blockchain by itself has taken a life of its own and
permeated a broad range of applications across many industries,
including finance, healthcare, government, manufacturing, and distribution.
The blockchain is poised to innovate and transform a wide range of applications,
including goods transfer, for example, supply chain.
Digital media transfer, for example, sale of art.
Remote services delivery, example, travel and tourism.
Platform for decentralized business logic, for example,
moving computing to data sources.
And distributed intelligence, example, education credentialing.
Additional applications of blockchain include distributed resources, for
example, power generation and distribution.
Crowd funding for example, startup fund raising.
Crowd operations, for example, electronic voting.
Identity management, for example, one ID for all your life's functions.
And government public records and open governing.
Moreover, blockchain can enable an inclusive economy.
It can enable a person in a remote corner of the world
to partake in a democratic process.
Opportunities for innovative applications are endless.
There is a dire need for critical thinkers, designers and developers who can
envision and create newer application models on blockchain to benefit the world.
This course is a first step in addressing this need.
At the end of this course, you will be able to explain the three fundamental
characteristic that define the blockchain using Bitcoin blockchain.
Bitcoin is not the only player in town.
By the end of the first module, we move beyond Bitcoin into introducing the next
generation blockchains with Ethereum.
You will also be able to discuss the important features of Ethereum blockchain
that is used as a reference implementation in many newer blockchains.
And explain the algorithms and techniques that enable the blockchain,
including a public gate cryptography and hashing.
Finally, you will be able to outline methods for
realizing trust in a blockchain.
[MUSIC]
Let's begin with an introduction of Bitcoin.
Two major contributions of cryptocurrency Bitcoin are a continuously
working digital currency system, and a model for
autonomous decentralized application technology called the blockchain.
Though our focus is on a general blockchain,
we've to understand the working of the technology behind Bitcoin to fully
appreciate the innovation of blockchain.
We can all agree that the advent of the internet in the world wide web
has transformed every aspect of our lives,
from stock markets to street corner food trucks.
It has enabled a technology explosion with Web 2.0 and
the world of e-commerce applications.
Around 2008, 2009, when the institutions and markets we trusted
went crumbling down, and everybody was running away from the Wall Street,
a mysterious person, or persons, called Satoshi Nakamoto,
introduced a new digital currency, a cryptocurrency called Bitcoin.
Bitcoin enabled an innovative platform for
peer to peer transfer of value without any central authority.
With no central authority, how did Bitcoin realize trust and security?
By implementing software programs for validation, verification,
consensus in a novel infrastructure called the blockchain.
Later on in about 2012, 2013,
computation elements were added to the blockchain infrastructure that has
opened up a whole world of possibilities beyond simple currency transfer.
These innovations are significantly shaping
the direction of Web 3.0 as you will learn in the next four courses.
What is a blockchain?
Blockchain is about enabling peer to peer transaction in a decentralized network.
Establishing trust among unknown peers.
Recording the transaction in an immutable distributed ledger.
Let's understand centralized versus decentralized network
using a common scenario.
Consider a scenario where customer wants to buy an item using her credit card.
Let's enumerate the intermediaries involved in accomplishing this task.
We have a credit card agency, we have a customer bank,
we have a credit cards bank, we have an exchange,
we have the merchant's bank, and finally, the merchant.
This is an example of a centralized system that we are so used to.
Now compare this with a system where peers can transact
directly with each other irrespective of where they are located.
Functions of the intermediaries are shifted to the periphery
to the peer participant in the blockchain infrastructure.
Peers are not necessarily known to each other.
This is a decentralized system.
How do we establish trust among the peers in such a decentralized system?
By having a process in place to validate, verify, and confirm transactions.
Record the transaction in a distributed ledger of blocks, create a tamper-proof
record of blocks, chain of blocks, and implement
a consensus protocol for agreement on the block to be added to the chain.
So, validation, verification, consensus, and
immutable recording lead to the trust and security of the blockchain.
Now I'll explain these concepts using another scenario.
I'm lending Amy $10,000.
This is one single peer to peer transaction.
We both make a note of it on a ledger.
What if I change my entry from 10,000 to 11,000?
Alternatively, Amy changes hers from 10,000 to 1,000.
To prevent this trust violation,
we need to seek the help of people around us, Lisa, Allison, and Francis.
Provide all of them a valid copy of this ledger.
This is the basic concept of an immutable distributed ledger
defined in a blockchain process.
In this scenario, we were all physically present in one location, Amherst.
Now imagine this to be an online transaction to an unknown peer.
Also, scale up the one transaction to 10,000 transactions,
how about a million transactions.
I should be able to transact with equal ease to any unknown peer in Amherst,
Albany, or Albania, maybe to send some flowers to a friend in Albania.
This is the tenet of a decentralized system supported by blockchain.
In the case just described, how do we trust our unknown peers?
Through verification and validation.
In our example, Amy requests Kevin to verify the amount I transacted with her.
Kevin checks it, oops, Kevin finds the amount of the transaction is not 10,000,
but 300, not valid.
Kevin rejects and nullifies the transaction.
Similar to these, validation, then verification methods devised by the blockchain and
implemented by the peers provide the collector trust needed in a decentralized system.
Summarizing, blockchain technology supports methods for a decentralized peer-to-peer
system, a collective trust model, and a distributed immutable ledger of records of
transactions.
Did Bitcoin enable a centralized or a decentralized system for exchange of value?
Decentralized
Centralized
Correct
Correct! Blockchain is about enabling peer-to-peer transactions in a decentralized network.
1 / 1 point
2.Question 2
Validation, Verification, Immutable Recording, and _____ lead to Trust and Security.
Algorithms
Consensus
Tokens
Coins
Correct
Correct! This process is in place for an agreement on the block to be added to the chain.
1 / 1 point
3.Question 3
Who introduced the digital online cryptocurrency known as Bitcoin?
Wei Dai
Hal Finney
Nick Szabo
Satoshi Nakamoto
Correct
Correct! This is the name of the person/group of people who developed bitcoin, authored the
bitcoin white paper, and created and deployed bitcoin's original reference implementation
1 / 1 point
4.Question 4
A blockchain enables peer-to-peer transfer of digital currency without any intermediaries
such as bank. True or False?
True
False
Correct
Correct! The functions of the intermediaries are shifted to the periphery,
2. Blockchain Structure Unspent Transaction Output, UTXO, Unspent Transaction
Output, UTXO, How the NSA identified Satoshi Nakamoto
Here is the basic structure of a blockchain. Transaction is the basic element of the Bitcoin
Blockchain.
Transactions are validated and broadcast.
Many transactions form a block.
Many box form a chain through a digital data link.
Blocks go through a consensus process,
to select the next block that will be added to the chain.
Chosen block is verified,
and added to the current chain.
Validation and consensus process are carried out by special peer nodes called miners.
These are powerful computers executing software defined by the blockchain protocol.
Let's now discuss the details of a single transaction in bitcoin.
A fundamental concept of a bitcoin network is an Unspent Transaction Output,
also known as UTXO.
The set of all UTXOs in
a bitcoin network collectively defined the state of the Bitcoin Blockchain.
UTXO's are referenced as inputs in a transaction.
UTXO's those are also outputs generated by a transaction.
All of that UTXO's is in a system,
are stored by the participant nodes in a database.
Now let's review the role of the UTXO's in a Bitcoin Blockchain.
The transaction uses the amount specified by
one or more UTXOs and transmits it to one or more newly created output UTXOs,
according to the request initiated by the sender.
The structure of a given UTXO is very simple.
It includes a unique identifier of the transaction that created this UTXO,
an index or the position of the UTXO in the transaction output list,
a value or the amount it is good for.
And an optional script,
the condition under which the output can be spent.
The transaction itself includes a reference number of the current transaction,
references to one no more input UTXOs,
references to one or more output UTXOs newly generated by the current transaction,
and the total input amount and output amount.
Participants can validate the transaction contents.
Does the UTXO's reference input exist in the network state?
This is the only one of the many validation criteria.
Recall our demonstrated scenario.
This is similar to Amy asking Kevin to verify the money in the envelope to be $10,000.
Are these UTXOs valid? All right.
It is time to explore the real transaction.
It is available at this link.
At the top left is the transaction number.
Just below, there are three input UTXOs referenced.
And an arrow points to the references of the two output UTXOs.
Note that there are three input UTXOs and only two output UTXOs.
This means that the total amount in
three input UTXOs are spent to generate two new output UTXOs.
Just below the output UTXOs is a total amount transferred in the Bitcoin value.
And that is shown in green.
Let's now move on to learn about a block.
As you can see, a block is composed of a header of information about the block,
and a set of valid transaction.
At first, we'll examined the genesis block.
It's available at this link.
We introduce this block number zero for posterity's sake.
This is where it all began.
Satoshi Nakamoto initiated the Bitcoin Blockchain with
one transaction of 50 Bitcoins or 50 BTC.
This one transaction created a UTXO output for half in his address.
The data the Blockchain creation is January third, 2009.
There was no previous block.
This field is all zeros.
It also list a block reward or minus fees of 50 BTC.
We'll discuss minus reward in our later lessons.
Let's now look at the more recent block 482808.
On the right panel,
note the current block hash.
The previous block hash that there's a link to the previous block.
And on the left panel down here, the Nonce.
You will learn about the block hash computation in
the module quiz and in the later lessons.
Now, let's look at the structure of
the Blockchain by peeking into the Bitcoin Blockchain.
Our goal is to understand the link between the blocks.
Let's consider the chain of three blocks: 488867, 488868.
488869. 488868 shown in the middle,
has the hash of 488867 as its previous hash.
Block 488869 has the hash of 488868 as its previous hash,
forming the links in the chain.
To summarize, transaction bring about transfer of value in the Bitcoin Blockchain.
The concept of UTXO defines the inputs and outputs of such a transaction.
Once a block is verified an algorithmic-ally agreed upon by the miners,
it is added to the chain of blocks, namely the Blockchain.
A block in a Blockchain has a header and _______________.
Transactions
Bitcoins
Inputs
Digital Ledger
Correct
Correct! A block is composed of a header of information about the block and a set of valid
transactions.
1 / 1 point
2.Question 2
What does UTXO stand for?
Unspent Trade Offer
Unique Transaction Offer
Unspent Transaction Xeroxed Output
Unspent Transaction Output
Correct
Correct! UTXOs are outputs generated by a transaction.
1 / 1 point
3.Question 3
A transaction generates new UTXOs for transferring the amount specified in the input
UTXOs. True or False?
False
True
Correct
Correct! The transaction uses the amount specified by one or more input UTXOs and
transfers it to one or more newly created output UTXOs.
1 / 1 point
4.Question 4
Miners are computers that execute ____.
operations defined by the blockchain protocol
operations defined by users
operations defined by transactions
Correct
Correct! Miners are powerful computer executing software defined by the Blockchain
protocol.
3. Basic Operations How a Bitcoin Transaction Works, How does the Blockchain
Work? (Part 1), How Does the Blockchain Work?
Now that we have reviewed the basics of a blockchain and its basic structure and origin,
let's consider the basic operations in a blockchain. Operations in the decentralized network
are the responsibility of the peer participants and their respective computational nodes.
For example, laptop, desktop, and server racks. These operations include validation
transactions, gathering the transactions for a block, broadcasting the ballot transactions in the
block, and consensus on the next block creation, and chaining the blocks to form an
immutable record.
In this lesson, we explore some of the fundamental operations of the bitcoin blockchain.
First, we have to discuss the participants. There are two major roles for the participants.
Participants that initiate transfer of value by creating a transaction, additional participants
called miners, who pick on added work or computation to verify transactions, broadcast
transaction, compete to claim the right to create a block, work on reaching consensus by
validating the block, broadcasting the newly created block, and confirming transactions.
You might wonder why participant would take on additional work.
Well, the miners are incentivised with bitcoins for the efforts in managing the blockchain, as
we'll find out. Transaction validation is carried out independently by all miners.
The process involves validation of more than 20 criteria, including size, syntax, et cetera.
Some of these criteria are: Referenced Input Unspent Transaction Output, UTXOs are valid,
recall, UTXO is well-defined earlier in lesson two, reference output UTXOs are correct,
reference input amount and output amount matched sufficiently, invalid transactions are
rejected and will not be broadcast. All the valid transactions are added to a pool of
transactions. Miners select a set of transaction from this pool to create a block.
This creates a challenge. If every miner adds the block to the chain, there will be many
branches to the chain, resulting in inconsistent state. Recall, the blockchain is a single
consistent linked chain of flux. We need a system to overcome this challenge, the solution.
Miners compete to solving a puzzle to determine who earn the right to create the next block.
In the case of bitcoin blockchain, this parcel is a computation of parcel and the central
processing unit or CPU intensive.
Once a miner solves the puzzle, the announcement is broadcast to the network and the block
is also broadcast to the network. Then, other participant verify the new block. Participants
reach a consensus to add a new block to the chain. This new block is added to their local copy
of the blockchain. Thus, a new set of transactions are recorded and confirmed. The algorithm
for consensus is called proof-of -work protocol, since it involves work a computational power
to solve the puzzle and to claim the right to form the next block. Transaction zero, index zero
of the confirmed block is created by the miner of the block. It has a special UTXO and does
not have any input UTXO. It is called the coinbase transaction that generates a minor's fees
for the block creation. Currently, the minor's fees is 12.5 BTC for a bitcoin. This is how new
coin is maintained in bitcoin. To summarize, the main operations in a blockchain are
transaction validation and block creation with the consensus of the participants. There are
many underlying implicit operations as well in the bitcoin blockchain.
The algorithm for consensus in the Bitcoin blockchain is called _____ protocol.
Proof of Worth
Proof of Elapsed Time
Proof of Stake
Proof of Work
Correct
Correct! It gets its name because it involves “work” or computational power to solve the
puzzle and to claim the right to form the next block.
1 / 1 point
2.Question 2
Transaction confirmation is independently performed by all miner nodes. True or False?
False
True
Correct
Correct! Miners, take on added work or computation to verify transactions, broadcast
transactions, compete to claim the right to create a block, work on reaching consensus by
validating the block, broadcasting the newly created block and confirming transactions.
1 / 1 point
3.Question 3
Transaction 0 in every block in the bitcoin blockchain ____.
is for paying the miner fees.
does not have any input UTXO.
is called the coinbase transaction
All of the above.
Correct
Correct!
4. Beyond Bitcoin A Gentle Introduction to Blockchain Technology, On Public and
Private Blockchains, On Public and Private Blockchains, 2017 Was Bitcoin's Year. 2018
Will Be Ethereum's, What is Cryptocurrency: Everything You Need To Know , What is
the Difference Between Public and Permissioned Blockchains?
Let's now look beyond Bitcoin. Bitcoin blockchain is open-source and the entire code is
available on the GitHub. During the initial years beginning roughly in 2009, this open-source
code was extended to release different cryptocurrencies. About 300 plus cryptocurrencies
were introduced. Bitcoin supports an optional and special feature called scripts for
conditional transfer of values. Ethereum Blockchain extended the scripting feature into
a full-blown code execution framework called smart contract.A smart contract provide the
very powerful capability of code execution for embedding business logic on the blockchain.
Based on such capabilities, three major types of blockchains emerge from Bitcoin foundation.
Type one deals with the coins in cryptocurrency currency chain. Example, Bitcoin.
Type two supports cryptocurrency and a business logic layer supported by code
execution. Example, ethereum. Type three involves no currency but supports software
execution for business logic. Example, The Linux Foundation's Hyperledger.
With the addition of code execution, comes the serious consideration about public access to
the blockchain hence, the classification of public, private, and permissioned blockchains
based on access limits. We have been watching Bitcoin blockchain continuously operational
since its inception. All supported by its public participants. Thus Bitcoin is a fantastic
example of a public blockchain class. Anybody can join and leave as they wish. Transaction
blocks and the blockchain are publicly observable even though participants are anonymous.
It is open-source. You can also create new coin digital currency by modifying the Bitcoin
code. Wallet applications provide the basic interface to transfer value through the Bitcoin
blockchain. In a private blockchain, access to the blockchain is limited to selected
participants for example, those participants within an organization. This restriction helps in
simplifying the normal operations such as block creation and contingence model.The third
classification of blockchain is permissioned blockchain, also called consortium blockchain. It
is meant for a consortium of collaborating parties to transact on a blockchain for ease of
governance, provenance, and accountability for example, a consortium of all automobile
companies or healthcare organizations. Permissioned blockchain has the benefits of a public
blockchain with allowing only users with permission to collaborate and transact. In summary,
significant innovations such as smart contracts have opened up broader applications for
blockchain technology. Private and permissioned blockchain allow for controlled access to
the blockchain enabling many diverse business models.
In a public blockchain, a participant can join and leave the blockchain as and when they wish.
True or False?
True
False
Correct
Correct!
https://etherscan.io/
https://blockexplorer.com/
https://www.blockchain.com/explorer
Blockchain, Bitcoin Block Explorer , Etherscan
A. Blockchain Defined - Week 1
Latest Submission Grade
88.88%
1.Question 1
What is the genesis block?
Any block created by the founder
The first transaction in each block
The first block of a Blockchain
The last block created in the Blockchain
Correct
Correct.
1 / 1 point
2.Question 2
Inspect and explore block #0 using this link to solve the below question.
How many transactions are there in the Genesis block in Bitcoin?
8893
10
Correct
Correct.
1 / 1 point
3.Question 3
Inspect and explore block #0 using this link to solve the below question.
How many transactions are there in the Genesis block in Ethereum (other than the transaction
for Miner fee)?
50
8893
1
Correct
Correct.
1 / 1 point
4.Question 4
Inspect and explore block #490624 using this link to solve the below question.
What is the hash of the previous block for Bitcoin block #490624? Copy and paste the answer
into the box below.
0000000000000000004239f2a01d8f579bc0dbb214d0f874ece5db587bee3457
Make sure you are checking for the parent hash(hash of the previous block) for the given
bitcoin block ID.
5.Question 5
Inspect and explore block #490624 using this link to solve the below question.
Which of these fields is present in a Bitcoin block summary?
Gas Used
Gas Limit
Private Key of the Sender
Difficulty
Correct
Correct.
1 / 1 point
6.Question 6
Where are the transactions recorded in a blockchain?
On a SQL Database
On a centralized immutable ledger
On a SQLite Database
On a distributed immutable ledger
Correct
Correct.
1 / 1 point
7.Question 7
What are UTXOs in a Bitcoin Blockchain?
These are rewards for miners
These are actual currency that is sent to the receiver of a transaction
These form the inputs and outputs for transactions
These are transaction output that has been expended
Correct
Correct.
1 / 1 point
8.Question 8
Blockchain was created to support security and trust in a ___________ environment of the
cryptocurrency Bitcoin.
decentralized trustless
decentralized trusted
centralized trustless
centralized trusted
Correct
Correct!
1 / 1 point
9.Question 9
What/Who are miners in a blockchain?
A person who receives money as the receiver of the transaction
An algorithm that you can use to calculate the next block in a blockchain
Computers that validate and process blockchain transactions and solve the
cryptographic puzzle to add new blocks
A person who just initiates a transaction in the blockchain
Correct
Correct.
Week 2 Smart Contracts Smart Contracts: The Blockchain Technology That Will
Replace Lawyers, Introduction to Smart Contracts, What is Ethereum?
Etherem Block Chain smart Contracts
Bitcoin blockchain is the mother of all blockchains.
It was intended for peer to peer transfer of value and it does that well.
Around 2013, a framework for code execution was introduced by Ethereum Founders.
The centerpiece and thrust of this Ethereum blockchain is a smart contract.
Consider this togged diagram comparing Bitcoin and Ethereum blockchain.
On the left is
the Bitcoin blockchain and a wallet application for initiating transactions.
On the right is Ethereum that took
a significant step towards transforming the blockchain into
a computational framework that opened up
a whole world of opportunities in the decentralized realm.
Ethereum supports smart contracts and of
virtual machine on which smart contracts execute.
Smart contracts in turn enable
decentralized application that accomplish more than a transfer of value.
Efficient automation of decentralized application such as supply chain.
Smart contract is an important topic that we have
allocated a full course for this topic in this specialization.
In this module, of course, one,
we provide a high level overview of smart contract as it relates to Ethereum.
After completing this module on Ethereum,
you will be able to discuss at a high level the innovation of the ethereum blockchain,
namely the smart contract.
Illustrate ethereum blockchain protocol,
structural elements, and operational aspects.
Demonstrate the concept of gas,
the fuel or the payment model for
code execution and the incentive model for the Ethereum blockchain.
What is a smart contract?
Let's review the basics.
A smart contract is a piece of code deployed in the blockchain node.
Execution of a smart contract is initiated by a message embedded in the transaction.
Digital currency transfer request simple addition and subtraction.
Ethereum enables transaction that may carry out more sophisticated operations.
For example, a transaction could require a conditional transfer,
it may require some evaluation,
it may need more than one signature for transfer of assets,
or it may involve waiting for a specific time or date.
Let's consider an example of what a smart contract can do.
An auction bidding smart contract could execute this logic.
If the age of a bidder is greater than 18 and the bid is greater than the minimum bid,
then, accept the bid,
or else reject the bid.
This can be done by a smart contract.
What does the smart contract look like?
How do you write a smart contract?
Structurally, a smart contract resembles a class definition in an object oriented design.
It has data, functions or methods with modifiers public or private,
along with getter and set of functions.
Specific programming languages have been designed for coding smart contracts.
Solidity is one such language.
Let's examine a simple Solidity smart contract to understand its structure.
First line with pragma indicates the version of the solidity language.
The contract's name is in the first line.
This particular contract is for one integer storage.
The data for the integer is defined with type a name, uint StoredData.
Two functions are defined for writing and reading the data.
Set and get. Code execution.
Where does the code in the smart contract get executed?
Where is it located in a node?
We need a computational infrastructure to execute any arbitrary code.
Every node in Ethereum network should be able to execute the code
irrespective of that underlying type of hardware or operating system.
Enter Ethereum Virtual Machine, EVM.
An EVM provides a run anywhere obstruction layer for the contract code.
A smart contract written
a high level programming language is translated into EVM byte code,
and then, deployed on the Ethereum Virtual Machine, EVM.
Every node will host the same smart contract codes on the EVM.
Summarizing, smart contracts add a layer of
logic and computation to the trust infrastructure supported by the blockchain.
Smart contracts allow for execution of code.
Enhancing the basic value transfer capability of the Bitcoin blockchain.
The code for this smart contract is written in
a high level language like Solidity and compiled into byte code.
The code for the smart contracts is executed on
a special structure known as Ethereum Virtual Machine.
Practitioner's Perspective: The Enterprise
Ethereum has worked out marvelously on how to solve these problems of
scaling and privacy and a number of other issues that needed to be worked out for public
networks. You have the Enterprise Ethereum Alliance that is the largest organization of
entities working on the Ethereum protocol and maturing it into something that industry can
use. But at the same time, companies around the Hyperledger project, Fabric and Iroha and
Sawtooth and all these other protocol initiatives under the Linux Foundation and what they
call the Hyperledger project.
That has led to a whole bunch of
other breakthroughs around channels and contracts segregation.
So you remember I was saying,
you and I have an agreement and we need to
all be in control but not anyone having the control system.
All right, well that's fine.
But if you and I have a confidential agreement and
nearly all business to business agreements are confidential.
It says right on the contract it says,
''not only is this contract confidential between you and me,
the existence of it is confidential.''
Most of the pharmaceutical industry operates on this.
The medical industry operate on this principle for good and bad.
You could say, ''Well we'd like some more transparency there.''
But we also don't want your medical records out in the clear,
and we don't want the fact that you're even
paying for a particular drug to be out in the clear.
Right? Or that you're using a particular drug. That's not Okay.
So, we need transparency for some things and
opacity for other things and getting that mix right is really hard.
So, we need things like channels and charting and now in Ethereum plasma and
what we call Layer two technologies that are coming out this year and next that really
will transform our concept of block chain.
I. WEEK 2, LESSON 1 RESOURCES: SMART CONTRACTS.
The following resources were selected to provide an overview of the topic of Smart
Contracts. We would like to acknowledge the authors of the various web articles, videos, and
papers for their insightful discussions and analytics which helped form the basis for some
sections of the lessons and modules.
Title of resource: Smart Contracts: The Blockchain Technology That Will Replace
Lawyers
Resource type: Website
Description: Article explains what smart contracts are and how they allow for the disposal of
intermediaries which will saves time and conflict for governments and corporations.
Title of resource: Introduction to Smart Contracts
Resource type: Website
Description: Introduction to the basics of smart contracts and solidity.
Title of resource: What is Ethereum?
Resource type: Website
Description: Introduction to Ethereum, Ethereum Virtual Machine, and how they work.
What allows for the execution of code in the Ethereum Blockchain, while enhancing the basic
value transfer capability of the Bitcoin Blockchain?
Byte-code
Solidity
Smart Contracts
Ethereum Virtual Machine Proof-of-Work
correct
To learn more about the execution of code, please refer back to the video "Ethereum
Blockchain: Smart Contracts".
0 / 1 point
2.Question 2
Solidity has data, functions or methods with modifiers, along with getter and setter functions.
True or False?
False
True
Correct
Correct! It has functions, methods with modifiers, along with getter and setter functions.
Ethereum Structure Smart Contracts: A White Paper , Account Management, Native:
Account management
Bitcoin blocking state was defined in terms of
unspent transaction outputs UTXOs and
a reference implementation of the Wallet application that held the account reference.
Ethereum formally introduce the concept of an account as a part of the protocol.
The account is the originator and the target of a transaction.
A transaction directly updates the account balances as opposed to
maintaining the state such as in the bitcoin UTXOs.
It allows for transmit of value and
messages and data between the accounts that may result in the state transitions.
These transfers are implemented using transactions.
There are two types of accounts,
Externally Owned Accounts and Contract Accounts.
Externally Owned Accounts or EOA are controlled by private keys.
Contract Accounts or CA are controlled by the code and can be activated only by an EOA.
An externally owned account is needed to participate in the Ethereum network.
It interacts with the blockchain using transactions.
A Contract Account represents a smart contract.
Every account has a coin balance.
The participant node can send transaction for Ether transfer
or it can send transaction to invoke a smart contract code or both.
Both types of transaction require fees.
An account must have sufficient balance to meet
the fees needed for the transactions activated.
Fees are paid in Wei.
Wei is a lower denomination of Ether.
One Ether 10 to the power of 18 Weis.
A transaction in Ethereum includes the recipient of the message,
digital signature of the sender authorizing the transfer,
amount of Wei to transfer,
an optional data field or payload that contains a message to a contract,
STARTGAS which is a value representing
the maximum number of computational steps the transaction is allowed.
Gas price a value representing the fee sender is willing to pay for the computations.
Let's examine an actual Ethereum transaction at the following address.
Elapsed time values may be different than those recorded at the time of this recording.
Observe transaction hash, height of the chain,
timestamp, from and to accounts,
value transport, gas limit,
gas used, transaction receipt,
success in this case and nonce.
This particular transaction is in walking a smart contract.
Of course the smart contract execution incurs fees
and the amount available is specified by the various gas fields.
Ethereum block structure has a header,
transaction, and runner-up block headers. Block details.
This is an actual Ethereum block at the height 4 4 4 6 3 0 8.
You can actually view this particular block at the link given.
It shows the height,
timestamp, block hash, previous hash,
difficulty and total difficulty,
size, gas used, gas limit,
nonce and block reward.
Summarizing, accounts are basic units of Ethereum protocol.
Externally Owned Accounts and Smart Contract Accounts.
An Ethereum transaction includes not only fields what transfer of Ethers but
also messages for invoking Smart contract.
An Ethereum block contains the usual previous block hash, nonce,
transaction details but also details about gas or fees limits,
the state of the Smart Contracts and Runner-Up headers,
that we'll discuss later.
I. WEEK 2, LESSON 2 RESOURCES: ETHEREUM STRUCTURE
The following resources were selected to provide an overview of the topic of Ethereum
Structure. We would like to acknowledge the authors of the various web articles, videos, and
papers for their insightful discussions and analytics which helped form the basis for some
sections of the lessons and modules.
Title of resource: Smart Contracts: A White Paper
Resource type: White paper
Description: Offers an overview of smart contracts, their types depending on the transaction
involved, and blockchain technology providers.
Title of resource: Account Management
Resource type: Website
Description: Documentation on account management from Ethereum Homestead, an ongoing
collaborative effort of volunteers from the Ethereum Community.
Title of resource: Native: Account management
Resource type: Website
Description: Introduces account management and how it can provide Ethereum integration
for your native applications.
How many types of accounts are on Ethereum?
1
3
2
Correct
Correct! There are two types of Accounts: Externally Owned Accounts and Contract
Accounts.
1 / 1 point
2.Question 2
The _____ can send transactions for ether transfer or they can send transactions to invoke a
smart contract code.
accounts (address)
algorithms
block headers
blocks
Correct
Correct!
1 / 1 point
3.Question 3
What is the smallest denomination of cryptocurrency on Ethereum?
Wei
Gas Point
Bitcoins
Ether
Correct
Correct!
Ethereum Operations How Ethereum Works, What Is Meant By The Term “Gas”?
For a simple Ether transfer,
the amount to transfer and the target address are specified along with the fees or
gas points.The amount and the fees are transferred to their respective accounts.
Here, we illustrate a transaction of
100 Ether transfer between the sender's and receiver's accounts.
Note that besides this transfer,
21,000 gas points are paid to
the miner who added the transaction block to the blockchain.
As discussed in a separate lesson,
an Ethereum node is
a computational system representing a business entity or an individual participant.
An Ethereum full node hosts the software needed for transaction initiation, validation,
mining, block creation, smart contract execution and the Ethereum Virtual Machine, EVM.
This figure depicts the deployment of
a smart contract and the invocation for a smart contract.
Smart contract is designed, developed,
compiled and deployed on the EVM that can be more than one smart contract in an EVM.
When the target address in a transaction is a smart contract,
the execution code corresponding to
the smart contract is activated and executed on the EVM.
The input needed for this execution
is extracted from the payload field of the transaction.
Current state of the smart contract is the values of the variables defined in it.
The state of the smart contract may be updated by this execution.
Results of this execution is told in the receipts.
A blockchain maintains both the state hash and the receipt hash.
We'll elaborate these in a later course on smart contract.
All the transactions generated are validated.
Transaction validation involves checking the time-stamp and
the nonce combination to be valid and the availability of sufficient fees for execution.
Miner nodes in the network receive,
verify, gather and execute transactions.
The in-work smart contract code are executed by all miners.
Validated transactions are broadcast and gathered for block creation.
The consensus protocol used is a memory-based rather than a CPU-based proof of work.
Who pays for all these operations;
validation, verification and consensus?
In the next lesson,
we'll explore the Incentive Model that answers this question.
I. WEEK 2, LESSON 3 RESOURCES: ETHEREUM OPERATIONS
The following resources were selected to provide an overview of the topic of Ethereum
Operations. We would like to acknowledge the authors of the various web articles, videos,
and papers for their insightful discussions and analytics which helped form the basis for some
sections of the lessons and modules.
Title of resource: How Ethereum Works
Resource type: Website
Description: This article dives deeper into how the platform functions under the hood.
Title of resource: What Is Meant By The Term “Gas”?
Resource type: Website
Description: Answers on Ethereum stack exchange that explains gas and where it comes
from?
____ hosts the software needed for transaction initiation, validation, mining, block creation,
and smart contract execution.
Ethereum full node
EVM
Smart Contract
External Account
Correct
Correct!
1 / 1 point
2.Question 2
_____ receive, verify, gather and execute transactions.
Light wallets
Smart Contracts
Miner nodes
Ethereum Virtual Machine
Correct
Correct!
1 / 1 point
3.Question 3
Any changes to the value of a state variable in a smart contract are stored on the blockchain.
True or False?
False
True
Correct
Correct!
Incentive Model Vitalik Buterin Doubles Down on Ethereum Incentive Strategy, Proof
of Work vs Proof of Stake: Basic Mining Guide
Module two, lesson four, the incentive model.
As we learned earlier in module one,
mining is the process used to secure the network by validating the computations,
collecting them to form a block, verifying them, and broadcasting it.
Ethereum also uses a incentive-based model for block creation.
In this lesson we'll explore some relevant concept about fee structure and
the incentive model.
Every action in Ethereum requires crypto fuel, or gas.
Gas points are used to specify the fees inside of Ether, for
ease of computation using standard values.
Gas points allow for
cryptocurrency independent valuation of the transaction fee and computation fees.
Ether, as a cryptocurrency, varies in value with market swings, but
gas points do not vary.
Ethereum has specified gas points for each type of operation.
Mining process computes gas points required for execution of a transaction.
If the fee specified and
the gas point in the transaction are not sufficient, it is rejected.
This is similar to mailing a letter with insufficient postage.
The letter will not be delivered if it had insufficient postage.
The gas points needed for execution must be in the account balance for
the execution to happen.
If there is any amount left over after the execution of a transaction,
it is returned to the originating account.
So far we looked at the gas related items in a transaction,
now let's look at the gas related items in a block.
Gas limit and gas spent.
Gas limit is the amount of gas points available for a block to spend.
For example, if a block specifies a limit of 1 million 5 hundred
thousand units of gas, and a basic Ether transaction fee is 21,000,
this particular Ethereum block can fit about 70 plain Ether transactions.
If we add smart contract transactions also into this block,
that usually requires more gas, and the number of transactions for
this block will likely be lower.
Gas spent is the actual amount of gas
spent at the completion of the block creation.
Now let's look at the mining incentive model.
The proof of work puzzle winner, miner that creates a new block,
is incentivized with the base fees of three Ethers, and
the transaction fees in Ethereum blockchain.
The winning miner also gets the fees, gas points for
execution of a smart contract transactions.
That there may be other miners who also solve the puzzle besides the winner.
These miners will solve the puzzle, but didn't win the block are called Ommers.
The blocks created by them are called Ommer Blocks.
These are added as Ommer Blocks, or side blocks, to the main chain.
Ommer miners also get a small percentage of the total gas points
as a consolation and for network security.
Summarizing, any transaction in Ethereum, including transfer of Ethers,
requires fees or gas points to be specified in the transactions.
Miners are paid fees for security, validation,
execution of smart contract, as well as for creation of blocks.
We presented a high level view of Ethereum blockchain.
We'll use Ethereum as a reference blockchain in the next two modules and
the following two courses.
I. WEEK 2, LESSON 4 RESOURCES: INCENTIVE MODEL
The following resources were selected to provide an overview of the topic of Incentive
Model. We would like to acknowledge the authors of the various web articles, videos, and
papers for their insightful discussions and analytics which helped form the basis for some
sections of the lessons and modules.
Title of resource: Vitalik Buterin Doubles Down on Ethereum Incentive Strategy
Resource type: Website
Description: An article written by Amy Castor that goes into Vitalik’s incentive strategy for
Ethereum during the Workshop on Trusted Smart Contracts.
Title of resource: Ether
Resource type: Website
Description: Official website of ethereum that lists the most important things to know about
ethers.
Title of resource: Proof of Work vs Proof of Stake: Basic Mining Guide
Resource type: Website
Description: This article will explain the main differences between Proof of Work vs Proof of
Stake and will provide a definition of mining.
A. Self-Check
Total points 3
1.Question 1
GASLIMIT is the actual amount of gas spent at the completion of the Block creation. True or
False?
True
False
Correct
Correct!
1 / 1 point
2.Question 2
What are miners who solved the puzzle but didn't win the block creation called?
Cousins
Sisters
Ommers
Brothers
Correct
Correct!
1 / 1 point
3.Question 3
_________ are paid fees for the creation of a block.
Receivers of transactions in the block
Miners of a block
All full nodes
Senders of transactions in the block
Correct
Correct!
I. WEEK 2 - ETHEREUM BLOCKCHAIN
II. QUIZ RESOURCES
The following resources are provided to assist you in answering the quiz questions. We
would like to acknowledge the authors of the various websites for their platform and
transactions which help form the basis for some sections of the lessons and modules.
Title of Resource: Etherscan
Resource Type: Website
Description: EtherScan is a Block Explorer, Search, API and Analytics Platform for
Ethereum, a decentralized smart contracts platform. You can use this website to explore and
answer questions related to Ethereum Blockchain.
III. QUIZ DIRECTIONS
Task 1: Exploring a Block in the Ethereum Blockchain (Q1-Q2)
In this task, you will inspect and explore block #4390176 in the Ethereum blockchain (You
can explore the Ethereum Blockchain at the Etherscan weblink given above). Locate the
block number, the hash of this block, the hash of the previous block (parent) and the number
of transactions in that block. You may explore other things in the block as well. After this,
you will go to the previous block (block #4390175) and verify if the hash of this block is
same as mentioned in the current block. You can explore the Ethereum Blockchain at the
website listed above.
Task 2: Exploring a Transaction in Ethereum (Q3-Q4)
In this task, you will inspect and explore a specific transaction in Ethereum. You will explore
the transaction with the hash:
0x5edb69874d0900d8857468fbe53715cc1a58137709b8b70e46299bf10983dc09. Use the
Etherscan website above to search for this transaction using the hash value provided. Locate
and inspect the various details mentioned in the transaction, specifically the Transaction
value, the Gas used, the Gas Limit and, the sender and receiver of the transaction.
Inspect and explore block #4390176 using this link to solve the below question.
What is the previous block hash of block #4390176 in Ethereum Blockchain? Provide the
answer in the box below.
0xc253f0917b33
1 point
2.Question 2
Inspect and explore block #4390176 using this link to solve the below question.
What is the total difficulty for block #4390176 in Ethereum Blockchain? Provide the answer
in the box below.
1,226,797,074,50
1 point
3.Question 3
Inspect and explore the transaction with the hash
“0x5edb69874d0900d8857468fbe53715cc1a58137709b8b70e46299bf10983dc09“ using
this link.
Approximately, how many Ethers are transferred in this transaction?
0.00042 ethers
4434720 ethers
21000 ethers
913.268 ethers
1 point
4.Question 4
Inspect and explore the transaction with the hash
“0x5edb69874d0900d8857468fbe53715cc1a58137709b8b70e46299bf10983dc09“ using
this link.
What is the address of the sender in this transaction? Provide the answer below in the
textbox.
0xf9fba58d8345b
1 point
5.Question 5
Which of the following is true about an externally owned account (EOA) in Ethereum
Homestead?
EOAs can send transactions (ether transfer or invoke a contract code)
EOAs execute code when triggered by a transaction.
EOAs have associated code with them.
1 point
6.Question 6
External Owned Accounts (EOA) are controlled by ____.
Private Key
Hash of the first transaction by that account
Public Key and Private Key
Public Key
1 point
7.Question 7
What is the differentiating factor between the Ethereum Blockchain and the Bitcoin
blockchain?
Distributed ledger
Currency Exchange
Wallets
Smart contracts
1 point
8.Question 8
Calculate the amount of gas points required to execute an operation that involves 2 steps and
1 load from memory. Use the following image.
42
22
23
1 point
9.Question 9
What is the correct sequence involved in a block creation:
1. Transactions validated
2. Transactions Bundled & broadcasted
3. Transaction initiated
4. Block added to the local chain and propagated to the network.
5. Proof of work consensus problem solved
3,2,1,4,5
5,3,1,2,4
3,1,2,5,4
1,2,3,4,5
1 point
I understand that submitting work that isn’t my own may result in permanent failure of this course or
deactivation of my Coursera account.
Week 3
Public Key Cryptography: What Is Public-Key Cryptography?, Asymmetric
Cryptography (Public-Key Cryptography), Public Key Cryptography - Computerphile
Two techniques are predominantly used for securing
the chain and for efficient validation and verification.
Hashing and asymmetric key encryption.
These techniques depend on several complex proven algorithms.
We provide a high level view of the application of these algorithms,
and the critical role they play in securing
the decentralized chain in the four lessons of this module namely;
Public-key cryptography, secure hashing,
transaction integrity, and block integrity.
We'll begin this module by discussing the concept of asymmetric key encryption,
then we'll define the concept of hashing,
followed by the algorithms used for various hashing needs of the block chain protocol.
We then explain the techniques that use these algorithms,
to manage the integrity of the transactions and the blocks in a block chain.
Learning outcomes of this module are;
to summarize the working of the Public-key cryptography,
explain simple hashing and Merkle tree hashing,
explore the application of hashing and cryptography in protecting the blockchain.
Recall that blockchains decentralized network participants,
are not necessarily known to each other.
Credentials cannot be checked by the conventional means such
as verifying who you are with your driver's license.
Participants can join and leave the chain as they wish.
They operate beyond the boundaries of trust.
Given this context.
how do you identify the peer participants?
How do you authorize and authenticate the transactions?
How do you detect forged or faulty transactions?
We can do these things by using
Public-key cryptography algorithm that we'll discuss in this lesson.
Let's begin by examining simple symmetric key encryption.
The same key is used for encryption and decryption,
so it is called symmetric key.
Example, Ceasar encryption is the simplest
one with alphabets of a message are shifted by a fixed number,
and this number is called the Key.
In this example F is a function defined by shift by three in alphabet.
Consider, "Meet me at the cinema."
You shift by three the S key value of every letter to encrypt it,
and your receiver decrypts it using the same three as the key.
Shift the other way every character to view the original message.
Three is the key in this trivial example.
Since the same key is used for encryption and decryption, it is a symmetric key.
Note that the key and
the encryption and decryption functions are
typically much more complex in a real application.
Note that symmetric key encryption has issues.
Number one, it is easy to derive the secret key from the encrypted data.
And number two, the key distribution,
how do you pass the key to the participant transacting?
These issues are further exasperated in
a block chain decentralized network where participants are unknown to each other.
Let's now examine how Public-key cryptography addresses these issues.
Instead of a single secret key,
it employs two different keys that take care
of both the issues of symmetric key encryption.
Let, lowercase b uppercase B be
the private public-key pair for a participant in Buffalo New York USA.
Let lowercase k and uppercase K be
the pair of keys for the participant and Kathmandu Nepal.
Public-key is published, private key is kept safe and locked.
Typically using a passphrase and the pair works as follows;
encrypting function holds two properties with a key pair.
The public-key private key pair has
the unique quality that even though a data is encrypted with the private key,
it can be decrypted with the corresponding public-key and vice versa.
Now let's look at an example,
authenticate the sender and the receiver.
We'll examine just one common use of a symmetric key encryption.
Let's say a participant in Buffalo wants to transact with the participant in Kathmandu.
Instead of sending just a simple message,
a participant in Buffalo will send a transaction data encrypted by Buffalo's private key,
and then encrypted by Kathmandu's public key.
Kathmandu will first decrypt the data using its own private key,
then use Buffalo's public key to decrypt assigned transaction data.
This ensures that only Kathmandu can decrypt and receive
the data and that only Buffalo could have sent the data.
A popular implementation of public key,
private key is the Rivest Shamir Adleman (RSA) algorithm.
Common application of RSA is the passwordless user authentication,
for example for accessing a virtual machine on Amazon cloud.
Though RSA is very commonly used in many applications,
block chains need a more efficient and stronger algorithm.
Efficiency is a critical requirement since public key pair is
frequently used in many different operations in block chain protocol.
Elliptic Curve Cryptography, ECC family of algorithms is
used in the bitcoin as well as an Ethereum block chain for generating the key pair.
Why ECC not RSA?
ECC is stronger than RSA for a given number of bits.
Did you know that 256 bit ECC key pair is equal in
strength to about 3072 bits of RSA key pair.
Both bitcoin and Ethereum use ECC based algorithms for their encryption needs.
I. WEEK 3, LESSON 1 RESOURCES: PUBLIC-KEY CRYPTOGRAPHY
The following resources were selected to provide an overview of the topic of Public-Key
Cryptography. We would like to acknowledge the authors of the various web articles, videos,
and papers for their insightful discussions and analytics which helped form the basis for some
sections of the lessons and modules.
Title of resource: What Is Public-Key Cryptography?
Resource type: Website
Description: A look at the encryption algorithm and its security benefits
Title of resource: Asymmetric Cryptography (Public-Key Cryptography)
Resource type: Website
Description: Article explains what Asymmetric cryptography is and how it works
Title of resource: Public Key Cryptography - Computerphile
Resource type: Video (Run time- 6:19)
Description: Youtube video that explains how public key cryptography works.
A popular public-private key implementation known as Rivest-Shamir-Adelman (RSA)
algorithm is used for the Bitcoin and Ethereum Blockchain. True or False?
True
False
Correct
Correct!
1 / 1 point
2.Question 2
For the simple symmetric key example discussed in the lecture, it is easy to derive the
“secret” key from the encrypted data. True or False?
False
True
Correct
Correct! Please note that symmetric keys have other issues such (i) key distribution -- how do
you send the key to the parties involved (ii) you need to create different secret key for
different receivers, you cannot share the same key with different participants.
On the contrary, in a public-key encryption, you can publish the public key for any
participant to use and not reveal the private key.
1 / 1 point
3.Question 3
256 bit ECC key-pair is equivalent in strength to approximately 3072-bit RSA key-pair. Thus
ECC is much stronger encryption than RSA method. True or False?
True
False
Correct
Correct!
Hashing, What Is Hashing? Under The Hood of Blockchain, SHA: Secure Hashing
Algorithm - Computerphile, Hash Functions, Blockchain demo
Why should we learn about encryption hashing, you may ask.
The private public key pair is
a metaphorical passport to participating in transacting on the blockchain.
Similar to how you learn to use a credit card,
secure it and protect it.
You need to protect the private key for the security of your assets on the blockchain.
In this lesson, we learn hashing that plays a critical role in the blockchain process,
and also in the integrity of the transaction and confidentiality of data.
You'll keep hearing the words hash rate, hash power,
hash this, hash that frequently in the blockchain world.
For these reasons, you ought to have some basic understanding of hashing techniques.
The primary goal of this lesson is to provide you with this knowledge.
What is hashing? A hash function or hashing transforms and maps
an arbitrary length of input data value to a unique fixed length value.
Input data can be a document,
tree data, or a block data.
Even a slight difference in the input data
would produce a totally different hash output value.
The following are two basic requirements of a hash function.
The algorithm chosen for the hash function should
be a one-way function and it should be collision free,
or exhibit extremely low probability of collision.
The first requirement is to make certain that no one can
derive the original items hashed from the hash value.
Can you make potatoes out of mashed potatoes?
The second requirement is to make sure that
the hash value uniquely represents the original items hashed.
There should be extremely low probability that
two different datasets map onto the same hash value.
These requirements are achieved by choosing a strong algorithm such as secure hash,
and by using appropriately large number of bits in the hash value.
Most common hash size now is 256 bits and
the common functions are SHA-3, SHA-256 and Keccak.
Hash value space, how good is 256 bits hash?
A 256-bit hash value space is indeed very large.
2 to the power of 256 possible combinations of values.
That is approximately 10 to the power of 77.
That is 10 followed by 77 zeros.
Odds of a meteor hitting your house is higher than
generating two of the same hash values of 256 bits when applying this algorithm.
Great. Let's proceed to explore some techniques now.
We'll compare two different approaches for hashing based
on how the constituent elements are organized.
A simple hash and a Merkle tree hash.
Here we illustrate simple hashing and Merkle tree hashing with ADD as a hash function.
We use the data 10, 4, 6,
21 and 19 and ADD as a hash function.
Actual hashing functions are quite complex and are variations of SHA-3,
and the data values are much larger,
mainly 256 to 512 bit values.
In the simple hash approach,
all the data items are linearly arranged and hashed.
In a tree-structured approach,
the data is at the leaf nodes of the tree,
leaves are pairwise hash to arrive at the same hash value as a simple hash.
When is a tree-structured hash used?
When is a simple hash used?
When we have a fixed number of items to be hashed,
such as the items in a block header,
and we are verifying the composite block integrity and not the individual item integrity,
we use simple hash.
When the number of items differ from block to block, for example,
number of transactions, number of states,
number of receipts, we use the tree structure for computing the hash.
Note that the state is a variable that may be modified by a smart contract execution,
and the result of the execution may be returned in a receipt.
We'll learn more about their use in course two.
Tree structure helps the efficiency of repeated operations,
such as transaction modification and the state changes from one block to the next.
Log N versus N. Summarizing, in Ethereum,
hashing functions are used for generating account addresses,
digital signatures, transaction hash,
state hash, receipt hash and block header hash.
SHA-3, SHA-256, Keccak-256 are
some of the algorithms commonly used by hash generation in blockchains.
I. WEEK 3, LESSON 2 RESOURCES: HASHING
The following resources were selected to provide an overview of the topic of Hashing. We
would like to acknowledge the authors of the various web articles, videos, and papers for
their insightful discussions and analytics which helped form the basis for some sections of the
lessons and modules.
Title of resource: What Is Hashing? Under The Hood of Blockchain
Resource type: Website
Description: An article that not only explains the basics of hashing but introduces a more
specific type of hashing and how it affects the mining process.
Title of resource: SHA: Secure Hashing Algorithm - Computerphile
Resource type: Video (Run time- 10:20)
Description: Dr. Mike Pound explains how files are used to generate seemingly random hash
strings.
Title of resource: Hash Functions
Resource type: Website
Description: Explanations and examples of simple hash functions and the hashing sequences
of characters.
Title of Resource: Blockchain demo
Resource type: website
Description: This website contains a hashing tool.
What is one of the requirements of secure hashing function?
It is an ECC function
It is log function
It is a one way function
It is a secret function
Correct
Correct!
1 / 1 point
2.Question 2
What type of hash is used when there is a fixed number of items to be hashed, such as the
items in a block header, and we are verifying the composite block integrity?
Complex hash
Simple Hash
Either
Tree-structured Hash
Correct
Correct!
1 / 1 point
3.Question 3
What type of hash function is used, when there is variable number of items to be hashed, such
as the many state changes in a block?
Complex hash
Tree-structured Hash
Either
Simple Hash
Correct
Correct!
1 / 1 point
4.Question 4
Keccak 256 is a commonly used algorithm for hash generation in Ethereum blockchain. True
or False?
True
False
Correct
Correct!
Transaction Integrity How Safe Are Blockchains? It Depends., Blockchains:
Embedding Integrity,
To manage the integrity of a transaction we need number one,
secure a unique account address.
We need a standard approach to uniquely identify
the participants in the decentralized network.
Number two, authorization of the transaction by the sender through digital signing.
And number three, verification that the content of that transaction is not modified.
We use a combination of hashing and public key cryptography,
that we learned in the last two lessons to solve these problems.
Let's start with the address of the accounts.
Addresses of accounts are generated using public key, private key pair.
Step 1, at 256-bit random number is generated,
and designated as the private key.
Kept secure and locked using a passphrase.
Step 2, an ECC algorithm is applied to the private key,
to get a unique public key.
This is the private public key pair.
Step 3. Then a hashing function is applied to the public key to obtain account address.
The address is shorter in size,
only 20 bytes or 160 bits.
Now that we have the account address,
let's look at the transaction initiated by this address.
A transaction for transferring assets will have to be authorized,
it has to be non-repudiable, and unmodifiable.
They first examined, the digital signing process,
and then apply it to that transaction.
Data is hashed and encrypted.
This is the digital signature.
The receiver gets the original data,
and the secure hash digitally signed.
Receiver can recompute the hash of the original data received,
and compare it with the received hash to verify the integrity of the document.
Now, consider the transaction to be that data.
Step number 1, find the hash of the data fields of the transaction.
Step number 2, encrypt that hash
using the private key of the participant originating the transaction.
Thus, digitally signing the transaction to
authorize and making the transaction non-repudiable.
Step number 3, this hash just added to the transaction.
It can be verified by others decryiptng
it using the public key of the sender of the transaction,
and recomputing the hash of the transaction.
Then, compare the computed hash,
and the hash received at the digital signature.
If that is a match,
accept the transaction.
Otherwise, reject it.
Note that for the complete transaction verification, the timestamp,
nons, account balances, and sufficiency of fees are also verified.
I. WEEK 3, LESSON 3 RESOURCES: TRANSACTION INTEGRITY
The following resources were selected to provide an overview of the topic of Transaction
Integrity. We would like to acknowledge the authors of the various web articles, videos, and
papers for their insightful discussions and analytics which helped form the basis for some
sections of the lessons and modules.
Title of resource: How Safe Are Blockchains? It Depends.
Resource type: Website
Description: Article explains the inherent security risks in blockchain technology, by going
into the differences between public and private blockchains.
Title of resource: Blockchains: Embedding Integrity
Resource type: Website
Description: Article explains why big corporations and financial institutions are spending lots
of time and money looking into Blockchain.
Digital signing of a transaction/document involves, hashing the content of the document and
then ____.
encrypting it with private key
rehashing it
encrypting it with nonce
encrypting it with public key
Correct
Correct!
Securing Block Chain Securing the Blockchain, Is It Chain of Headers Rather Than a
Chain of Blocks? What is a Block Header in Bitcoin?
As we discussed before,
some of the main components of the Ethereum block are the header, the transactions,
including the transaction hash or the transaction root,
and the state radio booth,
the state hash, or the state root.
Integrity of the block is managed by assuring
that the block header contents are not tampered with,
the transactions are not tempered with,
state transitions are efficiently computed, hashed, and verified.
Remember, the block chain is supposed to be an immutable record.
In Ethereum, the block hash is the block of all the elements in the block header,
including the transaction root and state root hashes.
It is computed by applying a variant of
SHA-3 algorithm called Keccak and all the items of the block header.
You would see a real example of
bitcoin block hash in the quiz associated with this module.
A typical block has about 2,000 transactions
in bitcoin and about 100 transaction Ethereum.
We need an efficient way to detect tampering and validate the transaction efficiently.
Hashes of transaction in a block are processed in a tree structure
called Mekle tree hash that we discussed in earlier lesson.
Merkle tree hash is also used for computing the state root hash,
since only the hash of the chained states from block to block have to be re-computed.
It is also used for receipt hash root.
Remember the advantage over flat versus tree representation.
If any transaction is to be verified,
only one path to the tree has to be checked.
You don't have to go through the entire set of transactions.
Smart contract execution in Ethereum results in state transitions.
Every state change requires state root hash re-computation.
Instead of computing hash for the entire set of states,
only the affected path in the Merkle tree needs to be re-computed.
When the state 19 is changed to 20,
that results in the path including 31,
41, and the state root hash 64 to be re-computed.
Only that path is re-computed,
not the entire tree.
Now, let's move on to block hash computation.
Block hash in Ethereum is computed by first computing the state root hash,
transaction root hash and then receipt root hash,
shown at the bottom of the block header.
These roots and all the other items in the header are
hash together with the variable nodes to solve the proof of work puzzle.
Block hash serves two important purposes;
verification of the integrity of the block and the transactions,
formation of the chain link by embedding
the previous block hash in the current block header.
If any participant node tampers with the block,
it's hash value changes resulting in the mismatch of
the hash values and rendering the local chain of the node in an invalid state.
Any future blocks initiated by the node would
be rejected by other miners due to hash mismatch.
This enforces the immutability of the chain.
Summarizing, a combination of
hashing and encryption are used for securing the various elements of the block chain.
Private public key pair and hashing are
important foundational concepts in
decentralized networks that operate beyond trust boundaries.
I. WEEK 3, LESSON 4 RESOURCES: SECURING BLOCKCHAIN
The following resources were selected to provide an overview of the topic of Securing
Blockchain. We would like to acknowledge the authors of the various web articles, videos,
and papers for their insightful discussions and analytics which helped form the basis for some
sections of the lessons and modules.
Title of resource: Securing the Blockchain
Resource type: Website
Description: Article talks about the high profile blockchain incidents that have occurred and
how organizations should move forward.
Title of resource: Is It Chain of Headers Rather Than a Chain of Blocks?
Resource type: Website
Description: Bitcoin Stack Exchange is a question and answer site for Bitcoin cryptocurrency
enthusiasts. Users comment on whether its chain of headers or chain of blocks.
Title of resource: What is a Block Header in Bitcoin?
Resource type: Website
Description: Article explains how to calculate and identify a block header.
In Ethereum, the block hash is the hash of all the elements in the _________ .
Block header
State tree
Transaction hash tree
Receipt tree
Correct
Correct!
1 / 1 point
2.Question 2
Merkle tree hash is used for computing _________ hash.
state root
transaction root
receipt root
all of the above
Correct
Correct!
1 / 1 point
3.Question 3
Block hash allows for the formation of the chain link by embedding previous block hash in
the current block header. True or False?
False
True
Correct
Correct!
1 / 1 point
4.Question 4
If a participant node tampers with a block, it results in ____.
hash changing
mismatch of hash values
the local chain of node rendered in an invalid state
All of the above
Correct
Correct!
I. WEEK 3 - ALGORITHMS AND TECHNIQUES
II. QUIZ RESOURCES
The following resources are provided to assist you in answering the quiz questions. We
would like to acknowledge the authors of the various websites for their platform and
transactions which help formed the basis for some sections of the lessons and modules.
Title of Resource: 1. Blockchain
Resource Type: Website
Description: Blockchain is the world's leading software platform for digital assets. Offering
the largest production blockchain platform in the world and using new technology to build a
radically better financial system. You can use this website to explore and answer questions
related to Bitcoin Blockchain.
Title of Resource: 2. Bitcoin Block Explorer
Resource Type: Website
Description: Block Explorer is an open source web tool that allows you to view information
about blocks, addresses, and transactions on the Bitcoin blockchain. You can use this website
to explore and answer questions related to Bitcoin Blockchain.
Title of Resource: 3. Bitcoin Wiki
Resource Type: Website
Description: A public resource wiki page for the community of Bitcoin users, developers, and
businesses as well as anyone interested in Bitcoin. Here you can find the Block hashing
algorithm in detail.
Title of Resource: 4. Bitcoin Block Hash Calculation
Resource Type: Website
Description: Tool to calculate the hash of a bitcoin block.
Title of Resource: 5. Encryption Tool
Resource Type: Website
Description: Tool to understand the Public-Private key encryption and decryption algorithm
with an example.
III. QUIZ DIRECTIONS
Task 1: Computing a block hash (Q2)
In this task, you are required to compute the block hash for Bitcoin block #490624. You can
choose to use the tool we provided or you can manually follow the block hash algorithm as
provided on the Bitcoin Wiki (Resource 3), linked above.
To compute the hash of a block using the Bitcoin Block Hash Calculation tool, open the
link provided in the Resource 4 above. Get the details required to compute the block hash by
exploring the Bitcoin block #490624 at Resource 1. Blockchain, or Resource 2. Bitcoin
Block Explorer.
Even if you use the tool, it is recommended that you read about the block hashing algorithm
using the Bitcoin Wiki website.
Task 2: Encrypting and decrypting a message (Q3)
In this task, you will perform the encryption and decryption of a message using the Resource
5. Encryption Tool that we have provided. Follow the guidelines in the tool itself to better
understand the concept of Public-Private key encryption
WEEK 3 - ALGORITHMS AND TECHNIQUES BLOCKCHAIN, BITCOIN BLOCK EXPLORER,
BITCOIN WIKI, BITCOIN BLOCK HASH CALCULATION, ENCRYPTION TOOL
A. Algorithms & Techniques - Week 3
Latest Submission Grade
80%
1.Question 1
1) The transaction Merkle Tree root value in a Bitcoin block is calculated using ____.
number of transactions
hash of transactions
none
previous block’s hash
Correct
Correct.
1 / 1 point
2.Question 2
Follow the steps given in the tool at this link to manually calculate the hash of the block
#490624. You can obtain the details required in the tool from this link except for the
timestamp. Please use the timestamp from this link.
What is the hash of the block #490624? Copy and paste the answer.
000000000000000000d4c8b9d5388e42bf084e29546357c63cba8324ed4ec8bf.
0 / 1 point
3.Question 3
Follow the guidelines in the encryption tool at this link to better understand the concept
of Public-Private key encryption and answer the question below.
When encrypting a message with the public key, which key is required to decrypt the
message?
Private Key
Both Public key and Private key
Inverted Public Key
Public Key
Correct
Correct
1 / 1 point
4.Question 4
2) What type of hashing algorithm does Bitcoin blockchain use to determine the hash of a
block?
SHA-512
SHA-1
SHA-256
MD5
Correct
That’s correct. Bitcoin uses: SHA256(SHA256(Block_Header))
1 / 1 point
5.Question 5
In Ethereum, which algorithm is applied to the private key in order to get a unique public
key.
RSA
Keccak
SHA 256
ECC
Correct
That’s correct. Addresses of account are generated using the public key-private key pair.
First, a 256-bit random number is generated and designated as a private key, kept secure and
locked using a passphrase. Then an ECC algorithm is applied to the private key to get a
unique public key.
1 / 1 point
6.Question 6
Which of the following methods can be used to obtain the original message from its
generated hash message using SHA-256?
Hashing the reverse of generated hash
Hashing the generated hash again
Original message cannot be retrieved
Hashing the generated hash again, twice
Correct
That’s correct. SHA-256 is a one-way hash function, that is a function which is infeasible to
invert.
1 / 1 point
7.Question 7
In Ethereum, hashing functions are used for which of the following?
1. Generating state hash.
2. Generating account addresses.
3. Decrypting senders message.
4. Generating block header hash.
1,3,4
1,2,4
1,2,3
2,3,4
Correct
That’s correct. In Ethereum, hashing functions are used for generating account addresses,
digital signatures, transaction hash, state hash, receipt hash, and block header hash.
1 / 1 point
8.Question 8
What is the purpose of using a digital signature?
It supports the integrity of messages
It supports user authentication
It supports both user authentication and integrity of messages
None of the above.
Correct
That’s correct. A valid digital signature gives a recipient reason to believe that the message
was created by a known sender (authentication), that the sender cannot deny having sent the
message, and that the message was not altered in transit (integrity).
1 / 1 point
9.Question 9
Encryption of a message provides ____.
security
nonrepudiation
authentication
integrity
Correct
Correct.
1 / 1 point
10.Question 10
A public key is derived from the ____.
hash of the first transaction by the account
genesis block hash
a different public key
private Key
Incorrect
Week4 Trust EssentialsBlockchain Based Trust & Authentication For Decentralized
Sensor Networks, How the Blockchain will Radically Transform the Economy
In the last module,
we learned about the use of
public key cryptography and hashing for validation of transactions and blocks.
After this module, you will be able to define elements of trust in a blockchain,
security, validation, verification, and consensus;
discuss consensus protocol, an algorithmic
approach to add a new block and to secure the chain;
explain trust and the robustness of the main chain;
illustrate trust in managing exceptional situations such as hard fork and soft fork.
Let us understand trust using
a common everyday scenario in a centralized system such as an airport system.
Say, you want to fly out of the Buffalo airport.
The airport authority would have pre-established
a secure environment for people to arrive and depart.
This establishes the base trust.
Then there is additional trust once you
enter and your passport and travel documents are verified,
validated, and your baggage is screened.
Even more trust in you is established when
the airline staff checks your boarding pass
at the gate and you enter the aircraft to fly.
Now, let's consider a decentralized system.
There is nobody checking your credentials and certifying that you are trustworthy.
Then, how do you do it?
You do it by using algorithms and techniques discussed in the last module.
Let's examine how these will help address the trust issues in a blockchain.
Similar to our airport scenario,
trust in a decentralized blockchain is also about securing, validating,
verifying, and making sure resources needed for transaction execution are available.
This is accomplished by securing the chain using specific protocols,
validating the transaction and blocks for tamper proofing,
verifying the availability of resources for transactions,
and executing and confirming the transactions.
The Trust Trail is defined by these operations: validate transaction,
verify gas and resources,
gather transactions, execute transaction to get a new state, form the block,
work towards consensus, finalize the block by the bidder,
and everyone add the block to their chain and confirm the transactions.
We will examine each of these steps.
Steps one and two are validate transaction and check resources.
In the case of a Bitcoin,
there are about 20 criteria that have to be checked before a transaction is validated,
as discussed in module one,
similarly in the case of Ethereum transaction.
The syntax, the transaction signature, time stamp, nonce,
gas limit, and sender account balance are validated before execution.
The fuel, or gas points,
and other resources available for smart contract execution, are also validated.
Transaction signatures and hash are also verified.
Step number three is execute transactions.
Merkle tree hash of the validated transactions is computed.
This is in Ethereum.
This is the transaction root of the block header.
All miners execute the transaction for either transfer,
as well as for execution of smart contracts.
The state resulting from transaction execution are
used in computing the Merkle tree hash of the states,
the state root of the block header.
The receipt root of the block header is also computed.
In the next lesson, we'll continue to talk about
the next step in trust trail, the consensus process.
I. WEEK 4, LESSON 1 RESOURCES: DECENTRALIZED SYSTEMS
The following resources were selected to provide an overview of the topic of Decentralized
Systems. We would like to acknowledge the authors of the various web articles, videos, and
papers for their insightful discussions and analytics which helped form the basis for some
sections of the lessons and modules.
Title of Resource: Blockchain Based Trust & Authentication For Decentralized Sensor
Networks
Resource type: Website
Description: The article contained on this website summarizes and explores decentralized
authentication and node trust informations.
Title of Resource: How the Blockchain will Radically Transform the Economy
Resource Type: Video - TEDtalk (Run time- 14:58)
Description: In this valuable TEDtalk of the complex (and confusing) technology, Bettina
Warburg describes how the blockchain will eliminate the need for centralized institutions like
banks or governments to facilitate trade, evolving age-old models of commerce and finance
into something far more interesting: a distributed, transparent, autonomous system for
exchanging value.
A. Self-Check
Total points 2
1.Question 1
Trust in a decentralized blockchain is about ____.
securing the chain using specific protocols.
validating the transactions and blocks for tamper proofing.
executing and confirming the transactions.
All of the above
Correct
Correct!
1 / 1 point
2.Question 2
Miners execute the transactions for Ether transfers but are not responsible for the execution of
smart contracts. True or False?
True
False
Correct
Correct!
Consensus Protocol
A secure chain is a single main chain with a consistent state.
Every valid block added to this chain,
adds to the trust level of the chain.
The miners are vying,
are competing to add their block to the chain.
What if everyone wants to add their candidate block to the chain?
Each of the candidate blocks is by a competing miner.
Which is the next block to be added to the chain?
Can they agree on the next block?
Is there a method or a protocol to choose the next block?
Yes, there is. It is called Proof of Work.
Proof of Work uses hashing.
Here is one more application of hashing.
Do you realize now how versatile hashing is?
We will now discuss Proof of Work as used in bitcoin and ethereum.
This is from the point of view of the miner.
First, compute the hash of the block header elements that is a fixed value,
and a nonce that is a variable.
If hash value is less than 2 par 128 for bitcoin,
and less than function of difficulty for ethereum,
the puzzle has been solved.
If it has not been solved,
repeat the process after changing the nonce value.
If the puzzle has been solved,
broadcast the winning block that will be verified by other miners.
Non-winning miner nodes add the new block to the local copy of the chain,
and move on to working on the next block.
The winner gets an incentive for creating the block.
Proof of Work is a consensus protocol used by
bitcoin block chain and also by the current version of ethereum.
The protocol may be the same,
the implementations in these two block chains are different.
Many other approaches such as Proof of Stake,
Proof of Elapsed Time have been proposed.
This is a hotly debated area among the developers of blockchain,
and you can contribute to it.
I. WEEK 4, LESSON 2 RESOURCES: CONSENSUS PROTOCOL
The following resources were selected to provide an overview of the topic of Consensus
Protocol. We would like to acknowledge the authors of the various web articles, videos, and
papers for their insightful discussions and analytics which helped form the basis for some
sections of the lessons and modules.
Title of Resource: A (Short) Guide to Blockchain Consensus Protocols
Resource Type: Website
Description: The article on this website summarizes the different types of proof.
Title of Resource: Review of blockchain consensus mechanisms
Resource Type: Website
Description: The article on this website summarizes the different types of proof.
Title of Resource: Blockchain Expert Explains One Concept in 5 Levels of Difficulty |
WIRED
Resource Type: Video (Run time 17:49)
Description: This video provides a great explanation of blockchain at varying levels of
comprehension. Blockchain, the key technology behind Bitcoin, is a new network that helps
decentralize trade, and allows for more peer-to-peer transactions. WIRED challenged
political scientist and blockchain researcher Bettina Warburg to explain blockchain
technology to 5 different people; a child, a teen, a college student, a grad student, and an
expert.
Practitioners perspectiveA (Short) Guide to Blockchain Consensus Protocols, Review of
blockchain consensus mechanisms, Blockchain Expert Explains One Concept in 5
Levels of Difficulty | WIRED
Something this important needs to be built by all of us for all of us.
You can't just have a small group of people or
one kind of person building this. It's too important.
Even the Internet itself is not as is as pervasively
disruptive and transformative as the Internet on blockchain is going to be,
because the blockchain or the Internet was and
is really an ideal system for broadcasting information.
That was great. That was Guttenberg's best day.
But it didn't invent a way of doing
transactions without having centralized authorities in there,
like banks and others that have issues or like we are seeing with Facebook today.
There are problems with central authorities being in control of your identity,
or your information, or your transactions.
But being able to democratize that and spread it all over the world, that's powerful,
but it's also really powerful,
which means it better be built by more than just a few knuckleheads
in a building with only one perspective on things.
So, it's very important that, A,
these technologies are being built in open source,
but not just in open source,
openly governed open source, meritocracies.
There are hundreds of people all over the world building the protocols for Ethereum,
and Hyperledger and other things.
That's the way it should be.
We need more of that.
We need more kinds of people.
It needs to be a highly diverse group of people.
What's great about blockchain is that, it's so young.
There is no group of people who can tell you that you don't know what they know,
that they're better than you.
Anybody that tells you that they know more about this than you do,
they might know a little more,
but mastery is 13 years and blockchain hasn't been around that long.
Right, so this is your opportunity if you are a student
who isn't represented by a lot of people that look like you or think like you.
This is your shot.
You can get in there and you can say,
"No, I'm the expert.
I'm the master on this," and that's good.
A. Self-Check
Total points 2
1.Question 1
Proof of work is the __________ used by Bitcoin blockchain and Ethereum Byzantium
Metropolis blockchain.
Trust function
Transaction confirmation
Consensus Protocol
Incentive function
Correct
Correct!
1 / 1 point
2.Question 2
An approach for consensus protocol that is hotly debated among developers of blockchain is
Proof of Age
Round Robin
Proof of Stake
Proof of Incentive
Correct
Correct!
Robustness, How The Blockchain Is Redefining Trust
Trust us not only about executing regular operations
correctly but also about managing exception satisfactory.
Robustness is the ability to satisfactorily manage exceptional situations.
It's all the more important in
a decentralized autonomous network such as
a blockchain where there are no intermediaries minding the store.
This lesson is about some of the exceptions
that may occur during the blockchaining process.
We'll discuss just two exceptions in
this lesson and more in future courses of the specialization.
Have you wondered, what if more than one miner
solves the consensus puzzle where it close in time to each other?
What if more than one transaction references as input the same digital asset?
This situation is called double spending.
Handling such exception satisfactorily
is critical for ensuring the security of the blockchain.
We start with the securechain indicated by three blocks and we want to add to this chain.
Here, you see two miners have solved the consensus puzzle very close to each other.
Bitcoin protocol allows this chain split or two chains for the next cycle.
One led by each of the competing blocks.
The probability that the next block will happen at
the same time in both these chains is extremely low.
So the winner of the next cycle for block creation
consolidates one of the chains and that chain becomes the accepted chain.
In this case, the newest block is added to the main chain.
Now this chain is the longest and the valid main chain.
The transaction in the other blocks are returned to the unconfirmed pool.
Summarizing with a very low probability,
the main chain may split but if it does,
the bitcoin protocol has methods to consolidate it to a single chain within a cycle.
Etherium handles more than one person we know by allowing
Omar or Runner-Up blocks and allocating a small incentive for these Runner-Up blocks.
This incentive model helps in keeping the chains secure.
New blocks are added only to the mainchain and not to the Runner-Up chains.
That are Runner-up blocks are maintained for six more blocks after they were added.
Here you see a blockchain with two blocks one at the height,
4567, another one at a height, 4557.
The one deeper inside the chain is more trustworthy than the one newly added.
Let's now add us the double spending problem.
There's a possibility that digital currency
and other consumables are single used digital assets,
can be intentionally or inadvertently reused in transactions.
Analogy time, using our airport flying analogy in lesson one,
this is like an airline double booking a seat on a flight.
In this case, a gate crew solved this problem by using
Ad hoc methods such as asking for volunteers to relinquish their seats for money, etc.
In a decentralized network,
like a blockchain, there is no intermediary.
We need a policy and an automatic deterministic way to handle this situation.
A policy for handling transaction and double spending in
Bitcoin is to allow the first transaction
that reference the digital asset and reject
the rest of the transaction that reference the same digital asset.
In Ethereum, a combination of
account number and a global nonce is used to address the doublet spending issue.
Every time a transaction is initiated by an account,
a global nonce is included in the transaction.
After that, the nonce is incremented.
Time stamp on the nonce in the transaction should be
unique and verified to prevent any double use of digital asset.
Summarizing, well-defined processes for
handling exception improve trust in the blockchain.
There are many other issues such as difficulty adjustment and
hard and soft fork exception that will be
discussed in the next lessons in the courses that follow.
I. WEEK 4, LESSON 3 RESOURCES: ROBUSTNESS
The following resources were selected to provide an overview of the topic of Robustness. We
would like to acknowledge the authors of the various web articles, videos, and papers for
their insightful discussions and analytics which helped form the basis for some sections of the
lessons and modules.
Title of Resource: How The Blockchain Is Redefining Trust
Resource Type: Website
Description: This helpful article highlights how the blockchain can remove intermediaries
from numerous transactions between people, corporations, and a host of other financial
interactions.
What happens if more than one miner solves the consensus puzzle very close in time to each
other in Ethereum?
Runner-up miners leave the network.
The new block is added to the main chain and not the runner-up chain
Small incentives are given to runner-up blocks
Small incentives are given to the runner up blocks and the new block is added to the main
chain
Correct
Correct!
1 / 1 point
2.Question 2
Double spending is reusing digital assets intentionally or inadvertently. True or False?
False
True
Correct
Correct!
1 / 1 point
3.Question 3
In Ethereum, a combination of account number and global nonce is used to address issues
regarding double spending. True or False?
False
True
Correct
Correct!
FORKSHave Blockchain Forks Shown Hayek to be Right or Wrong?, Split on Forks?
Blockchain Leaders Learn Tough Lessons from Bitcoin Scaling, Bitcoin, Blockchain
Forks & Lightning
Trust in Forks, a fork in the path.
Fork, hard fork and soft fork,
are most common phrases uttered in the context of a blockchain.
We hear, at the block 4.7 million,
Ethereum did a hard fork.
Beware, 2018 is a year of hard fork in Ethereum blockchain.
In this lesson, we explain at high level,
hard and soft forks.
Forks are just normal processes in
an evolutionary path of the nascent technology enabling a blockchain.
If robustness and trust is about managing exceptional situations,
hard forks and soft forks are indeed at the front and center.
We discussed change split in the last lesson,
that is a minor perturbation in the chain.
Such situation is handled as a naturally expected occurrence within the block chain.
On the other hand, occasionally,
a minor process adjustment has to be carried out typically
by bootstrapping a new software to the already running processes.
This is soft fork.
For example, the scrypt concept in Bitcoin was introduced using this method.
You can think of this as a software patch or a bug fix to address an issue.
Hard fork implies a major change in the protocol.
For example, the recent change from
Ethereum Homestead to Metropolis Byzantium version was
a planned hard fork and important note
after a hard fork the emerging two chains are incompatible.
Please be aware of this.
There was an unplanned hard fork in Ethereum protocol,
Ethereum Core and Ethereum Classic split,
that was enacted to address a critical software issue in
a decentralized autonomous organization (DAO).
That resulted in a multi-million dollar heist.
We'll discuss this in course three where we study decentralized organizations.
Let's discuss the hard fork that happened on October 17, 2017.
The Ethereum hard fork was a planned fork.
Here are a few Ethereum improvement proposals (EIP) for this fork,
parallel processing of transactions.
Proof of Work consensus still stays except that every hundred block,
Proof of Stake consensus protocol,
is applied for evaluating the latter.
And minor incentive was reduced from 5 ethers to 3 ethers for block creation.
These are just few EIPs.
You can look at the documentation for other EIPs.
Summarizing, soft fork and hard fork in
the blockchain word are like the release of software patches,
and new versions of operating systems respectively.
Forks are mechanisms that add to the robustness of the blockchain framework.
Well-managed forks help build credibility in the blockchain by
providing approaches to manage unexpected faults and planned improvements.
We are lucky that we have a front row seat to
the planned hard fork of Ethereum Homestead to Ethereum Metropolis,
and watch it as it plays out.
I. WEEK 4, LESSON 4 RESOURCES: FORKS
The following resources were selected to provide an overview of the topic of Forks. We
would like to acknowledge the authors of the various web articles, videos, and papers for
their insightful discussions and analytics which helped form the basis for some sections of the
lessons and modules.
Title of Resource: Have Blockchain Forks Shown Hayek to be Right or Wrong?
Resource Type: Website
Description: This valuable article explores the concept of free market money as proposed by
Friedrich Hayek in the 1970’s and its relationship to Blockchain and Bitcoin.
Title of Resource: Split on Forks? Blockchain Leaders Learn Tough Lessons from
Bitcoin Scaling
Resource Type: Website
Description: This website focuses on how developers need to find ways to conduct upgrades
to bitcoin in a smoother manner.
Title of Resource: Bitcoin, Blockchain Forks & Lightning
Resource Type: Video (Run time- 8:40)
Description: In this helpful video, an employee of UCL Security Group summarizes theories
to scale bitcoin.
I. WEEK 4, LESSON 4 RESOURCES: FORKS
The following resources were selected to provide an overview of the topic of Forks. We
would like to acknowledge the authors of the various web articles, videos, and papers for
their insightful discussions and analytics which helped form the basis for some sections of the
lessons and modules.
Title of Resource: Have Blockchain Forks Shown Hayek to be Right or Wrong?
Resource Type: Website
Description: This valuable article explores the concept of free market money as proposed by
Friedrich Hayek in the 1970’s and its relationship to Blockchain and Bitcoin.
Title of Resource: Split on Forks? Blockchain Leaders Learn Tough Lessons from
Bitcoin Scaling
Resource Type: Website
Description: This website focuses on how developers need to find ways to conduct upgrades
to bitcoin in a smoother manner.
Title of Resource: Bitcoin, Blockchain Forks & Lightning
Resource Type: Video (Run time- 8:40)
Description: In this helpful video, an employee of UCL Security Group summarizes theories
to scale bitcoin.
Bootstrapping the new software to the already running processes is known as ____.
Scripting
Hard Forks
Hashing
Soft Forks
Correct
Correct!
1 / 1 point
2.Question 2
After a hard fork, the emerging two chains are incompatible. True or False?
True
False
Correct
Correct!
1 / 1 point
3.Question 3
Bitcoin blockchain implemented a soft fork to realize a ____.
Split into Bitcoin core and Bitcoin cash
P2SH conditional payment script feature
P2SH Peer-to-Shell feature
P2SH payer gossip feature
Correct
Correct!
Which one of the following is correct?
A secure blockchain is a single chain in an inconsistent state.
Neither timestamp nor nonce can be verified.
There is only one, single criteria measured to perform validation.
Once a consensus is met, a new block is added to the chain.
Correct
Correct!
1 / 1 point
2.Question 2
True or False? Proof of work is an agreed upon method by which the creation of a new block
is achieved in the Bitcoin blockchain.
False
True
Correct
Correct! Proof of Work is the consensus protocol used by Bitcoin Blockchain.
1 / 1 point
3.Question 3
Trust in _________ is the ability to handle natural exceptional situations such as a chain split
and double spending.
mining
Proof of Work
smart contracts
robustness
correct
0 / 1 point
4.Question 4
Select the statement with the INCORRECT ending to the sentence "Forks are mechanisms
that _________"
Implement planned improvements
Manage issues
Build credibility.
Reduce the robustness of the blockchain framework.
Correct
Correct!
Module 2
Smart Contract Basics: Why Smart Contracts?
Welcome to the second course in the blockchain specialization titled Smart Contract.
This course is completely dedicated to smart contract,
the computational element of the blockchain technology.
Let's begin with the origins of a smart contract.
In the first course of the specialization, blockchain basics,
we discussed how proven algorithms and techniques for encryption,
hashing and peer to peer networks have been
creatively applied to the innovation of blockchain,
a decentralized, trusted, distributed, immutable ledger.
The concept of the smart contract was there well before the advent of the Bitcoin.
Computer scientist Nick Szabo detailed his idea of
cryptocurrency Bit gold as a sort of a precursor for Bitcoin.
He also outlined the concept of smart contract in his 1996 publication.
In fact, Szabo coined the term smart contract more than 20 years ago.
Smart contract is a centerpiece and main thrust of Ethereum blockchain.
It is the good, bad and the ugly of the blockchain technology.
It's a powerful feature.
Improper design and coding of a smart contract,
resulted in significant failures such as DAO hack and Parity wallet lockup.
It is such a dominant feature of blockchain,
which is why we've devoted the second course of this specialization to help you design,
code, deploy and execute a smart contract.
As we discussed in course one,
Bitcoin has a script feature that includes rules and policies.
Linux Foundation's Hyperledger blockchain has a smart contract feature called Chaincode.
The Chaincode is written in go language,
and executed in a docker environment.
Docker is a lightweight container technology for executing programs.
You can find more about these in the resource section.
Many variations of smart contracts are prevalent in the blockchain context.
We have chosen to discuss Ehereum implementation of
smart contracts since Ethereum is a general mainstream blockchain,
and it is being used as a reference blockchain for many others.
At the end of this course,
you'll be able to explain the elements of a smart contract,
discuss the syntax and semantics of a smart contract programming language Solidity,
solve a problem and design a smart contract solution,
use remix development environment for building and testing smart contracts,
and deploy the smart contract using remix,
and invoke the contract from a simple web interface.
In this course, it is imperative that you try the various concepts related
to smart contract in a test environment in order to understand and apply these concepts.
We'll use remix integrated development environment IDE,
which is a web interface for hands-on explorations.
At this time, please make sure you're able to
access this interface at remix.ethereum.org.
Be warned that remix is only a development environment,
and it keeps changing as new features are being added,
even as frequently as weekly.
This course is one in which you will experiment with smart contract.
Then, in the next course,
we'll develop complete end-to-end applications using a smart contract.
On completion of this module,
you will be able to explain the elements of a smart contract,
and explain the types of problems a smart contract can solve,
define the structure of a smart contract,
apply this knowledge to understand what
the real smart contract written in Solidity language,
use a web development environment remix to invoke and interact with a smart contract.
As we begin, let's remember
Bitcoin blockchain is primarily meant for transferring digital currency.
Bitcoin added a simple conditional transfer of value through an embedded script.
Recall from the blockchain basics course, course one,
that this is a conditional feature that was bootstrapped as a softfork in Bitcoin.
The script was limited in its capabilities.
It enabled simple conditional transfers.
After Bitcoin, evolved Ethereum.
The founders of Ethereum developed smart contract keeping
Nick Szabo's idea of a smart contract from over 20 years ago in mind.
A significant contribution of Ethereum is
a working smart contract layer that
supports any arbitrary code execution over the blockchain.
Smart contract allows for user-defined operations of arbitrary complexity.
This feature enhances the capability of
Ethereum blockchain to be a powerful decentralized computing system.
Why would you want to transfer currency?
Cryptocurrencies such as Bitcoin,
enable transfer of values such as money or
currency from peer-to-peer without any intermediaries.
For what? To gift somebody,
to buy a product,
maybe even renew a driver's license,
or send flowers to someone.
Let us elaborate further.
We may want the gift to be delivered on a certain date.
Buy a product of a particular color and quality.
We may need some credentials verified for renewing the license.
And we may need a specific tulip bouquet to be delivered to Buffalo.
This introduces conditions, rules,
policies beyond that of which
a simple money transfer cryptocurrency protocols can handle.
Smart contract addresses this need for
application specific validation for blockchain applications.
Smart contract has some advantages including,
a smart contract facilitates transaction
for transfer of assets other than value or cryptocurrency.
Smart contract allows specification of rules for an operation on the blockchain.
It facilitates implementation of policies for
transfer of assets in a decentralized network.
It also adds programmability and intelligence to the blockchain.
The smart contract represents a business logic layer,
with the actual logic coded in a special high level language.
A smart contract embeds function that can be
invoked by messages that are like function calls.
These messages and the input parameters for
a single message are specified in a transaction.
Let us compare Bitcoin transaction and a smart contract transaction.
As you can see in Bitcoin,
all the transactions are about send value.
In the case of a blockchain that supports a smart contract,
a transaction could embed a function implemented by a smart contract.
Here we have a voting smart contract.
The functions are ValidateVoter,
Vote, Count, Declare Winner.
Smart contract provides a layer of
computation logic that can be executed on the blockchain,
thus availing the features enabled by the blockchain framework.
Recall the layers of
a decentralized application that we discussed in course one, module two.
Observe that smart contract providing the application framework for a domain application.
For example, consider home mortgage application.
Smart contract could embed
all the business logic and the intelligence for the rules and regulation,
to allow for automatic computation and initiation of operation.
How might this be different from existing systems? You may ask.
Here, all the operations are transparent and are recorded on the blockchain.
Customers can directly access the tools without an intermediary like a bank.
It is like the ATM for mortgage initiation.
You are holding the assets,
it's therefore an intermediary.
Now that we have reviewed the advantages of a smart contract,
let's look at what problem or problems a smart contract can solve.
Typically, currency transfer is used to buy a service,
a product, or a utility from a person or a business.
There may be other conditions besides
availability of funds while executing a transaction.
For example, a business transaction may involve rules,
policies, laws, regulations and governing contexts.
Smart contract allows for
these other real world constraints to be realized on a blockchain,
thus a smart contract enables a wide variety of
decentralized application of arbitrary complexity to be implemented on the blockchain.
This can run the spectrum from supply chains to disaster recovery.
It is likely many of the applications for
the blockchain technology have not yet been conceived.
It is predicted that online shopping will overtake
retail shopping for the first time this holiday season, 2017-2018.
Some couldn't have even imagined online shopping,
mobile application or Uber 20 years ago.
Smart contract is ushering the next generation blockchain that
goes beyond the transfer of value into a visionary realm.
Smart contract allows for implementation of rules,
policies and with the help of blockchain,
supports the methods for governance and provenance.
Next in the upcoming lessons,
we'll explore how to design and implement a smart contract.
I. WEEK 1, LESSON 1 RESOURCES: WHY SMART CONTRACTS?
The following resources were selected to provide an overview of the topic of Why Smart
Contracts? We would like to acknowledge the authors of the various web articles, videos, and
papers for their insightful discussions and analytics which help formed the basis for some
sections of the lessons and modules.
Title of resource: Smart Contract: Building blocks for digital markets
Resource type: Paper
Description: This is a paper by Nick Szabo when he discussed the concept of smart contract.
This paper is dated 1996, well before the advent of the cryptocurrency Bitcoin.
Title of resource: How to Learn Solidity: The Ultimate Ethereum Coding Guide
Resource type: website
Description: This Guide will walk you step -by-step through learning Solidity.
Title of resource: Remix- Solidity IDE
Resource type: website
Description: Remix is an IDE for the smart contract programming language Solidity and has
an integrated debugger and testing environment.
Who coined the phrase “smart contract”?
Satoshi Nakamoto
Nick Szabo
Vitalik Buterin
Hal Finney
Correct
Correct!
1 / 1 point
2.Question 2
Smart contract is the centerpiece of Ethereum blockchain. What is another smart contract
model?
Chaincode of Hyperledger
Intelligent contract of Bitcoin
Bitgold of Szabo
Legal contracts
Correct
Correct!
1 / 1 point
3.Question 3
What does a smart contract represent?
Integration API
Business logic layer
Transaction layer
Proof of work
Correct
Correct!
1 / 1 point
4.Question 4
How does a smart contract transaction differ from the usual cryptocurrency transfer (say.
Bitcoin)?
It is confirmed faster
The validation process is simpler
It enables time ordered events to be recorded
It enables asset transfer in addition to digital currency
Correct
Correct!
1 / 1 point
5.Question 5
An important characteristic of a decentralized network enabled by the blockchain technology
is that ____.
the EVM holds the assets for you
a central authority holds your assets
you hold the assets instead of the intermediaries
Correct
Correct!
1) Smart Contracts Defined
a) Smart Contracts Defined (Part 1) (Remix IDE and Greeter Demos)
For currency transfer, the verification and validation,
we're just checking the existence and validity of UTXOs,
the balances, and the structural characteristics.
When a chain is thrown open for
an arbitrary decentralized application requiring trust and immutable recording,
conditions to be verified and validated become application-specific.
At the completion of this lesson,
you will be able to define the structure of a smart contract,
apply this knowledge to understand with a real contract written in Solidity language,
use a web development environment Remix to invoke and interact with a smart contract.
Structural and meta-level attributes of
a transaction are verified at the blockchain protocol level.
How were the application-specific constraints?
The answer is in the critical role played by the smart contract.
Smart contract work with
the application-specific semantics and constraints of the transaction and verify,
validates, and executes them.
Most of all, since it is deployed on the blockchain,
the smart contract leverages the immutable recording and trust model of the blockchain.
Since a smart contract is deployed in the blockchain,
it is an immutable piece of code,
and once deployed, it cannot be changed.
We will have to redeploy the code as a new smart contract,
or somehow redirect the calls from a old contract to the new one.
Smart contract can store variables in it called state variables.
We could retrieve how these variables change over the blocks.
Contract in the Ethereum blockchain has pragma directive,
name of the contract,
data or the state variable that define the state of the contract,
collection of function to carry out the intent of a smart contract.
Other items, we'll discuss in the later lessons.
Identifiers representing these elements are restricted to ASCII character set.
Make sure you select meaningful identifiers
and follow camel case convention in naming them.
We'll learn these concepts using
simple contracts written in high level language called Solidity.
We will use a web integrated development environment,
IDE, called Remix to create,
deploy, execute, and explore the working of few representative smart contracts.
Welcome to Remix IDE.
This is available at Remix.ethereum.org.
Here is the environment that is available as a web interface.
On the left side, you see the file browser,
where you can see all the smart contracts that you have created.
You can create a new one,
and it'll have an entry here.
In the middle is the editor window,
where you'll type in the smart contract.
At the bottom is a console or the output window.
On the right side,
you have the tools compile,
run, settings, analysis, debugger, and support.
At the bottom will be the web interface,
and ability to create a smart contract will be somewhere in this middle.
With all these features,
Remix is indeed a one-stop environment to develop,
deploy, and test a smart contract.
We will examine two very simple smart contracts,
greeter and one integer storage, simple storage.
These two examples are modified versions of the example given in Solidity documentation.
Our goal is to get an overview of the structure of
a smart contract without getting into the details of the Solidity language.
However, we'll explain every item in the smart contract we plan to explore.
Let's look at three steps in the development of a smart contract: design, code, and test.
Here is the design of the Greeter contract.
This is the Hello World of smart contract.
Greeter has a string variable named yourName, the constructor Greeter,
a set function to set the name,
and a hello function that returns
a string name so that you can use it to greet the world.
Here, we see the code for the Greeter contract.
It begins with the pragma that provides a version number so that
the compiler knows which version of Solidity this was developed in.
You also see the name of the contract Greeter,
the state variable yourName.
Note that it is in camel notation.
This is followed by functions,
the constructor Greeter that initializes yourName variable,
set function that sets a variable to a name supplied by the users message as a parameter,
and a hello function that retrieves the name for use by the invoking application.
Remix is where we test.
Now, let's look at the Greeter contract.
Here is a Greeter contract.
At the first line,
you see pragma Solidity.
This provides the version of the Solidity.
Then, it starts with the contract name,
followed up by the data or the state variables,
followed up by the functions.
There are three functions here: Greeter,
which is a constructor,
and a set function which is setting the data variable, and then,
a hello function which extracts the values of the state variable and returns it.
The state variable here is yourName and it has a public visibility modifier,
and the function Greeter,
the constructor initializes yourName to World,
and the function set initializes yourName to the name provided by the sender.
Hello returns whatever value that was set in the state variable.
Let's run it and see.
I'm going to start by compiling it,
and then, running it.
When I run, I have to deploy the smart contract on a JavaScript VM.
I'm going to change it to JavaScript VM,
and I'm going to create it.
When I create it,
this is the web interface where you will see all the public variables.
YourName is a public variable that's available there.
Hello is a public function that is available there,
and set is another public function that is available there.
When I just simply say yourName,
the current yourName given is World that shows up.
I'm going to set the name to Buffalo.
If I set the name to Buffalo and I click on yourName,
yourName shows up at Buffalo.
If I click on the function hello,
hello will return the current yourName that happens to be Buffalo, and it will show up.
a) Smart Contracts Defined (Part 2) (Simple Storage Demo)
Now onto the second example.
Here is the design representation of simple storage.
Observe that it looks exactly like
a regular class definition in a unified modeling language class diagram.
There are a few syntactic differences.
Also, note that the state transition that
result from execution of a smart contract functions.
Recall that the state and the state hash in a black header,
we discussed in course one.
These are those states.
Initial state is state one,
is updated by the message set and the state changes to state two.
Next, the execution of increment message results in state three and
the decrement message or function execution will transition to the next state and so on.
Now let's look at the code.
Open up remix environment and enter the solidity program shown here.
Please understand that it is a minimal environment that provides simple commands,
we're adding files, compiling,
deploying them for testing.
About this particular smart contract,
Imagine a big number that a whole world could share.
A simple de-centralized use case is world population.
Count to something that is distributed all over the planet.
This particular smart contract has get,
set, increment and decrement as functions.
You may expand these to more sophisticated operations such as,
dig the soil and evaluate the acidity,
identification of an isolated Ebola patient,
Work with a remote supply of rare mineral,
management of land deeds and any number of decentralized application.
Now let's test.
Next I'm going to close the greeter sol and let's move on to the Simple Storage.
Simple Storage. This is another smart contract.
Again, it starts up with pragma solidity and the contract name.
There is only one single state variable store data.
There are several function set,
get, increment, and decrement.
You notice that there is no explicit constructor but
a constructor is automatically by default created for the smart contract.
I'm going to compile it,
and I'm going to run it and by doing
that I can close any of the previous smart contracts that I've created
here and I'm going to go here and create
the Simple Storage and
all the public variables and public methods are displayed in the web interface.
You can see that set,
get, increment, and decrement are available.
Since stored data was not a public data,
it's not available in this public web interface.
And now, if I say Get,
there is no value set so you'd return to zero.
And let's set it to a value 456.
I'm going to set it and if I get it,
you can see 456 returned.
I'm going to increment it and if I increment it by some value,
let's say three, and increment it and if I get the value, I get 459.
Let say we decrement it by eight and decrement it i should get 451.
Yes I got the 451.
That is the Simple Storage.
Understand that I can create this simple storage,
Smart contract again by using the smart contract address.
I'm going to do that. I'm going to copy
the Smart Contract address and put it in the local contract address.
Paste. Then at that address,
I'm creating one more smart contract.
Here I have two smart contracts and they have the same address and
I can- whatever I do in this smart contract will be available throughout,
globally, everywhere you would see that.
So let me set this to some 789 and I set
it and I go back to the smart contract here and I get it,
I should get 789.
That's how the smart contracts all over the world are in consistent state.
You can see that in the simple global storage that we have here.
In summary, we examined
two simple smart contracts and learn the high-level structure of a smart contract.
We also got an introduction to
the remix integrated development environment for working with smart contracts.
In the next module,
we'll learn the solidity language itself.
I. WEEK 1, LESSON 2 RESOURCES: SMART CONTRACTS DEFINED
The following resources were selected to provide an overview of the topic of Smart Contracts
Defined. We would like to acknowledge the authors of the various web articles, videos, and
papers for their insightful discussions and analytics which help formed the basis for some
sections of the lessons and modules.
Title of resource: Structure of a Contract
Resource type: website
Description: Contracts in Solidity are similar to classes in object-oriented languages. Each
contract can contain declarations of State Variables, Functions, Function Modifiers, Events,
Struct Types and Enum Types. Furthermore, contracts can inherit from other contracts.
Title of resource: Camel Case
Resource type: website
Description: Camel case (stylized as camelCase or CamelCase; also known as camel caps or
more formally as medial capitals) is the practice of writing compound words or phrases such
that each word or abbreviation in the middle of the phrase begins with a capital letter, with no
intervening spaces or punctuation.
Title of resource: Introduction to Smart Contracts
Resource type: website
Description: This website provides an introduction to smart contracts.
What is a standard notation used for representing identifiers?
Upper case
Camel case
Lower case
Correct
Correct!
1 / 1 point
2.Question 2
According to Ethereum Metropolis version, once a smart contract is deployed it is immutable.
True or False?
False
True
Correct
Correct!
a) Processing Smart Contracts
On completion of this lesson,
you will be able to explain the address of a smart contract,
list the compilation artifacts generated by the compiler,
byte code, ABI, web3deploy script,
function hashes, and gas estimates.
A smart contract can be created,
on behalf of an externally owned account,
by application programmatically from the command-line interface and
by a script of commands from high level applications and user interface or UI.
It can also be created from inside a smart contract.
We'll cover this approach in a later course.
We need an address for the smart contract to deploy it and invoke its functions.
The address is computed by hashing
the account number of externally owned account UI and the nonce.
Let us review these steps with the Greeter smart contract on Remix.
Let's go back to the Greeter.sol and find out
how the compiler provides you many artifacts.
I'm going to compile,
and then click on the Details button,
and you can see there is the name of the contract,
the metadata of the contract,
the byte code of the smart contract that executes on
the Ethereum virtual machine.
The Application Binary Interface is here,
and if we can expand on it,
you can see the various details.
Web3deploy script is here.
This is used by the web application to interface to
the smart contract and the metadata hash.
There are few other details.
The function hashes, the hashes by which the functions are called,
and the gas estimates when the functions are executed,
and the runtime bytecode,
and then the assembly code.
As you can see, a contract needs to be compiled.
Various artifacts are generated including;
the bytecode for deploying the contract,
and the Application Binary Interface,
ABI for the application that smart contract interact with a deployed bytecode.
Remix compiler script generates many artifacts in one shot.
You can view these items generated by clicking on the Compile button,
and then the Details button just below the Compile button.
A pop-up screen appears with many details.
Here are some of the artifacts generated by
the Remix smart contract compile process and their use.
ABI, Application Binary Interface,
the interface schema for a transaction to
invoke functions on the smart contract instance bytecode.
Contract bytecode, this is the bytecode that is
executed for instantiating a smart contract on the EVM.
Think of it like executing a constructor of a smart contract to create an object.
WebDeploy script, this as two items;
json script to web application to invoke smart contract function,
script for programmatically deploying a smart contract from a web application.
Gas estimates, this provides a gas estimates for
deploying the smart contract and for the function invocation.
Function hashes, first four byte of
the function signatures to facilitate function invocation by a transaction.
Instance bytecode, the bytecode of the smart contract instance.
We will learn more about these and how to use them in
building blockchain application in the upcoming lessons.
Summarizing, Remix solidity compiler generate several artifacts as discussed.
Here are some important ones: name of the contract,
bytecode executed for the contract creation on the EVM, ABI,
Application Binary Interface, details functions,
parameters and return values,
Web3 deploy module that provide
the script for invoking the smart contract from web application,
gas estimates for execution of a function,
actual run-time bytecode of the smart contract.
Explore this list on Remix ID.
If you have Remix window open and the smart contract in it,
click the Compile, and then, the Details button.
I. WEEK 1, LESSON 3 RESOURCES: PROCESSING SMART CONTRACTS
The following resources were selected to provide an overview of the topic of Processing
Smart Contracts. We would like to acknowledge the authors of the various web articles,
videos, and papers for their insightful discussions and analytics which help formed the basis
for some sections of the lessons and modules.
Title of resource: Account Types, Gas, and Transactions
Resource type: website
Description: This website details the two type of accounts in Ethereum.
What is a CLI?
Call Level Interface
Common Language Infrastructure
Command Language Interpreter
Command Line Interface
Correct
Correct!
1 / 1 point
2.Question 2
You cannot execute a smart contract from another smart contract. True or False?
False
True
Correct
Correct!
I. WEEK 1, LESSON 4 RESOURCES: DEPLOYING SMART CONTRACTS
The following resources were selected to provide an overview of the topic of Deploying
Smart Contracts. We would like to acknowledge the authors of the various web articles,
videos, and papers for their insightful discussions and analytics which help formed the basis
for some sections of the lessons and modules.
Title of resource: Ethereum, Tokens, and Smart Contracts
Resource type: website
Description: This article details Ethereum, tokens, and smart contracts.
Title of resource: Decoding the Enigma of Bitcoin Mining
Resource type: website
Description: “Bitcoin miners” is somewhat a misleading term. The miners are actually
“bookkeepers” and “validators” of the network. It is called as Mining because the algorithm
somewhat approximates the declining supply of gold and the miner wins an award (which are
the new bitcoins created) for their effort.
Which of the following are used to determine the address of a contract? (Select 2)
Address of the creator’s account
Correct
Correct!
Nonce of the creator’s account
Correct
Correct!
Name of the contract
Contract creation date
https://remix.ethereum.org/#optimize=false&evmVersion=null&version=soljson-
v0.4.26+commit.4563c3fc.js
Smart Contract: Building blocks for digital markets, How to Learn Solidity: The
Ultimate Ethereum Coding Guide, Remix- Solidity IDE, Structure of a Contract, Camel
Case, Introduction to Smart Contracts, Account Types, Gas, and Transactions,
Ethereum, Tokens, and Smart Contracts, Decoding the Enigma of Bitcoin Mining
Week 2 Solidity Structure
Welcome to the second module, Solidity,
the second course in the blockchain specialization.
We will use Solidity as a high level language for
implementing a smart contract.
Solidity is a high level language that is a combination of JavaScript,
Java, and C++.
It is specially designed to write smart contracts and
to target the Ethereum Virtual Machine.
Recall from our course one that the format of a smart contract is like
the class definition in the object-oriented programming style.
In this course, we learn the important features of Solidity and
the development of a smart contract through two specific problems.
To create and view the smart contracts, we'll use Remix Web IDE for Solidity.
There are many IDEs available.
We chosen to use Remix, which provides not only a compiler, but
also a runtime to test a smart contract you will design.
Most of all, it works without any software insulation on your computer.
Remix supports free runtime test environments, JavaScript VM,
Injected Web3, like Metamask, and Web3 Provider,
for example, your locally running Ethereum node.
We'll use only JavaScript environment for this module.
Our goal is to master the Solidity basics in this course.
In the next module, we'll explore our approaches to deploying and invoking
a smart contract on a test blockchain based on Injected Web3 and Web3 Provider.
[MUSIC]
Recall that we examined the structure of a simple smart contract in the last lesson.
Here is a more detailed structure of a smart contract.
After this lesson, you will be able to discuss the elements of Solidity,
a high level language for writing smart contract.
Illustrate data types, and data structures, and
functions, enum, modifiers, and events using Solidity code.
Apply these concepts to design, develop, deploy, and test a smart contract.
Here is am ore detailed structure of a smart contract.
Data or state variables, functions, there are several types of functions allowed.
Constructor, default or user-specified, only one, meaning it cannot be overloaded.
Fallback function, there's a powerful feature of an anonymous function
that we'll discuss in later courses.
View functions, pure functions, no state change,
it computes under terms of value, example math functions.
Public functions, accessible from outside,
two transactions, state changes recorded on the blockchain.
Private function, accessible only with the current contract.
Internal function, accessible inside the current contract and inherited contracts.
External functions can be accessed only from outside the smart contract.
User defined types in struct and enums.
Modifiers and, finally, events.
Besides its explicit content, a smart contract can also inherit from
other smart contract, as shown in the following example.
Here standard policies contract defines a basics policies
that apply to all states, which is inherited by NYPolicies,
smart contract, where more policies can be added.
Now, we step into the smart contract and look at the function definition.
Function definitions are similar to functions in any
other high level language.
Function header, followed by the code, within curly brackets.
Function code contains the local data and
statements to process the data and return the results of processing.
Function header can be as simple as an anonymous noname function
to a complex function header loaded with a lot of details.
Here is more explanation of each of the items of the function header.
Function is a keyword at the beginning of all functions.
Parameters are any number of pairs type identifier, example, UInt count.
returnParameters, return values can be specified
as pair type identifier or just type.
When only type is specified,
it has to be explicitly returned using a return statement.
If type and identifier are specified in the return statement, any statechain
that happens to the identifier within the function is automatically returned.
Any number of values can be returned,
unlike common programming languages that allow only one return value.
For example, multiple variables, age and gender,
can be assigned return values from a function getAgeGender.
In summary, a smart contract for Ethereum can be specified
using Solidity defined structure and functions.
A variety of function types are provided for expressing smart contract operations.
A smart contract in Solidity can inherit its attribute and
functionality from another smart contract.
I. WEEK 2, LESSON 1 RESOURCES: SOLIDITY: STRUCTURE
The following resources were selected to provide an overview of the topic of Solidity:
Structure. We would like to acknowledge the authors of the various web articles, videos, and
papers for their insightful discussions and analytics which help formed the basis for some
sections of the lessons and modules.
Title of resource: What is Solidity? Our Guide to the Language of Ethereum Smart
Contracts
Resource type: website
Description: When you think of Ethereum, you probably think of its powerful smart contract
system. For those who don’t know, smart contracts are essentially programs that exist on the
Ethereum blockchain. They perform various tasks such as sending or receiving Ether or ERC-
20 tokens, among other tasks.
Title of resource: Intro to Solidity 2017 Edition
Resource type: video (16:11)
Description: An overview of Solidity 2017.
Title of resource: Ethereum Smart Contracts In Solidity 1 - State, Functions, Modifiers
and Events
Resource type: video (21:07)
Description: In this tutorial, the basics of Ethereum smart contracts are shown and state
variables, functions, modifiers and events are explained.
What does a simple function definition in Solidity contain?
Function header and code
Modifier definitions
Fallback definition
Owner of the contract
Correct
Correct!
What is Solidity? Our Guide to the Language of Ethereum Smart Contracts
Intro to Solidity 2017 Edition
Ethereum Smart Contracts In Solidity 1 - State, Functions, Modifiers and Events
What does a simple function definition in Solidity contain?
Function header and code
Modifier definitions
Fallback definition
Owner of the contract
Correct
Correct!
1 / 1 point
2.Question 2
Smart contracts can be inherited from other smart contracts? True or False?
True
False
Correct
Correct!
Basic Data Types & Statements (Bidder Data & Functions Demos)
On completion of this lesson,
you will be able to explain the basic data types and Solidity language,
explain the use of visibility modifier public,
illustrate the basic definition of functions,
and apply the basic data types and functions in constructing a smart contract.
Recall the concept that we discussed in course one.
Externally owned account, contract account, transactions, and blocks.
We use all of these in this lesson.
We'll also use gas or crypto fuel that is paid for transaction execution,
and an operation step as set by Ethereum Protocol.
Remember, one ether is 10 power 18 Wei.
Since operations consume gas,
choosing appropriate and efficient data structures
are important steps in constructing your smart contract.
Solidity supports many of the basic types of a high-level language.
We have given just a few.
Default modifier is private.
You explicitly state the public modifier,
if that is what is intended.
For every data declared public,
accessor or getter function is automatically provided.
Let us examine these concepts with a simple bidder example.
The common statements available in
any high-level language are available in solidity with very little variation.
Assignment statement, if-else, why, for, etcetera.
We learn them as we add code elements into the examples.
We will develop bidder smart contract in
incremental steps starting with the basic design representations shown here.
Always design before you code.
Let's move to the remix environment to work on this example.
The bidder smart contract design is shown as a class diagram.
It has three items;
name of the contract,
the data or states, the functions.
The first version of the bidder contract,
we add the data.
The next thing that we want to do is look at the bidder data,
and only the data.
We're going to do some incremental development here.
So, I have here the bidder contract and I have only the data,
and you see that many of these state variables or data are public, and so,
we should be able to access them from the web interface even without any functions.
So let's compile and run them and create or deploy the smart contract,
and I'm going to do that.
I'm going to say create and you can see that it was created by
this account number and the smart contract account number is here,
and it is different from the account of the creator.
The public variables are available here.
You can see when you click on the bid amount,
and you can see the $20,000 that was the initial value for the bid amount.
Nothing else is eligible,
it's initialized to false,
name, we don't know the name.
So, let's add the functions to
this basic dataset of the state variables and complete the bidder contract.
Now that we have added the data,
let's add the functions listed in the class diagram.
We'll implement the two setters and the one that determined eligibility to bid.
The code for this demo is in the resource section.
I'm going to go to the bidder sol that I pre-created for this.
I added the functions here.
The function setName that sets the name of the bidder and bid amount sets the bid amount.
Determine the eligibility is a function that based on
the state variable determines whether this bit is eligible or not.
Let's go through and run it.
I'm compiling it, running it,
and this time I'm going to close the previous smart contract.
I'm going to deploy one and new one and by clicking on the create button.
You can see lot more functions here because we have added
the public functions were set and determine eligibility.
I'm going to chain the name of the set name to let's say "Amherst".
So, I'm going to change the name and I'm going to obtain the bid amount
to 330,000 and set amount setName,
and let's look at and see whether these have been stored in the state variable.
I'm clicking on the name.
Buffalo has been changed to Amherst and I'm clicking on
the bid amount and you can see that it has been changed to 30,000.
We want to find out if this bid amount is eligible,
and I'm clicking on the function "Determine eligibility,"
and that sets the variable eligible which is a public variable.
Automatically, it has been given a getter function.
I click on it, I get true.
Yes, 30,000 is indeed higher than 1,000 and we got a true value.
Let change the bid amount now to 300.
Set the bid amount to 300,
and determine the eligibility and then click,
look at the bid amount it's 300.
Look at eligible.
It says false, and so,
that illustrates the simple smart contract of the bidder.
We looked at a few simple data types and their usage through an example.
This example should give enough background knowledge to select a type for your data,
and use it in your application design.
For more of the simple data types refer to solidity documentation in the resources.
pragma solidity ^0.4.0;
contract Bidder {
string public name;
uint public bidAmount = 20000;
bool public eligible;
uint constant minBid = 1000;
function setName(string nm) public{
name=nm;
}
function setBidAmount(uint x) public{
bidAmount=x;
}
function determineElegibility() public{
if(bidAmount>=minBid)
eligible=true;
else
eligible=false;
}
Solidity Frequently Asked Questions, Types
Transacting on the ethereum blockchain has a cost associated with it. Which of these units is
used to measure that cost?
Gas
Bytes
Coin
Ether
Correct
Correct!
1 / 1 point
2.Question 2
What is the size of “uint”?
128 bits
112 bits
64 bits
256 bits
Correct
Correct!
1 / 1 point
3.Question 3
1 ether equals
10 ^ 6 wei
10 ^ 16 wei
10 ^ 8 wei
10 ^ 18 wei
Correct
Correct!
1 / 1 point
4.Question 4
What is the default visibility modifier for an identifier in a smart contract?
Protected
Public
Static
Private
Correct
Correct!
a) Specific Data Types (Part 1) (Coin Demo)
On completion of this lesson,
you will be able to explain important data structures of Solidity: address,
mapping and message; explain
Solidity events that logs events and pushes data to an application level listener.
Address is a special Solidity define composite data type.
It can hold a 20-byte ethereum address.
Recall address is a reference address to access a smart contract.
Address data structure also contains the balance of the account in Wei.
It also supports a function transfer,
to transfer a value to a specific address.
Mapping is a very versatile data structure that is similar to a key value store,
it also can be thought of as a hash table.
The key is typically a secure hash of a simple Solidity data type such as
address and the value in key-value pair can be any arbitrary type.
Here we illustrate the idea of mapping with two examples.
We can use phone number to name mapping.
That's a common utility function on our phone system.
As a second example,
you can have a struct of all customer data and can use
mapping to map an account address to customer data as shown.
Let's now transition to message.
Message is a complex data type specific to smart contract.
It represents the call that can be used to invoke a function of a smart contract.
It supports many attributes of which we are interested in two of them now.
You can always look up other message details in the Solidity documentation,
msg.sender that holds the address of the sender,
msg.value that has the value in Wei sent by the sender.
Now, you can write statements that verify and validate
the address and the amount to make sure that the application specifics are met.
Let's use these data structures and mint some money.
Let's look at the smart contract for coin as specified in Solidity documentation.
Recall, we always start with the design,
say a class diagram whether we are analyzing a program or coding an application.
Here is a class diagram for coin contract.
Also make a note of the statements for, if-else assignment.
Coin uses the two Solidity features address and mapping.
Address holds the 20-byte ethereum address.
Recall, address is the base for a smart contract.
Let's review this code in Remix IDE.
The next contract that we're going to look at is the coin.
I created this under Minter.sol.
The name of the contract is Coin and this is also from the Solidity documentation,
and we have here one state variable, public minter.
You can see that it has a data type of address that is Solidity specific.
They are also illustrating
the mapping function here mapping table where
address is used to map on to the balances that we have.
It also illustrates the event,
an event has been defined as sent with three parameters: from whom the money was sent,
to what address the money was sent,
and the amount of money that was sent.
We have the constructor where the message sender or the person who's
creating this contract is defined as the minter and message sender.
We're also illustrating the use of message and the sender data of
the message and initializing the minter public data that we have in this contract.
Next comes the function mint,
where the coins are minted and in this case,
only the sender, only the minter should be able to mint the coins.
Only the owner of the smart contract should be able to mint the coin.
So, I have here a simple command
that tests the condition that whoever is the message sender for mint,
is indeed the minter who created this contract.
At this time, I'm going to close this bidder,
we don't need that anymore.
Once that is so, once a mint is requested by
the owner of the contract and I mint those newly created coins
and add to the receiver whose address was sent as a parameter.
Finally, I have a send function
where the coins created can be sent to a specific address.
You specify the address of the receiver and the amount to be
sent as a parameter and this is also a public function as you can see.
If the balance of the sender of this message is less than the amount to be transferred,
the function is returned.
This is not completed.
Otherwise, the balance of the sender is decremented,
balance of the receiver is incremented.
There is also an event log as what happened here?
The sent is the event and it is pushed,
it is logged with
message sender and the receiver is the coin and the amount has three parameters.
Three is the maximum number of parameters that is allowed for an event,
recall that from our lesson, okay.
This invokes that event and that gets logged.
We looked at the structure of coin, now let's look at it in operation.
And let's mint some coins and send it between accounts.
Compile, you have a clean compile.
Run, and I'm going to create.
And that deploys a smart contract with public data and public methods.
And I'm going to check the balance of the mentor.
None of that column should have any coins because we just started.
So I'm going to say balance and it's going to be zero.
If you check the other accounts also, it would be zero, and
I'm going to mint some coins for the minter, the creator of the.
I'm going to say 2,000, mint, and we have here, let me go back and
check if we have 2,000.
Now I'm going to go back to another account,
copy the account address, and put it in the send.
Make sure it is copied and it's the right address.
And I'm going to send 600 of the coin that I created
from the minter's account to the new account.
And let's go back here, let's go back here, and see whether we have
that particular account has that 600 coins that we sent.
So here we have balance 600.
So we minted 2,000 coins, we sent 600 coins.
And now I'm going to go back here to the minter's account.
Minter's account should show 1,400 because it has sent 600 of them, balance, yes.
We know that it's nicely balanced.
In summary,
it is impossible to enumerate every possible language element of solidity.
However, in this lesson we've established a method you can follow to learn and
practice new constructs for building smart contract.
We learned the concept of address, mapping, and message,
and applied these to analyze a simple contract coin.
One more thing.
Always design before you code.
We did that with the class diagram of the coin example.
And explore the coding examples by uploading them to the remix and map.
Learning Solidity : Tutorial 6 Data Types (Array, Mapping, Struct), Units and Globally
Available Variables, Solidity Tutorials
What is the size of an Ethereum Address?
64 Bytes
16 Bytes
20 Bytes
256 Bytes
Correct
Correct!
1 / 1 point
2.Question 2
Which one of the following elements of Solidity is equivalent to a hash table?
Address
Mapping
Struct
Array
Correct
Correct!
1 / 1 point
3.Question 3
In a smart contract, how can you access the address of an account that initiated a transaction?
msg.sender
msg.address
msg.sig
msg.value
Correct
Correct!
a) Data Structures (Part 1) (BallotV1 Demo)
On completion of this lesson you will be able to explain
the syntax and usage of arrays, enum,
struct data types of Solidity,
illustrate the use of time units pre-defined in Solidity.
We will begin with a simple smart contract as an example.
We'll develop this example to illustrate the concepts for this lesson,
struct, array, enum, and time units.
Let us begin our analysis of the code base with
a class diagram that visually represents an example,
a modified version of
the balanced smart contract specified in the Solidity documentation.
The smart contract creator is the chairperson who gets a weight of two for her vote.
Others get a weightage of one for their one vote.
Each voter has to be registered first by the chairperson before they can vote.
They can vote only once.
A constant function is included to enable
the client applications to call to obtain the result.
The constant modifier of the function prevents
it from changing any state of the smart contract.
More importantly, this call comes directly to the smart contract not via a transaction,
so it is not recorded in the blockchain.
Since it does not change the state of the smart contract, there is no need.
Struct is a composite data type of a group of
related data that can be referenced by a single, meaningful, collective name.
Individual elements of the struct can be accessed using the dot notation.
Here is a struct in ballot smart contract representing
a single voter with three attributes: weight of the vote,
whether this person has voted boolean,
and which proposal the person voted for.
Voter struct is used to define a mapping of address.
Another example for struct is a proposal data with just one element proposal number.
We could also add another data to the struct,
say proposal name that is of string type.
Set of proposals is represented by an array of proposals.
Let us now review the code on remix to check the usage of
the struct and the arrays in the functions: constructor,
register, vote, and winningProposals.
Let's examine ballot version one.
Once again, this is from Solidity documentation,
and we have modified it somewhat,
we have dropped one of the functions,
and we have made it a simple one.
It starts with the name of the ballot,
and we have several data variables.
One is a struct for the voters that has got the weightage of the vote,
whether they voted or not,
boolean and the vote itself,
which proposal they vote it to.
Then we have a structure proposal that has got the vote count for each one of them.
The proposal array maintains the votes for each one of the proposals.
The chairperson address is specified by a state variable and there is
a mapping from address to voter that is specified by the variable voters.
There are several functions,
even though we dropped one of them,
there are a couple of functions there to note.
One is a function ballot which is a constructor,
and then I have a register where that chairperson registers
the voter and the person or the people who registered vote for it,
vote for the proposals that are there and finally,
there's a function winningProposal that can be called by the application.
It doesn't come through a transaction.
This will determine the winningProposal and it can be obtained by a client application.
Let's run it and see.
You can see that there are several conditions specified,
and all the code is available inside the function.
We'll not go into the details, but well, let's compile.
We know, we understand the meaning of voting and deciding the proposal that wins.
Let's compile and run.
I'm going to go into JavaScript VM,
and let's wait for a few minutes so that all the addresses are generated.
These are the addresses that are available to you,
and we will be using several of them.
For the sake of demo,
I'm just going to use one of them as a chairman,
as you can see the ca,
the one that start with ca.
0x states that there's a hexadecimal address,
ca, the one that starts with ca3 is the chairperson.
I'm just going to use just one other person for the sake of demo.
But if you want to try it on your own,
you can try any of these addresses as other people who may be interested in voting.
You can try it at your leisure.
So, let's create the smart contract.
But in this case, when you're creating a smart contract
you have to tell how many proposals are there since
the constructor requires more than certain number of proposals.
So, I'm just going to say three for the sake of simplicity.
This is the chairperson.
Chairperson is going to create the smart contract, and I did that.
Here we have a simple interface since we had just three functions,
and these functions are available in the web interface for us to use.
First, I'm just going to simply press the winningProposal.
Remember, winningProposals shouldn't show anything or shouldn't be displaying anything,
should not be executing at all when nobody has voted, nobody has registered.
But we're going to click on the winningProposal,
and it shows it as zero.
This is an error or a issue with the design that we have right now.
Let's move on.
So, I'm going to register one person and start voting here.
So, in order to register you have to be the chairperson here.
I'm going to go into the other person to address.
This is the person, other voter and I'm going to copy
the address of this person and put it in here.
Addresses have to be within quotes and remix,
so I'm just going to put it within quotes.
These are all big numbers because they are 256 bits and I
got to go back to the chairperson because only the chairperson can register.
So I'm issuing this register from the chairperson's address,
and this transaction goes from the chairperson to register this person.
So, I'm going to register that person.
One person has been registered.
Now, let's vote.
We have one chairperson and one voter.
Just for the sake of understanding the balloting process,
we are going to use only these two people.
I'm going to vote for,
let's say the chairperson wants to vote for the proposal number 01 or two.
The chairperson votes were two.
So this is the chairperson,
the chairperson is initiating the vote transaction and number two is a parameter,
the chairperson is voting for two.
I'm going to press, and that's going through.
You can see all the transaction going through here.
Then I'm changing the address of
the originator of the message to the next person who has registered.
Then I'm going to say, "Okay,
the voter who is not a chairperson is voting for one."
So, understand what happened here.
The chairperson voted for two.
The regular voter voted for one and we want to find out the winningProposal.
Remember, chairperson has a weightage of two.
So obviously, it has to be two.
So you can see the winningProposal is two because the chairperson,
even though there was only one vote weightage was two and the winningProposal was two.
So that is a very simple demo of the ballot contract that is given in the Solidity,
a documentation, and we modified it somewhat by dropping a function.
But we will take this base contract and improve on it by adding enums,
stages, time, require, modifiers,
and other kinds of check modifiers and other kinds
of assertions so that it is a robust solution.
On Remix IDE, you can save the list of
transactions and view it to explain the sequence of operation.
Here is a sample transaction.
Can you guess what is wrong with this transaction?
The transaction did execute consumed gas,
but did not provide the result expected because it was from account two.
Remember, nobody except the chairperson account zero can register.
It has to be from account zero.
We made a mistake in not selecting that right from address for registering.
Check out the other correct transaction to understand this further.
data Types part 2
Let's discuss time units in solidity.
In a blockchain application,
all the participants and nodes have to synchronize to one universal time.
For this purpose, blockchain proposals include a time server that serves
the Unix Epoch time or time since January 1st 1970 in seconds.
See this link for a sample conversion of a real date time to Unix Epoch time.
This time is used in timestamping the block time.
When a block is added to the blockchain,
all the transaction confirmed by the block also have
the same 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.
In other words, now variable in
a function is not the time at which function transaction was initiated,
but it is the time when it was confirmed.
Time is defined as unit time; seconds,
minutes, hours, days, weeks and years.
Little numbers can be used in specifying time related computations.
For example; Assume one day is allocated for the duration of
voter registration and if we allow 60 Minutes as the duration time to vote.
Assign now value to creation time and after some elapsed time,
if now is greater than the creation time plus one days registration status is done.
After this If now is less than vote start time plus 60 minutes,
then allow user to vote.
Recall that now in smart contract is not the time at which the transaction was initiated,
but it is the time when it was confirmed.
Now, onto Enum data types.
Enum or enumerator data type,
allows for user defined data types with limited set of meaningful values.
It is mostly used for internal use and are not
supported currently at the ABI level of solidity.
However, it serves an important purpose of defining states or phases of a smart contract.
Recall that smart contract represent projects of contracts that
may transition through radius spaces based on time or input conditions.
Let us look at a simple example that combines time and the enumerated type elements.
We define the enumerated type stage;
Init, Reg, Vote, Done.
And we transition between the stages based on elapsed time.
Note that we have used one minutes or even less elapsed time,
so that we can verify the execution of this contract in a finite time.
In reality, you can set the time to something realistic such as one day or thirty days..
Etc. Let's look at
the state transition on Remix to reinforce this concept.
Let's look at the state transition where
we are considering only time-based state transitions.
Here we have contract state transition version two.
Here, I'm illustrating enum stage; Init, Reg,
Vote and Done and we are defining the enum followed by the state variables stage.
This is uppercase stage for the enumerated variable.
That is the type and the stage itself is the data variable.
I also have a start time variable and a time now variable,
only the time now is public.
And the function state transition version two is
a constructor where I'm initializing the stage to Init and the start time to now.
And now assuming there is a stage change has to be enacted approximately one minute,
I'm going to reduce it for the sake of this demo to 10 seconds,
because one minute takes too long a time for us to wait for the demo to elapse.
So I'm just going to ten seconds.
So instead of one minute, I'm changing it to ten seconds.
And you saw the little red button
with an X up here that means something is wrong and you can change it.
So I'm going to change the stage time to 10 seconds,
so that we can go through the stages quite quickly for the demo purposes.
Okay. Let's run it.
Let's compile and run it.
And you can see that this is simply going through the stages every 10 seconds.
Compile, run it and I'm going to create the smart contract.
It is deployed and the web interfaces available
here on the web interface of the Remix ID.
Time now, it is at zero,
stage is set to zero.
That is; it is at Init.
InIt is zero, Reg is one,
Vote is two, Done is three.
Even though enum has these names,
It is actually coded as zero, one, two and three.
And I go to advanced state,
and I look at the stage now, it is one.
10 seconds have elapsed and so it has moved on to one.
And I'm going to advanced state again and look at the stage,
it is still one.
It is not at ten seconds.
Now I get the time now, you can see it here.
And this is the epoch time from January 1st 1970.
Advanced state again and I can look at the stage two.
Ten more seconds and advanced state,
it is not at 10 seconds.
Advanced state, and I should be getting now,
advanced state I should getting it to stage three.
See even though I've given ten seconds for the sake of demo and you can also look at
the time it would advance approximately to the three ten seconds.
Even though it is based on 10 seconds,
In reality it would be a longer elapsed time for the smart contracts.
In summary, we have explored time and stages of contracts that are
very important for many real world contracts based applications.
We also illustrated Enum,
user defined data type and more examples for struct and array data type.
Types, Enums, Liquid Democracy uses Blockchain to Fix Politics, and Now You Can
Vote for It
What is an Enum?
A custom data type that can hold a group of several variables.
A custom data type that can hold finite set of values.
A custom data type that can hold infinite set of values.
A predefined data type with finite set of values.
Correct
Correct!
1 / 1 point
2.Question 2
Individual elements of “struct” can be accessed using
Colon notation[Eg. person:name]
Argument notation [Eg. name(person)]
Dot notation [ Eg. person.name]
Arrow notation [Eg. name => person]
Correct
Correct!
Access Modifiers & Applications
On completion of this lesson,
you will be able to explain usage of function modifiers,
explain the use of require clause for input validation,
illustrate the assert declaration
for post-condition checking,
discuss reverting a transaction and reward function.
The main intent of
smart contract transaction is to execute a function.
However, smart contracts often require
control over who are what can execute the function,
at what time a function needs to be executed,
what are the precondition to be
met before getting access to the function?
It's a good practice to
validate input values to the function
to avoid unnecessary execution and waste of gas.
If there are any errors
found during the input validation,
these have to be handled appropriately.
At the end of the function execution,
you may want to assert that certain conditions are met
to ensure the integrity of the smart contract.
Let's begin with
an important feature of solidity, modifiers.
They can address some of the concerns just mentioned.
Modifiers can change the behavior of a function.
That's why this feature is referred to as a modifier.
It is also known as
a function modifier since it is specified at
the entry to a function and
executed before the execution of the function begins.
You can think of a modifier as
a gatekeeper protecting a function.
A modifier typically checks a condition
using a require and if the condition failed,
the transaction that call
the function can be reverted using the revert function.
This will completely reject
the transaction and revert all its state changes.
There'll be no recording on the blockchain.
Let's understand the modifier and require
clauses using the ballot smart contract functions.
We'll add a modifier
onlyBy(chairperson) to the register function.
Will do that by the steps.
Define modifier for the clause onlyBy(chairperson).
Adding a special notation underscore
semicolon to the modifier definition
that includes the function.
Using the modifier clause in the function header.
Step 1 is a definition of the modifier onlyBy,
only the chairperson who created
the smart contract valid to register any new orders.
Step 2, shows how to make
the modifier include a place holder for any function.
Step 3, use the modifier clause
in the header of the function definition.
Now, let's change the existing if statement
of the ballot smart contract
such that it reverse
the transaction on input validation failure.
We don't need to waste
blockchain resources for a failed transaction.
Now, we'll illustrate assert using
a function payoff that computes and pays off bets.
It is preferable that the assert not fail and that it
requires checking the balance after
every payoff in the above case.
We are making sure bank has the reserves
of $10,000 after all the payoffs.
Under normal circumstance, assert should not fail.
This is more for handling an anomalous,
faulty or malicious condition.
In this case, the exceptional condition is
that bank balance somehow dipped below the reserves.
The picture summarizes all the features we discussed.
Modifiers and error handlers,
and where they are typically used.
The rules, laws, policies,
and governance conditions are coded as modifiers.
You can use the modifiers
as gatekeepers for the functions.
If your transaction to invoke the function
does not meet the condition
specified at the header of the function,
your transaction will be reverted.
Will not be recorded in the block chain.
Modifiers can be used to validate rules
outside the function such
as describing the opening of the lesson,
who has access to the function,
at what time, and what condition, etc.
Once the screening conditions are satisfied,
input validation can be carried out inside
the function using require declaration statement.
In this case, also
the transaction will be reverted on failed validation.
This is done before the execution of the function.
There are anomalous faulty malicious code
that may result in unexpected situations or exception.
These can be caught usually at
the end of the function or sometimes
within the function using assert declarative statement,
and the entire transaction including
the function execution and
the state change will be reverted.
Here is an example of an online digital media bazaar.
Input condition as specified by
a modifier is atLeast5Sellers.
This enforces the condition that
there should be atLeast5Sellers with
their products before a buyer
initiates a buy message through a transaction.
This is a global condition for all buyers.
So, it is appropriate to install it
using a modifier declarative statement.
Once there are enough sellers,
a buyer can buy.
Inside the function, we validate if the buyer has
enough money to buy the specific item requested.
If not, the transaction is reverted.
When the validation is satisfied,
money is transferred to the seller,
item is transferred to the buyer.
We have a simple assert declaration at
the end that the bought item
should have been transferred.
After all, it's a digital item.
This simply reached only if the item has not been
transferred and could not be
transferred due to exception reason.
This provides a simple example
of concepts learned in this lesson.
In summary, function modifiers
along with state reverting functions of revert,
required, and assert, collectively supported
robust error handling-approach for a smart contract.
These declarative features can be used
to perform formal verification and
static analysis of a smart contract to make
sure it implements the intent of a smart contract.
Contracts
Which is true about function modifiers?
Specified at the entry of a function and executed after the function ends
Specified at the exit of a function and executed after the function ends
Specified at the entry to a function and executed before the function begins
Correct
Correct!
1 / 1 point
2.Question 2
What function is used to reject a failed transaction without recording it in the blockchain?
return
revert
delete
reject
Correct
Correct!
Week 3 Putting It All Together: Developing Smart Contracts
We'll start this module with a discussion of a method for developing smart contracts.
Begin with a problem statement,
analyze the problem to come up with a basic design,
its state variables and functions,
recall our principle from the last lesson,
design first, represent the design using a class diagram.
Based on the problem statement,
define the visibility for the state variables and functions.
Based on the requirements,
define the access modifiers for the functions,
define validation for input variables of the functions,
define conditions that must hold true
on completion of critical operations within functions,
declaratively express the conditions that were
discovered in steps four to seven using access modifiers,
visibility modifiers require an assert classes.
We will use solidity language and remix IDE
to develop and test a smart contracts according to this method.
Upon completion of this module,
you will be able to apply the concepts learned in
the last two modules to write a smart contract,
analyze a problem statement to design and implement a smart contract,
program smart contracts using solidity language and remix IDE.
Incrementally, add features to the ballot smart contract code.
Let's review the ballot problem.
We'll use the ballot problem that is defined and solidity documentation.
This problem will be used as a base problem on which we'll develop our solution.
Recall that we discussed the ballot problem in the last module.
We have chosen a familiar problem so that we can
focus on designing and implementing the smart contract,
rather than spending time on explaining the problem that is unfamiliar to you.
Moreover, the concepts and the function used in
the solution can be easily adapted to any other problem.
Here is a formal problem statement for ballot.
Problem description, version one: An organization invites proposals for a project,
a chairperson organizes this process.
The number of proposals is specified at the time of creation of the smart contract.
The chairperson registers all the voters.
Voters including the chairperson vote on the proposal.
To make things interesting,
we've given a weight of two for
the chairperson's vote and a rate of one for the regular voter.
The winning proposal is determined and announced to the world.
We'll exclude the delegation of voting function that is
present in the current valid smart contract in solidity documentation,
we will not consider this function.
Let's perform an analysis to determine the state variables.
Let us now consider the data or state variables needed for the program.
Details of a proposal and the set of proposals
will keep track of only the proposal number and the vote for each proposal.
Auto details, the vantage of the vote,
one for the regular voter,
two for the chairperson.
Voted or not, and to what proposal number they voted.
Keep track of the addresses of the chairperson and other voters,
address of a voter will be used as a key to map to the details of the voter.
Major differences from the traditional object oriented analysis
is in the smart contract specific data types,
such as address and the message center.
Let us now discuss the functions.
The chairperson is the creator of the smart contract.
He or she will be the only person who can register the voters.
Here is a list of functions.
Constructor is a function that is called to create the smart contract.
In solidity, unlike a regular object oriented language,
there can be only one constructor.
Also, the constructor has the same name as a contract.
The sender of the message invoking the constructor is the chairperson.
The second function is the register function to register the voter.
Only the chairperson can register a voter.
The sender of the message for registration has to be the chairperson.
The third function is the vote function.
Voters including the chairperson.
can vote for a proposal.
The final function determines
the winning proposal and that can be called by client application.
Let's look at remix to explain the ballot version one.
Let's recap what we did in remix ballot version one.
Note that the visibility modifiers for the state variables and
the functions represent the details of a single voter using a struct.
Single proposal also using a struct possibly allowing for future expansion.
A mapping of voters,
mapping voter address, externally-owned accounts to voter details.
An array of proposals and a chairperson address are defined.
Also, review all the function.
Try it for yourself.
Putting it all together: Developing Smart Contracts
We'll start this module with a discussion of a method for developing smart contracts.
Begin with a problem statement,
analyze the problem to come up with a basic design,
its state variables and functions,
recall our principle from the last lesson,
design first, represent the design using a class diagram.
Based on the problem statement,
define the visibility for the state variables and functions.
Based on the requirements,
define the access modifiers for the functions,
define validation for input variables of the functions,
define conditions that must hold true
on completion of critical operations within functions,
declaratively express the conditions that were
discovered in steps four to seven using access modifiers,
visibility modifiers require an assert classes.
We will use solidity language and remix IDE
to develop and test a smart contracts according to this method.
Upon completion of this module,
you will be able to apply the concepts learned in
the last two modules to write a smart contract,
analyze a problem statement to design and implement a smart contract,
program smart contracts using solidity language and remix IDE.
Incrementally, add features to the ballot smart contract code.
Let's review the ballot problem.
We'll use the ballot problem that is defined and solidity documentation.
This problem will be used as a base problem on which we'll develop our solution.
Recall that we discussed the ballot problem in the last module.
We have chosen a familiar problem so that we can
focus on designing and implementing the smart contract,
rather than spending time on explaining the problem that is unfamiliar to you.
Moreover, the concepts and the function used in
the solution can be easily adapted to any other problem.
Here is a formal problem statement for ballot.
Problem description, version one: An organization invites proposals for a project,
a chairperson organizes this process.
The number of proposals is specified at the time of creation of the smart contract.
The chairperson registers all the voters.
Voters including the chairperson vote on the proposal.
To make things interesting,
we've given a weight of two for
the chairperson's vote and a rate of one for the regular voter.
The winning proposal is determined and announced to the world.
We'll exclude the delegation of voting function that is
present in the current valid smart contract in solidity documentation,
we will not consider this function.
Let's perform an analysis to determine the state variables.
Let us now consider the data or state variables needed for the program.
Details of a proposal and the set of proposals
will keep track of only the proposal number and the vote for each proposal.
Auto details, the vantage of the vote,
one for the regular voter,
two for the chairperson.
Voted or not, and to what proposal number they voted.
Keep track of the addresses of the chairperson and other voters,
address of a voter will be used as a key to map to the details of the voter.
Major differences from the traditional object oriented analysis
is in the smart contract specific data types,
such as address and the message center.
Let us now discuss the functions.
The chairperson is the creator of the smart contract.
He or she will be the only person who can register the voters.
Here is a list of functions.
Constructor is a function that is called to create the smart contract.
In solidity, unlike a regular object oriented language,
there can be only one constructor.
Also, the constructor has the same name as a contract.
The sender of the message invoking the constructor is the chairperson.
The second function is the register function to register the voter.
Only the chairperson can register a voter.
The sender of the message for registration has to be the chairperson.
The third function is the vote function.
Voters including the chairperson.
can vote for a proposal.
The final function determines
the winning proposal and that can be called by client application.
Let's look at remix to explain the ballot version one.
Let's recap what we did in remix ballot version one.
Note that the visibility modifiers for the state variables and
the functions represent the details of a single voter using a struct.
Single proposal also using a struct possibly allowing for future expansion.
A mapping of voters,
mapping voter address, externally-owned accounts to voter details.
An array of proposals and a chairperson address are defined.
Also, review all the function.
Try it for yourself.
Voting
Time Elements Part 1
Let us re-examine the ballot contract developed in the last lesson.
In a typical voting process,
voters are registered first.
There is usually a deadline for registration,
and also for the voting period.
For example, for most states in the USA,
you have to be registered 30 days before the voting day,
and the ordering takes place on a single day for in-person voters.
If that is the case,
registration has to be completed before voting.
The current ballot smart contract does not have these limitations.
For example, the function register and the function vote can be called in any order.
There are no rules such as the voters have to be registered before they can vote,
voting is open only for a specified period,
and the winning proposal can be decided only after all the voting is completed.
Currently, if you call the winning proposal,
it gives the zeroth proposal as the winner before anyone has registered or voted.
Now, let us add the stages and the time duration of the stages to the ballot version one.
Create a ballot version two,
ballot version two.all on Remix,
by copying ballots all we created earlier.
We add the enum for the stages and logic for modifying the stages within the functions.
We will compile and run it and make sure it works as expected.
Let's define the stage as enum datatype.
Stage is four distinct stages,
Init, Reg, Vote, and Done.
The stage is initialized to Init at the time of deployment of the Smart Contract.
Then, in the constructor,
the Init is changed to Reg stage.
After the registration period is over,
the stage changes to Vote.
After the voting duration elapses,
the stage is set to Done.
Enum, stage, Init, Reg, Vote, and Done.
Let's add this logic to the ballot two.soldsmartcontract,
and use this to set the stages of the smart contract.
We'll also add the time elements.
Solidity defines a time variable "now",
that is the current block timestamp.
We'll add the state variable, startTime, uint startTime.
startTime is initialized to now within the constructor.
Then, change the stage of the ballot process based
on the time allocated for registration and voting stage as shown.
We have added the startTime variable,
and the period for registration in this case is 10 days.
We also added the duration for voting period,
in this case it is one day.
The now solidity variable is the timestamp of the block,
block.timestamp function, in which the transaction is confirmed.
Thus, now may not accurately reflect the elapsed time.
For approximate intervals, and for testing simple concept,
now is a convenient time attribute.
In a realistic application, with specific deadlines,
a better solution will be to pass the deadlines in
a epoch time to the constructor of the smart contract at the time of creation,
and compare it with the current block timestamp where needed.
Recall that block timestamp is represented by the variable "now".
Time Elements Part 2
This is Ballot version 2.
Version 2 has a struct for Voter, it has a struct for Proposal.
And has something new here, enum stage,
that defines init reg vote and done stages for the smart contract.
And the variable stage is defined to be of this enum stage type, and
it has been initialized to the Init stage.
Actually Init is 0, Reg is 1, Vote is coded as 2, Done is coded as 3.
Remember that when we are looking at the outputs in the web interface.
Address chairperson, chairperson is the only person who can register other voters.
Mapping, address is mapped to the voter struct, and we have a Proposal and
an array of proposals that has each one of the structs for the Proposal.
That is just one data field called uint voteCount.
And we also define the time element uint startTime.
These are some of the things that are new.
We have the usual constructor, and
the constructor has two more lines besides the previous code that is defining
the stage to be reg, and also start startTime to be now.
So, it initiates the registration stage.
And the register function happens only if the stage happens to be reg,
otherwise it simply returns.
This is a new feature that we have added to the Ballot version 2, okay?
It used to be just this code, now we have added one more check in
the validation at the beginning of the function, okay.
And that is based on the enum stage that we've created.
The same way you can vote only if the stage happens to be,
I'm going down here and you can see that if you can vote only if the stage
happens to be vote, otherwise the function simply returns.
And finally, and
the winning proposal returns something useful only if the stage is done.
Otherwise, it doesn't even go through computing.
This winning proposal doesn't even execute if the stage is not done.
All right, so we enforce some checkpoints here,
some validations here from the first version of the Ballot.
So let's execute it and see it running.
I'm going to compile, it's already compiled, but anyway compile again.
JavaScript, and I am going to change that address like you can see that
we have several addresses and I am going to change that address to be
the chairperson's address, that is arbitrarily decided.
But I would like to have the ca3 to be chairperson's address every time, and
I am going to create it once again with just three proposals, Create, and
you can see the interface here, okay.
So I have here vote register, and I also put the stage,
stage also came up here, since I define the stage variable to be public.
It is also coming and showing in the web interface, since it's a public variable,
getters are automatically set for it, and so stages also here, so
you can view the stage also.
All right, so first thing is we need to register.
So the chairperson is here sending, ready to send the message.
And I want to find out who is to be registered first.
This is the second person, this the first person who is to be registered and so
I'm going to copy that address and then throw it in here.
[COUGH] And remember, remix requires it within quotes.
And I have to go back here and create or
show the chairperson as the sender of this register message.
Nobody else except the chairperson can register.
So I set the Account address who's sending the register function
to be the chairperson.
And then this is the person to be registered, and I say, register.
Okay, now that person is registered so we have two people.
One, the chairperson, and one more.
I’m going to show you registration for one more person, let's see.
I have here one more person, copy, and I can copy it here.
And again, I want to emphasize that this is going
to be within code, and I just want to make sure that I have a different address.
You can see it's 4b and I have to change the sender to be the chairperson and
then I'm going to register.
We've registered two people here.
Okay, let's register one more.
583, I'm going to copy, so you got the idea here right now, and
this has to be within codes, and you can use a Ctrl+V to copy that,
you could use copy and paste if you're a copy and paste person.
Let's see, Ctrl+V, I have it here, all right.
And so, I go back to the chairperson, and register.
In this case I registered three people here.
Okay, and the stage is two now, okay, so stage is two,
that means elapsed time is ready to go and we can vote.
So I'm going to go back to the chairperson.
Chairperson votes for let's say 1,
okay that means two votes are registered for 1 okay.
And I'm going to do only one more vote because for the sake of I don't want copy.
So I"m just going to, the second person votes for 2.
Okay, the regular voter votes for 2.
All right, and now let's look at the stage.
Okay 3, it's ready to go, it's all done.
So the winning proposal is 1, because remember, the chairperson voted for
1, the single voter voted for 2, the chairperson weighted is 2.
So the winning proposal is one, all right?
You can also keep checking the stages, every now and then,
whether you are in the right stage.
In this case I made the stage time to be very small so
I could go through it quickly.
But in reality, in a real smart contract it can be few days that it be
allowed to vote, and so on.
Right, that is the end of Ballot 2.
Time Elements (Part 3)
The newer variable added to ballot version 1R,
annum for stage, and start time for timekeeping.
Advancing the stages, will now depend on the time as specified in the state diagram.
Here is a solution ballot version two,
with stage and time elements added.
This is a traditional solution with the conditions validated by programmatic approach,
using if else statement.
Now, we are moving to the next question of the ballot.
Consider some opportunities for improvement.
Validation of time and stage are done inside the function code, programmatically.
Because of this, the transaction is executed and recorded on the block chain,
irrespective of whether the validation fails or succeeds.
Note the if else statement,
at the top of the function code of the ballot's smart contract.
Further, we ask these questions,
is there any way to reject the transaction?
In a way similar to how transactions were rejected,
at the block chain protocol level,
if they don't conform to the rules, that is,
if the problem specific conditions are not met toward the transaction.
In this case, the transaction will not be recorded on the block chain,
wasting effort and space.
If there is a way to separate the validation from
the actual code that the function executes,
is there a way to specify the problem specific rules and condition declaratively,
so that they can be independently specified,
as well as audited to assure that the smart contract does what it's supposed to do?
Auditing of the Smart Contract is specially critical,
since a smart contract is expected to be autonomous and permanent, once deployed.
We address these issues in the next lesson
that is built around problem-specific validation,
by using function modifiers,
required clause, revert and assert declarations.
Sol files
https://www.coursera.org/learn/smarter-contracts/supplement/BFRU8/required-quiz-
resources-and-directions-smart-contract-basics-week
Enum, Time units
Validation & Test (Part 1) (BallotV3 Demo)
Module three, lesson three: Problem-specific Validation and Testing.
The learning objectives of this lesson are: explain the concept of reverting
a transaction based on problem-specific validation and using a revert declaration,
apply the concepts of function modifier; require; and assert.
In this lesson, we will show the execution after modifying
ballotversion2.sol using solidity-specific declarations and error handlers.
Modifier, require and assert.
Solidity features a function revert that results in state-reverting exception.
This exception handling will undo all the changes made to the state in
the current call and reverses the transaction and also flags an error to the caller.
We will introduce a function modifier with the required stage as a parameter.
First, we'll add the modifier to the function header.
We'll add the modifier with the parameter, stage required stage.
Let us review the code with the modifier added.
Let us execute the ballot version three with all these improvement.
Every now and then when you're working with Remix,
it's good to refresh so that you get new account numbers and the space is clean,
and so on. I've done that.
And so you can see that I've been working on several of them,
so they're all open here,
and I'm going to choose the version three, ballot version three.
And, here, you can see that I have,
in the last one, I did not use any modifiers.
Here, this one illustrates modifiers require assert,
and all the gatekeeper elements that we discussed in the lectures.
Okay, so let's go back.
This is ballot version three.
I have the regular struct for voter, struct for proposal,
enum for stage, address for the chairperson,
mapping the address to the voters in the proposal array.
So, these are all quite familiar to you by now.
And you can see how beneficial incremental development is.
You take the base contract and put the essentials there and keep adding to it.
That helps in better development and a good design.
And now you also have the time element and start time,
and we see some new things here.
I have a single modifier, validStage.
Instead of checking the stage inside using if-else statement,
which requires the transaction to be executed inside the function,
we can prevent that from happening right
outside the function using the modifier as you can see here.
So, let's look at the modifier.
Modifier validStage has a parameters stage,
and so every time you want to execute a function, register,
vote, or winningProposal, we make sure
we are in the right stage to do that based on the elapsed time.
Once again, I given a very low elapsed time for the demo purposes.
In reality, it's going to be higher.
Let's review the code one last time before we go into run.
This is the constructor.
It has the same name as the ballot,
and it requires the number of proposals as a parameter.
Chairperson is the sender of this message,
and we have designated
chairperson voters two that I've been mentioning in the last few demos.
And number of proposals is what you were passing in as parameters.
For the sake of the demo,
we are setting it at three.
And more importantly, we are setting the stage to be the registration stage.
We are finished with the init stage.
Now, we are moving into registration stage and the start time is set as now.
And when you go into the register, here,
I have here the valid stage modifier specified as one of the modifiers for the function.
Function, register, parameters, public is a visibility modifier.
ValidStage is a access modifier,
custom access modifier, that we defined.
And we also have a parameter for that modifier.
So at the outset,
at the head of the function,
we can see clearly,
this function will not be executed if validStage is not reg.
Okay, that's the beauty of the modifier.
And once you go inside,
I replace the if statement,
the regular programmatic statement with that modifier.
So, this was the previous version.
Now, we made it at the header so
the modifier stops it from going into the function itself.
We were checking it inside the function,
now at the header of the function, we're checking it.
And then, the rest of the things are the regular code,
except for the last one,
where I'm checking if the elapsed time is over for the registration.
If so, I'm moving on to the stage,
vote, by setting the stage to the next stage.
And the vote function.
Here again, I have public,
which is a visibility modifier,
and I have an access modifier in validStage.
As you can see, that was stage registration for registration.
This has to be Stage.Vote in order for you to vote.
Once again, I'm also keeping the if statement from
last version so that you can see what replaced this.
This if statement was replaced by the modifier, validStage, Stage.Vote.
That is what we defined before.
And inside, I have the regular code for counting the votes,
and registering the votes, and other things.
And at the end,
if the elapsed time for the voting phase has moved,
I set the stage to the done stage.
I also have votingCompleted.
This is an event, okay?
We'll talk about that later.
And I have a winningProposal that also executes only if the stage is done.
Otherwise, it doesn't execute.
It simply returns false or error so
that we know that winning stage has not been arrived at,
and we don't have any valid results yet.
Validation & Test (Part 2) (BallotV4 Demo)
Here we see [COUGH] a familiar ballot contract with a few more items added.
We have a modifier, and also we have the time and stage elements of that.
[COUGH] You're allowed to vote only at certain times and
you're allowed to only register at certain times.
You can find out the winning proposal only at a certain stage.
Okay [COUGH] I'm going to compile and it's already compiled.
Run, and it's time dependent.
I'm going to go through a little faster.
And here I have all the public variables and methods.
And I'm going to register just one person.
And I just want to make sure that I'm in the stage 2 register.
So I'm going to copy that address [COUGH] and you can see that it is being copied.
And I have to go back to the base address or
the address of the owner of the smart contract.
I register, it goes through fine.
Now I'm looking at the stage, it is not changed.
So I'm going to register one more person, and copy [COUGH] and put it in there.
And I'm going to go back to the chairperson and register.
Two people have been registered.
So I'm in the stage, and now I can vote.
So chairperson votes for 2.
And I'm going to go back to one of the addresses and vote for 1.
Understand that the chairperson has voted for 2.
Now I go back to stage and, okay, so all right.
So now I'm going to go back to the third person and vote for 2 again.
So we have a lot of votes for 2.
We are in stage, it should be 2.
Okay, I'm looking at the winning proposal, and it's 2.
And we've completed a simple demo.
Let me just go back and see whether we can show a revert here.
Because we are not in the right stage, so I'm going to now vote for [COUGH] 1.
And you can see that it reverted because we are not anymore in
the reverting stages, and we are not anymore in the voting stages.
I'm going to register it reverted because we are not anymore in the register state.
We are only in the final stage of winning proposal.
And that is the demo of the ballot revert in case you
are not in the right timeframe and you are not in the right stage terminal.
Please do explore this on your own so to understand the various components here.
Observe that we have given the time duration for the registration and
voting processes one minutes so that we can complete the testing in a finite time.
In reality, these times will be replaced by
actual duration of each of the registration and voting activities.
Consider this issue.
The base mark contract for the ballot given in solidity documentation
will indicate proposal zero as the winning proposal even if no voters or
votes are registered.
That is by default the proposal that came first,
numbered zero, will be chosen as the winning proposal.
This is not intended.
How are we going to address this issue?
We will address it by using an assert clause
at the end of the function winningProposal.
Next, we'll look at interfacing with client applications.
Solidity Learning: Revert(), Assert(), and Require() in Solidity, and the New REVERT
Opcode in the EVM
Client Application
We'll use solidity feature called Events to Interface with Client Application.
We'll explain the concept of events: defining an event and pushing
an event to a subscribed listener and illustrate the event using the Ballot example.
First, a definition of event.
A generic format is,
event, name of the event, and parameters.
For example, event votingCompleted.
Here there are no parameters.
Invoking an event is by the name of the event and any parameters.
In the function vote,
when the state changes to done,
we invoke the event.
We indicate that by invoking votingCompleted event.
In the case of Ballot,
we'll push this event at the end of the voting period.
There are benefits to event logging.
An event is pushed as opposed to
regular function call that is pull to get an action performed.
Typically, an event feature is to indicate to a client application,
user interface or a transaction monitor that a significant milestone has been reached.
The application can listen to the events pushed,
using a listener code, to track transactions,
to receive results through parameters of the event,
initiate a pull request to receive information from the smart contract.
We'll explore these event handlers in
the next course when we discuss decentralized apps, dApps.
Let's now review the entire smart contract with all these features added.
In summary, we have developed the Ballot smart contract incrementally
to illustrate various features including time dependencies,
validation outside the function code
before accessing the function using access modifiers,
asserts and require declarations, and event logging.
Practitioner's Perspective: Shared Rules & Trust
These other problems that industry cared about like contract confidentiality.
That means if I have a smart contract between you and me,
I'll agree to give you three cookies if you give me four doughnuts.
But if on Thursday at noon you give me your four donuts,
I'll give you five cookies.
But if LIBOR goes over six percent, I'll give you 20 cookies.
I can write all those rules in any kind of code I want.
The problem is if I write it in traditional client server code,
if I have root access to the server,
then you can't be sure that I can't change the rules.
If you have root access to the control of the server,
I can't be sure that you're not doing it or we have to trust
some third party or the government and nobody wants that.
So, that's the problem that blockchain for industry
solves in that we can say we all have control,
we all have control of our information,
we all have had the control of agreeing on a set of rules between us, business rules.
But none of us is in control of the system through which we're doing business,
and that's the trick.
It's a social problem that we are solving.
We're solving a social problem.
Among the problems that are out there to solve that are really interesting
to me and to consensus and to the community,
I think the domain of problems that are around governance,
and I don't mean governing the blockchain.
I mean, using the blockchain to govern.
From where I sit,
blockchain isn't about moving tokens around.
I mean, that's just a feature.
What the blockchain really presents as an evolution of the Internet
is the notion of immutable shared rules,
and here we are taping in Washington DC.
I don't know, maybe Washington DC is the Silicon Valley of
the next Internet because who knows shared rules?
People around here.
Treaties on the blockchain,
taxes on the blockchain,
regulations on the blockchain,
and maybe even one day writing the code of
a regulation or a law and debugging it before it's sent to Congress to pass.
You could do that, you can do that with smart contracts.
You could say here are the rules.
If you're creating a security and
it's real security and you're selling it to an American,
then it needs to go through this process KYC or AML,
and if you do that and it's an American citizen,
then they need to be identified and then they need to be an accredited investor.
If you can't get that as a station,
then your token sale,
for example, will not complete.
All right.
You could write those rules so that a token sale might be come one day
the SCC or the CFTC's favorite security
because it's the only one that can actually self-regulate in part.
You can write the rules of the regulation around that transaction
into the transaction so that the transaction
simply can't complete without going through those rules.
That'd be pretty cool,
and be especially cool if we can start to do that over time in such a way that eventually
our law-making process is itself in some part a little bit cody.
Technical Introduction to Events and Logs in Ethereum, Capturing Smart Contract
Events in our User Interface (Solidity)
Best Practices: Evaluating Smart Contracts
We have discussed the design and development of
a smart contract throughout the course thus far.
This module will focus on the best practices.
We'll begin with the cautionary note about evaluating
whether a blockchain-based solution is suitable for your problem.
We'll then discuss some of the best practices when designing Solidity smart contract
focusing on data functions and their visibility modifiers and access modifiers.
We will follow it up with best practices as it relates to Remix IDE.
Upon completion of this module,
you will be able to list the best practices when designing blockchain-based application.
Illustrate the best practices for designing solutions with
smart contract using Solidity and Remix IDE.
Blockchain is not a solution for all applications.
Make sure your application requirements need blockchain features.
In other words, blockchain-based solutions and
smart contracts are not a panacea for all problems you have.
Then, what is it good for?
Recall that we learned in course one that blockchain solution is most suitable for
applications with these characteristics: Decentralized problems,
meaning participant hold the assets and are not co-located.
In more, peer-to-peer transaction without intermediaries.
Operate beyond the boundaries of trust among unknown peers.
Require validation, verification, and
recording on a universally timestamped, immutable ledger.
Autonomous operations guided by rules and policies.
Make sure you need a smart contract on blockchain for your application.
Understand that smart contracts will be visible to
all participants on the chain and will be executed on all the full nodes.
You need a smart contract when you need
a collective agreement based on rules, regulation,
policies, or governance enforced,
and the decision and the provenance for it must be recorded.
Smart contract is not for single node computation.
It does not replace your client server or inherently stateless distributed solutions.
Keep the smart contract code simple, coherent, and auditable.
Let it solve a single problem well to avoid design and coding errors.
In other words, let the state variables and the functions
specified in a smart contract be addressing a single problem.
Do not include redundant data or unrelated functions.
Make the smart contract functions auditable by using custom function modifiers
instead of inline if-else code for
checking pre and post conditions for a function execution.
Smart contracts are usually part of a large distributed application;
the part that requires the services provided by the blockchain.
Blockchain is not a data repository.
Keep only the necessary data in the smart contract.
Of course, it is an immutable distributed ledger of transactions.
Recall that the blockchain also manages
the state transitions and maintains the state hash,
transaction hash, and receipt hash in the header of each block.
These are indeed application dependent overheads.
Given these characteristics, it's a good practice to analyze
the application data and separate them into on-chain an off-chain data.
Design the state variables for the smart contract to
be efficient storage for the on-chain data.
Leave the off-chain data to be managed by higher level applications.
As an example, instead of keeping and enter
a 500 pages of a public legal document on the chain,
keep only the metadata about the document,
including a secure hash to protect the integrity of the document.
Designing Smart Contracts
Let's continue our discussion on best practices.
Use appropriate data types,
understand that Ethereum Virtual Machine,
is a two 56-bit processor optimized for integer computations.
It has a stack machine for execution with limited set of appcodes.
Consider the ballot example discussed in the last module.
For example, a variable proposal name of string type can be expensive,
since a string in a smart contract is a dynamic sized variable.
So, how can we address this issue?
Instead of using a variable string name for the proposals,
use an integer identification for the proposal.
This ID is used as an index into the array of proposals.
This is the number returned by the function winning proposal.
A user-level application outside the chain
can then map the ID to proposal name if so desired.
Make sure you use the integer arithmetic for most of your computational needs.
256-bit processor for the EVM,
is indeed very large in comparison to your regular 64-bit processor,
four times the sheer number of bits.
With every doubling of the number of bits of
the container size the range of values increases exponentially.
Solidity also provides different sizes ranging from eight bits
Uint8 all the way to 256 bits Uint256.
Understand the public visibility modifier for data.
All state variables are created as private.
Any variable on the block chain is viewable to all,
irrespective of the visibility modifier.
You have to explicitly state that a variable is public.
When a variable is declared public,
Solidity compiler automatically creates
a getter method to view the value of the variable.
Internal to the contract,
the variable is accessed as data,
externally it is accessed as a function.
Be aware of this difference in accessing the public data and the getter method.
Maintain a standard order for different function types within a smart contract,
according to their visibility as specified in Solidity docs.
The recommended order for functions within a smart contract are; constructor,
fallback function, external, public, internal, private.
Within a grouping, plays the constant functions last.
Functions can have many different modifiers,
functions have visibility modifiers as well as predefined and custom access modifiers.
The visibility modifiers for the function should come before any custom access modifiers.
Multiple modifiers that apply to a function,
by specifying them in a white space separated
list and are evaluated in the order presented.
Hence, if the output of one modifier depends on the other,
make sure you order them in the right sequence.
For example, function buy,
has three modifiers specified in the following order;
payable, enoughMoney, item available.
Use Solidity-defined payable modifier when sending value.
Only through payable functions,
can an account send value to another address.
Payable is a reserved keyword,
you may use payable as an addition to an existing function.
In the following example,
the bid function is to bid for an auction item,
the transaction bid invoking bid can send either B only if the function is payable.
In other words, deposit, register,
and bid functions are allowed to send money to the target smart contract address.
Pay attention to the order of statements within a function.
The first withdraw function checks the condition first and then allows for withdraw,
the second one has a withdraw code first and then condition check.
Something similar to this,
resulted in parody wallet losing several million ethers,
when a smart contract was killed before moving the ethers.
Use modifier declarations for implementing rules.
Use function access modifiers for;
implementing rules, policies and regulations.
Implementing common rules for all who may access a function,
declaratively validating application specific conditions and
providing auditable elements to allow
verification of the correctness of a smart contract.
Using events in smart contract.
Use events to log important milestones,
during the span of a smart contract execution especially long running ones.
Events can carry at most three index parameters that
can be used efficiently for searching through the events in the block chain.
Instead of a client application,
polling a smart contract using external functions,
events can push information to the application
that would have set up listeners to specific events.
Beware of "now" time variable.
Now is the alias for block timestamp of the block indicating
the universal time when the block and the transaction within it are mined and recorded.
Variable now can be used for approximate elapsed time comparison,
as we illustrated in the ballot example.
However, it is not a good practice to use it
for computation within the application logic.
Also, variable now provides time to
the accuracy of seconds if fine granular time is required,
you may have to resort to other mechanisms.
Use secure hashing for protecting data.
Recall that hashing is a very important function in a block chain.
Data in the block chain is viewable by all.
This means that we may want to secure hash,
to protect its visibility.
Solidity provides a variety of built-in functions for standard secure hash functions.
Keccak, SHA-256,
RIPEMD-160 are Solidity functions available to use for hashing application data.
Remix web IDE
Let's continue our discussion on best practices.
Use appropriate data types,
understand that Ethereum Virtual Machine,
is a two 56-bit processor optimized for integer computations.
It has a stack machine for execution with limited set of appcodes.
Consider the ballot example discussed in the last module.
For example, a variable proposal name of string type can be expensive,
since a string in a smart contract is a dynamic sized variable.
So, how can we address this issue?
Instead of using a variable string name for the proposals,
use an integer identification for the proposal.
This ID is used as an index into the array of proposals.
This is the number returned by the function winning proposal.
A user-level application outside the chain
can then map the ID to proposal name if so desired.
Make sure you use the integer arithmetic for most of your computational needs.
256-bit processor for the EVM,
is indeed very large in comparison to your regular 64-bit processor,
four times the sheer number of bits.
With every doubling of the number of bits of
the container size the range of values increases exponentially.
Solidity also provides different sizes ranging from eight bits
Uint8 all the way to 256 bits Uint256.
Understand the public visibility modifier for data.
All state variables are created as private.
Any variable on the block chain is viewable to all,
irrespective of the visibility modifier.
You have to explicitly state that a variable is public.
When a variable is declared public,
Solidity compiler automatically creates
a getter method to view the value of the variable.
Internal to the contract,
the variable is accessed as data,
externally it is accessed as a function.
Be aware of this difference in accessing the public data and the getter method.
Maintain a standard order for different function types within a smart contract,
according to their visibility as specified in Solidity docs.
The recommended order for functions within a smart contract are; constructor,
fallback function, external, public, internal, private.
Within a grouping, plays the constant functions last.
Functions can have many different modifiers,
functions have visibility modifiers as well as predefined and custom access modifiers.
The visibility modifiers for the function should come before any custom access modifiers.
Multiple modifiers that apply to a function,
by specifying them in a white space separated
list and are evaluated in the order presented.
Hence, if the output of one modifier depends on the other,
make sure you order them in the right sequence.
For example, function buy,
has three modifiers specified in the following order;
payable, enoughMoney, item available.
Use Solidity-defined payable modifier when sending value.
Only through payable functions,
can an account send value to another address.
Payable is a reserved keyword,
you may use payable as an addition to an existing function.
In the following example,
the bid function is to bid for an auction item,
the transaction bid invoking bid can send either B only if the function is payable.
In other words, deposit, register,
and bid functions are allowed to send money to the target smart contract address.
Pay attention to the order of statements within a function.
The first withdraw function checks the condition first and then allows for withdraw,
the second one has a withdraw code first and then condition check.
Something similar to this,
resulted in parody wallet losing several million ethers,
when a smart contract was killed before moving the ethers.
Use modifier declarations for implementing rules.
Use function access modifiers for;
implementing rules, policies and regulations.
Implementing common rules for all who may access a function,
declaratively validating application specific conditions and
providing auditable elements to allow
verification of the correctness of a smart contract.
Using events in smart contract.
Use events to log important milestones,
during the span of a smart contract execution especially long running ones.
Events can carry at most three index parameters that
can be used efficiently for searching through the events in the block chain.
Instead of a client application,
polling a smart contract using external functions,
events can push information to the application
that would have set up listeners to specific events.
Beware of "now" time variable.
Now is the alias for block timestamp of the block indicating
the universal time when the block and the transaction within it are mined and recorded.
Variable now can be used for approximate elapsed time comparison,
as we illustrated in the ballot example.
However, it is not a good practice to use it
for computation within the application logic.
Also, variable now provides time to
the accuracy of seconds if fine granular time is required,
you may have to resort to other mechanisms.
Use secure hashing for protecting data.
Recall that hashing is a very important function in a block chain.
Data in the block chain is viewable by all.
This means that we may want to secure hash,
to protect its visibility.
Solidity provides a variety of built-in functions for standard secure hash functions.
Keccak, SHA-256,
RIPEMD-160 are Solidity functions available to use for hashing application data.
pragma solidity ^0.4.0;
contract Greeter{
string public yourName;
function Greeter() public{
yourName="World";
}
function set(string name)public{
yourName=name;
}
function hello() constant returns(string){
return yourName;
}
}
pragma solidity ^0.4.0;
contract SimpleStorage{
uint storedData;
function set(uint x) public{
storedData=x;
}
function get() constant public returns (uint){
return storedData;
}
function increment(uint n) public{
storedData=storedData+n;
return;
}
function decrement(uint n) public{
storedData=storedData-n;
return;
}
}
pragma solidity ^0.4.24;
contract MyContract{
string value;
constructor() public {
value="myValue";
}
function get() public view returns(string){
return value;
}
function set(string _value) public {
value=_value;
}
}
pragma solidity ^0.5.1;
contract MyContract{
string public value="myValue";
constructor() public {
value="myValue";
}
function get() public view returns(string memory ){
return value;
}
function set(string memory _value) public {
value=_value;
}
}
pragma solidity ^0.5.1;
contract MyContract{
string public value ;
constructor() public {
value="myValue";
}
function set(string memory _value) public {
value=_value;
}
}
pragma solidity ^0.5.1;
contract MyContract{
string public value="myValue" ;
function set(string memory _value) public {
value=_value;
}
}
pragma solidity ^0.5.1;
contract MyContract{
string public constant value="myValue" ;
pragma solidity ^0.5.1;
contract MyContract{
string public constant stringvalue="myString" ;
bool public myBool=true;
int public myInt =-1;
uint public myUint=1;
uint8 public myUint8=8;
uint256 public myUint256=99999;
pragma solidity ^0.5.1;
contract MyContract{
enum State{Waiting, Ready, Active}
State public state;
constructor() public{
state=State.Waiting;
}
function activate() public{
state=State.Active;
}
function isActive() public view returns(bool){
return state==State.Active;
}
}
pragma solidity ^0.5.1;
contract MyContract{
Person[] public people;
uint256 public peopleCount;
struct Person{
string _firstName;
string _lastName;
}
function addperson(string memory _firstName, string memory _lastName) public {
people.push(Person(_firstName, _lastName));
peopleCount+=1;
}
}
pragma solidity ^0.5.1;
contract MyContract{
uint256 public peopleCount;
mapping(uint=>Person) public people;
struct Person{
uint _id;
string _firstName;
string _lastName;
}
function addperson(string memory _firstName, string memory _lastName) public {
peopleCount+=1;
people[peopleCount]=Person(peopleCount,_firstName,_lastName);
}
}
pragma solidity ^0.5.1;
contract MyContract{
uint256 public peopleCount;
mapping(uint=>Person) public people;
struct Person{
uint _id;
string _firstName;
string _lastName;
}
function addperson(string memory _firstName, string memory _lastName) public {
incrementCount();
people[peopleCount]=Person(peopleCount,_firstName,_lastName);
}
function incrementCount() internal{
peopleCount+=1;
}
}
pragma solidity ^0.4.22;
contract MyContract{
uint256 public peopleCount;
mapping(uint=>Person) public people;
address owner;
modifier onlyOwner() {
require(
msg.sender == owner,
"Only owner can call this function."
);
_;
}
struct Person{
uint _id;
string _firstName;
string _lastName;
}
constructor () public { owner = msg.sender; }
function addperson(
string memory _firstName, string memory _lastName) public onlyOwner {
incrementCount();
people[peopleCount]=Person(peopleCount,_firstName,_lastName);
}
function incrementCount() internal{
peopleCount+=1;
}
}
https://www.youtube.com/watch?v=ipwxYa-F1uY&t=1288s
https://www.epochconverter.com/
pragma solidity ^0.4.22;
contract MyContract{
uint256 public peopleCount;
mapping(uint=>Person) public people;
uint256 openingTime=1582255400;
modifier onlyWhileOpen() {
require(block.timestamp>=openingTime);
_;
}
struct Person{
uint _id;
string _firstName;
string _lastName;
}
function addperson(
string memory _firstName,
string memory _lastName
)
public
onlyWhileOpen
{
incrementCount();
people[peopleCount]=Person(peopleCount,_firstName,_lastName);
}
function incrementCount() internal{
peopleCount+=1;
}
}
pragma solidity ^0.5.1;
contract MyContract{
mapping(address =>uint256) public balances;
address payable wallet;
constructor(address payable _wallet) public {
wallet=_wallet;
}
function buyToken() public payable {
balances[msg.sender] +=1;
wallet.transfer(msg.value);
}
}
Account: Take 2nd address for considering it as the wallet. Copy its address by right side
clicking. Paste this address under deploy. Click deploy. The deploy should be successful.
BuyToken: Select the first account address. Press buy token. Select the second address.
select balance
Select ether . value = 1. Press buy token. Check balance of second address
https://www.youtube.com/watch?v=ipwxYa-F1uY&t=
Fallback function in solidity
select account 1
pragma solidity ^0.5.1;
contract MyContract{
mapping(address =>uint256) public balances;
address payable wallet;
event Purchase(
address indexed _buyer,
uint256 _amount
);
constructor(address payable _wallet) public {
wallet=_wallet;
}
function () external payable {
buyToken();
}
function buyToken() public payable {
balances[msg.sender] +=1;
wallet.transfer(msg.value);
emit Purchase(msg.sender,1);
}
pragma solidity ^0.5.1;
contract ERC20Token{
string public name;
mapping(address =>uint256) public balances;
function mint()public{
balances[tx.origin] ++;
}
}
contract MyContract{
mapping(address =>uint256) public balances;
address payable wallet;
address public token;
constructor(address payable _wallet, address _token) public {
wallet=_wallet;
token=_token;
}
function () external payable {
buyToken();
}
function buyToken() public payable {
ERC20Token(address(token)).mint();
wallet.transfer(msg.value);
pragma solidity ^0.5.1;
contract ERC20Token{
string public name;
mapping(address =>uint256) public balances;
constructor(string memory _name) public{
name=_name;
}
function mint()public{
balances[tx.origin] ++;
}
}
contract MyToken is ERC20Token{
string public symbol;
address[] public owners;
uint256 ownerCount;
constructor(
string memory _name,
string memory _symbol
)
ERC20Token (_name)
public{
symbol=_symbol;
}
function mint() public {
super.mint();
ownerCount++;
owners.push(msg.sender);
}
<html>
<body>
<div>
<input type="text" id="amount">
<p id='balance'></p>
<button id = 'deposit'>Deposit</button>
<button id = 'withdraw'>Withdraw</button>
</div>
<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.0.0-beta.36/dist/
web3.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" crossorigi
n="anonymous"></script>
<script>
var contract;
$(document).ready(function()
{
web3=new Web3(web3.currentProvider);
var address="0x60feB229da650d58c33bEcaC6280A201b976d0B7";
var abi=[
{
"constant": false,
"inputs": [
{
"internalType": "int256",
"name": "amt",
"type": "int256"
}
],
"name": "deposit",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"internalType": "int256",
"name": "amt",
"type": "int256"
}
],
"name": "withdraw",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"constant": true,
"inputs": [],
"name": "getBalance",
"outputs": [
{
"internalType": "int256",
"name": "",
"type": "int256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
];
contract=new web3.eth.Contract(abi,address);
contract.methods.getBalance().call().then(function(bal)
{
$('#balance').html(bal);
})
})
$('#deposit').click(function()
{
var amt=0;
amt=parseInt($('#amount').val());
ethereum.enable()
web3.eth.getAccounts().then(function(accounts)
{
var acc=accounts[0];
return contract.methods.deposit(amt).send({from:acc});
}).then(function(tx)
{
console.log(tx);
}).catch(function(tx)
{
console.log(tx);
})
})
$('#withdraw').click(function()
{
var amt=0;
amt=parseInt($('#amount').val());
ethereum.enable()
web3.eth.getAccounts().then(function(accounts)
{
var acc=accounts[0];
return contract.methods.withdraw(amt).send({from:acc});
}).then(function(tx)
{
console.log(tx);
}).catch(function(tx)
{
console.log(tx);
})
})
</script>
</body>
</html>