m Fabric Dev 1

Key Points

  1. focus is the new program model for smart contracts, IBM VSCode extension
  2. looking for full Composer modeling language to be implemented in v2x ( not a priority for team now )
  3. v2x has new chaincode life cycle for multiple orderers, multiple contract endorsements
  4. new Node SDK is completely refactored in v2x, won't be backported to v1x
  5. Composer is deprecated but under v1.4x it can still be used to prototype solutions


References

Reference_description_with_linked_URLs_______________________Notes______________________________________________________________
https://wiki.hyperledger.org/display/HYP/Paid+Tooling+PolicyFabric paid support and community support services **

 https://github.com/hyperledger-labs/fabric-operations-console

Fabric Operations Console

https://github.com/hyperledger-labs/fabric-token-sdk

Fabric Token SDK: 

[FireFly] Fabric plugin - 

FireFly is rapidly moving toward a full version 1.0.

https://github.com/hyperledger/bevelBevel to manage deployments to K8S

https://www.hyperledger.org/blog/2021/07/07/the-latest-on-minifabric-a-hyperledger-lab-aimed-at-accelerating-the-move-to-production     

Mini Fabric    

https://github.com/hyperledger/fabric-samplesFabric sample apps and smart contracts **
https://github.com/hyperledger/fabric-samples/tree/main/token-utxoThe UTXO token smart contract demonstrates how to create and transfer fungible tokens using a UTXO 
https://github.com/hyperledger/fabric-samples/tree/main/asset-transfer-basic

his sample shows create, read, update, transfer and delete of an asset.

https://hyperledger-fabric.readthedocs.io/en/latest/write_first_app.html

https://github.com/hyperledger/fabric-samples/tree/main/asset-transfer-eventsshows sending and receiving of events during create / update / delete of an asset, and during transfer of an asset to a new owner.
https://github.com/hyperledger/fabric-samples/tree/main/asset-transfer-private-datashows sending and receiving of asset along with its private data owned by organizations during create / delete of an asset , and during transfer of an asset to a new owner
https://github.com/hyperledger/fabric-samples/tree/main/asset-transfer-secured-agreementhow to transfer a private asset between two organizations without publicly sharing data .
https://github.com/hyperledger/fabric-samples/tree/main/full-stack-asset-transfer-guide

how a generic asset transfer solution can be modeled and deployed to take advantage of a blockchains qualities of service.

contract and app development. Kubernetes cloud deployment example

https://hyperledger.github.io/fabric-gateway/main/api/java/Using Fabric gateway API to connect to a Fabric net, write and read transaction
<< compare to DAML for simplicity 


Fabric chaincode development, deployment and test w Firefly - Jim Zhang 1/10/23see firefly youtube channel for video, pdf, chat text


https://wiki.hyperledger.org/pages/viewpage.action?pageId=6423554Fabric Dev Meeting Notes / Slides / mp4 – biweekly meetings
https://chat.hyperledger.org/channel/fabric-maintainersRocketchat channel ...  chat.hyperledger.org


https://jira.hyperledger.org/browse/FABN-1347

https://drive.google.com/open?id=1gTJHqGIlE8hzX3m6se-XfEr5HmSQEgH8

slides for Nodejs SDK refactor in v2x
https://www.ibm.com/blogs/blockchain/category/blockchain-developers/hyperledger-fabric/Fabric Developer IBM blog - tips, articles
https://github.com/hyperledger-labsHyperledger Labs project code  - most are Fabric now
https://wiki.hyperledger.org/display/labs/Hyperledger+Labs+HomeHyperledger Labs home


Other Fabric Solutions

https://github.com/hyperledger-labs/umbra

https://wiki.hyperledger.org/display/INTERN/Scaling+Real+World+Hyperledger+Fabric+Deployments

Umbra- simulate Fabric environment on mininet with Python

- create a platform by the means of Mininet and plugins for Hyperledger distributed ledgers so that they can run under emulation in a lab environment.

Tutorials

https://www.ibm.com/downloads/cas/OK5M0E49

Blockchain for Dummies -IBM- XIM12354USEN.PDF

IBM Blockchain for Dummies - 3rd edition

https://drive.google.com/open?id=1nK6OSD0tnekaKYHeypHCegk-Alk5-ZZU


Fabric-HANDSON_BLOCKCHAIN_WITH_HYPERLEDGER - Composer, Fabric v1x 

long but very good - from IBM

https://hyperledger-fabric.readthedocs.io/en/release-1.3/getting_started.html

https://hyperledger-fabric.readthedocs.io/en/release-2.0/getting_started.html

Getting Started

https://hyperledger-fabric.readthedocs.io/en/release-1.3/tutorials.html

https://hyperledger-fabric.readthedocs.io/en/release-2.0/tutorials.html

Tutorials




Articles

https://hub.packtpub.com/installing-a-blockchain-network-using-hyperledger-fabric-and-composertutorial/


Creating a blockchain network using Fabric and Composer - 2019 - packt> tutorial
https://drive.google.com/open?id=1l-xCY1p8MCCTBBlDJ4zgc1Kv8-543QZGOReilly ebook on Enterprise Blockchain
https://www.ibm.com/cloud/garage/architectures/blockchainArchitecture/0_1Fabric reference architecture
https://developer.ibm.com/patterns/implementing-blockchain-events-using-ibp-vscode-extension/Emit events from blockchain to automate workflow

https://developer.ibm.com/tutorials/cl-ibm-blockchain-101-quick-start-guide-for-developers-bluemix-trs/

https://drive.google.com/open?id=1I49bfcy8RMk5OI4fOz25SrB2cIe6OZEf

Blockchain 101 Quick Start Guide

Start a blockchain on IBM Cloud free tier

https://www.ibm.com/blogs/blockchain/2019/08/why-is-interoperability-important-in-blockchain/Cuomo - Blockchain Interoperability Concepts - 2019


Fabric Notes


fabric-notes-v2.docx file
fabric-notes-v2 gdoc
fabric-notes-v2 - Google Docs.pdf flle


Key Concepts


Program Model on v2.4 - Andrew Coleman

https://static.sched.com/hosted_files/hgf22/1e/Fabric-v2.4-AppDev.pdf

Fabric-v2.4-AppDev.pdf link

Fabric-v2.4-AppDev.pdf file

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.


Fabric Smart Contracts


Smart Contract notes____
• “Contracts are the central documents that govern
business transactions.” *
• A ‘contract’ is implemented as a class in chaincode.
• The methods in that class are the transaction functions.
• Each transaction proposal from the client will invoke that
named transaction function.
• Interacts with the ledger via the ‘stub API’.
– Encapsulated in the first argument (context).
– E.g., ctx.stub.getState(key)
– E.g., ctx.stub.putState(key, value)
– Forms the read-write set (RW-set)

// AssetManager Smart Contract class
const { Contract } = require('fabric-contract-api');
class AssetManager extends Contract {
async issue(ctx, assetId, value, description) {
// create asset
...
}
async transfer(ctx, assetId, cash) {
// exchange owners of asset and cash
...
}
async redeem(ctx, assetId) {
// destroy asset
...
}
async description(ctx, assetId) {
// lookup asset description
...
return description;
}
}
module.exports = AssetManager;

Write Client Apps 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.



// identity
Reader certReader = Files.newBufferedReader(certificatePath);
X509Certificate certificate = Identities.readX509Certificate(certReader);
Identity identity = new X509Identity("Org1MSP", certificate);
// signer
Reader keyReader = Files.newBufferedReader(privateKeyPath);
PrivateKey privateKey = Identities.readPrivateKey(keyReader);
Signer signer = Signers.newPrivateKeySigner(privateKey);
// grpc to peer
ManagedChannel grpcChannel = ManagedChannelBuilder.forAddress("peer0.org1.example.org", 7051)
.usePlaintext()
.build();
// connect to gateway
Gateway.Builder builder = Gateway.newInstance()
.identity(identity)
.signer(signer)
.connection(grpcChannel);
// target contract
try (Gateway gateway = builder.connect()) {
Network network = gateway.getNetwork("channelName");
Contract contract = network.getContract("chaincodeName");
// transact
contract.submitTransaction("CreateAsset", "asset001", "user001", "description");
contract.submitTransaction("TransferAsset", "asset001", "user002");
} finally {
grpcChannel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
}

• Where possible, the APIs are designed to adhere to the
common idioms and patterns for each language.

• Java – fluent API style. Uses the ‘builder’ pattern for
creating Gateway connection, Proposal object, etc.



• Node (JavaScript, TypeScript) – uses object to pass
options to Gateway, Proposal, etc.




• Go – uses functional arguments With…() to pass options.



// java
Gateway gateway = Gateway.newInstance()
.identity(identity)
.signer(signer)
.connection(grpcChannel)
.connect();

// node
const gateway = connect({
client: await newGrpcConnection(),
identity: await newIdentity(),
signer: await newSigner(),
});

// go
gateway, err := client.Connect(
identity,
client.WithSign(sign),
client.WithClientConnection(conn),
)












New Program Model for v2x



----------------------
hlf.maint>

- v2x next week
- features
external chaincode
LedgerAPI RFC =
https://github.com/hyperledger/fabric-rfcs/pull/16
GO SDK RFC =
https://github.com/hyperledger/fabric-rfcs/pull/14
Also the suggestion to adopt gh-pages to view RFCs... includes better rendering & full text search
https://github.com/hyperledger/fabric-rfcs/pull/15

use cucumber scripts for testing sdks



Node SDK refactor for v2x concepts

https://drive.google.com/open?id=1gTJHqGIlE8hzX3m6se-XfEr5HmSQEgH8

pdf   https://drive.google.com/open?id=1ZQreNwbZNsMxGeeDFLbeMrrDN03Lqe6f




Create blockchain network with Fabric v1x and Composer Tutorial

https://hub.packtpub.com/installing-a-blockchain-network-using-hyperledger-fabric-and-composertutorial/

https://drive.google.com/open?id=15ZlsmVhUxv7URL64Cea0KMs6qSOML4Gx



Create simple Nodejs smart contract on IBM blockchain network - Tutorial

https://developer.ibm.com/patterns/build-a-blockchain-network/

uses Nodejs, VScode IBM extension, IBM network



Using Fabric gateway API to connect to a Fabric net, write and read transaction - Java

<< compare to DAML for simplicity 


The Fabric Gateway SDK allows applications to interact with a Fabric blockchain network. It provides a simple API to submit transactions to a ledger or query the contents of a ledger with minimal code. The Gateway SDK implements the Fabric programming model as described in the Developing Applications chapter of the Fabric documentation.

Client applications interact with the blockchain network using a Fabric Gateway. A session for a given client identity is established by building and connecting to a Fabric Gateway using a gRPC connection to the Gateway endpoint, client identity, and client signing implementation. The returned Gateway enables interaction with any of the blockchain Networks (channels) accessible through the Fabric Gateway. This in turn provides access to Smart Contracts within chaincode deployed to that blockchain network, and to which transactions can be submitted or queries can be evaluated.

gRPC connections to a Fabric Gateway may be shared by all Gateway instances interacting with that Fabric Gateway.

The following shows a complete code sample of how to connect to a fabric network, submit a transaction and query the ledger state using an instantiated smart contract.


    import io.grpc.ManagedChannel;
    import io.grpc.ManagedChannelBuilder;
    import org.hyperledger.fabric.client.*;
    import org.hyperledger.fabric.client.identity.*;

    public static void main(final String[] args) throws CommitException, GatewayException, InterruptedException {
        Reader certReader = Files.newBufferedReader(certificatePath);
        X509Certificate certificate = Identities.readX509Certificate(certReader);
        Identity identity = new X509Identity("mspId", certificate);

        Reader keyReader = Files.newBufferedReader(privateKeyPath);
        PrivateKey privateKey = Identities.readPrivateKey(keyReader);
        Signer signer = Signers.newPrivateKeySigner(privateKey);

        ManagedChannel grpcChannel = ManagedChannelBuilder.forAddress("gateway.example.org", 1337)
                .usePlaintext()
                .build();

        Gateway.Builder builder = Gateway.newInstance()
                .identity(identity)
                .signer(signer)
                .connection(grpcChannel);

        try (Gateway gateway = builder.connect()) {
            Network network = gateway.getNetwork("channelName");
            Contract contract = network.getContract("chaincodeName");

            byte[] putResult = contract.submitTransaction("put", "time", LocalDateTime.now().toString());
            System.out.println(new String(putResult, StandardCharsets.UTF_8));

            byte[] getResult = contract.evaluateTransaction("get", "time");
            System.out.println(new String(getResult, StandardCharsets.UTF_8));
        } finally {
            grpcChannel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
        }
    }
    


HLF Dev meeting 3/19/20


https://wiki.hyperledger.org/display/fabric


https://wiki.hyperledger.org/display/fabric/Fabric+Application+Developer+Community+Calls


past recordings, slides 

https://wiki.hyperledger.org/pages/viewpage.action?pageId=6423554


https://github.com/hyperledger/fabric#documentation-getting-started-and-developer-guides



------------------------------------
chris g k8s


https://github.com/IBM/Hyperledger-Fabric-for-Trusted-IoT

learn k8s
https://www.bretfisher.com/


docker compose
minikube for local
k8s services on provider

why k8s?
scenario - don't want to lose wallet ids if pod or node restarts - pvc

provision storage > pvc > access modes ... from hlf docs

vscode env testing

a> test minikube
a> tutorials
a> read helm charts, ansible playbooks
a> NEXT - ca mgt in k8s


ibm github repo has trusted iot to review


>> security - dns, ip, end pt, tls, pgp, vpn ? , authn, authz,

if HA, if svcs running, keeps ip address if pods deleted etc

redeploy a file ( a pod )


------------------------------------
wallets changes from v1.4 to v2.0

compare docs on wallets in readdocs

see github docs on wallets

goals in v2x

simplify changing persistence storage
storage formats in v2x simpler - not linked to node sdk

view v14 wallet


view v2 wallet


issue can't use old wallets in new env

-------------------
fs wallet migration tool as npm

npmjs.com/package/fabric-wallet-migration


npm package to mgirate fab wallets to v2 format

steps

1> create new fs wallet store for v2 after using fs for old wallet


fabric-network report
new sdk = 2.0.0-beta.4

wallet type demo'd was filesystemwallet

wallet decision
filesystem
memory
hsm
couchdbwallet

commiteventlistener

a> see github page - tutorial-wallet.html


------------------------------------
fabric net deployment tutorial with tls
------------------------------------


github.com/lepar/hyperledger-fabric-generic-network


uses tls


------------------------------------

a> key rotation in hlf docs?


------------------------------------


Fabric 2x - Essential Elements of Smart Contracts - N Rodrigues


youtube video

https://www.youtube.com/watch?v=CaSM5E7XWu4

presentation

https://training.linuxfoundation.org/blog/an-overview-of-essential-components-of-smart-contracts-in-hyperledger-fabric/

fabric-2x-training.linuxfoundation.org-An Overview of Essential Components of Smart Contracts in Hyperledger Fabric.pdf file

The architecture of Hyperledger Fabric, by design, comes with essential components that are vital to the operation of enterprise blockchain applications. 

Smart contracts are chaincode

Smart contracts, or chaincodes, in Hyperledger Fabric play a more vital role than other components. Indeed, as a professional Hyperledger Fabric developer, you should gradually master all aspects of chaincodes from logical design to development, testing and deployment.

inside a chaincode you can have multiple smart contracts running simultaneously. Indeed, in a consortium model, each member can have its own smart contract in its node, a smart contract that is communicating inside a private channel with other members and the system smart contract that is connected to the Orderer and system admin node. 

use the JavaScript programming language (though you can also use Java, Python or Go)

fundamental concepts for developing Fabric chaincodes: 

  1. Contract class
  2. Contract Structure
  3. The ChaincodeStub Interface
  4. Distributed Ledger Data Representation
  5. Logging in Chaincode

default contract class

a smart contract needs to inherit all the methods from the contract class which is provided in the fabric-contract-api npm package. These different methods are called in response to transactions that are invoked on the blockchain. Here is an example of a contract class that is inherited from contract API, followed by a brief explanation of its key methods:


Contract Structure in Chaincode

The fabric-contract-api and fabric-shim are the two important dependencies that are required to write the chaincode in Hyperledger fabric. When we start the development of the chaincodes in node.js, we add dependencies in package.json file as follows:

The start command fabric-chaincode-node start is used by peers in the network for starting the chaincode which is exported in the index.js file which is the main entrypoint. 

The lib directory can contain one or more smart contracts derived from the Contract class. Additionally we can also have a test directory which will include test cases to test the contracts. The chaincode folder structure is as follows:


Chaincode Stub interface in Chaincode

every chaincode implements the chaincode interface defined in the Shim package and defines two important methods which are called when a transaction is requested:

The Init is called to initialize the internal data of the chaincode when it is first deployed in the Docker container.

The Invoke method is used by subsequent transactions for modifying or reading the ledger; note that the modified state variables as a result of transaction operation are committed to the ledger only when the transaction is committed.

Both methods accept a single parameter named stub of type chaincodeStubInterface. In chaincode, every function has a ctx field which is a context object that contains chaincodeStubInterface implementation which provides essential APIs to interact with world state, private collection, emit events, Cross-Chaincode Invocation, etc.


Ledger representation in Chaincode

Ledger is an integral component in which data is added and modified through consensus of the nodes participating in the network. It has two different but related parts – World State and Blockchain.

World State – A type of database that holds current and latest values. A world state helps chaincode in fetching the current value of data quickly rather than traversing an entire transaction log and then calculating it. The data or states recorded in the ledger are represented as key value pairs. There are two database options available – Leveldb and Couchdb.

Blockchain – All the changes that take place on the current world state are recorded as a transaction log. The transactions formed are collected inside the block and appended to the blockchain which allows anyone to view the history of the state of the asset stored. A blockchain data structure is immutable; meaning once changes are made they cannot be modified; if the modification is made it will represent a new state.


Interaction with Ledger Data- putState, getState and delState

ledger states are represented as key value pairs. The simplest way of interacting with them is by using APIs provided by chaincodeStub Interface. We will look into the most important and basic APIs for querying, modifying and deleting the states of the ledger.

putState – The API requires a key (string) and a value (byte array). It is used to form a data write proposal to be committed on the ledger; note that the ledger is affected only after the transaction is validated and successfully committed by peers in the network. The key should not be empty and not start with an empty character.

getState – The API requires a key (string). It returns the corresponding value to the key from the ledger. If the key does not exist in the state database, it returns the empty array.

delState – The API requires a key (string). It forms a proposal to delete the record from the ledger state. After the operation is successful the key and its corresponding value is marked as deleted from the world state. However, the record will still be available in the Blockchain and can be retrieved.


Logging in Chaincode

Logging is the most important part in the software development process. It helps you in making important decisions by analyzing the data, resolving errors and detecting problems early. Chaincode logging is the ultimate responsibility of a chaincode developer.

Any logging utilities that print messages to stdout or stderr can be examined in the relevant Docker container by writing the below command:

If you are preparing for the Certified Hyperledger Fabric Developer (CHFD) exam, this article is a great starting point. As a follow-up of this article you need to explore the chaincode lifecycle as well as running simple to complex queries on ledger data. Also, it is good to explore the chaincode external launcher feature which was introduced in Hyperledger Fabric V2 via Node.JS SDK. A relevant training course would be Hyperledger Fabric for Developers (LFD272).




Potential Value Opportunities



Potential Challenges



Candidate Solutions


Contributor Meetings


Contributor - 220511



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

option to run with rancher desktop as option to docker desktop

can use mobil daemons with rancher

allows separate build from deploy step now

external builders and launchers in Fabric

you can manage chaincode startup as wanted as a server and tell peer where it is 

i>>>> can this be improved as default config

deploy pre-built chaincode images

fabric-builder-k8s

chaincode package create step

sample package create - deploy with conga src

chaincode contacts peer on deploy step

o1> peer uses docker to manage all ccode

or

o2> ccode contacts peer from deployment

jtonline to Everyone (9:27 AM)
https://github.com/hyperledgendary/fabric-builder-k8s

Dave Enyeart to Everyone (9:28 AM)
Discord fabric-kubernetes - https://discord.com/channels/905194001349627914/945796983795384331

New process for k8s deploy

1> build package

2> config k8s env - add external builder cfg for peers

3> deploy package w new process

v>>>>> was too hard to start ccode in middle of ccode life cycle - builder manages k8s pods during life cycle, can debug locally with ccode as a service

https://github.com/hyperledger-labs/PerformanceSandBox





Step-by-step guide for Example



sample code block

sample code block
 



Recommended Next Steps