Hybrid electricity management system for residential power block applications Authors: Rabia Tehseen, Uzma Omer, Abdul Razzaq Hamraz, Anam Mustaqeem, Nosheen Sabahat, Nosheen Qamar Published: 2026 ABSTRACT AbstractDeveloping countries have been facing electricity crisis for decades, mainly due to insufficient electricity generating capacity as compared to its demand and extensive growth in population. This research outlines Electric_Fed, a decentralized electricity management model that incorporates blockchain and federated learning (FL). This model allows multiple clients, defined as houses or blocks, to privately and efficiently collaborate on electricity consumption and production forecasting without needing to exchange raw, shared data. The model achieves collaboration on a global model. Automated electricity trading is made possible through the use of Blockchain and smart contracts, which allows clients to securely and transparently participate in real-time peer-to-peer energy exchange. In this article, electricity production model using cross device FL technique and blockchain has been presented. In the proposed model, FL has been used to provide a secured client server model to facilitate clients having surplus electricity or facing electricity shortfall within the network. Central Server issues alert to the clients having surplus electricity to start Smart contract with the client facing electricity shortfall implementing blockchain. Blockchain ensures safe transaction and reliable transfer of payments to the client selling electricity. Electricity production and consumption dataset from Jan 2024 to Dec 2024 has been processed. Experimental validation proved that the proposed model is capable enough to fulfill 89.2% electricity need of the selected region. The experimental setup results (from June 2024) validate the model’s effectiveness. Client A reached a surplus of + 909 kWh, Client B + 12 kWh, Client C + 230 kWh and Client D fell short by − 693 kWh. The system automatically recognized surpluses and deficits, trading energy to balance the needs of Clients A and C, which allowed them to reach full self-sufficiency. This model lowered national grid dependency and reduced overall electricity costs. As compared to other models presented for electricity supply, our proposed model is not only more effective in fulfilling the regional electricity demands but it also suggested a secured mechanism to compensate the electricity selling client participating in electricity trade. This demonstrates, in and of itself, the effectiveness of the model proposed while providing intelligent decentralized energy management in a system that is, as a whole, efficient, scalable, and privacy preserving.Keywords: Client, Electric power, Machine learning, Server, Smart contractSubject terms: Energy science and technology, Physics Introduction The economies of numerous developing nations are being impacted, leading to instability in their national security environments, due to a severe energy crisis across various challenging situations1. Within these developing countries, a significant number of factories have been compelled to shut down due to the high cost of non-renewable energy in hub of industries2. The ongoing usage and escalating need for energy underscore the fact that energy has evolved into one of the most pressing global issues3. This has led to difficulties for power generation, transmission, and distribution enterprises as the escalating cost of power generation, driven by the soaring prices of fossil fuels and increased line losses, has resulted in higher tariffs. Consequently, there is a compelling need to address the energy crisis through the integration of novel electricity production units. As rate of inflation is surging in developing nations, it amplifies urgency of adopting such energy sources that could be renewed4. The electricity shortfall challenge currently confronted by developing nations could be alleviated through the utilization of renewable energy sources. Planners and policymakers are struggling hard to discover alternative energy resources as natural resources are depleting and the demand for electricity is increasing with extravagant growth in population5. To meet consumer demand, developing nations should consider the implementation of solar photovoltaic cells that would boost the country’s proportion of renewable energy6. Solar energy technologies (SETs) offer evident environmental advantages, facilitating sustainable human activities and the reduction of reliance on non-renewable resources7. Moreover, electricity theft can also be controlled to some extent by installation of local photovoltaic panels8. Classical machine learning (ML) necessitates training of data in centralized manner9. Despite its strong convergence, this training method introduces vulnerabilities as participants send data to central server. In response, Federated Learning (FL) technique has been adopted due to its emphasis on distributed training of data, enabling collaborative local model training on individual data without revealing private information to the central cloud server9. The concept of Federated Learning, encompassing a distributed machine learning approach10, enables training on a substantial dataset of decentralized data residing on devices like mobile phones. To handle the problems related to data privacy, security, and ownership, FL employs a broader approach by “taking the code to the data” rather than the reverse, as shown in Fig. 1. FL enables clients to keep their raw data on their devices and utilizes localized ML based model training process to reduce the burden of data transmission. The resulting models, which are acquired and shared, are subsequently sent to a central server for temporary storage, consolidation, global model training, and distribution to all clients11. Figure 1 presents an overview of energy production from various sources. Production capacities11. In spite of a centralized forecasting model and a private database might seem easier in managing residential power, the model presupposes that all the prosumers are eager to regularly exchange fine-grained information on the electricity generation and use with one reliable operator. In realistic residential power blocks, the assumption is frequently impractical since realistic load profiles can expose delicate behavioral habits, including occupancy charts and appliance use, routine routines of day-to-day actions. Due to this reason, Federated Learning (FL) is implemented in this work to allow collaborative forecasting without submitting unprocessed household data to a central repository. Nonetheless, FL is not sufficient in an energy peer-to-peer environment with multiple prosumers that engage in decentralized coordination and trading. Blockchain in these situations also offers an extra layer of trust and verification by assuring tamper-proof logging, open and transparent records of transactions, and secure smart-contract execution without using a single intermediary. Thus, FL and Blockchain are not integrated with one another due to being new technologies, instead, they are applied to two different needs of the suggested Electric_Fed framework privacy-preserving predicting and reliable decentralized energy trade. The authors recognize that the joint FL-Blockchain architecture adds more communication, computation, and latency overhead along with energy overhead in comparison to a traditional centralized solution. Specifically, federated round reuse can add to training delay, and Blockchain operation can introduce overhead in processing transactions. Due to this reason, the offered Electric_Fed framework is not supposed to be universally superior to centralized forecasting. Rather, it is aimed at privacy-aware and multi-stakeholder resident energy environments in which the advantages of local data storage, auditability, and decentralized trust supersede incremental system cost. Moreover, the given architecture does not compel severely resource-constrained IoT meters to perform heavy computations on their own; local training and coordination may be done by utilizing edge-capable home gateways or neighborhood-level controllers, whereas only lightweight metadata (model hashes, update proofs, transaction references) are stored on-chain. Such design minimizes storage load and does not keep all the computational power of end IoT devices. In the current research, “Power Block” describes the hybrid intelligent energy management unit that employs FL and Blockchain technologies to oversee, forecast, and manage electricity distribution among clients (prosumers) in our network. As the system’s primary computational and decision-making unit, it enables privacy-preserving learning, local optimization, and decentralized energy trading. Each Power Block functions as an independent unit comprising of a local data processing unit that documents electricity generation and consumption in real time, and a Blockchain interface that conducts electricity trading among clients through encrypted, automated smart contracts without a centralized intermediary. In essence, the Power Block is a hybrid control entity that bridges traditional energy management systems with modern distributed intelligence. It combines computational analytics, energy forecasting, and secure peer-to-peer transactions within a single integrated framework. The term “Power Block” symbolizes the fusion of physical energy infrastructure and digital intelligence, forming the foundation of the Electric_Fed-based decentralized energy ecosystem proposed in this research. Table 1 presents the motivation for conducting this research. The integration of blockchain technology holds the potential to resolve numerous challenges faced by the electric energy network12,13. Moreover, blockchain introduces distinctive possibilities for the distribution of renewable energy and the verification of authenticity14,15. The emergence of peer-to-peer energy trading has elevated energy management mechanisms, enabling multi-level market participants to engage in rapid energy trading with the involvement of new distributed clients and innovative technologies. Table 1Motivation for using federated learning and blockchain for electricity production and distribution.FeatureFederated learningBlockchainResearch gapEnhanced data privacy and securityEnables collaborative model training across multiple decentralized energy producers without sharing sensitive data, ensuring privacy and compliance with regulations.Provides a secure, immutable ledger for transactions and data, protecting against tampering and cyberattacks.Effective integration of privacy-preserving techniques with federated learning and blockchain to ensure comprehensive security.Decentralized energy tradingPredicts energy supply and demand across regions, facilitating dynamic pricing and efficient energy trading.Enables peer-to-peer energy trading through smart contracts, allowing producers to sell excess electricity directly to consumers or adjacent regions without intermediaries.Ensuring scalability and interoperability of blockchain systems for widespread adoption in energy markets.Scalability and flexibilityScales seamlessly with the addition of new data sources and participants, accommodating growing energy production and consumption needs.Supports a wide range of transactions and can integrate with existing energy infrastructure, providing flexibility in implementation.Addressing latency and throughput issues in blockchain to handle high transaction volumes.Cost savingsReduces costs associated with centralized data processing and storage by leveraging local data processing capabilities.Minimizes transaction fees and administrative costs by automating processes and eliminating intermediaries.Assessing long-term cost benefits and ROI for implementing federated learning and blockchain solutions. Motivation for using federated learning and blockchain for electricity production and distribution. Energy management system facilitates the decentralized synergy among multiple clients (prosumers). Proposed system employs Blockchain technology to ensure secure, transparent, and tamper-proof transactions while FL enables dispersed predictive modeling to ascertain energy surplus and demand across varying nodes. In the proposed model, unlike traditional systems, energy coordination is decentralized and clients can engage in energy exchanges with one another in a way that keeps personal information private. The main input for energy generation remains renewable sources, specifically solar photovoltaic (PV) panels. However, the true innovation is the seamless and secure energy trading, coordination, and management made possible through the combined use of Federated Learning (FL) and Blockchain technology. The Power Block is described as a hybrid computational–transactional functional unit that implements Federated Learning for decentralized energy forecasting and blockchains for automated secure trading between prosumers. The block is the main operational unit of the proposed system and is in charge of the energy trading, forecasting, and flow management system. Therefore, this innovative nature of Electric_Fed does not consist of just the combination of FL and Blockchain, but the functionally complementary use of both towards decentralized prediction, secure coordination, and peer-to-peer management of residential power blocks of renewable sources. Even though Blockchain enhances the transparency and integrity of the transactions, it does not prevent adversarial attacks on the Federated Learning layer completely. In ElectricFed, malicious houses/power blocks can endeavor to poison models or label flip by broadcasting corrupted local updates to manipulate the global forecasting model to gain unfair trading advantage. Thus, dishonest participants in the learning layer should be taken into consideration in a threat model. The effect of abnormal or malicious updates can be minimized by introducing strong aggregation techniques like Krum or Bulyan, which enhance reliability. By doing so, Blockchain will ensure the security of the transaction layer, and the AI layer is insured by powerful FL mechanisms. This article has been organized in following sections: “Introduction” section introduces electricity crisis in developing countries. “Literature review” section presents literature review. Proposed methodology is presented in “Materials and methods” section. Data analysis and experiment has been stated in “Experimental validation” section. Results and discussion have been presented in “Results and discussion” section. Conclusion of the research and future directions have been provided in “Conclusion” section. Literature review Over time different solutions to electricity shortfall challenge addressing scarcity of fossil-fuel based energy sources and their environmental impact, have been sought. Renewable sources are becoming increasingly popular due to their accessibility and cost-effectiveness. Energy trading and sharing, particularly using blockchain technology, have gained attention among researchers16,17. Existing models have emphasized the use of blockchain to ensure secure and encrypted trading and sharing between producers and consumers18–20. Blockchain’s scalability, security, and decentralization are important considerations. In the context of blockchain technology, Kumar and Chopra21, Zhang et al.22 assessed these factors and proposed strategies to enhance capacity while maintaining security and decentralization. While previous models have facilitated secure trading and sharing of energy, they often overlook the calculation of future consumer demand. Consumer participation is crucial to embrace renewable energy and the shift from fossil-fuels23–26. Blockchain-based peer-to-peer power trading systems have been introduced, allowing users to contribute renewable energy to the grid and enabling system functionality even when disconnected from the national grid27–29. Mohammed et al.30 presented various frameworks for trading energy among peers via blockchain have been proposed, including dual auction Vickrey–Clark–Groves (VCG) procedures to promote honest bidding and social welfare. However, these models often lack accurate estimation of future Client demand31. These models do not incorporate techniques or algorithms for predicting future consumption and efficient energy management. Table 2 presents advantages and disadvantages of using photovoltaic panels stated in literature. Table 2Advantages & disadvantages of photovoltaic panels.Ref.AdvantagesDisadvantagesRef.5,7,32Reliable systemHigh initial costRef.12–16,24,33,34Low cost of operation and maintenanceLarge area of installationRef.18,21,35Free energy sourceHighly dependent upon technologyRef.1,7,9,36–38High availabilitySolar irradiationRef.13,25,39,40NoiselessLimited availability in market Advantages & disadvantages of photovoltaic panels. Blockchain-based FL designs have been developed to address privacy concerns36. The study aims to explore how blockchain technology can complement FL, yet without specifying specific areas for further development. In the domain of cyber-physical systems, blockchain-based decentralized solutions offer potential solutions for scalability and security concerns22. Despite their advantages, these models often lack capabilities for estimating future generation and consumption. The proposed Electric_Fed model is inspired by new developments in multi-agent systems and blockchain technology in energy trading systems41–43. The combination of cloud energy storage with demand response and net load management techniques increases the scalability and efficiency of decentralized energy systems further44,45. In addition, previous research on intelligent energy management and optimization in microgrids serves as a basis for using federated learning and automation of smart contracts in this work46–48. Table 3 presents a comparison of proposed work with state-of-the-art approaches presented in the literature. Table 3Comparison with existing work.AspectExisting approachesProposed Electric_Fed modelArchitectureMost current energy management systems utilize centralized cloud systems for aggregating and optimizing data, as highlighted in references41,44,45,49–51The model described here employs a decentralized Federated Learning (FL) framework where local clients independently train models, share only model parameters, and observe advanced levels of efficiency and scalability.Data privacyCentralized systems forward unprocessed user data to cloud systems which aggravates privacy issues and data leakage risks42,45,52,53Electric_Fed observes data privacy by holding sensitive energy data locally while only exchanging encrypted updatesDecision automationIn classic systems, energy trading systems are supervised manually and lack decentralization for transactional validation43,44,54,55Electric_Fed implements transparent and trustless trading of electricity between clients with a surplus and those with a deficit using smart contracts on BlockchainScalabilityWhen growing large networks of consumers, cloud systems and multi-agent systems struggle with computational efficiency41,42,56–58FL’s distributed learning mechanism allows the processing of a vast number of clients and participants while maintaining efficiency and scalability, all without overloading a single nodeSecurity and integrityExisting systems depend on centralized databases that are susceptible to manipulation, hacking, or single-point failures43,48,59Electric_Fed utilizes Blockchain’s core functionalities by integrating immutability, decentralized authentication, and secure auditing to eliminate single points of failureOptimization intelligencePrevious systems used unchanging, rule-based optimization relying on static historical data-sets of demand-response41,42,44Electric_Fed is able to continuously learn adaptable models in real-time as there is decentralized energy data to adjust to real-time energy production and consumptionEconomic impactUnder current systems, users are primarily passive consumers and have limited means to gain economically from energy surplus41,46,60Electric_Fed allows users to become energy prosumers by facilitating the trading of surplus energy directly and diminishing the level of energy reliance on the national gridEnergy trading processThe majority of systems do not facilitate real-time, direct peer-to-peer (P2P) energy trading and engage in centralized control43,48Electric_Fed employs blockchain technology to offer real-time electricity trading and smart contracts perform automatic P2P trading when supply and demand thresholds are crossed Comparison with existing work. Research has been conducted to examine blockchain-based energy trading and machine learning-based electricity forecasting, individually. Nevertheless, the literature is sparse about using privacy-preserving federated learning in conjunction with blockchain-based peer-to-peer electricity trading of residential energy networks. This paper fills this gap by suggesting a hybrid electricity management system which integrates federated learning of decentralized forecasting with blockchain-based smart contracts of the secure energy transactions. Proposed study introduces a novel approach that leverages solar energy for electricity production through Photovoltaic panels (PV) and utilizes FL and blockchain technology for secure and efficient energy management. Unlike previous works, our model integrates these technologies to accurately predict future energy generation and demand while ensuring privacy and secure transactions. The proposed model contributes to resolving the energy crisis and shifting toward renewable energy sources. Recent studies have examined some of the intelligent technologies to enhance management of energy and smart grid functions. Research thereof, like61, indicates the role of advanced information and communication technologies at the realization of effective demand-side management in current smart grids. Similarly, smart forecasting methods of photovoltaic systems have been explored in order to enhance integration of renewable energy and market sustainability62. The combination of blockchain, IoT, and machine learning technologies has also been used to develop security and reliability of smart micro-grids63. Additionally, it has been suggested that decentralized electrical trading systems and profit optimization algorithms on electric vehicles can be implemented and based on blockchain and machine learning systems64. Moreover, the strategies of charging and discharging of the electric vehicles have been devised as flexible to ensure grid stability and efficiency of the energy utilisation65. Even with these developments, the majority of current solutions are based on centralized data processing or a particular application case, e.g. EV management or photovoltaic predictions. However, the proposed Federated Learning-based Hybrid Electricity Management System will allow distributed learning on residential blocks of power and maintain data privacy and lessen centralized computational resources. Such solution can be used in residential settings to offer intelligent electricity management with privacy-preserving and scalable approach. More in-depth research has been conducted into the subject of advanced optimization and energy management measures to enhance the efficiency and reliability of the latest smart grid systems. A bi-level multi-energy scheduling framework of virtual power plants in a competitive electricity market was proposed by66, which showed how coordinated scheduling can improve operational flexibility and economic performance. In a similar paper, Samadi Gharehveran67, provided an overview of energy management techniques in multi-microgrid systems with particular focus on the complications brought about by uncertainty in distributed generation resources including the solar and wind power. In addition, Karimi and Heydarian-Forushani68 proposed a multi-objective bi-level optimization model to examine the action of distribution system operators that are involved in the wholesale and local transactive energy markets. The problem of reliable monitoring of distributed power systems has also been studied by Esmaili and Haddadi69 who presented an optimal placement strategy of the measurement devices over the distribution networks to enhance the accuracy of the state estimation without conflicting the reliability issues. Moreover, Pirmohammad Talatape et al.70 examined the operations of distributed energy sources aimed at, at the same time, minimizing the pollution of the environment and enhancing economic performance, which explained the significant role of smart coordination between the units of renewable generation. All these works indicate the increasing popularity of advanced optimization, monitoring, and management methods of distributed energy systems, which is why intelligent and decentralized systems can be designed, e.g., the Federated Learning and Blockchain-based electricity management system, offered as the solution to the problem of residential power block applications. Materials and methods Energy is an essential component of economic activities for a country. In this research, we proposed a FL-based electricity management system to address electricity shortfall problem in developing countries. Main objective of this research is to develop a model that urges on the installation of photovoltaic panels on rooftop of houses located in the selected region for production of electricity locally. The proposed system is composed of two modules namely electricity management system (EMT) and electricity selling system (ESS). A. Electricity management system (EMS) Electricity management system (EMS) Each participating house can consume self-produced electricity to fulfil its needs and sell surplus electricity to the local grid station for earning money. Local grid station receives electricity declared as surplus from each house and digitalizer system installed at local grid will maintains a database to record daily electricity sold and daily electricity demanded by the particular house to calculate net benefit at the end of every month. Digitalizer will also determine the amount of actual surplus electricity for this local station after fulfilling all electricity demands per month. Digitalizer system will alert the central server informing about surplus electricity available for sale to other Clients. Central server in the proposed model is responsible to send an initial model to all digitalizer systems installed at local grid station of all Clients. Digitalizer system will receive initial model from server. Every digitalizer system is responsible for triggering the central server about surplus electricity or electricity shortfall within the service area by training multiple parameters of initial data model received from server. Local data model updates are transmitted to central server from each digitalizer system hence completing cross device FL circle. Central server receives model updates from all grid stations located in the selected region indicating surplus electricity or electricity shortfall. Central server sends an alert to the local stations that have declared surplus energy to sell electricity to the grid station who has intimated about electricity shortfall. Central server will also trigger the Client facing electricity shortfall to get required electricity from the adjacent Client willing to supply its surplus electricity as presented in Fig. 2. Proposed model. Figure drawn using Vega-lite editor Link: https://vega.github.io/schema/vega-lite/v5. Two major stakeholders of EMS are prosumers and consumers. Prosumers present the set of houses that not only produce electricity using PV panels placed on their roof tops but also sell the electricity surplus to their need. Consumers comprises of all such house in the same regions that are buying electricity from regional grid while not contributing in energy production. Smart meters collect prosumer’s data parameters including electricity consumed and total electricity produced per day that is further used to calculate surplus energy to be sold to regional grid station. Table 4 presents the description of all Clients involved in our proposed FL based model. Table 4Client details31.Client (Residential prosumer)Local model trainedSupply details (Per transformer)Max. load current recorded (A)Voltage ratio (kV)Power (MW)HV/LC current (A)Client-Ax12202501200109.6Client-Bx22202501230112.3Client-Cx32202701200112.3Client-Dx4220260120599.6HV, high voltage; LC, parallel resonant converter. Client details31. HV, high voltage; LC, parallel resonant converter. B. Electricity selling system (ESS) Electricity selling system (ESS) Blockchain is involved in selling and buying the surplus electricity among Clients. This research presents a secure, transparent, and efficient framework to manage electricity within the Client and among Clients having surplus electricity by employing a state-of-the-art technology blockchain. In this scenario, each individual client is considered a residential prosumer with a small smart energy meter and rooftop photovoltaic (PV) panels, as well as a prosumer within a distributed grid of blood. As with well-designed prosumer blocks within smart grids, the power blocks manage the production, consumption, and trading of the (decentralized) energy with the prosumers using a combination of Federated Learning and Blockchain. This technology adds transparency in the system by allowing the prosumer to see status of surplus units by using blockchain traceability characteristic and get notified when it reaches the consumers. Once a prosumer sells surplus electricity, its payment is locked by smart contracts that provides a secure transaction with proof of work. Payment locked by a smart contract cannot be tampered and the prosumer will keep track of the units sold by finding a trace of the supplier and eventual consumers. Once the consumer gets units, prosumer gets notified by blockchain platform and the blockchain nodes are updated against each entry. Meanwhile, payments are locked using a smart contract., whereby a smart contract is nothing but a computer program that enable the blockchain to perform credible transactions without any third parties in a distributed system. Payments remain locked and cannot be handed over until approved by the authorized sources. It can be simply defined as payment on delivery. The whole system is transparent and keeps track of every transaction for external authorities such as government, if they notice any unusual event, they can take action against the person responsible for that transaction. Figure 2 illustrates how blockchain technology can be used to improve the existing electricity management systems. C. Proposed architecture Proposed architecture The proposed architecture comprises of four layers physical layer, network layer, processing layer, application layer as presented in Fig. 3. Internal structure of proposed federated grid. i. Physical layer Physical layer Data collection has been performed through physical layer, using four Clients covering different regions of the selected area as presented in Table 1. PV panels have been installed on flat roof tops of selected houses a smart meter that records total energy consumed per day is connected to each house externally. Houses with solar panels produce electricity and after fulfilling its electricity need, leftover energy is supplied to regional grid station where digitalizer system calculates total energy supplied or demanded by every house per day. Digitalizer system also records the electricity consumed in daily social utilities like enlightening streetlights, running water pumps etc. At the end of each month, digitalizer system performs some processing on collected records like calculating total surplus electricity (Ts), total demand (Td) per house per month to maintain their wallets. It also calculates electricity net balance (Tb) at the end of each month that is necessary to trigger the server about surplus electricity or electricity shortfall using predefined equation presented in Eq. (1). Clients participating per round to update their weights at global model have been presented in Eq. (2). Total active devices participating in each round = D. Number of devices updating their weights per iteration = Di. Local dataset size of client i = Di. Total data across all participating clients = ∑ Di. Number of active clients selected in each global communication round = n To implement cross-device federated learning, digitalizer system installed at regional grid station of all Clients receive initial model from central server. Initial model is composed of multiple parameters including batch size of the local model (b) used in every iteration during the learning process, rate of learning local data(η), training rounds needed (e), threshold criteria and time (t) needed for the completion of each training round. Every Client updates the initial model at each round and transmits model updates to central server through network. Equation 3 presents local trainings performed by each client (household). Current Local model parameters at iteration t = Learning rate controlling the step size of gradient descent = η. Gradient of the local loss function Fi, computer from local energy data = ii. Network layer Network layer Working of the network layer is 2-fold. In first fold, it is responsible for secured two-way transfer of local model updates towards central server or updated global model from central server to Clients. TCP/IP protocol has been used in this layer for ensuring privacy preservation of local models. Network layer establishes asynchronous communication by collecting model updates from Clients and transporting them to the server for updating central model. The updated model generated from the central server is also transferred to all connected Clients using network layer. In second fold, it is responsible to transfer alerts generated from central server towards the Clients guiding about electricity transfer. iii. Processing layer Processing layer Local model updates are received at central server where these are kept in a log file and server implements FL algorithm (Electric_Fed) for the calculation of weighted average to update central model as presented in Eq. (2). Parameters necessary for FL are determined in two phases. In Phase 1, local models are trained on Client devices with following specifications T = 0 (time), w0 (initial weight) b = 32 (minimum batch size), η = 0.5 (learning rate), e = [1–10 epochs], current status (s) = {0 for inactive and 1 for active} and x={+ for surplus, - for shortfall} is obtained from server by Clients to append their updated new weight as w1 = model (x, b, e, η, s). In next phase, server retrieves local updation of initial weights from all connected Clients and determine average weight wn by the application of Electric_Fed algorithm. Equations (1) and (2) has a strong relation to the Proposed Model. In the Electric_Fed algorithm, each client (A–D) is assigned the role of training a portion of the local model with real-time energy data including readings on consumption, production, and surplus/shortfall. The model’s server captures the value of each distributed client’s data and consolidates the local model parameters. The model captures value from clients with larger amounts of data and equally, a global intelligence model is created which predicts patterns of electricity consumption, generation, and trade for the forthcoming period. This step of aggregation corresponds with the proposed algorithm in the ServerUpdate() function, lines 1–15. Every client (house) personalizes its model weights based on its unique electricity records (consumption vs. production). The loss function captures the prediction errors as Fi(wi) balances estimated versus actual records in power. The update rule employs gradient descent to further reduce the loss function. After a few epochs of training locally, the updated weights are sent to the server to be aggregated as in Eq. (1). This is represented as the function ClientUpdation () (lines 17–30) in the proposed algorithm. The Electric_Fed model is driven by the core set of equations; In Eq. (2) the clients collaborate and are synchronized using federated averaging whereas the learning captured in Eq. (3) draws on decentralized energy data. The final global model aids in smart contract triggers for auto electricity trading on the blockchain between clients. At the central server Electric_Fed algorithm starts with initial weight presented as w0 = 0. Now, central server simultaneously communicates with all active local devices and shares model wt−1 with all active Clients St from total Client pool J having participation rate M. One or more training rounds are performed by every active Client with learning rate η and model updates are sent back to central server indicating completion of local training. Central server applies Electric_Fed algorithm on model updates received from connected Clients to know about Client’s status and transmit back the updated central model towards all active Clients. Client takes Tlocal time in completing one round of local training and one complete global round takes λTg time, where λ is communication delay. Hence total time (T) taken in one iteration is. At the same time, each Client calculates total energy demand of the region covered under it and total energy produced in its scope. Server receives the status about surplus electricity (Ts) or electricity shortfall(Td) from all Clients and applies federated averaging method to calculate the average need of electricity. Server generate alerts to the regional grid station of the specific Client when it has surplus electricity and is interested in selling it. At this stage, blockchain technology facilitated the process of demand and supply of electric potential generated and consumed. Blockchain is initiated and a smart contract (SC) is established between the Client having surplus electricity and the Client facing electricity shortfall. Major stakeholders involved in this model are owner of houses (people) who have installed PV panels on their rooftops, Companies that want to buy the additional electricity produced, local government institutes that manage local grid stations and stable internet WIFI used to transmit all the alerts between all stakeholders. Hence, a single robust global model is generated through aggregation of local models at central server which is again distributed among all Clients to get their recent updates about surplus electricity or electricity shortfall. After model aggregation central server would determine the Client which have reported surplus electricity and the one that is facing shortfall. Central server will trigger the Client that have surplus electricity to send electricity to the electricity deficient Client. Clients will receive trigger issued from the server at digitalizer system installed at regional grid station. Client with surplus electricity will establish Blockchain smart contract (SC), as presented in Figs. 4 and 5, with the Client facing deficiency to sell its surplus electricity performing electricity transaction without intervention of third party. Smart contract for electricity coin ICO. Implementing ERC20 standards. Electric_Fed. Client buying electricity will pay bitcoins to the electricity selling Client for the electricity purchased that will be further distributed among prosumers located in electricity selling Client. Digitalizer system at local grid station will calculate the total surplus electricity generated by prosumers after subtracting the units recorded as demand. Prosumer’s payments will be added in their wallets maintained by digitalizer system. Prosumers can withdraw or transfer money from these wallets to their bank accounts. Grid station of particular region will supply the extra electricity traded by the prosumer towards the consumer. Now, the electricity from grid station will be sold to Clients that are facing electricity shortfall through smart contract27,28. There might be certain special cases like a Client have surplus electricity but no buyer available or all Clients are electricity deficient and none of them have surplus electricity to sell. In both cases, electricity will be sold or purchased from the main grid station indicated in Fig. 3. A routine bill will be issued by the main grid station at the end of the month, blockchain will not be involved in such case. Blockchain module The blockchain layer of the hybrid electricity management system will be provided to offer secure, transparent, and tampered transactions among residential power blocks. A permissioned blockchain network topology is deployed since the actors (residential units, local energy managers, and grid operators) are familiar actors in the smart grid system. Permissioned networks offer reduced latency and increased throughput and additional access control compared to public blockchains, which are more appropriate in energy management applications. The system utilises Practical Byzantine Fault Tolerance (PBFT) consensus mechanism that validates transactions among the participating nodes. The reason why PBFT is chosen is that it can reach consensus quickly in contrast to Proof-of-Work (PoW) mechanisms that have a high computational cost. There is a set of validator nodes that are the representatives of the energy management controllers in the proposed architecture that are involved in the mechanism of the consensus to verify the records of the energy trading, the actions of the demand-response, and choices of the electricity allocation. In residential distributed systems, PBFT can support up to (n − 1)/3 faulty nodes, and hence the reliability of the system. To carry out transaction processing, a light weight transaction cost model is deployed. It utilizes a micro-transaction cost of a fixed cost as opposed to cryptocurrency-based gas fees that would be paid in the public blockchain to record energy exchange events. This will minimize the overhead of operation and enable the blockchain to operate as a secure accounting and verification layer, not as a financial trading platform. The computational resources, storage requirements, and the overhead of the communication in the network are the principal cost of a single transaction. Scalability wise, the permissioned blockchain with PBFT consensus has both minimal confirmation latency and computation demands than PoW-based networks. This is because, the only nodes that are involved in the consensus process are authorized and hence, the system can facilitate the high frequency transactions of energy involving residential power blocks with low processing delay and resource efficient utilization. This renders the proposed architecture as being fit in the real-time smart grid electricity management applications. iv. Application layer Application layer The application layer includes public sector and private organizations that are interested in becoming a stakeholder in proposed electricity trading system to get electricity at lower price than getting it from main grid station. The main aim of our research is to formulate an electricity trading framework in which prosumers and consumers can sell and buy electricity without involving electricity supplying companies at lower rates. Experimental validation Electricity load shading is one of the major issues faced in developing countries that seriously effect domestic and industrial operations. Their regional government agencies with limited resources have been struggling to find significant solutions for generating electricity using solar power. We have designed this experiment capturing data from 54,900 m2 area located at 31.4312o N and 72.244o East. In this region. average temperature remains in the range of 24.6–35 °C31. A. Experimental setup Experimental setup All houses located in the selected region have been arranged into four categories (A, B, C, D) according to their covered area as presented in Table 4. Rooftops of selected houses from each category have been digitalized. Digitalization criteria has been listed in Table 5. To perform FL A, B, C and D will serve as Clients that will send and receive data from cloud based central server. Table 5House selection criteria.ParametersValueDirection of the buildingSouthRoof tiltNot selectedSurface areaFlatOrientationAnyShaded rooftopNot selected¬Havc system ˄ ¬ChimneysNot selected House selection criteria. Hence, only such roofs have been selected that receive direct solar radiations. Energy demand for the electrical appliance installed inside the houses has been determined using IoT based smart meters. Total electricity consumed is recorded on smart meter from where net balance of electricity for the house is calculated. It is determined that whether electricity is surplus or the house has to demand electricity from the regional grid station. Digitalizer receives all updates from all houses located in the region to determine electricity sold or demanded per day by each house of the region. This calculation is ultimately used to get overall net balance of each house in electricity trading per month. Digitalizer system also calculates total surplus electricity generated by all houses after satisfying all electricity needs of the region and uses this calculation to train the initial model received from the central server during FL process. In the same way, all Clients train the initial model received from the central server and transmit their status by updating the initial model. Server receives updates from all Clients and apply Electric_Fed algorithm for calculation of federated average. Server updates the global model and issues alerts to Clients that can trade electricity and the Clients that are facing electricity shortage as presented in Table 6. Table 6Total digitalized area and electricity net balance in experimental setup (Month: June 2024).Client (Residential Prosumer)Covered area (sqm)No. of houses selectedDigitalized ares (sqm)Avg. electricity estimate/house/month kWhNet balance/month electricitykWhStatus FlagSurplus: True or 1, Shortfall: False or 0ConsumptionProductionA6000 10 36 50005909+ 909TrueB4000 10 30 21002112+ 12TrueC3500102817001930+ 230TrueD1000101718801187− 693FalseSignificant values are in bold. Total digitalized area and electricity net balance in experimental setup (Month: June 2024). Significant values are in bold. The production potential of all Clients is listed in Table 6. Client A has enough surplus units that it can supply to Client D for fulfilling its need. Table 7 presents hyper parameters and training configuration of Electric_Fed. All Clients receive initial model given in Table 8. Table 7Hyper parameters and training configuration of Electric_Fed.Hyper parameterValueLocal model typeFeedforward neural network (MLP)Input features8Hidden layers2Neurons per hidden layer64, 32Output layer1 neuronHidden activation functionReLUOutput activation functionLinearLoss functionMean squared error (MSE)OptimizerSGDLearning rate (η)0.5Batch size (b)32Local epochs (e)1–10Number of clients4Client participation fraction (M)1.0Active clients per round (n)4Global aggregation methodWeighted Federated Averaging (Electric_Fed)Global aggregation frequencyOnce per communication roundCommunication modeCross-device asynchronous FLCommunication rounds for convergence100 Hyper parameters and training configuration of Electric_Fed. Table 8Model training process.ClientUpdated model (first iteration)Aw1={+,32,1,0.5,1}Bw1={+,32,1,0.5,1}Cw1={+,32,1,0.5,1}Dw1={+,32,1,0.5,0} Model training process. w0 = model (x, b, e, η, s). masked as w0 = model (ϕ, 32, 0, 0.5, 0). Client A, B, C send alert to the server about surplus electricity by training initial model received from it. Client D also informs the server about its electricity shortfall by training the initial model wo. Server triggers Client A, B, C reporting surplus electricity to establish smart contact with Client D facing electricity shortfall. After receiving trigger from server, Client A, B, C initiate smart contract with Client D. Client D accepts smart contract with Client A as it has sufficient surplus electricity that might be needed to fulfill need to Client D and requests from Client B, C are declined. Client B, C sells their surplus electricity to the main grid and all prosumers located in the region covered by these Clients gets compensation in their electricity bills. Client D buys as much electricity from Client A as it needs and adds bitcoins in the main wallet of digitalizer system working in Client A. Digitalizer system will further distributes the payments to prosumers accordingly. Remaining surplus electricity of Client A that is not even bought by Client D is sold to main grid station and unit level compensation is added in their routine electricity bills. B. Dataset description Dataset description ItemDescriptionDataset nameRenewable electricity datasetSource/LinkKaggle—rabiatehseen/renewable-electricity-datasetRecords17,844 rowsAttributes8 columnsFile size1.8 MBTime span2000–2023Geographic coverage7 zonesFile formatCSV (comma-separated)Key variablesCountry, Year, Month, Renewable Electricity (GWh), Non-Renewable Electricity (GWh), Total Electricity (GWh), Renewable Share (%), Emission Rate (kg CO₂/kWh)GranularityMonthlyUsage in paperUsed for federated training and validation of the Power Block model for electricity generation and consumption forecastingRemarksPublic dataset ideal for energy trend modeling, renewable energy forecasting, and cost-benefit simulations C. Analysis Analysis Electricity production potential of the experimental region is presented here. Total digitalized area on which PV panels have been installed is 111 sqm. Table 6 presents the electricity produced and consumed during the whole year 2024 through the experimental setup formulated in this research. It can be observed from Table 6 that amount of electricity produced by multiple Clients is varied and is in direct proportion to its total area with PV panel installation. Generation of electric potential is directly related to the area of PV installation. Table 9 presents the monthly and yearly record of electricity produced or consumed by each Client and total potential of the complete region is also stated . Table 9Monthly electricity production (P) and consumption (C) record in kVh.Months (Year: 2024)Client: AClient: BClient: CClient: D P CNet P CNet P CNet P CNetJan19102245− 33510451534− 48910001049− 495681100− 532Feb20762295− 21910681532− 46410431297− 2546951106− 411Mar20802142− 6213571658− 30111221385− 2637851096− 311Apr31704130− 96015671695− 12814171552− 1359121185− 273May41584785− 62719862089− 1031735163510010281045− 17Jun5909500090921122100121930170023011871880− 693Jul5723485886520092093− 841915169522011051365− 260Aug5158426289619982045− 471805153626910021254− 252Sep49953241175418641987− 123177714773009351209− 274Oct213521003517601800− 4014361353838491185− 336Nov2089197011913831675− 29212841216686971135− 438Dec17402250− 51010351605− 570119610951015991125− 526Total (yearly)41,14339,278 1865 19,18421,813− 262917,66016,99067010,36214,185− 4323Significant values are in bold. Monthly electricity production (P) and consumption (C) record in kVh. Significant values are in bold. It can be observed from Table 9 that total surplus electricity generated by Client A is 1865 kWh and from Client C surplus electricity 1079 kWh is available for sale. It can be supplied to Client B and Client D in less rates then buying electricity from main grid. Moreover, Client A and C have fulfilled their 100% electricity demand and are also able to earn money by selling the surplus electricity. They will know about electricity deficient Clients by receiving alert from the server and then Client A and Client C will try to establish smart contract with Client B and D as presented in Figs. 4 and 5. Even though smart contracts based on Ethereum allow a fully automated and transparent peer-to-peer energy trading, the practical implementation in residential power blocks should consider the scalability constraints of transaction throughput and cost of execution. The high frequency trading environment can result in a substantial cumulative gas cost due to many daily micro-transactions that can be more than the economic value of small-scale energy transactions. Hence, the suggested framework cannot be understood as being based on an open on-chain implementation of each micro-transactions. Rather, scalability can be enhanced through a private or permissioned Ethereum network, aggregating many trades together, or storing only aggregated settlement data on-chain and keeping a fine-grained trading logic off-chain. This saves gas money and enhances throughput rendering the ledger more applicable in energy trading situations of residential usage. Even though blockchain has immutability and transparency of recorded transactions, it alone cannot confirm whether the physical electricity recorded by a hardware meter is accurate. The system proposed thus presupposes a hardware-to-blockchain trust anchor, according to which smart meters and digitalizer gateways are recognized as trusted sources of data concerning reporting on the generation, consumption, and transfer of electricity. Assuming one of the local meters is compromised and sends incorrect readings, a smart contract can transfer a fraudful payment even with the integrity of the blockchain ledger. To mitigate this threat, the framework ought to have secure smart meters with hardware that is difficult to tamper with, validated communication between the meter and digitalizer, verification of device identity, and periodically verify the reported energy values at the regional grid station. By doing so, blockchain insures the records of transactions once data is entered whereas the metering infrastructure is trusted to be able to verify the validity of the off-chain physical measurements before they are announced on-chain. Therefore, the security of a smart contract in electricity trading is not the only determinant of the reliability of a blockchain-based electricity trading system, but the credibility of the metering and gateway systems that provide the data that the blockchain-based electricity trading system uses. It has been observed from this experiment that overall, 89.2% electricity need of the region has been fulfilled by installing PV solar panels on the rooftops of 40 houses in total. If more houses are digitalized then more electricity need can be fulfilled locally without involving national electricity supplying company. Table 9 compares the total energy consumed by all houses in the selected region with the overall energy produced by PV installation. It can be observed from Table 9 that Client A consumes 95.5% of its produced electricity and remaining 4.5% electricity is surplus. In the same way, C consume 96% of its produced electricity and sells remaining 4% of electricity to the Clients B and D facing electricity shortfall. Collectively Client A and C can fulfill 8.5% electricity needs of Clients B and D. Client B fulfills its 88% electricity demand on its own and may get 8.5% electricity from Client A and C. Similarly, Client D fulfills its 74% needs by generating electricity locally or can contact Client A and C for taking surplus electricity through blockchain. National electricity supply company will supply remaining electricity units needed by Client B and D. Figure 6 presents per month surplus electricity and shortfall. The studied area is in central Asia and it is usually very hot summer during the month of May, June and July. Electricity production in these months have been significantly raised. Monsoon starts in the studied region during August, September and October that cause significant rainfall that decreases the electricity generation capability of or experimental setup. Winter season starts in November that lasts till February in the studied region. Comparison of per month surplus electricity and shortfall. Electricity production is again low during these months. However, electricity consumption during these months is also low because fans and air conditioners are not working during winter season. It can be observed from Fig. 6 that Client B have minor electricity shortfall and Client D is facing major electricity shortfall. Covered area where PV panels have been installed is also comparably smaller than other three participating Clients. Shortfall of Client D can be controlled by digitalizing more houses, currently 40 houses have been digitalized. If number of digitalized houses is doubled then there would be a significant raise in electricity production power of the region and this region could also trade surplus electricity to earn profit. On the same way, Client B comprising of more commercial areas, schools and hospital buildings. High electric potential can be generated by installing PV panels on their rooftop due to more roof top space availability. If all these buildings are also digitalized like houses that are generating electricity, then amount of electric units produced in Client B’s region would be much higher than that are currently being produced and this way Client B can also participate in electricity trade for earning profit. Figure 7 presents working process of the ElectricityCoin smart contract system and Fig. 8 illustrates the total production and consumption capacity of all Clients participating in electricity trade. Working process of the electricitycoin smart contract system. Comparison of energy production and consumption of clients in the study area. D. Buyer–seller selection mechanism in multi-client scenarios Buyer–seller selection mechanism in multi-client scenarios During the months when a higher number of clients are coupled with surplus energy production while the other clients are under energy deficits, the Power Block coordinates trading through a dynamic selection algorithm which is integrated within the Electric_Fed federated network. The selection dynamics are based on a triage of priorities, which is as follows: i. Energy balance calculation Energy balance calculation Each client node (prosumer) under federated updates will predict and then periodically supply the Power Block aggregator with their predicted consumption and production balance data. Clients with a surplus (production > consumption) are categorized as potential sellers, while clients with a deficit (consumption > production) are categorized as potential buyers. ii. Priority ranking via federated model prediction Priority ranking via federated model prediction Using data from local clients, the federated model calculates the severity of local demand and the reliability of local supply. Buyers are given a rank according to their deficit ratio (kWh shortfall ÷ average monthly consumption), while sellers are ranked according to their surplus ratio (kWh surplus ÷ installed PV capacity). This process guarantees that the clients experiencing the worst shortages will be prioritized and provided energy from the clients with the most surplus energy. iii. Blockchain-based matching and transaction formation Blockchain-based matching and transaction formation After ranking the clients, the Power Block runs the smart contracts to match the highest ranked buyers and sellers. In the matching process, we first apply a lowest-cost, highest surplus policy to ensure equity and maximize the efficiency of the trade. All the transactions are captured by the blockchain to guarantee transparency and accountability. In the case of conflicting orders, the smart contract enforces timestamp arbitration, and the earliest energy request is prioritized. iv.Application scenario (Based on Table 6) Application scenario (Based on Table 6) During June and July, when clients A and C had energy surpluses and clients B and D had energy deficits. Client C, with the surplus ratio over Client D, was chosen to be the primary seller. Since Client D had the larger deficit, the surplus energy was first allocated to her, while clients B and D were the buyers. Once satisfied, the surplus energy left with Client C was offered to Client B. The implementer of the buyer-seller selection mechanism guarantees equal access to energy resources within a fully decentralized energy trading system. The flowchart presented in Fig. 7 illustrates the working process of the electricitycoin smart contract system, one of which is the ERC20 token contract and the other one is the electricitycoin ICO contract. It starts by setting up significant parameters like the name of the token, symbol, overall supply, and mappings holding user balances and allowances. ERC20 contract section demonstrates how such core operations as transfer, approve and transferfrom operate with transactions of tokens and control access to various addresses. The section on the ICO contract elaborates on how investors would be able to sell or buy electricitycoins depending on the amount of USD they have invested in the project and the fixed exchange rate. In the process, conditions that are checked during decision steps are that there is enough balance, limits of allowance, and maximum coinage prior to any transaction being transacted. Results and discussion In short, the system combines Blockchain and Federated Learning to provide energy independence with minimized costs and safe and secure decentralized trading. It is a flexible and smart renewable energy solution focused on privacy in the renewable energy systems of developing countries. Figure 8 presents surplus electricity that has been calculated by comparing the electricity production and consumption. Even though only a little portion of the rooftops is chosen, the energy output is extremely great. According to the electric potential scales defined by National Renewable Energy Lab, the selected region has a high electricity generation potential31. Figure 8 shows that Client A is earning profit in our proposed electricity trade system as it does not need to buy electricity from any other Client or from national electricity supply company (NESC) at high rates. It has extra units available for sale to other electricity deficient Clients or to NESC. Currently Client B and D are facing electricity shortfall but they can meet their demands by installing more PV panels on rooftops of houses and other public areas. The proposed model is very effective in fulfilling the regional electricity demands. It facilitated prosumer houses to control their electricity bills and save huge amount of money being paid for electricity bill to NESC. In case of facing electricity shortfall, Client can get electricity from other Client participating in electricity trading system. This way prosumers would not only receive lower electricity bills, but they could also receive additional cash adjustments by investing in electricity trading system. In this experiment, very small area has been utilized for PV installation. If the entire roof space was used to generate power, the amount of energy produced from the study area would be enormous. It can be inferred from current calculation for the year 2024 that at least same output solar energy potential must be required in the study area for the year of 2025. Recently it is 88,349 kwh/m2/year as shown in the Table 9. Keeping the current electricity produced as a threshold value with the passage of time due more construction electric potential requirements would increase drastically. A.Computational analysis of the proposed FL + blockchain model Computational analysis of the proposed FL + blockchain model Scope: As illustrated, we evaluate the EMS, Electric_Fed algorithm, and ESS smart-contract workflow coupled with the described clients A- D (parameters b, η, e, participation M, communication delay λ, Eqs. (2) and (3)); storage, communication, and computational costs of the system. Figure 9 presents step by step computational flow of the proposed model. Computational workflow of proposed model. i.Notation N: total clients; n = ⌈M·N⌉: active clients per global roundDi: local examples at client i; Bi = ⌈Di/b⌉: batches per epoch|w|: size of model parameters (bytes); Cfb: compute per batch (flops)e: local epochs per round; R: number of global rounds Notation N: total clients; n = ⌈M·N⌉: active clients per global roundDi: local examples at client i; Bi = ⌈Di/b⌉: batches per epoch|w|: size of model parameters (bytes); Cfb: compute per batch (flops)e: local epochs per round; R: number of global rounds N: total clients; n = ⌈M·N⌉: active clients per global round N: total clients; n = ⌈M·N⌉: active clients per global round Di: local examples at client i; Bi = ⌈Di/b⌉: batches per epoch Di: local examples at client i; Bi = ⌈Di/b⌉: batches per epoch |w|: size of model parameters (bytes); Cfb: compute per batch (flops) |w|: size of model parameters (bytes); Cfb: compute per batch (flops) e: local epochs per round; R: number of global rounds e: local epochs per round; R: number of global rounds ii.Client-side computation Client-side computation Per global round, client i runs e epochs of SGD on Bi batches: Cost_client_i_compute = e × Bi × Cfb. This scales linearly in e, Di, and inversely in b. With b = 32 and e∈[1, 10], the client workload is tunable by trading accuracy vs. Latency. iii.Server-side computation (aggregation) Server-side computation (aggregation) Electric_Fed performs weighted averaging of n updates: Cost_server_compute = O(n·|w|). Memory is O(|w|) for the global model plus O(|w|) workspace. Aggregation is linear in the number of active clients and model size. iv.Client-side computation Client-side computation Per global round: Downlink: server → n clients: n·|w| Downlink: server → n clients: n·|w| Uplink: n clients → server: n·|w| Uplink: n clients → server: n·|w| Total: 2n·|w| bytes/round; 2nr·|w| over training Total: 2n·|w| bytes/round; 2nr·|w| over training v.End-to-end latency per round. End-to-end latency per round. T_round = λTg + T_local, where T_local ∝ e·Bi. Overall convergence time ≈ R × T_round. vi.Blockchain (ESS) transaction cost and throughput. Blockchain (ESS) transaction cost and throughput. Smart contracts process every energy trade. On-chain storage for every trade as metadata (ids of seller and buyer, kwh, price, time). Instead of making O(houses) on-chain calls, we make O(Clients) on-chain calls, thanks to batch settlements. vii.Storage requirements. Storage requirements. Off-chain (digitalizer logs): per house, daily tuple < consumption, production, Ts, Td>. For 40 houses and 365 days, ~ 2.9 MB/year; hourly logging < 70 MB/year. viii.Scalability. Scalability. Compute grows linearly with n; bandwidth = 2n|w| per round. Use model compression to reduce |w|. Semi-asynchronous aggregation mitigates slow clients. ix.Computational complexity analysis. Computational complexity analysis. The suggested electricity management framework uses a Federated Learning (FL) architecture whereby various residential power blocks can train their own local models and send only model parameters to a central server. The local model training and the aggregation process mainly define the computational complexity of the FL model. Suppose every client has N training samples and d model parameters, local training by gradient-based learning has computational complexity of about O(N d) per training round. The central server does parameter aggregation, which is normally by federated averaging (fedavg) algorithm, which has complexity of O(K d) where K is the number of interacting clients. The FL-based approach spreads the load of the training process across clients compared with centralized machine learning schemes, where all the data should be sent and processed in one central server with a complexity of about O ((KN) d ). This saves the central server computation and vastly minimizes the overheads of communication. The FL framework is more scalable than deep reinforcement learning (DRL) or metaheuristic optimization algorithms (e.g., genetic algorithms or particle swarm optimization) that typically involve several iterative steps and massive data sets, usually requiring many iterations and a large training set to achieve accuracy. DRL-based frameworks can have complexity of the order of O(T·N·d) with T being the number of training episodes, which is computationally expensive on large-scale residential systems. Computational cost analysis has been presented in Table 10. Table 10Computational complexity analysis.Ref.MethodTraining architectureApprox. ComplexityRemarksRef.9,11,17,20Centralized MLCentral serverO(KN·d)High data transfer and server loadProposed workFederated learning + BlockchainDistributedO(N·d) per client + O(K·d) aggregationPrivacy-preserving and scalableRef.29,37,23Deep reinforcement learningCentralized/DistributedO(T·N·d)High computational demandRef.5,8,9Metaheuristic optimization (GA/PSO)Iterative searchO(P·I·d)Large number of iterations requiredWhere: N = samples per client K = number of clients d = model parameters T = number of training episodes P = population size I = iterations. Computational complexity analysis. Where: N = samples per client K = number of clients d = model parameters T = number of training episodes P = population size I = iterations. Hence, the suggested FL-based electricity management system provides a good trade-off between computational and scalability and privacy maintenance, whereas it is applicable to distributed residential power block applications. x.Convergence and accuracy. Convergence and accuracy. Weighted averaging works for convergence on non-IID streams of data as long as e is small to moderate. 89.2% local demand satisfaction and accurate trade alerts is delivered by the four-client topology. xi.Privacy and security. Privacy and security. Secure aggregation ensures confidentiality of data but adds O(|w|) cryptographic overhead per client. Smart contracts on the blockchain will take care of integrity as well as minimal computation load. xii.Practical sizing. Practical sizing. If |w|=1 MB, N = 4, M = 1 → n = 4: Per round, ≈ 8 MB (4 MB download + 4 MB upload) is required. Over R = 100 rounds → 800 MB transfer; server aggregation is sub-second on a commodity CPU. xiii.Bottlenecks & mitigations. Bottlenecks & mitigations. Bottleneck observed: uplink bandwidth and latency → Mitigation: compression, smaller M, semi-asynchronous aggregation. Bottleneck on-chain fees observed → Mitigation: batch settlements, rollups, off-chain proofs. xiv.Convergence Behavior in the Case of Non-IID Data. Convergence Behavior in the Case of Non-IID Data. In real-life residential settings, the electricity consumption and generation measurements of various houses will be non-independent and non-identically distributed (non-IID) as a result of variation in the size of the rooftop PV installation, energy demand, and the local weather conditions. In the experimental set up proposed, four residential customers (A-D) have different electricity generation and consumption patterns as are depicted in Table 9. As an illustration, Client A produced 41,143 kwh/year and Client D produced 10,362 kwh/year, which means that the local data distributions are quite different. In order to test how convergence behavior would behave under these heterogeneous conditions, an Electric_Fed federated averaging procedure was tested on several rounds in the world. Every client trains the model locally with batch size b = 32, learning rate η = 0.5, and local epochs e = [1, 10] and the server then combines the model updates. The convergence of the federated model is assessed by stability of global models update between training rounds, prediction stability between surplus/shortfall in clients and precision of electricity trading alerts produced by the system. Although the local datasets may be heterogeneous, the global model can be gradually stabilized by weighted averaging of the model parameters. It was able to determine the clients with excess and deficit of electricity as shown in Table 6 with Clients A, B and C being classified as surplus nodes and Client D being a deficit node with − 693kwh. Such findings indicate that the federated model is not affected by the significant difference in the distributions of client data. xv.Learning stability in real-world environments. Learning stability in real-world environments. In order to further assess stability of the federated learning process, we examine changes in the electricity generation and consumption over the stated time. The data reveals high seasonal fluctuations as the electricity is produced more in the summer season (May-July) and less in the winter seasons (November-February) based on the weather patterns. For instance: Client A surplus in June = + 909 kwh. Client A over in September = + 1754 kwh. Client D deficit in June = − 693 kwh. These variations are actual non-IID operating conditions. Regardless of such variations, Electric_Fed model is constantly finding trading opportunities and the satisfaction to the local electricity demand is at 89.2% in the region. This shows that the proposed FL-based electricity management can retain constant learning results during the variation of energy production and consumption in the real world as presented in Table 11. Table 11Client data heterogeneity demonstrating non-IID distribution.ClientAnnual production (kwh)Annual consumption (kwh)Net balanceA41,14339,278+ 1865B19,18421,813−2629C17,66016,990+ 670D10,36214,185−4323 Client data heterogeneity demonstrating non-IID distribution. The developed system demonstrates cost linearity with clients, model size, and system discontinuities. It identifies communication as the dominant cost of federated learning, while the system’s blockchain costs focus on settlement-delay due to on-chain interaction, which aligns with scalable deployment. Figure 10 presents net electricity deficit and surplus electricity of residential clients. Net electricity surplus and deficit of residential clients. B. Results of the proposed FL + Blockchain electricity management model Results of the proposed FL + Blockchain electricity management model The developed model offers practical and financial value within the federated learning and blockchain paradigm in electricity trading. i.Surplus and shortfall detection Surplus and shortfall detection The Electric_Fed algorithm accurately identified clients with surplus and shortfall electricity production. Client A: +909 kwh (surplus) Client A: +909 kwh (surplus) Client B: +12 kwh (surplus) Client B: +12 kwh (surplus) Client C: +230 kwh (surplus) Client C: +230 kwh (surplus) Client D: −693 kwh (deficit) Client D: −693 kwh (deficit) This classification enabled efficient trading among clients through smart contracts. ii.Smart contract execution Smart contract execution Smart contracts driven by the blockchain layer initiated full automation of electricity trading agreements between clients. Electricity was sold by Client A to Client D for less than the retail price charged by NESC. Clients B and C sold their surplus electricity to the main grid. Payments were processed through the digitalizer system wallet in bitcoins, ensuring both transparency and automation. iii.Energy production and consumption (2024) Energy production and consumption (2024) Total digitalized area: 111 sqm Total digitalized area: 111 sqm Clients A and C achieved 100% self-sufficiency and obtained additional income from the energy sales Clients A and C achieved 100% self-sufficiency and obtained additional income from the energy sales The regional solar potential was calculated as 88,349 kwh/m2/year, establishing a benchmark for future installations. Energy generation was directly proportional to the PV installation area. iv.Economic and Environmental Impact Economic and Environmental Impact Decreased reliance on national grid electricity Decreased household electricity costs Decreased household electricity costs Increased household income from selling electricity Increased household income from selling electricity Potentially increased energy generation from complete rooftop solar installations Potentially increased energy generation from complete rooftop solar installations v.Regional and Social Benefits. Regional and Social Benefits. Yearly targets of dc renewable energy sources are met. Trade with no surveillance or privacy intrusions Trade with no surveillance or privacy intrusions A balanced p2p electricity trading system A balanced p2p electricity trading system Prosumers are active participants in the energy cycle Prosumers are active participants in the energy cycle C. Forecasting accuracy evaluation Forecasting accuracy evaluation The conventional statistical tests of evaluation were used to measure the performance of the electricity production and consumption forecasting process quantitatively. Specifically, the deviation between the predicted and actual electricity values was measured in terms of Mean Absolute Error (MAE), Root Mean Square Error (RMSE) and Mean Absolute Percentage Error (MAPE). Using the monthly production (P) and consumption (C) data in Table 12, MAE, RMSE, and MAPE for each client has been calculated. Table 12Forecasting performance of the proposed FL model.ClientMAE (kwh)RMSE (kwh)MAPE (%)Client A607.58775.0317.10Client B221.08289.8713.42Client C172.67193.5811.95Client D360.25397.0029.24 Forecasting performance of the proposed FL model. The findings suggest that the federated learning based forecasting system is able to report acceptable prediction accuracy on the various residential clients. It is observed that forecasting errors are relatively lower in Clients A and C as they have larger PV installation areas and more predictable generation shapes and in the case of Client D, the prediction error is larger as it has large electricity deficits and smaller PV installation capacity. The model in general has a reasonable forecasting accuracy in conditions of heterogeneous energy consumption and generation. Figure 11 presents an overview of forecasting performance of proposed model. Forecasting performance of proposed FL model. D. Cost analysis of electricity trading Cost analysis of electricity trading Electricity trading systems financial viability is greatly impacted by system costs. The suggested Electric_Fed model shifts energy consumption costs downward by facilitating direct P2P trading among residential prosumers to replace costly national grid energy. In 2024, residential grid electricity costs in Pakistan are about PKR 45–50 per kwh. In the Power Block network we proposed, transaction costs, which include the handling of smart contract fees, validation of the blockchain, and costs of communication, accumulate to around PKR 18–22 per kwh, depending on energy surplus, and volume of transactions at the given period. Comparative cost analysis has been presented in Table 13. Table 13Comparative cost analysis.Cost componentConventional Grid Electricity (USD)Proposed Electric_Fed P2P Trading (USD)Difference/SavingsEnergy cost (per kwh)0.17(avg)0.71 (avg)−57.9%Transmission & Distribution fee0.0200.00EliminatedBilling & Admin overhead0.0070.001 (smart contract fee)−85%Blockchain transaction fee (Gas fee)–0.001+ 0.001Total cost per kwh0.1960.074≈ 63% lowerAverage monthly saving per prosumer–10.00–11.43(for 150–200 kwh traded) Comparative cost analysis. Such costs entail: As energy surplus prosumers sell to energy deficit clients directly, bypassing distributors or transmission lines, prosumers and deficit clients save on costs As energy surplus prosumers sell to energy deficit clients directly, bypassing distributors or transmission lines, prosumers and deficit clients save on costs The smart contract automating the enforcement of the agreement and payment eliminates the need for third-party intermediaries The smart contract automating the enforcement of the agreement and payment eliminates the need for third-party intermediaries Microgrid functions on less energy, providing savings on loss incurred during transmission Microgrid functions on less energy, providing savings on loss incurred during transmission Figure 12 presents comprehensive view of cost comparison between conventional grid and proposed Electric_Fed model. Cost comparison between conventional grid and proposed Electric_Fed. E. Economic implications Economic implications The Electric_Fed Power Block system allows trading of electricity which results in grid-locked households saving 60–65% of electricity bills in addition to what is paid for electricity to the national grid. Surplus energy prosumers on the other hand may sell their excess electricity to clients to earn, if the profit margin is PKR 27–30 per kwh sold. The client, in return, is paying 40% less than the national grid rate. F. Economic feasibility analysis Economic feasibility analysis To implement the Electric_Fed system in practice, one also will have to consider the economic viability of the proposed system. In the electric world, the structure of tariffs differs according to the peak seasons and off-peak seasons. In the suggested system, peer-to-peer electricity trading is possible at a rate slightly below the grid rate and this will be advantageous to buyers and sellers. An example is given by the fact that in the case the national grid tariff is 0.18/kwh at peak hours, in-block trading can take place at 0.15/kwh and consumer can save money on electricity bills and producers can make extra money on the excess production. Cryptocurrency volatility may affect the value of a transaction since the payment is done using blockchain-based payment. To alleviate this problem, the system can use stablecoins or energy-backed tokens whose value can be fixed to local electricity tariffs where the payment will be stable and predictable. Economic feasibility analysis has been presented in Table 14. Table 14Economic feasibility analysis.ParameterValueGrid tariff$0.18/kwhP2P trading price$0.15/kwhBlockchain fee$0.01 per transactionSmart meter cost$40Monthly savings per house$12–$20 Economic feasibility analysis. There is also the cost of operations that should be taken into account, such as the installation of smart meters, blockchain transaction costs, and the federated learning coordination cloud infrastructure. Nevertheless, the expenses will decline with time as there will be more development in smart grid and distributed computing. Moreover, these costs can be compensated with the decrease in the reliance on the national grid and the optimal use of the local renewable energy, which makes the suggested model economically reasonable in the residential energy communities. Table 15 presents a comparison of Electric_Fed proposed model and the existing solutions available in the literature, such as centralized machine learning, deep reinforcement learning, and metaheuristic optimization, and blockchain-based energy trading systems. Contrary to those that are centralized and demand high-scale transfer of data to a centralized server, the suggested federated learning system ensures that the privacy of users remains intact since data within the system is localized to the client nodes. The proposed model is competitive in forecasting accuracy and has reduced computational complexity and a higher level of scalability compared to DRA and the metaheuristic methods. Moreover, it can feature the integration of blockchain, which allows the secure and transparent peer-to-peer trading in electricity, a feature many of the current forecasting-based energy management systems do not have. Table 15Comparison of the proposed Electric_Fed model with recent methods in literature.Ref.Method/ApproachArchitectureKey FeaturesForecasting Accuracy/PerformancePrivacyScalabilityRemarksRef.9,11,17Centralized Machine Learning for Smart Grid Energy ManagementCentralized serverGlobal dataset processing, centralized optimizationModerate accuracy but depends on large data collectionLow-user data transferred to central serverLimited due to high server loadHigh communication cost and privacy risksRef.29,37Deep Reinforcement Learning (DRL) based Energy TradingCentralized/HybridAdaptive decision making, dynamic energy tradingHigh learning capability but requires many training episodesMediumModerate scalabilityHigh computational complexity and training costRef.5,8,23Metaheuristic Optimization (GA/PSO)Iterative optimizationOptimal energy scheduling through population searchEffective for optimization but slow convergenceMediumLimited for large networksRequires many iterations and computational resourcesRecent Blockchain P2P Trading SystemsBlockchain-only energy tradingDistributed ledgerTransparent and secure transaction recordsNo forecasting capabilityHighModerate (limited by blockchain throughput)Focus mainly on transaction security rather than prediction Proposed Electric_Fed Model Federated Learning + Blockchain Fully distributed Privacy-preserving learning, smart-contract trading, decentralized energy management MAPE = 11.95–29.24% across clients High-data remains local High-computation distributed across clients Enables secure energy trading with accurate forecasting and reduced grid dependence Comparison of the proposed Electric_Fed model with recent methods in literature. Limitations Integrating FL and blockchain systems requires significant technical expertise and coordination. Ensuring seamless interoperability between the two technologies can be challenging Integrating FL and blockchain systems requires significant technical expertise and coordination. Ensuring seamless interoperability between the two technologies can be challenging The combined use of FL and blockchain may result in high computational and communication overhead, potentially affecting the overall system performance and efficiency The combined use of FL and blockchain may result in high computational and communication overhead, potentially affecting the overall system performance and efficiency Scaling FL to accommodate a large number of PV panel systems and energy producers can be difficult, especially with varying data quality and formats Scaling FL to accommodate a large number of PV panel systems and energy producers can be difficult, especially with varying data quality and formats Blockchain networks may face scalability challenges, particularly with transaction throughput and latency, which can be exacerbated when integrating with FL systems Blockchain networks may face scalability challenges, particularly with transaction throughput and latency, which can be exacerbated when integrating with FL systems While FL enhances data privacy by keeping data localized, there is still a risk of data leakage during model updates. Robust mechanisms are needed to prevent reverse engineering of sensitive data from shared model parameters While FL enhances data privacy by keeping data localized, there is still a risk of data leakage during model updates. Robust mechanisms are needed to prevent reverse engineering of sensitive data from shared model parameters Blockchain provides a secure and immutable ledger, but smart contracts and consensus mechanisms can have vulnerabilities. Ensuring the security of smart contracts and protecting against 51% attacks are crucial concerns Blockchain provides a secure and immutable ledger, but smart contracts and consensus mechanisms can have vulnerabilities. Ensuring the security of smart contracts and protecting against 51% attacks are crucial concerns Establishing and maintaining the infrastructure for a hybrid FL and blockchain system can be costly. This includes expenses related to hardware, software, and ongoing maintenance. Continuous operation of the hybrid system may incur significant costs, particularly for data processing, communication, and blockchain transaction fees Establishing and maintaining the infrastructure for a hybrid FL and blockchain system can be costly. This includes expenses related to hardware, software, and ongoing maintenance. Continuous operation of the hybrid system may incur significant costs, particularly for data processing, communication, and blockchain transaction fees Conclusion The aim of this study is to fulfill the electricity demand of consumer by producing electricity locally using PV panels. In this article, FL technique has been applied to determine the total regional need of electricity. Blockchain technology has been used to trade surplus electricity to electricity deficient Clients through digitalizer system installed on region grid station. Our proposed system contains smart meters that collect data of electricity consumption from every house. Digitalizer system installed at regional grid station keeps record of the surplus units applied by each digitalized house. Cross device federated learning technique has been used in this research in which all Clients receive central model with initial parameters from the central server. Every Client is responsible to update the initial model and set status to inform server about surplus electricity or shortfall. Server collects all local updates and after aggregating all local updates it triggers Clients with surplus electricity to connect with Client reported electricity shortfall. Smart contract is initiated for secure energy transaction between both agreeing Clients for selling and buying electricity. Payments are added as bitcoins to the wallet maintained by digitalizer system installed at Client’s grid station from where it will be shifted to the wallets of prosumer maintained by the digitalizer system. Electricity produced per year has been calculated to forecast electricity requirement for the upcoming year. More PV panels might be installed, and more house could be digitalized for producing more electricity to meet demand or trade the excessive energy produced to regional grid station for earning money. It has also been concluded that profit rate is high in June, July and August in summer season, as these are very hot months in the selected region. Although more electricity is consumed due to rise in regional temperature but production rate is also very high. Proposed model fulfilled 88.9% electricity demand of the selected region. Even though the records of transactions are secure with the help of Blockchain, the FL layer needs to be specifically safeguarded in case of adversarial interference, like model poisoning and label flipping, by means of robust aggregation and monitoring of client behavior. In future, more Clients can be added in the proposed electricity production and trading system to earn more profit. In future work, scalability challenges must be addressed by investigating efficient protocols for federated learning and blockchain that can handle large-scale networks of PV panels and extensive energy trading volumes. Acknowledgements We are thankful to Mr. M. Inayat Ali for his valuable guidance and support throughout this research. Author contributions R.T led this research work and statistically analyzed the whole article. U.O has supported for theproblem statement refinement with state-of-the-art literaturereview. Moreover, A.R.H and A.M have contributed in theselection of frequently used open-source software in the field ofrenewable energy production. The manuscript draft was proofread and revised threetimes before submitting to your prestigious journal by N.Q andN.S. RT and A.R.H has made contribution in designingmethodology and proof reading of manuscript. In the end, allauthors read and final the manuscript. Data availability The datasets analysed during the current study are available in the Kaggle repository, ( [https://www.kaggle.com/datasets/rabiatehseen/renewable-electricity-dataset](https:/www.kaggle.com/datasets/rabiatehseen/renewable-electricity-dataset) ) Accessed on: 05 January 2025. 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 datasets analysed during the current study are available in the Kaggle repository, ( [https://www.kaggle.com/datasets/rabiatehseen/renewable-electricity-dataset](https:/www.kaggle.com/datasets/rabiatehseen/renewable-electricity-dataset) ) Accessed on: 05 January 2025.