Author: Gerard Castell Ferreres
Advisor: Jose Luis Muñoz Tapia Barcelona
Barcelona, October 26, 2023
1
In today's digitalized world everyone and everything is connected through the Internet
Their processes use to:
1
Information governance problem
Generates a huge amount
of data
Companies govern the information management
Web 2.0
Web 3.0
The Internet and web applications play a main role in this interconnectivity between people and companies
Centralization
Companies have monopolized:
- User data
- Platform access
- Content distribution
Decentralization
Dapps offer a digital experience:
- Public
- Transparent
- User-centric
1
Web evolution
Dapps
Technological innovation
Growing desire of transparency and user control
Rethinking of traditional web limitations
1
Emergence of dapps
Decentralized applications are applications built on a decentralized network that run software programs and are accessed through a frontend user interface.
Blockchain
Smart contracts
Web application
1
Definition
1
Benefits of building dapps with blockchain smart contracts
Control Decentralization. No single authority controls the data.
Trustless Environment. Trust is distributed across the network rather than being concentrated in a single entity.
Censorship Resistance. Access to smart contracts is open and any single entity can censure their access.
Transparency. The transparent nature of blockchain allows the users to verify our data.
Data Integrity. Data stored is cryptographically secured, making it really challenging for anyone to corrupt.
Traditional and centralized digital product
1
Statement of purpose
Objective: Develop a dapp solution for replacing a centralized business case in order to harness the capabilities provided by blockchain and smart contracts.
Decentralized Application
Decentralized Application
Traditional and centralized digital product
1
Statement of purpose
convert to
Objective: Develop a dapp solution for replacing a centralized business case in order to harness the capabilities provided by blockchain and smart contracts.
1
Business case
Car insurance
Centralized server
Centralized model of car insurance
Drawbacks
1
Business case
Centralized model of car insurance
1
Business case
convert to
Centralized model of car insurance
Decentralized model
of car insurance
1
Business case
Decentralized model
of car insurance
Advantages
What do we need to know
to build the dapp?
Decentralized model
of car insurance
1
What do we need to know to build the dapp?
2
2.1
A blockchain is a way of building a distributed ledger where the transactions that modify the ledger’s state are sequentially and immutably ordered by consensus.
Definition
2.1
Block
State t
Chain
Node
Anatomy
2.1
A blockchain is a way of building a distributed ledger where the transactions that modify the ledger’s state are sequentially and immutably ordered by consensus.
refers to data that conforms the state
refers to each block referencing its parent
refer to the computers which shape the network
Nodes
Block
Chain
State t
Anatomy
2.1
Block: refers to data that conforms the state
Chain: refers to each block referencing its parent
Nodes: refer to the computers which shape the network
Nodes
Block
Chain
State t
State t'
State t''
Anatomy
2.1
State t
State t'
State t''
Permissionless
Permissioned
Hybrid
Consortium
Depending on who can participate in the blockchain we may classify them in four types:
Classification
2.1
State t
State t'
State t''
Permissionless
Ethereum
Bitcoin
Permissionless blockchains
2.1
State t
State t'
State t''
Permissionless
Alice
Bob
Transactions
Transactions
Ethereum
Permissionless blockchains
2.1
State t
State t'
State t''
Distributed Ledger
How do we identify senders in the ledger?
Alice
Bob
Authentication
2.1
Public Key Cryptography (PCK)
Alice
Bob
Each one of them has a key pair:
2.1
Digital Signature Authentication
Authentication is the act of proving an assertion, in this case, the identity of the sender which is represented by a public key.
Bob
Alice
Cypher
Digital Signature
Message
Signature
Message
Message
Decypher
2.1
Transactions
State t
State t'
State t''
Alice
All transactions are authenticated through digital signature, which means they can only be generated by the corresponding owners.
Ethereum
Transaction 1
Bob
Signature
Message
Signature
Message
Transaction 2
2.1
Consensus
State t
State t'
State t''
Ethereum
Transaction 2
Signature
Message
Transaction 1
Signature
Message
2.1
Do we need to order transactions in the ledger if they are authenticated?
Tx 2
Tx 1
Node B
State t
State t'
State t'
State t
Tx 2
Tx 1
Node A
Tx1: Alice sends to Bob 1 unit
Tx2: Bob sends to Charlie 2 units
Distributed ledger at State t
Address | Balance |
---|---|
a11... (Alice) | 3 units |
b9b (Bob) | 1 units |
ca7... (Charlie) | 1units |
Distributed ledger at State t
State t' in option A is different from option B!!
If we focus on option B, by selecting Tx2 before Tx1, Tx2 is invalid because Bob does not have 2 units to send.
However, sending Tx2 after Tx1
makes both transactions valid, so the order is very relevant.
We need consensus to select an order in the distributed ledger
Consensus
2.1
Consensus mechanism must satisfy some requirements
Agreement
Two correct replicas (processes) cannot decide different values.
Validity
The decided value is a value proposed by some replica.
Termination
All correct replicas eventually decide some value.
Consensus mechanisms
2.1
Consensus mechanism must satisfy some requirements
Agreement
Validity
Termination
Consensus mechanisms
Proof of Work
Proof of Stake
Proof of Authority
Ethereum
Bitcoin
Consensus mechanisms
2.1
Blockchains use consensus mechanisms referring to the stack of protocols, incentives and ideas that allow a network of nodes to agree on the state of the blockchain
Consensus mechanisms
Proof of Work
Proof of Stake
Proof of Authority
Ethereum
Bitcoin
Consensus mechanisms
2.1
A cryptocurrency is a digital asset to exchange secured and trusted by a blockchain ledger.
Each blockchain implements different cryptocurrencyies.
The ledger reflects the amount of a cryptocurrency that each address own.
Ether (ETH)
Bitcoin (BTC)
Cryptocurrencies
2.1
Ether (ETH)
The Ethereum ledger reflects the amount of Ethers that each address own.
Address | Balance |
---|---|
a11... (Alice) | 3 ETH |
b9b (Bob) | 1 ETH |
ca7... (Charlie) | 1 ETH |
Ethereum ledger at State t
Ethers
2.1
State t
State t'
State t''
Alice
Ethereum
Transaction 1
Bob
Signature
Message
Signature
Message
Transaction 2
Wallets appeared in order to ease communication with the blockchain networks and manage all cryptographic items from a user point of view.
Usability
Wallets
2.1
State t
Balance
State t'
State t''
Alice
Ethereum
Tx 1 signed
Bob
Tx 2 signed
Balance
Usability
Wallets
2.1
Wallets appeared in order to ease communication with the blockchain networks and manage all cryptographic items from a user point of view.
Usability
Alice
One of the most common wallets is
Wallets
2.1
In the context of web applications, the wallet acts as a web3 provider to connect with the blockchains.
The analogy is to think about this web3 provider as a telecom company offering you access to the cell network. Without such a provider, web applications would not be able to access the blockchains.
Web interaction
Web interaction with wallets
2.1
2.2
Ethereum is a blockchain that works like a computer embedded, so it can build apps and organizations in a decentralized, permissionless and censorship-resitant way.
State t
State t'
State t''
Definition
2.2
In the Ethereum universe, there is a single "canonical computer", called the Ethereum Virtual Machine (EVM), whose state everyone on the Ethereum network agrees on.
State t
State t'
State t''
EVM
Ethereum Virtual Machine
2.2
State t
State t'
State t''
EVM
Alice
Bob
Anyone can request to this computer to perform an arbitrary computation.
Ethereum Virtual Machine
Transaction
Request
2.2
Ethereum transactions
Bob
EVM
Transaction
Whenever such a request is sent to a node it notifies the network, other participants on the network validate and carry out ("execute") the computation.
2.2
Ethereum transactions
Whenever such a request is sent to a node it notifies the network, other participants on the network validate and carry out ("execute") the computation.
Bob
EVM
Transaction
Transaction
Transaction
2.2
Ethereum transactions
Bob
EVM
Validation
Validation
Validation
Whenever such a request is sent to a node it notifies the network, other participants on the network validate and carry out ("execute") the computation.
2.2
Ethereum transactions
Bob
EVM
Execution
Execution
Execution
Whenever such a request is sent to a node it notifies the network, other participants on the network validate and carry out ("execute") the computation.
2.2
Ethereum transactions
This execution causes a state change in the EVM, which is committed and propagated throughout the entire network in consensus.
Bob
EVM
State t'
State t
State t'
State t
State t'
State t
State t'
State t
State t'
State t
2.2
Gas
Bob
EVM
State t'
State t
State t'
State t
State t'
State t
State t'
State t
State t'
State t
Who pays the energy of running the computation of a transaction?
2.2
Gas
Gas
Gas
Transaction
2.2
The node owners are who pay for the energy of the computers,
however the senders pay a fee for the computation expenses called gas.
Who pays the energy of running the computation of a transaction?
Gas
The node owners are who pay for the energy of the computers,
however the senders pay a fee for the computation expenses called gas.
Who pays the energy of running the computation of a transaction?
Gas refers to the unit that measures the amount of computational effort required to execute specific operations on the Ethereum network.
Gas
Transaction
2.2
Gas
Gas = (the amount of gas used to do some operation) * (cost per unit gas)
How much gas has to be paid in a transaction?
Pritority fee (tip)
Defined by the sender
It is rewarded to the validators for the computational effort
Sum of all operations carried out.
Each operation consumes a different amount of gas: adding, multiplying, storing, etc.
Base fee
Defined by the Ethereum protocol
It is burned (removed permanently)
Gas
Transaction
2.2
Gas
Bob
Validator
Alice
How much gas has to be paid in a transaction?
Base fee
Pritority fee
The base fee is equal for Bob and Alice.
The validators prioritze the transactions with greater priority fees.
Gas
Transaction
Gas
Transaction
EVM
2.2
Gas
It avoids accidental or hostile wastage in code such as infinite loops.
Transactions must set a limit of gas to use that is returned in case of not consumed. This lets the users define the maximum price per gas that they want to expend.
The gas is consumed regardless of whether the transaction succeeds or fails because the validators have worked until the point of failure or termination.
2.2
By requiring fee for every computation prevents bad actors from spamming the network.
Smart Contracts
A "smart contract" is simply a program that runs on the Ethereum blockchain. It's a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain.
Smart contracts are a type of Ethereum account. This means they have a balance and can be the target of transactions.
Smart Contract B
(S.C. B)
Address | Balance |
---|---|
a11... (Alice) | 3 ETH |
s4c (S.C. B) | 1 ETH |
EVM
State t
Sends transaction to S.C. B
Tx
Read balance of smart contract B
Alice
2.2
Smart Contracts
EVM
State t
Alice
Transactions to the s.c. B execute its functions and modify its state.
Smart Contract B
Bob
Everyone in the network can access a smart contract and run its code.
They act like a public backend API.
Tx
Sends transaction to S.C. B
Tx
Tx
Tx
Sends transaction to S.C. B
2.2
Smart Contracts
Everyone can develop, deploy and interact with smart contracts into the network.
Smart contracts define a set of rules, like a regular contract, and automatically enforce them to modify the state through the code.
Smart contracts cannot be deleted once deployed and interactions are irreversible just like other transactions.
2.2
Smart Contracts
This is a crucial piece to understand dapps...
2.2
Dapps
A dapp is an application built on a decentralized network that combines smart contracts and a frontend user interface to provide accessible features.
State t
State t'
State t''
EVM
Backend
Frontend
Alice
Metamask
wallet
UI
2.2
Dapps challenges
Which are the challenges when comparing dapps over centralized apps?
Cumbersome maintenance. Since the code deployed in the blockchain cannot be modified, bugs and improvements are difficult to add in a working flow.
Performance overhead. Ethereum demands that every node runs and stores each transaction and the consensus algorithm takes its time as well.
Congestion
Can proceed 10-15 transactions per second.
2.2
Dapps benefits
Zero downtime. Since the code is deployed in smart contracts that run distributed on the network it will be always available for users.
Data integrity. On the blockchain, the data and transactions are "immutable".
Censorship resistance. No single entity can unilaterally block users from submitting transactions.
Trustless environment. Smart contracts can be analyzed whenever and check the code it executes, so there are no opaque processes on the blockchain.
Which are the benefits of dapps over centralized apps?
2.2
3
3
Elements involved in a car insurance centralized model
Client
Web app
Frontend
Backend server
Database
Backend
Centralized business case
Insurance company
3
This flow is the standard for most of use cases that an insurance digital product provides.
Claim a sinister
Cancel a policy
Renew a policy
Centralized business case
Insurance company
Web app
Frontend
Backend server
Database
Backend
Contract a policy
Alice
3
Centralized business case
Alice
Contract a policy
Claim a sinister
Cancel a policy
Renew a policy
Alice does not own her data, but the company does.
Insurance company
Web app
Frontend
Backend server
Database
Backend
3
Alice
Claim a sinister
Cancel a policy
Renew a policy
Alice does not own her data, but the company does.
Alice does not know what the company does with her data.
The processes are opaque and may involve third parties which Alice may not agree.
Centralized business case
Insurance company
Web app
Frontend
Backend server
Database
Backend
Contract a policy
3
Alice
Contract a policy
Cancel a policy
Centralized business case
Web app
Frontend
Backend server
Database
Backend
The project is focused on solving these problems by translating the business case into a decentralized application.
The result offers an end-to-end solution for contracting a policy and canceling it.
Insurance company
3
Alice
Contract a policy
Cancel a policy
Decentralized experiment
Web app
Frontend
Backend server
Database
Backend
Policy S.C.
Factory S.C.
Insurance company
EVM
With this approach, the policy logic and data storage are carried out in the blockchain, and the ownership is distributed between Alice and the company.
The experiment consists of building this insurance dapp called Insurechain.
3
Alice
Contract a policy
Cancel a policy
Backend partition
Web app
Frontend
Backend server
Database
Backend
Policy S.C.
Factory S.C.
Insurance company
EVM
Since every computation that runs on the smart contract consumes gas, there are several scenarios where the business model is not interesting for a client if he has to pay.
A possible solution is to apply a backend domain partition.
With this approach, the policy logic and data storage are carried out in the blockchain, and the ownership is distributed between Alice and the company.
The experiment consists of building this insurance dapp called Insurechain.
3
Backend partition
Insurance
company
Alice
Generating a proposal
3
Backend partition
The business model is not viable if Alice has to pay for generating a proposal that she does not know yet if she will eventually purchase.
Running the proposal computation on the smart contract
Insurance
company
Alice
Generating a proposal
3
Backend partition
Insurance
company
Alice
Contract a policy
Alice
Running the policy purchase computation on the smart contract
On-blockchain Backend
Off-blockchain Backend
Generating a proposal
3
Alice
Contract a policy
Cancel a policy
Software parts
Web app
Frontend
Backend server
Database
Backend
Policy S.C.
Factory S.C.
Insurance company
EVM
Therefore, the project development was divided into three different pieces of software:
1. On-blockchain
backend
2. Off-blockchain
backend
3. Frontend web application
3
On-blockchain backend
We need to compose two types of smart contracts to implement the policy user flows.
It is in charge of creating the policy smart contracts and canceling them.
It manages all the balance of the company so it is in charge of collecting and refunding when needed.
Factory smart contract
Policy smart contract
It stores all the data related to the policy.
3
On-blockchain backend
Policy smart contract
Factory smart contract
1:N
We need to compose two types of smart contracts to implement the policy user flows.
Alice
Insurance
company
3
On-blockchain backend
Create a policy
Transaction that includes the proposal premium price and the data of the risk figures
1
Factory smart contract
Policy smart contract
Alice
1
Factory stores the money and deploys a new smart contract.
2
2
3
4
3
The policy smart contract is created with the proper values passed from the factory.
4
The factory smart contract stores the policy smart contract address to the list bound the sender address.
ETH
3
On-blockchain backend
Cancel a policy
Factory smart contract
Policy smart contract
Alice
3
On-blockchain backend
Cancel a policy
1
Factory smart contract
Policy smart contract
Alice
1
2
2
3
4
3
4
5
5
Factory sends automatically to the sender the proportional refund in Ethers.
The factory smart contract calculates the portion of time the the policy has not been consumed.
If so, factory sends a transaction to the policy
calling the cancel method.
This checks the policy is active and sets is as inactive with the current date.
Factory retrieve the cancel policy and verifies the sender address matches the policy owner one.
Transaction that includes the policy smart contract id to cancel.
ETH
ETH
3
On-blockchain backend
The smarts contracts have been developed with Solidity.
An ABI JSON which is used by the web applications to understand how must be the transactions to the smart contract
A bytecode file which is understandable by the Ethereum Virtual Machine and can be deployed on the network
A developer codes a smart contract with Solidity
Compiler
Code is compiled and it genetares two files
3
On-blockchain backend
Solidity offer a comprehensive set of features to develop smart contracts.
Getters & Setters
"Require" assessments
Modifiers
Blockchain out-of-the-box
functions and variables
OOP-like behaviour
3
On-blockchain backend
OOP-like behaviour
contract Policy {
string riskData;
uint256 premium;
address owner;
address public factoryAddress;
uint endDate;
uint renewalDate;
uint startDate;
mapping(uint256 => Claim) claims;
uint256[] claimIdList;
constructor(string memory _proposalData, uint256 _premium,
address _owner, uint256 _endDate){
require(_endDate > block.timestamp, "Renewal date has to be upcoming");
require(_premium > 0 , "Required a premium to activate the policy");
riskData = _proposalData;
premium = _premium;
owner = _owner;
factoryAddress = msg.sender;
startDate = block.timestamp;
endDate = _endDate;
renewalDate = _endDate;
}
}
3
On-blockchain backend
constructor() payable {
require(msg.value >= minimumBudget, "Minimum budget is not achieved to start an Insurance Smart Contract");
insuranceAddress = payable(msg.sender);
}
"Require" assessments
function renew(uint newEndDate, uint256 _renewalPremium) onlyFactory external returns (uint){
require(newEndDate > endDate, "New end date has to be after the current one");
endDate = newEndDate;
renewalDate = newEndDate;
premium = _renewalPremium;
emit Renewal(endDate);
return renewalDate;
}
3
On-blockchain backend
modifier companyOnly() {
require(msg.sender == insuranceAddress, "Just the insurance company can perform this action");
_;
}
Modifiers
modifier onlyFactory(){
require(msg.sender == factoryAddress, "Just the insurance company can perform this action");
_;
}
modifier isActive(){
require(endDate > block.timestamp && renewalDate > block.timestamp, "Policy is not active");
_;
}
3
On-blockchain backend
function getOwnerAddress() onlyFactoryOrOwner external view returns (address) {
return owner;
}
Getters & Setters
function cancelPolicy() onlyFactory() isActive external {
endDate = block.timestamp;
}
Note that the functions are followed by the modifiers that contain the require assertions
3
On-blockchain backend
function cancelPolicy() onlyFactory() isActive external {
endDate = block.timestamp;
}
function createPolicy(string memory proposalData, uint endDate) public payable returns (address){
require(msg.value > 0, "To create a policy you must pay a premium.");
Policy policyContract = new Policy( proposalData, msg.value, msg.sender, endDate);
address policyAddress = address(policyContract);
address holderId = msg.sender;
policiesMapping[holderId].push(policyAddress);
return policyAddress;
}
Blockchain out-of-the-box functions and variables
3
On-blockchain backend
function cancelPolicy(address addressPolicy) public {
Policy policy = Policy(addressPolicy);
address owner = policy.getOwnerAddress();
require(msg.sender == owner || msg.sender == insuranceAddress, "Just the policyholder of the policy is able to cancel it.");
policy.cancelPolicy();
uint premium = policy.getPremium();
uint256 startDate = policy.getStartDate();
uint256 renewalDate = policy.getRenewalDate();
uint256 cancellationDate = policy.getEndDate();
uint256 timeNotEnjoyed = renewalDate - cancellationDate;
uint256 totalTimeSpan = renewalDate - startDate;
uint256 timePercentage = (timeNotEnjoyed * 100) / totalTimeSpan;
address payable holderAddress = payable(owner);
uint256 amountToReturn = premium * timePercentage / 100;
require (amountToReturn < address(this).balance, "Insufficient balance to pay the cancellation.");
holderAddress.transfer(amountToReturn);
emit PolicyCanceled(addressPolicy, cancellationDate, amountToReturn);
}
Combining all features
3
On-blockchain development network
To develop and test the smart contracts it is been used a testnet in order to not spend real Ethers while developing features.
Hardhat offers a testnet called Hardhat Network. It is simple a process that anybody can launch on his computer and it simulates a Blockchain network running the Ethereum Virtual Machine locally.
3
On-blockchain development network
The wallets and web apps served locally in the same computer can reach the Hardhat network and interact with it.
3
Off-blockchain backend technologies
The off-blockchain backend is built with two main technologies
Backend server
It is used to create a server that can receive HTTP requests and execute some logic
Database
It is used to define the business models of the relational database. In addition, it provides the methods to the backend server to access the database
3
Off-blockchain backend modules
The off-blockchain backend logic is separated into two modules
Off-blockchain backend
Backend server
Database
It handles all the users authentication process
Authentication
Module
It generates proposals and can store them for the related users
Proposals
Module
3
Off-blockchain backend: Authentication module
Authentication
Module
Takes advantage of the Ethereum accounts to use them as identifiers for users. This process is called "Sign In With Ethereum" (SIWE).
3
Off-blockchain backend: Proposal module
Proposals
Module
3
Frontend web application
The frontend web application is developed with Next.js, which is based on the React library.
Next.js
React
3
Frontend web application
React lets us create components to compose a web application.
Next.js
React
3
Frontend web application
Components
There are some components in charge of using the wallets to interact with the blockchain.
Make HTTP requests to interact with a backend server.
Modify the user interface when the data changes.
React to user interactions.
4
Dapp overview
Dapp overview
Github repository: https://github.com/gerardcastell/insurechain
Total lines of code: 98602
Dapp overview
Dapp overview
4
Dapp overview
Dapp overview: Backend
The Hardhat network is served locally and contains the factory and policies deployed contracts. So the business policy logic is collected here.
The off-blockchain module is served locally as well. It is able to receive HTTP requests and generate proposals, authenticate users and save their proposals as well.
4
Dapp overview
Dapp overview
All the users and policy holders access the dapp through the web application.
The users use a wallet like Metamask to authenticate themself in the off-blockchain and on-blockchain network.
Dapp overview
Dapp overview: Frontend
4
Dapp overview
Demo
DEMO
4
5
5
Dapp overview
The experiment of translating a centralized digital product into a decentralized application has succeeded and proved it is feasible from a technological point of view.
The resulting user experience is quite intuitive and does not differ so much from the centralized model from the user's point of view.
Some important technologies as wallets have emerged to ease the adoption of the blockchain for the standard users but I consider that currently, we are still far away from using it regularly.
In this decentralized model, we may find benefits for both, clients and the company, as well as some drawbacks.
It has been really rewarding to implement a comprehensive end-to-end solution for a real business case with such a disruptive technology.
Dapp overview