9. Minimum Viable Product

1. Approach for the Minimum Viable Product

The broad scope of the intended technical concept required to split up the Minimum Viable Product (MVP) into three smaller Proof of Concepts (PoC) to focus on proofing the practicability of the technical concept theoretically. Furthermore, the partitioning made it possible to work simultaneously on different systems during the limited time of the hackathon. The first PoC regards the purposed private Blockchain as the operating network to secure the technical basis of proofing blocks. The second and third PoC are based on an additional, simplified Blockchain network as a development environment for defining smart contracts and deploying them to the Blockchain on the one hand and for connecting energy simulation data generated in Matlab with defined smart contracts, on the other hand. The following figure represents the three PoCs with details regarding the technical intents. Further on, every PoC is documented as a sub item of this chapter.

Figure 26 - Segmentations of the MVP

2. Blockchain as a Network

As already mentioned this part of the MVP is supposed to prove the technical foundation of the project. There is no need to prove that an Etherum-based network can be built as there are many projects that did already do so - including the fact that the actual Ethereum chain is up and running since 2015.

What is indeed a question open for discussion is how the Ethereum protocol should be implemented in the given scenario. Since the given hardware solely consists of Raspberry Pis that have very limited computation resources it has to be evaluated whether the aimed use case can be implemented.

Figure 27 - Blockchain

There are pre-existing projects that worked specifically on this question like Ethraspbian (http://www.ethraspbian.com/). The goal of this project was to use widely adopted solutions (like geth) and to build a network that ran a stable Blockchain although only using Raspberries for hardware.

2.1 Technical Overview

For the MVP a network using the Ethereum protocol was to be implemented. Of the five given Raspberries four were used as sealers. To tackle the problem of the limited resources the proof-of-authority consensus mechanism was employed. In the later network test it would have to be evaluated whether the proof-of-authority is sufficient to implement the system. The fifth Raspberry was used as a bootnode - a node with the sole purpose of pointing other nodes to their peers without having to link them manually.

2.2 Setup Tutorial

A detailed summary of the steps necessary to set up the network can be found in the subsection 6. Development of Technical Concept.

2.3 Network Communication

For this system to work the bootnode needs to be uniquely addressable in the network without that network address changing. To ease the overall work fixed IP-addresses were assigned to all nodes. The network this took place in was set up for this hackathon but it should be pointed out that there are no specific conditions for the network. Every standard IP-based network can be used for this setup which is important for later adoption. The exact IP-addresses can be seen in the following figure.

Figure 28 - Network Communication

Every node that is part of the network uses two ports: the 30130 port for the network and the 8545 port for remote-procedure-calls (RPC). Whenever a node starts the geth client automatically connects to the bootnode. Said bootnode saves the IP-address of the newly connected node for later distribution to other nodes. Whenever a node wants to transact it can look up its peers via the bootnode. Another important aspect is the RPC-port. This port is used by applications using the network for addressing accounts running on specific nodes.

2.4 Network Testing

The network testing done for this hackathon was a complete success. Not only could the nodes (and the accounts) transact with one another, it was also visible on the bootnode's command line interface. Here one could see the nodes ping each other. On the respective node's interfaces one could see them taking turns sealing the blocks. Therefore all functions associated with the network and furthermore the network port 30310 are functioning. This could also be proven while testing the functions associated with the RPC port 8545. Using this port one can establish a connection to one account running on the respective node in order to run geth on it. Any transaction issued using this procedure could be seen in the whole network. Therefore, the functionality of the Blockchain was proven. The following images shows that there are several new chain segements from nodes that are communicating with each other. There is also one chain segement that contains a transaction, marked in white.

Figure 29 - Live Network Testing

3. Network

This PoC targets the setup of an additional blockchain network as a development environment for defining smart contracts written in the programming language Solidity and deploying them to a blockchain network. This chapter exists of correlating subitems that represent the practicability of deploying several smart contracts to a blockchain network and accessing the contracts to enrich them with energy simulation data from Matlab.

3.1 Development Network

The first step of this PoC is to setup a blockchain network for mining blocks as a basis to deploy smart contracts as a further purpose. This chapter contains an overview of the development blockchain network and gives insights on how to setup this network.

3.1.1 Blockchain Overview

The development network is a simplified blockchain that is used as a basis to develop smart contracts and deploy them to the blockchain network. Due to these intents a simplified blockchain is sufficient because the ideal deployment shall be part of the operational blockchain as descibed in 2. Blockchain as a Network. The characteristics of the development network are as follows:

Blockchain Type: The development network is a private blockchain running the Ethereum protocol.

Number of Nodes: The development blockchain is accessed only via one node what is a minimalistic requirement for running a blockchain.

Node Implementation: By using Geth, the node is written in the programming language Go. There are other node clients but Geth has the highest share in the market.

Consensus: The consesus approach is proof of work which algorithm is based on the computing power of the node.

For deploying smart contracts into the blockchain network those characteristics are sufficient but minimalistic as well. The deployment of smart contracts is based on confirmed blocks, so mining is required implicitly for the development blockchain. For the purposed PoCs it does not matter if the consensus of the development network differs from the ideal operating blockchain one.

Figure 30 - Ethereum

3.1.2 Setup Tutorials

The setup of the development blockchain was done on a Windows 10 configured notebook. All necessary steps are enriched by screenshots and code snippets to improve the understandability. The overall setup is based on the following tutorials but had to be adapted due to the Windows operating system:

Smart Contract Tutorial

3.1.2.1 Installation of the command line interface Geth

The command line interface Geth allows to run a full ethereum node on the Windows 10 notebook and gives access to the established private Ethereum network.

1. Download the latest 64-bit installer of Geth for Windows:

Figure 31 - Geth Release Overview

2. Open the downloaded installer and agree on installing Geth:

Figure 32 - Geth Installation Confirmation

3. Select Geth to be installed:

Figure 33 - Geth Installation Options

4. Choose C:\Program Files\Geth as the destinated path:

Figure 34 - Geth Installation Path

5. Wait until installation has completed and close the installation window:

Figure 35 - Geth Installation Window

3.1.2.2 Establishing the private Ethereum network

The next logical step is to establish the private Ethereum network as a basis of deploying smart contracts. Several steps have to be performed using the Command Prompt having adminstrator rights.

1. Creating a directory for the project using Command Prompt:

mkdir project
cd project

2. Creating the genesis block to initialize the blockchain:

echo $null >> genesis.json

3. Change the created genesis.json file content to:

{
"config": {
"chainId": 42,
"homesteadBlock": 0,
"eip155Block": 0,
"eip158Block": 0
},
"alloc": {
"0x0000000000000000000000000000000000000001": {"balance": "111111111"},
"0x0000000000000000000000000000000000000002": {"balance": "222222222"}
},
"coinbase" : "0x0000000000000000000000000000000000000001",
"difficulty" : "0x20000",
"extraData" : "",
"gasLimit" : "0x8880000",
"nonce" : "0x0000000000000042",
"mixhash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"parentHash" : "0x0000000000000000000000000000000000000000000000000000000000000000",
"timestamp" : "0x00"
}

4. Use the Command Prompt to create a folder privchain to store the chaindata of the project:

mkdir privchain

5. Initialize chaindata with the genesis.json:

geth --datadir privchain init genesis.json

6. Run the private blockchain by opening a Command Prompt window and entering the following command:

geth --port 3000 --networkid 58342 --nodiscover --datadir=./privchain --maxpeers=0 --rpc --rpcport 8545 --rpcaddr 127.0.0.1 --rpccorsdomain "*" --rpcapi "eth,net,web3,personal,miner"

If successful the output of the Command Prompt looks as follows:

Figure 36 - Running Blockchain

7. Open the Geth Javascript console in an additional Command Prompt to interact with the blockchain:

geth attach http://127.0.0.1:8545

The output of the Command Prompt should look similiar to the following:

Figure 37 - Javascript Console

8. Create an account in the Javascript console by defining a password:

personal.newAccount('password')

After creating the account the account address can be retrieved:

Figure 38 - Account Address

9. Unlock the created account in the Javascript console:

personal.unlockAccount(‘0x419323c6f68a30954de5521700a7a5a21e7a6cec’, "password)

10. Mine Ether via the Javscript console to confirm blocks:

miner.start()

The output of the Command Prompt shall indicate new mining operations and look similiar to the following response:

Figure 39 - Mining Operation

3.2 Smart Contracts

As mentioned before, smart contracts enable the creation of contracts that are automatically filled with data when specific actions will take place. They do not necessarily need human interaction and due to this characteristic smart contracts are a promising approach for a peer to peer network in the energy market for automatically processing the energy consumption and provision.

3.2.1 Installing Solidity

Within the Ethereum blockchain smart contracts can be defined using different programming languages. The famoust programming language for smart contracts is Solidity, a JavaScript based highlevel language that targets the Ethereum Virtual Machine (EVM). Solidity is offering a lot of advantages, for example predefined libraries and features.

Solidity can be installed via the Command Prompt using the Paket Manager npm and the following the command:

npm install -g solc

The previous command installs the node module solc that is a library for complex functions regarding smart contracts.

Smart contracts represent the logic of the energy peer-to-peer network and enable digital contracts that are consistent, secure and transparent.

3.2.2 Energy Smart Contracts

In total there are four smart contracts as skeletons for the billing of a peer-to-peer energy market. The stakeholders are Load, CHP, Battery, Grid, and Pv, as mentioned 4.1 Matlab Simulation. The Grid represents the stakeholder that is responsible for the interconnection between all other stakeholders and is therefore the main stakeholder of the peer-to-peer network. The energy consumption and provision of the stakeholders are all linked to the Grid because of the Matlab Model that was designed this way.

As follows the Solidity code of the smart contract between Grid and Pv is being analyzed as an example:

SmartContractPv.sol
pragma solidity ^0.4.24;
contract SmartContractPv {
mapping(address => uint) public tokens;
event OnValueChanged(address indexed _from, uint _value);
address public otherAddr;
address public gridAddr;
uint public other_token;
uint public grid_token;
uint public other_token_live;
uint public grid_token_live;
function storeAddress(address other, address grid) public {
otherAddr = other;
gridAddr = grid;
}
function energyToken(uint otherKw) public returns (bool success){
other_token = otherKw;
grid_token = otherKw;
return true;
}
function depositTokens() public returns (bool success) {
other_token_live -= other_token;
tokens[otherAddr] -= other_token;
otherAddr.send(other_token);
grid_token_live +=grid_token;
tokens[gridAddr] += grid_token;
gridAddr.send(grid_token);
emit OnValueChanged(otherAddr, tokens[otherAddr]);
emit OnValueChanged(gridAddr, tokens[gridAddr]);
return true;
}
function getTokens(address x) public constant returns (uint value) {
return tokens[x];
}
function payMe() public payable returns(bool success) {
return true;
}
function fundtransfer(address etherreceiver, uint256 amount ) public {
if(!etherreceiver.send(amount)){
revert();
}
}
}

Considerable are the datatypes address for storing the addresses of the involved stakeholders and uint, an integer responsible for storing the recent energy token. These two parameters are dynamic datastores of the smart contracts that are filled with data everytime a smart contract is written. The tokens were developed as a representation of the actual energy transmision.

address public otherAddr;
address public gridAddr;
uint public other_token;
uint public grid_token;

The logic of the smart contract is applied by functions that were defined in Solidity before deploying the smart contract. First of all, storing the addresses of the involved stakeholder is a required step before tokens and Ether can be transferred between them. Due to the concept of using several micro contracts in the energy system, only two addresses are required compared to a solution with one global smart contract for all stakeholders. The following function, called storeAddress represents the functionality of storing given addresses as involved stakeholders in the smart contract:

function storeAddress(address other, address grid) public {
otherAddr = other;
gridAddr = grid;
}

The logic of the smart contract also contains several functions regarding storing and transfering tokens as well as Ether. Ether are transfered in exchange of consumed or provided energy tokens. The reason for this concept is the wanting of a complete representation of the energy system. These functions are described in several tabs below:

energyToken
depositTokens
getTokens
payMe
fundtransfer

The function energyToken stores a given amount of enery tokens in the datastore for the recent energy tokens and returns the boolean feedback true if successful.

function energyToken(uint otherKw) public returns (bool success){
other_token = otherKw;
grid_token = otherKw;
return true;
}

depositTokens is liable for adding or substracting the recent token that represents the recent energy transmission from the overall energy token of the stakeholders address. The method send() is responsible for transferring tokens from on to the other address. Furthermore, the event OnValueChanged is triggered for both involved addresses. The function returns true as a feedback if successful.

function depositTokens() public returns (bool success) {
other_token_live -= other_token;
tokens[otherAddr] -= other_token;
otherAddr.send(other_token);
grid_token_live +=grid_token;
tokens[gridAddr] += grid_token;
gridAddr.send(grid_token);
emit OnValueChanged(otherAddr, tokens[otherAddr]);
emit OnValueChanged(gridAddr, tokens[gridAddr]);
return true;
}

This function returns the overall energy token for an given address that is represented with the address x. Moreover, it is about a constant function that does not require gas when being called.

function getTokens(address x) public constant returns (uint value) {
return tokens[x];
}

The function payMe is a payable function that takes Ether and stores it at the address of the contract. This concept is required to liquidate the payment via the smart contracts. On success the function returns the boolean true.

function payMe() public payable returns(bool success) {
return true;
}

fundtransfer sends a given amount of Ether from the contract to the given address stored in etherreceiver. If sending the Ether to the given address is not successful the transfer is going to be reverted.

function fundtransfer(address etherreceiver, uint256 amount ) public {
if(!etherreceiver.send(amount)){
revert();
}
}
Figure 40 - Smart Contract Gif

3.3 Deployment of Smart Contracts

The defined smart contract logic must be deployed to the blockchain before the logic can be used calling the its functions. This chapter concerns the deployment of the smart energy contracts to the development blockchain.

3.3.1 Deployment Approaches

There are three approaches listed on how to deploy smart contracts to a blockchain. The specified approaches are the following:

Mist: A browser that offers an overview over the blockchain and provides functionality to manually deploy smart contracts.

Truffle: Is an Ethereum development framework for smart contract compilation and deployment management using an command line interface.

Web3: Is a collection of libraries that offers a programmatically interaction with local or remote nodes and therefore contains functions for the deployment of smart contracts.

The deployment via Truffle was best suited for the intention of deploying several smart contracts in one go. Truffle offers the compilation and deployment of several smart contracts using configuration files.

3.3.2 Deployment Tutorial

This tutorial includes the setup of Truffle as a deployment framework for smart contracts and on how to test the accessibility of the deployed smart contracts.

1. Install Truffle via the Command Prompt using npm:

npm install -g truffle

2. Create a folder truffle in the same directory as the project directory before and switch into that directory:

mkdir truffle
cd truffle

3. Initialize Truffle in the created truffle directory using the following command:

truffle.cmd init

4. Create a file called SmartContractPv.sol in the contracts folder:

echo $null >> SmartContractPv.sol

Paste the defined Solidity code of the smart contract defined in 3.2 Smart Contracts into that file:

5. Create a file called 2_deploy_contracts.js in the migration folder and paste the following code to reference the created smart contract:

var SmartContractPv = artifacts.require("./SmartContractPv.sol");
module.exports = function(deployer) {
deployer.deploy(SmartContractPv);
};

6. Replace the current code in truffle.js with the following configuration specification:

module.exports = {
networks: {
development: {
host: "localhost",
port: 8545, // port where your blockchain is running
network_id: "*",
gas: 4600000
}
}
};

7. Compile the smart contract via the Command Prompt in the truffle directory using the command:

truffle.cmd compile

8. Deploy the smart contract via the Command Prompt in the truffle directory:

truffle.cmd migrate –reset

It is important to unlock the account under which the deployment will take place via the Javascript console before deploying with this command:

personal.unlockAccount(‘0x419323c6f68a30954de5521700a7a5a21e7a6cec’, "password")

If successful the Command Prompt console will show a similar output:

Figure 41 - Smart Contract Deployment via Truffle

9. The deployed smart contract can be tested using the Truffle console. Before testing the Truffle console has to be opened from Command Prompt with:

truffle.cmd console

10. In the Truffle console the following code can be used to call the variable gridAddr from the deployed smart contract SmartContractPv:

var app
SmartContractPv.deployed().then(function(instance) { app = instance; })
app.gridAddr.call()

The output could look like this:

Figure 42 - Smart Contract Testing

3.3.3 Visualization in Mist

The deployed smart contract can be accessed manually via the Mist browser. Before importing the smart contract, Mist has to be installed. This chapter addresses both, the installation of Mist and the import of smart contracts into Mist.

3.3.3.1 Mist Installation

First of all the Mist browser must be installed to interact with its import functions for smart contracts. The installation can proceed as follows:

1. Download the latest Mist installer from GitHub :

Figure 43 - Mist Release Overview

2. Open the downloaded installer and agree on installing Mist:

Figure 44 - Mist Installation Agreement

3. Use C:\Program Files\Mist as the installation folder:

Figure 45 - Mist Installation Path

4. Use …\AppData\Roaming\Ethereum as location folder for the blockchain data:

Figure 46- Blockchain Data Installation Path

5. Run Mist via the Command Prompt using the local blockchain:

Start “” “C:\Program Files\Mist\mist“ –rpc http://127.0.0.1:8545

In Mist use the account by selecting the local user that was created in 3.1 Development Network.

3.3.3.2 Import of Smart Contracts

The address and the Application Binary Interface (ABI) of the deployed smart contract is required as an identifier in the blockchain. The next steps show how to visualize the deployed contract in Mist.

1. The two required information can be retrieved using the Truffle console and entering the two following commands:

SmartContractPv.address
JSON.stringify(SmartContractPv.abi)

2. Select Watch Contract in Mist and confirm the following form with the address and ABI of the deployed smart contract:

Figure 47 - Smart Contract Import

3. The smart contract is now visible and can be used for manual interaction:

Figure 48 - Smart Contract Overview in Mist

So far there are two smart contracts that have been deployed to the development blockchain. The grid is stakeholder in every smart contract due to the logic of the Matlab model.

4. In Mist smart contract information can be retrieved:

Figure 49 - Smart Contract Values

5. Furthermore the created functions that were written in Solidity can be executed:

Figure 50 - Smart Contract Execution

After blocks are mined in the blockchain value changes to the smart contract information can be recognized. The execution of smart contracts therefore requires mining.

3.3.4 Monitoring the blockchain

Visualizing the blockchain is a big advantages for managing ongoing transactions within the network. As follows, an approach for monitoring the blockchain is being described. The setup is based on the following tutorial:

Monitoring the private blockchain can be achieved using two tools that work together to visualize statistics and information about the blockchain. The backend service is called eth-netstats and the frontend will be provided from a service called eth-netstatus. The steps to setup the monitoring tools are listed below:

1. Download eth-netstats from GitHub.

2. Use the Command Prompt with admin rights and open the path of the downloaded project.

3. Install required NodeJS modules using the following commands:

npm install
npm install -g grunt-cli
grunt

4. Download eth-net-intelligence-api from GitHub.

5. Configure the app.json file that is located in the eth-net-intelligence-api directory:

app.json
[
{
"name" : "node-app",
"script" : "app.js",
"log_date_format" : "YYYY-MM-DD HH:mm Z",
"merge_logs" : false,
"watch" : false,
"max_restarts" : 10,
"exec_interpreter" : "node",
"exec_mode" : "fork_mode",
"env":
{
"NODE_ENV" : "production",
"RPC_HOST" : "127.0.0.1",
"RPC_PORT" : "8545",
"LISTENING_PORT" : "3000",
"INSTANCE_NAME" : "privchain",
"CONTACT_DETAILS" : "",
"WS_SERVER" : "http://localhost:3030",
"WS_SECRET" : "test",
"VERBOSITY" : 3
}
}
]

6. Install the production process manager PM2 using the Paket Manager npm:

npm install pm2

7. Start the app in the eth-net-intelligence-api directory location:

pm2 start app.json

If successful the following output is generated and the represents a running backend:

Figure 51 - Monitoring Backend

8. In a different Command Prompt change the path to the eth-netstats directory and execute the following command to start the frontend service:

set WS_SECRET=test&& npm start

9. In a browser the dashboard can be visited from http://localhost:3000:

If Geth is running the dashboard shows the running node and gives graphical insights into the statistics of the private blockchain e. g. the timing for confirming blocks:

Figure 52 - Blockchain Monitoring (1/2)
Figure 53 - Blockchain Monitoring (2/2)

4. Development

This PoC concerns the transmission between the energy simulation data generated in Matlab and the smart energy contracts. As a premiss the smart contracts have already been deployed to the blockchain, as described in 3.3 Deployment of Smart Contracts.

4.1 Matlab Simulation

Matlab is a productive software environment for simulating mathematical models and is used from engineers and scientists. In the context of this hackathon a Matlab model simulates the energy flow of various energy providers and consumers that are combined in an energy system. The model is a representation of a realtime energy system.

Figure 54 - Matlab Simulation

4.1.1 Matlab Installation

The usage of Matlab requries several steps that have to be considered before executing the simulation. The steps are described as follows:

1. MathWorks Account: First of all, a MathWorks account must be requested using a student e-mail address of Reutlingen University. This is the registration link.

2. Account Verification: After verifying the e-mail address an MathWorks account can be created.

3. Campus License Reference: Next, the Campus License of Reutlingen University must be referenced in the tab My Licenses.

4. Download Matlab: With a valid license the Matlab release R2018a can be downloaded from the tab Download Products.

5. Authentification: The MathWorks account must be authenticated using the given MathWorks credentials.

Still there are add-on packages that have to be installed when executing the real-time energy simulation.

The required Matlab packages can be retrieved from the following screenshot:

Figure 55 - Required Matlab Packages

4.1.2 Simulation Model

The Matlab model was provided by Petr Tugarinov who has developed a comprehensive energy system simulation which is the basis of the data that shall be stored in the smart contracts.

The following image represents an overview of the simulation model in Matlab which consists of various energy components:

Figure 56 - Matlab Model Overview

Aim of the simulation model is to calculate the energy provision or/and consumption from every component of the energy system. The Grid and the Battery are the only two components that can have positive and negative values, due to the fact that they can provide or consume energy. The time dimension of the Matlab model is designed to output energy data every 15 seconds that represents the intended energy data of 24 hours in a realtime scenario. Besides the amount of energy in kWh a price in euro/kWh is calculated as an output for every system component.

3.1.3 Data Transmission via UDP

A possible transmission approach for Matlab data is using the User Datagram Protocol (UDP) which is described in this chapter because it has already been set up by Petr Tugarinov.

3.1.3.1 Matlab Packet Output

The Matlab model contains functionalies to transmit data via UDP to a defined endpoint where the data can be accessed from other applications or devices. The functionality is applied using the Packet Output block that can be seen in the following image.

Figure 57 - Matlab Packet Output

The Packet Output block can be configured and contains the following settings for communicating locally with other applications:

Timing: Every 15 seconds a new dataset is transmitted.

Output size: A packet has the size of 10 parameter.

Data type: The output has the data type int8.

Host name: The local address127.0.0.1 is configured as host name.

UDP Port: The remote port which to listen to is 12703.

The output packet size represents the 5 components of the energy systems with its kWh and price/kWh value. The information are output to the local host due to the blockchain upload service that runs locally as well. The output packet field data type int8 makes it difficult to use all data from Matlab because the datatype can only store data from -128 to 127 and therefore values that are not in this range are not transmitted correctly.

3.1.3.2 Node UDP Listener

For connecting the Matlab simulation data and the smart contracts a JavaScript/NodeJS implementation is used because JavaScript offers, on the one hand, a comprehensive Web3 library for publishing data to smart contracts and, on the other hand, JavaScript allows to receive the UDP data that is send from Matlab. A JavaScript websever that can be started with the JavaScript runtime environment NodeJS is the overall environment that executes the UDP listener and uses Web3js the JavaScript version of the Web3 library.

The UDP listener code can be retrieved below and represents a socket connection that listens to the host 127.0.0.1 with port 12703 as defined in Matlab and executes the code that is stored in the method server.on() every time a UDP packet is being recognized from the listener.

var PORT = 12703;
var HOST = '127.0.0.1';
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
server.on('listening', function () {
var address = server.address();
});
//UDP Listener
server.on('message', function (message, remote) {
//Code an Logic
});

3.1.3.3 Transforming the data

Due to the fact, that the Matlab model sends the energy data as int8 datatypes some data cannot be transmitted properly when it is not part of the previously mentioned data range. Based on this circumstance, there is also an issue when receiving the Matlab data because in JavaScript the received data is stored in a hexadecimal buffer that solely stores positive values. Therefore, a conversion of negative data has to be done as reason of negative int8 Matlab data that is represented as an value overflow in the JavaScript buffer. The following code stores the ten energy values in the array output after converting buffer values which decimal values are higher than the value 127 to unsigned integer values by cause of negative Matlab values.

var output = [];
for(var i = 0; i < message.toString('hex').length; i=i+2){
var char = message.toString('hex').substring(i,i+2);
var solution;
if(hexToUnsignedInt(char)>127){
solution=hexToSignedInt(char);
}else{
solution=hexToUnsignedInt(char);
}
if(i==16){
solution=output[0]+output[2]-output[4]+output[6];
}
output.push(solution);
};
console.log(output);

As an result JavaScript logs the array output every 15 seconds containing different values as Matlab sends energy data in the same time interval. The data format of the array is as follows:

[kWh_Pv, euro/kWh_Pv, kWh_CHP, euro/kWh_CHP, kWh_Load, euro/kWh_Load, kWh_Battery, euro/kWh_Battery, kWh_Grid, euro/kWh_Grid]

If a working connection is set up the logged simulation data from the UDP listener in JavaScript shall look like this:

Figure 58 - Logged Simulation Data

4.2 Data in Smart Contract

The received data from the JavaScript UDP Listener must be partially published to different smart energy contracts between the components of the energy system. In the previous PoC the smart contracts have already been deployed to the blockchain where the logic can be accessed.

4.2.1 Introduction to Web3js

The existing smart contract can be addressed from several programming languages. As JavaScript offers big adavantages due to a comprehensive Web3 library Web3js is used to address the deployed smart contracts.

Web3js is a broad collection of libraries that can be used to programatically interact with a local or external blockchain. The JavaScript Web3 API implements a generic JSON RPC specification and offers a simple interface for transmitting data to the blockchain.

4.2.2 Datatypes to store information

In the programming code there are several datastores that contain important information that are necessary to perform the smart contract logic. Required datastores are the account information for addressing the stakeholders of the energy system and the contract information. The array nodes contains the addresses and passwords for all the stakeholders.

var nodes=[
['0x14d29918c4738671a0b6efc7328b005a1d8d3159','password'], //Grid
['0x1dfb9f1349d88ac963a97dcb54b279aca3d6768e','password2'], //Pv
['0xa53d64b9e96162bea6e377e26339fae667f46f0d','password3'], //CHP
['0x17f993e86a0bf0eeb0a04b26767d0ec9e88df1cc','password4'], //Battery
['0x0eff20bc520571a067818040dbf55adbfafb199c','password5'] //Load
];

For accessing the deployed smart contracts the contract address and contract ABI is required. Both information have to be provided for all four contracts.

So far there are the two smart contracts between Grid and Pv and between Grid and CHP deployed to the development blockchain.

var contracts=[
[contractAbiGridPv,'0x9cbcc6f95c6a1a5e0f9913155ad190d115a15884'], //Grid_Pv
[contractAbiGridCHP,'0x7c16c0d30ca49b828a21be59b6a332d77558290e'], //Grid_CHP
[,], //Grid_Load
[,] //Grid_Battery
];

4.2.3 Used Web3js functions

The Web3js library offers the functionality to create a contract instance of previously deployed contracts. This functionality requires the contract address and contract ABI to identify the contract. Both information are stored in the mentioned datastore contracts. The following code is responsible for creating a contract instance and defining characteristics for the transaction object.

var contractAbi=_contractAbi;
var contractAddress=_contractAddress;
const contract = web3.eth.contract(_contractAbi);
const contractInstance = contract.at(_contractAddress);
const transactionObject = {
from: _grid,
gas: "1000000"
};

For performing further Web3 logic the account under which the logic is execuded must be unlocked. The function unlockAccount(address, password) unlocks accounts if the address/password key pair is correct.

web3.personal.unlockAccount(_grid, _gridpw);
web3.personal.unlockAccount(_from, _frompw);

The logic of the energy systems is not stored in the JavaScript code but is stored in the smart contracts which have already been deployed. The JavaScript webserver executes the logic stored in the smart contract by calling its variables and funtions. The following components are contained in the JavaScript programming code:

Store Addresses: Changes the smart contract addresses to the addresses of the involved components of the energy system:

contractInstance.storeAddress.sendTransaction(_from, _grid, transactionObject, (error, result) => { });

Payment: Transfers Ether from one address to the address of the smart contract and sends it in a second step to the receiver as payment for provided or consumed energy:

var _value=web3.toWei(_kwh*_price, "finney");
contractInstance.payMe({from: _grid, gas: 1000000, value: _value}, function(err, res){});
contractInstance.fundtransfer.sendTransaction(_from, _value, transactionObject, (error, result) => { });

Token Exchange: Transfers energy tokens as a digital twin of the provided or consumed energy:

contractInstance.energyToken.sendTransaction(_kwh*_price, transactionObject, (error, result) => { });
contractInstance.depositTokens.sendTransaction(transactionObject, (error, result) => { });

5. Proof of MVP

As a proof of automatically sending energy data to two different smart contracts the following screenshot of the JavaScript console can be conducted. The screenshot represents the received Matlab data as an array and the written contract information at the time when the first data was received via UDP:

Figure 59 - Proof of MVP

The following section refers to provide evidence for the proof of the MVP based on the previous screenshot. The functionality was tested on the development network but can also be used on the operative blockchain, described 2. Blockchain as a Network.

Distinctive Addresses: Both smart contracts as well as the involved accounts do have different addresses within the blockchain network. The Ether balances of the stakeholder and contract addresses differs as well.

Consistent Stakeholder: The Grid with its address 0x14d29918c4738671a0b6efc7328b005a1d8d3159 is part of both smart contracts.

Energy Token: Both smart contracts have different energy values that were calculated from the Matlab simulation data.

Write Initiation: Both smart contracts were written based on the same UDP initiation at second 15.

Moreover, the MVP focuses on the automation of the energy system and therefore the described concept is well-suited due to the fact that manually approving transactions by the stakeholders is not required anymore.

Figure 60 - Automatic Smart Contract

6. Programming Code

The actual programming code can be retrieved from the following public GitHub repository:

This chapter gives an overview of the stored programming projects on the GitHub and describes them briefly:

EthereumContractDeployment: The main project where the blockchain and smart contract data is storred.

There are three subfolders in the project EthereumContractDeployment containing the JavaScript logic, the actual development blockchain data and the smart contract data used within Truffle.

eth-netstats-master: The backend of the external monitoring app for accessing the running blockchain.

eth-net-intelligence-api-master: The frontend of the external monitoring app that visualizes the data from the monitoring backend.