Class: Client

Client

Main interaction handler with end user. A client instance provides a handler to interact with a network of peers, orderers and optionally member services. An application using the SDK may need to interact with multiple networks, each through a separate instance of the Client. Each client when initially created should be initialized with configuration data from the consensus service, which includes a list of trusted roots, orderer certificates and IP addresses, and a list of peer certificates and IP addresses that it can access. This must be done out of band as part of bootstrapping the application environment. It is also the responsibility of the application to maintain the configuration of a client as the SDK does not persist this object. Each Client instance can maintain several Chain instances representing channels and the associated private ledgers.

new Client()

Methods


<static> addConfigFile(path)

Adds a file to the top of the list of configuration setting files that are part of the hierarchical configuration. These files will override the default settings and be overriden by environment, command line arguments, and settings programmatically set into configuration settings. hierarchy search order: 1. memory - all settings added with sdkUtils.setConfigSetting(name,value) 2. Command-line arguments 3. Environment variables (names will be change from AAA-BBB to aaa-bbb) 4. Custom Files - all files added with the addConfigFile(path) will be ordered by when added, were last one added will override previously added files 5. The file located at 'config/default.json' with default settings
Parameters:
Name Type Description
path String The path to the file to be added to the top of list of configuration files

<static> buildTransactionID(nonce, userContext)

Utility method to build an unique transaction id based on a nonce and the user context.
Parameters:
Name Type Description
nonce int a one time use number
userContext User the user context
Returns:
An unique string
Type
string

<static> getConfigSetting(name, default_value)

Retrieves a setting from the hierarchical configuration and if not found will return the provided default value. hierarchy search order: 1. memory - settings added with sdkUtils.setConfigSetting(name,value) 2. Command-line arguments 3. Environment variables (names will be change from AAA-BBB to aaa-bbb) 4. Custom Files - all files added with the addConfigFile(path) will be ordered by when added, were last one added will override previously added files 5. The file located at 'config/default.json' with default settings
Parameters:
Name Type Description
name String The name of a setting
default_value Object The value of a setting if not found in the hierarchical configuration

<static> newDefaultKeyValueStore(options)

Obtains an instance of the KeyValueStore class. By default it returns the built-in implementation, which is based on files (FileKeyValueStore). This can be overriden with an environment variable KEY_VALUE_STORE, the value of which is the full path of a CommonJS module for the alternative implementation.
Parameters:
Name Type Description
options Object is whatever the implementation requires for initializing the instance. For the built-in file-based implementation, this requires a single property "path" to the top-level folder for the store
Returns:
KeyValueStore an instance of the KeyValueStore implementation

<static> setConfigSetting(name, value)

Adds a setting to override all settings that are part of the hierarchical configuration. hierarchy search order: 1. memory - settings added with this call 2. Command-line arguments 3. Environment variables (names will be change from AAA-BBB to aaa-bbb) 4. Custom Files - all files added with the addConfigFile(path) will be ordered by when added, were last one added will override previously added files 5. The file located at 'config/default.json' with default settings
Parameters:
Name Type Description
name String The name of a setting
value Object The value of a setting

<static> setLogger(logger)

Configures a logger for the entire HFC SDK to use and override the default logger. Unless this method is called, HFC uses a default logger (based on winston). When using the built-in "winston" based logger, use the environment variable HFC_LOGGING to pass in configurations in the following format: { 'error': 'error.log', // 'error' logs are printed to file 'error.log' relative of the current working dir for node.js 'debug': '/tmp/myapp/debug.log', // 'debug' and anything more critical ('info', 'warn', 'error') can also be an absolute path 'info': 'console' // 'console' is a keyword for logging to console }
Parameters:
Name Type Description
logger Object a logger instance that defines the following methods: debug(), info(), warn(), error() with string interpolation methods like util.format.

createChannel(request)

Calls the orderer to start building the new channel. Only one of the application instances needs to call this method. Once the chain is successfully created, this and other application instances only need to call Chain joinChannel() to participate on the channel.
Parameters:
Name Type Description
request Object An object containing the following fields:
`name` : required - {string} The name of the new channel
`orderer` : required - {Orderer} object instance representing the Orderer to send the create request
`envelope` : optional - byte[] of the envelope object containing all required settings and signatures to initialize this channel. This envelope would have been created by the command line tool "configtx".
`config` : optional - {byte[]} Protobuf ConfigUpdate object extracted from a ConfigEnvelope created by the ConfigTX tool. see extractChannelConfig()
`signatures` : optional - {ConfigSignature[]} the list of collected signatures required by the channel create policy when using the `config` parameter.
Returns:
Result Object with status on the create process.
Type
Result

createUser(opts)

Returns an authorized user loaded using the private key and pre-enrolled certificate from files based on the MSP config directory structure:
root
   \_ keystore
      \_ admin.pem <<== this is the private key saved in PEM file
   \_ signcerts
      \_ admin.pem <<== this is the signed certificate saved in PEM file
Parameters:
Name Type Description
opts object
- username {string} - the user name used for enrollment
- mspid {string} - the MSP id

- cryptoContent {object}
---- privateKey {string} - the PEM file name including the root path - required when using the file system
---- signedCert {string} - the PEM file name including the root path - required when using the file system
---- or
---- privateKeyPEM {string} - the PEM string - required when no file system is available
---- signedCertPEM {string} - the PEM string - required when no file system is available

extractChannelConfig(The)

Extracts the protobuf 'ConfigUpdate' object out of the 'ConfigEnvelope' that is produced by the ConfigTX tool. The returned object may then be signed using the signChannelConfig() method of this class. Once the all signatures have been collected this object and the signatures may be used on the updateChannel or createChannel requests.
Parameters:
Name Type Description
The Array.<byte> bytes of the ConfigEnvelope protopuf
Returns:
The bytes of the ConfigUpdate protobuf
Type
Array.<byte>

getChain(name)

Get a Chain instance from the state storage. This allows existing chain instances to be saved for retrieval later and to be shared among instances of the application. Note that it’s the application/SDK’s responsibility to record the chain information. If an application is not able to look up the chain information from storage, it may call another API that queries one or more Peers for that information.
Parameters:
Name Type Description
name string The name of the chain.
Throws:
if the state store has not been set or a chain does not exist under that name.
Type
Error
Returns:
The chain instance
Type
Chain

getStateStore()

A convenience method for obtaining the state store object in use for this client.
Returns:
The KeyValueStore implementation object set within this Client, or null if it does not exist.
Type
KeyValueStore

getUserContext(name, checkPersistence)

Returns the user with the signing identity. This can be a synchronous call or asynchronous call, depending on whether "checkPersistent" is truthy or not. If truthy, the method is asynchronous and returns a Promise, otherwise it's synchronous. As explained above, the client instance can have an optional state store. The SDK saves enrolled users in the storage which can be accessed by authorized users of the application (authentication is done by the application outside of the SDK). This function attempts to load the user by name from the local storage (via the KeyValueStore interface). The loaded user object must represent an enrolled user with a valid enrollment certificate signed by a trusted CA (such as the CA server).
Parameters:
Name Type Description
name String Optional. If not specified, will only return the in-memory user context object, or null if not found in memory. If "name" is specified, will also attempt to load it from the state store if search in memory failed.
checkPersistence boolean Optional. If specified and truthy, the method returns a Promise and will attempt to check the state store for the requested user by the "name". If not specified or falsey, the method is synchronous and returns the requested user from memory
Returns:
The user object corresponding to the name, or null if the user does not exist or if the state store has not been set.
Type
Promise

installChaincode(request)

Sends an install proposal to one or more endorsing peers.
Parameters:
Name Type Description
request Object An object containing the following fields:
`chaincodePath` : required - String of the path to location of the source code of the chaincode
`chaincodeId` : required - String of the name of the chaincode
`chaincodeVersion` : required - String of the version of the chaincode
`chaincodePackage` : optional - Byte array of the archive content for the chaincode source. The archive must have a 'src' folder containing subfolders corresponding to the 'chaincodePath' field. For instance, if the chaincodePath is 'mycompany/myproject', then the archive must contain a folder at the path 'src/mycompany/myproject', where the GO source code resides.
`chaincodeType` : optional - Type of chaincode ['golang', 'car', 'java'] (default 'golang')
`txId` : required - String of the transaction id
`nonce` : required - Integer of the once time number
See:
  • /protos/peer/proposal_response.proto
Returns:
A Promise for a `ProposalResponse`
Type
Promise

isDevMode()

Determine if dev mode is enabled.

loadUserFromStateStore()

Restore the state of this member from the key value store (if found). If not found, do nothing.
Returns:
A Promise for a {User} object upon successful restore, or if the user by the name does not exist in the state store, returns null without rejecting the promise
Type
Promise

newChain(name)

Returns a chain instance with the given name. This represents a channel and its associated ledger (as explained above), and this call returns an empty object. To initialize the chain in the blockchain network, a list of participating endorsers and orderer peers must be configured first on the returned object.
Parameters:
Name Type Description
name string The name of the chain. Recommend using namespaces to avoid collision.
Throws:
if the chain by that name already exists in the application's state store
Type
Error
Returns:
The uninitialized chain instance.
Type
Chain

newCryptoKeyStore(KVSImplClass, opts)

Returns a new instance of the CryptoKeyStore. When the application needs to use a key store other than the default, it should create a new CryptoKeyStore and set it on the CryptoSuite. cryptosuite.setCryptoKeyStore(client.newCryptoKeyStore(KVSImplClass, opts))
Parameters:
Name Type Description
KVSImplClass function Optional. The built-in key store saves private keys. The key store may be backed by different KeyValueStore implementations. If specified, the value of the argument must point to a module implementing the KeyValueStore interface.
opts object Implementation-specific option object used in the constructor returns a new instance of the CryptoKeystore

newCryptoSuite(setting)

Returns a new instance of the CryptoSuite API implementation. Creating a new CryptoSuite is optional and should be used if options other than defaults are needed. This instance should be set on the User and the Fabric CA Client. If not specified, an instance of CryptoSuite will be constructed based on the current configuration settings: crypto-hsm: use an implementation for Hardware Security Module (if set to true) or software-based key management (if set to false) crypto-keysize: security level, or key size, to use with the digital signature public key algorithm. Currently ECDSA is supported and the valid key sizes are 256 and 384 crypto-hash-algo: hashing algorithm key-value-store: some CryptoSuite implementation requires a key store to persist private keys. A CryptoKeyStore is provided for this purpose, which can be used on top of any implementation of the KeyValueStore interface, such as a file-based store or a database-based one. The specific implementation is determined by the value of this configuration setting.
Parameters:
Name Type Description
setting object This optional parameter is an object with the following optional properties: - software {boolean}: Whether to load a software-based implementation (true) or HSM implementation (false) default is true (for software based implementation), specific implementation module is specified in the setting 'crypto-suite-software' - keysize {number}: The key size to use for the crypto suite instance. default is value of the setting 'crypto-keysize' - algorithm {string}: Digital signature algorithm, currently supporting ECDSA only with value "EC" - hash {string}: 'SHA2' or 'SHA3' returns a new instance of the CryptoSuite API implementation

newMSP()

build an new MSP with the definition.
Returns:
The newly created MSP object.
Type
MSP

newOrderer(url, opts)

Returns an order instance with the given url.
Parameters:
Name Type Description
url string The URL with format of "grpcs://host:port".
opts Object The options for the connection to the peer.
- request-timeout {string} A integer value in milliseconds to be used as node.js based timeout. This will break the request operation if the grpc request has not responded within this timeout period.
- pem {string} The certificate file, in PEM format, to use with the gRPC protocol (that is, with TransportCredentials). Required when using the grpcs protocol.
- ssl-target-name-override {string} Used in test environment only, when the server certificate's hostname (in the 'CN' field) does not match the actual host endpoint that the server process runs at, the application can work around the client TLS verify failure by setting this property to the value of the server certificate's hostname
- any other standard grpc call options will be passed to the grpc service calls directly
Returns:
The orderer instance.
Type
Orderer

newPeer(url, opts)

Returns a peer instance with the given url.
Parameters:
Name Type Description
url string The URL with format of "grpcs://host:port".
opts Object The options for the connection to the peer.
- request-timeout {string} A integer value in milliseconds to be used as node.js based timeout. This will break the request operation if the grpc request has not responded within this timeout period.
- pem {string} The certificate file, in PEM format, to use with the gRPC protocol (that is, with TransportCredentials). Required when using the grpcs protocol.
- ssl-target-name-override {string} Used in test environment only, when the server certificate's hostname (in the 'CN' field) does not match the actual host endpoint that the server process runs at, the application can work around the client TLS verify failure by setting this property to the value of the server certificate's hostname
- any other standard grpc call options will be passed to the grpc service calls directly
Returns:
The Peer instance.
Type
Peer

queryChainInfo(name, peers)

This is a network call to the designated Peer(s) to discover the chain information. The target Peer(s) must be part of the chain to be able to return the requested information.
Parameters:
Name Type Description
name string The name of the chain.
peers Array.<Peer> Array of target Peers to query.
Returns:
The chain instance for the name or error if the target Peer(s) does not know anything about the chain.
Type
Chain

queryChannels(peer)

Queries the names of all the channels that a peer has joined.
Parameters:
Name Type Description
peer Peer
Returns:
A promise to return a ChannelQueryResponse proto Object
Type
Promise

queryInstalledChaincodes(peer)

Queries the installed chaincodes on a peer returning the details of all chaincodes installed on a peer.
Parameters:
Name Type Description
peer Peer
Returns:
ChaincodeQueryResponse proto
Type
object

saveUserToStateStore()

Save the state of this member to the key value store.
Returns:
A Promise for the user context object upon successful save
Type
Promise

setDevMode()

Set dev mode to true or false.

setStateStore(keyValueStore)

The enrollment materials for Users that have appeared in the instances of the application. The SDK should have a built-in key value store file-based implementation to allow easy setup during development. Production systems would use a store backed by database for more robust storage and clustering, so that multiple app instances can share app state via the database. This API makes this pluggable so that different store implementations can be selected by the application.
Parameters:
Name Type Description
keyValueStore KeyValueStore Instance of an alternative KeyValueStore implementation provided by the consuming app.

setUserContext(user, skipPersistence)

Sets an instance of the User class as the security context of self client instance. This user’s credentials (ECert), or special transaction certificates that are derived from the user's ECert, will be used to conduct transactions and queries with the blockchain network. Upon setting the user context, the SDK saves the object in a persistence cache if the “state store” has been set on the Client instance. If no state store has been set, this cache will not be established and the application is responsible for setting the user context again if the application crashes and is recovered.
Parameters:
Name Type Description
user User An instance of the User class encapsulating the authenticated user’s signing materials (private key and enrollment certificate)
skipPersistence boolean Whether to skip saving the user object into persistence. Default is false and the method will attempt to save the user object to the state store.
Returns:
Promise of the 'user' object upon successful persistence of the user to the state store
Type
Promise

signChannelConfig(config)

Sign a configuration
Parameters:
Name Type Description
config Array.<byte> The Configuration Update in byte form
Returns:
- The signature of the current user on the config bytes
Type
ConfigSignature

updateChannel(request)

Calls the orderer to update an existing channel. Only one of the application instances needs to call this method.
Parameters:
Name Type Description
request Object An object containing the following fields:
`name` : required - {string} The name of the new channel
`orderer` : required - {Orderer} object instance representing the Orderer to send the update request
`envelope` : optional - byte[] of the envelope object containing all required settings and signatures to initialize this channel. This envelope would have been created by the command line tool "configtx".
`config` : optional - {byte[]} Protobuf ConfigUpdate object built by the buildChannelConfig() method of this class.
`signatures` : optional - {ConfigSignature[]} the list of collected signatures required by the channel create policy when using the `config` parameter. see signChannelConfig() method of this class
Returns:
Result Object with status on the update process.
Type
Result