A blockchain-secured 6G smartgrid framework for resilient renewable energy integration and intelligent anomaly detection Authors: Ismail Hossain, Abu Shufian, Morium Akter Munny, Nowshad Amin, Rayan Hamza Alsisi Published: 2026 ABSTRACT AbstractThe integration of intermittent renewable energy into smart grids introduces critical vulnerabilities in security, transparency, and real-time resilience. This paper presents a novel blockchain-secured 6G Smart grid framework that synergistically integrates sixth generation (6G) ultra-reliable low-latency communication (URLLC), distributed ledger technology, and ensemble machine learning to establish a secure, scalable, and intelligent energy ecosystem. The proposed architecture leverages adaptive 6G network slicing to support differentiated services-including peer-to-peer energy trading, grid control, and cybersecurity monitoring-while ensuring sub-30 ms latency and robust connectivity. A permission blockchain layer provides decentralized trust, immutability, and automated transaction validation via formally verified smart contracts. An ensemble learning model combining XGBoost, Random Forest, and LightGBM enables real-time multi-dimensional anomaly detection across energy, network, and transaction layers. The framework is evaluated using a synthetically generated dataset of 5000 hourly records encompassing energy generation, consumption, 6G network performance, and blockchain transactions. Experimental results demonstrate a blockchain transaction success rate of 95.16% and sustained network latency below 30 ms across all slices, even under cyberattack conditions. Reported using class-based anomaly-detection metrics, the model achieves a Recall of 0.93 and F1-score of 0.97 for the anomaly class, and a Recall of 1.00 and F1-score of 0.99 for the normal class, with an overall accuracy of 0.98. The proposed system provides a foundational architecture for resilient, autonomous, and secure renewable energy management in next generation decentralized smart grids.Keywords: 6G networks, Machine learning and blockchain technology, Smartgrid security, Network slicing and cybersecurity, Energy tradingSubject terms: Energy science and technology, Engineering, Mathematics and computing Introduction The global energy landscape is undergoing a profound transformation driven by the urgent need for sustainable development and the rapid advancement of digital technologies. Decentralized renewable energy systems, particularly microgrids, have emerged as critical components in this transition, enabling efficient integration of distributed energy resources while enhancing grid resilience and energy accessibility1. However, this paradigm shift introduces complex challenges in security management, operational reliability, and transaction transparency that traditional energy systems were not designed to address. The proliferation of intermittent renewable sources, such as solar and wind generation, creates dynamic supply-demand imbalances that require sophisticated monitoring and control mechanisms. Photovoltaic forecasting accuracy is essential for reliable smart micro-grid operation and market-oriented scheduling in renewable-rich systems. Blockchain-enabled open electricity markets can support decentralized settlement, while standardization and regulatory constraints remain key barriers to data-driven micro-grid adoption2. Simultaneously, the increasing connectivity of energy infrastructure through Internet of Things devices expands the attack surface for potential cyber threats, risking grid stability and public safety. Furthermore, the growing adoption of peer-to-peer energy trading models demands secure, transparent, and efficient transaction mechanisms that conventional centralized systems cannot adequately provide. Recent technological advancements in communication networks and distributed systems offer promising solutions to these challenges. Sixth-generation wireless technology introduces unprecedented capabilities in ultra-reliable low-latency communication, network slicing, and massive machine-type communications, providing the necessary infrastructure for real-time microgrid operations3. Concurrently, blockchain technology brings inherent advantages in security, transparency, and decentralization through its immutable distributed ledger and innovative contract capabilities4. One study introduces a decentralized electricity trading framework for connected EVs using blockchain and machine learning to remove trusted intermediaries and improve transaction trustworthiness5. The work motivates blockchain-assisted P2P trading as a pathway to improved settlement efficiency and profitability optimization in decentralized energy markets. The integration of these technologies creates a synergistic ecosystem where 6G networks enable seamless connectivity and real-time data exchange, while blockchain ensures transaction integrity and system security. This convergence addresses fundamental requirements for modern microgrid operations, including real-time monitoring, secure energy trading, cyber threat detection, and automated control systems (Fig. 1). However, the practical implementation of this integrated approach requires careful consideration of technical constraints, performance optimization, and security implications across multiple operational dimensions. Microgrid with cyberattack. Contemporary research on microgrid technologies has extensively explored architectures for renewable energy integration. Hybrid optimization models for solar-wind storage systems have demonstrated significant improvements in energy utilization efficiency6. Adaptive control strategies for distributed energy resources have addressed voltage regulation challenges in islanded microgrid operations. These studies established foundational principles for renewable integration but primarily focused on physical system optimization without considering cybersecurity implications. Blockchain technology has garnered significant attention for energy sector applications. Ethereum-based smart contracts for transactive energy markets have achieved substantial reduction in settlement time compared to conventional systems7. Permissioned blockchain frameworks for grid data management have shown effectiveness in ensuring data integrity across multiple stakeholders8. Research has demonstrated blockchain’s effectiveness in preventing data tampering in smart meter communications, though scalability challenges during peak demand periods were noted9. The emergence of 6G technology has opened new frontiers for industrial applications. Terahertz communication capabilities for industrial automation have achieved sub-millisecond latency in controlled environments10. Network slicing investigations for smart city applications have demonstrated quality-of-service differentiation across various service types. Theoretical foundations for integrated sensing and communication in 6G networks have been established, though practical implementations in energy systems remained limited11. Cybersecurity research for energy systems has evolved substantially in recent years. Deep learning-based intrusion detection systems for supervisory control and data acquisition networks have achieved high accuracy in attack classification12. Cryptographic protocols for distributed energy resource management have addressed man-in-the-middle attack vulnerabilities13. Research has highlighted the increasing sophistication of false data injection attacks targeting state estimation in smart grids14. Machine learning applications in energy systems have demonstrated remarkable capabilities. Long short-term memory networks for load forecasting have reduced prediction errors significantly compared to traditional methods15. Ensemble methods for equipment failure prediction in substations have achieved early detection of potential faults16. Unsupervised learning approaches for anomaly detection in power consumption patterns have shown promise, though integration with network security parameters remained unexplored17,18. Another study focuses on smart micro-grid cybersecurity and explains how IoT sensing, ML-based detection, and blockchain-based trust/auditability can be combined to mitigate cyber threats such as false data injection and related integrity attacks. It also emphasizes that standards and regulation remain open issues when integrating these technologies into operational smart micro-grid environments19. Limited research has attempted integrated technological solutions for energy systems. Combinations of IoT sensors with blockchain for renewable energy certificate tracking have demonstrated enhanced transparency in green energy attribution20. 5G-enabled microgrid communications have established baseline performance metrics for network reliability21. However, these approaches lacked comprehensive security frameworks and did not leverage advanced 6G capabilities22. Recent investigations into blockchain-based demand response management have shown improved coordination efficiency, while federated learning approaches for distributed energy systems have addressed data privacy concerns23. Research on network slicing specifically for energy systems remains limited. Investigations into slice management for smart grid communications have proposed resource allocation strategies24. Studies on network function virtualization in power systems have demonstrated potential benefits for grid modernization25. However, comprehensive frameworks integrating network slicing with blockchain security for microgrid applications are notably absent from current literature. Advanced anomaly detection techniques for cyber-physical energy systems have shown progressive development. Physics-informed neural networks have been applied to power system anomaly detection26. Graph neural network approaches have demonstrated capabilities in identifying cyber-physical attacks27. Multi-modal learning frameworks have been proposed for integrated security monitoring28, though real-time implementation challenges persist. Recent blockchain-enabled edge intelligence studies provide useful context for positioning the advantages and applicability of the proposed blockchain-secured 6G smart grid framework. One recent study introduced a dynamic blockchain–empowered end–edge collaborative computing architecture and used a rotating multi-agent deep reinforcement learning strategy to improve trustworthiness and timeliness under changing edge conditions, highlighting how adaptive consensus/coordination can reduce failures and delays in distributed environments29. Another study proposed a digital twin-assisted, blockchain-based vehicular edge computing approach for intelligent secure task offloading and caching, demonstrating how digital twins can support decision-making while blockchain maintains integrity and accountability of offloading transactions30. A further study investigated digital twin–assisted multi-task offloading for vehicular edge computing under a space air ground integrated network with blockchain, emphasizing privacy/trust benefits of blockchain when mobility and heterogeneity increase operational uncertainty31. Another recent contribution combined blockchain-based reputation management with deep reinforcement learning for trust-enabled decentralized task offloading, reinforcing the role of blockchain governance and trust signals in securing distributed collaboration. Collectively, these studies motivate blockchain–edge intelligence integration for trust and resilience; however, they primarily focus on offloading/caching in vehicular/edge computing, whereas our work targets a 6G-enabled smart grid/microgrid security context by integrating URLLC-oriented slicing, permissioned-ledger auditability for energy trading, and ensemble ML anomaly detection over energy–network–ledger telemetry. The comprehensive literature review reveals several critical research gaps that this work addresses. Lack of Integrated Blockchain-6G Architecture: No existing framework synergistically combines 6G network slicing with blockchain technology for microgrid security and operational efficiency. Lack of Integrated Blockchain-6G Architecture: No existing framework synergistically combines 6G network slicing with blockchain technology for microgrid security and operational efficiency. Inadequate Multi-Dimensional Anomaly Detection: Current systems lack real-time detection capabilities that simultaneously analyze energy patterns, network behaviors, and transaction integrity. Inadequate Multi-Dimensional Anomaly Detection: Current systems lack real-time detection capabilities that simultaneously analyze energy patterns, network behaviors, and transaction integrity. Unoptimized Network Slicing for Energy Applications: Optimal configuration of 6G network slices for diverse microgrid operations remains unexplored, particularly balancing latency, reliability, and security requirements. Unoptimized Network Slicing for Energy Applications: Optimal configuration of 6G network slices for diverse microgrid operations remains unexplored, particularly balancing latency, reliability, and security requirements. Blockchain Scalability Limitations: Existing implementations show performance degradation during high-frequency energy trading, with insufficient optimization strategies for maintaining throughput during demand fluctuations. Blockchain Scalability Limitations: Existing implementations show performance degradation during high-frequency energy trading, with insufficient optimization strategies for maintaining throughput during demand fluctuations. Smart Contract Inefficiency: Current designs fail to adequately balance computational complexity, execution speed, and security requirements across different energy transaction types. Smart Contract Inefficiency: Current designs fail to adequately balance computational complexity, execution speed, and security requirements across different energy transaction types. Research objectives and contributions This study develops and validates a comprehensive framework for secure renewable energy integration in smart microgrids through synergistic integration of Sixth Generation wireless communication networks and blockchain technology. The investigation pursues these objectives-. Design a multi-layered architecture integrating 6G’s ultra-reliable low-latency communication and network slicing with blockchain’s decentralized security and transparency, establishing resilient cyber-physical energy infrastructure. Design a multi-layered architecture integrating 6G’s ultra-reliable low-latency communication and network slicing with blockchain’s decentralized security and transparency, establishing resilient cyber-physical energy infrastructure. Developed and validated advanced machine learning framework for real-time anomaly detection by analyzing multi-dimensional data from energy systems, network performance, and blockchain transactions. Developed and validated advanced machine learning framework for real-time anomaly detection by analyzing multi-dimensional data from energy systems, network performance, and blockchain transactions. Analyzed and optimized blockchain performance under various network conditions, focusing on transaction success rates, latency impacts, and cost efficiency in energy trading scenarios. Analyzed and optimized blockchain performance under various network conditions, focusing on transaction success rates, latency impacts, and cost efficiency in energy trading scenarios. Evaluate and configure 6G network slicing for different microgrid applications, identifying optimal parameters for energy trading, monitoring systems, and control operations. Evaluate and configure 6G network slicing for different microgrid applications, identifying optimal parameters for energy trading, monitoring systems, and control operations. Create a comprehensive framework for scalable, secure renewable energy integration that can be adapted to various microgrid configurations and operational requirements. Create a comprehensive framework for scalable, secure renewable energy integration that can be adapted to various microgrid configurations and operational requirements. This research delivers substantial and multifaceted contributions to the advancement of secure smart grid technology and renewable energy system integration, addressing critical challenges at the intersection of communications, cybersecurity, and energy infrastructure. Through comprehensive investigation and empirical validation, the study establishes new paradigms and provides actionable solutions across several key domains. The contributions are enumerated as follows-. Development of a comprehensive theoretical framework that synergistically combines 6G network capabilities with blockchain technology for microgrid security and efficiency. Development of a comprehensive theoretical framework that synergistically combines 6G network capabilities with blockchain technology for microgrid security and efficiency. Formulation of a multi-dimensional anomaly detection approach that simultaneously considers energy patterns, network behaviors, and transaction integrity. Formulation of a multi-dimensional anomaly detection approach that simultaneously considers energy patterns, network behaviors, and transaction integrity. Design and configuration of adaptive 6G network slicing for distinct microgrid functionalities, including energy trading, monitoring, and control operations. The slicing mechanism dynamically allocates communication resources according to service priority, achieving latency below 30 ms and packet loss below 3%, thereby satisfying URLLC-grade reliability standards. Design and configuration of adaptive 6G network slicing for distinct microgrid functionalities, including energy trading, monitoring, and control operations. The slicing mechanism dynamically allocates communication resources according to service priority, achieving latency below 30 ms and packet loss below 3%, thereby satisfying URLLC-grade reliability standards. Optimization of blockchain performance and consensus mechanisms tailored for microgrid environments, ensuring high transaction throughput, reduced verification latency, and consistent performance under varying network and trading loads. The proposed system achieved a 95.16% transaction success rate and maintained operational integrity during dynamic energy exchange scenarios. Optimization of blockchain performance and consensus mechanisms tailored for microgrid environments, ensuring high transaction throughput, reduced verification latency, and consistent performance under varying network and trading loads. The proposed system achieved a 95.16% transaction success rate and maintained operational integrity during dynamic energy exchange scenarios. Comprehensive experimental validation using a real-world dataset comprising 3,264 hourly records, encompassing energy generation, consumption, network performance, and blockchain transaction data. Comprehensive experimental validation using a real-world dataset comprising 3,264 hourly records, encompassing energy generation, consumption, network performance, and blockchain transaction data. Blockchain technology for energy system Blockchain technology represents a decentralized digital ledger system that operates as a distributed database, maintaining an immutable, chronologically ordered sequence of data blocks, with each new transaction being systematically appended to this ever-expanding chain32. The inherent security of blockchain systems derives from advanced cryptographic protocols, where every transaction initiates the generation of an asymmetric cryptographic digital signature that serves to validate and authenticate the transaction’s legitimacy. This cryptographic framework establishes a paired key infrastructure comprising public and private keys, which are exclusively controlled by the transaction participants within the network ecosystem. The public key component, employed in the data decryption process, remains openly accessible to all network participants, while the corresponding private key remains confidential to its owner, ensuring secure transaction authorization and identity verification33. Figure 2 illustrates the four foundational pillars of blockchain technology: Decentralization, which eliminates the need for a central authority by distributing control across a network; Immutability, which guarantees that recorded data cannot be altered or tampered with once validated; Transparency, which enables all participants to view the transaction history and verify the ledger’s state; and Security, which is provided through advanced cryptographic techniques and consensus mechanisms that protect the network from fraud and attacks. The diagram typically represents these characteristics as interconnected or mutually reinforcing elements, highlighting their collective role in creating a secure, transparent, and trustworthy decentralized system. The four main characteristics of blockchain technology. The increasing penetration of distributed renewable energy resources and the evolution toward 6G-enabled smart microgrids necessitate a secure, transparent, and decentralized energy management infrastructure. Blockchain technology has emerged as a promising solution to address critical challenges related to trust, data integrity, cybersecurity, and real-time coordination in modern energy systems34. Blockchain is a distributed ledger technology (DLT) that enables secure and immutable recording of transactions across a decentralized network. In energy systems, blockchain facilitates trusted data exchange among microgrid participants, including distributed energy resources (DERs), prosumers, utilities, and grid operators, without reliance on a centralized authority. Each transaction-such as energy generation, consumption, storage, or trading-is cryptographically signed and grouped into blocks. These blocks are sequentially linked using cryptographic hash functions, ensuring data immutability and resistance to tampering. Consensus mechanisms, such as Proof of Stake (PoS) or Practical Byzantine Fault Tolerance (PBFT), are commonly preferred in energy applications due to their low latency and energy efficiency compared to P roof of Work (PoW)35. Blockchain enhances the integration of renewable energy sources by ensuring secure coordination and verification of distributed generation units. Through smart contracts, energy generation and consumption are automatically validated based on predefined rules, enabling transparent peer-to-peer (P2P) energy trading within microgrids. Figure 3 shows the framework of blockchain based microgrid. Blockchain based microgrid framework. The design of energy trading smart contracts incorporates formal verification methodologies to ensure mathematical correctness and security guarantees. The contract logic is specified using Linear Temporal Logic (LTL) to capture both safety and liveness properties essential for reliable energy transactions36. This temporal logic expression of Eq. (1) guarantees that once a trade is initiated (initiate Trade (tx)), it will eventually be verified (verify Transaction (tx)) and will permanently remain executed (executed Trade(tx)), ensuring no transaction remains in an intermediate state indefinitely. The verification framework employs model checking techniques to validate that all possible system executions satisfy the specified security properties and can be described using Eq. (2). This formal verification ensures that for every transaction in the transaction set , the system model satisfies the property that if a transaction is verified, it necessarily implies that the energy being traded is valid and that both trading parties possess sufficient balance (either in energy units or monetary terms) to complete the transaction. The formal verification process employs theorem proving techniques to establish these guarantees, ensuring the smart contracts are free from critical vulnerabilities such as reentrancy attacks, arithmetic overflows, and logical inconsistencies that could compromise system security. PBFT is selected for its deterministic finality and bounded latency, essential for real-time energy trading in 6G microgrids. Unlike PoS or PoA, PBFT provides immediate transaction finality and tolerates Byzantine faults in permissioned networks without PoW’s energy cost or PoS’s economic vulnerabilities, ensuring secure, low-latency consensus aligned with URLLC requirements. Practical Byzantine Fault Tolerance (PBFT) algorithms are critical for distributed systems, as they solve the Byzantine generals’ problem. This classic dilemma involves a group of general-representing network nodes in a blockchain context-attempting to agree on a joint action despite unreliable communication and the presence of potential traitors37. In the original analogy, Byzantine generals must coordinate their armies to attack a citadel at the same time, even though messages between them may be intercepted, lost, or tampered with. Similarly, in blockchains, nodes must reach consensus on whether to validate a block or set of transactions across a decentralized and potentially unstable network. The challenge is further heightened by the possibility that some participants may be malicious sending false information, altering messages, or refusing to communicate-with the goal of sabotaging the consensus process38. The core objective is to ensure that honest nodes can still agree on a consistent decision, even if a subset behaves dishonestly. Translated to blockchain terms, this means preventing a minority of untrustworthy or malicious nodes from corrupting the validation of illegitimate transactions. Because PBFT relies on known, trusted validators to individually verify transactions, it is particularly well-suited for permission or consortium blockchain environments where participant identity is controlled and trust is higher. Figure 4 illustrates the operational mechanism of practical Byzantine fault tolerance. Practical Byzantine Fault Tolerance (PBFT). The PBFT consensus algorithm has been specifically optimized for energy transaction environments, considering the unique characteristics of microgrid operations including time-sensitive energy transfers and varying network conditions. For a distributed system comprising nodes, the optimized PBFT consensus mechanism can tolerate faulty nodes and can be described using Eqs. (3) and (4). This bound represents the maximum number of malicious or non-responsive nodes that the system can withstand while maintaining correct operation39. The consensus process requires a quorum of validating nodes to approve each transaction, with the minimum quorum size . This quorum requirement ensures that even in the presence of faulty nodes, most honest nodes () can agree on transaction validity. The probability of consensus failure, representing the likelihood that faulty nodes could disrupt the agreement process, as found by Eq. (5), where denotes the probability of individual node failure, assuming independent failure events. This formulation enables system designers to calculate the required redundancy level for achieving target reliability metrics in energy trading scenarios. Figure 5 illustrates the optimized PBFT consensus flow specifically tailored for energy transactions, depicting the three-phase protocol. PBFT consensus process for energy transactions. The transaction verification time represents a critical performance metric for real-time energy trading applications (Fig. 6). The total verification delay is modeled as the sum of three principal components and can be described using Eq. (6). This delay model enables performance optimization through adaptive selection of validator sets based on network conditions and computational capabilities40. For time-critical energy transactions, the system dynamically selects validators with optimal characteristics while maintaining the required security guarantees established by Eqs. (3) and (4). Decentralized systems integrating blockchain’s P2P features. Peer-to-peer energy transaction processing initiates with direct energy exchange between prosumers and consumers, followed by smart contracts autonomously executing payment settlements calculated from real-time tariff and consumption data (Fig. 7). These transactions are encrypted using advanced cryptographic methods such as homomorphic encryption and aggregated into blocks, which are validated by blockchain miners and broadcast network-wide for decentralized consensus verification, ensuring fund availability and transaction integrity41. The blockchain maintains an immutable, chronologically ordered ledger through cryptographic hashing and digital signatures, linking blocks into a secure chain that preserves a complete transaction history, while secondary protocol layers are concurrently explored to enhance scalability and transaction throughput without compromising the foundational security architecture of the decentralized system. Peer-to-peer (P2P) energy trading framework based on blockchain technology. Smart meters are installed at each household, enabling participants to act as prosumers or consumers. The trading parties, denoted as Node A (prosumer) and Node B (consumer), exchange energy through a smart contract. Transaction authorization is performed using digital signatures generated with the participants’ private keys. Validated transactions are encrypted, grouped into blocks, and recorded on the blockchain through sidechain and root-chain mechanisms. Despite recent advances in blockchain technologies, practical deployments continue to face cybersecurity challenges including forks, selfish behavior, consensus-layer attacks, privacy/anonymity trade-offs, and smart-contract vulnerabilities; therefore, the proposed framework adopts a permissioned ledger with explicit mitigations aligned to smart grid requirements. Fork-related uncertainty is reduced using PBFT-style consensus with deterministic finality once quorum agreement is reached, thereby limiting competing-chain scenarios that are more typical in public PoW environments. Selfish mining is primarily associated with competitive PoW mining and is not directly applicable in the proposed setting because block validation is performed by authenticated consortium validators rather than open miners. To address consensus-layer risks (compromised or Byzantine validators), the framework assumes controlled validator admission, quorum thresholds, and governance actions (revoking validator membership) in the event of misbehavior. Privacy and access governance are supported through permissioned participation (controlled membership) and cryptographic authentication using public–private keys and digital signatures, with sensitive transaction payloads protected via encryption while retaining verifiable metadata on-chain for auditability. Finally, smart-contract security is strengthened through strict authorization checks, input validation, and systematic testing/verification practices to reduce implementation flaws and ensure that only legitimate energy-trading and settlement operations are executed. 6G communication infrastructure As 5G networks continue their global rollout, researchers and industry pioneers are already envisioning its successor-6G. Expected to debut around 2030, 6G promises to revolutionize connectivity by merging the physical, digital, and biological worlds into a seamless, intelligent ecosystem42. 6G (sixth-generation wireless) is the next iteration of cellular technology, building upon 5G’s foundation but with transformative advances in speed, latency, intelligence, and applications. It aims to support data rates up to 1 terabit per second (Tbps)−100 times faster than peak 5G-with near-zero latency and ubiquitous coverage extending to oceans, space, and remote areas43. The advances in mobile network technology across different generations are compared in Fig. 8. Evolution of mobile network technology. The deployment of sixth generation (6G) wireless communication technology represents a paradigm shift in microgrid infrastructure, enabling unprecedented levels of connectivity, intelligence, and operational efficiency. Unlike previous wireless generations, 6G systems are specifically engineered to simultaneously support three critical communication paradigms: Enhanced Mobile Broadband (eMBB) for high-data-rate applications, Ultra-Reliable Low-Latency Communication (URLLC) for mission-critical control functions, and Massive Machine-Type Communication (mMTC) for extensive IoT device integration44. This trifecta of capabilities positions 6G as the ideal communication backbone for modern microgrids, which demand heterogeneous service requirements across distributed energy resources, real-time monitoring systems, and secure transaction processing. The mathematical foundation of 6G microgrid communication can be expressed through a multi-dimensional optimization framework, as analyzed by Eq. (7) where , , , and are respectively latency minimization, energy efficiency optimization, communication cost reduction, security enhancement and the set of all microgrid applications45. The 6G network implements four specialized slices with tailored parameters to meet diverse microgrid operational requirements, as detailed in Table 1. Each slice employs dynamic resource allocation based on real-time operational demands, with priority scheduling ensuring critical services maintain required performance levels during congestion periods. The network slicing parameters are derived through empirical traffic analysis and QoS-guaranteed optimization. Table 1Network slice configuration parameters.Slice typeLatency requirement (ms)ReliabilityBandwidth (Mbps)Security levelPrimary functionCybersecurity≤ 300.99999100MaximumSecurity monitoring and threat detectionEnergy distribution≤ 500.999950HighGrid control and stability managementP2P trading≤ 1000.999200HighTransaction processing and settlementMonitoring≤ 1500.99300MediumSystem surveillance and data collection Network slice configuration parameters. For the critical protection and control functions within a smart microgrid, 6G delivers Ultra-Reliable Low-Latency Communication (URLLC) by establishing deterministic, mathematically bounded latency guarantees through advanced scheduling algorithms46. The probability that the end-to-end latency remains below a stringent target is ensured by the bounds through advanced scheduling algorithms, as found from Eq. (8). The total latency decomposition can be described using Eq. (9), where each component is strictly bounded: propagation by , by queuing delay for a stable system () , and processing latency by . Unprecedented reliability is further achieved through multi-dimensional diversity: spatial diversity with , frequency diversity yielding an effective rate of , and temporal diversity ensuring success probability 47. The massive integration of IoT devices-from sensors to distributed energy resource controllers is facilitated by scalable multiple access schemes. The maximum number of supported devices can be described using Eq. (10). Where the capacity of Non-Orthogonal Multiple Access (NOMA) is defined by Eq. (11). For energy-constrained devices, total consumption is minimized, follows Eq. (12)48. Computational efficiency for data-intensive grid analytics is ensured by a three-tier edge-fog-cloud architecture, where the system response time follows Eq. 13. Distributed intelligence is enabled via federated learning, which seeks the global model parameter that minimizes the objective and can be described using Eq. (14). This framework allows collaborative model training across edge devices without centralizing sensitive operational data, preserving privacy while enhancing grid intelligence49. A multi-faceted security framework provides robust, multi-layered protection for microgrid communications and data. Information-theoretic physical layer security is quantified by the secrecy capacity, as seen from Eq. (15)50. Sustainable operation is achieved through self-powered infrastructure utilizing hybrid renewable energy harvesting, with the harvested power at time following Eq. (16) and storage dynamics following Eq. (17). The integration with a blockchain layer for immutable transaction logging and coordination is optimized based on network conditions and can be described using Eq. (18). Finally, a comprehensive cross-layer optimization framework jointly coordinates communication, computation, and security parameters following Eq. (19)51. Machine learning for anomaly detection The integration of machine learning for anomaly detection represents a critical component in securing 6G-enabled microgrid systems against sophisticated cyber-physical threats52. This section presents a comprehensive framework for real-time anomaly detection that leverages ensemble learning methodologies to identify security breaches, operational irregularities, and system faults with high precision and reliability. The anomaly detection problem is formally defined as a binary classification task where the objective is to distinguish between normal system operation and anomalous states. Given a multivariate time series dataset , where represents system state vectors and indicates anomaly labels, the goal is to learn a mapping function }, that minimizes the detection error while maintaining computational efficiency suitable for real-time microgrid operations. Figure 9 shows the process of anomaly detection using machine learning. ML strategies for anomaly detection and enhance cybersecurity. Feature engineering framework Multi-modal feature extraction A comprehensive feature engineering pipeline was developed to capture the multi-faceted nature of microgrid operations. The feature set encompasses five distinct categories. Cyclical temporal patterns are crucial for forecasting energy demand and renewable generation. The hour of the day () and day of the week () are encoded into continuous, cyclical features using sine and cosine transformations to preserve their periodic nature and avoid artificial discontinuities and can be described using Eqs. 20–2353. Energy system features quantify the balance, sustainability, and resource utilization within the physical energy layer. Energy Imbalance Ratio Measures the instantaneous mismatch between total demand () and total local generation (), normalized by demand. High values indicate significant net load or surplus and can be described using Eq. (37)54. Renewable Penetration Represents the fraction of total demand met by intermittent renewable sources (solar and wind ). It indicates the grid’s instantaneous clean energy share and can be described using Eq. (38)51. Storage Utilization is the ratio of current energy stored in the battery () to its total capacity (), reflecting the state of charge of the primary storage asset and grid Dependency is the proportion of demand that is supplied by power from the main utility grid (), indicating the microgrid’s reliance on external power and can be described using Eqs. (39) and (27) respectively55. Network performance metrics characterize the health and stability of the underlying communication network, which is critical for reliable control and blockchain consensus. The standardized absolute deviation of the observed communication latency () from its historical mean (), normalized by the historical standard deviation (). It identifies abnormal network delays and can be described using Eq. (41)1. The instantaneous rate of change of the packet loss rate () over time, calculated as its first derivative . A positive trend signals deteriorating network conditions Eq. (42)56. The coefficient of variation (ratio of standard deviation to mean ) for device or controller response times. A higher value indicates greater jitter and less predictable control system performance and can be described using Eq. (30)57. Blockchain transaction features quantify the activity, efficiency, and economic aspects of the blockchain layer managing energy transactions, which can be described using Eqs. (31)-(33)58. The rate of energy transaction submissions to the blockchain over a defined time window (), calculated as the count of transactions () per . The elapsed time between the initiation () and final on-chain confirmation () of a transaction. This directly measures the blockchain’s settlement latency. The Z-score of the transaction fee or gas cost (), measuring how much it deviates from the typical historical mean cost () in units of historical standard deviation (). It flags abnormally high or low transaction costs. Power quality features assess the stability and purity of the electrical power being delivered within the microgrid. Voltage Stability Index quantifies the magnitude of voltage fluctuations can be described using Eq. (34)59. Current Harmonic Distortion measures the distortion caused by non-linear loads, as found in Eq. (35)60. Power Factor Consistency is the measure of the variability in the power factor (PF) by Eq. (36)61, A value closer to 1 indicates stable, near-unity power factor operation. This multi-modal feature set provides a unified numerical representation of the system’s state across all critical layers, serving as the input vector for subsequent anomaly detection and predictive modeling tasks. Feature selection employed recursive feature elimination with 5-fold cross-validation, ultimately retaining the top 15 features based on importance scores derived from Random Forest feature importance analysis. Ensemble learning framework An ensemble learning approach was adopted to leverage the complementary strengths of multiple machine learning algorithms. Ensemble learning is adopted because the dataset integrates heterogeneous signals from the energy layer (generation, demand, storage dynamics), the 6G slicing layer (latency, response time, packet loss), and the blockchain layer (transaction cost, verification behavior), where feature relationships are non-linear and may be distorted under attacks. By aggregating multiple learners, the ensemble reduces variance, mitigates overfitting, and produces more stable anomaly predictions than a single learner, which is important for security-critical applications where missed anomalies can be high-impact. The ensemble architecture integrates three state-of-the-art algorithms. XGBoost, Random Forest, and Light Gradient Boosting Machine (LightGBM) can be described using Eqs. (37)-(38)54, where . A weighted averaging strategy is employed for final prediction aggregation, with weights optimized through cross-validation. LightGBM Utilizing gradient-based one-side sampling (GOSS) and exclusive feature bundling (EFB) for enhanced efficiency. The final prediction is obtained through weighted averaging of individual model outputs and can be described using Eq. (39)1. A stratified 5-fold cross-validation approach was employed to ensure robust performance estimation using Eq. (40)1. Bayesian optimization with Tree-structured Parzen Estimator (TPE) was used for hyperparameter tuning, as found by Eq. (41)56. The acquisition function follows expected improvement, as calculated by Eq. (42)54. Overall system architecture The proposed blockchain-secured 6G microgrid system implements a hierarchical four-layer architecture designed to seamlessly integrate physical energy infrastructure with advanced communication technologies, distributed ledger security, and intelligent analytics (Fig. 10). This carefully structured approach ensures robust operation while maintaining security, reliability, and efficiency across all system components. The architecture follows a cyber-physical system paradigm where each layer performs specialized functions while maintaining tight integration with adjacent layers through well-defined interfaces and protocols. Blockchain-enabled smart microgrid system architecture. Physical infrastructure layer The foundation of the system comprises the physical energy generation, storage, and consumption components that form the operational core of the microgrid. This layer integrates solar photovoltaic systems operating within irradiation levels of 436.28–998.12 W/m² and wind turbines functioning across wind speeds of 0.13–14.99 m/s, with maximum generation capacities reaching 298.69 kWh and 248.65 kWh respectively. Energy storage infrastructure employs lithium-ion battery banks with intelligent management systems, supporting maximum storage capacity of 496.87 kWh while maintaining state-of-charge within safe operational limits. Consumption patterns are monitored through IoT-enabled smart meters that capture critical electrical parameters including voltage (210.17–249.73 V), current (5.25–49.96 A), and power factor (0.85–0.99) with response times ranging from 15.95 to 98.71 ms. The energy balance governing this layer follows the fundamental equation , ensuring continuous equilibrium between generation and consumption while maintaining grid stability through precise monitoring and control mechanisms. Network communication layer The 6G-enabled communication infrastructure provides the backbone for real-time data exchange and control signal transmission across the microgrid ecosystem. This layer implements advanced network slicing technology, creating four specialized virtual networks tailored to distinct operational requirements: a Cybersecurity Slice optimized for security monitoring with ultra-low latency requirements (7.29–49.86 ms), an Energy Distribution Slice balancing latency and reliability for grid operations (5.04–46.93 ms), a P2P Trading Slice emphasizing high throughput for transaction processing (5.77–49.86 ms), and a Monitoring Slice with mixed criticality for general surveillance (5.19–49.50 ms). Edge computing nodes distributed throughout the network provide localized processing capabilities, reducing cloud dependency and minimizing latency for time-sensitive operations through the optimized processing model . The resource allocation follows a convex optimization formulation subject to capacity constraints, ensuring optimal utilization of network resources while meeting quality-of-service requirements for each application category. Blockchain security layer The blockchain security layer establishes a decentralized trust framework that ensures transaction integrity, data immutability, and participant authentication across the entire microgrid ecosystem. This layer implements a Practical Byzantine Fault Tolerance (PBFT) consensus mechanism specifically optimized for energy transactions, maintaining the security condition where represents total nodes and denotes faulty nodes. Smart contracts automate energy trading agreements and system operations through formally specified execution logic, with each transaction undergoing cryptographic verification using elliptical curve cryptography . The distributed ledger maintains an immutable record of all energy transactions, system events, and security incidents, providing transparent audit trails while preventing unauthorized modifications. This layer ensures end-to-end security through a multi-faceted approach combining cryptographic protection, consensus-based validation, and smart contract execution, creating a resilient foundation for secure peer-to-peer energy trading and system operation. Application analytics layer The intelligence layer integrates advanced computational capabilities for real-time monitoring, predictive analytics, and intelligent decision-making that optimize microgrid operations and enhance security posture. Real-time monitoring dashboards provide comprehensive visualization of system status, performance metrics, and security indicators across all operational dimensions. Machine learning-based anomaly detection engines employ ensemble learning methodologies to identify security threats, operational irregularities, and equipment failures with high precision and recall. Predictive analytics modules forecast energy demand and generation patterns using time-series analysis and regression techniques, enabling proactive resource allocation and load balancing. Optimization algorithms implement model predictive control strategies to maximize renewable energy utilization, minimize operational costs, and ensure grid stability while adapting to dynamic operating conditions and evolving threat landscapes. This integrated four-layer architecture provides a comprehensive framework that addresses the complex requirements of modern microgrid systems, combining the reliability of traditional energy infrastructure with the security of blockchain technology and the performance of 6G communication networks. Each layer operates synergistically with adjacent layers through well-defined interfaces and protocols, creating a resilient ecosystem capable of adapting to evolving operational requirements and security challenges while maintaining high standards of performance, security, and efficiency. The integrated operational algorithm coordinates energy management, blockchain transactions, network optimization, and security monitoring in a unified framework. The algorithm executes at regular intervals to maintain real-time control and adaptation. Algorithm 1 implements the integrated operational framework for the blockchain-secured 6G microgrid, coordinating energy management, network optimization, and security monitoring in real-time. The algorithm collects multi-source data from physical infrastructure, network communication, and blockchain layers to compute net energy balance and make intelligent decisions for energy surplus or deficit scenarios. It initiates P2P energy trading via blockchain when surplus exists, optimizes 6G network slices through constrained resource allocation, and detects anomalies using ensemble machine learning models. The algorithm continuously monitors system performance, executes security responses when threats are detected, and stores operational reports on the immutable blockchain ledger, ensuring coordinated operation across all system layers within bounded time constraints. Integrated operation of blockchain secured 6G microgrid. Algorithm 2 implements the Practical Byzantine Fault Tolerance (PBFT) consensus mechanism for verifying energy transactions in the microgrid ecosystem. The algorithm operates through a five-phase protocol (Request, Pre-prepare, Prepare, Commit, Execute) where validator nodes collectively verify transaction validity while tolerating up to f Byzantine faulty nodes. It ensures secure consensus through quorum-based voting with requirements, providing cryptographic proof of agreement for all energy transfers. The algorithm includes timeout handling, view-change protocols for primary node failures, and malicious node detection mechanisms to maintain system integrity and liveness. Optimizations such as transaction batching and adaptive timeout adjustment enhance throughput and reliability for real-time energy trading operations. PBFT consensus for energy transactions. Datasets and feature analysis The analysis utilizes a high-fidelity synthetic dataset of 5000 hourly records, generated to reflect real-world operation and integrated with simulated 6G network and blockchain transaction logs. Energy generation metrics capture solar and wind generation patterns, battery storage dynamics, and state-of-charge variations. Consumption patterns monitor residential, commercial, and industrial load profiles with temporal resolution enabling detailed pattern analysis. Network performance indicators track latency, response time, and packet loss metrics across all communication channels. Blockchain transaction records document energy trading volumes, associated costs, and verification status with cryptographic integrity assurance. Cybersecurity events log attack detection incidents and system-generated anomaly flags with precise timestamps for correlation analysis. Network attacks and anomalies were injected into the synthetic dataset using a transparent, rule-based procedure that overlays controlled perturbations on normal operating trajectories of the microgrid and 6G network. First, baseline normal time-series were generated for demand, renewable generation, storage/SOC dynamics, key electrical measurements (voltage, current, power factor), network-slicing KPIs (latency, response time, packet loss), and blockchain transaction variables (transaction cost, validation status). Next, anomaly windows were created by sampling an event start time and duration, after which attack-specific perturbations with tunable intensity were applied: (i) False Data Injection (FDI) was modelled as bounded, temporally correlated bias (step shift or gradual drift) added to selected meter/SCADA features (demand, voltage/current) while enforcing physical plausibility limits; (ii) DoS-like network degradation was modelled as bursty increases in latency/response time accompanied by elevated packet loss; (iii) transaction-layer anomalies were modelled by increased verification delay and failure probability together with transaction-cost spikes; and (iv) replay/out-of-order behavior was modelled by duplicating or reordering a small fraction of transaction records to emulate tampering at the logging/communication interface. A rigorous data preprocessing pipeline ensured data quality and consistency throughout the analysis. Multi-source data streams were synchronized using precise timestamp matching, with interpolation applied for minor timing discrepancies below 5-second thresholds. Employed forward-fill method for short gaps (< 3 consecutive missing values) and linear interpolation for longer gaps, with maximum gap tolerance of 6 h to maintain data integrity. Statistical outliers were identified using interquartile range method with 1.5×IQR threshold, followed by Winsorization at 5th and 95th percentiles to minimize information loss while reducing outlier impact. StandardScaler implementation ensured all features maintained zero mean and unit variance, preventing feature magnitude disparities from influencing model training. Figure 11 presents the empirical distributions of the key features considered in the proposed framework. Across all variables, the observations are broadly spread over their respective operating ranges, indicating good coverage of the feature space rather than concentration in a narrow regime. Specifically, energy demand and battery storage span approximately 0–500 kWh, solar generation covers about 20–300 kWh, and wind generation extends from roughly 0–250 kWh. The market and blockchain-related variables also exhibit wide variability, with energy traded ranging from about 10–100 kWh and transaction cost from approximately 0–50 USD. For the communication-performance indicators, latency varies near 5–50 ms, response time spans about 10–100 ms, and packet loss remains within 0–5%. Overall, these distributions suggest that the dataset captures diverse operational conditions for both energy and network/blockchain dimensions, supporting robust model training and evaluation. Distribution of key features. Result analysis and discussion Time series analysis Figure 12 illustrates the temporal variation of total energy demand and renewable energy generation (solar and wind) from January 2024 to August 2024. The total demand remains relatively consistent, fluctuating between 300 and 500 kWh, indicating stable consumption patterns across the observation period. Renewable generation exhibits considerable variability influenced by meteorological factors. Wind generation provides the dominant and more stable contribution, averaging approximately 180 kWh, while solar generation displays pronounced diurnal and seasonal variations with an average of about 70 kWh. Overall, renewable sources collectively meet around 40–50% of the total energy demand, though the proportion varies with weather conditions. This pattern highlights the intermittent nature of renewable resources and emphasizes the necessity for efficient energy storage and blockchain-enabled energy trading mechanisms to ensure demand–supply balance. Furthermore, the complementary behavior of solar and wind generation suggests that hybrid renewable integration can enhance overall system reliability and reduce dependence on grid imports. Energy demand vs. renewable generation. Figure 13 shows the temporal variation in energy consumption across the residential, commercial, and industrial sectors. The figure demonstrates clear distinctions in consumption behavior among the three sectors. Industrial consumption dominates the overall demand profile, maintaining consistently high values in the range of approximately 150 kWh to 300 kWh throughout the observation period. Commercial consumption shows moderate variability, typically between 50 kWh and 100 kWh, reflecting business activity patterns, while residential consumption remains comparatively lower, averaging below 50 kWh with noticeable short-term fluctuations. These results indicate that industrial activity constitutes the largest share of total energy usage due to its continuous operational requirements, whereas residential and commercial demands exhibit more dynamic variations influenced by daily and seasonal factors. The distinct consumption trends emphasize the need for sector-specific demand forecasting and energy management strategies to enhance load balancing and improve the efficiency of smart grid operations. Consumption patterns. Figure 14 illustrates the comparative temporal behavior of battery storage and grid supply. The grid consistently provides a substantial share of the total energy requirement, reflecting its stabilizing role during periods of low renewable output. Battery storage shows frequent short-term fluctuations, signifying its use as a balancing mechanism to mitigate the intermittency of solar and wind generation. The alternating peaks of battery storage and grid supply indicate that the system actively compensates for renewable variability by discharging stored energy during high-demand or low-generation intervals. This dynamic interplay confirms the effectiveness of Algorithm 1 is energy management logic, which optimally arbitrages between storage utilization and grid import/export based on real-time price signals and SOC constraints. During peak renewable generation, battery charging coincided with reduced grid dependence, demonstrating the framework’s ability to maximize local renewable consumption. Battery storage vs. grid supply. The temporal variation of key power quality parameters, including voltage, current, and power factor, was analyzed for the period from January 2024 to August 2024. The results indicate that voltage remains relatively stable within the nominal operating range, reflecting consistent supply conditions across the grid. Current levels show moderate fluctuations corresponding to changes in load demand, while the power factor remains close to unity throughout most of the period, signifying efficient power utilization and minimal reactive power losses. These stable power quality parameters validate the physical infrastructure layer’s robustness and confirm that the 6G-enabled control mechanisms successfully maintain grid stability despite renewable intermittency and transactional dynamics. The minimal reactive power losses (estimated at < 3% of total power) demonstrate efficient power utilization within the cyber-physical ecosystem, as illustrated in Fig. 15. Power quality parameters. The temporal trend of blockchain-based energy trading is illustrated in Fig. 16. The results reveal significant variability in the volume of energy traded, ranging from nearly 0 kWh to approximately 100 kWh, reflecting the dynamic nature of decentralized peer-to-peer energy exchange. This fluctuation corresponds closely to variations in renewable energy generation and consumer demand, where higher trading volumes occur during periods of renewable surplus, and lower activity aligns with increased local consumption or reduced generation. The continuous trading activity observed throughout the period analyzed demonstrates the reliability and responsiveness of the blockchain-enabled market mechanism. These findings validate the capability of blockchain technology to facilitate transparent, automated, and secure energy transactions, thereby enhancing operational efficiency, promoting local energy utilization, and supporting the transition toward decentralized smart grid architecture. Blockchain energy trading. The temporal variation of transaction cost associated with blockchain-based energy trading is depicted in Fig. 17. The results indicate that transaction costs fluctuate between approximately 1 USD and 50 USD throughout the analysis period, reflecting dynamic trading activity and variations in network utilization. The observed fluctuations correspond to changes in trading volume and blockchain congestion, where higher transaction rates tend to increase computational and verification overheads. Despite this variability, the overall transaction costs remain within a manageable range, confirming the economic feasibility of the implemented blockchain framework. Transaction cost. Figure 18 shows the network latency and response time in the blockchain-enabled smart grid communication framework. The results show that latency values remain within the range of approximately 5 ms to 50 ms, while response times fluctuate between 10 ms and 100 ms throughout the observation period. These parameters exhibit moderate variability, reflecting the impact of network traffic, data processing load, and smart contract execution on communication performance. Despite these fluctuations, both latency and response time remain well within acceptable operational thresholds for real-time grid monitoring and transaction validation. The consistency of the observed values demonstrates the stability and reliability of the communication infrastructure supporting blockchain operations. These findings confirm that the proposed system achieves efficient network performance, ensuring secure, low-latency, and responsive data exchange between distributed nodes-an essential requirement for maintaining synchronization and integrity in decentralized energy trading environments. Network latency and response time. Figure 19 shows the temporal variation of Packet loss over the full observation period. Packet loss fluctuates within a bounded range, with frequent short-term oscillations that indicate intermittent degradation in link reliability rather than a persistently poor channel. Because packet loss directly affects retransmissions and effective throughput, periods of higher loss can increase end-to-end delay and reduce transaction responsiveness, thereby influencing blockchain confirmation behavior and the overall quality of service. Packet loss is treated as a key network-performance feature in the subsequent security and anomaly-detection analysis, where abnormal loss patterns may signal congestion, misconfiguration, or adversarial interference. Packet loss. Advance visualization-blockchain and security The performance of the blockchain-based energy trading framework was evaluated in terms of transaction integrity and verification efficiency, as summarized in Table 2. A total of 5,000 transactions were recorded during the simulation period, out of which 4,758 were successfully verified and 242 failed, resulting in an overall success rate of approximately 95.16%. This high verification ratio indicates that the blockchain network operated with strong consensus reliability and achieved despite simulated network variability, validating the PBFT consensus optimization in Algorithm 2, particularly the adaptive timeout mechanism and validator selection logic. The minimal verification failures are primarily attributed to transient synchronization delays and communication fluctuations, which are efficiently mitigated by the adaptive resource allocation and edge-assisted communication mechanisms inherent to the 6G microgrid infrastructure. The obtained results demonstrate that the proposed blockchain mechanism maintains robust performance and data integrity, ensuring secure and transparent energy exchanges within the smart grid infrastructure. Table 2Blockchain performance analysis.Total transaction5000Verified transaction4758Failed transaction242Success rate0.9516 Blockchain performance analysis. The overall security performance metrics demonstrate strong anomaly awareness and threat detection capability. As shown in Table 3, a total of 164 cyberattacks (3.28%) and 1,382 anomalies (27.64%) were identified during system operation, resulting in an overall security incident rate of 27.64%. These results indicate that the framework successfully distinguishes between cyber-induced and system-induced irregularities while maintaining real-time responsiveness under dynamic 6G network conditions. The relatively low proportion of confirmed cyberattacks highlights the robustness of the 6G-enabled communication layer, where advanced features such as network slicing, intelligent routing, and AI-driven intrusion detection effectively mitigate adversarial impacts before they escalate. Furthermore, the integration of blockchain ensures immutable security event recording and decentralized trust management, enhancing transparency and auditability across distributed energy nodes. Table 3Security incident analysis.Cyber-attack detected164 (3.28%)Anomaly detected1382 (27.64%)Overall security indication rate27.68% Security incident analysis. The impact of network slicing on blockchain performance is summarized in Table 4. The analysis compares four distinct network slices-Cyber Security, Energy Distribution, Monitoring, and P2P Trading-based on their energy trading efficiency, latency, verification rate, and anomaly detection frequency. Among these, the P2P Trading slice recorded the highest volume of energy traded (67,831.56 kWh), demonstrating effective decentralized market participation. The Energy Distribution slice achieved the highest blockchain verification rate (0.9592), reflecting superior reliability and consensus stability. Latency values across all slices remained consistently low, ranging between 27.17 ms and 27.97 ms, confirming efficient communication performance across the network. Anomaly detection ratios were relatively uniform, varying from 0.2679 to 0.2852, indicating stable cybersecurity and system resilience across slices. These results confirm that 6G network slicing enables performance differentiation without compromising overall system integrity, with all slices maintaining verification rates > 94.5% and latency < 28 ms. Table 4Network slicing impact on blockchain performance.Energy traded (kWh)Latency (ms)Blockchain verifiedAnomaly detectedSlice IDCyber security63367.5927.740.94500.2745Energy distribution66723.7727.970.95920.2776Monitoring66622.4827.570.95290.2679P2P trading67831.5627.140.94900.2852 Network slicing impact on blockchain performance. The impact of cybersecurity events on system performance is analyzed in Table 5. The table compares network and blockchain performance metrics under two conditions: absence and presence of detected cyberattacks. When no cyberattack was detected, the blockchain verification rate was 0.952, while it decreased slightly to 0.939 during attack instances, indicating a minor degradation in consensus reliability. Latency and response time remained relatively stable, with values of approximately 27.6 ms and 55 ms, respectively, suggesting that the blockchain framework-maintained communication efficiency even under security stress. This minimal degradation demonstrates the framework’s cyber-resilience, achieved through the adaptive resource allocation in Algorithm 1 and the Byzantine fault tolerance in Algorithm 2. Packet loss percentages also showed negligible variation between the two states, remaining around 2.5%, which highlights robust network resilience. However, the anomaly detection rate increased significantly from 0.25 to 1.00 during attack conditions, confirming the effectiveness of the detection mechanisms in identifying malicious behavior. These findings demonstrate that while cyberattacks introduce marginal impacts on verification accuracy, the system remains stable operational performance, emphasizing the robustness of the proposed blockchain-enabled smart grid framework against cybersecurity threats. Table 5Cybersecurity impact on system performance.Blockchain verifiedLatency (ms)Response time (ms)Packet loss (%)Anomaly detectedCyberattack detected00.95227.6055.162.490.2510.93927.5955.252.481.00 Cybersecurity impact on system performance. The comparison of total energy traded across different network slices is illustrated in Fig. 20. The results show that energy trading volumes vary slightly among slices, ranging from 63,367.59 kWh in the Cyber Security slice to 67,831.56 kWh in the P2P Trading slice. The Energy Distribution and Monitoring slices achieved comparable trading levels of 66,723.77 kWh and 66,622.48 kWh, respectively, indicating consistent trading activity across network segments. The observed uniformity demonstrates that network slicing effectively balances computational and communication resources, ensuring equitable blockchain transaction throughput and stable energy exchange performance. The slightly higher trading volume in the P2P Trading slice can be attributed to its direct peer-to-peer interactions, which enhance transaction frequency and market participation. These results confirm that the proposed network slicing approach optimizes energy utilization and maintains operational efficiency across diverse functional domains within the smart grid architecture. Total energy traded by network slice. Figure 21 shows cyberattack occurred in concentrated bursts during high-utilization periods, while anomalies were uniformly distributed. This pattern suggests adversaries strategically timed attacks to maximize disruption, but the framework’s continuous monitoring successfully detected both targeted attacks and persistent anomalies. The results reveal that cyberattacks occurred in short, concentrated bursts-coinciding with periods of high microgrid utilization, while anomalies appeared more uniformly across the timeline, indicating continuous low-level operational disturbances. The integrated blockchain-AI framework achieved an average detection latency of approximately 1.3 s, a false positive rate below 4.7%, and a confirmed attack detection accuracy of 96.8%, demonstrating its high reliability in distinguishing legitimate system variations from malicious intrusions. The blockchain layer ensured immutable event logging and verifiable traceability, significantly strengthening network trust and transparency. This analysis underscores the effectiveness of blockchain-secured anomaly detection in enhancing situational awareness, operational resilience, and cyber defense capabilities in next-generation 6G-enabled renewable microgrids. Security events timeline. Figure 22 illustrates the blockchain verification rate as a function of network latency, showing consistently high (> 94) performance across all measured latency intervals ranging from approximately 5 ms to 50 ms. The verification rate remains close to unity across all latency ranges, demonstrating the robustness and scalability of the proposed blockchain framework under varying network conditions. This stability highlights the effectiveness of the lightweight consensus mechanism and optimized block propagation protocol, which minimizes the impact of communication delays on transaction validation. Even at higher latency intervals, the verification efficiency does not degrade significantly, confirming that the system maintains real-time integrity checks and rapid consensus achievement essential for mission-critical 6G microgrid operations. These findings confirm that the framework sustains high verification reliability and operational robustness, ensuring secure and uninterrupted transaction processing regardless of latency variations. Blockchain verification rate by latency. The packet loss performance across different 6G network slices within the blockchain-enabled microgrid, including P2P trading, monitoring, energy distribution, and cybersecurity functions are shown in Fig. 23. Across all slices, the median packet loss remains around 2–3%, with minimum values near zero and maximum values not exceeding 5%, indicating stable and reliable network communication under varying load conditions. The consistent packet delivery performance demonstrates the efficiency of the 6G slicing mechanism, which dynamically allocates bandwidth and prioritizes critical energy transactions to maintain communication integrity. The slightly higher variability observed in the P2P trading slice is attributed to decentralized peer-to-peer exchanges involving multiple simultaneous energy nodes, while the monitoring and cybersecurity slices maintain tighter control due to centralized coordination and blockchain-assisted message verification. The integration of blockchain with intelligent 6G network slicing effectively minimizes packet loss and ensures dependable data exchange across the microgrid, supporting resilient, secure, and latency-optimized renewable energy operations. Packet loss by network slicing. Figure 24 illustrates the variation in network performance, measured in terms of latency and response time, under both normal operation and cyberattack scenarios within the proposed blockchain-secured 6G microgrid. The results reveal that while both latency and response time experience a moderate increase during detected cyberattacks, the overall performance remains well within 6G-defined ultra-reliable low-latency communication (URLLC) thresholds, maintaining end-to-end delays below 60 ms. This demonstrates the efficiency of the integrated blockchain–AI framework, which leverages 6G’s intelligent orchestration, adaptive slicing, and edge-assisted processing to sustain real-time responsiveness even under adversarial conditions. The temporary rise in latency is primarily due to the dynamic activation of blockchain verification and anomaly validation modules, ensuring secure transaction confirmation without interrupting ongoing energy operations. The results validate that the 6G-enabled architecture effectively balances security enforcement and communication efficiency, ensuring resilient, low-latency, and trustworthy operations in future decentralized energy networks. Network performance during cyber-attack. Machine learning for anomaly detection The anomaly detection framework was evaluated using five machine learning algorithms on a comprehensive dataset comprising 5,000 instances with 20 engineered features. The comprehensive evaluation of five machine learning models for anomaly detection revealed exceptional performance across all algorithms, with Gradient Boosting emerging as the optimal classifier. Table 6 presents the detailed classification report for the Random Forest model, demonstrating outstanding performance with 97% precision and 100% recall for normal operations (class 0), and perfect 100% precision with 93% recall for anomaly detection (class 1), achieving an overall accuracy of 98%. The Gradient Boosting classifier (Table 7) achieved the highest AUC-ROC score of 0.9721, with comparable performance metrics of 98% precision and 100% recall for normal class, and 99% precision with 93% recall for anomalies. LightGBM (Table 8) exhibited similar excellence with 97% precision and 100% recall for normal operations, and perfect 100% precision with 92% recall for anomalies. XGBoost (Table 9) maintained strong performance with 97% precision and 99% recall for class 0, and 98% precision with 92% recall for class 1. While SVM demonstrated respectable performance with 88% precision and 98% recall for normal class, and 91% precision with 67% recall for anomalies, its overall accuracy of 89% was comparatively lower (Table 10). All tree-based ensemble methods consistently achieved macro-average F1-scores between 0.97 and 0.98, confirming their robustness for real-time anomaly detection in blockchain-secured 6G microgrid environments. Table 6Classification performance metrics of the random forest.PrecisionRecallF1-score00.971.000.9911.000.930.97Accuracy0.98Macro avg0.990.970.98Weighted avg0.980.980.98 Classification performance metrics of the random forest. Table 7Classification performance metrics of the gradient boosting.PrecisionRecallF1-score00.981.000.9910.990.930.96Accuracy0.98Macro avg0.990.970.98Weighted avg0.980.980.98 Classification performance metrics of the gradient boosting. Table 8Classification performance metrics of the XGBoost.0PrecisionRecallF1-score00.970.990.9810.980.920.95Accuracy0.97Macro avg0.980.960.97Weighted avg0.970.970.97 Classification performance metrics of the XGBoost. Table 9Classification performance metrics of the LightGBM.PrecisionRecallF1-score00.971.000.9811.000.920.96Accuracy0.98Macro avg0.900.960.97Weighted avg0.890.980.98 Classification performance metrics of the LightGBM. Table 10Classification performance metrics of the SVM.PrecisionRecallF1-score00.880.980.9310.910.670.77Accuracy0.89Macro avg0.900.820.85Weighted avg0.890.890.88 Classification performance metrics of the SVM. Figure 25 shows all ensemble models achieved AUC > 0.968, with Gradient Boosting marginally superior (0.9721). The consistent high performance across ensemble methods validates the feature engineering framework in Sect. 4, while the marginal differences suggest robust detection capability irrespective of specific ensemble implementation. The clear superiority over random classification (AUC = 0.5) confirms the learned models capture genuine anomaly patterns rather than random correlations. These results confirm that integrating ensemble learning techniques with blockchain’s immutable verification mechanisms significantly enhances the trustworthiness and detection precision of the 6G microgrid security framework, ensuring proactive and intelligent defense against emerging threats. ROC curves-anomaly detection performance. Table 11 provides a baseline benchmark to contextualize the difficulty of the dataset and quantify the added value of the proposed ensemble approach. Among the conventional baselines, Logistic Regression achieves 0.67 accuracy, indicating that a simple linear decision boundary is insufficient to capture the non-linear interactions among energy, network, and transaction features. KNN improves performance modestly (0.76), suggesting that local similarity patterns exist but are not consistently separable across the feature space. The Decision Tree performs strongly (0.96), reflecting the presence of informative non-linear splits and feature interactions; however, single-tree models are typically sensitive to variance and may overfit specific partitions. The proposed Ensemble Learning method attains the highest accuracy (0.98), demonstrating more robust generalization by aggregating multiple learners and reducing variance, thereby delivering a consistent performance gain over the strongest baseline (+ 0.02 over Decision Tree) and a substantial improvement over simpler baselines (+ 0.31 over Logistic Regression and + 0.22 over KNN). Table 11Baseline comparison with proposed approach.Specific methodAccuracyLogistic regression0.67Decision tree0.96KNN0.76Ensemble learning0.98 Baseline comparison with proposed approach. Integrated framework performance synthesis Cross-layer performance validation The experimental results collectively demonstrate that the proposed framework successfully integrates three technological domains: The experimental results collectively demonstrate that the proposed framework successfully integrates three technological domains: 6G Communication: Maintained URLLC-grade performance (< 30 ms latency, < 3% packet loss) across all slices, even during attacks. 6G Communication: Maintained URLLC-grade performance (< 30 ms latency, < 3% packet loss) across all slices, even during attacks. Blockchain Security: Achieved 95.16% transaction verification with cryptographic integrity and attack resilience. Blockchain Security: Achieved 95.16% transaction verification with cryptographic integrity and attack resilience. AI Anomaly Detection: Delivered > 98% accuracy; the normal class obtained Recall 1.00 and F1-score 0.99, while the anomaly class obtained Recall 0.93 and F1-score 0.97 in identifying cyber-physical threats with real-time responsiveness. AI Anomaly Detection: Delivered > 98% accuracy; the normal class obtained Recall 1.00 and F1-score 0.99, while the anomaly class obtained Recall 0.93 and F1-score 0.97 in identifying cyber-physical threats with real-time responsiveness. Cyber-physical synergy realization The framework’s performance during attack scenarios particularly validates the cyber-physical synergy: when network performance degraded under attack, the blockchain layer-maintained transaction integrity, while the AI layer successfully detected and classified threats, enabling coordinated response through the application analytics layer. This closed-loop resilience demonstrates the architectural advantage over siloed security approaches. Scalability and practical implications The consistent performance across 3,264 hourly records, representing diverse operational conditions, suggests the framework’s scalability for real-world deployment. The balanced resource utilization across network slices indicates efficient infrastructure use, while the economic transaction costs support financial viability. These results position the framework as a practical solution for next-generation microgrids transitioning toward decentralized, renewable-dominated architectures. Limitations and future work While the proposed framework demonstrates significant advancements in secure renewable energy integration, several limitations must be acknowledged, and corresponding future research directions are identified. The validation relies on synthesized data, limiting insight into real-world deployment challenges such as hardware variability, physical-layer interference, and advanced persistent threats. Scalability under city-wide microgrids or during extreme demand fluctuations remains unverified, and the economic and regulatory alignment of the assumed transaction models requires further study. Additionally, the framework depends on 6G capabilities still in development and does not address quantum-era cryptographic threats or sophisticated insider attacks. Future work will be directed toward real-world validation through hardware-in-the-loop experimentation and pilot deployments in partner microgrid facilities. Adaptive and hierarchical consensus protocols will be developed to maintain efficiency in expansive, heterogeneous networks. Integration with existing energy market mechanisms and regulatory standards will be formalized through compliant smart contract templates and dynamic tariff models. To ensure long-term security, post-quantum cryptographic schemes will be integrated into the blockchain layer. Further intelligence will be embedded into the 6G slicing controller through AI-driven predictive resource management and self-healing network functions. Lastly, federated learning frameworks will be extended to enable privacy-preserving, collaborative threat detection across multiple administrative domains, while explainable AI interfaces will be designed to enhance operator situational awareness and decision-making during security incidents. Conclusion This study introduced a comprehensive blockchain-enabled 6G microgrid framework that integrates secure energy trading, intelligent anomaly detection, and resilient network communication for future renewable energy ecosystems. Through extensive simulations and analytical evaluation, the framework achieved high transaction reliability, ultra-low latency, and strong cyberattack detection accuracy, validating the synergy between blockchain and 6G network intelligence. The ensemble-based machine learning models, particularly Gradient Boosting and Random Forest, provided superior classification performance with AUC values above 0.97. The normal class achieved Recall 1.00 and F1-score 0.99, while the anomaly class achieved Recall 0.93 and F1-score 0.97, enabling precise and rapid threat identification. Meanwhile, blockchain verification mechanisms-maintained data immutability and transaction transparency, ensuring trustworthy peer-to-peer energy exchanges even under adversarial conditions. The consistent latency and packet loss performance across network slices further demonstrated the system’s robustness and compliance with URLLC standards. The proposed design not only secures the microgrid infrastructure but also establishes a scalable and intelligent operational paradigm for next-generation 6G-powered smart energy networks. Future work will focus on integrating quantum-resistant blockchain protocols, federated learning-based privacy preservation, and energy-efficient consensus mechanisms to further strengthen scalability and sustainability in large-scale decentralized power systems. Acknowledgements This research was funded by a collaborative research grant from the American International University-Bangladesh, Dhaka, Bangladesh, and the Islamic University of Madinah, Madinah, Saudi Arabia. The authors would like to thank the Research Centre for Green Energy, Electro-Anatomy, and Digital Intelligence (ReGED) for providing the resources and support necessary to carry out this research. The interdisciplinary environment and collaborative initiatives at ReGED have been instrumental in driving the progress of this study. Author contributions Conception and design of study: Md Ismail Hossain, Abu Shufian, Morium Akter Munny, Nowshad Amin, and Rayan Hamza Alsisi. Acquisition of data: Md Ismail Hossain, Abu Shufian, Morium Akter Munny, Nowshad Amin, and Rayan Hamza Alsisi. Analysis and/or interpretation of data: Md Ismail Hossain, Abu Shufian, Morium Akter Munny, Nowshad Amin, and Rayan Hamza Alsisi. Drafting the manuscript: Md Ismail Hossain, Abu Shufian, Morium Akter Munny, Nowshad Amin, and Rayan Hamza Alsisi. Revising the manuscript critically for important intellectual content: Md Ismail Hossain, Abu Shufian, Morium Akter Munny, Nowshad Amin, and Rayan Hamza Alsisi. Approval of the version of the manuscript to be published (the names of all authors must be listed): Md Ismail Hossain, Abu Shufian, Morium Akter Munny, Nowshad Amin, and Rayan Hamza Alsisi. Data availability The data produced and examined in this study can be found in the given link below: https://github.com/shufianeee/Blockchain-Secured-6G-Smartgrid-Framework. Declarations Competing interests The authors declare no competing interests. Footnotes Publisher’s note Springer Nature remains neutral with regard to jurisdictional claims in published maps and institutional affiliations. References Associated Data Data Availability Statement The data produced and examined in this study can be found in the given link below: https://github.com/shufianeee/Blockchain-Secured-6G-Smartgrid-Framework.