You are on page 1of 45

Mining

Module 6
WHAT IS CONSENSUS?
• By consensus, we mean that a general agreement has
been reached.
• Consider a group of people going to the cinema. If
there is no disagreement on a proposed choice of
film, then a consensus is achieved. If there is
disagreement, the group must have the means to
decide which film to see. In extreme cases, the group
will eventually split.
• In regard to the Ethereum blockchain, the process is
formalized, and reaching consensus means that at
least 66% of the nodes on the network agree on the
global state of the network
WHAT IS A CONSENSUS MECHANISM?
• The term consensus mechanism refers to the entire
stack of protocols, incentives and ideas that allow a
network of nodes to agree on the state of a
blockchain.
• Ethereum uses a proof-of-stake-based consensus
mechanism that derives its crypto-economic security
from a set of rewards and penalties applied to capital
locked by stakers. This incentive structure encourages
individual stakers to operate honest validators,
punishes those who don't, and creates an extremely
high cost to attack the network.
• Then, there is a protocol that governs how honest
validators are selected to propose or validate blocks,
process transactions and vote for their view of the
head of the chain.
TYPES OF CONSENSUS MECHANISMS
• Proof-of-work based
– Like Bitcoin, Ethereum once used a proof-of-work
(PoW) based consensus protocol.
– Block creation
• Miners compete to create new blocks filled with processed
transactions. The winner shares the new block with the rest of the
network and earns some freshly minted ETH. The race is won by the
computer which is able to solve a math puzzle fastest. This produces
the cryptographic link between the current block and the block that
went before. Solving this puzzle is the work in "proof-of-work". The
canonical chain is then determined by a fork-choice rule that selects
the set of blocks that have had the most work done to mine them.
– Security
• The network is kept secure by the fact that you'd need 51% of the
network's computing power to defraud the chain. This would require
such huge investments in equipment and energy; you're likely to
spend more than you'd gain
• Proof-of-stake based
– Ethereum now uses a proof-of-stake (PoS) based consensus
protocol.
– Block creation
• Validators create blocks. One validator is randomly selected in each
slot to be the block proposer. Their consensus client requests a
bundle of transactions as an 'execution payload' from their paired
execution client. They wrap this in consensus data to form a block,
which they send to other nodes on the Ethereum network. This
block production is rewarded in ETH. In rare cases when multiple
possible blocks exist for a single slot, or nodes hear about blocks at
different times, the fork choice algorithm picks the block that forms
the chain with the greatest weight of attestations (where weight is
the number of validators attesting scaled by their ETH balance).
– Security
• A proof-of-stake system is secure crypto-economically because an
attacker attempting to take control of the chain must destroy a
massive amount of ETH. A system of rewards incentivizes individual
stakers to behave honestly, and penalties disincentivize stakers from
acting maliciously
PROOF-OF-STAKE (POS)
• Proof-of-stake underlies certain consensus
mechanisms used by blockchains to achieve
distributed consensus.
• In proof-of-work, miners prove they have capital at
risk by expending energy.
• Ethereum uses proof-of-stake, where validators
explicitly stake capital in the form of ETH into a smart
contract on Ethereum.
• This staked ETH then acts as collateral that can be
destroyed if the validator behaves dishonestly or
lazily.
• The validator is then responsible for checking that
new blocks propagated over the network are valid
and occasionally creating and propagating new
blocks themselves.
• Proof-of-stake comes with a number of improvements to the
now-deprecated proof-of-work system:
• better energy efficiency – there is no need to use lots of
energy on proof-of-work computations
• lower barriers to entry, reduced hardware requirements –
there is no need for elite hardware to stand a chance of
creating new blocks
• reduced centralization risk – proof-of-stake should lead to
more nodes securing the network
• because of the low energy requirement less ETH issuance is
required to incentivize participation
• economic penalties for misbehavior make 51% style attacks
exponentially more costly for an attacker compared to proof-
of-work
• the community can resort to social recovery of an honest
chain if a 51% attack were to overcome the crypto-economic
defenses
VALIDATORS
• To participate as a validator, a user must deposit 32 ETH into the
deposit contract and run three separate pieces of software: an
execution client, a consensus client, and a validator. On
depositing their ETH, the user joins an activation queue that
limits the rate of new validators joining the network. Once
activated, validators receive new blocks from peers on the
Ethereum network. The transactions delivered in the block are
re-executed, and the block signature is checked to ensure the
block is valid. The validator then sends a vote (called an
attestation) in favor of that block across the network.
• Whereas under proof-of-work, the timing of blocks is determined
by the mining difficulty, in proof-of-stake, the tempo is fixed.
Time in proof-of-stake Ethereum is divided into slots (12
seconds) and epochs (32 slots). One validator is randomly
selected to be a block proposer in every slot. This validator is
responsible for creating a new block and sending it out to other
nodes on the network. Also in every slot, a committee of
validators is randomly chosen, whose votes are used to
determine the validity of the block being proposed
HOW A TRANSACTION GETS EXECUTED
IN ETHEREUM POS
• The following provides an end-to-end explanation of how a transaction
gets executed in Ethereum proof-of-stake.
• A user creates and signs a transaction with their private key. This is
usually handled by a wallet or a library such as ether.js, web3js, web3py etc
but under the hood the user is making a request to a node using the
Ethereum JSON-RPC API. The user defines the amount of gas that they are
prepared to pay as a tip to a validator to encourage them to include the
transaction in a block. The tips get paid to the validator while the base
fee gets burned.
• The transaction is submitted to an Ethereum execution client which
verifies its validity. This means ensuring that the sender has enough ETH to
fulfill the transaction and they have signed it with the correct key.
• If the transaction is valid, the execution client adds it to its local
mempool (list of pending transactions) and also broadcasts it to other
nodes over the execution layer gossip network. When other nodes hear
about the transaction they add it to their local mempool too.
• One of the nodes on the network is the block proposer for the current slot,
having previously been selected pseudo-randomly using RANDAO. This
node is responsible for building and broadcasting the next block to be
added to the Ethereum blockchain and updating the global state. The node
is made up of three parts: an execution client, a consensus client and a
validator client. The execution client bundles transactions from the local
mempool into an "execution payload" and executes them locally to
generate a state change. This information is passed to the consensus client
where the execution payload is wrapped as part of a "beacon block" that
also contains information about rewards, penalties, slashings, attestations
etc that enable the network to agree on the sequence of blocks at the head
of the chain.
• Other nodes receive the new beacon block on the consensus layer gossip
network. They pass it to their execution client where the transactions are
re-executed locally to ensure the proposed state change is valid. The
validator client then attests that the block is valid and is the logical next
block in their view of the chain (meaning it builds on the chain with the
greatest weight of attestations as defined in the fork choice rules). The
block is added to the local database in each node that attests to it.
• The transaction can be considered "finalized", i.e., that it can not be
reverted, if it has become part of a chain with a "supermajority link"
between two checkpoints. Checkpoints occur at the start of each epoch
and to have a supermajority link they must both be attested to by 66% of
the total staked ETH on the network
Sybil resistance & chain selection
• Sybil resistance measures how a protocol fares against a Sybil
attack. Sybil attacks are when one user or group pretends to be
many users. Resistance to this type of attack is essential for a
decentralized blockchain and enables miners and validators to
be rewarded equally based on resources put in. Proof-of-work
and proof-of-stake protect against this by making users expend a
lot of energy or put up a lot of collateral. These protections are
an economic deterrent to Sybil attacks.
• A chain selection rule is used to decide which chain is the
"correct" chain. Bitcoin uses the "longest chain" rule, which
means that whichever blockchain is the longest will be the one
the rest of the nodes accept as valid and work with. For proof-
of-work chains, the longest chain is determined by the chain's
total cumulative proof-of-work difficulty. Ethereum used to use
the longest chain rule too; however, now that Ethereum runs on
proof-of-stake it adopted an updated fork-choice algorithm that
measures the 'weight' of the chain. The weight is the
accumulated sum of validator votes, weighted by validator
staked-ether balances.
WHAT IS ETHEREUM MINING?
• Mining is the process of creating a block of transactions to be
added to the Ethereum blockchain.
• The word mining originates in the context of the gold
analogy for cryptocurrencies. Gold or precious metals are
scarce, so are digital tokens, and the only way to increase the
total volume in a proof-of-work system is through mining. In
proof-of-work Ethereum, the only mode of issuance was via
mining. Unlike gold or precious metals however, Ethereum
mining was also the way to secure the network by creating,
verifying, publishing and propagating blocks in the
blockchain.
• Mining ether = Securing the Network
• Mining is the lifeblood of any proof-of-work blockchain.
Ethereum miners - computers running software - used their
time and computation power to process transactions and
produce blocks prior to the transition to proof-of-stake
WHY DO MINERS EXIST?
• In decentralized systems like Ethereum, we need to
ensure that everyone agrees on the order of
transactions. Miners helped this happen by solving
computationally difficult puzzles to produce blocks,
securing the network from attacks.
• Anyone was previously able to mine on the Ethereum
network using their computer. However, not
everyone could mine ether (ETH) profitably. In most
cases, miners had to purchase dedicated computer
hardware, and have access to inexpensive energy
sources. The average computer was unlikely to earn
enough block rewards to cover the associated costs of
mining
Cost of mining
• Potential costs of the hardware necessary to build
and maintain a mining rig
• Electrical cost of powering the mining rig
• If you were mining in a pool, these pools typically
charged a flat % fee of each block generated by
the pool
• Potential cost of equipment to support mining rig
(ventilation, energy monitoring, electrical wiring,
etc.)
HOW ETHEREUM TRANSACTIONS
WERE MINED
• The following provides an overview of how transactions were mined in Ethereum
proof-of-work. An analogous description of this process for Ethereum proof-of-
stake can be found here.
• A user writes and signs a transaction request with the private key of
some account.
• The user broadcasts the transaction request to the entire Ethereum network from
some node.
• Upon hearing about the new transaction request, each node in the Ethereum
network adds the request to their local mempool, a list of all transaction requests
they’ve heard about that have not yet been committed to the blockchain in a
block.
• At some point, a mining node aggregates several dozen or hundred transaction
requests into a potential block, in a way that maximizes the transaction fees they
earn while still staying under the block gas limit. The mining node then:
– Verifies the validity of each transaction request (i.e. no one is trying to transfer ether
out of an account they haven’t produced a signature for, the request is not
malformed, etc.), and then executes the code of the request, altering the state of their
local copy of the EVM. The miner awards the transaction fee for each such transaction
request to their own account.
– Begins the process of producing the proof-of-work “certificate of legitimacy” for the
potential block, once all transaction requests in the block have been verified and
executed on the local EVM copy.
• Eventually, a miner will finish producing a certificate for a block which
includes our specific transaction request. The miner then broadcasts the
completed block, which includes the certificate and a checksum of the
claimed new EVM state.
• Other nodes hear about the new block. They verify the certificate,
execute all transactions on the block themselves (including the
transaction originally broadcasted by our user), and verify that the
checksum of their new EVM state after the execution of all transactions
matches the checksum of the state claimed by the miner’s block. Only
then do these nodes append this block to the tail of their blockchain, and
accept the new EVM state as the canonical state.
• Each node removes all transactions in the new block from their local
mempool of unfulfilled transaction requests.
• New nodes joining the network download all blocks in sequence,
including the block containing our transaction of interest. They initialize a
local EVM copy (which starts as a blank-state EVM), and then go through
the process of executing every transaction in every block on top of their
local EVM copy, verifying state checksums at each block along the way.
• Every transaction is mined (included in a new block and propagated for
the first time) once, but executed and verified by every participant in the
process of advancing the canonical EVM state. This highlights one of the
central mantras of blockchain: Don’t trust, verify
HOW TO SET UP AND RUN AN
ETHEREUM NODE
• Running an Ethereum node consists of running
software with hardware while being connected to
the internet.
• In the early days of the Ethereum network, users
needed to interact with the command-line in order
to operate an Ethereum node.
• Today, users have the option to use DAppNode,
which is free and open-source software providing
users with an app-like experience while managing
their node.
Step 1: Local
or Cloud

Step 2:
Buying
Hardware

Step 3:
Choose
Software

Step 4:
Operating
the Node
• Step 1: Local or Cloud
– Ethereum nodes can be run on personal computers and
don’t require special hardware. Nevertheless, there is
the option to run a node on a cloud server
like QuickNode, Blockdaemon, LunaNode,
or Alchemy. However, for censorship-resistant and
permissionless access to the network, users should not
rely on cloud providers. It’s safer to run your node on
your personal hardware.
• Step 2: Buying Hardware
– Ethereum has been designed in a way that nodes can
be run on personal computers. Nevertheless, it can
make sense to buy dedicated hardware to enhance
your node’s performance.
– -> For the simplest onboarding experience you can
purchase plug-and play-devices to run a node.
Ethereum recommends
the DAppNode solution. Avado is another well-known
provider.
– -> A cheaper and more customizable option
is building or using your own device. Minimum specs
as listed on the Ethereum webpage are:
• 4–8 GB Ram
• 2 TB SSD
• Intel NUC, 7th gen. or higher
• Step 3: Choose Software
– Once the hardware is ready, users can choose different
software options to run their node with.
– Plug and Play: Users having opted for the DAppNode plug-
and-play device can find detailed instructions on how to set
up their device in the Installation Guide and the First Steps
Guide.
– Users running the Ethereum node on their personal
computer or self-built device can choose from at least five
different Ethereum client software options. The vast
majority (>80%) uses Geth software to run their nodes.
– Before installing and starting the software, make sure that:
• There is enough disk space.
• Memory and CPU are not halted by other programs.
• Operating system is updated to the latest version.
• System has the correct time and date.
• The router and firewall accept connections on listening ports. By
default, Ethereum clients use a listener (TCP) port and a discovery
(UDP) port, both on 30303 by default
• Step 4: Operating the Node
– Once your node is up and running, you should
monitor it regularly to ensure it runs properly.
– Keep the node online. It doesn’t have to be online
24/7 but it should be online as much as possible to
stay in sync with the Ethereum network.
– Keep the software updated. This ensures that your
node runs with the latest patches, features, and EIP
updates.
Whisper was a protocol that aimed to deliver secure messaging between
peers without writing any information to the blockchain.

WHISPER PROTOCOL
Whisper
• An application typically needs three kinds of
resources for application services:
– Compute
– Storage
– Messaging
• Ethereum EVM and smart contracts provide
compute, while Swarm/IPFS handles large data
storage and is the decentralized storage layer.
Whisper handles Ethereum messages.
• Whisper is an Ethereum P2P communication
protocol that allows messaging between DApps.
• It provides a simple API that we can use to send
an encrypted message through the Ethereum
blockchain and receive and decrypted messages
with the hash key.
• Whisper is currently at the POC 2 stage and
supports the Geth and Parity clients.
• It can be used for DApps publish-subscribe
coordination signaling and building secure,
untraceable decentralized communication.
Whisper protocol
• Whisper currently uses the ssh protocol string of devp2p. When
sending an encrypted message, the message content can be
encrypted by default either asymmetrically or symmetrically.
• Asymmetric cryptography, also known as public key
cryptography, uses public and private keys to encrypt and
decrypt data. One key is public and it is shared with everyone.
The other is a private key; only the owner can see or access
private key information. When encrypting the Whisper message,
it uses the standard Elliptic Curve Integrated Encryption Scheme
with the SECP-256k1 public key to encrypt a message; the other
key is used for decryption. Symmetric cryptography (also known
as the secret key), on the other hand, uses the hash key with the
AES GCM algorithm with a random 96-bit nonce for both
encryption and decryption. It typically facilitates one-to-many
messages. The sender and receiver use the same symmetric key
to encrypt and decrypt the message.
Whisper envelopes
• Each field in the Whisper envelope contains important
information for the message:
• Version: This can be up to 4 bytes (currently one byte
containing zero) and indicates the encryption method. If
the Version is higher than the current one, the envelope
cannot be decrypted, and therefore can only be forwarded
to the peers.
• Expiry: This is the message expiry time (Unix time in
seconds).
• TTL: This defines the message's time-to-live in seconds.
• Topic: This is 4 bytes of arbitrary data.
• AESNonce: This is used in symmetric encryption and
represents 12 bytes of random data.
• Data: This is encrypted byte array data.
• EnvNonce: This is 8 bytes of arbitrary integer data that's
used for Proof-of- Work (PoW) calculations.
Whisper message
• Envelope's payload has encrypted byte array data; it is the
Whisper message in plain format.
Here is the message's structure:
• [ flags, optional padding, payload, optional signature]
• Let's explain the structure in more detail:
• Flags: There's a single byte for the flag to specify the message
has a signature.
• Padding: This is used to align the message size, and it can
contain random data.
• Signature: This is the signature that's used for sending the
message. It is the ECDSA signature of the Keccak-256 hash of the
unencrypted data.
• Payload: This is the payload of the message.
• Whisper messages are sent to all Whisper nodes with TTL
and PoW consensus to prevent Direct Denial-of-Service (DDoS)
attacks. The nodes pass envelopes around, and only the
receiver who has the private key can read the message.
ROUTING
Overview
• In recent years, there has been an increase in the number of layer 1
and layer 2 networks designed to address Ethereum’s scalability
constraints.
• These solutions have played a vital role in onboarding an increasing
number of users onto the DeFi ecosystem by reducing gas costs
and improving network throughput.
• However, the proliferation of such networks has meant that most of
the action is now fragmented across these networks instead of
being concentrated on a single network such as Ethereum.
• This has resulted in a series of unconnected blockchain ecosystems
operating alongside but siloed from each other, preventing the
industry from reaching its full potential.
• To address this issue, what is required, it seems, is a mechanism
that facilitates interoperability among these networks, i.e., a
mechanism that enables these networks to communicate and
share data with each other.
Router Protocol
• The router is a cross-chain liquidity framework
crude that expects to consistently give spanning
infra between different current and arising layer-1
and layer-2 blockchain solutions, like Matic and
Ethereum.
• Logically, Router intends to work out spanning
infra between numerous different chains in its
guide.
• The router is dedicated to developing the bridging
infrastructure to allow the contract-level data
flow across various blockchains, thus enabling
asset-level data transfer.
Features
Optimal Price for Token Swaps
• The router uses a proprietary pathfinder algorithm to find the optimal
route for cross-chain swaps.
Unified Gas Fees
• Use $ROUTE as a unified gas token for all transfers/swaps on Router
Protocol.
Cross-chain Settlement Engine
• By settling all transactions atomically, Router Protocol ensures user funds
are never blocked.
SDK for Developers
• Leverage Router’s SDK to build complex decentralized applications for a
cross-chain environment.
Multi-chain Token Standard
• Launch and manage multi-chain tokens with a built-in accountability
standard.
Application-specific Blockchain
• Router blockchain will function as a global multi-chain accounting layer.
Architecture
• When coming to its architecture, unlike traditional
deployments of cross-chain protocols, which use
1-to-1 bridges, Router creates a mesh network
where all chains are connected to each other via
the same set of router nodes.
• These nodes can listen to and write transactions
on all blockchains that are part of the Router’s
super mesh.
• Any new chain can therefore be simply plugged
into Router’s super mesh by pushing its relevant
configurations to all the router nodes.
Router’s Architecture
Factors
• Router Protocol is an extensible multi-directional
bridge that connects current and emerging layer 1
and layer 2 blockchains to allow contract-level
data flow across them.
• This could be a token that is locked on the source
chain and redeemed on the target chain or an
operation that is initiated on the source chain and
executed on the target chain.
• Let’s look at what are the important factors you
need to know about Router Protocol
Chains
• These are blockchain networks that are a part of
Router’s liquidity ‘super mesh.’
• The chain where a transaction is initiated is referred to
as the source chain, while the chain where the
transaction is executed is called the target chain.
• During a cross-chain transfer, Router Protocol locks
users’ funds on the source chain and releases them on
the target chain.
• To facilitate these transfers, there are two crucial
specifications associated with each chain:
– Chain ID: A unique 8-bit identifier used to identify a chain.
– Resource ID: A 32-byte identifier used to map actions on the
source chain with actions on the destination chain. For
example, the resource ID is used by Router Protocol to
represent token mappings between different chains.
Bridge Contracts
• Every chain supported by Router Protocol will have a bridge contract
deployed on it.
• On the source chain, the bridge contract locks users’ assets and
broadcasts an event that can be picked up by listeners associated with
Router nodes.
• On the destination chain, the bridge contract aggregates votes from
Router nodes on proposals relayed from the source chain.
• When the voting quorum is achieved, the bridge contract unlocks/mints
tokens on the destination chain.
• Whenever a transaction is submitted on the source chain, a deposit
function is initiated on the bridge contract, which takes in three
parameters: destinationChainID, resourceID, and calldata.
• The bridge contract generates a nonce for every deposit transaction, and
depending on the resourceID, delegates the call to a separate handler
contract.
– Calldata: This field includes the parameters required by the handler. Calldata
differs based on the nature of the transaction, e.g., ERC20 transfer, arbitrary
message passing, etc.
– Deposit Nonce: It is an unsigned 64-bit integer that is generated by
ParaRouters for all cross-chain transfers. All router nodes track a sequential
nonce for all possible target chains.
Fee Manager Module
• With Router, users will have the utmost flexibility in choosing
which token to use for transaction fees. Users can choose
between:
– Native gas token on the source chain (default)
– USDC
– ROUTE (50% concession in transaction fees)
– DFYN (20% concession in transaction fees)
• Router Protocol uses a fee manager module that estimates
the transaction fees every 30–60 minutes depending on the
congestion on different networks.
• This fee manager module is entirely modular and can
support tokens other than the ones mentioned above, giving
users even more flexibility.
• Since Router’s fee manager module is not tightly coupled
with the rest of the code, other projects are welcome to use
it.
Router’s UI
• It is the interface where users can interact with
Router’s bridge contracts. The Router’s UI is
responsible for calling the deposit function on
behalf of the users. It is also responsible for
communicating with the pathfinder algorithm on
the source chain before calling the bridge contract.
Pathfinder Algorithm
• The router uses a proprietary pathfinder algorithm to find
the optimal route to move assets from the source chain to
the destination chain. Pathfinder algorithm is called directly
by Router’s UI and takes in four parameters:
• Chain ID: Instructs the pathfinder to access DEX protocols
on a particular chain. Pathfinder algorithm maintains a list
of DEX contract addresses mapped to each chain ID.
• fromTokenAddress: ERC20 token address of the asset to be
sold.
• toTokenAddress: ERC20 token address of the asset to be
bought.
• Amount: The number of tokens that need to be traded.
• Based on these parameters, the pathfinder creates a JSON
object which includes the optimal route for the swap and
returns it to Router’s UI, which forwards the object to the
bridge contract on the source chain.
Router Nodes
• Router Protocol maintains a set of nodes that listen for events on the
source chain, generate proposals for those events, and submit signed
proposals on the destination chain as a vote.
• For a transfer to be accepted and sent across the bridge, it must receive
enough votes to exceed a predetermined threshold.
• All the bridge contracts maintain a safe list of addresses so that votes
received only from approved router nodes are taken into consideration.
• Each router node runs a Golang chain module that has four components:
– Connector: Responsible for connecting a router node to all chains which are a
part of Router Protocol’s super mesh. A connector is shared by a node’s
listener and writer.
– Listener: Actively observes chain state transitions to listen for initiated
transfers. Whenever a transfer is detected, it constructs a message and passes
it to the router interface. The message has a total of 6 parameters: source
chain ID, destination chain ID, resource ID, transfer type (fungible transfer,
non-fungible transfer or generic transfer), deposit nonce, and payload (data
for the specific transfer).
– Router: Receives constructed messages from listeners and forwards them to
the writer.
– Writer: Responsible for parsing the bridge message into a valid transaction
and submitting it to the destination chain.
Router Nodes
Voting Process
• Once a proposal is created on the destination chain,
other router nodes vote on it by signing the proposal.
• Once the voting threshold is achieved, Router
Protocol’s voting module runs a randomizer function
to select a node to perform the executeProposal call.
• This is done to prevent multiple router nodes from
calling the executeProposal function simultaneously.
• Although unlikely, if the selected node fails to execute
this call, the voting module reruns the randomizer
function, but this time it will exclude the node that
failed to perform this task before.

You might also like