Abstract
Nowadays, smart applications are increasing day by day to improve the standard of living in smart cities. A modern-day smart city is characterized by the presence of numerous smart Information and Communication Technology (ICT)-enabled services such as automated healthcare, automatic building monitoring, home automation, smart parking, traffic management, data security, among others. Such cities employ multitudes of Internet of Things (IoT) devices to collect and share data between trusted users by means of a centralized intermediary for monitoring and control of the myriad automatic activities. However, a centralized intermediary is plagued by issues such as single point of failure, risk of data loss, man-in-the-middle attack, and so forth. Blockchain-based smart contracts for automated control in smart cities provide a decentralized and secure alternative. In this paper, an Ethereum based system design for decentralized applications in smart cities has been proposed that enables systems to share data without an intermediary between trusted and non-trusted stakeholders using Ethereum based self-executing contracts. Such contracts allow automated multi-step workflows for smart applications. Two use cases, have been considered namely smart healthcare and smart building monitoring, as proof of stake of the proposed Ethereum based contract. The performance of the proposed scheme for these use cases has been presented with Keccack 256 transaction hash, the total number of transactions, gas consumed by each contract. Such an attempt is a worthwhile addition to state of the art as evident from the results presented herein. The modeling simulation and analysis of hashing power shows that for hashing power greater than 55% the probability of double spending attack reaches to 42% maximum. So it is concluded that the probability of double spending increases with the increase of transaction values.
Introduction
Future urban communities are required to be more secure, progressive, comfortable, interactive, and smart. Such future urban communities shall be highly integrated and dependent on smart city services. Generally, in smart cities, a system of sensors, cameras, remote gadgets, client-server structures are the key foundation for a convenient, quick, and effective handling of the city resources. Besides the utilization of conventional energy resources combined with green and clean resources in a smart, optimized methodology leads to reduced pollution [30].
A smart city’s constituent services include smart healthcare, safe transport, smart roads, smart parking, smart environment with less pollution, smart building with automated features of monitoring and controlling the smart devices, location tracking, and monitoring, smart agriculture, and so forth. The growth in these applications have been enabled by advances in the Internet of things (IoT) that also allows the city resources to be further utilized [17,19]. The IoT devices collect, generate, and process data from smart cities. However, widespread use of IoT devices in smart cities poses a security threat for different levels starting from cyber attacks to privacy and security threats for users [13,16] . The data collected at IoT devices can be breached, tampered with, or forged. Hence, IoT data requires authentication, privacy, security, and a countermeasure towards attacks [12,21].
Blockchain technology can provide a practical solution that can be implemented for data security of IoT devices in smart cities with consensus mechanisms and digital signatures [5,11,31]. Blockchain provides complete security solutions to make a transaction between untrusted nodes or parties. Blockchain technology combines the advantages of decentralized, distributed ledger, reduced transaction cost, faster transaction settlement, transparency, cryptographic property, enhanced security, and immutability to ensure secured transaction communication. IoT devices interconnect among themselves through private and public networks and can be controlled remotely [26]. Smart contracts are self-executing workflow scripts that can operate in an automated, secure, and verifiable manner. Moreover, the Blockchain implementation in smart cities is suitable because of its independent nature concerning heterogeneous communication protocols such as Zigbee, Wifi, Bluetooth, etc. [20]. This makes blockchains enticing for future researchers and developers working in the Internet of Things (IoT) domain.
The unique contributions of this paper include:
Proposing a distributed, decentralized framework for smart cities that use Ethereum based public Blockchain technique to perform energy control in a building and remote healthcare services for patients in an easy, transparent, immutable, and audit-able fashion. Such a framework eliminates the need for human intervention and makes it easy for smart city authorities and other intended users to keep track of transactions by employing solidity smart contract, generated Application Binary Interface (ABI), and secure Inter Planetary File System (IPFS).
Double-spending behaviour of proposed PoS based Ethereum application is simulated through a network simulator (NS-3), and the evaluated result shows that the increase of the hash rate of an attacker also increases the number of double-spending problems.
Implementation of a basic Blockchain-enabled smart city prototype that uses Truffle for enacting client communications. The proposed framework has a higher fault-tolerant capability, higher transaction verification speed (>110sec), and has a good scalability feature.
As already discussed, such an attempt hugely adds to the credibility of the performance analysis. In addition, this paper also implemented a realistic scenario for simulating Blockchain based transactions.
This is done by creating individual accounts for each smart building users and for each patient with in this remote healthcare system having unique account address and private key. Ganache is employed for realistic transaction processing with tracing capacity for transactions and their hashes.
The rest of this paper is organized as follows: Section II presents related background. Section III describes the research works smart cities. Section IV presents the proposed framework model and architecture for smart cities. Section V analyzes and discusses experimental implementation and validation. Section VI presents the results of this paper. Finally section VII presents the conclusion and future work.
Background
The background related to Blockchain and Ethereum components are presented in subsequent subsections.
Blockchain
Blockchain Technology is a distributed public ledger of all transactions among nodes. Each verified transaction is accumulated as a block. Each block consists of a variable number of verified transactions. The consensus technique is to confirm the source node to be trusted. Blockchain uses a cryptographic method to send secret information so that the target node can decrypt the data. In the simplest of terms, a blockchain is a time-stamped series of immutable records of data that is managed by a cluster of computers not owned by any single entity. Each of these blocks of data (i.e., block) is secured and bound to each other using cryptographic principles (i.e., chain). The blockchain network has no central authority, and it is a democratized system [2,14].
Ethereum and smart contract
Ethereum is a decentralized, open-source, and end-to-end smart contract cryptocurrency. Ether (ETH) is the digital currency for Ethereum. Proof of Work (POW) or Proof of Stake (PoS) consensus algorithm is used in the Ethereum framework. Nowadays, Ethereum is one of the most popular cryptocurrencies after Bitcoin. The trusted cryptocurrency is installed on top of any decentralized peer-to-peer (P2P) application [6,29]. It supports smart city applications. Essential components of Ethereum are
Whisper: This protocol is used for messaging. It is a decentralized chat technique that operates as per P2P protocol.
EVM: Ethereum virtual machine converts the smart contract coding to bytecode, taking consensus mechanism into account.
Inter Planetary File System (IPFS): This protocol is designed for data storage and sharing [8].
Gas: This is a virtual fuel for the ethereum network. Gas is used while validating transactions in a permission-less Ethereum network [21].
Ethereum was created by Vitalik Buterin, formalized by Gavin Wood, and crowdfunded to kick-start development. Their vision was to introduce a global computer that can store and execute programs. These programs are called smart contracts as the conditions of an agreement between two or more parties are enforced using the same consensus protocol that secures the Blockchain. Smart contracts are computer programs that are stored on the Blockchain and executed by Ethereum’s peer-to-peer network. This concept was first envisioned by Szabo back in 1994, and he provided the following definition [7]: “A smart contract is a computerized transaction protocol that executes the terms of a contract [3,9].
Error handling
Handling errors in solidity language was done by throw( ) and catch( ) methods. It also supported checkuser( ) function to handle errors. But all these functions consume a large amount of gases. So it has been deprecated now. In this paper, we have used efficient methods for error handling by inserting functions such as e.g., assert( ), require( ), and revert( ). These functions are in the current version of solidity and have more refined and cleaner syntax [3].
Double Spending attack and effect of hash power
The core behind the double-spending problem in a distributed platform is synchronization. Spending the same digital token, such as Ethereum, Bitcoin, and so forth, more than once is called double-spending. Transactions in an Ethereum network are included as blocks that are broadcasted to the entire network. To prevent a double-spending attack that relies on synchronous communication, a hashing power mechanism is used.
Related work
Research literature survey on blockchain in general and smart city based on smart contracts, in particular, is limited to only last few years because writing smart contract with solidity programming on ethereum platform has started recently and the development still goes on. H. Hasan [10] has discussed an ethereum blockchain-based solution for efficiently performing the supply chain operation through a smart contract that helps track the products. Shuai Zhang et al. [32] investigated issues related to the elderly patient’s health monitoring and have designed the smart home to help them by providing a reminder to complete their daily activities. A decision support system was used to decide the tasks. M. Moniruzzaman. [15] proposed a new architecture supported to perform transactions inside a smart home and shows how a middleman’s need becomes zero by using blockchain smart contracts. Similarly, A. Suliman et al. [25] proposed an Ethereum based blockchain to make an automatic payment system for IoT data without involving any third party. The output of the ethereum transaction and smart contracts are also presented. Another work by S. Agarwal et al. [1] presents a taxonomy for blockchain-based smart things and discusses the security based on application such as financial, transportation, energy trading healthcare, and IoT [3,4,27]. M. Shen et al. [22] presented a support vector machine training by which the data collected at IoT devices can share data by preserving privacy. R. Chen et al. [7] designed a blockchain-based provable data possession method that can handle decentralization data possession by using a multi replica storage technique. The authors in [19] have proposed a hybrid architecture for blockchain and Software-defined networks (SDN) based smart cities with two parts, i.e., core part and edge part. The authors have also simulated their model to get the various performance metrics such as hash rate vs. difficulty, average time and block size, etc. They have collected the data set from litecoinpool.org and mined the blocks. Abdur Rahman et al. [18] proposed the safety system based on blockchain to facilitate stable data exchange in a smart city. Incorporating blockchain technologies with devices in a smart city creates a shared forum for safe connectivity among all users in a distributed system. Developed the mobile edge computing (MEC) distributed economy program that uses blockchain and off-chain systems to store unchanging documents. Meng Shen et al. [23] suggested the secure support vector machine (SVM), privacy-preserving SVM training strategy over blockchain encrypted IoT data to bridge the difference between ideal expectations and limitations. The blockchain strategies enable creating a safe and transparent network for information exchange between various service providers, which encrypts and records IoT data on a shared database. Paillier used to create effective and exact privacy security that preserves the SVM learning algorithm. Homomorphic cryptosystem has been used to secure SVM performance and health.
Jayne Vora et al. [28] suggested the blockchain-based computing capacity system and electronic health records (EHR) managing. In turn, doctors, clinicians, and third parties have reliable and convenient access to medical records, while patient data protected confidentiality. The main objective to examine the new system addressed patients, providers, and third party’s needs and explained the structure preserves the protection and privacy issues of healthcare 4.0. Singh et al. [24] conducted an empirical Blockchain performance measurement for an healthcare system in a single host, multiple organizations, and SOLO orderer with varying configurations such as block size, network traffic, transaction per second, latency, memory and CPU usage for a healthcare application by using Hyperledger Fabric 1.4, composer and caliper benchmarking tool. Most of the researcher’s work has been published for IoT-based smart cities to the best of our knowledge. Still, there is a need for the design of a complete security solution and automatic blockchain transaction without the middleman’s intervention.
Proposed framework for smart cities
In this section a Ethereum based public Blockchain storing the transactions in a smart city has been proposed. Two use cases has been considered, that are smart building and smart healthcare. The proposed model is given in Fig. 1, which depicts the entire ecosystem and technologies used in smart cities. These smart contracts message themselves by whisper and store the data in IPFS. In our case, the smart contracts monitors and control with the help of events triggered, and an error occurred. A Smart building contains sensors, power meters, plug load controller, lighting load controller, Heating Ventilation and Air Conditioning (HVAC) load controller to optimize energy consumption. Similarly, the temperature, humidity, pressure can be measured both indoor and outdoor to effectively take the decisions. The maximum and minimum recorded temperature in a city helps us to compare many things. The thermostat in a room can be remotely on or off based on the angular velocity measured through a motion sensor. Similarly, we have designed events and corresponding error violation rules for the smart remote healthcare system in Fig. 2. A public (Ethereum) blockchain-based solution for the smart remote healthcare monitoring where IoT data such as body temperature, heart rate, pulse rate, etc., are recorded in a blockchain. In this paper, two algorithms are used for smart cities. Algorithm 1 is used to automate the process of controlling the energy transactions in a building and alerting the building owner whenever there is any violation. We have used methods to collect the data from the appliances such as a thermostat, power meter, light load, HVAC load, etc. Algorithms in terms of smart contracts are auto executed, which are based on the Ethereum ledger data. These methods send the control signals to toggle automatically ON or OFF of the above-mentioned appliances to participate in a smart city. The primary purpose of this contract is no involvement of a third party. Algorithm 2 is used in remote healthcare to record, track, and alerts through a message whenever there is any critical health condition. In this algorithm, we have considered three remote services for the patients such as tele medicine, emergency remote doctor, and call for an ambulance. Based on the transaction values recorded for a remote patient, these services are offered.

Proposed Ethereum based system design for decentralized application in smart cities.

Smart healthcare system.
Smart cities can be connected distributively and decentralized way. Information related to buildings, remote healthcare, parking areas, safety transport, supply chain systems can be collected in blocks. Table 1 shows the indicators to evaluate a smart city. Blockchain-based smart cities can efficiently regulate smart devices.

Automated control system for smart building

Automated control system for remote healthcare
Smart city evaluation criteria

Ethereum based decentralized application in smart cities.
In Fig. 3, the entire ecosystem and the technologies that we can use for this decentralized application. In addition to all this, we can use Whisper for peer-to-peer communication between different parties. Even notifications can be sent using this protocol. An Ethereum Blockchain implements a smart contract on an Ethereum account address or by an externally owned accounts. These accounts have been generated by ethereum clients and other services like Metamask, truffle, ganache, Mist browser, and web3.js. These account addresses are limited for web3.js and Metamask, whereas we can create ten addresses with each 100 ether as fuel for transaction cost. Other security tools in smart cities in a distributed system environment work among the trusted intermediary, who store, manage and access the data. But our Ethereum and Blockchain-based automated smart cities empower the end-users to regulate each transaction without any intermediary. The unique benefits of this scheme over other security tools in smart cities can be summarized as follows – (1) A solution for decentralized and distributed storage of smart city files in a secured way via Inter Planetary File System (IPFS) and accessing the file through localhost: port number 3000 and generated hash values. (2) It completely eliminates any third-party involvement in transactions. (3) Such scheme deals with transaction data that are encrypted and hashed in the block and accessible to those involved in the network.
We have used the Proof of stake (PoS) consensus algorithm, which will handle malicious nodes of up to 55 percent. The blockchain performance using PoS is constrained to eliminate bifurcations and wait for appropriate blocks to validate everything. The delegated witnesses build blocks and validate data transfer in the PoS ledger.
In this section we have discussed implementation details of our high level smart building and healthcare application developed on Ethereum platform.
Environment setup
For setting of Ethereum for local environment and to execute the smart city use-cases these steps are followed.
Setting Ethereum on local environment. Creation of Genesis block. Creation of accounts Installing Ethereum wallets Installing smart contracts in the Ethereum wallet.
Installing Ethereum wallets and creation of accounts
Ethereum wallet provides an graphical interface to manage accounts and execute smart contracts. Ganache is a Blockchain-based software used to create Ethereum accounts and deploy the smart contract on those addresses. After installation the wallets are connected to the local instances. Accounts are created for the users of smart city application.
Creating, deployment and executing of smart contracts for smart city application
In this subsection we have implemented and deployed smart contract for two use cases. The contracts are designed and developed using Solidity language. To compile the contract in the Solidity code first we specify the version name i.e. pragma solidity version name. The proposed smart contract was implemented and tested by utilizing Remix IDE found at
Invoking contracts through web application
Decentralized application (Dapp) comprises of front-end and back-end code. We have implemented the back-end code for smart city using solidity. To interact with the smart city contract and Blockchain application, front-end framework Truffle has been installed. Truffle provides a development and testing environments for building decentralized application. The smart building and remote healthcare contracts has been called through Mist browser to see user interface. Cross verification status of the transaction generated and committed in the block to our local Blockchain network has been done. While simulating the local clients, we used testrpc Node.js Ethereum based client. We have conducted an experiment on a public testnet with Ropsten and Ganache decentralized apps, which interact with one another through the internet. With the help of the NodeJS package and Ganache (previously Testrpc), we created the Ethereum network on a single computer. Then we wrote programs for Ethereum Blockchain and paid for their deployment transaction usage cost in Gas. For Testnet free Ethers, we used the Ropsten Faucet. This cost also prohibits in terms of network overuse. Testnets are the essential tools for EVM development. They provide an easy platform for Ethereum software testing and provide a safety layer on which the Mainnet can be launched as experiments. Perspectives identified with the full framework testing and usage of the Message Queue Telemetry Transport (MQTT) authentication of users and data generated and exchanged through sensors, IoT devices are left for future work.
Experimentation, results and discussion
The implementation of the proposed framework was carried out for both the use cases, namely smart building and remote healthcare system, as described in the previous section. In this section, experiments carried out for testing the effectiveness of smart contracts are presented for those use cases. A powerful open source tool such as Remix is used for testing smart contracts. It is written in JavaScript and independent of web browser. Testing, debugging and deployments is performed in Remix integrated development environments. Smart contract decides the user account associated with Ethereum state by predefined rules. To manage the identity of smart city users, the Metamask tool is used. The traceability feature of transactions are implemented through Truffle platform. The Dapp is an front end application created from the application binary interface code to interact with the Blockchain network. Verification of all transactions is stored in this work with the help of etherscan. This allows the smart city users to lookup, confirm and validate transaction from user sides.
Smart contract execution and analysis of gas consumed
The contract smart building has six participating entities namely HVAC Load ( ), thermostat ( ), lightload ( ), powermeter( ), temperature( ), and CO2level( ). Each of these entities have individual Ethereum addresses and can participate whenever they are called in the contract. Specific restrictions for calling the methods are set with the help of modifiers. Functions such as temperature ( ) can be called by anybody where as methods like HVAC Load ( ), and lightload ( ) can only be called by building owners. Similarly for the proposed remote healthcare system, call for participants such as emergency doctor,ambulance and remote doctor are restricted to patients only.

Output in case of a successful deployment of smart building.

Output in case of a event HVAC load violation.
The Contract is deployed in two Ethereum addresses 0x10f1BACf1aC27d15C9A092024a159D9646 0DCe23 and 0xaBE583a4d83EF02BAGA2e4E2ede2764306A 36Eca which are created by Ganache. The Etherscan website is used to see the transaction details such as transaction hash, time of creation, from account address to address, transaction cost in Wei, Gas limit, Gas used by transaction, nonce, and input data. Ganache is used to shows the output when the contract is deployed, and the account address is created. The output includes the status of a transaction, transaction hash, account address, transaction cost, decoded input, output, log values, etc. Each transaction, such as providing a lock code to open the door in a smart building, costs some value called Gas. The overall model is designed in the Remix IDE platform, Keccak 256 hashing. Information related to the buildings and healthcare is accessed or transferred securely to the intended users. Additionally, the proposed system’s traceability feature monitors detailed information on patient health from temperature to hemoglobin. Healthcare reports, building information can be connected distributively and decentralized way. The experimental work and result and ABI code have been carried out for proposed automated smart cities. The ABI generated by smart building and healthcare solidity code through a Remix IDE is a way of interactions among the contracts from outside and contract-to-contract. The ABI follows the encoding technique by selecting the subcontract function and generates the Keccak (SHA-3) hash signature, which is a canonical expression of function name with parameters. The contracts are strongly typed and call the subcontracts at compile time. These ABIs are used to generate Blockchain decentralized applications. Figure 4 and Fig. 5 illustrate the Ethereum Blockchain’s output for successful deployment and violations that occurred for smart building.
Ethereum Blockchain secured hashing transactions
We have deployed both the contracts on Ropsten and Ganache testnet. The addresses of the smart contracts are given in Table 2. The ABI’s are saved in JSON. To validate our result, we have created the following JavaScript files such as web3.js, ipfs.js, storehash.js, app.js, and index.js. Finally, we accessed our contract through localhost:3000 port. We found that by uploading any file, we get the generated hash, and access can be done via the IPFS gateway. In order to confirm the transaction, the Metamask request has been accepted. This work describes how a file can be taken from a smart city user and uploaded to the IPFS by invoking an Ethereum based smart contract. The hash of the file is being stored on Ethereum. Analysis of Gas consumed, transaction hash, and time required concerning complete the transaction are visible on the etherscan tool. Table 2 depicts the detailed analysis. Smart building and remote healthcare monitoring is an internet-based smart city application that is shareable to authorized stakeholders such as building owners, doctors, specialists, and remote patients. One of the essential parameters in the smart building is temperature, humidity, CO2 in ppm. Apart from these parameters, we have considered other main parameters, such as power meters, plug load controllers, lighting load controllers, heating, ventilation, and air conditioning (HVAC) load controllers. These controllers, if effectively controlled and regulated, can result in significant energy-savings. Blockchain-based smart cities can resolve individuals’ need to retrieve, trace, handle, share their building and health-related information, which is immutable. The blockchain-based system is a confidential environment that acts as a communication hub between building owners, municipality officers, doctors, patients, and other subscribers. Solidity is used for the smart contract in Ethereum. Figures 6 and 7 depict the message sequence diagram when a transaction occurs successfully and with a violation. The smart building contract contains other subcontracts such as HVAC load, light load, plug load, power meter, water meter, temperature, and humidity. Similarly, the healthcare contracts also contain the subcontract as a remote doctor, doctors at hospitals, and ambulance as shown in Fig. 8. As per the threshold value, the contracts and subcontracts give violation error and alert messages to users in a smart city.The attack on double-spending eventually works when the malicious computing capacity is above 55 percent of the total network. Double spending occurs when the hashing of a transaction takes much time.

Sequence diagram with no violation.

Sequence diagram with violation.

List of smart contracts proposed for smart cities.

Analysis of hashing power and double-spending.
In this analysis, we have evaluated number of double-spending attacks against the hashing power by varying between 30% and 60% for each transaction value. The experiment was repeated thrice with transaction values of 15, 25, and 35, as depicted in the Fig. 9. It is observed that for hashing power greater than 55%, the count of double-spending attacks increased up to 42% highest. The count of double-spending attacks increases with the increase of transaction values. We obtained the double-spending values 16, 30, and 34 with respect to transaction values 15, 25 and 35 respectively. It can be observed that for transaction value 15 and hashing power of 0.3, the number of double-spending attacks is 12. Whereas for the same transaction value with 0.6 hashing power, the number of double-spending attacks is 16. Similarly, for transaction values 25 and 35 with specified hashing power, we calculated the number of double-spending attacks. Finally it was concluded that as hashing power of attacker increases, the number of double spending attacks also increases. By increasing value of the attacker’s hash rate Blockchain security suffers.
Conclusion
The application of Blockchain in smart cities can have many advantages such as tracking older transactions, process automation, and immutability. In this paper, we have proposed and implemented a smart city application based on healthcare and an automated home system, which leverages the Ethereum blockchain to store transactions on a decentralized ledger. Our proposed framework uses the Ethereum smart contracts to govern and manage interaction between the smart city authorities, smart building owners, and remote assistance for patients. We provided a detailed analyses of transaction cost in terms of Gas and double spending behaviour with respect to hash values. Although the proposed design is for single- echelon systems, it can also be applied for multi-echelon system. In future, real time implementation with Rasberry Pi board connected to various sensors is envisioned with testing contingencies. We further aim to run our experiment globally by using Mainnet.
