$$\rightleftharpoonup{xx}$$
$$\longleftharp{xx}$$,
$$\longrightharp{xx}$$,
All experiments were conducted exclusively using publicly available benchmark network intrusion datasets (UNSW-NB15, CIC-IDS-2017, and Bot-IoT), which contain network traffic records without identifiable personal or medical information. The datasets were used in accordance with their respective licenses and terms of use. Because no human participants, patient samples, or identifiable personal data were involved, institutional ethics approval and informed consent were not required.
Overview of the Proposed Framework
This section presents the proposed dual-layer intrusion detection and prevention framework for securing IoMT environments. The framework integrates an Extended BiLSTM network for spatio-temporal intrusion detection with a lightweight blockchain layer for tamper-proof logging and automated mitigation. Unlike conventional IDS approaches that focus solely on detection accuracy, the proposed architecture is designed to simultaneously support real-time detection, forensic accountability, and regulatory compliance, which are essential requirements in healthcare systems. The overall workflow and architecture of the proposed Extended BiLSTM–Blockchain intrusion detection framework for IoMT networks are illustrated in Figure 1.

Figure 1. Architecture of the proposed Extended BiLSTM–Blockchain intrusion detection framework for Internet of Medical Things networks. Schematic representation of the proposed framework showing the training and deployment workflows. In the training workflow, Internet of Medical Things (IoMT) devices generate network traffic that undergoes data preprocessing and feature engineering before being analyzed by the Extended Bidirectional Long Short-Term Memory (BiLSTM) model with temporal attention. Model parameters are optimized through loss-function computation and iterative training. In the deployment workflow, the trained model performs intrusion detection according to the decision function defined in Equation 13. Detected intrusion events are forwarded to the blockchain module, where immutable logging, node isolation, and administrator alert generation are performed. BiLSTM, Bidirectional Long Short-Term Memory; IoMT, Internet of Medical Things. Please click here to view a larger version of this figure.
IoMT devices generate heterogeneous data streams consisting of network traffic, device metadata, and patient-related signals. Such raw inputs are often noisy, redundant, and inconsistent, making them unsuitable for direct model training. Therefore, a preprocessing pipeline is applied to ensure the quality and structure of the data before feeding it into the Extended BiLSTM model. The detailed preprocessing pseudocode is provided in Algorithm 1 (Supplementary File 1), which outlines the preprocessing pipeline applied to IoMT data streams prior to Extended BiLSTM training (pseudocode in Supplementary File 1; implementation in Supplementary File 2). The complete Extended BiLSTM architecture is summarized in Algorithm 2 (Supplementary File 1).
End-to-End Reproduction Workflow
The full study can be reproduced using the steps below. Software and hardware are listed in the Experimental Setup, and the supplementary code covers each step.
Get the datasets → Download UNSW-NB15. Use the files UNSW_NB15_training-set.csv and UNSW_NB15_testing-set.csv. Download CICIDS2017. Use the five MachineLearningCSV day files (Monday to Friday). Download Bot-IoT. Use the 5% subset files UNSW_2018_IoT_Botnet_Full5pc_1_to_4. Earlier intrusion detection studies commonly relied on benchmark datasets such as KDD Cup 9914; however, this study uses the more recent UNSW-NB15, CICIDS2017, and Bot-IoT datasets to better represent contemporary network traffic. Process each dataset separately. The UNSW-NB15 dataset is available from the University of New South Wales at https://research.unsw.edu.au/projects/unsw-nb15-dataset (last modified: February 8, 2024). The CICIDS2017 dataset is available from the Canadian Institute for Cybersecurity at https://www.unb.ca/cic/datasets/ids-2017.html (released: July 2017). The Bot-IoT dataset is available from the University of New South Wales at https://research.unsw.edu.au/projects/bot-iot-dataset (last modified: February 5, 2024). All datasets were accessed in May 2025 for this study.
Preprocess the data → Remove corrupted records. Fill missing values using training-set means. Apply EMA denoising (α = 0.3). Normalize features to [0,1] using training-set statistics. Label-encode categorical fields. Build sliding windows (T = 20, stride = 1). These preprocessing steps support robust intrusion detection by reducing noise and improving the quality of network traffic representations for machine-learning-based IDSs15,16.
Select features (AQU-IMF-RFE) → Rank features by mutual information. Refine with the Aquila Optimizer. Apply Random Forest RFE with 10-fold cross-validation. Keep the final features. This hybrid feature-selection strategy follows the broader concept of combining complementary intrusion detection techniques17 and is implemented using the AQU-IMF-RFE framework developed in our previous work18.
Train the model → For each dataset, the data were randomly partitioned into training (80%) and testing (20%) sets using a fixed random seed of 42. Twenty percent of the training partition was further reserved as the validation set. Build the Extended BiLSTM. Train using weighted binary cross-entropy loss and the Adam optimizer (learning rate = 0.001, batch size = 64, maximum of 50 epochs, with early stopping). Save the trained model. The use of temporal deep-learning models is well suited to heterogeneous IoMT traffic19. The complete model-training workflow is summarized in Algorithm 3 (Supplementary File 1). The final class weights were computed automatically from the training-set class distributions according to Equations 19 and 20. The resulting class weights were as follows: UNSW-NB15:
,
; CICIDS2017:
,
; and Bot-IoT (5% subset):
,
. The large value of wn for the Bot-IoT dataset reflects the severe underrepresentation of benign samples in the training partition of the 5% subset.
Deploy the blockchain → Start the Proof-of-Authority (PoA) chain. Deploy the smart contract and note its address. Authorize the gateway accounts. Run the client so that each detected intrusion is logged and triggers isolation and alerts. The complete detection, blockchain logging, and mitigation workflow is summarized in Algorithm 4 (Supplementary File 1). The blockchain layer was implemented using the go-ethereum (Geth) client version 1.13.15 to operate the permissioned PoA network, the Solidity compiler (solc) version 0.8.19 for smart-contract compilation and deployment, and the web3.py library version 6.15.1 for communication between the IDS and the blockchain network.
Evaluate → Test the model on the held-out test set. Compute accuracy, precision, recall, F1-score, and false-positive rate. Record latency and throughput. Verify the integrity of the blockchain ledger. The complete evaluation workflow is summarized in Algorithm 5 (Supplementary File 1). Detection latency (Td) was measured from immediately before the model inference call to the time at which the predicted probabilities were returned. End-to-end mitigation latency (Td + Tb) was measured from the same starting point until completion of the corresponding blockchain block-creation transaction. Throughput was calculated as the total number of preprocessed test windows processed by the complete detection-and-logging pipeline divided by the elapsed wall-clock time required for a single complete pass through each dataset’s test set. The workload consisted of the windowed test partitions while preserving the original benign-to-intrusion class distribution. Malicious windows additionally incurred the blockchain-logging overhead, whereas benign windows incurred only the intrusion-detection cost.
Generate figures and tables → Plot the accuracy and loss curves, confusion matrix, and comparative evaluation charts. Build the comparison tables. The complete figure and table generation workflow is summarized in Algorithm 6 (Supplementary File 1). The complete custom-developed source code used to generate all figures and tables is provided in Supplementary File 2. In particular, the figures.py script reproduces the manuscript figures directly from the saved experimental outputs (e.g., training history and confusion-matrix files), while the remaining scripts generate the processed data and performance metrics used to construct the reported tables.
Figure 2 is the implementation-level data flow between the IDS and blockchain modules. The Extended BiLSTM produces a per-window decision (Equation 13); on a malicious classification, the gateway client constructs and signs a transaction and submits it over web3/JSON-RPC to the PoA smart contract, which appends a hash-linked block (Equation 14) to the immutable ledger and emits events (BlockCreated, NodeIsolated, and AdminAlert) that trigger node isolation and administrator alerts.

Figure 2. Implementation-level interaction between intrusion detection and blockchain modules. Workflow diagram illustrating communication between the intrusion detection system and blockchain components. The Extended BiLSTM model classifies each input window and applies the decision rule defined in Equation 13. When an intrusion is detected, the gateway client generates and signs a transaction that is transmitted through Web3.py/JSON-RPC to the Proof-of-Authority (PoA) smart contract. The contract appends a hash-linked block to the immutable ledger according to Equation 14 and emits BlockCreated, NodeIsolated, and AdminAlert events that trigger containment and notification actions. IDS, Intrusion Detection System; BiLSTM, Bidirectional Long Short-Term Memory; PoA, Proof-of-Authority; JSON-RPC, JavaScript Object Notation–Remote Procedure Call. Please click here to view a larger version of this figure.
Data Representation
Let’s consider R as the raw IoMT traffic stream. After preprocessing, each raw record
is mapped into a normalized d-dimensional feature vector (Equation 1):
(1)
Here, f (⋅) is the feature transformation function mapping raw records into a d dimensional normalized feature vector. Let the IoMT network consist of a set of nodes (Equation 2):
N = {n1 , n2, ... , nk} (2)
Each node nj ∈ R produces a time-series data stream (Equation 3):
(3)
Here, xt is the feature vector at time t, with d features (e.g., packet size, protocol type, source/destination address) commonly observed in Internet of Things healthcare network traffic19. The corresponding label set is (Equation 4):
(4)
Here, yt=0 represents normal traffic and yt =1 denotes an intrusion.
Data Preprocessing
The preprocessing pipeline includes the following steps, which address common data-quality and security challenges associated with IoMT traffic20:
Data Cleaning and Missing-Value Handling:
A record was identified as corrupted and removed prior to imputation if it satisfied either of the following explicit conditions: (i) all feature fields in the record were missing (i.e., the entire record was null), or (ii) the record contained a non-finite value (positive or negative infinity) in any numeric field after type coercion. The second rule removes invalid entries such as those produced by division-by-zero during flow-feature computation (for example, infinite flow-rate values arising from zero-duration flows). After corrupted records were removed, remaining missing values were imputed by mean replacement computed per feature, per dataset, and from the training partition only; the resulting means were applied to the training, validation, and test sets to prevent information leakage. Imputation was not class-conditional, and means were not pooled across datasets.
Temporal Denoising:
Temporal denoising was performed using a per-feature exponential moving average (EMA) filter applied along the time axis. The recursive (causal) form yt = α·xt + (1 − α)·yt−1 was used, with smoothing factor α = 0.3, implemented via the pandas ewm function with adjust=False. Each feature was smoothed independently. As an exponential (infinite-impulse-response) filter, the EMA has no fixed window or kernel size; the smoothing factor α is the single parameter governing the degree of smoothing and the effective memory of the filter.
Min–Max Normalization:
Min–max normalization was applied to scale each feature to the [0,1] range using the transformation x′=(x−min)/(max−min+ε), where ε = 1 × 10−8. The minimum and maximum statistics were computed per feature, per dataset, and from the training partition only; these stored training statistics were then applied to normalize the training, validation, and test sets, preventing leakage of held-out information. During inference, feature values falling outside the training range were clipped to the [0,1] interval.
Encoding of Categorical Features:
Categorical features were converted to numeric form using label encoding. This was applied to all categorical variables: in UNSW-NB15, the proto, service, and state fields; in Bot-IoT, the proto field; CICIDS2017 contains no categorical fields among the selected features. Encoding was implemented with LabelEncoder fitted per variable.
Temporal Windowing for Sequential Learning:
The preprocessed feature stream was segmented into fixed-length sequences using a sliding window of length T = 20 time steps with a stride of s = 1. Each generated window was validated before inclusion. A window was accepted only if it contained exactly T = 20 consecutive time steps and all feature values were finite. Streams shorter than T = 20 records produced no windows. This configuration (T = 20, s = 1, 95% overlap) was applied consistently across all experiments and datasets. The complete preprocessing workflow is summarized in Algorithm 1 (Supplementary File 1).
The goal of preprocessing is to enable a predictive mapping from input sequences to intrusion labels (Equation 5).
(5)
parameterized by θ, that predicts whether an event is benign or malicious.
Feature Selection Using AQU-IMF-RFE
Feature selection was performed using AQU-IMF-RFE, a hybrid method that integrates Mutual Information (MI), the Aquila Optimizer (AO), and Recursive Feature Elimination (RFE), introduced in our prior work18. The method operates in three stages. In the first stage, the mutual information between each feature and the class label is computed to obtain an initial relevance ranking. In the second stage, the Aquila Optimizer performs a global search over candidate feature subsets using its four optimization strategies. In the third stage, the refined subset is passed through Recursive Feature Elimination with 10-fold cross-validation using a Random Forest (RF) estimator.
The Aquila Optimizer was configured with a population size of 100, a maximum of 10 iterations, an exploitation factor of 0.1, a learning rate of 0.1, and an attraction factor of 0.005. Applied independently to each dataset, AQU-IMF-RFE retained 14 features for UNSW-NB15, 24 for CICIDS2017, and 12 for Bot-IoT. The complete pseudocode is provided in Supplementary File 1, and the selected feature subsets are listed in Table 4.
| Table 4A. Selected Features Retained for UNSW-NB15 |
| S. No. | Feature | Type | Category |
| 1 | dur | Numeric (float) | Basic |
| 2 | sbytes | Numeric (integer) | Basic |
| 3 | rate | Numeric (float) | Basic |
| 4 | dload | Numeric (float) | Basic |
| 5 | sinpkt | Numeric (float) | Time |
| 6 | dinpkt | Numeric (float) | Time |
| 7 | sjit | Numeric (float) | Time |
| 8 | tcprtt | Numeric (float) | Time |
| 9 | synack | Numeric (float) | Time |
| 10 | ackdat | Numeric (float) | Time |
| 11 | smean | Numeric (integer) | Content |
| 12 | ct_srv_src | Numeric (integer) | Connection |
| 13 | ct_dst_src_ltm | Numeric (integer) | Connection |
| 14 | ct_srv_dst | Numeric (integer) | Connection |
| Table 4B. Selected Features Retained for CICIDS2017 |
| S. No. | Feature | | |
| 1 | Destination Port | | |
| 2 | Flow Duration | | |
| 3 | Total Length of Forward Packets | | |
| 4 | Total Length of Backward Packets | | |
| 5 | Forward Packet Length Maximum | | |
| 6 | Backward Packet Length Maximum | | |
| 7 | Backward Packet Length Mean | | |
| 8 | Flow Packets | | |
| 9 | Flow Inter-Arrival Time Maximum | | |
| 10 | Forward Inter-Arrival Time Total | | |
| 11 | Forward Header Length | | |
| 12 | Backward Header Length | | |
| 13 | Forward Packets per Second | | |
| 14 | Maximum Packet Length | | |
| 15 | Packet Length Mean | | |
| 16 | Packet Length Standard Deviation | | |
| 17 | Packet Length Variance | | |
| 18 | Average Packet Size | | |
| 19 | Average Backward Segment Size | | |
| 20 | Subflow Forward Bytes | | |
| 21 | Subflow Backward Bytes | | |
| 22 | Initial Window Bytes Forward | | |
| 23 | Initial Window Bytes Backward | | |
| 24 | Forward Packet Length Mean | | |
| Table 4C. Selected Features Retained for Bot-IoT |
| S. No. | Feature | Type | |
| 1 | seq | Numeric | |
| 2 | mean | Numeric | |
| 3 | stddev | Numeric | |
| 4 | min | Numeric | |
| 5 | max | Numeric | |
| 6 | srate | Numeric (float) | |
| 7 | drate | Numeric (float) | |
| 8 | N_IN_Conn_P_SrcIP | Numeric (integer) | |
| 9 | N_IN_Conn_P_DstIP | Numeric (integer) | |
| 10 | proto | Categorical (encoded) | |
| 11 | state_number | Numeric (integer) | |
| 12 | rate | Numeric (float) | |
Table 4: Features selected by the AQU-IMF-RFE feature-selection method. This table lists the final feature subsets selected by the AQU-IMF-RFE feature-selection framework for the UNSW-NB15, CICIDS2017, and Bot-IoT datasets. Feature names, data types, and functional categories are provided where applicable.
Experimental Setup
All experiments were conducted on a Dell PowerEdge R740 server equipped with an Intel Xeon Silver 4214 processor operating at a base frequency of 2.20 GHz, with 12 physical cores, 24 logical threads, 16.5 MB cache, and an Intel Ultra Path Interconnect (UPI) speed of 9.6 GT/s. The server was configured with 128 GB RAM, a 512 GB solid-state drive (SSD), and operated on Microsoft Windows 11. The software stack comprised Python 3.12.7, TensorFlow 2.16.1, scikit-learn 1.8.0, pandas 3.0.2, and NumPy 2.4.4. The blockchain layer was implemented on the same workstation using a PoA Ethereum network. Communication between the IDS and the blockchain was performed via JSON-RPC using the go-ethereum (Geth) client version 1.13.15, the Solidity compiler (solc) version 0.8.19 for smart-contract compilation and deployment, and the Web3.py library version 6.15.1. Reported training time, inference latency, and throughput were measured on this hardware and software configuration.
Model Architecture and Training
The Extended BiLSTM model constitutes the core detection component of the framework, building upon previous learning-based intrusion detection approaches developed for IoMT environments21. Earlier intrusion detection studies highlighted both the importance of balancing detection performance with false-alarm reduction15 and the unique challenges of applying machine-learning methods to evolving network traffic16. Collaborative neural-network intrusion detection architectures have further demonstrated the value of deep sequential feature learning for complex network traffic22. While standard BiLSTM models capture bidirectional temporal dependencies, IoMT traffic exhibits both short-term burst patterns and long-range dependencies caused by multistage attacks. To address this, the proposed model extends BiLSTM with temporal feature extraction, enhanced bidirectional temporal learning, residual connections, and attention-based temporal prioritization. Bidirectional LSTMs (BiLSTM) overcome this limitation by combining forward and backward hidden states, enabling richer temporal representation of IoMT traffic patterns, as given in Algorithm 2 (Supplementary File 1).
Let the input sequence be X(nj) = {x1 , x2 , ... , xT }, where each xt ∈ Rd is a preprocessed feature vector.
Temporal Feature Extraction:
A lightweight one-dimensional convolution is applied across the time dimension to emphasize short-range temporal anomalies (Equation 6):
U = φ (Conv1D(X(nj)), U = {u1, u2, ..., uT } (6)
Here, φ(⋅) is a nonlinear activation function and the convolved features ut are fed to the BiLSTM.
The Conv1D layer extracts short-range temporal patterns before bidirectional sequence modeling. Complete implementation parameters are provided in Supplementary File 3B.
Stacked Bidirectional LSTM Learning:
Forward and backward hidden states are computed as (Equation 7):
(7)
The final BiLSTM representation is the concatenation of past (forward) and future (backward) hidden states (Equation 8).
(8)
Two stacked BiLSTM layers model bidirectional temporal dependencies. Detailed architectural parameters are provided in Supplementary File 3B. Weight initialization details are provided in Supplementary File 3B.
Residual Connection and Normalization
After linear projection to matching dimensions, residual connections and layer normalization are applied (Equation 9):

Residual projection and layer normalization align the convolutional and BiLSTM feature representations before attention. Detailed implementation parameters are provided in Supplementary File 3B.
Attention Mechanism
Although BiLSTM provides strong temporal modeling, not all time steps contribute equally to the prediction. To emphasize critical timestamps (e.g., sudden anomalous spikes), an attention mechanism is introduced. Each hidden state
is assigned a relevance score αt to enhance detection accuracy (Equation 10).

Here, Wa is a trainable parameter and the attention weights satisfy 
The context vector c aggregates the hidden states based on their learned importance (Equation 11):

The attention mechanism aggregates temporal representations into a context vector. Detailed implementation parameters are provided in Supplementary File 3B.
Output Layer and Classification
The aggregated context vector is passed through a fully connected layer followed by a sigmoid activation to yield the final prediction (Equation 12):

Here, Wc and bc are trainable parameters, and σ(·) is the sigmoid activation function mapping the output to the interval [0,1]. A threshold is applied to classify traffic as benign (
) or intrusive (
).
Dropout regularization and the fixed classification threshold used during inference are described in Supplementary File 3B.
The Extended BiLSTM architecture is identical across the three datasets; only the input feature dimension differs, taking values of 14, 24, and 12 for UNSW-NB15, CICIDS2017, and Bot-IoT, respectively. Because the Conv1D layer maps any -dimensional input to a fixed 64-channel representation, all subsequent layers are independent of the dataset, and only the input shape and the Conv1D parameter count vary with . The complete layer-by-layer architecture is summarized in Table 5, with parameter counts expressed in terms of d; the resulting totals are 184,641, 186,561, and 184,257 trainable parameters for d = 14, d = 24, and d = 12, respectively.
| S. No. | Layer (Type) | Output Shape | Trainable Parameters | Activation Function |
| 1 | Input | (20, d) | 0 | — |
| 2 | Conv1D (64 filters, kernel size = 3, same padding) | (20, 64) | 192d + 64 | ReLU |
| 3 | Bidirectional LSTM Layer 1 (64 units per direction) | (20, 128) | 66,048 | tanh / sigmoid |
| 4 | Bidirectional LSTM Layer 2 (64 units per direction) | (20, 128) | 98,816 | tanh / sigmoid |
| 5 | Dense Residual Projection | (20, 128) | 8,320 | Linear |
| 6 | Residual Addition | (20, 128) | 0 | — |
| 7 | Layer Normalization (axis = −1, ε = 1 × 10⁻³) | (20, 128) | 256 | — |
| 8 | Temporal Attention (Wa ∈ ℝ¹²⁸×¹) | 128 | 128 | Softmax |
| 9 | Dense Hidden Layer | 64 | 8,256 | ReLU |
| 10 | Dropout (p = 0.3) | 64 | 0 | — |
| 11 | Dense Output Layer | 1 | 65 | Sigmoid |
Table 5: Layer-by-layer architecture of the Extended Bidirectional Long Short-Term Memory model. This table summarizes the architecture of the proposed Extended Bidirectional Long Short-Term Memory (BiLSTM) model, including layer types, output dimensions, trainable parameter counts, and activation functions.
The software and computational environment used for all experiments is summarized in Table 6.
| Component | Version / Specification |
| Operating System | Windows |
| Server Platform | Dell PowerEdge |
| CPU | 64-core processor |
| RAM | 128 GB |
| Storage | 512 GB SSD |
| Python | 3.12.7 |
| NumPy | 2.4.4 |
| pandas | 3.0.2 |
| scikit-learn | 1.8.0 |
| TensorFlow / Keras | 2.16.1 |
| web3 (blockchain client) | 6.15.1 |
| eth-account | 0.1 |
| Solidity Compiler (solc) | 0.8.19 |
| go-ethereum (Geth) | 1.13.15 |
Table 6: Software and computational environment used for implementation and evaluation of the proposed framework. This table summarizes the hardware specifications, software components, blockchain tools, and version numbers used for data preprocessing, feature selection, model training, blockchain deployment, and performance evaluation.
Intrusion Decision and Automated Response
Intrusion detection in healthcare environments is only effective if followed by rapid response and mitigation. The Intrusion Detection Layer converts the predicted probability into a decision. Formally, the intrusion decision at time step t is represented as follows (Equation 13):

Here,
is the predicted intrusion probability at time t and
is the classification threshold.
Once an intrusion is detected, the Intrusion Detection Layer interfaces directly with the blockchain module, which performs immutable logging, automated mitigation, and closed-loop security enforcement. Event details, including source information, destination information, and selected traffic features, are recorded in a new blockchain block. Smart contracts execute real-time mitigation actions such as node isolation and administrator alerts. This closed-loop architecture allows intrusion detection results to feed directly into prevention mechanisms, thereby minimizing mitigation latency. Thus, the Intrusion Detection Layer serves as the bridge between temporal detection using the Extended BiLSTM model and secure response using blockchain technology, completing the end-to-end functionality of the proposed framework.
Blockchain-Based Forensic Logging
While the Extended BiLSTM model enables real-time intrusion detection, secure storage and verifiable auditing of intrusion events are equally critical in IoMT healthcare environments. Traditional centralized logging mechanisms are vulnerable to tampering and compromise forensic traceability. To address this limitation, the proposed framework incorporates a lightweight blockchain module that ensures immutability, decentralization, and smart-contract-based automated response.
Each detected intrusion event generates a block that is added to the blockchain. A block Bi is defined as follows (Equation 14):

Here, Hi is the cryptographic hash of the event data, timestamp, and prediction result, Ti is the timestamp, Di contains selected intrusion-event features, Sigi is the digital signature, and PrevHash links the block to the previous block, ensuring immutability.
This design guarantees tamper resistance because any modification of Di or Ti changes the block hash and breaks chain integrity. It also provides auditability because all detected anomalies are permanently stored and verifiable. Automated mitigation is supported through smart contracts that execute predefined actions such as node isolation and administrator alerts. Decentralization is achieved through multiple IoMT gateways maintaining the distributed ledger, thereby eliminating a single point of failure.
Block generation uses the Keccak-256 cryptographic hash function, the native hashing primitive of the Ethereum/Solidity environment (invoked through Solidity’s keccak256). For each intrusion block, the block hash is computed as follows:

Here, Di is the event feature digest, Ti is the timestamp, and PrevHash is the hash of the preceding block. The fields are concatenated using Solidity's tightly packed encoding (abi.encodePacked) before hashing, producing a 256-bit digest.
The same Keccak-256 computation is used by the chain-verification routine, which recomputes each block hash from its stored fields and confirms that it matches the recorded value, thereby validating chain integrity. Keccak-256 was selected because it is the standard collision-resistant hashing algorithm used natively within Ethereum smart contracts. The smart contract was developed in Solidity and compiled using the Solidity compiler (solc) version 0.8.19. It was deployed on a private Ethereum Proof-of-Authority (PoA) network operated using Geth version 1.13.15. The blockchain network was configured with four validator nodes using the Clique Proof-of-Authority consensus protocol, a chain ID of 9848, a block period of 5 s, and a block gas limit of 30,000,000. Communication between the Extended BiLSTM intrusion detection engine and the blockchain layer was implemented using the Web3.py library version 6.15.1 through the HTTP JSON-RPC interface.
PoA Consensus Mechanism
Because healthcare IoMT systems are highly latency sensitive, the proposed framework employs a PoA consensus mechanism instead of computationally expensive Proof-of-Work (PoW)23. In PoA, a fixed set of trusted validator nodes, such as hospital gateways, authorize transactions, providing both efficiency and resilience.
The time complexity of block validation under PoW can be expressed as follows (Equation 15):

Here, d represents mining difficulty.
In contrast, the time complexity of PoA consensus is given as follows (Equation 16):

because validation only requires digital-signature verification by authorized validator nodes.
As a result, PoA provides low-latency operation suitable for real-time medical alerts, energy efficiency by avoiding computationally intensive mining, and resilience against a limited number of malicious validators. The PoA network was configured with four validator nodes, and this configuration was kept fixed throughout all experiments to ensure consistent latency measurements, reproducible performance evaluation, and fair comparison across all benchmark datasets.
Blockchain Implementation and Smart-Contract Operation
The blockchain component was implemented on a permissioned Ethereum network operating under the PoA consensus model24. The network was run using the go-ethereum (Geth) client with the Clique PoA consensus protocol25, in which a set of authorized validator (sealer) nodes are responsible for producing and validating blocks. The intrusion-logging smart contract (IoMTIntrusionLedger) was written in Solidity and deployed to this network, following blockchain-based IoT security architectures for secure decentralized event management26. Only gateway accounts authorized on-chain (via the contract’s access-control function) were permitted to submit intrusion records, consistent with permissioned blockchain smart-contract architectures for Internet of Things applications27. The blockchain layer was implemented using the go-ethereum (Geth) client version 1.13.15 for operating the permissioned PoA network, the Solidity compiler (solc) version 0.8.19 for smart-contract compilation and deployment, and the Web3.py library version 6.15.1 for communication between the IDS and the blockchain network.
Detailed blockchain deployment and configuration parameters are provided in Supplementary File 3C.
Each intrusion record is digitally signed before being committed to the ledger, supporting blockchain-based healthcare auditability and secure forensic record keeping28. Digital signature generation and verification procedures, including ECDSA over the secp256k1 curve29,30, are described in Supplementary File 3D. Each gateway holds an Ethereum key pair consisting of a 256-bit (32-byte) private key and the corresponding public key, from which its account address is derived; key generation follows the standard Ethereum procedure, using a cryptographically secure random 256-bit private key with the public key obtained by secp256k1 scalar multiplication. To create a signature, the gateway client computes the event feature digest Di and signs it with its private key using the EIP-191 message-signing format, producing a 65-byte signature consisting of the r, s, and v components. The signature is submitted together with the intrusion record. Verification is performed on-chain by the smart contract: using the EVM ecrecover precompile, the contract recovers the signer's address from the signed digest and signature and requires it to equal the address of the authorized gateway submitting the transaction. If the recovered address does not match an authorized gateway, the transaction is rejected. This binds every ledger entry to a specific authorized gateway and prevents unauthorized or forged intrusion records.
Smart contracts are triggered automatically upon intrusion detection
, ensuring real-time response without requiring manual intervention (Equation 17):
(17)
The blockchain module operates in parallel with the Extended BiLSTM classifier. Once an anomaly is detected: (i) the event is labeled and classified by the BiLSTM, (ii) a block is generated, signed, and appended to the blockchain ledger, and (iii) smart contracts enforce automatic response policies.
The intrusion-logging smart contract (IoMTIntrusionLedger) maintains an append-only ledger of intrusion blocks and a registry of authorized gateway accounts, and it exposes the functions summarized in Table 7. The contract enforces two access roles through modifiers: onlyAdmin (the deploying administrator) and onlyGateway (accounts authorized to submit intrusion records). State consists of the gateway authorization mapping, the block ledger array, and the current chain head (the hash of the most recent block).
| S. No. | Function / Component | Type | Access | Logic |
| 1 | constructor | Constructor | — | Sets the deployer as the administrator and authorizes it as the initial gateway. |
| 2 | setGateway(address, bool) | Function | onlyAdmin | Adds or removes an authorized gateway account; emits GatewayUpdated. |
| 3 | recordIntrusion(nodeId, patientId, attackClass, probabilityBp, dataDigest, signature, isolate) | Function | onlyGateway | Computes Hi = Keccak-256(Di ∥ Ti ∥ probability ∥ PrevHash); verifies the gateway's ECDSA signature on Di via ecrecover; appends the block to the ledger; advances the chain head; emits BlockCreated, optionally NodeIsolated, and AdminAlert. Returns Hi. |
| 4 | verifyChain() | View Function | Public | Recomputes every block's hash from its stored fields and checks the PrevHash linkage; returns true only if the entire chain is consistent (tamper detection). |
| 5 | ledgerLength() | View Function | Public | Returns the number of blocks in the ledger. |
| 6 | _recoverSigner(hash, sig) | Internal Function | — | Splits the 65-byte signature into (r, s, v) and recovers the signing address via the ecrecover precompile. |
| 7 | BlockCreated / NodeIsolated / AdminAlert / GatewayUpdated | Events | — | Emitted for off-chain listeners to drive logging, node isolation, administrator alerts, and gateway-registry updates. |
| 8 | onlyAdmin / onlyGateway | Modifiers | — | Restrict functions to the administrator and to authorized gateways, respectively. |
Table 7: Functions, events, and access-control components of the IoMTIntrusionLedger smart contract. This table summarizes the principal functions, events, and access-control modifiers implemented within the permissioned blockchain smart contract. These components support gateway authorization, intrusion logging, blockchain verification, event generation, and automated mitigation.
The immutability property of the blockchain directly follows from Equation 14, where any modification to event data or timestamps invalidates the hash chain. Blockchain thus provides data integrity, traceability, and auditability for healthcare systems through immutable forensic records. Patient and device intrusion records remain unchanged once stored, each block securely links to the previous block enabling chronological event reconstruction, and healthcare administrators or regulators can verify intrusion incidents without risk of falsification.
Loss Function and Model Optimization
The proposed Extended BiLSTM model addresses the binary classification problem of distinguishing between normal traffic and intrusion events in IoMT networks. To guide the training process, a binary cross-entropy (BCE) loss is adopted, which is well suited for probabilistic outputs from the sigmoid activation layer. For a dataset with N samples, the loss is defined as follows (Equation 18):
(18)
Here,
is the ground-truth label of the ith input sequence (0 = benign, 1 = intrusion), and
is the predicted probability of intrusion.
The framework operates as a two-stage classification pipeline. The first stage performs binary intrusion detection: the Extended BiLSTM produces a sigmoid output
and applies the threshold τ = 0.5 to classify each window as benign or intrusive (Equations 12,13), trained with weighted binary cross-entropy loss. A second stage can perform attack categorization, in which windows identified as intrusions are passed to a multiclass classifier that assigns the specific attack category using a softmax output layer trained with categorical cross-entropy. The present study focuses on and evaluates the binary detection stage. The two stages share the same Extended BiLSTM feature-extraction backbone (Conv1D, BiLSTM, residual, normalization, and attention layers); they differ only in their output layer (sigmoid for detection and softmax for categorization) and corresponding loss function. The binary detection stage and the multiclass categorization stage were trained and evaluated under the same data partitions, random seed, and training conditions described above.
While IoMT traffic is often imbalanced, a weighted binary cross-entropy loss is used to penalize misclassification of the minority class. Class weights are computed using the number of intrusion samples Np, the number of benign samples Nn, and the total number of samples N (Equations 19,20):


The weighting ensures that the model is not biased toward the dominant benign traffic class and remains sensitive to rare but critical intrusion events.
The weighted binary cross-entropy loss is given as follows (Equation 21):
(21)
Training was performed using mini-batches of size 64. At the start of every epoch, the training samples were randomly shuffled before being partitioned into batches so that batch composition varied across epochs and the model did not see examples in a fixed order. Batches were not explicitly balanced or stratified by class; instead, each batch reflected the natural class distribution of the training set, and class imbalance was addressed through the class-weighted binary cross-entropy loss (Equations 19–21). The validation subset reserved from the training partition remained fixed across epochs and was not shuffled into the training batches.
The class weights in the weighted binary cross-entropy loss were not set manually but were computed automatically for each dataset from its training-set class counts according to Equations 19 and 20. For the UNSW-NB15 dataset, the resulting class weights were
for the normal class and
for the intrusion class. For the CICIDS2017 dataset, the resulting class weights were
for the normal class and
for the intrusion class. For the Bot-IoT dataset (5% subset), the resulting class weights were
for the normal class and
for the intrusion class.
Training Strategy and Optimization
The Extended BiLSTM model was trained using mini-batches of size B = 64 with weighted binary cross-entropy loss, the Adam optimizer, and early stopping based on validation loss. Training was capped at 50 epochs, and early stopping was applied with patience K = 5. If validation loss did not improve for five consecutive epochs, training was halted and the model weights were restored to those from the epoch with the lowest validation loss. Thus, 50 epochs represented the maximum training budget rather than a fixed training duration. A dropout probability of 0.3 was applied for regularization. The architectural settings included 64 Conv1D filters, 64 LSTM units per direction, a window length of T = 20, and a stride of s = 1. The adopted training strategy is summarized in Algorithm 3 (Supplementary File 1). The Adam update equations used for optimization are provided in Supplementary File 3A.
The Adam optimizer was configured with a learning rate of
, a first-moment decay rate (β1) of 0.9, a second-moment decay rate (β2) of 0.999, and a numerical-stability constant (
) of 1 × 10-7. No additional optimizer options were used, and no weight decay or gradient clipping was applied.
Alert Generation and Automated Mitigation
Detection alone is insufficient in latency-sensitive IoMT networks, where rapid response is critical to ensure patient safety. The Alert Generation and Mitigation Layer operationalizes the intrusion decision made by the Extended BiLSTM model and the blockchain logging mechanism. If δt = 1, the blockchain module appends a new block containing the intrusion details
. Simultaneously, a smart contract is executed to trigger mitigation actions (Equation 22):
(12)
Here, BlockCreation ensures immutable forensic logging of the event, NodeIsolation (nj) quarantines the compromised IoMT node to prevent further damage, and AdminAlert delivers real-time notification to system administrators. To operate this dual-layer response pipeline, the pseudocode is presented in Algorithm 4 (Supplementary File 1).
Smart-contract event processing and off-chain response mechanisms are described in Supplementary File 3E.
Each entry committed to the blockchain ledger is stored as an IntrusionBlock record, whose fields and data formats are listed in Table 8. The ledger is an append-only array of these records, and the current chain head stores the hash of the most recently added block.
| S. No. | Field | Data Type | Size | Description |
| 1 | hashId | bytes32 | 32 bytes | Block hash Hi = Keccak-256(Di ∥ Ti ∥ probability ∥ PrevHash) |
| 2 | timestamp | uint256 | 32 bytes | Block creation time Ti (Unix epoch seconds, from the block timestamp) |
| 3 | nodeId | bytes32 | 32 bytes | Identifier of the IoMT node nj |
| 4 | patientId | bytes32 | 32 bytes | Patient/device identifier (forensic metadata) |
| 5 | attackClass | uint16 | 2 bytes | Attack-category code (0 = Normal, 1 = DDoS, 2 = Spoofing, ...) |
| 6 | probabilityBp | uint16 | 2 bytes | Predicted intrusion probability ŷ in basis points (0–10000, i.e. 0.00–100.00%) |
| 7 | dataDigest | bytes32 | 32 bytes | Digest Di of the selected event features |
| 8 | signature | bytes | Variable (65 bytes) | ECDSA signature Sigi of the event digest by the gateway (r, s, v) |
| 9 | prevHash | bytes32 | 32 bytes | Hash of the previous block (PrevHash), linking the chain |
| 10 | isolated | bool | 1 byte | Whether node isolation was triggered for this record |
Table 8: Structure of the IntrusionBlock record stored in the blockchain ledger. This table describes the fields, data types, storage sizes, and purposes of the blockchain ledger records used to store intrusion events. The structure supports cryptographic integrity verification, forensic traceability, and automated response mechanisms.
The overall mitigation latency can be expressed as the sum of the detection delay (Td) from the Extended BiLSTM model and the blockchain execution delay (Tb) (Equation 23):
(23)
Computational Complexity Analysis
The efficiency of the proposed Extended BiLSTM–Blockchain framework is determined by both the computational cost of the BiLSTM model and the overhead introduced by the blockchain module. The proposed framework integrates Extended BiLSTM detection with blockchain logging to satisfy the core security requirements of the Confidentiality, Integrity, and Availability (CIA) triad.
Let the preprocessed input sequence length be T, the feature dimension be d, and the hidden dimension of the BiLSTM be h.
For each time step, a BiLSTM processes input of dimension d with hidden size h. Since it is bidirectional (forward + backward) (Equation 24):
) (24)
Here, T is sequence length (time steps), d is input feature dimension, h is hidden state dimension
The attention layer computes importance weights and aggregates hidden states with complexity (Equation 25).
(25)
which is linear in both the sequence length T and hidden dimension h.
The overall detection complexity per sequence is therefore given as follows (Equation 26):
(26)
demonstrating that temporal modeling dominates the computational cost, while the attention mechanism introduces only a lightweight overhead.
For each detected intrusion event, blockchain logging performs hashing, signing, and block-appending operations (Equation 27):
(27)
For N intrusion-detection events, the combined complexity becomes as follows (Equation 28):
(28)
which can be simplified as follows (Equation 29):
(29)
because the blockchain overhead grows linearly with the number of events and remains negligible compared with sequence-processing computations.
Computational complexity is summarized in Equations 24–29. Detailed interpretation is provided in Supplementary File 3F.