0% found this document useful (0 votes)
136 views27 pages

Fabric v2.4 AppDev

Uploaded by

Bilgehan Savgu
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)
136 views27 pages

Fabric v2.4 AppDev

Uploaded by

Bilgehan Savgu
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/ 27

Developing Enterprise

Blockchain Applications with


Hyperledger Fabric

Andrew Coleman, IBM


Agenda
• Hyperledger Fabric

• Smart contracts and blockchain-enabled applications

• The Hyperledger Fabric programming model

• Fabric v2.4 and the Gateway

• Writing client applications


– Submit transactions to modify the ledger
– Evaluate transactions to query ledger state
– Handling private or sensitive data
– Responding to events

• Documentation, samples, tutorials

© 2022 IBM Corporation


What is Hyperledger Fabric?
• Open source, enterprise-grade, permissioned DLT platform.
– Contributions from ~200 developers across 35 organizations.

• Modular, configurable architecture, implementing execute-order-validate model.


– Pluggable consensus protocols – CFT (Raft), BFT (in development).
– Smart contracts authored in general purpose programming languages.
– Transactions executed on a sub-set of peers, according to endorsement policy, ensures scalability.

• Permissioned – participants are known to each other.


– Privacy and confidentiality achieved through channel and private data architecture.

• Supports broad range of industry use-cases.


– Banking, finance, insurance, healthcare, human resources, supply chain, etc.

© 2022 IBM Corporation


Applications and Smart Contracts
Client
Blockchain develops
Application
developers D
API
develops invokes

Smart Contract emits


!
event

Ledger

block
emits
txn txn txn !
event
World state Blockchain
Peer

© 2022 IBM Corporation 4


Fabric Programming Model – Recap
• Provides a consistent programming model and set of APIs to meet needs of application developers.
– Introduced in Fabric v1.4.
– High-level APIs, declarative strategies.
– Maximum functionality with minimum code.
– Seamless access to older low-level APIs.

• Using the vocabulary of the target audience.


– Networks, Contracts, Transactions.
– Connects to Fabric servers via virtual “Gateway”.

• Coherent experience across client application and smart contract.


– Available in Node, Java and Go.

© 2022 IBM Corporation 5


Fabric v2.4 and the Gateway
• Latest release of Fabric contains the high-level gateway logic in the peer.

• New set of ‘lightweight’ client API libraries for developing applications.


– Replaces existing SDKs, which will be deprecated.
– Simpler to use (no CCP files, no commit strategies, no wallets, optimal endorser selection).
– Supports more application patterns (e.g. async submit, offline signing).

• Client app needs only make single (gRPC) connection to its (trusted) gateway peer.
– Gateway peer interacts with other peers to gather endorsements.
– Gateway peer also connects to ordering service nodes to submit transactions.
– Built in support for load balancing and retry logic.

© 2022 IBM Corporation 6


Anatomy of a Smart Contract
const { Contract } = require('fabric-contract-api');
• “Contracts are the central documents that govern
class AssetManager extends Contract {
business transactions.” *
async issue(ctx, assetId, value, description) {
// create asset
• A ‘contract’ is implemented as a class in chaincode. }
...

async transfer(ctx, assetId, cash) {


• The methods in that class are the transaction functions. // exchange owners of asset and cash
...
}

• Each transaction proposal from the client will invoke that async redeem(ctx, assetId) {
named transaction function. // destroy asset
...
}

• Interacts with the ledger via the ‘stub API’. async description(ctx, assetId) {
// lookup asset description
– Encapsulated in the first argument (context). ...
return description;
– E.g., ctx.stub.getState(key) }
}
– E.g., ctx.stub.putState(key, value)
– Forms the read-write set (RW-set) module.exports = AssetManager;

© 2022 IBM Corporation * https://www.justia.com/business-operations/contracts-transactions/ 7


Writing client applications using the Gateway API
• Gateway
– Represents a connected identity to the fabric network via a trusted (gateway) peer.

• Network
– Represents the set of peers associated with a network channel.

• Contract
– Represents a smart contract instance on a network channel.
– evaluateTransaction()
• Invokes a transaction function to read from the ledger (query).
– submitTransaction()
• Invokes a transaction function to modify the ledger.

• Events
– Enables applications to process emitted contract and block events.

© 2022 IBM Corporation 8


Anatomy of a client application

}
Reader certReader = Files.newBufferedReader(certificatePath);
X509Certificate certificate = Identities.readX509Certificate(certReader);
Identity identity = new X509Identity("Org1MSP", certificate);
Identity
Reader keyReader = Files.newBufferedReader(privateKeyPath);
PrivateKey privateKey = Identities.readPrivateKey(keyReader);
Signer signer = Signers.newPrivateKeySigner(privateKey);
} Signer
ManagedChannel grpcChannel = ManagedChannelBuilder.forAddress("peer0.org1.example.org", 7051)
.usePlaintext()
.build();
} gRPC to Peer

Gateway.Builder builder = Gateway.newInstance()

}
.identity(identity)
.signer(signer)
.connection(grpcChannel);
Connect Gateway

}
try (Gateway gateway = builder.connect()) {
Network network = gateway.getNetwork("channelName");
Contract contract = network.getContract("chaincodeName");
Target contract
contract.submitTransaction("CreateAsset", "asset001", "user001", "description");
contract.submitTransaction("TransferAsset", "asset001", "user002");
} Transact
} finally {
grpcChannel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
}

© 2022 IBM Corporation 9


Language idioms
• Where possible, the APIs are designed to adhere to the
common idioms and patterns for each language.
Gateway gateway = Gateway.newInstance()
.identity(identity)
• Java – fluent API style. Uses the ‘builder’ pattern for .signer(signer)
creating Gateway connection, Proposal object, etc. .connection(grpcChannel)
.connect();

const gateway = connect({


client: await newGrpcConnection(),
• Node (JavaScript, TypeScript) – uses object to pass identity: await newIdentity(),
options to Gateway, Proposal, etc. });
signer: await newSigner(),

gateway, err := client.Connect(


identity,
• Go – uses functional arguments With…() to pass options. client.WithSign(sign),
client.WithClientConnection(conn),
)

© 2022 IBM Corporation 10


Connecting to the gateway
• A gateway object represents the connection to the Fabric network with a given identity.

• The application developer provides:


– gRPC connection to the gateway peer.
– Client identity used to transact with the
network. conn, err := grpc.Dial("peer1.example.org:7051", creds)
if err != nil {
– Signing implementation used to generate panic(err)
digital signatures for the client identity. }
defer conn.Close()

import { connect } from '@hyperledger/fabric-gateway’; id := newIdentity()


sign := newSign()
const client = await newGrpcConnection();
gateway, err := client.Connect(
const gateway = connect({ id,
client, client.WithSign(sign),
identity: await newIdentity(), client.WithClientConnection(conn))
signer: await newSigner(), if err != nil {
}); panic(err)
}
defer gateway.Close()

Node Go
© 2022 IBM Corporation 11
Managing a gRPC connection
• The new client API doesn’t create or manage ManagedChannel grpcChannel = NettyChannelBuilder
.forTarget("peer0.org1.example.org:7051")
gRPC connections for you. .sslContext(...)
.build();

Java

• The application developer writes the code to


create the connection, using a gRPC library. connection, err := grpc.Dial(
"peer0.org1.example.org:7051"
grpc.WithTransportCredentials(...),
)

• There is significant overhead associated with Go


establishing gRPC connections, so this
connection should be retained by the
const tlsRootCert = await fs.readFile(tlsCertPath);
application and used for all interactions with const tlsCredentials = grpc.credentials.createSsl(tlsRootCert);
the Fabric Gateway.
const conn = new grpc.Client(‘peer0.org1.example.org:7051’,
tlsCredentials);

Node

© 2022 IBM Corporation 12


Identity and Signing
• Each Gateway instance has a single identity import { Identity } from '@hyperledger/fabric-gateway’;
associated with it.
async function newIdentity(): Promise<Identity> {
– Any transaction submitted to a const credentials = await fs.readFile(certPath);
return { mspId: 'Org1MSP', credentials };
network will use that identity. }

Node

• A signing function must be provided. import { Signer, signers } from '@hyperledger/fabric-gateway';


import * as crypto from 'crypto’;
– Used to generate digital signatures
from a supplied message digest. async function newSigner(): Promise<Signer> {
const privateKeyPem = await fs.readFile(keyPath);
– Gateway API provides standard const privateKey = crypto.createPrivateKey(privateKeyPem);
return signers.newPrivateKeySigner(privateKey);
implementations using factory }
methods.
Node

© 2022 IBM Corporation 13


Submitting transactions
• Any transaction that modifies the ledger must:
const network = gateway.getNetwork(channelName);
– Be endorsed (simulated) by multiple orgs’ peers to const contract = network.getContract(ccName);
satisfy the endorsement policy. await contract.submitTransaction(
– All endorsements agree on the same state changes ‘create’, ‘asset001’, ‘owner1’, ‘my asset');

(RW-set). Node
– Be sent to the ordering service for inclusion in block,
and subsequent validation and commit.
network := gateway.GetNetwork(channelName)
contract := network.GetContract(chaincodeName)

• Using the Gateway API, this can all be achieved in a single _, err := contract.SubmitTransaction(
line of code. "create", "asset001", "owner1", "my asset",
)
– submitTransaction()
Go

© 2022 IBM Corporation 14


Submitting transactions (internals)

1 Endorse
2 Submit
Org2 Org3 3 Broadcast block
Peer Peer

1 3
Ordering
Org 1 Service
Client Org1
submitTransaction() Peer
2

© 2022 IBM Corporation 15


Querying the ledger
Gateway.Builder builder = Gateway.newInstance()
• All interactions with the ledger are done via a smart contract. .identity(identity)
.signer(signer)
– If the contract doesn’t have any transaction functions .connection(grpcChannel);

that return ledger state, then querying can’t be done. try (Gateway gw = builder.connect()) {
Network nw = gw.getNetwork("chnlName");
Contract contract = nw.getContract("ccName");

• A transaction function that doesn’t modify the ledger state byte[] desc = contract.evaluateTransaction(
does not need to be endorsed or sent for ordering. "description", "asset001");
} finally {
– The endorsement policy is only enforced when peers ...
}
attempt to commit a change to the ledger.
Java

• Use the evaluateTransaction() function for this.


const gateway = connect({
client,
identity: await newIdentity(),
• The gateway will choose a peer (preferably itself) that has signer: await newSigner(),
the highest block height. });

– To maximise the chance of returning the most up-to- const network = gateway.getNetwork(channelName);
const contract = network.getContract(ccName);
date value.
const desc = await contract.evaluateTransaction(
‘description’, ‘asset001');

© 2022 IBM Corporation Node 16


Handling private data
• Private Data Collections (PDCs) are used to store sensitive data off-chain.
– Only the hash of the data gets written to the shared ledger.

• The usual application pattern is to send this data to the smart contract using transient data.

• The gateway will take a more guarded approach to which orgs are selected for endorsement.
– Will only select orgs which own a copy of the PDC being written to.
– Could result in gateway not collecting sufficient endorsements.
• Application developer can override which orgs should endorse.

• In order to maintain security of any private data used in transactions, the application should
connect to a gateway peer belonging to the same organization as the client identity.

• If the client identity’s organization does not host any peers, then a peer in another trusted
organization should be used.

© 2022 IBM Corporation 17


How the gateway chooses endorsers (internals)
• Each smart contract (chaincode) is deployed with an endorsement policy. For example,
– 2 OF (Org1, Org2, Org3)
– Org1 AND (Org3 OR Org4)

• However, some transactions might have to satisfy multiple policies at the same time.
– Chaincode to chaincode calls must satisfy the policies of both chaincodes.
– Transactions that write to private data collections will also need to satisfy the collection policy.
– Transactions that read private data will be restricted to orgs that own copies of that PDC.
– Any changes to states that have state-based endorsement (SBE) policies also need to be satisfied.

• The gateway handles this automatically on behalf of the client application.


– First it simulates the transaction proposal in a local peer.
– During simulation, gathers info on which chaincodes, PDCs and SBEs are affected.
– Works with discovery service to derive a set of endorsers required to satisfy combined policies.
– Prefers peers with highest block height to maximize chance of agreement.

© 2022 IBM Corporation 18


submit() and evaluate() – for more options
• An alternative way of invoking a named transaction method.
– submit() and evaluate() methods on Contract class.

• Extra options can be associated with the transaction before it is evaluated or submitted to the ledger.
– E.g., pass transient data.
– E.g., target specific endorsing organizations.

secrets := map[string][]byte{ const secrets = { price: '3000' };


"price": []byte("3000"),
} await contract.submit('transactionName', {
arguments: ['one', 'two’],
result, err := contract.Submit( transientData: secrets,
"transactionName", endorsingOrganizations: ['Org1MSP', 'Org3MSP']
client.WithArguments("one", "two"), });
client.WithTransient(secrets),
client.WithEndorsingOrganizations("Org1MSP", "Org3MSP"),
)

Go Node

© 2022 IBM Corporation 19


Propose, Endorse, Submit – for finer control
• The single submitTransaction() method handles the full var tx = contract.newProposal("transactionName")
transaction lifecycle. .putTransient("price", "3000")
.setEndorsingOrganizations("Org1MSP", "Org3MSP")
– Builds the proposal, collects endorsements, .build()
.endorse();
submits to orderer, awaits commit notification.
var result = tx.getResult();
var txID = tx.getTransactionId()

tx.submit();
• These steps can be invoked individually in your Java
application.
– Allows more options to be assigned to each step.
– Allows results of each step to examined.
– Allows for alternative flow logic, if required.

© 2022 IBM Corporation


Asynchronous submission
• submit() waits for the transaction to be committed the var commit = contract.newProposal("transactionName")
gateway peer’s ledger before returning. .build()
.endorse()
.submitAsync();

• submitAsync() returns as soon as the transaction has var result = commit.getResult();

been sent to the ordering service. // Update UI or reply to REST request before waiting
for commit status
– This returns the result of the transaction function,
– and a ‘commit’ object which can be used to wait Status status = commit.getStatus();
if (!status.isSuccessful()) {
for the commit notification. // Commit failure
}

Java
• Can be used to implement responsive, asynchronous
patterns in the client application. For example,
– Update a UI with the result.
– Return a REST response.

© 2022 IBM Corporation 21


Handling blockchain events
• Client application can receive events.

ctx, cancel := context.WithCancel(context.Background())


• Block events. defer cancel()

– Emitted when a block is added to the ledger. events, err := network.ChaincodeEvents(


ctx,
"chaincodeName",
• Chaincode (contract) events. )
client.WithStartBlock(101),

– As triggered by the emit() method in a if err != nil {


panic(err)
smart contract (on transaction commit). }

for event := range events {


fmt.Printf("Received event: %#v\n", event)
• Supports event playback – from given start block. // Break and cancel the context when done reading.
}

• Supports checkpointing – to resume event listening Go


after a failure or application restart.

© 2022 IBM Corporation 22


Error handling
• Errors returned from the gateway server back to the statusErr := status.Convert(err)
for _, detail := range statusErr.Details() {
client conform to the gRPC richer error model. switch detail := detail.(type) {
case *gateway.ErrorDetail:
– https://www.grpc.io/docs/guides/error/ fmt.Printf("address: %s, mspId: %s, message: %s\n",
detail.Address, detail.MspId, detail.Message)
}
• Error type indicates the point in the transaction flow }

at which a submit failed. Go

var details = ex.getDetails();


• Contains a status code following the gRPC for (var detail : details) {
conventions which indicate whether retry is System.out.println("address: " + detail.getAddress() +
", mspId: " + detail.getMspId() +
appropriate. ", message: " + detail.getMessage());
}
– RW-set mismatches should be retried.
Java
– Invoking transaction with wrong number of
arguments should not.
err.details.forEach(d => {
console.log(d.address, d.mspId, d.address);
});
• If errors are being propagated from downstream
peers/orderers, then these details will be embedded. Node

© 2022 IBM Corporation 23


High availability
• Client app manages gRPC connection lifecycle.

• In a cloud-based network, the client app would typically connect through


an ingress controller which will load balance.
– The gateway is state-less so peer affinity is not an issue.

• The gateway implements retry logic when interacting with other peers
and ordering nodes.

© 2022 IBM Corporation 24


Documentation

© 2022 IBM Corporation 25


Samples, API docs and Tutorials
• New set of asset-transfer samples as described in the Fabric docs.
– Includes smart contracts and client applications in Go, Java & TypeScript.
– From simple to advanced.
– Demonstrates use of private data, state-based endorsement, events, HSM.
– https://github.com/hyperledger/fabric-samples

• JavaDoc, JSDoc, GoDoc API reference.


– https://hyperledger.github.io/fabric-gateway/

• Getting help.
– Fabric mailing list: https://lists.hyperledger.org/g/fabric/topics
– Hyperledger Discord server: https://discord.com/invite/hyperledger
– Stack Overflow: https://stackoverflow.com/questions/tagged/fabric

© 2022 IBM Corporation 26


Summary
• Consistent programming model and set of APIs to meet needs of application developers.

• Coherent experience across client application and smart contracts.

• Maximum functionality with minimum code.

• Documentation, tutorials and samples focus on new programming model.

• Try it out – hands-on session, Wednesday morning.

© 2022 IBM Corporation 27

You might also like