This paper first preprocesses gate-level netlists by uniformly modeling them as standardized directed acyclic graphs (DAGs) to explicitly characterize signal flow relationships within circuits. Building upon this foundation, an improved Louvain community detection algorithm is employed to partition the circuit graph. This algorithm enhances modeling capabilities for gate-level circuit structure and functional characteristics by introducing directed modularity functions, resolution parameters, and logic gate semantic weighting strategies. Following community partitioning, the original circuit is decomposed into several structurally compact, functionally coherent community subgraphs. For these subgraphs, this paper enriches the feature system beyond traditional extraction methods, characterizing potential Hardware Trojan behavior patterns across three dimensions: topological features, functional features, and anomaly metrics. Specifically, topological features focus on structural attributes within communities, such as the proportion of XOR/NAND gates, equivalent feedback paths, and maximum path depth. Functional features describe the dynamic behavior of subcircuits through output entropy and power variance descriptors under random or specific stimuli. Anomaly metrics utilize KL divergence and Jensen–Shannon distance to evaluate the deviation in feature distributions between communities and their corresponding clean circuits. Finally, these community-level features are fed into models such as CommunityGNN, CommunityGAT, Graph-Based Detector, and Local Outlier Factor to achieve effective detection and precise localization of Hardware Trojans. The overall detection methodology is illustrated in the figure below
Figure 1.
3.1. Expanded Circuit Dataset
In practical model training, the Trust-Hub database contains a limited number of original benchmark circuits for Hardware Trojan detection. Each benchmark typically includes only dozens of instances, making it difficult to support the demand for large-scale training samples in deep learning models. To address this, this paper generates many functionally equivalent clean circuits and corresponding trojan-injected circuits through an automated process based on the original benchmarks. This approach builds a comprehensive and structurally diverse experimental dataset.
This paper evaluates the proposed method against post-synthesis Trojan insertion by an untrusted third-party foundry, using c880, s27, and s1488 from Trust-Hub as foundational circuits. The attacker model assumes complete netlist access with functional equivalence constraints, targeting rare-trigger activation (combinational or sequential) to evade detection. c880 is a classic combinational logic benchmark, featuring moderate structural complexity and logic functionality entirely determined by current inputs. Its verification process is straightforward, and simulation efficiency is high, making it suitable for generating diverse structural variants. Additionally, its logic cone and critical paths are well-defined, facilitating structural feature extraction. s27 and s1488 are classic small-scale and medium-scale sequential logic benchmarks proposed at ISCAS’89, respectively. They feature finite state spaces and strong controllability, supporting exhaustive or near-exhaustive verification. These characteristics facilitate sequential trigger condition design and rapid algorithm iteration. These three circuit types complement each other at both combinational and sequential logic levels, providing a unified and representative experimental platform for generating diverse combinational-triggered and sequential-triggered Hardware Trojans.
Clean circuit generation prioritizes functional equivalence while introducing structural variations through multiple logic optimization sequences. Specifically, operations such as redundant logic removal, node restructuring, rewriting and substitution, and multi-level logic optimization from synthesis tools (e.g., ABC) are employed. Different execution sequences and parameter configurations generate functionally equivalent yet structurally distinct logic networks. Subsequently, the universal Boolean network is mapped to a specific process cell library. Unlike area-optimized or delay-optimized mapping, this paper employs a random decision-based mapping strategy. This allows the synthesizer to randomly select from multiple equivalent decomposition schemes, yielding clean circuits with significantly different topologies and enhanced unpredictability. Such circuits are better suited for constructing diverse training samples.
To prevent generating invalid circuits or highly similar samples, diversity constraints are introduced during generation (
1). Newly generated circuits are filtered using structural distance constraints, ensuring sufficient differentiation from existing samples in node distribution, edge connectivity characteristics, and topological depth. This effectively enhances the structural diversity of the dataset while reducing the risk of model overfitting:
where
,
and
denotes node type distribution difference (L1 distance, KL divergence), edge count and fanout distribution difference, topological depth or hierarchical distribution difference. A minimum distance threshold
is set. If (
2):
If the similarity is too high, the circuit is discarded, and a new random mapping is performed. This iterative process ensures the generated clean circuits exhibit sufficient structural diversity.
Before generating trojan circuits, this paper constructs a series of malicious logic variants with enhanced stealthiness, and diverse trigger conditions based on the original baseline circuit through an automated process. These variants are then embedded into the original circuit to form many trojan training samples. To ensure the systematic and scalable generation of trojan circuits, a parameterized design approach based on classic trojan templates is adopted. Specifically, drawing from the open-source Hardware Trojan dataset Trust-Hub and related research, five representative Hardware Trojan trigger templates were summarized and selected: counter-triggered [
26], rare-event signal-triggered [
27], state machine-triggered [
28], comparator-triggered [
29], and multi-point distributed trojans [
30]. The trigger mechanisms and key parameter configurations for each trojan type are shown in
Table 1.
Based on the structural characteristics of the selected original circuit and the trigger conditions of different templates, trojan templates are randomly selected and their trigger parameters are instantiated during the generation process. This approach constructs Trojan circuit variants with diverse structures and behaviors. The trigger mechanism is a core factor in Hardware Trojan design, directly determining the difficulty of activation and the concealment of the Trojan. This paper employs a probability-based trigger design strategy. First, extensive logic simulation is performed on the target circuit. By analyzing tens of thousands to millions of test vectors, the signal probabilities at each node under normal operating conditions are statistically determined. This process identifies rare nodes with low switching probabilities as potential trigger sources. To further reduce the risk of accidental activation, multiple rare nodes are combined to form composite trigger conditions, significantly enhancing trigger rarity and concealment.
After completing the Trojan horse logic embedding, the generated circuit samples undergo rigorous validity verification. First, structural consistency checks are performed to ensure the absence of multiple drivers, undriven nodes, and topological loops within the circuit. Subsequently, for combinational logic circuits (e.g., c880), formal equivalence verification is employed to guarantee functional consistency. For sequential circuits containing flip-flops (e.g., s27 and s1488), functional verification is achieved through large-scale random simulation. Simultaneously, the Trojan horse must be triggerable under random inputs while maintaining a low activation probability. Only when all structural and functional constraints are satisfied is the corresponding circuit sample included in the final experimental dataset. In total, 2400 circuit instances are generated (1200 clean and 1200 Trojan-inserted), with specific per-type composition and train/validation/test split detailed in
Section 4.2.
3.2. Gate-Level Netlist to Directed Acyclic Graph Conversion
When constructing the directed acyclic graph (DAG) corresponding to the gate-level netlist, the original netlist is first parsed using standardized methods to remove redundant formatting characters, yielding a unified, parsable netlist representation. Subsequently, the netlist structure is parsed to extract logic gates, flip-flops, and port instances, assigning a unique identifier to each node to establish one-to-one mapping between netlist objects and graph nodes.
During graph construction, directed edges are established based on each component’s fan-in and fan-out relationships to explicitly represent signal drive directions. Concurrently, necessary timing dependencies are introduced by incorporating sequential element boundaries (i.e., flip-flops/registers) as natural breakpoints. To satisfy DAG modeling requirements, pure combinational loops (cycles within combinational logic without intervening flip-flops) are detected and resolved through topological sorting and depth-first search. These sequential elements serve as breakpoints to sever combinational feedback paths: edges crossing flip-flop boundaries are preserved as directed connections (FF input to FF output), while cyclical paths within pure combinational logic are disrupted. This approach ensures that sequential structures—including sequential Trojan triggers such as state machines and counters—are retained as directed paths through flip-flop nodes rather than being eliminated.
Following loop elimination, lightweight optimizations are applied to the graph structure, including redundant node merging and path rearrangement, yielding a compact, semantically clear DAG. The resulting DAG serves as a unified intermediate representation that fully preserves node logic attributes and signal dependencies, providing a foundation for subsequent community partitioning and Hardware Trojan feature extraction.
3.3. Improvements to Community Partitioning Algorithms
This paper addresses the structural characteristics of directed acyclic graphs generated from gate-level netlists and the typical small scale and covert structure of Hardware Trojans. The proposed improved Louvain algorithm integrates three complementary enhancement mechanisms, as shown in Algorithm 1. First, the algorithm introduces a directed modularity function to explicitly model signal propagation directions in gate-level netlists, forming the theoretical foundation of this method. Second, by incorporating a resolution parameter to control the granularity of community partitioning, the algorithm can detect small, covert Hardware Trojans often overlooked by traditional modularity-based methods. Finally, the algorithm employs a logic-gate-semantics weighting mechanism to enhance focus on trojan-sensitive components like XOR gates, multiplexers, and flip-flops. These three mechanisms operate at distinct levels yet are equally crucial, collectively achieving precise, fine-grained, and semantically aware community discovery tailored for Hardware Trojan analysis.
| Algorithm 1 Directed and Resolution-Adaptive Louvain Community Method |
Input: (node set), (weighted adjacency matrix), (resolution parameter), max_iter (maximum iterations) Output: community_assignment (final node-community labels)
1 Initialization: 2 Assign for all ; set 3 Greedy Optimization: 4 While improved and max_iter 5 ; shuffle to avoid order bias 6 For each 7 Compute for moving i to neighbor communities (via ) 8 Move i to the community with maximum (set if moved) 9 Graph Aggregation: 10 Build aggregated graph where each node represents a community; compute aggregated edge weights 11 Iteration & Mapping: 12 Repeat Steps 2–3 on the aggregated graph until no improvement; map aggregated communities back to original nodes 13 Return community_assignment 14 Function 15 Calculate modularity change for moving node i to community c: 16 17 Return 18 Notation: 19 : Total out/in-weight of node i; /: Weight from i to/X to i; .
|
3.3.1. Directed Modularity Function
Given the inherent structural property of gate-level netlists possessing signal-driven directionality, this paper introduces directed modularity to theoretically extend the traditional Louvain algorithm. Unlike the default symmetric connection assumption in undirected networks, logic gate connections in gate-level netlists exhibit explicit input–output directionality, which directly reflects the functional dependencies within the circuit. Based on the directed modularity definitions proposed by Newman and Leicht & Newman, this paper represents gate-level netlists as directed weighted graphs and employs a directed modularity function of the following form (
3):
where,
denotes the weight of the directed edge from node
i to node
j, and the asymmetric definitions of in-degree and out-degree explicitly capture the unidirectional signal propagation in gate-level circuits, thereby enabling community partitions that preserve logical dependencies and signal flow characteristics.
3.3.2. Introduction of the Resolution Parameter
To address the tendency of conventional modularity-based methods to favor large communities and obscure small-scale anomalous structures, a resolution parameter is introduced into the directed modularity formulation to control the granularity of community partitioning. A larger leads to finer-grained communities, which facilitates the isolation of small-scale Hardware Trojans, whereas a smaller results in coarser partitions that better capture high-level functional modules. By incorporating , the proposed approach effectively mitigates the resolution limit inherent in the traditional Louvain algorithm, enabling controllable community scales and significantly improving the visibility of small Trojan structures while preserving global structural consistency.
The resolution parameter in Algorithm 1 is not tuned using Trojan labels. It is fixed based on unsupervised structural statistics on the training set and then applied to all test circuits. Preliminary analysis shows that the performance is stable within a reasonable range of . Here, “resolution-adaptive” denotes the capability of adjusting community granularity via rather than label-dependent adaptation.
3.3.3. Logic Gate Semantic Weighting
Given the significant variations in semantic importance among different logic gates in Hardware Trojan design, this paper further introduces a logic gate semantic weighting mechanism to enhance the sensitivity of community partitioning toward high-risk nodes. In practical circuits, logic units such as XOR gates, multiplexers, and flip-flops are frequently employed for trojan triggering or payload implementation. However, traditional community detection algorithms assign identical weights to all nodes, making it difficult to highlight such critical structures. To address this, during the directed weighted graph modeling phase, this paper assigns differentiated weights to different logic gate types by adjusting edge weights or introducing node semantic weights. This approach increases the influence of relevant nodes on community partitioning results during modularity optimization. Without altering the overall greedy framework of the Louvain algorithm, this semantic weighting mechanism achieves collaborative modeling of structural information and functional semantics, resulting in communities that better align with the actual distribution characteristics of Hardware Trojans. In DW-Louvain, edge weights in the weighted adjacency matrix are modulated by gate type semantics. Specifically, edges incident to XOR/XNOR/MUX/comparator-related nodes receive higher multiplicative weights (), AND/OR/NAND/NOR edges receive medium weights (), and NOT/BUF edges retain base weights (). These semantic weighting factors are applied to the adjacency matrix prior to community detection (Algorithm 1, line 1) and are determined based on circuit design knowledge rather than tuned using detection labels. The method is empirically robust to moderate variations in these factors, and a fixed weighting scheme is used throughout all experiments.
Computational Complexity Analysis: The directed and resolution-adaptive Louvain algorithm exhibits near-linear time complexity with respect to the number of edges in practice, where represents the number of gates. The introduction of resolution parameters and semantic weighting does not alter the dominant complexity term, as these are incorporated as constant-time adjustments during the modularity optimization phase. For sparse gate-level netlists where , this results in effectively linear scaling with circuit size.
3.4. Feature Extraction
Traditional subgraph feature extraction methods currently focus solely on conventional metrics such as the distribution of node in-degree and out-degree, degree centrality, graph density, and community size. This approach yields suboptimal results for Trojan detection. This paper innovatively incorporates the extraction of topological features, functional features, and anomaly indicators during the feature extraction phase.
3.4.1. Topological Feature Extraction
After completing community partitioning using the improved Louvain algorithm, each community corresponds to a structurally compact subgraph, which can be approximately regarded as a local functional module or potential abnormal region in the circuit. To characterize the structural differences between different subgraphs, this paper extracts discriminative topological features from a topological perspective, which serve as inputs to the subsequent detection model.
First, considering that Hardware Trojans often rely on specific logic units (such as XOR/NAND gates) in trigger and payload design, we calculate the proportion of the number of XOR/NAND gates in the community to the total number of nodes. Compared with the relatively uniform gate-type distribution in normal functional modules, Trojan-related subgraphs usually exhibit obvious gate-type concentration or proportional imbalance. This feature can effectively reflect potential abnormal structures.
Second, although gate-level combinational circuits can be modeled as directed acyclic graphs (DAGs), Hardware Trojans often realize hidden cyclic trigger mechanisms through sequential feedback across flip-flop (FF) boundaries. To capture this characteristic while preserving the DAG representation, this paper introduces an equivalent feedback path feature to quantify potential sequential feedback interactions within each community.
Specifically, for a node pair in a community C, it is counted as an equivalent feedback path if the following two conditions are simultaneously satisfied:
- (1)
There exists a combinational driving path (feed-forward influence);
- (2)
There exists a path that traverses one or more flip-flops (feedback influence through sequential elements).
This definition captures intentional sequential feedback preserved through register boundaries, distinguishing it from pure combinational loops that are removed during DAG construction (
Section 3.2). The equivalent feedback path feature thus quantifies the density of state-machine-like dependencies within a community—precisely the cyclic trigger structures (e.g., counter states feeding back to enable Trojan payload logic) that Hardware Trojans commonly exploit.
Its quantification is defined as the number of node pairs in the community that satisfy the above two conditions.
Normal functional modules usually optimize performance or area, so their logic depth is not too large. However, some Trojans may insert deep logic paths for concealment. The maximum path length inside the subgraph is also an important indicator for measuring structural complexity and a key aspect of topological feature extraction. For a subgraph
C, the maximum path depth is defined as (
4):
where
denotes the length of the longest directed path from node
i to node
j.
These topological features complement each other, enabling the detection model to perceive both local structural anomalies and global topological deviations, thereby improving the recognition ability for small-scale and highly concealed Trojans.
3.4.2. Functional Feature Extraction
The output entropy is commonly used to measure the uncertainty and information complexity of the output signal of a subgraph under a given stimulus, and the output distribution of Hardware Trojans is often abnormal. For a given subgraph, we collect the output values of the key output node set under random or specific stimulus sequences and count their probability distributions. The output entropy is defined as (
5):
where
denotes the subgraph output space, and
is the occurrence probability of the corresponding output pattern. In practical implementation, the output entropy can be calculated separately under random and specific stimuli: random stimuli are used to characterize the statistical behavior of the subgraph under normal operation, while specific stimuli target potential trigger paths or highly sensitive input configurations to amplify Trojan-related responses. The simulation stimuli are generated using random and activity-oriented input patterns without any knowledge of Trojan trigger conditions. This strategy aims to maximize signal transitions and internal propagation, thereby amplifying potential abnormal behaviors while remaining applicable to realistic detection scenarios. The output entropy of normal modules changes stably with stimuli, whereas Trojan subgraphs may exhibit sudden changes in output entropy under specific stimuli.
When activated, the triggering of Hardware Trojans usually causes abnormal local switching activity, resulting in unstable dynamic power consumption. This paper uses power consumption variance to represent this behavioral feature. Under a given input stimulus sequence, we count the instantaneous power consumption of nodes inside the subgraph and calculate its variance over the time dimension (
6):
Power variance is estimated using a switching-activity-based proxy derived from toggle counts during logic simulation, rather than cell library power models. This approach avoids expensive power analysis while capturing abnormal switching behavior with negligible additional simulation cost, where is the total power consumption of the subgraph at time t, is the average power consumption, and T is the number of simulation cycles. Power consumption variance helps identify logic structures with low activation probability but high disturbance.
To enhance the recognition capability based on functional features, this paper also takes the differences between the output entropy and power consumption variance features extracted under random and specific stimuli as auxiliary features to input into the model.
3.4.3. Anomaly Metric Extraction
We introduce an anomaly index based on distribution differences to quantify the degree of behavioral and structural anomalies in subgraphs. We construct a graph and perform community topological partitioning on a clean circuit (without Trojans) to obtain a “clean golden model”, which serves as the criterion for normal behavior. The KL/JS-based anomaly metrics are computed relative to a golden clean reference circuit. Thus, the proposed method assumes access to a trusted clean design, following a common threat model in Hardware Trojan detection. Suppose the empirical distribution of a feature vector in the clean model is P, and the feature distribution of the circuit under test is Q.
The community Kullback–Leibler (KL) divergence is commonly used to measure the information deviation between two probability distributions, and its definition is as follows (
7):
The KL divergence describes the amount of information lost when using
P to characterize data under the assumption of distribution
Q. Since the KL divergence is asymmetric, to overcome its shortcomings in numerical stability and symmetry, this paper further introduces the Jensen–Shannon (JS) distance as a supplementary anomaly index. The JS distance is defined based on the KL divergence (
8):
The JS distance is symmetric and measures the mutual deviation between P and Q. Meanwhile, it is insensitive to sparse samples and noise, thus exhibiting excellent robustness.
3.4.4. Community Feature Vector via GNN Embedding
After constructing community topological features, functional features, and anomaly indices, a key issue remains: although manually designed features have good interpretability, Trojans exhibit complex high-order structural patterns in gate-level netlists. Manually designed features cannot fully cover these patterns, and the potential nonlinear structural correlations within subgraphs still need to be explored. Therefore, a Graph Neural Network (GNN) is introduced to encode each community subgraph into a vector, which serves as a high-level feature input to the detection model.
For each community obtained via the improved Louvain algorithm, it is treated as an independent directed subgraph, and the corresponding GNN input is constructed. Node features can be defined as logic gate types (represented by one-hot encoding), node in-degree/out-degree, node semantic weights, and local logic depth; edge features can be defined as signal propagation directions and edge weights. This modeling method can simultaneously perceive the circuit’s topological structure and signal flow semantics.
Since gate-level circuits are inherently directional, this paper adopts a GNN structure that supports directed edge modeling. In the first layer, the update form of node
i can be abstracted as (
9):
where
and
denote the in-neighbor and out-neighbor sets of node
i, respectively. By distinguishing incoming and outgoing information flows, the GNN can more accurately model the signal propagation relationships of the circuit.
After multi-layer GNN message passing, node-level features need to be aggregated into a community-level vector. This paper uses a community-level readout function (Readout) to generate a fixed-dimensional embedding vector; Readout can be implemented via attention pooling. This process compresses the subgraph’s structural features, gate type distribution, and signal flow features into a compact vector.
Introducing GNN to generate compact vectors can enhance the generalization ability for unknown Trojans, as it does not rely on specific Trojan structures. More importantly, it can model multi-hop neighborhood dependencies and capture high-order structural patterns.
3.5. Hardware Trojan Detection Model
To fully leverage the subgraph structural information after community partitioning, this paper introduces multiple community-level detection models, including graph neural network (GNN)-based representation learning methods and density-based unsupervised anomaly detection methods. Models are selected for detection from the perspectives of different supervision assumptions and modeling capabilities.
CommunityGNN is a hierarchical representation learning method that integrates community detection and GNNs. Its core idea is to treat community subgraphs as the basic modeling units, then use GNNs to encode each community subgraph into a fixed-dimensional embedding vector. This approach can both preserve local functional characteristics and characterize the overall structure and semantic features of the subgraph. Using CommunityGNN can significantly reduce the graph scale and computational complexity, making it suitable for large-scale, modular circuit detection tasks. Training protocol: 200 epochs, Adam optimizer (), cross-entropy loss with class weighting (1:10 for positive:Trojan) to handle imbalance, early stopping (patience = 20).
Graph-Based Detector [
31]: This baseline is implemented following the method proposed by Gao et al. [
31]. In this approach, each gate-level netlist is first converted into a directed graph, where logic gates are represented as nodes and signal connections as edges. A set of handcrafted graph structural features is then extracted, including node degree statistics, connectivity patterns, and path-related metrics. These graph features are used as inputs to a machine learning classifier to distinguish Trojan-infected circuits from clean ones and to localize suspicious gates. We strictly follow the feature definitions and experimental protocol described in [
31] to ensure a fair and reproducible comparison. Notably, this method operates on the entire circuit graph (global-level detection) rather than community subgraphs, making it susceptible to interference from normal logic structures in large-scale netlists. Therefore, applying it to community-level detection serves as a critical baseline to isolate the performance gains attributable to community partitioning.
CommunityGAT is an attention-enhanced variant of CommunityGNN. Unlike traditional GNNs, it can learn adaptive attention weights between different nodes within a community, assigning higher aggregation weights to high-saliency signals (e.g., Trojan trigger and payload logic). This improves the modeling ability for fine-grained structural differences within the community, generating more interpretable community representations. It is typically used in scenarios where community subgraphs have uneven signal propagation intensity and highly coupled logic functions. Training protocol: 200 epochs, Adam optimizer (), focal loss () for hard example mining on imbalanced Trojan samples, attention dropout , early stopping (patience = 20).
The Local Outlier Factor (LOF) is a density-based unsupervised anomaly detection algorithm that identifies outliers by comparing the local density deviation between each node and its neighboring nodes. In this paper, it is applied to the community feature space: the comprehensive feature vector of each subgraph is scored for anomalies. It is suitable for fine-grained anomaly screening after community partitioning, and serves as an auxiliary detector in unsupervised scenarios and a supplementary verification method for GNN model detection results.