0% found this document useful (0 votes)
63 views19 pages

Wallets of Ethereum

An Ethereum Wallet is a software application that enables users to manage their Ethereum accounts, allowing for transactions and interactions with smart contracts. It relies on private keys for security, which are essential for accessing funds and creating Ethereum addresses. The document outlines two types of Ethereum accounts, methods to create wallet addresses from private keys, and the importance of private keys in the Ethereum network.

Uploaded by

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

Wallets of Ethereum

An Ethereum Wallet is a software application that enables users to manage their Ethereum accounts, allowing for transactions and interactions with smart contracts. It relies on private keys for security, which are essential for accessing funds and creating Ethereum addresses. The document outlines two types of Ethereum accounts, methods to create wallet addresses from private keys, and the importance of private keys in the Ethereum network.

Uploaded by

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

An Ethereum Wallet is a type of software application that allows users to

interact with their Ethereum Account on the Ethereum Network or the


Ethereum Blockchain. Ethereum Wallets are controlled through a password
or a private key that allows users to send or receive funds or transactions
within the wallet. These private keys are only available to the owner of the
wallet due to privacy as anyone who knows the private key can access the
wallet and hence also access their funds. Ethereum Accounts are used to
create smart contracts, interact with decentralized applications, and are used
to run applications smoothly without any fraud, downtime, or third-party
interference. There are two types of Ethereum accounts:
1. Externally Owned Account: Externally Owned Accounts also known
as EOA are accounts that don’t have a Smart Contract code. EOA’s have
a private key, which means that the user has control over access to funds
or contracts. Only Externally Created Accounts can initiate transactions.
You can make an ETH transfer or payment by signing transactions with a
private key.
2. Contract Account: Contract Accounts have Smart Contract Codes
which Externally Owned Accounts don’t have. Contract Accounts don’t
have their own private key and are controlled by their smart contract
code. These accounts can only be activated by sending Ethereum (ETH)
into them. These accounts cannot initiate transactions because they don’t
have a private key.
There are many types of Wallets like MetaMask, Atomic Wallet, Electrum
Wallet, MyEtherWallet, CoinBase, etc.

What is the Ethereum Wallet Address?

Ethereum Wallet Address is a distinct alphanumeric crypto identifier that


contains 42 hexadecimal characters that start with 0x and is followed by a
series of 40 random characters which can send transactions and has a
balance in it.
 For example, 0xdB055877e6c13b6A6B25aBcAA29B393777dD0a73 is
a type of Ethereum address.
 The unique address is required to receive funds from another
cryptocurrency network and to access it, you should have your own
private key.
 In order to access your private key, you must have your own wallet
such as MetaMask, CoinBase, or TrezorOne to name a few.

What is a Private Key?

A private key is a secure and secret number that helps users to secure their
digital money and also allows them to make transactions and generate the
receiving addresses.
 It is an integral part of the Ethereum Network as this secret number
acts as a secure password that protects the user from unauthorized
access to their funds.

 A private key provides a very high level of security as it can take years
and years to crack a private key.
 The private key is only known to the user and is used to carry out any
cryptocurrency transaction from their account.
 Private keys can derive public keys and hence public keys can derive
Ethereum addresses but the same cannot be said for vice-versa as it is
not possible to derive public keys from Ethereum addresses and private
keys from public keys.

Why do we Need a Private Key?

There are several reasons why a private key is required:


 Private keys are secure codes and are not meant to be given to
anyone but users need a method by which they can allow other users to
find their assets and vice-versa.
 As a result, we use Ethereum addresses that are derived from private
keys which we can share with other users to know our cryptocurrency
assets and balance.
 To create an Ethereum address, we need a public key which is derived
from a private key.

Prerequisites

1. Node.js: Follow the installation steps for Node.js .


2. Microsoft Visual Studio Code: Follow the installation steps for Visual
Studio Code. After installing the visual studio code, follow the steps below to
install the CodeRunner extension.
 Now open Visual Studio Code and Go to Extensions (Ctrl + Shift + X).
 Search CodeRunner and install it.
Hence, the prerequisites that we needed are successfully installed and now
we are ready to create our Ethereum Wallet Address from a private key.
There are 2 methods to create an Ethereum wallet address from a
private key:
1. Using Elliptic Curve Digital Signature Algorithm (ECDSA).
2. By installing Node.js Packages.

Method 1: Using Elliptic Curve Digital Signature Algorithm


(ECDSA).

An Elliptic curve is a curve that is defined by the equation y2 = x3 + ax + b.


Elliptic curve cryptography is a form of public key cryptography which is
based on the algebraic structure of elliptic curves over infinite fields. There
are many such curves for different types of cryptocurrencies that are widely
used in the world. Ethereum uses the secp256k1 curve. This is the special
feature of ECDSA that we can derive the public key from the private key. We
need to apply ECDSA to our private key to get the 64-byte integer in which
the first 32 integers represent X and the other 32 integers represent Y on the
elliptic curve.
Below are the steps to create an Ethereum wallet address from a private key:
Step 1: Convert the private key to hexadecimal format.
The first step is to convert our private key into a hexadecimal format. Let’s
consider a private key to understand why a private key is converted to
hexadecimal format:
Private
Key: 996094132110262171918484876014596509006094617146853067801
98554267270848908445
A private key can be selected randomly in the range of values ranging from 1
to 2^256-1. The computer understands the binary language that is 0 and 1,
and our private key is in a decimal format so there is a need to represent the
private key in terms of bits and bytes. Decimal numbers have a base of 10
whereas binary numbers have a base of 2. For example, 78 is in decimal
format. Let’s convert 78 into binary by the following steps:
Divide (78)10 successively by 2 until the quotient is 0:
78/2 = 39, remainder = 0
39/2 = 19, remainder = 1
19/2 = 9, remainder = 1
9/2 = 4, remainder = 1
4/2 = 2, remainder = 0
2/2 = 1, remainder = 0
1/2 = 0, remainder = 1
Read from the bottom (MSB) to top (LSB) and hence we get 1001110 which
is 78 in binary format.
Now, if we convert the private key into a binary format it will become very
large. So instead of converting this private key into binary, computers
generally convert this into a hexadecimal format which has a base of 16.
Hexadecimal numbers are represented by only 16 symbols and use
ABCDEF to represent 10 to 15. The private key in hexadecimal format can
be written as:
Private key in decimal
format: 996094132110262171918484876014596509006094617146853067
80198554267270848908445
Private key in hexadecimal
format: DC38EE117CAE37750EB1ECC5CFD3DE8E85963B481B93E732C
5D0CB66EE6B0C9D
To convert the private key (hexadecimal format) to Ethereum wallet address
Javascript will be used for the implementation.
Step 2: Install packages for implementation.
A. Create a node project: Open the terminal in Visual Studio Code and type
the following command in the terminal to create a node project:
npm init –y
B. Install ethereumjs-wallet: Type the below command to install the
ethereumjs-wallet package, which is a library that allows you to interact with
an Ethereum wallet.
npm install –save ethereumjs-wallet
C. Install Keccak-256 and SHA-3 package: To install the Keccak-256 and
SHA-3 packages type the below command in the terminal:
npm i keccak
npm install js-sha3
Ethereum uses Keccak-256 cryptographic hash function in a consensus
engine known as Ethash. It is a version of Secure Hash Algorithm Version 3
or SHA-3.
 It can be used for transparency, scam-less authentication, encryption,
and pseudo-random number generation.
 After getting the public key, the Keccak-256 hash function is applied
and Ethereum Address is obtained.
 In order to derive the address from the public key, apply the Keccak-
256 to the key and then take the last 20 bytes of the address.
 Keccak-256 returns a 32-byte array.
Step 3: Implementation.
Below is the implementation of the above approach:

 Javascript

const EC = require('elliptic').ec;

const BN = require('bn.js')

// Apply the Keccak-256 hash function

const keccak256 = require('js-sha3').keccak256;

// Elliptic Curve used by Ethereum that is secp526k1

const ec = new EC('secp256k1');

const SK = new BN('DC38EE117CAE37750EB1ECC5CFD3DE8E85963B481B93E732C5D0CB66EE6B0C9D', 16

// Elliptic Curve Generator Point

const G = ec.g;

// Public Point Elliptic Curve Multiplication


const pp = G.mul(SK);

// The first 32 bits representing point x

const x = pp.getX().toBuffer();

// The last 32 bits representing point y

const y = pp.getY().toBuffer();

// Concatenation of the 64 bit of Elliptic Curve Multiplication

const bt = Buffer.concat([x,y])

// Here we are doing keccak256 hashing of our ECDSA public key

const kc = keccak256(bt)

// Here we will be doing two things

// First we will get the hex format of our Keccak-256 hash

// Secondly we will obtain the right most 160 bits

const ethereumAddress = Buffer.from((kc, 'hex').slice(-20).toString('hex'))

console.log('Address is', ethereumAddress);

Output:
Address is c5ed5d9b9c957be2baa01c16310aa4d1f8bc8e6f
Step 4: After getting the output, just add 0x at the start of the address and
your Ethereum Wallet Address is ready.
0xc5ed5d9b9c957be2baa01c16310aa4d1f8bc8e6f
Explanation:
 The code starts by creating a new EC object.
 This is an elliptic curve that secp256k1 uses.
 The EC object is then used to create a BN object called SK, which has
16 bytes of entropy.
 The code then creates a G object that is initialized with ec curve’s
generator point (G=ec.g).
 The code then multiplies this private key by G, which is ec’s
multiplication function for Elliptic Curve Groups (ECG).
 Then x and y are created from pp using getX() and getY().
 Then, it gets x and y from G’s mul function which returns two value on
the curve: X and Y
 Then bt is created as an array of bytes that contains x and y and are
then concatenated into one buffer using Buffer.concat().
 Now, keccak256 is used to hash this buffer to get kc as its result.
 Finally, ethereumAddress is created by taking kc and converting it into
hexadecimal string format before returning it to display in the console
window.
 The code above will then concatenate the hex string representation of
the keccak256 hash to a buffer and return it as an Ethereum address.
 The code is a simple example of how to create an Ethereum Address.

Method 2: By Installing Node.js packages.

There is also another method of deriving the Ethereum address from a


private key. Also, this method is simpler than the previous one.
Step 1: Installing the packages.
A. Type the following code in the terminal. It will create a node project in
Visual Studio Code.
npm init –y
B. After this, type the following code in your terminal. The following code
installs the ethereumjs-wallet package, which is a library that allows you to
interact with an Ethereum wallet.
npm install –save ethereumjs-wallet
C. Open Visual Studio Code and type the following code in your terminal.
The package will create a new public and private key pair.
npm install ethereum-private-key-to-public-key
D. After installing the above package, type the following code in your
terminal. The package will be used to convert a public key into an Ethereum
address.
npm install ethereum-public-key-to-address
Step 2: Implementation.
1. Import the privateKeyToPublicKey module.
2. Apply console.log in order to get the output.
Below is the implementation of the above approach to convert the private key
to the public key:

 Javascript

const privateKeyToPublicKey = require('ethereum-private-key-to-public-key')

console.log(privateKeyToPublicKey(Buffer.from(

'4f3edf983ac986a65a342ce7c78d9ac076d3b113bce9c46f30d7d25171b32b1d',

'hex')).toString('hex'))

Output:
04c1573f1528638ae14cbe04a74e6583c5562d59214223762c1a11121e2461
9cbc09d27a7a1cb989dd801cc028dd8225f8e2d2fd57d852b5bf697112f69b62
29d1
After getting the public key, import the publicKeyToAddress module and
again apply console.log in order to get the address.

 Javascript

const publicKeyToAddress = require('ethereum-public-key-to-address')

console.log(publicKeyToAddress(Buffer.from(

'04c1573f1528638ae14cbe04a74e6583c5562d59214223762c1a11121e24619cbc09d27a7a1cb989dd801cc

'hex')))

Output:
0xAf3CD5c36B97E9c28c263dC4639c6d7d53303A13
Explanation:
 The first code starts by requiring the privateKeyToPublicKey module.
 The code then uses that module to convert a private key into its
corresponding public key.
 The first line of the program is
console.log(privateKeyToPublicKey(Buffer.from(‘4f3edf983ac636a65a842
ce7c78d9aa706d3b113bce9c46f30d7d21715b23b1d’,’hex’)).toString(‘hex’
)) which converts the private key to public key.
 Step 3 starts by requiring the publicKeyToAddress function.
 This function takes a public key and returns an address for it.
 The code then prints out the result of calling this function with the hex
string
04c1573f1528638ae14cbe04a74e6583c5562d59214223762c1a11121e2
4619cbc09d27a7a1cb989dd801cc028dd8225f8e2d2fd57d852b5bf697112
f69b6229d1
 The code generates an address for the public key of
04c1573f1528638ae14cbe04a74e6583c5562d59214223762c1a11121e2
4619cbc09d27a7a1cb989dd801cc028dd8225f8e2d2fd57d852b5bf697112
f69b6229d1
 The code is a method that takes in a private key and returns the
address of the corresponding Ethereum
Smart Contract (or cryptocontract) is a computer program that directly and
automatically controls the transfer of digital assets between the parties under
certain conditions. A smart contract works in the same way as a traditional
contract while also automatically enforcing the contract. Smart contracts are
programs that execute exactly as they are set up(coded, programmed) by
their creators. Just like a traditional contract is enforceable by law, smart
contracts are enforceable by code.
 The bitcoin network was the first to use some sort of smart contract by
using them to transfer value from one person to another.
 The smart contract involved employs basic conditions like checking if
the amount of value to transfer is actually available in the sender
account.
 Later, the Ethereum platform emerged which was considered more
powerful, precisely because the developers/programmers could make
custom contracts in a Turing-complete language.
 It is to be noted that the contracts written in the case of the bitcoin
network were written in a Turing-incomplete language, restricting the
potential of smart contracts implementation in the bitcoin network.
 There are some common smart contract platforms like Ethereum,
Solana, Polkadot, Hyperledger fabric, etc.
History:
In 1994, Nick Szabo, a legal scholar, and a cryptographer recognized the
application of a decentralized ledger for smart contracts. He theorized that
these contracts could be written in code which can be stored and replicated
on the system and supervised by the network of computers that constitute
the blockchain. These smart contracts could also help in transferring digital
assets between the parties under certain conditions.
Features of Smart Contracts
The following are some essential characteristics of a smart contract:
1. Distributed: Everyone on the network is guaranteed to have a copy of
all the conditions of the smart contract and they cannot be changed by
one of the parties. A smart contract is replicated and distributed by all the
nodes connected to the network.
2. Deterministic: Smart contracts can only perform functions for which
they are designed only when the required conditions are met. The final
outcome will not vary, no matter who executes the smart contract.
3. Immutable: Once deployed smart contract cannot be changed, it can
only be removed as long as the functionality is implemented previously.
4. Autonomy: There is no third party involved. The contract is made by
you and shared between the parties. No intermediaries are involved
which minimizes bullying and grants full authority to the dealing parties.
Also, the smart contract is maintained and executed by all the nodes on
the network, thus removing all the controlling power from any one party’s
hand.
5. Customizable: Smart contracts have the ability for modification or we
can say customization before being launched to do what the user wants it
to do.
6. Transparent: Smart contracts are always stored on a public
distributed ledger called blockchain due to which the code is visible to
everyone, whether or not they are participants in the smart contract.
7. Trustless: These are not required by third parties to verify the integrity
of the process or to check whether the required conditions are met.
8. Self-verifying: These are self-verifying due to automated possibilities.
9. Self-enforcing: These are self-enforcing when the conditions and
rules are met at all stages.

Capabilities of Smart Contracts

1. Accuracy: Smart contracts are accurate to the limit a programmer has


accurately coded them for execution.
2. Automation: Smart contracts can automate the tasks/ processes that
are done manually.
3. Speed: Smart contracts use software code to automate tasks, thereby
reducing the time it takes to maneuver through all the human interaction-
related processes. Because everything is coded, the time taken to do all
the work is the time taken for the code in the smart contract to execute.
4. Backup: Every node in the blockchain maintains the shared ledger,
providing probably the best backup facility.
5. Security: Cryptography can make sure that the assets are safe and
sound. Even if someone breaks the encryption, the hacker will have to
modify all the blocks that come after the block which has been modified.
Please note that this is a highly difficult and computation-intensive task
and is practically impossible for a small or medium-sized organization to
do.
6. Savings: Smart contracts save money as they eliminate the presence
of intermediaries in the process. Also, the money spent on the paperwork
is minimal to zero.
7. Manages information: Smart contract manages users’ agreement,
and stores information about an application like domain registration,
membership records, etc.
8. Multi-signature accounts: Smart contracts support multi-signature
accounts to distribute funds as soon as all the parties involved confirm the
agreement.
How Do Smart Contracts Work?

A smart contract is just a digital contract with the security coding of the
blockchain.
 It has details and permissions written in code that require an exact
sequence of events to take place to trigger the agreement of the terms
mentioned in the smart contract.
 It can also include the time constraints that can introduce deadlines in
the contract.
 Every smart contract has its address in the blockchain. The contract
can be interacted with by using its address presuming the contract has
been broadcasted on the network.
The idea behind smart contracts is pretty simple. They are executed on a
basis of simple logic, IF-THEN for example:
 IF you send object A, THEN the sum (of money, in cryptocurrency) will
be transferred to you.
 IF you transfer a certain amount of digital assets (cryptocurrency, for
example, ether, bitcoin), THEN the A object will be transferred to you.
 IF I finish the work, THEN the digital assets mentioned in the contract
will be transferred to me.
Note: The WHEN constraint can be added to include the time factor in the
smart contracts. It can be seen that these smart contracts help set conditions
that have to be fulfilled for the terms of the contract agreement to be
executed. There is no limit on how much IF or THEN you can include in your
intelligent contract.
Smart Contract Working
 Identify Agreement: Multiple parties identify the cooperative
opportunity and desired outcomes and agreements could include
business processes, asset swaps, etc.
 Set conditions: Smart contracts could be initiated by parties
themselves or when certain conditions are met like financial market
indices, events like GPS locations, etc.
 Code business logic: A computer program is written that will be
executed automatically when the conditional parameters are met.
 Encryption and blockchain technology: Encryption provides secure
authentication and transfer of messages between parties relating to smart
contracts.
 Execution and processing: In blockchain iteration, whenever
consensus is reached between the parties regarding authentication and
verification then the code is executed and the outcomes are memorialized
for compliance and verification.
 Network updates: After smart contracts are executed, all the nodes
on the network update their ledger to reflect the new state. Once the
record is posted and verified on the blockchain network, it cannot be
modified, it is in append mode only.

Applications of Smart Contracts

1. Real Estate: Reduce money paid to the middleman and distribute


between the parties actually involved. For example, a smart contract to
transfer ownership of an apartment once a certain amount of resources
have been transferred to the seller’s account(or wallet).
2. Vehicle ownership: A smart contract can be deployed in a blockchain
that keeps track of vehicle maintenance and ownership. The smart
contract can, for example, enforce vehicle maintenance service every six
months; failure of which will lead to suspension of driving license.
3. Music Industry: The music industry could record the ownership of
music in a blockchain. A smart contract can be embedded in the
blockchain and royalties can be credited to the owner’s account when the
song is used for commercial purposes. It can also work in resolving
ownership disputes.
4. Government elections: Once the votes are logged in the blockchain,
it would be very hard to decrypt the voter address and modify the vote
leading to more confidence against the ill practices.
5. Management: The blockchain application in management can
streamline and automate many decisions that are taken late or deferred.
Every decision is transparent and available to any party who has the
authority(an application on the private blockchain). For example, a smart
contract can be deployed to trigger the supply of raw materials when 10
tonnes of plastic bags are produced.
6. Healthcare: Automating healthcare payment processes using smart
contracts can prevent fraud. Every treatment is registered on the ledger
and in the end, the smart contract can calculate the sum of all the
transactions. The patient can’t be discharged from the hospital until the
bill has been paid and can be coded in the smart contract.
Example Use cases:
1. Smart contracts provide utility to other contracts. For example,
consider a smart contract that transfers funds to party A after 10 days.
After 10 days, the above-mentioned smart contract will execute another
smart contract which checks if the required funds are available at the
source account(let’s say party B).
2. They facilitate the implementation of ‘multi-signature’ accounts, in
which the assets are transferred only when a certain percentage of
people agree to do so
3. Smart contracts can map legal obligations into an automated process.
4. If smart contracts are implemented correctly, can provide a greater
degree of contractual security.

Advantages of Smart Contracts

1. Recordkeeping: All contract transactions are stored in chronological


order in the blockchain and can be accessed along with the complete
audit trail. However, the parties involved can be secured cryptographically
for full privacy.
2. Autonomy: There are direct dealings between parties. Smart
contracts remove the need for intermediaries and allow for transparent,
direct relationships with customers.
3. Reduce fraud: Fraudulent activity detection and reduction. Smart
contracts are stored in the blockchain. Forcefully modifying the blockchain
is very difficult as it’s computation-intensive. Also, a violation of the smart
contract can be detected by the nodes in the network and such a violation
attempt is marked invalid and not stored in the blockchain.
4. Fault-tolerance: Since no single person or entity is in control of the
digital assets, one-party domination and situation of one part backing out
do not happen as the platform is decentralized and so even if one node
detaches itself from the network, the contract remains intact.
5. Enhanced trust: Business agreements are automatically executed
and enforced. Plus, these agreements are immutable and therefore
unbreakable and undeniable.
6. Cost-efficiency: The application of smart contracts eliminates the
need for intermediaries(brokers, lawyers, notaries, witnesses, etc.)
leading to reduced costs. Also eliminates paperwork leading to paper
saving and money-saving.

Challenges of Smart Contracts


1. No regulations: A lack of international regulations focusing on
blockchain technology(and related technology like smart contracts,
mining, and use cases like cryptocurrency) makes these technologies
difficult to oversee.
2. Difficult to implement: Smart contracts are also complicated to
implement because it’s still a relatively new concept and research is still
going on to understand the smart contract and its implications fully.
3. Immutable: They are practically immutable. Whenever there is a
change that has to be incorporated into the contract, a new contract has
to be made and implemented in the blockchain.
4. Alignment: Smart contracts can speed the execution of the process
that span multiple parties irrespective of the fact whether the smart
contracts are in alignment with all the parties’ intention and
understanding.

Some Attacks on Smart contracts are programs running on top of


blockchain platforms. They interact with each other through well-defined
interfaces to perform financial transactions in a distributed system with no
trusted third parties. But these interfaces also provide a favorable setting for
attackers, who can exploit security vulnerabilities in smart contracts to
achieve financial gain.
 A smart contract is basically a piece of code where the written code is
publicly visible in the blockchain, and transparent to anyone who is
connected to the network.
 Upon fulfilling the conditions by the desired time, the contract gets
triggered to execute the digital transaction.
 Since the conditions are encrypted cryptographically, no party is able
to alter the contents of a contract.
 The immutable nature of blockchain also ensures that every single
device connected to the network contains a copy of the contract, thus
securing a backup version of the contract.
The article focuses on discussing the overflow and underflow attacks on
smart contracts. The overflow and underflow attacks are classified as Integer
overflows.

What is Integer Overflow?

In Solidity, there are 2 types of integers:


 unsigned integers (uint): These are the positive numbers ranging
from 0 to (2256 – 1).
 signed integers (int): This includes both positive and negative
numbers ranging from -2 255 to (2255 – 1).
An overflow/ underflow occurs when an operation is performed that requires
a fixed-size variable to store the result of the operation.
Overflow Situation:
Consider an unsigned 8-bit integer variable uint8 a. This variable has a
range from 0 to 255:
uint8 a = 255;
a++;
This results in an overflow error as the variable a can take values in the
interval 0-255 then incrementing the value of a by 1 would result in an
overflow situation.
Underflow Situation:
Consider an unsigned 8-bit integer variable uint8 a. This variable has a
range from 0 to 255:
uint8 a = 0;
a–;
This results in an underflow error as the variable a can take a value in the
range of 0-255 and decrementing the value by 1 would result in code
collapse.

Process and Challenges of Detecting Integer Overflow in


Ethereum

1. No indication: In other programming languages there is an indication


of integer overflow but this is not the case with EVM. It is possible to
deduce that overflow has occurred from the values stored after the
transaction. The most common way is to rerun the transaction to identify if
there is an overflow condition.
2. Arithmetic Operations: Addition or subtraction of 2 numbers can also
result in Integer overflow/ underflow. The multiplication operation is based
on addition and exponent operation is based on multiplication, so both of
these operations are also prone to overflow attack.
3. False positives: In some cases, it is possible to identify what
operation has caused integer overflow and whether the operands are
signed or unsigned integers. Some compilers intentionally create overflow
conditions to run some functionality so when there is an overflow
condition it is hard to guess whether it is an actual error or an intentionally
raised situation.
4. No types on byte code level: The types of signed and unsigned
integers are declared in high-level programming language only but not on
the byte code level. So in cases where there is no Solidity source code for
the smart contract then it is hard to guess the type of integers.

Overflow Error Attacks on Smart Contract


An overflow error attack on a smart contract occurs when more value is
provided than the maximum value. When this happens, it circles back to
zero, and this feature can be exploited by repeatedly invoking the feature
that increases the value. Since Solidity does not provide native overflow
detection, it is important for developers to be aware of this issue and to
ensure that their code takes these possible errors into account. This can be
done by using safe math libraries or using appropriate types such as uint256
for operations with integers.
Example 1:
function transfer(address _to, uint256 _amount) {
// Check if sender has sufficient balance
require(balanceOf[msg.sender] >= _amount);
// Add and subtract new balances
balanceOf[msg.sender] -= _amount;
balanceOf[_to] += _amount;
Explanation:
 In this example, the malicious user is able to send a large amount of
ether to the contract that exceeds the maximum value of a unit.
 If the value of the amount variable reaches the maximum value of uint
(2^256) then it is going to circle back and make it 0 which can be very
problematic to handle.
 This can lead to an unexpected result, such as the total balance
becoming negative, and can enable the attacker to steal funds from the
contract.
Solution:
function transfer(address _to, uint256 _amount) {
// Check if sender has balance and for overflows
require(balanceOf[msg.sender] >= _amount &&
balanceOf[_to] + _amount >= balanceOf[_to]);
/* Add and subtract new balances */
balanceOf[msg.sender] -= _amount;
balanceOf[_to] += _amount;
Explanation: Here, the overflow condition is checked by checking if the sum
of balance in the recipient’s account and the amount to be transferred is
greater than or equal to the balance in the recipient’s account or not. This
ensures that even if the user is allowed to increment the value by 1 at a time,
even then there is no feasible way to reach this limit.
To prevent this type of attack, developers should make sure to use safe math
libraries or appropriate types that provide overflow detection.

You might also like