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()

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> 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

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

<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 (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
query string Query string native to the underlying state database
Returns:
Promise for a StateQueryIterator 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

<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. 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

<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). 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

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.

<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> 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> 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

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