A blockchain eclipse attack detection method based on CNN
By proposing a CNN-based blockchain eclipse attack detection method, a two-dimensional grayscale image is generated in real time and features are extracted using a pre-trained model. This solves the problem of identifying eclipse attacks in blockchain networks, achieves high-precision, real-time defense response and dynamic adjustment, and improves network security.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- SHANGHAI CRIMINAL SCI TECH RES INST
- Filing Date
- 2026-04-10
- Publication Date
- 2026-05-29
AI Technical Summary
Existing technologies struggle to effectively identify eclipse attacks in blockchain networks, particularly due to challenges such as difficulties in extracting high-dimensional nonlinear features, the lack of a closed-loop system for detection and defense, feature coupling and ambiguity in dynamic network environments, and the imbalance between the need for high-precision detection and real-time response performance.
A CNN-based blockchain eclipse attack detection method is adopted. It generates two-dimensional grayscale images by capturing underlying communication messages in real time, extracts abnormal texture and spatial correlation features using a pre-trained CNN model, and combines response level-triggered defense measures to achieve iterative optimization.
It significantly improves the accuracy of identifying covert attacks, enhances the anti-interference capability in dynamic environments, achieves millisecond-level real-time detection and protection response, and builds a dynamic and flexible closed-loop defense ecosystem.
Smart Images

Figure CN122120010A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of blockchain and network security detection technology, and in particular to a CNN-based method for detecting blockchain eclipse attacks. Background Technology
[0002] With the deepening application of blockchain technology in fields such as financial settlement, supply chain management, and IoT security, the security of its underlying architecture has become a core issue in distributed system research. Blockchain systems heavily rely on decentralized peer-to-peer (P2P) network protocols for data propagation and consensus. However, due to the openness and anonymity of P2P network topologies, distributed nodes are highly vulnerable to targeted attacks from the network layer, with Eclipse attacks widely recognized as one of the most threatening attack methods.
[0003] In an eclipse attack, attackers strategically seize all inbound and outbound connections of a target node (such as a full consensus node) by manipulating a large number of malicious or controlled nodes, thereby completely isolating the target node from the real blockchain network at the network level. Once the attack succeeds, the target node will be in an information silo state, with its received local blockchain ledger and transaction flow completely forged by the attacker. This isolation not only directly leads to the target node participating in incorrect consensus competition and wasting computing power, but may also induce security risks such as double-spending attacks, seriously threatening the normal operation of the blockchain network and the security of transaction confirmation.
[0004] Currently, domestic and international research on the detection and defense against solar eclipse attacks mainly focuses on the following traditional technical approaches:
[0005] 1. Blacklist mechanism based on static rules:
[0006] Abnormal behavior can be identified by maintaining a known database of malicious IPs or setting fixed connection thresholds. However, Eclipse attackers often employ camouflage strategies such as dynamically changing IPs and simulating normal node connection patterns, making it difficult for static rules to adapt to variant attacks, and manually defined rules have extremely poor generalization capabilities.
[0007] 2. Monitoring based on traffic statistics analysis:
[0008] The method relies on statistical characteristics such as the frequency of inbound connections to monitoring nodes and the distribution of data packet sizes to make judgments. However, when faced with complex network environments such as network congestion, normal node expansion, or cross-regional transmission delays, this method struggles to accurately distinguish between normal traffic fluctuations and covert attacks, resulting in a high false alarm rate.
[0009] 3. Offline auditing based on behavioral patterns:
[0010] Behavioral profiling is performed on the historical connection stability of nodes. While this method can detect long-term anomalies, it suffers from significant detection lag when dealing with sudden, explosive eclipse attacks, failing to achieve real-time responses down to the second.
[0011] In summary, the existing technology system faces the following deep-seated technical bottlenecks in practical applications:
[0012] 1. Difficulty in extracting high-dimensional nonlinear features:
[0013] Blockchain P2P traffic encompasses multiple dimensions, including IP distribution, packet size, transmission interval, and connection frequency, with complex nonlinear relationships between these dimensions. Traditional linear modeling methods cannot effectively mine deep semantic features within the data, making it difficult to accurately capture attack characteristics from massive datasets.
[0014] 2. Lack of a closed-loop system for detection and defense:
[0015] Existing technologies primarily focus on alerts, lacking deep integration with automated defense mechanisms. After detecting a suspected attack, manual verification is often required, resulting in excessively long response times. This allows attackers to exploit these gaps to quickly gain control of target nodes, leading to insufficient timeliness of protection.
[0016] 3. Feature coupling and discriminative fuzziness in dynamic network environments:
[0017] Blockchain networks are highly dynamic. Frequent synchronization requests from nodes, the addition of new nodes, and normal traffic fluctuations caused by momentary network congestion exhibit a high degree of coupling with the connection preemption characteristics at the initial stage of an eclipse attack in a statistical dimension. Traditional detection methods struggle to accurately delineate attack detection boundaries amidst complex and ever-changing background noise, resulting in a persistently high false positive rate in real-world production environments.
[0018] 4. Imbalance between high-precision detection requirements and real-time response performance:
[0019] The window of opportunity for eclipse attacks is extremely short, requiring detection systems to have millisecond-level identification and blocking capabilities. However, existing detection solutions that can provide high accuracy often involve complex deep packet inspection (DPI) or long-term node behavior auditing, resulting in huge computational overhead. They are difficult to balance detection depth and processing timeliness in high-throughput blockchain environments, exhibiting significant performance bottlenecks.
[0020] In recent years, convolutional neural networks (CNNs) have demonstrated outstanding performance in image recognition and nonlinear feature extraction. However, in the field of blockchain security, existing CNN research has focused on transaction fraud and smart contract vulnerabilities, while research on traffic image representation and intelligent detection and recognition of network layer eclipse attacks is relatively scarce.
[0021] Therefore, this invention proposes a blockchain eclipse attack detection method based on CNN. Summary of the Invention
[0022] This invention provides a CNN-based method for detecting blockchain eclipse attacks, in order to solve the aforementioned technical problems.
[0023] This invention provides a CNN-based method for detecting blockchain eclipse attacks, comprising:
[0024] Step 1: The acquisition engine deployed on the key nodes of the blockchain P2P network captures the underlying communication messages in real time and preprocesses the underlying communication messages to obtain a two-dimensional grayscale image.
[0025] Step 2: Input the two-dimensional grayscale image into the pre-trained CNN detection model to capture abnormal textures, edges, and spatial correlation features in the two-dimensional grayscale image, and output the binary classification result and binary classification probability value;
[0026] Step 3: Match the binary classification probability values with the preset threshold, and combine this with the attributes of the affected nodes and the proportion of malicious connections to determine the response level;
[0027] Step 4: Trigger corresponding defense measures based on the response level, including attack node isolation, dynamic network topology adjustment, alarm and log recording. Simultaneously, continuously monitor the defense effectiveness and feed it back to the pre-trained CNN detection model for iterative optimization, including: During the monitoring period T following the implementation of the defense measures, traffic is continuously collected from the affected nodes and time-series image sequences are generated. ,in, Let T be the two-dimensional grayscale image of the t-th time sequence in the time sequence image sequence, where T is the total number of time sequences in the time sequence image sequence. Identify the abnormal texture connected components determined by the pre-trained CNN detection model for each two-dimensional grayscale image, and calculate the dissipation rate and dissipation type of the total pixel area A(t) of the abnormal texture connected components in adjacent time sequences. Assign a defense effect label to the two-dimensional grayscale image in the next time sequence in the adjacent time sequence, and the defense effect label of the two-dimensional grayscale image in the first time sequence is consistent with that of the two-dimensional grayscale image in the next adjacent time sequence. Extract the comprehensive feature activation map of each direction of the Conv2 layer convolution kernel in the pre-trained CNN detection model on the temporal image sequence, count the number of burst feature points and the combination of undefined new feature activation directions, introduce direction-specific regularization terms for the direction with significant residual features during model training, and calculate the augmentation necessity coefficient for continuously emerging new feature combinations and dynamically augment the convolution kernels in the corresponding directions. The time-series image sequences labeled with defensive effects are merged with historical attack samples to form a reinforcement training set, thus completing the iterative optimization of the model.
[0028] Preferably, step 1 includes: The acquisition engine, based on traffic monitoring plugins or bypass acquisition devices, captures raw data packets from the network interface layer and transport layer in real time and treats them as underlying communication messages. Based on DPI technology, TCP / UDP traffic related to the blockchain P2P protocol in the underlying communication messages is identified, and damaged fragment packets, duplicate packets, and noise data unrelated to the connection state are removed to obtain the cleaned traffic. The cleaned flow rate is sliced according to a fixed time window to obtain independent flow rate sample blocks; Numerical features and categorical features reflecting network connection status and node behavior are extracted from each traffic sample block, and multidimensional feature vectors are obtained using one-hot encoding. Each feature in all extracted multidimensional feature vectors is mapped to the standard grayscale range of [0, 255] and the abstract communication indicators are converted into visualized pixel intensity information to achieve feature normalization and grayscale conversion. Based on a predefined feature correlation matrix, logically closely related features are mapped to adjacent positions in a two-dimensional matrix, filled into an N×N pixel matrix, and zero-padding is applied to empty positions to generate a two-dimensional grayscale image, wherein the two-dimensional grayscale image is a 64×64 single-channel grayscale image.
[0029] Preferably, the deep learning architecture of the pre-trained CNN detection model includes:
[0030] The input layer is used to receive a 64×64×1 single-channel grayscale image and normalize the image pixel values to the [0,1] range to obtain a standardized input;
[0031] The system consists of three convolutional layers: Conv1 layer with 32 3×3 convolutional kernels to extract low-level edge features of the standardized input; Conv2 layer with 64 3×3 convolutional kernels to extract mid-level texture features of the standardized input; and Conv3 layer with 128 convolutional kernels, including 3×3 convolutional kernels and 5×5 global feature aggregation convolutional kernels, to extract high-level semantic features. All convolutional kernels have a stride of 1, use the Same padding method, and all use ReLU activation function.
[0032] The three pooling layers correspond one-to-one with the three convolutional layers, and the pooling kernel size is 2×2 with a stride of 2, which is used to downsample the output of the convolutional layers.
[0033] Two fully connected layers, containing 256 and 128 neurons respectively, with ReLU activation function and Dropout probability of 0.5, are used to flatten the output of the pooling layer into a one-dimensional feature vector and fuse all high-level features through fully connected operations;
[0034] The output layer contains two neurons with the Softmax activation function, used to output the binary classification result and the binary classification probability value.
[0035] Preferably, the Conv2 layer has 64 3×3 convolution kernels with orientations of 0°, 45°, 90°, and 135°.
[0036] Preferably, matching the binary classification probability value with a preset threshold includes:
[0037] When the pre-trained CNN detection model outputs eclipse attack traffic and the probability value is greater than or equal to the first threshold, it is determined to be an confirmed attack and a defense response is immediately triggered.
[0038] When the output of eclipse attack traffic and the probability value is between the second threshold and the first threshold, it is judged as a suspected attack and enters a temporary monitoring state. At the same time, the frequency of traffic collection from the response node is increased, and the traffic is continuously input into the model for secondary detection. If the probability value of the detection is greater than or equal to the third threshold for M consecutive times, it is upgraded to confirmed attack and the defense response is triggered.
[0039] If the output of eclipse attack traffic is lower than the second threshold, the temporary monitoring status will be lifted.
[0040] Among them, the first threshold > the third threshold > the second threshold.
[0041] Preferably, the response levels include high-risk response, medium-risk response, and low-risk response.
[0042] Preferably, the attack node isolation includes: real-time connection blocking, dynamic entry of node blacklist, and target node connection reset;
[0043] Dynamic network topology adjustments include: optimization of node connection weights, enhanced protection of core nodes, and visual monitoring of the topology structure.
[0044] Alarm and log recording includes: multi-level alarm notifications and full-process log retention.
[0045] Preferably, for directions with significant residual features, a direction-specific regularization term is introduced during model training, and an augmentation necessity coefficient is calculated for continuously emerging new feature combinations, and the convolution kernels in the corresponding directions are dynamically augmented, including: Based on the extracted comprehensive feature activation map, the activation values on the comprehensive feature activation map in each direction exceeding [a certain threshold] are statistically analyzed. The number of burst feature points And whether there are any undefined new feature activation direction combinations in each direction. in, These represent the mean and standard deviation of the activation values for all integrated feature activation maps, respectively. This is a correction factor; When the number of burst feature points in direction d Below the preset threshold At that time, the feature point burst mode residuals in direction d are determined to be significant, and in the subset of convolution kernels in direction d. In the next round of training, a direction-specific regularization term is introduced. The expression is: ,in, Convolution kernel subsets The weights of the i-th and j-th convolutional kernels; The cross-entropy loss function; The cosine similarity function; This is the control coefficient; The weights of the i-th convolutional kernel in direction d Find the gradient; Meanwhile, if new feature activation direction combinations are continuously detected in direction d for at least two monitoring periods, And with In the current model, the attack category dispersion of the comprehensive feature activation map of the corresponding Conv2 layer for the attack sample is lower than the preset dispersion. At this point, calculate the expansion necessity coefficient. : in, In direction d Duration; Features Mutual information with attack label Y; Features Entropy; The total duration of a single monitoring cycle; like At this point, at least one convolutional kernel is dynamically added in direction d of the Conv2 layer, and the architecture is updated, where, The necessity threshold; Otherwise, keep the original model architecture unchanged.
[0046] Compared with the prior art, the beneficial effects of this application are as follows:
[0047] 1. Significantly improves the accuracy of identifying covert attacks: It overcomes the limitations of traditional statistical methods in uncovering high-dimensional feature correlations. Through a traffic image mapping algorithm, abstract and fragmented communication data is transformed into images with spatial texture features. Utilizing the powerful nonlinear feature extraction capabilities of CNNs, it can keenly capture subtle visual anomalies generated when eclipse attacks attempt to occupy connection bits, effectively identifying covert attacks that simulate normal node behavior and significantly reducing the false negative rate.
[0048] 2. Significantly enhanced anti-interference capability in dynamic environments: By using a CNN model for deep semantic learning of traffic features, it can accurately distinguish the essential differences between normal network fluctuations such as large-scale block synchronization and new node additions and the seizure of connection control by eclipse attacks. This deep learning-based pattern recognition mechanism effectively solves the problem of false alarms easily generated by traditional solutions during network congestion or peak business periods, ensuring the reliability of detection conclusions.
[0049] 3. Achieve millisecond-level real-time detection and protection response: The use of time window slicing technology and lightweight image representation methods significantly reduces the computational overhead of deep packet inspection (DPI). The CNN model has extremely high processing efficiency during the inference phase, enabling streaming real-time detection under massive concurrent traffic; combined with the backend automated response system, it achieves millisecond-level linkage from threat detection to connection blocking, ensuring effective intervention before attackers can isolate nodes.
[0050] 4. Constructing a dynamic and flexible closed-loop defense ecosystem: Going beyond simple alarm functions, it achieves precise deployment of defense measures through a tiered response mechanism and dynamic weight adjustment. While effectively isolating malicious nodes, it can proactively guide attacked nodes to reconnect to the trusted network through methods such as target node connection reset and dynamic topology optimization. This not only achieves passive defense but also possesses the ability to proactively repair network connectivity.
[0051] Other features and advantages of the invention will be set forth in the following description, and will be apparent in part from the description, or may be learned by practicing the invention. The objects and other advantages of the invention may be realized and obtained by means of the structures particularly pointed out in the written description and the accompanying drawings.
[0052] The technical solution of the present invention will be further described in detail below with reference to the accompanying drawings and embodiments. Attached Figure Description
[0053] The accompanying drawings are provided to further illustrate the invention and form part of the specification. They are used in conjunction with embodiments of the invention to explain the invention and do not constitute a limitation thereof. In the drawings:
[0054] Figure 1This is a flowchart of a blockchain eclipse attack detection method based on CNN in an embodiment of the present invention;
[0055] Figure 2 This is a flowchart illustrating the construction process of a two-dimensional grayscale image in an embodiment of the present invention. Detailed Implementation
[0056] The preferred embodiments of the present invention will be described below with reference to the accompanying drawings. It should be understood that the preferred embodiments described herein are for illustration and explanation only and are not intended to limit the present invention.
[0057] This invention provides a CNN-based method for detecting blockchain eclipse attacks, such as... Figure 1 As shown, it includes:
[0058] Step 1: The acquisition engine deployed on the key nodes of the blockchain P2P network captures the underlying communication messages in real time and preprocesses the underlying communication messages to obtain a two-dimensional grayscale image.
[0059] Step 2: Input the two-dimensional grayscale image into the pre-trained CNN detection model to capture abnormal textures, edges, and spatial correlation features in the two-dimensional grayscale image, and output the binary classification result and binary classification probability value;
[0060] Step 3: Match the binary classification probability values with the preset threshold, and combine this with the attributes of the affected nodes and the proportion of malicious connections to determine the response level;
[0061] Step 4: Trigger corresponding defense measures based on the response level, including attack node isolation, dynamic network topology adjustment, alarm and log recording. Simultaneously, continuously monitor the defense effectiveness and feed it back to the pre-trained CNN detection model for iterative optimization, including: During the monitoring period T following the implementation of the defense measures, traffic is continuously collected from the affected nodes and time-series image sequences are generated. in, Let T be the two-dimensional grayscale image of the t-th time sequence in the time sequence image sequence, where T is the total number of time sequences in the time sequence image sequence. Identify the abnormal texture connected components determined by the pre-trained CNN detection model for each two-dimensional grayscale image, and calculate the dissipation rate and dissipation type of the total pixel area A(t) of the abnormal texture connected components in adjacent time sequences. Assign a defense effect label to the two-dimensional grayscale image in the next time sequence in the adjacent time sequence, and the defense effect label of the two-dimensional grayscale image in the first time sequence is consistent with that of the two-dimensional grayscale image in the next adjacent time sequence. Extract the comprehensive feature activation map of each direction of the Conv2 layer convolution kernel in the pre-trained CNN detection model on the temporal image sequence, count the number of burst feature points and the combination of undefined new feature activation directions, introduce direction-specific regularization terms for the direction with significant residual features during model training, and calculate the augmentation necessity coefficient for continuously emerging new feature combinations and dynamically augment the convolution kernels in the corresponding directions. The time-series image sequences labeled with defensive effects are merged with historical attack samples to form a reinforcement training set, thus completing the iterative optimization of the model.
[0062] Preferably, the deep learning architecture of the pre-trained CNN detection model includes:
[0063] The input layer is used to receive a 64×64×1 single-channel grayscale image and normalize the image pixel values to the [0,1] range to obtain a standardized input;
[0064] The system consists of three convolutional layers: Conv1 layer with 32 3×3 convolutional kernels to extract low-level edge features of the standardized input; Conv2 layer with 64 3×3 convolutional kernels to extract mid-level texture features of the standardized input; and Conv3 layer with 128 convolutional kernels, including 3×3 convolutional kernels and 5×5 global feature aggregation convolutional kernels, to extract high-level semantic features. All convolutional kernels have a stride of 1, use the Same padding method, and all use ReLU activation function.
[0065] The three pooling layers correspond one-to-one with the three convolutional layers, and the pooling kernel size is 2×2 with a stride of 2, which is used to downsample the output of the convolutional layers.
[0066] Two fully connected layers, containing 256 and 128 neurons respectively, with ReLU activation function and Dropout probability of 0.5, are used to flatten the output of the pooling layer into a one-dimensional feature vector and fuse all high-level features through fully connected operations;
[0067] The output layer contains two neurons with the Softmax activation function, used to output the binary classification result and the binary classification probability value.
[0068] Preferably, the Conv2 layer has 64 3×3 convolution kernels with orientations of 0°, 45°, 90°, and 135°.
[0069] Preferably, matching the binary classification probability value with a preset threshold includes:
[0070] When the pre-trained CNN detection model outputs eclipse attack traffic and the probability value is greater than or equal to the first threshold, it is determined to be an confirmed attack and a defense response is immediately triggered.
[0071] When the output of eclipse attack traffic and the probability value is between the second threshold and the first threshold, it is judged as a suspected attack and enters a temporary monitoring state. At the same time, the frequency of traffic collection from the response node is increased, and the traffic is continuously input into the model for secondary detection. If the probability value of the detection is greater than or equal to the third threshold for M consecutive times, it is upgraded to confirmed attack and the defense response is triggered.
[0072] If the output of eclipse attack traffic is lower than the second threshold, the temporary monitoring status will be lifted.
[0073] Among them, the first threshold > the third threshold > the second threshold.
[0074] Preferably, the response levels include high-risk response, medium-risk response, and low-risk response.
[0075] Preferably, the attack node isolation includes: real-time connection blocking, dynamic entry of node blacklist, and target node connection reset;
[0076] Dynamic network topology adjustments include: optimization of node connection weights, enhanced protection of core nodes, and visual monitoring of the topology structure.
[0077] Alarm and log recording includes: multi-level alarm notifications and full-process log retention.
[0078] In this embodiment, the training samples and training process of the pre-trained CNN detection model include:
[0079] Sample Types and Sources: The training set includes positive samples (normal blockchain traffic data) and negative samples (eclipse attack traffic data), with a 1:1 ratio to ensure balanced model training. Positive samples are collected from normal blockchain operation scenarios of different scales (small testnets, medium-sized consortium chains, and large public chains), covering traffic data at different times and with different numbers of nodes. Negative samples are generated by building a simulated blockchain test environment to simulate scenarios where attackers control malicious nodes to launch eclipse attacks, including attack traffic data with different attack intensities and camouflage strategies. A small number of eclipse attack samples centrally labeled in publicly available blockchain security datasets are also included.
[0080] Sample preprocessing: All samples undergo preprocessing steps consistent with the actual detection process, including traffic cleaning, feature extraction (IP, packet size, packet interval, number of connections, etc.), one-hot encoding conversion, and two-dimensional image mapping, ultimately generating 64×64 single-channel grayscale image samples.
[0081] Dataset partitioning: The constructed sample set is divided into a training set, a validation set, and a test set in a ratio of 7:2:1. The training set is used for iterative updates of model parameters, the validation set is used to monitor overfitting during training and adjust hyperparameters, and the test set is used to evaluate the final detection performance of the model.
[0082] Regarding the model training process:
[0083] Initialization: The weight parameters of the convolutional and fully connected layers are initialized using the He normal distribution, and the bias parameters are initialized to 0; the optimizer is set to the Adam optimizer, the initial learning rate is 0.001, and a learning rate decay strategy is adopted (the learning rate decays to 0.9 every 10 epochs); the cross-entropy loss function is used to adapt to the binary classification task, where epoch refers to the training round, which is the complete process of all samples in the training set completing one forward and backward propagation.
[0084] Iterative training: Training set samples are input into the model in batches (batchsize=32). Forward propagation is used to calculate the prediction results, and the error between the predicted value and the true label is calculated using the loss function. Then, the parameters of each layer are updated using the backpropagation algorithm. During training, after each epoch, the model's accuracy, precision, recall, and F1 score are evaluated using a validation set. If the validation set accuracy does not improve after 5 consecutive epochs, an early stopping mechanism is triggered to prevent overfitting. Here, batchsize refers to the batch size, which is the number of samples input into the model in a single forward and backpropagation process.
[0085] Model optimization: In order to address the overfitting problem that occurs during training, in addition to using Dropout layers and early stopping mechanisms, L2 regularization (regularization coefficient of 0.0001) is introduced to constrain the parameter size; data augmentation techniques (such as image rotation, horizontal flipping, slight pixel perturbation, etc.) are used to expand the diversity of training set samples and improve the model's generalization ability.
[0086] Model Validation and Consolidation: After training, a test set is used for final performance evaluation to ensure that the model detection accuracy is ≥95%, false positive rate is ≤3%, and recall rate is ≥94%. The model parameters that meet the performance requirements are consolidated to generate a deployable CNN detection model file for real-time attack detection.
[0087] In this embodiment, 64 3×3 convolutional kernels are evenly distributed in 4 directions (e.g., 16 in each direction). Each group of convolutional kernels refines the extraction of different texture intensities and densities in the same direction (e.g., the 16 convolutional kernels in the 0° direction can capture different scenes such as "sparse horizontal texture" and "dense horizontal texture" respectively).
[0088] In this embodiment, key nodes in a blockchain P2P network refer to nodes in the blockchain network that undertake core functions such as data forwarding, consensus participation, or data storage, including full nodes, consensus nodes, seed nodes, etc. The security of these nodes directly affects the stability of the entire network.
[0089] Low-level communication messages refer to the raw data units transmitted between nodes in a blockchain P2P network. They include data packets from the network interface layer and the transport layer, carrying core data such as transaction information and block synchronization information between nodes. For example, the data packets corresponding to Ping messages and Find_Node messages transmitted by Ethereum nodes through the devp2p protocol are low-level communication messages.
[0090] Preprocessing involves a series of operations, including cleaning, feature extraction, encoding, and image mapping, on the captured low-level communication messages. The goal is to transform the discrete, high-dimensional raw data into standardized data that can be processed by CNN models.
[0091] A two-dimensional grayscale image is a two-dimensional matrix image that uses grayscale values (0-255) to represent network traffic characteristics. It can intuitively reflect the state and mode of network communication. In this invention, it is specifically a 64×64 single-channel grayscale image.
[0092] Anomalous texture, edges, and spatial correlation features are unique visual characteristics of eclipse attack traffic in 2D grayscale images. Anomalous texture refers to pixel distribution patterns that are inconsistent with those of normal traffic images. Edges refer to regions in the image where grayscale values change abruptly. Spatial correlation features refer to the correlation patterns between pixels in different regions. For example, a large number of repeated connection requests in an eclipse attack will form continuous texture stripes in the image, a feature that can be captured by CNN models.
[0093] Binary classification results are two possible outcomes output by the model: normal traffic or eclipse attack traffic. These are used to determine the current network state. The binary classification probability value represents the confidence level of the corresponding binary classification result, ranging from 0 to 1. The closer the probability value is to 1, the higher the model's confidence in that classification result. For example, if the model outputs a probability value of 0.92 for eclipse attack traffic, it means the model has a 92% confidence level in classifying the current traffic as eclipse attack traffic.
[0094] The attributes of affected nodes refer to the functional positioning of nodes under attack threats in the blockchain network. They are divided into core nodes and ordinary nodes. Core nodes include consensus nodes, ledger nodes, seed nodes, etc., while ordinary nodes refer to nodes that only participate in data synchronization and do not undertake core functions.
[0095] The percentage of malicious connections is the proportion of all inbound and outbound connections of an affected node that are established with malicious nodes (attack nodes identified by the model). For example, if a node has 20 connections, and 12 of them are with malicious nodes, then the percentage of malicious connections is 60%.
[0096] The defensive measures are specific operations used to resist eclipse attacks, including three core measures: attack node isolation, dynamic network topology adjustment, and alarm and log recording. These measures are flexibly combined and executed according to the response level.
[0097] Iterative optimization involves feeding new attack samples and defense effectiveness data collected during the defense process back into the CNN model, retraining the model to improve its ability to identify variant attacks, and achieving continuous improvement in model performance.
[0098] In this embodiment, a libpcap-based traffic monitoring plugin (acquisition engine) is deployed on three full nodes (key nodes) of the Ethereum network to capture TCP / UDP packets (lower-level communication messages) at the network interface layer and transport layer in real time. Subsequently, a preprocessing script cleans, extracts features, performs one-hot encoding, and maps the packets to an image, ultimately generating a 64×64 single-channel grayscale image. For example, a packet corresponding to a captured Ping message, after preprocessing, is represented as a specific pixel distribution area in the grayscale image. The generated grayscale images are input in batches (batchsize=32) into a CNN model trained using TensorFlow. The model extracts abnormal features from the image through convolutional layers, pooling layers, etc., such as continuous texture stripes (abnormal textures) caused by eclipse attacks, and grayscale value abrupt change boundaries (edges). Finally, the output layer outputs the classification result. If the output corresponding to a certain grayscale image is eclipse attack traffic with a probability value of 0.85, it indicates that the model determines that the traffic is eclipse attack traffic with a confidence level of 85%. The system presets a first threshold of 0.8, a second threshold of 0.6, and a third threshold of 0.7. If the model outputs a probability value of 0.85 for eclipse attack traffic (≥ the first threshold of 0.8), the affected node is a consensus node (core node), and the malicious connection ratio is 55%, then it is classified as a high-risk response. If the probability value is 0.65 (between the second threshold of 0.6 and the first threshold of 0.8), the affected node is a normal node, and the malicious connection ratio is 25%, then it is classified as a suspected attack and enters temporary monitoring status. If it is a high-risk response, the system immediately implements attack node isolation (blocking malicious connections and adding them to a blacklist), core node protection enhancement (activating redundant connections), and multi-channel alerts (SMS + platform pop-ups). After the defense is implemented, the system continuously monitors the connection status of the affected nodes, collects new attack samples, adds them to the training set, retrains the CNN model, optimizes the model parameters, and improves the accuracy of identifying similar attacks.
[0099] In this embodiment, for example, a grayscale image corresponding to a certain solar eclipse attack flow, after processing by the input layer, normalizes the image pixel values to the [0,1] interval, resulting in a 64×64×1 standardized tensor input. The value range of each element in the tensor is 0-1, such as the element value corresponding to the original grayscale value 255 being 1, and the element value corresponding to the original grayscale value 128 being 0.5. The initial weights of the 32 3×3 convolutional kernels are initialized using a He normal distribution, and the bias parameters are initialized to 0. The convolutional kernels are convolved with the standardized input, and each convolutional kernel outputs a 64×64 feature map. The 32 convolutional kernels output a total of 32 64×64 feature maps. The feature maps are input into the ReLU activation function, and each element undergoes a non-linear transformation (values less than 0 become 0, values greater than 0 become 1, and so on). (Keep the original features unchanged), and finally obtain the output feature map of Conv1 layer. This feature map mainly contains the low-level edge features of the input image, such as the features corresponding to the boundary regions of gray value abrupt changes in the traffic image. The first pooling layer performs pooling operation on the 32 64×64 feature maps output by Conv1 layer, and selects the maximum value from each 2×2 feature map region as the output. For example, the element value of a certain 2×2 region is [0.3, 0.5, 0.4, 0.6], and the output after max pooling is 0.6. After the pooling operation, the size of the feature map is reduced from 64×64 to 32×32, and the number of 32 feature maps remains unchanged. Finally, 32 32×32 pooled feature maps are obtained, which not only retain the core edge features, but also reduce the data dimension and computation.
[0100] The initial weights of the 64 3×3 convolutional kernels are also initialized using the He normal distribution with a bias of 0. The convolutional kernels are convolved with the output feature maps of the first pooling layer, and each convolutional kernel outputs a 32×32 feature map. The 64 convolutional kernels output a total of 64 32×32 feature maps. After processing by the ReLU activation function, the output feature map of the Conv2 layer is obtained. This feature map mainly contains mid-level texture features, such as the continuous stripe texture features corresponding to the solar eclipse attack flow. The second pooling layer performs max pooling on the 64 32×32 feature maps, reducing the feature map size from 32×32 to 16×16. The number of feature maps remains 64, resulting in 64 16×16 pooled feature maps, which retain the core texture features and further reduce the computational cost.
[0101] The two sizes of convolutional kernels in the Conv3 layer are convolved with the output feature maps of the second pooling layer. The 3×3 convolutional kernel outputs a 16×16 feature map, and the 5×5 convolutional kernel also outputs a 16×16 feature map through Same padding. A total of 128 convolutional kernels output 128 16×16 feature maps. After processing by the ReLU activation function, the output feature map of the Conv3 layer is obtained. This feature map contains high-level semantic features, such as the "centralized connection request" feature that can directly represent the eclipse attack. The third pooling layer performs max pooling on the 128 16×16 feature maps, reducing the feature map size from 16×16 to 8×8, while maintaining the number of feature maps at 128. Finally, 128 pooled feature maps of 8×8 are obtained, providing simplified high-level features for subsequent fully connected layer processing.
[0102] The first fully connected layer (FC1) flattens the 128 8×8 feature maps output from the third pooling layer into a one-dimensional feature vector with a length of 128×8×8=8192. This one-dimensional vector is then input into the FC1 layer, processed by weighted summation of neurons and the ReLU activation function, outputting a feature vector of length 256. During training, 50% of the neurons are randomly deactivated to suppress overfitting. The second fully connected layer (FC2) inputs the 256-dimensional feature vector output from the FC1 layer into the FC2 layer, processes it by weighted summation and the ReLU activation function, and outputs a feature vector of length 128. During training, 50% of the neurons are also randomly deactivated to further suppress overfitting.
[0103] The output layer takes the 128-dimensional feature vector output from the FC2 layer as input, and obtains the original output (logits) through weighted summation of neurons. Then, it is converted into a probability distribution by the Softmax activation function. For example, if the original output is [3.1, 1.2], it becomes [0.89, 0.11] after Softmax transformation. The first neuron corresponds to the probability of eclipse attack flow (0.89), and the second neuron corresponds to the probability of normal flow (0.11). The model finally outputs a binary classification result as eclipse attack flow with a probability value of 0.89.
[0104] This CNN model architecture, through a layered design of convolutional layers, pooling layers, and fully connected layers, achieves progressive extraction from low-level edge features to high-level semantic features. Combined with optimization techniques such as ReLU activation function and Dropout, it ensures both the comprehensiveness and accuracy of feature extraction while effectively suppressing overfitting. It can quickly and accurately identify eclipse attack traffic, solving the problems of traditional technologies relying on manual features and having poor generalization ability. At the same time, the lightweight architecture design meets the real-time detection requirements of blockchain scenarios.
[0105] In this embodiment, the four directions of 0°, 45°, 90°, and 135° designed in this invention can fully cover the horizontal, vertical, and diagonal texture features in the image.
[0106] In this embodiment, a high-risk response is triggered when: the attack target is a core node (such as a consensus node, ledger node, or seed node), or the proportion of malicious connections is ≥50%, or the peak traffic exceeds twice the normal threshold. If the affected node is a consensus node (core node) of the Ethereum network, the model outputs an attack probability value of 0.91, and the proportion of malicious connections is 62%, then a high-risk response is triggered. At this time, all defense measures must be executed in parallel, including blocking all malicious connections in real time, adding the attacking node's IP to the global blacklist and synchronizing it to all nodes, resetting the connection of the attacked consensus node, starting redundant connections for the core node, and issuing alerts through multiple channels such as SMS, telephone, and platform pop-ups.
[0107] Medium-risk response trigger scenario: The attack target is a cluster of 3 or more ordinary nodes, or the proportion of malicious connections is between 30% and 50%. If the affected nodes are 5 ordinary synchronization nodes, the model outputs an attack probability value of 0.83, and the proportion of malicious connections is 38%, then a medium-risk response is triggered; at this time, core defense measures (blocking malicious connections and adding to the blacklist) are executed first, and auxiliary defense measures are implemented simultaneously (optimizing node connection weights and issuing alerts via platform pop-ups and emails).
[0108] Low-risk response trigger scenario: The attack target is a single ordinary node, and the proportion of malicious connections is <30%. For example, if the affected node is a single Hyperledger Fabric ordinary node, the model outputs an attack probability value of 0.81, and the proportion of malicious connections is 22%, then a low-risk response is triggered. In this case, only core defense measures are executed (blocking the connection between the node and the malicious node, adding the attacking node's IP to the local blacklist, and issuing alerts via platform messages), and the attack situation is continuously monitored. There is no need to start resource-intensive measures such as redundant connections.
[0109] By dividing the response levels into three levels, the defense resources can be precisely deployed, avoiding a one-size-fits-all defense model. While ensuring the effectiveness of the defense, the impact of the defense measures on the normal operation of the blockchain network is minimized, the system's resource utilization efficiency is improved, and differentiated protection solutions are provided for attacks of different intensities.
[0110] In this embodiment, M is the threshold for the number of consecutive two detections, which is a positive integer and ranges from 3 to 5 times. It can be adjusted according to the scale of the blockchain network.
[0111] The beneficial effects of the above technical solution are: through the fully automated design, a closed-loop protection from traffic collection to model optimization is realized, which solves the problems of disconnect between detection and defense and delayed response in existing technologies. It can quickly identify solar eclipse attacks and accurately trigger defense measures. At the same time, the protection capability is continuously improved through model iteration, taking into account both detection accuracy and real-time performance.
[0112] This invention provides a CNN-based method for detecting blockchain eclipse attacks, such as... Figure 2 As shown, step 1 includes:
[0113] Step 11: Based on the acquisition engine composed of traffic monitoring plugins or bypass acquisition devices, capture the raw data packets of the network interface layer and transport layer in real time and regard them as the underlying communication messages.
[0114] Step 12: Based on DPI technology, identify the TCP / UDP traffic related to the blockchain P2P protocol in the underlying communication messages, and remove damaged fragment packets, duplicate packets, and noise data unrelated to the connection state to obtain the cleaned traffic;
[0115] Step 13: Slice the cleaned flow rate according to a fixed time window to obtain independent flow rate sample blocks;
[0116] Step 14: Extract numerical features and categorical features reflecting network connection status and node behavior from each traffic sample block, and use one-hot encoding to obtain a multi-dimensional feature vector;
[0117] Step 15: Map each feature in all extracted multidimensional feature vectors to the standard grayscale range of [0, 255] and convert the abstract communication indicators into visualized pixel intensity information to achieve feature normalization and grayscale conversion;
[0118] Step 16: Based on the predefined feature correlation matrix, map logically related features to adjacent positions in the two-dimensional matrix and fill in the blanks. The pixel matrix is processed and zero-padding is applied to empty positions to generate a two-dimensional grayscale image, wherein the two-dimensional grayscale image is 64 64-channel grayscale image.
[0119] In this embodiment, the damaged fragment packets are data packets with incomplete data due to network transmission errors, node failures, or other reasons. These types of data packets cannot be parsed normally and need to be removed from the traffic.
[0120] Set a fixed time window of 500ms, meaning that traffic every 500ms is considered an independent sample block.
[0121] Numerical features are traffic characteristics that can be quantified numerically, reflecting attributes such as the timing and scale of network connections, including the arrival time interval (IAT), packet length distribution, connection duration, and inbound / outbound traffic ratio. Categorical features are features that cannot be directly quantified numerically and can only be classified. They are related to the message types of blockchain P2P protocols, including message types such as Find_Node, Ping, Pong, and Neighbors.
[0122] Multidimensional feature vectors are vector data formed by integrating the numerical and categorical features of each traffic sample block. Each feature corresponds to one dimension of the vector. For example, the multidimensional feature vector of a sample block is [IAT mean = 10ms, packet length mean = 200 bytes, Find_Node = 1, Ping = 0, etc.].
[0123] In this embodiment, a predefined feature correlation matrix is used to characterize the degree of correlation between various traffic features, providing a basis for feature space mapping of the two-dimensional grayscale image. Its specific construction method is as follows: Feature set determination: This involves determining the full feature set used to construct the matrix, including numerical features such as packet arrival time intervals, packet length distribution, connection duration, and inbound / outbound traffic ratio, as well as categorical features for protocol message types such as Ping, Pong, Find_Node, and Neighbors, totaling [amount missing]. One characteristic.
[0124] Sample set construction: Collect massive traffic samples under normal operation scenarios of the blockchain network, as well as eclipse attack traffic samples with different attack intensities and different camouflage strategies, and construct a feature sample set of no less than 100,000 records to ensure that the samples cover all business scenarios and attack scenarios.
[0125] Correlation coefficient calculation: For any two features in the feature set, calculate the Pearson correlation coefficient between them based on the sample set. The calculation formula is as follows: in, Let x be the Pearson correlation coefficient between feature x and feature y, with a value range of [-1, 1]. Let x and y be the values of features in the i-th 3rd sample. Let x and y be the mean values of features x and y in the sample set. i is the total number of samples, and i3 is the sample number.
[0126] Matrix construction and threshold setting: Each feature is represented by rows and columns. The Pearson correlation coefficients between pairs of features are then filled into the corresponding positions to construct... The feature correlation matrix is used; two features with an absolute correlation coefficient ≥ 0.6 are defined as logically closely related features, and when generating a two-dimensional grayscale image, they are mapped to adjacent positions in the pixel matrix.
[0127] In this embodiment, the nDPI open-source DPI engine is used to parse data packets and identify relevant TCP traffic (port number 8333). Damaged fragmented packets (data packets with incorrect checksums) are removed by checking the data packet checksum. Duplicate packets are removed by comparing the data packet timestamp + source IP + destination IP + data length combination. Noisy data (such as HTTP browser traffic on port 80) is removed by filtering traffic from ports other than 8333. Finally, cleaned data containing only P2P protocol traffic is obtained. A fixed time window of 500ms is set, and the cleaned continuous traffic is divided according to this time interval. For example, traffic from 10:00:00.000 to 10:00:00.500 constitutes the first sample block, traffic from 10:00:00.500 to 10:00:01.000 constitutes the second sample block, and so on, resulting in multiple independent traffic sample blocks. Numerical features are extracted from each sample block: the mean of the data packet arrival time interval (IAT) is 8ms, and the variance of the packet length distribution is... The maximum connection duration is 120s, and the inbound / outbound traffic ratio is 1.2. Categorical features are extracted: including Ping and Neighbors messages, but excluding Find_Node and Pong messages. One-hot encoding is performed on the categorical features: Ping messages are encoded as [1,0], Neighbors messages as [0,1], Find_Node messages as [0,0], and Pong messages as [0,0]. These are then integrated to obtain a multi-dimensional feature vector. The min-max normalization method is used to map the values of numerical features to the [0,255] interval. For example, the IAT mean of 8ms (original range 0-100ms) is normalized to 20.4, rounded to the nearest integer of 20. The encoded values of categorical features (0 or 1) are directly mapped to 0 or 255; for example, the Ping message encoding [1,0] is mapped to 255.
[0128] Based on the feature correlation matrix, the "number of connections" and "request frequency" (correlation coefficient 0.85) are mapped to adjacent positions (10,10) and (10,11) in a 64×64 matrix, and the mean IAT and mean packet length (correlation coefficient 0.78) are mapped to positions (12,12) and (12,13). All normalized feature values are filled into the corresponding positions in the matrix, and empty positions in the matrix without filled feature values (such as (15,20)) are filled with 0. Finally, a 64×64 single-channel grayscale image is generated. The high grayscale value areas in the image correspond to the key features of the traffic. It should be noted that features with an absolute correlation coefficient ≥ 0.6 are judged to be logically closely related and mapped to adjacent positions in the two-dimensional matrix; features with an absolute correlation coefficient < 0.6 are filled into the remaining positions in a random order to ensure the rationality of the feature space distribution.
[0129] The beneficial effects of the above technical solution are as follows: the preprocessing process transforms high-dimensional, discrete blockchain P2P traffic data into standardized two-dimensional grayscale images through precise traffic filtering, comprehensive feature extraction, and scientific image mapping. This not only preserves the core correlation features in the traffic but also reduces data complexity, laying the foundation for efficient detection by subsequent CNN models and solving the problem of failure of high-dimensional nonlinear feature processing in traditional technologies.
[0130] This invention provides a CNN-based method for detecting blockchain eclipse attacks. It introduces a direction-specific regularization term during model training for directions with significant residual features, and calculates an augmentation necessity coefficient for continuously emerging new feature combinations, dynamically augmenting the convolutional kernels in the corresponding directions. The method includes: Based on the extracted comprehensive feature activation map, the activation values on the comprehensive feature activation map in each direction exceeding [a certain threshold] are statistically analyzed. The number of burst feature points And whether there are any undefined new feature activation direction combinations in each direction. in, These represent the mean and standard deviation of the activation values for all integrated feature activation maps, respectively. This is a correction factor; When the number of burst feature points in direction d Below the preset threshold At that time, the feature point burst mode residuals in direction d are determined to be significant, and in the subset of convolution kernels in direction d. In the next round of training, a direction-specific regularization term is introduced. The expression is: in, Convolution kernel subsets The weights of the i-th and j-th convolutional kernels; The cross-entropy loss function; The cosine similarity function; This is the control coefficient; The weights of the i-th convolutional kernel in direction d Find the gradient; Meanwhile, if new feature activation direction combinations are continuously detected in direction d for at least two monitoring periods, And with In the current model, the attack category dispersion of the comprehensive feature activation map of the corresponding Conv2 layer for the attack sample is lower than the preset dispersion. At this point, calculate the expansion necessity coefficient.
[0131] in, In direction d Duration; Features Mutual information with attack label Y; Features Entropy; The total duration of a single monitoring cycle; like At this point, at least one convolutional kernel is dynamically added in direction d of the Conv2 layer, and the architecture is updated, where, The necessity threshold; Otherwise, keep the original model architecture unchanged.
[0132] In this embodiment, at least one convolutional kernel is dynamically added in direction d of the Conv2 layer, including:
[0133] Locking to satisfy All directions are analyzed, and the comprehensive feature activation map of each locked direction output in the Conv2 layer within the monitoring period T is extracted and regarded as the map to be analyzed.
[0134] The local gradient directions of each burst feature point in the image to be analyzed are statistically analyzed, and the normalized entropy is calculated. Where B is the total number of intervals that divide the 360° direction; This represents the probability that the gradient direction of the burst feature point corresponding to the locked direction falls within the b-th interval.
[0135] Density clustering based on spatial location is performed on all burst feature points in the graph to be analyzed to obtain C spatial clusters, where each cluster is regarded as a potential spatial sub-pattern;
[0136] Determine the number of convolutional kernels that need to be amplified for the corresponding locked direction. ,in, This is a normalization factor corresponding to the dispersion of the locking direction, with a value ranging from 0 to 1, used to quantify the diversity of directions; This is a preset capacity expansion factor used to control the aggressiveness of the overall expansion. It is a rounding function;
[0137] Based on the main direction of the spatial cluster distribution of each spatial cluster, it is mapped to the existing basic convolution kernel that is closest to the corresponding graph to be analyzed. The mapped basic convolution kernel is then subjected to a structured linear transformation and perturbation related to the statistical characteristics of the corresponding spatial sub-pattern. This determines the direction-spatial sub-pattern of each new kernel from the initialization stage, which is biased towards capturing the corresponding locking direction.
[0138] In this embodiment, the dynamic expansion mechanism of the convolutional kernel adopts a periodic offline execution mode, rather than real-time online execution, which is fully feasible for practical implementation. The specific implementation rules are as follows: Execution timing and cycle settings: The judgment and execution of dynamic expansion of convolutional kernels adopts a fixed-cycle offline batch processing mode with an execution cycle of 7 days. It is only executed during the off-peak period of blockchain network business (such as 2:00-4:00 am), which will not occupy the computing resources of the system for real-time detection and will not affect the real-time performance of attack detection. At the same time, a minimum execution interval is set, with the interval between two expansion operations not less than 7 days, to avoid system instability caused by frequent modifications to the model architecture.
[0139] Optimized design of computational resources: The calculation of statistics such as mutual information, entropy, and dispersion is only performed on samples corresponding to new feature activation direction combinations that appear continuously for more than two monitoring periods, not on the entire sample set. The number of samples involved in the calculation within a single period is usually no more than 500, resulting in extremely low computational load, which can be completed in minutes on a regular server; Optimization of the necessity coefficient. The calculation involves only basic multiplication and division operations, without complex iterative calculation processes. The determination can be completed quickly by the program without requiring a large amount of computing resources.
[0140] The feasibility of kernel augmentation: Dynamic kernel augmentation is performed only on a subset of kernels in specific directions of the Conv2 layer, without modifying the architecture and parameters of other layers in the model. New kernels are added based on existing base kernels through structured linear transformations and perturbation initialization, eliminating the need for training from scratch. Convergence is achieved with only 5-10 epochs of fine-tuning on a reinforced training set, significantly reducing training costs and time. Testing shows that the total time for a single kernel augmentation and model fine-tuning operation is ≤30 minutes. Once completed, it can seamlessly replace the online model without interrupting system operation.
[0141] In this embodiment, the mathematical formula for the structured linear transformation is: in, For fixed transformation coefficients, and Furthermore, adjustments are made based on the convergence performance after kernel augmentation. S is the existing basis convolution kernel weight matrix of the mapping; S is the spatial sub-pattern statistics matrix (composed of the pixel distribution mean, variance, and covariance of the spatial cluster).
[0142] Perturbation: Gaussian distribution random perturbation is adopted, with the weight perturbation interval being [−0.1, 0.1]. The mean of the Gaussian distribution is 0 and the standard deviation is 0.03, ensuring that the perturbed convolution kernel retains the core features of the base convolution kernel and can adapt to the new spatial sub-pattern.
[0143] Example of initializing a new convolutional kernel: Assume the main direction of a spatial cluster is 30°, the nearest existing base convolutional kernel is the 8th convolutional kernel in the 0° direction (the weight matrix Wbase is a 3×3 matrix), and the spatial sub-pattern statistics matrix S is: The initial weight matrix of the newly added convolutional kernel is: The final initial weights are obtained after Gaussian perturbation.
[0144] In this embodiment, a progressive, fully automated model optimization system is constructed, which goes from quantitative feature analysis to parameter optimization and then to conditional structure expansion. This system takes the evolution of network state image features after defense (such as pixel cluster dissipation and feature point burst mode) as the only signal driving the self-evolution of the model, thus achieving precise alignment between optimization goals and actual combat effects.
[0145] By using image temporal features such as the dissipation rate of abnormal pixel clusters and the residual / newly generated feature point burst patterns as core indicators for quantitatively evaluating defense effectiveness and diagnosing model defects, a direct and quantifiable mapping relationship between cybersecurity events and computer vision features is established.
[0146] The optimization is divided into two logical levels: the first level (parameter optimization) solves the problem of the model's discriminative accuracy for known feature patterns by fine-tuning parameters through techniques such as direction-specific regularization; the second level (structural expansion) solves the problem of the model's expression of new feature patterns by using rigorous conditional judgments and quantification formulas to determine whether and how to add neurons (convolutional kernels) to form an organic whole.
[0147] By imposing constraints on the update gradients of the weights of convolutional kernels in the same direction and penalizing their internal similarity, the set of convolutional kernels is forced to learn more diverse and discriminative features, which in principle improves the model's ability to distinguish between subtle attack patterns and normal fluctuations.
[0148] By combining the duration of the new model with the purity of its information, its calculation is based on mutual information and entropy, scientifically quantifying the urgency and necessity of model expansion, enabling structural expansion decisions to break away from subjective experience and achieve data-driven decision-making.
[0149] Compared to existing techniques that rely solely on periodic retraining through the collection of new samples, this approach enables online, real-time, and on-demand self-evolution of the model. It not only adjusts thresholds and weights but also safely and controllably expands its structure when necessary, significantly improving the speed of adaptation to unknown attack variants and long-term defense effectiveness. At the same time, it effectively avoids catastrophic forgetting through mechanisms such as local fine-tuning, ensuring system stability.
[0150] In this embodiment, the monitoring period T is the length of time for continuous traffic collection and status monitoring of the affected nodes after the defense measures are implemented, used to capture the evolution of attack characteristics and the effectiveness of the defense. For example, based on the transaction frequency and attack response speed of the blockchain network, the monitoring period T is set to 10 minutes, that is, continuous monitoring for 10 minutes after the defense is implemented.
[0151] Time-series image sequence: A set of grayscale images generated by collecting traffic from affected nodes within a monitoring period T at fixed time windows (500ms). For example, 10 minutes × 60 seconds / minute divided by 0.5 seconds / window = 1200 windows, i.e., T = 1200.
[0152] In this embodiment, the entire process of generating defense effect tags adopts fully automated and quantifiable execution logic, without any manual intervention. It can stably and efficiently generate high-quality tags in a real system. The specific implementation steps, stability assurance, and performance verification are as follows: Step 801: Time-series image sequence preprocessing: For the time-series image sequences generated within the monitoring period T Each 64×64 single-channel 2D grayscale image is subjected to a 3×3 kernel-size median filter to filter out salt-and-pepper noise and pixel perturbations in the image, thus avoiding interference from instantaneous traffic fluctuations in the blockchain network on subsequent detection results.
[0153] Step 802: Abnormal Texture Connected Component Identification and Quantization: A mature eight-neighbor connected component detection algorithm in digital image processing is used to identify abnormal texture connected components in each two-dimensional grayscale image. The specific execution rules are as follows: Set the grayscale threshold to 200, and mark pixels with a grayscale value ≥ 200 in the image as abnormal pixels, and pixels with a grayscale value < 200 as background pixels; Traverse all abnormal pixels in the image. Taking the current abnormal pixel as the center, check the pixels in its eight neighboring regions: above, below, left, right, upper left, upper right, lower left, and lower right. If the neighboring pixels are abnormal pixels, they are included in the same connected component, and the coordinates of all pixels in the connected component are recorded. Merge adjacent connected components with a spatial distance of ≤2 pixels to avoid the same attack feature being split into multiple connected components; remove tiny connected components with a total number of pixels <10, as these are all noise interference and are not included in the attack feature quantization range. Calculate the sum of the total pixel areas of all valid anomalous texture connected regions in each image, denoted as the total anomalous feature area A(t) for that time series, where t is the time sequence number of the time series image.
[0154] Step 803: Dissipation Rate Calculation and Dissipation Type Determination: Based on the total area of anomaly features in adjacent time series, calculate the attack feature dissipation rate using the following formula: in, Let be the rate at which the attack signature dissipates from time series t to time series (t+1). Let be the total area of the anomalous features in the t-th time series. Let be the total area of the anomalous features in the (t+1)th time series; if The dissipation rate is directly determined to be 1, corresponding to the fast dissipation type. Here, the t-th time series and the t-th two-dimensional grayscale image are in one-to-one correspondence.
[0155] Based on the dissipation rate calculation results, the dissipation type is determined according to a pre-set fixed rule, as detailed in Table 1.
[0156]
[0157] Step 804: Automated assignment of defense effect labels: Based on the dissipation type determination result, defense effect labels are automatically assigned to images in the time-series image sequence. The assignment rules are as follows: The two-dimensional grayscale image of the (t+1)th time series Assign a defense effect label corresponding to the dissipation type. Each label uniquely corresponds to a dissipation type: fast dissipation corresponds to label code 2 (defense successful), slow dissipation corresponds to label code 1 (defense partially effective), and stagnation or growth corresponds to label code 0 (defense failed); the first time-series two-dimensional grayscale image. Directly inherit the second time series image The defense effect label ensures the continuity of labels in the time-series image sequence; for all time-series images within the monitoring period T, after completing the full label assignment, a time-series consistency check is performed: if the label of a single image is inconsistent with the labels of the two adjacent images, the dissipation type and label are recalculated based on the average dissipation rate of the three time series before and after, to avoid label misassignment caused by instantaneous noise and ensure label quality.
[0158] In this embodiment, to ensure the stability and real-time performance of tag generation, multiple safeguard mechanisms are implemented: Data source consistency guarantee: The traffic data used to generate time series image sequences all undergo the same DPI protocol identification, traffic cleaning, feature extraction, and grayscale mapping process as the detection stage, ensuring that the time series images are completely consistent with the image data format and feature distribution of the input model in the detection stage, avoiding label deviation caused by differences in data sources; Outlier filtering mechanism: targeting outliers appearing in a single time series image. Mutation value, using The criteria for outlier removal are as follows: Exceeding all time series within this monitoring period When the mean is within ±3 standard deviations, use adjacent time series. The mean value is used to replace the outlier to avoid errors in the dissipation rate calculation caused by instantaneous flow pulses; Execution efficiency guarantee: The eight-neighbor connected component detection algorithm and dissipation rate calculation adopted in this solution are both lightweight numerical operations. The entire process of generating labels for a single 64×64 grayscale image takes milliseconds, which fully meets the real-time requirements of the system.
[0159] After 72 hours of continuous testing and verification in an Ethereum consortium blockchain test environment (100 consensus nodes, 500 ordinary nodes, simulating 12 eclipse attack variant scenarios), based on the model with the improved defense effect label of this solution, the identification recall rate for eclipse variant attacks where the existing defense system fails has increased from 81.2% of the baseline model to 95.9%, a relative improvement of 42.7%.
[0160] In this embodiment, conventional iterative optimization methods for CNN models in the prior art all use manually labeled attack / normal binary tags, which can only optimize by improving classification accuracy. This has core drawbacks such as a disconnect between the optimization goal and the actual protection goal, high cost of manual labeling, delayed sample updates, and inability to adapt to rapidly evolving attacks. The defense effect labeling mechanism of this solution brings the following significant benefits: The defense effectiveness label in this scheme directly characterizes the suppression effect of defense measures on attacks, shifting the goal of model iteration and optimization from improving classification accuracy to enhancing the ability to identify attack samples that breach defenses. This deeply aligns the model optimization direction with actual security protection objectives. Testing showed that the model iterated based on this labeling mechanism improved the recall rate for identifying the variant eclipse attack (defense failure type) from 81.2% to 95.9%, an increase of 42.7%, significantly enhancing the defense capabilities against persistent and variant attacks.
[0161] This solution eliminates the need for security experts to manually label samples. Based on the temporal characteristics of traffic after defense execution, it continuously generates attack samples with fine-grained labels, solving the industry pain points of long labeling cycles, high costs, and lagging samples in existing technologies. The model's adaptation speed to new variant attacks is reduced from days to minutes, enabling real-time capture and learning of new attack characteristics, significantly improving the system's responsiveness to dynamically evolving attacks.
[0162] Differentiated loss weight allocation can be implemented during model iterative training: samples where defenses fail are assigned 3 times the base loss weight, samples where defenses are effective are assigned 1.5 times the base loss weight, and samples where defenses are successful are assigned 1 times the base loss weight. This mechanism allows the model to focus on learning attack features that are easily breached while avoiding overfitting. Testing showed that the false positive rate of the iterative model decreased from 4.1% to 2.53% in complex dynamic environments such as network congestion and node expansion, significantly improving its anti-interference and generalization capabilities.
[0163] In this embodiment, the comprehensive feature activation map is a superposition of the activation responses of convolutional kernels in each direction of the Conv2 layer on a temporal image sequence. It can intuitively reflect the capture effect of convolutional kernels in each direction on attack features. The higher the activation value, the higher the matching degree between the convolutional kernel in that direction and the attack feature. By extracting the activation value of each convolutional kernel in the Conv2 layer on each temporal image, the activation values of 16 convolutional kernels in the same direction are superimposed to obtain the comprehensive feature activation map for each direction.
[0164] The mean activation value is the average of the activation values of all pixels in the overall feature activation map, reflecting the overall activation level.
[0165] The standard deviation of activation values reflects the dispersion of activation values across all pixels in the overall feature activation map.
[0166] The correction coefficient is a parameter used to adjust the activation value threshold. It is calibrated experimentally to screen for burst-like feature points that are significantly higher than the normal activation level. In this embodiment, the parameter adaptation table for different scenarios is shown in Table 2.
[0167] Table 2 Parameter Adaptation Table for Different Scenarios
[0168]
[0169] In this embodiment, the complete list of activated direction combinations is: {0°}, {45°}, {90°}, {135°}, {0°,45°}, {0°,90°}, {0°,135°}, {45°,90°}, {45°,135°}, {90°,135°}, {0°,45°,90°}, {0°,45°,135°}, {0°,90°,135°}, {45°,90°,135°}, {0°,45°,90°,135°}.
[0170] The new feature activation direction combination is a feature combination formed by the simultaneous activation of multiple directional convolution kernels, indicating the emergence of a new attack mode (variant attack). For example, the simultaneous high-intensity activation of 0° and 45° directional convolution kernels forms an undefined combination. ={0°,45°}.
[0171] Preset threshold The critical value used to determine whether the residual burst mode of feature points in direction d is significant.
[0172] Convolution kernel subset It is the set of all convolutional kernels in the corresponding direction d in the Conv2 layer, such as the 16 convolutional kernels in the 0° direction. .
[0173] New feature activation direction combination This refers to undefined feature activation combinations appearing in direction d, such as a combination of dense texture and abrupt edge changes in the 45° direction. ={Dense texture, edge mutation}.
[0174] Attack category discreteness is used to quantify model pairs The degree of ambiguity in the classification of the attack samples is calculated using Shannon entropy. Lower dispersion indicates a more ambiguous classification boundary for that class of samples. When dispersion < When this occurs, it indicates that the model cannot effectively distinguish between this type of attack sample and normal samples.
[0175] Attack label: 1 indicates an attack, 0 indicates normal.
[0176] Necessity threshold The critical value used to determine whether the convolution kernel needs to be expanded, when When the value is greater than Γ0, it indicates that increasing the convolutional kernel can significantly improve the model performance and trigger the convolutional kernel to increase.
[0177] The reinforcement training set, composed of time-series image sequences, defense effect labels, and historical attack samples, is used for iterative training of the model and can improve the model's ability to identify new attack patterns. The reinforcement training set is formed by merging 1200 time-series images and their defense effect labels within the monitoring period T with 10,000 historically accumulated attack samples and 20,000 normal samples.
[0178] In this embodiment, a direction-specific regularization term is introduced. With cross-entropy loss function It is compatible, will not cause training conflicts, and can ensure stable convergence during the training process. The specific design and implementation are described below: How regularization terms and loss functions are integrated: The total loss function for model training is... Among them, the direction-specific regularization term It only applies to a subset of convolutional kernels in the corresponding direction within the Conv2 layer, without affecting parameter updates in other layers of the model, thus avoiding damage to the effective features already learned by the model; the regulation coefficient in the regularization term... The default value is 0.0005, which can be adjusted to suit different network scenarios to ensure that the constraint strength of the regularization term is within a reasonable range and will not dominate the optimization direction of the loss function, but only serve as a supplementary constraint to the cross-entropy loss function.
[0179] Convergence guarantee mechanism: The regularization term adopts the gradient constraint form of L2 norm, which belongs to the category of convex optimization and is consistent with the optimization direction of the cross-entropy loss function, thus avoiding training oscillations caused by conflicting optimization objectives; the regularization term introduces a cosine similarity penalty term for convolutional kernels in the same direction, forcing convolutional kernels in the same direction to learn differentiated features, avoiding redundancy of convolutional kernel parameters, which can accelerate the convergence speed of the model and reduce the risk of overfitting during training; a gradient pruning mechanism is adopted during training, setting the maximum gradient norm to 5.0. When the gradient norm of parameter updates exceeds the threshold, pruning is performed to further avoid the gradient explosion problem caused by the introduction of the regularization term and ensure stable convergence during training.
[0180] Actual training results verification: Tests showed that introducing a direction-specific regularization term significantly improved the model's convergence speed, further reduced the risk of overfitting, and effectively optimized the model's F1 score.
[0181] In this embodiment, traditional L2 regularization imposes indiscriminate constraints on all convolutional kernels, resulting in insufficient feature discrimination. In this scheme, the direction-specific regularization term targets convolutional kernels in the same direction and forces them to learn diverse features by penalizing the similarity of weights, thereby improving the distinguishability between subtle attack patterns and normal fluctuations by 30%.
[0182] Existing technologies mostly rely on manually setting fixed thresholds to determine whether to expand the convolutional kernel, which is highly subjective. Based on quantitative calculations using mutual information and entropy, and taking into account both the duration of the new pattern and information purity, the accuracy of structural expansion decisions is improved by 40%.
[0183] Existing technologies only optimize models through parameter fine-tuning or sample expansion, which cannot adapt to unknown attack variants. This invention provides a two-layer system of parameter optimization and structural expansion, which not only solves the problem of the accuracy of the discrimination of known attack patterns, but also can quickly adapt to unknown variants, thus improving the model's adaptation speed by an order of magnitude.
[0184] The beneficial effects of the above technical solution are as follows: This iterative optimization process achieves dynamic evolution of the model through time-series image acquisition, dissipation feature analysis, feature activation map mining, regularization optimization, and convolution kernel expansion. It not only solves the problem of low recognition rate of variant attacks in existing models, but also continuously improves the detection accuracy and generalization ability of the model through defense effect feedback, forming a complete closed loop of detection-defense-optimization, ensuring that the system can adapt to the ever-evolving eclipse attack methods in the blockchain network.
[0185] The above test data and performance improvement are merely exemplary verification results of this invention under a specific test environment. Those skilled in the art will understand that performance may fluctuate reasonably under different blockchain network scales, number of nodes, and attack scenarios, which will not affect the implementation of the core technical solution of this invention or the realization of its beneficial effects.
[0186] Obviously, those skilled in the art can make various modifications and variations to this invention without departing from its spirit and scope. Therefore, if these modifications and variations fall within the scope of the claims of this invention and their equivalents, this invention also intends to include these modifications and variations.
Claims
1. A CNN-based method for detecting blockchain eclipse attacks, characterized in that, include: Step 1: The acquisition engine deployed on the key nodes of the blockchain P2P network captures the underlying communication messages in real time and preprocesses the underlying communication messages to obtain a two-dimensional grayscale image. Step 2: Input the two-dimensional grayscale image into the pre-trained CNN detection model to capture abnormal textures, edges, and spatial correlation features in the two-dimensional grayscale image, and output the binary classification result and binary classification probability value; Step 3: Match the binary classification probability values with the preset threshold, and combine this with the attributes of the affected nodes and the proportion of malicious connections to determine the response level; Step 4: Trigger corresponding defense measures based on the response level, including attack node isolation, dynamic network topology adjustment, alarm and log recording. Simultaneously, continuously monitor the defense effectiveness and feed it back to the pre-trained CNN detection model for iterative optimization, including: During the monitoring period T following the implementation of the defense measures, traffic is continuously collected from the affected nodes and time-series image sequences are generated. ,in, Let T be the two-dimensional grayscale image of the t-th time sequence in the time sequence image sequence, where T is the total number of time sequences in the time sequence image sequence. Identify the abnormal texture connected components determined by the pre-trained CNN detection model for each two-dimensional grayscale image, and calculate the dissipation rate and dissipation type of the total pixel area A(t) of the abnormal texture connected components in adjacent time sequences. Assign a defense effect label to the two-dimensional grayscale image in the next time sequence in the adjacent time sequence, and the defense effect label of the two-dimensional grayscale image in the first time sequence is consistent with that of the two-dimensional grayscale image in the next adjacent time sequence. Extract the comprehensive feature activation map of each direction of the Conv2 layer convolution kernel in the pre-trained CNN detection model on the temporal image sequence, count the number of burst feature points and the combination of undefined new feature activation directions, introduce direction-specific regularization terms for the direction with significant residual features during model training, and calculate the augmentation necessity coefficient for continuously emerging new feature combinations and dynamically augment the convolution kernels in the corresponding directions. The time-series image sequences labeled with defensive effects are merged with historical attack samples to form a reinforcement training set, thus completing the iterative optimization of the model.
2. The CNN-based blockchain eclipse attack detection method according to claim 1, characterized in that, Step 1 includes: The acquisition engine, based on traffic monitoring plugins or bypass acquisition devices, captures raw data packets from the network interface layer and transport layer in real time and treats them as underlying communication messages. Based on DPI technology, TCP / UDP traffic related to the blockchain P2P protocol in the underlying communication messages is identified, and damaged fragment packets, duplicate packets, and noise data unrelated to the connection state are removed to obtain the cleaned traffic. The cleaned flow rate is sliced according to a fixed time window to obtain independent flow rate sample blocks; Numerical features and categorical features reflecting network connection status and node behavior are extracted from each traffic sample block, and multidimensional feature vectors are obtained using one-hot encoding. Each feature in all extracted multidimensional feature vectors is mapped to the standard grayscale range of [0, 255] and the abstract communication indicators are converted into visualized pixel intensity information to achieve feature normalization and grayscale conversion. Based on a predefined feature correlation matrix, logically related features are mapped to adjacent positions in a two-dimensional matrix, and then filled in. The pixel matrix is processed and zero-padding is applied to empty positions to generate a two-dimensional grayscale image, wherein the two-dimensional grayscale image is 64 64-channel grayscale image.
3. The CNN-based blockchain eclipse attack detection method according to claim 1 or 2, characterized in that, The deep learning architecture of the pre-trained CNN detection model includes: The input layer is used to receive a 64×64×1 single-channel grayscale image and normalize the image pixel values to the [0,1] interval to obtain a standardized input; The system consists of three convolutional layers: Conv1 layer with 32 3×3 convolutional kernels to extract low-level edge features of the standardized input; Conv2 layer with 64 3×3 convolutional kernels to extract mid-level texture features of the standardized input; and Conv3 layer with 128 convolutional kernels, including 3×3 convolutional kernels and 5×5 global feature aggregation convolutional kernels, to extract high-level semantic features. All convolutional kernels have a stride of 1, use the Same padding method, and all use ReLU activation function. The three pooling layers correspond one-to-one with the three convolutional layers, and the pooling kernel size is 2×2 with a stride of 2, which is used to downsample the output of the convolutional layers. Two fully connected layers, containing 256 and 128 neurons respectively, with ReLU activation function and Dropout probability of 0.5, are used to flatten the output of the pooling layer into a one-dimensional feature vector and fuse all high-level features through fully connected operations; The output layer contains two neurons with the Softmax activation function, used to output the binary classification result and the binary classification probability value.
4. The CNN-based blockchain eclipse attack detection method according to claim 3, characterized in that, The Conv2 layer has 64 3×3 convolutional kernels with orientations of 0°, 45°, 90°, and 135°.
5. The CNN-based blockchain eclipse attack detection method according to claim 1, characterized in that, Matching binary classification probability values with preset thresholds includes: When the pre-trained CNN detection model outputs eclipse attack traffic and the probability value is greater than or equal to the first threshold, it is determined to be an confirmed attack and a defense response is immediately triggered. When the output of eclipse attack traffic and the probability value is between the second threshold and the first threshold, it is judged as a suspected attack and enters a temporary monitoring state. At the same time, the frequency of traffic collection from the response node is increased, and the traffic is continuously input into the model for secondary detection. If the probability value of the detection is greater than or equal to the third threshold for M consecutive times, it is upgraded to confirmed attack and the defense response is triggered. If the output of eclipse attack traffic is lower than the second threshold, the temporary monitoring status will be lifted. Among them, the first threshold > the third threshold > the second threshold.
6. The blockchain eclipse attack detection method based on CNN according to claim 1, characterized in that, The response levels include high-risk response, medium-risk response, and low-risk response.
7. The CNN-based blockchain eclipse attack detection method according to claim 1, characterized in that, The isolation of attacking nodes includes: real-time connection blocking, dynamic entry of node blacklists, and resetting of target node connections; Dynamic network topology adjustments include: optimization of node connection weights, enhanced protection of core nodes, and visual monitoring of the topology structure. Alarm and log recording includes: multi-level alarm notifications and full-process log retention.
8. The CNN-based blockchain eclipse attack detection method according to claim 1, characterized in that, For directions where feature residuals are significant, a direction-specific regularization term is introduced during model training. Additionally, for continuously emerging new feature combinations, an augmentation necessity coefficient is calculated, and the convolutional kernels in the corresponding directions are dynamically augmented. This includes: Based on the extracted comprehensive feature activation map, the activation values on the comprehensive feature activation map in each direction exceeding [a certain threshold] are statistically analyzed. The number of burst feature points And whether there are any undefined new feature activation direction combinations in each direction. in, These represent the mean and standard deviation of the activation values for all integrated feature activation maps, respectively. This is a correction factor; When the number of burst feature points in direction d Below the preset threshold At that time, the feature point burst mode residuals in direction d are determined to be significant, and in the subset of convolution kernels in direction d. In the next round of training, a direction-specific regularization term is introduced. The expression is: in, Convolution kernel subsets The weights of the i-th and j-th convolutional kernels; The cross-entropy loss function; The cosine similarity function; This is the control coefficient; The weights of the i-th convolutional kernel in direction d Find the gradient; Meanwhile, if new feature activation direction combinations are continuously detected in direction d for at least two monitoring periods, And with The corresponding attack sample under the current model is... The attack category dispersion of the layer's comprehensive feature activation map is lower than the preset dispersion. At this point, calculate the expansion necessity coefficient. : in, In direction d Duration; Features Mutual information with attack label Y; Features Entropy; The total duration of a single monitoring cycle; if At this point, at least one convolutional kernel is dynamically added in direction d of the Conv2 layer, and the architecture is updated, where, The necessity threshold; Otherwise, keep the original model architecture unchanged.