m Fabric Dev 1
Key Points
- focus is the new program model for smart contracts, IBM VSCode extension
- looking for full Composer modeling language to be implemented in v2x ( not a priority for team now )
- v2x has new chaincode life cycle for multiple orderers, multiple contract endorsements
- new Node SDK is completely refactored in v2x, won't be backported to v1x
- Composer is deprecated but under v1.4x it can still be used to prototype solutions
References
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 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 | |
Write Client Apps using the Gateway API Gateway • Network • Contract • Invokes a transaction function to read from the ledger (query). • Invokes a transaction function to modify the ledger. • 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 • Java – fluent API style. Uses the ‘builder’ pattern for • Node (JavaScript, TypeScript) – uses object to pass • Go – uses functional arguments With…() to pass options. | // java // node // go | |
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://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
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:
- Contract class
- Contract Structure
- The ChaincodeStub Interface
- Distributed Ledger Data Representation
- 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