An Optimized and Decentralized Energy Provision System for Smart Cities

: Energy efficiency and data security of smart grids are one of the major concerns in the context of implementing modern approaches in smart cities. For the intelligent management of energy systems, wireless sensor networks and advanced metering infrastructures have played an essential role in the transformation of traditional cities into smart communities. In this paper, a smart city energy model is proposed in which prosumer communities were built by interconnecting energy self-sufficient households to generate, consume and share clean energy on a decentralized trading platform by integrating blockchain technology with a smart microgrid. The efficiency and stability of the grid network were improved by using several wireless sensor nodes that manage a massive amount of data in the network. However, long communication distances between sensor nodes and the base station can greatly consume the energy of sensors and decrease the network lifespan. Therefore, bio-inspired algorithm approaches were proposed to improve routing by obtaining the shortest path for traversing the entire network and increasing the system performance in terms of the efficient selection of cluster heads, reduced energy consumption, and extended network lifetime. This was carried out by studying the properties and mechanisms of biological systems and applying them in the communication systems in order to obtain the best results for a specific problem. In this comprehensive model, particle swarm optimization and a genetic algorithm are used to search for the optimal solution in any problem space in less processing time.


Introduction
A smart city is an idealistic city where the quality of life and quality of services for citizens is significantly improved by promoting innovative solutions. By integrating information and communication technology (ICT) and the Internet of Things (IoT), the efficiency and effectiveness of city functionality is impressively improved. Over the years, urban life within smart cities had undergone many challenges and transformations so as to contribute to a better quality of life. In recent developments of smart cities, the quality of power has been improved significantly by developing smart grids and by the emergence of smart communities, despite the high level of energy consumption in smart cities.
Smart grids are intelligent and flexible power grids that use two-way communication technologies which enable safe, efficient and sustainable energy consumption, unlike electro-mechanically controlled conventional electric grid. Information and communication technology is used for aggregating and analyzing large amounts of data generated by various sources, such as sensor networks, wearable devices, and IoT devices deployed across the city [1]. Within this smart network, consumers can actively participate in renewable energy production and consumption at individual and community levels and This paper presents a smart city energy model in which smart microgrid technology is incorporated with blockchain technology to improve the energy distribution capability between citizen houses in a smart community. Since WSNs form an essential component of an AMI, this paper presents a technique using two population-based bio-inspired algorithms, i.e., particle swarm optimization (PSO) and genetic algorithm (GA), to obtain an energy-efficient strategy for cluster head selection and achieve the optimal route connecting the sensor nodes to minimize total communication distance for transmission of data in less processing time. This helps in preventing data loss and maximizing energy efficiency and lifetime of the system. The strategies used in these algorithms are simple, robust, and adaptive since they imitate the nature of biological systems to solve real-world problems.
For the secure transmission of information in the network, blockchain technology is used to maintain the security and privacy of the systems [7,8]. In this paper, this technology is mainly used in the context of peer-to-peer energy trading in microgrids, which allows prosumers to sell excess energy directly to other households in the community in a transparent and cost-effective way. A blockchain-based solution is implemented, which enables local consumers to purchase electricity directly with cryptocurrency without any third-party intervention and maintain energy transaction records in a decentralized manner in blockchain.
The remainder of this paper is organized as follows. Section 2 is divided into three sub-sections. Section 2.1 presents an overview of the literature related to wireless sensor network optimization and blockchain-based systems. The papers have been referenced as well as their authors and works are highlighted in this section. Section 2.2 provides the background study necessary to understand the concepts involved. Section 2.3 presents the proposed methodology, working, as well as its possible implementation. Section 3 contains the results and Section 4 contains the analysis of the implementation. Section 5 concludes the paper.

Literature Review
As the theme of the article is based on blockchain-based energy systems and optimization techniques in smart grid using bio-inspired algorithms, the entire literature review is based on two broad divisions: bio-inspired algorithms and blockchain technology for the smart energy system. Being an important building block of the smart grid technology, the wireless sensor network (WSN) has always attracted significant interest in both industries as well as research areas in recent years. In this context, much recent research has been conducted to optimize WSNs in order to improve the performance of the smart energy grid. Various applications and issues associated with the WSN in smart grids are discoursed in [9]. Several algorithms have been implemented with respect to the localization of nodes, the formation of clusters and selection of cluster heads, optimal routing, network lifetime, energy constraints, data compression and aggregation, network security, and self-organization, which are the current focus areas of research in the field of WSNs. The quality of service (QoS) protocols, energy efficiency, bandwidth utilization, and secured routing in WSN are the major areas of concern discussed in [10,11].
Several metaheuristic algorithms used for optimizing various aspects in WSNs to provide sufficiently good solutions in acceptable time constraints are presented in [12]. A firefly-based approach to perform the clustering of nodes in the WSN and the optimization of packet delivery ratio and network lifetime is proposed in [13]. In [14], the ant colony optimization (ACO) algorithm is combined with the harmonic search algorithm (HSA) to find the optimal cluster head with minimum routing path and achieve a faster transmission of packets without losing data accuracy, which results in a higher network throughput and reduced energy consumption. A novel nature-inspired algorithm named the salp swarm algorithm (SSA) is presented in [15] for accurate node localization in WSNs and is compared with four other optimization algorithms, namely the firefly algorithm, butterfly optimization algorithm, particle swarm optimization, and grey wolf optimizer based on its performance and simulation results [16]. An energy-efficient routing technique based on the artificial cee colony (ABC) algorithm that mimics the foraging behavior and waggle dance of bees is proposed in [17].
Different routing protocols in WSN are discussed and analyzed in terms of performance, limitations, and security issues in [18]. A survey based on the multipath routing techniques is presented along with its fundamental challenges and future guidelines in [19]. It also emphasizes the relevant pros and cons associated with the routing protocols which can be used as a road map for further research. An improved genetic algorithm technique is presented in [20], which optimizes the performance of mobile agents in finding the shortest route for traversing the sensor network. A hybrid GA is implemented in heterogeneous WSNs, which integrates greedy initialization and bidirectional mutation operation in order to achieve full coverage of the monitoring area and prolong the network lifetime [21]. In research conducted in [22], genetic algorithm-based clustering and routing are proposed in which both clustering and routing methods are combined into a single chromosome to construct a fitness function that improves the energy efficiency in the network. In this work, the best load balancing is achieved, which results in the lowest average energy being consumed by the cluster heads. In [23], a GA-based classification method is used to categorize the DOA (direction-of-arrival) estimates for multiple sources' position of each sensor node in a three-dimensional space. It is seen that this method could lower the computational burden to a greater extent as compared to other conventional methods without reducing the accuracy of the estimation. In [24], a multiobjective GA is proposed to optimize the problem of node deployment in WSNs based on topology, environment, the specifications of various applications and network designers' preferences.
A precise technique based on the GA-NSGAII (non-dominated sorting genetic algorithm) algorithm is designed in [25] to develop a framework for a smart cyber physical energy system which is used to manage the energy sources for electric vehicles. The cloud computing is also implemented to gather the sensing information through a Wi-Fi system from the various sensors which are deployed in the EV (electric vehicles) to realize the health monitoring system of EVs. In [26], the PSO is integrated with a multi-hop routing protocol to obtain uneven dynamic clustering in a WSN that makes the cluster distribution change dynamically upon the failure of some nodes. This improves the energy efficiency of multi-hop transmission between the base station and cluster head nodes and increases the scalability for various sizes of the network. In [27], a PSO approach is implemented to produce energy-aware clusters by the optimal selection of cluster head nodes, which is based on residual energy, least average distance from member nodes and head count of possible head nodes. The performance of this algorithm is compared with other protocols such as LEACH-C (low energy adaptive clustering hierarchy centralized) and PSO-C (particle swarm optimization centralized). In [28], a PSO technique is proposed for improving the network lifespan by forming clusters and selecting the cluster head, and the results are compared with previously proposed LEACH algorithm. Traditional clustering algorithms such as the LEACH algorithm are presented in [29], in which uniform clustering results in high communication costs in single-hop inter-cluster routing, whereas in the EEUC (energy efficient unequal clustering) algorithm [30], non-uniform clustering results in a lack of the node's residual energy consideration during the cluster head selection phase. This leads to the premature death of cluster head nodes present far away as well as near to the sink node because of the high communication cost and insufficient energy to forward data, respectively, thus affecting the overall network lifecycle. Taking the drawbacks of LEACH and EEUC algorithms into account, the PSO algorithm is presented, which considers the node's residual energy, the number of neighbors, and distance from the base station to select the cluster head node in an energy-efficient manner that can improve the quality of network monitoring and extend the network lifespan. In this paper, we mainly focus on the two nature-inspired metaheuristic algorithms, i.e., particle swarm optimization and genetic algorithm, to solve the optimization problems in WSNs for smart grid applications. GA-based route optimization is presented to obtain the shortest path connecting the cluster head nodes to the base station for the cost-effective transmission of data in less processing time. This significantly reduces the energy consumption by sensor nodes and enhances the performance and lifetime of the network.
Data security is also achieved in this work along with the enrichment of node lifetime. With the handling of the massive amount of data in WSNs, the privacy and security of energy systems also need to be achieved, since communications take place over the energy internet. Moving up to blockchain technology, different sectors such as power, energy, electrical network, and smart grid are the key areas. The literature from [31][32][33][34][35][36][37][38] focuses on the application of blockchain technology to power sectors. A vision with analysis is offered in [31] for a networked microgrid by utilizing blockchain technology for the optimum use of a power distribution system. This also suggests an additional smart contract for secured energy operation amongst local grids and network microgrids. A virtual power plant model based on blockchain technology is proposed in [32] for a distributed energy resource to reduce the cost and a secure grid connection and similarly in [33], to improve energy efficiency and power quality in a power grid blockchain expertise is implemented. The work [34] represents the optimal utilization of a power distribution energy system using blockchain technology where multiple control, operation, planning are mainly addressed, and [35] proposes the blockchain application in the electric power system area with the latest technology and innovative applications. An overview and classification of blockchain technology for the power industry is discussed with some notable projects in [36]. The appositeness and outlook of blockchain technology in the energy sector are discussed in [37] by considering the socio-technical aspects related to trading, information storage, energy flow, and service in the energy sector. In [38], the utilization of blockchain technology is discussed to form the energy communities where energy is exchanged among the prosumers.
Regarding the electrical network in a smart city, the notion of a grid consisting of many hybrid micro grids for a smart city is presented in [39] where many advantageous characteristics such as better power quality, consistency, safety, low cost etc. over a general power grid are illustrated. Pertaining to the application of blockchain towards the power grid, reference [40] proposes blockchain-based hierarchical bidding with a transaction structure for local electricity networks with the use of the Bayesian theorem and the Nash equilibrium for the accurate probability of cost and optimum quotation, respectively, and the double auction mechanism along with blockchain technology is combinedly realized in [41] for a decentralized microgrid. The blockchain (Hyperledger) with IoT devices (Raspberry Pi) are combinedly realized in [42] to generate the bill with smart metering for an electrical network. A state-of-art regarding the security issues of a blockchain-based smart city is discussed in [43] where different issues related to medical facilities, conveyance, smart grid, logistics network are focused.
Pertaining to blockchain technology in the field of the microgrid, this is discussed in [44][45][46][47][48][49]. A centralized blockchain-controlled system with advanced metering infrastructures is discussed in [44] with a bandwidth requirement comparison for a microgrid infrastructure. It is found that an about 10 times higher demand in bandwidth is found in the blockchain-based solution as compared with an advanced metering type structure. A holistic exploration is proposed in [45] about the different challenges faced in the practical implementation of blockchain-based peer-to-peer (P2P) microgrid networks. The article [46] presents a solution of double energy spending in a microgrid by applying hybrid blockchain technology by sharing a secure environment for energy exchange between the consumer and prosumer. A smart transaction is performed in [47] using the blockchain technology in the smart grid and a smart contract. In [48], a microgrid design problem is addressed by blockchain technology for a real time-based demand response program. A fuzzy optimization approach is proposed for the localization and determination of renewable generation units with dynamic pricing. This study reveals a profitable growth of 1.68% and increased consumer satisfaction of 2.61% in the area of Vietnam. The estimation of power and price with an optimum power loss for a microgrid using blockchain technology with some differential evolution algorithms is aimed in [49]. In this, the blockchain is mainly involved in reactive power pricing which is acquired from service providers.

Particle Swarm Optimization
The particle swarm optimization (PSO) algorithm is a metaheuristic populationbased algorithm that was proposed by James Kennedy and Russell Eberhart in 1995. It helps in obtaining the optimal solution of an optimization problem by simulating the movement and foraging of a bird flock or school of fish [11]. In this algorithm, a population of candidate solutions, named particles, explores the search landscape by initiating with a random direction and following a search strategy that results in finding the best solution. Every particle stochastically traverses a certain distance towards the personal best location (pbest) and global best location (gbest) to reach a new location (shown in Figure 1), where it updates its velocity vector and position vector for the next iteration, only if the pbest and gbest values of the current iteration are better than those of the previous iteration. The particle's position and velocity are updated by using the following equation: where t is the iteration number, v is velocity of i particle and s is its position vector in t iteration. Here, ωv is the inertia, k r (pbest − s ) is the cognitive component and k r (gbest − s ) is the social component, where r and r are random components lying in the range [0, 1] and k1 and k2 are acceleration coefficients. Tuning the parameters such as k1, k2 and ω will affect the movement of particles and the exploration and exploitation of the search space. As the swarm keeps track of the best solution in the problem space and searches around them only, the time complexity of performing a search operation is greatly reduced and the probability of finding the global optimum increases, as compared to other deterministic algorithms.

Genetic Algorithm
The genetic algorithm (GA) is one of the first evolutionary algorithms, proposed by John Henry Holland in 1992, which mimics the Darwinian theory of evolution [16]. It was inspired by the natural selection or survival of the fittest in the biological evolution of living beings, in which genes having desirable traits are selected by nature and passed to the next generation through inheritance. In the genetic algorithm, a chromosome represents a candidate solution, and a set of candidate solutions represents a population, as shown in Figure 2. The GA is applied to an optimization problem by using the genetic representation of candidate solutions known as genes, and a fitness function or objective function. Each gene is represented by an array of bits or bit string and evaluated by the fitness function to obtain a unique value that determines the fitness of a given combination of bits with respect to the problem in consideration. The initial population is generated with random solutions and subjected to changes in subsequent generations by applying four genetic operators to every individual solution with a certain probability, i.e., selection, crossover, mutation, and elitism. The natural selection is simulated by a roulette wheel mechanism which is implemented by first creating a sorted array of normalized fitness values of all individuals, calculating their cumulative sums, and then generating a random number in the interval [0, 1] and looping through the array of cumulative sums to find the first value greater than the random number. Each cumulative sum in the array represents the probability of the corresponding individual getting selected. Thus, individuals having cumulative sums nearly equal to 1 have greater chances of being selected since they occupy larger parts in the simulated roulette wheel.
Crossover or recombination is used to combine the genetic information of two parents by swapping their genes before and after a point which is chosen randomly in each generation, to generate a new population with a fixed number of chromosomes. The rate of crossover is determined by using the probability of crossover (Pc).
Mutations are small random changes in the genetic sequence of a chromosome that result in the addition of new features to the population and increasing its genetic variation. It also helps in preventing the GA from converging to local optima. Mutated genes that result in less fit solutions are eliminated by selection and crossover in each generation. A predefined parameter named the probability of mutation (Pm) is used to determine the rate of mutation by generating a random number in the range [0, 1] and comparing it with Pm. A gene is mutated only if Pm is greater than the random number generated.
The fourth operator, i.e., elitism, is used to preserve a small portion of the best individuals in a population, known as elites, and transfer them unchanged to the next generation in order to prevent the loss of good traits due to crossover and mutation operators. The portion of elite individuals is determined based on the elitism ratio (Er), which can then be utilized in the process of selection, recombination, and mutation in the next generation for improving the quality of solutions. This is how the evolutionary mechanisms in the genetic algorithm are used to maximize the fitness of the population through each generation.

Blockchain Technology
Blockchain is one of the most cutting-edge technologies, which is a highly secure, immutable and decentralized database that stores transactional data in an encrypted manner in the form of blocks. It is a distributed ledger system consisting of a chain of blocks that keeps growing every time a transaction is carried out by users and validated by network engineers. These blocks are linked to each other through cryptographic hashing [7], as shown in Figure 3. The basic advantage of blockchain is that it is a decentralized system that operates as a layer on top of the internet, which reduces the expenses of buying servers, eliminates the intermediaries and third parties and ensures autonomy, data integrity and security to various systems [8]. The encryption in the blockchain is implemented using a 256-bit hashing algorithm, for example, SHA-256 in the case of Bitcoin and ETHash in the case of Ethereum cryptocurrency, for providing a high level of security. Since each block contains the unique transaction hash of the previous block (Figure 3), tampering with the data of one block will completely change the transaction hash of that block as well as all subsequent blocks, which will require immense computing power to break all the encryptions, making it extremely difficult for attackers to manipulate the information. In order to initiate transactions as well as decrypt the secured information by the users, every blockchain user is provided with unique public and private keys which form a digital signature of the user. Blockchain also provides security at the node level. A node is a participating computer in a peer-to-peer (P2P) network in which a ledger or blockchain is stored. In a distributed ledger system, each node is provided with a copy of the ledger in order to achieve transparency and consensus among other nodes within the network at the time of mining and adding a new block to the ledger. Mining is the process of verifying and validating the transactions by solving the proof of work (PoW) consensus algorithm before adding them to the blockchain. In the case of data tampering in one node, the ledger in that node will automatically become invalid and get discarded by other nodes, due to the presence of a copy of the ledger in every node that will create an inconsistency with the tampered node.
One of the popular and leading blockchain-based platforms is Ethereum, which is an open-source, public blockchain, developed by Vitalik Buterin in 2015, that features smart contract functionality. The smart contract is an immutable computer program written mainly in Solidity programming language in case of Ethereum, which cannot be changed once deployed on the blockchain and is executed only upon meeting a certain predefined set of instructions or conditions written in the program [40]. It enables users to build and deploy decentralized applications (dApps) on top of the Ethereum blockchain, which are controlled by the logic written into the smart contract. Hence, every process in the application is automated and the system verifies and validates all the transactions without any third-party intervention.
The decentralized digital currency of Ethereum is 'Ether' (ETH) which is currently worth INR 1,23,743.91. It is used to carry out all the transactions on a P2P network and to deploy smart contracts and run dApps. In order to perform a transaction or execute certain tasks, a smaller unit of the Ethereum token, known as "Gas" (1 Gwei = 10 −9 ETH), is used as a fuel to drive the process of adding a block to the public ledger so as to compensate for the computational power spent by the miners to verify and validate the transactions. This is how the consensus mechanism and hence a trustless computation works in blockchain technology.

Proposed Work
In order to promote renewable energy adoption in households and optimize their local energy resources efficiently, a smart energy community model is proposed in which a coalition of neighboring prosumers is formed based on an agreed sharing mechanism which is implemented as a smart contract on blockchain. In this model, blockchain technology is integrated with the smart microgrid for clean and decentralized energy trading between potential prosumers and consumers within the community, as shown in Figure  4. It mainly consists of energy-independent households in an interconnected energy network and decentralized storage systems that are coupled with distributed renewable energy generations of each prosumer. For the intelligent management of the microgrid, it is incorporated with a wireless sensor network and advanced metering infrastructure which monitor the generation, transmission, and consumption of electricity in real-time and send energy transaction information to the blockchain via smart contract. In this model, the microgrid acts as a small energy market in which prosumers can change their roles to sellers or buyers, depending on their net energy profiles in different time periods. For example, if the load demand of prosumers is not met by their own power generation, they can buy electricity from other prosumers in the network who have surplus energy production. The excess energy can also be exported to the utility grid for which prosumers are incentivized in the form of a feed-in tariff for generating electricity from renewable sources. The rate at which energy is shared among the households is determined by the amount of energy produced by PV prosumers on a daily basis. The energy pricing will be based on the availability of generation sources, demand, economic cost and pricing regulations, considering the power consumption flexibility of prosumers. The smart contract regulates the energy sharing activities by taking into account the energy prices agreed among all the prosumers and managing their energy supply in the community. This peer-to-peer energy trading mechanism results in sharing energy economically among the households and maximizing the consumption of power from distributed energy systems, while reducing the impact on utility grid.
Apart from managing the P2P energy sharing, it is required to handle the complexities in energy systems and uncertainty of renewable energy by monitoring and reporting the instantaneous energy flows in real time. In the proposed system, a blockchain-based advanced metering infrastructure is considered, which consists of various sensor nodes that collect energy usage data from the smart meters installed in all the houses and transmit it to the blockchain database system in the decentralized data and control center (DCC) by means of a two-way communication network in real-time, as shown in Figure  5. The energy information and transactions are securely stored in the blockchain ledger to track the electricity usage for analysis and management of energy systems without the aid of a central authority. It also enables secured access to authorized users, in this case prosumers and consumers, participating in the blockchain network. In order to regulate the peer-to-peer energy trading in our smart city model, a wireless sensor network is extensively used for monitoring the energy systems and disseminating the data in a timely manner to the base station. Since energy and lifetime are two major constraints in developing a sensor network, an optimization technique is proposed for the optimal selection of cluster heads and energy-efficient routing in the network that extends node lifetime and improves the performance of the network.
Initially, the sensor nodes are deployed in random locations within an area and each node is equipped with a finite energy supply. The base station is located outside the sensing area and it is grid powered, for which it has an unlimited supply of energy. In our proposed methodology, it is assumed that the WSN is a homogeneous network, the sensor nodes, and base station are stationary after deployment and all the nodes, except the sink node, have the same amount of initial energy and are left unattended once deployed. These nodes interact with each other to aggregate data and transmit it to the target nodes at regular intervals. Due to limited energy constraints, these nodes are grouped into clusters, where the most resourceful node in each cluster is selected as the cluster head (CH) for energy-efficient communication within the network, as shown in Figure 6. Each node in the network can operate as both sensors as well as a cluster head. A cluster head is selected based on the node's residual energy, number of neighbor nodes, and the Euclidean distance to the base station. The member nodes in a cluster transmit their data to the CH which then processes the information and forwards it to the base station directly or through multiple CHs by using the shortest path from the CH to the base station. This is carried out to minimize the cost of communication and the draining of energy during data transmission. In the proposed approach, an energy-efficient selection of the CH in a cluster of nodes is carried out by using the PSO algorithm, and the optimal route connecting the CHs to the base station is achieved by using the genetic algorithm.
The PSO algorithm is implemented by creating a cost function or objective function for the efficient selection of a cluster head. An ideal cluster head must have the highest residual energy, least average distance from the neighbor nodes, and minimum distance from the base station. So, the structure of the cost function is as follows: Cost function, f = α * dm + β * Er + γ * db (3) where, dm is the average Euclidean distance of a node from all other member nodes in a cluster, i.e., dm = (xixj) +(yiyj) , db is the distance from the base station and Er is the total residual energy of all alive member nodes divided by the residual energy of node in consideration. The residual energy of a node will be maximum if the factor [sum of residual energy of all memner nodes residual energy of current node ⁄ ] is minimum. α, β and γ are the constants having values equal to 0.38, 0.38 and 0.18 respectively. So, all the three factors sum-up to the structure of the cost function. The aim is to minimize the cost function that will give the optimal location of the cluster head which has the maximum residual energy and minimum distance from the member nodes and base station. The steps involved in the PSO algorithm are as follows: 1. Initialization of a set of particles and their position, velocity, and residual energy; 2. Initialization of PSO parameters such as swarm size, number of iterations, inertia weight, personal acceleration, and social acceleration coefficients; 3. Calculation of the cost function of each particle; 4. Finding the personal best and global best location; 5. Updating particles' position, velocity and energy lost in each iteration; 6. Updating the particle with the least value of cost function as the cluster head in every iteration; 7. Repeating steps 3 to 6 till all the nodes become dead.
After nominating the cluster heads, data packets are needed to be sent from the cluster head node to the base station directly or through a series of other cluster heads in the network. Therefore, the optimal route is needed to be determined to reduce the cost of communication of data packets across the nodes and balance the energy and data load in the network. For this, we have used the genetic algorithm to find the shortest route that connects a set of sensor nodes from the source node to the sink node and visits every node exactly once.
In order to implement the genetic algorithm, a set of points representing sensor nodes (CH) are randomly placed on a 2-D space. The Euclidean distance between consecutive nodes serves as the fitness function for the algorithm. A population of random solutions is generated in which each candidate solution or chromosome represents a route. The steps involved in the genetic algorithm to find the shortest route connecting all the points are as follows: 1. Initialization of population; 2. Calculation of fitness value of each chromosome; 3. Selection of best chromosomes as parents for the next generation using the roulette wheel mechanism; 4. Crossover of parent chromosomes; 5. Mutation of chromosomes; 6. Evaluating fitness of each chromosome in the new population; 7. Repeating steps 3 to 6 until the shortest path is established.
With the optimization of wireless sensor networks, we will be able to monitor the energy consumption in urban households in order to regulate decentralized energy trading within the community. To implement P2P energy trading in our model, prosumers are equipped with residential PV panels and energy storage systems to produce and store clean energy and supply the excess energy to local consumers by using a P2P energy trading platform. Therefore, a blockchain-based web application powered by smart contracts is developed, which enables houses to sell and purchase clean energy without any thirdparty intervention. It enables authorized users' easy access to the Ethereum blockchain network and provides each node with a copy of the ledger. Thus, secured communication between energy suppliers and buyers is achieved through the AMI and distributed ledger feature of the blockchain under a decentralized keyless signature scheme.
The blockchain web application is a prototype for decentralized trading systems that allows local consumers to purchase energy directly from prosumers with Ether cryptocurrency on the web app. A model of this web app is shown in Figure 7. The front end of the web app is built using the HTML5 and React library of JavaScript that creates an interactive user interface for the web app. The web3.js library is used to develop a website that can interact with the Ethereum blockchain. A smart contract, which contains a predefined set of rules and agreement between buyer and seller embedded into lines of code, is created using Solidity programming language and deployed on Ethereum. In this web app prototype, we have used "Ganache" that creates and runs a virtual Ethereum node on our PC and allows us to develop, deploy and test decentralized applications (or dApps) without spending any real money. The Ganache user interface contains a list of user accounts, each credited with a balance of 100 ETH, along with unique public and private key for each account, as shown in Figure 8. These accounts are considered as the Ethereum accounts of prosumers and consumers, which can be used for transactions in the web app. In order to access our dApp and interact with the Ganache blockchain from the web app, we have used the "MetaMask" browser extension that serves as an Ethereum wallet and works as a bridge between regular web browsers (such as Chrome, Firefox, etc.) and Ethereum blockchain. To connect MetaMask to our virtual Ethereum blockchain, all the Ganache accounts are imported into the MataMask wallet using the private key of each user, and the default Main Ethereum Network of MetaMask is changed to Localhost 7545.

Results
This section describes the experimental setup and various parameters of the proposed protocol and also demonstrates their results. The proposed method of WSN optimization is implemented in the MATLAB 2020b environment using a Windows 10-based PC with 2.71 GHz, Intel Core i5 processor, and 8 GB RAM. In order to implement the PSO algorithm for the optimal selection of a cluster head, the following parameter settings are considered; The inertia coefficient is varied from 0.9 to 0.3 over 30 iterations. The particles explore the search landscape, optimizing the objective function for finding the best location of cluster head and in every iteration, the best particle and its corresponding cost function value are obtained, as shown in Figure 9. The node nearest to the optimal location of the best particle is selected as the cluster head, which has the highest residual energy, maximum number of neighbor nodes, and the smallest distance from the base station. Due to energy dissipation by both cluster head and non-cluster head nodes caused by the transmission of data, the total energy consumed by the alive nodes gradually decreases in every round, as shown in Figure 10. It is evident from the above results that with a swarm size of 10 particles and 30 iterations, all the nodes die, or the total residual energy becomes zero on iteration number 25. In contrast to the EEUC algorithm which does not consider the node's residual energy during the cluster head selection phase, the proposed PSO technique gives better results, since EEUC's non-uniform clustering technique leads to the premature death of cluster head nodes present far away as well as near to the sink node due to the high communication cost and insufficient energy to forward data, which affects the overall network lifecycle. The proposed PSO algorithm selects a cluster head node in an energy-efficient manner that can improve the quality of network monitoring and extend the network lifespan.
After selecting the cluster head nodes using the PSO algorithm approach, an optimal path is established connecting all the CH nodes to the base station for faster transmission of data from sending node to receiving node. This is carried out by using the genetic algorithm to find the shortest route in the network. To implement this algorithm, initially, a group of 20 sensor nodes is randomly placed on a 50 × 50 sq. unit area, assuming each node except the last node is a cluster head, as shown in Figure 11. The genetic algorithm improves the individual solutions in every generation by using selection, crossover, and mutation operators and creates a sequence of new populations. The algorithm thus establishes the shortest route in the network, as shown in Figure  12.  After successfully optimizing the wireless sensor networks, P2P energy trading can be carried out between households by implementing a real-time decentralized application using the blockchain-based web app. The user interface of our web application is shown in Figure 14. In this application, it is assumed that the average energy produced by a single PV prosumer on a good day of 5 h of direct sunlight is 38 kW-h. As per the survey by the US Energy Information Administration (EIA) in 2019, the cost of 1 kW-h of electricity is USD 0.14 (i.e., 0.0000938 ETH) for households and their average power consumption in a day is 29 kW-h. Based on this information and our assumption, the energy pricings and supply are produced accordingly on this web app. Using this web application, prosumers can sell clean energy by adding the price of electricity supplied by them in the given field and selling it on the web app by clicking on the "sell" button. A block will be created containing the digital signature of the seller and the energy information in the Ganache blockchain and consequently a record containing the electricity price in Ether and the public key of the owner will be added in the web app. A "buy" button will be added across each record for other users to buy electricity directly from the web app. As soon as a consumer purchases energy from a prosumer, the public key of the seller will change into the consumer's public key, which indicates a transfer of ownership of energy from prosumer to consumer. The "buy" button is the payment link that will redirect to the MetaMask wallet when clicked by respective consumers due to contract interaction, where they have to sign their transactions in order to confirm payment of Ethers. Thus, blocks with encrypted transaction details will be created and added to Ganache blockchain and the red "buy" buttons will automatically change to green "sold" marks, as shown in Figure 15, which signifies the successful transaction of Ethers from the consumer's account to the seller's account. The smart contract is written in a way that restricts sellers from buying their own energy; it will throw a transaction error in MetaMask which means the block is discarded and the transaction is not successful. We can view a list of transactions in the form of blocks wrapped with a transaction hash in the Ganache blockchain, as shown in Figure 16. With this method, we can securely store the history of transactions, which is beneficial for audit. We can also implement the proposed model on a public blockchain network such as the "Kovan test network" where the households can pay real Ethers for grid energy transactions directly through the web app if they are connected to a public blockchain network.

Discussion
It is evident from the above work on WSN optimization that the framework of both the GA and the PSO is similar, in that they initiate with a population of random solutions, explore and exploit the search space with specific parameters and estimate the global optimum for a given optimization problem. The control parameters of each algorithm depend on the nature of a problem and thus, selecting their appropriate values can have a great impact on the performance of the algorithms. In our proposed methodology, the population size in the GA should not be very large since it can slow down the algorithm, increasing the computational time significantly. The diversity of the population should be maintained in order to avoid premature convergence. For this, the mutation rate should be kept small to search locally around the promising regions found by the crossover operator without affecting the convergence of GA. Similarly, choosing appropriate values for the initial and final inertia weight in the PSO can tune its global and local searchability. Additionally, smaller values of acceleration constants c1 and c2 may result in the termination of the algorithm before finding a good solution and larger values can increase the acceleration, resulting in the abrupt movement of particles over the search space. So, the summation of c1 and c2 should be maintained less than or equal to 4 for the smooth trajectories of particles. Therefore, the parameters in these stochastic algorithms should be set carefully. Even though the genetic algorithm is easy to implement and uses less computational resources, it might not give the best results in the case of complex problems. In the case of PSO, the algorithm is simple, efficient, and robust, however, it is computationally expensive as it consumes a lot of memory, which can limit its usage in high-speed applications. Based on these limitations, future work can be carried out by developing more efficient computational intelligence strategies that can improve data aggregation and transmission and prolong network lifetime in heterogeneous sensor networks.
From the proposed work on blockchain technology in smart grid applications, it is seen that the use of decentralized energy trading platform ensures data security and immutability and offers tamper-proof transactions. The use of smart contracts in this system makes end-to-end power delivery efficient and simpler by making executed trades automatically validated and recorded in the blockchain, thereby significantly reducing delays and cost of the settlement. It empowers consumers with transparency and flexibility over transactions by eliminating intermediaries and third parties and enables prosumers to actively participate in the energy market. However, the optimal usage of blockchain technology is prevented due to its nascent stage of evolution and experimental stage of blockchain-based projects. Hence, future work can be carried out by increasing the scalability in the blockchain, introducing incentive mechanisms for using blockchain-based applications, encouraging decentralized power generation, and making this technology commercially viable.

Conclusions
The main goal of a smart city is to improve the quality of life of urban residents by making better utilization of resources while reducing energy usage and operational costs. In this work, an optimized and decentralized energy model for smart cities is presented that deals with the optimization of wireless sensor networks in the smart grid and facilitates peer-to-peer energy sharing among prosumers in a decentralized energy trading system. A bio-inspired approach for energy-efficient routing in a wireless sensor network is also realized by using particle swarm optimization and the genetic algorithm, which can greatly minimize the energy consumption by sensor nodes and extend network lifetime. This also helps in disseminating the data in a timely manner to the base station by finding the shortest path connecting the cluster head nodes in the network for data transmission. The privacy of a massive amount of data and security of communication networks is achieved by integrating blockchain technology with the smart grid. With the aid of smart contracts, energy transactions are maintained securely on the blockchain in a consensus manner. The proposed model for a peer-to-peer energy trading system not only promotes the sustainable use of energy but also encourages the use of renewable energy sources in microgrids.