KEMBAR78
blockchain unit 3 | PDF
Unit 3
Hyperledger:
Hyperledger (or the Hyperledger project) is an umbrella project of open source
blockchains and related tools, started in December 2015 by the Linux
Foundation.
and has received contributions from IBM, Intel and SAP Ariba, to support the
collaborative development of blockchain-based distributed ledgers.
Goals
Hyperledger has the following goals:
• Create enterprise grade, open source, distributed ledger frameworks
and code bases to support business transactions
• Provide neutral, open, and community-driven infrastructure supported
by technical and business governance
• Build technical communities to develop blockchain and shared ledger
POCs, use cases, field trails and deployments
• Educate the public about the market opportunity for blockchain
technology
• Promote our community of communities taking a toolkit approach with
many platforms and frameworks
Hyperledger Febric :
Hyperledger Fabric is a permissioned blockchain framework, with a modular
architecture (plug-and-play).
Hyperledger Fabric is an open-source enterprise-grade framework. It relies on
permissioned distributed ledger technology to provide much-needed
applications and solutions.
As it is open-source, anyone can join the project and contribute to it. Right
now, 35 organizations are working together to make Hyperledger Fabric the
best enterprise framework out there.
Hyperledger Fabric is a modular blockchain framework which acts as a
foundation for developing blockchain-based products, solutions and
applications using plug-and-play components that are aimed for use within the
private enterprises.
• It is permissioned
New members of network enroll through a Membership Service
Provider
• Offers several pluggable options
Store data in multiple formats, switchable consensus mechanisms
• Offers the ability to create channels
Allowing a group of participants to create a separate ledger of
transactions
Fabric consist of below major components
• Membership Service Provider(MSP)
• Client
• Peer
• Orderer
1. Membership Service Provider (MSP)
The membership service provider (MSP), is a component that defines the
rules in which, identities are validated, authenticated, and allowed access
to a network.
The MSP is implemented as a Certificate Authority to manage certificates
used to authenticate member identity and roles.
No unknown identities can transact in the Hyperledger Fabric network. It
manages user IDs and auth
enticates all participants on the network which enables Hyperledger
Fabric as a Private and Permissioned network.
The MSP makes use of a Certificate Authority, which is a pluggable
interface that verifies and revokes user certificates upon confirmed
identity.
There are two types of MSPs.
Local MSP: It defines users(Clients) and nodes(peers, orderers). It
defines who has administrative or participatory rights at that level.
Channel MSP: It defines administrative and participatory rights at the
channel level.
2. Client :
Clients are applications that act on behalf of a person to propose
transactions on the network.
The client uses a Fabric SDK in order to communicate with the network.
The client communicates with the SDK in order to Read or Write the data
in a Fabric blockchain and an in-state DB.
Even the client is issued with a certificate from the CA authority in order
to make sure that a valid client has initiated the transaction over the
network.
3. Peer nodes:
Peers are a fundamental element of the network because they host
ledgers and smart contracts.
A peer executes chaincode, accesses ledger data, endorses
transactions, and interfaces with applications. Some peers can
be endorsing peers, or endorsers.
Every chaincode may specify an endorsement policy, which defines the
necessary and sufficient conditions for a valid transaction endorsement.
Types of Peers
Endorsing Peer: (Endores declare one's public approval )
Endorsing peers is a special type of committing peers who have an additional
role to endorse a transaction. They endorse the transaction request which
comes from the client. Each endorsing peer possesses the copy of smart
contract installed and a ledger. The main function of Endorser is to simulate
the transaction. It is executed based on the smart contract on the personal
copy of the ledger, and generates the Read/Write sets which are sent to Client.
Committing Peer:
Peers who commit the block which is received from the Ordering service, in
their own copy of the blockchain. This block contains the list of transactions
where committing peer to validate each transaction and mark it as either valid
or invalid and commits to the block.
Anchor Peer:
As Fabric network can extend across multiple organization, we need
some peers to have communication across an organization. Not all peers
can do this, but these are special peers who are only authorized to do so
which are nothing but Anchor peer. The anchor peers are defined in
Channel configuration.
Leading Peer:
Leader peers are those who communicate or disseminate messages from
Ordering service to other peers in the same organization. These peers use
Gossip protocol to make sure that every peer receives the message.
Leading peers cannot communicate across an organization. If any
Leading peer is not responding or is out of network, then we can select a
leading peer from available peer based on voting or randomly choose one.
4. Orderer
• The ordering service packages transactions into blocks to be delivered to
peers on a channel. It guarantees the transaction delivery in the
network. It communicates with peers and endorsing peers.
• Hyperledger Fabric provides three ordering mechanisms: SOLO, Kafka,
and Simplified Byzantine Fault Tolerance (SBFT)
SOLO
It is the Hyperledger Fabric ordering mechanism most typically used by
developers experimenting with Hyperledger Fabric networks. SOLO involves
a single ordering node. In this, the transactions are ordered in chronological
order to form a block.
Kafka
It is the Hyperledger Fabric ordering mechanism that is recommended for
production use. This ordering mechanism utilizes Apache Kafka, an open
source stream processing platform that provides a unified, high-throughput,
low-latency platform for handling real-time data feeds. In this case, the data
consists of endorsed transactions and RW sets. The Kafka mechanism
provides a crash fault-tolerant solution to ordering service.
SBFT
It stands for Simplified Byzantine Fault Tolerance. This ordering mechanism
is both crash fault-tolerant and byzantine fault-tolerant, meaning that it can
reach agreement even in the presence of malicious or faulty nodes. The
Hyperledger Fabric community has not yet implemented this mechanism,
but it is on their roadmap.
5. Channel :
Channels are a logical structure formed by a collection of peers. This capability allows
a group of peers to create a separate ledger of transactions.
6. Assets :
An asset is anything that has value. An asset has state and
ownership. Assets are represented in Hyperledger Fabric as a
collection of key-value pairs.
7. Shared ledger :
The ledger records the state and ownership of an asset. The ledger
consists of two components:
• The world state describes the state of the ledger at a given
point in time. It’s the database of the ledger.
• The blockchain is a transaction log history that records all
transactions.
The components of a Hyperledger Fabric network (for simplicity,
channels are not shown)
OR
Hyperledger Fabric Architecture
In the fabric architecture, the key components are:
1. Membership Services
2. Certificate Authorities
3. Nodes
4. Peers
Membership Services:
The main function of the membership service is to provide the identity to the users who are
going to transact in the Blockchain network and it is done simply by digital certificates.
Users use this digital certificates to sign the transactions and submit it to the blockchain.
The digital certificate issued to the user would have the authentication to get into the
system and a certain level of privileges for right access depending upon the roles the user
performs.
Certificate Authorities:
The certificate authority in the Hyperledger is pluggable and so it can either be an internal
or an external certificate authority. The certificates rely on the Public Key Infrastructure
where the Certificate authority would announce in the network that a particular public key
is of a particular user and then the user would use his private key to transact.
Nodes:
In the permissioned blockchain network, all the nodes are not equal as in the public
blockchain network where all nodes are equal. In the public blockchain network, every user
is a node and has to download the node software to participate in the blockchain network.
Simply, for the public blockchain, the node software is WALLET. Whereas in the
permissioned blockchain network we have different nodes like client node, peer node
& orderer node and each has different roles to play.
Peers:
Peers are an important component in the Blockchain infrastructure and every organization
in the Blockchain would have one or more peers in the network they are connected with.
The peers again play different roles like endorsing peers & committing peers and these
roles are assigned during the setup of the network.
The orderer node is responsible for the distribution of the data. The main goal of the
ordering service is to totally give ordered set of transactions. The ordering service would
put the transactions from multiple peers in an order and then sends to each peer as a block
to get updated in the ledger.
Chaincode :
• A chaincode typically handles business logic agreed to by members of the network,
so it similar to a “smart contract”.
• All your business logic is inside the chaincode.
• Its written in Go, node.js or java
• Chaincode me installed in every peer and channel.
• Chaincode runs in a secured Docker container isolated from the endorsing peer
process.
• It is a program that implements the business logic and is run on top of blockchain.
• The application can interact with the blockchain by invoking chaincode to manage the
ledger state and keep the transaction record in the ledger.
How many ways to write chaincode in hyperledger fabric ?
In this post, we will talk about chaincode in Go language. Go is very powerful language from
Google.
At high level, you can categories chaincode in below sections.
1. Import section
2. Struct section
3. Init function section
4. Invoke function section
5. Custom functions section
6. Main function section
1. Import Section
As the name suggests, this section contains the details about import statements as shown below.
To start off with our chaincode, we will need to import two libraries into our code.
import (
"fmt"
"github.com/hyperledger/fabric/core/chaincode/shim"
)
Here
fmt - contains Println for debugging/logging
github.com/hyperledger/fabric/core/chaincode/shim - contains the definition for the chaincode interface and
the chaincode stub, which you will need to interact with the ledger, as we described in the Chaincode Key APIs
section
Struct Section
In this section, you define the Chaincode type. In below example, TestChaincode is type that will
implement the chaincode functions, as shown in the following snippet.
type TestChaincode struct {
}
Main function Section
Last section is main function section and this is the starting point of chaincode.
Like all code, our chaincode needs a main function as well. The main function is
defined something like this
func main() {
err := shim.Start(new(SmartContract))
if err != nil {
fmt.Printf("Smart Contract could not be run. Error Occured: %s", err)
} else {
fmt.Println("Smart Contract successfully Initiated")
}
}
Now, we get to the ‘Real’ parts of the chaincode. When a chaincode is called, either one
of the following two functions is called
• Init
• Invoke
Init function Section
Init is called during the chaincode instantiation to initialize data required by the application.
Init is called when chaincode is deployed for the first time, or is upgraded to a newer version. This
function can have any logic that you want to implement, or it can be left empty. Example of a simple
init function is the following:
func (t *SmartContract) Init(stub shim.ChaincodeStubInterface) peer.Response {
fmt.Println("Init Firing!")
return shim.Success(nil)
}
Invoke function Section
In this section, Invoke function of Chaincode is implemented. Invoke method, which gets called
when a transaction is proposed by a client application.
This is the function you actually call to interact with your deployed logic or Smart Contracts. The
invoke function separates the function to be invoked and its arguments through this line
func (t *SmartContract) Invoke(stub shim.ChaincodeStubInterface) peer.Response {
// Retrieve the requested Smart Contract function and arguments
function, args := stub.GetFunctionAndParameters()
fmt.Println("Chaincode Invoke Is Running " + function)
if function == "addAsset" { //Add new Asset
return t.addAsset(stub, args)
}
if function == "deleteAsset" { //Delete an Asset
return t.deleteAsset(stub, args)
}
if function == "queryAsset" { //Query for Asset
return t.queryAsset(stub, args)
}
fmt.Println("Invoke did not find specified function " + function)
return shim.Error("Recieved unknown")
}
As shown above, GetFunctionAndParameters function from shim package helps to get the
function name and arguments to that function. In this example, SDK can either call setValue()
function or getValue() function with required arguments.
function name is getting saved in fn and arguments in args. Later you can check the function
name and based upon that invoke custom functions such as setValue or getValue.
Custom function Section
As shown above, Invoke function can further call custom defined functions. These custom
functions can be defined as per the requirement.
Below is definition of setValue() function, that set the key and value.
func setValue(stub shim.ChaincodeStubInterface, args []string) (string, error) {
if len(args) != 2 {
return "", fmt.Errorf("Incorrect arguments. Expecting a key and a value")
}
err := stub.PutState(args[0], []byte(args[1]))
if err != nil {
return "", fmt.Errorf("Failed to set values: %s", args[0])
}
return args[1], nil
}
The setValue method will modify the world state to include the key/value pair specified. If the key
exists, it will override the value with the new one, using the PutState method; otherwise, a new
asset will be created with the specified value.
Below is definition of getValue() function, that provide the value based upon key.
func getValue(stub shim.ChaincodeStubInterface, args []string) (string, error) {
if len(args) != 1 {
return "", fmt.Errorf("Incorrect arguments. Expecting a key")
}
value, err := stub.GetState(args[0])
if err != nil {
return "", fmt.Errorf("Failed to get value: %s with error: %s", args[0], err)
}
if value == nil {
return "", fmt.Errorf("Value not found: %s", args[0])
}
return string(value), nil
}
The getValue method will attempt to retrieve the value for the specified key. If key is not
passed in the arguments then error is returned and if key is there then GetState function is
called and that in turn query the state database and get the value for that key.
Fabric SDK :
Blockchain is a shared, immutable ledger for recording the history of transactions.
The Linux Foundation’s Hyperledger Fabric, the software implementation of
blockchain IBM is committed to, is a permissioned network. Hyperledger Fabric is
a platform for distributed ledger solutions underpinned by a modular architecture
delivering high degrees of confidentiality, resiliency, flexibility and scalability.
In a Blockchain solution, the Blockchain network works as a back-end with an
application front-end to communicate with the network using a SDK. To set up the
communication between front-end and back-end, Hyperledger Fabric community
offers a number of SDKs for a wide variety of programming languages like the
NodeJS SDK and Java SDK.
Hyperledger Fabric offers a number of SDKs to support developing applications in various
programming languages. There are two application SDKs available for Node.js and Java:
• Node.js SDK and Node.js SDK documentation.
• Java SDK and Java SDK documentation.
In addition, there are two more application SDKs that have not yet been officially released (for
Python and Go), but they are still available for downloading and testing:
• Python SDK.
• Go SDK.
Currently, Node.js and Java support the new application programming model delivered in
Hyperledger Fabric v1.4. Support for Go is planned to be delivered in a later release.
Node.js SDK :
The Hyperledger Fabric SDK for Node.js provides a powerful API to interact with a Hyperledger
Fabric blockchain. The SDK is designed to be used in the Node.js JavaScript runtime.
The SDK's list of features include:
• fabric-network (the recommended API for):
o Submitting transactions to a smart contract.
o Querying a smart contract for the latest application state.
• fabric-client:
o create a new channel
o send channel information to a peer to join
o install chaincode on a peer
o instantiate chaincode in a channel, which involves two
steps: propose and transact
o submitting a transaction, which also involves two steps: propose and transact
o query a chaincode for the latest application state
o various query capabilities:
▪ channel height
▪ block-by-number, block-by-hash
▪ all channels that a peer is part of
▪ all installed chaincodes in a peer
▪ all instantiated chaincodes in a channel
▪ transaction-by-id
▪ channel configuration data
o monitoring events:
▪ connect to a peer's event stream
▪ listen on block events
▪ listen on transactions events and find out if the transaction was
successfully committed to the ledger or marked invalid
▪ listen on custom events produced by chaincodes
o serializable User object with signing capabilities
o hierarchical configuration settings with multiple layers of overrides: files,
environment variable, program arguments, in-memory settings
o logging utility with a built-in logger (winston) and can be overriden with a
number of popular loggers including log4js and bunyan
o pluggable CryptoSuite interface describe the cryptographic operations
required for successful interactions with the Fabric. Two implementations are
provided out of box:
▪ Software-based ECDSA
▪ PKCS#11-compliant ECDSA
o pluggable State Store interface for persisting state caches such as users
▪ File-based store
▪ CouchDB-base store which works with both CouchDB database and
IBM Cloudant
o customizable Crypto Key Store for any software-based cryptographic suite
implementation
o supports both TLS (grpcs://) or non-TLS (grpc://) connections to peers and
orderers, see Remote which is the superclass for peers and orderers
The SDK is made up of 4 top-level modules that can be accessed through the navigation
menu Modules:
• fabric-network: Provides high level APIs for client applications to submit transactions
and evaluate queries for a smart contract (chaincode).
• api: Pluggable APIs for application developers to supply alternative implementations
of key interfaces used by the SDK. For each interface there are built-in default
implementations.
• fabric-client: Provides APIs to interact with the core components of a Hypreledger
Fabric-based blockchain network, namely the peers, orderers and event streams.
• fabric-ca-client: Provides APIs to interact with the optional component, fabric-ca, that
contains services for membership management.
JAVA SDK :
The SDK helps facilitate Java applications to manage the lifecycle of Hyperledger channels
and user chaincode. The SDK also provides a means to execute user chaincode, query blocks
and transactions on the channel, and monitor events on the channel.
Flow
1. Generate the artifacts using cryptogen and configtx for peers and channel in
network. Currently these are already generated and provided in the code
repository to use as-is.
2. Build the network using docker-compose and the generated artifacts.
3. Use Hyperledger Fabric Java SDK APIs to work with and manage the network.
o Create and initialize the channel
o Install and instantiate the chaincode
o Register and enroll the users
o Perform invoke and query to test the network
Included Components
• Hyperledger Fabric:
Hyperledger Fabric is a platform for distributed ledger solutions
underpinned by a modular architecture delivering high degrees of
confidentiality, resiliency, flexibility and scalability.
• Docker:
Docker is an open platform for developers and sysadmins to build,
ship, and run distributed applications.
• Hyperledger Fabric Java SDK
Hyperledger Composer
Hyperledger Composer is a set of tools that allows various business owners,
operators, and developers a way to create blockchain applications and smart
contracts aimed at solving business problems and/or improving operational
efficiencies.
Hyperledger Composer includes an object-oriented modeling language that is
used to define the domain model for a business network definition.
Hyperledger Composer is an extensive, open development toolset and
framework to make developing blockchain applications easier. Our primary
goal is to accelerate time to value, and make it easier to integrate your
blockchain applications with the existing business systems. You can use
Composer to rapidly develop use cases and deploy a blockchain solution in
weeks rather than months. Composer allows you to model your business
network and integrate existing systems and data with your blockchain
applications.
You can use Hyperledger Composer to quickly model your current business
network, containing your existing assets and the transactions related to them;
assets are tangible or intangible goods, services, or property. As part of your
business network model, you define the transactions which can interact with
assets. Business networks also include the participants who interact with them,
each of which can be associated with a unique identity, across multiple
business networks.
Hyperledger Composer is a set of collaboration tools for business owners
and developers that make it easy to write chaincode for Hyperledger Fabric
and decentralized applications (DApps). With Composer, you can quickly
build POC and deploy chaincode to the blockchain in a short amount of
time. Hyperledger Composer consists of the following toolsets:
• A modeling language called CTO: A domain modeling language
that defines a business model, concept, and function for a business
network definition
• Playground: Rapid configuration, deployment, and testing of a
business network
• Command-line interface (CLI) tools: The client command-line tool
is used to integrate business network with Hyperledger Fabric
Composer-CLI is the most important tool for Composer deployment; it
contains all the essential command-line operations. Other very useful tools
include Composer REST server, generator Hyperledger
Composer, Yeoman, and Playground. Composer CLI provides many useful
tools for developers.
The Hyperledger Composer Business Network and Development
Components
• You can use Hyperledger Composer to quickly build a business
network. Here, you can define assets, participants, transactions,
access-control rules, and optional events and queries in the business
network.
• A model (.cto) file contains all of the preceding definitions in the
business network. Asset is an associate with a real-world object, and
participants have their own unique identity. The transactions will
interact with assets.
• Participants can do this via transactions. The structure of a business
network also includes an access control (permissions.acl), which
specifies the access-control rules, a script (logic.js) file that
implements transaction logic, and a package.json file that contains
project metadata:
```````
``

blockchain unit 3

  • 1.
    Unit 3 Hyperledger: Hyperledger (orthe Hyperledger project) is an umbrella project of open source blockchains and related tools, started in December 2015 by the Linux Foundation. and has received contributions from IBM, Intel and SAP Ariba, to support the collaborative development of blockchain-based distributed ledgers. Goals Hyperledger has the following goals: • Create enterprise grade, open source, distributed ledger frameworks and code bases to support business transactions • Provide neutral, open, and community-driven infrastructure supported by technical and business governance • Build technical communities to develop blockchain and shared ledger POCs, use cases, field trails and deployments • Educate the public about the market opportunity for blockchain technology • Promote our community of communities taking a toolkit approach with many platforms and frameworks Hyperledger Febric : Hyperledger Fabric is a permissioned blockchain framework, with a modular architecture (plug-and-play).
  • 2.
    Hyperledger Fabric isan open-source enterprise-grade framework. It relies on permissioned distributed ledger technology to provide much-needed applications and solutions. As it is open-source, anyone can join the project and contribute to it. Right now, 35 organizations are working together to make Hyperledger Fabric the best enterprise framework out there. Hyperledger Fabric is a modular blockchain framework which acts as a foundation for developing blockchain-based products, solutions and applications using plug-and-play components that are aimed for use within the private enterprises. • It is permissioned New members of network enroll through a Membership Service Provider • Offers several pluggable options Store data in multiple formats, switchable consensus mechanisms • Offers the ability to create channels Allowing a group of participants to create a separate ledger of transactions Fabric consist of below major components • Membership Service Provider(MSP) • Client • Peer • Orderer 1. Membership Service Provider (MSP) The membership service provider (MSP), is a component that defines the rules in which, identities are validated, authenticated, and allowed access to a network. The MSP is implemented as a Certificate Authority to manage certificates used to authenticate member identity and roles.
  • 3.
    No unknown identitiescan transact in the Hyperledger Fabric network. It manages user IDs and auth enticates all participants on the network which enables Hyperledger Fabric as a Private and Permissioned network. The MSP makes use of a Certificate Authority, which is a pluggable interface that verifies and revokes user certificates upon confirmed identity. There are two types of MSPs. Local MSP: It defines users(Clients) and nodes(peers, orderers). It defines who has administrative or participatory rights at that level. Channel MSP: It defines administrative and participatory rights at the channel level. 2. Client : Clients are applications that act on behalf of a person to propose transactions on the network. The client uses a Fabric SDK in order to communicate with the network. The client communicates with the SDK in order to Read or Write the data in a Fabric blockchain and an in-state DB. Even the client is issued with a certificate from the CA authority in order to make sure that a valid client has initiated the transaction over the network. 3. Peer nodes: Peers are a fundamental element of the network because they host ledgers and smart contracts. A peer executes chaincode, accesses ledger data, endorses transactions, and interfaces with applications. Some peers can be endorsing peers, or endorsers. Every chaincode may specify an endorsement policy, which defines the necessary and sufficient conditions for a valid transaction endorsement. Types of Peers
  • 4.
    Endorsing Peer: (Endoresdeclare one's public approval ) Endorsing peers is a special type of committing peers who have an additional role to endorse a transaction. They endorse the transaction request which comes from the client. Each endorsing peer possesses the copy of smart contract installed and a ledger. The main function of Endorser is to simulate the transaction. It is executed based on the smart contract on the personal copy of the ledger, and generates the Read/Write sets which are sent to Client. Committing Peer: Peers who commit the block which is received from the Ordering service, in their own copy of the blockchain. This block contains the list of transactions where committing peer to validate each transaction and mark it as either valid or invalid and commits to the block. Anchor Peer: As Fabric network can extend across multiple organization, we need some peers to have communication across an organization. Not all peers can do this, but these are special peers who are only authorized to do so which are nothing but Anchor peer. The anchor peers are defined in Channel configuration. Leading Peer: Leader peers are those who communicate or disseminate messages from Ordering service to other peers in the same organization. These peers use Gossip protocol to make sure that every peer receives the message. Leading peers cannot communicate across an organization. If any Leading peer is not responding or is out of network, then we can select a leading peer from available peer based on voting or randomly choose one. 4. Orderer • The ordering service packages transactions into blocks to be delivered to peers on a channel. It guarantees the transaction delivery in the network. It communicates with peers and endorsing peers. • Hyperledger Fabric provides three ordering mechanisms: SOLO, Kafka, and Simplified Byzantine Fault Tolerance (SBFT) SOLO
  • 5.
    It is theHyperledger Fabric ordering mechanism most typically used by developers experimenting with Hyperledger Fabric networks. SOLO involves a single ordering node. In this, the transactions are ordered in chronological order to form a block. Kafka It is the Hyperledger Fabric ordering mechanism that is recommended for production use. This ordering mechanism utilizes Apache Kafka, an open source stream processing platform that provides a unified, high-throughput, low-latency platform for handling real-time data feeds. In this case, the data consists of endorsed transactions and RW sets. The Kafka mechanism provides a crash fault-tolerant solution to ordering service. SBFT It stands for Simplified Byzantine Fault Tolerance. This ordering mechanism is both crash fault-tolerant and byzantine fault-tolerant, meaning that it can reach agreement even in the presence of malicious or faulty nodes. The Hyperledger Fabric community has not yet implemented this mechanism, but it is on their roadmap. 5. Channel : Channels are a logical structure formed by a collection of peers. This capability allows a group of peers to create a separate ledger of transactions. 6. Assets : An asset is anything that has value. An asset has state and ownership. Assets are represented in Hyperledger Fabric as a collection of key-value pairs. 7. Shared ledger : The ledger records the state and ownership of an asset. The ledger consists of two components: • The world state describes the state of the ledger at a given point in time. It’s the database of the ledger. • The blockchain is a transaction log history that records all transactions. The components of a Hyperledger Fabric network (for simplicity, channels are not shown)
  • 6.
    OR Hyperledger Fabric Architecture Inthe fabric architecture, the key components are: 1. Membership Services
  • 7.
    2. Certificate Authorities 3.Nodes 4. Peers Membership Services: The main function of the membership service is to provide the identity to the users who are going to transact in the Blockchain network and it is done simply by digital certificates. Users use this digital certificates to sign the transactions and submit it to the blockchain. The digital certificate issued to the user would have the authentication to get into the system and a certain level of privileges for right access depending upon the roles the user performs. Certificate Authorities: The certificate authority in the Hyperledger is pluggable and so it can either be an internal or an external certificate authority. The certificates rely on the Public Key Infrastructure where the Certificate authority would announce in the network that a particular public key is of a particular user and then the user would use his private key to transact. Nodes: In the permissioned blockchain network, all the nodes are not equal as in the public blockchain network where all nodes are equal. In the public blockchain network, every user is a node and has to download the node software to participate in the blockchain network. Simply, for the public blockchain, the node software is WALLET. Whereas in the permissioned blockchain network we have different nodes like client node, peer node & orderer node and each has different roles to play.
  • 8.
    Peers: Peers are animportant component in the Blockchain infrastructure and every organization in the Blockchain would have one or more peers in the network they are connected with. The peers again play different roles like endorsing peers & committing peers and these roles are assigned during the setup of the network. The orderer node is responsible for the distribution of the data. The main goal of the ordering service is to totally give ordered set of transactions. The ordering service would put the transactions from multiple peers in an order and then sends to each peer as a block to get updated in the ledger. Chaincode : • A chaincode typically handles business logic agreed to by members of the network, so it similar to a “smart contract”. • All your business logic is inside the chaincode. • Its written in Go, node.js or java • Chaincode me installed in every peer and channel. • Chaincode runs in a secured Docker container isolated from the endorsing peer process. • It is a program that implements the business logic and is run on top of blockchain. • The application can interact with the blockchain by invoking chaincode to manage the ledger state and keep the transaction record in the ledger.
  • 9.
    How many waysto write chaincode in hyperledger fabric ? In this post, we will talk about chaincode in Go language. Go is very powerful language from Google. At high level, you can categories chaincode in below sections. 1. Import section 2. Struct section 3. Init function section 4. Invoke function section 5. Custom functions section 6. Main function section 1. Import Section As the name suggests, this section contains the details about import statements as shown below. To start off with our chaincode, we will need to import two libraries into our code. import ( "fmt" "github.com/hyperledger/fabric/core/chaincode/shim" ) Here fmt - contains Println for debugging/logging github.com/hyperledger/fabric/core/chaincode/shim - contains the definition for the chaincode interface and the chaincode stub, which you will need to interact with the ledger, as we described in the Chaincode Key APIs section Struct Section In this section, you define the Chaincode type. In below example, TestChaincode is type that will implement the chaincode functions, as shown in the following snippet. type TestChaincode struct { } Main function Section Last section is main function section and this is the starting point of chaincode.
  • 10.
    Like all code,our chaincode needs a main function as well. The main function is defined something like this func main() { err := shim.Start(new(SmartContract)) if err != nil { fmt.Printf("Smart Contract could not be run. Error Occured: %s", err) } else { fmt.Println("Smart Contract successfully Initiated") } } Now, we get to the ‘Real’ parts of the chaincode. When a chaincode is called, either one of the following two functions is called • Init • Invoke Init function Section Init is called during the chaincode instantiation to initialize data required by the application. Init is called when chaincode is deployed for the first time, or is upgraded to a newer version. This function can have any logic that you want to implement, or it can be left empty. Example of a simple init function is the following: func (t *SmartContract) Init(stub shim.ChaincodeStubInterface) peer.Response { fmt.Println("Init Firing!") return shim.Success(nil) } Invoke function Section In this section, Invoke function of Chaincode is implemented. Invoke method, which gets called when a transaction is proposed by a client application. This is the function you actually call to interact with your deployed logic or Smart Contracts. The invoke function separates the function to be invoked and its arguments through this line func (t *SmartContract) Invoke(stub shim.ChaincodeStubInterface) peer.Response { // Retrieve the requested Smart Contract function and arguments
  • 11.
    function, args :=stub.GetFunctionAndParameters() fmt.Println("Chaincode Invoke Is Running " + function) if function == "addAsset" { //Add new Asset return t.addAsset(stub, args) } if function == "deleteAsset" { //Delete an Asset return t.deleteAsset(stub, args) } if function == "queryAsset" { //Query for Asset return t.queryAsset(stub, args) } fmt.Println("Invoke did not find specified function " + function) return shim.Error("Recieved unknown") } As shown above, GetFunctionAndParameters function from shim package helps to get the function name and arguments to that function. In this example, SDK can either call setValue() function or getValue() function with required arguments. function name is getting saved in fn and arguments in args. Later you can check the function name and based upon that invoke custom functions such as setValue or getValue. Custom function Section As shown above, Invoke function can further call custom defined functions. These custom functions can be defined as per the requirement. Below is definition of setValue() function, that set the key and value. func setValue(stub shim.ChaincodeStubInterface, args []string) (string, error) { if len(args) != 2 { return "", fmt.Errorf("Incorrect arguments. Expecting a key and a value") } err := stub.PutState(args[0], []byte(args[1])) if err != nil { return "", fmt.Errorf("Failed to set values: %s", args[0]) } return args[1], nil }
  • 12.
    The setValue methodwill modify the world state to include the key/value pair specified. If the key exists, it will override the value with the new one, using the PutState method; otherwise, a new asset will be created with the specified value. Below is definition of getValue() function, that provide the value based upon key. func getValue(stub shim.ChaincodeStubInterface, args []string) (string, error) { if len(args) != 1 { return "", fmt.Errorf("Incorrect arguments. Expecting a key") } value, err := stub.GetState(args[0]) if err != nil { return "", fmt.Errorf("Failed to get value: %s with error: %s", args[0], err) } if value == nil { return "", fmt.Errorf("Value not found: %s", args[0]) } return string(value), nil } The getValue method will attempt to retrieve the value for the specified key. If key is not passed in the arguments then error is returned and if key is there then GetState function is called and that in turn query the state database and get the value for that key. Fabric SDK : Blockchain is a shared, immutable ledger for recording the history of transactions. The Linux Foundation’s Hyperledger Fabric, the software implementation of blockchain IBM is committed to, is a permissioned network. Hyperledger Fabric is a platform for distributed ledger solutions underpinned by a modular architecture delivering high degrees of confidentiality, resiliency, flexibility and scalability.
  • 13.
    In a Blockchainsolution, the Blockchain network works as a back-end with an application front-end to communicate with the network using a SDK. To set up the communication between front-end and back-end, Hyperledger Fabric community offers a number of SDKs for a wide variety of programming languages like the NodeJS SDK and Java SDK. Hyperledger Fabric offers a number of SDKs to support developing applications in various programming languages. There are two application SDKs available for Node.js and Java: • Node.js SDK and Node.js SDK documentation. • Java SDK and Java SDK documentation. In addition, there are two more application SDKs that have not yet been officially released (for Python and Go), but they are still available for downloading and testing: • Python SDK. • Go SDK. Currently, Node.js and Java support the new application programming model delivered in Hyperledger Fabric v1.4. Support for Go is planned to be delivered in a later release. Node.js SDK : The Hyperledger Fabric SDK for Node.js provides a powerful API to interact with a Hyperledger Fabric blockchain. The SDK is designed to be used in the Node.js JavaScript runtime. The SDK's list of features include: • fabric-network (the recommended API for): o Submitting transactions to a smart contract. o Querying a smart contract for the latest application state. • fabric-client: o create a new channel o send channel information to a peer to join o install chaincode on a peer o instantiate chaincode in a channel, which involves two steps: propose and transact o submitting a transaction, which also involves two steps: propose and transact o query a chaincode for the latest application state o various query capabilities: ▪ channel height ▪ block-by-number, block-by-hash ▪ all channels that a peer is part of ▪ all installed chaincodes in a peer
  • 14.
    ▪ all instantiatedchaincodes in a channel ▪ transaction-by-id ▪ channel configuration data o monitoring events: ▪ connect to a peer's event stream ▪ listen on block events ▪ listen on transactions events and find out if the transaction was successfully committed to the ledger or marked invalid ▪ listen on custom events produced by chaincodes o serializable User object with signing capabilities o hierarchical configuration settings with multiple layers of overrides: files, environment variable, program arguments, in-memory settings o logging utility with a built-in logger (winston) and can be overriden with a number of popular loggers including log4js and bunyan o pluggable CryptoSuite interface describe the cryptographic operations required for successful interactions with the Fabric. Two implementations are provided out of box: ▪ Software-based ECDSA ▪ PKCS#11-compliant ECDSA o pluggable State Store interface for persisting state caches such as users ▪ File-based store ▪ CouchDB-base store which works with both CouchDB database and IBM Cloudant o customizable Crypto Key Store for any software-based cryptographic suite implementation o supports both TLS (grpcs://) or non-TLS (grpc://) connections to peers and orderers, see Remote which is the superclass for peers and orderers The SDK is made up of 4 top-level modules that can be accessed through the navigation menu Modules: • fabric-network: Provides high level APIs for client applications to submit transactions and evaluate queries for a smart contract (chaincode). • api: Pluggable APIs for application developers to supply alternative implementations of key interfaces used by the SDK. For each interface there are built-in default implementations. • fabric-client: Provides APIs to interact with the core components of a Hypreledger Fabric-based blockchain network, namely the peers, orderers and event streams. • fabric-ca-client: Provides APIs to interact with the optional component, fabric-ca, that contains services for membership management. JAVA SDK : The SDK helps facilitate Java applications to manage the lifecycle of Hyperledger channels and user chaincode. The SDK also provides a means to execute user chaincode, query blocks and transactions on the channel, and monitor events on the channel.
  • 15.
    Flow 1. Generate theartifacts using cryptogen and configtx for peers and channel in network. Currently these are already generated and provided in the code repository to use as-is. 2. Build the network using docker-compose and the generated artifacts. 3. Use Hyperledger Fabric Java SDK APIs to work with and manage the network. o Create and initialize the channel o Install and instantiate the chaincode o Register and enroll the users o Perform invoke and query to test the network Included Components • Hyperledger Fabric: Hyperledger Fabric is a platform for distributed ledger solutions underpinned by a modular architecture delivering high degrees of confidentiality, resiliency, flexibility and scalability. • Docker: Docker is an open platform for developers and sysadmins to build, ship, and run distributed applications. • Hyperledger Fabric Java SDK
  • 16.
    Hyperledger Composer Hyperledger Composeris a set of tools that allows various business owners, operators, and developers a way to create blockchain applications and smart contracts aimed at solving business problems and/or improving operational efficiencies. Hyperledger Composer includes an object-oriented modeling language that is used to define the domain model for a business network definition. Hyperledger Composer is an extensive, open development toolset and framework to make developing blockchain applications easier. Our primary goal is to accelerate time to value, and make it easier to integrate your blockchain applications with the existing business systems. You can use Composer to rapidly develop use cases and deploy a blockchain solution in weeks rather than months. Composer allows you to model your business network and integrate existing systems and data with your blockchain applications. You can use Hyperledger Composer to quickly model your current business network, containing your existing assets and the transactions related to them; assets are tangible or intangible goods, services, or property. As part of your business network model, you define the transactions which can interact with assets. Business networks also include the participants who interact with them, each of which can be associated with a unique identity, across multiple business networks.
  • 17.
    Hyperledger Composer isa set of collaboration tools for business owners and developers that make it easy to write chaincode for Hyperledger Fabric and decentralized applications (DApps). With Composer, you can quickly build POC and deploy chaincode to the blockchain in a short amount of time. Hyperledger Composer consists of the following toolsets: • A modeling language called CTO: A domain modeling language that defines a business model, concept, and function for a business network definition • Playground: Rapid configuration, deployment, and testing of a business network • Command-line interface (CLI) tools: The client command-line tool is used to integrate business network with Hyperledger Fabric Composer-CLI is the most important tool for Composer deployment; it contains all the essential command-line operations. Other very useful tools include Composer REST server, generator Hyperledger Composer, Yeoman, and Playground. Composer CLI provides many useful tools for developers. The Hyperledger Composer Business Network and Development Components • You can use Hyperledger Composer to quickly build a business network. Here, you can define assets, participants, transactions,
  • 18.
    access-control rules, andoptional events and queries in the business network. • A model (.cto) file contains all of the preceding definitions in the business network. Asset is an associate with a real-world object, and participants have their own unique identity. The transactions will interact with assets. • Participants can do this via transactions. The structure of a business network also includes an access control (permissions.acl), which specifies the access-control rules, a script (logic.js) file that implements transaction logic, and a package.json file that contains project metadata: ```````
  • 19.