KEMBAR78
Blockchain Technologies Module 5 | PDF | Bitcoin | Software Engineering
0% found this document useful (0 votes)
127 views24 pages

Blockchain Technologies Module 5

Blockchain Technologies Module 5 KTU Notes s8 CSE

Uploaded by

suryajit27
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)
127 views24 pages

Blockchain Technologies Module 5

Blockchain Technologies Module 5 KTU Notes s8 CSE

Uploaded by

suryajit27
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/ 24

Blockchain Technologies

Module 5

Explain error handling in Solidity language.


Error handling in Solidity is a crucial aspect of writing robust smart contracts.
Solidity provides various constructs and functions to handle errors effectively.
Here’s an explanation of the main error handling mechanisms in Solidity, along
with an example contract illustrating their use:

Constructs and Functions for Error Handling


1. Assert:

Purpose: Used to check for conditions that should never be false,


indicating a bug in the contract. It is intended for internal errors and
invariant checking.

Behavior: If the condition is false, the transaction is reverted, and any


changes to the state are undone. It results in an invalid opcode,
consuming all remaining gas.

Usage: Mainly for debugging and checking internal consistency.

function assertExample(uint x, uint y) public pure retur


ns (uint) {
uint result = x + y;
assert(result > x); // Ensure that the result of the
addition is greater than `x`
return result;
}

2. Require:

Blockchain Technologies Module 5 1


Purpose: Used to validate inputs, return values, or conditions before
executing further logic. Commonly used for checking preconditions.

Behavior: If the condition is false, the transaction is reverted, and an


optional custom error message can be provided. It refunds the
remaining gas.

Usage: Typically used for input validation and ensuring correct contract
state before executing critical code.

function requireExample(uint x, uint y) public pure retu


rns (uint) {
require(y != 0, "Cannot divide by zero"); // Check i
f `y` is not zero, otherwise revert the transaction with
the error message
uint result = x / y; // Calculate the result of divi
ding `x` by `y`
return result;
}

3. Revert:

Purpose: Explicitly abort the transaction and revert the state. Useful for
complex conditional logic.

Behavior: Similar to require , it reverts the transaction and undoes any


state changes. It can also return a custom error message.

Usage: Used within more complex conditions or to provide clearer


intent in the code.

function revertExample(uint x, uint y) public pure retur


ns (uint) {
if (y == 0) {
revert("Cannot divide by zero");
}
uint result = x / y; // Calculate the result of divi
ding `x` by `y`
return result;
}

Blockchain Technologies Module 5 2


4. Try/Catch:

Purpose: Handle exceptions that occur during external calls to other


contracts. This is crucial when interacting with untrusted contracts.

Behavior: Allows catching errors and handling them gracefully without


reverting the entire transaction.

Usage: Used for interacting with external contracts to catch errors and
implement fallback logic.

function safeDivide(uint x, uint y) public view returns


(uint) {
try externalContract.divide(x, y) returns (uint
result) {
return result;
} catch {
return 0; // Return 0 if an error occurs
}
}
}

5. Throw:

Purpose: Legacy construct to stop execution and revert changes.

Behavior: Stops execution and reverts the transaction, consuming all


remaining gas.

Usage: Deprecated in favor of revert and require .

function throwExample(uint x, uint y) public pure return


s (uint) {
if (y == 0) {
throw; // If `y` is zero, revert the transaction
}
uint result = x / y; // Calculate the result of divi
ding `x` by `y`
return result;
}

Blockchain Technologies Module 5 3


Explain data types in the Solidity language with
proper examples in detail.
Data Types in Solidity
In Solidity, data types are crucial for defining the kind of data that variables can
hold or functions can return. Solidity supports both value types and reference
types.

Value Types
Value types hold their data directly and include:

1. Boolean: Represents true or false.

bool public myBool = true;

2. Integer: Supports both signed ( int ) and unsigned ( uint ) integers of


various sizes (e.g., uint8 , uint256 , int8 , int256 ).

uint8 public myUint8 = 255;


int256 public myInt256 = -123456789;

3. Fixed Point: Represents decimal numbers with fixed precision (Note: Fixed-
point types are currently not fully supported in Solidity).

fixed8x1 public myFixed8x1 = 1.5; // Hypothetical, not c


urrently supported

4. Address: Represents Ethereum addresses, which are 20-byte values.

address public myAddress = 0x5B38Da6a701c568545dCfcB03Fc


B875f56beddC4;

5. Enum: Custom data type for a set of named values.

enum State { Created, Locked, Inactive }


State public myState = State.Created;

6. Mapping: Key-value store where keys and values can be of any type.

Blockchain Technologies Module 5 4


mapping(address => uint) public balances;

function setBalance(address account, uint amount) public


{
balances[account] = amount;
}

function getBalance(address account) public view returns


(uint) {
return balances[account];
}

Example Contract for Value Types

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

contract DataTypesExample {
bool public myBool = true;
uint8 public myUint8 = 255;
int256 public myInt256 = -123456789;
address public myAddress = 0x5B38Da6a701c568545dCfcB03F
cB875f56beddC4;

enum State { Created, Locked, Inactive }


State public myState = State.Created;

mapping(address => uint) public balances;

function setBalance(address account, uint amount) publi


c {
balances[account] = amount;
}

function getBalance(address account) public view return


s (uint) {
return balances[account];

Blockchain Technologies Module 5 5


}
}

Reference Types
Reference types store data in a different location and include:

1. Arrays: Collections of elements of the same type. Arrays can be dynamic


(variable length) or fixed (fixed length).

uint[] public dynamicArray;


uint[5] public fixedArray;

2. Structs: Custom data structures with multiple fields.

struct Person {
string name;
uint age;
}

Person public person = Person("Alice", 30);

3. Strings: Sequences of characters.

string public myString = "Hello, Solidity!";

4. Bytes: Fixed-length sequence of bytes.

bytes32 public myBytes32 = "Hello, Solidity!";

5. Function Types: Can represent function pointers.

function(uint, uint) external returns (uint) public myFu


nction;

Define structure of a smart contract by giving


contract examples.

Blockchain Technologies Module 5 6


A smart contract is a self-executing program that resides on the blockchain
and performs certain functions when specific conditions are met. Here,
we'll go through the structure of a smart contract in Solidity with a detailed
example.

Example Smart Contract: Simple Storage

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

contract SimpleStorage {
// State variable
uint256 private storedData;

// Event declaration
event DataStored(uint256 data);

// Constructor
constructor(uint256 initialData) {
storedData = initialData;
}

// Public function to set the value


function set(uint256 x) public {
storedData = x;
emit DataStored(x); // Emit an event
}

// Public function to get the value


function get() public view returns (uint256) {
return storedData;
}
}

Breakdown of the Components


1. SPDX-License-Identifier:

Blockchain Technologies Module 5 7


// SPDX-License-Identifier: MIT

This specifies the license under which the contract is released. It is


optional but recommended for clarity and legal purposes.

2. Pragma Statement:

pragma solidity ^0.8.0;

This specifies the version of the Solidity compiler to be used. In this


example, any version of Solidity from 0.8.0 onwards is allowed.

3. Contract Definition:

contract SimpleStorage {

The contract keyword defines a new smart contract named


SimpleStorage .

4. State Variables:

uint256 private storedData;

State variables are stored on the blockchain. storedData is a private


variable of type uint256 (unsigned integer).

5. Event Declaration:

event DataStored(uint256 data);

Events are used to log information to the blockchain that can be


accessed externally. The DataStored event will log the value that is
stored.

6. Constructor:

constructor(uint256 initialData) {
storedData = initialData;
}

Blockchain Technologies Module 5 8


The constructor is a special function that is executed once when the
contract is deployed. It initializes the storedData variable with the
provided initialData .

7. Public Functions:

function set(uint256 x) public {


storedData = x;
emit DataStored(x); // Emit an event
}

function get() public view returns (uint256) {


return storedData;
}

set: This function allows users to store a value in the storedData

variable. It also emits the DataStored event.

get: This function returns the current value of storedData . The view
keyword indicates that this function does not modify the state.

With the help of a figure show the relationship


between the
transaction, transaction trie, and block header in
Ethereum.
1. Transaction Structure
A transaction in Ethereum is a digitally signed data packet that contains the
following fields:

Nonce: A counter that ensures each transaction can only be processed


once.

Gas Price: The amount of Wei (smallest unit of Ether) the sender is
willing to pay per unit of gas.

Gas Limit: The maximum amount of gas the sender is willing to use for
the transaction.

To: The recipient address (20 bytes) of the transaction.

Blockchain Technologies Module 5 9


Value: The amount of Wei to be transferred to the recipient.

Data: The input data for contract execution or message calls.

V, R, S (Signature): Components of the transaction's digital signature,


ensuring its authenticity.

2. Transaction Trie (Merkle Patricia Trie)


Transactions in Ethereum are organized in a data structure called the
Merkle Patricia Trie (MPT). This trie ensures efficient and secure
verification of transactions within a block. It has the following features:

Root Hash of Transactions: A unique hash that represents the root of


the MPT, summarizing all transactions in the block.

3. Block Header
The block header is a critical component of a block, containing metadata
about the block and links to the preceding block in the blockchain. It
includes:

Parent Block Hash: The hash of the previous block in the blockchain.

Transactions Trie Root: The root hash of the transaction trie.

State Trie Root: The root hash of the state trie, representing the global
state of all accounts.

Receipts Trie Root: The root hash of the receipts trie, summarizing all
transaction receipts.

Timestamp: The time when the block was mined.

Nonce: A number that miners adjust to find a valid hash for the block.

Relationship Between Transaction, Transaction Trie, and


Block Header
Transactions are the individual actions (like transferring Ether or
interacting with smart contracts) initiated by users.

Transaction Trie is a Merkle Patricia Trie that organizes all transactions


in a block, ensuring their integrity and quick verification.

Block Header contains the root of the transaction trie, linking the
transactions securely to the block.

Blockchain Technologies Module 5 10


Define block difficulty. Explain how block difficulty
is adjusted in Ethereum blockchain network
Block difficulty in the Ethereum blockchain refers to the level of
computational effort required to find a valid block hash that meets the
network's consensus rules. This difficulty is adjusted periodically to
maintain a relatively constant block generation time, ensuring the network's
stability and security.

How Block Difficulty is Adjusted:


1. Time-Based Adjustment:

The Ethereum network adjusts the block difficulty based on the time
difference between the generation of the current block and its
parent block.

If the time difference is less than 10 seconds, the difficulty


increases.

If the time difference is between 10 and 19 seconds, the difficulty


remains unchanged.

If the time difference is 20 seconds or more, the difficulty


decreases.

The magnitude of the increase or decrease is proportional to the


time difference, up to a maximum decrease of parent_diff / 2048 *
-99 .

Blockchain Technologies Module 5 11


2. Exponential Increase:

Additionally, the difficulty increases exponentially after every


100,000 blocks.

This is known as the "difficulty time bomb" or "ice age," designed to


incentivize the transition from Proof of Work (PoW) to Proof of Stake
(PoS).

The exponential increase makes mining on the PoW chain


increasingly difficult, encouraging miners to switch to PoS.

Ice Age Postponement and Byzantium Release:


1. Ice Age Postponement:

The ice age proposal, originally intended to make PoW mining


prohibitively difficult, was postponed with the Byzantium release.

Instead, the mining reward was reduced from 5 ETH to 3 ETH in


preparation for the transition to PoS in the Serenity upgrade.

2. Byzantium Difficulty Adjustment:

In the Byzantium release, the difficulty adjustment formula was


updated to consider the number of uncles (stale blocks) in the
calculation.

The adjustment factor is determined based on the presence of


uncles and the time difference between blocks.

Gas Fee Mechanism:


In Ethereum, each operation performed on the network, such as
transaction creation, validation, and execution of smart contract code,
consumes computational resources and incurs a cost.

This cost is denoted in gas, and users must pay a gas fee to execute
transactions and smart contracts on the Ethereum network.

The gas fee mechanism ensures that the network remains efficient and
prevents abuse by limiting resource consumption.

Explain the concept of Gas in Ethereum. Explain


how transaction cost can be calculated in an

Blockchain Technologies Module 5 12


Ethereum blockchain network.
Gas in the Ethereum blockchain is a unit of measure for the computational
work required to execute operations or smart contracts on the Ethereum
Virtual Machine (EVM). It acts as a mechanism to prevent infinite loops and
other resource-intensive operations from stalling the entire blockchain
network. Gas is also used to incentivize miners to include transactions in
blocks and to ensure that the network remains efficient and secure.

Concept of Gas:
1. Transaction Fees:

Gas is required to be paid for every operation performed on the


Ethereum blockchain.

When a user initiates a transaction, they specify a gas limit and a


gas price (in Gwei, a unit of ETH), which together determine the
maximum amount of gas they are willing to pay for the transaction.

The transaction fee, calculated as the gas used multiplied by the


gas price, is deducted from the sender's account balance.

2. Preventing Resource Exhaustion:

Gas limits prevent resource exhaustion by limiting the amount of


computational work that can be performed within a transaction.

If a transaction exceeds its gas limit during execution, it is reverted,


and any changes made are rolled back. This prevents malicious or
unintentional attacks that could disrupt the network.

3. Transaction Cost Estimation:

Gas costs for transactions can be estimated using the formula: Total

cost = gasUsed * gasPrice .

GasUsed represents the total gas consumed during the execution of


the transaction.

GasPrice is specified by the transaction originator and serves as an


incentive for miners to include the transaction in a block.

Calculation of Transaction Cost:


1. Gas Usage:

Blockchain Technologies Module 5 13


Each EVM opcode (operation) has a predetermined gas cost
associated with it. For example, simple operations like addition or
subtraction have lower gas costs, while complex operations like
storage access have higher gas costs.

The gas usage for a transaction is the sum of the gas costs for all
operations performed during its execution.

2. Gas Price:

The gas price is specified by the transaction originator and is


denoted in Gwei (1 ETH = 1,000,000,000 Gwei).

Miners prioritize transactions with higher gas prices, as they receive


higher rewards for including them in blocks.

3. Example Calculation:

For instance, if the gas cost for a SHA-3 operation is 30 gas, and
the gas price is 25 Gwei, the total cost would be calculated as: 30
gas * 25 Gwei = 0.00000075 ETH .

Gas plays a crucial role in incentivizing miners, maintaining network


efficiency, and preventing abuse of computational resources on the
Ethereum blockchain. By accurately estimating gas costs, users can ensure
the successful execution of their transactions while optimizing their costs.

Explain how transactions are processed in


Ethereum. Briefly explain the concept of gas and
how does it affect the transaction processing?
How Transactions Are Processed in Ethereum
Transactions in Ethereum follow a specific sequence to ensure their validity
and proper execution. The steps are as follows:

1. Transaction Creation and Signing:

A user creates a transaction specifying the recipient, amount of


ether to transfer, and any additional data.

The transaction is signed using the sender's private key, ensuring


authenticity and integrity.

2. Broadcasting the Transaction:

Blockchain Technologies Module 5 14


The signed transaction is broadcasted to the Ethereum network.
Nodes in the network receive and validate the transaction.

3. Validation:

Syntax Check: Ensures the transaction is well-formed and encoded


correctly.

Signature Verification: Confirms that the transaction is signed by


the account holder.

Nonce Check: Verifies that the nonce (a counter to prevent double-


spending) is correct. The nonce must match the sender's account's
current nonce.

Gas Limit Check: Ensures the gas limit specified in the transaction
is sufficient to cover the computational cost.

Balance Check: Confirms that the sender's account has enough


balance to cover the transaction fee and the amount being
transferred.

4. Execution:

Once validated, the transaction is added to the transaction pool,


waiting to be included in a block by miners.

Miners pick transactions from the pool, prioritize them based on the
gas price (higher gas prices typically get processed first), and
include them in a new block.

5. Mining and Block Inclusion:

Miners compete to solve a computational puzzle (Proof of Work).


The first miner to solve it gets to add the block containing the
transaction to the blockchain.

The block is broadcasted to the network, and once other nodes


validate it, the block is added to their copy of the blockchain.

6. State Changes:

The state of the blockchain is updated to reflect the transaction.


This includes debiting the sender's account, crediting the recipient,
and updating the nonce.

7. Transaction Receipts:

Blockchain Technologies Module 5 15


A transaction receipt is generated, containing details like the
transaction status, gas used, and any logs created by smart
contracts during execution.

The Concept of Gas in Ethereum


Gas is a fundamental concept in Ethereum, designed to measure the
computational work required to perform operations such as executing
transactions and smart contracts. Here’s how gas works:

1. Purpose of Gas:

Gas serves as a fee mechanism to incentivize miners to include


transactions in blocks and to prevent misuse of computational
resources on the network.

Each operation in a transaction or smart contract execution


consumes a specific amount of gas, depending on its complexity
and resource requirements.

2. Gas Limit and Gas Price:

Gas Limit: The maximum amount of gas a transaction can consume.


Users set this limit when creating a transaction to ensure it doesn’t
exceed their budget.

Gas Price: The amount of ether a user is willing to pay per unit of
gas, measured in gwei (1 gwei = 10^-9 ether). The higher the gas
price, the more likely miners will prioritize the transaction.

3. Gas Cost Calculation:

The total gas cost of a transaction is the product of the gas used
and the gas price. For example, if a transaction uses 21,000 gas and
the gas price is 50 gwei, the cost is 21,000 * 50 gwei.

4. Impact on Transaction Processing:

Execution: If a transaction runs out of gas during execution, it fails,


and any changes are reverted, but the gas spent up to that point is
not refunded.

Incentivization: Miners prioritize transactions with higher gas


prices, as it increases their potential reward. This creates a market
where users bid for computational resources.

Blockchain Technologies Module 5 16


Limitations: Setting a gas limit too low can result in transaction
failure if it doesn’t cover the execution cost. Conversely, setting it
too high doesn’t lead to additional costs but can lock up more funds
than necessary until the transaction is processed.

5. Refunds:

If a transaction uses less gas than the gas limit, the remaining gas is
refunded to the sender. This ensures users don’t overpay for
computational resources they don’t use.

Components of Ethereum Blockchain


1. Keys and Addresses
Keys: Ethereum uses a pair of cryptographic keys—a private key and a
public key. The private key is a randomly generated 256-bit number
kept secret, while the public key is derived from the private key using
the Elliptic Curve Digital Signature Algorithm (ECDSA).

Addresses: An address in Ethereum is derived from the public key and


is a 20-byte code that identifies user accounts. It's used to send and
receive transactions.

2. Accounts
Ethereum has two types of accounts:

Externally Owned Accounts (EOAs): Controlled by private keys, they


can send transactions and have an Ether balance but do not contain
code.

Contract Accounts (CAs): Contain code and are controlled by the logic
of the code. They can execute smart contracts in response to
transactions.

3. Transactions and Messages


Transactions: These are signed data packets that represent a transfer
of value or a call to a smart contract. They include fields such as nonce,
gas price, gas limit, recipient address, value, and signature.

Messages: Internal actions triggered by transactions, used to call


functions in smart contracts.

Blockchain Technologies Module 5 17


4. Ether (ETH)
Ether is the native cryptocurrency of Ethereum. It is used to compensate
participants who perform computations, and it serves as a medium for
transactions on the network.

5. Ethereum Virtual Machine (EVM)


The EVM is the runtime environment for smart contracts in Ethereum. It's a
Turing-complete virtual machine that executes bytecode instructions,
ensuring that smart contracts run as programmed.

6. Smart Contracts and Native Contracts


Smart Contracts: These are self-executing contracts with the terms
directly written into code. They automatically enforce and execute
terms of the agreement when certain conditions are met.

Native Contracts: Built-in contracts that are integral to the Ethereum


platform, often used for basic operations like managing Ether.

7. Blocks and Blockchain


Blocks: Contain batches of transactions, a timestamp, a reference to
the previous block (parent hash), and other metadata.

Blockchain: A chain of blocks where each block is linked to its


predecessor, forming a distributed ledger. This ensures the integrity
and immutability of the data.

Technical Comparison of Bitcoin and Ethereum


Feature Bitcoin Ethereum

Digital currency, Platform for dApps and smart


Purpose
store of value contracts

Creator Satoshi Nakamoto Vitalik Buterin

Consensus Proof of Work (PoW), transitioning to


Proof of Work (PoW)
Mechanism Proof of Stake (PoS) with Ethereum 2.0

Supply Limit 21 million BTC No fixed supply limit

Block Time ~10 minutes ~15 seconds

Feature Bitcoin Ethereum

Blockchain Technologies Module 5 18


Ethash (PoW), transitioning to
Consensus Algorithm SHA-256 (PoW)
Casper (PoS)

Programming Script (limited, stack-


Solidity (Turing-complete)
Language based)

UTXO (Unspent
Transaction Model Account/Balance model
Transaction Output)

~1 MB (with SegWit: ~4
Average Block Size ~70 KB
MB)

~30 (potentially thousands with


Average Transactions
~7 Layer 2 solutions and Ethereum
per Second (TPS)
2.0)

Determined by
Gas fees (determined by
Transaction Fees transaction size (in
computation and storage needs)
bytes)

Ethash (PoW), transitioning to


Mining Algorithm SHA-256
Casper (PoS)

Smart Contract
Limited (script-based) Advanced (Turing-complete)
Capability

Extensive (Truffle, Remix,


Development Tools Limited
MetaMask, etc.)

Ethereum World State


The Ethereum world state is a critical component of the Ethereum
blockchain, maintaining the state of all accounts and smart contracts at any
given block. It represents the current status of the entire Ethereum network.

State Storage in the Ethereum Blockchain


1. World State:

A mapping between Ethereum addresses (20 bytes/160 bits) and


account states, serialized using Recursive Length Prefix (RLP)
encoding.

2. Account State:

Nonce: Incremented with each transaction from the address. For


contract accounts (CAs), it represents the number of contracts
created.

Blockchain Technologies Module 5 19


Balance: The amount of weis (smallest unit of ether) held by the
address.

Storage Root: The root node of a Merkle Patricia Trie (MPT)


encoding the storage contents of the account.

Code Hash: Immutable hash of the smart contract code associated


with the account, or Keccak-256 hash of an empty string for normal
accounts.

Components of the Diagram


Block Header: Contains the state root hash, the Keccak-256
hash of the root node of the world state trie.

World State Trie: A modified MPT mapping Ethereum addresses


to account states.

Account State Trie: An MPT encoding the storage contents of


an account, mapping Keccak-256 hashes of 256-bit integer
keys to RLP-encoded 256-bit integer values.

Account State: Includes nonce, balance, storage root (root


node of the account storage trie), and code hash (hash of the
smart contract code).

Blockchain Technologies Module 5 20


This compact structure efficiently manages and updates the state of
all accounts and smart contracts on the Ethereum blockchain.

Using Solidity language, create a simple bank


contract that allows a user to deposit, withdraw
and view balance.
// Set the version of Solidity to use
pragma solidity ^0.8.0;

// Define the SimpleBank contract


contract SimpleBank {
// Declare a private mapping to store each user's ba
lance
mapping(address => uint256) private balances;

// Define the deposit function


function deposit() public payable {
// Increase the user's balance by the amount sen
t with the transaction
balances[msg.sender] += msg.value;
}

// Define the withdraw function


function withdraw(uint256 amount) public {
// Check if the user has enough balance to withd
raw
require(balances[msg.sender] >= amount, "Insuffi
cient balance");

// Decrease the user's balance by the withdrawal


amount
balances[msg.sender] -= amount;

// Transfer the withdrawal amount to the user's


address

Blockchain Technologies Module 5 21


payable(msg.sender).transfer(amount);
}

// Define the getBalance function


function getBalance() public view returns (uint256)
{
// Return the balance of the user calling the fu
nction
return balances[msg.sender];
}
}

Explanation:

deposit: This function allows users to deposit Ether into their account.
The payable modifier allows the function to receive Ether. It increases
the balance of the caller ( msg.sender ) by the amount sent with the
transaction.

withdraw : Users can withdraw Ether from their account using this
function. It takes an amount parameter representing the amount of Ether
to withdraw. The function checks if the caller has sufficient balance
using a require statement. If the balance is enough, it decreases the
user's balance and transfers the specified amount of Ether back to the
caller's address.

getBalance: This function returns the balance of the caller. It is a view


function, meaning it does not modify the contract state and is free to
call.

Using Solidity language, create a simple voting


smart contract where a chairperson will give the
right to vote to each address individually.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

contract Voting {
address public chairperson; // The chairperson who c

Blockchain Technologies Module 5 22


an give out voting rights
mapping(address => bool) public voters; // Mapping t
o track voters
mapping(uint256 => uint256) public votes; // Mapping
to track votes for each option

constructor() {
chairperson = msg.sender; // Set the chairperson
to the deployer of the contract
}

// Function to give a voter the right to vote


function giveRightToVote(address voter) public {
require(msg.sender == chairperson, "Only the cha
irperson can give voting rights.");
voters[voter] = true; // Give the voter the righ
t to vote
}

// Function for voters to cast their vote


function vote(uint256 optionIndex) public {
require(voters[msg.sender], "You are not authori
zed to vote.");
require(optionIndex < 100, "Invalid option.");
// Assuming a maximum of 100 options
votes[optionIndex] += 1; // Record the vote for
the selected option
}

// Function to get the vote count for a specific opt


ion
function getVoteCount(uint256 optionIndex) public vi
ew returns (uint256) {
require(optionIndex < 100, "Invalid option.");
// Assuming a maximum of 100 options
return votes[optionIndex]; // Return the vote co
unt for the selected option

Blockchain Technologies Module 5 23


}
}

Blockchain Technologies Module 5 24

You might also like