Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views20 pages

LatexTemplate Copy - 8

The document presents SCARF, a hybrid deep learning model that combines Convolutional Neural Networks (CNNs) and Transformers to enhance the detection of vulnerabilities in Ethereum smart contracts. It addresses the limitations of traditional tools by improving efficiency and accuracy in identifying security flaws, which are critical given the immutable nature of smart contracts. The study evaluates various existing tools and demonstrates that SCARF outperforms them, contributing to the overall security of blockchain networks.

Uploaded by

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

LatexTemplate Copy - 8

The document presents SCARF, a hybrid deep learning model that combines Convolutional Neural Networks (CNNs) and Transformers to enhance the detection of vulnerabilities in Ethereum smart contracts. It addresses the limitations of traditional tools by improving efficiency and accuracy in identifying security flaws, which are critical given the immutable nature of smart contracts. The study evaluates various existing tools and demonstrates that SCARF outperforms them, contributing to the overall security of blockchain networks.

Uploaded by

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

SCARF: Smart Contract Analysis and Risk

Framework for Detecting Vulnerabilities Using


Advanced Deep Learning Hybrid Model

Anuswethaa S1 , Akshaya Hariharan2 , Yash Puthalath3 , and Uma J∗

Department of Computer Science and Engineering


Amrita School of Computing, Coimbatore
Amrita Vishwa Vidyapeetham, India
[email protected]
[email protected]
[email protected]
[email protected]

Abstract. As blockchain technology becomes more popular, smart con-


tracts are gaining traction in fields like IoT, finance, and healthcare. It
brings security risks, with vulnerabilities that result in financial losses.
Current tools rely on strict rules, which slow down the detection process
as contracts grow in complexity. This study introduces a hybrid deep
learning model combining CNNs for feature extraction and Transform-
ers for contextual awareness and achieves efficient and accurate vulner-
ability detection on Ethereum smart contract datasets. It also evaluates
three key tools using static analysis and symbolic execution. The results
prove that the model performs better in efficiency thereby enhancing the
overall security of blockchain network.

Keywords: Timestamp Dependence [TD], Delegate Call [DC], Integer


Overflow [IO], Re-Entrancy [RE], Convolutional Neural Network [CNN],
Transformers

1 Introduction
For more than ten years, blockchain technology has acted as a decentralized
and distributed ledger that keeps a permanent record of transactions. Once a
transaction is logged, it remains on the blockchain permanently which makes
post-correction of mistakes nearly impossible. The system retains all bugs and
vulnerabilities without exceptions unless implementation of hard forks becomes
necessary. Minor mistakes in code programming generate severe financial loss
along with security risks. Smart contracts are programs that are encoded within
decentralized blockchains and are intended to execute their commands automat-
ically, removing the middlemen improving the efficiency of operations, fostering
transparency, and improving security [10]. The blockchain also ensures that ev-
ery single device connected contains a copy of the contract, thus securing a
backup of the contract. Smart contract are written using many high-level lan-
guages, popularly solidity, which will be first compiled into EVM bytecode and
sent to Ethereum by user as a transaction for deployment [4]. The Ethereum’s
imperative way of securing the transactions allows a thorough assessment of how
blockchain’s core mechanisms can be fortified. This assessment is warranted lead-
ing to an examination of how smart contracts security can be strengthened. Since
the contracts face vulnerabilities and lead to significant loss, an early detection
of these defects are crucial and tools have been developed to analyze smart
contracts. [15].
The modern programming languages face difficulty in detecting security er-
rors compared to the syntax and run-time errors due to the large number of
conditions to be met to consider to be vulnerable [11].Smart contracts develop
security vulnerabilities because they result from intricate logical flaws that go
beyond compiler detection along with unexpected interactions that occur within
smart contracts. While traditional methods are limited due to a lack of effec-
tiveness in integrating advanced machine learning technologies decreasing the
chances of effective vulnerability detection and it is crucial to defend against
these evolving threats [17]. With the development of artificial intelligence, deep
learning models are trained to predict the programs with vulnerabilities. Machine
learning techniques undergo training processes using extensive datasets which in-
clude secure and vulnerable smart contracts to identify characteristic patterns
of potential weaknesses [1]. The implementation of AI enables vulnerability de-
tection through better security protection while eliminating the need for manual
auditing which often requires long durations and human mistake vulnerability.
It is vital to maintain the durability of decentralized applications (dApps) and
smart contracts because blockchain ecosystems keep increasing. The research
aims in improving the resilience of blockchain technologies by pointing out the
prospects of vulnerability detection.

1.1 Types of Vulnerability


Smart contracts become vulnerable to attacks due to various security flaws like
in features of blockchain, and coding issues, which can incur an enormous loss.
Most of these vulnerabilities arise due to the immutable nature of blockchain,
the complexity of contract logic, and external dependencies on third-party in-
tegrations. Unlike traditional software, where patches and updates can mitigate
security flaws, smart contracts become permanently deployed on-chain, making
any discovered vulnerabilities irreversible unless addressed through governance
mechanisms [17]. Most of the smart contract vulnerability falls under the listed
categories.

1. Reentrancy The Reentrancy attack is a type of security vulnerability tar-


geting smart contracts, potentially leading to the full destruction of the
contract or theft of sensitive information.

2. Integer Overflow/Underflow This vulnerability occurs in smart contracts


and includes arithmetic errors, truncation errors, and sign errors that accept
unauthorized input data or value. The contracts can handle up to 256-bit
numbers, thus increment by 1 can cause an overflow, whereas underflow oc-
curs in the opposite way to the overflow.

3. Timestamp dependence Timestamp Dependence vulnerability occurs when


a contract relies on a block timestamp and re-arranges it by a few seconds
in order to gain a benefit. This makes it vulnerable to attacks and prone to
manipulation.

4. Dangerous Delegatecall Delegatecall is a low-level function in which the


code of the the target contract is executed within the context of the calling
contract. This means that the target contract can access and modify the
storage variables of the calling contract. It can also execute its own logic
using the storage and state of the calling contract.

5. Transaction Order dependency(TOD) Occurs when the outcomes of a


contract function’s execution are contingent upon the order of transaction
execution. This vulnerability inherent in smart contracts can be exploited by
malicious actors who deliberately rearrange transaction sequences to achieve
an unfair advantage or to compromise the smart contract’s designed func-
tionality.

6. Access control vulnerability These are security flaws that can give unau-
thorized individuals the ability to access or change a contract’s data or fea-
tures. They often arise when the contract’s code does not properly enforce
access restrictions according to the user’s authorization status.

7. Gas Limit and Loops A certain quantity of gas or processing power is


required for each action a smart contract takes. The maximum quantity of
gas that can be used in a single block is indicated by the block gas limit.
The transaction will fail if a smart contract function uses unbounded loops,
by running out of gas than the limit permits.

2 Related Work
Research activity into blockchain applications for e-commerce exists at both
comprehensive levels of security detection as well as other operational aspects.
The adoption of Blockchain technology creates stronger transaction security as it
improves monitoring and executive functions for supply chains and digital asset
tracking and fidelity program administration. The expanded use of blockchain
remains limited because blockchain technology struggles to scale and meets regu-
latory requirements [19]. The E-commerce businesses utilizes smart contracts to
manage and secure the buying and selling of products via the internet, shipping
of the products and tracking every processes within the supply chain in order to
reduce order loss and theft.
Smart contracts enables government operations to achieve transparent and
cost-effective administration by their implementation. Widespread adoption of
blockchain remains limited although the system offers benefits because technical
challenges alongside regulatory changes continue to act as barriers for adoption.
And the terms of the contract cannot be alter until there is a consensus among
the nodes involved [16]. Important research that have advanced this discipline
since 2020 are highlighted in this literature review. The study has been made to
understand the significance of smart contract analysis and their risk mitigation
technique using advance deep learning model.
Smart contract vulnerability detection is one of the critical issues in blockchain
security. A research proposed a fully automated vulnerability analyzer for smart
contracts. The researcher studies the various model and compare with existing
models, they explicitly model the fallback mechanism of smart contracts, con-
sider relation between program elements, and they also explore the possibility
of using novel graph neural networks for vulnerability detection. Extensive ex-
periments show that their method constructs a contract graph highlighting a
semantic structure, which limits the feature representation compared to other
model that can incorporate various type of data through convolutional layers
and attention mechanisms. The study concludes that the potential of using deep
learning methods on smart contract vulnerability detection tasks. This will in-
crease the accuracy and efficiency in identifying the smart contracts. [20]
A study proposes a method to generate hybrid heterogeneous graphs con-
taining Abstract syntax trees [ASTs], code property graph [CPGs] and Data
flow graphs [DFGs] based on smart contract source code to capture more com-
plete semantic information. It suggests that, the model’s understanding of the
source code and detects vulnerability at both the contract level and line level.
The results of several simulations with both original and enhanced datasets show
that the proposed method is giving good results and outperforms the other mod-
els due to its reliance on graph structures, but fail to capture the global and local
features effectively. This study also proposes that, most of the existing detection
tools only identify which part of the source code is vulnerable but cannot de-
termine specific attack routes, thus the results are less interpretable. Therefore,
determining the specific line of attack should be the focus of future work [7].
There was lot of research studies conducted on machine-learning-based de-
tection of smart contract vulnerabilities. A research paper focus on studies that
have employed deep-learning models for detection. The study suggest that suffi-
cient training data and deep-learning models typically attain better performance
than traditional machine-learning models. And the impact of four different in-
put types on the vulnerability detection performance using a public dataset
was systematically studied. A binary classification, which is quite pervasive in
machine-learning-based vulnerability detection studies, and a multiclass clas-
sification experiments was implemented on the existing dataset. The research
proposes many desirable future research directions such as comparing the im-
pact of deep-learning models in vulnerability detection and finding out how to
coherently infuse the various types of input for better detection performance. To
improve further, the study suggest that the vulnerability detection performance,
a much more advanced scheme will have to be developed that could clearly
identify and club complementary features from different types of input [6].
The researcher proposed a smart contract vulnerabilities detection model
based on bidirectional encoder representation from transformers (BERT) and
control flow graph (CFG). This research proposed model that integrates Bidi-
rectional Encoder Representations from Transformers (BERT) with control flow
graphs (CFGs). This approach involves the CFG into a format suitable for BERT
input data, retaining control flow and structural information. Empirical evalua-
tions on large-scale datasets showed that this method outperformed five state-of-
the-art baseline methods, achieving a higher F1-scores. This study gives complete
insight about the control flow graph [CFG] based model and the significance on
contract vulnerability detection [8].
In this research, the author presented HyMo, a multi-modal hybrid network
model with deep learning practices. The study shows that arithmetic vulner-
abilities in smart contracts shows that this model outperforms other hybrid
models, due to its utilisation of multi-modal architecture. The selection of opti-
mal arrangements for the model’s components, as well as the choice of various
input data, word embeddings, and deep learning architectures, is critical for
hybrid model. The study findings from comparisons with other models indi-
cate that Hybrid Model achieved good performance level, achieving an accuracy
level of 79.71%. The results further demonstrates that Hybrid Model exceeds
its counterparts in classification accuracy. In Addition, Hybrid Model identifies
vulnerabilities at various level, offering a more efficient and rapid alternative to
conventional smart contract vulnerability detection methods. This study clearly
explained that the model can extract feature values with higher level of pre-
cision when allowing diverse input data representations and word embedding
techniques. In future research, the author planning to identify all types of vul-
nerabilities within smart contracts. Also planning to do further study on multiple
vulnerabilities present in a single smart contract, while enhancing the Hybrid
model’s capacity to detect flaws characterised by cryptic features [12].
The Hybrid Attention mechanism [HAM] model explains that the HAM
model outperforms other advanced vulnerability detection models with higher
level of accuracy with a large number of smart contract vulnerabilities. How-
ever, The Research paper infer that the current deep learning-based smart con-
tract vulnerability detection methods are based on black box detection processes,
which only present final vulnerability detection results by training models and
the specific internal working state and processing process are not transparent.
The study infer that, there is no interpretation about the vulnerability detection
results. It concludes that, the deep learning model should consider how to pro-
vide its reasonable explanatory description for unconvincing results. In addition
to that , the Author mentioning that expert rules defined in traditional detection
tools are powerful tools for analysing contract vulnerabilities. The Authors sug-
gest that , for better result the future deep learning model should be integrated
with expert rules related to vulnerabilities in traditional detection methods, so
as to better improve the accuracy of vulnerability detection [5].
ESCORT presents a deep neural network framework designed to detect mul-
tiple types of vulnerabilities in Ethereum smart contracts. The model employs a
multi-output architecture with a shared feature extractor and multiple branches,
each dedicated to learning a specific vulnerability type. Notably, ESCORT sup-
ports transfer learning, facilitating the extension to new vulnerabilities with
minimal adjustments. ESCORT explores a multi-output NN [Neural Network]
architecture that consists of two parts: A common feature extractor that learns
the semantics of the input contract and multiple branch structures where each
branch learns a specific vulnerability type based on features obtained from the
feature extractor. From this research article we understand the framework that
enables transfer learning on new vulnerability types with minimal modification
of the DNN [Deep Neural Network model ]architecture and re-training over-
head [14].
The integration of advanced deep learning techniques and hybrid models
has significantly advanced the field of smart contract vulnerability detection.
The findings from various studies suggest that classical machine learning tech-
niques, outperform static tools in vulnerability detection. Moreover, multi-model
approaches integrating with deep learning and classical machine learning show
significant improvements in precision and recall. Hybrid models employing var-
ious techniques achieve better performance in vulnerability detection accuracy.
Various Approaches that combine multiple analytical tools /methods, such as
multimodal feature fusion and graph-based neural networks, offer improved ac-
curacy and efficiency. Future research studies may focus on refining these mod-
els, exploring transfer learning capabilities, and incorporating real-time dynamic
analysis to further enhance detection capabilities.

3 Proposed Methodology

The section provides a detailed approach to identify vulnerabilities in smart con-


tracts. It focuses on gathering real-world Ethereum smart contracts and devels
into a detailed implementation of a hybrid model. This model combines various
features and techniques to enhance detection and leverages advanced method-
ologies to improve the accuracy and efficiency of vulnerability idenetification.

3.1 Data collection

The dataset consists of over 3K real-world Ethereum smart contracts from vari-
ous resources where inherited contracts were also included. These contracts were
selected focusing on the four types of vulnerability, where we implement the pre-
processing methods. The contracts have been previously audited and contain
contracts with vulnerabilities expecting it to be a good test for the detection
tools. Figure 1 represents a scatter plot of the vulnerabilities in terms of the
predicted probabilities for the different classes. Every dot corresponds to a par-
ticular sample selected from the test dataset; on the horizontal axis we have the
true class labels; on the vertical axis, the model’s predicted probability for one
Fig. 1: Scatter plot to visualize predicted probabilities for the vulnerabilities

of the classes. The process involves identifying samples belonging to each class
and plotting the predicted probabilities (y_pred[:, class_idx]. This visualization
emphasizes the spread and distribution of the dataset, highlighting the patterns
and class specific variations.

Channel
Attention
Input layer Transformer Feature Squeeze- and- Excitation
(Global Max Pool + Dense)
Multi- Head Attention
Tokens IDs Aggregated
Features
Add (Attention1 + Attention2)
Embedding layer Global Max Pooling
Residual + Dropout
Query/Key/
+Position Value Layer Normalization Flattened
Features
CNN feature Normed Output
Dense layer
Positional Encoding Feedforward Network (128)
(MaxLen: 128, DModel: 128) (256 - > 128)
Class
Feature Extraction Residual + Dropout
Probabilities
Conv1D + MaxPooling Layer Normalization Output Layer
(128 filters, 3x3 kernel)
(4 classes, softmax)

Fig. 2: SCARF: A Hybrid Model for Smart Contract Vulnerability Detection

3.2 CNN-Transformer Hybrid Model


This research uses CNN with Transformer architecture to identify vulnerabil-
ities in smart contracts. The smart contracts(.sol files) have components like
SPDX License Identifier , Pragmas Version, Import statements , Contract dec-
laration statements and other tokens like delimiters and punctuators which may
hamper the processing of the Model, in order to overcome this shortcoming.
The model analyzes sequences of tokenized representations until it reaches its
token limit at 128 followed by dense embedding conversion. Transformers need
additional positional encoding because they normally lose track of sequence in-
formation [3]. The CNN-Transformer block contains three elements featuring
a 1D convolutional layer that detects contextual token connections besides a
max-pooling layer which shortens sequences while retaining critical informa-
tion. Multi-head attention in transformers allows the system to discover distant
correlations by evaluating dependencies among all tokens in their transformed
representations [13]. Such feed-forward combination strengthens the model to de-
tect complex relationships in data. The squeeze-and-excitation block enhances
both model conduct along with representational capability by adjusting channel-
wise feature responses. The essential token-level features go through global max
pooling which results in a condensed representation. Each dense layer adopts
weighted values to form complex decision boundaries through non-linear acti-
vated functions during its execution of input features from previous layers. The
refined inputs undergo softmax activation in the output layer to determine multi-
class classifications using probabilistic distributions. Security analysis of smart
contracts receives optimization from the CNN-transformer framework which in-
tegrates local feature extraction of CNN with transformer-dependent features
from distant locations.

4 Computational Framework
In order to evaluate the effectiveness of the vulnerability detection tool, the
performances of 2 tools have been compared and analyzed, where each operates
on a different method. These tools are one of the efficient practices in the field
of blockchain security:

Fig. 3: Analysis using Slither tool

Slither performs static analysis on smart contracts, emphasizing on performance


and vulnerabilities. The tool utilizes data flow analysis and automation to find
vulnerabilities. Static analysis examines source code, program binaries, or other
software tools without running the code. In Figure 3, it is inferred that the used
smart contract has a reentrancy problem. Based on the paper by Slither [9], this
vulnerability is rooted in the withdraw function of the code as it transfers money
to the user’s destination before setting the balance to zero. This issue arises be-
cause an external call permits the attacker the ability to have momentary control
of the transaction.The solution to this is to update the balance before making a
transaction so that the attacker cannot continue to make withdrawals.
Mythril performs symbolic execution with input in the form of Ethereum byte-

Fig. 4: Analysis using Mythril tool

code detecting security vulnerabilities like re-entrancy,integer overflow, times-


tamp dependency, and dangerous delegatecall. In the Mythril analysis, the with-
draw function has an access control issue where any one can withdraw Ether
from the contract. Again there are no limitations, so any address can deploy
the function. The attacker referred to as [ATTACKER] is able to invoke the
function and thereby, withdraw Ether. It connects to a dangerous contract since
it allows anyone below to directly withdraw Ether without asking for identifi-
cation using payable(msg.sender).transfer(amount). This can be solved by
adding certain access control limitations that allow only the contract owner to
do the withdrawal.

Fig. 5: Analysis using Oyente tool

Oyente uses symbolic execution to find vulnerabilities. It evaluates the symbolic


state and routes of vulnerabilities to decrease false positive rates. This tool works
directly with EVM byte code, but with so many potential pathways to traverse,
it is expensive to run programs. Oyente identified Transactional Ordering Depen-
dency (TOD), in which the withdraw function initiates an external call before
modifying the contract ledger result, which leads to a TOD problem.Other vul-
nerabilities were all labeled as False which means that they were not found in
the code. The analysis was completed for 98.7% of the code (the EVM code
coverage).
Tool Command Type Command
Slither Installation docker pull trailofbits/slither
Run docker run -v /path/to/contracts:/
contracts trailofbits/eth-security-
toolbox bash -c "solc-select
use <version> && slither
/contracts/MyContract.sol"
Oyente Installation docker pull luongnguyen/oyente &&
docker run -i -t luongnguyen/oyente
Run cd /oyente/oyente && python oyente.py
-s greeter.sol
Mythril Installation docker pull mythril/myth
Run docker run -v /path/to/contracts:/tmp
mythril/myth analyze –solv <version>
/tmp/<file>

Table 1: Tool Commands for Setup and Execution

5 Implementation

This section is elaborates about the process of setting up and deploying an e-


commerce website leveraging blockchain technology where users could securely
make transactions using smart contracts. Computational framework was im-
plemented functionally to identify vulnerabilities in the smart contracts. This
process allowed for a more secure deployment of the website and the following
subsections detail the steps taken to setup the platform, with a focus on the
security analysis of the smart contracts.

Test Run - 1:
1

2 function makePayment ( uint256 orderId ) public payable


nonReentrant {
3 require ( msg . value > 0 , " Payment amount must be greater
than zero ") ;
4 require ( payments [ orderId ]. amount == 0 , " Payment already
exists for this order ") ;
5 payments [ orderId ] = Payment ( orderId , msg . sender , msg .
value , " Pending ") ;
6 orderCount ++;
7 emit PaymentReceived ( orderId , msg . sender , msg . value ) ;
8 }
9

10 function refundPayment ( uint256 orderId ) public onlyAdmin


nonReentrant {
11 Payment storage payment = payments [ orderId ];
12 require ( payment . amount > 0 , " No payment found for this
order ") ;
13 require ( keccak256 ( abi . encodePacked ( payment . status ) ) ==
14 keccak256 ( abi . encodePacked (" Pending ") ) ,
15 " Refund can only be issued for pending payments ") ;
16 uint256 refundAmount = payment . amount ;
17 payment . status = " Refunded ";
18 payment . amount = 0;
19 Address . sendValue ( payable ( payment . buyer ) , refundAmount ) ;
20 emit PaymentRefunded ( orderId , payment . buyer , refundAmount
);
21 }
Listing 1.1: Non-Vulnerable Solidity Code snnipet

This Solidity smart contract implements a secure payment system along with
refund and withdrawal mechanisms. The makePayment function allows users
to make payments for orders, ensuring each order has a payment entry done
only once. The refundPayment function, which is restricted to admins, processes
refunds only for pending payments, preventing double spending. The withdraw-
Funds function helps the admin to transfer funds securely. All functions in the
contracts utilize reentrancy protection and safe transfer methods to enhance the
overall security.

Test Run - 2:

2 function refundPayment ( uint256 orderId ) public onlyAdmin {


3 Payment storage payment = payments [ orderId ];
4 require ( payment . amount > 0 , " No payment found for this
order ") ;
5 uint256 refundAmount = payment . amount ; payable ( payment .
buyer ) . transfer ( refundAmount ) ;
6 payment . status = " Refunded ";
7 payment . amount = 0;
8 emit PaymentRefunded ( orderId , payment . buyer , refundAmount
);
9 }
Listing 1.2: Vulnerable Solidity Code Snippet with Refund Payment Mechanism

In case of a Reentrency Attack, The refund Payment function is vulnerable as


it transfers funds before updating the state, allowing a malicious contract to
repeatedly withdraw funds using recursive calls. Since Ethereum’s fallback exe-
cution enables reentry, an attacker can drain funds before payment amount value
is set to 0.

2 function splitPayment ( uint256 orderId , address []


3 memory recipients , uint256 [] memory amounts ) public onlyAdmin
{
4 require ( recipients . length == amounts . length , " Mismatched
recipients and amounts ") ;
5 Payment storage payment = payments [ orderId ];
6 require ( payment . amount > 0 , " No payment found for this
order ") ;
7 uint256 totalAmount = 0;
8

9 for ( uint256 i = 0; i < amounts . length ; i ++) {


10 totalAmount += amounts [ i ]; // Integer Overflow Risk
11 payable ( recipients [ i ]) . transfer ( amounts [ i ]) ;
12 }
13

14 require ( totalAmount <= payment . amount , " Total exceeds


payment amount ") ;
15 payment . amount -= totalAmount ;
16

17 }

Listing 1.3: Vulnerable Solidity Code Snippet with Split Payment mechanism

The above code snippet highlights the integer overflow vulnerability. The split
Payment function is vulnerable, as the total Amount is incremented without
bounds, which may exceed uint256 limits. If an overflow occurs, the validation
check done can be bypassed, allowing unintended fund distribution.

User Interface: The frontend of the system includes a login page for user
authentication. Once logged in, users can browse available products along with
their respective prices, displayed in Ethereum (ETH). The interface is designed
for ease of use, ensuring seamless navigation and accessibility for users of all
experience levels.

Fig. 6: User Interface showcasing available products in Shopsphere


The system sends a request to MetaMask to execute the transaction after com-
pleting vulnerability checks on the smart contract successfully. The transaction
moves funds between accounts while the network fee depends on current network
usage levels. The system notifies users about transaction information before they
can approve the final action. After vulnerability checks complete successfully
MetaMask receives an execution request for the transaction.

Fig. 7: Transaction Request at Metamask Interface

The transaction process stops when vulnerabilities are found in the smart con-
tract which prevents the MetaMask extension from making payments to ensure
security compliance. The security system protects smart contract transactions
from financial damage while maintaining their integrity. The transaction stops
when vulnerabilities appear in the smart contract which prevents the MetaMask
extension from making payments to maintain security standards. The security
system protects both financial assets and maintains the integrity of smart con-
tract deals.

Fig. 8: Transaction Accounts and their corresponding Private Keys


Deployment: The Ethereum development environment Hardhat enables smart
contract deployment and testing. When Hardhat executes it creates 20 accounts
containing 10,000 ETH and their matching private keys for simulating system
transactions. The deployment script controls smart contract implementation by
allocating a particular address to the contract. The Solidity code then receives
vulnerability testing through Slither which detects security flaws in smart con-
tracts.

Transaction Flow: The smart contract deployment enables users to start


their transactions. All payment transactions record sender and receiver addresses
together with gas fees and block hash for secure auditing and reference purposes.
A refund request from customers for defective products or unwanted items leads
to both transaction reversal and money transfer back to their account for risk-
free purchases with added trust. The admin has the ability to withdraw all funds
accumulated in the system’s main account to maintain financial flexibility while
retaining control over smart contract funds.

Fig. 9: A successful fund transfer transaction recorded on the blockchain.

Blockchain Records: A transaction log system preserves every payment and


refund activity which lets the financial records be checked at any point. The
transaction entries contain timestamps alongside sender and recipient addresses
and transaction amount and network fee and transaction hash for blockchain
verification. The structured logging system creates a complete financial transac-
tion record for the system.

Slither Based Audits: Smart contracts require Slither analysis because it


helps locate potential security issues throughout contracts. The analysis con-
cludes with a false value for the isVulnerable flag which indicates the contract
provides secure conditions for buyer-seller transactions. The verification process
enables uninterrupted execution while eliminating the need for human security
checks. The analysis tool sets the flag to true when vulnerabilities are identified
so that operators must resolve security risks before approving transactions. The
detection system identifies three main vulnerabilities: Ether Transfer to Arbi-
trary Users, Reentrancy Issues, and External Call Risks that create potential
security risks for attackers. The Slither report highlights critical vulnerabilities
Fig. 10: Slither vulnerability analysis—secure vs. insecure smart contract results.

in red and lower-risk issues, such as low-level calls, in green. Blockchains prevent
financial losses by obstructing unsafe transactions which warn both users and
developers about security threats.

User Notifications: Upon successful transaction completion, a confirmation


email is automatically forwarded to the buyer’s registered email address, ensuring
proper communication of purchase details. This email includes a receipt of the
transaction, along with relevant metadata such as the transaction hash, making
it easy for users to track their purchases.

Fig. 11: Email Notification confirming the Purchase

Risk Prevention: The system blocks transactions that reveal vulnerabili-


ties while showing an alert containing security risk information including Ether
Transfer to Arbitrary Users and Reentrancy Issues and External Calls. The
system safeguards users from financial loss and potential attacks by stopping
dangerous transactions from running before execution.

Fig. 12: Transaction blocked due to detected smart contract vulnerabilities.


6 Results and Analysis

In this section, the performance of the CNN-Transformer model in detecting


vulnerabilities is analyzed. The results are evaluated showcasing its accuracy,
precision, recall and other metrics. The analysis enhances the research work in
understanding the strengths and limitations of our model.

6.1 CNN-Transformer Hybrid Model

Precision Recall F1-Score Support


DC 1.00 0.70 0.82 10
IO 0.86 0.93 0.89 59
RE 0.96 0.94 0.95 122
TD 0.87 0.87 0.87 31
Accuracy 0.94 222
Macro Avg 0.96 0.86 0.9 222
Weighted Avg 0.94 0.94 0.94 222

Table 2: Vulnerability Classification Report for Hybrid Model

The proposed model achieves an overlapping ratio of 94%, indicating a strong


agreement between detected vulnerabilities and actual vulnerabilities present
in the dataset. This high overlap suggests that the model is highly effective in
recognizing vulnerability patterns with minimal deviation. Compared to exist-
ing vulnerability detection methods, which often struggle with incomplete or
inconsistent detection, our approach demonstrates superior reliability in iden-
tifying security risks.Precision consistently remains above 80% across both DC
(Data Classification) and TD (Transaction Detection) tasks, signifying that the
model is highly accurate in distinguishing genuine vulnerabilities from false posi-
tives. This is particularly crucial in security applications, as a high precision rate
minimizes unnecessary alerts and prevents misclassification of secure contracts
as vulnerable. Unlike conventional rule-based systems, which tend to generate
a high number of false alarms due to rigid matching criteria, the hybrid AI-
driven approach adapts to complex vulnerabilities more effectively, ensuring that
developers receive fewer misleading warnings.The recall analysis highlights the
model’s effectiveness in detecting a substantial portion of existing vulnerabilities.
A high recall value indicates that the model successfully identifies most security
risks present in the dataset [2]. However, analysis of day class vulnerabilities,
which typically fall into the minority category, reveals a weaker recall.
The model’s high precision and performances enhance smart contract secu-
rity by proactively detecting vulnerabilities before deployment. This reduces the
reliance on manual audits, which are both time-consuming and prone to human
error. The ability to accurately identify security risks also helps mitigate finan-
cial losses in decentralized applications (dApps), particularly in decentralized
finance (DeFi), where undetected vulnerabilities can lead to significant mone-
tary exploits. By reducing false alarms while maintaining a strong detection rate,
this model provides a significant improvement over traditional methods, making
it a valuable asset for enhancing blockchain security.

Fig. 13: Confusion Matrix

The confusion matrix in Figure 7 provides a detailed breakdown of the classifica-


tion model’s predictions across four classes: DC, IO, RE, and TD. The diagonal
values represent correct predictions, while off-diagonal values indicate misclas-
sifications [18]. The results show only minor misclassifications, demonstrating
the model’s strong predictive capability and accuracy in distinguishing between
different vulnerability types. Training vs validation Loss graph shows how the
model’s error (loss) decreases during training and validation. The decreasing loss
graph here indicates the model is learning and thereby improving its general ca-
pabilities. The absence of general overfitting suggests that model maintains its
consistency and enforces its reliability.

Fig. 14: Loss Graph of the CNN-Transformer Hybrid Model


AUC-ROC graph indicates a good model has been built as the values resulted
in great scores. This shows how well a classifier distinguishes between classes, in
this case, the graph is aligned mostly towards the TPR indicating an excellent
model performance.The AUC (Area Under the Curve) quantifies the overall per-
formance of the classifier, where a value closer to 1 indicates better classification
performance. When AUC scores are high the model displays exceptional vul-
nerability detection abilities together with low numbers of wrong positives and
wrong negatives which indicates its effectiveness for smart contract vulnerability
detection.

Fig. 15: AUC-ROC Graph of the CNN-Transformer Hybrid Model

7 Conclusion
This study presents a hybrid model for the classification of vulnerabilities in
smart contracts that combines the benefits of Convolutional Neural Networks
(CNN) with Transformer Models. Our hybrid model does have some shortcom-
ings, such as both models CNN and transformer are considered black-box so it
may have some difficulty in determining why the particular input is vulnera-
ble though it is classified. In addition, we did a complete static investigation of
three important vulnerability detection tools: Mythril, Slither, and Oyete, and
compared them thoroughly. Our research constitutes an important milestone in
the ongoing efforts to improve vulnerability detection in smart contracts, with
opportunities for future refinement.

8 Future Work
This study highlights the use of major tools and Neural Network models for
detecting and classifying smart contract vulnerabilities into commonly exploited
categories. Nonetheless, the progression of security vulnerabilities is advancing
beyond the reach of the tools and machine learning models currently in opera-
tion. Future work should concentrate on advanced vulnerability detection tools
alongside training ML models with large variations in features while also solv-
ing scalability problems to conduct multiple contract analysis efficiently while
enhancing false detection assessment. Further improvement of our model will
involve enhancing its ability to detect new vulnerabilities regardless of previ-
ously observed features in known security flaws. Additionally, integrating XAI
techniques on security vulnerabilities can provide more insights on why a vul-
nerability is flagged.

References
1. Akshat Kotadia, Bhavy Masalia, O.M.L.P.: Machine learning for threat detection
in softwares. International Journal of Innovative Science and Research Technology
(2024)
2. Brendan Juba, H.S.L.: Precision-recall versus accuracy and the role of large data
sets. ResearchGate (2019)
3. Han, L.: Smart contract reentrancy vulnerability detection based on cnn and lstm-
attention. IEEE (2024)
4. Haoyang Ma, Wuqi Zhang, Q.S.Y.T.J.C.S.C.C.: Towards understanding the bugs
in solidity compiler. arXiv:2407.05981v3 (2024)
5. Huaiguang Wu 1, ORCID, H.D..O.Y.H..a.D..: Smart contract vulnerability detec-
tion based on hybrid attention mechanism model. semanticsscholar (2022)
6. Izdehar M. Aldyaflah 1, Wenbing Zhao 1, .S.Y.., 3, X.L.: The impact of input types
on smart contract vulnerability detection performance based on deep learning: A
preliminary study. MDPI (2024)
7. Jingjie Xu1, Ting Wang1, M.L.T.C.T.Z., Ji1, B.: Mvd-hg: multigranularity smart
contract vulnerability detection method based on heterogeneous graphs. Springer
(2024)
8. KeXin Gong, Xiangmei Song, N.W.C.W.: Smart contract vulnerability detection
based on control flow graph and transformer. ResearchGate (2023)
9. Liao, J.W., Tsai, T.T., He, C.K., Tien, C.W.: Soliaudit: Smart con-
tract vulnerability assessment based on machine learning and fuzz test-
ing. In: 2019 Sixth International Conference on Internet of Things:
Systems, Management and Security (IOTSMS). pp. 458–465 (2019).
https://doi.org/10.1109/IOTSMS48152.2019.8939256
10. Liu, Z., Qian, P., Yang, J., Liu, L., Xu, X., He, Q., Zhang, X.: Rethinking smart
contract fuzzing: Fuzzing with invocation ordering and important branch revisiting.
arXiv preprint arXiv:2301.03943 (2023)
11. Misha Abraham, J.K.: Runtime verification and vulnerability testing of smart con-
tracts. ResearchGate (2019)
12. Mohammad Khodadadi, J.T.: Hymo: Vulnerability detection in smart contracts
using a novel multi-modal hybrid model. semanticsscholar (2023)
13. Nicholas Ampazis, F.S.: Diversifying multi-head attention in the transformer
model. MDPI (2024)
14. Oliver Lutz, Huili Chen, H.F.C.S.A.D.A.R.S.F.K.: Escort: Ethereum smart con-
tracts vulnerability detection using deep neural network and transfer learning.
arxiv (2021)
15. Priyanka Kumar, G. A. Dhanush, D.S.S.N.A..S.S.: An efficient and novel buyer and
seller’s distributed ledger based protocol using smart contracts. Springer (2019)
16. Singh, K.K.: Application of blockchain smart contracts in e-commerce and govern-
ment. arXiv preprint arXiv:2208.01350 (2022)
17. Wu, N.Z.S.: Security vulnerability detection using deep learning natural language
processing. IEEE (2021)
18. Yan Xiong· GuoXinya, J.X.: Cnn-transformer: A deep learning method for auto-
matically identifying learning engagement. Research Gate (2023)
19. Yuan Yao, Zhiqiang Zhao, Y.S.G.H.J.W.W.W.: Blockchain-based e-commerce: A
review on applications and challenges. Electronics (2023)
20. Yuan Zhuang1, , Z.L..Q..L.X.W.Q.H.: Smart contract vulnerability detection using
graph neural networks. ijcai.org (2020)

You might also like