0% found this document useful (0 votes)
19 views29 pages

Module 5

The Ethereum network is a peer-to-peer blockchain system that includes three types of networks: the mainnet for live transactions, testnets for testing smart contracts, and private networks for consortium use. Key components of the Ethereum ecosystem include the Ethereum client, web3.js library, keys and addresses, accounts, transactions, and the Ethereum Virtual Machine (EVM). Ether (ETH) serves as the native cryptocurrency for transaction fees, and the EVM executes smart contracts in a secure, isolated environment.

Uploaded by

g3273650
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)
19 views29 pages

Module 5

The Ethereum network is a peer-to-peer blockchain system that includes three types of networks: the mainnet for live transactions, testnets for testing smart contracts, and private networks for consortium use. Key components of the Ethereum ecosystem include the Ethereum client, web3.js library, keys and addresses, accounts, transactions, and the Ethereum Virtual Machine (EVM). Ether (ETH) serves as the native cryptocurrency for transaction fees, and the EVM executes smart contracts in a secure, isolated environment.

Uploaded by

g3273650
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

The Ethereum network : (important-3 marks)

The Ethereum network is a peer-to-peer network where nodes participate in order to maintain
the blockchain and contribute to the consensus mechanism.

Networks can be divided into three types, based on the requirements and
usage((important-3 marks)

1. The mainnet

• The mainnet is the current live network of Ethereum.

• Its network ID is 1 and its chain ID is also 1.

• The network and chain IDs are used to identify the network.

• A block explorer that shows detailed information about blocks and other
relevant metrics, This can be used to explore the Ethereum blockchain.

2. Testnets

• There is a number of testnets available for Ethereum testing.

• The aim of these test blockchains is to provide a testing environment for smart
contracts and DApps before being deployed to the production live blockchain.

• Moreover, being test networks, they also allow experimentation and research.

• The main testnet is called Ropsten, which contains all the features of other
smaller and special-purpose testnets that were created for specific releases.

• For example, other testnets include Kovan and Rinkeby, which were
developed for testing Byzantium releases.

• The changes that were implemented on these smaller testnets have also been
implemented in Ropsten. Now the Ropsten test network contains all properties
of Kovan and Rinkeby.

[Link] nets

• As the name suggests, these are private networks that can be created by generating a
new genesis block.
• This is usually the case in private blockchain networks, where a private group of entities
start their blockchain network and use it as a permissioned or consortium blockchain.

Components of the Ethereum ecosystem (8 or 9 marks)


• The Ethereum blockchain stack consists of various components.
• At the core, there is the Ethereum blockchain running on the peer-to-peer Ethereum
network.
• Secondly, there's an Ethereum client (usually Geth) that runs on the nodes and connects
to the peer-to-peer Ethereum network from where the blockchain is downloaded and
stored locally.
• It provides various functions, such as mining and account management.
• The local copy of the blockchain is synchronized regularly with the network.
• Another component is the [Link] library that allows interaction with the Geth client
via the Remote Procedure Call (RPC) interface.

The main elements of the Ethereum blockchain include:


• Keys and addresses
• Accounts
• Transactions and messages
• Ether cryptocurrency / tokens
• Ethereum Virtual Machine (EVM)
• Smart contracts and native contracts
1. Keys and Addresses:
• Keys and addresses are used in the Ethereum blockchain to represent ownership
and transfer ether.
• The keys used are made up of pairs of private and public parts.
• The private key is generated randomly and is kept secret, whereas a public key is
derived from the private key.
• Addresses are derived from public keys and are 20-byte codes used to identify
accounts.
• The process of key generation and address derivation is as follows:
• First, a private key is randomly chosen (a 256-bit positive integer) under the rules
defined by the elliptic curve secp256k1 specification (in the range [1, secp256k1n
− 1]).
• The public key is then derived from this private key using the Elliptic Curve Digital
Signature Algorithm (ECDSA) recovery function.
• An address is derived from the public key, specifically, from the rightmost 160 bits
of the Keccak hash of the public key.


2. Accounts :
• Another key element in Ethereum is an account, which is required in order to
interact with the blockchain. It either represents a user or a smart contract.
• Accounts are one of the main building blocks of the Ethereum blockchain. They are
defined by pairs of private and public keys.
• Accounts are used by users to interact with the blockchain via transactions. A
transaction is digitally signed by an account before submitting it to the network via
a node.
• Ethereum, being a transaction-driven state machine, updates its state as a result of
interactions between accounts and transaction executions.
• All accounts have a state that, when combined together, represents the state of the
Ethereum network.
• With every new block, the network state is updated. Operations performed between
and on accounts represent state transitions.
• The state transition is achieved using the Ethereum state transition function, which
works as follows:
1. Confirm the transaction validity by checking:
• Syntax
• Signature validity
• Nonce
2. Calculate the transaction fee and resolve the sender’s address using
the signature.
• Check the sender’s account balance and deduct the required
amount.
• Increment the nonce.
• Return an error if the balance is insufficient.
3. Provide enough ETH (gas) to cover the transaction cost.
• Gas is charged per byte and is proportional to transaction size.
• The transfer of value occurs from the sender’s account to the
receiver’s account.
• If the destination account does not exist, it is created
automatically.
• If the destination is a smart contract, its code is executed.
• Execution depends on available gas:
• If enough gas is available, execution completes fully.
• If not, execution stops when gas runs out
4. In cases of transaction failure due to insufficient account balance or
gas, all state changes are rolled back except for the fee payment,
which is paid to the miners.
5. Finally, the remainder (if any) of the fee is sent back to the sender as
change and the fee is paid to the miners accordingly. At this point,
the function returns the resulting state, which is also stored on the
blockchain.

Types of Accounts:
• Two kinds of accounts exist in Ethereum:

• Externally Owned Accounts (EOAs)

• Contract Accounts (CAs)

• The first type is EOAs, and the other is CAs.


EOAs are similar to accounts that are controlled by a private key in Bitcoin.
CAs are accounts that have code associated with them along with the private key.

Properties of EOAs
• They have a state.
• They are associated with a human user; hence they are also called user accounts.
• EOAs have an ether balance.
• They are capable of sending transactions.
• They have no associated code.
• They are controlled by private keys.
• EOAs cannot initiate a call message.
• Accounts contain a key-value store.
• EOAs can initiate transaction messages.
3. Transactions and Messages :
• A transaction in Ethereum is a digitally signed data packet using a private key that
contains instructions that.
• when completed, either result in a message call or contract creation.
• Transactions can be divided into two types based on the output they produce:
• Types of Transactions
a. Message call transactions:
This transaction simply produces a message call that is used to pass messages
from one CA (Contract Account) to another.
b. Contract creation transactions:
As the name suggests, these transactions result in the creation of a new CA.
This means that when this transaction is executed successfully, it creates an
account with the associated code

• A transaction is represented as a tuple of standard fields.


• Transactions are stored in a transaction trie.
• The transaction trie is a modified Merkle-Patricia Tree (MPT).
• The root of the transaction trie is hashed using the Keccak-256 algorithm.
• The resulting hash is stored in the block header.
• The block header also contains the list of transactions in the block.

• Block is a data structure that stores a batch of transactions.


• Transactions exist in two places:
• Transaction pool – waiting for verification.
• Blocks – added after successful verification.
• A mining node begins verification by selecting highest-paying transactions from
the transaction pool.
• Transactions are processed one by one.
• Mining starts when:
• The gas limit is reached, or
• No more transactions remain in the transaction pool.

• During mining, the block is repeatedly hashed until a valid nonce is found.
• The resulting hash must be less than the difficulty target.
• After a block is successfully mined:
• It is broadcast to the network.
• Other nodes verify and accept the block.
• Ethereum’s mining process is similar to Bitcoin mining.
• Ethereum uses a Proof-of-Work (PoW) algorithm called Ethash.
• Ethash was designed to be ASIC-resistant by requiring large memory to find the
nonce.
• However, ASIC hardware for Ethash now exists.
• To improve resistance to ASICs, Ethereum developers proposed ProgPow, a more
ASIC-resistant PoW consensus mechanism.
Types of transaction
1. Contract Creation Transactions (Smart Contracts in Blockchain)
A contract creation transaction is used to create smart contracts on the
blockchain. It requires several essential parameters.
• Sender – The account that sends the transaction.
• Transaction originator – The original account that initiated the transaction.
• Available gas – Maximum gas allowed for executing the transaction.
• Gas price – Amount of ether paid per unit of gas.
• Endowment – Amount of ether allocated to the new contract.
• Byte array of arbitrary length – Input data used in contract creation.
• Initialization EVM code – Code executed to initialize the contract.
• Current depth of message call/contract-creation stack – Number of items
already present in the execution stack.
• Contract Address Generation
• The contract address is 160 bits long.
• It is derived from the rightmost 160 bits of the Keccak hash.
• The hash is calculated from the RLP encoding of the sender and
nonce.
• Initial Account State
• Nonce of the account is initially 0.
• Account balance is set to the value sent to the contract.
• Storage is initially empty.
• Code hash is the Keccak-256 hash of an empty string.
• Contract Initialization
• The new account is created when the initialization EVM code
executes successfully.
• If an exception occurs (e.g., Out of Gas – OOG), no state changes
occur.
• If execution is successful, the contract account is created after
paying the required gas cost.
• Key Idea: Contract creation transactions deploy smart contracts on the
blockchain, generate a unique contract address, and initialize the contract
state through EVM code execution.

[Link] Call Transactions

• A message call transaction is used to send messages between accounts and


execute code in Ethereum. It requires several parameters for execution.
• Sender – The account that sends the message call.
• Transaction originator – The account that originally initiated the transaction.
• Recipient – The account that receives the message.
• Account whose code is executed – Usually the same as the recipient account.
• Available gas – Maximum gas allowed for executing the operation.
• Value – Amount of ether transferred with the message.
• Gas price – Cost paid per unit of gas.
• Arbitrary-length byte array – Data sent with the message.
• Input data of the call – Data provided as input for the contract execution.
• Current depth of the message call/contract creation stack – Number of
calls already present in the stack.
• Message calls cause a state transition in the Ethereum blockchain.
• They can also produce output data.
• If message calls are triggered by EVM code, the output is used by the
transaction execution.
• According to the Ethereum Yellow Paper, a message call is the process of
passing a message from one account to another.
• If the destination account contains EVM code, the Ethereum Virtual
Machine (EVM) executes the code when the message is received.
• If the sender is an external actor (user), the call returns any data produced
by the EVM execution.
• Transactions change the blockchain state and are:
• Created by external users
• Signed digitally
• Broadcast to the Ethereum network
• Message calls enable communication between accounts and allow smart
contract functions to be executed.

4. Messages
• Messages are the data and values passed between two accounts in the Ethereum
network.
• A message is a data packet sent between two accounts, which contains: Data and
Value (amount of ether).
• Messages can be sent in two ways:
o Through a smart contract (autonomous object)
o From an Externally Owned Account (EOA) using a digitally signed
transaction
• Contracts can send messages to other contracts.
• Messages exist only during execution and are not permanently stored on the
blockchain.
• Messages are similar to transactions, but there is a key difference:
o Messages are generated by smart contracts.
o Transactions are generated by external users (EOAs).
A message consists of the following components:

• Sender of the message – Account that sends the message.


• Recipient of the message – Account that receives the message.

• Amount of Wei – Ether value transferred to the contract address.

• Optional data field – Input data sent to the contract.

• Maximum gas (startgas) – Maximum gas that can be consumed during execution.

• Transaction receipts store the state after a transaction has been executed. They record
the outcome of transaction execution.’
[Link]-transaction state

• Stores the state of the system after transaction execution.

• Implemented as a trie structure.

• Encoded as a byte array.

2. Gas used

• Represents the total gas consumed in the block containing the


transaction receipt.

• Calculated immediately after transaction execution.

• Value is a non-negative integer

[Link] of logs

• Contains log entries generated during transaction execution.


• Each log entry includes:

• Logger’s address

• Log topics

• Log data

[Link] filter

• Created from information in the log entries.

• Used for efficient searching of logs.

• Each log entry is converted into a 256-byte hash.


• Stored in the block header as logs bloom.

• Log topics are encoded as 32-byte data structures.

• Log data contains a few bytes of information.

5. Ether (ETH) cryptocurrency:


• Ether (ETH) is a cryptocurrency
• Ether (ETH) is the native cryptocurrency of the Ethereum network.
• It is used to pay transaction fees (gas) and execute smart contracts on the Ethereum
blockchain.
• Ether is created and managed by the Ethereum protocol itself, not by a smart contract.

6. The Ethereum Virtual Machine (EVM) :


• The Ethereum Virtual Machine is a stack-based execution machine that runs
bytecode instructions to transform the system state from one state to another on the
Ethereum network.
• The word size of EVM is 256 bits.
• The stack size is limited to 1,024 elements.
• It follows the Last In, First Out (LIFO) principle.
• The EVM is Turing complete, meaning it can execute complex computations.
• Execution is limited by gas, preventing infinite loops and denial-of-service attacks.
• If exceptions occur (e.g., insufficient gas or invalid instruction), the EVM halts
execution and returns an error.
• Security and Environment
• The EVM operates in an isolated and sandboxed runtime environment.
• It cannot access external resources such as networks or file systems.
• This ensures:
• Higher security
• Deterministic execution
• Ability to run untrusted code (smart contracts) safely on Ethereum.

Architecture Features

• The EVM is a stack-based architecture.


• It uses 256-bit wide words and big-endian design.
• The 256-bit word size supports:
• Keccak-256 hashing
• Elliptic Curve Cryptography (ECC) computations.

Storage Types in EVM

• There are three main types of storage available for smart contracts and the EVM.
1. Memory

• Temporary (volatile) memory used during contract execution.


• Implemented as a word-addressed byte array.
• Cleared after execution of a contract.
• Similar to RAM in computers.
• Write operations can be 8 bits or 256 bits, while read operations are 256-bit
words.
• Memory is unlimited but limited by gas fees.
2. Storage

• Permanent key-value storage on the blockchain.


• Keys and values are 256 bits wide.
• Allocated to accounts on the Ethereum blockchain.
• Only accessible by its own contract account (CA) for security.
• Similar to hard disk storage.
3. Stack

• The EVM performs computations using a stack data structure.


• All temporary computation values are stored in the stack.
• Maximum depth: 1024 elements.
• Word size: 256 bits.
• EVM storage is a word-addressable non-volatile array maintained as part of
the system state.
• Keys and values are 32 bytes (256 bits) in storage.
• Program code is stored in virtual read-only memory (virtual ROM).
• The CODECOPY instruction copies program code from virtual ROM to main
memory.
• Initially, all storage and memory values are set to zero in the EVM.
• Execution Process
• The EVM executes instructions step-by-step.
• The program counter tracks the current instruction.
• The EVM stack and program counter are updated after each instruction
execution

Blocks and blockchain:
• main building structure of a blockchain
• Ethereum blocks consist of
• The block header
• The transactions list
• The list of headers of ommers or uncles
An uncle block is a block that is the child of a parent but does not have
any child block. Ommers or uncles are valid, but stale, blocks that are
not part of the main chain but contribute to security of the chain. They
also earn a reward for their participation but do not become part of the
canonical truth.

Block finalization :
● Block finalization is a process that is run by miners to validate
the contents of the block and apply rewards
● 4 steps
○ Ommers validation - checks whether the header is valid
and whether the relationship between the uncle and the
current block satisfies the maximum depth of six blocks
and a block can contain a maximum of two uncles
○ Transaction validation - checking whether the total gas
used in the block is equal to the final gas consumption
after the final transaction
○ Reward application - updating the beneficiary's account
with a reward balance. Current block reward is 2 ether
○ State and nonce validation - compute a valid state and
block nonce
Block difficulty mechanism :
● Block difficulty is increased if the time between two blocks
decreases, whereas it increases if the block time between two
blocks decreases
● This is required to maintain a roughly consistent block generation
time
● The difficulty adjustment algorithm in Ethereum's Homestead
release is as follows
● if the time difference between the generation of the parent
block and the current block is less than 10 seconds, the
difficulty goes up by parent_diff // 2048 * 1
● If the time difference is between 10 and 19 seconds, the
difficulty level remains the same
● Finally, if the time difference is 20 seconds or more, the
difficulty level decreases
● This decrease is proportional to the time difference from
parent_diff // 2048* -1 to a maximum decrease of parent_diff
// 2048 * -99
Gas :
● Gas is required to be paid for every operation performed on the Ethereum blockchain
● mechanism that ensures that infinite loops cannot cause the whole blockchain to stall
due to the Turing-complete nature of the EVM
● transaction fee is charged as an amount of Ether and is taken from the account balance
of the transaction originator
● A fee is paid for transactions to be included by miners for mining
● If this fee is too low, the transaction may never be picked up
● the more the fee, the higher are the chances that the transactions will be picked up by
the miners for inclusion in the block
● if the transaction that has an appropriate fee paid is included in the block by miners but
has too many complex operations to perform, it can result in an out-of-gas exception if
the gas cost is not enough
● the transaction will fail but will still be made part of the block, and the transaction
originator will not get any refund
● Transaction costs can be estimated using the following formula:
Total cost = gasUsed * gasPrice
● gasUsed is the total gas that is supposed to be used by the transaction during the
execution, and gasPrice is specified by the transaction originator as an incentive to the
miners to include the transaction in the next block
● This is specified in ETH
● Each EVM opcode has a fee assigned to it
● It is an estimate because the gas used can be more or less than the value specified by
the transaction originator originally

Solidity :
● statically-typed (type checking at compile time) curly-braces object-oriented
programming language designed for developing smart contracts that run on
Ethereum
● domain-specific language of choice for programming contracts in Ethereum
● syntax is closer to both JavaScript and C
● also called a contract-oriented language
The layout of a Solidity source code file:
● contracts are equivalent to the concept of classes
● three types of variables in Solidity: local variables, global variables, and state
variables
● State variables have their values permanently stored in smart contract storage
● State variables are declared outside the body of a function, and they remain available
throughout the contract depending on the accessibility assigned to them and as long
as the contract persists

● Solidity has two categories of data types: value types and reference types
● Reference types store the address of the memory location where the value is stored
● Value types mainly include Booleans, integers, addresses, and literals
Data Types :
• Boolean - true or false


• Address -holds a 160-bit long (20 byte) value
o has several members that can be used to interact with and query the contracts
o Balance: returns the balance of the address in Wei
o Send: used to send an amount of ether to an address and returns true or false
depending on the result of the transaction
o Call functions: call , callcode , and delegatecall functions
o to interact with functions that do not have an ABI (Application Binary Interface)
o Array value types (fixed-size and dynamically sized byte arrays): Fixed-size
keywords range from bytes1 to bytes32 , whereas dynamically sized keywords
include bytes and string
o The bytes keyword is used for raw byte data, and string is used for strings
encoded in UTF-8


• Literals - to represent a fixed value

Reference types:
● include arrays, structs, and mappings
● Arrays - contiguous set of elements of the same size and type
● Arrays have two members, named length and push
● Structs - used to group a set of dissimilar data types under a logical group
Mappings - used for a key-to-value mapping

Control structures :
Events :
● used to log certain events in EVM logs
● useful when external interfaces are required to be notified of any change or event in
the contract
● These logs are stored on the blockchain in transaction logs
● Logs cannot be accessed from the contracts but are used as a mechanism to notify
change of state or the occurrence of an event (meeting a condition) in the contract
Inheritance:
● is keyword is used to derive a contract from another contract
● derived contract has access to all non-private members of the parent contract

Libraries:

● deployed only once at a specific address and their code is called via the CALLCODE
or DELEGATECALL opcode of the EVM
● code reusability

● similar to contracts and act as base contracts to the calling contracts


Function:
● Two types

○ Internal functions - used only within the context of the current contract

○ External functions - called via external function calls

● A function in Solidity can be marked as a constant


● Constant functions cannot change anything in the contract; they only return values
when they are invoked and do not cost any gas

● Functions in Solidity are identified by their signature - first four bytes of the Keccak-
256 hash of its full signature string


Functions within the context of the current contract can be called internally in a direct
manner known as internal function call

● These calls result in simple JUMP calls at the EVM bytecode level

● External function calls are made via message calls from a contract to another contract

● In this case, all function parameters are copied to the memory. If a call to an internal
function is made using the this keyword, it is also considered an external call

● Fallback functions: unnamed function in a contract with no arguments and return data

● executes every time ether is received

● required to be implemented within a contract if the contract is intended to


receive ether

● otherwise, an exception will be thrown and ether will be returned

● also executes if no other function signatures match in the contract

● If the contract is expected to receive ether, then the fallback function should be declared
with the payable modifier
● can be called using the [Link]() method
● Modifier functions: to change the behavior of a function and can be called before other
functions
● used to check some conditions or verification before executing the function

● _ (underscore) is used in the modifier function

● replaced with the actual body of the function when the modifier is called

● similar to guard functions in other languages


● Constructor function: optional function that has the same name as the contract

● executed once a contract is created

● cannot be called later on by users

● only one constructor allowed in a contract

Function Visibility Specifiers

● External: accessible from other contracts and transactions They cannot be called
internally unless the this keyword is used

● Public: By default, functions are public and can be called either internally or by using
messages

● Internal: visible to other derived contracts from the parent contract

● Private: only visible to the same contract they are declared in

Function modifiers
● pure: prohibits access or modification to state

● view: disables any modification to state

● payable: allows payment of ether with a call

● constant: disallows access or modification to state

● This is available before version 0.5.0 of Solidity

Error handling

● By default, in Solidity, whenever an error occurs, the state does not change and reverts
back to the original state

● Assert: to check for conditions and throw an exception if the condition is not met

○ intended to be used for internal errors and invariant checking


○ When called, this method results in an invalid opcode and any changes in the
state are reverted back

● Require: used for checking conditions and throws an exception if the condition is not
met
○ require is used for validating inputs, return values, or calls to external contracts
○ also results in reverting back to the original state

○ It can also take an optional parameter to provide a custom error message

● Revert: aborts the execution and reverts the current call

○ optionally take a parameter to return a custom error message to the caller


● Try/Catch: to handle a failure in an external call.

● Throw: to stop execution

○ As a result, all state changes are reverted

○ In this case, no gas is returned to the transaction originator because all the
remaining gas is consumed

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

// Define the contract


contract Voting {

// Store the address of the admin


(contract deployer)
address public admin;

// Structure to represent a Candidate


struct Candidate {
uint id; // Unique ID of
candidate
string name; // Name of candidate
uint voteCount; // Total votes
received
}

// Mapping to store candidates (id =>


Candidate)
mapping(uint => Candidate) public
candidates;

// Mapping to track if a voter has


already voted (address => true/false)
mapping(address => bool) public voters;
// Total number of candidates
uint public candidatesCount;

// Constructor runs once when contract is


deployed
constructor() {
admin = [Link]; // Assign deployer as
admin
}

// Function to add a new candidate (only


admin allowed)
function addCandidate(string memory
_name) public {
require([Link] == admin, "Only
admin"); // Check admin

candidatesCount++; // Increment candidate


count
// Add new candidate to mapping
candidates[candidatesCount] = Candidate(
candidatesCount,
_name,
0 // Initial vote count is 0
);
}

// Function to vote for a candidate


function vote(uint _id) public {

// Check if voter has already voted


require(!voters[[Link]], "Already
voted");

// Check if candidate ID is valid


require(_id > 0 && _id <=
candidatesCount, "Invalid candidate");
// Mark voter as voted
voters[[Link]] = true;

// Increase vote count of selected candidate


candidates[_id].voteCount++;
}

// Function to get vote count of a candidate


function getVotes(uint _id) public view
returns(uint) {
return candidates[_id].voteCount;
}
}

You might also like