Class: ChaincodeStub

ChaincodeStub

The ChaincodeStub is implemented by the fabric-shim library and passed to the ChaincodeInterface calls by the Hyperledger Fabric platform. The stub encapsulates the APIs between the chaincode implementation and the Fabric peer

new ChaincodeStub(client, channel_id, txId, chaincodeInput, signedProposal)

Parameters:
Name Type Description
client Handler an instance of the Handler class
channel_id string channel id
txId string transaction id
chaincodeInput any decoded message from peer
signedProposal any the proposal

Methods


createCompositeKey(objectType, attributes)

Creates a composite key by combining the objectType string and the given `attributes` to form a composite key. The objectType and attributes are expected to have only valid utf8 strings and should not contain U+0000 (nil byte) and U+10FFFF (biggest and unallocated code point). The resulting composite key can be used as the key in putState().

Hyperledger Fabric uses a simple key/value model for saving chaincode states. In some use case scenarios, it is necessary to keep track of multiple attributes. Furthermore, it may be necessary to make the various attributes searchable. Composite keys can be used to address these requirements. Similar to using composite keys in a relational database table, here you would treat the searchable attributes as key columns that make up the composite key. Values for the attributes become part of the key, thus they are searchable with functions like getStateByRange() and getStateByPartialCompositeKey().

Parameters:
Name Type Description
objectType string A string used as the prefix of the resulting key
attributes Array.<string> List of attribute values to concatenate into the key
Returns:
A composite key with the objectType and the array of attributes joined together with special delimiters that will not be confused with values of the attributes
Type
string

<async> deletePrivateData(collection, key)

deletePrivateData records the specified `key` to be deleted in the private writeset of the transaction. Note that only hash of the private writeset goes into the transaction proposal response (which is sent to the client who issued the transaction) and the actual private writeset gets temporarily stored in a transient store. The `key` and its value will be deleted from the collection when the transaction is validated and successfully committed.
Parameters:
Name Type Description
collection string The collection name
key string Private data variable key to delete from the state store

<async> deleteState(key)

Deletes the state variable key from the state store.
Parameters:
Name Type Description
key string State variable key to delete from the state store
Returns:
Promise will be resolved when the peer has successfully handled the state delete request or rejected if any errors
Type
Promise

getArgs()

Returns the arguments as array of strings from the chaincode invocation request. Equivalent to getStringArgs()
Returns:
Type
Array.<string>

getBinding()

Returns a HEX-encoded string of SHA256 hash of the transaction's nonce, creator and epoch concatenated, as a unique representation of the specific transaction. This value can be used to prevent replay attacks in chaincodes that need to authenticate an identity independent of the transaction's submitter. In a chaincode proposal, the submitter will have been authenticated by the peer such that the identity returned by stub.getCreator() can be trusted. But in some scenarios, the chaincode needs to authenticate an identity independent of the proposal submitter.

For example, Alice is the administrator who installs and instantiates a chaincode that manages assets. During instantiate Alice assigns the initial owner of the asset to Bob. The chaincode has a function called transfer() that moves the asset to another identity by changing the asset's "owner" property to the identity receiving the asset. Naturally only Bob, the current owner, is supposed to be able to call that function. While the chaincode can rely on stub.getCreator() to check the submitter's identity and compare that with the current owner, sometimes it's not always possible for the asset owner itself to submit the transaction. Let's suppose Bob hires a broker agency to handle his trades. The agency participates in the blockchain network and carry out trades on behalf of Bob. The chaincode must have a way to authenticate the transaction to ensure it has Bob's authorization to do the asset transfer. This can be achieved by asking Bob to sign the message, so that the chaincode can use Bob's certificate, which was obtained during the chaincode instantiate, to verify the signature and thus ensure the trade was authorized by Bob.

Now, to prevent Bob's signature from being re-used in a malicious attack, we want to ensure the signature is unique. This is where the binding concept comes in. As explained above, the binding string uniquely represents the transaction where the trade proposal and Bob's authorization is submitted in. As long as Bob's signature is over the proposal payload and the binding string concatenated together, namely sigma=Sign(BobSigningKey, tx.Payload||tx.Binding), it's guaranteed to be unique and can not be re-used in a different transaction for exploitation.

Returns:
A HEX-encoded string of SHA256 hash of the transaction's nonce, creator and epoch concatenated
Type
string

getChannelID()

Returns the channel ID for the proposal for chaincode to process. This would be the 'channel_id' of the transaction proposal (see ChannelHeader in protos/common/common.proto) except where the chaincode is calling another on a different channel.

getCreator()

Returns the identity object of the chaincode invocation's submitter
Returns:
Type
ProposalCreator

getDateTimestamp()

Returns the Date object of when the transaction was created. This is taken from the transaction ChannelHeader, therefore it will indicate the client's date, and will have the same value across all endorsers.

getFunctionAndParameters()

Returns an object containing the chaincode function name to invoke, and the array of arguments to pass to the target function
Returns:
Type
FunctionAndParameters

<async> getHistoryForKey(key)

Returns a history of key values across time. For each historic key update, the historic value and associated transaction id and timestamp are returned. The timestamp is the timestamp provided by the client in the proposal header. This method requires peer configuration core.ledger.history.enableHistoryDatabase to be true.

The query is NOT re-executed during validation phase, phantom reads are not detected. That is, other committed transactions may have updated the key concurrently, impacting the result set, and this would not be detected at validation/commit time. Applications susceptible to this should therefore not use GetHistoryForKey as part of transactions that update ledger, and should limit use to read-only chaincode operations.
Parameters:
Name Type Description
key string The state variable key
Returns:
Promise for a HistoryQueryIterator object
Type
Promise

getMspID()

Returns the MSPID of the peer that started this chaincode
Returns:
MSPID
Type
string

<async> getPrivateData(collection, key)

getPrivateData returns the value of the specified `key` from the specified `collection`. Note that GetPrivateData doesn't read data from the private writeset, which has not been committed to the `collection`. In other words, GetPrivateData doesn't consider data modified by PutPrivateData that has not been committed.
Parameters:
Name Type Description
collection string The collection name
key string Private data variable key to retrieve from the state store
Returns:
Promise for the private value from the state store
Type
Promise.<Array.<byte>>

getPrivateDataByPartialCompositeKey(collection, objectType, attributes)

getPrivateDataByPartialCompositeKey queries the state in a given private collection based on a given partial composite key. This function returns an iterator which can be used to iterate over all composite keys whose prefix matches the given partial composite key. The `objectType` and attributes are expected to have only valid utf8 strings and should not contain U+0000 (nil byte) and U+10FFFF (biggest and unallocated code point). See related functions SplitCompositeKey and CreateCompositeKey. Call Close() on the returned StateQueryIteratorInterface object when done. The query is re-executed during validation phase to ensure result set has not changed since transaction endorsement (phantom reads detected).
Parameters:
Name Type Description
collection string The collection name
objectType string A string used as the prefix of the resulting key
attributes Array.<string> List of attribute values to concatenate into the partial composite key
Returns:
Promise for a PrivateQueryResponse object
Type
Promise

getPrivateDataByRange(collection, startKey, endKey)

getPrivateDataByRange returns a range iterator over a set of keys in a given private collection. The iterator can be used to iterate over all keys between the startKey (inclusive) and endKey (exclusive). The keys are returned by the iterator in lexical order. Note that startKey and endKey can be empty string, which implies unbounded range query on start or end. Call Close() on the returned StateQueryIteratorInterface object when done. The query is re-executed during validation phase to ensure result set has not changed since transaction endorsement (phantom reads detected).
Parameters:
Name Type Description
collection string The collection name
startKey string Private data variable key as the start of the key range (inclusive)
endKey string Private data variable key as the end of the key range (exclusive)
Returns:
Promise for a PrivateQueryResponse object
Type
Promise

<async> getPrivateDataHash(collection, key)

getPrivateDataHash returns the hash of the value of the specified `key` from the specified `collection`.
Parameters:
Name Type Description
collection string The collection name
key string Private data variable key to retrieve a hash from the state store
Returns:
Promise for the private value hash from the state store
Type
Promise.<Array.<byte>>

getPrivateDataQueryResult(collection, query)

getPrivateDataQueryResult performs a "rich" query against a given private collection. It is only supported for state databases that support rich query, e.g.CouchDB. The query string is in the native syntax of the underlying state database. An iterator is returned which can be used to iterate (next) over the query result set. The query is NOT re-executed during validation phase, phantom reads are not detected. That is, other committed transactions may have added, updated, or removed keys that impact the result set, and this would not be detected at validation/commit time. Applications susceptible to this should therefore not use GetQueryResult as part of transactions that update ledger, and should limit use to read-only chaincode operations.
Parameters:
Name Type Description
collection string The collection name
query string The query to be performed
Returns:
Promise for a PrivateQueryResponse object
Type
Promise

<async> getPrivateDataValidationParameter(collection, key)

GetPrivateDataValidationParameter retrieves the key-level endorsement policy for the private data specified by `key`. Note that this introduces a read dependency on `key` in the transaction's readset.
Parameters:
Name Type Description
collection string The collection name for this private data
key string Private data variable key by which to retrieve endorsement policy
Returns:
endorsement policy for this key
Type
Buffer

<async> getQueryResult(query)

Performs a "rich" query against a state database. It is only supported for state databases that support rich query, e.g. CouchDB. The query string is in the native syntax of the underlying state database. An StateQueryIterator is returned which can be used to iterate over all keys in the query result set.

However, if the number of keys in the query result set is greater than the totalQueryLimit (defined in core.yaml), this iterator cannot be used to fetch all keys in the query result set (results will be limited by the totalQueryLimit). The query is NOT re-executed during validation phase, phantom reads are not detected. That is, other committed transactions may have added, updated, or removed keys that impact the result set, and this would not be detected at validation/commit time. Applications susceptible to this should therefore not use GetQueryResult as part of transactions that update ledger, and should limit use to read-only chaincode operations.
Parameters:
Name Type Description
query string Query string native to the underlying state database
Returns:
Promise for a StateQueryIterator object
Type
Promise

getQueryResultWithPagination(query, pageSize, bookmark)

getQueryResultWithPagination performs a "rich" query against a state database. It is only supported for state databases that support rich query, e.g., CouchDB. The query string is in the native syntax of the underlying state database. An iterator is returned which can be used to iterate over keys in the query result set. When an empty string is passed as a value to the bookmark argument, the returned iterator can be used to fetch the first `pageSize` of query results. When the bookmark is a non-emptry string, the iterator can be used to fetch the first `pageSize` keys between the bookmark and the last key in the query result. Note that only the bookmark present in a prior page of query results (ResponseMetadata) can be used as a value to the bookmark argument. Otherwise, an empty string must be passed as bookmark. This call is only supported in a read only transaction.
Parameters:
Name Type Description
query string
pageSize int
bookmark string
Returns:
Promise for a PaginationQueryResponse object
Type
Promise

getSignedProposal()

Returns a fully decoded object of the signed transaction proposal
Returns:
Type
SignedProposal

<async> getState(key)

Retrieves the current value of the state variable key
Parameters:
Name Type Description
key string State variable key to retrieve from the state store
Returns:
Promise for the current value of the state variable
Type
Promise.<Array.<byte>>

<async> getStateByPartialCompositeKey(objectType, attributes)

Queries the state in the ledger based on a given partial composite key. This function returns an iterator which can be used to iterate over all composite keys whose prefix matches the given partial composite key. However, if the number of matching composite keys is greater than the totalQueryLimit (defined in core.yaml), this iterator cannot be used to fetch all matching keys (results will be limited by the totalQueryLimit). The `objectType` and attributes are expected to have only valid utf8 strings and should not contain U+0000 (nil byte) and U+10FFFF (biggest and unallocated code point).

See related functions splitCompositeKey and createCompositeKey.

Call close() on the returned StateQueryIterator object when done.

The query is re-executed during validation phase to ensure result set has not changed since transaction endorsement (phantom reads detected).
Parameters:
Name Type Description
objectType string A string used as the prefix of the resulting key
attributes Array.<string> List of attribute values to concatenate into the partial composite key
Returns:
A promise that resolves with a StateQueryIterator, rejects if an error occurs
Type
Promise

getStateByPartialCompositeKeyWithPagination(objectType, attributes, pageSize, bookmark)

GetStateByPartialCompositeKeyWithPagination queries the state in the ledger based on a given partial composite key. This function returns an iterator which can be used to iterate over the composite keys whose prefix matches the given partial composite key. When an empty string is passed as a value to the bookmark argument, the returned iterator can be used to fetch the first `pageSize` composite keys whose prefix matches the given partial composite key. When the bookmark is a non-emptry string, the iterator can be used to fetch the first `pageSize` keys between the bookmark (inclusive) and the last matching composite key. Note that only the bookmark present in a prior page of query result (ResponseMetadata) can be used as a value to the bookmark argument. Otherwise, an empty string must be passed as bookmark. The `objectType` and attributes are expected to have only valid utf8 strings and should not contain U+0000 (nil byte) and U+10FFFF (biggest and unallocated code point). See related functions SplitCompositeKey and CreateCompositeKey. Call Close() on the returned StateQueryIteratorInterface object when done. This call is only supported in a read only transaction.
Parameters:
Name Type Description
objectType string
attributes Array.<string>
pageSize int
bookmark string
Returns:
Promise for a PaginationQueryResponse object
Type
Promise

<async> getStateByRange(startKey, endKey)

Returns a range iterator over a set of keys in the ledger. The iterator can be used to iterate over all keys between the startKey (inclusive) and endKey (exclusive). However, if the number of keys between startKey and endKey is greater than the totalQueryLimit (defined in core.yaml, which is the peer's configuration file), this iterator cannot be used to fetch all keys (results will be limited by the totalQueryLimit). The keys are returned by the iterator in lexical order. Note that startKey and endKey can be empty string, which implies unbounded range query on start or end.

Call close() on the returned StateQueryIterator object when done. The query is re-executed during validation phase to ensure result set has not changed since transaction endorsement (phantom reads detected).
Parameters:
Name Type Description
startKey string State variable key as the start of the key range (inclusive)
endKey string State variable key as the end of the key range (exclusive)
Returns:
Promise for a StateQueryIterator object
Type
Promise

getStateByRangeWithPagination(startKey, endKey, pageSize, bookmark)

getStateByRangeWithPagination returns a range iterator over a set of keys in the ledger. The iterator can be used to fetch keys between the startKey (inclusive) and endKey (exclusive). When an empty string is passed as a value to the bookmark argument, the returned iterator can be used to fetch the first `pageSize` keys between the startKey (inclusive) and endKey (exclusive). When the bookmark is a non-emptry string, the iterator can be used to fetch the first `pageSize` keys between the bookmark (inclusive) and endKey (exclusive). Note that only the bookmark present in a prior page of query results (ResponseMetadata) can be used as a value to the bookmark argument. Otherwise, an empty string must be passed as bookmark. The keys are returned by the iterator in lexical order. Note that startKey and endKey can be empty string, which implies unbounded range query on start or end. Call Close() on the returned StateQueryIteratorInterface object when done. This call is only supported in a read only transaction.
Parameters:
Name Type Description
startKey string
endKey string
pageSize int
bookmark string
Returns:
Promise for a PaginationQueryResponse object
Type
Promise

<async> getStateValidationParameter(key)

getStateValidationParameter retrieves the key-level endorsement policy for `key`. Note that this will introduce a read dependency on `key` in the transaction's readset.
Parameters:
Name Type Description
key string State variable key to set endorsement policy
Returns:
returns the endorsement policy for this key
Type
Buffer

getStringArgs()

Returns the arguments as array of strings from the chaincode invocation request
Returns:
Type
Array.<string>

getTransient()

Returns the transient map that can be used by the chaincode but not saved in the ledger, such as cryptographic information for encryption and decryption
Returns:
Type
Map.<string:Buffer>

getTxID()

Returns the transaction ID for the current chaincode invocation request. The transaction ID uniquely identifies the transaction within the scope of the channel.

getTxTimestamp()

Returns the timestamp when the transaction was created. This is taken from the transaction ChannelHeader, therefore it will indicate the client's timestamp, and will have the same value across all endorsers. Object returned: { seconds: [Long] { low: [int32], high: [int32], unsigned: [bool] }, nanos: [int32] }

<async> invokeChaincode(chaincodeName, args, channel)

Locally calls the specified chaincode invoke() using the same transaction context; that is, chaincode calling chaincode doesn't create a new transaction message.

If the called chaincode is on the same channel, it simply adds the called chaincode read set and write set to the calling transaction.

If the called chaincode is on a different channel, only the Response is returned to the calling chaincode; any PutState calls from the called chaincode will not have any effect on the ledger; that is, the called chaincode on a different channel will not have its read set and write set applied to the transaction. Only the calling chaincode's read set and write set will be applied to the transaction. Effectively the called chaincode on a different channel is a `Query`, which does not participate in state validation checks in subsequent commit phase.

If `channel` is empty, the caller's channel is assumed.
Parameters:
Name Type Description
chaincodeName string Name of the chaincode to call
args Array.<Array.<byte>> List of arguments to pass to the called chaincode
channel string Name of the channel where the target chaincode is active
Returns:
Promise for a Response object returned by the called chaincode
Type
Promise

<async> putPrivateData(collection, key, value)

putPrivateData puts the specified `key` and `value` into the transaction's private writeSet. Note that only hash of the private writeSet goes into the transaction proposal response (which is sent to the client who issued the transaction) and the actual private writeSet gets temporarily stored in a transient store. PutPrivateData doesn't effect the `collection` until the transaction is validated and successfully committed. Simple keys must not be an empty string and must not start with null character (0x00), in order to avoid range query collisions with composite keys, which internally get prefixed with 0x00 as composite key namespace.
Parameters:
Name Type Description
collection string The collection name
key string Private data variable key to set the value for
value string | Array.<byte> Private data variable value

<async> putState(key, value)

Writes the state variable key of value value to the state store. If the variable already exists, the value will be overwritten.
Parameters:
Name Type Description
key string State variable key to set the value for
value Array.<byte> | string State variable value
Returns:
Promise will be resolved when the peer has successfully handled the state update request or rejected if any errors
Type
Promise

setEvent(name, payload)

Allows the chaincode to propose an event on the transaction proposal. When the transaction is included in a block and the block is successfully committed to the ledger, the block event will be delivered to the current event listeners that have been registered with the peer's event producer. Note that the block event gets delivered to the listeners regardless of the status of the included transactions (can be either valid or invalid), so client applications are responsible for checking the validity code on each transaction. Consult each SDK's documentation for details.
Parameters:
Name Type Description
name string Name of the event
payload Array.<byte> A payload can be used to include data about the event

<async> setPrivateDataValidationParameter(collection, key, ep)

SetPrivateDataValidationParameter sets the key-level endorsement policy for the private data specified by `key`.
Parameters:
Name Type Description
collection string The collection name for this private data
key string Private data variable key to set endorsement policy
ep Buffer endorsement policy

<async> setStateValidationParameter(key, ep)

Sets the key-level endorsement policy for `key`
Parameters:
Name Type Description
key string State variable key to set endorsement policy
ep Buffer endorsement policy

splitCompositeKey(compositeKey)

Splits the specified key into attributes on which the composite key was formed. Composite keys found during range queries or partial composite key queries can therefore be split into their original composite parts, essentially recovering the values of the attributes.
Parameters:
Name Type Description
compositeKey string The composite key to split
Returns:
An object which has properties of 'objectType' (string) and 'attributes' (string[])
Type
Object