Block Chain
Block Chain
LECTURE NOTE ON
INTRODUCTION TO
BLOCKCHAIN TECHNOLOGY
Dr Md Ashraf Uddin
Federation University Australia
Email: [email protected]
Table of Contents
chapter 2 ........................................................................................10
blockchain fundamentals ..............................................................10
Double-Spending........................................................................... 10
Bitcoin: A Decentralized Solution for the Double-Spending Problem
...................................................................................................... 12
Blockchain Technology ................................................................. 14
Cryptography in Blockchain Technology ....................................... 15
Symmetric Key Cryptography ........................................................ 16
Public Key Cryptography (Asymmetric Key Cryptography)............ 16
Hashing, and Merkle Tree.............................................................. 20
Merkle Tree ................................................................................... 25
Description of blockchain technology ........................................... 27
Data Layer ..................................................................................... 27
The consensus layers ..................................................................... 34
The network layers ........................................................................ 38
The infrastructure layers ............................................................... 40
The application layers ................................................................... 42
Exercise: ........................................................................................ 44
chapter 3 ........................................................................................46
iii
Chapter 4 ....................................................................................... 68
Consensus Protocol in Blockchain ................................................ 68
Chapter 5 ....................................................................................... 82
Ethereum Blockchain .................................................................... 82
Accounts ....................................................................................... 82
Gas and payment ........................................................................... 84
Transaction and messages............................................................. 86
Blocks ............................................................................................ 88
Ommers explained ........................................................................ 89
Block header .................................................................................. 90
Contract creation .......................................................................... 91
Exercise ......................................................................................... 92
Chapter 6 ....................................................................................... 94
Smart Contract using Solidity Language ...................................... 94
iv
Table of Contents
Contract ........................................................................................ 95
Enums and Struct .......................................................................... 99
Storage and Memory.................................................................... 110
Function Definition ..................................................................... 113
Function Modifier........................................................................ 118
Cryptographic functions .............................................................. 121
Event ........................................................................................... 123
Creating an event ........................................................................ 123
Creating and verifying signature ................................................. 126
The Ethereum Virtual Machine ................................................... 126
Accounts ..................................................................................... 126
Transactions ................................................................................ 127
Gas .............................................................................................. 128
Storage, Memory, and the Stack .................................................. 128
Instruction Set............................................................................. 129
Message Calls .............................................................................. 130
Delegatecall / Callcode and Libraries ........................................... 131
Logs ............................................................................................. 131
Exercise ....................................................................................... 132
Chapter 7 .....................................................................................135
Decentralized Application ...........................................................135
Chapter 8 .....................................................................................150
Blockchain in IoT.........................................................................150
vi
PREFACE
vii
MD ASHRAF UDDIN
viii
CHAPTER 1
INTRODUCTION TO BLOCKCHAIN
1. They are more stable and fault resistant since they do not
have a single point of failure. If a client becomes
detached from the server, it doesn’t have any effect on
other clients of the server.
Definition of Blockchain
Assume that there are three candidates: Alice, Bob, and Charlie
who are doing some monetary transactions among each other on a
blockchain network. Let us go through the transactions step by
step to understand blockchain’s open and decentralized features.
Step 01: Assume Alice had $50 in her possession, which is the
starting point for all transactions, and that every node is aware of
it, as depicted in Figure 1.4-1.6.
Charlie Alice
Genesis block
Genesis block Alice has 50$
Alice has 50$
Genesis block
Genesis block
Alice has 50$ Alice has 50$
Shelly Bob
Figure 1.4: Alice has 50$ and all participants have this information
Charlie Alice
Genesis block
Alice has 50$
Genesis block Alice →Bob: 20$
Figure 1.5: Alice pays $20 to Bob and every participant has this
information including the previous records.
Charlie
Alice
Genesis block
Genesis block Alice has 50$
Alice pays $20 to Bob.
You may have a lot of questions, such as "What if Alice sends the
same amount to Dave to double-spend the same amount, or what
if she's making a payment without adequate cash in her account?"
"How is the security ensured?" and so on. In the following
chapters, we will go through those specifics.
Exercise
CHAPTER 2
BLOCKCHAIN FUNDAMENTALS
Double-Spending
Assume Alice wishes to pay Bob $1. If Alice and Bob pay with
actual currency, Alice will lose the $1 when the transaction is
completed. The dilemma becomes more difficult if Alice and Bob
use digital money. Digital money is in the form of a digital file that
can be easily copied. If Alice sends Bob a $1 digital file over email,
for example, Bob has no way of knowing if Alice has deleted her
copy of the file. If Alice still has the $1 digital file, she has the
option of sending it to Carol. Double spending is the term for this
issue.
10
Carol
Alice
Bob
11
12
13
Blockchain Technology
14
Cryptography
Consensus
mechanism Distributed ledger
15
16
the public key. RSA and Elliptic Curve Digital Signature (ECDSA)
are the most popular public-key cryptography algorithms.
17
Figure 2.8 shows how public and private key can be used to
perverse the confidentiality of two parties communicating over
insure channel.
18
19
20
SHA-2
It belongs to the SHA family of hash functions, but itself is a
family of hash functions. It has many SHA variants such as SHA-
224, SHA-256, SHA-384, SHA-512, SHA-512/224, and SHA-
512/256. SHA-256 and SHA-512 are the primitive hash functions
and the other variants are derived from them.
21
RIPEMD
22
23
24
Merkle Tree
25
Audit proof lets you verify that a specific data record is included in
the database. Usually, the server maintaining the database
provides the client with a proof that the record exists in that
database. If a Merkle audit proof fails to produce a root hash that
matches the Merkle root hash (which is obtained from a trusted
authority), it means that the data record is not in the database.
26
A Merkle consistency proof lets you verify that any two versions of
a database are consistent: that is, the later version includes
everything in the earlier version, in the same order, and all new
entries come after the entries in the older version.
Data Layer
27
28
29
Digital Signature
30
31
The public key of a user is known as his or her address like a bank
account in BC technologies such as Bitcoin or Ethereum. Anyone
can send digital currencies to a user’s address (Public Key) and
only the user can access the currencies using his private key of the
corresponding PKI. Figure 2.19 explains signing a message using
the private key and verifying the message with the public key in
the Bitcoin BC.
32
33
34
Proof of Work:
condition. You can use the app below to simulate block mining.
When you type in the "Data" text box or change the nonce value,
you can notice the change in the hash value. When you click the
"Mine" button, the app starts with a nonce equal to zero, computes
the hash value and checks if the leading four digits of the hash
value is equal to "0000". If the leading four digits are not equal to
"0000", it increments the nonce by one and repeats the whole
process until it finds a nonce value that satisfies the condition. If
the block is considered mined, the background color turns green.
36
Any changes to the data in any block will affect all the hash values
of the blocks that come after it and they will become invalid. This
gives the blockchain its immutability characteristic.
You can use the app below to simulate a blockchain with 3 blocks.
When you type in the "Data" text box or change the nonce value,
you can notice the change in the hash value and the "Prev" value
(previous hash) of the next block. You can simulate the mining
process by clicking on the “Mine” button of each individual block.
After mining the 3 blocks, try changing the data in block 1 or 2,
and you will notice that all the blocks that come after becoming
invalid. Both mining simulators above were adapted from Anders
Brown Worth's excellent Blockchain Demo.
37
All the miners in the Bitcoin network compete to find a valid block
that will be added to the blockchain and get the reward from the
network. Finding a nonce that validates a block is rare, but because
of the number of miners, the probability of a miner in the network
validating a block is extremely high. The first miner to submit a
valid block gets his block added to the blockchain and receives the
reward in bitcoins. But what happens if two miners or more submit
their blocks at the same time?
Resolving Conflicts
38
39
40
41
42
43
Exercise:
44
45
CHAPTER 3
BLOCKCHAIN IMPLEMENTATION
Installing Flask
46
app.route(rule, options)
47
set FLASK_APP=hello
flask run
* Running on http://127.0.0.1:5000/
To run on python shell
Python Hello.py
48
import sys
import hashlib
import json
from time import time
from uuid import uuid4
from flask import Flask, jsonify, request
import requests
from urllib.parse import urlparse
class Blockchain(object):
difficulty_target = "0000"
block_encoded = json.dumps(block,
sort_keys=True).encode()
49
return
hashlib.sha256(block_encoded).hexdigest()
def __init__(self):
self.chain = []
self.current_transactions = []
genesis_hash = self.hash_block("genesis_block")
self.append_block( hash_of_previous_block =
genesis_hash, nonce = self.proof_of_work(0,
genesis_hash, []) )
50
nonce = 0
while self.valid_proof(index,
hash_of_previous_block, transactions, nonce) is
False:
nonce += 1
51
return nonce
The proof_of_work() function first starts with zero for the nonce
and check if the nonce together with the content of the block
produces a hash that matches the difficulty target. If not, it
increments the nonce by one and then try again until it finds the
correct nonce.
content =
f'{index}{hash_of_previous_block}{transactions}{nonce}'.encode()
content_hash = hashlib.sha256(content).hexdigest()
return content_hash[:len(self.difficulty_target)] ==
self.difficulty_target
Once the nonce for a block has been found, you can now write the
method to append the block to the existing blockchain. This is the
function of the append_block() method :
52
block = {
'index': len(self.chain),
'timestamp': time(),
'transactions': self.current_transactions,
‘nonce': nonce,
'hash_of_previous_block': hash_of_previous_block
self.current_transactions = []
self.chain.append(block)
return block
Adding Transactions
self.current_transactions.append({
'amount': amount,
53
'recipient': recipient,
'sender': sender,
})
return self.last_block['index'] + 1
@property
def last_block(self):
return self.chain[-1]
app = Flask(__name__)
54
blockchain = Blockchain()
For the REST API, we want to create a route for users to obtain the
current blockchain, so append the following statements to the end
of blockchain.py :
@app.route('/blockchain', methods=['GET'])
def full_chain():
response = {
'chain': blockchain.chain,
'length': len(blockchain.chain),
Performing Mining
@app.route('/mine', methods=['GET'])
def mine_block():
55
blockchain.add_transaction(
sender="0",
recipient=node_identifier,
amount=1,
last_block_hash =
blockchain.hash_block(blockchain.last_block)
# using PoW, get the nonce for the new block to be added
to the blockchain
index = len(blockchain.chain)
nonce = blockchain.proof_of_work(index,
last_block_hash, blockchain.current_transactions)
# add the new block to the blockchain using the last block
response = {
'index': block['index'],
'hash_of_previous_block':
block['hash_of_previous_block'],
56
'nonce': block['nonce'],
'transactions': block['transactions'],
When mining a block, you need to find the hash of the previous
block and then use it together with the content of the current
block to find the nonce for the block. Once the nonce is found, you
will append it to the blockchain.
Adding Transactions
Another route that you want to add to the API is the ability to add
transactions to the current block:
@app.route('/transactions/new', methods=['POST'])
def new_transaction():
values = request.get_json()
57
index = blockchain.add_transaction(
values['sender'],
values['recipient'],
values['amount']
response = {'message':
We are now ready to test the blockchain. In this final step, add the
following statements to the end of blockchain.py:
if __name__ == '__main__':
app.run(host='0.0.0.0', port=int(sys.argv[1]))
58
Synchronizing Blockchains
For our example, we shall modify it so that each node can be made
aware of neighboring nodes on the network (see Figure 3.1).
def __init__(self):
59
self.nodes = set()
self.chain = []
...
This nodes member will store the address of other nodes. Next,
add a method called add_node() to the Blockchain class:
parsed_url = urlparse(address)
self.nodes.add(parsed_url.netloc)
print(parsed_url.netloc)
block = chain[current_index]
60
if block['hash_of_previous_block'] !=
self.hash_block(last_block):
return False
if not self.valid_proof(
current_index,
block['hash_of_previous_block'],
block['transactions'],
block['nonce']):
return False
last_block = block
current_index += 1
return True
61
def update_blockchain(self):
neighbours = self.nodes
new_chain = None
max_length = len(self.chain)
# grab and verify the chains from all the nodes in our
# network
response = requests.get(f'http://{node}/blockchain')
if response.status_code == 200:
length = response.json()['length']
chain = response.json()['chain']
# is valid
self.valid_chain(chain):
max_length = length
62
new_chain = chain
if new_chain:
self.chain = new_chain
return True
return False
With the methods in the Blockchain class defined, you can now
define the routes for the REST API:
@app.route('/nodes/add_nodes', methods=['POST'])
def add_nodes():
values = request.get_json()
nodes = values.get('nodes')
if nodes is None:
63
blockchain.add_node(node)
response = {
'nodes': list(blockchain.nodes),
@app.route('/nodes/sync, methods=['GET'])
def sync():
updated = blockchain.update_blockchain()
if updated:
response = {
'message':
'blockchain': blockchain.chain
else:
response = {
64
'blockchain': blockchain.chain
Tip
Figure 3.2 shows the two nodes aware of each other’s existence.
65
Figure 2-5 The current states of the two nodes in our blockchain
network
Install Postman
GET method
http://localhost:5000/blockchain
To mine a block
http://localhost:5000/mine
http://localhost:5000/nodes/sync
POST method
Header: http://localhost:5000/transactions/new
Body:
"sender": "04d0988bfa799f7d7ef9ab3de97ef482",
"recipient":
66
"cd0f75d2367ad456607647edde665d8f",
"amount": 111
Header: http://localhost:5001/nodes/add_nodes
Exercise
67
CHAPTER 4
CONSENSUS PROTOCOL IN
BLOCKCHAIN
Proof of Work:
68
● The nodes that receive the new block will accept it only
after verifying that all transactions in the block are valid
and not already spent.
69
Note that the hash generation works at random and is beyond your
control - that is you cannot force the hash function to generate a
certain hash. Thus, it may take several iterations until the desired
hash with four leading zeros is generated. The expected time for
generating a block in the bitcoin system is 10 minutes. Once the
miner successfully mines the block, he releases that in the system
making it now the last block in the chain.
70
Pros Cons
Proof-of-work is neutral. You don't
need ETH to get started and block Proof-of-work uses up so much
rewards allow you to go from 0ETH to energy that it's bad for the
a positive balance. With proof-of- environment.
stake you need ETH to start with.
Proof-of-work is a tried and tested
If you want to mine, you need
consensus mechanism that has kept
such specialized equipment that
Bitcoin and Ethereum secure and
it's a big investment to start.
decentralized for many years.
Due to increasing computation
needed, mining pools could
potentially dominate the
Compared to proof-of-stake it's
mining game, leading to
relatively easy to implement.
centralization and security
risks.
71
What is Proof-of-Stake?
72
● If the block is ‘OK’-ed, the validator gets the stake back and
the reward too. If the algorithm is using a coin-age based
mechanism to select validators, the validator for the
current block has its coin-age reset to 0. This puts him in a
low priority for the next validator election.
Advantages of PoS
● Energy-efficient:
As all the nodes are not competing against each other to
73
● Decentralization:
In blockchains like Bitcoin (Proof of Work system to
achieve distributed consensus), an extra incentive of
exponential rewards are in place to join a mining pool
leading to a more centralized nature of blockchain. In the
case of a Proof-of-Stake based system (like Peercoin),
rewards are proportional(linear) to the amount of stake. So,
it provides absolutely no extra edge to join a mining pool;
thus, promoting decentralization.
● Security:
A person attempting to attack a network will have to own
51% of the stakes (pretty expensive). This leads to a secure
network.
75
● The kth block producer signs the kth block, until k=N.
Any user is able to run a block validator and verify the network.
There is no incentive to be a block validator.
Advantages:
77
Disadvantages:
78
pBFT consensus rounds are broken into 4 phases (refer with the
image below):
79
Limitations of pBFT
80
81
CHAPTER 5
ETHEREUM BLOCKCHAIN
Ethereum is a decentralized, open source blockchain with smart
contract functionality. Ether is the native cryptocurrency of the
platform. After Bitcoin, it is the largest cryptocurrency by market
capitalization. Ethereum is the most actively used blockchain.
let’s dive deeper into the main components that the Ethereum
system is comprised of:
• accounts
• state
• gas and fees
• transactions
• blocks
• transaction execution
• mining
• proof of work
Accounts
82
Account state
83
Every block has a “header” which stores the hash of the root node
of three different Merkle trie structures, including:
• State trie
• Transactions trie
• Receipts trie
84
Gas is the unit used to measure the fees required for a particular
computation. Gas price is the amount of Ether you are willing to
spend on every unit of gas and is measured in “gwei.” “Wei” is the
smallest unit of Ether, where 1⁰¹⁸ Wei represents 1 Ether. One gwei
is 1,000,000,000 Wei.
With every transaction, a sender sets a gas limit and gas price. The
product of gas price and gas limit represents the maximum
amount of Wei that the sender is willing to pay for executing a
transaction.
For example, let’s say the sender sets the gas limit to 50,000 and a
gas price to 20 gwei. This implies that the sender is willing to
spend at most 50,000 x 20 gwei = 1,000,000,000,000,000 Wei =
0.001 Ether to execute that transaction.
One important aspect of the way the Ethereum works is that every
single operation executed by the network is simultaneously
affected by every full node. However, computational steps on the
Ethereum Virtual Machine are very expensive. Therefore,
Ethereum smart contracts are best used for simple tasks, like
running simple business logic or verifying signatures and other
cryptographic objects, rather than more complex uses, like file
storage, email, or machine learning, which can put a strain on the
network. Imposing fees prevents users from overtaxing the
network.
85
86
87
Blocks
88
Ommers explained
Because of the way Ethereum is built, block times are much lower
(~15 seconds) than those of other blockchains, like Bitcoin (~10
minutes). This enables faster transaction processing. However, one
of the downsides of shorter block times is that more competing
block solutions are found by miners. These competing blocks are
also referred to as “orphaned blocks” (i.e. mined blocks do not
make it into the main chain).
89
Block header
90
Contract creation
91
However, if the sender sent any Ether value with the transaction,
the Ether value will be refunded even if the contract creation
fails. If the initialization code executes successfully, a final
contract-creation cost is paid. This is a storage cost and is
proportional to the size of the created contract’s code (again, no
free lunch!) If there’s not enough gas remaining to pay this final
cost, then the transaction again declares an out-of-gas exception
and aborts. If all goes well and we make it this far without
exceptions, then any remaining unused gas is refunded to the
original sender of the transaction, and the altered state is now
allowed to persist.
Exercise
93
CHAPTER 6
SMART CONTRACT USING SOLIDITY
LANGUAGE
Smart Contract
Smart contracts are where all the business logic of our application
lives. This is where we’ll code the decentralized portion of our app
discussed in the next chapter. Smart contracts are in charge of
reading and writing data to the blockchain, as well as executing
business logic. Smart contacts are written in a programming
language called Solidity, which looks a lot like Javascript. It is a
full-blown programming language that will allow us to do many of
the same types of things Javascript is capable of, but it behaves a
bit differently because of its use case.
Solidity Language
https://docs.soliditylang.org/en/v0.8.4/introduction-to-smart-
contracts.html#a-simple-smart-contract
The first line is a pragma directive which tells that the source code
is written for Solidity version 0.4.0 or anything newer that does
not break functionality up to, but not including, version 0.6.0.
94
contract SimpleStorage {
uint storedData;
storedData = x;
return storedData; }
Contract
Importing Files
import "filename";
95
To import a file x from the same directory as the current file, use
import "./x" as x;. If you use import "x" as x; instead, a different file
could be referenced in a global "include directory".
Reserved Keywords
96
contract SolidityTest {
constructor() public{
uint a = 1;
uint b = 2;
uint result = a + b;
return result;
Example
/*
* This is a multi-line comment in solidity
* It is very similar to comments in C Programming
*/
uint a = 1;
97
uint b = 2;
uint result = a + b;
return result;
}
Value Types
Fixed
Signed and unsigned fixed point numbers of
Point fixed/unfixed
varying sizes.
Numbers
Fixed
Signed and unsigned fixed point numbers of
Point fixed/unfixed
varying sizes.
Numbers
Signed fixed point number where M
represents number of bits taken by type and
Fixed
N represents the decimal points. M should
Point fixedMxN
be divisible by 8 and goes from 8 to 256. N
Numbers
can be from 0 to 80. fixed is same as
fixed128x18.
98
Syntax:
enum <enumerator_name> {
99
// Defining function to
// Declaring variables of type // return default value
enumerator function getdefaultvalue(
) public pure
week_days week; returns(week_days) {
return default_value;
week_days choice; }
}
Output:
100
Struct
Solidity allows users to create their own data type in the form of
structure. The struct contains a group of elements with a different
data type. Generally, it is used to represent a record. To define a
structure struct keyword is used, which creates a new data type.
Syntax:
struct <structure_name> {
<data type> variable_1;
<data type> variable_2;
}
Struct student
{
String name;
String id;
Uint age;
}
101
102
Output :
Address
address x = 0x212;
103
State Variable
Local Variable
104
Example:
pragma solidity ^0.5.0;
contract SolidityTest {
uint storedData; // State variable
constructor() public {
storedData = 10;
}
function getResult() public view returns(uint){
uint a = 1; // local variable
uint b = 2;
uint result = a + b;
return result; //access the local variable
}
}
Run the above program using steps provided in the beginning of
the chapter.
Output
0: uint256: 10
Global Variables
These are special variables that exist in the global workspace and
provide information about the blockchain and transaction
properties.
Name Returns
105
msg.sender (address
Sender of the message (current caller)
payable)
First four bytes of the calldata (function
msg.sig (bytes4)
identifier)
106
Variable Scope
Example
107
Mapping in Solidity
Syntax:
Creating a Mapping
108
contract Courses {
struct Instructor {
uint age;
string fName;
string lName;
}
Example
Try the following code to see the use of msg, a special variable to
get the sender address in Solidity.
109
}
}
Run the above program. First Click updateBalance Button to set
the value as 10 then look into the logs which will show the
decoded output as −
Output
{
"0": "uint256: 10"
}
110
Output:
111
Output:
112
Function Definition
Syntax
//statements }
113
Example
Calling a Function
114
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);//access local variable
}
}
Run the above program.
Output
0: string: 3
Function Parameters
115
Example
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
116
Output
0: string: 3
Output
117
0: uint256: product 2
1: uint256: sum 3
Function Modifier
contract Owner {
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier costs(uint price) {
if (msg.value >= price) {
_;
}
}
}
The function body is inserted where the special symbol "_;"
appears in the definition of a modifier. So, if the condition of the
modifier is satisfied while calling this function, the function is
executed and otherwise, an exception is thrown. See the example
below.
118
_;
}
modifier costs(uint price) {
if (msg.value >= price) {
_;
}
}
}
contract Register is Owner {
mapping (address => bool) registeredAddresses;
uint price;
constructor(uint initialPrice) public { price = initialPrice; }
View functions ensure that they will not modify the state. A
function can be declared as a view. The following statements if
present in the function are considered modifying the state and the
compiler will throw a warning in such cases.
119
Example
contract Test {
function getResult() public view returns(uint
product, uint sum){
uint a = 1; // local variable
uint b = 2;
product = a * b;
sum = a + b;
}
}
Run the above program.
Output
0: uint256: product 2
1: uint256: sum 3
Pure functions ensure that they do not read or modify the state. A
function can be declared as pure. The following statements if
present in the function are considered reading the state and the
compiler will throw a warning in such cases.
120
Example
Output
0: uint256: product 2
1: uint256: sum 3
Cryptographic functions
121
Example
Output
122
0: bytes32: result
0xe1629b9dda060bb30c7908346f6af189c16773fa148d3366701fbaa
35d54f3c8
Event
Creating an event
Events are defined within the contracts as global and called within
its functions. Events are declared by using the event keyword,
followed by an identifier and the parameter list, and ends with a
semicolon. The parameter values are used to log the information
or for executing the conditional logic. Its information and values
are saved as part of the transactions inside the block. There is no
need of providing variables, only datatypes are sufficient. An event
can be called from any method by using its name and passing the
required parameters.
event <eventName>(parameters) ;
123
// Creating a contract
contract eventExample {
// Declaring an event
event Increment(address owner);
//Declare an Event
event Deposit(address indexed _from, bytes32 indexed _id, uint
_value);
124
//Emit an event
emit Deposit(msg.sender, _id, msg.value);
Example
contract Test {
event Deposit(address indexed _from, bytes32 indexed _id, uint
_value);
function deposit(bytes32 _id) public payable {
emit Deposit(msg.sender, _id, msg.value);
}
}
Then access the contract's event in JavaScript code.
var abi = /* abi as generated using compiler */;
var ClientReceipt = web3.eth.contract(abi);
var clientReceiptContract = ClientReceipt.at("0x1234...ab67" /*
address */);
Output
{
"returnValues": {
"_from": "0x1111...FFFFCCCC",
"_id": "0x50...sd5adb20",
125
"_value": "0x420042"
},
"raw": {
"data": "0x7f...91385",
"topics": ["0xfd4...b4ead7", "0x7f...1a91385"]
}
}
Accounts
There are two kinds of accounts in Ethereum which share the same
address space: External accounts that are controlled by public-
private key pairs (i.e. humans) and contract accounts which are
controlled by the code stored together with the account.
126
Transactions
Note
127
Gas
The Ethereum Virtual Machine has three areas where it can store
data- storage, memory, and the stack, which are explained in the
following paragraphs.
128
Instruction Set
129
For a complete list, please see the list of opcodes as part of the
inline assembly documentation.
Message Calls
As already said, the called contract (which can be the same as the
caller) will receive a freshly cleared instance of memory and has
access to the call payload - which will be provided in a separate
area called the calldata. After it has finished execution, it can
return data which will be stored at a location in the caller’s
memory preallocated by the caller. All such calls are fully
synchronous.
130
Calls are limited to a depth of 1024, which means that for more
complex operations, loops should be preferred over recursive calls.
Furthermore, only 63/64th of the gas can be forwarded in a
message call, which causes a depth limit of a little less than 1000
in practice.
Logs
131
Exercise
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
contract Coin {
// The keyword "public" makes variables
// accessible from other contracts
address public minter;
mapping (address => uint) public balances;
132
133
revert InsufficientBalance({
requested: amount,
available: balances[msg.sender]
});
balances[msg.sender] -= amount;
balances[receiver] += amount;
emit Sent(msg.sender, receiver, amount);
}
}
134
CHAPTER 7
DECENTRALIZED
APPLICATION
Now let’s take a quick look at the structure of the dApp we’re
building.
135
Now we’ve seen what a blockchain is and how it works. We’ve seen
why we want to build our voting dApp on the blockchain instead of
the current web. And we’ve seen that we want to code our dApp by
writing a smart contract that will be deployed to the Ethereum
blockchain. The following steps need to be followed to implement
a dApp.
o Install Node.js
136
137
$ node -v
Truffle Framework
You can install Truffle with NPM in your command line like this:
Ganache
Metamask
139
140
141
142
143
Our dApp will take a digital forensics report as input from a user
and upload it to the IPFS by invoking an Ethereum contract. The
hash of the file will be stored on Ethereum. This is the process
we’ll go through:
144
What is IPFS?
145
146
147
Dependencies:
npm i create-react-app
npm install react-bootstrap
npm install fs-extra
npm install ipfs-api
npm install web3
npm install @babel/core @babel/register --save-dev
Download code from the following link and keep the file on the
Desktop:
https://drive.google.com/drive/folders/1UCXQQENuX8RJsf7AOgei
CUvNHhGuJY9B?usp=sharing
~ % cd Desktop
Desktop % cd Lab12
Install all dependencies using the following command:
$ npm install
$ truffle migrate
If the above command does not work, use the following command:
149
CHAPTER 8
BLOCKCHAIN IN IOT
150
151
152
153
154
155
156
157
158
159
Health Data
End
Figure 8.2: The high-level view of the PCA managed IoT eHealth
Architecture.
161
162
However, the current Cloud system is not designed for meeting all
requirements of IoT data including volume, variety, and velocity of
data. Every day, billions of interconnected IoT devices generate
more than two exabytes of data. Transferring all IoT data to the
Cloud takes huge quantities of bandwidth. Instead of sending vast
amounts of IoT data to the Cloud, the most time-sensitive data
can be analyzed at the network edge, near the user’s devices where
data is generated. The selected data that requires historical
analysis and longer-term storage can be transmitted to the Cloud.
163
164
165
transactions, Blocks, and security keys, the PCA on the Fog can
execute the consensus protocol for rapid outcomes related to
Blocks and the PCA on the Cloud permanently stores patient data.
The BC nodes require the consensus protocol to confirm and insert
a Block into a decentralized ledger. The standard consensus
mechanism such as Proof of Work (PoW) which is the most
decentralized protocol needs excessive computational resources
and experiences lower throughput when it is applied to the Fog
network.
166
167
168
169
170
171
172
173
The PCA in a layer can monitor and analyze requests from other
replicated PCAs of other layers. One of the replicated PCA in each
layer acting as master PCA can activate other instances of PCA in
that layer if the master PCA experiences flood of responses from
malicious nodes or other PCAs of higher or lower layer. The
existing state-of-the-art works in task offloading considered all
tasks as similar same category and designed task migration
algorithm accordingly. However, tasks on health data vary in the
level of sensitivity with respect to privacy, time and energy
required.
174
175
176
177
178
Exercise
References
[1] D. C. Nguyen, P. N. Pathirana, M. Ding, and A. Seneviratne, “Integration of
blockchain and cloud of things: Architecture, applications and challenges,” arXiv
preprint arXiv:1908.09058, 2019.
[3] M. A. Khan and K. Salah, “Iot security: Review, blockchain solutions, and open
challenges,”
179
[6] Y. Yu, Y. Li, J. Tian, and J. Liu, “Blockchain-based solutions to security and
privacy issues in the internet of things,” IEEE Wireless Communications, vol. 25,
no. 6, pp. 12–18, 2018.
[8] J. Huang, L. Kong, G. Chen, M.-Y. Wu, X. Liu, and P. Zeng, “Towards secure
industrial iot: Blockchain system with credit-based consensus mechanism,” IEEE
Transactions on Industrial Informatics, vol. 15, no. 6, pp. 3680–3689, 2019.
[14] K. J. O’Dwyer and D. Malone, “Bitcoin mining and its energy footprint,” 2014.
180
[19] E. Karafiloski and A. Mishev, “Blockchain solutions for big data challenges: A
literature review,” in IEEE EUROCON 2017-17th International Conference on
Smart Technologies. IEEE, 2017, pp. 763–768.
[21] T. Yu, X. Wang, and Y. Zhu, “Blockchain technology for the 5g-enabled
internet of things systems: Principle, applications and challenges,” 5G-Enabled
Internet of Things, 2019.
[23] A. Reyna, C. Mart´ın, J. Chen, E. Soler, and M. D´ıaz, “On blockchain and its
integration with iot. challenges and opportunities,” Future Generation Computer
Systems, vol. 88, pp. 173–190, 2018.
181
182