Class: Channel

Channel

Channels provide data isolation for a set of participating organizations.

A Channel object captures the settings needed to interact with a fabric backend in the context of a channel. These settings including the list of participating organizations, represented by instances of Membership Service Providers (MSP), the list of endorsing peers, and an orderer.

A client application can use the Channel object to create new channels with the orderer, update an existing channel, send various channel-aware requests to the peers such as invoking chaincodes to process transactions or queries.

A Channel object is also responsible for verifying endorsement signatures in transaction proposal responses. A channel object must be initialized after it has been configured with the list of peers and orderers. The initialization sends a get configuration block request to the primary orderer to retrieve the configuration settings for this channel.

new Channel(name, clientContext)

Returns a new instance of the class. This is a client-side-only call. To create a new channel in the fabric, call createChannel().
Parameters:
Name Type Description
name string Name to identify the channel. This value is used as the identifier of the channel when making channel-aware requests with the fabric, such as invoking chaincodes to endorse transactions. The naming of channels is enforced by the ordering service and must be unique within the fabric backend. Channel name in fabric network is subject to a pattern revealed in the configuration setting channel-name-regx-checker.
clientContext Client The client instance, which provides operational context such as the signing identity

Methods


<async, static> sendSignedProposal(request, timeout)

Send signed transaction proposal to peer
Parameters:
Name Type Description
request SignedProposal signed endorse transaction proposal, this signed proposal would be send to peer directly.
timeout number the timeout setting passed on sendSignedProposal

<async> _discover(request)

Send a request to a known peer to discover information about the fabric network.
Parameters:
Name Type Description
request DiscoveryRequest -
Returns:
The results from the discovery service
Type
DiscoveryResponse

addOrderer(orderer, replace)

Add the orderer object to the channel object, this is a client-side-only operation. An application may add more than one orderer object to the channel object, however the SDK only uses the first one in the list to send broadcast messages to the orderer backend.
Parameters:
Name Type Description
orderer Orderer An instance of the Orderer class.
replace boolean If an orderer exist with the same name, replace with this one.

addPeer(peer, mspid, roles, replace)

Add the peer object to the channel object. A channel object can be optionally configured with a list of peer objects, which will be used when calling certain methods such as sendInstantiateProposal(), sendUpgradeProposal(), sendTransactionProposal.
Parameters:
Name Type Description
peer Peer An instance of the Peer class that has been initialized with URL and other gRPC options such as TLS credentials and request timeout.
mspid string The mpsid of the organization this peer belongs.
roles ChannelPeerRoles Optional. The roles this peer will perform on this channel. A role that is not defined will default to true
replace boolean If a peer exist with the same name, replace with this one.

close()

Close the service connections of all assigned peers and orderers

compareProposalResponseResults(The)

Utility method to examine a set of proposals to check they contain the same endorsement result write sets. This will validate that the endorsing peers all agree on the result of the chaincode execution.
Parameters:
Name Type Description
The Array.<ProposalResponse> proposal responses from all endorsing peers
Returns:
True when all proposals compare equally, false otherwise.
Type
boolean

generateUnsignedProposal(request, mspId, certificate, admin)

Generates the endorse proposal bytes for a transaction Current the sendTransactionProposal sign a transaction using the user identity from SDK's context (which contains the user's private key). This method is designed to build the proposal bytes at SDK side, and user can sign this proposal with their private key, and send the signed proposal to peer by [sendSignedProposal] so the user's private key would not be required at SDK side.
Parameters:
Name Type Description
request ProposalRequest chaincode invoke request
mspId string the mspId for this identity
certificate string PEM encoded certificate
admin boolean if this transaction is invoked by admin
Returns:
Type
Proposal

generateUnsignedTransaction(request)

generate the commit proposal for a transaction
Parameters:
Name Type Description
request TransactionRequest

getChannelCapabilities(configEnvelope)

This utility method takes a ConfigEnvelope as queried from a channel and locates the channel's capabilities
Parameters:
Name Type Description
configEnvelope ConfigEnvelope The grpc ConfigEnvelope as returned from the getChannelConfig() method.
Returns:
An array of strings with this channels capablities
Type
Array.<String>

<async> getChannelConfig(target, timeout)

Asks the peer for the current (latest) configuration block for this channel.
Parameters:
Name Type Description
target string | Peer Optional. The peer to be used to make the request.
timeout Number Optional. 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(s) and the global timeout in the config settings.
Returns:
A Promise for a ConfigEnvelope object containing the configuration items.
Type
Promise

<async> getChannelConfigFromOrderer()

Asks the orderer for the current (latest) configuration block for this channel. This is similar to getGenesisBlock(), except that instead of getting block number 0 it gets the latest block that contains the channel configuration, and only returns the decoded ConfigEnvelope.
Returns:
A Promise for a ConfigEnvelope object containing the configuration items.
Type
Promise

getChannelEventHub(name)

Returns a ChannelEventHub object. An event hub object encapsulates the properties of an event stream on a peer node, through which the peer publishes notifications of blocks being committed in the channel's ledger. This method will create a new ChannelEventHub if one does not exist.
Parameters:
Name Type Description
name string The peer name associated with this channel event hub. Use the Peer#getName method to get the name of a peer instance that has been added to this channel.
Returns:
- The ChannelEventHub associated with the peer.
Type
ChannelEventHub

getChannelEventHubsForOrg(mspid)

Returns a list of ChannelEventHub based on the peers that are defined in this channel that are in the organization.
Parameters:
Name Type Description
mspid string Optional - The mspid of an organization
Returns:
An array of ChannelEventHub instances
Type
Array.<ChannelEventHub>

getChannelPeer(name)

See in getPeer
Parameters:
Name Type Description
name string The name of the peer
Returns:
The ChannelPeer instance
Type
ChannelPeer

getChannelPeers()

See in getPeers
Returns:
The channel peer list on the channel.
Type
Array.<ChannelPeer>

<async> getDiscoveryResults(endorsement_hints)

Return the discovery results. Discovery results are only available if this channel has been initialized. If the results are too old, they will be refreshed
Parameters:
Name Type Description
endorsement_hints Array.<DiscoveryChaincodeInterest> Indicate to discovery how to calculate the endorsement plans.
Returns:
Type
Promise.<DiscoveryResults>

<async> getEndorsementPlan(endorsement_hint)

Return a single endorsement plan based off a DiscoveryChaincodeInterest.
Parameters:
Name Type Description
endorsement_hint DiscoveryChaincodeInterest The chaincodes and collections of how the discovery service will calculate an endorsement plan.
Returns:
The endorsement plan based on the hint provided.
Type
DiscoveryResultEndorsementPlan

getGenesisBlock(request)

A channel's first block is called the "genesis block". This block captures the initial channel configuration. For a peer node to join the channel, it must be provided the genesis block. This method must be called before calling joinChannel().
Parameters:
Name Type Description
request OrdererRequest Optional - A transaction ID object
Returns:
A Promise for an encoded protobuf "Block"
Type
Promise

getMSPManager()

Get the MSP Manager for this channel
Returns:
Type
MSPManager

getName()

Get the channel name.
Returns:
The name of the channel.
Type
string

getOrderer(name)

This method will return a Orderer instance if assigned to this channel. Peers that have been created by the Client#newOrderer method and then added to this channel may be reference by the url if no name was provided in the options during the create.
Parameters:
Name Type Description
name string The name or url of the orderer
Returns:
The Orderer instance.
Type
Orderer

getOrderers()

Returns the orderers of this channel object.
Returns:
The list of orderers in the channel object
Type
Array.<Orderer>

getOrganizations()

Get organization identifiers from the MSP's for this channel
Returns:
Array of OrganizationIdentifier Objects representing the channel's participating organizations
Type
Array.<OrganizationIdentifier>

getPeer(name)

This method will return a ChannelPeer instance if assigned to this channel. Peers that have been created by the Client#newPeer method and then added to this channel may be reference by the url if no name was provided in the options during the create. A ChannelPeer provides a reference to Peer, channel event hub objects along with attributes of how this peer is being used on this channel.
Parameters:
Name Type Description
name string The name of the peer
Returns:
The ChannelPeer instance.
Type
ChannelPeer

getPeers()

Returns a list of ChannelPeer assigned to this channel instance. A ChannelPeer provides a reference to peer and channel event hub along with how this peer is being used on this channel.
Returns:
The channel peer list on the channel.
Type
Array.<ChannelPeer>

getPeersForOrg(mspid)

Returns a list of Peer that are defined in this channel that are in the named organization.
Parameters:
Name Type Description
mspid string Optional - The name of an organization
Returns:
An array of Peer instances
Type
Array.<Peer>

<async> initialize(request)

Initializes the channel object with the Membership Service Providers (MSPs). The channel's MSPs are critical in providing applications the ability to validate certificates and verify signatures in messages received from the fabric backend. For instance, after calling sendTransactionProposal(), the application can verify the signatures in the proposal response's endorsements to ensure they have not been tampered with.

This method retrieves the configuration from the orderer if no "config" parameter is passed in. Optionally a configuration may be passed in to initialize this channel without making the call to the orderer.

This method will also automatically load orderers and peers that represent the fabric network when using discovery. This application must provide a peer running the fabric discovery service.
Parameters:
Name Type Description
request InitializeRequest Optional. a InitializeRequest
Returns:
A Promise that will resolve when the action is complete
Type
Promise

joinChannel(request, timeout)

For a peer node to become part of a channel, it must be sent the genesis block, as explained here. This method sends a join channel proposal to one or more endorsing peers.
Parameters:
Name Type Description
request JoinChannelRequest
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(s) and the global timeout in the config settings.
Returns:
A Promise for an array of ProposalResponse from the target peers
Type
Promise

newChannelEventHub(peer)

Returns a ChannelEventHub object. An event hub object encapsulates the properties of an event stream on a peer node, through which the peer publishes notifications of blocks being committed in the channel's ledger. This method will create a new ChannelEventHub and not save a reference. Use the {getChannelEventHub} to reuse a ChannelEventHub.
Parameters:
Name Type Description
peer Peer | string Optional. A Peer instance or the name of a peer that has been assigned to the channel. If not provided the ChannelEventHub must be connected with a "target" peer.
Returns:
The ChannelEventHub instance
Type
ChannelEventHub

<async> queryBlock(blockNumber, target, useAdmin, skipDecode)

Queries the ledger on the target peer for Block by block number.
Parameters:
Name Type Description
blockNumber number The number of the Block in question.
target Peer Optional. The peer to send this query to. If no target is passed, the query is sent to the first peer that was added to the channel object.
useAdmin boolean Optional. Indicates that the admin credentials should be used in making this call to the peer.
skipDecode boolean Optional. If true, this function returns an encoded block.
Returns:
A Promise for a Block at the blockNumber slot in the ledger, fully decoded into an object.
Type
Promise

<async> queryBlockByHash(blockHash, target, useAdmin, skipDecode)

Queries the ledger on the target peer for a Block by block hash.
Parameters:
Name Type Description
blockHash Array.<byte> of the Block in question.
target Peer Optional. The peer to send the query to. If no target is passed, the query is sent to the first peer that was added to the channel object.
useAdmin boolean Optional. Indicates that the admin credentials should be used in making this call to the peer.
skipDecode boolean Optional. If true, this function returns an encoded block.
Returns:
A Promise for a Block matching the hash, fully decoded into an object.
Type
Promise

<async> queryBlockByTxID(tx_id, target, useAdmin, skipDecode)

Queries the ledger on the target peer for a Block TransactionID.
Parameters:
Name Type Description
tx_id string The TransactionID of the Block in question.
target Peer Optional. The peer to send the query to. If no target is passed, the query is sent to the first peer that was added to the channel object.
useAdmin boolean Optional. Indicates that the admin credentials should be used in making this call to the peer.
skipDecode boolean Optional. If true, this function returns an encoded block.
Returns:
A Promise for a Block matching the tx_id, fully decoded into an object.
Type
Promise

<async> queryByChaincode(request, useAdmin)

Sends a proposal to one or more endorsing peers that will be handled by the chaincode. There is no difference in how the endorsing peers process a request to invoke a chaincode for transaction vs. to invoke a chaincode for query. All requests will be presented to the target chaincode's 'Invoke' method which must be implemented to understand from the arguments that this is a query request. The chaincode must also return results in the byte array format and the caller will have to be able to decode these results. If the request contains a txId property, that transaction ID will be used, and its administrative privileges will apply. In this case the useAdmin parameter to this function will be ignored.
Parameters:
Name Type Description
request ChaincodeQueryRequest
useAdmin boolean Optional. Indicates that the admin credentials should be used in making this call. Ignored if the request contains a txId property.
Returns:
A Promise for an array of byte array results returned from the chaincode on all Endorsing Peers
Type
Promise
Example

Get the list of query results returned by the chaincode

const responsePayloads = await channel.queryByChaincode(request);
for (let i = 0; i < responsePayloads.length; i++) {
    console.log(util.format('Query result from peer [%s]: %s', i, responsePayloads[i].toString('utf8')));
}

<async> queryCollectionsConfig(options, useAdmin)

Query for the collection definitions associated with a chaincode.
Parameters:
Name Type Description
options CollectionQueryOptions Required. The options to query the collections config.
useAdmin boolean Optional. To indicate that the admin identity should be used to make the query request
Returns:
returns a promise for an array of CollectionQueryResponse objects.
Type
Promise.<Array.<CollectionQueryResponse>>

<async> queryInfo(target, useAdmin)

Queries for various useful information on the state of the Channel (height, known peers).
Parameters:
Name Type Description
target Peer Optional. The peer that is the target for this query. If no target is passed, the query will use the first peer that was added to the channel object.
useAdmin boolean Optional. Indicates that the admin credentials should be used in making this call to the peer.
Returns:
A Promise for a BlockchainInfo object with blockchain height, current block hash and previous block hash.
Type
Promise

<async> queryInstantiatedChaincodes(target, useAdmin)

Queries the ledger on the target peer for instantiated chaincodes on this channel.
Parameters:
Name Type Description
target Peer Optional. The peer to send this query to. If no target is passed, the query is sent to the first peer that was added to the channel object.
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 for a fully decoded ChaincodeQueryResponse object.
Type
Promise

<async> queryTransaction(tx_id, target, useAdmin, skipDecode)

Queries the ledger on the target peer for Transaction by id.
Parameters:
Name Type Description
tx_id string The id of the transaction
target Peer Optional. The peer to send this query to. If no target is passed, the query is sent to the first peer that was added to the channel object.
useAdmin boolean Optional. Indicates that the admin credentials should be used in making this call to the peer.
skipDecode boolean Optional. If true, this function returns an encoded transaction.
Returns:
A Promise for a fully decoded ProcessedTransaction object.
Type
Promise

<async> refresh()

Refresh the channel's configuration. The MSP configurations, peers, orderers, and endorsement plans will be queired from the peer using the Discover Service. The queries will be made to the peer used previously for discovery if the 'target' parameter is not provided.
Returns:
- The results of refreshing
Type
DiscoveryResults

removeOrderer(orderer)

Remove the first orderer object in the channel object's list of orderers whose endpoint url property matches the url of the orderer that is passed in.
Parameters:
Name Type Description
orderer Orderer An instance of the Orderer class.

removePeer(peer)

Remove the peer object in the channel object's list of peers whose endpoint url property matches the url or name of the peer that is passed in.
Parameters:
Name Type Description
peer Peer An instance of the Peer class.

sendInstantiateProposal(request, timeout)

Sends a chaincode instantiate proposal to one or more endorsing peers. A chaincode must be instantiated on a channel-by-channel basis before it can be used. The chaincode must first be installed on the endorsing peers where this chaincode is expected to run, by calling client.installChaincode().

Instantiating a chaincode is a full transaction operation, meaning it must be first endorsed as a proposal, then the endorsements are sent to the orderer to be processed for ordering and validation. When the transaction finally gets committed to the channel's ledger on the peers, the chaincode is then considered activated and the peers are ready to take requests to process transactions.
Parameters:
Name Type Description
request ChaincodeInstantiateUpgradeRequest
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 the ProposalResponseObject
Type
Promise

<async> sendSignedProposal(request, timeout)

Send signed transaction proposal to peer
Parameters:
Name Type Description
request SignedProposal signed endorse transaction proposal, this signed proposal would be send to peer directly.
timeout number the timeout setting passed on sendSignedProposal

<async> sendSignedTransaction(request, timeout)

send the signed commit proposal for a transaction
Parameters:
Name Type Description
request SignedCommitProposal the signed commit proposal
timeout number the timeout setting passed on sendSignedProposal

<async> sendTransaction(request, timeout)

Send the proposal responses that contain the endorsements of a transaction proposal to the orderer for further processing. This is the 2nd phase of the transaction lifecycle in the fabric. The orderer will globally order the transactions in the context of this channel and deliver the resulting blocks to the committing peers for validation against the chaincode's endorsement policy. When the committing peers successfully validate the transactions, it will mark the transaction as valid inside the block. After all transactions in a block have been validated, and marked either as valid or invalid (with a reason code), the block will be appended (committed) to the channel's ledger on the peer.

The caller of this method must use the proposal responses returned from the endorser along with the original proposal that was sent to the endorser. Both of these objects are contained in the ProposalResponseObject returned by calls to any of the following methods:
  • sendInstantiateProposal()
  • sendUpgradeProposal()
  • sendTransactionProposal()
  • Parameters:
    Name Type Description
    request TransactionRequest TransactionRequest
    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 Orderer instance and the global timeout in the config settings.
    Returns:
    A Promise for a "BroadcastResponse" message returned by the orderer that contains a single "status" field for a standard HTTP response code. This will be an acknowledgement from the orderer of a successfully submitted transaction.
    Type
    Promise

    <async> sendTransactionProposal(request, timeout)

    Sends a transaction proposal to one or more endorsing peers. After a chaincode gets installed and instantiated, it's ready to take endorsement proposals and participating in transaction processing. A chaincode transaction starts with a proposal that gets sent to the endorsing peers, which executes the target chaincode and decides whether the proposal should be endorsed (if it executes successfully) or not (if the chaincode returns an error).
    Parameters:
    Name Type Description
    request ChaincodeInvokeRequest
    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 the ProposalResponseObject
    Type
    Promise

    sendUpgradeProposal(request, timeout)

    Sends a chaincode upgrade proposal to one or more endorsing peers. Upgrading a chaincode involves steps similar to instantiating a chaincode. The new chaincode must first be installed on the endorsing peers where this chaincode is expected to run.

    Similar to instantiating a chaincode, upgrading chaincodes is also a full transaction operation.
    Parameters:
    Name Type Description
    request ChaincodeInstantiateUpgradeRequest
    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 the ProposalResponseObject
    Type
    Promise

    setMSPManager(msp_manager)

    Set the MSP Manager for this channel. This utility method will not normally be use as the initialize() method will read this channel's current configuration and reset MSPManager with the MSP's found in the channel configuration.
    Parameters:
    Name Type Description
    msp_manager MSPManager The msp manager for this channel

    toString()

    return a printable representation of this channel object

    verifyProposalResponse(proposal_response)

    Utility method to verify a single proposal response. It checks the following aspects:
  • The endorser's identity belongs to a legitimate MSP of the channel and can be successfully deserialized
  • The endorsement signature can be successfully verified with the endorser's identity certificate

    This method requires that the initialize method of this channel object has been called to load this channel's MSPs. The MSPs will have the trusted root certificates for this channel.
  • Parameters:
    Name Type Description
    proposal_response ProposalResponse The endorsement response from the peer, includes the endorser certificate and signature over the proposal + endorsement result + endorser certificate.
    Returns:
    A boolean value of true when both the identity and the signature are valid, false otherwise.
    Type
    boolean