0% found this document useful (0 votes)
30 views76 pages

Chapter3 - Ethereuemf

Chapter 3 discusses Ethereum, highlighting its differences from Bitcoin, including its programmability and use of smart contracts. It details the evolution from Ethereum 1.0 to Ethereum 2.0, emphasizing improvements in scalability and the transition from proof of work to proof of stake. Additionally, it covers Ethereum wallets, types of accounts, and the significance of the Ethereum Virtual Machine in enabling decentralized applications.

Uploaded by

asavari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views76 pages

Chapter3 - Ethereuemf

Chapter 3 discusses Ethereum, highlighting its differences from Bitcoin, including its programmability and use of smart contracts. It details the evolution from Ethereum 1.0 to Ethereum 2.0, emphasizing improvements in scalability and the transition from proof of work to proof of stake. Additionally, it covers Ethereum wallets, types of accounts, and the significance of the Ethereum Virtual Machine in enabling decentralized applications.

Uploaded by

asavari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Chapter 3:

Permissionless Blockchain: Ethereum

Dr. Trupti Lotlikar


Department of Information Technology
FR.CRIT, Vashi.
Commonalities between Bitcoin and Ethereum

• ➔ Peer-to-peer network
• ➔ Blocks and structure of blocks
• ➔ Blocks chained as ledger(blockchain)
• ➔ Cryptography primitives
• ➔ Securing network with consensus algorithm
Difference between Bitcoin and Ethereum

• ➔ UTXO vs Account-based
• ➔ Bitcoin PoW vs Ethereum 1.0 PoW vs Ethereum 2.0 PoS
• ➔ Turing in-complete vs Turing complete
• ➔ Ethereum virtual machine
• ➔ Bitcoin block header vs Ethereum Block header
Ethereum
• Vitalik Buterin invented Ethereum network , which has a special token called Ether,
in 2015
• The key feature of Ethereum is its programmability, which enables the development
of decentralized applications.
• Completely decentralised as it is run by thousands of separate computers.
• It was the first technology to implement a smart contract. That has ever taken place.
• Turing complete system. In its virtual machine, Ethereum can run programs and
read and write data to memory. Any programme that a turing complete machine can
compute may be done by this machine.
• Immutable public database that stores a history of each transaction
• It is referred to as ETH and has its own currency called Ether.
Ether
• ➔ In every civilization, currency is used as a medium of exchange for
• goods and services.
• ➔ In Ethereum world, the currency is called ether (ETH or 𝚵).
• It is the second largest cryptocurrency around.
• The Ethereum network and smart contracts are powered by ether, which is used as fuel
or gas.
• Users utilize ether to pay for services rendered by the network.
• ➔ Ether is subdivided into several denominations:
Ethereum 1.0
• Bitcoin founder Vitalik Buterin in 2013 wrote that blockchain technology and bitcoin
might have uses beyond just monetary transactions.
• Creation of applications required the use of scripting language , inorder to make the
blockchain possible to be attached to tangible assets like equities and real estate.
• Therefore, Ethereum transformed the use cases of blockchain from an open ledger that
just permits peer to peer money transfers to one that permits the creation of smart
contracts and decentralised applications.
• Challenges:
• Energy waste: takes more electricity than a small country. 22kwh per transaction.
• Scalability :max 1-3m Transactions per day
• Centralization: code is controlled by small group of people. Small node count
Ethereum 2.0
• Ethereum 2.0, also known as Eth2, ETH 2.0, or “Serenity,”
• It attempts to increase the speed of the Ethereum network, effectiveness and scalability
to address bottlenecks and handle more transactions.
• Ethereum 2.0 first launch was scheduled in 2021.
• Makes use of proof of stake
• Sharding adds to the network ability to scale and increase security. By splitting the
blockchain into numerous smaller blockchains, shard chains boost efficiency by allowing
transactions to be handled concurrently rather than sequentially. As the workload is
divided among the validations, processing power grows.
Ethereum 2.0 :Development phases
• Phase 0: Launch of beacon chain
• The initial release of Ethereum 2.0 will not include the capabilities of sending
transactions, storing user data or deploying smart contracts
• Phase 0 is concerned with turning on the new PoS system for Ethereum , which is
the central centre for coordination and consensus
• Phase 0 focussed on coordinating validators and supervising their work
• The beacon chain , has been secured by validators uses PoS
• The main Ethereum blockchain continues to use PoW
• Phase1: This begins with sharding.
• Sharding refers to the division of a database among several computers,In context of
blockchain , it refers to the division of a a single cryptocurrency network among
many blockchains.
• Phase 1 will activate sharding which is ethereums scalability solution , after the
foundation, the beacon chain and its PoS network is operational.
• Shard in Ethereum 2.0 refers to each unique PoS blockchain , As an alternative ,
users will have the option of selecting one of several shards to send their
transactions to rather than having to validate each transaction through a single slow-
moving blockchain ,Because each shard chooses its own validators at random, it can
process transactions and build new blocks simultaneously with other shards.
• The beacon chain compiles shard data into a single central blockchain , enabling the
necessary bridge between all shards,
• Ethereum attempts to increase network throughput and performance by sharding
which splits up transaction load among many blockchains.
• Phase 1.5
• This phase enables a bridge between the blockchain environment , fusing the old PoW
Ethereum with the PoS chain
• Ethereum 2.0 is a distinct network from Ethereum before Phase 1.5
• Phase2
• Enabling smart contract execution and cross –shared connectivity are 2 of Phase 2’s key
characteristics
• Users will have the ability to install and store new smart contract data on any of the shards
in the Ethereum 2.0
• Purpose : enable creation of execution environments that can initiate the protocols of
another blockchain such a s bitcoin
• Solidity is the only programming language that can currently be used to create smart
contracts on Ethereum .
• However, with phase1.5/2, dAPPs will be written in any programming language.
• How does Ethereum 2.0 differ from Ethereum 1.0?
• Ethereum 2,0 will use a PoS consensus method, in contrast to Ethereum 1.0 which used PoW
• Scalability feature:The network can only support 30 transactions /sec with Ethereum 1.0 which
leads to delay and congestion. Ethereum 2,0 claims to support 1 million transactions/sec. Shard
chains will be used to boost this.
• Ethereum 1.0 is made of single chain of consecutive blocks. While secure, this is incredibly slow
and ineffective. This blockchain is divided up with the introduction of shard chains, allowing
transactions to be handled in parallel chains rather than sequential ones.the network becomes
faster and easier to scale
• Ethreuem 2.0 will decrease the gas price
Ethereum’s Components
• In Ethereum, the components of a blockchain system described
• P2P network
• Ethereum runs on the Ethereum main network, which is addressable on TCP port 30303, and runs a
protocol called DΞVp2p.
• Consensus rules
• Ethereum’s consensus rules are defined in the reference specification, the Yellow Paper
• Ethereum transactions are network messages that include (among other things) a sender, recipient,
value, and data payload.
• State machine Ethereum state transitions are processed by the Ethereum Virtual Machine (EVM), a
stack-based virtual machine that executes bytecode (machine-language instructions).
• EVM programs, called “smart contracts,” are written in high-level languages (e.g., Solidity) and compiled
to bytecode for execution on the EVM.
• Data structures
• Ethereum’s state is stored locally on each node as a database (usually Google’s LevelDB), which contains the
transactions and system state in a serialized hashed data structure called a Merkle Patricia Tree.
• Consensus algorithm
• Ethereum uses Bitcoin’s consensus model, Nakamoto Consensus, which uses sequential single-signature blocks,
weighted in importance by PoW to determine the longest chain and therefore the current state. However, there
are plans to move to a PoS weighted voting system, codenamed Casper, in the near future.
• Economic security
• Ethereum currently uses a PoW algorithm called Ethash, but this will eventuallybe dropped with the move to PoS
at some point in the future.
• Clients
• Ethereum has several interoperable implementations of the client software, the most prominent of which are Go-
Ethereum (Geth) and Parity.
Turing Completeness EVM
• EVM:
• Before Ethereum , blockchain apps could only be created to do small number of tasks.
• The only purpose for which crypto currencies were intended was to function as peer-to –peer
digital currencies.
• This presented a challenge for programmers since they could create a anew class of blockchain
based platforms and programmes.
• The engine that executes transaction code is the Ethereum virtual machine(EVM)
• The EVM is a global computer that anybody can utilize for a nominal fee paid in cryptocurrency.
• The portion of Ethereum that executes smart contract instructions are known as EVM
• Every Ethereum node runs EVM
• EVM is completely isolated and has no access to
file system and processes . So , each node in the
system runs the EVM,that way it can maintain
consensus across the network.
• The EVM makes it possible to construct hundreds
of distinct apps on a single platform rather than
having to create a unique blockchain for each app.
• Turing Completeness
• Alan Turing further defined a system to be Turing complete if it can be used to
simulate any Turing machine. Such a system is called a Universal Turing machine
(UTM).
• Ethereum’s ability to execute a stored program, in a state machine called the
Ethereum Virtual Machine, while reading and writing data to memory makes it a
Turing complete system and therefore a UTM. Ethereum can compute any
algorithm that can be computed by any Turing machine, given the limitations of
finite memory.
• Given the restriction of finite memory, Ethereum can calculate any algorithm
that can be calculated by any turing machine.
• Because Ethereum is Turing complete, it enables anybody, given enough
memory and time, to run any program they choose, independent
of programming language it is created in.Turing demonstrated that running a
programme through computer simulation does not allow you to forecast when it
would end.
• Turing-complete computers are capable of running in infinte loops..(i.e.
programme never ends.
• Ethereum introduces a concept called Gas to address this problem.
• Every instruction to be executed in a a smart contract has a fixed price in terms
of units of gas.
• The amount of gas that determines the maximum allowable consumption must
be included in transaction that cause a smart contract to be executed. If more
gas is needed for computation than it is available for the transaction , the EVM
will stop running.
Ethereum Wallets
• At a high level, a wallet is a software application that serves as the primary user interface to Ethereum. The
wallet controls access to a user’s money, managing keys and addresses, tracking the balance, and creating and
signing transactions.
• In addition, some Ethereum wallets can also interact with contracts, such as ERC20 tokens.
• More narrowly, from a programmer’s perspective, the word wallet refers to the system .used to store and
manage a user’s keys. Every wallet has a key-management component.
Wallet is a software programme that controls your Ethereum account .
• A common misconception about Ethereum is that Ethereum wallets contain ether or tokens. In fact, very
strictly speaking, the wallet holds only keys. The ether or other tokens are recorded on the Ethereum
blockchain.
• Users control the tokens on the network by signing transactions with the keys in their wallets
• Nondeterministic (Random) Wallets
• It is considered good practice to avoid Ethereum address reuse as part of maximizing your privacy
while using Ethereum—i.e., to use a new address (which needs a new private key) every time you
receive funds.
• In non-deterministic wallets, every private key is generated from a different random source and are
independent of each other.
• To follow this practice, a nondeterministic wallet will need to regularly increase its list of keys,
which means you will need to make regular backups.
• If you ever lose your data (disk failure, drink accident, phone stolen) before you’ve managed to
back up your wallet, you will lose access to your funds and smart contracts.
• The “type 0” nondeterministic wallets are the hardest to deal with, because they create a new
wallet file for every new address
• Deterministic (Seeded) Wallets
• Deterministic or “seeded” wallets are wallets that contain private keys that are all derived from a single
master key, or seed.
• The seed is a randomly generated number that is combined with other data, such as an index number or
“chain code”
• In a deterministic wallet, the seed is sufficient to recover all the derived keys, and therefore a single
backup, at creation time, is sufficient to secure all the funds and smart contracts in the wallet.
• This design makes the security of the seed of utmost importance, as only the seed is needed to gain
access to the entire wallet.
• Hierarchical Deterministic Wallets (BIP-32/BIP-44)
• Deterministic wallets were developed to make it easy to derive many keys from a single seed.
• Currently, the most advanced form of deterministic wallet is the hierarchical deterministic (HD)
wallet defined by Bitcoin’s BIP-32 standard.
• HD acontain keys derived in a tree structure, such that a parent key can derive a sequence of child
keys, each of which can derive a sequence of grandchild keys, and so on

HD wallet: a tree of keys generated from a single seed


• HD wallets offer a few key advantages over simpler deterministic wallets.:
• A specific branch of subkeys is used to receive incoming payments and a different branch is used
to receive change from outgoing payments. Branches of keys can also be used in corporate
settings, allocating different branches to departments, subsidiaries, specific functions, or
accounting categories.
• The second advantage of HD wallets is that users can create a sequence of public keys without
having access to the corresponding private keys.
• This allows HD wallets to be used on an insecure server or in a watch-only or receive-only
capacity, where the wallet doesn’t have the private keys that can spend the funds.
Difference between non deterministic and deterministic wallet
• Wallet Best Practices
• As cryptocurrency wallet technology has matured, certain common industry standards
• have emerged that make wallets broadly interoperable, easy to use, secure, and
• flexible. These standards also allow wallets to derive keys for multiple different cryptocurrencies,
• all from a single mnemonic. These common standards are:
• • Mnemonic code words, based on BIP-39
• • HD wallets, based on BIP-32
• • Multipurpose HD wallet structure, based on BIP-43
• • Multicurrency and multiaccount wallets, based on BIP-44
Working with Meta Mask
• Wallets are basically software that allows users to connect to Ethereum
• A wallet is a lightweight node that connects toa a blockchain to conduct basic activities like
transferring and receiving bitcoin
• A browser extension wallet called Meta mask operates within your browser.
• It is convenient for testing and simple to use
• It can connect to various Ethereum nodes and run tests on different blockchains
• Metamask is a web based wallet
• MetaMask is a browser extension wallet that runs in your browser (Chrome, Firefox,
Opera, or Brave Browser).
• It is easy to use and convenient for testing, as it is able to connect to a variety of
Ethereum nodes and test blockchains.
• Meta-mask assignment 1
• ➔ Website:
• ◆ https://metamask.io/
• ➔ Setup instructions:
• ➔ Switching networks
• ➔ Visibility of testnets
• ➔ Adding Sepolia testnet
• ➔ Getting test ether from sepolia
• ➔ Sending ether from metamask
• ➔ Exploring etherscan for transactions
EOA and Contracts
• Accounts
• It is a crucial part of Ethereum system .and has an ether(ETH)balance
• A users account can transmit transactions through the Ethereum network.
• Transactions are produced by the interactions between several accounts and are kept in the distributed database.
• Sender, recipient and contract accounts are all involved in every transaction,
• An account can be managed by a user or a programme running on th ethereum network.

• ➔ Ethereum follows an account model similar to modern banking


• system.
• ◆ Ethereum has two types of accounts:
• ● Externally owned account
• ● Contract account.
• Externally Owned Accounts (EOAs)
• The type of account that is owned by people on the Ethereum network and created in the MetaMask wallet is called an
externally owned account (EOA).
• Externally owned accounts are those that have a private key; having the private key means control over access to funds or
contracts. The user maintains security of private key
• EOA do not contain code. It has balance in ether and can send messages by generating and signing a transaction.
• It is used for holding, sending and receiving ETH and for interacting with smart contracts like
• deployment and calling functions etc.
• Has an associated nonce (amount of transactions sent from the account)
and a balance.
• codeHash - Hash of associated account code, i.e. a computer program
for a smart contract (hash of an empty string for external accounts, EOAs)
• Storage Root is root hash of Merkle-Patricia trie of associated account data
• The identity of the account is represented by the public key generated from private key
• Public keys are used for account to account transactions and creates the account address
Contract Account
• Ethereum accounts can store and execute code
• A smart contracts code is contained in the Contract Account .
• The account doesn’t have a public or private key
• Public key@identification .Private keys not owned
• Functions to run and state variables are present in the code.
• Account is manged by smart contracts logic.
• When a transaction with a contarct account is started by a aexternally owned account, the
contracts code is run on EVM.
• When a contract account receives a message, it activates its code.

Campbell R. Harvey 2018 34


• Four fields :
• Nonce: By acting as a counter, the nonce makes sure that each transaction is only ever
finished once.
• Balance:The amount of ether the user presently holds.
• Code hash or contract code: is empty if account is EOA.If account is contract account, thi.s
field contains the code that will be executed when a message sent to the account This EVM
bytecode is unchangeable.
• Storage: initially empty, through transactions and contract codes, it can be filled and read
from.
EOA V/s Contract
• A contract account has smart contract code, which a simple EOA can’t have.
• Furthermore, a contract account does not have a private key. Instead, it is owned (and controlled)
by the logic of its smart contract code: the software program recorded on the Ethereum
blockchain at the contract account’s creation and executed by the EVM.
• Contracts have addresses, just like EOAs.
• Contracts can also send and receive ether, just like EOAs. However, when a transaction destination
is a contract address, it causes that contract to run in the EVM, using the transaction, and the
transaction’s data, as its input.
• In addition to ether, transactions can contain data indicating which specific function in the
contract to run and what parameters to pass to that function.
• In this way, transactions can call functions within contracts.in the MetaMask wallet is called an
externally owned account (EOA).
Transactions
• A request to modify the state of the blockchain
▪ Can run code (contracts) which change global state
o Contrasts only balance updates in BTC
• Signed by originating account
• Types:
▪ Send value from one account to another account
▪ Create smart contract
▪ Execute smart contract code
38
Transactions
• ➔ A transaction is a signed message originating from an EoA.
• ➔ Transaction contents:
• ◆ Nonce
• ◆ Gas price
• ◆ Gas limit
• ◆ Recipient
• ◆ Value
• ◆ Data
• ◆ v,r,s
Transaction
• Transactions are signed messages originated by an externally owned account, transmitted by the Ethereum
network, and recorded on the Ethereum blockchain.
• They are the only things that can trigger a change of state, or cause a contract to execute in the EVM.
• The Structure of a Transaction:
• A transaction is a serialized binary message that contains the following data:
• Nonce
• A sequence number, issued by the originating EOA, used to prevent message replay
• Gas price
• The price of gas (in wei) the originator is willing to pay
• Gas limit
• The maximum amount of gas the originator is willing to buy for this transaction
• .
• Recipient
• The destination Ethereum address
• Value
• The amount of ether to send to the destination
• Data
• The variable-length binary data payload
• v,r,s
• The three components of an ECDSA digital signature of the originating EOA
The Transaction Nonce

• Transaction nonce: A scalar value equal to the number of transactions sent from this address or, in the
case of accounts with associated code, the number of contract-creations made by this account.
• The nonce is an attribute of the originating address; that is, it only has meaning in the context of the
sending address. However, the nonce is not stored explicitly as part of an account’s state on the
blockchain. Instead, it is calculated dynamically, by counting the number of confirmed transactions that
have originated from an address.
• There are two scenarios where the existence of a transaction-counting nonce is important: the usability
feature of transactions being included in the order of creation, and the vital feature of transaction
duplication protection.
• In practical terms, the nonce is an up-to-date count of the number of confirmed (i.e., on-chain)
transactions that have originated from an account.
• The nonce is a zero-based counter, meaning the first transaction has nonce 0.
• Examples: two scenarios where the existence of a transaction-counting nonce is important: the usability
feature of transactions being included in the order of creation, and the vital feature of transaction duplication
protection
• Scenario 1: Imagine you wish to make two transactions. You have an important payment to make of 6 ether,
and also another payment of 8 ether. You sign and broadcast the 6-ether transaction first, because it is the
more important one, and then you sign and broadcast the second, 8-ether transaction.
• Sadly, your account contains only 10 ether, so the network can’t accept both transactions: one of them will fail.
Because you sent the more important 6-ether one first, you understandably expect that one to go through and
the 8-ether one to be rejected.
• However, in a decentralized system like Ethereum, nodes may receive the transactions in either order; there is
no guarantee that a particular node will have one transaction propagated to it before the other. As such, it will
• almost certainly be the case that some nodes receive the 6-ether transaction first and others receive the 8-
ether transaction first. Without the nonce, it would be random as to which one gets accepted and which
rejected.
• However, with the nonce included, the first transaction you sent will have a nonce of, let’s say, 3,
• while the 8-ether transaction has the next nonce value (i.e., 4). So, that transaction will be ignored
until the transactions with nonces from 0 to 3 have been processed, even if it is received first.
• Now imagine you have an account with 100 ether. You find someone online who will
accept payment in ether for a iphone that you really want to buy. You send them 20
ether and they send you iphone .
• To make that 20-ether payment, you signed a transaction sending 20 ether from your
account to their account, and then broadcast it to the Ethereum network to be verified
and included on the blockchain. Now, without a nonce value in the transaction, a second
transaction sending 20 ether to the same address a second time will look exactly the
same as the first transaction. This means that anyone who sees your transaction on the
Ethereum network (which means everyone, including the recipient or your enemies) can
“replay” the transaction again and again and again until all your ether is gone simply by
copying and pasting your original transaction and resending it to the network.
• However, with the nonce value included in the transaction data, every single transaction
is unique, even when sending the same amount of ether to the same recipient address
multiple times. Thus, by having the incrementing nonce as part of the transaction, it is
simply not possible for anyone to “duplicate” a payment you have made.
Transaction Gas
• Gas is the fuel of Ethereum. Gas is not ether—it’s a separate virtual currency with its own
exchange rate against ether. Ethereum uses gas to control the amount of resources that a
transaction can use, since it will be processed on thousands of computers around the world.
• Gas is separate from ether in order to protect the system from the volatility that might arise along
with rapid changes in the value of ether, and also as a way to manage the important and sensitive
ratios between the costs of the various resources that gas pays for (namely, computation,
memory, and storage).
• The gasPrice field in a transaction allows the transaction originator to set the pricethey are willing
to pay in exchange for gas. The price is measured in wei per gas unit.
• Wallets can adjust the gasPrice in transactions they originate to achieve faster confirmationof
transactions. The higher the gasPrice, the faster the transaction is likely to be confirmed.
• Conversely, lower-priority transactions can carry a reduced price,resulting in slower confirmation.
The minimum value that gasPrice can be set to is zero, which means a fee-free transaction.
• The web3 interface offers a gasPrice suggestion, by calculating a median price across several blocks (we
can use the truffle console or any JavaScript web3 console to do that):
• > web3.eth.getGasPrice(console.log)
• GasLimit gives the maximum number of units of gas the transaction originator is willing to buy in order to
complete the transaction.
• For simple payments, meaning transactions that transfer ether from one EOA to another EOA, the gas
amount needed is fixed at 21,000 gas units.
• To calculate how much ether that will cost, you multiply 21,000 by the gasPrice you’re willing to pay.
• For example:
• > web3.eth.getGasPrice(function(err, res) {console.log(res*21000)} )
• > 210000000000000
Ether Denominations
• Wei - lowest denomination
▪ Named after Wei Dai - author of b-money paper (1998), many core
concepts used in BTC implementation
▪ 1/1,000,000,000,000,000,000 (quintillion)
• Szabo - next denomination
• Named after Nick Szabo -
author of Bit-Gold
• Finney – 2nd highest denomination
• Named after Hal Finney -
received first Tx from Nakamoto
Campbell R. Harvey 2018 48

http://www.weidai.com/bmoney
• Gas and Gas Price
• ➔ Gas
• ◆ Gas is a fuel of Ethereum.
• ◆ Every opcode in EVM instruction set has predetermined cost in the units of gas
• ◆ For example: Add opcode consumes 3 gas
• ◆ All opcodes gas costs
• ◆
• ➔ Gas Price
• ◆ Gas can be purchased using Ethers.
• ◆ However, the price of the gas is not fixed.
• ◆ Before, EIP 1559, there is no limitation on gas price. The higher the gas price you
• pay, the faster your transaction is confirmed on the Blockchain.
• ➔ Transaction cost = gas consumed * gas price. However, the initial
• transaction cost = gas limit * gas price.
• ➔ (gas limit - gas consumed) * gas price is refunded.
• ➔ The miner/validator receives all the transaction cost for the transaction.
Transaction Recipient
• The recipient of a transaction is specified in the to field. This contains a 20-byte Ethereum
address. The address can be an EOA or a contract address.
• Ethereum does no further validation of this field. Any 20-byte value is considered valid. If the 20-
byte value corresponds to an address without a corresponding private key, or without a
corresponding contract, the transaction is still valid. Ethereum has no way of knowing whether an
address was correctly derived from a public key in existence.
• Sending a transaction to the wrong address will probably burn the ether sent, rendering it forever
inaccessible (unspendable), since most addresses do not have a known private key and therefore
no signature can be generated to spend it.
Transaction Value and Data

• The main “payload” of a transaction is contained in two fields: value and data.
• Transactions can have both value and data, only value, only data, or neither value nor
• data. All four combinations are valid.
• A transaction with only value is a payment. A transaction with only data is an invocation.
• A transaction with both value and data is both a payment and an invocation.
• A transaction with neither value nor data—well that’s probably just a waste of gas! But it
is still possible.
• First we’ll set the source and destination addresses from our wallet, just to make the demo easier
to read:
• src = web3.eth.accounts[0];
• dst = web3.eth.accounts[1];
• Our first transaction contains only a value (payment), and no data payload:
• web3.eth.sendTransaction({from: src, to: dst, \
• value: web3.toWei(0.01, "ether"), data: ""});
• Our wallet shows a confirmation screen indicating the value to send, as shown in

Parity wallet showing a transaction with value, but no data


• The next example specifies both a value and a data payload:
• web3.eth.sendTransaction({from: src, to: dst, \
• value: web3.toWei(0.01, "ether"), data: "0x1234"});
• Our wallet shows a confirmation screen indicating the value to send as well as the data payload,
as shown in Figure

Parity wallet showing a transaction with value and data


• The next transaction includes a data payload but specifies a value of zero:
• web3.eth.sendTransaction({from: src, to: dst, value: 0, data: "0x1234"});
• Our wallet shows a confirmation screen indicating the zero value and the data payload, as shown
in Figure

Parity wallet showing a transaction with no value, only data


• Finally, the last transaction includes neither a value to send nor a data payload:
• web3.eth.sendTransaction({from: src, to: dst, value: 0, data: ""}));
• Our wallet shows a confirmation screen indicating zero value, as shown in Figure

Parity wallet showing a transaction with no value, and no data


Transmitting Value to EOAs and Contracts
• When you construct an Ethereum transaction that contains a value, it is the equivalent of a payment. Such transactions behave
differently depending on whether the destination address is a contract or not.
• For EOA addresses, or rather for any address that isn’t flagged as a contract on the blockchain, Ethereum will record a state
change, adding the value you sent to the balance of the address. If the address has not been seen before, it will be added to the
client’s internal representation of the state and its balance initialized to the value of your payment.
• If the destination address (to) is a contract, then the EVM will execute the contract and will attempt to call the function named in
the data payload of your transaction. If there is no data in your transaction, the EVM will call a fallback function and, if that
• function is payable, will execute it to determine what to do next. If there is no fallback function, then the effect of the transaction
will be to increase the balance of the contract, exactly like a payment to a wallet.
• A contract can reject incoming payments by throwing an exception immediately when a function is called, or as determined by
conditions coded in a function. If the function terminates successfully (without an exception), then the contract’s state is
• updated to reflect an increase in the contract’s ether balance.
Transmitting a Data Payload to an EOA or Contract
• When your transaction contains data, it is most likely addressed to a contract address.
• That doesn’t mean you cannot send a data payload to an EOA—that is completely valid in the
Ethereum protocol.
• However, in that case, the interpretation of the data is up to the wallet you use to access the EOA.
It is ignored by the Ethereum protocol.
• Most wallets also ignore any data received in a transaction to an EOA they control.
• In the future, it is possible that standards may emerge that allow wallets to interpret data the way
contracts do, thereby allowing transactions to invoke functions running inside user wallets.

How Digital Signatures Work

• A digital signature is a mathematical scheme that consists of two parts. The first
part is an algorithm for creating a signature, using a private key (the signing key),
from a message (which in our case is the transaction). The second part is an
algorithm that allows anyone to verify the signature by only using the message
and a public key.
• Creating a digital signature
• In Ethereum’s implementation of ECDSA, the “message” being signed is the transaction,
• or more accurately, the Keccak-256 hash of RLP-encoded data from the transaction.
• The signing key is the EOA’s private key. The result is the signature:
• Sig = Fsig Fkeccak256 m , k
• where:
• k is the signing private key.
• m is the RLP-encoded transaction.
• Fkeccak256 is the Keccak-256 hash function.
• Fsig is the signing algorithm.
• Sig is the resulting signature.
• The function Fsig produces a signature Sig that is composed of two values, commonly referred to as r and s:
• Sig = r, s
• Verifying the Signature
• To verify the signature, one must have the signature (r and s), the serialized transaction, and the
public key that corresponds to the private key used to create the signature.
• Essentially, verification of a signature means “only the owner of the private key that generated this
public key could have produced this signature on this transaction.”
• The signature verification algorithm takes the message (i.e., a hash of the transaction for our usage),
the signer’s public key, and the signature (r and s values), and returnstrue if the signature is valid for
this message and public key.
Smart contracts
• There are two different types of accounts in Ethereum:externally owned accounts (EOAs) and
contract accounts.
• EOAs are controlled by users, often via software such as a wallet application that is external to the
Ethereum platform.
• In contrast, contract accounts are controlled by program code (also commonly referred to as “smart
contracts”) that is executed by the Ethereum Virtual Machine.
• In “Smart contracts” refer to immutable computer programs that run deterministically in the context
of an Ethereum Virtual Machine as part of the Ethereum
• Computer programs
• Smart contracts are simply computer programs. The word “contract” has no legal meaning in this
context.
• Immutable
• Once deployed, the code of a smart contract cannot change. Unlike with traditional software, the
only way to modify a smart contract is to deploy a new instance.
• Deterministic
• The outcome of the execution of a smart contract is the same for everyone who runs it, given the
context of the transaction that initiated its execution and the state of the Ethereum blockchain at the
moment of execution.
• EVM context
• Smart contracts operate with a very limited execution context. They can access their own state, the
context of the transaction that called them, and some information about the most recent blocks.
• Decentralized world computer
• The EVM runs as a local instance on every Ethereum node, but because all instances of the EVM operate
on the same initial state and produce the same final state, the system as a whole operates as a single
“world computer
Life Cycle of a Smart Contract
• Smart contracts are typically written in a high-level language, such as Solidity.
• But in order to run, they must be compiled to the low-level bytecode that runs in the EVM.
• Once compiled, they are deployed on the Ethereum platform using a special contract creation transaction,
which is identified as such by being sent to the special contract creation address, namely 0x0
• Each contract is identified by an Ethereum address, which is derived from the contract creation transaction
as a function of the originating account and nonce.
• The Ethereum address of a contract can be used in a transaction as the recipient, sending funds to the
contract or calling one of the contract’s functions
• A contract can call another contract that can call another contract, and so on, but the first contract in such a
chain of execution will always have been called by a transaction from an EOA.
• Contracts never run “on their own” or “in the background.”
• Contracts effectively lie dormant until a transaction triggers execution, either directly or indirectly as part of
a chain of contract calls
Building a Smart Contract with Solidity
• Solidity was created by Dr. Gavin Wood as a language explicitly for writing smart contracts with
features to directly support execution in the decentralized environment of the Ethereum world
computer.
• The resulting attributes are quite general, and so it has ended up being used for coding smart
contracts on several other blockchain platforms.
• It was developed by Christian Reitiwessner and then also by Alex Beregszaszi, Liana Husikyan, Yoichi
Hirai, and several former Ethereum core contributors.
• Solidity is now developed and maintained as an independent project on GitHub.
• The main “product” of the Solidity project is the Solidity compiler, solc, which converts programs
written in the Solidity language to EVM bytecode.
Setting up a development environment

• The first task is to set up a development environment.


• The ethereum setup for Test Net and Private Net:
• Test Net is called Ropsten and is used by developers or users as a test platform to test smart contracts
and other blockchain-related proposals.
• The Private Net option in Ethereum allows the creation of an independent private network that can be
used as a distributed ledger between participating entities and for the development and testing of smart
contracts.
• Test Net (Ropsten)
• The Ethereum Go client, geth, can be connected to the test network using the following command:
• $ geth --TestNet
• The output shows the type of the network chosen and various other pieces of information regarding
the blockchain download.
• A blockchain explorer for test net is located at
• https://testnet.etherscan.io/ and can be used to trace transactions and blocks on the Ethereum test
network.

Output of the geth command connecting to Ethereum test net


• Setting up a Private Net
• Private Net allows the creation of an entirely new blockchain. This is different from Test Net or Main Net in the
sense that it uses its on-genesis block and Network ID. In order to create Private Net, three components are
needed:
• 1. Network ID.
.
• 2. Genesis file.
• 3. Data directory to store blockchain data. Even though data directory is not strictly required to be mentioned, if
there is more than one blockchain already active on the system, then data directory should be specified so that a
separate directory is used for the new blockchain.
• Private Net allows the creation of an entirely new blockchain. This is different from Test Net or Main Net in the
sense that it uses its own unique genesis block and Network ID.
• On Main Net, geth knows about peers by default and connects automatically, but on Private Net, geth needs to be
configured by specifying appropriate flags and configuration in order for it to be able to be discoverable by other
peers or to discover other peers.
• Disable node discovery so that other nodes on the Internet cannot discover your private network and is truly
private.
• If other networks happen to have the same genesis file and Network ID, they may connect to your Private Net.

TRUFFLE
Truffle is a development environment that makes it easier and simpler to test and deploy Ethereum contracts.
• Truffle provides contract compilation and linking along with an automated testing framework using Mocha and
Chai.
• It also makes it easier to deploy the contracts to any PrivateNet, public, or Test Net Ethereum blockchain. Also,
asset pipeline is provided, which makes it easier for all JavaScript files to be processed, making them ready for
use by a browser.
• Installation
• Before installation, it is assumed that the node is available.If the node is not available, then the installation of
the node is required first in order to install truffle:
• drequinox@drequinox-OP7010:~/testdapp$
• nodejs --version
• v7.2.1
• The installation of truffle is very simple and can be done using the
following command via npm:
• $ sudo npm install -g truffle
• Once it is installed, truffle can be used to display help and make sure that
it is installed correctly.

Truffle help
Assignment 1 continuation
• 2)a) Use cases of Smart Contract
• B) Smart Contracts: Opportunities and Risk.
• 3) Smart Contract Deployment:
• 3a) Use of Remix and test networks for deployment

You might also like