<<

DEGREE PROJECT IN COMPUTER SCIENCE AND ENGINEERING, SECOND CYCLE, 30 CREDITS STOCKHOLM, SWEDEN 2018

P2P Electricity transaction between DERs by Technology

RUOGU LI

KTH ROYAL INSTITUTE OF TECHNOLOGY SCHOOL OF ELECTRICAL ENGINEERING AND COMPUTER SCIENCE KTH Royal Institute of Technology

School of Electrical Engineering and Computer Science

Master’ Thesis in Computer Science and Computer Engineering P2P Electricity transaction between DERs by Blockchain Technology Author: Ruogu Liu Supervisors: Anne Håkansson Xue Wang

Examiner: Prof.Mihhail Matskin, KTH, Sweden

ii Abstract

The popularity of blockchain technologies increases with a significant rise in the price of in 2017, which drew much attention in the academia and industry to research and implement new application or new blockchain technology. Many new have emerged over the last year in a broad spectrum of sectors and use cases including IOT, Energy, Finance, Real estate, Entertainment, etc. Despite many exciting research and applications have been done, there are still many areas worth investigating, and implementation of the blockchain based distributed application are still facing much uncertainty and challenging since blockchain is still an emerging technology. Meanwhile, the energy sector is under a transition to be digitalized and more distributed. A global technology revolution has disrupted the conventional centralized power system with distributed resources and technologies, like photovoltaic units (PV), batteries, electric mobilities, etc. The citizens then have control of their generation and consumption profiles. The purpose of this master thesis is to explore existing blockchain technology, and smart contracts such as IOTA, NEO, Tobalaba, which can be adapted in the energy sector. Within this thesis, blockchain and the is proposed as a way of building distributed applications for a p2p transaction use case in the energy asset management platform. A design science research methodology is applied for the artifact development and evaluation for the research result. The design was implemented on Ethereum and tested on Tobalaba public network with ether and GAS. The evaluation shows the artifact for the p2p transaction in energy asset man- agement platform fulfill the completeness, and correctness of the design requirement. The result of the performance test on Tobalaba networks shows a correlation between GAS consumption and transaction time.

Keywords— Blockchain, Peer-to-peer, Energy System, Ethereum, Tobalaba, Transaction, Energy asset

Referat

Den popularitet av blockchain-tekniker ökar med en signifikant ökning av kryp- tokurrencyprisen år 2017, vilket gav stor uppmårksamhet i akademin och indus- trin för att undersöka och implementera applikation eller ny blockchain-teknik. Många nya blockblock har uppstått under det senaste året inom ett brett spektrum av sektorer och anvånder fall som IOT, energi, finans, fastigheter, underhållning etc. Pågrund av många spånnande undersökningar och applikationer finns det fortfarande många områden som år vårda att undersöka, och implementeringen av den blockchain- baserade distribuerade applikationen år fortfarande konfronterad med stor osåkerhet och utmanande eftersom blockchain fortfarande år en uppkommande teknik. Under tiden år energisektorn under en övergång att bli digitaliserad och mer distribuerad. En global teknologirevolution har stört det konventionella centraliserade kraftsys- temet med distribuerade resurser och teknologier, såsom fotovoltaiska enheter (PV), batterier, elektrisk rörlighet etc. Medborgarna har dåkontroll över sina generations- och konsumtionsprofiler. Den hår inriktningen år att undersöka befintliga blockchainteknologi och smarta kontrakt som IOTA, NEO, Ethereum Tobalaba, som kan anpassas inom energisek- torn. Inom denna avhandling har blockchain och the slimme kontrakt föreslagits som en metod för byggfördelade applikationer för en p2p-transaktionsanvåndning i energiförvaltningsplattformen. En designvetenskaplig forskningsmetodik anvånds för artefaktutveckling och utvårdering av forskningsresultatet. Designen genom- fördes påEthereum och testades påTobalabas entliga nåtverk med eter och gas. Utvårderingen visar att artefakt för p2p-transaktionen i plattformen för energiför- valtning hanterar designkravets fullståndighet och korrekthet. Resultatet av re- sultatprøven påTobalaba-nåtverket visar en koppling mellan GAS-konsumtion och transaktionstid. Keywords— Blockchain, peer-to-peer, energisystem, Ethereum, Tobalaba, Transaktion, Energi tillgång

Acknowledgment

I am deeply thankful to my examiner Prof.Mihhail Matskin and supervisor Anne Håkansson. Without their guidance, this thesis would not have been possible. I would also like to thank my current company Power2U and my co-supervisor Xue Wang and Dr.Arshad Saleem at Power2U that provide me with this research project. Special thanks to the support of -regio project, under the management of EU Era-net program.

Stockholm, 15th. December 2018 Ruogu Liu

Contents

List of Figures xi

List of Tables xiii

List of Glossary xiii

1. Introduction 3 1.1. Background ...... 3 1.2. Problem...... 5 1.3. Purpose and Goal ...... 6 1.4. Ethics and Sustainability ...... 6 1.5. Contributions ...... 7 1.6. Choice of Methodology ...... 8 1.7. Outline ...... 8

2. Technical Background 11 2.1. Cryptography ...... 11 2.1.1. Hashing Functions ...... 11 2.1.2. Digital Signatures ...... 12 2.1.3. MerkleTrees ...... 13 2.1.4. Consensus Algorithm ...... 14 2.2. Blockchain Technology ...... 15 2.2.1. NEO ...... 16 2.2.2. IOTA ...... 18 2.2.3. Ethereum ...... 20 2.2.4. Powerledger ...... 22 2.2.5. Tobalaba ...... 23 2.3. Related Research ...... 24 2.3.1. ADMM Optimization ...... 24 2.3.2. IOTA Micro Transaction ...... 25

3. Implementation 27 3.1. System Description and Requirements Analysis ...... 27 3.1.1. System Analysis ...... 28 3.1.2. Design on the Smart Contract ...... 29 3.2. Implementation of Smart Contract on Energy Web UI ...... 32 3.2.1. Deployment on EWF web UI ...... 32 Contents

3.2.2. Execute contract on EWF web UI ...... 32

4. Result and Evaluation 37 4.1. Evaluation ...... 37 4.2. Result ...... 38 4.2.1. Descriptive analysis ...... 38 4.2.2. Functional testing ...... 38 4.2.3. Performance analysis ...... 40 4.2.4. Outcome ...... 43

5. Conclusion 45 5.1. Discussion...... 45 5.2. Limitations of this work ...... 45 5.3. Futurework...... 46

Bibliography 48

Appendices 51

A. Source code Ethereum 53

B. Source code NEO 57

List of Figures

1.1. Price based on Coindesk ...... 4 1.2. The Blockchian Graph ...... 4 1.3. Energy Trading Rrice with DSO and Retailer in Sweden. Graph and Data provided by Xue Wang, Power2U AB ...... 7 1.4. Design Science Approach Overview Retrieved and Adapted from Hvner, 2004 ...... 8

2.1. Digital Signature in Bitcoin...... 12 2.2. MerkleTree...... 14 2.3. NEO Virtual Machine ...... 16 2.4. Tangles and Bundles in IOTA Network ...... 18 2.5. Transaction using IOTA Flash Channel ...... 19 2.6. Comparison of Blockchain Technologies: Ethereum, NEO, IOTA . . 20 2.7. The Ethereum Network and its Interaction with Metamask...... 21 2.8. Ethereum based Dapp architecture and its Interaction with web3 lib and front-end application...... 21 2.9. Technical Layer of Power (15) ...... 22 2.10. Two Type of "token" issued by Power Ledger Platform...... 23 2.11. Comparison of an ecient market in which the optimal quantity * is cleared at price P(Q*), and a market operated by a monopoly who is able to charge separate prices for generation and consumption.(4) 25 2.12. IOTA charger Proof of Concept by ElaadNL (20) ...... 26

3.1. P2p Transaction for Smart Energy Asset Management System . . . 28 3.2. Smart Contract Application Interface implemented on NEO smart contract.https://github.com/liuruogu/NeoEnergyTransaction . . . . 29 3.3. Overview of Dierent Electricity and their Interactions with the Blockchain and System of Smart Contracts which exist on the Blockchain. 30 3.4. Create the Account on EWF web UI ...... 33 3.5. Initiate a Contract ...... 33 3.6. Deploy Smart Contract on EWF web UI...... 34 3.7. Deployed Contracts available on EWF web UI, ...... 34 3.8. Execute a Smart Contract on EWF web UI...... 35 3.9. Transaction records in Tobalaba Network...... 35

4.1. GAS Consumption on PV Smart Contract(GAS) ...... 41 4.2. GAS Consumption on EV Charger Smart Contract(GAS) ...... 41 List of Figures

4.3. Transaction Execution time on EV Charger Smart Contract(s) . . . 42 4.4. Transaction Execution time on PV Smart Contract(s) ...... 42

xii List of Tables

2.1. Consensus Algorithms for Usage in Blockchains...... 15

3.1. List of Action by Participants ...... 31

4.1. List of Descriptive Actions by Participants and Implementation . . . 38 4.2. Table of Experiments Environment ...... 40 4.3. GAS Consumption on TOBALABA Network(GAS) ...... 40

EV DSO TSO DERS IOTA NEO M2M p2p POW POS POA POC IOT KWh OCPP EVM PV Consensus DAPP Digital Signature Smart contract Tobalaba Flash channel

Abbreviations and Glossary

Consensus all participants of the network agree on the validity of the transactions.

DAPP Decentralized Application. DERS distributed energy resources. Digital Signature is a digital code generated by public key encryption. DSO Distribution System Operator.

EV Electric vehicle. EVM Ethereum Virtual Machine.

Flash channel Flash is a bi-directional o-Tangle payment channel.

IOT Internet of Things. IOTA is the Blockchain for Machine Economy.

KWh Kilowatt hours.

M2M Machine-to-machine.

NEO is the blockchain for digitized assets.

OCPP Open Charge Point Protocol. p2p Peer-to-peer. POA . POC Proof of Concept. POS . POW . PV Photovoltaics. Abbreviations and Glossary

Smart contract programmable language onto the blockchain. Solidity Is Ethereumâs programming language for developing smart contracts.

Tobalaba A blockchain network created by Energy Web Foundation. TSO Transmission System Operator.

1

Chapter 1. 1 Introduction In this chapter, the introductory of the background of the research subject and the problem and use case will be introduced. Furthermore, the motivation of this research and the contributions of the thesis will be presented, followed by the choice of the methodology for this research.

1.1. Background

The blockchain is a , which is open to anyone. It maintains an ever- increasing list of records containing sequences, which are called blocks. Blocks have data or programs written in them. Each block is connected to the last generated block and includes the data, the hash of the block and the previous block such as the figure 1.1. The hash of each block is its fingerprint and unique. The blockchain technology has features such as Decentralization: due to the use of distributed accounting and storage, the system does not have a centralized hardware or management organization. The nodes maintain the data blocks in the system with maintenance functions in the whole blockchain system.

Energy system in the worldwide has been designed in a centralized system with large-scale use in the industry and a massive customer base in order to achieve the scalability and control the power supply. These centralized systems have been suitable in the past as they can reach high eciency and transmission with the use of non-renewable energy. However, the energy industry is in the process of digitalization, many new information technologies emerged in this industry and create new value and application in the industrial or consumer level.

The energy sector is currently one of the most advanced sectors in its adoption of blockchain. One of the applications of blockchain in the energy sector is to establish digital trust between users, to facilitate transactions of services and resources over a network. This case is a software innovation for digitalizing distributed energy assets on the network. Implementation of the Smart Contract(10) embraces a significant 1. Introduction

Figure 1.1.: Bitcoin Price based on Coindesk

Figure 1.2.: The Blockchian Graph

4 1.2. Problem potential in the energy sector regarding establishing trust in the transactions. Com- plicated transaction conditions and terms can be written on the smart contract. It enables trust to be distributed throughout a network, to approve and verify the digital exchange of values.

Expanding the use of blockchain to Smart Contract, and upon the "contract layer" more sophisticated transaction conditions and use case requirements for establishing energy-related services are added in short, any type of interactions between two parties that can be implemented digitally. Furthermore, a visionary concept will be reached when blockchain is deployed in big data and predictive task automation (e.., Artificial intelligence). As a result, the smart contract would be evolved to a more decentralized organizational unit, with own rules and a high degree of autonomy.

1.2. Problem

Power2U is a start-up in Stockholm focus on optimizing the energy consumption for building owner through intelligent load balancing and peak shaving. To achieve the energy consumption optimization and control the electrical assets for the customer, Power2U require historical data electricity meters data and then predict and forecast the potential cost and proposal a peak shaving solution. This system contains numerous distributed energy resources, such as an Electric vehicle(EV), charging stations, batteries, etc. My work in Power2U includes Research and development for the prototype of IOTA based Microtransaction (M2M) and eWallet for managing decentralized data flow with ELaadNL smart charger and prototype the smart contracts for the p2p transaction in EV booking system based on NEO. In the business development side, I help to explore and verify the business model based on the state-of- art Blockchain technology in the energy management platform.

The goal of this master thesis is to research and prototype how DERs and IOT data can be secured, traced and governed by using blocking technology especially Ethereum and other blockchain technology which can support high throughput and low latency with reasonable cost. However, even the blockchain is a very promising and disruptive technology in many fields, it still in an emerging and early stage. Meanwhile, the proof of work(POW) mechanism requires a certain level of computing power which is significantly varied from dierent blockchain platform. It becomes essential to get more understanding about the capabilities and limitations in the blockchain technology and its use within the energy sector.

5 1. Introduction

1.3. Purpose and Goal

The purpose of this master thesis is to discover how Blockchain based technology especially smart contract can be applied to p2p energy transaction use cases among distributed energy resources(DERS). Since use cases in Blockchain based application are mostly at the stage of proof of concept or testing nowadays, which is far from a robust and secure system that can be immediately adapt.

The goal of this thesis is to gain insights from the current state-of-art blockchain- based blockchain technology such as NEO, IOTA, Ethereum and their use cases and existing research to help Power2U AB to identify the potential use of blockchain in their future use cases. Furthermore, the energy asset management platform developed by Blockchain technology will be initiated, to achieve a decentralized data storage with trust, traceability, consensus.

1.4. Ethics and Sustainability

The research of the thesis is intended to help energy company to understand how blockchain technologies could be applied into a use case that adapts p2p energy transaction without DSO and TSO involved. Aforementioned section described that blockchain could help entities to have a trust-free, traceable, and highly transparent data record. Hence, it could potentially save many cost from the centralized electricity control system and electricity retailer. It can also help with the data integrity and private data protection.

In the aspect of ethics, this research is using open source blockchain technology and public network. All record and the transaction initialized from my computed are completely transparent to the network. And all my source code are shared on the Github public repository; all the work have been implemented on this the- sis are traceable and transparent to other people inside or outside of blockchain community.

In the aspect of sustainability, blockchain technologies such as Bitcoin and Ethereum are currently depended on proof of work(21)(12) approach which is not environment- friendly because of the current consensus mechanism. The master research paper had used technology such as NEO, IOTA, Ethereum, and TOBALABA. All the node are running on the personal computer as well as the testing and transaction processed in the blockchain network, which does not require any external computing resources such as mining machine or cloud vendor services, etc. Moreover, the performance and the cost of DAPP will be analyzed. The resulting outcome of this thesis can also be helpful for future adoption of blockchain technologies in the energy sector.

6 1.5. Contributions

1.5. Contributions

Figure 1.3.: Energy Trading Rrice with DSO and Retailer in Sweden. Graph and Data provided by Xue Wang, Power2U AB

Even though many blockchains based use cases and technology already exist within the energy sector, there is still limited research to explore and understand the advantages of blockchain and how to utilize the technology to implement for the electric assets. Additionally, there are too many blockchain technologies in the market, and they have dierent features and design. Given the reasons above, it is needed to initiate the research within the field of blockchain technology and provide the energy industry with relevant knowledge for future research and further development. The outcome of the master thesis will be both the blockchain technologies comparison and a real-world use case implementation using ethereum. In the energy trading, TSO and DSO stand for the Transmission System Operator and the Distribution System Operator respectively. They are jointly in charge of maintaining the quality and the security of electricity supply (3). The blockchain based p2p transaction model could potentially save many cost from the centralized electricity control system and electricity retailer.

7 1. Introduction

1.6. Choice of Methodology

This thesis is focusing on the Distributed system and IT artifacts for dierent blockchain technology. Given the scope of this thesis, Qualitative research method will be adapted to carry on the research process(9). The process of building this IT artifact will be presented in chapter 4 will be evaluated using a descriptive evaluation method according to design science in information system research by Havner(1). The unit testing and functional testing was carried out on the remix (https://remix.ethereum.org), the online compiler provided by Ethereum founda- tion.

Figure 1.4.: Design Science Approach Overview Retrieved and Adapted from Hvner, 2004

1.7. Outline

The first chapter of the study is a brief introduction of the background and scope of this thesis, and the choice of a design science research methodology which will be applied for the artifact development and evaluation.

The following chapter 2 will the basic knowledge of blockchain, the concept of cryptography being used in blockchain and analysis of dierent blockchain technology including NEO, IOTA, Ethereum, Powerledger, and Tobalaba. Moreover, current

8 1.7. Outline academic research and an industrial project will be introduced in the related research section. Chapter 3 of the study is the design and implementation of energy asset management platform that supports p2p energy transaction via smart contract on the according to the design science for the information system. A system and requirement analysis will be conducted for this DApp, and then design of the smart contracts for the use cases. In the end, the procedures of deployment of smart contract and execute them on a public test network TOBALABA will be performed. In the end, chapter 4 will use the evaluation methods for IT artifact in design science in information systems research to justify if completeness and eectiveness in this energy asset management platform are satisfied the requirements and constraints of the problem are fulfilled. Finally, the achievement, as well as limitations of this work will be discussed, and the conclusion will be drawn in chapter 5.

9

Chapter 2. 2 Technical Background 2.1. Cryptography

In this section, the basic knowledge of cryptography will be presented. The cryp- tography is the essence of how the blockchain technology works. In the blockchain implementations, cryptography is being used in the transaction, block creation, etc. It guarantees the integrity of the data in an encrypted distributed and decentralized environment. The primitives being used in blockchain technology including hashing functions, digital signatures and Merkle tree which will be discussed in the following paragraphs.

2.1.1. Hashing Functions

The hashing function takes an arbitrary volume of data as the input and then produce a number as output. In the context of the blockchain, Firstly, whatever the size of the input will produce the same volume output. Secondly, the same input will always output the same value. Thirdly, a slightly dierent input will give completely dierent output. Lastly, the hashing function should be non-invertible using current state computing power to brute force search for the result.

The current common Hash algorithms include the International Message Digest (MD) series and the Secure Hash Algorithm (SHA) series of algorithms, as well as the domestic SM3 algorithm.

The MD algorithm mainly includes two algorithms, MD4(17) and MD5(18). MD4 (RFC 1320) was first proposed by Ronald . Rivest of MIT in 1990 with an output of 128 bits. MD4 has proven to be insuciently secure. MD5 (RFC 1321) is a successor of MD4 by Rivest in 1991. It still groups the inputs in 512 bits, and the output is 128 bits. MD5 is more secure than MD4, but the process is more complicated, and the calculation speed is slower. MD5 had successfully collided in 2004, and its security is no longer sucient for economic scenarios. 2. Technical Background

Figure 2.1.: Digital Signature in Bitcoin.

The SHA algorithm was developed by the National Institute of Standards and Technology (NIST). The first implementation of the SHA-0 algorithm was introduced in 1993 and was cracked in 1998. Subsequent revisions of the SHA-1 algorithm were introduced in 1995, and its output is a 160-bit Hash value for better security. The SHA- 1 design uses a similar principle of the MD4 algorithm. SHA-1 was successfully collided in 2005, meaning that it could not meet commercial needs. To improve security, NIST later developed a more secure SHA-224, SHA-256, SHA- 384, and SHA-512 algorithms (collectively referred to as the SHA-2 algorithm). A new generation of SHA-3 related algorithms is also under study. In practice, Google researcher cracked SHA-1 (http://shattered.io/) using computing resources equivalent to 110 years using one graphics processor. It raises the awareness of SHA-1 is a weak cryptographic algorithm and should not be used in blockchain technology. Here is an online tool to demonstrate how every cryptographic algorithm works(https://emn178.github.io/online-tools/).

2.1.2. Digital Signatures

In blockchain, each user has an account. Upon the creation of an account, a pair of public and private keys is generated. The public key can be used as a public identifier in the blockchain network, which is comparable to the IP address of each device in the network. And the private key as a digital signature to approve the transaction on blockchain network. The asymmetric cryptographic system of blockchain uses the digital signature to perform authentication and encryption. The following Figure 2.1 shows an example that how the digital signature works in Bitcoin. TXID is output index of the previous transaction, the previous outputs pubkey script. Bob’s pubkey script that makes next recipient spend the amount, following Bob’s private key will be written into transaction TX2, and then the TX2 will be assembled and broadcasted into the Blockchain network.

12 2.1. Cryptography

2.1.3. Merkle Trees

One of the core concepts of blockchain is Merkle trees, which can be used to varify the validity of the block. It was invented by Ralph . Merkle and owns the patent for it since 1979(11). The defined data structure is a binary tree containing cryptographic hashes, which can provide ecient summary and verification. The hashing function used in Merkle tree is SHA256 applied twice (double- SHA256). From the bottom up construction recursively hashing pairs of nodes until only one hash remains which are the (Merkle) roots. The time complexity of computing for elements is 2*log2(N). Eciency becomes evident with increasing scale of the merkle tree node. We can also verify transaction by using the Merkle authentication path.

The following example shows how to compute the merkle tree, hash(A) and hash() which are the leave nodes, will be computed using SHA256 hash algorithm thice. Then, the root node of merkle tree will compute double SHA256 again for hash(A) add hash(B).

H(A)=SHA256(SHA256(TransactionA)) (2.1)

H(B)=SHA256(SHA256(TransactionB)) (2.2)

H(AB)=SHA256(SHA256(H(A)+H(B))) (2.3)

13 2. Technical Background

Figure 2.2.: Merkle Tree

2.1.4. Consensus Algorithm

The consensus mechanism is vital to avoid information inconsistance in the distributed environment of the blockchain network. The goal of the consensus mechanism is to let the blockchain history does not contain an invalid or contradictory record. A list of commonly used consensus mechanisms has been listed here on the following table 2.1.

Bitcoin uses the POW mechanism(12) in the block generation process. A matching Block Hash consists of N leading zeros, and the number of zeros depends on the diculty value of the network. To get a reasonable Block Hash requires a lot of trial calculations, the calculation time depends on the machine’s hash speed. When a node provides a reasonable Block Hash value, it indicates that the node does undergo a lot of trial calculations. Of course, the absolute value of the number of calculations cannot be obtained, because finding a reasonable hash is a probability event. When a node has a computing power of n percentage of the entire network, the node has a probability of n/100 to find the Block Hash.

14 2.2. Blockchain Technology

Consensus algo- Expmple Im- Basic Description rithm plementation Bitcoin, Proof of Perform compuational expensive task to verify , work(POW) expenses Ehtereum, Proof of Ownership of fixed amount of tokens NEO, stake(PoS) Proof of Correct- Aggregate supermajority of a known set of Ripple ness(PoC) network Proof of Storage Provide the storage of hardware to verify ex- Burst, StorJ Capacity(PoSC) penses Proof of Authority Selected authorities are randomly selected to Parity PoA (PoA) validate transactions

Table 2.1.: Consensus Algorithms for Usage in Blockchains.

2.2. Blockchain Technology

In this section, a brief introduction and explanation of some of the blockchain technologies will be given. In the first section, the architecture of NEO a state-of-art blockchain technologies and its smart contract will be presented. In the second section, IOTA will be shown, and the features that support the internet of things such as Tangle, Flash channels, Mask authentication message will be discussed. In the third section, Ethereum and the architecture for DAPP development will be presented. In the last part, powerledger the Ethereum based blockchain which can support bi- directional communication for energy trading will be explored.

15 2. Technical Background

2.2.1. NEO

Figure 2.3.: NEO Virtual Machine

NEO is a distributed network that uses blockchain and digital identity for asset digitization, intelligent management of digital assets using smart contracts, and can be used in ’smart economy’.(13) Neo smart contract provides us with a decentralized and highly ecient network and with the tamper-resistant system.

Digital assets are programmablely controlled by the smart contract. The use of NEO to achieve asset digitization has the characteristics of decentralization, de- intermediation, trust-free, traceable, and highly transparent. NEO supports multiple digital assets at the bottom, users can register their own assets on NEO, freely trade and transfer, and solve the mapping relationship with physical assets through digital

16 2.2. Blockchain Technology identity. Assets registered in the NEO smart contract through a compliant digital identity are protected by law. (13)

There are two kinds of digital assets in NEO: global assets and contract assets. Global assets can be recorded in system space and can be recognized by all smart contracts and clients node of NEO; contract assets are recorded in the private storage area of ââthe smart contract and need to be recognized by clients that are compatible with the smart contract. Contract assets can be referenced to certain agreed-upon standards to achieve compatibility with most clients.

NEO system includes two type of tokens the NEO and the GAS. The NEO with total 100 million tokens shows the owner of the token the right to manage the network. The initial token of NEO is 10 million, which will increase to million within about 22 years. The GAS is the fuel token being used for resource control for NEO network, with a total limit of 100 million as well as the NEO token. Gas can be used to deploy contracts in the network, issue transaction, and execution of the smart contract. The initial number of Gas is 0 too, and it will be generated when the new block is generated.

The consensus mechanism of NEO is delegated Byzantine Fault Tolerant(dBFT). Basically, NEO holder vote to decide the bookkeepers and the bookkeepers will use BFT algorithm to generate new block in the main network. dBFT is consist of n consensus node and could provide =(n-1)/3 fault tolerant ability to resist general break down of the system. Under the control of dBFT consensus mechanism, a block in the main network will be generated every 15 20 seconds. The transaction throughput can reach 1000tps. In the public network. The transaction will be able to reach 10000tps. NEO can support decentralized application in the fields such as a , data exchange market, AI-assisted legal smart contract and etc.

NEO is using a built-in compiler for compiling smart contract the architecture of this compiler is based on .NET. The main developing language of the smart contract in NEO is C but it also supports copmuter programming languages such as Java, c, c++, Javascript, Python, Ruby, Go, Kotlin, and etc. It has the open API and development SDK for developers and the developer community is very large as you can find many updates in their GitHub repository.

Neo provide public network, test network and private network for its users. The public network can deploy Dapp and consume "real" gas. The test network is provided and maintained by the NEO organization for developers to test and develop their own application. The test network provides testing NEO gas which does not cost real money. NEO organization also provided a docker images that can set up a private network. The user can set up their own network in the Docker environment using the image provided by NEO.

17 2. Technical Background

2.2.2. IOTA

Figure 2.4.: Tangles and Bundles in IOTA Network

In 2015, IOTA was created by David Sonstebo, Sergey Ivancheglo, Dominik Schiener, and Serguei Popov. ’IOTA is a revolutionary new transaction settlement and data transfer layer designed for the Internet of Things. It is based on the newly distributed ledger - Tangle. Tangle overcomes the ineciencies in existing blockchain designs and creates a new approach to the decentralized P2P system consensus. Transferring through IOTA does not require a fee, which is the first case. This means that no matter how much money is paid, it can be done through IOTA’ (6). Tangle is based on a directed acyclic graph (DAG) (5) rather than a continuous chained architecture that periodically adds blocks. With DAG, IOTA is able to achieve higher transaction throughput (through parallel verification) and does not charge transaction fees. As Tangle continues to evolve, more and more participants will initiate transactions, the entire system will become more secure and fast, con- firmation time will be shortened, and transactions will be completed faster and faster. In the IOTA system, every participant in the network can trade and actively par- ticipate in the consensus. More specifically, you directly locate two transactions (primary and branch) and indirectly locate other transactions in the child tangle. In this way, verification can be done simultaneously, the network can remain completely decentralized, no miners need to pass on trust, and no transaction fees are required. IOTA has no transaction fee This is achieved through IOTA’s unique consensus approach. Usually, in order to verify the transaction and include it in the next block, it is necessary to pay the

18 2.2. Blockchain Technology

Figure 2.5.: Transaction using IOTA Flash Channel transaction fee, but there is no miner or verifier in the IOTA system (to complete the work, so there is no need to pay the fee). The IOTA consensus is completely decentralized, and each network member can initiate a transaction to directly or indirectly confirm past transactions. It is because of the inherent characteristics of this consensus (transaction terminal selection and computing needs) that you do not have to pay a fee.

Flash Channels is a bi-directional way oine (o-Tangle) payment channel that supports instant high-throughput transactions. Essentially, they provide a high- frequency trading method for all parties without waiting for each transaction to be acknowledged on a public IOTA network. The Lightning Channel is the first module to extend the IOTA core capabilities to enable it to handle real-time transaction flows. This feature fits perfectly with the fast and free solutions of the IOTA network and is a new and disruptive application in the Internet of Things and other Internet sectors.

Mask Authentication Message (MAM) is one of IOTA’s most powerful IXI modules, opening up new areas of IOTA-based applications. Ensuring data integrity and access management controls are essential for applications such as online updates (OTA), data sourcing, fog analysis, end-to-end verifiable supply chains, automated insurance, and more. Like Youtube and other media, MAM also has channels. Channel owners can post new data, and viewers can subscribe to channels to get the data available. This ownership is implemented and protected by IOTA through Seed. When posting a new message on a channel, the publisher can have three options. Public (public mode): Everyone can view it. Private (private mode): Only you (ie the seed owner) can view it. Restricted: You can tell someone a key and authorize him to be a viewer. This key is named sideKey in the source code.

19 2. Technical Background

Figure 2.6.: Comparison of Blockchain Technologies: Ethereum, NEO, IOTA

2.2.3. Ethereum

Ethereum was first created by Vitalik Buterin, who authored a white paper on his own on December 2013. Vitalik Buterin was also a proponent of the bitcoin. And the Ethereum network went online in July 2015. Ethereum is designed to be used in more complex application than Bitcoin, which only allow for transferring money. It adapted the POW machanism bitcoin with brute-force search hashing value in a target range, but with more input variable from the block header. Its white paper discussed the need for more programmatic control over the transaction and wanted to enable the creation of decentralized autonomous cooperations (DAC). The white paper also introduced the most imvportant part of the Ethereum network: smart contract. The smart contract is consisted of solidity code that is stored in the Ethereum blockchain.(10).

The Ethereum consist of the Ethereum network and Ethereum nodes. Ethereum has three types of network: Main Ethereum network, Test network, and the local network. The main Ethereum network allows users to transfer ’real’ money through the network and deploy their Dapp in the production environment. The test network allows the user to test their smart contracts on a testing environment, the mechanism of cryptocurrency inside the test network are the same as in the main network but is free to use. Users can even create their own private Ehtereum network on their computer or server, which can be restricted to own usage or open the network for others to use. The Ethereum node is a machine that runs an Ethereum client application and it can be run in any computer. Each Ethereum node inside the network has a full and separate copy of the blockchain.

20 2.2. Blockchain Technology

Figure 2.7.: The Ethereum Network and its Interaction with Metamask.

Figure 2.8.: Ethereum based Dapp architecture and its Interaction with web3 lib and front-end application.

21 2. Technical Background

Figure 2.9.: Technical Layer of Power Ledger (15)

2.2.4. Powerledger

"Smart grids equipped with bi-directional communication flow are expected to provide more sophisticated consumption monitoring and energy trading. However, the issues related to the security and privacy of consumption and trading data present serious challenges". (14) The study points out blockchain technology can help to improve scalability and avoid single point failure in the central system and also providing transaction security in decentralized smart grid energy trading without reliance on trusted third parties.

"Power Ledger is a distributed, interoperable energy trading platform that supports an extensive suite of energy-focused applications. It features a live and deployed platform that let other develop the decentralized application "(DAPP) (15). It allows the peer to peer transaction which also incentive the penetration of renewable energy in an apartment building. Power ledger proposed a dual token system.

22 2.2. Blockchain Technology

Figure 2.10.: Two Type of "token" issued by Power Ledger Platform.

"Power Ledger is a distributed, interoperable energy trading platform that supports an extensive suite of energy-focused applications. It features a live and deployed platform that let other develop the decentralized application"(DAPP) (15). It allows the peer to peer transaction which also incentive the penetration of renewable energy in an apartment building. Power ledger proposed a dual token system.

2.2.5. Tobalaba

Tobalaba is an open source blockchain test network developed by the Energy Web Foundation (EWF) and based on Ethereum. (Energyweb.org, 2018). The Tobalaba has the following features. Decentralized: platform that anyone can participate in. However, the platform encrypts and verifies network transactions based on the whitelist "permissions" and Authorized institutions in Tobalaba are able to target specific network participants and transactions. High eciency: Tobalaba currently achieves 2,500 transactions per second and will eventually be able to run millions of transactions per second. Confidentiality. The platform uses a unique approach to "protect confidentiality," Tabalaba has a new feature in the blockchain field, which we call a "secret contract." Through this function, authorized organizations and users can maintain intelligent contract and transaction data with absolute confidentiality through built-in encryption, and only open to specific groups. Open source: anyone can use the platform or develop new applications on top of the platform. Blockchain technology for energy sector professionals in the energy sector

23 2. Technical Background

The development goal of the EWF test network is to support a wide range of distributed applications in the energy sector, which is why the platform has built its unique network topology. That is, anyone can download the EWF client and submit a transaction or write a smart contract on the Tobalaba network, but only the organization that has the specified authority (such as the EWF Power Market aliate) has the right to activate the engine that requires authentication to authenticate the transaction. This kind of participation by anyone, combined with the topology of whitelisted authentication rights, enables EWF to serve multiple applications and business models, including regulatory market applications. In contrast, public blockchain technologies such as Bitcoin cannot handle regulatory applications because the identity of key players in these networks, such as bitcoin âmining machinesâ, is unknown.

2.3. Related Research

2.3.1. ADMM Optimization

According to the research paper(19), abuse of market power is observed in the energy market monopoly. (4) "Such a monopoly aggregator can have strong incentives to shift the market away from a cost-minimizing equilibrium and towards a profit-maximizing monopoly outcome."

The figure above shows the comparison of an ecient energy market and a market operated by a monopoly who can decide the price for electricity generation and consumption.(4) The paper from Energy Control and Application Lab at the Uni- versity of California Berkeley show a possibility of eliminating trust issues with microgrid operators by using Ethereum blockchain technology and formulated an Alternating Direction Method of Multipliers (ADMM) optimal scheduling program for distributed energy resources, from which they discovered a way to optimize the distributed power flow algorithm with battery and loads. The advantage features and smart contract from Ethereum blockchain platform can create a transparent and trustless platform for data storage and computation. According to this paper, "It makes a private blockchain the perfect platform for conducting the aggregation step of ADMM, allowing all participants to audit the progress of the algorithm, the accuracy of the solution, and the integrity of their scheduled commitments. Further, ADMM is a natural fit for implementation on a blockchain, as it guarantees conver- gence yet has a computationally cheap aggregation step (minimizing the burden of verification)."(4)

The blockchain technology could provide a consensus-based security layer to coordi- nate these decentralized optimization problems.(4)

24 2.3. Related Research

Figure 2.11.: Comparison of an ecient market in which the optimal quantity Q* is cleared at price P(Q*), and a market operated by a monopoly who is able to charge separate prices for generation and consumption.(4)

2.3.2. IOTA Micro Transaction

IOTA runs on a system called "The Tangle," a form of the directed acyclic graph (DAG) data structure applied to a distributed ledger protocol. (6) The unique feature makes the IOTA diverges from other blockchain technology is it allows free transaction on a decentralized network without the need of miners, block, and chains.ElaadNL is the knowledge and innovation center in the field of smart charging infrastructure in the Netherlands. ElaadNL is also a business partner of Power2U, and they built a PoC Charge Station running entirely on IOTA [5], for payment of the charging energy. All communication, measurement and transaction information between customer and charging station is stored in the tangle structure of IOTA, which can ensure security and traceability of data. Even though it was just a proof of concept case study. It shows the potential of IOTA blockchain technology to be embedded in the EV charging station, which could also bring a business opportunity for grid operator and EV charging station manager. However, based on an IOTA transaction experiment on my MacBook Pro laptop, the average time of a wallet attached to the network is more than one minutes. The time from initiating a transaction to finish a transaction between IOTA sender wallet and IOTA receiver wallet also require more than 10 minutes. It shows the process of the transaction of IOTA requires more time than the real-time transaction application

25 2. Technical Background

Figure 2.12.: IOTA charger Proof of Concept by ElaadNL (20) needed. This indicates the drawback of IOTA that small IOT devices like sensors could not carry out the computation overhead for the transaction, and Its current unstable network might render some unexpected error for applications. To solve network overhead of IOTA network, IOTA foundation developed the Flash channel. "Flash is a bi-directional o-Tangle payment channel to enable instanta- neous, high-throughput transactions. In essence, they provide a way for parties to transact at high frequency without waiting for each transaction to confirm on the public IOTA network."(7) Flash Channels use a binary "tree topology to re- duce the number of transactions to be attached. Usually, each transfer would have to be connected to the tangle"(7), Flash enables real-time streaming of tokens o-tangle(7). An o-Tangle approach reduces the per-transaction overhead to a negligible level by creating signed transactions othe tangle. "Only two transactions will ever occur on the main IOTA network: opening and closing transactions of the Flash channel"(7), which reduce the overhead for the system.

26 Chapter 3. 3 Implementation In this chapter, the energy asset management platform that supports p2p energy transaction via smart contract and blockchain technology is presented. Firstly, the system analysis will describe the system usage in the small renewable energy community and further descriptions of how given blockchain technology and smart contracts can provide an innovative solution for the use case. Secondly, the specifi- cation of the blockchain system design and its smart contracts for each distributed energy assets ownership will be presented to show how the decentralized, trust- less, transparency and Immutable properties of blockchain could change the energy community.

3.1. System Description and Requirements Analysis

A global technology revolution has disrupted the conventional centralized power system with distributed resources and technologies, like photovoltaic units (PV), batteries, electric mobilities, and digitalization, etc. The citizens then have control of their generation and consumption profiles, at the same time, revolutionize with a bottom-up approach. Accordingly, an era for energy market moving towards a service-based local space has been established.

Energy asset management platform contributes to the development of a local energy service market (LEM). It designs a new way to implement local energy service market around managing energy storage units (batteries), local green energy generation units and electric vehicles (EV), etc. These assets are so-called Distributed Energy Assets. Energy asset management platform integrates the new business models, IoT, blockchain technologies and energy management solutions for facilitating smart energy services and providing a trading space for renewable energy services and resources in a decentralized area. The complexity in the diverse ownership of the distributed energy assets introduces challenges to the real-world operation of the LEM, such as security of the assets, transparent of the payment flows and prices, and also traceability of the supply request records, etc. 3. Implementation

Figure 3.1.: P2p Transaction for Smart Energy Asset Management System

Meanwhile, Energy asset management platform also aims at delivering additional impacts while exploring further development of the fundamental technology structure. It will continuously be developed and tested in pilot sites with the purpose of wide- spread replication and adoption across the world. During the process, more social responsibility, more citizen empowerment, more sustainability, more resilience in the energy market will be arising. The regulatory impedance of developing a more democratic energy market will be eliminated via implementing an open platform, like Energy asset management platform.

3.1.1. System Analysis

The smart energy asset management system is designed to enable the people who live in the smart community powered by distributed energy assets, to exchange local renewable energy resources and services such as EV booking, without worrying about the inconvenience in transaction settlement, potential energy asset security loophole, and diculty of managing various new devices. Within this thesis, a p2p transaction function has been developed for the smart energy asset management system. Each type of the owner of the p2p transaction has a ’wallet’ to store their cryptocurrency for the p2p transaction. And the smart contract among the users will have an overall control for all the energy transaction. The smart contract will be running over Ehtereum network and supports a trustless transaction, a transparent data value flow, and a traceable assurance. The Figure above shows the logic of NEO blockchain based energy asset manage- ment platform. The contract contents for the four types of user are defined as

28 3.1. System Description and Requirements Analysis

Figure 3.2.: Smart Contract Application Interface implemented on NEO smart contract.https://github.com/liuruogu/NeoEnergyTransaction follows:

3.1.2. Design on the Smart Contract

Tenant driver • The tenant driver has two service options. 1. Tenant driver can rent an EV from the fleet owner. The cost of renting an electric vehicle from an EV fleet owner is set and could be changed by the fleet owner and not be changed by the driver, but the user needs to type in the duration of using the renting service. 2. Charge the car via private chargers operator. The cost of using the private charger operator is fixed, but the user has to choose the charging power volume (kW) and the service duration (hr).

Private charger operator contract • The private charger operator has two service options. 1. Rent out my private charger are specified. The fee for renting out the charger, the power volume, and the availability duration (rent-out time periods) are decided and typed in by the operator. 2. Procure electricity from the local green provider. The fee of the procurement per unit is fixed, while the operator needs to fill in the electricity volume that needs to be procured.

29 3. Implementation

Figure 3.3.: Overview of Dierent Electricity and their Interactions with the Blockchain and System of Smart Contracts which exist on the Blockchain.

Local green energy provider contract • The local energy providers are usually the ones providing renewable electricity from distributed generation assets, like solar panels. The provider has one service option 1. âSell the local green energyâ via the platform The price (gas/kWh) of the local generation and available surplus volume are filled in by the provider on the contract definition page. Electric vehicle (EV) fleet owner contract • The fleet owner has two service options: 1. Rent out EVs from the car fleet: in this service, the EV fleet owner provides a one-stop service, which means the cars rented out are with fully charged batteries. The fee for renting out vehicles from the fleet is fixed and could be changed by a fleet owner, while the fleet owner needs to type in the number of available cars. At the same time, the fleet owner has to specify the available duration slots for renting out the EVs. 2. Procure electricity from local green provider, the fee of the procurement for each unit is fixed, while the fleet owner needs to fill in the electricity volume.

After defining the contracts, the smart contracts on the energy asset management platform will be executed. The entire executing process is automated. The user can monitor the real-time status, and track the historic service records and balance left in their own account. Since all the transaction record will be written in the blockchain with full history. There are not need for data storage on databas. In this way, the users are empowered to pay for decentralized clean energy/mobility services with a transparent, traceable and secure transaction system.

30 3.1. System Description and Requirements Analysis

Action Participant Trace Number Set the price for its energy or PV EVfleet Charger 1 services Find out how many ether left PV EVfleet Charger Driver 2 on the account Sell the local generated green PV 3 energy with a fixed price Buy the energy from the local EVfleet Charger 4 generated green energy(PV) Rent out the charger to other Charger 5 customers Rent out the electic vehicle EVfleet 6 Rent the electric vehicle from Driver 7 EV fleet Rent the charger from EV Driver 8 charger View the charger(Availability, Charger 9 price, etc) View the EV(Availability, EVfleet 10 price, etc) View the PV(Availability, Vol- PV 11 umn, price, id, etc) Deactive the contract PV EVfleet Charger Driver 12

Table 3.1.: List of Action by Participants

The function defined on the smart contract are listed as following:

setPrice() • Set the fee for selling the local green energy(PV)(ether/kWh), rent out the EV charger, rent out electric vehicle from EV fleet.

getBalance() • Get the balance from the contract of PV, EV Charger, Electric vehicle fleet.

sellEnergy() • Sell the local green energy(PV)(ether/kWh) from PV.

buyEnergy() • Initialized by EV fleet and charger. Buy energy from local green energy(PV)(ether/kWh).

rentoutCharger() • For renting out the charger. The fee depends on the the charging power volume (kW) and the service duration (hr).

31 3. Implementation

rentoutEV() • For renting out the EV. The fee depends on the the service duration (hr). rentCharger() • For renting the charger. The fee depends on charging power volume (kW) and the service duration (hr). rentEV() • For renting the EV. The fee depends on and the service duration (hr). viewCharger() • Fetch and return state variables from the current charger contract. viewPV() • Fetch and return state variables from the current PV contract. viewEV() • Fetch and return state variables from the current EV contract. kill() • Deactivate the this contract.

3.2. Implementation of Smart Contract on Energy Web UI

After defining the contracts, the implementation, deployment for the smart contract will be carried out on the EWF platform. The EWF web UI can be download from https://energyweb.atlassian.net/wiki/spaces/EWF/pages/72974337/Install+the+Energy- Web+Client. User can create the account and corresponding wallet for testing purpose, then request ether from tobalaba testing network: http://tobalaba.slock.it/faucet/ from where I received ether within few seconds. Implementation for smart contract in this section is using a language called Solidity https://solidity.readthedocs.io/. Solidity is a contract-oriented, high-level programming language created for smart contracts. The language is influenced by the C++, Python, and Javascript and is designed to run on the Ethereum Virtual Machine (EVM). The solidity ver- sion for compiling the Ethereum smart contract that being used in this section is 4.21.

3.2.1. Deployment on EWF web UI

3.2.2. Execute contract on EWF web UI

32 3.2. Implementation of Smart Contract on Energy Web UI

Figure 3.4.: Create the Account on EWF web UI

Figure 3.5.: Initiate a Contract

33 3. Implementation

Figure 3.6.: Deploy Smart Contract on EWF web UI.

Figure 3.7.: Deployed Contracts available on EWF web UI,

34 3.2. Implementation of Smart Contract on Energy Web UI

Figure 3.8.: Execute a Smart Contract on EWF web UI.

Figure 3.9.: Transaction records in Tobalaba Network.

35

Chapter 4. 4 Result and Evaluation 4.1. Evaluation

According to the evaluation method for IT artifact in Design Science in Information Systems Research (1) evaluation phase provides essential feedback to the construction phase as to the quality of the design process and the design product under development. A designed artifact is complete and eective when it satisfies the requirements and constraints of the problem it was meant to solve.

According to the design science of information system by Henver, IT artifact can be evaluated by functionality, completeness, consistency, accuracy, performance, reliability, usability, and fit well enough with the organization. Within this chapter, the IT artifact that presented on chapter 3 will be evaluated using the design evaluation methods in Henver’s paper.

Since the the energy asset management platform is developed by using Blockchain technologies, which is an innovative solution and also hard to be described in Analytical, Experimental or Observational way, due to the reason mentioned above, we will mainly use Black box testing and descriptive method to evaluate the energy asset management platform, and its p2p transaction features over Tobalaba network. Functional test will be carried out in the system using online solidity compiler provided by the Ethereum community. All the smart contract is being deployed using the EnergyWeb UI in the Ethereum TOBALABA testing network provided by the Energy Web Foundation.

Functional (Black Box) Testing • Execute artifact interfaces to discover failures and identify defects(1).

Descriptive analysis • Use information from the knowledge base (e.g., relevant research) to build a convincing argument for the artifact’s utility. Scenarios: Construct detailed scenarios around the artifact to demonstrate its utility(1). 4. Result and Evaluation

Performance and time, space complexity •

4.2. Result

4.2.1. Descriptive analysis

Action Participant Trace Number Fulfillment Set the price for its energy or PV EVfleet Charger 1 setPrice() services Find out how many ether left PV EVfleet Charger 2 getBalance() on the account Driver Sell the local generated green PV 3 sellEnergy() energy with a fixed price Buy the energy from the local EVfleet Charger 4 buyEnergy() generated green energy(PV) Rent out the charger to other Charger 5 rentoutCharger() customers Rent out the electic vehicle EVfleet 6 rentoutEV() Rent the electric vehicle from Driver 7 rentoutEV() EV fleet Rent the charger from EV Driver 8 rentCharger() charger View the charger(Availability, Charger 9 viewCharger() price, etc) View the EV(Availability, EVfleet 10 viewEV() price, etc) View the PV(Availability, Vol- PV 11 viewPV() umn, price, id, etc) PV EVfleet Charger Deactive the contract 12 kill() Driver

Table 4.1.: List of Descriptive Actions by Participants and Implementation

4.2.2. Functional testing

The function defined on the smart contract are listed as following:

setPrice() • PV, EV fleet and Charger can call this function to set the fee for selling the

38 4.2. Result

local green energy(PV)(ether/kWh), rent out the EV charger, rent out the electric vehicle from EV fleet.

getBalance() • PV, EVfleet and Charger can call this function to get the balance from the contract of PV, EV Charger, Electric vehicle fleet.

sellEnergy() • PV can call this function to sell the local green energy(PV)(ether/kWh) from PV. The user can decide how much volume to sell and check the availability of the PV by calling this function. If the current volume small than the requested volume, then the transaction can not be executed.

buyEnergy() • This feature can be initialized by EV fleet and charger. Buy energy from local green energy(PV)(ether/kWh). EV fleet or charger can decide how much volume they want to procure from the PV.

rentoutCharger() • The charger can call this function to rent out the charger to driver or EV fleet. A user can decide how long to rent out the charger and check the availability of the chargers by calling this function.

rentoutEV() • EV fleet can call this function to rent out the EV to driver. User can decide how long to rent out the EV and check the availability of the EVs by calling this function.

rentCharger() • This feature can be initialized by EV fleet and driver. Rent the EV charger from the chargers. EV fleet or charger can decide how long they want to rent the charger.

rentEV() • This feature can be initialized by driver. Rent the EV from the EV fleet. Driver can decide how long they want to rent the EV for.

viewCharger() • The view function will be triggered by the charger smart contract and return the information including ID, availability, current price, and another state variables.

viewPV() • The view function will be triggered by the pv smart contract and return the information including ID, Current volume, availability, current price, and another state variables.

39 4. Result and Evaluation

viewEV() • The view function will be triggered by the EV smart contract and return the information including ID, availability, current price, and another state variables.

kill() • Deactivate the current contract.

4.2.3. Performance analysis

The process of deployment, execution of smart contract had been done on the local environment and then published to public TOBALABA network. The following graph shows the detail setup of the environment.

Computer MacBook Pro Retina 13-inch macOS High Sierra SSD 128G CPU 2.5GHz Intel Core i5 Environment Dependencies Parity EVM node, Solidity compiler Compiler version Solidity 0.4.21 Network Tobalaba network

Table 4.2.: Table of Experiments Environment

GAS consumption •

The following graphs GAS consumption when executing functions on PV and Charger smart contract. With comparison with basic Greeting smart contract transaction.

GAS consumption for deployment

Contracts PV Charger Greeting Gas Consumption 680279 588725 340623

Table 4.3.: GAS Consumption on TOBALABA Network(GAS)

40 4.2. Result

Figure 4.1.: GAS Consumption on PV Smart Contract(GAS)

Figure 4.2.: GAS Consumption on EV Charger Smart Contract(GAS)

Transaction execution time •

The following graphs show transaction execution time when executing functions on PV and charger smart contract with comparison with basic Greeting smart contract transaction. The data was collected from EWF web UI, and the GAS can be calculated automated when executing the smart contract. The contracts execution time was collected on TOBALABA network after the contract was executed and recorded on the block. The precision is in second.

41 4. Result and Evaluation

Figure 4.3.: Transaction Execution time on EV Charger Smart Contract(s)

Figure 4.4.: Transaction Execution time on PV Smart Contract(s)

From the figure above, we can see the correlation between GAS consumption and transaction time. This fee(GAS) of the transaction depends on the complexity of the computation to be performed, the complexity of the input data, and the number of verifiers(8).

The execution time of the function also related to the space and time complexity of the smart contract(see Appendix source code) function. The implimentation for the p2p transaction currently has O(n) time complexity," due to the restric- tions set by the EVM (i.e., gas cost of operations), implementing functions in Ethereum with time and space complexity greater than O(n) is not feasible"(8).

42 4.2. Result

Although, the transaction speed could be aected by the network trac and other factors. The Tobalaba have very stable performance regarding transaction speed. Most of the smart contract can be processed within 2 seconds. But the performance needs to be improved in comparison to centralized platforms such as PayPal (450 tps) and Visa (56,000 tps)(16).

4.2.4. Outcome

Functional (Black box)test (1)was carried out in the system using online solidity compiler provided by the Ethereum community and continuous deployment using EWF web UI to deploy in the TOBALABA network. The test result can be visible in the blockchain record in the TOBALABA network. https://tobalaba.etherscan.com/. The user only needs to type in the address of the smart contract to retrieve all the transaction been executed in this smart contract. Given the considerations are taken in the functionality, completeness, and correctness of the features in the artifact (energy asset management platform) which give it a strong argument for the usage of such an IT artifact for the p2p transaction in energy asset management platform. .

43

Chapter 5. 5 Conclusion 5.1. Discussion

In this paper, We have shown how blockchain based technology is being utilized in the energy field. From the prototype of energy asset management platform shows how smart contract can provide a natural solution for trust, security and reliable system which the users will be empowered to pay for decentralized clean energy/mobility services with a transparent, traceable and secured transaction system powered by Ethereum and Tobalaba test network. But this Ethereum based energy asset management platform is a proof of concept, which requires user testing and business analysis to justify it is a feasible system in the real world. Meanwhile, the drawback of energy consumption in some blockchain technology still creates a dilemma in energy sectors. The high throughput distributed networks is also a critical technical challenge remained in many blockchain technologies.

5.2. Limitations of this work

The object of this thesis is to discover how Blockchain based technology especially smart contract can be applied into p2p energy transaction use cases among distributed energy resources(DERS), and implementation an IT artifact to verify the proof of concept using the current popular blockchain technologies. However, during the research process and we have discovered a few limitations of this work 1.Security: the IT artifact does not protect user’s data and private key. Protect smart contrac from DAO exploit(2).

2.Scalability: the transaction over Tobalaba network is relatively fast compared to other blockchain technologies, but still can not handle high throughput for the transaction. 3.Robustness: the basic functionality of the smart contract has been developed, but there are many potential loopholes in the smart contract that could make the system very vulnerable. 5.3. Future work

Within the work, the proof of concept for p2p transaction energy asset management platform is already accomplished. Although, there are many aspects could allow us to make a more significant improvement for the current system. Regarding the trade-obetween computing resources consumption and transaction eciency, we should consider a better solution than existing POW ethereum network to reach a higher transaction throughput and a more secure system for the energy market. As for the ’currency’ for the p2p transaction of future energy asset management platform applications, we should adopt out own ’currency’ Performance will be boosted and scaled up and it can be carried with its own "token" issued in the future. The energy asset management platform applications token will serve as the fuel of the energy asset management ecosystem and can be developed based on other blockchain structure. In the primary market, the customers of, e.g. the aforementioned p2p transaction, pay for the EV services they need with ’token.’ As the blockchain technologies are continually evolving, I am very excited to see what the future brings. I hope you are too. Declaration

I hereby certify that I have written this thesis independently and have only used the specified sources and resources indicated in the bibliography.

Stockholm, 13. Nov 2018

...... My Name

Bibliography

[1] Jinsoo Park Sudha Ram Alan . Hevner, Salvatore . March. Design science in information systems research. 28(11):75–105, 2004. [2] .. Chan Bo Jiang, Ye Liu. Contractfuzzer: Fuzzing smart contracts for vulnerability detection. Cryptography and Security, 2018. [3] CEDEC. General guidelines for reinforcing the cooperation between tsos and dsos, May 2014. [4] Cott Moura Eric Munsing, Jonathan Mather. Blockchains for decentralized optimization ofenergy resources in microgrid network. 28:2164–2171, 2017. [5] IOTA foundation. Iota bitcoin wiki, May 2014. [6] IOTA foundation. Iota whitepaper, May 2014. [7] Lewis Freiberg. Instant feeless flash channels, September 2018. [8] Dominik Harz. Trust and verifiable computation for smart contracts in permis- sionless blockchains. KTH Master Thesis, 2017. [9] Anne Håkansson. Portal of research methods and methodologies for research projects and degree projects. World Congress in Computer Science, Computer Engineering, and Applied Computing,, 5:38–43, 2013. [10] Livio Pompianu Massimo Bartoletti. An empirical analysis of smart contracts: platforms, applications, and design patterns. Cryptography and Security, 2017. [11] Ralph C. Merkle. Protocols for public key cryptosystems. 1979. [12] Satoshi Nakamoto. Bitcoin: A peer-to-peer electronic cash system, 2008. [13] Neo. Neo white paper a distributed network for the smart economy, May 2014. [14] Davor Svetinovic Nurzhan Zhumabekuly Aitzhan. Security and privacy in de- centralized energy trading through multi-signatures, blockchain and anonymous messaging streams. IEEE Transactions on Dependable and Secure Computing, 99:1–1, 2016. [15] Powerledger. Power ledger (powr)-whitepaper, May 2014. [16] Raul. Transactions speeds: How do stack up to visa or paypal?, 2018. [17] Ronald L. Rivest. The md4 message digest algorithm. Advances in Cryptology- CRYPTO 90, 537(1-3):303–311, 1990. [18] Ronald L. Rivest. The md5 message-digest algorithm. RFC 1321, 1992. [19] Frank Wolak Severin Borenstein, James Bushnell. Measuring market ineciencies in californiaâs restructured wholesale electricity market. Information Quarterly, 92.5:1376â1405, 2002. [20] Harm van den Brink. How elaadnl built a poc charge station running fully on , and iota only., October 2017. [21] Qianchen Yu. Design, implementation, and evaluation of a blockchain-enabled multi-energy transaction system for district energy systems. Zurich Master Thesis, 2018. Appendices

Appendix A. A Source code Ethereum pragma solidity ^0.4.21; contract PV {

// parameter of PV address PvEnergySeller; // Public Address of PV energy seller uint public PVid; // PVidid int public currentVolumn = 300 ; //Capable volumn (kWh) int public sellVolumn ; int public price;// (gas/kWh) string message = ’This is a contract to sell energy from pv’; event Receive(uint value);

// Get cucrrent account balance of the PV function getBalance() public returns (uint) { return address(this).balance; }

function getEther() public payable { emit Receive(msg.value); }

// Sell the energy from a PV (Transaction will cost GAS) function sellEnergy( int _price, string _message, int _currentVolumn, int _sellVolumn ) public payable{ price = _price; message = _message; sellVolumn = _sellVolumn; currentVolumn = _currentVolumn - _sellVolumn; PvEnergySeller = msg.sender; emit Receive(msg.value); }

// Get the information from the Pv (only view, does not cost GAS) function getPV() public view returns( address _PvEnergySeller, string _message, int _currentVolumn, int _price ){ return(PvEnergySeller, message, currentVolumn, price); }

// deactivate the contract function destroyContract() public { selfdestruct(PvEnergySeller); }

function setPrice(int _price) public{ price = _price; }

} contract Charger {

// parameter of PV address public evCharger; // Public Address of PV energy seller uint public chargerId; // chargerId

bool public isAvailable = true; // If the charger is available then int public price;// (ether/kWh) string message = ’This is a contract to for charger’; event Receive(uint value);

// Get cucrrent account balance of the PV function getBalance() public returns (uint) { return address(this).balance; } function getEther() public payable { emit Receive(msg.value); }

// Rent the charger to Driver or EV fleet (Transaction will cost GAS) function rentCharger( int _price, bool _isAvailable, string _message) public payable{ price = _price; message = _message; isAvailable = _isAvailable; evCharger = msg.sender; emit Receive(msg.value); }

// Get the information from the EV (only view, does not cost GAS) function getPV() public view returns( address _evCharger, string _message, bool _isAvailable, int _price ){ return(evCharger, message, isAvailable, price); }

// deactivate the contract function destroyContract() public { selfdestruct(PvEnergySeller); }

function setPrice(int _price) public{ price = _price; } // function buyEnergy(){ }

} pragma solidity ^0.4.21; //For testing purpose contract Greeter { string public greeting; function Greeter() public { greeting = ’Hello’; }

function setGreeting(string _greeting) public { greeting = _greeting; }

function greet() view public returns (string) { return greeting; } } Appendix B. B Source code NEO using Neo.SmartContract.Framework; using Neo.SmartContract.Framework.Services.Neo; using Neo.SmartContract.Framework.Services.System; using System; using System.Numerics; using System.ComponentModel; namespace SC1prosumer { public class Prosumer : SmartContract { // token is the energy, 1 token = 1 kwh public static readonly byte[] Owner = "AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y".ToScriptHash(); // neo assetId: scriptHash public static byte[] neoAssetId = { 197, 111, 51, 252, 110, 207, 205, 12, 34, 92, 74, 179, 86, 254, 229, 147, 144, 175, 133, 96, 190, 14, 147, 15, 174, 190, 116, 166, 218, 255, 124, 155 };

public delegate void MyAction(T p0, T1 p1, T2 p2, T3 p3); public static event MyAction Transferred; public static Object Main(string operation, params object[] args) { if (Runtime.Trigger == TriggerType.Verification) { if (Owner.Length == 20) { return Runtime.CheckWitness(Owner); } else if (Owner.Length == 33) { byte[] signature = operation.AsByteArray(); return VerifySignature(signature, Owner); } } else if (Runtime.Trigger == TriggerType.Application) { if (operation == "sellSurplus") { // params: from, to, price, surplus volume if (args.Length != 4) return false; byte[] from = (byte[])args[0]; byte[] to = (byte[])args[1]; int price = (int)args[2]; int volume = (int)args[3]; return SellSurplus(from, to, price, volume); } if (operation == "txHistory") { // tbd } if (operation == "checksurplus") { // params: from if (args.Length != 1) return false; byte[] from = (byte[])args[0]; return CheckSurplus(from); } if (operation == "balanceOf") { if (args.Length != 1) return false; byte[] from = (byte[])args[0]; return BalanceOf(from); } } return false; // make sure this is the client //if (!VerifySignature(signature, client)) return false;

// get account of agent ad client //Account ageAccount = Blockchain.GetAccount(agent);

// get balance (surplus) of agent’s account //long balance = ageAccount.GetBalance(assetId); // see if there’s enough surplus //if (balance > volume * 100000000) return true; //else return false;

// create contract -- tbd } public static bool SellSurplus(byte[] from, byte[] to, int price, int volume) { if (price < 0) return false; if (volume < 0) return false; if (!Runtime.CheckWitness(from)) return false; if (from == to) return true; int amount = price * volume;

// substract surplus volume from sc1 user(seller) BigInteger from_volume = CheckSurplus(from); if (volume > from_volume) return false; if (from_volume == volume) Storage.Delete(Storage.CurrentContext, from); else Storage.Put(Storage.CurrentContext, from, from_volume - volume); // add balance to seller BigInteger from_balance = Update_balance(from, amount);

// add surplus volume to buyer BigInteger to_volume = Storage.Get(Storage.CurrentContext, to).AsBigInteger(); Storage.Put(Storage.CurrentContext, to, to_volume + volume);

// substract balance of buyer BigInteger to_balance = Update_balance(to, -amount); Transferred(from, to, price, volume); return true; } public static BigInteger CheckSurplus(byte[] from) { return Storage.Get(Storage.CurrentContext, from).AsBigInteger(); } public static BigInteger BalanceOf (byte[] from) { Account account = Blockchain.GetAccount(from); long balance = account.GetBalance(neoAssetId); return balance; }

public static BigInteger Update_balance (byte[] addr, int amount) { BigInteger updated_balance = BalanceOf(addr) + amount; return updated_balance; } } } using Neo.SmartContract.Framework; using Neo.SmartContract.Framework.Services.Neo; using System; using System.Numerics; namespace sc2Charger {

public class Chargers : SmartContract { // token is the energy, 1 token = 1 kwh public static readonly byte[] Owner = "AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y".ToScriptHash(); // neo assetId: scriptHash public static byte[] neoAssetId = { 197, 111, 51, 252, 110, 207, 205, 12, 34, 92, 74, 179, 86, 254, 229, 147, 144, 175, 133, 96, 190, 14, 147, 15, 174, 190, 116, 166, 218, 255, 124, 155 };

public delegate void MyAction (T p0, T1 p1, T2 p2, T3 p3, T4 p4, T5 p5, T6 p6); public static event MyAction Transferred; public static Object Main(string operation, params object[] args) { if (Runtime.Trigger == TriggerType.Verification) { if (Owner.Length == 20) { return Runtime.CheckWitness(Owner); } else if (Owner.Length == 33) { byte[] signature = operation.AsByteArray(); return VerifySignature(signature, Owner); } } else if (Runtime.Trigger == TriggerType.Application) { if (operation == "rentChargers") { //params: from, to, price, min, max, timeslot, chargerNum if (args.Length != 5) return false; byte[] from = (byte[])args[0]; byte[] to = (byte[])args[1]; int price = (int)args[2]; int minPowerRate = (int)args[3]; int maxPowerRate = (int)args[4]; int timeslot = (int)args[5]; int chargerNum = (int)args[6]; return rentChargers( from, to, price, minPowerRate, maxPowerRate, timeslot, chargerNum); } if (operation == "buyEnergy") { // params: from, volume if (args.Length != 1) return false; byte[] from = (byte[])args[0]; return CheckChargerNum(from); } if (operation == "balanceOf") { if (args.Length != 1) return false; byte[] from = (byte[])args[0]; return BalanceOf(from); } } return false; } public static bool rentChargers(byte[] from, byte[] to, int price, int minPowerRate, int maxPowerRate, int timeslot, int chargerNum) { if (price < 0) return false; if (minPowerRate < 0 || maxPowerRate < 0 || maxPowerRate < minPowerRate) return false; if (timeslot < 0 || timeslot > 7) return false; if (!CheckAvailableTime(timeslot)) return false; if (!Runtime.CheckWitness(from)) return false; if (from == to) return true; int amount = price * 2 * chargerNum;

// subtract charger num from sc2 users (chargers) BigInteger from_charger_num = CheckChargerNum(from); if (chargerNum > from_charger_num) return false; if (chargerNum == from_charger_num) Storage.Delete(Storage.CurrentContext, from); else Storage.Put( Storage.CurrentContext, from, from_charger_num - chargerNum);

// add balance to sc2 users Update_balance(from, amount);

// substract balance of buyer Update_balance(to, -amount);

Transferred(from, to, price, minPowerRate, maxPowerRate, timeslot, chargerNum); return true; } public static bool CheckAvailableTime(int timeslot) { // 1 timeslot equals 3 hours, 1 day has 8 timeslots if (timeslot == 1 || timeslot == 5 || timeslot == 7) return true; else return false; //int[] currentAvailableTime = new int[4] { 3, 5, 7, 1 }; //int id = Array.IndexOf(currentAvailableTime, timeslot); //if (id == -1) return false; //else return true; } public static bool BuyEnergy(byte[] from, byte[] to, BigInteger price, BigInteger volume) { // tbd return true; } public static BigInteger CheckChargerNum(byte[] addr) { return Storage.Get(Storage.CurrentContext, addr).AsBigInteger(); }

public static BigInteger BalanceOf(byte[] from) { Account account = Blockchain.GetAccount(from); long balance = account.GetBalance(neoAssetId); return balance; }

public static BigInteger Update_balance(byte[] addr, BigInteger amount) { return BalanceOf(addr) + amount * 100000000; } } } using Neo.SmartContract.Framework; using Neo.SmartContract.Framework.Services.Neo; using System; using System.Numerics; namespace sc3Driver { // this contract enable consumers //rent car from Eve fleet manager (sc4) in available time slot // public class SC3Driver : SmartContract { // token is the energy, 1 token = 1 kwh public static readonly byte[] Owner = "AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y".ToScriptHash(); // neo assetId: scriptHash public static byte[] neoAssetId = { 197, 111, 51, 252, 110, 207, 205, 12, 34, 92, 74, 179, 86, 254, 229, 147, 144, 175, 133, 96, 190, 14, 147, 15, 174, 190, 116, 166, 218, 255, 124, 155 };

public delegate void MyAction (T p0, T1 p1, T2 p2, T3 p3, T4 p4, T5 p5, T6 p6); public static event MyAction Transferred; public static Object Main(string operation, params object[] args) { if (Runtime.Trigger == TriggerType.Verification) { if (Owner.Length == 20) { return Runtime.CheckWitness(Owner); } else if (Owner.Length == 33) { byte[] signature = operation.AsByteArray(); return VerifySignature(signature, Owner); } } else if (Runtime.Trigger == TriggerType.Application) { if (operation == "chargeCar") { //params: from, to, price, min, max, timeslot, chargerNum if (args.Length != 4) return false; byte[] from = (byte[])args[0]; int price = (int)args[1]; int timeslot = (int)args[2]; int volume = (int)args[3]; return ChargeCar(from, price, timeslot, volume); } if (operation == "rentCar") { // params: from, volume if (args.Length != 1) return false; byte[] from = (byte[])args[0]; return CheckChargerNum(from); } if (operation == "balanceOf") { if (args.Length != 1) return false; byte[] from = (byte[])args[0]; return BalanceOf(from); } } return false; } public static bool ChargeCar(byte[] from, int price, int timeslot, int volume) { return true; } public static BigInteger CheckChargerNum(byte[] addr) { return Storage.Get(Storage.CurrentContext, addr).AsBigInteger(); }

public static BigInteger BalanceOf(byte[] from) { Account account = Blockchain.GetAccount(from); long balance = account.GetBalance(neoAssetId); return balance; }

public static BigInteger Update_balance(byte[] addr, BigInteger amount) { return BalanceOf(addr) + amount * 100000000; } } } TRITA -EECS-EX-2018:782

www.kth.se