0% found this document useful (0 votes)
6 views8 pages

BlockChain Technology Unit - 2

Block chain second chapter

Uploaded by

Anish Murali
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)
6 views8 pages

BlockChain Technology Unit - 2

Block chain second chapter

Uploaded by

Anish Murali
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/ 8

BlockChain Technology

Unit-2

1. Consensus Algorithms
These are mechanisms that allow blockchain nodes to agree on the state of the network, ensuring that
transactions are valid and trust is maintained.
a. Proof of Work (PoW):
• Definition: PoW requires participants (miners) to solve complex mathematical puzzles (hashing
problems) to validate transactions and create new blocks.
• How it works:
o Miners compete to solve a cryptographic puzzle.
o The first miner to solve the puzzle gets to add the block to the blockchain and is rewarded.
o The puzzle involves finding a hash that is less than a target value by repeatedly hashing
block data.
o This system is energy-intensive and slow but is highly secure.
• Example: Bitcoin uses PoW.
• Drawbacks: High energy consumption, low transaction speed.
b. Proof of Stake (PoS):
• Definition: PoS assigns block validation rights to nodes in proportion to their holdings of the
network's cryptocurrency, eliminating the need for energy-intensive mining.
• How it works:
o Validators are chosen to create new blocks based on their stake (amount of cryptocurrency
they hold).
o Validators lock up their stake, which they may lose if they attempt to validate fraudulent
transactions (slashing).
o Less energy is consumed as compared to PoW.
• Example: Ethereum 2.0 is transitioning from PoW to PoS.
• Drawbacks: Potential for centralization, as wealthier nodes have more power.
c. Practical Byzantine Fault Tolerance (PBFT):
• Definition: PBFT is a consensus mechanism designed for distributed systems that ensures
consensus even if some nodes are faulty or malicious.
• How it works:
o The network requires a majority of honest nodes (at least ⅔) to agree on the transaction’s
validity.
o Nodes exchange messages to reach a consensus, tolerating up to ⅓ faulty nodes.
o Faster than PoW or PoS, as it doesn't rely on solving puzzles or staking.
• Example: Hyperledger Fabric, Tendermint.
• Drawbacks: Doesn't scale well with large numbers of nodes.
d. Delegated Proof of Stake (DPoS):
• Definition: DPoS is a variation of PoS where stakeholders elect a small number of delegates
(witnesses) to validate blocks on their behalf.
• How it works:
o Stakeholders vote for delegates by pooling their tokens.
o The elected delegates produce and validate blocks.
o Delegates can be voted out if they fail to perform efficiently.
• Example: EOS, Tron.
• Drawbacks: Risk of centralization, as the power is concentrated in the hands of a few elected
validators.

2. Smart Contracts
Definition:
• A smart contract is a self-executing contract where the terms of the agreement (i.e., conditions,
rules, and penalties) are directly written in the code.
• It runs on blockchain networks like Ethereum, ensuring that once the contract conditions are met,
the agreed-upon actions are executed automatically without the need for intermediaries such as
lawyers, banks, or escrow services.
Key Characteristics:
1. Self-Executing: Once the conditions in the contract are met, the contract automatically enforces its
terms.
2. Immutable: Once deployed, the code of a smart contract cannot be altered, ensuring transparency
and security. However, upgradeable patterns exist, such as proxy contracts, which allow for certain
changes.
3. Trustless: The need for trust between parties is eliminated. The code enforces the contract’s rules.
4. Transparent: Since smart contracts are stored on a public blockchain, anyone can audit the
contract to verify its rules and execution.
5. Autonomous: Smart contracts function without any third-party interference, reducing the need for
human intervention once deployed.
Benefits of Smart Contracts:
• Cost Efficiency: By removing the need for intermediaries like lawyers or financial institutions,
transaction costs are reduced.
• Speed: Smart contracts execute in real time as soon as conditions are met, without delays caused
by paperwork or middlemen.
• Security: The contracts are encrypted and distributed across a decentralized blockchain network,
making them tamper-resistant and highly secure.
• Precision: Since smart contracts are based on code, they execute exactly as written, eliminating
human error or misinterpretation of terms.
Components of Smart Contracts:
1. Parties Involved: These are the individuals or entities entering into the contract.
2. Contractual Clauses: The terms of the agreement, written in the form of logical code (e.g., “If party
A sends X amount of tokens, then party B will send Y product”).
3. Triggering Events: Conditions that must be met to trigger the contract’s execution (e.g., date,
payment received, product delivered).
4. Outcomes: The contract executes its agreed actions (e.g., transfer of funds or assets) based on
predefined outcomes.
Example of a Smart Contract:
• Escrow in a Sale: Suppose two parties want to perform an online transaction:
o Step 1: The buyer places cryptocurrency into a smart contract.
o Step 2: The smart contract holds the funds in escrow.
o Step 3: The seller ships the goods.
o Step 4: Upon delivery confirmation (e.g., a tracking system), the smart contract releases the
funds to the seller.
o Step 5: If there’s a dispute, the smart contract might execute a predefined resolution
mechanism, like a refund.

Example of a Basic Solidity Smart Contract:

solidity
Copy code
pragma solidity ^0.8.0;

contract SimpleBank {
mapping(address => uint) private balances;

// Deposit money into the bank


function deposit() public payable {
balances[msg.sender] += msg.value;
}

// Withdraw money from the bank


function withdraw(uint _amount) public {
require(balances[msg.sender] >= _amount, "Insufficient
balance");
payable(msg.sender).transfer(_amount);
balances[msg.sender] -= _amount;
}

// Check the balance of the sender


function getBalance() public view returns (uint) {
return balances[msg.sender];
}
}

• deposit(): Allows users to send ETH and add it to their balance.


• withdraw(): Lets users withdraw funds if their balance is sufficient.
• getBalance(): Allows users to check their own balance.

3. Solidity Programming

Solidity is a high-level, statically typed programming language designed specifically for creating smart
contracts that run on the Ethereum Virtual Machine (EVM). Solidity is similar in syntax to JavaScript,
Python, and C++, and is primarily used for writing decentralized applications (DApps) on blockchain
platforms like Ethereum.

Why Solidity?

• Ethereum-Compatible: Solidity is designed to compile into bytecode that can be run by the
Ethereum Virtual Machine.
• Smart Contract Focused: It enables developers to define complex agreements that automatically
execute based on the rules written in the contract, ensuring decentralization, transparency, and
immutability.
• Widely Used: It is the most popular language for smart contract development, supported by a rich
ecosystem of tools, documentation, and developer communities.

Key Concepts in Solidity:

1. Contracts:
o Solidity contracts are collections of code (functions) and data (state) that reside on the
Ethereum blockchain. Contracts are the primary building blocks of DApps.
o Example:

solidity
Copy code
pragma solidity ^0.8.0;

contract SimpleContract {
// Contract code goes here
}

2. State Variables:
o These are permanently stored on the blockchain and represent the contract’s data (like class
variables in OOP languages).
o Example:

solidity
Copy code
uint public count; // State variable

3. Functions:
o Functions are actions that can be performed by or on the contract. Functions can be public,
private, or internal.
o Example:

solidity
Copy code
function increment() public {
count += 1;
}

o View Functions: These do not modify the state and only read data from the blockchain.

solidity
Copy code
function getCount() public view returns (uint) {
return count;
}

4. Modifiers:
o Modifiers are used to change the behavior of functions. They often check for conditions
before allowing a function to execute (like access control).
o Example:

solidity
Copy code
modifier onlyOwner() {
require(msg.sender == owner, "Not the contract owner");
_;
}

function restrictedAction() public onlyOwner {


// Code that only the owner can execute
}

5. Events:
o Events are used to communicate with off-chain applications by emitting logs. Events allow
data to be stored in a way that can be easily read externally (by dApps or other services).
o Example:

solidity
Copy code
event Incremented(uint newCount);

function increment() public {


count += 1;
emit Incremented(count);
}
4.Ethereum Virtual Machine (EVM)
The Ethereum Virtual Machine (EVM) is the runtime environment for executing smart contracts on the
Ethereum blockchain. It acts as a decentralized, global supercomputer, enabling the execution of code in a
distributed manner across thousands of nodes, ensuring security, consistency, and decentralization. The
EVM is a key component of Ethereum's architecture, abstracting away the complexity of managing the
blockchain's state.
Key Functions of the EVM:
1. Smart Contract Execution:
o The EVM is responsible for executing smart contracts, which are written in high-level
programming languages like Solidity. Once a contract is deployed to the blockchain, the
EVM processes any function calls made to that contract.
2. Decentralized Computation:
o Every Ethereum node runs an instance of the EVM. When transactions (which might
include smart contract executions) are submitted, they are processed by the EVM on each
node, ensuring that the same results are reached on all nodes, maintaining consensus.
3. Isolation and Security:
o The EVM operates in a completely sandboxed environment, meaning that it does not have
direct access to the machine on which it is running. This ensures that any bugs or malicious
actions in a smart contract do not compromise the underlying infrastructure.
4. State Management:
o The EVM maintains the global state of the Ethereum blockchain, which includes all
accounts, balances, contract states, and storage. This state is updated with each transaction
that modifies the blockchain, such as transfers of Ether or smart contract executions.
Gas and EVM Execution:
• Gas:
o In the Ethereum ecosystem, "gas" refers to the fee required to perform a transaction or
execute a contract. Every operation that the EVM performs—whether it's adding two
numbers or deploying a complex contract—requires a certain amount of gas.
o Gas is used to limit the computational resources required for executing contracts,
preventing the system from being overwhelmed by poorly optimized or malicious code.
• Gas Limits:
o Every transaction sets a "gas limit" that defines the maximum amount of gas the
transaction can consume. If the execution exceeds this limit, the transaction fails, and the
EVM halts execution, reverting all changes.
• Gas Price:
o Users pay for gas in Ether (ETH), and they can choose the gas price they are willing to pay.
The higher the gas price, the more likely it is that miners will prioritize their transaction.
EVM Opcodes:
• The EVM operates using low-level instructions known as opcodes. Each opcode is a basic operation
like adding numbers, accessing data from memory, or interacting with the blockchain’s state.
• Solidity contracts are compiled into EVM bytecode, which is essentially a series of opcodes that the
EVM understands and executes.
• Examples of common opcodes:
o ADD: Adds two values.
o SSTORE: Stores a value in contract storage (state variable).
o CALL: Executes a call to another contract or address.
o LOG: Logs an event that can be accessed off-chain.
Accounts in EVM:
1. Externally Owned Accounts (EOAs):
o These are standard user accounts controlled by private keys. EOAs can send and receive
ETH, and they can initiate contract calls.
2. Contract Accounts:
o These are smart contract accounts, which are controlled by the contract code rather than a
private key. Contracts cannot initiate transactions on their own but can be triggered by
EOAs or other contracts.
Stack, Memory, and Storage in EVM:
1. Stack:
o The EVM is a stack-based machine, meaning that it uses a stack data structure to manage
its operations. Each opcode manipulates the stack by pushing or popping values.
2. Memory:
o Memory in the EVM is temporary and only persists during the execution of a contract. Once
the execution ends, the memory is wiped.
3. Storage:
o Storage is persistent and stored on the blockchain. This is where state variables and
contract data are stored. Writing to storage is more expensive in terms of gas than writing
to memory.
EVM's Role in Ethereum Consensus:
• Consensus Algorithms:
o Every node in the Ethereum network runs an instance of the EVM. When a transaction is
submitted, it is propagated to the network, and miners (in Proof of Work) or validators (in
Proof of Stake) execute the transaction on their local instance of the EVM.
o The EVM ensures that all nodes reach the same results and agree on the current state of
the blockchain, maintaining consensus across the network.
Ethereum Upgrades and EVM:
• EVM and Ethereum 2.0:
o With the shift to Ethereum 2.0 and Proof of Stake (PoS), the EVM will continue to serve as
the computational engine for smart contracts. However, scalability improvements like
sharding and layer-2 solutions will impact how efficiently the EVM processes transactions.
o Optimizations: Ethereum is exploring optimizations to the EVM, such as eWASM
(Ethereum WebAssembly), which would allow for faster execution and support for more
programming languages.

5.Deploying and Executing Smart Contracts on Ethereum


Smart contracts are self-executing programs on the blockchain that automate processes and enforce
agreements. On Ethereum, deploying and executing smart contracts involves writing the contract code,
compiling it into bytecode, deploying it to the blockchain, and then interacting with it through
transactions. The Ethereum Virtual Machine (EVM) handles the execution of the contracts, ensuring
consistency and security across all nodes.
1. Writing a Smart Contract:
• Smart contracts are written in high-level languages like Solidity.
• Example: A simple contract to store and retrieve a number.
2. Compiling the Contract:
• Use tools like Remix IDE or Truffle to compile Solidity code into EVM bytecode.
• The compiler also generates an ABI (Application Binary Interface) to interact with the contract.
3. Deploying the Contract:
• Deploy by submitting the bytecode through a transaction to the Ethereum network.
• This requires paying a gas fee in Ether (ETH). A successful deployment gives the contract a unique
address.
4. Interacting with the Contract:
• Read-only functions (like retrieving data) don’t cost gas and don’t alter the state.
• State-changing functions (like updating data) require a transaction and consume gas.
5. Gas Costs:
• Gas is needed for deploying and executing contracts. Set a gas limit and gas price based on the
complexity of the transaction.
6. Security:
• Ensure code is secure to avoid vulnerabilities (e.g., reentrancy attacks, overflow errors).
• Once deployed, smart contracts can’t be changed, so testing is essential.
7. Tools:
• Use platforms like Remix, Truffle, or Hardhat to deploy, test, and interact with smart contracts.
Test networks like Ropsten or Goerli are used before mainnet deployment.

You might also like