2. ZeroLAB
ZeroLAB
Welcome back!
In the last session, we got to know more about smart contract – a
powerful component which help blockchain become programmable.
We hope you have had a good learning experiences so far!
In this session, we will learn about another powerful and crucial
component of blockchain technology which ensures blockchain
network function as it is expected. The component is consensus
protocol.
INTRO
6. ZeroLAB
ZeroLAB
As we learned in lesson 1
and 2, blockchain network
is decentralized and that is
why people want it.
Consensus protocol was
said to help the blockchain
network secure and
moving forward. And,
blockchain is owned and
governed by everyone
LESSON REWIND
Decen-
tralization
Trustless
Environment
Data
Availability &
Integrity
Network
Persistance
Optimized
Resource
Accessibility
7. ZeroLAB
ZeroLAB
Blockchain nodes run in
decentralized manners. Thus,
there is no central entity
ensuring network
consistency and security.
But the absence of a central
party is preferable as it
provides transparency and
lack of ownership, meaning
data is accessible, verifiable
and auditable to everyone.
THE NEED
However, there must be something
that:
▪ Controls the decentralized system
to make sure “bad nodes” cannot
manipulate it.
▪ Ensures the blockchain network is
functional even there are some
faults or malicious actions that may
compromise it. This is called fault-
tolerant.
▪ Decides what is true. Any updates
of on-chain data need to be
validated.
8. ZeroLAB
ZeroLAB
The term consensus, in
computer science, was
defined before the
introduction of blockchain.
Its utilization was mainly
mentioned in distributed
systems where participants
need to agree on one
single state for the entire
system. This is referred to as
“reaching consensus”.
THE CONSENSUS
9. ZeroLAB
ZeroLAB
Consensus is placed at the
core of blockchain system.
In blockchain, it is referred
to as the mechanism
ensuring the common
state of the system is
correctly derived by all
nodes and decentralization
is maintained.
BLOCKCHAIN CONSENSUS
10. ZeroLAB
ZeroLAB
Blockchain consensus usually
functions based on incentive
and punishment scheme. In
other words, blockchain system
rewards honest behaviours,
which keep the system secure
and consistent, and punish
those with malicious ambition
to manipulate the system state.
In short, blockchain consensus
implements “strict rules
without rulers”.
BLOCKCHAIN CONSENSUS
12. ZeroLAB
ZeroLAB
As the blockchain technology is thriving to
make enormous impacts. Multiple types
consensus protocols were introduced. The
principles of any consensus protocols
can be comprehended by answering the
following questions:
▪ Who can change the past, and how can
the past be changed?
▪ Who can change the future, and how
can the future be changed?
▪ What cost has to be paid for making
changes?
▪ How decentralized is the power to
make changes?
▪ Who and how will know if something
has changed?
CONSENSUS PROTOCOLS
13. ZeroLAB
ZeroLAB
The proof of work (PoW) was created for the original
blockchain Bitcoin as a consensus algorithm. PoW is an
important part of Bitcoin to stabilize the difficulties for
mining.
Mining is a process which requires nodes to solve a
“cryptographic puzzle” to derive a block. In PoW, the
reward for discovering a legitimate block is a certain
amount of cryptocurrency (e.g., bitcoins, ethers). In
contrary, miners will lose the money for a huge amount
of electricity they invested in solving the cryptographic
puzzle, if they propose a “sketchy block”.
PROOF OF WORK (PoW)
14. ZeroLAB
ZeroLAB
PROOF OF WORK (PoW)
Pros
▪ Security
▪ Decentralization
▪ Double spending prevention
Cons
▪ Excessive energy consumption.
▪ Low transaction speed.
Bitcoin and Ethereum are the
biggest blockchains using PoW.
Miners
Block
Crypto-
graphic
puzzle
Proof of Work
Broadcast new
block
Verified block
Restart
Transaction
15. ZeroLAB
ZeroLAB
The proof of stake (PoS) was proposed as the successor
of PoW to solve the problems that are known in PoW. A
core difference in PoS is that nodes do not have to do
mining, they need to stake and attest instead.
Staking is the process when a node nominate itself as
validator in the PoS protocol by depositing a certain
amount of cryptocurrency via a special transaction.
Attesting is referred to as the action that the validators
take to decide whether a block is valid.
PROOF OF STAKE (PoS)
16. ZeroLAB
ZeroLAB
▪ The blockchain maintains a list of validators.
▪ Any users who deposit some ether can self nominate as a
validator by staking.
▪ Validators are randomly appointed to propose and attest
on the next valid block.
▪ Each validator’s vote is weighted by its stake.
▪ A validator may lose deposit when staking on rejected
block.
▪ A validator may also gain reward for proposing and
staking on block that is accepted by the majority.
PROOF OF STAKE (PoS)
Pros
▪ Energy saving
▪ Higher transaction speed
▪ Higher finality
Cons
▪ Less security
▪ Less decentralization
Algorand, Tezos and Polkadot are
examples of blockchains using PoS
https://developer.algorand.org/docs/get-
started/basics/why_algorand/#proof-of-stake-versus-proof-
of-work
17. ZeroLAB
ZeroLAB
There are still more consensus
protocols in the industry:
▪ Proof of Authority
▪ Proof of Elapsed Time
▪ Proof of Capacity
▪ Byzantine Fault Tolerant Protocol
▪ And more…
Those protocols were not
elaborated because either they are
not widely adopted, or they are
not used in public blockchain.
CONSENSUS PROTOCOLS
18. ZeroLAB
ZeroLAB
There is no one-solution-fits-all
consensus algorithm, at least
for the moment. There are
always trade-offs whether it is
security, cost, decentralization
or finality.
Therefore, the answer to
which consensus algorithm
is “better” lies under your
needs, your goals and your
solution.
CONTROVERSY & CONCLUSION
19. ZeroLAB
Time to build
Our exploration about consensus protocol is over, it is
time for practical activities.
20. ZeroLAB
ZeroLAB
We already made it through
two thirds of the journey!
Let’s keep it going.
This practical session will
show you how to write,
deploy and test a smart
contract.
PRACTICAL JOURNEY
Topics
1. Create and fund your account
with testnet funds.
2. Setup your development
environment.
3. Connect account to a Dapp.
4. Write a simple smart contract,
deploy and test.
5. Upload images to IPFS through a
Dapp.
6. Create NFT on the Dapp and
transfer using your wallet.
22. ZeroLAB
ZeroLAB
Clone the
pyteal-prac
repo into the
zerolab-prac
folder by
running the
following
commands
CLONE PYTEAL-PRAC
// Change directory to zerolab-prac
cd zerolab-prac
// Check directory content
ls
// Remove pyteal-prac directory if there is one
rm –rf pyteal-prac
// Clone the pyteal-prac repo
git clone https://github.com/jasonhtpham/pyteal-
prac.git
// Change directory to pyteal-prac
cd pyteal-prac
23. ZeroLAB
ZeroLAB
Check the
content of the
cloned repo
and launch
VS Code to
edit the
smart
contracts
code
LAUNCH VS CODE
// Check directory content
ls
// Launch VS Code with the current directory
code .
24. ZeroLAB
ZeroLAB
In Algorand smart contracts:
▪ The ApprovalProgram is responsible for
processing all application calls to the contract.
This program is responsible for implementing
most of the logic of an application.
▪ The ClearStateProgram is used to handle
accounts using the clear call to remove the smart
contract from their balance record. This program
will pass or fail the same way the
ApprovalProgram does.
APPROVAL AND CLEARSTATE PROGRAM IN ALGORAND
26. ZeroLAB
ZeroLAB
This piece of
code tells the
smart
contract to
run the
on_create
sequence
when it is
initialized.
UPDATE SC CODE
# TODO1: The function to call when the smart contract is
initialized
[Txn.application_id() == Int(0), on_create],
27. ZeroLAB
ZeroLAB
This piece of
code defines
the on_create
sequence
that set 0 as
the initial
value of the
“number”
global state.
UPDATE SC CODE
# TODO2: This sequence will be executed when the smart
contract is initialized.
on_create = Seq([
App.globalPut(Bytes("number"), Int(0)),
Return(Int(1)),
])
28. ZeroLAB
ZeroLAB
This piece of
code takes the
first
transaction
argument as
the name of
the sequence
called by the
users.
If the user asks
for the
“set_number”,
then executes
the
set_number
sequence
UPDATE VS CODE
# TODO3: Determine which function to call based on the
transaction argument
called_function = Txn.application_args[0]
# TODO3: Based on called_function, call the relevant
function
handle_noop = Cond(
[called_function == Bytes("set_number"),
set_number]
)
29. ZeroLAB
ZeroLAB
This piece of
code defines
the
set_number
sequence that
set the second
transaction
argument
passed by the
user as the
new value of
the “number”
global state.
UPDATE SC CODE
# TODO4: The sequence to set the global variable number
to provided value
set_number = Seq([
# Take the 2nd transaction argument and store it in
the "number" global variable
App.globalPut(Bytes("number"),
Btoi(Txn.application_args[1])),
Return(Int(1)),
])
30. ZeroLAB
ZeroLAB
simple_clear.py
file which, in
this case, does
not have any
logic as we do
not have to
worry about
this part.
CLEAR STATE
from pyteal import *
def clear_state_program():
program = Seq([
Return(Int(1))
])
return program
with open("simple_clear.teal", "w") as f:
compiled = compileTeal(clear_state_program(),
mode=Mode.Application, version=2)
f.write(compiled)
31. ZeroLAB
ZeroLAB
Install the
pyteal
module to
compile the
smart
contract. In
the VS Code
terminal, run
the following
commands.
COMPILE SC
// Install pip, type ‘y’ and hit ‘Enter’ when
prompted
sudo apt install python3-pip
// Install pyteal module
pip install pyteal
// Compile smart contract
python3 simple_approval.py
33. ZeroLAB
ZeroLAB
Now, we start
the sandbox
to get us
ready to
deploy the
compiled
smart
contract. This
may take 5 –
10 minutes.
START SANDBOX
// Change directory to sandbox/
cd ../sandbox/
// Start the sandbox (this may take a few minutes)
./sandbox up testnet -v
34. ZeroLAB
ZeroLAB
After the
sandbox is up
and running,
we create a
test wallet and
import our
account from
the Pera Algo
Wallet by
providing your
Account 1’s 25
words
mnemonic
IMPORT ACCOUNT
// Go inside the algod container
./sandbox enter algod
// Change directory to data/
cd /data
// Create a new wallet called test
goal wallet new test
// Import our Account 1 from Pera Algo Wallet
goal account import
If you did not save your 25 words mnemonic, open Pera Algo Wallet app,
choose Account 1 > More > View Passphrase
35. ZeroLAB
ZeroLAB
Copy your
Account 1
address and
store it in
MY_ACCOUNT
and run the
“goal app
create”
command to
deploy the
smart contract.
DEPLOY SC
// Create a variable called MY_ACCOUNT
export MY_ACCOUNT = <your account address>
// Deploy the smart contract using teal files
goal app create --creator $MY_ACCOUNT --approval-
prog simple_approval.teal --clear-prog
simple_clear.teal --global-ints 1 --global-
byteslices 0 --local-ints 0 --local-byteslices 0
37. ZeroLAB
ZeroLAB
Now we need a
frontend to
provide a user
interface to set
a number. This
front end is
built on top of
our Wallet
Connect Dapp
in the previous
practical
session.
CLONE THE DAPP
// Change directory to zerolab-prac
cd zerolab-prac
// Clone the pyteal-prac repo
git clone https://github.com/jasonhtpham/set-number-
dapp.git
// Change directory to pyteal-prac
cd set-number-dapp
// Launch VS Code with the current directory
code .
38. ZeroLAB
ZeroLAB
INSTALL PACKAGES AND RUN THE DAPP
In the VS Code termimal, run “npm i” to install packages (this may take a
few minutes) > Run “npm start” to launch the app.
39. ZeroLAB
ZeroLAB
INCOMPLETE DAPP
The Set Number Dapp requires you to connect to an account to function
properly. Go ahead and connect the Dapp to your account via Pera
Algo Wallet like what we did in the last session.
40. ZeroLAB
ZeroLAB
INCOMPLETE DAPP
At this stage, the set number function is not working as we have not
implemented it and not connected to the smart contract yet. So, the
current number is not available.
42. ZeroLAB
ZeroLAB
UPDATE DAPP
In VS Code, navigate and open a file named SetNumber.js. Then, copy the
following provided pieces of code in there under the relevant // TODO.
43. ZeroLAB
ZeroLAB
This code will
create an
Algorand client
instance and
store your app
index in the
appIndex
variable to be
used later.
SET NUMBER FUNCTION
// TODO1: Connect to the algorand node
const client = new algosdk.Algodv2('', 'https://testnet-
api.algonode.cloud', 443);
// TODO1: Provide the app ID on testnet
const appIndex = <your appId>;
Take you app index from the previous step and replace <your appId> with it.
44. ZeroLAB
ZeroLAB
This piece of
code will use
the Algorand
client instance
to get the
current first
global state
value, which is
the “number”
variable in our
created
contract.
SET NUMBER FUNCTION
// TODO2: Use the Algorand client to get the current number from the smart
contract
const getCurrentNumber = useCallback(async () => {
try {
setLoading(true);
const app = await client.getApplicationByID(appIndex).do();
if (!!app.params['global-state'][0].value.uint) {
setCurrentNumber(app.params['global-state'][0].value.uint);
setLoading(false);
} else {
setCurrentNumber(0);
setLoading(false);
}
} catch (e) {
setLoading(false);
console.error('There was an error connecting to the algorand node: ', e)
}
}, []);
useEffect(() => {
getCurrentNumber();
}, [getCurrentNumber]);
45. ZeroLAB
ZeroLAB
This piece of
code takes the
entered
number from
the user and
send it as the
parameter to
set the new
value to the
“number”
global state of
our smart
contract.
SET NUMBER FUNCTION
// TODO3: Use the Algorand client to set the current number to the new number
const setNumber = async () => {
try {
setLoading(true);
const numberToSet = parseInt(document.getElementById('number-to-set').value);
const suggestedParams = await client.getTransactionParams().do();
const appArgs = [new Uint8Array(Buffer.from("set_number")), encodeUint64(numberToSet)];
const transaction = algosdk.makeApplicationNoOpTxn(
props.account,
suggestedParams,
appIndex,
appArgs
);
const transactionDetails = [{ txn: transaction, signers: [props.account] }];
const signedTx = await props.wallet.signTransaction([transactionDetails]);
const { txId } = await client.sendRawTransaction(signedTx).do();
const result = await waitForConfirmation(client, txId, 2);
alert(`Result: ${JSON.stringify(result)}`);
getCurrentNumber();
} catch (e) {
setLoading(false);
console.error(`There was an error calling the counter app: ${e}`);
}
}
51. ZeroLAB
ZeroLAB
TRANSACTION DETAILS
On your browser, go to AlgoExplorer (https://testnet.algoexplorer.io/) >
Search for your application (smart contract) > Application Global State
> Verify the current number.
52. ZeroLAB
We have created our first Dapp. Although it is a very
simple one, but we have learned how to write smart
contract, deploy and connect it to a frontend
component. We hope you enjoyed the activity.
In the next practical session, we will look at a tool
which provides us with decentralized file storage.
PRACTICAL 3