MODULE 4 , Module 5 Notes Internal 3
MODULE 4 , Module 5 Notes Internal 3
Definition:
A smart contract is a secure and unstoppable computer program that represents an agreement,
which is automatically executable and enforceable.
Key Features:
2. Automatic Execution: Executes predefined actions when specified conditions are met,
requiring no intermediaries.
3. Enforceability: Ensures that all contractual terms are followed, even in adversarial
conditions.
Operation:
• Smart contracts operate using a state machine model, advancing their internal state based
on predefined conditions.
• They function deterministically, ensuring consistent outputs across nodes, which is crucial for
maintaining blockchain consensus.
Challenges:
• Bridging the gap between human-readable legal contracts and machine-executable code.
• Legal and regulatory compliance for making smart contracts legally binding.
Applications:
• Used in financial transactions, supply chain automation, real estate (title deeds), and more.
In essence, smart contracts embody the principle of "code is law," eliminating the need for external
enforcement while ensuring reliability and efficiency.
Note on The transaction substate 5 m
A transaction substate is created during the execution of the transaction that is processed
immediately after the execution completes.
This transaction substate is a tuple that is composed of four items. These items are described here:
Suicide set or self-destruct set:
This element contains the list of accounts (if any) that are disposed of after the transaction executes.
Log series:
This is an indexed series of checkpoints that allow the monitoring and notification of contract calls to
the entities external to the Ethereum environment, such as application frontends.
It works like a trigger mechanism that is executed every time a specific function is invoked, or a
specific event occurs.
Logs are created in response to events occurring in the smart contract. It can also be used as a
cheaper form of storage.
Events will be covered with practical examples in Chapter 14, Introducing Web3. Refund balance:
This is the total price of gas in the transaction that initiated the execution.
Refunds are not immediately executed; instead, they are used to offset the total execution cost
partially.
Touched accounts: This is the set of touched accounts from which empty ones are deleted at the
end of the transaction
1. Nonce:
2. Balance:
o Represents the amount of Wei (the smallest unit of Ether) held by the account.
3. Storage Root:
o The root node of a Merkle Patricia Trie, encoding the storage contents of the
account.
o This trie is used for efficient and verifiable storage of key-value pairs.
4. Code Hash:
o Stores the hash of the smart contract code associated with the account.
o For externally owned accounts (non-contract accounts), this is the Keccak-256 hash
of an empty string.
• The accounts trie encodes account information using a Merkle Patricia Trie.
• The root of the world state trie represents the mapping of account addresses to their
respective account states.
• This root is stored in the block header as the state root hash, ensuring integrity and
consistency of the blockchain.
This hierarchical structure ensures efficient storage, verification, and updates to the blockchain state.
After the DAO hack (described later in this chapter), a hard fork was proposed in order to mitigate
the issue; therefore, there are now two Ethereum blockchains: one is called Ethereum Classic, and its
currency is represented by ETC, whereas the hard-forked version is ETH, which continues to grow and
on which active development is being carried out.
ETC, however, has its following with a dedicated community that is further developing ETC, which is
the unforked original version of Ethereum.
This chapter is focused on ETH, which is the currently the most active and official Ethereum
blockchain.
Ether is minted by miners as a currency reward for the computational effort they spend to secure
the network by verifying and with validation transactions and blocks.
Ether is used within the Ethereum blockchain to pay for the execution of contracts on the EVM.
Ether is used to purchase gas as crypto fuel, which is required to perform computation on the
Ethereum blockchain.
The denomination table is shown as follows
Core Features:
1. Stack-Based Architecture:
2. Turing-Complete Machine:
o Prevents infinite loops by requiring gas for every instruction, thus avoiding denial-of-
service (DoS) attacks.
3. Gas Mechanism:
o Ensures that computational tasks have a cost, making infinite or malicious loops
economically infeasible.
1. Memory:
2. Storage:
o Persistent, like hard disk storage, and stored permanently on the blockchain.
3. Program Code:
Execution Flow:
• The EVM reads instructions from memory, updates the program counter, and pushes or
pops values from the stack during execution.
• Ensures integrity by maintaining all storage and memory initialized to zero by default.
• Research into EVM optimization is ongoing, with WebAssembly (WASM) being explored for
faster and more efficient execution.
• New tools and languages, such as JULIA, aim to enhance smart contract development by
compiling to multiple backends, including EVM and eWASM.
Execution environment
The execution environment in Ethereum provides all necessary parameters and context for code
execution. These key elements ensure that smart contracts and transactions can be executed
securely and deterministically. Below are the essential components required for the execution
environment:
Key Elements:
1. System State:
o The global state of the Ethereum blockchain, which includes account balances,
storage, and code.
2. Remaining Gas:
o Tracks the gas available for executing the code. Gas ensures efficient resource
allocation and prevents infinite loops.
4. Sender's Address:
o The address of the entity (user or contract) that initiated the transaction or message.
5. Originating Address:
o The address from which the execution originated. This may differ from the sender’s
address in certain scenarios.
6. Gas Price:
o The cost per unit of gas specified in the transaction that initiated the execution.
9. Code to be Executed:
o Information about the current block, such as the block number, timestamp, and
miner.
Precompiled contracts in Ethereum are built-in contracts that provide efficient implementations of
complex cryptographic and mathematical operations. These contracts run at specific fixed addresses
and execute faster than regular smart contracts. Below is a list of the eight precompiled contracts
introduced in the Byzantium release, along with their descriptions:
• Address: 0x1
• Purpose:
o Derives the public key from a given private key using elliptic curve cryptography.
• Inputs:
• Output:
• Address: 0x2
• Purpose:
• Output:
• Purpose:
• Output:
4. Identity/Datacopy Function
• Address: 0x4
• Purpose:
• Output:
• Gas Cost:
• Address: 0x5
• Purpose:
• Address: 0x6
• Purpose:
• Purpose:
• Address: 0x8
• Purpose:
1. Nonce
• Definition:
• Usage:
o The first transaction from an account has a nonce of 0, the next is 1, and so on.
o For example, if a transaction with nonce 3 is submitted before nonce 2, it will not be
processed until nonce 2 is completed.
2. Gas Price
• Definition:
o The amount of Ether (in wei) the sender is willing to pay per unit of gas for the
execution of the transaction.
• Usage:
3. Gas Limit
• Definition:
o The maximum amount of gas a sender is willing to allow for the transaction to
execute.
• Usage:
• Example:
o If the gas limit is set to 50,000 but only 25,000 gas is used, the remaining gas is
returned.
4. To Address
• Definition:
• Usage:
o Specifies the destination of the Ether or the smart contract to interact with.
5. Value
• Definition:
• Usage:
• Data: Contains input data for smart contract execution, such as function arguments or
parameters.
a) Zerocoin
1. Key Features:
o Basecoins can be converted into zerocoins, and later redeemed for new basecoins,
making the new coins unlinkable to the old ones.
2. How It Works:
o These zerocoins act as proofs that a user previously owned basecoins but do not
reveal which specific coins were owned.
3. Cryptographic Guarantees:
4. Challenges:
o Not directly compatible with Bitcoin without significant changes (e.g., soft or hard
forks).
b) Zero-Knowledge Proofs
Zero-knowledge proofs are cryptographic techniques that enable proving the validity of a statement
without revealing any additional information.
1. Definition:
o A method to prove a statement (e.g., "I know a secret") is true without disclosing the
actual secret.
o Suppose you solved a hash puzzle and want to prove it. Instead of revealing the
solution (x), a zero-knowledge proof allows you to demonstrate that a solution exists
without revealing x.
3. Key Properties:
o Completeness: If the statement is true, the verifier will accept the proof.
o Soundness: If the statement is false, the verifier will reject the proof.
o Zero-Knowledge: The proof does not reveal any information beyond the validity of
the statement.
4. Applications in Cryptocurrency:
o Form the foundation of more advanced privacy protocols like zk-SNARKs (used in
Zerocash).
5. Benefits:
o Enhances privacy by keeping transaction data (e.g., inputs and outputs) hidden.
c) Zerocash
Zerocash is an evolution of the Zerocoin protocol, offering even greater privacy and efficiency by
using advanced cryptographic techniques.
1. Key Features:
o Eliminates the need for a basecoin by enabling all transactions to occur in a zero-
knowledge manner.
2. How It Works:
o All transaction amounts and recipient/sender details are hidden from the public
blockchain.
o The public ledger only records the existence of transactions and cryptographic proofs
that ensure correctness.
5. Applications:
o They validate transactions by ensuring that the digital signatures are correct and that
the outputs being spent have not already been spent.
o New miners start by downloading the entire blockchain from other nodes to obtain
the historical blocks.
o They listen for new blocks and validate them by checking the transactions they
contain and ensuring that the block has a valid nonce.
o Miners collect valid transactions from the pending transaction pool and assemble
them into a new candidate block.
o The candidate block extends the latest block in the blockchain, ensuring that all
included transactions are valid.
4. Find a Valid Nonce
o Miners search for a nonce value that makes the hash of their candidate block satisfy
the network’s difficulty target.
o Once a valid block is found, miners broadcast it to the network as quickly as possible.
o Other miners must verify and accept this block as part of the blockchain. If multiple
miners find valid blocks simultaneously, only one will eventually be accepted as part
of the main chain, depending on the chain’s growth.
o If the miner’s block is accepted into the blockchain, they receive the block reward,
which includes newly minted bitcoins and any transaction fees from the transactions
included in the block.
o This reward serves as an incentive for miners to continue securing and validating the
network.
o Essential for ensuring the Bitcoin network remains secure and operational.
2. Profit-Driven Tasks
o Provides financial incentives for miners to perform the network maintenance tasks
effectively.
By performing these tasks, miners help secure the network, confirm transactions, and maintain the
integrity of the blockchain.
Explanation of CPU Mining, GPU Mining, FPGA Mining, and Mining Hardware
1. CPU Mining:
• Definition: Mining performed using the central processing unit (CPU) of a general-purpose
computer. Early Bitcoin mining relied solely on CPUs, which computed SHA-256 hashes in
software by iterating over different nonces.
• Performance: A high-end CPU could achieve about 20 MH/s (20 million hashes per second),
which became insufficient as Bitcoin’s mining difficulty increased.
• Challenges: CPU mining is no longer profitable due to high difficulty levels and the
introduction of more efficient hardware.
2. GPU Mining:
• Definition: Mining using a graphics processing unit (GPU). GPUs are designed for parallel
computation, making them far more efficient than CPUs for tasks like Bitcoin mining.
• Performance: High-end GPUs could achieve around 200 MH/s, an order of magnitude faster
than CPUs.
• Advantages:
• Disadvantages:
o GPUs consume significant power and generate heat, requiring cooling systems.
• Current Status: GPU mining is largely obsolete for Bitcoin but may still be used for early-
stage altcoins.
3. FPGA Mining:
• Definition: Mining using Field Programmable Gate Arrays (FPGAs), which can be
programmed to perform specific tasks efficiently, like mining Bitcoin.
• Performance: A well-implemented FPGA could achieve 1 GH/s (1 billion hashes per second),
significantly outperforming CPUs and GPUs.
• Advantages:
• Disadvantages:
o Less accessible due to limited availability and the need for specialized knowledge.
o Errors and malfunctions were common when operated beyond their design limits.
• Current Status: FPGA mining was a transitional phase that lasted a few months before
custom ASICs replaced it.
4. Mining Hardware:
o GPUs: More efficient than CPUs but no longer competitive for Bitcoin.
o FPGAs: Specialized but limited in use due to high cost and short lifespan.
Explain the following terms : a) High variance c) Mining pools e)Mining shares b) Pay-per-share
d)pool hopping
a) High Variance
High variance in mining refers to the significant uncertainty and fluctuation in rewards that small
miners face due to the probabilistic nature of finding a valid block. Mining rewards are governed by a
Poisson distribution, and a small miner may experience long periods without finding a block despite
the expected rewards over time. This makes mining akin to gambling, where consistent outcomes are
not guaranteed. For instance, a miner might expect to find one block in 14 months but could go years
without finding any, resulting in financial losses.
b) Pay-Per-Share (PPS)
Pay-per-share is a mining pool reward system where miners are paid a fixed amount for each share
they submit, irrespective of whether the pool finds a valid block. This model shifts all the risk to the
pool manager, ensuring steady payouts for miners. However, it can incentivize dishonest behavior,
such as miners discarding valid blocks, as they receive the same payout for submitting shares.
c) Mining Pools
Mining pools are cooperative groups of miners who combine their computational power to increase
the likelihood of finding a block. In a pool, all miners work together on the same block, and when a
valid block is found, the rewards are distributed among participants based on their contribution to
the pool's effort. The pool manager organizes the pool, distributes tasks, and handles the reward-
sharing process, typically taking a small fee for their service.
d) Pool Hopping
Pool hopping is a strategy used by miners to maximize their earnings by switching between pools
based on their payout structure. For example, miners might initially mine in a proportional pool,
where early shares in a cycle are more valuable, and later switch to a pay-per-share pool to avoid
diminishing returns in the proportional pool. This behavior can destabilize proportional pools and has
led to the development of more complex reward schemes to mitigate such manipulation.
e) Mining Shares
Mining shares are proofs submitted by miners to the pool manager to demonstrate their mining
effort. These are "near-valid" blocks with hashes that meet a lower difficulty target than required for
a valid block. Mining shares help pool managers verify the work done by each miner and distribute
rewards accordingly. Shares serve as a fair way to measure contributions without requiring miners to
find valid blocks individually.