Sunteți pe pagina 1din 20

Fabric SDK: New Programming Model

FABN-692 – Node SDK


FABJ-400 – Java SDK

Andrew Coleman
Simon Stone
Mark Lewis

© 2019 IBM Corporation


The Commercial Paper Example
Transaction: Issue
Commercial Paper
Issuer: IBM
Owner: IBM
Face value: $1,000,000
Maturity date: 2019-10-31

Transaction: Move

Commercial Paper Cash Commercial Paper Cash


Issuer: IBM Issuer: Fed Issuer: IBM Issuer: Fed
Owner: IBM Owner: ACME Owner: ACME Owner: IBM
Face value: $1,000,000 Face value: $900,000 Face value: $1,000,000 Face value: $900,000
Maturity date: 2019-10-31 Maturity date: 2019-10-31

Transaction: Redeem

Commercial Paper Cash Cash


Issuer: IBM Issuer: Fed Issuer: Fed
Owner: ACME Owner: IBM Owner: ACME
Face value: $1,000,000 Face value: $1,000,000 Face value: $1,000,000
Maturity date: 2019-10-31

© 2019 IBM Corporation 2


The application programming challenge
2.1 peer invokes chaincode
Applications must know too much:
1. connect to peer
S1
2. invoke chaincode 2.2 chaincode generates
A P1 query or update
3. transaction response proposal transaction
L1 response
5. ledger update 4.2 peer updates
notification ledger using
transaction blocks
4. update transactions ordered
O1 4.1 Transactions
sent to peers in WHAT
blocks

• WHO are the endorsing organizations (Endorsement policy)


• WHERE are the endorsing organizations (Peers)
• HOW to get transactions validated (Ordering)
not HOW
Simplify for the developer
• Applications should only need to know WHAT system does – not WHO, WHERE or HOW it does it
• Allow developers to concentrate on their business logic
© 2019 IBM Corporation 3
New Programming Model
• Provide a consistent programming model and set of APIs to meet needs of application developers

• Using the vocabulary of the target audience


– Networks, Contracts, Transactions

• Coherent experience across client application and chaincode

• Maximum functionality with minimum code


– High-level APIs, declarative HA strategies
– Seamless access to low-level APIs (full spectrum of capabilities)

• Consistent across all supported languages


– Already delivered in Node (v1.4)
– Java in development (v2.0)
– Go next
© 2019 IBM Corporation 4
High-level and low-level APIs
• Existing SDK contains the low-level APIs that interact with Fabric
– Client / HFClient class is the entry point
• The new programming model provides a high-level API
– Built on top of the low-level API
• New classes/interfaces
– Gateway
• Represents a connected identity to the fabric network via a peer or set of peers (HA)
• 1 to 1 relationship to underlying Client object
– Network
• Represents the set of peers associated with a Channel
– Contract
• Represents a chaincode instance on a channel
– Transaction
• Enables finer control of transaction parameters (e.g. transient data)
– Wallet
• Manages the storage of identities 5
© 2019 IBM Corporation
Networks, Contracts and Transactions
Network Contract
getContract(chaincodeId [, name]) submitTransaction(name, arg1, arg2, …)

- Initialize and cache objects representing a - Create Txn Id


contract (chaincode instance on a channel) - Create Txn proposal object
- Call sendTransactionProposal()
- Validate the responses
- Create Txn event handler & start listening
- Call sendTransaction()
Gateway - Wait for events
getNetwork(networkName) - Return the Txn function response payload

Options evaluateTransaction(name, arg1, arg2, …) (query)


- commitHandler – strategy & timeout
- queryHandler – single / round robin - Try the last successful peer
Identity - If that fails or this is the first time try all query
peers in order

Wallet
© 2019 IBM Corporation 6
Example client application – JavaScript
• IBM issues a commercial paper, face value $1M, redemption date 2019-10-31
• IBM sells paper to ACME Inc. for $900,000
const gateway = new Gateway();
const wallet = new FileSystemWallet('./WALLETS/wallet');

try {
await gateway.connect(ccp, {
identity: 'admin',
wallet: wallet
});

const network = await gateway.getNetwork('market1234');


const contract = await network.getContract('commercial-paper');

// issue commercial paper


const paper = await contract.submitTransaction('issue', 'ibm', '1000000', '2019-10-31');

// sell paper to buyer 'acme' for $900,000


await contract.submitTransaction('move', paper, 'acme', '900000');

} catch(error) {
console.log(error);
} finally {
gateway.disconnect();
}
© 2019 IBM Corporation 7
Example client application – Java
• IBM issues a commercial paper, face value $1M, redemption date 2019-10-31
• IBM sells paper to ACME Inc. for $900,000
// Create a new file system based wallet for managing identities.
Path walletPath = Paths.get("wallet");
Wallet wallet = Wallet.createFileSystemWallet(walletPath);

// load a CCP
Path networkConfigPath = Paths.get("..", "..", "paper-network", "connection.json");
NetworkConfig networkConfig = NetworkConfig.fromJsonFile(networkConfigPath.toFile());

// create a gateway, then connect


Gateway.Builder builder = Gateway.createBuilder();
builder.identity(wallet, "admin").networkConfig(networkConfig);

try (Gateway gateway = builder.connect()) {


// get the network and contract
Network network = gateway.getNetwork("market1234");
Contract contract = network.getContract("commercial-paper");

// issue commercial paper


String paper = contract.submitTransaction("issue", "ibm", "1000000", "2019-10-31")
// then sell paper to acme for $900,000
contract.submitTransaction("move", paper, "acme", "900000"))

} catch (Exception ex) {


ex.printStackTrace();
}

© 2019 IBM Corporation 8


Gateway and gateway builder
• In common with the Node SDK, a gateway object represents the 'connection' to the Fabric network
for a given identity

• The gateway gets configured with predefined 'strategies' that specify the behavior of low-level
interactions
– E.g. what conditions define successful transaction commitment
– E.g. how to share out queries amongst available peers

• This allows common strategies to be selected declaratively, eliminating boilerplate code

• In Java, we adopt the 'builder' design pattern to configure the gateway options
Gateway.Builder builder = Gateway.createBuilder();
builder.identity(wallet, "admin").networkConfig(networkConfig);
builder.commitHandler(DefaultCommitHandlers.MSPID_SCOPE_ALLFORTX);

try (Gateway gateway = builder.connect()) {


...
}
© 2019 IBM Corporation 9
Pluggable handlers
• Commit event handlers and query handlers are both designed to be pluggable
– Allows developers to implement bespoke HA strategies

• Default commit handler provides a set of pre-built strategies – choose one:


– Listen for all on your org (wait for all responses of all org’s event hubs) – DEFAULT
– Listen for any on your org (first response of all org’s event hubs)
– Listen for all peers in the channel (minimum one from each org)
– Listen for any peers in the channel (first response of all event hubs)

• Default query handler strategies:


– Stick to a single peer. Move to another one if it stops responding – DEFAULT
– Round-robin between available peers within org.

© 2019 IBM Corporation 10


Handler SPI
• A service provider interface (SPI) is available to allow developers create their own strategies

• Typically done by a more 'advanced' fabric developer and implemented using lower-level APIs

• Implements a factory method and a handler class

• Object lifecycle is managed by the Gateway

© 2019 IBM Corporation 11


Identity Management
• The Wallet interface is used to manage identities including the storage of credentials
– Storage scheme delegated to implementation class
– E.g. FileSystemWallet, InMemoryWallet , CouchDBWallet

• Compatible wallet format between Node.js and Java (as well as future CLI utilities)

• Provides management API – import, export, list, delete, update, etc.

• Each Gateway instance has one wallet associated with it


– Used to select identities stored in that wallet
– At any one time only a single identity can be active on that gateway & its network instances
– Any contract obtained from that network instance will use the identity assigned to that network

© 2019 IBM Corporation 12


Transaction object – for finer control
• An object representing a named transaction method can be created in the client app
– createTransaction() method on Contract class

Network network = gateway.getNetwork("market1234");


Contract contract = network.getContract("commercial-paper");

// issue commercial paper


Transaction issue = contract.createTransaction("issue");
issue.submit("ibm", "1000000", "2019-10-31");

• Extra options can be associated with this transaction before it is evaluated or summited to the ledger
– E.g. transient data

• contract.submitTransaction('issue', 'ibm', ...) is syntactic sugar for the code above

© 2019 IBM Corporation 13


Private Data Collections
• In the smart contract API, the getTransient() method is used to access transient (private) data

• In the base SDK, this transient data is passed as a property in the transaction request object

• In the new programming model, there is a setTransient() method in the Transaction interface
– Passes a Map of name/value pairs to subsequent invocation of submit() & evaluate()

• This provides API symmetry between the existing smart contract (shim) API and the application SDK

Transaction txn = contract.createTransaction("move");


Map<String, byte[]> secrets = new HashMap<>();
secrets.put("price", "900000".getBytes());
txn.setTransient(secrets);
txn.submit("paper001", "myCorp");

© 2019 IBM Corporation 14


Mixing high and low level APIs
• The Gateway interface has a method getClient() that returns a reference to the underlying
HFClient object
– HFClient is the entry point to the underlying API
– Allows access to low-level Channel, Peer, Orderer, etc. APIs

• The Gateway object can also be instantiated from an existing HFClient object
– Allows existing client code to start using the new submitTransaction() function
without rewriting

• Existing client code continues to work as is


– No breaking changes introduced by this API

© 2019 IBM Corporation 15


Package structure – NodeJS
• Low-level and high-level APIs co-exist in fabric-sdk-node repo
– https://gerrit.hyperledger.org/r/#/admin/projects/fabric-sdk-node
– https://github.com/hyperledger/fabric-sdk-node (read-only mirror)

• NPM module structure


– fabric-network – contains new high-level API
– fabric-client – existing low-level API
– fabric-ca-client – CA API
– fabric-common – shared classes

© 2019 IBM Corporation 16


Package structure – Java
• Application Programmers Interface
– The client app developer will interact with these
– All Java interfaces

• The implementation classes


– Internal

• Service Provider Interface


– For extending the API with more strategies
– All Java interfaces

© 2019 IBM Corporation 17


Documentation

© 2019 IBM Corporation 18


Samples
• New commercial-paper sample as described in the Fabric docs
– https://github.com/hyperledger/fabric-samples/tree/release-1.4/commercial-paper

• Fabcar sample updated with Javascript and Typescript implementations using the new
fabric-network API
– https://github.com/hyperledger/fabric-samples/tree/release-1.4/fabcar/javascript
– https://github.com/hyperledger/fabric-samples/tree/release-1.4/fabcar/typescript

• Java implementations will be added to these samples

© 2019 IBM Corporation 19


Summary
• Provide a consistent programming model and set of APIs to meet needs of application developers

• Using the vocabulary of the target audience


– Networks, Contracts, Transactions

• Coherent experience across client application and chaincode

• Maximum functionality with minimum code


– High-level APIs, declarative HA strategies
– Seamless access to low-level APIs (full spectrum of capabilities)

• Consistent across all supported languages


– Already delivered in NodeJS (v1.4)
– Java in development (v2.0)
– Go next
© 2019 IBM Corporation 20

S-ar putea să vă placă și