Class: Client

Client

A client instance provides the main API surface to interact with a network of peers and orderers. An application using the SDK may need to interact with multiple networks, each through a separate instance of the Client.

An important aspect of the current design of the Client class is that it is stateful. An instance must be configured with a userContext before it can be used to talk to the fabric backend. A userContext is an instance of the User class, which encapsulates the ability to sign requests. If the SDK is used in a multi-user environment, there are two recommended techniques to manage the authenticated users and instances of clients.
  • Use a dedicated client instance per authenticated user. Create a new instance for each authenticated user. You can enroll each authenticated user separately so that each user gets its own signing identity.
  • Use a shared client instance and a common signing identity among authenticated users.

    It is important to understand that switching userContexts with the same client instance is considered an anti-pattern. This is the direct result of the stateful design. A JIRA work item has been opened to discuss adding support for stateless usage of the SDK: FAB-4563

    The client also supports persistence via a stateStore. A state store is a simple storage plugin that implements the module:api.KeyValueStore interface, which helps the SDK save critical information to be used across server restarts/crashes. Out of the box, the SDK saves the signing identities (instances of the User class) in the state store.

  • new Client()

    Extends

    Methods


    <static> loadFromConfig(loadConfig)

    Load a common connection profile object or load a JSON file and return a Client object.
    Parameters:
    Name Type Description
    loadConfig object | string This may be the config object or a path to the configuration file
    Returns:
    An instance of this class initialized with the network end points.
    Type
    Client

    <async> _setUserFromConfig(opts)

    Utility Method Sets the user context based on the passed in username and password and the organization in the client section of the common connection profile settings.
    Parameters:
    Name Type Description
    opts Object contains - username [required] - username of the user - password [optional] - password of the user - caName [optional] - name of the Certificate Authority

    addConnectionOptions(options)

    Add a set of connection options to this client. These will be available to be merged into an application's options when new peers and orderers are created or when a channel uses discovery to automatically create the peers and orderers on the channel. This would be a convenient place to store common GRPC settings that affect all connections from this client. These settings will be used when this client object builds new Peer or Orderer instances when the Client#newPeer, Client#getPeer, Client#newOrderer or Client#getOrderer methods are called. Options will be automatically added when loading a common connection profile and the client section has the 'connection' section with an 'options' attribute. Default connection options will be initially loaded from the system configuration 'connection-options' setting.
    Parameters:
    Name Type Description
    options object The connection options that will be added to this client instance.

    addTlsClientCertAndKey(opts)

    Utility method to add the mutual tls client material to a set of options.
    Parameters:
    Name Type Description
    opts object The options object holding the connection settings that will be updated with the mutual TLS clientCert and clientKey.
    Throws:
    Will throw an error if generating the tls client material fails

    buildConnectionOptions(options)

    Utility method to merge connection options into a set of options and return a new options object. The client's options and default connection options will not override any passed settings by the same name, these will only be added as new settings to the application's options being passed in. see Client#addConnectionOptions for how this client will have connection options to merge.
    Parameters:
    Name Type Description
    options object The object holding the application options that will be merged on top of this client's options.
    Returns:
    - The object holding both the application's options and this client's options.
    Type
    object

    createChannel(request)

    Calls the orderer to start building the new channel. A channel typically has more than one participating organizations. To create a new channel, one of the participating organizations should call this method to submit the creation request to the orderer service.

    Once the channel is successfully created by the orderer, the next step is to have each organization's peer nodes join the channel, by sending the channel configuration to each of the peer nodes. The step is accomplished by calling the joinChannel() method.
    Parameters:
    Name Type Description
    request ChannelRequest The request object.
    Returns:
    Promise for a result object with status on the acceptance of the create request by the orderer. Note that this is not the confirmation of successful creation of the channel. The client application must poll the orderer to discover whether the channel has been created completely or not.
    Type
    Promise

    <async> createUser(opts)

    Returns a User object with signing identities based on the private key and the corresponding x509 certificate. This allows applications to use pre-existing crypto materials (private keys and certificates) to construct user objects with signing capabilities, as an alternative to dynamically enrolling users with fabric-ca

    Note that upon successful creation of the new user object, it is set to the client instance as the current userContext.
    Parameters:
    Name Type Description
    opts UserOpts Essential information about the user
    Returns:
    Promise for the user object.
    Type
    Promise

    extractChannelConfig(config_envelope)

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

    getCertificateAuthority(name)

    Returns a CertificateAuthority implementation as defined by the settings in the currently loaded common connection profile and the client configuration. A common connection profile must be loaded for this get method to return a Certificate Authority. A crypto suite must be assigned to this client instance. Running the 'initCredentialStores' method will build the stores and create a crypto suite as defined in the common connection profile.
    Parameters:
    Name Type Description
    name string Optional - the name of the Certificate Authority defined in the loaded connection profile.
    Returns:
    Type
    CertificateAuthority

    getChannel(name, throwError)

    Get a Channel instance from the client instance. This is a memory-only lookup. If the loaded common connection profile has a channel by the 'name', a new channel instance will be created and populated with Orderer objects and Peer objects as defined in the common connection profile.
    Parameters:
    Name Type Default Description
    name string Optional. The name of the channel. When omitted the first channel defined in the loaded common connection profile will be returned
    throwError boolean true Indicates if this method will throw an error if the channel is not found. Default is true.
    Returns:
    The channel instance
    Type
    Channel

    getClientCertHash(create)

    Get the client certificate hash
    Parameters:
    Name Type Description
    create boolean Optional. Create the hash based on the current user if the client cert has not been assigned to this client
    Returns:
    The hash of the client certificate
    Type
    Array.<byte>

    getClientConfig()

    Returns the "client" section of the common connection profile.
    Returns:
    The client section from the configuration
    Type
    object

    getCryptoSuite()

    Returns the CryptoSuite object used by this client instance
    Inherited From:
    Overrides:
    Returns:
    Type
    module:api.CryptoSuite

    getMspid()

    Returns the mspid of the client. The mspid is also used as the reference to the organization.
    Returns:
    the mspid of the organization defined in the client section of the loaded common connection profile
    Type
    string

    getOrderer(name)

    This method will create the Orderer if it does not exist and hold a reference to the instance object by name. This method is only able to create an instance of an orderer if there is a loaded connection profile that contains an orderer with the name. Orderers that have been created by the newOrderer method may be reference by the url if no name was provided in the options.
    Parameters:
    Name Type Description
    name string The name or url of the orderer
    Returns:
    The Orderer instance.
    Type
    Orderer

    getPeer(name)

    This method will create a Peer instance. This method is only able to create an instance of a peer if there is a loaded connection profile that contains a peer with the name.
    Parameters:
    Name Type Description
    name string The name of the peer
    Returns:
    The Peer instance.
    Type
    Peer

    getPeersForOrg(mspid)

    Returns a list of Peer for the mspid of an organization as defined in the currently loaded common connection profile. If no id is provided then the organization named in the currently active network configuration's client section will be used.
    Parameters:
    Name Type Description
    mspid string Optional - The mspid of an organization
    Returns:
    An array of Peer instances that are defined for this organization
    Type
    Array.<Peer>

    getStateStore()

    A convenience method for obtaining the state store object in use by this client.
    Returns:
    The KeyValueStore implementation object set on this Client, or null if one has not been set.
    Type
    module:api.KeyValueStore

    <async> getUserContext(name, checkPersistence)

    Returns the user by the given name. 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 current in-memory user context object, or null if none has been set. 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:
    Promise for 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.<User>

    <async> initCredentialStores()

    Sets the state and crypto suite for use by this client. This requires that a common connection profile has been loaded. Will use the settings from the common connection profile along with the system configuration to build instances of the stores and assign them to this client and the crypto suites if needed.
    Returns:
    - A promise to build a key value store and crypto store.
    Type
    Promise

    <async> installChaincode(request, timeout)

    A chaincode must be installed to peers and instantiated on a channel before it can be called to process transactions.

    Chaincode installation is simply uploading the chaincode source and dependencies to the peers. This operation is "channel-agnostic" and is performed on a peer-by-peer basis. Only the peer organization's ADMIN identities are allowed to perform this operation.
    Parameters:
    Name Type Description
    request ChaincodeInstallRequest The request object
    timeout Number A number indicating milliseconds to wait on the response before rejecting the promise with a timeout error. This overrides the default timeout of the Peer instance and the global timeout in the config settings.
    Returns:
    A Promise for a ProposalResponseObject
    Type
    Promise

    isDevMode()

    Determine if the fabric backend is started in development mode. In development mode, the endorsing peers will not attempt to spin up a docker instance to run the target chaincode requested by a transaction proposal, but instead redirect the invocation requests to the chaincode process that has registered itself with the endorsing peer. This makes it easier to test changes to the chaincode during chaincode development.

    The client instance can be set to dev mode to reflect the backend's development mode. This will cause the SDK to make adjustments in certain behaviors such as not sending the chaincode package to the peers during chaincode install.

    loadFromConfig(config)

    Load a common connection profile object or load a JSON file and update this client with any values in the config.
    Parameters:
    Name Type Description
    config object | string This may be the config object or a path to the configuration file

    <async> loadUserFromStateStore(name)

    Restore the state of the User by the given name from the key value store (if found). If not found, return null.
    Parameters:
    Name Type Description
    name string Name of the user
    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

    newChannel(name)

    Returns a Channel instance with the given name. This represents a channel and its associated ledger.
    Parameters:
    Name Type Description
    name string The name of the channel. Recommend using namespaces to avoid collision.
    Returns:
    The uninitialized channel instance.
    Type
    Channel

    newOrderer(url, opts)

    Returns an Orderer object with the given url and opts. An orderer object encapsulates the properties of an orderer node and the interactions with it via the grpc stream API. Orderer objects are used by the Client objects to broadcast requests for creating and updating channels. They are used by the Channel objects to broadcast requests for ordering transactions. This method will create the orderer.
    Parameters:
    Name Type Description
    url string The URL with format of "grpc(s)://host:port".
    opts ConnectionOpts The options for the connection to the orderer.
    Returns:
    The Orderer instance.
    Type
    Orderer

    newPeer(url, opts)

    Returns a Peer object with the given url and opts. A peer object encapsulates the properties of an endorsing peer and the interactions with it via the grpc service API. Peer objects are used by the Client objects to send channel-agnostic requests such as installing chaincode, querying peers for installed chaincodes, etc. They are also used by the Channel objects to send channel-aware requests such as instantiating chaincodes, and invoking transactions. This method will return a new Peer object.
    Parameters:
    Name Type Description
    url string The URL with format of "grpc(s)://host:port".
    opts ConnectionOpts The options for the connection to the peer.
    Returns:
    The Peer instance.
    Type
    Peer

    newTransactionID(admin)

    Returns a new TransactionID object. Fabric transaction ids are constructed as a hash of a nonce concatenated with the signing identity's serialized bytes. The TransactionID object keeps the nonce and the resulting id string bundled together as a coherent pair.

    This method requires the client instance to have been assigned a userContext.
    Parameters:
    Name Type Description
    admin boolean If true, this transactionID should be built based on the admin credentials Default is a non admin TransactionID based on the userContext.
    Returns:
    An object that contains a transaction id based on the client's userContext and a randomly generated nonce value.
    Type
    TransactionID

    <async> queryChannels(peer, useAdmin)

    Queries the target peer for the names of all the channels that a peer has joined.
    Parameters:
    Name Type Description
    peer Peer The target peer to send the query
    useAdmin boolean Optional. Indicates that the admin credentials should be used in making this call to the peer. An administrative identity must have been loaded by common connection profile or by using the 'setAdminSigningIdentity' method.
    Returns:
    A promise to return a ChannelQueryResponse
    Type
    Promise

    <async> queryInstalledChaincodes(peer, useAdmin)

    Queries the installed chaincodes on a peer.
    Parameters:
    Name Type Description
    peer Peer The target peer
    useAdmin boolean Optional. Indicates that the admin credentials should be used in making this call to the peer. An administrative identity must have been loaded by common connection profile or by using the 'setAdminSigningIdentity' method.
    Returns:
    Promise for a ChaincodeQueryResponse object
    Type
    Promise

    <async> queryPeers(request)

    Queries the target peer for a list of Peer objects of all peers known by the target peer.
    Parameters:
    Name Type Description
    request PeerQueryRequest The request parameters.
    Returns:
    The list of peer information
    Type
    PeerQueryResponse

    <async> saveUserToStateStore()

    Persist the current userContext to the key value store.
    Returns:
    A Promise for the userContext object upon successful persistence
    Type
    Promise

    setAdminSigningIdentity(private_key, certificate, mspid)

    Set the admin signing identity object. This method will only assign a signing identity for use by this client instance and will not persist the identity.
    Parameters:
    Name Type Description
    private_key string the private key PEM string
    certificate string the PEM-encoded string of certificate
    mspid string The Member Service Provider id for the local signing identity

    setCryptoSuite(cryptoSuite)

    Sets the client instance to use the CryptoSuite object for signing and hashing Creating and setting a CryptoSuite is optional because the client will construct an instance based on default 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
    cryptoSuite module:api.CryptoSuite the CryptoSuite object
    Inherited From:
    Overrides:

    setDevMode(devMode)

    Set dev mode to true or false to reflect the mode of the fabric backend. See Client#isDevMode for details.
    Parameters:
    Name Type Description
    devMode boolean

    setStateStore(keyValueStore)

    Set an optional state store to persist application states. The state store must implement the module:api.KeyValueStore interface.

    The SDK supports persisting the User objects so that the heavy-weight objects such as the certificate and private keys do not have to be passed in repeatedly. Out of the box the SDK provides a file-based implementation, and a CouchDB-based implementation, which also supports Cloudant. Applications can provide alternative implementations.
    Parameters:
    Name Type Description
    keyValueStore module:api.KeyValueStore Instance of a KeyValueStore implementation

    setTlsClientCertAndKey(clientCert, clientKey)

    Sets the mutual TLS client side certificate and key necessary to build network endpoints when working with a common connection profile (connection profile). This must be called before a peer, orderer, or channel eventhub is needed. If the tls client material has not been provided for the client, it will be generated if the user has been assigned to this client. Note that it will always use the default software cryptosuite, not the one assigned to the client.
    Parameters:
    Name Type Description
    clientCert string The pem encoded client certificate.
    clientKey Array.<byte> The client key.

    <async> setUserContext(user, skipPersistence)

    Sets an instance of the User class as the security context of this client instance. This user’s signing identity (the private key and its corresponding certificate), will be used to sign all requests with the fabric backend.

    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 | UserNamePasswordObject An instance of the User class encapsulating the authenticated user’s signing materials (private key and enrollment certificate). The parameter may also be a UserNamePasswordObject that contains the username and optionally the password and caName. A common connection profile must has been loaded to use the UserNamePasswordObject which will also create the user context and set it on this client instance. The created user context will be based on the current network configuration( i.e. the current organization's CA, current persistence stores).
    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. When using a common connection profile and UserNamePasswordObject, the user object will always be stored to the persistence store.
    Returns:
    Promise of the 'user' object upon successful persistence of the user to the state store
    Type
    Promise

    signChannelConfig(loadConfig)

    Channel configuration updates can be sent to the orderers to be processed. The orderer enforces the Channel creation or update policies such that the updates will be made only when enough signatures from participating organizations are discovered in the request. Typically channel creation or update requests must be signed by participating organizations' ADMIN principals, although this policy can be customized when the consortium is defined.

    This method uses the client instance's current signing identity to sign over the configuration bytes passed in, and returns the signature that is ready to be included in the configuration update protobuf message to send to the orderer.
    Parameters:
    Name Type Description
    loadConfig 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. After the channel updates are successfully processed by the orderer, the orderer cuts a new block containing the new channel configuration and delivers it to all the participating peers in the channel.
    Parameters:
    Name Type Description
    request ChannelRequest The request object.
    Returns:
    Promise for a result object with status on the acceptance of the update request by the orderer. A channel update is finally completed when the new channel configuration block created by the orderer has been committed to the channel's peers. To be notified of the successful update of the channel, an application should use the ChannelEventHub to connect to the peers and register a block listener.
    Type
    Promise