0% found this document useful (0 votes)
19 views111 pages

BCT

Uploaded by

Yashaswini S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views111 pages

BCT

Uploaded by

Yashaswini S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 111

SOLIDITY

&
Development Tools Frameworks
Solidity language
• Solidity is a domain-specific language of choice
for programming contracts in Ethereum.

• There are, however, other languages that can be


used, such as Serpent, Mutan, and LLL ( Low-level
Lisp-like Language) but Solidity is the most
popular at the time of writing this. Its syntax is
closer to both JavaScript and C.

• It is a statically typed language, which means that


variable type checking in Solidity is carried out at
compile time.

• Solidity is also called a contract-oriented


language. In Solidity, contracts are equivalent to
the concept of classes in other object-oriented
programming languages.
Data Types
Value types & Reference types

Value-type variables store Reference type variables


their own data. store the location of the
data. They don’t share the
• Boolean data directly. With the
help of reference type,
• Integers
two different variables
• Address can refer to the same
• Literals location where any
• Integer literals change in one variable can
• String literals affect the other one.
• Hexadecimal
literals • Arrays
• Enums • Structs
• Function types • Data location
• Internal • Mappings
• External
Value Types
Boolean
• This data type has two possible values, true or false

Example:

This statement assigns the value true to v.


Integers
• This data type represents integers. The following table
shows various keywords used to declare integer data types:

Keyword Types Details


Signed to , which means that
integer keywords are available from up to
in increments of 8, for
example: .
Unsigned , ... to ,
integer unsigned integer from 8 bits to 256 bits.
The usage is dependent on the
requirements that how many bits are
required to be stored in the variable

Example :

Note: These types can also be declared with the constant keyword
Address
• This data type holds a 160-bit long (20 byte) value.
• This type has several members that can be used to interact with and query the contracts. Example :
static (fixed size) array
• Balance: The balance member returns the balance of the address in Wei.

• Send: This member is used to send an amount of ether to an address (Ethereum's 160-
bit address) and returns true or false depending on the result of the transaction
dynamically sized array

Example
Get length of trades
• Call functions: The and calls are provided in order to
interact with functions that do not have ABI. These functions should be used with caution
as they are not safe to use due to the impact on type safety and security of the contracts.

• Array value types (fixed size and dynamically sized byte arrays): Solidity has fixed
size and dynamically sized byte arrays. Fixed size keywords range from to
, whereas dynamically sized keywords include and . The
keyword is used for raw byte data and is used for strings encoded in UTF-8. As
these arrays are returned by the value, calling them will incur gas cost. is a
member of array value types and returns the length of the byte array.
Literals
• These used to represent a fixed value.

Integer literals :
• Integer literals are a sequence of decimal numbers in the
range of 0-9.

Example

String literals :
• String literals specify a set of characters written with
double or single quotes.

Example

Hexadecimal literals :
• Hexadecimal literals are prefixed with the keyword hex
and specified within double or single quotation marks.

Example
Enums
• This allows the creation of user-defined types.

Example

• Explicit conversion to and from all integer


types is allowed with enums.
Reference types
Arrays
• Arrays represent a contiguous set of elements of the same size and
type laid out at a memory location.

• The concept is the same as any other programming language. Arrays


have two members named and
Structs
• This data type represents integers. The following table
shows various keywords used to declare integer data types:
Data location
• Data location specifies where a particular complex data type will be stored. Depending
on the default or annotation specified, the location can be storage or memory. This is
applicable to arrays and structs and can be specified using the or
keywords.

• As copying between memory and storage can be quite expensive, specifying a location
can be helpful to control the gas expenditure at times. Calldata is another memory
location that is used to store function arguments.

• Parameters of external functions use calldata memory. By default, parameters of


functions are stored in memory, whereas all other local variables make use of storage.
State variables, on the other hand, are required to use storage.
Mappings
• Mappings are used for a key to value mapping. This
is a way to associate a value with a key. All values
in this map are already initialized with all zeroes,

• This example shows that offers is declared as a mapping.


Another example makes this clearer:

• This is basically a dictionary or a hash table


where string values are mapped to integer
values. The mapping named has string
mapped to value 10
Global variables

• Solidity provides a number of global variables that are always available in


the global namespace.
• These variables provide information about blocks and transactions.
• Additionally, cryptographic functions and address related variables are
available as well.

• A subset of available functions and variables is shown as follows:

// This function is used to compute the Keccak-256 hash of the argument provided
to the function:

// This function returns the associated address of the public key from the elliptic curve
signature:

// This returns the current block number.


Control structures
• Control structures available in solidity language are
and
. They work exactly the same as other languages such
as C-language or JavaScript.

Control
structures
Events

• Events in Solidity can be used to log certain events in EVM logs.


• These are quite useful when external interfaces are required to be notified
of any change or event in the contract.
• These logs are stored on the blockchain in transaction logs. Logs cannot
be accessed from the contracts but are used as a mechanism to notify
change of state or the occurrence of an event (meeting a condition) in the
contract.
Inheritance
• Inheritance is supported in Solidity. The is keyword is used to
derive a contract from another contract. In the following
example, is derived from the
contract. The derived contract has access to all non-private
members of the parent contract
Libraries
• Libraries are deployed only once at a specific address and their
code is called via or opcode of the
EVM. The key idea behind libraries is code reusability.
• They are similar to contracts and act as base contracts to the
calling contracts. A library can be declared as shown in the
following example

• This library can then be called in the contract, as shown


here. First, it needs to be imported and then it can be
used anywhere in the code.
Functions

• Functions in Solidity are modules of code that are


associated with a contract. Functions are declared with a
name, optional parameters, access modifier, optional
constant keyword, and optional return type.

How to define a function:


Input parameters of a Output parameters of a
function function

• Input parameters of a function are • Output parameters of a function


declared in the form of <data type> are declared in the form of <data
<parameter name> type> <parameter name>
Ch.Aravind
HYPERLEDGER
• Hyperledger is not a blockchain, but a project that was
initiated by the Linux Foundation in December 2015 to
advance blockchain technology.
• This project is a collaborative effort by its members to build an
open source distributed ledger framework that can be used to
develop and implement cross-industry blockchain applications
and systems.
• The principal focus is to create and run platforms that support
global business transactions.
• The project also focuses on improving the reliability and
performance of blockchain systems.
PROJECTS UNDER HYPERLEDGER

There are two categories of projects under Hyperledger.

Relevant tools or
Blockchain projects modules that support
these blockchains

• Hyperledger Fabric • Hyperledger Cello


• Hyperledger Sawtooth Lake • Hyperledger Composer
• Hyperledger Iroha • Hyperledger Explorer
• Hyperledger Burrow • Hyperledger Quilt
• Hyperledger Indy
• Iroha was contributed by Soramitsu, Hitachi, NTT
Data, and Colu in September 2016. Iroha is aiming
to build a library of reusable components that
users can choose to run on their own Hyperledger-
based distributed ledgers.
• This project is currently in the incubation state.
• The Sawtooth Lake is a blockchain project Hyperledger Burrow was contributed by Monax,
proposed by Intel in April 2016 with some key who develop blockchain development and
innovations focusing on the decoupling of deployment platforms for business.
ledgers from transactions, flexible usage across • Hyperledger Burrow introduces a modular
multiple business areas using transaction blockchain platform and an Ethereum Virtual
families, and pluggable consensus. Machine (EVM) based smart contract execution
environment.

• This project is under incubation


under Hyperledger. Indy is a
distributed ledger developed for
• The fabric is a blockchain project
building a decentralized identity.
that was proposed by IBM and
• It provides tools, utility libraries, and
DAH (Digital Asset Holdings)
modules which can be used to build
• This blockchain framework
blockchain based digital identities
implementation is intended to
provide a foundation for the
development of blockchain
solutions with a modular
architecture.
• This project aims to build a
blockchain explorer for
Hyperledger Fabric that can be
used to view and query the
transactions, blocks, and
associated data from the
blockchain.
• It also provides network
information and the ability to • The aim behind Cello is to allow easy
interact with chain code. deployment of blockchains. This will
provide an ability to allow "as a service"
deployments of blockchain service.
Currently, this project is in the
• This utility makes the development incubation stage.
of blockchain solutions easier by
allowing business processes to be
described in a business language,
while abstracting away the low-
level smart contract development
details. • This utility implements the Interledger
protocol, which facilitates
interoperability across different
distributed and non-distributed ledger
networks.
HYPERLEDGER AS A PROTOCOL
• Hyperledger is aiming to build new blockchain platforms that are driven by
industry use cases.

• As there have been many contributions made to the Hyperledger project by the
community, Hyperledger blockchain platform is evolving into a protocol for
business transactions. Hyperledger is also evolving into a specification that can be
used as a reference to build blockchain platforms as compared to earlier
blockchain solutions that address only a specific type of industry or requirement.

• a reference architecture is presented that has been published by the Hyperledger


project.
THE REFERENCE ARCHITECTURE
• Identity that provides authorization, identification, and authentication services under
membership services.

• Policy component, which provides policy services.

• Ledger and transactions, which consists of the distributed ledger, ordering service,
network protocols, and endorsement and validation services. This ledger is
updateable only via consensus among the participants of the blockchain network.

• Smart contracts layer, which provides chaincode services in Hyperledger and makes
use of secure container technology to host smart contracts. We will see all these in
more detail in the Hyperledger Fabric section shortly.
Rich
data The modular
queries approach

Privacy and
Portability
confidentiality

REQUIREMENTS
AND
DESIGN GOALS
OF
Interoperability HYPERLEDGER FABRIC Scalability

Deterministic
Auditability
transactions

Identity
Fabric

• Fabric can be defined as a collection of components


providing a foundation layer that can be used to deliver
a blockchain network.
• There are various types and capabilities of a fabric
network, but all fabrics share common attributes such
as immutability and are consensus-driven.
• The fabric is the contribution made initially by IBM and Digital Assets Holding to
the Hyperledger project. This contribution aims to enable a modular, open, and
flexible approach towards building blockchain networks.
• Various functions in the fabric are pluggable, and it also allows the use of any
language to develop smart contracts. This functionality is possible because it is
based on container technology (Docker), which can host any language
• Chaincode is sandboxed in a secure container, which includes a secure operating
system, chaincode language, runtime environment, and SDKs for Go, Java, and
Node.js.
• Transactions in the fabric are private, confidential, and anonymous for general
users, but they can still be traced and linked to the users by authorized auditors.
• As a permissioned network, all participants are required to be registered with the
membership services to access the blockchain network
Membership services
• User identity verification
• User registration
• Assign appropriate permissions to the users depending on
their roles

• Membership services make use of a certificate authority ( Fabric CA ) in order to support identity
management and authorization operations.

• Fabric CA issues enrollment certificates (E-Certs), which are produced by enrollment certificate
authority (E-CA)
Blockchain services
Consensus services:
• A consensus service is responsible for providing the interface to the consensus mechanism.
• Consensus in Hyperledger V1 is implemented as a peer called orderer, which is responsible for
ordering the transactions in sequence into a block. Orderer does not hold smart contracts or
ledgers.
• There are two types of ordering services available in Hyperledger Fabric:

• SOLO: This is a basic ordering service intended to be used for development and testing
purposes.
• Kafka: This is an implementation of Apache Kafka, which provides ordering service. It should
be noted that currently Kafka only provides crash fault tolerance but does not provide
byzantine fault tolerance. This is acceptable in a permissioned network where chances of
malicious actors are almost none.
Distributed ledger
• Blockchain and world state are two main elements of the distributed ledger. Blockchain is simply a
cryptographically linked list of blocks and world state is a key-value database.
• These transactions contain chaincode, which runs transactions that can result in updating the world
state. Each node saves the world state on disk in LevelDB or CouchDB depending on the
implementation.

• Block Header consists of three fields, namely Number, Previous hash,


and Data hash. BLOCK HEADER
• Transaction is made up of multiple fields such as transaction type,
version, timestamp, channel ID, transaction ID, epoch, payload visibility,
chaincode path, chaincode name, chaincode version, creator identity,
signature, chaincode type, input, timeout, endorser identities and TRANSACTION
signatures, proposal hash, chaincode events, response status,
namespace, read set, write set, start key, end key, list of read, and Merkle
tree query summary.
BLOCK METADATA
• Block Metadata consists of creator identity, relevant signatures, last
configuration block number, flag for each transaction included in the
block, and last offset persisted (kafka).
The peer to peer protocol

• The P2P protocol in the Hyperledger Fabric is built using google RPC (gRPC). It uses protocol buffers to
define the structure of the messages.
• There are four main types of messages in Hyperledger Fabric:
• Discovery
• Transaction
• Synchronization
• Consensus

• Discovery messages are exchanged between nodes when starting up in order to discover other
peers on the network.
• Transaction messages are used to deploy, invoke, and query transactions.
• Consensus messages are exchanged during consensus.
• Synchronization messages are passed between nodes to synchronize and keep the blockchain
updated on all nodes.
Ledger storage

• In order to save the state of the ledger, by default, LevelDB is used which is available at each peer.
An alternative is to use CouchDB which provides the ability to run rich queries.
Chaincode services

• These services allow the creation of secure containers that are


used to execute the chaincode.

• Secure container: Chaincode is deployed in Docker containers


that provide a locked down sandboxed environment for smart
contract execution. Currently, Golang is supported as the main
smart contract language, but any other mainstream languages
can be added and enabled if required.

• Secure registry: This provides a record of all images containing


smart contracts.
Components of the fabric
• There are various components that can be part of the Hyperledger Fabric blockchain.
• These components include but are not limited to the ledger, chaincode, consensus mechanism,
access control, events, system monitoring and management, wallets, and system integration
components.
Peers

• Peers participate in maintaining the state of the distributed ledger. They also hold a local copy of
the distributed ledger.
• Peers communicate via gossip protocol.
• There are three types of peers in the Hyperledger Fabric network:
• Endorsing peers or endorsers which simulate the transaction execution and generate a read-
write set. Read is a simulation of transaction's reading of data from the ledger and write is the
set of updates that would be made to the ledger if and when the transaction is executed and
committed to the ledger. Endorses execute and endorse transactions. It should be noted that
an endorser is also a committer too. Endorsement policies are implemented with chaincode
and specify the rules for transaction endorsement.
• Committing peers or committers which receives transaction endorsed by endorsers, verify
them and then update the ledger with the read-write set. A committer verifies the read-write
set generated by the endorsers along with transaction validation.
• Submitters is the third type of peers which has not been implemented yet. It is on the
development roadmap and will be implemented
Orderer nodes

• Ordering nodes receive transactions from endorsers along with read-write sets, arrange them in a
sequence, and send those to committing peers. Committing peers then perform validation and committing
to the ledger.

• All peers make use of certificates issued by membership services.


Clients

• Clients are software that makes use of APIs to interact with the Hyperledger Fabric and propose
transactions.

Channels
• Channels allow the flow of confidential transactions between different parties on the network. They
allow using the same blockchain network but with separate blockchains.

• Channels allow only members of the channel to view the transaction related to them, all other
members of the network will not be able to view the transactions.
World state database
• World state reflects all committed transaction on the blockchain. This is basically a key-value store
which is updated as a result of transactions and chaincode execution. For this purpose, either LevelDB
or CouchDB is used.

• LevelDB is a key-value store whereas CouchDB stores data as JSON objects which allows rich queries to
run against the database.

Transactions
• Transaction messages can be divided into two types: deployment transactions and invocation
transactions. The former is used to deploy new chaincode to the ledger, and the latter is used to call
functions from the smart contract. Transactions can be either public or confidential.

• Public transactions are open and available to all participants whilst confidential transactions are visible
only in a channel open to its participants.
Membership Service Provider (MSP)
• MSP is a modular component that is used to manage identities on the blockchain network. This
provider is used to authenticate clients who want to join the blockchain network.

Smart contracts
• In Hyperledger Fabric same concept of smart contracts is implemented but they are called chain
code instead of smart contracts.
• They contain conditions and parameters to execute transactions and update the ledger.
Chaincode is usually written in Golang

Crypto service provider


• As the name suggests this is a service that provides cryptographic algorithms and standards for usage in
the blockchain network.
• This service provides key management, signature and verification operations, and encryption-
decryption mechanisms.
• This service is used with the membership service to provide support for cryptographic operations for
elements of blockchain such as endorsers, clients, and other nodes and peers.
Scalability and Other Challenges

• Even though various use cases and proof of concept systems have been developed and the
technology works well for many of the scenarios, there still is a need to address some fundamental
limitations that are present in blockchains in order to make this technology more adaptable.

• At the top of the list of these issues comes scalability and then privacy.

• Both of these are important limitations to address, especially as blockchains are envisioned to be
used in privacy-demanding industries too. There are specific requirements around confidentiality of
transactions in finance, law, and health.

• scalability is generally a concern where blockchains do not meet the adequate performance levels
expected by the users.
Approach toward tackling the scalability issue:
• Block size increase
• This is the most debated proposal for increasing blockchain performance (transaction processing
throughput).
• Currently, Bitcoin can process only about three to seven transactions per second, which is a
major inhibiting factor in adapting the Bitcoin blockchain for processing microtransactions.
• Block size in Bitcoin is hardcoded to be 1 MB, but if the block size is increased, it can hold more
transactions and can result in faster confirmation time. There are several Bitcoin Improvement
Proposals (BIPs) made in favor of block size increase. These include BIP 100, BIP 101, BIP 102, BIP
103, and BIP 109.
• In Ethereum, the block size is not limited by hardcoding; instead, it is controlled by a gas limit. In
theory, there is no limit on the size of a block in Ethereum because it's dependent on the amount
of gas, which can increase over time
• a blockchain can be divided into various abstract layers called planes. Each plane is responsible for
performing specific functions. These include the network plane, consensus plane, storage plane, view
plane, and side plane.
• A key function of the network plane is transaction
propagation.
• This plane underutilizes the network bandwidth due
• This plane represents the idea of off-chain to the way transaction validation is performed by a
transactions whereby the concept of Network node before propagation and duplication of
payment or transaction channels is used to Plane transaction propagation, first in the transaction
offload the processing of transactions broadcast phase, and then after mining in a block.
between participants but is still backed by
the main Bitcoin blockchain.
• This layer is responsible for mining and
Consensus achieving consensus.
Side Plane • Bottlenecks in this layer revolve around
Plane
limitations in PoW algorithms whereby
Blockchain increasing consensus speed and
bandwidth results in compromising the
security of the network due to an
increase in the number of forks.

• Bitcoin has a method available called pruning, which


• Bitcoin miners do not need the full allow s a node to operate without the need to keep
blockchain to operate, and a view can be Storage the full blockchain in its storage.
View Plane
constructed out of the complete ledger as a Plane • Pruning means that when a Bitcoin node has
representation of the entire state of the downloaded the blockchain and validated it, it
system, which is sufficient for miners to deletes the old data that it has already validated.
function. This saves storage space. This functionality has
resulted in major improvements from a storage
point of view.
Block interval reduction
• Another proposal is to reduce the time between each block generation. The time between blocks can
be decreased to achieve faster finalization of blocks but may result in less security due to the
increased number of forks.
• Ethereum has achieved a block time of approximately 14 seconds.

Invertible Bloom Lookup Tables

• The key idea is based on the fact that there is no need to transfer all transactions between nodes;
instead, only those that are not already available in the transaction pool of the syncing node are
transferred.
• This allows quicker transaction pool synchronization between nodes, thus increasing the overall
scalability and speed of the Bitcoin
Sharding
• The key idea behind sharding is to split up the tasks into multiple chunks that are then processed by
multiple nodes. This results in improved throughput and reduced storage requirements.
• In blockchains, a similar scheme is employed whereby the state of the network is partitioned into
multiple shards. The state usually includes balances, code, nonce, and storage. Shards are loosely
coupled partitions of a blockchain that run on the same network. There are a few challenges related to
inter-shard communication and consensus on the history of each shard.
State channels
• The basic idea is to use side channels for state updating and processing
transactions off the main chain; once the state is finalized, it is written back
to the main chain, thus offloading the time-consuming operations from the
main blockchain.
• State channels work by performing the following three steps:
1. First, a part of the blockchain state is locked under a smart
contract, ensuring the agreement and business logic between
participants.
2. Now off-chain transaction processing and interaction is started
between the participants that update the state only between
themselves for now. In this step, almost any number of
transactions can be performed without requiring the
blockchain and this is what makes the process fast and a best
candidate for solving blockchain scalability issues. However, it
could be argued that this is not a real on-blockchain solution
such as, for example, sharding, but the end result is a faster,
lighter, and robust network which can prove very useful in
micropayment networks, IoT networks, and many other
applications.
3. Once the final state is achieved, the state channel is closed and
the final state is written back to the main blockchain. At this
stage, the locked part of the blockchain is also unlocked.
• Private blockchain
• Proof of Stake
• Sidechains
• Subchains
• Tree chains
• Block propagation

Plasma
• This proposal describes the idea of running smart contracts on root blockchain (Ethereum MainNet)
and have child blockchains that perform high number of transactions to feedback small amounts of
commitments to the parent chain.
• In this scheme, blockchains are arranged in a tree hierarchy with mining performed only on the root
(main) blockchain which feeds the proofs of security down to child chains. This is also called a Layer-
2 system, like state channels also operate on Layer 2, and not on the main chain.
Privacy
• Privacy of transactions is a much-desired property of blockchains.
• However, due to its very nature, especially in public blockchains, everything is transparent, thus
inhibiting its usage in various industries where privacy is of paramount importance, such as
finance, health, and many others.
• There are different proposals made to address the privacy issue and some progress has already
been made. Several techniques, such as Indistinguishability Obfuscation (IO), usage of
homomorphic encryption, ZKPs, and ring signatures
Indistinguishability Obfuscation

• This cryptographic technique may serve as a silver bullet to all privacy and confidentiality issues
in blockchains but the technology is not yet ready for production deployments.
• IO allows for code obfuscation, which is a very ripe research topic in cryptography and, if applied
to blockchains, can serve as an unbreakable obfuscation mechanism that will turn smart
contracts into a black box.

Homomorphic encryption

• This type of encryption allows operations to be performed on encrypted data. Imagine a


scenario where the data is sent to a cloud server for processing. The server processes it and
returns the output without knowing anything about the data that it has processed.
• d fully homomorphic encryption that allows all operations on encrypted data is still not fully
deployable in production
Zero-Knowledge Proofs

• Zero-Knowledge Proof is a cryptographic technique where no information is revealed


during a transaction except for the interchange of some value known to both the prover
and verifiers (the two ends of the process).
• The idea behind zero-knowledge proof is that a user can prove to another user that they
know an absolute value without actually revealing any other or extra information.

State channels

• Privacy using state channels is also possible, simply due to the fact that all transactions
are run off-chain and the main blockchain does not see the transaction at all except for
the final state output, thus ensuring privacy and confidentiality.
Secure multiparty computation

• The concept of secure multiparty computation is not new and is based on the notion that
data is split into multiple partitions between participating parties under a secret sharing
mechanism which then does the actual processing on the data without the need of the
reconstructing data on a single machine. The output produced after processing is also shared
between the parties.

Usage of hardware to provide confidentiality

Confidential transactions
Security
• Even though blockchains are generally secure and make use of asymmetric and symmetric
cryptography as required throughout the blockchain network, there still are few caveats that
can result in compromising the security of the blockchain.
• There are a few examples of transaction malleability, eclipse attacks, and the possibility of
double spending in bitcoin that, in certain scenarios, have been shown to work by various
researchers. Transaction malleability opens up the possibility of double withdrawal or deposit
by allowing a hacker to change a transaction's unique ID before the Bitcoin network can
confirm it, resulting in a scenario where it would seem that transactions did not occur.
• BIP 62 is one of the proposals along with SegWit that have suggested solutions to solve this
issue.
THANK YOU!

You might also like