New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce...

97
FACULDADE DE E NGENHARIA DA UNIVERSIDADE DO P ORTO Decentralized Application for E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics and Computing Engineering Supervisor: Pedro Souto July 28, 2020

Transcript of New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce...

Page 1: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

FACULDADE DE ENGENHARIA DA UNIVERSIDADE DO PORTO

Decentralized Application forE-Commerce Using Blockchain and

Trusted Compute

João Carlos Oliveira Lago

Masters in Informatics and Computing Engineering

Supervisor: Pedro Souto

July 28, 2020

Page 2: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Decentralized Application for E-Commerce UsingBlockchain and Trusted Compute

João Carlos Oliveira Lago

Masters in Informatics and Computing Engineering

July 28, 2020

Page 3: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Resumo

De momento, soluções centralizadas para comércio eletrônico são a principal escolha do con-sumidor para efetuar comércio online, o que leva a grandes empresas possuírem enormes porçõesdos nossos dados privados e a controlarem a forma como realizamos comércio. Isto implica inter-mediários nestas empresas com poder de nos espiar e, potencialmente, vender os nossos dados ouusá-los para ganho de terceiros. Ao dar tanto poder a instituições e governos para nos monitorizar,corremos o risco de uma grande deterioração das nossas liberdades.

Em dar tanto controlo para tão poucas empresas efetuarem o nosso comércio, também podepermitir a que intermediários sem nome manipulem os consumidores, apresentando-lhes com in-formações em favor dos interesses dessas grandes empresas. Também permite a censura de par-ticipantes que usam os tais serviços centralizados e a aplicação de elevadas taxas, entre outrosproblemas associados à centralização do comércio eletrônico para apenas algumas grandes em-presas.

A descentralização do comércio eletrônico é uma possível solução para o intermediário, sendoque negócios realizados diretamente entre comprador e vendedor resultaria na remoção do inter-mediário e como tal os problemas anteriormente mencionados deixariam de estar presentes.

Este trabalho será benéfico para todos que usem serviços centralizados para efetuar comércioeletrônico, e em longo prazo pode ajudar a evitar tirania por parte de grandes empresas ao possi-bilitar mais liberdades, menos censura e maior controlo sobre os nossos dados pessoais, e tudo acustos acessíveis.

Neste documento é apresentada uma alternativa às plataformas de comércio eletrônico maisusadas atualmente, ao aproveitar os benefícios da descentralização, tentando manter a facilidadede uso crucial das soluções de comércio eletrônico centralizadas.

Através do uso de várias tecnologias, principalmente a blockchain, contratos inteligentes, etrusted compute, o foco do projeto é criar código que combine todas estas tecnologias para criaruma alternativa descentralizada para o comércio eletrônico. Esta deve ser rápida, escalável, e fácilde usar. Numa breve explicação, a blockchain e contratos inteligentes seriam usadas como a ca-mada base da aplicação sendo que esta camada mantém o estado da aplicação de forma fidedigna,enquanto que a trusted compute seria usada para computações que seriam demasiado custosas paracorrer em contratos inteligentes.

PALAVRAS-CHAVE: e-commerce, blockchain, bitcoin, sistemas distribuídos, contratos inteligentes,criptomoedas, descentralização

i

Page 4: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Abstract

Currently, centralized e-commerce solutions are the mainstream consumer choice for onlinetrade which leads to large companies owning big portions of our private data and controlling howwe conduct business, this entails middleman in these companies with power to spy on us andpotentially sell our data or make use of it for third party gain. By giving away such tremendouspower to institutions and governments to monitor us, we risk a major deterioration of our freedoms.

Handing over this much control to few large entities for conducting our electronic commercecan also enable nameless middleman to manipulate consumers by feeding them information in fa-vor of their interests, allow for censorship of the participants using the centralized services and theapplication of high fees among other problems associated with the centralization of e-commerceto a few large entities.

The decentralization of e-commerce would provide a solution to the middleman, as businesswould be performed on a peer-to-peer basis and consequently, with the removal of the middleman,the aforementioned issues would cease to exist.

This work will benefit anyone who uses centralized e-commerce and in the long term it mighthelp everyone avoid tyranny by providing more freedoms, less censorship and more ownership ofour own data, at cheaper costs.

In this document it’s presented an alternative to commonly used online commerce which lever-ages the benefits of decentralization while attempting to maintain the crucial ease of use fromcentralized electronic commerce solutions.

Through the use of several technologies, mainly blockchain and trusted compute, this projectaims to create code which glues these all together in an effort to create a scalable, fast and easyto use decentralized alternative to online commerce. Explained very briefly, the blockchain andsmart contracts are used as the base layer for trustless state handling and other back-end tasks suchas escrow, while trusted compute is used for intensive computations which would be too expensiveto run on smart contracts.

KEYWORDS: E-commerce. Blockchain. Bitcoin. Distributed systems. Smart contracts. Cryp-tocurrencies. Decentralization

ii

Page 5: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Acknowledgments

I am grateful for my supervisor, professor Pedro Souto, for the incredible commitment to helpme with this dissertation.

I want to thank my faculty colleagues for moral support and overcoming this task together.And of course, I want to express appreciation for my family and their moral support through

the making of this work.

João Lago

iii

Page 6: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

“Once a new technology rolls over you,if you’re not part of the steamroller, you’re part of the road.”

Stewart Brand

iv

Page 7: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Contents

1 Introduction 11.1 Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.3 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.4 Dissertation Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

2 Literature review 32.1 The Blockchain and Bitcoin . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32.2 Smart Contracts and Ethereum . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.3 Trusted Compute Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92.4 Oracles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102.5 Intel SGX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112.6 Scone . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122.7 InterPlanetary File System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132.8 iExec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

2.8.1 Who Are The Users or Requesters . . . . . . . . . . . . . . . . . . . . . 162.8.2 What Are The Accounts . . . . . . . . . . . . . . . . . . . . . . . . . . 162.8.3 What Are The Apps, Datasets and Workerpools . . . . . . . . . . . . . . 172.8.4 What Are The App, Dataset and Workerpool Orders . . . . . . . . . . . 172.8.5 How a Task is Executed . . . . . . . . . . . . . . . . . . . . . . . . . . 172.8.6 How Consensus is Established . . . . . . . . . . . . . . . . . . . . . . . 182.8.7 How Permissioning Works . . . . . . . . . . . . . . . . . . . . . . . . . 192.8.8 iExec Oracle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

3 Application 213.1 Roles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223.2 Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

4 Dapp Design 244.1 System’s architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

4.1.1 Ethereum Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254.1.2 Workerpools Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . 264.1.3 Interface Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274.1.4 Other Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

4.2 Use-Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284.2.1 Logging In . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284.2.2 Selling a Product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304.2.3 Handling Private Information . . . . . . . . . . . . . . . . . . . . . . . 33

v

Page 8: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

CONTENTS vi

4.2.4 Making a Purchase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

5 Dapp Implementation 485.1 Tools Used . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485.2 Web Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485.3 Ethereum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525.4 iExec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

6 Dapp Evaluation 576.1 Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

6.1.1 Ethereum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576.1.2 iExec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

6.2 Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596.2.1 Ethereum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596.2.2 iExec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

6.3 Cost . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 616.3.1 Ethereum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 616.3.2 iExec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

7 Conclusions 657.1 Achieved Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 657.2 Future Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

7.2.1 Dispute resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667.2.2 Sybil Attack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667.2.3 Accepting Cryptocurrencies . . . . . . . . . . . . . . . . . . . . . . . . 677.2.4 Ethereum Meta Transactions . . . . . . . . . . . . . . . . . . . . . . . . 67

A Setting up the web client 68

B Dispute resolution 69

C Source Code Listings 72

Page 9: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

List of Figures

2.1 Transaction sequence diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.2 Remote attestation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

4.1 Interaction between blockchain and user interface . . . . . . . . . . . . . . . . . 254.2 Decentralized e-commerce component diagram . . . . . . . . . . . . . . . . . . 254.3 Infura service interaction with the web client . . . . . . . . . . . . . . . . . . . . 284.4 Logical architecture of Smart Contracts, from the Purchase Side . . . . . . . . . 284.5 Logged out web client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294.6 Logged in account . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304.7 Product selling form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314.8 Product form marketplace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324.9 Component diagram when calling deployProduct . . . . . . . . . . . . . . . . . 324.10 Access to client information from the Dapp@iExec . . . . . . . . . . . . . . . . 334.11 Client Information displayed on web client . . . . . . . . . . . . . . . . . . . . . 344.12 Client Information deployment form . . . . . . . . . . . . . . . . . . . . . . . . 364.13 Catalog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374.14 Ongoing purchase or order in the first stage . . . . . . . . . . . . . . . . . . . . 384.15 Component diagram when calling ’performorder’ . . . . . . . . . . . . . . . . . 394.16 Component diagram involved in the buying of a product . . . . . . . . . . . . . 404.17 Ongoing purchases information tables . . . . . . . . . . . . . . . . . . . . . . . 414.18 Order state machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424.19 Balance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424.20 Order waiting for confirmations . . . . . . . . . . . . . . . . . . . . . . . . . . 434.21 User allowing the order contract to manage 20 RLC of the user’s balance . . . . . 434.22 Ongoing purchase at the second stage . . . . . . . . . . . . . . . . . . . . . . . 444.23 Ongoing purchase awaiting validation . . . . . . . . . . . . . . . . . . . . . . . 454.24 Interaction with the iExec stack . . . . . . . . . . . . . . . . . . . . . . . . . . . 454.25 Encrypting client information with seller’s public key . . . . . . . . . . . . . . . 464.26 Last stage of an order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

5.1 Interaction between blockchain and user interface . . . . . . . . . . . . . . . . . 49

6.1 Scone-Based SGX PySpark Performance . . . . . . . . . . . . . . . . . . . . . 586.2 Mining pools share of hashing power . . . . . . . . . . . . . . . . . . . . . . . . 606.3 Ethereum’s fee vs network utilisation chart . . . . . . . . . . . . . . . . . . . . . 626.4 Ethereum’s average daily fee in Gwei . . . . . . . . . . . . . . . . . . . . . . . 63

vii

Page 10: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

List of Tables

6.1 Some of the DAPP’s off-chain executions . . . . . . . . . . . . . . . . . . . . . 596.2 Transactions’ cost . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

B.1 Nash equilibrium . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69B.2 Dispute resolution payoff matrix . . . . . . . . . . . . . . . . . . . . . . . . . . 70B.3 Dispute resolution payoff matrix attack . . . . . . . . . . . . . . . . . . . . . . . 71

viii

Page 11: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

List of Code Listings

4.1 Dataset contract provided by iExec . . . . . . . . . . . . . . . . . . . . . . . . . 334.2 Client information in file format . . . . . . . . . . . . . . . . . . . . . . . . . . 354.3 Dataset order object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365.1 reloadProducts function from the Web Client . . . . . . . . . . . . . . . . . . . 495.2 buyThisProduct function from the Web Client . . . . . . . . . . . . . . . . . . . 505.3 approveAndCall function from RLC.sol [1] . . . . . . . . . . . . . . . . . . . . 525.4 receiveApproval function from Order.sol . . . . . . . . . . . . . . . . . . . . . . 525.5 runDataValidation function from Order.sol . . . . . . . . . . . . . . . . . . . . . 535.6 completePurchase function from Order.sol . . . . . . . . . . . . . . . . . . . . . 545.7 entrypoint file app.py of the off-chain application . . . . . . . . . . . . . . . . . 555.8 _sendRequestAPI function from verifyAddress.py . . . . . . . . . . . . . . . . . 555.9 addressApi.json . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565.10 callback and determinism functions from utils.py . . . . . . . . . . . . . . . . . 56C.1 ItemFactoy.sol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72C.2 Item.sol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72C.3 Order.sol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73C.4 app.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77C.5 verifyAddress.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77C.6 creditcardcheck.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78C.7 utils.py . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79C.8 resources.json . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80C.9 exceptions.json . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80C.10 addressApi.json . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80C.11 Dockerfile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

ix

Page 12: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Symbols Abbreviations

UTXO Unspent Transaction Output

EEA Ethereum Enterprise Alliance

TCF Trusted Compute Framework

SGX Software Guard Extensions

IAS Attestation Service for Intel SGX

DLT Distributed Ledger Technology

API Application programming interface

IPFS InterPlanetary File System

SCONE Secure Container Environment

DAPP Decentralized Application

TEE Trusted Execution Environment

SMS Secret Management Service

ABI Application Binary Interface

EVM Ethereum Virtual Machine

x

Page 13: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Glossary

Enclave Private region of memory secured through Intel’s SGX, where data is protected from

being read by any outside process, including privileged host processes.. 10–13, 58, 59, 61

ETH Otherwise known as Ether, it’s the digital currency used as fuel in the Ethereum platform..

9, 16, 30

Gwei A denomination of ETH, where 1e−9 Ether equals 1 Gwei. vii, 7, 61–63

IAS Attestation service, hosted by Intel, whose main goal is attesting Intel’s SGX created enclaves

to a replying party. Otherwise known as remote attestation.. 11

Task A Task relating to iExec is a computational job that needs computing power to be executed..

14–19, 44, 45, 59

USD The official currency of the United States of America.. 62–64

xi

Page 14: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Chapter 1

Introduction

This project merges together a wide range of technologies associated with distributed systems,

in an effort to provide a scalable but yet decentralized solution to electronic commerce, where

there doesn’t need to be one or more entities controlling all the information and processes for

all parties involved in digital trade. It takes advantage of the advances in decentralization pro-

vided by blockchain and smart contracts while maneuvering around its shortcomings with other

technologies, namely trusted compute.

1.1 Context

International electronic commerce is concentrated to a few large companies such as eBay,

Amazon, AliExpress, and Wish [2].

This level of centralization in the way we conduct our trades is unprecedented in human his-

tory and gives away immeasurable power to a few large entities, therefore making the general

population more controllable and paving the way for the deterioration of our freedoms.

1.2 Motivation

As centralized electronic commerce platforms have middleman expenses and can easily col-

laborate when setting fees on goods sold due to being few in number, fees on these platforms

are expected to be high. There’s also the issue of the censorship forced on by governments and

the platform owner’s ideals and beliefs, and the lack of privacy as we need to provide our name,

address, contact and payment methods to these centralized entities.

1.3 Objectives

The main objective of this work is to explore a way to remove the middleman from our online

commerce while still retaining the features and characteristics present in centralized e-commerce

1

Page 15: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Introduction 2

platforms that are necessary to achieve mainstream adoption in a private, decentralized and scal-

able alternative.

1.4 Dissertation Structure

In addition to this chapter, this document has six more chapters. In the next chapter, we survey

the state of the art related to the technological aspects of decentralized e-commerce and relevant

concepts that provide detailed technical information on the core technologies used for this project.

With a focus on Ethereum and iExec so the reader can more easily understand the following

chapters.

The third chapter presents in more detail the problem this work tries to address, by describing

the requirements of an application that supports decentralized e-commerce.

Chapters 4 to 6 describe the design, the implementation and the evaluation of a decentralized

e-commerce application that satisfies the requirements presented in Chapter 3.

The seventh and last chapter concludes with a summary of the main contributions of the work

documented in this report and elaborates on future work that would further flesh out this project.

Page 16: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Chapter 2

Literature review

In this section we review the state of the art of the relevant technologies to this work.

2.1 The Blockchain and Bitcoin

Blockchain technologies were popularized with the emergence of Bitcoin at the start of 2009,

brought by an anonymous person or group called Satoshi Nakamoto and their whitepaper entitled

"Bitcoin: A Peer-to-Peer Electronic Cash System" [3]. As the name of the whitepaper suggests,

Bitcoin enables peer-to-peer transfer of a digital money whose scarcity and useful characteristics

such as being portable, durable, divisible and fungible give it a perceived value.

Bitcoin is the solution of the double spending problem in digital currencies. This problem

arises when a party sends the same digital token, representing some digital currency amount, to

multiple different parties and thus creates new tokens, one for each different party, essentially

spending the same digital cash more than once.

Bitcoin uses Proof of Work, known before mainly for its implementation in the Hashcash

system to prevent denial-of-service attacks and spam emails [4]. The Proof of Work consensus

algorithm adjusts difficulty to mine new Bitcoins so that it takes miners around 10 minutes to find

the winning hash and include the next block to the chain which includes Bitcoin transactions made

during those 10 minutes. During this interval of time the whole network can also get in sync with

the latest work done for the chain.

Finding the winning hash is a matter of probability, and the more computational power a miner

has to compute new hashes per second, the higher the probability that it will find the winning hash.

The winning hash is a hash whose number of leftmost zeros is the required length based on current

difficulty levels, the higher the difficulty level the lengthier the number of leftmost zeros on the

hash needs to be. Difficulty level is managed based on the amount of processing power, or hash

rate, available at present on the network and the higher the global hash rate is, the harder the

difficulty level needs to be to maintain the 10 minute interval between new blocks added to the

chain.

3

Page 17: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Literature review 4

Besides the intervals between blocks, each block has a limited space for which to store trans-

actions. The limit was initially set to 1 Megabyte [5] but as since changed to around double the

size.

Bitcoin manages accounts with public-key cryptography, an account can be thought of as a

public-private key pair where transactions are signed with the private keys, and the destination

addresses, where Bitcoins are sent, are public keys. Balances are managed through a system

of unspent transaction outputs, or UTXO, where an account’s balance is the sum of all UTXOs

belonging to it. When an account spends Bitcoins, it aggregates enough of its UTXOs, which

were from transactions made to it, and uses them as input for the new transaction, these UTXOs

become spent and no longer usable. If the sum of the UTXOs exceeds the amount required for the

transfer then a new UTXO is created for the account with the difference minus the transaction fee.

Every transaction needs to be accompanied with a fee payed in bitcoins by the sender to the

miner which includes it in a block. Otherwise, the miner won’t have any incentive to include a

fee-less transaction in a block.

In order to execute a transaction, i.e. include it in the Blockchain, a user sends it to a node

in the Bitcoin network, which then spreads it to the other nodes, so that it eventually is received

by most nodes. Every node stores the transaction in what is called the mempool, where tentative

transactions the node receives get stored. When a node finds the winning hash that warrants it gets

to include the next block to the chain and receive the reward in Bitcoins, the transactions it chooses

to include in the block are removed from its mempool and if the transactions exceed the limit size

of the block, the miner will prioritize the transactions that include the highest fees. Therefore due

to the limit in block space, the transactions that pay the higher fees have priority to be included in

the blockchain.

When two incompatible transactions that together would place its account’s balance in the

negative get included in the tentative transaction mempool, where all transactions exist before

getting included in a block, the transaction that first gets added to a block will invalidate the second

one. If the two transactions get included in different blocks, and those blocks are concatenated to

different chains, then the longest chain will include the transaction that prevails. In the Proof of

Work consensus algorithm, miners are economically motivated to mine only for the longest chain

since mining for a soon to be dead chain is a waste of resources. Any other shorter chain either

doesn’t survive or remains as a fork, or new blockchain, sharing only the same history from the

point it first forked from the main chain.

After a transaction gets included in a block and added to the chain, the party in the receiving

end of the transaction should wait for at least a few more block to be added to the chain before

considering the transaction valid. As for every block added after a transaction is included is a

confirmation that the transaction was indeed included on the longest chain. In other words, the

higher confirmation number a transaction has, the exponentially higher the probability the trans-

action was included on the main chain, and thus not a shorter chain that dies off. Confirmations

are important to reduce the chance of being victim to a double spend attack.

A high accumulated hash rate on the Bitcoin network makes the Bitcoin network safer and

Page 18: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

2.2 Smart Contracts and Ethereum 5

less prone to attacks due to a higher cost to do so, such as the most famous attack vector for the

Bitcoin network, the 51% attack. The 51% attack happens when more than half of the mining

hashing power is allocated to one or a few collaborating entities, in this case scenario the entity

or collaborating entities are able to perform double spends. This is done by creating two chains,

each containing a different incompatible transaction, and the attacker is able to mine concurrently

for the two chains, where there isn’t a longest chain for enough time that both incompatible trans-

actions get enough confirmations to appear valid.

A few alternatives to the Proof of Work consensus algorithm have been proposed such as the

less resource intensive Proof Of Stake [6], which shares the same principles to Proof Of Work, but

instead of being the amount of hash power that indicates the probability to mine a block, it’s the

amount of coins or tokens of the chain a miner, or staker in this case, has that sets the probability

of mining a block and getting the reward for it. This raises a concern of having nothing at stake

when mining for chain forks, as in the Proof Of Work algorithm miners have economic incentive

to not waste resources mining for shorter chains but for the Proof Of Stake algorithm a staker can

stake for any chain without the worry of wasting resources doing it and this in turn could lower

the percentage of stake in the network needed to perform a double spend attack drastically from

its sibling Proof Of Work 51%.

Other alternatives to the Proof Of Work algorithm are mainly variants of the Delegated Proof

of Stake [7] algorithm, which sacrifice decentralization in trade for higher performance and trans-

action throughput by having all stake holders vote for a small group of highly equipped miners

or pools, where each vote is weighted by the amount of stake, or tokens staked, of the voter.

Blockchains supported by this consensus algorithm are byzantine fault tolerant, in that at least

2/3rds of the small group of miners need to be trusted, or in other words, if 1/3rd or more of the

small group of miners are traitorous the blockchain is at risk of attack.

2.2 Smart Contracts and Ethereum

Traditional programs implemented in code stored and executed in computers owned and con-

trolled by centralized entities are subject to alteration by the owners of said computers, and thus

lack integrity and trust that the correct code is executed with the provided inputs.

By leveraging Blockchain and Smart Contract technology a platform could be created which

would allow for the seller to sell any item without having to pay monthly hosting fees or middle-

man.

The seller would pay a few cents to interact with the Smart Contract hosted by the Blockchain,

allowing the seller to publish the product’s details and terms of purchase to the immutable database

which is the Blockchain. The smart contract would implement the value transfer business logic

transparently through the blockchain, guaranteeing code integrity for all parties involved.

Bitcoin essentially allows the movement of digital money from one account to other accounts.

Although useful it is somewhat limited. Ethereum [8] supports transactions that when executed

Page 19: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Literature review 6

allow not only to transfer money from one account to others, but also to execute user-defined

programs, which are known as smart contracts.

Smart contract platforms such as Ethereum provide what can be seen as a global world com-

puter, with no owner or entities controlling what’s stored and executed on this world computer,

effectively supporting a censorship resistant, immutable storage where programs, known as smart

contracts, can manage digital money without the need for trust in a third party.

A smart contract can be viewed as a class of objects on Ethereum, whose programming is

based on a state machine where the state can be changed with a call to any of the functions im-

plemented in the smart contract. The objects created from said smart contracts can send and

receive in the monetary value kept by the DLT, however these transfers of value would have to

follow the requirements and logic implemented in whichever function is called from the smart

contract instance. All changes to the state of the contract can only be done by the business logic

implemented in the smart contract code. For each state change, nodes in the network verify the

validity of each and if all requirements, business logic and authorizations from the executed smart

contract’s immutable code were followed correctly.

The account system works through the use of public key cryptography. More specifically the

ECDSA algorithm is used to generate key pairs where the public key is a string of 64 bytes that

can be shared with anyone and the private key is a secret for the owner. The public key is hashed

with the keccak-256 algorithm and from the first 20 bytes of the result we get the address. An

account in the Ethereum blockchain then is identified by the address.

Just like Bitcoin, Ethereum keeps track with its Blockchain of the balance each account has,

however the system used for this is not the UTXO system but a simpler model where each account

records a balance and when a transfer is made the amount is simply subtracted from one account

and added to the other. This simpler model raises the problem that an attacker can just replay

the signed transaction to the network and have it mined all over again, however Ethereum solves

this by having each account hold a nonce number which is incremented with every transaction

the account makes. This nonce is used for signing a transaction before it is broadcasted to the

network, thus preventing replay.

To support Smart Contracts, Ethereum holds in its immutable decentralized ledger, code de-

ployed to it which include most importantly the functions, and state variables which can be altered

or manipulated with signed transactions to the blockchain with instructions to call the contract’s

functions.

Smart contracts are identified by public addresses and can be seen as accounts on the network,

just like any other account controlled by humans. However, a Smart Contract account can only do

what it’s programmed to do, using the ETH payed to it. Also, a Smart Contract will never execute

on its own, as there needs to be a transaction made to it, from a human or an internal transaction

made by another smart contract, to trigger any of its functions. A transaction on Ethereum can be

one of three types. The first type of transactions are transactions that just move value from one

account to another, without calling any other function. The second type of transaction is similar

to the first, but calls functions from other contracts that may call functions of other contracts and

Page 20: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

2.2 Smart Contracts and Ethereum 7

so on. Finally, the third type, are functions that create new smart contracts; these transactions

do not send value to any account and therefore don’t even need the field for a ’to’ or receiving

address. After a transaction is included in a block, nodes in the Ethereum network check to see if

the contract’ state transitions are correct.

Every transaction made on the network incurs a fee which is given to miners as reward and also

works to avoid spamming of transactions. The fee payed for a transaction depends on the amount

of computation and is called Gas, the calculation of the total Gas usage is the sum of the cost

of the different kinds of opcodes (POP, PUSH1, ADD, SUB, JUMP....) used in the computation.

The cost per Gas is expressed in Gwei, a monetary unit that is worth 1e−9 ETH. An Ethereum

transaction includes a gas limit which mustn’t be exceeded so as to pay the fee. The execution of

every operation subtracts a given amount from this value. If the transaction runs out of gas, the

transaction is aborted and all its changes are essentially rolled back. Thus by including the gas

limit in a transaction, Ethereum prevents potential bugs in a contract where code executes forever

therefore wiping out an account’s balance. Ethereum’s size per block is determined based on gas

limit per block which as of the of time writing this is set to 12.5 million total gas limit per block.

Blockchain follows the reactive programming model and transactions share some properties

with ACID and BASE databases, mainly the transactions can be thought as having Atomicity

since a transaction is either fully completed successfully or it’s completely reverted if something

goes wrong, transactions are probabilistically more immutable with each added block and always

available. A paper was written on the topic, where Blockchain is described as being neither ACID

nor BASE, but instead SALT [9], where a blockchain is sequential, agreed, "ledgered" and tamper-

resistant.

Once a transaction is sent to the Ethereum network, it goes through the process of being

included in a block and interpreted by nodes running the Ethereum virtual machine that verify the

its validity and perform the computations encoded in the transaction which creates a new state for

the accounts and contracts affected by the transaction. The transaction details such as price, gas

limit, and other data are logged on the blockchain, and its effects change the state of all accounts

and contracts affected. As an example, if Alice wants to send 1 Ether to Bob, she will assign

Bob’s address to the transaction’s ’to’ field, its own address to the transaction’s ’from" field, this

way when the transaction is signed and sent to the worldwide network of nodes that make up

Ethereum, the 1 Ether will be deducted from Alice’s account and added to Bob’s account.

Through the client-side web3.js library and using the credentials provided, a transaction’s

conditions are sent to the Ethereum node containing information on what contract is targeted, what

function is being called, with what parameters and other details such as the nonce, and a signature

by the user. The function and parameters are encoded into the ABI format and the transaction’s

data field is initialized with the result. The ABI format is essentially encoding a function identifier,

the parameters and other details to a hexadecimal sequence for the EVM, run by nodes, to decode.

Fig. 2.1 shows the sequence diagram for all transactions to the blockchain through the gateway

of the Infura service. The Infura service is a free service, with also payed plans, that allows the

use of a remote Ethereum node through their gateway, removing the need for a DAPP user to have

Page 21: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Literature review 8

to run a node themselves. The ‘sendRawTransaction’ call will include the transaction’s conditions

and a data field specifying the function id and its parameters in ABI format, as is shown from the

txObject to the left of the sequence diagram. After calling the function, the web client effectively

subscribes to be alerted every time a block is added on top of the transaction.

Figure 2.1: Transaction sequence diagram

The changes to Ethereum smart contracts by a transaction become effective only when that

transaction is included in the blockchain. The time when this happens is difficult to predict. Each

block has a total gas limit, thus the highest bidders for that space are added the quickest. Each

block has a Gas limit, as of writing it stands at 12,500,000 Gas for Ethereum, and each transaction

spends a certain amount of Gas. When a block is added, the miner profiting from it prioritizes all

transactions with the highest Gas price to fill in a block, thus the higher the Gas price set for the

transaction, the faster a transaction will be picked up and added to the blockchain.

A transaction can be initiated by a call to a smart contract function from code external to

the blockchain. Internal calls to smart contract functions do not initiate new transactions, but are

executed in the context of the existing transaction instead, and Ethereum’s state will change to

the next stage having the function, called externally, fully finished execution including functions

called from other contracts by it.

If something goes wrong with the transaction all the changes done until the point of failure will

be reverted. Situations where something goes wrong include insufficient Gas limit provided by the

transaction’s issuer, or a requirement not being met due to a wrong function parameter given.

During a contract’s function execution, logs can be emitted which allow for low cost storage

of data to be used for future reference by web clients or other such software outside the Ethereum

network. These logs can not be read or changed from within a contract’s function execution, and

their sole purpose is to document changes to the contract. The contract’s code stores the possible

formats these logs can take, these formats are called Events, so when during a function execution

Page 22: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

2.3 Trusted Compute Framework 9

an Event is emitted, what really happens is that data is stored and indexed by the Event, so if for

example a declared event contains two integers and one boolean then when that event is emitted,

two integers and one boolean value will be recorded for the contract. Afterwards, by using the

Event’s name, external software can find the values for the two integers and the one boolean.

Client-side software can acquire Event names from the contract’s ABI which is generated from

it’s source code, granted the source code is published and matched to the bytecode of the contract

stored on the blockchain.

As an example of a Smart Contract use case, let’s say Alice wants to make a contract with

Bob to buy his used lawnmower without intermediaries or an escrow taking a share of the money.

Bob would write a contract in code and deploy it to the blockchain via a transaction which would

contain an amount of ETH to pay for the transaction plus a collateral amount for future reference,

and the contract would contain a buy with collateral function that would be called by Alice’s

transaction to the blockchain which would include the amount in ETH to pay for the lawnmower

plus a collateral amount. All collateral would be unlocked and sent back after the trade’s made

successfully. Now the contract has both Alice’s and Bob’s ETH, and Bob has incentive to go

through with the trade after Alice made the purchase because he has locked ETH in the contract,

and Alice will have incentive to confirm the delivery of the lawnmower because Alice has locked

additional ETH beyond the price of the lawnmower for that purpose. After Alice receives the

lawnmower, she sends a transaction to the blockchain calling a function of the contract that returns

both Alice’s and Bob’s collateral. In this example both Alice and Bob have incentive for the trade

to go through successfully through the Smart Contract, with the advantage Blockchain and Smart

Contract offer of full transparency and trustworthiness.

2.3 Trusted Compute Framework

The trusted compute framework was the original name for the Hyperledger Avalon [10] pro-

posal which aimed to make a blockchain independent implementation of the EEA’s Trusted Com-

pute Specification [11]. Hyperledger is an umbrella project for open source Blockchains and tools

and it is hosted by the Linux Foundation consortium, Hyperledger Avalon is one of the open source

proposals by the Hyperledger collaborative effort.

The EEA’s off-chain trusted compute specification and the Hyperledger Avalon proposal’s

objectives are to introduce support for confidential contract execution, off-loading algorithms with

high time complexity from a blockchain’s smart contracts to an off-chain secure Trusted Compute

system.

Trusted off-chain execution comes as a solution to the limited capabilities of blockchain when

it comes to complex tasks, confidentiality and improved privacy. Joining together the two tech-

nologies combines the immutability and capability to audit all results and transactions publicly on

the blockchain with the high throughput and confidentiality of code running on a Trusted Compute

system.

Page 23: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Literature review 10

The architecture for the TCF is based on a worker pool managed by a worker service which

receives work orders, or computational tasks, and workers execute those tasks assuring execution

integrity and that no memory from what’s executed can be leaked to anyone including the host. To

achieve this, workers execute their tasks using a Trusted Compute system. Trusted Compute can

make these guarantees of data confidentiality, execution integrity and data access policies in one

of three ways, using trusted execution environments, such as the ones created using Intel’s SGX,

using Multi-Party compute or utilizing cryptographic security guarantees like the zero-knowledge

protocol.

Workers are registered with an on-chain smart contract where they can be discovered. After the

worker is registered, there can be two invocation models used to communicate with the requester.

The first model, the direct model has the worker communicate directly with the requester to submit

the work order and likewise the worker to send back the work order result to the requester, receipts

are stored on the blockchain or another mutually trusted location for future auditing. The second

model, the proxy model, utilizes smart contracts running on the blockchain for managing the APIs

used for the communication between the requester and the worker, the receipts are stored on the

distributed ledger.

One implementation of the EEA’s off-chain trusted compute specification and the TCF is the

Trusted Reward Token [12], developed with Token Taxonomy Initiative [13] specifications by

the EEA, which aims to create a reward system for contributing individuals to the participating

organization, e.g. commits to a source code repository. This implementation uses the TCF to

off-load business rules to trusted execution environment Enclaves so that the cost of running this

logic, which requires frequent updates on-chain, is diminished.

2.4 Oracles

Oracles systems, or data on-chaining systems, in association with blockchain technology refers

to the bridging of off-chain data into the distributed ledger [14]. Oracles are a bridge between the

off-chain data source and the on-chain smart contract. A smart contract may interact with one

or more oracles, and the oracles can interact with many data sources. Since data external to

a blockchain can be unreliable, malicious or simply wrong, data on-chaining isn’t as simple as

transferring data to the blockchain, there has to be security guarantees that the data is truthful and

safe to be used for smart contract computations.

The smart contract requiring external data can only receive such data in transactions to the

blockchain, since this is the only way to change the state of the smart contract, therefore the oracle

must own an account on the blockchain for which to sign the transactions with. Once the data is

transferred to the smart contract, the smart contract can be fully trusted to function as intended.

Several solutions have been proposed for reliable, secure and truthful on-chaining of data.

One such solution is the TLS-N [15] protocol which relies on the Transport Layer Security for

authentication and integrity of data between the data source server and the consumer contract

while removing the trust factor from the off-chain oracle auditor by generating a non-repudiation

Page 24: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

2.5 Intel SGX 11

proof that can be verified by any third party. Another solution is the Town Crier [16] Enclave

based oracle which uses Intel’s SGX to create trusted execution environment Enclaves to remove

the trust from the oracle since all critical functionality run by the oracle can be executed inside the

trusted Enclaves, however due to the use of Intel’s SGX technology to launch these Enclaves there

is still need to trust the centralized Intel Attestation Server, or IAS, to validate the Enclave and

the need to trust Intel’s CPU to not leak any data from the Enclave. There’s also the voting based

oracles such as the Astraea [17] proposal where the oracle logic present on-chain does a vote in

which data sources vote on answers and the ones who vote on the majority answer get rewarded

while the ones who vote on a different answer get penalized, so it’s in their economic interest to

vote correctly on the right answer.

One of the most famous oracle systems, especially for the Ethereum smart contract platform,

is from the ChainLink [18] project.

Chainlink on-chain architecture uses an interfacing contract to communicate with the requester

contract before the process can begin. It features a reputation based voting system where data

sources are rated by the consumer contracts and the reputation of a data source can affect the

weight of its vote and the reward gained. Chainlink tries to achieve full decentralization and

diversification by allowing a number of oracle options which in turn communicate with a number

of different data sources. The protocol includes an order-matching contract for requesters to filter

out the best oracle option for them, and an aggregation system to aggregate oracle responses.

Chainlink, offers privacy-preserving oracles by combining with the trusted compute frame-

work and using Town Crier’s approach to trusted execution environment Enclaves where input

data sent to the Enclave is encrypted beforehand using a public key matching an inaccessible pri-

vate key contained only inside the Enclave and thus the input data can be securely decrypted inside

the Enclave and used in its computational task to output a result which can’t be used to deduce the

given input data, this also allows for the secure handling of credentials by the oracle.

2.5 Intel SGX

Intel’s Software Guard Extensions help protect code confidentiality and integrity when exe-

cuted on an untrusted remote host, by providing a secure Enclave enabled by most Intel’s CPU

after 6th generation Skylake processors.

The problem comes when a user has to rely on data remaining private and code being run by a

remote untrusted host which is often the case when using web services. To solve this, Intel SGX

enabled Enclaves can be leveraged to protect the code run in them from any and all malware, even

privileged malware from any layer, be it the OS or kernel of the host’s computer.

When first establishing a channel to the untrusted remote host, attestation needs to occur so

that the user can safely be assured that they are communicating with the correct program hosted

by trusted hardware. The remote host creates a trusted execution environment, to where the user

uploads the program and related data for execution by the Enclave. The remote host can provide

proof they run an Enclave by having the data and program uploaded by the user hashed and signed

Page 25: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Literature review 12

by the Enclave, this value is called MrEnclave, then sent back for attestation. It should be noted

that the user will have to trust the hardware manufacturer, in this case Intel, as the manufacturer’s

endorsement certificate will be used to prove that the attestation key used to sign the hash of data

from the Enclave is safely stored only by the trusted execution environment. An Enclave need

only possess the essentials for running the security critical program with the provided private data.

A great use case for this technology is the secure aggregation of sensitive data for use in

machine learning algorithms, the data would remain private while a machine learning model would

be trained with it and which would then be outputted by the trusted Enclave. To make this happen

the Enclave could create a key pair which then would be used between it and the user to send

encrypted data in and out of the Enclave, the Enclave would in turn have the tools to use the keys

to decrypt the private data sent to the Enclave.

It should be mentioned that a user of an application run by a trusted Enclave not only trusts

the hardware manufacturer, but also the hardware itself and the author of the application being run

inside the Enclave, since if the author’s code is malicious or even just faulty then output from the

Enclave could reveal any of the sensitive data stored inside it or produce unexpected results which

might trick the user. Therefore the program’s code which is to be run inside the Enclave should be

properly audited by the user itself or a trusted delegate.

The protected memory used by the Enclave for it’s computation is named processor reserved

memory or PRM. The CPU itself ensures that no component other than the trusted execution

environment has access to it, including from any of the layers which constitute the host computer,

including the kernel. The PRM stores the application code and data via the Enclave page cache or

EPC. The CPU makes sure that for each 4KB EPC page there is exactly one Enclave which has

access to it. This initial process of loading the application data and code into these EPC pages is

done by computers untrusted software, so it stands to reason if anything malicious happens during

this process the Enclaves contents will have a different hash value from the expected and therefore

a user would refuse to interact with the Enclave in this scenario.

After this initialization process the Enclave is set up and ready for attestation and computation.

The hash of the Enclave’s code and data is also finished and ready to take part in the attestation

process between the Enclave and the user to assure the user the Enclave is legitimate and carries

the intended code.

2.6 Scone

The scone platform is built on top of Intel SGX to provide an always encrypted execution,

both code and data can be encrypted or otherwise merely have their integrity secured.

Scone allows for the encryption of almost any and all data, including data relating to commu-

nications, inputs and outputs, data in persistent storage and the main memory for the execution of

the application. The keys for these encryptions are stored in SCONE CAS, or Scone Configuration

and Attestation Service which is run inside an Enclave.

Page 26: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

2.7 InterPlanetary File System 13

The Scone Configuration and Attestation Service features local attestation which makes sure

that an application running in an Enclave has the correct signature, before sensitive data is passed

to it.

Scone features a file protection system where each file and directory can be given one of three

types of protection: authenticated which checks the file’s integrity from unauthorized change,

encrypted which in addition to integrity check it also provides confidentiality to the files, and

finally not-protected. As changing every files protection type would be tedious, it’s defined regions

as paths in the file where all files under such a region are of a set protection type, and the more

specific a path is the higher priority would the protection type of such a path or region be.

Scone provides numerous advantages than just using the Intel SGX SDK, from greater side-

channel attack security which is a troublesome issue for Intel SGX, to automation of attestation

without need for extra coding.

2.7 InterPlanetary File System

Similar to torrent peer-to-peer technology, IPFS or interPlanetary file system allows for un-

censorable websites by having a copy of the website replicated to many peer’s cache to assist in

distributing the website instead of relying on only a central server.

This in turn allows for greater resilience against censorship, and higher up-time. It also fa-

cilitates, as the name suggests, an interplanetary web as data for a website would need only to

travel once the distance between two planets before being distributed between peer caches on the

destination planet it traveled to, thus no longer needing high latency to view the website or data in

question.

2.8 iExec

A customer in electronic commerce wants to make an order for a used car online, he wants to

go through the regular procedure as he would on an intuitive user interface provided by a current

top e-commerce platform, however he doesn’t want to give away sensitive information to 3rd

parties if he can avoid it.

Towards a scalable utilization of smart contracts for a decentralized electronic trades platform,

running large computations on smart contracts would have to be avoided as not only would it be

costly for the user to run on the blockchain, smart contract enabled, platform but also wouldn’t be

feasible for a large number of users running the same contract on the same blockchain platform

as it would easily throttle, quickly rising fees to absurd levels as demand for space inside a block

increased. Working on personal data on smart contracts would also compromise the customers

data, as calls to smart contracts are public and completely transparent.

A great example where Ethereum suffered from the scalability limitation is when the animal

crossing game called Crypto Kitties [19] had such great success that the number of players using

Page 27: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Literature review 14

the application to cross cats and generate new digital cats put Ethereum under heavy load and thus

raised fees tremendously.

There needs to be a way to execute the more computationally intensive parts of this DAPP

and the parts demanding confidentiality, on an off-chain trusted system and return the result back

on-chain. Not only that but during order execution there needs to be access to external world data

in a secure as possible manner.

That’s where Trusted Compute comes in, by utilizing a distributed computing architecture

where nodes working on the computations leverage trusted execution environments, such a those

provided by Intel Software Guard Extensions. Hence, complex computations can be done off-

chain on a distributed cloud computing architecture while preserving data privacy and connecting

to external data sources to retrieve relevant external data. I found out that such a system is already

being worked on and big advances have been made. IExec [20] provides such a computation

service, and in this section we explain its inner workings.

While iExec is a work in progress, and a lot of development is still being done on it as of the

time of writing this, it is the only company providing an open source stack for deployment of a

decentralized cloud network, on Ethereum, with an economy entirely powered by a digital decen-

tralized currency. Anyone can join iExec and sell their spare computing resources in exchange

for a cryptocurrency named RLC, a decentralized non-governmental controlled digital currency.

IExec is an Ethereum specific implementation of EEA’s Off-Chain Trusted Compute Specification,

similar to the TCF in Chapter 2.3.

The economy of the iExec stack is powered by the cryptocurrency named RLC. This cryp-

tocurrency is used in exchange for cash to buy and sell resources such as computing resources

and data, these computing resources are what this project buys with RLC to perform off-chain

computations.

iExec is a decentralized cloud computing platform and it currently offers a marketplace of

worker pools, app and dataset providers on a pay-per-task basis. Payments are automated through

the use of smart contracts and are made in the token of the iExec platform, the RLC token. Anyone

can become a requester or a worker on the network, requesters must pay in RLC.

The iExec network is made up of workers, worker pools and the schedulers which manage

these pools, app providers, dataset providers, requesters, the smart contracts deployed to Ethereum

and the off-chain iExec-order marketplace.

The roles in the iExec network are the following:

1. The workers perform Tasks in exchange for the RLC token.

2. The worker pools are aggregations of workers managed by schedulers that compete for

workers to join their pool through the efficient management of the pools.

3. App providers are the entities that publish applications for requesters to have run by workers

pools. The app provider take a share of revenue from the execution of the application.

Page 28: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

2.8 iExec 15

4. Dataset providers are entities that allow for the usage of their dataset in return for RLC.

Their dataset/data is kept private through the use of TEEs.

5. Users pay for the execution of Tasks. A smart contract can be a user.

The iExec platform enables the monetisation of datasets like trained AI models, by having

workers take inputs to these trained AI models and returning the output to the requester without

compromising the trained AI model’s ownership. Since the AI models are used in trusted execution

environments they remain private to the owner of the dataset, thus allowing for the monetisation

of the dataset to anyone while retaining ownership of the dataset to the original owner.

IExec already has enterprise workers running nodes on their platform like those of Genesis

Cloud [21], a company which provides high performance GPUs, and requesters like the french

company EDF which run on iExec the GPUSPH application that needs high performance GPUs

for use in running simulations.

To avoid bad workers publishing wrong results and penalising users, all agents involved in the

network follow what is called the Proof of Contribution [22] protocol. The protocol has the goal of

giving trust to users, of what the consensus algorithm deems to be the correct result. The protocol

makes it so multiple workers execute a Task and then aggregates the results. Each worker has a

reputation score which is impacted whenever the worker publishes a result, if the result matches

the majority consensus then the worker’s score is incremented, otherwise if the result is deemed

bad then the workers loses 1/3rd of their score.

The use of a PoCo protocol can be avoided if workers run applications in a Trusted Execution

Environment such as Intel SGX, as there is no need for replication nor the PoCo’s consensus layer

due to the application being run on an enclave. However, as discussed in an article published by

the iExec company ("Aren’t enclaves and PoCo contradictory?" [23]), the enclave technology is

not perfect as not only does the worker’s CPU need to support it, it also needs to be supported in

the BIOS so few computers have it. It’s also important to mention that the Intel SGX technology

has been found to have vulnerabilities in the past [24].

An advantage of running applications in TEEs is that of additional privacy, if data is delivered

to the the TEE in a privacy-preserving way, e.g. by encrypting the data with a secret key. This is

implemented using the Secret Management Service which is explain in the below Section 2.8.7.

The SMS verifies that the indented program is running on the worker’s enclave before provid-

ing a secret. However, to guarantee also that the worker doesn’t return a misleading result even

after executing the correct program, a remote attestation is made between scheduler and worker.

Once an enclave is initialized by a worker, it generates a key pair inside it and the worker

sends the public key to the scheduler of the worker pool through an authenticated channel. The

scheduler verifies that the public key was generated inside the worker’s enclave through the IAS,

as shown in Fig. 2.2, and it registers the public key on the blockchain. When a worker executes

our DAPP’s off-chain component, it will sign the result with it’s private key, generated previously

by its enclave, and it will send the result and the corresponding signature to the blockchain.

Page 29: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Literature review 16

Figure 2.2: Remote attestation

Requesters can specify what level of trust they need to have that the result coming from the

workers is valid. If the level specified is 0 then a worker of any score will deliver the result,

otherwise if the level is higher then the reputation level of the workers also needs to be, this means

more workers with higher score would need to execute the Task and aggregate results to determine

the most agreed upon result.

Workers and schedulers must stake RLC to participate in the network. Bad behaviour from

any of these actors results in a loss of stake. Also, to avoid Sybil attacks where any actor could

create multiple workers to join a pool and publish bad results, there is a minimum stake of RLC

and reputation that a worker must have.

The off-chain component running on workers can integrate information from oracles thus ex-

panding greatly the use cases for decentralised applications. Since now developers can run the

off-chain component of their decentralized application with full trust that the application runs as

expected with encrypted input from the user and input from external off-chain data from oracles.

The following sections go into more detail on aspects of iExec.

2.8.1 Who Are The Users or Requesters

Requesters are whoever requests to run an application on the network. Requesters need to pay

in RLC to run applications in the iExec network, the RLC is first locked during the execution. If

consensus is achieved, the RLC is then distributed by the parties that contributed with the winning

result. Otherwise, the RLC is unlocked and returned to the requester.

2.8.2 What Are The Accounts

Wallets and accounts are different concepts in iExec, as wallets are simply the key pair con-

taining ETH or RLC in the Ethereum network, and accounts are what’s used to interact with the

iExec network.

Accounts are managed by an escrow which is part of the IexecClerk smart contract running

on-chain. Accounts are funded by wallets, and accounts hold RLC as either staked or locked.

When moving RLC from the wallet into an account, the RLC is initially stored as stake to be

used in the iExec network. When the RLC in stake is used by a Task, then the RLC becomes locked

until it’s either sent back to stake, e.g. if consensus is not reached (see below), or confiscated as

payment or punishment.

Page 30: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

2.8 iExec 17

2.8.3 What Are The Apps, Datasets and Workerpools

An app in iExec can be either the application code to execute in the platform, or an instance

of the App contract on Ethereum provided by iExec for running that application code. The App

contract instance has a link to a docker image with the application code that may be published to

docker hub, or any other alternative.

Likewise, a dataset in iExec can be either a data to be used by some application, or an instance

of the Dataset contract on Ethereum provided by iExec for access to the data set. The Dataset

contract instance has a link to a file with the data set as well as a checksum of the data.

Finally, a workerpool in iExec can be either a pool of worker nodes to perform computations,

or an instance of the Workerpool contract on Ethereum provided by iExec for the user to choose

to run an application and workers.

2.8.4 What Are The App, Dataset and Workerpool Orders

In order to monetize applications, datasets and workerpools, iExec provides a way to publish

offers, or otherwise referred to as orders, to an off-chain marketplace. Orders reference the app,

dataset or workerpool by the address of their contract instances on Ethereum, and also state their

usage conditions and provide a signature of the creator of these resources to prove their authentic-

ity.

Order information is picked up by a requester through the use of the iExec SDK, so as to create

a request by combination of orders. A request can, for example, use an order for an application,

another for a specific dataset, and finally another order for the workerpool which will run the

application. If all these orders cost 1 RLC, then the request costs 3 RLC total.

When the requester publishes the request, the orders are matched on the blockchain and the

request is picked up by the scheduler of the workerpool specified in the workerpool order.

Each order has a limit for the number of times they can be used, known as volume. Every time

an order is used, the volume is decremented by 1.

2.8.5 How a Task is Executed

In this section we describe the sequence of steps both on-chain and off-chain to run a Task

whose app, dataset and workerpool orders have been uploaded to the off-chain iExec market.

2.8.5.1 The Deal Is Made

A Deal is a smart contract object, on Ethereum. Its creation is the first step in executing a Task,

as a Deal needs to be established for execution of the Task. Deals are created by the IexecClerk

smart contract instance.

While the orders for publishing applications, datasets, requests, and workerpool are stored in

the off-chain iExec marketplace, they are signed off-chain by the responsible entities and therefore

Page 31: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Literature review 18

the security of the off-chain marketplace can be guaranteed as the origin of the orders can be

verified cryptographically by the signature of the in them.

The IexecClerk smart contract which is on-chain and has the security guarantees blockchain

provides, verifies the origin of the orders from the off-chain iExec marketplace before matching

them and creating the Deal object. When matching the orders, an Event, named ’SchedulerNotice’,

is emitted from the smart contract which is watched by the scheduler of the corresponding work-

erpool of the workerpool order.

2.8.5.2 Workers Are Assigned

When the ’SchedulerNotice’ Event is emitted from the IexecClerk smart contract instance, it is

watched by the scheduler of the workerpool mentioned in the Deal. Afterwards the scheduler calls

’initialize()’ from the IexecHub smart contract instance, which creates the Task smart contract

object. Then the scheduler randomly assigns workers to work on the Task, the number of workers

depending on the trust level designated by the requester. The Scheduler then signs a message

containing the addresses of the assigned workers, Task id and the Ethereum address of the worker’s

enclave, and sends this message to the workers through an off-chain channel.

2.8.5.3 Computation Is Made

Once the workers verify the signature was made by the scheduler, they begin fetching the data

for the application (e.g. docker hub) and the dataset (e.g. IPFS), and begin execution. As input

for the application, arguments can be passed to it and the application can also read input files from

the previously configured input ’\iexec_in’ directory, and it outputs likewise to the ’\iexec_out’

directory. As output the application stores in stdout.txt the logs printed during the application’s

execution, and all other output files are stored in the ’\iexec_out’ folder, these are then bundled in

a ’result.zip’ file which can be downloaded once the Task is finished.

2.8.6 How Consensus is Established

Consensus over the result of an application run on the decentralized cloud by multiple workers

is done on the blockchain. The results need to be deterministic so as to converse to a single true

result.

Consensus is needed in case the requester opts for redundancy of workers executing the ap-

plication, since a result needs to be agreed upon to be the correct one out of all results calculated

by the different workers. Of course, if all workers act honestly and the application’s code is not

erroneous, most if not all workers should reach the same result value.

There is also the case where requesters want workers to execute on TEEs, in which case opting

for redundancy is not necessary, but still possible.

If consensus is not achieved, the requester is reimbursed and the locked funds return to the

requester’s stake.

Page 32: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

2.8 iExec 19

2.8.6.1 Consensus Is Achieved

To achieve consensus on the result, workers call ’contribute()’ from IexecHub contract in-

stance, providing as parameters a hash of result and a seal of the result. The hash of the result

is the hash of both the Task ID and the result digest. The seal of the result is the hash of the

worker’s Ethereum address, the Task ID, and the result digest. The consensus on the correct result

is established by the hash of the result, where the majority vote wins.

Once all workers have provided both the hash of result and a seal of the result as described

before, the workers now call the ’reveal()’ with the parameter being the digest of the result which is

the hash of the ’\iexec_out’ and ’stdout.txt’ files. Now by hashing the digest together with the Task

ID and the worker’s Ethereum address, and comparing the resulting hash with the previously given

seal hash, the worker can prove to the IexecHub contract instance that it knew of the digest before

providing it, and thus did in fact contribute. In case the application is non-deterministic, or in other

words doesn’t always reach the same state after execution, then a ’\iexec_out\determinism.iexec’

file must be created by the worker with a deterministic result, this file overrides the digest of the

result folder.

Finally, by calling ’finalize()’ from the IexecHub contract instance, the workers can get payed.

If it was a contract object that initiated the request then a callback function of said contract is

called.

2.8.6.2 Bad behaviour Is Penalized

Workers and schedulers must also stake a minimum amount of RLC to participate, so that bad

behaviour, such as returning a false result, is punished by the loss of this stake.

2.8.7 How Permissioning Works

The IExec’s Secret Management Service (SMS) is used to store encryption keys for datasets,

and provide said keys to applications which have authorization to read the keys during their exe-

cution inside secure Intel SGX enclaves, so that these applications can decrypt the dataset and use

it during the execution of the application while maintaining the secrecy of the dataset as the TEE

isn’t supposed to leak any memory even to the host executing the application.

Before the user pushes a secret of their encrypted dataset to iExec’s SMS, they verify the

SMS’s enclave certificate, as it is attested by the IAS, to know that the SMS is running the correct

open-source SMS program. However if the user wishes to, they can run their own Secret Man-

agement Service running a modified version of the open-source SMS program that could add an

additional layer of security.

When the worker’s TEE needs a secret to decrypt a dataset, it establishes a secure channel

with the Secret Management Service, which verifies that the actual software is running inside the

enclave of the worker.

Page 33: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Literature review 20

2.8.8 iExec Oracle

Oracles are a vital part of this project, since for the validation of client information there needs

to be calls to external APIs, and the data returned by these APIs needs then to be exposed to the

blockchain smart contracts. Oracles in the cryptocurrency space are essentially systems outside of

the blockchain that allow outside data to be fed to the blockchain.

With oracle systems special care needs to be taken for calls to be done in a secure trustworthy

manner as they present an attack vector for decentralized applications that use this external data

because data from outside a blockchain cannot be trusted in the same manner as the data stored

inside the blockchain and the process used to bring data on-chain needs to be secure. If done

incorrectly, false data can enter the blockchain and potentially be used in smart contracts thus

tricking it to execute using false data, eroding the trust on the smart contract.

Use of Oracles in iExec affects several steps in the execution of an iExec application:

1. Creating a request from a smart contract

Smart contracts live on the blockchain. To initiate the oracle process, the smart contract

needs to advertise the need for data external to the blockchain.

2. Workers execute application that makes API calls to data source

Once the scheduler detects a request from the blockchain, it will assign it to workers, from

its workerpool, to execute the application which makes API calls to external data sources.

3. Smart contract’s callback function is called with the application’s result, possibly deter-

mined by running consensus.

After consensus on the off-chain application’s execution by the workers is established, the

callback of the on-chain contract will be called in a transaction, with the results from the

application’s API calls to the external data sources.

Proof of Contribution protocol establishes consensus on the application’s result through the

use of blockchain. By running the application on different workers, the system is more resilient to

rogue workers.

However, the system is still vulnerable to the rogue data sources. Indeed the use of a single

data source requires the application to trust in that data source. So security can be further improved

with the help of redundant data sources and the use of some voting mechanism.

Page 34: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Chapter 3

Application

Let’s say a seller wants to sell a used car online, without the hassle of setting up a website,

by using one of the e-commerce platforms already available. The seller wants to make the most

profit possible. He searches and finds many platforms which pay middlemen to serve as service

providers for hosting and providing the infrastructure for payment, shipping, promotions, vouchers

and other functionalities. The problem is that the seller will have to pay a minimum of 15% as

fee for each product sold on these platforms and this would be especially costly for expensive

products. This work presents an application that the seller can use to sell the used car and not have

to set up the store website, paying for hosting and services involved or even paying middleman

absurd fees to abstract these complexities.

This application provides an e-commerce alternative which doesn’t need to place trust in any

central entity to keep private information secure, by leveraging decentralization through blockchain

together with Trusted Compute.

The user is met with an interface enabling the user to sell and buy products, much like Amazon

or other e-commerce solution, but in decentralized application. The website itself wouldn’t be

hosted by a centralized entity but rather have it’s contents hosted in a decentralized way. As the

application is meant to be decentralized and not rely on any central authority or single point of

failure, the website’s contents for which to access the DAPP, also needs to be stored and hosted in

such a decentralized way.

By using IPFS to host the website, each user who downloaded the website and used it would

then have the website cached on their1 computer and this cached version potentially shared with

other users as a node in the network if they so wished to, thus users of the platform would them-

selves proliferate the website’s interface files among the entirety of the user base of the platform.

The website could then be accessed through a URL provided by Unstoppable Domains, a technol-

ogy which uses blockchain to store records.

At the back-end there would need to be a database, as we can’t rely on a centralized entity to

provide one we would need a sort of decentralized database where peers in the network would all

host a record of the database to be incrementally updated with new data and synced with all other

1They/them/their was used as a singular and-or gender-neutral pronoun.

21

Page 35: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Application 22

nodes in the network. While solutions for this exist such as OrbitDB, or GUN, there is one glaring

problem in these solutions which is the lack of incentive to run a node which records and syncs

with other nodes on distributed databases. While there’s a solution in the works named Filecoin,

there’s already one way, which while impractical to store large amounts of data, can be used

with almost perfect guarantee the data will remain registered and immutable, which is blockchain.

Using Ethereum for example would provide storage for the basic information in products sold in

the platform, such as the seller’s public key, the products name, the products details registered as

logs on Ethereum, the product images IPFS identifier, and other details.

For server side computations which demand trust in the correct execution of the code between

the buyer and seller, using Ethereum alone wouldn’t be feasible for computations of state changes,

as to perform these executions would require a scalability which Ethereum presently does not

have. Thus for the verification of data and performing the required computations such as address

validation, credit card validation, implementing vouchers, and other options such as gifting op-

tions, and other computations there needs to be another solution, as without a trusted intermediary

like Amazon these computations would then be left to be executed by either untrusted party thus

needing the store owner to have a server running constantly to perform these verifications on each

sale at the store. These computations could then be executed by a decentralized peer-to-peer cloud

network which would provide trust in the computations results by redundancy of peers executing

the code and reaching consensus on the results. But the issue would then become the complete

disregard for confidentiality and privacy, as all of the sensitive data from the buyer would have to

be exposed for the purpose of executing the relevant computations. But if these peers ran the code

inside trusted enclaves such as those offered by Intel SGX, then both confidentiality and integrity

of the code could be ensured with a relatively high level of trust.

3.1 Roles

An actor can have the role of a buyer or seller on the platform.

• A seller’s goal is to publish items to be sold on the decentralized online marketplace;

• A buyer’s goal is to purchase the goods published by the seller on the marketplace.

3.2 Actions

• As a seller, the user can publish a product to the blockchain free of censorship;

• As a buyer, the user can securely store and use personal information regarding their payment

method and delivery address through a system which guarantees the data is kept safe without

relying on central parties;

Page 36: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

3.2 Actions 23

• As a buyer, the user can choose a payment method and delivery address to use for a purchase

of a product listed on the decentralized platform, without ever having to reveal their personal

information to central parties;

• As a buyer, the user can proceed with their purchase being in control until the purchase is

completed.

Page 37: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Chapter 4

Dapp Design

In this chapter we present the DAPP design. We first show the system architecture, explaining

not only the components of the DAPP, but also other components with which the DAPP interfaces.

Then we detail the interaction among these components in the most relevant use-cases of the

DAPP, including to publish products for sale and to purchase them. Along the way, we describe

a simple user interface we have designed with the dual purpose of exemplifying the interactions

with the user and of testing the DAPP.

4.1 System’s architecture

This application essentially has three components, the Ethereum network, the iExec decentral-

ized cloud computing, and the Web Client. The Ethereum component stores some of the iExec’s

system contracts necessary for this work, and also stores instances of the three base smart con-

tracts for the DAPP, the ItemFactory, the Item and the Order. The iExec cloud enables confidential

off-chain code execution, and an oracle, for validating information provided by the buyer, such

as shipping address and payment information. Lastly the Web client provides an interface for the

user to sell or buy products, interacting with the other components. In Fig. 4.1 is a representation

of the interaction between all three main components, where the internal structure of the three

components are also shown.

A more detailed and full component diagram is shown in Figure 4.2. The diagram shows a

view of all the related subsystems that make this decentralized e-commerce platform work. The

two main subsystems, otherwise referred to as components, contain parts of the code which make

up the DAPP. The Ethereum component has the three smart contracts ItemFactory, Item and Order,

designed specifically for this decentralized application, and the Workerpools subsystem is where

the off-chain code will be uploaded to, from the Docker Hub image library, to be executed using

the TEE of Intel SGX.

24

Page 38: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

4.1 System’s architecture 25

Figure 4.1: Interaction between blockchain and user interface

Figure 4.2: Decentralized e-commerce component diagram

4.1.1 Ethereum Subsystem

The Ethereum subsystem contains in total nine components, these are all smart contracts en-

abled by the Ethereum platform. For the purpose of this DAPP, they allow the creation of products

Page 39: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Dapp Design 26

or items, via the Create Item interface, the purchase of those products, via the Create Order in-

terface, and to execute some steps that are required to fulfil the purchase, via the Complete Order

interface. The DAPP Web Client also uses the Approve and Call interface, provided by the RLC

component. This component is not part of the Dapp, but instead it is provided by the iExec plat-

form for paying the computing resources used by running off-chain code in the iExec platform,

as detailed in Section 4.2.4. The Ethereum subsystem, namely the IexecClerk, also interacts with

the Schedulers, so that these schedule off-chain computation. This is represented via an interface

named Run Validation. However, this interface is not an ordinary API, because Ethereum smart-

contracts cannot use APIs to communicate with off-chain components. Instead, communication is

via the blockchain itself: the smart-contract emits a log to the blockchain that is later "picked up"

by the iExec Scheduler component leading to the off-chain scheduling of the Dapp application.

4.1.2 Workerpools Subsystem

The Workerpools subsystem contains three components, the Schedulers, Workers and the

Trusted Compute component. The Scheduler allows to run the off-chain validation code of the

information provided by the client for the purchase, this is done by exposing the interface Run

Validation. The Scheduler component also uses required interface Return Result to initiate a call-

back of the Order component with the result of the off-chain computation by its workers. The

scheduler also allows for computers to monetize spare processing power by joining the sched-

uler’s workerpool as new workers, this is exposed by the Join Pool interface.

The Workers use required interface Join Pool to join a worker pool run by a Scheduler, this

component also has a usage dependency with the Intel SGX component. The Workers run the

off-chain code designed for this DAPP and uploaded as an image to Docker hub, to validate the

client’s data. The client’s data, that is the shipment address and payment information, are retrieved

from IPFS to be decrypted using the secret from the SMS, and used by the worker for the DAPP’s

off-chain execution.

The Intel SGX is used by the Worker to perform computations on private data with a higher

protection from disclosure or modification. This component uses many interfaces provided by

other components. It uses interfaces to retrieve the docker image from the Docker Hub compo-

nent so that it creates the container with the DAPP’s off-chain code protected using the SCONE

framework. The component also uses required interfaces Download Data and Download Secret

so that the Intel SGX generated TEE can decrypt the client’s data using the secret allowed for

the application, and use it during computation to validate it. And finally the Intel SGX also uses

interfaces from the only two API components, named Address Validator and Payment Account

Validation, and both these API components are meant to receive requests from the worker’s TEE

protected by transport layer security to validate both the shipping address and payment method of

the client, the API services may be payed.

Page 40: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

4.1 System’s architecture 27

4.1.3 Interface Component

The Interface component was specifically designed for this DAPP and it naturally has the most

required interfaces since it’s the gate for interacting with the platform. It uses several interfaces

that we have already described provided by the Ethereum component: Create Item, Create Order

and Approve and Call. It also uses the Upload Data and Upload Secret interfaces for uploading

the encrypted clients’s data to IPFS and the decryption key to the SMS, respectively. As already

described these will be retrieved later by the DAPP’s off-chain validation code, inside a trusted

execution environment (TEE). Finally, the Interface component also uses the iExec’s Get/Add

IExec orders. This interface is used with two purposes. First, it is used for getting the terms of

usage of the workerpool and the off-chain DAPP. Second, it is used to set the terms of usage for

the data set with the users private information, namely shipping address and payment data.

4.1.4 Other Components

As shown in Fig. 4.2, the Dapp interacts also with other components: the IPFS decentralized

file system, the secret management service. In addition, although not shown in Fig. 4.2, for the

sake of simplicity, the Dapp interfaces with the Infura service. We now briefly describe each of

these interactions in its own paragraph.

Inter-Planetary File Service (IPFS) This component provides a decentralized storage service.

It provides the Upload Data and the Download Data, which are used by the DAPP Interface.

Secret Management Service (SMS) This manages permissions for the secret keys which are

used to decrypt client data inside the Workers’ Intel SGX components. The keys are sent to the

SMS enclave via the Upload Secret provided interface, and are retrieved to the Workers’ Intel SGX

components through the Download secret provided interface.

Infura The platform uses a third party service called Infura so that the user does not need to

run an Ethereum node to connect to the Ethereum network. Thus, Infura is used like a gateway to

communicate with Ethereum from the external world. In Fig. 4.3 shows how the user’s computer

interacts with the Infura service through the web to connect to a remote node.

DAPP Smart contracts Highlighted in yellow in the Ethereum component are the DAPP’s base

smart contracts. The logical architecture for them is based on a item factory meant for sellers to

advertise their product, and an order factory within the item smart contract object. The Figure 4.4

illustrates an UML diagram explaining what smart contracts exist and how they interact with each

other.

Page 41: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Dapp Design 28

Figure 4.3: Infura service interaction with the web client

Figure 4.4: Logical architecture of Smart Contracts, from the Purchase Side

4.2 Use-Cases

In this section we go through the design of the use-cases for this decentralized application.

Logging in is the first use-case since to perform the other use-cases the user needs to be logged in

and, like the other use-cases, it describes how it was designed taking into consideration all com-

ponents involved. The selling of a product use-case only involved the Web Client and Ethereum,

while the other two use-cases, handling private information and making a purchase, interact also

with iExec.

4.2.1 Logging In

In order to perform some actions, e.g. publishing or buying a product, a user has to authenticate

itself. This is done, upon logging in to the web client.

Page 42: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

4.2 Use-Cases 29

Each user has an account which is associated with a pair of private and public keys. Each

account has an address that is used to identify it, which is derived from the public key using the

keccak-256. When the user needs to be identified for a transaction, the address will be used to

identify them. The key pair acts like an anonymous identity, where anyone with ownership of the

private key can become that identity and do anything on behalf of it. The private key is used to

sign the transactions.

It’s worth explaining that transactions in the context of blockchain are how users interact with

the Ethereum network in order to change the state in blockchain, be it an account’s balance or a

contract’s state, this is explained further in the background section on Ethereum and smart con-

tracts.

In relation to this project, transactions can be abstracted to a way to invoke functions in the

contracts made for this decentralized e-commerce platform.

The user has the choice of using their metamask plugin to perform authentication through any

of the accounts managed by metamask, or, if they’re inclined to do so, they could use their own

key pair outside the metamask by unchecking the ‘use metamask’ checkbox inside the account

box and entering in their own key pair.

If the user opts to use their own key pair by unchecking the metamask checkbox, the page

changes to where most of the interface is blurred while highlighting a form in the top right corner

with the fields to input the key-pair, since it would be useless to access the whole interface without

first providing the credentials needed to perform any of the platform’s functionalities. The Fig.

4.5 image shows how the interface looks while blurred.

Figure 4.5: Logged out web client

The interface becomes clear after the user has inserted both their public key hash and private

key, hinting that the user may interact with the rest of the interface as the account credentials used

Page 43: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Dapp Design 30

for such interactions are provided.

In Fig. 4.6 is a figure of the form where the credentials will be inserted.

Figure 4.6: Logged in account

The public key is automatically inserted from the account logged inside through the metamask

plugin, but the user can just delete and replace it.

To go back to using the metamask plugin, the user can check the ‘use metamask’ checkbox

again.

Once the user is logged in through either method, they will see a balance for two cryptocur-

rencies shown below their account’s private key, these currencies are denominated as ETH and

RLC. These two cryptocurrencies power the economy for all parties involved in the platform. If

the balance for either currency is zero or insufficient you’ll need to use the faucet websites for the

goerli testnet to replenish your balances as mentioned in the setup.

When a user logs in, the system displays the lists of their orders. This is fetched from the

blockchain using their public key hash. A list of products being sold in the entire marketplace

from all sellers are also shown under the title ‘Marketplace Catalog’.

4.2.2 Selling a Product

To sell a product the user needs to be logged in with their keys corresponding to the identity

they wish to sell the product as. The user first needs to set up the portal and log in as detailed

earlier, before being able to publish a product to this platform.

In Fig. 4.7 is illustrated how the form to publish a product looks like.

For simple demonstration purposes the fields necessary to publish a product are a description

of the product, image CID of the IPFS link hosting your image, the stock quantity of the product

and the price of each unit in US dollars. To include an image the user first needs to upload one to

IPFS, and insert the CID of the resulting upload into the correct field, which is the second on the

form.

Page 44: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

4.2 Use-Cases 31

Figure 4.7: Product selling form

The user needs only to fill in all the fields and press on the sell button and the product will be

published for the entire world, as anyone around the world should be able to view the product and

have the opportunity to purchase it once it is deployed on the blockchain.

If the user is opting to use metamask for authentication, they will be prompted to sign the

transaction information, providing a signature which will be used to prove the authorization to

modify the state of the involved contracts in the Ethereum network using the information provided

through the transaction on behalf of the authenticated account. If the user opts to provide a public

and private key, without resorting to using metamask, the user will never be prompted to sign

anything since the raw private key is already provided.

After the transaction has been sent to the Ethereum network, the interface subscribes through

the web3js library to receive an event for when the transaction, which includes our operations, is

included in the Ethereum blockchain as is shown in Fig. 2.1 when the web client calls ’sendTrans-

action’ to later receive a call to the callback with the hash of the transaction. After this, the web3js

library subscribes for the next times a block is added to the blockchain, this is shown in Fig. 2.1

when a transaction is a success inside the alt frame, for each time further raising the probability

the transaction will be solidified in the blockchain, as explained in the blockchain state of the art

section.

The Fig. 2.1 represents the sequence diagram for all transactions to the blockchain, including

for example the ‘deployProduct’ function call of the ItemFactory smart contract instance.

After the product has at least one confirmation, or in other words a block has been added after

its own, it will be listed in the marketplace catalog on the interface of the platform. This was

a design decision of the interface, and the number of confirmations could have been set to any

number. The product’s information lists the product’s image, text information, the sellers account

address and the number of blocks following the one including our transaction, this number is

referenced as confirmations. In Fig. 4.8 is an image which shows how a buyer would view a

product being sold on the platform, it includes the area with the dollar price and remaining stock

right above the call to action to purchase the product.

Page 45: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Dapp Design 32

Figure 4.8: Product form marketplace

The hexadecimal sequence above the information table is the address, which can be otherwise

thought of as the identifier, of the contract instance representing the product on Ethereum. This

contract stores the state of the item, and contains the functions which if called can change this

state. When the contract instance is created after the seller publishes it, Ethereum will emit an

Event with some parameters, this event stores the parameters as read-only logs for future refer-

ence to interfaces. These events allow the interface to index the logs on the blockchain, so the

interface can search for information on the blockchain. As an example, let’s say a seller calls the

function named deployProduct from the Item Factory to create a new product, the function will

emit the event named DeployedProduct with the parameters containing the address of the deployed

product, the text information, the image CID, the price and stock. In the interface by using the

web3.js library I can get back this information from the blockchain by using the address of the

Item Factory from where the events were emitted, and the name of the Event, thus pinpointing on

the blockchain where the information for each deployed product is so it can be read and displayed

on the marketplace’s interface. As the size of the data in the blockchain can be significant, I am

able to search from one block number to the latest, thus narrowing the search and making it faster.

As shown on the diagram in Fig. 4.9, the user interacts only with the blockchain, to call on

the deployProduct function from the ItemFactory instance, this results in the creation of an Item

contract instance, i.e., the smart contract object representing the product for sale.

Figure 4.9: Component diagram when calling deployProduct

Page 46: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

4.2 Use-Cases 33

Once the transaction is executed by the EVM by calling the deployProduct function, further

internal transactions will be executed calling the constructor of the Item contract and potentially

methods from other contract objects, this does not require further transactions to be mined as

function calls from other objects are included in the main transaction from the call to the ’de-

ployProduct’ function.

4.2.3 Handling Private Information

The client information needed to perform purchases is managed in such a way that the off-

chain computations can access it to validate and verify the private data while never leaking it

to anyone, including the host running the computations. This is enabled by Trusted Compute

technology and the decentralized cloud stack provided by iExec.

Figure 4.10: Access to client information from the Dapp@iExec

As illustrated in the diagram in Fig. 4.10, the client uploads their encrypted information to

IPFS to later be retrieved by an Intel SGX enclave where it will be decrypted securely using the

secret stored on the Secret Management Service (SMS).

The client data has a representation in the form of a contract instance on Ethereum, this rep-

resentation uses a contract class called ‘Dataset’. In code Listing 4.1 the contract’s code is shown

and it contains fields for the name given to the data, contains also the link to the data stored

on IPFS, named as m_datasetMultiaddr, and finally a field for the data’s checksum. The dataset

contract is used by the iExec stack when performing the off-chain computations of this project’s

decentralized e-commerce platform.

1c o n t r a c t D a t a s e t i s Ownable2{3

Page 47: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Dapp Design 34

4s t r i n g p u b l i c m_datasetName ;5b y t e s p u b l i c m _ d a t a s e t M u l t i a d d r ;6b y t e s 3 2 p u b l i c m_datase tChecksum ;7c o n s t r u c t o r (8address _da ta se tOwner ,9s t r i n g memory _datase tName ,10b y t e s memory _ d a t a s e t M u l t i a d d r ,11b y t e s 3 2 _da t a se tChecksum )12p u b l i c13{14_ t r a n s f e r O w n e r s h i p ( _ d a t a s e t O w n e r ) ;15m_datasetName = _da tase tName ;16m _ d a t a s e t M u l t i a d d r = _ d a t a s e t M u l t i a d d r ;17m_datase tChecksum = _da ta se tChecksum ;18}19f u n c t i o n t r a n s f e r O w n e r s h i p ( address ) p u b l i c { r e v e r t ("disabled" ) ; }20}

Listing 4.1: Dataset contract provided by iExec

Figure 4.11: Client Information displayed on web client

The Fig. 4.11 shows what in the interface is a representation of the client’s information and

the call to actions to create more information. From the figure it is shown a table and two buttons.

The table contains information already deployed for the payment methods and shipping ad-

dresses.

The first button named ‘Encrypt Data to Send’ will be used as part of the purchase process,

its utility is to encrypt the data payment method and shipping address with the sellers public key

and have it sent to he seller through the ongoing purchase smart contract, this function is detailed

further in the purchase section so it won’t explained in detail here.

The second button called ‘Add Payment Method and Shipping Address’ creates a new payment

method and shipping address, this new information is deployed to iExec and to the blockchain in

the form of the contract from the code Listing 4.1, and it gets displayed on the interface imme-

diately after being included in the blockchain with zero confirmations. Due to current limitations

of the iExec stack, the shipping address and payment method need to be created in pairs, as in

the shipping address cannot be created independently from the payment method and vice versa,

therefore when the user presses on the ‘Add Payment Method and Shipping Address’, they will

Page 48: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

4.2 Use-Cases 35

need to fill out both a payment method and a shipping address to go together. For demonstration

purposes the user can pick a payment and address option pair by ticking the checkbox on top of

the pair, however in reality when making a purchase only the last added payment method and

shipping address are used, this was a decision made to speed up the development and testing of

this decentralized e-commerce demo.

Because the interface is meant for demonstration purposes, some things such as the initial

shipping and payment option displayed on the interface is hard-coded and doesn’t really exist

outside of the interface. If the user does not add data for themselves to use when making purchases,

the interface will use a default payment method and address already created with the values shown

in Fig. 4.11 and in code Listing 4.2.

1a d d r e s s . j s o n :2{3"StreetAddress" : "Heilsbronner Str. 4" ,4"City" : "Neuendettelsau" ,5"PostalCode" : "91564" ,6"CountryCode" : "de"

7}89c r e d i t c a r d . j s o n :10{11"type" : "mastercard" ,12"number" : "5563218655744379" ,13"CVV2" : "123"

14}

Listing 4.2: Client information in file format

When pressing on the ‘Add Payment Method and Shipping Address’ button, the user will

be greeted with the form in Fig. 4.12. This form was originally meant to allow the user to in-

put the client data such as the data shown in code Listing 4.2, however since the iExec SDK is

still relatively new and while implemented some functionalities are not documented, a decision

was made to have the form prompt the user to fill in a URL to their encrypted payment method

and shipping address, which will fill the field named ‘m_datasetMultiaddr’ of an instance of the

‘Dataset’ contract shown in code Listing 4.1, and also the checksum of the encrypted file gener-

ated using SHA-256. This file can be created using the iExec SDK on the terminal by following

the iExec documentation for creating and publishing datasets, and for this two files with the pay-

ment method and shipping address information will be needed with the format of the the examples

shown in code Listing 4.2.

Once the user fills in the data link, and the checksum, and presses on the ‘Create’ button

the interface will deploy an instance of the dataset contract shown on code Listing 4.1, and by

using the iExec SDK the interface will publish an iExec-order to an off-chain order-marketplace,

managed by iExec, with the terms of usage for the data.

The iExec-order, also called dataset order, will feature the terms of usage for the client data,

and will restrict the usage of the data solely for the validator app created for this project, so that

others won’t be able to create their own app and have the decrypted data sent to them.

The app contract is represented in the blockchain in a similar fashion as the dataset contract

shown on code Listing 4.1, but instead of having the contract instance store the IPFS link, it

Page 49: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Dapp Design 36

Figure 4.12: Client Information deployment form

instead stores a docker image with the application code set to run, other details needed for Intel

SGX are stored in the app contract instance on Ethereum, as this is the case the contract instance

is identified by it’s 21 byte address. The dataset Exec-order is signed and stored on an off-chain

marketplace of iExec orders with an ‘apprestrict’ field containing the app address. In code Listing

4.3, the dataset order as an object is shown.

1{2d a t a s e t : address ,3d a t a s e t p r i c e : ’0’ ,4volume : ’1000’ ,5a p p r e s t r i c t : C o n s t a n t s . app ,6t a g : ’tee’

7}

Listing 4.3: Dataset order object

As shown on Fig. 4.10, the encryption key used to encrypt the data exemplified in code Listing

4.2 is pushed to the SMS so that it’s made available for the authorized app created for this project

through the use of the ‘apprestrict’ as seen on the dataset order in code Listing 4.3. This way

only our validator app, run when making a purchase, will be able to access the data and compute

Page 50: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

4.2 Use-Cases 37

whether it’s valid data or not through the use of algorithms and calling APIs. The data should

never leak due to Intel SGX technology.

4.2.4 Making a Purchase

To buy a product the user needs to be logged in with their keys corresponding to the identity

they wish to buy the product with. The user first needs to set up the portal and log in as detailed

in the previous section about accessing the system’s portal and logging in, before being able to

purchase a product on this platform.

Right after logging in the user is met with a list of products being sold on the entire market,

all products are public and viewable to anyone through the blockchain.

Shown in Fig 4.13 is how the products are represented. For simplicity purposes they show

merely the essential to identify a product worth buying.

Figure 4.13: Catalog

Shown to the user are the details of a product, the address of the seller, the price and quantity

for sale. To purchase the product the buyer indicates the quantity they wish to buy, and finally

simply presses the call to action. The order will show up, under the user’s account, after the

transaction is mined.

Much like the process when selling a product, a javascript object will be constructed that

includes all the information necessary to broadcast to the remote node and have the transaction

mined on the Ethereum network. The object will include all necessary fields for the EVM to

decode and execute the function ’performOrder’.

The interface will subscribe to the event for when the transaction gets included in the blockchain,

and for every time a block is mined on top of the block including the transaction, the confirmation

counter for the order on that transaction will increment.

In Fig. 4.14 is an example of the table that shows up under the user’s account after the trans-

action that creates it gets successfully added to the blockchain.

The interface represents an order, or ongoing purchase, as a table of information with every-

thing the user needs to know. For each row on the table the following information is represented:

• Contract: Address of the contract instance;

Page 51: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Dapp Design 38

Figure 4.14: Ongoing purchase or order in the first stage

• Information: Product/Service information;

• Quantity: Amount purchased;

• Price: Price per unit of the product;

• Seller’s Public Key: The public key (not the keccak hash) of the seller;

• RLC Cost: The cost for completing the purchase;

• Confirmations: How many blocks have passed since the purchase was mined.

After the buyer presses ‘Buy’ on the products, as shown in Fig. 4.13, and the creation of the

order contract instance triggers, the web client through Infura merely interacts with the Ethereum

network to call on the performOrder function. Shown in Fig. 4.15 is the diagram of the two

components interacting with each other to call on the performOrder function from the Item in-

stance which results in the creation of an Order contract instance, i.e., the smart contract object

representing the purchase.

Code wise the creation of an order is a similar process to the creation of an item, however

whereas in publishing a product the ‘deployProduct’ function is called from the ItemFactory con-

tract instance, instead the performOrder function is called from one of the Item contract instances.

Therefore much of what’s detailed in the publishing an item process is similar when purchasing

an item. The Fig. 4.15 illustrates the process when creating an order, where the two components,

the web client and blockchain, interact.

Once the order contract is set up, the order needs to go through stages where the validation of

the client’s data is performed. The stages are detailed later in this document, and quickly are shown

in Fig. 4.18, but briefly they are: the deposit of the RLC cryptocurrency, initiation of a request

for execution of the off-chain validation by the decentralized iExec cloud, waiting for the end of

the execution and have a callback function called with the validation result and hash of the client’s

information, and finally completing the purchase by calling a function called ‘completePurchase’

with the IPFS link of the client data encrypted with the seller’s public key.

Page 52: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

4.2 Use-Cases 39

Figure 4.15: Component diagram when calling ’performorder’

When buying a product the information provided by the user needs to be validated, as the

shipping address and the payment method need to be verified. The shipping address needs to

exist and satisfy shipping restrictions, and the credit card used for the payment method needs

to be correct, active and allowed to be used for the purchase. All this requires the execution of

several code instructions and calls to APIs, therefore using only smart contracts is not feasible as

it would become very expensive to run all of this code on Ethereum, and an oracle would need to

be established for trustworthy API calls. While in current e-commerce solutions there would exist

a central server that would process this code, in a decentralized alternative this is not an option.

A possible approach would be to rely on the seller to run the data validation, however that

would require the seller to run a server and as observed from other attempts at decentralized

commerce this approach leads to low user adoption as the platform becomes less user friendly

for the sellers. The approach adopted for this project is having this code and api calls run on a

decentralized cloud where we can replace the centralized servers present on current mainstream

e-commerce options while maintaining data privacy and security through the utilization of Intel

SGX technology by the cloud’s workers. For this project’s implementation, the iExec stack was

used as the decentralized cloud.

After purchasing items on the platform, the user can come back wherever they wish to view

and continue their orders by logging into the platform with their buyer account. Afterwards the

user will be able to see their ongoing orders/purchases and interact with them.

Each item created from the ItemFactory instance is logged for future reference, as is every

order created from an Item instance. This way the web client can run through all Orders and filters

which do belong to the user by comparing the public key hash the user used to log in, and the

public key hash used to create the order.

After a user makes a purchase, the web client will perform the transaction to Ethereum which

will create the order instance out of the Order contract class. This transaction will eventually be

Page 53: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Dapp Design 40

Figure 4.16: Component diagram involved in the buying of a product

added to the blockchain and all users afterwards should be able to view it from the web client due

to the interaction between the web client and the blockchain seen on Fig. 4.16.

In the Fig. 4.17 image shows two examples of ongoing purchases, the first example the pur-

chase has yet to send the client’s data while the second example is already in completed state.

For each table of ongoing purchases there’s an instance of the smart contract called Order,

stored on the blockchain. These instances have a variable to determine the progress of the purchase

and this variable is crucial to the functionality of the contract but also serves to determine at what

stage the ongoing purchase is in. These stages are not relative to the shipment of the product,

but instead related to the stages at which the purchase needs to go through to have the client’s

information validated securely.

The image in Fig. 4.18 shows a state machine for the Order contract where the progression

of the purchase is marked by the state variable of type Enum, and the progression of the state

to a new state effectively occurs only when the respective function completes, or in other words

the transaction is added to the blockchain and the function finishes successfully. This way each

function is called only if the variable is set to a specific state, and the state won’t reach complete

unless the entire validation of the client’s data is successful.

Located inside the order’s information table is a state machine, with the current state of the

ongoing purchase being highlighted in a different color from the rest of the map. This serves to

indicate how many states are left before the order is complete.

After creating the order contract instance, the interface waits for a certain amount of confir-

mations before allowing the first function to be called, this is done so there’s a relatively good

chance the transaction will be included in the longest chain. Every time a function is called and

Page 54: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

4.2 Use-Cases 41

Figure 4.17: Ongoing purchases information tables

the state changes, the interface makes it so a certain amount of confirmations are needed to be able

to proceed. Using web3 javascript api, the interface subscribes for notifications of new blocks or

confirmations.

If user interaction is needed to progress an order, the user will be prompted to press a button

next to the state machine, as is shown from Fig. 4.14, and if any further action is needed a message

will be displayed showing what the user needs to do to progress.

When the user agrees to progress to the next stage by pressing the button and fulfilling the

requirements, the interface will launch the process referenced in Fig. 4.18, where the function of

the respective current state is called to progress to the next state. For every state there’s a function

that when called propels the user to the next state of the order, these functions are represented in

Fig. 4.18 and all functions have a reason to exist, as in each serve a purpose.

At the first state after the creation of the contract instance, named inside the contract as

‘NULL’, the contract instance is waiting for the deposit of the cryptocurrency denominated in

RLC, to pay for all parties involved in the off-chain computation. The Fig. 4.14 shows an ongoing

purchase in this state, awaiting for the user to click on Next to begin the deposit.

For the deposit, the interface will call the function ‘approveAndCall’ from the RLC contract

made available by iExec, this contract is what creates the cryptocurrency named RLC. The func-

Page 55: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Dapp Design 42

Figure 4.18: Order state machine

tion is called with parameters for the quantity and address of the custodian contract. The user

needs to deposit at least the amount asked by the ongoing purchase, which is written in red on the

ongoing purchase’s information table, so the user needs to certify that they have enough balance

in RLC from the Balance under their account.

In Fig. 4.19 is an image of what the balance can look like after the user logs in, in the example

the user account has 3.35 Ether and 110 RLC in cryptocurrency. As seen in Fig. 4.18, the RLC

cost to complete the purchase on that order is 10 RLC, which is displayed in red, therefore the

balance of the account in Fig. 4.19 after they completed the first stage would equal 100 RLC,

as the 10 RLC cost of performing the off-chain computation using the iExec decentralized cloud

would deduct from the initial balance of 110 RLC.

Figure 4.19: Balance

Every time the user progresses an order, the interface will make the user wait a certain number

of confirmations until it lets the user advance to the next state, or explained in other words, after

the client publishes the transaction calling the function which will change the state of the contract,

the interface will make the user wait for confirmations on that transaction. On Fig. 4.20 is an

ongoing purchase representation in the interface, after the user has pressed the button to continue

with the purchase, and thus effectively calling on the first state function from the order contract.

The image in Fig. 4.20 shows the interface making the user wait for at least two confirmations

for the transaction including the first function call of the order contract, until the user is able to

Page 56: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

4.2 Use-Cases 43

Figure 4.20: Order waiting for confirmations

call on the next function. In the case presented in the example, the function that the user is waiting

for the confirmations is named ‘receiveApproval’, and the function which will be allowed next is

named ‘runDataValidation’.

The order contract has the callback function named ‘receiveApproval’ which is a callback

to the ‘approveAndCall’ method of the RLC currency contract, in this function the order’s state

variable is changed to the next state named ‘APPROVED’ inside the contract enum variable type,

so after the deposit is successfully completed the callback function ‘receiveApproval’ is called and

changes the state variable in the order contract instance to ‘APPROVED’.

Figure 4.21: User allowing the order contract to manage 20 RLC of the user’s balance

The diagram in Fig. 4.21 shows how the calls follow one another to reach the state ‘AP-

PROVED’. The client calls the ‘approveAndCall’ function from the RLC contract supplied by the

iExec company, and a callback function in our order contract is called within it to perform any

changes needed to the contract instance. It’s important to note that the transaction that calls ‘ap-

proveAndCall’ is atomic, and the function calls within it the ‘receiveApproval’ function from a

different contract synchronously, so the transaction that includes the call to ‘approveAndCall’ also

makes the call to the ‘receiveApproval’ and if anything goes wrong within any of the functions all

Page 57: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Dapp Design 44

changes to that point are reverted.

After the ‘approveAndCall’ function is done, the order contract inserted as the first parameter

for the function will now be able to spend up to the amount specified in the second parameter of

the function in the RLC cryptocurrency.

Figure 4.22: Ongoing purchase at the second stage

At the ‘APPROVED’ state, as seen in Fig. 4.22, the user will press on ‘Next’ after the confir-

mations, as seen on Fig. 4.20, that 2 blocks were added to the blockchain after the block containing

the transaction with the call to ‘approveAndCall’, and the web client will proceed to call for the

function ‘runDataValidation’ that will create a request and match orders for the workerpool, app

and dataset using the ’matchOrders’ function of the IexecClerk contract, a contract developed by

iExec to match sellers of computing power and sellers of apps and datasets to fulfill the request of

the user granted they have the required amount of RLC to pay all these parties, as in the app and

dataset and workers.

Of course, since the development of the app and dataset are part of this project I can choose

what price I set the use of these at in which case I’ll set them to zero cost so the user will only

have to pay for the workerpool, the workerpool chosen is fetched from the workerpool iExec-

order market, an off-chain marketplace of orders hosted by iExec. A deal will be created on the

blockchain and from this deal a Task ID can be derived which will be used later to fetch the result.

As shown in Fig. 4.25 when ‘runDataValidation’ is called, the request will be published on

the blockchain and schedulers will elect a worker, from their workerpool, to perform the Task of

validating the client’s information, the shipping address and payment method, by executing the

E-Commerce app on Intel SGX enclave, with the payment method and shipping address selected

by the user. Once the function is successfully finished executing the state will be set to AWAIT-

ING_VALIDATION, and as the name suggests the user will have to wait until the workers are

finished executing the app in a Trusted Compute environment.

The Fig. 4.23 shows an order after the ‘runDataValidation’ has been called and it’s awaiting

completion of the off-chain component of this DAPP.

Page 58: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

4.2 Use-Cases 45

Figure 4.23: Ongoing purchase awaiting validation

After consensus on the deterministic result has been achieved, the scheduler will call the func-

tion named ‘receiveResult’ from the originating contract instance, which in this case is the ongoing

purchase contract, and the function will retrieve the callback result from the executed Task to con-

firm if the consensus was that the client’s data was valid. The ‘receiveResult’ also stores the hash

of both the shipping address and payment method delivered by the callback result of the task, and

sets the new state of the contract to ‘VALIDATED’.

Figure 4.24: Interaction with the iExec stack

Finally, with the data properly validated the Web Client will encrypt the shipping address and

payment info using the sellers public key which is shown from the order information as exempli-

fied by Fig. 4.20. To do this the user can press on ‘Create IPFS’ as seen on Fig. 4.11, and fill in

the seller’s public key, or any other shared key with the seller. Seen in Fig. 4.25 is what the form

looks like after pressing the button.

Page 59: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Dapp Design 46

Figure 4.25: Encrypting client information with seller’s public key

The client’s data, previously encrypted and uploaded to IPFS with a secret known only by the

client and by iExec’s secret management service as seen on Fig. 4.10, is stored on IPFS but also

locally on cache and while this is the case the web client may use the client’s data and encrypt it

with the public key of the seller, or in case the cache gets cleared the web client would have to

download the data from IPFS, decrypt the data and encrypt it again with the sellers public key.

After the user presses on the blue ‘Encrypt’ button on the form at Fig. 4.25, a download button

will show up to download the client’s data encrypted with the seller’s key. Once downloaded the

user needs to upload the file to IPFS, and once uploaded the user will take the CID of the file and

enter it into the field present on the ongoing purchase’s information table. It should look like the

illustration in Fig. 4.26.

Figure 4.26: Last stage of an order

After pressing on ‘Send’, the final function named ‘completePurchase’ of the order will be

launched with the CID as parameter. The function will change the state of the contract to the last

one in Fig. 4.18 and emit an Event to have the CID logged onto the blockchain, finally completing

the purchase.

Page 60: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

4.2 Use-Cases 47

Once the call to ‘completePurchase’ is mined and successful, the seller will be able to acquire

from the contract the CID of the encrypted file through the order contract instance, and with their

private key they will be able to decrypt the file thus obtaining the clients details to perform the

sale. The seller can certify that the decrypted data is the correct validated data from the client

by hashing the data and comparing the hashes with the ones stored on the blockchain when the

‘receiveResult’ function was called.

While the web client might make it seem that the platform is not user friendly, it’s important

to mention that many of the design decisions were done to make it easier to test the platform,

both testing the components deployed to Ethereum and the off-chain component run on Intel SGX

enclaves. It is possible to design an interface where the client may only press buy and all stages in

Fig. 4.18 are automatically achieved sequentially, however the user would have to keep the web

client running while doing this as the platform doesn’t have a server to make requests to, and there

being a time interval between the calls to the order contract object getting mined, the web client

would have to keep track of when a transaction got added to the blockchain to perform another,

since it isn’t feasible to send all transactions at once because it’s up to the miner to arrange the

transactions and the order in which they arrange the transactions might not be the desired. It’s

not possible either to make a function in the Order contract class which calls all transactions in

sequence, the first function called in Fig. 4.18 is necessarily by another contract named RLC made

by iExec and after the second function call the contract needs to wait for a callback by the off-chain

component of the platform, finally once the off-chain component is done and returns a callback

the web client may call the last function which can not be called from the callback function since it

needs a parameter which is not provided by the callback from the off-chain component. The client

may always open up the interface and continue to progress orders previously left in an unfinished

state.

Page 61: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Chapter 5

Dapp Implementation

The implementation describes how important details of the DAPP were coded, how they func-

tion and their reasoning for being implemented. The main components with code written for them

are the Ethereum smart contracts, the python application run in a trusted execution environment,

and of course the web client.

5.1 Tools Used

To manage the Ethereum accounts, the main tools used were Metamask and Infura. Infura

provides a remote Ethereum node to be able to interact with Ethereum without having to run our

own node, while metamask is a browser plugin that once installed creates a few key pairs to be

used as accounts on Ethereum. Docker was used to create container images of the application to

be executed off-chain by the iExec workers using Intel SGX, and Docker Compose was used to

orchestrate the iExec stack to get a better understanding of how it worked. The Ganache tool is

used to create a local blockchain simulation, and it was used in a docker container as part of the

iExec stack orchestration. The web client is based on node.js, and the React library was a big

component. The web3.js library collection was used in the web client to interact with the remote

Ethereum node in making transactions and fetching data from the blockchain.

5.2 Web Client

The web client is an application built on node.js using the React library, it does not connect to

any server outside the host to perform authentication. The private key is only stored locally and

never leaves the user’s computer, the private key is only used for local signing of messages and

transactions. It makes use of the web3.js library to easily create objects containing the transaction

conditions, sign them and seamlessly transmit them to the remote Ethereum node provided by

Infura.

The web client was developed for testing of the DAPP. See Figure 5.1 to have an idea of what

the front end looks like. The aesthetics were, clearly, not the focal point of this project, but instead

48

Page 62: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

5.2 Web Client 49

the goal was to show that by leveraging both Blockchain and Trusted Compute technology a de-

centralized e-commerce platform could be conceived to be more effective at providing a solution.

Figure 5.1: Interaction between blockchain and user interface

The code Listing 5.1 shows the ’reloadProducts’ function which is invoked when the client

reloads products to read from the blockchain what new products have been added to the market-

place catalog by sellers on the platform.

As shown from the function in line 10, the function ’getPastEvents’ is called from the object

representing the marketplace contract object, constructed from a web3js class, and the function

takes as parameters the event name and the interval of blocks in the blockchain for which to search

for the event having been emitted within said interval. The function takes as the last parameter a

callback function which will receive an array of all emitted ’DeployedProduct’ events. The event

is emitted by the contract ItemFactory represented in appendix in code Listing C.1, in line 25.

1r e l o a d P r o d u c t s ( f i r s t I t e m = u n d e f i n e d ) {2c o n s t a b i = S t o r e C o n t r a c t . a b i ;34c o n s t address = C o n s t a n t s . s t o r e C o n t r a c t A d d r e s s ;56c o n s t c o n t r a c t = new t h i s . s t a t e . web3 . e t h . Contract ( ab i , address )78l e t p r o d s A v a i l a b l e = [ ] ;910c o n t r a c t . g e t P a s t E v e n t s (11’DeployedProduct’ ,12{13f romBlock : C o n s t a n t s . START_BLOCK,14t o B l o c k : ’latest’

15} ,16f u n c t i o n ( e r r , e v e n t s ) {1718e v e n t s . f o r E a c h ( event => {19i f ( event . r e t u r n V a l u e s !== u n d e f i n e d ) {

Page 63: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Dapp Implementation 50

20l e t _ c o n t r a c t A d d r e s s = event . r e t u r n V a l u e s . _ c o n t r a c t A d d r e s s ;21l e t pubkey = event . r e t u r n V a l u e s . s e l l e r P K ;22l e t _ images = event . r e t u r n V a l u e s . _ images ;23l e t _ d e s c r i p t i o n = event . r e t u r n V a l u e s . _ d e s c r i p t i o n ;24l e t _ i n i c i a l S t o c k = event . r e t u r n V a l u e s . q u a n t i t y I n S t o c k ;25l e t _ v a l u e = event . r e t u r n V a l u e s . _ p r i c e ;2627c o n s t c o n t r a c t = new t h i s . s t a t e . web3 . e t h . Contract ( P u r c h a s e C o n t r a c t . ab i , _ c o n t r a c t A d d r e s s )28t h i s . s t a t e . web3 . e t h . getBlockNumber ( ) . t h e n ( d a t a => {2930c o n t r a c t . methods . nS tock ( ) . c a l l ( ) . t h e n ( ( c u r r e n t S t o c k , e r r ) => {31p r o d s A v a i l a b l e . push ( {32t r a n s a c t i o n H a s h : event . t r a n s a c t i o n H a s h ,33c o n t r a c t A d d r e s s : _ c o n t r a c t A d d r e s s ,34c o n f i r m a t i o n s : d a t a . va lueOf ( )−event . blockNumber +1 ,35p r i c e : _va lue ,36bough t : ( c u r r e n t S t o c k > 0) ? f a l s e : true ,37s e l l e r : pubkey ,38images : _images ,39d e s c r i p t i o n : _ d e s c r i p t i o n ,40i n i c i a l S t o c k : _ i n i c i a l S t o c k ,41c u r r e n t S t o c k : _ i n i c i a l S t o c k − ( _ i n i c i a l S t o c k − c u r r e n t S t o c k ) ,42} ) ;4344i f ( f i r s t I t e m !== u n d e f i n e d ) {45p r o d s A v a i l a b l e . s o r t ( f u n c t i o n ( x , y ) { re turn x . d e s c r i p t i o n == f i r s t I t e m ? −1 : y .

d e s c r i p t i o n == f i r s t I t e m ? 1 : 0 ; } ) ;46}4748t h i s . s t a t e . p r o d u c t s A v a i l a b l e = p r o d s A v a i l a b l e ;4950t h i s . s e t S t a t e ( { p r o d u c t s A v a i l a b l e : p r o d s A v a i l a b l e } ) ;51} )52} ) ;53}54} ) ;55} . b ind ( t h i s )56) ;57}

Listing 5.1: reloadProducts function from the Web Client

Listing 5.2 shows the function ’buyThisProduct’ which is invoked when the user makes a

purchase on the DAPP. It utilizes the web3.js library to send a transaction to Ethereum in lines

54 and 68. These lines show two different ways to send a signed transaction. In line 54, the web

client is prompting the user to sign the transaction through the metamask plugin, whereas in line

68 the web3js library is using a private key provided by the user in case the user chooses not to

use metamask.

The callback function at line 31 is called once the transaction gets mined, and for the following

times that there are confirmations on the transaction, that is blocks mined on top of the block

including the transaction. The function updates the interface with the received information.

The transaction details and conditions are stored in the txObject defined in line 20, the ’to’ field

specifies the address of the product smart contract object to which the transaction is applied. The

’data’ field of the object specifies which function will be called, performOrder, and its arguments,

and it’s encoded in ABI format.

1b u y T h i s P r o d u c t ( c o n t r a c t A d d r e s s , q u a n t i t y ) {23l e t p r o d u c t = t h i s . s t a t e . p r o d u c t s A v a i l a b l e . f i n d ( p r o d u c t => p r o d u c t . c o n t r a c t A d d r e s s === c o n t r a c t A d d r e s s )45re turn ( ) =>{6

Page 64: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

5.2 Web Client 51

7t h i s . s e t S t a t e ( { w a i t i n g N e x t : t rue } ) ;89c o n s t c o n t r a c t A B I = P u r c h a s e C o n t r a c t . a b i ;1011c o n s t c o n t r a c t = new t h i s . s t a t e . web3 . e t h . Contract ( c o n t r a c t A B I , c o n t r a c t A d d r e s s )1213i f ( t h i s . s t a t e . a c c o u n t 1 ( ) . l e n g t h === 42)1415t h i s . s t a t e . web3 . e t h . g e t T r a n s a c t i o n C o u n t ( t h i s . s t a t e . a c c o u n t 1 ( ) , ( e r r , t xCoun t ) => {1617var d a t a s e t A d d r e s s = t h i s . s t a t e . g e t D a t a s e t A d d r e s s ( )18var clDS = ( d a t a s e t A d d r e s s !== u n d e f i n e d ) ? d a t a s e t A d d r e s s : C o n s t a n t s . c l i e n t D a t a s e t ;1920c o n s t t x O b j e c t = {21nonce : Web3Uti ls . toHex ( txCoun t ) ,22g a s L i m i t : Web3Uti l s . toHex (8000000) , // Raise the gas limit to a much higher amount

23g a s P r i c e : Web3Uti ls . toHex ( Web3Uti l s . toWei (’10’ , ’gwei’ ) ) ,24t o : c o n t r a c t A d d r e s s ,25d a t a : c o n t r a c t . methods . p e r f o r m O r d e r ( clDS , C o n s t a n t s . workerpoo l , q u a n t i t y , C o n s t a n t s .DEBUG) .

encodeABI ( ) ,26from : t h i s . s t a t e . a c c o u n t 1 ( )27}2829c o n s o l e . l o g ("Sending transaction..." )3031var c a l l b a c k _ = ( confsN , r e c e i p t ) => {3233var o r d e r C o n t r a c t = r e c e i p t . l o g s [ 0 ] . t o p i c s [ 1 ]3435o r d e r C o n t r a c t = ’0x’ + o r d e r C o n t r a c t . s u b s t r i n g ( 2 6 , 66) ;3637t h i s . p u r c h a s e P u b l i s h e d ( confsN ,38{ . . . r e c e i p t , c o n t r a c t A d d r e s s : o r d e r C o n t r a c t } ,39p r o d u c t . p r i c e ,40p r o d u c t . s e l l e r ,41p r o d u c t . d e s c r i p t i o n ,42q u a n t i t y ,43p r o d u c t . s e l l e r ,44r e c e i p t . blockNumber ,450 ,46’’

47) ;48}4950i f ( t h i s . s t a t e . useMetamask ( ) ) {51t x O b j e c t . c h a i n = C o n s t a n t s . chainName52t x O b j e c t . c h a i n I d = C o n s t a n t s . cha in ID5354t h i s . s t a t e . getWeb3 ( ) . e t h . s e n d T r a n s a c t i o n ( t x O b j e c t , ( e r r , txHash ) =>{55i f ( e r r !== n u l l ) {56c o n s o l e . l o g ( e r r )57a l e r t (’Please refill your balance!’ )58}59} ) . on ("confirmation" , c a l l b a c k _ )60} e l s e {6162c o n s t t x = new T r a n s a c t i o n ( t x O b j e c t , {’chain’ : C o n s t a n t s . chainName } )63t x . s i g n ( B u f f e r . from ( t h i s . s t a t e . p r i v a t e K e y 1 ( ) , ’hex’ ) )6465c o n s t s e r i a l i z e d T x = t x . s e r i a l i z e ( )66c o n s t raw = ’0x’ + s e r i a l i z e d T x . t o S t r i n g (’hex’ )6768t h i s . s t a t e . web3 . e t h . s e n d S i g n e d T r a n s a c t i o n ( raw , ( e r r , txHash ) => {69i f ( e r r !== n u l l ) {70c o n s o l e . l o g ( e r r )71a l e r t (’Please refill your balance!’ )72}73} ) . on ("confirmation" , c a l l b a c k _ )74}75}76)77}78}

Listing 5.2: buyThisProduct function from the Web Client

Page 65: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Dapp Implementation 52

5.3 Ethereum

The Ethereum component consists of a set of smart contracts. These are implemented in the

programming language Solidity, which by convention have the extension ".sol". Although it’s not

the only programming language available to develop smart contracts on Ethereum, it is the most

widely used by developers.

In this section, we describe some relevant details of the implementation of smart contracts in

Solidity, using as an example the Order contract, which is the most important DAPP’s contract.

As already mentioned, an Order contract goes through several stages before its completion,

upon which the seller should begin shipping the product to the buyer’s home address.

The first state requires the order contract object to own and manage an amount in the RLC

cryptocurrency, to do this the user has to delegate an allowance to the contract instance out of their

own balance. To achieve this, the user needs to call the function ’approveAndCall’ in shown in

line 2 of the code Listing 5.3 from the smart contract that governs the RLC cryptocurrency.

1/* Approve and then comunicate the approved contract in a single tx */

2f u n c t i o n approveAndCal l ( address _spender , uint256 _va lue , b y t e s _ e x t r a D a t a ) {3TokenSpender s p e n d e r = TokenSpender ( _ s p e n d e r ) ;4i f ( app rove ( _spender , _ v a l u e ) ) {5s p e n d e r . r e c e i v e A p p r o v a l ( msg . sende r , _va lue , t h i s , _ e x t r a D a t a ) ;6}7}

Listing 5.3: approveAndCall function from RLC.sol [1]

The ’approveAndCall’ function takes as parameters the address of the order instance, the al-

lowance, and an additional optional parameter. The function then calls from the order instance,

via its address, the function ’receiveApproval’ that is shown in the listing 5.4.

1f u n c t i o n r e c e i v e A p p r o v a l ( address _sende r , uint256 fee , address , b y t e s c a l l d a t a )2e x t e r n a l3{4r e q u i r e ( msg . s e n d e r == address ( t o k e n ) ) ;56_depos i tWorkFee ( _sende r , f e e ) ;7}8f u n c t i o n _depos i tWorkFee ( address _buyer , uint256 worke rPoo lFee )9i n t e r n a l10{11r e q u i r e ( t o k e n . t r a n s f e r F r o m ( _buyer , address ( t h i s ) , worke rPoo lFee ) ) ;1213m_orderMetada ta . p o t V a l u e = m_orderMetada ta . p o t V a l u e . add ( worke rPoo lFee ) ;1415m_orderMetada ta . s t a t u s = OrderS ta tusEnum .APPROVED;1617emit NewFeeDeposi t ( worke rPoo lFee ) ;18}

Listing 5.4: receiveApproval function from Order.sol

The ’receiveApproval’ changes the status of the contract instance to ’APPROVED’ where it

will from then on allow the contract instance to start running the validation.

The client’s data validation starts by running the function ’runDataValidation’, see Listing 5.5,

which will create an iExec request to validate address and payment info. This request includes

Page 66: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

5.3 Ethereum 53

details of the app, dataset, which contains address and payment info, and workerpool, including

their usage conditions which are all provided as parameters to the function. After the creation of

the request the function will call ’signRequestOrder’ followed by ’matchOrders’, at lines 37 and

43 respectively, these functions belong to the IexecClerk [25] contract instance which is referenced

in the order contract’s abstract contract named ’IexecDoracle’, and they will create a Deal object

and if successful will emit an event with the deal’s id. The contract IexecClerk is provided by

iExec and was not developed for this project.

1f u n c t i o n r u n D a t a V a l i d a t i o n (2IexecODBLibOrders . AppOrder c a l l d a t a _apporde r ,3IexecODBLibOrders . D a t a s e t O r d e r c a l l d a t a _ d a t a s e t o r d e r ,4IexecODBLibOrders . Workerpoo lOrder c a l l d a t a _ w o r k e r p o o l o r d e r )5e x t e r n a l s e n d e r I s O r d e r O w n e r ( )6{78Orde rMe tada t a s t o r a g e d e t a i l s = m_orderMetada ta ;910r e q u i r e ( m_orde rMetada ta . p o t V a l u e > 0 , ’pot value equals zero’ ) ;1112r e q u i r e ( d e t a i l s . s t a t u s == OrderS ta tusEnum . APPROVED, ’Order status not null’ ) ;13r e q u i r e ( d e t a i l s . o r a c l e C a l l == b y t e s 3 2 ( 0 ) , ’Oracle call in progress’ ) ;1415r e q u i r e ( m_author izedApp == address ( 0 ) | | _ c h e c k I d e n t i t y ( m_author izedApp , _ a p p o r d e r . app ,

i e x e c C l e r k .GROUPMEMBER_PURPOSE( ) ) , "unauthorized-app" ) ;16r e q u i r e ( m _ a u t h o r i z e d D a t a s e t == address ( 0 ) | | _ c h e c k I d e n t i t y ( m _ a u t h o r i z e d D a t a s e t , _ d a t a s e t o r d e r . d a t a s e t ,

i e x e c C l e r k .GROUPMEMBER_PURPOSE( ) ) , "unauthorized-dataset" ) ;17r e q u i r e ( m_au tho r i zedWorke rpoo l == address ( 0 ) | | _ c h e c k I d e n t i t y ( m_au thor i zedWorkerpoo l , _ w o r k e r p o o l o r d e r .

workerpoo l , i e x e c C l e r k .GROUPMEMBER_PURPOSE( ) ) , "unauthorized-workerpool" ) ;1819IexecODBLibOrders . R e q u e s t O r d e r memory r e q u e s t o r d e r ;2021r e q u e s t o r d e r . app = _ a p p o r d e r . app ; //address

22r e q u e s t o r d e r . appmaxpr i ce = _ a p p o r d e r . a p p p r i c e ; //uint256

23r e q u e s t o r d e r . d a t a s e t = _ d a t a s e t o r d e r . d a t a s e t ; //address

24r e q u e s t o r d e r . d a t a s e t m a x p r i c e = _ d a t a s e t o r d e r . d a t a s e t p r i c e ; //uint256

25r e q u e s t o r d e r . w o r k e r p o o l = _ w o r k e r p o o l o r d e r . w o r k e r p o o l ; //address

26r e q u e s t o r d e r . w o r k e r p o o l m a x p r i c e = _ w o r k e r p o o l o r d e r . w o r k e r p o o l p r i c e ; //uint256

27r e q u e s t o r d e r . r e q u e s t e r = address ( t h i s ) ; //address

28r e q u e s t o r d e r . volume = 1 ; //uint256

29r e q u e s t o r d e r . t a g = TAG; //bytes32

30r e q u e s t o r d e r . c a t e g o r y = _ w o r k e r p o o l o r d e r . c a t e g o r y ; //uint256

31r e q u e s t o r d e r . t r u s t = TRUST ; //uint256

32r e q u e s t o r d e r . b e n e f i c i a r y = address ( 0 ) ; //address

33r e q u e s t o r d e r . c a l l b a c k = address ( t h i s ) ; //address

34r e q u e s t o r d e r . params = PARAMS; //string

35r e q u e s t o r d e r . s a l t = keccak256 ( a b i . encodePacked ( now , address ( t h i s ) ) ) ; //bytes32

3637r e q u i r e ( i e x e c C l e r k . s i g n R e q u e s t O r d e r ( r e q u e s t o r d e r ) , ’error signing request’ ) ;3839uint256 d e a l p r i c e = _ a p p o r d e r . a p p p r i c e . add ( _ d a t a s e t o r d e r . d a t a s e t p r i c e ) . add ( _ w o r k e r p o o l o r d e r . w o r k e r p o o l p r i c e ) ;40i E x e c D e p o s i t ( d e a l p r i c e ) ;41d e t a i l s . p o t V a l u e = d e t a i l s . p o t V a l u e . sub ( d e a l p r i c e ) ;4243b y t e s 3 2 d e a l i d = i e x e c C l e r k . ma tchOrde r s ( _apporde r , _ d a t a s e t o r d e r , _ w o r k e r p o o l o r d e r , r e q u e s t o r d e r ) ;4445b y t e s 3 2 t a s k i d = keccak256 ( a b i . encodePacked ( d e a l i d , uint256 ( 0 ) ) ) ;4647d e t a i l s . o r a c l e C a l l = t a s k i d ;48d e t a i l s . s t a t u s = OrderS ta tusEnum . AWAITING_VALIDATION ;4950i f (DEBUG == t rue ) {51r e c e i v e R e s u l t ( ) ;52}5354emit V a l i d a t i o n S t a r t e d ( t a s k i d ) ;55}

Listing 5.5: runDataValidation function from Order.sol

Page 67: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Dapp Implementation 54

After the deal has been created, the workerpool’s scheduler will detect the emitted event, and

will begin performing the request by assigning a worker to execute the app, by creating the Intel

SGX enclave and running the docker container inside it.

The docker container’s image is acquired from a field of the first parameter ’_apporder’ of the

’runDataValidation’ function, which contains a link to the public image in docker hub.

The Dockerfile with the docker image contains an entry-point which unzips the dataset file

acquired by downloading from the IPFS link in a field of the second parameter ’_datasetorder’ of

the ’runDataValidation’ function. During the execution of the application, a secured authenticated

channel is be established with the Secret Management Service hosted by iExec, which will deliver

the secret to decrypt the dataset file inside the Intel SGX enclave run by a worker.

Once the Intel SGX enclave completes the off-chain computation, it will invoke the ’receiveRe-

sult’ callback of the order smart contract instance with the result of the off-chain computation as

a parameter. The result will contain a boolean indicating whether the client’s data was deemed to

be valid, and, if so, will contain a hash for both the payment method and shipping address. This

result is stored on the blockchain as a read-only log for future reference by the seller.

If the client’s data was valid, the user will be able to call the ’completePurchase’ function

in line 1, by pressing the SEND button as described in Section 4.2.4. Listing 5.6 shows the

code of this function, which changes the order’s status to ’COMPLETE’. The ’completePurchase’

function takes as parameter a string with a CID of an IPFS file with the client’s data encrypted

with the seller’s public key.

1f u n c t i o n c o m p l e t e P u r c h a s e ( s t r i n g c a l l d a t a i p f s D a t a s e t )2e x t e r n a l s e n d e r I s O r d e r O w n e r ( )3{4Orde rMe tada t a s t o r a g e d e t a i l s = m_orderMetada ta ;56r e q u i r e ( d e t a i l s . s t a t u s == OrderS ta tusEnum . VALIDATED) ;78d e t a i l s . s t a t u s = OrderS ta tusEnum .COMPLETE;910i t em . r e d u c e S t o c k ( ) ;1112emit E n c r D a t a s e t U p l o a d e d ( i p f s D a t a s e t ) ;13}

Listing 5.6: completePurchase function from Order.sol

The ’completePurchase’ function will emit an event with the IPFS CID of the file contain-

ing the client’s information encrypted with the seller’s public key, thus logging the CID on the

blockchain to be picked up later by the seller who will use their private key to decrypt the file and

acquire the data needed to perform the shipping and get payed.

After the seller has the raw client’s information, they can hash the information and compare

the hashed value with the hashes stored on the blockchain when the ’runValidation’ function was

called. This way the seller can verify that the previously validated data match’s the data provided

later by the client through the call to ’completePurchase’, while never publicly disclosing sensitive

data.

Page 68: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

5.4 iExec 55

5.4 iExec

When the workers have initialized the trusted execution environment, they will start execution

of the app, unzipping the dataset file and fetching the secret from the secret management service

managed by iExec to decrypt the data to from the dataset file. The executed app was developed in

Python, and consequently all the app’s files have the ’.py’ extension.

The file in 5.7 is the entry-point of the app, and as shown the shipping address will be verified

from the execution of the ’verifyDeliveryAddress’ function in line 10, and the verification of the

payment method will start from the execution of the ’checkCreditCard’ function at line 12.

1from v e r i f y A d d r e s s import v e r i f y D e l i v e r y A d d r e s s2from c r e d i t c a r d c h e c k import c h e c k C r e d i t C a r d34from u t i l s import ∗5import j s o n67i f __name__ == ’__main__’ :8v a l i d i t y = j s o n . l o a d s (’{"address": false, "credit": false}’ ) ;910a d d r e s s R e t = v e r i f y D e l i v e r y A d d r e s s ( v a l i d i t y )1112c r e d i t R e t = c h e c k C r e d i t C a r d ( v a l i d i t y )1314w r i t e R e s u l t ( v a l i d i t y , a d d r e s s R e t , c r e d i t R e t )

Listing 5.7: entrypoint file app.py of the off-chain application

As described in Section 4.2.4, these verifications are performed by third party services. In our

prototype we have implemented them as very simple Web services. Thus to send a request for ver-

ification of the shipping address, the verifyDeliveryAddress function calls the _sendRequestAPI

function, see line 15 in Listing 5.8. The result from the request is a JSON record whose ’status’

field indicates whether the address does indeed exist or not. The URL and API key are stored in a

file included in the docker image, an example of this file is shown in 5.9.

1def _sendReques tAPI ( i n p u t s , a p i ) :2i n p u t s ["APIKey" ] = a p i ["APIKey" ]3f r a g m e n t s = ""

4c o n c a t _ c h a r = "?"

56f o r key in i n p u t s . keys ( ) :7v a l u e = i n p u t s [ key ] . r e p l a c e (" " , "%20" ) ;8i f v a l u e i s not None :9f r a g m e n t s += ’{}{}={}’ . format ( c o n c a t _ c h a r , key , v a l u e )10c o n c a t _ c h a r = "&"

1112u r l = "https://{}/api/verify{}" . format ( a p i [’host’ ] , f r a g m e n t s )1314h e a d e r s = {}15d a t a = u r l l i b . r e q u e s t . u r l o p e n ( u r l l i b . r e q u e s t . Reques t ( u r l , h e a d e r s = h e a d e r s ) ) . r e a d ( )16r e s u l t s = j s o n . l o a d s ( d a t a )1718r e s u l t s ["status" ] = True i f r e s u l t s ["status" ] == "VALID" e l s e F a l s e1920re turn r e s u l t s

Listing 5.8: _sendRequestAPI function from verifyAddress.py

Page 69: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Dapp Implementation 56

1 {2 "host" : "api.address-validator.net" ,3 "APIKey" : "av-19fd302e6d0255bdad5f4b6abeab502b"

4 }

Listing 5.9: addressApi.json

Once both the address and the payment method have been validated, the application will gen-

erate a callback response by calling the ’encodeCallback’ function, see Listing 5.10, first line.

This function hashes separately both the shipping address (line 6) and the payment method (line

4). These are concatenated with the result of the validations on together with the response, ’valid-

ityX’, to generate the response to the DAPP.

The callback response will then get hashed entirely by the function at line 16, so that it can be

used later on the consensus algorithm between all workers who ran this application to determine

honest workers from a majority deterministic result. In reality, as our DAPP is run in a TEE

the consensus is not needed as explain in Chapter 2.8, so the ’generateDeterminism’ function is

technically not necessary.1def e n c o d e C a l l b a c k ( v a l i t i y X , c r e d i t D a t a , a d d r e s s D a t a , p a t h s ) :2k = sha3 . keccak_256 ( )3k . u p d a t e ( c r e d i t D a t a . encode ("utf8" ) )4c r e d i t D a t a = k . h e x d i g e s t ( )5k . u p d a t e ( a d d r e s s D a t a . encode ("utf8" ) )6a d d r e s s D a t a = k . h e x d i g e s t ( )78c a l l b a c k = e t h _ a b i . e n c o d e _ a b i ( [ ’bool’ , ’string’ , ’string’ ] , [ v a l i t i y X , c r e d i t D a t a , a d d r e s s D a t a ] ) . hex ( )910wi th open ( p a t h s ["callbackFilePath" ] , ’w+’ ) a s c a l l b a c k F i l e :11c a l l b a c k F i l e . s eek ( 0 )12c a l l b a c k F i l e . w r i t e ("0x{}" . format ( c a l l b a c k ) )1314re turn c a l l b a c k1516def g e n e r a t e D e t e r m i n i s m ( raw , e x i t c o d e , p a t h s ) :17d t = b y t e s . f romhex ( raw ) i f e x i t c o d e == 0 e l s e s t r ( raw ) . encode ( )1819d e t e r m i n i s m = sha3 . keccak_256 ( )20d e t e r m i n i s m . u p d a t e ( d t )2122wi th open ( p a t h s ["determinismFilePath" ] , ’w+’ ) a s d e t e r m i n i s m F i l e :23d e t e r m i n i s m F i l e . w r i t e (’0x{}’ . format ( d e t e r m i n i s m . h e x d i g e s t ( ) ) )

Listing 5.10: callback and determinism functions from utils.py

Just before terminating, the application calls the ’receiveResult’ function of the order smart

contract using as a parameter the ’callback’ returned by the ’encodeCallback’ function.

Page 70: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Chapter 6

Dapp Evaluation

In this section we evaluate the Dapp along three dimensions: performance, security and cost.

Performance is certainly an important criteria because it is essential for adoption, security is critical

for e-commerce, and the monetary cost of using Ethereum and iExec is important for the viability

of the application. Because the Dapp is built on top of Ethereum and iExec, our discussion focuses

on these three components.

6.1 Performance

This section evaluates the performance of using Ethereum and iExec, or in other words how

much time a user has to wait to complete an action on this application.

6.1.1 Ethereum

As described on the Ethereum section in Chapter 2.2, changes to the Ethereum blockchain are

enacted through transactions. Lets say the user wants to create an instance of the Item contract

on Ethereum, the user would have to create a transaction message with all data for the creation of

the Item contract instance in Ethereum. Then the transaction message would have to be sent to an

Ethereum node and from there spread to other Ethereum nodes where the nodes would house the

transaction in a transaction pool. Once an Ethereum miner node got their turn in including a block

to the blockchain, they would fetch the transactions from their pool to add to the block. A rational

miner would always include the highest paying transactions until it hit the block limit.

If the Ethereum platform is overwhelmed with transactions, to the point of not being able to

include all transactions in a block, including reasonably priced ones, then the user would have

to either increase the payed fee or wait until Ethereum got less congested. This would mean a

potentially sizable delay for a transaction to be included in the Ethereum blockchain. It’s not

possible to predict when the Ethereum network gets congested, so it would have to be accepted as

something that can happen occasionally, at least while Ethereum isn’t upgraded.

Block time on Ethereum is on average 13 seconds [26], which means that on average every 13

seconds a new block gets added to the Ethereum blockchain. In the best case, if the transaction

57

Page 71: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Dapp Evaluation 58

to create the Item contract instance is immediately mined in the next block, then it should take

13 seconds on average for a transaction to be included and change the state of the Ethereum

blockchain, plus a few second for the latency of message propagation and having the transaction

included in the lucky node’s pool. However, realistically the fee payed would have to be high for

a timing close to 13 seconds.

To complete a purchase of a product, it takes 4 transactions in total to be made, and these

transactions need to be sequential and in different blocks. That would mean in a best-case scenario

it would take around one minute to perform all transactions to Ethereum needed to complete

a purchase, if the the number of confirmations the interface demands the user to wait for each

transaction is set to zero. Now realistically, it may take much longer depending on the fee of a

transaction and the utilization of the Ethereum platform at the time the transaction is received.

6.1.2 iExec

While the iExec company hasn’t released any benchmarks for their platform, there are bench-

marks on the technology used by iExec, since workers run SCONE based SGX Enclaves.

As shown in Figure 6.1, the software PySpark is used to test through the different TPC-H

benchmark queries. TPC-H is a database benchmark for ad-hoc queries by decision making com-

putational systems, and PySpark is a Python API for Apache Spark which is a Big Data tool for

processing large quantities of data. These tools while not relevant for this work, provide a mea-

sure of the impact in performance when using the SCONE SDK. From the chart it is shown that

the difference in latency between running PySpark on SCONE based SGX Enclaves and as native

PySpark is small, with an average slowdown of 22% [27].

Figure 6.1: Scone-Based SGX PySpark PerformanceSource: [27]

Running the off-chain component of this DAPP locally in a docker container takes around

an average of 3 seconds under the simulation mode for SCONE, so the time it should take for

the execution of the application by a cloud worker is most likely close to this value, specially

considering the chart in Fig. 6.1.

However, the speed of execution for the actual off-chain application is likely one-order of

magnitude lower than the latency experienced by all the steps required to execute an application

Page 72: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

6.2 Security 59

on the iExec decentralized cloud computing. First the request needs to be picked up by the work-

erpool, workers needs to be assigned, the Enclave initialized, the download of the dataset along

with the secret from the SMS, until finally the execution finishes and the callback function of the

originating contract instance is called.

There exists a testing ground for the iExec decentralized cloud on the goerli Ethereum testnet,

that we used to carry-out many tests for the off-chain application. From making the transaction

that starts the process, until the callback with the result is called from the originating order contract

object, the test network consistently took close to 4 minutes. This time interval was measured by

computing the difference between the initialize block time and the finalize block time from the

iExec explorer in Task details [28]. In Table 6.1 is listed some off-chain executions of the DAPP’s

off-chain component, and the time when the Task is picked up and initialized to the time the

callback of the order contract instance is called and the Task is finalized.

Task ID Initialize Finalize Interval

0xce95b51119d5 f 4146 f f b1c3b6ba f 69b2b7373be58acc7a21cce7695dd0687408 03 : 46 : 22 03 : 50 : 37 00 : 04 : 15

0x1cd58262a941c32512b466896817215 f 53 f 421 f 368b6a5bbb168cdc688a7cb26 04 : 26 : 07 04 : 30 : 07 00 : 04 : 00

0xde8a59d f f 5e9a7a23d44016c483b1 f 102e88 f ea34150441395daa8149 f 531803 04 : 49 : 37 04 : 53 : 22 00 : 03 : 45

0x5c0ee28c012ea0b4c56811e4b8a f a f 2397a1d0c59616e242b1c470de63bc560c 05 : 03 : 52 05 : 07 : 37 00 : 03 : 45

0xe4ac7b f 0e5578 f 8edc5d27018ed7e f 836 f c f cb6e6dad f 7 f 436ec6ab43782cc94 05 : 26 : 07 05 : 30 : 07 00 : 04 : 15

0x19c3322959266c5aab6600ca0e3c0647b00db8c8d1aca5c6c77 f 2b105629cd04 05 : 59 : 37 06 : 03 : 37 00 : 04 : 00

0xb53a524c f 98a0a30b8c9b090b8966402648 f 062c07a f 1606c48eae6941b5 f e6c 06 : 28 : 52 06 : 32 : 37 00 : 03 : 45

0x687eb81d08804 f be9bb769eda917665b1143e91b57c68ea49 f 95 f 1b5d59c7721 06 : 41 : 07 06 : 45 : 07 00 : 04 : 00

0x0d64 f c91 f 5008edb78e92d5b460c4d6b9603ab3091842146 f f 7 f b8393 f 06 f e f 6 06 : 50 : 07 06 : 54 : 22 00 : 04 : 15

0xda1c25815552d54c65b15ce410 f 2217982ed0dc44ad518b68cc1c392b23ddd9d 06 : 58 : 37 07 : 02 : 37 00 : 04 : 00

Table 6.1: Some of the DAPP’s off-chain executions

Concluding, the off-chain component to make a purchase adds around 4 minutes to the waiting

time for a complete purchase and some of this time is the transaction that the iExec system makes

to call the callback function of the order contract instance.

6.2 Security

This section evaluates the security of using Ethereum and iExec, as security is a focal point

for this application.

6.2.1 Ethereum

Even after a transactions is included in a block, it’s down to probability if it remains part of the

longest chain the consensus agrees to be the real blockchain of Ethereum. To have a good proba-

bility that a transaction will remain immutable on the blockchain, the transaction’s sender should

Page 73: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Dapp Evaluation 60

wait for a few more blocks to get added after its own, otherwise known as confirmations. For ev-

ery confirmation, the probability of the transaction being included in the longest chain increases,

this is the reason most websites who offer payment via Ether demand for at least 35 confirmations

before considering the payment fulfilled. At 35 confirmations, a transaction has a probability of

well over 99% to remain immutable, as the cost of keeping up a 51% attack past 35 blocks would

be very high on Ethereum, however since websites that allow payment in Ether are the primary

victims of double spending attacks they need many confirmations to be cautions.

The Ethereum network offers the most decentralized and secure, smart contract enabled, plat-

form in the cryptocurrency space. The biggest security risk for Ethereum is that a few mining pools

are responsible for mining a significant fraction of all the blocks of the Ethereum blockchain as

shown in Fig. 6.2. Theoretically, this makes it vulnerable to 51% attacks, as the two largest mining

pools (in number of mined blocks) account to almost 50% of all blocks. In practice, it should be

more profitable for mining pools to remain honest participants of the mining community.

Figure 6.2: Mining pools share of hashing powerSource: Top 25 Miners by Blocks [29]

Nevertheless, to avoid this problem, there is a plan to replace the Proof of Work consensus

algorithm to one that is based on a Proof of Stake. With that change, the likelihood of mining

a block will be determined by the amount of Ether held by a pool rather then by its processing

(hashing) power. So the pie chart at Figure 6.2 won’t be so relevant after the upgrade.

Page 74: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

6.3 Cost 61

6.2.2 iExec

The security and privacy provided by using the iExec decentralized cloud is entirely dependent

on Intel, because not only are the users dependent on the design security of Intel’s SGX and their

processors, but also during the remote attestation which proves to the SMS that the proper software

is running in the Enclave thus establishing a secure channel between the SMS and the worker’s

Enclave where a service by a remote Intel’s component, named the Intel’s Attestation Service, is

used to verify the enclave, further raising the dependency on Intel.

While there are alternatives for decentralized private computing that don’t rely on Trusted

Compute, including the multi-party computation protocol (MPC) [30], Intel’s Trusted Compute is

still a good option as most likely a DAPP’s user is already trusting Intel with the manufacturing

of their computer’s own CPU. There is however the case for accidental vulnerabilities introduced

to the technology, which have happened in the past, so the user would need to be conscious of

something of the sort happening.

The iExec worker SGX Enclaves download the encrypted client’s information (address and

payment details) to be decrypted inside the Enclave. Ideally, a decentralized form of storage such

as IPFS should be used, however it can be inconvenient for the user to use this form of storage

as the user needs to run an IPFS node to store data and wait for it to propagate through the IPFS

network. Alternatively, the user may use a centralized form of storage which, while not ideal for a

decentralized application, does provide a more user friendly experience for the user.

6.3 Cost

This section evaluates the monetary cost of using Ethereum and iExec in place of a central

server, since all transactions to Ethereum incur fees payed in ETH and computations on iExec cost

RLC.

6.3.1 Ethereum

When performing a transaction on Ethereum, the its cost is calculated based on the number and

type of calculations performed by it. The code developed in solidity is compiled to bytecode which

can be composed to opcodes, and the execution of each opcode requires a given amount of gas.

So the cost of a transaction is calculated by multiplying the gas price and the gas consumption,

for example, if the gas unit price for a transaction is 10 Gwei, and the gas consumed by the

transaction’s executed code is 1,000,000 gas, then the cost would be 0.01 Ether. The transaction

conditions include a gas limit, which is a limit for the amount of gas a transaction can spend, this is

to protect the user from overspending in potentially erroneous code where for example an infinite

loop exists.

As an example, to complete a purchase it takes 4 transactions. On a normal day, a non con-

gested Ethereum would include a transaction in a block after around a minute with a gas price of

10 Gwei. Although a fee of 1 Gwei or lower could be used, the user would need to be prepared

Page 75: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Dapp Evaluation 62

to wait a long time, sometimes even days, for the transaction to be mined. Actually, the waiting

time is highly dependent on the overall global usage of the Ethereum network, and on the fees of

transactions. As long as there are transactions advertising higher gas prices to fill the blocks, the

transaction with a lower gas price would have to wait as transactions are ordered by the highest

paying transactions first, that is the transactions offering the highest gas prices are added first to

the block, independent of the gas usage or limit of the transaction.

Figure 6.3: Ethereum’s fee vs network utilisation chart

The chart in Figure 6.3 shows the plotting of the transaction fee payed in USD, and the net-

work’s utilization in percentage. The daily average transaction fees in USD are calculated from

the etherscan website’s chart on fees [31] plus the chart on daily price of Ether in USD [32]. The

daily utilisation is calculated from the average gas used divided by the gas limit [33]. And as can

be observed from the chart, when the daily utilisation is over 90% the average fees go over 2 USD

Nevertheless, the number of days with a daily utilisation over 90% is smaller than the number of

days with a daily utilization below 90% [33].

As shown in the chart at Fig. 6.4, the average daily fee denominated in Gwei has largely

remained around the same levels throughout Ethereum’s existence, with the average since the start

of 2019 being 28.66 Gwei and the median being 22.31 Gwei.

At the time of writing this document, the total gas limit for a each block was recently raised to

12.5 million Gwei in an effort to reduce network congestion and fees.

To perform a purchase, the user needs to make 4 transactions. The first transaction, that creates

the order contract object, costs around 3,473,288 gas and with a gas price of 10 Gwei, and the

current price of 200 dollars per Ether, would cost close to 7 USD for this first transaction.

Page 76: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

6.3 Cost 63

Figure 6.4: Ethereum’s average daily fee in Gwei

Since it’s unacceptable to charge the seller, and consequently the buyer, 7 USD to create an

order, a solution to this can be devised using a proxy contract [34] for the Order contract. As the

main issue for such a high gas cost on creating the order contract object is that for every time an

order contract object is created from the Item contract object, the source code of the order contract

needs to be stored as bytecode, so there would be redundant copies of the same bytecode. This

can be avoided by using a clone factory. In this case, the Item contract would have a master copy

of the order contract code, so the orders can refer to the same program logic and new order objects

only have separate states [35]. Using this solution, the first transaction which creates the order

object would cost nearly 300k gas which would make the fee be under 0.6 USD at 10 Gwei gas

price and 200 USD per Ether.

Table 6.2 shows the cost of all transactions involved in a product purchase. For the remaining

transactions after the creation of the order the gas usage is 835,000, and adding up the creation of

the order contract instance the total gas usage is 1,135,000. At 10 Gwei gas price and the current

price of 200 USD per Ether, makes the total cost around 2.27 USD. However, by implementing

gas optimizations the price would fall considerably, especially considering the implementation of

nearing upcoming scaling solutions for the Ethereum network.

2Considering a gas price of 10 Gwei and the, as of now, Ether price of 200 USD.

Page 77: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Dapp Evaluation 64

Action Contract Function Gas Usage Price2

Initiating a Purchase Item per f ormOrder 300,000 gas $0.6

Depositing RLC RLC approveAndCall 100,000 gas $0.2

Initiating Data Validation Order runDataValidation 700,000 gas $1.4

Completing Purchase Order completePurchase 35,000 gas $0.07

Table 6.2: Transactions’ cost

6.3.2 iExec

The cost for the execution of an off-chain component when making a purchase is very depen-

dent on market demand vs. supply. As the iExec decentralized cloud service is still in its early

stages, there is very low adoption, meaning not many people bother with setting up workers to

supply spare CPU resources, which consequently means most of the workers set up currently are

owned and operated by the iExec company and the prices aren’t competitive. The worker resources

are priced in the RLC cryptocurrency, so workerpools are payed in RLC.

As of the time of writing this, the cryptocurrency’s price per coin is around 0.6 USD3, and since

currently the only workerpools available are all priced at 5 RLC per task, that would make the cost

of performing a purchase from the DAPP to be 3$. However, with future adoption of the iExec

decentralized cloud, the price of workerpools will vary depending on supply and demand, and

anyone can join a workerpool and get payed for their spare CPU power without any middleman,

including the sellers on the DAPP.

3Currently, because of the low RLC-based trade volume, this cryptocurrency is very volatile.

Page 78: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Chapter 7

Conclusions

7.1 Achieved Objectives

In this project we explored the combined use of Trusted Compute and Blockchain technologies

to create a scalable decentralized alternative to electronic commerce. We have chosen Ethereum as

the smart-contract enabled blockchain because of its superior level of decentralization compared

to the alternatives, and for its wide developer adoption. For Trusted Compute, we used the IExec

stack as a decentralized cloud computing that supports Intel SGX for its cloud workers.

We designed and implemented a decentralized application that uses Ethereum smart contracts

to create other smart contracts such as products and purchases and allow change to these objects

by only the authorized buyers and sellers. To access external data we used the IExec decentralized

computing cloud. While Ethereum dealt with the state of essential elements of the application,

demanding computations which proved to be too costly to be run on Ethereum were delegated to

the IExec.

Since computations done outside Ethereum by the IExec cloud are protected by Intel SGX, the

executed code and resulting output have their integrity secured by Intel’s technology, which while

not at the same level of security as computations executed by Ethereum smart contracts, provide

a much less costly alternative. Also by using Intel SGX, the customer’s private data is securely

transferred to an enclave where it will never leak to anyone including the host computer, so while

performing executions using this private data it will never expose the customer’s personal data to

any third party. Calls to external APIs were also made by the cloud worker’s trusted execution

environments, thus providing an oracle for which data could be gathered by the TEE and securely

sent to the blockchain via a transaction.

To conclude, the resulting decentralized application while with much more potential for scal-

ability than purely using blockchain, and being more user friendly as to not need a user to run a

full time node, there certainly are many potential improvements possible, and with the foundations

laid out a continued feature integration could produce an application to rival current centralized

e-commerce alternatives, thereby solving the problems of consolidation of power to a few large

companies as laid out from the start of this document.

65

Page 79: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Conclusions 66

7.2 Future Work

While a lot was done for this project, it still remains many features which this platform would

need implemented to be user more friendly, with the exception of a better web interface, some of

these features are present in the following sub-sections.

7.2.1 Dispute resolution

Since this project aims to layout a fully decentralized e-commerce platform, thought needs to

be put into the dispute resolution mechanism which can not be like current centralized alternatives

that rely on either the entity in charge of trading to act as escrow or have the responsibility passed

to a third party. The Appendix B explores decentralized solutions for dispute resolutions in a

decentralized online marketplace.

7.2.2 Sybil Attack

A Sybil attack is when a single individual can use a number of pseudonymous identities to

subvert a system which relies on unique individual ratings or opinions, therefore the individual

gains as much influence equal to the number of pseudonymous identities the individual has which

could be many.

This is a serious issue for this project, since sellers and products would have the possibility

of being rated or flagged and as there isn’t the use of an email or phone numbers present on this

platform, anyone could create multiple Ethereum accounts, and therefore identities, with ease.

Since the platform is aiming for security and anonymity, a solution needs to be devised to

identify unique individuals while maintaining their privacy in a decentralized platform. For this

the most promising non evasive solutions on the cryptocurrency space are Idena [36] and Proof of

Humanity by Kleros [37]. Idena’s main developer team is anonymous and there isn’t any official

document to explain the project however their website and git has information on this.

Idena is a cryptocurrency platform of its own forked from the Ethereum source code, where

mining nodes need to perform a task, around two times every month, to prove they are human and

not a bot. This task is creating capchas and participating in a timed event where the individual

behind the node has to solve capchas from other nodes in under a certain time limit. This solutions

relies on a single person having the intellectual capacity to solve the capchas under the time limit

for one account but not multiple accounts at the same time, or no account at all. With this solution

it can be assumed with a relative degree of certainty that for each node running the mining software

there is only one person, with potentially rare cases where a person with enough skill could trick

the system by being able to manage more than one node. The main downside of this solution is

requiring users to create capchas, which can be tedious to do.

The Proof of Humanity by Kleros offers a different approach where individuals would upload

a picture of their face to a system which would associate their account to their portrait, and an

Page 80: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

7.2 Future Work 67

artificial intelligence algorithm would then compare faces to find if two accounts were being man-

aged by the same face. This solution is more evasive as users would need to upload their portrait

to the system although the faces would be shuffled and the associated account known only to the

algorithm, users most likely wouldn’t feel safe uploading images of their face to a permanent data

storage. There are also problems with potential image fabrications and the questionable ability for

algorithms to detect them.

7.2.3 Accepting Cryptocurrencies

While a focal point of this project was to allow for credit card payment, thus enabling larger

user adoption, a feature which accepted cryptocurrency as payment should still be considered

since the project already dabbles in the cryptocurrency to pay for transaction fees, and it uses the

Ethereum network as an essential component for decentralization.

7.2.4 Ethereum Meta Transactions

Since it is a barrier of entry for the buyer to have to own cryptocurrency to pay for purchase

transaction fees, through the use of meta-transactions the transactions would still be signed by the

buyer but funded by the seller.

Page 81: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Appendix A

Setting up the web client

1. Install the metamask plugin for your browser;

2. Follow metamask’s instructions in creating your account on the goerli testnet;

3. Fund your account with ETH and RLC with the respective faucets, goerli-faucet.slock.it and

faucet.iex.ec/goerli;

4. Clone the interface repository and enter interface folder:

• $ git clone [email protected]:disserta-p/interface.git;

• $ cd interface;

5. Make sure you have nodejs and the node package manager installed and updated, and exe-

cute the following commands:

• $ npm i;

• $ npm start;

6. Enter into the browser the url localhost:3000.

In Fig 5.1 the image illustrates what should show on the browser after completing all steps.

The interface uses the goerli Ethereum testnet, a testing ground for the ethereum platform

so the user won’t have to spend real money to test the platform. Please make sure the selected

network on the metamask plugin is set to Goerli Test Network, otherwise you might lose real

cryptocurrency.

68

Page 82: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Appendix B

Dispute resolution

Since this project aims to layout a fully decentralized e-commerce platform, thought needs to

be put into the dispute resolution mechanism which can not be like current centralized alternatives

that rely on either the entity in charge of trading to act as escrow or have the responsibility passed

to a third party.

Solutions for decentralized dispute resolution have shown up already as projects belonging

to the cryptocurrency market, the ones I explored most are Kleros [38] and Aragon [39], these

projects rely on Nash equilibrium between jurors of a dispute to arrive at a judgement.

Nash equilibrium is a solution to a game where players have conflicting interests and where

each player has choices which affect the outcome of the other player choices, effectively laying out

a payoff matrix where all cells represent each player’s payoff given their choices, and each player

in the search for the most selfishly advantages choice, considering the other players’ choices, find

that a possible choice exists where, irregardless of there being no cooperation between the players,

there is no other better choice to make that while more advantages for the individual player would

be to the detriment of other players. On table B.1 is an example of such a payoff matrix.

In this payoff matrix, if both players are rational they would choose A gaining a positive reward

for both, as it would not be rational to choose otherwise since no other choice provides a better

payoff for neither player, and both players win the most by this choice.

Disputes are recorded on blockchain, evidence and proof of transactions are also all recorded

on the blockchain so that there’s no one entity or group in charge of storing this data and potentially

Player 2

A B

Player 1A 1,1 1,−1

B −1,1 0,0

Table B.1: Nash equilibrium

69

Page 83: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Dispute resolution 70

Single Juror

Buyer Seller

Majority JurorsSeller R 0

Buyer 0 R

Table B.2: Dispute resolution payoff matrix

having it manipulated wrongfully.

Assuming the blockchain platform used for the dispute resolution has a resilient consensus al-

gorithm which can be trusted, data recorded on said blockchain can be guarantied to be immutable

as it is backed by thousands of nodes around the world running software which verifies that, for

every block mined, each state change is correct. Therefore it can be safely assumed that the

data related to the dispute resolution stored on a blockchain platform with strong decentralization,

through the characteristics talked about, is reliably unchanged.

These decentralized solutions organize groups of jurors to solve disputes published on the

blockchain. Disputes are published by the client towards the seller, and the client needs to provide

proofs to aid in the dispute for the jurors to use in achieving a resolution for the dispute, the

resolution can be returning money to the client where the seller would pay for the expenses for the

dispute such as paying the jurors, or the jurors could side on the seller thus having the client pay

for the dispute expenses.

The juror system rely on Nash equilibrium, where random individuals become jurors, anal-

yse a dispute and vote on what they find to be the appropriate action, or more realistically these

individuals would vote on what would be the most profitable choice for them.

If a juror votes on what the majority of jurors vote on they are rewarded with a prize in the

form of an amount in cryptocurrency that would have a certain perceived value derived from the

cryptocurrency’s demand or usefulness, and so it is assumed that since every juror expects every

other juror to vote honestly they will in turn also vote in what they believe is true in order to match

others votes and be included in the majority vote, or in other words, jurors would vote in what

other jurors thought they themselves think the other jurors would vote on, and so on ...

The table B.2 is a payoff matrix for the juror system where it’s assumed there isn’t any vote

buying or any malpractices. As can be seen from the matrix if jurors all agree on the same reso-

lution for the dispute they will all receive a reward, named R in the matrix, however if one juror

votes differently from the majority that one juror will receive nothing, or 0, in compensation. This

way jurors will try to guess what the majority vote will be, therefore they should make the effort to

figure out which side, the seller or buyer, is objectively right or wrong in the dispute and the juror

should theoretically vote based on that, believing others will do the same. This is if the jurors do

not know each other and are chosen randomly from a large pool of people.

Page 84: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Dispute resolution 71

Bribed Juror

Buyer Seller

Majority JurorsBuyer R R+ ε

Seller 0 R

Table B.3: Dispute resolution payoff matrix attack

One major issue with this system lies in the P + epsilon attack, as explained in the blog post

by Vitalik Buterin [40] the attacker could convince the jurors to change the outcome of the dispute

resolution by bribing them while also not spending anything to do so. To do this the attacker

would claim to every juror that if they, the juror, voted for one outcome and the rest of the other

jurors voted for another different outcome then the bribed juror would receive a higher reward

than the promised reward if they were honest, of course since the attacker is communicating with

all jurors they would converge to the same vote only not the honest one, and consequently the

attacker wouldn’t actually have to pay anything because the conditions initially communicated by

the attacker weren’t meet.

On table B.3 the payoff matrix shows that if the bribed juror votes on the side of the seller but

the majority vote on the side of the buyer, the briber will pay the seller a value higher than the

reward to the juror.

Both projects are working on bribing resistance and the P + epsilon attack vector, where an

appeal system lets the attacked party create another dispute on top of the original dispute but with

a larger pool of jurors thus increasingly making the attack more costly and less viable. As the juror

system is unable to identity distinct individual people to act as jurors, the proposed solutions rely

on each juror having a percentage stake on a cryptocurrency. Therefore a juror vote weight would

be proportional to the amount of the cryptocurrency the juror as an individual held, so it would

stand to reason that if the jurors hold a share of this cryptocurrency, they would want to be honest

thus keeping the system trustworthy, and consequently their share in the system valuable.

Concluding, this solution for dispute resolution would work only if the currency transacted

were part of a smart contract platform where the currency could be programmed to be refunded in

case a dispute resolution deemed it so, and a more complicated system would need to be conceived

to accept government currency payments. The projects working on this solution have only come

out in 2020 and later 2019 so there’s a lot still in development and what’s currently running lacks

participation from the community to act as jurors, so it’s far from being a viable solution right now,

but may become a cornerstone of decentralized e-commerce once the technology is perfected,

since dispute resolution is a necessary component for e-commerce.

Page 85: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Appendix C

Source Code Listings

1 pragma s o l i d i t y >=0 .4 .22 < 0 . 7 . 0 ;23 import "./Item.sol" ;45 c o n t r a c t I t e m F a c t o r y {67 us ing SafeMath f o r u in t256 ;89 event Dep loyed Produc t ( address i n d e x e d _ c o n t r a c t A d d r e s s , s t r i n g s e l l e r P K , s t r i n g _images , s t r i n g _ d e s c r i p t i o n ,

s t r i n g _ p r i c e , uint256 q u a n t i t y I n S t o c k ) ;1011 address p r i v a t e iexecHub ;1213 address p r i v a t e v a l i d a t o r A p p ;1415 c o n s t r u c t o r ( address _iexecHub , address _ v a l i d a t o r A p p ) p u b l i c {16 iexecHub = _iexecHub ;17 v a l i d a t o r A p p = _ v a l i d a t o r A p p ;18 }1920 f u n c t i o n d e p l o y P r o d u c t ( s t r i n g c a l l d a t a pubkey , s t r i n g c a l l d a t a _ d e s c r i p t i o n , s t r i n g c a l l d a t a _images , s t r i n g

c a l l d a t a _ p r i c e , uint256 q u a n t i t y I n S t o c k )21 e x t e r n a l22 payable23 {24 address i t em = address ( new I t em ( msg . s ende r , iexecHub , v a l i d a t o r A p p , q u a n t i t y I n S t o c k ) ) ;25 emit Dep loyed Produc t ( i tem , pubkey , _images , _ d e s c r i p t i o n , _ p r i c e , q u a n t i t y I n S t o c k ) ;26 }27 }

Listing C.1: ItemFactoy.sol

1 pragma s o l i d i t y >=0 .4 .22 < 0 . 7 . 0 ;23 import "./Order.sol" ;45 c o n t r a c t I t em {67 us ing SafeMath f o r u in t256 ;89 address payable p u b l i c s e l l e r ;

1011 address p r i v a t e iexecHub ;1213 address p r i v a t e v a l i d a t o r A p p ;1415 uint256 p u b l i c nStock ;16

72

Page 86: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Source Code Listings 73

17 enum PurchaseS ta tu sEnum18 {19 FINISHED ,20 STARTED21 }2223 s t r u c t P u r c h a s e M e t a d a t a24 {25 PurchaseS ta tu sEnum s t a t u s ;26 uint256 n I t e ms ;27 }2829 mapping ( address => P u r c h a s e M e t a d a t a ) p u b l i c o r d e r s _ ;3031 event NewOrder ( address i n d e x e d o r d e r ) ;32 event F i n i s h e d O r d e r ( address i n d e x e d o r d e r ) ;33 event I n c r e a s e d S t o c k ( uint256 nStock ) ;3435 c o n s t r u c t o r ( address payable s e l l e r _ , address iexecHub_ , address v a l i d a t o r A p p _ , uint256 nStock_ )36 p u b l i c {37 s e l l e r = s e l l e r _ ;38 iexecHub = iexecHub_ ;39 v a l i d a t o r A p p = v a l i d a t o r A p p _ ;40 nStock = nStock_ ;41 }4243 f u n c t i o n p e r f o r m O r d e r (44 address c l i e n t D a t a s e t ,45 address workerPool_ ,46 uint256 nI tems ,47 boo l debug )48 e x t e r n a l49 {50 r e q u i r e ( ( nS tock − n I t e ms ) >= 0) ;5152 address o r d e r = address ( new Order ( iexecHub , v a l i d a t o r A p p , c l i e n t D a t a s e t , worke rPoo l_ , msg . s ende r , address (

t h i s ) , debug ) ) ;5354 o r d e r s _ [ o r d e r ] = P u r c h a s e M e t a d a t a ( Pu rchaseS ta tu sEnum . STARTED, n I t em s ) ;5556 emit NewOrder ( o r d e r ) ;57 }5859 f u n c t i o n i n c r e a s e S t o c k ( uint256 i n c r e m e n t I n S t o c k )60 p u b l i c {6162 r e q u i r e ( msg . s e n d e r == s e l l e r ) ;6364 nStock += i n c r e m e n t I n S t o c k ;6566 emit I n c r e a s e d S t o c k ( i n c r e m e n t I n S t o c k ) ;67 }6869 f u n c t i o n r e d u c e S t o c k ( )70 p u b l i c {7172 r e q u i r e ( o r d e r s _ [ msg . s e n d e r ] . s t a t u s != PurchaseS ta tu sEnum . FINISHED ) ;7374 o r d e r s _ [ msg . s e n d e r ] . s t a t u s = PurchaseS ta tu sEnum . FINISHED ;7576 nStock −= o r d e r s _ [ msg . s e n d e r ] . n I t ems ;7778 emit F i n i s h e d O r d e r ( msg . s e n d e r ) ;79 }80 }

Listing C.2: Item.sol

1 pragma s o l i d i t y ^ 0 . 5 . 1 0 ;2 pragma e x p e r i m e n t a l ABIEncoderV2 ;34 import "@iexec/interface/contracts/libs/IexecODBLibOrders.sol" ;

Page 87: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Source Code Listings 74

5 import "@iexec/interface/contracts/IexecInterface.sol" ;6 import "@iexec/doracle/contracts/IexecDoracle.sol" ;7 import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol" ;8 import "openzeppelin-solidity/contracts/math/SafeMath.sol" ;9

10 import "./Item.sol" ;111213 c o n t r a c t Order i s I e x e c D o r a c l e14 {15 us ing SafeMath f o r u in t256 ;1617 b y t e s 3 2 p u b l i c c o n s t a n t TAG = 0 x0000000000000000000000000000000000000000000000000000000000000001 ;18 uint256 p u b l i c c o n s t a n t TRUST = 0 ; // No replication

19 s t r i n g p u b l i c c o n s t a n t PARAMS = "python /app/app.py" ;2021 IERC20 p u b l i c t o k e n ;2223 I t em p u b l i c i t em ;2425 address p u b l i c buyer ;2627 boo l DEBUG;2829 enum OrderS ta tusEnum30 {31 NULL,32 APPROVED,33 AWAITING_VALIDATION ,34 VALIDATED,35 COMPLETE36 }3738 s t r u c t Orde rMe tada t a39 {40 OrderS ta tusEnum s t a t u s ;41 b y t e s 3 2 o r a c l e C a l l ;42 uint256 p o t V a l u e ;43 }4445 Orde rMe tada t a p u b l i c m_orderMetada ta ;4647 event V a l i d a t i o n S t a r t e d ( b y t e s 3 2 t a s k i d ) ;48 event F a i l l u r e ( ) ;49 event V a l i d a t e d D a t a ( s t r i n g h a s h C r e d i t , s t r i n g hashAddre s s ) ;50 event NewFeeDeposi t ( uint256 f e e ) ;51 event E n c r D a t a s e t U p l o a d e d ( s t r i n g i p f s D a t a s e t ) ;525354 m o d i f i e r s e n d e r I s O r d e r O w n e r ( )55 {56 r e q u i r e ( msg . s e n d e r == buye r ) ;57 _ ;58 }5960 c o n s t r u c t o r (61 address _iexecHubAddr ,62 address _app ,63 address _ d a t a s e t ,64 address _workerpool ,65 address _buyer ,66 address _i tem ,67 boo l debug )68 p u b l i c I e x e c D o r a c l e ( _iexecHubAddr )69 {70 _ i e x e c D o r a c l e U p d a t e S e t t i n g s (71 _app ,72 _ d a t a s e t ,73 _workerpool ,74 TAG,75 TRUST76 ) ;7778 DEBUG = debug ;79 buye r = _buyer ;

Page 88: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Source Code Listings 75

80 i t em = I tem ( _ i t em ) ;81 m_orderMetada ta = Orde rMe tada t a ( OrderS ta tusEnum .NULL, b y t e s 3 2 ( 0 ) , 0 ) ;82 t o k e n = IERC20 ( i e x e c C l e r k . t o k e n ( ) ) ;83 }8485 f u n c t i o n r e c e i v e A p p r o v a l ( address _sende r , uint256 fee , address , b y t e s c a l l d a t a )86 e x t e r n a l87 {88 r e q u i r e ( msg . s e n d e r == address ( t o k e n ) ) ;8990 _depos i tWorkFee ( _sende r , f e e ) ;91 }9293 f u n c t i o n _depos i tWorkFee ( address _buyer , uint256 worke rPoo lFee )94 i n t e r n a l95 {96 r e q u i r e ( t o k e n . t r a n s f e r F r o m ( _buyer , address ( t h i s ) , worke rPoo lFee ) ) ;9798 m_orderMetada ta . p o t V a l u e = m_orderMetada ta . p o t V a l u e . add ( worke rPoo lFee ) ;99

100 m_orderMetada ta . s t a t u s = OrderS ta tusEnum .APPROVED;101102 emit NewFeeDeposi t ( worke rPoo lFee ) ;103 }104105 f u n c t i o n r u n D a t a V a l i d a t i o n (106 IexecODBLibOrders . AppOrder c a l l d a t a _apporde r ,107 IexecODBLibOrders . D a t a s e t O r d e r c a l l d a t a _ d a t a s e t o r d e r ,108 IexecODBLibOrders . Workerpoo lOrder c a l l d a t a _ w o r k e r p o o l o r d e r )109 e x t e r n a l s e n d e r I s O r d e r O w n e r ( )110 {111112 Orde rMe tada t a s t o r a g e d e t a i l s = m_orderMetada ta ;113114 r e q u i r e ( m_orde rMetada ta . p o t V a l u e > 0 , ’pot value equals zero’ ) ;115116 r e q u i r e ( d e t a i l s . s t a t u s == OrderS ta tusEnum . APPROVED, ’Order status not null’ ) ;117 r e q u i r e ( d e t a i l s . o r a c l e C a l l == b y t e s 3 2 ( 0 ) , ’Oracle call in progress’ ) ;118119 r e q u i r e ( m_author izedApp == address ( 0 ) | | _ c h e c k I d e n t i t y ( m_author izedApp , _ a p p o r d e r . app ,

i e x e c C l e r k .GROUPMEMBER_PURPOSE( ) ) , "unauthorized-app" ) ;120 r e q u i r e ( m _ a u t h o r i z e d D a t a s e t == address ( 0 ) | | _ c h e c k I d e n t i t y ( m _ a u t h o r i z e d D a t a s e t , _ d a t a s e t o r d e r . d a t a s e t ,

i e x e c C l e r k .GROUPMEMBER_PURPOSE( ) ) , "unauthorized-dataset" ) ;121 r e q u i r e ( m_au tho r i zedWorke rpoo l == address ( 0 ) | | _ c h e c k I d e n t i t y ( m_au thor i zedWorkerpoo l , _ w o r k e r p o o l o r d e r .

workerpoo l , i e x e c C l e r k .GROUPMEMBER_PURPOSE( ) ) , "unauthorized-workerpool" ) ;122123 IexecODBLibOrders . R e q u e s t O r d e r memory r e q u e s t o r d e r ;124125 r e q u e s t o r d e r . app = _ a p p o r d e r . app ; //address

126 r e q u e s t o r d e r . appmaxpr i ce = _ a p p o r d e r . a p p p r i c e ; //uint256

127 r e q u e s t o r d e r . d a t a s e t = _ d a t a s e t o r d e r . d a t a s e t ; //address

128 r e q u e s t o r d e r . d a t a s e t m a x p r i c e = _ d a t a s e t o r d e r . d a t a s e t p r i c e ; //uint256

129 r e q u e s t o r d e r . w o r k e r p o o l = _ w o r k e r p o o l o r d e r . w o r k e r p o o l ; //address

130 r e q u e s t o r d e r . w o r k e r p o o l m a x p r i c e = _ w o r k e r p o o l o r d e r . w o r k e r p o o l p r i c e ; //uint256

131 r e q u e s t o r d e r . r e q u e s t e r = address ( t h i s ) ; //address

132 r e q u e s t o r d e r . volume = 1 ; //uint256

133 r e q u e s t o r d e r . t a g = TAG; //bytes32

134 r e q u e s t o r d e r . c a t e g o r y = _ w o r k e r p o o l o r d e r . c a t e g o r y ; //uint256

135 r e q u e s t o r d e r . t r u s t = TRUST ; //uint256

136 r e q u e s t o r d e r . b e n e f i c i a r y = address ( 0 ) ; //address

137 r e q u e s t o r d e r . c a l l b a c k = address ( t h i s ) ; //address

138 r e q u e s t o r d e r . params = PARAMS; //string

139 r e q u e s t o r d e r . s a l t = keccak256 ( a b i . encodePacked ( now , address ( t h i s ) ) ) ; //bytes32

140141 r e q u i r e ( i e x e c C l e r k . s i g n R e q u e s t O r d e r ( r e q u e s t o r d e r ) , ’error signing request’ ) ;142143 uint256 d e a l p r i c e = _ a p p o r d e r . a p p p r i c e . add ( _ d a t a s e t o r d e r . d a t a s e t p r i c e ) . add ( _ w o r k e r p o o l o r d e r . w o r k e r p o o l p r i c e ) ;144 i E x e c D e p o s i t ( d e a l p r i c e ) ;145 d e t a i l s . p o t V a l u e = d e t a i l s . p o t V a l u e . sub ( d e a l p r i c e ) ;146147 b y t e s 3 2 d e a l i d = i e x e c C l e r k . ma tchOrde r s ( _apporde r , _ d a t a s e t o r d e r , _ w o r k e r p o o l o r d e r , r e q u e s t o r d e r ) ;148149 b y t e s 3 2 t a s k i d = keccak256 ( a b i . encodePacked ( d e a l i d , uint256 ( 0 ) ) ) ;150151 d e t a i l s . o r a c l e C a l l = t a s k i d ;

Page 89: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Source Code Listings 76

152 d e t a i l s . s t a t u s = OrderS ta tusEnum . AWAITING_VALIDATION ;153154 i f (DEBUG == t rue ) {155 r e c e i v e R e s u l t ( ) ;156 }157158 emit V a l i d a t i o n S t a r t e d ( t a s k i d ) ;159 }160161 f u n c t i o n i E x e c D e p o s i t ( uint256 v a l u e )162 i n t e r n a l163 {164 t o k e n . app rove ( address ( i e x e c C l e r k ) , v a l u e ) ;165 i e x e c C l e r k . d e p o s i t ( v a l u e ) ;166 }167168 f u n c t i o n r e c e i v e R e s u l t ( b y t e s 3 2 _ d o r a c l e C a l l I d , b y t e s memory )169 p u b l i c170 {171 Orde rMe tada t a s t o r a g e d e t a i l s = m_orderMetada ta ;172173 r e q u i r e ( d e t a i l s . s t a t u s == OrderS ta tusEnum . AWAITING_VALIDATION) ;174175 boo l s u c c e s s ;176 b y t e s memory r e s u l t s ;177178 i f (DEBUG == t rue )179 {180 s u c c e s s = t rue ;181 r e s u l t s = ’\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\

x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\

x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00‘\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00

\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa0\x00\x00\x00

\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00

\x00\x00\x00\x03foo\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\

x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\

x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03bar\x00\x00\x00\x00\x00\x00\x00\x00\

x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00’ ;182 } e l s e {183184 ( s u c c e s s , r e s u l t s ) = _ i e x e c D o r a c l e G e t R e s u l t s ( _ d o r a c l e C a l l I d ) ;185 }186187188 i f ( s u c c e s s )189 {190 boo l r e s u l t ;191 s t r i n g memory h a s h C r e d i t ;192 s t r i n g memory hashAddre s s ;193 ( r e s u l t , h a s h C r e d i t , ha shAddre s s ) = a b i . decode ( r e s u l t s , ( bool , s t r i n g , s t r i n g ) ) ;194195 i f ( r e s u l t ) {196197 d e t a i l s . s t a t u s = OrderS ta tusEnum . VALIDATED;198199 emit V a l i d a t e d D a t a ( h a s h C r e d i t , ha shAddre s s ) ;200 }201 }202 e l s e i f ( keccak256 ( r e s u l t s ) != keccak256 ("result-not-available" ) )203 {204 d e t a i l s . s t a t u s = OrderS ta tusEnum .APPROVED;205206 d e t a i l s . o r a c l e C a l l = b y t e s 3 2 ( 0 ) ;207208 emit F a i l l u r e ( ) ;209 }210 }211212 f u n c t i o n c o m p l e t e P u r c h a s e ( s t r i n g c a l l d a t a i p f s D a t a s e t )213 e x t e r n a l s e n d e r I s O r d e r O w n e r ( )214 {215 Orde rMe tada t a s t o r a g e d e t a i l s = m_orderMetada ta ;216217 r e q u i r e ( d e t a i l s . s t a t u s == OrderS ta tusEnum . VALIDATED) ;218

Page 90: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Source Code Listings 77

219 d e t a i l s . s t a t u s = OrderS ta tusEnum .COMPLETE;220221 i t em . r e d u c e S t o c k ( ) ;222223 emit E n c r D a t a s e t U p l o a d e d ( i p f s D a t a s e t ) ;224 }225 }

Listing C.3: Order.sol

1 from v e r i f y A d d r e s s import v e r i f y D e l i v e r y A d d r e s s2 from c r e d i t c a r d c h e c k import c h e c k C r e d i t C a r d34 from u t i l s import ∗5 import j s o n67 i f __name__ == ’__main__’ :8 v a l i d i t y = j s o n . l o a d s (’{"address": false, "credit": false}’ ) ;9

10 a d d r e s s R e t = v e r i f y D e l i v e r y A d d r e s s ( v a l i d i t y )1112 c r e d i t R e t = c h e c k C r e d i t C a r d ( v a l i d i t y )1314 w r i t e R e s u l t ( v a l i d i t y , a d d r e s s R e t , c r e d i t R e t )

Listing C.4: app.py

1 import j s o n2 import u r l l i b . r e q u e s t3 from u t i l s import ∗45 a d d r e s s D a t a s e t = ’iexec_in/address.json’

67 def _ r e t r i e v e A d d r e s s D a t a s e t ( p a t h s , e x c e p t i o n s ) :8 t r y :9 a d d r e s s f i l e = open ( a d d r e s s D a t a s e t , ’r’ )

10 a d d r e s s D a t a = j s o n . l o a d ( a d d r e s s f i l e )11 re turn a d d r e s s D a t a12 e xc ep t I O E r r o r :13 wi th open ( p a t h s ["errorFilePath" ] , ’a’ ) a s e r r o r F i l e :14 e r r o r F i l e . w r i t e ("{}{}{}" . format ( e x c e p t i o n s ["Exception_Location_Address" ] , e x c e p t i o n s ["JSON_Open_Error" ] ,15 e x c e p t i o n s ["Dataset_Error" ] ) )16 p r i n t ("Failed to open exception json file." )17 re turn None1819 def _sendReques tAPI ( i n p u t s , a p i ) :20 i n p u t s ["APIKey" ] = a p i ["APIKey" ]21 f r a g m e n t s = ""

22 c o n c a t _ c h a r = "?"

2324 f o r key in i n p u t s . keys ( ) :25 v a l u e = i n p u t s [ key ] . r e p l a c e (" " , "%20" ) ;26 i f v a l u e i s not None :27 f r a g m e n t s += ’{}{}={}’ . format ( c o n c a t _ c h a r , key , v a l u e )28 c o n c a t _ c h a r = "&"

2930 u r l = "https://{}/api/verify{}" . format ( a p i [’host’ ] , f r a g m e n t s )3132 h e a d e r s = {}33 d a t a = u r l l i b . r e q u e s t . u r l o p e n ( u r l l i b . r e q u e s t . Reques t ( u r l , h e a d e r s = h e a d e r s ) ) . r e a d ( )34 r e s u l t s = j s o n . l o a d s ( d a t a )3536 r e s u l t s ["status" ] = True i f r e s u l t s ["status" ] == "VALID" e l s e F a l s e3738 re turn r e s u l t s394041 def v e r i f y D e l i v e r y A d d r e s s ( v a l i d i t y ) :42 e x c e p t i o n s = loa dE xce p t i onM sgs ( )

Page 91: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Source Code Listings 78

4344 r e s o u r c e s = l o a d R e s o u r c e s ( e x c e p t i o n s )4546 a p i = r e s o u r c e s ["api" ]47 p a t h s = r e s o u r c e s ["paths" ]4849 i n p u t s = _ r e t r i e v e A d d r e s s D a t a s e t ( p a t h s , e x c e p t i o n s )5051 e x i t C o d e = 05253 t r y :54 r e s u l t s = _sendReques tAPI ( i n p u t s , a p i )5556 v a l i d i t y ["address" ] = r e s u l t s ["status" ] ;5758 e xc ep t u r l l i b . r e q u e s t . HTTPError a s h t t p e r r o r :5960 e x i t C o d e = 161 wi th open ( p a t h s ["errorFilePath" ] , "a" ) a s e r r o r F i l e :62 e r r o r F i l e . w r i t e ("{}{}" . format ("[VERIFY ADDRESS] [ERROR]: " , s t r ( h t t p e r r o r ) ) )6364 g e n e r a t e D e t e r m i n i s m ( h t t p e r r o r , ex i tCode , p a t h s ["determinismFilePath" ] )65 p r i n t ("Verify address HTTP error." )6667 re turn {"exitcode" : ex i tCode , "value" : i n p u t s }

Listing C.5: verifyAddress.py

1 from u t i l s import ∗23 c r e d i t c a r d P a t h = "iexec_in/creditcard.json"

45 def _ r e t r i e v e c r e d i t c a r d D a t a s e t ( p a t h s , e x c e p t i o n s ) :6 t r y :7 c r e d i t c a r d = j s o n . l o a d ( open ( c r e d i t c a r d P a t h , ’r’ ) )8 re turn c r e d i t c a r d9 e xc ep t I O E r r o r :

10 wi th open ( p a t h s ["errorFilePath" ] , ’a’ ) a s e r r o r F i l e :11 e r r o r F i l e . w r i t e ("{}{}{}" . format ( e x c e p t i o n s ["Exception_Location_Credit" ] , e x c e p t i o n s ["JSON_Open_Error" ] ,12 e x c e p t i o n s ["Dataset_Error" ] ) )13 p r i n t ("Failed to open exception json file." )14 re turn None1516 def _checkLuhn ( cardNum ) :17 nSum = 018 i s S e c o n d = F a l s e19 f o r num in cardNum [ : : − 1 ] :20 inum = i n t ( num )21 i f ( i s S e c o n d == True ) :22 inum = inum ∗ 22324 nSum += i n t ( inum / 10)25 nSum += inum % 102627 i s S e c o n d = not i s S e c o n d2829 re turn ( nSum % 10 == 0)3031 def c h e c k C r e d i t C a r d ( v a l i d i t y ) :32 e x i t C o d e = 03334 e x c e p t i o n s = loa dE xce p t i onM sgs ( )3536 r e s o u r c e s = l o a d R e s o u r c e s ( e x c e p t i o n s )3738 p a t h s = r e s o u r c e s ["paths" ]3940 c r e d i t c a r d = _ r e t r i e v e c r e d i t c a r d D a t a s e t ( p a t h s , e x c e p t i o n s )4142 i f ( c r e d i t c a r d != None ) :43 r e s u l t s = _checkLuhn ( c r e d i t c a r d ["number" ] )44 v a l i d i t y ["credit" ] = r e s u l t s ;

Page 92: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Source Code Listings 79

4546 e l s e :4748 e x i t C o d e = 149 wi th open ( p a t h s ["errorFilePath" ] , "a" ) a s e r r o r F i l e :50 e r r o r F i l e . w r i t e ("{}{}" . format ("[VERIFY ADDRESS] [ERROR]: " , s t r ( h t t p e r r o r ) ) )5152 g e n e r a t e D e t e r m i n i s m ( h t t p e r r o r , ex i tCode , p a t h s ["determinismFilePath" ] )53 p r i n t ("Creditcard check HTTP error." )5455 re turn {"exitcode" : ex i tCode , "value" : c r e d i t c a r d }

Listing C.6: creditcardcheck.py

1 import j s o n2 import e t h _ a b i3 import sha34 import s y s56 except ionJSON = "/app/assets/exceptions.json"

7 pathsJSON = "/app/assets/resources.json"

8 apiJSON = "/app/assets/addressApi.json"

91011 def l o a d R e s o u r c e s ( e x c e p t i o n s ) :12 t r y :13 p a t h s = j s o n . l o a d ( open ( pathsJSON , ’r’ ) )14 a p i = j s o n . l o a d ( open ( apiJSON , ’r’ ) )15 e xc ep t I O E r r o r :16 p r i n t ("{}{}" . format ( e x c e p t i o n s ["Exception_Location_Address" ] , e x c e p t i o n s ["JSON_Open_Error" ] ) )17 p r i n t ("Failed to open exception json file." )1819 re turn {"paths" : p a t h s , "api" : a p i }202122 def l o adE xce p t i onM sgs ( ) :23 t r y :24 e x c e p t i o n s = j s o n . l o a d ( open ( except ionJSON ) )25 re turn e x c e p t i o n s26 e xc ep t I O E r r o r :27 p r i n t ("Failed to open exception json file." )28 re turn None293031 def e n c o d e C a l l b a c k ( v a l i t i y X , c r e d i t D a t a , a d d r e s s D a t a , p a t h s ) :32 k = sha3 . keccak_256 ( )33 k . u p d a t e ( c r e d i t D a t a . encode ("utf8" ) )34 c r e d i t D a t a = k . h e x d i g e s t ( )35 k . u p d a t e ( a d d r e s s D a t a . encode ("utf8" ) )36 a d d r e s s D a t a = k . h e x d i g e s t ( )3738 c a l l b a c k = e t h _ a b i . e n c o d e _ a b i ( [ ’bool’ , ’string’ , ’string’ ] , [ v a l i t i y X , c r e d i t D a t a , a d d r e s s D a t a ] ) . hex ( )3940 wi th open ( p a t h s ["callbackFilePath" ] , ’w+’ ) a s c a l l b a c k F i l e :41 c a l l b a c k F i l e . s eek ( 0 )42 c a l l b a c k F i l e . w r i t e ("0x{}" . format ( c a l l b a c k ) )4344 re turn c a l l b a c k454647 def g e n e r a t e D e t e r m i n i s m ( raw , e x i t c o d e , p a t h s ) :48 d t = b y t e s . f romhex ( raw ) i f e x i t c o d e == 0 e l s e s t r ( raw ) . encode ( )4950 d e t e r m i n i s m = sha3 . keccak_256 ( )51 d e t e r m i n i s m . u p d a t e ( d t )5253 wi th open ( p a t h s ["determinismFilePath" ] , ’w+’ ) a s d e t e r m i n i s m F i l e :54 d e t e r m i n i s m F i l e . w r i t e (’0x{}’ . format ( d e t e r m i n i s m . h e x d i g e s t ( ) ) )555657 def w r i t e R e s u l t ( r e s u l t , a d d r e s s , c r e d i t ) :58 r e s o u r c e s = l o a d R e s o u r c e s ( l o adE xce p t i onM sgs ( ) )

Page 93: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Source Code Listings 80

5960 r e s u l t = r e s u l t ["address" ] and r e s u l t ["credit" ]6162 c a l l b a c k = e n c o d e C a l l b a c k ( r e s u l t ,63 a d d r e s s ["value" ] [ "StreetAddress" ] ,64 c r e d i t ["value" ] [ "number" ] ,65 r e s o u r c e s ["paths" ] )6667 g e n e r a t e D e t e r m i n i s m ( c a l l b a c k , 0 , r e s o u r c e s ["paths" ] )

Listing C.7: utils.py

1 {2 "root" : "/app" ,3 "inFolder" : "iexec_in/" ,4 "outFolder" : "scone/" ,5 "addressPath" : "/iexec_in/address.json" ,6 "credircardPath" : "/iexec_in/credircardPath" ,7 "determinismFilePath" : "/iexec_out/determinism.iexec" ,8 "callbackFilePath" : "/iexec_out/callback.iexec" ,9 "errorFilePath" : "/iexec_out/error.iexec"

10 }

Listing C.8: resources.json

1 {2 "JSON_Open_Error" : "Unable to open JSON files!" ,3 "Exception_Location_Address" : "[VERIFY ADDRESS] [ERROR] " ,4 "Exception_Location_Credit" : "[VERIFY CREDIT] [ERROR] "

5 }

Listing C.9: exceptions.json

1 {2 "host" : "api.address-validator.net" ,3 "APIKey" : "av-19fd302e6d0255bdad5f4b6abeab502b"

4 }

Listing C.10: addressApi.json

1 FROM i e x e c h u b / s c o n e c u r a t e d i m a g e s−i e x e c : c l i −a l p i n e AS scone23 FROM i e x e c h u b / s c o n e c u r a t e d i m a g e s−i e x e c : python −3.7.3− a l p i n e −3.1045 COPY −−from= scone / o p t / scone / scone−c l i / o p t / s cone / scone−c l i6 COPY −−from= scone / u s r / l o c a l / bin / s cone / u s r / l o c a l / bin / s cone7 COPY −−from= scone / o p t / scone / bin / o p t / s cone / bin8 COPY / s i g n e r . py / s i g n e r / s i g n e r . py9

10 ################################

1112 ### install apk packages

13 RUN apk u p d a t e \14 && apk add −−no−cache bash b u i l d−base gcc l i b g c c \15 && apk add −−upda te−cache −−no−cache l i b g c c \16 && apk −−no−cache −−upda te−cache add gcc g f o r t r a n py thon python−dev py−p i p b u i l d−base wget f r e e t y p e −dev l i b p n g−dev

\17 && apk add −−no−cache −−v i r t u a l . b u i l d−deps gcc musl−dev181920 ### install python3 dependencies

21 RUN SCONE_MODE=sim p ip3 i n s t a l l a t t r d i c t python−gnupg web3 e th−a b i pysha322

Page 94: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Source Code Listings 81

23 ### copy the code inside the image

24 COPY app / / app25 COPY app / a s s e t s / app / a s s e t s /26 #COPY app/datasetProvisional /app/datasetProvisional/

2728 ### Testing locally

29 ##COPY iexec_out/ /iexec_out

3031 ### protect file system with scone

32 COPY p r o t e c t −f s . sh / p r o t e c t −f s . sh33 RUN bash / p r o t e c t −f s . sh / app34 RUN rm / p r o t e c t −f s . sh / k e y t a g353637 ### The entrypoint should match the params attribute

38 ### written on the blockchain (the --params option of

39 ### "iexec app run" command).

40 ENTRYPOINT ["/bin/sh" , "-c" ,"unzip -o /iexec_in/$IEXEC_DATASET_FILENAME -d /iexec_in && python /app/app.py" ]

Listing C.11: Dockerfile

Page 95: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

Bibliography

[1] iExec Blockchain Tech SAS, “rlc-faucet-contract,” 2017, [Online]. Available: https://github.

com/iExecBlockchainComputing/rlc-faucet-contract/tree/mainnet. Accessed: 25/7/2020.

[2] J. Clement, “Digital retailer from which cross-border digital buyers world-

wide made their most recent cross-border digital purchase as of Septem-

ber 2019,” [Online]. Available: https://www.statista.com/statistics/878623/

digital-retailers-digital-buyers-cross-border-digital-purchases/. Accessed: 25/7/2020.

[3] S. Nakamoto, “Bitcoin: A Peer-to-Peer Electronic Cash System,” Tech. Rep., 2008.

[4] A. Back, “Hashcash-A Denial of Service Counter-Measure.” Tech. Rep., 2002.

[5] S. Nakamoto, “fix openssl linkage problems,” [Online]. Available: https://github.com/

bitcoin/bitcoin/commit/a30b56eb. Accessed: 25/7/2020.

[6] S. King and S. Nadal, “PPCoin: Peer-to-Peer Crypto-Currency with Proof-of-Stake,” Tech.

Rep., 2012.

[7] D. Larimer, “DPOS BFT— Pipelined Byzantine Fault Tolerance,” Tech. Rep., 2018.

[8] W. Gavin, “Ethereum: A secure decentralised generalised transaction ledger byzantium ver-

sion,” Tech. Rep., 2019.

[9] S. Tai, J. Eberhardt, and M. Klems, “Not ACID, not BASE, but SALT A Transaction

Processing Perspective on Blockchains,” Tech. Rep., 2017, [Online]. Available: http://www.

ise.tu-berlin.de/fileadmin/fg308/publications/2017/2017-tai-eberhardt-klems-SALT.pdf.

Accessed: 25/7/2020.

[10] E. Yarmosh, “Hyperledger Avalon Proposal,” Tech. Rep., 2019.

[11] G. Bill, A. Freund, J. Bertani , Thomas Cabelguen, B. Towne, D. Kohorn, G. Polzer,

P. Karamsetty, M. Bowman, M. Steiner, B. Vavala, T. Willis, J. Katto, P. J. Siemion,

C. Nevile, A. Simonet-Boulogne, and H. Croubois, “Enterprise Ethereum Alliance Off-Chain

Trusted Compute Specification v1.1,” Tech. Rep., 2019.

[12] Ethereum Enterprice Alliance, “EEA Trusted Token,” 2019, [Online]. Available: https://

github.com/EntEthAlliance/EEA-Trusted-Reward-Token. Accessed: 25/7/2020.

82

Page 96: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

BIBLIOGRAPHY 83

[13] Token Taxonomy Initiative, “Token Taxonomy Framework,” 2019, [Online]. Avail-

able: https://github.com/token-taxonomy-initiative/TokenTaxonomyFramework. Accessed:

25/7/2020.

[14] J. Heiss, J. Eberhardt, and S. Tai, “From Oracles to Trustworthy Data On-Chaining Systems,”

Tech. Rep., 2019.

[15] H. Ritzdorf, K. Wüst, A. Gervais, G. Felley, and S. Capkun, “TLS-N: Non-repudiation over

TLS Enabling Ubiquitous Content Signing for Disintermediation,” 2017.

[16] F. Zhang, E. Cecchetii, K. Croman, A. Juels, and E. Shi, “Town Crier: An Authenticated

Data Feed for Smart Contracts,” Tech. Rep., 2016.

[17] R. Berryhill and A. Veneris, “Astraea: A Decentralized Blockchain Oracle,” Tech. Rep.,

2019.

[18] S. Ellis, A. Juels, and S. Nazarov, “ChainLink A Decentralized Oracle Network,” Tech. Rep.,

2017.

[19] A. H. from Coindesk, “Loveable Digital Kittens Are Clogging Ethereum’s

Blockchain,” 2017, [Online]. Available: https://www.coindesk.com/

loveable-digital-kittens-clogging-ethereums-blockchain. Accessed: 25/7/2020.

[20] iExec Blockchain Tech SAS. (2016) iExec decentralized cloud computing. [Online]. Avail-

able: https://iex.ec/. Accessed: 25/7/2020.

[21] W. Bendella, “iExec Onboards New GPU Computing Provider Genesis Cloud,

Used by EDF,” Tech. Rep., 2019, [Online]. Available: https://medium.com/iex-ec/

iexec-onboards-new-gpu-computing-provider-genesis-cloud-used-by-edf-73a8d3211c4.

Accessed: 25/7/2020.

[22] H. Croubois, “PoCo Series 1 - About Trust and Agents Incentives,” 2017, [Online]. Avail-

able: https://medium.com/iex-ec/about-trust-and-agents-incentives-4651c138974c. Ac-

cessed: 25/7/2020.

[23] ——, “PoCo Series #4 — Enclaves and Trusted Execu-

tions,” 2018, [Online]. Available: https://medium.com/iex-ec/

poco-series-4-sgx-enclaves-and-trusted-executions-6f2ebed8d4fa#8e28. Accessed:

25/7/2020.

[24] S. Haig, “Intel SGX Vulnerability Discovered, Cryptocurrency Keys

Threatened,” 2020, [Online]. Available: https://cointelegraph.com/news/

intel-sgx-vulnerability-discovered-cryptocurrency-keys-threatened. Accessed: 25/7/2020.

[25] iExec Blockchain Tech SAS, “Poco,” 2020, [Online]. Available: https://github.com/

iExecBlockchainComputing/PoCo/tree/v3.mainnet. Accessed: 25/7/2020.

Page 97: New Decentralized Application for E-Commerce Using Blockchain … · 2020. 8. 12. · E-Commerce Using Blockchain and Trusted Compute João Carlos Oliveira Lago Masters in Informatics

BIBLIOGRAPHY 84

[26] etherscan.io. Ethereum average block time chart. [Online]. Available: https://etherscan.io/

chart/blocktime. Accessed: 25/7/2020.

[27] S. UG. Performance of scone-based programs. [Online]. Available: https://sconedocs.github.

io/performance/. Accessed: 25/7/2020.

[28] iExec Blockchain Tech SAS. Task details. [Online]. Available: https://explorer.iex.ec/goerli/

task/0xda1c25815552d54c65b15ce410f2217982ed0dc44ad518b68cc1c392b23ddd9d.

Accessed: 25/7/2020.

[29] etherscan.io. Top 25 miners by blocks. [Online]. Available: https://etherscan.io/stat/miner?

range=7&blocktype=blocks. Accessed: 25/7/2020.

[30] D. Evans, V. Kolesnikov, and M. Rosulek, “A Pragmatic Introduction to Secure Multi-Party

Computation,” Tech. Rep., 2018, [Online]. Available: https://www.cs.virginia.edu/~evans/

pragmaticmpc/pragmaticmpc.pdf. Accessed: 25/7/2020.

[31] etherscan.io. Ethereum network transaction fee chart. [Online]. Available: https://etherscan.

io/chart/transactionfee. Accessed: 25/7/2020.

[32] ——. Ether daily price (usd) chart. [Online]. Available: https://etherscan.io/chart/etherprice.

Accessed: 25/7/2020.

[33] ——. Ethereum network utilization chart. [Online]. Available: https://etherscan.io/chart/

networkutilization. Accessed: 25/7/2020.

[34] P. Murray, N. Welch, and J. Messerman, “Eip 1167,” 2019, [Online]. Available: https://

github.com/ethereum/EIPs/blob/master/EIPS/eip-1167.md. Accessed: 25/7/2020.

[35] P. Murray, N. Welch, and L. Saether. clone-factory. [Online]. Available: https://github.com/

optionality/clone-factory. Accessed: 25/7/2020.

[36] Anonymous authors. Idena. [Online]. Available: https://github.com/idena-network. Ac-

cessed: 25/7/2020.

[37] C. Lesaege. Kleros: Proof of humanity. [Online]. Available: https://docs.google.com/

document/d/1z01MS0-h75ESVmWymU2Gv3Z43p35oZAFtQLStOeu7Ek/edit#heading=h.

w7l0ot1fwng. Accessed: 25/7/2020.

[38] C. Lesaege, F. Ast, and W. George, “Kleros,” Tech. Rep., 2019, [Online]. Available: https:

//kleros.io/whitepaper_en.pdf. Accessed: 25/7/2020.

[39] Aragon, “Aragon court,” 2020, [Online]. Available: https://help.aragon.org/article/

41-aragon-court. Accessed: 25/7/2020.

[40] V. Buterin, “The P + epsilon Attack,” 2015, [Online]. Available: https://blog.ethereum.org/

2015/01/28/p-epsilon-attack. Accessed: 25/7/2020.