0% found this document useful (0 votes)
57 views72 pages

Etherum Componets

Uploaded by

ledasi2421
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views72 pages

Etherum Componets

Uploaded by

ledasi2421
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 72

Ethereum Blockchain

Ethereum Blockchain
With Ethereum’s state machine, we begin with a “genesis state.” This is analogous
to a blank slate, before any transactions have happened on the network
When transactions are executed, this genesis state transitions into some final
state.
At any point in time, this final state represents the current state of Ethereum.

The state of Ethereum has millions of transactions. These transactions are grouped
into “blocks.” A block contains a series of transactions, and each block is chained
together with its previous block.
Components of the Ethereum ecosystem
• 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 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 web3.js library that allows
interaction with the geth client via the Remote Procedure Call
(RPC) interface.
Ethereum Architecture
Ethereum Architecture

• A formal list of all high-level elements present in the


Ethereum blockchain is presented here:
– Keys and addresses
– Accounts
– Transactions and messages
– Ether crypto currency/tokens
– The EVM
– Smart contracts
Keys and addresses
• Mainly to represent ownership and transfer of Ether. Keys are used in pairs of private
and public type.
• The private key is generated randomly and is kept secret whereas a public key is derived
from the private key.
• Addresses are derived from the public keys which are a 20-bytes code used to identify
accounts.
• The process of key generation and address derivation is described here:
1. A private key is randomly chosen (256 bits positive integer) under the rules defined by
elliptic curve secp256k1 specification (in the range [1, secp256k1n − 1]).
2. The public key is then derived from this private key using ECDSA recovery function.
3. An address is derived from the public key which is the right most 160 bits of the Keccak
hash of the public key.
Example
1.Privatekey: b51928c22782e97cca95c490eb958b06fab7a70b9512c38c36974f47b954ffc2
2.Publickey:
3aa5b8eefd12bdc2d26f1ae348e5f383480877bda6f9e1a47f6a4afb35cf998ab847f1e394
8b1173622dafc6b4ac198c97b18fe1d79f90c9093ab2ff9ad99260
3. Address: 0x77b4b5699827c5c49f73bd16fd5ce3d828c36f32
Accounts
• Accounts are one of the main building blocks of the Ethereum blockchain.
• Ethereum, being a transaction driven state machine, the state is created or
updated as a result of the interaction between accounts and transaction
execution.
• Operations performed between and on the accounts, represent state
transitions. The state transition is achieved using what's called the
Ethereum state transition function, which works as follows:
1. Confirm the transaction validity by checking the syntax, signature validity,
and nonce.
2. The transaction fee is calculated, and the sending address is resolved using
the signature. Furthermore, sender's account balance is checked and
subtracted accordingly, and nonce is incremented. An error is returned if
the account balance is not enough.
Accounts
3. Provide enough Ether (gas price) to cover the cost of the transaction. This
is charged per byte incrementally proportional to the size of the
transaction. here the actual transfer of value occurs.
⮚ The flow is from the sender's account to receiver's account. The account is
created automatically if the destination account specified in the
transaction does not exist yet.
⮚ Moreover, if the destination account is a contract, then the contract code
is executed. This also depends on the amount of gas available.
If enough gas is available, then the contract code will be executed fully;
otherwise, it will run up to the point where it runs out of gas.
4. In case of transaction failure due to insufficient account balance or gas, all
state changes are rolled back except for 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 fee are 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:


1. Externally Owned Accounts (EOAs) : EOAs are similar to accounts
that are controlled by a private key in Bitcoin.
2. Contract Accounts (CAs): the accounts that have code associated
with them along with the private key.

EOAs properties are :


⮚ EOAs has ether balance
⮚ They are capable of sending transactions
⮚ They have no associated code
⮚ They are controlled by private keys
⮚ Accounts contain a key-value store
⮚ They are associated with a human use
Types of accounts

CAs properties are


⮚ CAs have Ether balance.
⮚ They have associated code that is kept in memory/storage on the
blockchain.
⮚ They can get triggered and execute code in response to a
transaction or a message from other contracts. It is worth noting
that due to the Turing completeness property of the Ethereum
blockchain, the code within contract accounts can be of any level
of complexity. The code is executed by Ethereum Virtual Machine
(EVM) by each mining node on the Ethereum network.
⮚ Also, CAs can maintain their permanent state and can call other
contracts. It is envisaged that in the serenity release, the
distinction between externally owned accounts and contract
accounts may be eliminated.
⮚ They are not intrinsically associated with any user or actor on the
blockchain.
⮚ CAs contain a key-value store.
Externally owned accounts vs. contract accounts

• An externally owned account can send messages to other


externally owned accounts OR to other contract accounts by
creating and signing a transaction using its private key.
• A message between two externally owned accounts is simply a value
transfer.
• But a message from an externally owned account to a contract
account activates the contract account’s code, allowing it to perform
various actions (e.g. transfer tokens, write to internal storage, mint
new tokens, perform some calculation, create new contracts, etc.).
• Unlike externally owned accounts, contract accounts can’t initiate
new transactions on their own. Instead, contract accounts can only
fire transactions in response to other transactions they have
received (from an externally owned account or from another
contract account).
Externally owned accounts vs. contract accounts
Transactions and messages

• A transaction in Ethereum is a digitally signed data packet using


a private key that contains the 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:
• Message call transactions: This transaction simply produces a
message call that is used to pass messages from one contract
account to another.
• Contract creation transactions: As the name suggests, these
transactions result in the creation of a new contract account.
This means that when this transaction is executed successfully,
it creates an account with the associated code.
Transaction
Transactions and messages
• Both of these transactions are composed of some standard fields, which
are described here.
• Nonce
✔ Nonce is a number that is incremented by one every time a transaction is
sent by the sender.
✔ It must be equal to the number of transactions sent and is used as a
unique identifier for the transaction.
✔ A nonce value can only be used once. This is used for replay protection on
the network.
• Gas price
✔ The gas price field represents the amount of Wei required to execute
the transaction. In other words, this is the amount of Wei you are willing to
pay for this transaction.
✔ This is charged per unit of gas for all computation costs incurred as a result
of the execution of this transaction
• Wei is the smallest denomination of ether; therefore, it is used to count
ether.
Transactions and messages

• Gas limit
✔ The gas limit field contains the value that represents the maximum
amount of gas that can be consumed to execute the transaction.
✔ it is sufficient to say that this is the amount of fee in ether that a
user (for example, the sender of the transaction) is willing to pay
for computation.
• To
✔ This field is a value that represents the address of the recipient of
the transaction. This is a 20-byte value.
• Value
✔ represents the total number of Wei to be transferred to the
recipient; in the case of a contract account, this represents the
balance that the contract will hold.
• Signature: The signature is based on ECDSA scheme and makes
use of the secp256k1 Elliptic curve
Gas and payment

• With every transaction, a sender sets a gas limit and gas price.
• The product of gas price and gas limit represents the maximum
amount of Wei that the sender is willing to pay for executing a
transaction.
• For example, let’s say the sender sets the gas limit to 50,000 and a
gas price to 20 gwei.
• This implies that the sender is willing to spend at most 50,000 x 20
gwei = 1,000,000,000,000,000 Wei = 0.001 Ether to execute that
transaction.
Transactions and messages

▪ Init: The Init field is used only in transactions that are intended to create
contracts, that is, contract creation transactions.
✔ This represents a byte array of unlimited length that specifies the EVM code
to be used in the account initialization process. The code contained in this
field is executed only once when the account is created for the first time, it
(init) gets destroyed immediately after that.
✔ Init also returns another code section called body, which persists and runs in
response to message calls that the contract account may receive. These
message calls may be sent via a transaction or an internal code execution.
▪ Data: If the transaction is a message call, then the data field is used instead
of init, which represents the input data of the message call. It is also
unlimited in size and is organized as a byte array.
✔ This structure can be visualized in the following diagram, where a transaction
is a tuple of the fields mentioned earlier, which is then included in a
transaction trie (a modified Merkle-Patricia tree) composed of the
transactions to be included.
✔ Finally, the root node of transaction trie is hashed using a Keccak 256-bit
algorithm and is included in the block header along with a list of transactions
in the block.
Transactions and messages
• Transactions can be found in either transaction pools or blocks.
• In transaction pools, they wait for verification by a node or in blocks, they
are added after successful verification.
• When a mining node starts its operation of verifying blocks, it starts with
the highest paying transactions in the transaction pool and executes them
one by one.
• When the gas limit is reached, or no more transactions are left to be
processed in the transaction pool, the mining starts.
• In this process, the block is repeatedly hashed until a valid nonce is found
such that, once hashed with the block, it results in a value less than the
difficulty target.
• Once the block is successfully mined, it will be broadcasted immediately to
the network, claiming success, and will be verified and accepted by the
network.
• This process is similar to Bitcoin's mining process discussed in the previous
chapters, The only difference is that Ethereum's PoW algorithm is ASIC-
resistant, known as Ethash, where finding a nonce requires large memory.
Transactions and messages
Contract creation transaction
• There are a few essential parameters that are required when
creating an account. These parameters are listed as follows:
– Sender
– Original transactor (transaction originator)
– Available gas
– Gas price
– Endowment, which is the amount of ether allocated
– A byte array of an arbitrary length
– Initialization EVM code
– Current depth of the message call/contract-creation stack (current depth
means the number of items that are already there in the stack)
Contract creation transaction

• Addresses generated as a result of contract creation transaction are 160 bit


in length.
• They are the rightmost 160-bits of the Keccak hash of the RLP encoding of
the structure containing only the sender and the nonce.
• Initially, the nonce in the account is set to zero. The balance of the account
is set to the value passed to the contract.
• Storage is also set to empty. Code hash is Keccak 256-bit hash of the empty
string.
• The new account is initialized when the EVM code (the Initialization EVM
code, mentioned earlier) is executed.
• In the case of any exception during code execution, such as not having
enough gas (running Out Of Gas, OOG), the state does not change.
• If the execution is successful, then the account is created after the
payment of appropriate gas costs.
• Since the Ethereum (Homestead) is the result of a contract creation
transaction is either a new contract with its balance or no new contract is
created with no transfer of value.
Message call transaction

• A message call requires several parameters for execution, which


are listed as follows:
– The sender
– The transaction originator
– Recipient
– The account whose code is to be executed (usually same as the recipient)
– Available gas Value
– Gas price
– Arbitrary length byte array
– Input data of the call
– Current depth of the message call/contract creation stack
Message call transaction

• Message calls result in a state transition.


• The message calls also produce output data, which is not used if
transactions are executed.
• In cases where message calls are triggered by VM code, the output
produced by the transaction execution is used.
• message call is the act of passing a message from one account to another.
If the destination account has an associated EVM code, then the virtual
machine will start, upon the receipt of the message to perform the required
operations.
• If the message sender is an autonomous object (external actor), then the
call passes back any data returned from the EVM operation.
• The state is altered by transactions. These are created by external factors
and are signed and then broadcasted to the Ethereum network. Messages
are passed using message calls.
• A description of a message is shown in next slide.
Messages
• Messages are the data and value that are passed between two accounts.
• A message is a data packet passed between two accounts. This data packet
contains data and value (amount of ether).
• It can either be sent via a smart contract (autonomous object) or from an external
actor (externally owned account) in the form of a transaction that has been
digitally signed by the sender.
• Contracts can send messages to other contracts. Messages only exist in the
execution environment and are never stored.
• Messages are similar to transactions; however, the main difference is that they
are produced by the contracts, whereas transactions are produced by entities
external (externally owned accounts) to the Ethereum environment.
• A message consists of the components:
✔ The sender of the message
✔ Recipient of the message
✔ Amount of Wei to transfer and message to the contract address
✔ Optional data field (Input data for the contract)
✔ The maximum amount of gas (start gas) that can be consumed Messages are
generated when CALL or DELEGATECALL opcodes are executed by the code in
execution by the contracts.
Messages
Calls
• A call does not broadcast anything to the blockchain; instead,
it is a local call to a contract function and runs locally on the
node.
• It is almost like a local function call.
• It does not consume any gas as it is a read-only operation.
• It is akin to a dry run or a simulated run.
• Calls are executed locally on a node VM and do not result in
any state change because they are never mined.
• Call basically runs message call transactions in simulated
mode and is available in the web3.js JavaScript API.
Transaction validation and execution
• Transactions are executed after verifying the transactions
for validity. Initial tests are listed as follows:
• A transaction must be well-formed and RLP(Recursive
Length Prefix)-encoded without any additional trailing bytes
• The digital signature used to sign the transaction is valid
Transaction
• nonce must be equal to the sender's account's current
nonce gas limit must not be less than the gas used by the
transaction
• The sender's account contains enough balance to cover the
execution cost.
The transaction substate
• 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.
• 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.
State storage in the Ethereum blockchain
• At a fundamental level, Ethereum blockchain is a transaction and
consensus-driven state machine.
• The state needs to be stored permanently in the blockchain.
• For this purpose, world state, transactions, and transaction receipts are
stored on the blockchain in blocks.
• The world state It is a mapping between Ethereum addresses and account
states. The addresses are 20 bytes (160 bits) long. This mapping is a data
structure that is serialized using Recursive Length Prefix (RLP). RLP is a
specially developed encoding scheme that is used in Ethereum to serialize
binary data for storage or transmission over the network and also to save
the state in a Patricia tree on storage media.
• The RLP function takes an item as an input, which can be a string or a list
of items and produces raw bytes that are suitable for storage and
transmission over the network.
• RLP does not encode data; instead, its primary purpose is to encode
structures.
The account state
• The account state consists of four fields: nonce, balance, storage
root and code hash
• Nonce: This is a value that is incremented every time a transaction
is sent from the address. In case of contract accounts, it represents
the number of contracts created by the account.
• Balance: This value represents the number of Weis which is the
smallest unit of the currency (Ether) in Ethereum held by the
address
• Storage root: This field represents the root node of a Merkle
Patricia tree that encodes the storage contents of the account.
• Code hash: This is an immutable field that contains the hash of the
smart contract code that is associated with the account.
• In the case of normal accounts, this field contains the Keccak 256-
bit hash of an empty string. This code is invoked via a message call.
Transaction receipts
• Transaction receipts are used as a mechanism to store the state after a transaction has been executed.
or these structures are used to record the outcome of the transaction execution. It is produced after the
execution of each transaction.
• All receipts are stored in an index-keyed trie.
• The hash (Keccak 256-bit) of the root of this trie is placed in the block header as the receipts root.
• It is composed of four elements that are described here:
• The post-transaction state: This item is a trie structure that holds the state after the transaction has
been executed. It is encoded as a byte array.
• Gas used: This item represents the total amount of gas used in the block that contains the transaction
receipt. The value is taken immediately after the transaction execution is completed. The total gas used
is expected to be a non-negative integer.
• Set of logs: This field shows the set of log entries created as a result of transaction execution. Log entries
contain the logger's address, a series of log topics, and the log data.
• The bloom filter: A bloom filter is created from the information contained in the set of logs discussed
earlier. A log entry is reduced to a hash of 256 bytes, which is then embedded in the header of the block
as the logs bloom. Log entry is composed of the logger's address, log topics, and log data. Log topics are
encoded as a series of 32-byte data structures. Log data is made up of a few bytes of data. With the
release of Byzantium, an additional field returning the success (1) or failure (0) of the transaction is also
available.
• This process of transaction receipt generation can be visualized in the following diagram: Transaction
receipts and logs bloom As the result of transaction execution process, the state morphs from an initial
state to a target state.
• This state needs to be stored and made available globally in the blockchain
Transaction receipts
Ether crypto currency / tokens
• As an incentive to the miners, Ethereum also rewards its own
native currency called Ether, abbreviated as ETH.
• After the DAO hack, 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.
• ETH, which is the currently the most active and official
Ethereum blockchain.
Ether
• 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.
• Fees are charged for each computation performed by
the EVM on the blockchain
• The denomination table is shown in next slide:
denomination table
The Ethereum Virtual Machine (EVM)
• EVM is an entirely isolated and sandboxed runtime
environment.
• The code that runs on the EVM does not have access to any
external resources, such as a network or filesystem.
• This results in increased security, deterministic execution and
allows untrusted code (anyone can run code) to be run on
Ethereum blockchain.
• As discussed earlier, EVM is a stack-based architecture. EVM is
big-endian by design, and it uses 256-bit wide words.
• This word size allows for Keccak 256-bit hash and ECC
computations.
• There are two types of storage available to contracts and EVM.
The Ethereum Virtual Machine (EVM)
• The first one is called memory, which is a byte array. When a
contract finishes the code execution, the memory is cleared. It
is akin to the concept of RAM.
• The other type is called storage which is permanently stored on
the blockchain. It is a key value store and can be thought of like
a hard disk storage.
• Memory is unlimited but constrained by gas fee requirements.
• The storage associated with the virtual machine is a word
addressable word array that is nonvolatile and is maintained as
part of the system state.
• Keys and value are 32 bytes in size and storage.
• The program code is stored in a virtual read-only memory
(virtual ROM) that is accessible using the CODECOPY
instruction.
The Ethereum Virtual Machine (EVM)
• The CODECOPY instruction is used to copy the program code
into the main memory.
• Initially, all storage and memory are set to zero in the EVM.
• The following diagram shows the design of the EVM where the
virtual ROM stores the program code that is copied into main
memory using CODECOPY.
• The main memory is then read by the EVM by referring to the
program counter and executes instructions step by step.
• The program counter and EVM stack are updated accordingly
with each instruction execution.
The Ethereum Virtual Machine (EVM)

diagram shows an EVM stack on the left side showing that elements are
pushed and popped from the stack. It also shows that a program counter is
maintained which is incremented with instructions being read from main
memory. Main memory gets the program code from virtual ROM / storage via
the CODECOPY instruction.
The Ethereum Virtual Machine (EVM)
• EVM optimization is an active area of research, and recent research has
suggested that EVM can be optimized and tuned to a very fine degree
to achieve high performance.
• Research into the possibility of using WebAssembly (WASM) is
underway already.
• WASM is developed by Google, Mozilla, and Microsoft and is now being
designed as an open standard by the W3C community group.
• WASM aims to be able to run machine code in the browser that will
result in execution at native speed.
• Similarly, the aim of EVM 2.1 is to be able to run the EVM instruction
set (opcodes) natively in CPUs, thus making it faster and efficient.
• Another language called Joyfully Universal Language for (Inline)
Assembly (JULIA) that can compile to various backends such as EVM
and eWASM
Execution environment
• There are some key elements that are required by the execution
environment to execute the code. The key parameters are
provided by the execution agent, for example, a transaction.
These are listed as follows:
✔ System state.
✔ Remaining gas for execution.
✔ The address of the account that owns the executing code.
✔ The address of the sender of the transaction.
✔ The originating address of this execution (it can be different from
the sender).
✔ The gas price of the transaction that initiated the execution.
✔ Input data or transaction data depending on the type of executing
agent. This is a byte array; in the case of a message call, if the
execution agent is a transaction, then the transaction data is
included as input data.
Execution environment
✔ The address of the account that initiated the code execution or
transaction sender.
✔ This is the address of the sender in case the code execution is
initiated by a transaction; otherwise, it is the address of the
account.
✔ The value or transaction value. This is the amount in Wei. If the
execution agent is a transaction, then it is the transaction value.
✔ The code to be executed presented as a byte array that the
iterator function picks up in each execution cycle.
✔ The block header of the current block.
✔ The number of message calls or contract creation transactions
currently in execution. In other words, this is the number of
CALLs or CREATEs currently in execution.
✔ Permission to make modifications to the state.
Execution environment
• The execution environment can be visualized as a tuple of
10 elements, as follows:
Machine state
• Machine state is also maintained internally by the EVM.
• Machine state is updated after each execution cycle of
EVM.
• An iterator function runs in the virtual machine, which
outputs the results of a single cycle of the state machine.
• Machine state is a tuple that consists of the following
elements:
– Available gas
– The program counter, which is a positive integer up to 256
memory contents
– Contents of the stack
– Active number of words in memory
Machine state
• The EVM is designed to handle exceptions and will halt (stop
execution) in case any of the following exceptions occur:
- Not having enough gas required for execution invalid
instructions
- Insufficient stack items
- Invalid destination of jump opcodes
- Invalid stack size (greater than 1024)

• Machine state can be viewed as a tuple shown in the


following diagram:
Machine state
The iterator function
• The iterator function mentioned earlier performs various vital
functions that are used to set the next state of the machine
and eventually the world state.
• These functions include the following:
• It fetches the next instruction from a byte array where the
machine code is stored in the execution environment.
• It adds/removes (PUSH/POP) items from the stack accordingly.
• Gas is reduced according to the gas cost of the
instructions/opcodes.
• It increments the Program Counter (PC).
• The virtual machine is also able to halt in normal conditions if
STOP, SUICIDE, or RETURN Opcodes are encountered during
the execution cycle.
Smart contracts
• This concept is not new, but, with the advent of the
blockchain, interest in this idea was revived, and this is
now an active area of research in the blockchain space.
• History: Smart contracts were first theorized by Nick
Szabo in the late 1990s in an article named
Formalizing and Securing Relationships on Public
Networks.s
• Smart contracts are described by Szabo as follows:
• Generalized definition of a smart contract: A smart
contract is a secure and unstoppable computer
program representing an agreement that is
automatically executable and enforceable.
Smart contracts
• A smart contract is, in fact, a computer program that is written
in a language that a computer or target machine can
understand.
• Also, it encompasses agreements between parties in the form
of business logic.
• Another fundamental idea is that smart contracts are
automatically executed when certain conditions are met.
• They are enforceable, which means that all contractual terms
are executed as defined and expected, even in the presence of
adversaries.
• Enforcement is a broader term that encompasses traditional
enforcement in the form of law, along with the implementation
of specific measures and controls that make it possible to
execute contract terms without requiring any mediation.
Smart contracts
• True smart should work on the principle that code is law, meaning that there is
no need for an arbitrator or a third party to control or influence the execution of
the smart contract. Smart contracts are self enforcing as opposed to legally
enforceable.
• Moreover, they are secure and unstoppable, which means that these computer
programs are required to be designed in such a fashion that they are fault-
tolerant and executable in a reasonable amount of time.
• These programs should be able to execute and maintain a healthy internal
state, even if external factors are unfavorable.
• property of smart contracts ensures that smart contracts produce same output
every time they are executed.
• This deterministic nature of smart contracts is highly desirable in blockchain
platforms due to consistent consensus requirements.
• This property will allow a smart contract to be run by any node on a network
and achieve the same result.
• This means that smart contracts are not really smart, they are simply doing
what they are programmed to do.
• A smart contract has the following four properties: 1. Automatically executable
2.Enforceable 3. Semantically sound 4. Secure and unstoppable
Smart contracts
• "A smart contract is an electronic transaction protocol that
executes the terms of a contract.
• The general objectives are to satisfy common contractual
conditions (such as payment terms, liens, confidentiality, and
even enforcement), minimize exceptions both malicious and
accidental, and minimize the need for trusted intermediaries.
Related economic goals include lowering fraud loss,
arbitrations and enforcement costs, and other transaction
costs.“
• This idea of smart contracts was implemented in a limited
fashion in Bitcoin in 2009, where Bitcoin transactions using a
limited scripting language can be used to transfer value
between users, over a peer-to-peer network where users do
not necessarily trust each other, and there is no need for a
trusted intermediary.
Smart contracts
• It is sufficient to say here that Ethereum supports the
development of smart contracts that run on the EVM.
• Different languages can be used to build smart contracts.
• there are also various contracts that are available in the
precompiled format in Ethereum blockchain to support
different functions.
• These contracts, known as precompiled contracts or native
contracts .
• These are not strictly smart contracts in the sense of user
programmed solidity smart contracts, but in fact are functions
that are available natively on the blockchain to support various
computationally intensive tasks.
• They run on the local node and are coded within the Ethereum
client, for example, parity or geth.
Native contracts
• Native contracts There are eight precompiled contracts in
Ethereum Byzantium release. Here is the list of these contracts
and details:
• The elliptic curve public key recovery function: ECDSARECOVER
(Elliptic Curve DSA Recover function) is available at address 0x1.
• It is denoted as ECREC and requires 3,000 gas fees for execution.
• If the signature is invalid, then no output is returned by this
function.Public key recovery is a standard mechanism by which
the public key can be derived from the private key in elliptic
curve cryptography.
• The ECDSA recovery function : ECDSARECOVER (H, V, R, S) = Public Key
• It takes four inputs: H, which is a 32-byte hash of the message to
be signed and V, R, and S, which represent the ECDSA signature
with the recovery ID and produce a 64-byte public key.
Native contracts
• The SHA-256-bit hash function: The SHA-256-bit hash function
is a precompiled contract that is available at address 0x2 and
produces a SHA256 hash of the input.
• The gas requirement for SHA-256 (SHA256) depends on the
input data size. The output is a 32-byte value.
• The RIPEMD-160-bit hash function: The RIPEMD-160-bit hash
function is used to provide RIPEMD 160-bit hash and is
available at address 0x3.
• The output of this function is a 20-byte value.
• The gas requirement, similar to SHA-256, is dependent on the
amount of input data.
Native contracts
• The identity/datacopy function: The identity function is available at
address 0x4 and is denoted by the ID.
• It simply defines output as input; in other words, whatever input is
given to the ID function, it will output the same value.
• The gas requirement is calculated by a simple formula: 15 + 3
[Id/32] where Id is the input data.
• This means that at a high level, the gas requirement is dependent
on the size of the input data albeit with some calculation
performed, as shown in the preceding equation.
• Big mod exponentiation function: This function implements a
native big integer exponential modular operation.
• This functionality allows for RSA signature verification and other
cryptographic operations. This is available at address 0x05.
• Elliptic Curve (EC) point addition function: This is the
implementation of the same EC point addition function. This
contract is available at address 0x06.
Native contracts
• Elliptic Curve (EC) scalar multiplication: EC multiplication
(point doubling)
• This is the implementation of the same EC point multiplication
function. Both EC addition and doubling functions allow for ZK-
SNARKS and implementation of other cryptographic
constructs.
• This contract is available at 0x07.
• Elliptic Curve (EC) pairing: EC pairing functionality allows for
performing EC pairing (bilinear maps) operations which
enables ZKSNARKS verification.
• This contract is available at address 0x08. All the
aforementioned precompiled contracts can potentially
become native extensions and can be included in the EVM
opcodes in the future.
SC-Solidity
Solidity issues
1. Unchecked External Call
• This is a major solidity issue.
The most commonly used
function is the transfer
function that can send Ether to
any external account.
• But there are other ways to do it as well. you can use the call() and send()
function to do it as well.
• developers use the call() function for more external calls.
• Unfortunately, the send and call function will only return a Boolean value
which will tell you whether the call was successful or not.
• But if these functions face any exceptions, in which case they can’t perform
the task, they only return a false value rather than reverting.
• So, if you don’t check the return value, you won’t know if the transaction
was a success or not.
• The developer may just expect to get a revert rather than check the value.
• Thus, it’s completely necessary to check the return value of unsuccessful
transfers.
Solidity issues

2. Reentrancy
• In reality, Ethereum smart
contracts come with a special
feature that can call or even use
codes from other external contracts.
• Typically, contracts use Ether and send Ether to other external contract
addresses.
• However, to perform all of these functions, the contract needs to use
an external call.
• Actually, these external calls don’t have adequate safety features;
thus, the hacker can attack these codes and ensure to execute more
tasks with the contract calling it.
• Therefore, the code can re-enter the contract, misuse the
information, or even send tokens to other addresses.
• In reality, this is exactly what happened in the DAO attack. Mainly this
attack can happen when you send Ether to an unknown contract.
Solidity issues
• The attacker can create a malicious program in an external
address, and this will introduce the fallback function.
• Therefore, when a contract sends any amount of Ether to that
address, it will start the malicious program.
• Fallback function is a special function available to a contract. It
has following features −
• It is called when a non-existent function is called on the contract.
• It is required to be marked external.
• It has no name and no arguments
• It can not return any thing.
• It can be defined one per contract.
• If not marked payable, it will throw exception if contract
receives plain ether without data.
Solidity issues

• 3. Costly Loops and Gas Limit


• The costly loops problem. As you
already know that computational
power in the Ethereum blockchain is
not for free.
• You need to pay Ether to buy Gas in order to get the amount of Computational
power for your transaction to execute.
• So, if you can somehow reduce the number of computational steps, it will also save
time and even save you a lot of money.
• Adding loops into the program is one way to increasing the costs. In reality, an array
already comes with a lot of loops. However, if the elements increase, more
integration is required to complete that specific loop.
• So, if an attacker can include infinite loops, he/she can single-handedly exhaust all
available Ethereum Gas.
• In this case, the attacker can influence the elements of the array length, which will
create a DOS issue and won’t allow the system to jump out of the loop.
• It will ensure that the contract is stalled as every contract comes with a Gas limit.
• Even though this solidity issue is not as prominent as other issues, more than 8%
of smart contracts seem to have this problem.
Solidity issues

4. Clearing Mappings
• Clearing mappings is a huge solidity
issue due to having some limitations
of this programing language.
• In reality, the Solidity type mapping offers a key-value data structure,
which is storage-only for blockchain platforms.
• Thus, it will not track all the keys with a value other than zero.
• you can’t clean a mapping without adding any extra informationt,.
• In a dynamic storage array, if you want to use Mapping as the base type, if
you delete or even pop the array, that won’t affect the Mapping.
• More so, if you use Mapping in a struct’s member field as a type in a
dynamic storage array, here the Mapping will also be ignored even if you
delete the array.
Solidity issues

5. Arithmetic Precision
• Solidity does not support any floating-
or fixed-point numbers.
Therefore, to represent these floating points ,
you need to use an integer type in the Solidity.
• In reality, many developers can make errors or
create loopholes if they can’t implement this correctly.
• Therefore, developers need to implement their very own fixed-point data type
using the standard integer data type.
• This process is not easy and quite complex and can pose a lot of problems if not
pulled off correctly.
• More so, the 256 bits Ethereum Virtual Machine can create a lot of issues for the
data types as types shorter than 32 bytes are assembled together into the 32
bytes slot.
• Therefore, it affects the precision of any calculations as you can’t expect a proper
rounding when you perform any division before multiplication.
Solidity issues

• 6.Unexpected Ether
• Usually, when you are sending Ether to an
address, it needs to execute the fallback
function or other functions needed for the
contract.
• However, there are certain exceptions to these rules. In this case, the Ether can
stay in the contract without executing any code.
• Thus, contracts that rely on programs for every single Ether transaction are
vulnerable because it can send Ether forcibly to another contract.
• Typically, there are 2 ways one can send Ether forcibly to another contract, and it
will not use any payable function for that.
• In most cases, the blockchain developers don’t realize that you can accept or
even obtain Ether via other means aside from the payable function.
• It can lead to contracts having a false Ether balance, and it will lead to
vulnerability.
• It’s best to check the current Ether stored in the contract when before calling
any functions
Solidity issues

• 7. Relying on tx.origin
• tx.origin is another one of the issues with
Solidity.
• This one is a global variable and will scan
the call stack and give you the
address of the account that sent the transaction.
• The problem is that if you use this variable for authentication purposes, it can make your smart
contracts vulnerable.
Therefore, there is a heavy chance that your contract will face a phishing attack.
Basically, the attacker can trick the user into using the tx.origin variable to authenticate the
attacker to the contract.
• Here, the attacker can hide the function withdrawAll() within the tx.origin variable and create a
malicious code for the phishable cont ract.
• Usually, the attacker will deploy the code and convince the user to send some Ether to this
contract.
• The user will think that it’s a typical authentication contract and will send the Ether to the
contract (attackers address disguised within the contract).
• Thus, once the victim does that, it will invoke a fallback function which will call the withdrawAll()
function.
• As a result, all the funds from the victim will go to the attacker’s address.
• Thus, users should not depend on tx.origin for authentication purpose only as it’s one of the
major blockchain risks.
Solidity issues
8. Default Visibilities
• In Solidity, the functions have visibility to the public
unless you are assigning how anyone can call that function.
• Therefore, the visibility can determine who can call the function – external users,
derived contracts, internal users, etc.
• Any function which is default to public viewing can be called by users externally.
• In reality, many times, the developers tend to use incorrect specifiers, which will
severely damage the integrity of the smart contract.
• As the default is public, so always make sure to specify the visibility if you want to
change it.
• For example, if you are offering a reward to users who can perform a certain task
make sure to keep the visibility of the function private.
• If it’s public, then any user can just see the function and call it and take the reward
without performing any single task.
• It’s really easy to misuse this type of blockchain security concerns as many
newcomers don’t understand the concept fully.
• Therefore, it can become one of the dangerous solidity security issues if not checked
in time.
Solidity issues

• 9. Overflow and Underflow


• one of the prominent solidity security issues.
• In reality, Ethereum Virtual Machine can
only support a fixed size for integer data types.
So, blockchain professionals can only use a certain range of number to represent an
integer variable.
For example, in unit8, you can only store values from [0,255]. So, here, if you want to
store 256, you will only get 0 as a result.
Thus, using variables in Solidity needs to take precautions as attackers can exploit this
issue.
Typically, the underflow or overflow issues happen when you are trying to store a
value that is out of the data type’s range.
• In reality, an underflow issue occurs when you are trying to subtract 1 from a unit8
variable that had 0 as the initial value. In this case, it will only return the number 255.
• On the other hand, if you are trying to add a value that is larger than the data type’s
range will create an overflow issue.
• So, if you are adding 257 to a unit8 0 value, it will give you a result of 1. it can create
vulnerabilities, and attackers can use it to misuse the code and even create
unexpected logic that results in an infinite loop.
Solidity issues

• 10. Timestamp Manipulation


• In reality, blockchain timestamps are one of the most important elements in
blockchain applications.
• You can use it for various purposes, for example, locking funds, setting a timer for
funds to be released, entropy for numbers, state-changing conditions and so on.
• However, a miner has the freedom to change the timestamp, which is risky if
they’re using it incorrectly in the smart contract.
• In times of any rewards, with the use of enough Ether in the contract, the miner
can change the timestamp and win the reward along with the pooled Ether.
Obviously, it’s not a fair trade.

You might also like