<<

CALIFORNIA STATE UNIVERSITY, NORTHRIDGE

BLOCKCHAIN TECHNOLOGY: DECENTRALIZED CROWDFUNDING APPLICATION IMPLEMENTATION ON THE PLATFORM

A thesis submitted in partial fulfillment of the requirements for the degree of Master of Science in Computer Science

By

Francis Lagueu Fogang

December 2018

The thesis of Francis Lagueu Fogang is approved by:

______Kyle Dewey Date

______John Noga Date

______Jeff Wiegley, Ph.D. (Chair) Date

California State University, Northridge

ii

Table of Contents

Signature Page ii List of Figures vi Abstract vii Chapter 1: Introduction 1 1.1 Crowdfunding Application 2 Chapter 2: Background and Related Work 5 2.1 Technology 5 2.1.1 Background and History 5 2.2 Related Work 6 2.3 Blockchain Architecture 7 2.3.1 8 2.3.2 Distributed Ledgers 9 2.3.3 Consensus 10 2.3.4 Smart Contracts 10 2.3.5 Cryptography 11 2.3.6 Cryptocurrency 12 2.3.7 Accounts 13 2.3.8 Blocks 14 2.3.9 Transactions 15 2.3.10 Tokens 16 2.4 Decentralized Applications (Dapps) 17 2.5 Type of 17 2.5.1 Bitcoin 18 2.5.2 Ethereum 19 2.5.3 Hyper Ledger 20 2.5.4 Distributed Acyclic Graphs 21 2.6 Blockchains Stack 22 2.6.1 Computational Platform 23 2.6.2 Storage Platform 24 2.6.3 Messaging Platform 25

iii

2.6.4 File Sharing and Storage Platform 25 2.7 Security and Scalability 26 2.7.1 Double Spending Problem 26 2.7.2 Byzantine Fault Tolerance 27 2.7.3 Sybil Attack 28 2.7.4 Blockchain Scalability 29 Chapter 3: Smart Contracts and Blockchain Consensus 30 3.1 Smart Contracts 30 3.1.1 Definition and Origin 30 3.1.2 Structure of a Smart Contract 31 3.1.3 Design And Implementation 32 3.1.4 Interactions 32 3.1.5 Vulnerabilities 33 3.2 Consensus Protocol 35 3.2.1 Proof of Work 35 3.2.2 Proof of Stake 36 3.2.3 Proof of Authority 37 3.2.4 Others 38 Chapter 4: Decentralized Application and Decentralized Autonomous Organizations 40 4.1 Decentralized Applications (DApps) 40 4.1.1 Definition 40 4.1.2 Architecture 41 4.1.3 Advantages and Disadvantages 42 4.2 Decentralized Autonomous Organizations (DAO) 44 4.2.1 Definition 44 4.2.2 Architecture 46 4.2.3 Advantages and Disadvantages 47 Chapter 5: Crowdfunding 48 5.1 Traditional Model of Crowdfunding 48 5.2 Others Means of Crowdfunding 52 5.3 Merits of Crowdfunding 53 5.4 Disadvantages of Crowdfunding 54

iv

Chapter 6: Design And Implementation 56 6.1 Model 56 6.2 Structure And Functionalities 56 6.3 Implementation guidelines 57 6.4 Technical Tools 58 6.5 Client Application 75 Chapter 7: Conclusion 90 References 91

v

List of Figures

Figure 2.1 Blockchain Structure 7 Figure 2.2 Accounts types on the Ethereum Blockchain 14 Figure 2.3 Blockchain Stack 23 Figure 3.1 Smart Contract Structure 31 Figure 4.1 Decentralized Application Structure 42 Figure 4.2 Web Application Vs Decentralized Application 43 Figure 6.1 Remix IDE Environment 61 Figure 6.2 Token Smart Contract 64 Figure 6.3 TokenSale Smart Contract 66 Figure 6.4 CrowdFunding Smart Contract 70 Figure 6.5 Campaign Smart Contract 71

vi

Abstract

BLOCKCHAIN TECHNOLOGY: DECENTRALIZED CROWDFUNDING APPLICATION IMPLEMENTATION OF THE ETHEREUM PLATFORM

By

Francis Lagueu Fogang

Master of Science in Computer Science

Blockchain is disrupting the way traditional are run in the age of the . This thesis explores the potential of the Blockchain technology and the power of Smarts Contract in building

Decentralized applications (DApps), Decentralized autonomous organization (DAO), and the creation of currency (Cryptocurrency) that enable the exchange of assets and wealth. The focus will be to build a Decentralized community crowdfunding application on the Ethereum blockchain platform. The Blockchain technology would be used to implement the decentralized architecture of the application by building Smart Contracts to handle the transaction and management of the application on the Blockchain network.

vii

Chapter 1. INTRODUCTION

The growing trend in economy nowadays is the adoption of a shared economy by new and established businesses by means of decentralization into a peer to peer model of the service they provide [19]. Blockchain technology has gained popularity in recent years since Satoshi Nakamoto published the White paper of Bitcoin in 2008 [1]. Bitcoin is the cryptocurrency in the forefront of this technological revolution. Satoshi was able to solve the critical problem of Double Spending emerged in the electronic cash system which has been around since the 90s. The mass adoption of

Bitcoin and Blockchain technology has given rise to many cryptocurrencies called Altcoins and the rise of other blockchain platforms that go beyond cryptocurrency and introduce new concepts and technology tools such as Smart Contracts, Decentralized Applications (DApps), Decentralized

Autonomous Organizations (DAO), Decentralized File Storage systems (IPFS), and Decentralized

Messaging Channels (Whisper). According to the www.stateofthedapps.com which list and keeps track decentralized applications, one of the leading platforms in this domain is

Ethereum; which is the platform on top of which the application that the subject of this paper is built. Discovering the potential of Blockchain technology, Vitalik Buterin published the Ethereum white paper in 2013 with the purpose of extending the Bitcoin blockchain platform by adding a scripting language to allow application development on the platform and the capability to store computer program in the form of bytecode for different usage [20]. With the current system in place, building an application that allows users to raise money on a typical platform is not an easy task. It requires a third party that acts as the middleman for the transparency and fluidity of the process which leads to higher transaction fees and delays in the process due to verification and processing of users’ personal and credit card information. The purpose of this project is to use a

1

different approach to build the same application as the traditional one by eliminating the middleman and therefore speeding the process and reducing the transaction cost.

A cryptocurrency is an encrypted network value of peer-to-peer exchange which facilitates digital trade; it is known to pave the way for financial systems of payment. Cryptocurrency, which was developed about eight years ago, as a form of Bitcoin, which is the first and, of course, the commonest cryptocurrency, is unlikely to take the place of the traditional order of currency.

However, it would transform the mode of global internet markets and its interaction with business, and also remove obstacles of fiat transactions. Cryptocurrencies may bring about the revolution of the digital world and trade markets, as its flexibility gives room for crowdfunding even on an advanced scale compared with fiat currency.

We are going to build a community crowdfunding application that allows different communities to raise money for charity or for community interests very easily and at very low cost. We are going to take advantage of the features offered by the blockchain technology such as no need for a central authority or middleman to coordinate transactions between the protagonists involved, its security and transparency, its privacy and its openness. Users, by contributing to a particular campaign, will receive tokens as a reward and can later use them for other purposes such contributing to another campaign or to purchase goods.

1.1 Crowdfunding Application

The mechanism by which start-up, struggling businesses, not for profit organization and people raise money to develop a new project is very diverse. Some choose to go to big banks to borrow

2

money. This form of access to cash comes at a cost of a high-interest rate attached to the loan and the businesses have a determined period of time after which they have to repay the bank the money they borrowed plus any interest accrued during the lending period depending on the condition and terms of the loan. Some choose to seek investment from Venture Capitalists in exchange for a stake in the company. This task can be very tedious for start-up or struggling businesses because they are competing with thousands of other companies seeking . Venture Capitalists tend to favor businesses with a working model rather than early stage Start-up or even struggling business and Organization doing charity work. Other problems they run into are regulations put in place by the SEC for issuing equity in the company in exchange for funding. The best option for start-up, struggling business and not for profit organization to have access to cash is by raising money from individuals and or groups of people through Crowdfunding on an online platform built solely for that purpose. Crowdfunding can help circumvent financial institutions, venture capitalists, and the SEC regulations. Choosing the crowdfunding option depends on business maturity and its goals. -based crowdfunding is best suited for a charity organization and early-stage startup still trying to define their business model since they are not required to give any equity to their backers but would give them some access privileges to their products as soon as it becomes available. Donation-based crowdfunding has gained a lot of popularity in recent years.

People raise money to fund the development of their product crowdfunding platforms such as

Indiegogo and . Another popular platform called Gofundme is mostly used for a charity donation. As of October 2018, Gofundme has raised over 5 Billion dollars with 50 Million users and 4 Million Dollars raised daily. Since the launch in 2010, they had over 2 Million funding campaign launched on their platform [21]. On these platforms, the person launching the campaign registers it with the goal which is the amount of money they need and the deadline. The only

3

drawback is that these platforms collect fees and some these can be very high due to credit card processing and overheads cost. Blockchain offers a solution to circumvent this middleman and the money being collected are deposited directly into the account of the designated entity if the goal is met and it depends on the conditions written in the smart contract of the campaign.

4

Chapter 2. BACKGROUND AND RELATED WORK

2.1 Blockchain Technology

2.1.1 Background and History

In 2008, Satoshi Nakamoto introduced the Bitcoin white paper to the world [1]. This paper details the peer to peer electronic cash system in which parties can exchange assets or cash without relying on a third party or a financial institution. In order to solve the problem of double spending encountered by Nick Szabo in the 90s when he developed the electronic cash system. Double- spending occurs when an individual spends the money, they own twice without any party involved to verify if they own it or have already spent it on a different transaction. In the traditional system, financial institutions maintain records of all transactions in a ledger that is used to verify any new transaction in order to avoid double-spending. This process takes a long time and delays transactions time. Satoshi proposed a solution using a peer to peer network to make each participant broadcast their transactions to other participants and have an agreement mechanism in place for participants to validate transactions and add sequentially on to the network distributed database or ledger. This solution proposed by Satoshi gave birth to Bitcoin in 2009 and opened the path to the proliferation of blockchain technology and the development of cryptocurrency and distributed ledger technology (DLT).

Blockchain can be defined as an immutable public distributed electronic ledger implemented as a network of nodes with no central authority. Blockchain is a stack of blocks linked together with each block containing the hash of the previous forming a chain of blocks hence the name

Blockchain. Every node on the network has the exact same copy of the transaction’s records. The

5

nodes on the network maintain the network and add and confirm transactions as they occur. Each block on the chain has a fixed sized. Each block is time-stamped and identified by its cryptographic hash value. Transactions are added to the block until the block is full then the block is added to the chain and the new chain is broadcasted to all the nodes on the network to update their current chain. Blockchain maintains the record of all transactions on the network accessible by anyone but protected using a cryptographic technique. Blockchain doesn’t require a third party as a central authority that will verify and authenticate each party involved in the transaction, its settlement or control of the infrastructure by which all this is possible. Blockchain technology relies on a distributed self-governing consensus mechanism built in its core to handle trust or distrust between the involved party, tamper proof the data and secure the network from any malicious attack.

Blockchain is not only seen as a potential disruptor of the financial industry but also industries such as Healthcare, , Marketing, Supply chain, Manufacturing, Logistics and many more

[6].

2.2 Related Work

The explosion of Blockchain technology due to the mass adoption of Bitcoin has given rise to a lot of research in Blockchain and distributed ledger technology. This research has led to the creation of different blockchain platforms. Most research focuses on the technicality of the blockchain and distributed ledger in order to understand its extent, limits, security, and scalability; and how these new technologies can be applied to different economic sectors. In the research on how to eliminate the middleman, researchers have come up with many different consensus mechanisms [22]. There are dozens of consensus protocols nowadays; thanks to the hard work of

6

academic’ researchers on this revolutionary technology since the invention of the internet. In 2016,

Brening and Al publish a paper detailing the understanding of the value of a decentralized digital infrastructure but fell short on their claims due to lack of empirical data and statistics to support their claim [23]. Their work focused mainly on Bitcoin because this technology was new and is very difficult to find any data for analysis. Bitcoin doesn't represent Blockchain and distributed ledger technology in all their forms. Given the fact that the consensus algorithm used by Bitcoin claims to be very secure, some researchers were able to point out some vulnerabilities and flaws in the consensus protocol used by Bitcoin; which is the proof of work algorithm [24].

2.3 Blockchain Architecture

Figure 2.1: Blockchain Structure

The figure above shows the structure of the blockchain which is a sequence of blocks linked together. Each block is identified by its cryptographic hash and has a field in its header representing the cryptographic hash of the block that comes before it in the sequence. The cryptographic hash of the block is represented by the Nonce field of the header of the block. The cryptographic technique is used in blockchain structure to verify the proof of work meaning that a very complex

7

mathematical computation has been carried out on each block and the proof of work is valid. Each block maintains the record of all the transactions verified since the creation of the last block. The

Merkle tree data structure is used to store transactions on the blockchain. The Merkle tree data structure is a type of binary tree structure where data is stored on the leaf node of the tree. Every node on the tree that is not a leaf node is labeled with the hash value of its two children nodes. Any changes made on the leaf node results in changes of every node on the tree up to the root node.

Only the root of the Merkle tree data structure is stored on the block. This is done to avoid storing all the information of transactions inside the block. Since the size of the block is limited.

2.3.1 Decentralization

The decentralized nature of the blockchain technology gives this technology an advantage over traditional centralized systems which are prone to failure. When a system is centralized, that is a potential single point of failure. When an application runs on a single server, which is the case in traditional systems, if the server goes down the entire application is shut down and this puts businesses at risk of attack by hackers and make them lose money and therefore lose value. A decentralized system can be explained as being a peer-to-peer network using a consensus algorithm technique to record a public history of transactions that quickly becomes computationally impractical for an attacker to tamper the information of transactions stored on the network if honest nodes control a majority of computational power of the entire network. Nodes connected to the network work all at once with little coordination. They do not need to be identified, since messages are not routed to any particular place and only need to be delivered on a best effort basis. Nodes can leave and rejoin the network at will, accepting the longest chain on the network as proof of what happened while they were gone in order to bring their machine to the same state as all the other connected nodes of the network. They vote with their CPU power, expressing their

8

acceptance of valid blocks by working on extending them and rejecting invalid blocks by refusing to work on them. Any needed rules and incentives can be enforced with this consensus mechanism.

2.3.2 Distributed Ledgers

A distributed ledger is a form of decentralized database that is shared and synchronized across the blockchain network run by a set of rules and conditions implemented by the consensus mechanism.

It is spread across many geographical areas on the blockchain network. It keeps records of any transactions and smart contracts running on the blockchain. It is opened to any who join the blockchain network to see and thus eliminating the need for a third party to maintain and prevent any manipulation of data. Any transaction data and smart contract stored on the distributed ledger is accurate and secured using various cryptographical mechanism. Once a record is stored on the distributed ledger it cannot be changed, it is immutable. Since every single node on the network stores a copy of the ledger, it become very difficult to attack because in order for an attack to succeed the attacker has to simultaneously attack all the node of the network. A single malicious node on the network cannot attempt to change a record without the agreement of the other nodes on the network. These characteristics makes it very secure and reliable. Distributed Ledger

Technology has the potential to change the way many institutions and corporations even the government are run by bringing a revolutionary technology that provides transparency and trust in the day to day activities of the institution. Some of the areas it will be of good use when it arrives at governmental institutions, collection, land record and registries, issuing passports, issuing licenses, voting systems, and distributions of social security benefits.

9

2.3.3 Consensus

Consensus protocols are amongst the foremost necessary and revolutionary aspects of blockchain technology. These protocols produce an undeniable system of agreement between numerous connected nodes across a distributed network while preventing exploitation of the system. Here we are going to explore how these systems work and the way numerous protocols disagree with each other. Blockchain agreement protocols are what keep all the nodes on a network synchronized with one another. Consensus involves the establishment on a set rules upon which every single connected node of the network agrees. Blockchain technologies have multiple consensus mechanisms that are analyzed later in this paper. Block creation and transaction involves a form of consensus mechanism. They are Proof of Work, Proof of Stake, Proof of Authority and many more. Consensus is the driving force of the blockchain technology that ensures its reliability by eliminating any form of trust amongst its participants.

2.3.4 Smart Contracts

A Smart Contract is a digital form of contract written using a programming language and deployed and running on the blockchain network platform. A smart contract contains rules and conditions that allow parties involved in the contract to agree and interact with each other. The agreement is enforced only if the rules and condition defined in the smart contract are met. The smart contract is automated based on the rules written in the code. These allows the verification, facilitation, and enforcement of the negotiation of transactions. Smart contract eliminates the need of a third party to enforce agreement. Everything is built in the code of the smart contract. A smart contract is a very powerful tool. The blockchain technology is viewed today as the catalyst of the propagation

10

of smart contracts even though smart contracts are not new. It existed years before blockchain technology. The use of a smart contract in any transaction can slash the cost of the transaction tremendously by auto enforcing the rules written in the code at the protocol level or the application level. Some of the characteristics of a smart contract are: it is self-verifying, it doesn’t need anyone to verify its validity. It is self-executing; it doesn’t need the involvement of any third party to enforce agreements. It is tamper-resistant, no attack can be hack it and modify its rules when it is already deployed on the blockchain. Some advantages of using smart contracts are that it can automate the legal process by having the rules of law written in the smart contract. It is secure and reduces any reliance on trusted third party to enforce its rules, and it lowers the transaction cost.

2.3.5 Cryptography

Cryptography is a mathematical technique to secure data when it is being transferred between two people preventing a third from intercepting the communication and understanding the meaning of the data being transferred. There are multiple techniques involved in cryptography. Some of the main techniques are Hashing, Encryption and Decryption. Hashing is a mathematical mechanism of taking data of an arbitrary size and converting it into a digital string of predefined fixed size called a “hash”. The technique uses a computational function called the Hash Function. The hash function concept is very simple but at the same time very complex in the sense that a lot people using cryptography want to have control over the hashing technique, but this is impossible.

Hashing is one way. There is no way to take the output of a hashing function and recover the input data. It is a one-way computation. The mechanism taking place in a hash function is that it takes the input data and digest its bits in a convoluted way to make it impossible to reverse the computation. The output of the hash function is a fixed size hexadecimal format. If the output is passed again into the hash function it will generate another hash value. A hash technique is used

11

to hash user password before storing it in the database rather than storing the password in plain text. In case there is a breach and the user data is stolen there won’t be a way the hacker can recover the user’s password. Some of the popular hashing functions are MD5, SHA1, SHA2, SHA128,

SHA256, and SHA512. Hashing is heavily used in blockchain technology to protect the data and secure transactions on the network. Encryption and Decryption is another cryptographic technique used in blockchain. This technique involves using a public key to encrypt data that can only be decrypted with the private key associated with that public key. It is used in digital signature and transaction verification on the blockchain. Public/Private Key is a very important concept in blockchain technology. Data on the blockchains are public, opened to anyone to have access to it.

In order to preserve the identity of who the data belongs to, blockchain uses different encryptions techniques to make that possible.

2.3.6 Cryptocurrency

Cryptocurrency is a digital and virtual asset in the blockchain network that heavily uses cryptography to keep itself secure. It can also be defined as an electronic cash system using a peer to peer technological architecture to allow users to exchange values. Electronic cash has been around for decades but what is most particular to the form of electronic cash called cryptocurrency is that it relies on cryptography and cryptographic algorithms for security purposes and transactions verifications. When cryptocurrency is registered on the blockchain network, which is simply recording in a distributed database no one can change it unless a certain condition required for the modification are met. Unlike Fiat currency that is created out of thin air, cryptocurrency requires solving a complex mathematical problem to generate coins. This concept applies mostly

12

to the Bitcoin proof of work algorithm. Blockchain network, which has cryptocurrency as a form of transaction incentives, relies on the absolute consensus of verifying transactions by all connected nodes of the network. If one node on the network disagrees on one transaction verification, then the entire network will break and stop. However, there are certain rules and conditions programmed into the network to avoid this type of situation from happening.

2.3.7 Accounts

Every party involved in the blockchain network is identified by an address which is contained in an account. There are two types of accounts in the blockchain. I am going talk particularly here about the Ethereum blockchain account system. They are an externally owned account and a contract account. Externally owned accounts are owned and controlled by the participants of the blockchain network. On the Ethereum blockchain platform, each externally owned account has an ether balance associated with it. Ether is the Ethereum blockchain platform built-in token. Every transaction on the Ethereum platform is initiated by an externally owned account. They send transactions to other externally owned accounts or to contract accounts. Each externally owned account has a combination of a private and public key. The address of an externally owned account is derived from its public key. These keys are required to verify and sign transactions. A contract account however is controlled by its programming code. They also have an ether balance associated with their account. Transactions issued by contract account are called messages. The execution of a contract is triggered by an externally owned account or a message sent by another contract account. Some contract code execution changes the state of the contract.

13

Figure 2.2: Accounts Type on the Ethereum Blockchain

2.3.8 Blocks

In blockchain, a block represents a list of electronic transactions and set of data grouped together to meet the size of a block. The size of the block varies based on the blockchain platform. On the

Bitcoin platform the size of the block was set at 1MB. The block size limits the amount of data and transactions that can be stored on the block. When the size of the block grows it requires more computing power to mine that block. At the end of 2017, in the middle of the Bitcoin hyper-mania, there were more than 200 thousand unconfirmed transactions sitting on the Bitcoin blockchain.

This situation caused the delay in fulfilling orders on many blockchain exchanges, increasing the transaction’s fees, and hype the price of many cryptocurrencies. Miners had difficulty confirming transactions faster since a batch of transaction was being put on the blockchain simultaneously.

The Bitcoin developers came together to try and find a solution to the block size problem. Some developers proposed increasing the size of the block, but some didn’t agree. This prompted the

Segwit soft fork of Bitcoin. This solution allows processing transactions off the main chain on an additional consensus layer. Segwit allowed to store the main chain’s cumbersome data somewhere

14

else bumping the block size to 4MB. Ethereum does not have a block size limit. But rather has a gas limit. The structure of a block consists of the header and the transactions. The header of the block contains the block’s number, the timestamp which is time when the block was added on the chain, the hash of the current block, the hash of the previous block, and the data which is a structured data about the transactions stored in the block.

2.3.9 Transactions

Transactions area the items that provide a blockchain purpose. They are the smallest building blocks of a blockchain system. Transactions typically accommodate a recipient address, a sender address, and a value. This is not too different from a regular transaction that can be realized using credit card. A Bitcoin transaction for example is the process of moving value from one bitcoin account address to another bitcoin account address. Every transaction effectuated on the blockchain network changes the state of the network. A blockchain is a shared, decentralized, distributed state machine. This means that each node (users of the blockchain system) hold their own copy of the blockchain, and therefore update their copy of the blockchain based on the change in state of the network. Transactions are bundled unit and are broadcast to every node within the blockchain network. Every transaction broadcasted in the network is a process to verify its validity.

This is done to prevent anyone on the network spending what they own twice, thus the double spending problem. The solution is to make all the nodes on the network be aware of all the transactions on the network therefore knowing what asset belongs to who. Transactions contain one-or-more inputs and one-or-more outputs. An input may be a relevancy associated output from a previous transaction. An output specifies an amount and an address. An input always references

15

to a previous transaction output. This continual pointer of inputs to previous transactions outputs allow for an uninterrupted, verifiable exchange of values between addresses on the blockchain network platform. Also included in the input data structure is a script. This is a cryptographic signature that proves that the creator of this transaction can create it given inputs. Remember that an associated input may be a relevant associated output from a previous transaction. The scripts contain the address in the referenced transaction's output and a digital signature of this current transaction. It is this straight-forward value-transfer mechanism exploitation of "transactions" over time that make a blockchain. As every group action happens, it gets added to the blockchain ledger.

Each transaction is added to the current block being created after verification. Transactions are stored in the blockchain network using the Merkle tree data structure on which transaction information are stored on the leaf nodes and their hash value is stored on the parent node. Only the root of the Merkle tree data structure is stored in a block representing a big chunk of confirmed and verified transactions.

2.3.10 Tokens

A token is defined as the unit value that is exchanged between participants in the blockchain during a transaction. It is also used as a currency on the blockchain market platform. Built-in tokens in the blockchain are considered as a form of security. By investing in a particular project, you received a token as a form of share in the project which you can later trade on an exchange for a different token or just sell it to cash in your investment. Their value goes up and down based on interest in it just like on the stock market. The most popular tokens are bitcoin for the

Bitcoin blockchain, Ether for the Ethereum Blockchain, XRP for the Ripple blockchain, ADA for

16

Cardano blockchain, etc. There are many of them. Any project built on the blockchain have a form a built-in token.

2.4 Decentralized Applications (DAPPS)

Decentralized Applications are applications developed using smart contracts deployed and running on the decentralized peer to peer network. Decentralized applications are viewed as a client-side user friendly interface that users to interact with a smart contract on the blockchain. An example of a decentralized application would be the exchange application that is used to trade cryptocurrencies on the blockchain network. Building a decentralized application involves developing a user interface using HTML, CSS and JavaScript; Implementing a Smart Contract using a high-level programming language; Using a language specific compiler to compile the smart contract and generate a contract binary usually call Application Binary Interface or ABI;

Deploying the generated contract binary code on the blockchain using any blockchain platform based on the platform the contract was written for and obtain the address of the smart contract that will be used by the web application to interact with the smart contract on the blockchain.

2.5 Type of Blockchain

There are currently three type of Blockchain: public Blockchain, private Blockchain, and federated

Blockchain. Public Blockchain is opened to anyone who wants to join. You don’t need permission to participate in a public blockchain. Anyone who possess a computer can go on the internet and download the source of the blockchain they want to join, compile it and run it and start confirming transactions on the blockchain. Any valid transaction sent by anyone is included on the blockchain.

17

All transactions are opened to anyone to view them. This can be done on a block explorer website.

Transactions appear to be transparent and pseudonymous because you can only identify transaction actors if you know the identity of the person who owns the public key linked to the transaction.

Some of the biggest public blockchain platforms are Bitcoin, Ethereum, and Litecoin. On the other hand, federated Blockchain have a different mode of operation. It is under the control and leadership of a group of people or group of corporations. The participation process is very selective. Anyone can not join and verify transactions as is the case with public blockchain.

Transactions on the federated blockchain are private, secure and highly scalable. The transaction confirmation process is done by a selective set of nodes connected on the network. Federated blockchain is mostly used in the banking, insurance, and energy industries. Some of the biggest names are: R3 in the banking sector, EWF in the energy sector and B3i in the insurance sector.

The last type of blockchain to talk about is private blockchains. A private blockchain is not much different from the current centralized system we have today. Reading transactions on the private blockchain is open to anyone with some restrictions but the transaction verification is centralized to one entity in charge of the blockchain. Private blockchain are highly scalable and comply efficiently with data privacy rules but they are vulnerable to attack and security breach. The biggest name here are MONAX and Multi-Chain.

2.5.1 Bitcoin

Created in the 2008 and launched in 2009 by an individual or group of people named Satoshi

Nakamoto, Bitcoin was the first proof of concept of the blockchain technology. Bitcoin was able to demonstrate the exchange of values between two users without the need of a third party to confirm the validity of the transaction using a peer to peer network system. This is made possible

18

by the interconnected network nodes which verify and records all transactions between users into a distributed public ledger known as the blockchain. The unit of exchange between the users and the networks node’s actors is known as Bitcoin. Bitcoin’s blockchain is a public blockchain and thus consist of all the characteristics of public blockchain. On the Bitcoin white paper, Satoshi

Nakamoto define Bitcoin as “A peer-to-peer electronic cash system” which allow transaction payment to be sent from one party to another without any third party involved through a peer to peer network system. Bitcoin uses the Proof of Work (POW) consensus protocol to run its operations and secure its network. Bitcoin is the most popular cryptocurrency in the blockchain universe and in the mainstream and is also at the top of the chart of all cryptocurrencies by market value and market capitalization. As of this writing, Bitcoin market capitalization is close to 98 billion US Dollar with one being priced at 5614 US Dollar according to the website www.coinmarketcap.com.

2.5.2 Ethereum

Ethereum is the second generation of blockchain technology. Created in 2013 by Vitalik Buterin and launched in 2015. In the Ethereum white paper, Vitalik proposed a blockchain network where different type of applications can be developed. Each application on this platform is stored as a form of “smart contract”. These smart contracts are developed using high level programming languages to be deployed on the network and made accessible to whoever want to use it. In Late

2014, an Ethereum yellow paper was published by Gavin Wood, one of the lead developer in the project [25]. This paper detail the Ethereum blockchain protocols with most of it borrowed from the Bitcoin blockchain protocols; and the first functional implementation of the Ethereum blockchain. Gavin Wood on the yellow paper also proposed a programming language that will be

19

used to develop smart contracts on the Ethereum platform. This language is called Solidity.

Solidity syntax is similar to JavaScript’s syntax. Programs written for the Ethereum blockchain platform use the Ethereum Virtual Machine to compile the code to byte code. Transactions on the

Ethereum blockchain platform has a cost of operation. Meaning that you have to pay an incentive to run an operation on the platform. This is called “gas” and is proportionate to the processing complexity of an operation. Ethereum uses the same consensus protocol as bitcoin, the proof of work protocol. But due to its high electric power consumption and the requirement of hardware with high computational power because of the mathematical complexity of the proof of work algorithm, Ethereum is adopting a new protocol called proof of stake. There are currently thousands of applications being built on the Ethereum blockchain. The issue faced by most of the public blockchains are scalability and security.

2.5.3 Hyperledger

According to the Hyperledger website, the project was created as an open source collaborative effort to facilitate and advance cross-industry adoption of blockchain technology [26]. It was initiated by the Linux foundation. The goal of Hyperledger is to combine knowledge across industries and use blockchain to develop solution for their specific needs. Many industry leaders from financial institutions to Healthcare and High-tech companies joined the movement. The

Hyperledger initiative has more than 270 organizations contributing to its development. According to the Hyperledger white paper published in 2016, their mission is to “create an enterprise grade, open source distributed ledger framework and code base; promote participation of leading members of the ecosystem” [27]. They wanted to create an environment where developers and companies meet to discuss challenges faced by the blockchain technology and build blockchain

20

frameworks. Hyperledger doesn’t have built in cryptocurrency token like other blockchain platforms. There are currently many projects and industry applications being developed on the

Hyperledger infrastructure. Some of the leading Hyperledger projects are:

- Hyperledger Sawtooh: developed by Intel, its goal is to allow companies to run their application on a maintained distributed ledger with no central authority. This blockchain uses a new form of consensus protocol called Proof of Elapsed Time (PoeT). This consensus algorithm distributes network mining permission through a random but fair system.

- Hyperledger Fabric: created by IBM, Hyperledger Fabric is the most adopted blockchain by big companies. It provides a basis to develop blockchain platforms for a specific industry and also develop application required for specific needs. It is easily scalable to provide transparency, decentralization and security which are the core of blockchain technology.

- Hyperledger Indy: It is a ledger developed for decentralized identities. It provides tools and libraries for developing applications and using digital identities. Hyperledger Indy uses blockchain based identity solutions in its core.

- Hyperledger Burrow: Is developed to mimic the specification of the Ethereum Virtual

Machine on top of which smart contracts are developed. But it requires permissions.

- Hyperledger Iroha: Is a blockchain technology framework developed to facilitate blockchain technology use in projects that require a distributed ledger technology.

2.5.4 Distributed Acyclic Graph (DAG)

21

Distributed Acyclic Graph or Direct Acyclic Graph is a data structure based on directed graphs and uses topological ordering to store data. It is an alternative solution to chain-like storage structures used by the traditional blockchain technology. Each transaction is stored individually on the DAG blockchain. This process speeds up the transaction confirmation process. There is no block involved here. Transactions are stored directly into the Distributed Acyclic Graph networks.

Transaction validations are decided by the number of existing confirmed transaction behind them.

Since the rate of transactions coming back into the network are lower, the transaction time is very low and safe. There is no mining mechanism involved here since all the transaction validations go directly to the transactions themselves. There are minimum transactions fee paid to those maintaining the network. The leading blockchain platform using this form of data structure to store transactions is IOTA. The technology they use is called Tangle.

2.6 Blockchain Stack

The problem blockchain was trying to solve when it was created was the double spending problem in order to facilitate transactions between users without the intervention of a third party.

Blockchain structure was a good fit to record all these transaction on its distributed ledger stored on the network. However, the size of the data stored on the Blockchain is limited. Blockchain is not designed to store larger amounts of data than the one specified in its protocol or handle any communication between its peer to peer connected nodes.

22

Figure 2.3: Blockchain Stack

2.6.1 Computational Platform (EOS)

A decentralized computational platform is a programmable blockchain platform that allows the development of applications using smart contracts and they also perform highly complex mathematical computation to ensure the safety and security of the data stored on the blockchain.

Ethereum will be a very good example here but we are going to look at a different blockchain platform called EOS in order to see what Ethereum and EOS as computational platform have in common. EOS is another very popular public blockchain platform similar to Ethereum. EOS was created by Dan Larrimer in 2017 [28]. It allows the development of decentralized applications.

The goal of EOS is to become a decentralized operating system that provides resources to develop scalable decentralized applications. They provide services such as user authentication, cloud storage and server hosting to make applications development faster and secure. Some of the key features of EOS are:

23

- Parallel processing: It has the ability to perform multiple tasks in parallel and thus faster

transactions processing and higher scalability.

- Constitution: This is defined as a set rules upon which every actor involved in the platform

agrees on and these rules are linked to every block created in the platform.

- Self-sufficient and Evolution

- Decentralized Operating System: Any developer can build an application on the EOS

platform under one condition which is they should own a certain amount of EOS built in

coin even though development, deployment and interaction with applications on the

platform is free of charge.

Something that is making the blockchain community excited about the EOS platform is because there is no transaction fee, it has the ability to process thousands of transactions in seconds, it is secure and highly scalable and interacting with the platform is very user friendly.

2.6.2 Storage Platform (SWARM)

The storage limitation on the blockchain is being solved by the development of the distributed storage platform called SWARM. SWARM is a decentralized storage platform and content distribution service for the Ethereum public blockchain platform. Swarm is the base layer of the

Ethereum blockchain stack. Swarm was designed to provide decentralized space to store

Ethereum’s data and public records, and blockchain data and decentralized application source code. Because of its peer to peer architecture, SWARM doesn’t have a single point of failure, and is resistant to all kind of attacks such as fault attacks, and distributed denial of service attacks. The

SWARM platform is not controlled by a central authority and therefore it is censorship resistant.

24

Since it is decentralized, individuals joining the network and offering storage space are rewarded by the built-in incentive system of the platform. SWARM is highly scalable and serve popular content by ensuring the availability of resources and content that are not popular.

2.6.3 Messaging Platform (WHISPER)

The solution to allow communication between decentralized applications is called WHISPER. It is a communication protocol developed to facilitate communication and exchange of data between decentralized applications and users. Each message sent through the network has a time to live set and one or more topics associated with it. WHISPER uses the infrastructure of the Ethereum blockchain network. It has a modular privacy and anonymity that allow users to opt-in or opt-out of different privacy features offered by the system. WHISPER uses a cryptographic peer to peer network and protocol to transport and communicate messages containing data via their peer to peer network. Every decentralized application running on a particular network node inform that node about the topic that it wants to subscribe to. Every node on the WHISPER network advertises topics that interest them to their peers. Messages are filtered based on the topic subscribed to by the node and the message is then delivered to that node if requested and the node dispatches the message to all the decentralized application running on that node. WHISPER uses the UDP protocol to transfer data because it is faster than the TCP protocol.

2.6.4 File Sharing and Storage Platform (IPFS)

25

IPFS stand for Interplanetary File System. It is a decentralized platform for file sharing and storage.

It stores files and tracks their changes over time. It implements the movement of files across shared networks. IPFS sets the protocol how data and files are transferred over the blockchain network.

It does this by using the representation of the content itself to address that content rather using the location address of the content. IPFS represents contents by their cryptographic hash value. When consuming a content over the IPFS network, users don’t need to establish a connection to a server but rather get it from the closest node on the network. According to the founder of IPFS Juan

Benet, “IPFS connects all theses different blockchains in a way that’s similar to how the web connects all the together. The same way that you can drop a link on one page that links to another page, you can drop a link in a blockchain platform that links to another blockchain platform and IPFS can resolve all of that”. Users willing to offer storage resources on their computer are rewarded with a built in coin called Filecoin that they can trade on any cryptocurrency exchange for any other currency.

2.7 Security and Scalability

In this section we are going to look at some of the security and scalability issues faced by the blockchain technology.

2.7.1 Double Spending Problem

The major problem faced by peer to peer digital cash systems and cryptocurrency is the double spending problem. The double spending problem occurs when an individual on the network tries

26

to spend the currency the own twice or they want to double the amount they own. In the traditional system, there is a central authority that serve as a validator of ownership of every currency amount and keeps track of the balance of that amount at all time. But in the peer to peer system where there is no central authority and both parties involved in the transaction don’t trust each other this problem becoming very challenging. Satoshi Nakamoto proposed a realistic solution to this problem. First, he proposed that all transactions should be publicly announced and broadcast to all parties involved. This led to development of the peer to peer network which is the blockchain today. Second, developed a system where all parties involved agree on certain rules and protocol of transactions and their sequence before adding them on the public ledger. This led to the development of consensus algorithms with the first being the Proof of Work algorithm.

2.7.2 Byzantine Fault Tolerance

Since there is no central authority in a distributed system, achieving a consensus between all the peers and nodes involved in the network become a very challenging problem to solve. All the actors of the network need to come to an agreement of the overall state of the network at all time to ensure its validity and security since all the parties involved do not trust each other. This problem is called the Byzantine Generals’ problem named by Lamport et. Al [4]. This problem is characterized by the fact that all the nodes and peers involved in the network do not trust each other and therefore communications between them during the broadcast or public announcement of transactions might not be reliable. A Byzantine fault tolerance system is a system that is vulnerable to the Byzantine Generals’ Problem. Satoshi Nakamoto proposed a solution to this problem by combining the blockchain with its peer to peer network system protected by the

27

cryptographic mechanism and the proof of work algorithm with its difficulty and high computation power. This proposal was the solution to bring all the peers and nodes to an agreement even though they didn’t trust each other and maintain the state of the network at a global scale.

2.7.3 Sybil Attack

A Sybil attack occurs when an attacker forges a large amount of anonymous identities by creating multiple accounts on the network and take control of the network. Many decentralized applications on the blockchain are prone to this attack. an example here will be a decentralized voting application built on the blockchain. Here an attacker can open multiple accounts and then gain influence over the outcome of the voting system. Even though the blockchain network itself is protected from this type attacks, individual applications running on the blockchain platform are not safe from these attacks. The solution to prevent these attacks from happening is to integrate a certain identification mechanism of an individual account during the development of smart contracts. For example, the person developing the voting contract has to setup a certain mechanism in the contract that ensures that only the authorized account is allowed to participate in the vote and an individual account cannot not vote twice. They can also setup a certain amount to be paid to interact with the smart contract or more importantly they can take advantage of the identity and reputation system of the blockchain where a certain score is attached to every public key of an account on the blockchain network.

2.7.4 Blockchain Scalability

28

One of the major concerns faced by the blockchain technology today is scalability. All the mechanisms (Consensus mechanism and block time) involved in a blockchain network are the deterministic characteristic in processing and confirming transactions faster on the network.

Traditional system of payment such Visa and Mastercard process more than 24 000 transactions per second. Unlike traditional system, blockchain technology take more time to confirm transactions on their network since there is no central authority to verify and confirm the validity of transactions and the peers involved do not trust each other. Bitcoin process between 3 to 7 transactions per second because it has set its block time to 10 minutes and an average block size of 1MB, this means that on the Bitcoin blockchain platform 1 block is created every 10 minutes.

Ethereum platform also process 3 to 7 transactions per second but has a very short block time of

17 seconds. But according the Vitalik Buterin the creator of Ethereum, with the second layer solution protocol being develop on the Ethereum network layer called Sharding and Plasma,

Ethereum will have the capacity to process from 1 Million up to 100 Million transactions per second. This is hard to believe because blockchain applications require solving a mathematical computation and multiple confirmation stage for a newly mined block in order to prevent double the spending problem. Modifying the block time in other to confirm a large amount of transactions faster is possible but it will impact the security of the network and make it vulnerable to attacks.

This modification can also lead to a centralization where a miner with bigger computation power would be the only one to confirm transactions and therefore control the entire system. Another major scalability concern is the size of the blockchain itself. As of September 2018, the Bitcoin blockchain size was 185 gigabytes and the size is increasing very fast [7]. This also can lead to centralization of the mining operation to those with large storage capacity and high computational power.

29

Chapter 3. SMART CONTRACTS AND BLOCKCHAIN CONSENSUS

3.1 Smart Contracts

3.1.1 Definition and Origin

A smart contract is a set of instructions and digital protocols written in a programming language with the intent to verify and enforce contracts between parties involved which reside on a blockchain platform and possess a unique identifier called an address. The concept of Smart

Contracts was introduced back in 1996 by an American Cryptographer and programmer named

Nick Szabo [8]. Szabo established the concept by defining a Smart Contract as being a set of digital protocols to transfer information using mathematical algorithms to automate the execution of a transaction when all the conditions established by that transaction have been met. The smart contract should be able to fully control the process from start to finish. At that time, it was impossible to realize this concept due to technological and infrastructure limitations. In 2008, the distributed ledger technology introduced to the world by the revolution of the blockchain technology, revived the smart contract concept and gave rise to its potential. Ethereum was the first blockchain platform capable of implementing a smart contract and made its use available to the general through a form of developing decentralized applications on its platform. There are many blockchain platforms that allow the use of smart contracts to develop decentralized applications.

30

3.1.2 Structure of a Smart Contract

There are variances that constitute a smart contract. A smart contract comprises a set of executable functions and state variables. Functions included in a smart contract are executed when a transaction is sent to it. A typical transaction includes a set of input parameters required by the functions in the smart contract. The variables in the smart contract change their state depending on the logic implemented in the function upon execution of that function. A Smart Contract includes:

● Functions: set of code executed when transactions are sent to the smart contract.

● Constructor: special function in the smart contract that is executed only when the

contract is deployed.

● State variables: variables stored in the contract’s storage and used to main the state

of the smart contract.

● Event: special functions within the smart contract used to track the execution of the

transaction sent to the smart contract

● Modifiers: special function within the smart contract used to change the behavior

of other functions within the same contract when transaction is sent to the contract.

Figure 3.1: Smart Contract Structure

31

3.1.3 Design and Implementation

Writing a smart contract is difficult. There are many tools being developed to facilitate the adoption of blockchain technology by means of making it easy to write a smart contract. A smart contract can be written in multiple high-level programming languages. The most popular programming language developed specifically to write smart contracts is Solidity. Smart contracts can be written in other programming languages such Python, Java, Go and C++. But languages that are compiler specific for smart contract are Solidity (Which is a JavaScript-like language) and Serpent (Which is a Python-like language). These two languages (Solidity and Serpent) are used to compile smart contracts into bytecode and deploy them on the blockchain network which in return assigns to the contract a unique identifier (usually an address). This unique address can be used by anyone connected on the blockchain network to send transactions to that smart contract. Each node connected on the network that participate in the verification process of a new block being added to the blockchain executes the smart contract code on their node.

3.1.4 Interaction

Every smart contract deployed on the blockchain network can communicate with other smart contracts residing on the network by sending messages to them or receiving messages from them.

A typical message transiting between smart contracts contains the address of the contract sending the message, the address of the recipient of the message, value being transferred and the input data to the recipient smart contract. We should note here that there is a difference between a transaction and a message. A transaction is when an externally owned account, meaning an account owned by an individual, interacts with a smart contract. While a message is when a smart contract interacts

32

with another smart contract. They both are similar, but their underlying structure and interaction are quite different. Transactions sent by externally owned accounts are signed using the sender’s account private key and contains the following:

● nonce: scalar value representing the number of transactions already sent by the initiator of

the transaction.

● gasprice: price per unit of gas paid for all mathematical computation involved in the

execution of this transaction.

● gasLimit: scalar value representing the maximum allowed amount of gas used to execute

the transaction.

● to: address of the recipient of the transaction in this case the contract address. If the

transaction is creating a new contract, then this field is left empty.

● value: scalar value representing the amount being transferred with the transaction. If the

transaction is to create a new contract, then this value will represent the initial balance of

the newly created contract.

● data: an array containing the data that is part of the transaction. This field represents an

input data to a contract when the transaction is sent to a contract.

● (v, s, r): value representing the signature of the transaction. these values are used to identify

the address of the account sending the transaction.

3.1.5 Vulnerabilities

Even though blockchain technology is very secure, applications running on the blockchain network are not immune to external attack. Attackers have tendency to exploit a vulnerability in a smart

33

contract to gain control of the decentralized application. There are several type of vulnerabilities a

Smart Contract can be opened to:

● The “re-entrance” problem: this situation occurs when a smart contract during a call to

another contract can be tricked to call back into its own function before the condition of its

state are updated from receiving the response to the message sent to the other contract.

Attacker usually exploit this vulnerability in a smart contract to steal funds stored in the

contract. In order to avoid this situation a developer need to properly implement the correct

ordering of the conditions-effects-interactions steps in a smart contract.

● Call-stack limit: this situation happen whenever a contract invokes its own function or a

function from another contract causing the associated call stack for these transactions to

grow faster reaching one gigabytes frame. This can be exploited by an attacker to generate

a full call stack then invoke the victim contract function. A solution has been solved in the

Ethereum blockchain by changing the way gas price is calculated by limiting its amount.

● Immutability of a smart contract: when a smart contract is compiled and deployed on the

network, its code can no longer be changed or modified. Therefore, if any contract exposes

any vulnerability, they cannot be updated with a new version fixing the vulnerability in the

previous version. A good solution here will be to write a function within the smart contract

that can be call by the owner of the contract (The person or contract who deployed the

contract to the network) to replace any error within the implementation of the contract and

its dependencies.

● Time constraints: smart contract deployed on the blockchain network relies on the block

timestamp of the blockchain network to implement any time constraint required within the

contract. An attacker (in this case a miner since they have access to the block timestamp)

34

can take advantage of this vulnerability by manipulating and changing the timestamp of its

block and therefore alter the behavior of the contract.

3.2 Consensus Protocol

Blockchain technology requires a type of consensus mechanism to ensure its reliability, security, immutability, validity and the prevention of the double spending problem. In order to achieve this, blockchain developers have come up with different types of consensus algorithms with unique implementation protocol. There are multiple consensus algorithm in the blockchain universe. Let’s look at some of the popular consensus protocol.

3.2.1 Proof of Work

Proof of Work (PoW) is a consensus protocol mechanism used to validate transactions and confirm blocks on the blockchain platform. Every blockchain using this mechanism implement it differently based on their needs. Bitcoin was the first blockchain to come up with this consensus protocol. Bitcoin’s Proof of Work algorithm uses the SHA-256 hash algorithm to implement their consensus protocol while Ethereum uses Ethash for their own Proof of Work implementation.

Mining nodes on the network create blocks by collecting every transaction broadcasted on the network since the confirmation of the last created block. The miner (mining node) then add transactions into a newly created block until the required size of the block is reached, and then compute the proof of work on the block to confirm and add it to the main chain of blocks on the network. The computation process consists of generating a random integer called the nonce with the goal to generate a value of a hash of the current block in combination with the block’s header.

35

This generated value has to be smaller than the predefined targeted value. The targeted value during the block mining is different for every newly created block and its value is adjusted dynamically based on the current total hashing power of the entire network. On the Bitcoin, this target value is adjusted to ensure that a new block is created every 10 minutes. This mining process makes it very difficult for a single node to alter the state of the blockchain. A node can alter the state of the blockchain only if they control the majority of the entire blockchain network mining power. This situation is called the 51% attack. Even though every miner can create new blocks, only the first miner to find the target value is able to add the new block on the main chain and only the longest chain on the blockchain is accepted and broadcast to all the nodes on the network for them to update their local copy of the chain. The miner that succeeds to find the nonce and add the newly created block on the blockchain is rewarded with a certain amount of coin. This is how new coins are created. Proof of Work is very inefficient and very expensive even though it assures the security of the blockchain. It requires miners to have hardware with higher computational power and lot of energy to perform complex mathematical computations to find the nonce. This situation can lead to centralization since miners with higher computational power hardware can control the network. Proof of Work has been criticized on its environmental impact in energy consumption.

3.2.2 Proof of Stake

In order to solve the environmental impact produced by the Proof of Work consensus algorithm, blockchain developers came up with a new consensus algorithm called Proof of Stake (PoS). Proof of Stake does not involve mining activities. Nodes on the network that validate transactions are called validators instead of miners as is the case in Proof of Work consensus protocol. In order for

36

a node on the network to be validator, they should own a stake in the network in the form of a security deposit or . Every node on the network that wants to be a validator makes a security deposit. The more you deposit as security the higher your chances are for being selected to create the next block. When the block reaches a certain height, the Proof of Stake algorithm randomly selects a node and give it the right to create the next block. Other non-chosen nodes who are validators then vote to confirm the newly created block. The weight of each validator vote is proportionate to their security deposit. Each vote is then broadcasted to the other validators and they come to a consensus to confirm the newly created block. The Proof of Stake built-in incentive mechanism for validators is in such a way that a validator gets rewarded for voting for the confirmation of the newly created block and lose their security deposit if they choose to vote against the newly created block. If a validator tries to vote for a bloc with invalid transactions in it, they will lose their security deposit and the right to ever vote on any block in the future. Proof of Stake consensus does not require higher computational power hardware and does not consume a lot of energy compared to the Proof of Work consensus algorithm. it is considered eco-friendly, it does not involve mining therefore even a node with a small computational power can participate and earn rewards. It is faster to confirm blocks using Proof of Stake protocol and centralization risk is very low or even non-existent.

3.2.3 Proof of Authority

In the Proof of Authority (PoA) consensus protocol, a certain set of nodes are granted the ability to create new blocks by verifying transactions and ensuring the security of the network. These selected set of nodes are known as authorities. Even though the consensus protocol relies on these

37

trusted nodes, the transaction validation process is not different from the transaction validation process in the Proof of Work consensus protocol. Proof of Authority is considered to be an optimized version of the Proof of Stake. Instead of making a security deposit, authorities leverage their identity (reputation) as a form of stake in order to be selected in the small group that of nodes

(usually limited to 25 or less) to ensure the efficiency and security of the blockchain network. The

Proof of Authority consensus doesn’t require high computational power in hardware or higher energy consumption or any communication between authorities (chosen nodes) to reach consensus. Transaction time here is faster. But a major drawback of the Proof of Authority consensus is the authoritie’s selection process. The identity of the authority must be identified on the blockchain making them not anonymous. The eligibility process is very difficult to satisfy because the authority needs to have and maintain a clear reputation. This selection process makes the Proof of Authority consensus protocol to suitable for private blockchains, not public.

3.2.4 Others

● Delegated Proof of Stake: the node with the greatest security deposit is selected to create

the block and has the power to select nodes that will verify transactions and confirm the

newly created block.

● Proof of Capacity: the node who created a new block is selected based on their hardware

storage capacity.

● Proof of Burn: the node who created the new block is selected based on the amount of coins

they owned in their wallet and which they cannot recover.

38

● Proof of Activity: this consensus algorithm uses the combination of Proof of Stake and

Proof of Work consensus to ensure that the reward points of the miners are allocated

properly and on time.

● Proof of Elapsed Time: this consensus protocol is very similar to Proof of Work consensus

protocol, but the only difference is that this protocol focuses more on the consumption.

39

Chapter 4 DECENTRALIZED APPLICATION AND DECENTRALIZED AUTONOMOUS ORGANIZATIONS

4.1 Decentralized Applications (DAPPS)

4.1.1 Introductions and Definition

Decentralized application (DApp) is avery new concept introduced to the world by the proliferation of the blockchain technology. Decentralized applications are not known by the masses opposed to the traditional web applications that are used more often in today’s world by businesses, organizations and individuals. A Decentralized Application (DApp) can be thought of as a new model and technique for developing applications that are viewed as lucrative and promising for the direction in which technology is heading in the future. The majority of web applications that exist are built using a centralized model. They are built and deployed on servers and are controlled by a single company. These types of centralized architectural applications were the standard until blockchain technology was introduced to the world by Satoshi Nakamoto in

2008. Decentralized applications are deployed and run on the blockchain network and are backed by one or more smart contracts. There is no single organization controlling the infrastructure on top of which the application is deployed. Decentralized applications provide a user-friendly interface for users of the blockchain to interact with smart contracts running on the blockchain.

Decentralized applications are controlled and maintained by the users that are participants of the decentralized network which host the application and involve trustless protocols. Data and records of the decentralized application are stored on the blockchain on which the application is deployed.

These data and records are public and therefore accessible by any participants of the blockchain.

They are encrypted and protected by cryptographic algorithms that prevent users from identifying

40

which data belongs to who even though they have access to it. This show transparency and democracy and in the application development and consumption process. The interface of a decentralized application is deployed on the server. Users of the decentralized application use the interface to send transactions to the smart contract hosted on the blockchain network. The smart contract then processes the transaction and returns the state of the transaction to the web interface which displays it to the user. Decentralized applications are accessible through a web browser just like a traditional web application.

4.1.2 Architecture

Decentralized applications are no more than a web client calling either a smart contract or anything else in the blockchain. Compared to the traditional web application, the blockchain is playing a server role, except it’s not central at all, but rather a copy that replicates to all nodes (machines).

A centralized application can be visualized as a point or node acting as the central entry point with edges extending outward which leads to numerous nodes. Even though this model is globally recognized and utilized, the concept shouldn’t be thought of as the best practice especially when it comes to security. Services such as PayPal or Amazon make its users rely on this centralized structure of receiving and sending data back and forth to the centralized points. Even though they might have multiple servers around the globe running application, there is only one central entity controlling all those servers. Decentralized applications can be visualized as a collection of nodes with extended edges leading to different nodes. No node is directing any other nodes with regard to instructions. Each node on the network run a copy of the network state and listen to the broadcast of any new change of network state and then updates their own state to be in sync with the entire

41

network. These records are immutable and essentially impossible to hack into considering they are maintained on a distributed ledger that is public. Decentralized applications can be thought of as a front end to smart contract for the blockchain. The smart contracts are utilized by decentralized applications to execute commands and retrieve data from the blockchain.

Figure 4.1: Decentralized Application Structure.

4.1.3 Advantages and Disadvantages

Typically, most technologies possess advantages and disadvantages. Decentralized systems allow business to experience healthy growth overall. The elimination of decision making is distributed which allows more focus on the company’s true goals and visions. Decentralization allow thhe collection of people within the company from all levels to concentrate on the enterprise’s development process. Decentralization also keeps organizations honest and transparent which allows their customers to feel comfortable and at ease when it comes to being affiliated with the company and what it has to offer. Pinpointing where problems exist, and where requirements are

42

needed become easier. Because they are distributed, there is no single point of failure.

Decentralized Applications are more scalable due to the fact that they are deployed on the blockchain. Because developers cannot make alterations to the code, a usefulness is being delivered to the application which every user can take advantage of. Another benefit of decentralized applications are the stability they bring when it comes to crashing due to technical errors. The availability is consistent and remains accessible through all times due to the peer to peer network. The smart contracts discussed previously establishes amongst its users a sense of reliability, assurance, and security from hacking. In a day and age where centralized establishments such as banks have lost their appeal to the newer generation due to crashing markets and down times, decentralization takes away the authority of a centralized application by stripping the control factor and decision making. This also makes the decentralized application faster and safer to use.

Figure 4.2: Web Application VS Decentralized Application

43

The disadvantages of Decentralized applications revolve around the fact that fixing bugs in decentralized application can be very difficult due to a massive number of users having to update the software of the node and the fact that when a smart contract is deployed on the blockchain network it cannot be modified. Verification can be an issue with some applications but not all.

Verification of a user’s identity due to the lack of central authority can become an issue during the development of decentralized application. Being deployed on the blockchain means that the decentralized application cannot be taken down from a network unless the entire network is terminated. Lastly, decentralized applications can be very difficult to develop due to the protocols being more complex. Later additions of features are very difficult to add on while maintaining scalability. The pros outweigh the cons when it comes to decentralized applications [3]. The technology, itself, is finding its ways into the homes and phones of users. Time is usually the determining factor when talking about the existence of newer technology becoming the most dominant. As the news about blockchain becomes more customary, decentralized applications will be the more desired application. The concept of eliminating third parties and the mentality of the newer generation run parallel. Security and lower costs will eventually win over many once the options are more popular.

4.2 Decentralized Autonomous Organization (DAO)

4.2.1 Introduction and Definition

The centralization of power of organization in the hands of an individual in the current system has become very problematic over the year. We have seen CEOs of big company making bad decisions

44

that hurt the company reputation and financial status and they were never held accountable for those decisions. For instance, the Wells Fargo bank fraud of 2015 that led the CEO to step down with a good severance package but was never held accountable for the chaos he created. This type of situation not only hurt the company but also all its stakeholders. There is new way of managing organization now where all stakeholder participates in the decision-making process in the company. There is a new form of organization that is gaining popularity thanks to the proliferation of the blockchain technology. Decentralized Autonomous Organization (DAO) is a management of an organization using blockchain technology. It takes the traditional concept of managing organizations and decentralizes it. This is done by implementing a very complex smart contracts to handle the activities of the organization. Rules and policies of the decentralized autonomous organization are embedded in the code of the smart contract that govern the organization. The governance rules of the organization are token based. Decentralized autonomous organizations activities are coordinated through a system of distributed consensus protocol. The use of the legal system by the decentralized autonomous organization to protect its physical properties is not a primary concern. A smart contract deployed on the blockchain can allow the organization to control and manage its assets such as buildings, vehicles and even liquid assets.

There is a smart contract of the organization that hold the records of all the shareholders of the organization and the set of rules allowing them to select members of the board of directors and employees for tasks of the organization that cannot be autonomous. Decentralized autonomous organization are open source, transparent and incorruptible.

45

4.2.2 Architecture

Decentralized Autonomous organizations don’t have a hierarchical governance structure like the traditional system. There are no executives or management team running the organization. Some of the characteristics of a decentralized autonomous organization are:

● Autonomous: Once the smart contract governing the organization is deployed on the

blockchain network, it become independent of its developers and cannot be influenced by

any outside entity. Its rules, financial records and transactions are controlled and

maintained by the blockchain and therefore eliminate the need of a middleman.

● Consensus: Stakeholders of the organization must come into an agreement for any

decision-making process within the organization. This is done by vote of every single

stakeholder and the majority win.

● Tokens of transactions: there is a token built into the decentralized autonomous

organization as a form of reward mechanism for activities within the organization. This

token is the internal property of the organization and is funded at its deployment on the

blockchain network.

● Voting: Every proposal made to the organization and any decision making goes through a

voting system where the proposal or decision making with most votes is adopted.

● Proposals: within a decentralized autonomous organization, the primary form of decision

making is made by proposal which then must go through a vote from its stakeholders and

adopted if it gets the majority of the votes.

● Contractors: Decentralized autonomous organizations go voting system to select

contractors in order to achieve its goals.

46

4.2.3 Advantages and Disadvantages

Advantages of decentralized autonomous organizations include: maximum automation, minimal costs considering there are no cost for employees or administration, which means the work is automated for companies. Contractors from the community come from different areas of the world giving many perspectives and allowing flexibility to work from around the world. The

Decentralized Autonomous Organizations can exist, but it doesn’t need a physical location that allows it to be anywhere in the world. Although changes may come in the future but as of now, laws and that are deemed complicated by companies are eliminated when it comes to a

Decentralized Autonomous Organization. They are reliable organizations due to the users relying on the system in place to act justly. The system is also evolving continuously which brings confidence of consistency to its members. The disadvantages include errors happening by humans who are developing the program. The system is implemented by smart contracts which can have errors from the developers. The risk lies in the fact that the blockchain and smart contracts can be executed on these vulnerabilities.

47

Chapter 5. CROWDFUNDING

Crowdfunding is the practice of raising money from a large number of sources to accumulate into a more substantial sum, usually through the Internet. As crowdfunding is a form of alternative finance and sourcing through multiple units of minute values, scholars have researched crowdfunding both as an innovative alternative mode of funding and as a source of financing for creative ventures and out-of-stream enterprises [12]. This decade is an era of blockchain and crowdfunding. The ever-growing crypto market comprises of a distinct and new set of entrepreneurs and . As the newly emerged ecosystem of the economy appears, significant disruptions occur, affecting the traditional method of payment and also influences the banking industry [10]. Digital cryptocurrencies which revolutionize internet transactions such as; Bitcoin,

Ethereum, etc. are bringing in new archetypes for fund transactions and of course, serve as alternative means of making money.

This section aims at elaborating crowdfunding of cryptocurrency in relation to its traditional models, merits, and disadvantages.

5.1 Traditional Model of Crowdfunding

Since the year 2008, the crowdfunding of cryptocurrencies has been developing into small units, but its impact hits the global market. Crowdfunding of cryptocurrency was estimated in the year

2014 to have accumulated to about three billion euros in transactions [18]. Crowdfunding gives room for people to collect resources and gather fund for; projects, and other purposes.

Crowdfunding’s traditional platforms were created to provide a personal fund-raising domain of

48

standard service for direct family or friends. This gives room for quick set up of a page which is easy to use. There are several traditional models of crowdfunding today such as; GoFundMe,

GoGetFunding, Razoo, , Kickstarter, etc.

● GoFundMe

This is a traditional means of crowdfunding certified by public bodies such as The New York

Times, Forbes, CNN, TIME, etc. GoFundMe is one of the most popular sites used for crowdfunding. Fund can be raised for any purpose on GofundMe and is not limited to family and friends only. This platform creates the opportunity to leverage people seeking to contribute to one’s community to a smaller cause instead of a global cause. It also offers user-friendly interface which is simple enough for anyone wishing to be involved in crowdfunding.

● GoGetFunding

This is another platform which aid people the raising of funds for a lot of causes, (events, personal, projects, etc.) GoGetFunding has features which ensure that individuals raise the closest amount of the fund to the actual amount needed. GoGetFunding is a platform recognized by a lot of people.

● Razoo

Razoo was initiated with the idea of providing money for underfunded people in dire need of a fund and to facilitate the funding of underfunded non-profits. Razoo grew into one of the largest crowdfunding platforms which focus on charity. The central theme of this crowdfunding platform is; “We combine social power, community drive, a swift checkout process, and beautiful design to give you the most comprehensive soapbox to stand on. How you use it is up to you.” Razoo sustains the community mindset of charity and give low fees.

49

● Fundly

Fundly gives room for the creation of online for almost any cause, it also includes volunteering. Fundly caters for the community, which is somewhat referred to as their strength. It is, however, a free service which gives an open technology which transmits essential activities. Fundly allows the import of contacts, enable the exchange of communication with family and family, and also will enable the customization of email templates.

● KickStarter

This is an American corporation in New York, (Brooklyn) which serves a public benefit of crowdfunding on a global scale and focuses on merchandise and creativity. KickStarter’s motto is known to be "help bring creative projects to life." This draw individuals to pull fund for their public benefit via Kickstarter.

● ICOs

ICO ( is a crowdfunding platform which uses cryptocurrencies. However, private ICO's have become very popular. An amount of cryptocurrency in an ICO is valued as

‘token’ especially to investors or speculators in exchange for other forms of tender. The tokens are promoted and sold as functional units of currency. In instances where Ethereum (ETH) is involved, the system is required for the token’s purpose(s) Initial Coin Offering is a means of funding for start-up enterprises. ICOs give room for startup enterprises to bypass compliance with intermediaries and regulations such as; stock exchanges and banks [13]. ICOs can be regarded as a platform which is not precisely within the traditional regulations [11]. This instance depends on the type of commitment (project) and is banned completely in some jurisdictions, some of which are; South Korea and China.

50

● OpenIDEO

This is a unique crowdfunding platform because it does not only serve as a crowdfunding platform, it also operates based on the belief that the hands of many will shape and put the future where its supposed to be, via . Participants are allowed to use OpenIDEO as a means of development of cause. Individuals also get feedback from the community which can be used to develop the projects. And by allowing this not-so-easy process, the project/cause will be enabled to get a devoted following as it develops. The OpenIDEO is made up of people around the globe with about eighteen thousand projects and ideas empowered worldwide.

● Exponential, Inc.

Exponential Inc. was founded by a French-American entrepreneur known as Dom Einhorn. XPO2 is a known to be a revolutionary platform of crowdfunding. Exponential Inc. aids SMEs, nongovernmental organizations and nonprofits nongovernmental organizations in gathering funds.

XPO2’s platforms are easy to use and free, thus providing access to a broader audience and a more significant number of contributors to funds the NGOs. This platform has helped many organizations including; Morani Preserve and Research Center Laikipia in Africa and The Bully

Rehab Awareness Program (US). The XPO2’s contributions (cashless) optimizes special browser extensions which enable users to contribute to a non-profit cause of their choice. This is done by checking retailers which XPO2 partner with. The retailers are well-developed brands such as;

Walgreens, HSN, etc.

XPO2 recently increases its scope by launching a crowdfunding campaign based on rewards to reach five hundred thousand dollars per project. It also caters to both non-materialistic and material contributors. The platform ensures that funds contributed goes straight to the NGOs intended.

51

5.2 Other Crowdfunding Means

There are different crowdfunding means apart from the traditional methods which are known as

Social Crowdfunding Platforms. Most of the social crowdfunding means gather fund for social causes, not necessarily for project or business-enterprise. Some of these social means of crowdfunding are; YouCaring, FundMyTravel, etc.

● YouCaring

This crowdfunding platform concentrates on keeping costs at the bare minimum. YouCaring aims to offer utterly free funding thus enabling individuals to support charitable or personal causes worldwide. YouCaring is dedicated to offering help to the majority, as a charity means.

● FundMyTravel

FundMyTravel is a known to be a unique crowdfunding website which solely funds travelers.

FundMyTravel gives free and easy access to an extensive Fundraiser’s Toolkit which gives detailed information on how to start a fundraising campaign and ensure success. FundMyTravel was initiated with the primary goal of increasing financial support to individuals who desire to volunteer, study, or travel abroad for other purposes.

● Generosity by

This is a crowdfunding platform for socially minded causes and human kindness projects in which no significance is placed on the scale or size. IndieGoGo was developed for the sole purpose of creating a community catered for. IndieGoGo's usual statement is “the very people and causes that

52

often need help the most. The ones that fall through the cracks, The ones that need a second chance,

The ones on the brink.”. This is the motivation behind giving fund to those who need it the most

● StartSomeGood

StartSomeGood is a website which concentrates on social change and initiates support for non- profits, social entrepreneurs, and community groups at large. StartSomeGood aims to grant funds to an individual struggling to make the earth a better world to live in. Crowdfunding on

StartSomeGood start by the submission of the project to the organization, if the project is approved, the organization (StartSomeGood) will work as a partner with the individual or group throughout the process, till the page is up and running. However, It may take a long time to get it started, but the wait is no problem compared to the efficiency of the organization’s experts on crowdfunding.

5.3 Merits of Crowdfunding

As Crowdfunding is known to facilitate the funding of projects through cryptocurrency, its perks cannot be over highlighted. The followings are some of the benefits of crowdfunding of cryptocurrency;

● It is one of the fastest ways to raise fund without collateral nor prior fees

● Pitching a business idea through an online platform is an incredible form of creating media

attention for marketing.

● Getting feedback to enable guidance from feedback, thus inducing improvement.

● Crowdfunding of cryptocurrency allows project coordinators and individuals to test the

reaction of the public to a product or idea

53

● Online crowdfunding gives investors the chance to monitor progress.

● Ideas which may not easily get funding via conventional means will get funding through

crowdfunding of cryptocurrency.

● It gives room for investors to become regular customers, thus inducing further investments.

● Crowdfunding of cryptocurrency is an alternative means of funding and is much easier than

bank loans.

5.4 Disadvantages of Crowdfunding

As alluring as crowdfunding of cryptocurrency is, there are some downsides to it. Crowdfunding websites cannot guarantee the completion of projects funded on their sites. This, however, gives room for fraud. Crowdfunding of cryptocurrency on many occasions are unable to live up to the promised plan. This happens when the platforms leave investors (backers) with disappointment and of course reduced pockets.

Crowdfunding of cryptocurrencies will not necessarily be a more straightforward process to go through compared to the more traditional ways of raising finance as not all the projects registered to crowdfund platforms eventually get onto them. Also, individuals need to go through the hurdles of persuading people to develop an interest in the project launched. This procedure, however, is time-consuming and can be discouraging.

Crowdfunding of cryptocurrencies might not eventually work out as planned because, if the project coordinator does not attain the fund budget, any pledged or contributed fund will be returned to the respective investors, and the project coordinator eventually receives nothing.

54

Also, failed projects increase the risk of damage to the reputation of one’s business, the platform and reduces the interest of investors. This gives room for the copying of ideas and might be funded to someone else’s advantage. Crowdfunding of cryptocurrencies also allows giving away too much of the business to investors.

Crowdfunding of cryptocurrency is a 21st-century innovation which aid fact accumulation of fund, and of course comes with numerous perks such as access to the ready crowd, a collection of funds in tiny bits which does not have to stress anyone, and the security provided by the Traditional

Model Platforms. However, the disadvantages of it when evaluated cannot be easily ignored as it gives room for fraud and comes with some other downsides. Traditional models of crowdfunding which enable the contribution of tokens of cryptocurrency, limit fraud which associated with crowdfunding as they are responsible for financial activities

55

Chapter 6. DESIGN AND IMPLEMENTATION OF DECENTRALIZED CROWDFUNDING

APPLICATION

The purpose of this chapter is to describe the design and implementation of the decentralized crowdfunding application.

6.1 Business Model

The business model of this application is to provide a crowdfunding application platform where a verified user can create a crowdfunding campaign and seek contributions from users of the application. Using the cryptocurrency that is built in the application, users should be able to raise money at minimum cost and in a very short amount of time. Users can buy the built-in cryptocurrency using fiat currency and are also able to convert that cryptocurrency into a fiat currency after the fund-raising event has ended.

6.2 Structure and Functionalities

The functionality of the application is quite simple. Using a wallet, a user that needs to raise money for a cause needs to submit a campaign on the website. The campaign itself have a title, a brief description, the deadline and goal which is the amount the campaign is wishing to raise. The application has sections where users are able to buy the built-in tokens and use those tokens to contribute to the crowdfunding campaign they want. The creator of the campaign is able to

56

withdraw funds contributed by users only if the goal of the campaign is reached after the deadline.

A campaign is allowed to collect more funds that the intended goal.

6.3 Technical Tools

The principal tool we are going to use to scaffold the application is Truffle. Truffle is a framework that facilitates the decentralized application development configuration and settings. According to the truffle framework website, truffle is a development environment, testing framework and asset pipeline for developing decentralized applications on blockchains using the Ethereum virtual machine (EVM) [29]. The truffle framework allows us to write smart contracts using the Solidity scripting language and HTML, CSS and JavaScript for the client side of the application. We are going to use VueJS framework for the client side. VueJS is a JavaScript web client framework. In order to speed up the development process and interact with a local blockchain installed on our computer we are going to use Ganache from the Truffle suite framework. Ganache is a personal blockchain environment running on your personal computer for Ethereum development. It is used to develop, run, test, and deploy smart contracts. It is available as both a command line tool and desktop application. We are going to use Google’s NoSQL database called Firebase to authenticate and store users’ information. We are going to use the Chrome Metamask extension as a wallet to interact with our decentralized application. The Ethereum’s browser integration development environment, called remix, will be used to write the smart contract and compile it in real time. We are going to be using the Web3JS library, which is the Ethereum JavaScript API, to interact with all the contracts of our application deployed on the Ethereum blockchain platform

57

6.4 Implementations Guidelines

First step is to use the remix IDE in the web browser to write a first smart contract to issue the built-in token on the Ethereum platform. The second smart contract will allow a user with an account address to be able to purchase the built-in token. The user will be also be able to transfer the token to another user. The third contract will be the Crowdfunding campaign contract for the user to create a campaign for a particular cause. The last contract will be a special contract that facilitates the creation and deployment of crowdfunding campaign contract on the blockchain network.

Using the truffle framework, I am going to create the crowdfunding project. Using the Solidity compiler to generate a JSON file containing our smart contracts functions and state variables that are used by the Web3JS library to communicate with the smart contract on the blockchain. The output of the compilation returns the address of the smart contract. This address is used to access the functionality of the smart contract on the blockchain.

• Prerequisites:

o NodeJs version 6 or higher

o VueJS version 2

o Truffle version 4 or high

o Metamask installed in your Chrome or Brave browser.

o Ganache GUI or CLI or any other Ethereum network running on your computer.

• Installation

58

o Nodejs can be downloaded from their website nodejs.org; choose the right

package for your operating system. It also installs the NPM which is a package

manager for NodeJS packages. An alternative to NPM is Yarn. Yarn is much

faster than NPM and can be installed on your operation system globally with

administrative privileges. These commands are on a MacOS computer.

o Install truffle globally with the following command

o Create an empty directory in your computer and go into that directory

o Run the following command to create a project using truffle. Make sure the

directory is empty before running the command. o The above command will create a scaffold for your project with the following

directories

▪ Contracts: this directory stores all the smart contracts of the project.

▪ Migrations: this is where deployment script files are stored.

▪ Test: this directory contains test files.

▪ Truffle.js: this is the configuration file for the project. o Next step is to configure a blockchain connection by adding the network

configuration into the configuration file. In this case, add the host, port number,

and network Id from ganache into you truffle.js file.

▪ Download the Ganache GUI from the truffle framework website and

launch it.

59

▪ Open the project into the text editor of your choice.

▪ Go into the truffle.js file and add the following

▪ Developers on a Windows computers need to copy the same content of

truffle.js into truffle-config.js

▪ The host and the port can be found on the ganache GUI

• Smart contracts development

The use of the remix IDE is optional but is a good practice for syntax errors highlight and compilation errors in real time. Using the remix IDE gives options to test the behavior of your smart contract in the browser. You can deploy it on the blockchain running in your Chrome or

Brave browser and interact with it. You can also connect to your Metamask from the remix IDE and send transactions (Not recommended in case you have some real ether in your account, you might lose them). On the Run tab of the remix IDE, choose JavaScript VM from the dropdown of the environment (this step is very important because if you are logged into your Metamask, it will automatically select that option).

60

Figure 6.1 Remix IDE Environment

61

We are going to use Solidity to write our smart contracts code. You can also use other programming languages but the most popular and widely used language to write smart contract on the Ethereum platform is Solidity. Before writing any contract, choose the right Solidity compiler in the IDE compiler section and in your smart contract. The first line of the smart contract should be `pragma solidity ^0.4.22`. The number 0.4.22 represent the version of the compiler that will be used to compile the code. This is very important because the language is still in development, and new syntaxes are being introduced, and the structure of the contract changes.

The first smart contract is the token contract. Is the smart contract that allows the creation of a token for the crowdfunding application. These tokens will be used to fuel operations on the application. Collection of funds in a crowdfunding campaign is based on these tokens. Users can only contribute to an active campaign using these tokens.

o Token contract

▪ The token smart contract has a list of state variables

• Owner (address): Hold the address of the account that deploy the

contract on the blockchain network.

• Name (string): The name description of the token be created.

• Symbol (string): Symbolic representation of the token.

• Decimals (uint): The most common number of decimals place.

This is relative to the value of ether.

• CurrentBalance (uint): Keeps track of the current balance of the

account.

• TotalSupply (uint): The number of coins being created when the

contract is deployed on the network.

62

• BalanceOf (mapping): represents the balance of each individual

account.

• Allowance (mapping): represent the permission of an account to

spend coin on behalf of another account.

▪ Constructor

• Special function that is run once when the contract is created or

deployed on the network.

▪ Functions

• GetBalanceOf (function): return the balance of an address.

• Transfer (function): allow a user to transfer tokens to another user.

• TransferFrom (function): allow user transfer token to another user

using another user’s account and balance.

• Approve (function): approve an account to spend tokens on behalf

of another account.

▪ Events

• Transfer (event): notify light client of the transfer event in the

contract so that they can react to it efficiently.

• Approval (event): notify the light client of the approve event in the

contract.

63

Figures 6.2 Token Smart Contract

64

The second smart contract is the TokenSale contract. This contract allows the distribution of the tokens created. For a user of the crowdfunding application to donate to an active campaign, they need to possess the token that is used for the operations of the application. The token is bought using the TokenSale contract. The user sends an amount of ether to the TokenSale contract and receive the number of tokens proportionate to the amount of ether they sent and based on the value of a single token. The value of the token is set when deploying the TokenSale contract. This value can be changed in the future by the owner of the TokenSale contract.

o TokenSale Contract

▪ State variables

• Owner (address): The person that deployed the contract.

• Token (Token): Token to be sold.

• TokenPrice (uint): Price of the token.

• Sold (uint): Number of tokens sold.

▪ Functions

• Helper (function): Helper function to safely compute the amount

required for the number of coins being bought.

• BuyToken (function): Function to buy the token.

• SetToken (function): Set the token price. Only the owner of this

contract can call this function.

• EndSale (function): End the sale of token; can only be called by

the owner of the contract.

▪ Modifiers

65

• OwnerOnly (modifier): Restrict the accessibility of the function.

Can only call the function that has a modifier when certain

conditions are met.

▪ Events

• Sell (event): Notify the client of a sale event

Figure 6.3 TokenSale Smart Contract

66

The third smart contract is the crowdfunding contract. When deployed on the blockchain, the crowdfunding holds the instance of one campaign. This smart contract collects tokens from contributors as a donation. The only token allowed in this smart contract is the token created earlier.

o Crowdfunding contract

▪ State variables

• Owner (address): Owner of the contract or the person who deploys

the contract on the network.

• Goal (uint): Number of tokens the creator of the campaign is

looking to raise.

• Raised (uint): Number of tokens raised.

• Token (Token): Token used to raise money.

• Title (string): Title of the campaign.

• Description (string): Description of the campaign.

• Deadline (uint): Deadline of the campaign.

• Closed (bool): Status of the campaign to check if it is closed or it is

still active. This value is updated when the funds are sent to the

receiver of the campaign.

• Reached (bool): Check if the goal of the campaign is reached.

• Complete (bool): Set the status of the campaign as complete.

• NumberOfContributors (uint): Keeps track of the number of

contributors.

• Receiver (address): Address of the receiver of the funds collected

during the campaign.

67

• Donation (mapping): Keeps track of the amount donated by each

address.

• Contributors (mapping): Keep track of all the contributors.

▪ Functions

• Constructor (function): Call to deploy the contract on the network.

• SendMoney (function): Call when sending money to the campaign.

• SendFund (function): Call when sending the fund collected to the

receiver.

• CheckGoal (function): Check if the goal of the campaign is

reached.

• GetCampaignDetails (function): Return information details about a

campaign.

▪ Modifiers

• OwnerOnly (modifier): Restriction to allow only the owner of the

campaign to perform certain task.

• CompleteCampaign (modifier): Restriction to perform a task only

if the campaign is completed.

68

69

Figure 6.4 CrowdFunding Smart Contract.

The last smart contract is the Campaign contract. Since only crowdfunding can be deployed at the time, there should be a way to deploy multiple crowdfunding campaign on the blockchain.

The role of the Campaign contract is to facilitates the deployment of multiple crowdfunding contracts on the blockchain. It also keeps tracks of all deployed crowdfunding campaigns.

o Campaign contract

▪ State variables

• ActiveCampaigns (address []): Array of addresses of all active

campaigns.

▪ Functions

70

• CreateNewCampaign (function): Function to deploy a new

campaign instance on the network.

• GetActiveCampaigns (function): Return an array of all active

campaigns.

Figure 6.5 Campaign Smart Contract.

Deployment

• After testing the contract and its behavior in the remix IDE, it is time to deploy the contract

on the test network running on the computer.

• Create 4 files representing each of the smart contracts written in remix IDE in your

contracts folder directory

71

• Copy the smart contract code written in remix IDE and paste in the appropriate file.

• Create a new migration file in the migrations folder.

• Write the deployment script for our smart contracts in that file.

• Import the “Token.sol” and “Crowdfunding.sol” files in the “Campaign.sol” and

“TokenSale.sol” files accordingly.

• Run the command to deploy the contract

• If the deployment is successful you get the following output:

72

• This operation will generate a build folder in the root of the project folder. It contains a

contracts folder with the JSON file of the all the contracts deployed on the network. These

files contain the compiled code of the smart contract and other information related to the

contract

• Copy the address of each contract from the terminal when you migrated your contract into

a file and save.

73

• Next, we are going to write a test for the token deployment.

• Create a file called “Token.js” in the test folder of our project.

• Write the code to test the deployment of the coin on the network and if the initial supply is

properly set.

• After writing the code to test the smart contract run the command

• The output of the token test will be:

74

• Follow the same process to test other smart contracts.

With the truffle framework, you have a choice of writing your test in Solidity or JavaScript.

Truffle uses the Mocha framework for testing and the Chai framework for assertion. The only difference from regular testing is that instead of using “describe”, truffle uses “contract”

6.5 Client Application

The client side of our decentralized application will be developed using the VueJS framework.

VueJS is an open-source progressive JavaScript web client framework for building nice and smooth looking user interfaces for web application. VueJS is designed to be incrementally adoptable and its integration into other web applications using JavaScript libraries is very simple.

It is approachable, versatile and has high performance. It is a great tool for building progressive web applications and single page web applications.

• Run the command to install VueJS globally. The VueJS installation command line on

MacOS is:

• Run the command to create a VueJS project:

75

During the settings choose vue-router and vuex options. To avoid having issues with the path of files I suggest moving all the folders and files created with truffle into the root folder of the VueJS project. Let’s add a couple of NodeJS packages to help us with the development. We are going to install the firebase package. That is also going to allow us to authenticate the user.

• Install firebase, ethers, and the specific version of web3JS

• Create a project on firebase and copy the API keys.

• Open the main.js file in the src folder in the root of the project and add the following line

of code.

Replace the config object with the one you copied from your firebase project. There is a sweet alert package for vueJS that can be found on the npmjs.org. It is used to set up notification. You can use any User Interface or CSS framework of your choice. Let’s look at the code to interact with the smart contract on the blockchain. I will suggest creating an account on the infura.io

76

platform to see how the application will behave when deployed on the real blockchain network.

After creating an account on infura.io, create a project and the API key for the rinkeby test network. That API key will be required for the web3JS provider configuration. You also need the mnemonic you were given when you created an account on Metamask.

• Create a folder called ‘dapp’ at the root of your project. This is where we are going to add

all the logic to communicate with the blockchain network.

• Create a file in dapp folder call web3js and write in the following code

• Replace the INFURA_KEY environment variable with your API key from Infura.io

• Move the file with addresses from the root of the project into the dapp folder

• We need to get new addresses since we are going to deploy our contract on the rinkeby test

network.

• Open the truffle.js configuration file and add the following

77

• We need to install the two more packages with yarn ‘dotenv’ to handle our environment

variables and ‘truffle-hdwallet-wallet' to facilitate the connection to the blockchain

network.

• Create a ‘.env’ file at the root of the project and save in there your mnemonic from earlier

and the your infura.io API key.

• After the step above run the following command to get the new addresses of your smart

contract on the rinkeby test network and replace the addresses in the address file

accordingly.

• Create a folder called ‘services’ in the src folder.

• Create a file called ‘auth.js’ to handle the authentication of users the following code in the

file:

78

• Create three files named token.js, tokenSale.js, and campaign.js in the dapp folder. These

files return an instance of each contract. Paste the following code in each of the files

accordingly.

79

• Create a file crowdfunding.js that has a function that take the address of a crowdfunding

contract and return the instance of that contract.

• In the following section, we are going to write a couple of functions to interact with the

smart contract. Let assume that you have imported the right files and libraries used in the

function

• Create a welcome component in the components folder this represent the Welcome page

of the application. Create also a component to display a single campaign. I called it

‘ShowComponent.vue’

• Next captions are from the ‘ShowCampaign.vue’ component.

80

• The lifecycle function ‘mounted’ from vueJS uses the campaign address passed in the

component from the parent component to retrieve the campaign object from the blockchain

and display its details in the screen.

81

• The donation is called when the user clicks the ‘contribute’ button from the form to submit

a contribution to a campaign. This function uses the Token instance to call the ‘transfer’

function from the token contract and make a contribution to a campaign from the account

of the currently logged in user on Metamask.

• The moment library (need to be installed using yarn) converts the UNIX timestamp to a

human readable date and time and displays it on the screen based on the format you want

to display.

• Create a login and registration component to handle the user authentication with firebase

and also validate the login and registration inputs from the user.

82

• The following captions are from the register component. Same as the login component to

validate the inputs of the user. Register the user in firebase. Generate a random wallet for

the user and store in firebase’s firetore database. The ‘createWallet’ function uses the ethers

library to randomly generate a new wallet for a user when they register.

83

84

• Create a component call ‘Home.vue’. The user can only display this component when they

are logged in the application. These rules are implemented in ‘router.js’ file which contains

all the routes of the application. The content of the file looks like this:

85

86

• Here is the content of the ‘Home.vue’ component created earlier

• The lifecycle function ‘mounted’ uses the campaign instance to read all active campaigns

from the blockchain and passes their addresses to the ‘ShowCampaign.vue’ component

that displays them on the screen. This function reads the ether balance of the currently

logged in account on Metamask and display the balance on the screen. This function also

reads the token balance of the logged in account on Metamask and displays the balance on

the screen.

87

• The ‘send’ function is called when the user click on the send button to send token to another

user.

• The function pay is called when the user clicks on the Buy button on the screen to buy

tokens.

• The logged in users can also contribute to the campaign of their choice from the displayed

campaigns in the home page.

88

The development of the decentralized application was not as evident as previously thought due to some limitations in the framework I originally chose. For the client side of the application, I originally chose the Angular as framework, but the Angular framework was robust for the purpose of the application. The fact that Angular is built using TypeScript requires some configurations to consume all the third-party libraries used in the development. Angular provides server-side rendering but I didn’t want that because all the server side of my application is handled by the truffle framework. My next option was reactJS. React was a good choice at first, but I ran into some issues with routing in react. The way to get around these issues was to install NextJS package to handle server side rendering even though I didn’t need it, but also handle routing in the react application. Using NextJS library requires a lot of configurations. The best choice I found so far was VueJS. VueJS is a light weight framework and close to the JavaScript syntax and structure. It is easy to understand and has support for serve side rendering. It is component based. It is reactive and updates component as data change. It has support for routing. The documentation library is very detailed.

89

Chapter 7. CONCLUSION

Building a community crowdfunding decentralized application on the blockchain can bring a positive impact to our economy and generate benefits to our society and in our community. The potential of using this new application development approach rather than the traditional method for building application such as the community crowdfunding application is that it lowers the cost involved in running and maintaining the application and therefore stimulates the growth of the economy in the community and distributes wealth and value across the population. Its cost efficiency is based on the fact that a distributed application running on the blockchain network doesn’t require a middleman to handle transactions. Since the application runs on a trustless system, the risk of exposing sensitive information for potential attack is very low. Transaction fees in a decentralized application are very low.

The goal of this thesis was to explore blockchain technology characteristics and its impact on how applications are being developed using this new distributed architecture. I also analyzed the inefficiency of the traditional way of raising money through crowdfunding campaigns and platforms and explored the solution to not only use the blockchain technology to lower the fees collected by those traditional crowdfunding platforms but also by making it much easier for users to interact with those platforms and contribute to any crowdfunding campaign they wish at a very lower cost. The power of the smart contract running on the blockchain give the opportunity to anyone to launch a crowdfunding campaign on the decentralize application platform to raise money for a good cause. I explained how to develop a decentralized application on the Ethereum blockchain. I suggested the tools required to build a decentralized application. I analyzed different choices when choosing the right framework for the front end of the application.

90

REFERENCES

[1] - Nakamoto, S. (2008). Bitcoin: A peer-to-peer electronic cash system. Online Multimedia.

Retrieved from https://bitcoin.org/bitcoin.pdf

[2] - Monax - Solidity explainer: The Five-types model. (2016). Retrieved from https:

//monax.io/docs/tutorials/solidity/solidity_1_the_five_types_model

[3] - Understanding DApp’s: Decentralized Applications (2018). P. Chandrayan. Retrieved from https://medium.com/swlh/understanding-dapps-decentralized-applications-8f3668ebdc9a

[4] - The Byzantine Generals Problem (1982). Lamport, Shostak, Pease

[5] - Buterin, V. (2015). Visions, part 1: The value of blockchain technology. Retrieved from https://blog.ethereum.org/2015/04/13/visions-part-1-the-value-ofblockchain- technology/

[6] - Bahga A, Madisetti. (2017). Blockchain Applications, A hands on approach.

[7] - Size of the Bitcoin blockchain from 2010 to 2018, by quarter (in megabytes). Retrieved from https://www.statista.com/statistics/647523/worldwide-bitcoin-blockchain-size/

[8] - Smart Contract (1996). N. Szabo

[9] - Bashir I. (2017). Mastering Blockchain. Pub. Packt Publishing.

[10] - Braeden Anderson, “How blockchain and crowdfunding are revolutionizing traditional finance and ,” Published Author. NY Times Featured, 2018.

91

[11] - Carey Olsen, "Carey Olsen and JTC advise ARC Fiduciary Ltd on Jersey's first ICO,"

[12] - Djamchid Assadi, “Crowdfunding: democratizing networking, financing, and innovation,”

CEREN, EA 7477, Burgundy School of Business, Bourgogne University, Franche-Comté, France,

2018, pages 3-13.

[13] - Higgs, Stan, "Japanese Billionaire: ICOs; Democratize Venture Financing,” 2017.

[14] - Peter D. DeVries, “An Analysis of Cryptocurrency, Bitcoin, and the Future,” University of

Houston, Downtown (October 2016). Retrieved from https://www.researchgate.net/publication/316656878_An_Analysis_of_Cryptocurrency_Bitcoin_ and_the_Future .

[15] - Schueffel Patrick, “The Concise Fintech Compendium.” Fribourg: School of Management

Fribourg/Switzerland, 2017.

[17] - SEC, “Company Halts ICO after SEC Raises Registration Concerns," 2018.

[18] - Zhang, B., Rau, R., Gray, M., and Wardrop, R., “Moving Mainstream: Benchmarking the

European Alternative Finance Market.” The Journal of Financial Perspectives, December 2015,

Volume 3 – Issue 3, London. 60-77.

[19] - Emerging trends of the in 2018 and beyond (2018). Retrieved from https://www.marketplaceplatform.com/emerging-trends-of-the-sharing-economy-in-2018-and- beyond/

[20] - A next-generation smart contract and decentralized application platform . V. Buterin.

2014. weusecoins.com white paper.

92

[21] - 10 Interesting GoFundMe statistics and facts (October 2018). C. Smith. Retrieved from https://expandedramblings.com/index.php/gofundme-statistics/

[22] - Consensus Algorithms, Explained: What you need to know about proof-of-work, proof-of- stake, and delegated proof-of-stake (May 2018). J. Van Zwanenburg. Retrieved from https://www.investinblockchain.com/consensus-algorithms-explained/ [23] – Value of the decentralized consensus systems evaluation framework (2016). Brenig, Christian, Jonas, Nadine, Scwarz, and Ruckeshauser. [24] - Eclipse Attack on Bitcoin’s Peer-to-peer Network, USENIX Security (2013). Heilman, Ethan et al. [25] - Ethereum: A secure decentralized generalized transaction ledger. Ethereum Project Yellow paper (2014). G. Wood [26] - About Hyperledger (2018). Retrieved https://www.hyperledger.org/about [27] - Introduction to hyperledger business blockchain design philosophy and consensus (2016).

Retrieved from https://www.hyperledger.org/wp- content/uploads/2017/08/Hyperledger_Arch_WG_Paper_1_Consensus.pdf

[28] - EOS.io Technical white paper (2017). D. Larrimer

[29] - Truffle Smart contracts made sweeter (2018). Retrieved from https://truffleframework.com/

93