github.com/darrenli6/fabric-sdk-example@v0.0.0-20220109053535-94b13b56df8c/docs/source/chaincode4noah.rst (about) 1 Chaincode for Operators 2 ======================= 3 4 What is Chaincode? 5 ------------------ 6 7 Chaincode is a program, written in `Go <https://golang.org>`_, and eventually 8 in other programming languages such as Java, that implements a 9 prescribed interface. Chaincode runs in a secured Docker container isolated from 10 the endorsing peer process. Chaincode initializes and manages ledger state 11 through transactions submitted by applications. 12 13 A chaincode typically handles business logic agreed to by members of the 14 network, so it may be considered as a "smart contract". State created by a 15 chaincode is scoped exclusively to that chaincode and can't be accessed 16 directly by another chaincode. However, within the same network, given 17 the appropriate permission a chaincode may invoke another chaincode to 18 access its state. 19 20 In the following sections, we will explore chaincode through the eyes of a 21 blockchain network operator, Noah. For Noah's interests, we will focus 22 on chaincode lifecycle operations; the process of packaging, installing, 23 instantiating and upgrading the chaincode as a function of the chaincode's 24 operational lifecycle within a blockchain network. 25 26 Chaincode lifecycle 27 -------------------- 28 29 The Hyperledger Fabric API enables interaction with the various nodes 30 in a blockchain network - the peers, orderers and MSPs - and it also allows 31 one to package, install, instantiate and upgrade chaincode on the endorsing 32 peer nodes. The Hyperledger Fabric language-specific SDKs 33 abstract the specifics of the Hyperledger Fabric API to facilitate 34 application development, though it can be used to manage a chaincode's 35 lifecycle. Additionally, the Hyperledger Fabric API can be accessed 36 directly via the CLI, which we will use in this document. 37 38 We provide four commands to manage a chaincode's lifecycle: ``package``, 39 ``install``, ``instantiate``, and ``upgrade``. In a future release, we are 40 considering adding ``stop`` and ``start`` transactions to disable and re-enable 41 a chaincode without having to actually uninstall it. After a chaincode has 42 been successfully installed and instantiated, the chaincode is active (running) 43 and can process transactions via the ``invoke`` transaction. A chaincode may be 44 upgraded any time after it has been installed. 45 46 .. _Package: 47 48 Packaging 49 --------- 50 51 The chaincode package consists of 3 parts: 52 53 - the chaincode, as defined by ``ChaincodeDeploymentSpec`` or CDS. The CDS 54 defines the chaincode package in terms of the code and other properties 55 such as name and version, 56 - an optional instantiation policy which can be syntactically described 57 by the same policy used for endorsement and described in 58 :doc:`endorsement-policies`, and 59 - a set of signatures by the entities that “own” the chaincode. 60 61 The signatures serve the following purposes: 62 63 - to establish an ownership of the chaincode, 64 - to allow verification of the contents of the package, and 65 - to allow detection of package tampering. 66 67 The creator of the instantiation transaction of the chaincode on a channel is 68 validated against the instantiation policy of the chaincode. 69 70 Creating the package 71 ^^^^^^^^^^^^^^^^^^^^ 72 73 There are two approaches to packaging chaincode. One for when you want to have 74 multiple owners of a chaincode, and hence need to have the chaincode package 75 signed by multiple identities. This workflow requires that we initially create a 76 signed chaincode package (a ``SignedCDS``) which is subsequently passed serially 77 to each of the other owners for signing. 78 79 The simpler workflow is for when you are deploying a SignedCDS that has only the 80 signature of the identity of the node that is issuing the ``install`` 81 transaction. 82 83 We will address the more complex case first. However, you may skip ahead to the 84 :ref:`Install` section below if you do not need to worry about multiple owners 85 just yet. 86 87 To create a signed chaincode package, use the following command: 88 89 .. code:: bash 90 91 peer chaincode package -n mycc -p github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02 -v 0 -s -S -i "AND('OrgA.admin')" ccpack.out 92 93 The ``-s`` option creates a package that can be signed by multiple owners as 94 opposed to simply creating a raw CDS. When ``-s`` is specified, the ``-S`` 95 option must also be specified if other owners are going to need to sign. 96 Otherwise, the process will create a SignedCDS that includes only the 97 instantiation policy in addition to the CDS. 98 99 The ``-S`` option directs the process to sign the package 100 using the MSP identified by the value of the ``localMspid`` property in 101 ``core.yaml``. 102 103 The ``-S`` option is optional. However if a package is created without a 104 signature, it cannot be signed by any other owner using the 105 ``signpackage`` command. 106 107 The optional ``-i`` option allows one to specify an instantiation policy 108 for the chaincode. The instantiation policy has the same format as an 109 endorsement policy and specifies which identities can instantiate the 110 chaincode. In the example above, only the admin of OrgA is allowed to 111 instantiate the chaincode. If no policy is provided, the default policy 112 is used, which only allows the admin identity of the peer's MSP to 113 instantiate chaincode. 114 115 Package signing 116 ^^^^^^^^^^^^^^^ 117 118 A chaincode package that was signed at creation can be handed over to other 119 owners for inspection and signing. The workflow supports out-of-band signing 120 of chaincode package. 121 122 The 123 `ChaincodeDeploymentSpec <https://github.com/hyperledger/fabric/blob/master/protos/peer/chaincode.proto#L78>`_ 124 may be optionally be signed by the collective owners to create a 125 `SignedChaincodeDeploymentSpec <https://github.com/hyperledger/fabric/blob/master/protos/peer/signed_cc_dep_spec.proto#L26>`_ 126 (or SignedCDS). The SignedCDS contains 3 elements: 127 128 1. The CDS contains the source code, the name, and version of the chaincode. 129 2. An instantiation policy of the chaincode, expressed as endorsement policies. 130 3. The list of chaincode owners, defined by means of 131 `Endorsement <https://github.com/hyperledger/fabric/blob/master/protos/peer/proposal_response.proto#L111>`_. 132 133 .. note:: Note that this endorsement policy is determined out-of-band to 134 provide proper MSP principals when the chaincode is instantiated 135 on some channels. If the instantiation policy is not specified, 136 the default policy is any MSP administrator of the channel. 137 138 Each owner endorses the ChaincodeDeploymentSpec by combining it 139 with that owner's identity (e.g. certificate) and signing the combined 140 result. 141 142 A chaincode owner can sign a previously created signed package using the 143 following command: 144 145 .. code:: bash 146 147 peer chaincode signpackage ccpack.out signedccpack.out 148 149 Where ``ccpack.out`` and ``signedccpack.out`` are the input and output 150 packages, respectively. ``signedccpack.out`` contains an additional 151 signature over the package signed using the Local MSP. 152 153 .. _Install: 154 155 Installing chaincode 156 ^^^^^^^^^^^^^^^^^^^^ 157 158 The ``install`` transaction packages a chaincode's source code into a prescribed 159 format called a ``ChaincodeDeploymentSpec`` (or CDS) and installs it on a 160 peer node that will run that chaincode. 161 162 .. note:: You must install the chaincode on **each** endorsing peer node 163 of a channel that will run your chaincode. 164 165 When the ``install`` API is given simply a ``ChaincodeDeploymentSpec``, 166 it will default the instantiation policy and include an empty owner list. 167 168 .. note:: Chaincode should only be installed on endorsing peer nodes of the 169 owning members of the chaincode to protect the confidentiality of 170 the chaincode logic from other members on the network. Those members 171 without the chaincode, can't be the endorsers of the chaincode's 172 transactions; that is, they can't execute the chaincode. However, 173 they can still validate and commit the transactions to the ledger. 174 175 To install a chaincode, send a `SignedProposal 176 <https://github.com/hyperledger/fabric/blob/master/protos/peer/proposal.proto#L104>`_ 177 to the ``lifecycle system chaincode`` (LSCC) described in the `System Chaincode`_ 178 section. For example, to install the **sacc** sample chaincode described 179 in section :ref:`simple asset chaincode` 180 using the CLI, the command would look like the following: 181 182 .. code:: bash 183 184 peer chaincode install -n asset_mgmt -v 1.0 -p sacc 185 186 The CLI internally creates the SignedChaincodeDeploymentSpec for **sacc** and 187 sends it to the local peer, which calls the ``Install`` method on the LSCC. The 188 argument to the ``-p`` option specifies the path to the chaincode, which must be 189 located within the source tree of the user's ``GOPATH``, e.g. 190 ``$GOPATH/src/sacc``. See the `CLI`_ section for a complete description of 191 the command options. 192 193 Note that in order to install on a peer, the signature of the SignedProposal 194 must be from 1 of the peer's local MSP administrators. 195 196 .. _Instantiate: 197 198 Instantiate 199 ^^^^^^^^^^^ 200 201 The ``instantiate`` transaction invokes the ``lifecycle System Chaincode`` 202 (LSCC) to create and initialize a chaincode on a channel. This is a 203 chaincode-channel binding process: a chaincode may be bound to any number of 204 channels and operate on each channel individually and independently. In other 205 words, regardless of how many other channels on which a chaincode might be 206 installed and instantiated, state is kept isolated to the channel to which 207 a transaction is submitted. 208 209 The creator of an ``instantiate`` transaction must satisfy the instantiation 210 policy of the chaincode included in SignedCDS and must also be a writer on the 211 channel, which is configured as part of the channel creation. This is important 212 for the security of the channel to prevent rogue entities from deploying 213 chaincodes or tricking members to execute chaincodes on an unbound channel. 214 215 For example, recall that the default instantiation policy is any channel MSP 216 administrator, so the creator of a chaincode instantiate transaction must be a 217 member of the channel administrators. When the transaction proposal arrives at 218 the endorser, it verifies the creator's signature against the instantiation 219 policy. This is done again during the transaction validation before committing 220 it to the ledger. 221 222 The instantiate transaction also sets up the endorsement policy for that 223 chaincode on the channel. The endorsement policy describes the attestation 224 requirements for the transaction result to be accepted by members of the 225 channel. 226 227 For example, using the CLI to instantiate the **sacc** chaincode and initialize 228 the state with ``john`` and ``0``, the command would look like the following: 229 230 .. code:: bash 231 232 peer chaincode instantiate -n sacc -v 1.0 -c '{"Args":["john","0"]}' -P "OR ('Org1.member','Org2.member')" 233 234 .. note:: Note the endorsement policy (CLI uses polish notation), which requires an 235 endorsement from either member of Org1 or Org2 for all transactions to 236 **sacc**. That is, either Org1 or Org2 must sign the 237 result of executing the `Invoke` on **sacc** for the transactions to 238 be valid. 239 240 After being successfully instantiated, the chaincode enters the active state on 241 the channel and is ready to process any transaction proposals of type 242 `ENDORSER_TRANSACTION <https://github.com/hyperledger/fabric/blob/master/protos/common/common.proto#L42>`_. 243 The transactions are processed concurrently as they arrive at the endorsing 244 peer. 245 246 .. _Upgrade: 247 248 Upgrade 249 ^^^^^^^ 250 251 A chaincode may be upgraded any time by changing its version, which is 252 part of the SignedCDS. Other parts, such as owners and instantiation policy 253 are optional. However, the chaincode name must be the same; otherwise it 254 would be considered as a totally different chaincode. 255 256 Prior to upgrade, the new version of the chaincode must be installed on 257 the required endorsers. Upgrade is a transaction similar to the instantiate 258 transaction, which binds the new version of the chaincode to the channel. Other 259 channels bound to the old version of the chaincode still run with the old 260 version. In other words, the ``upgrade`` transaction only affects one channel 261 at a time, the channel to which the transaction is submitted. 262 263 .. note:: Note that since multiple versions of a chaincode may be active 264 simultaneously, the upgrade process doesn't automatically remove the 265 old versions, so user must manage this for the time being. 266 267 There's one subtle difference with the ``instantiate`` transaction: the 268 ``upgrade`` transaction is checked against the current chaincode instantiation 269 policy, not the new policy (if specified). This is to ensure that only existing 270 members specified in the current instantiation policy may upgrade the chaincode. 271 272 .. note:: Note that during upgrade, the chaincode ``Init`` function is called to 273 perform any data related updates or re-initialize it, so care must be 274 taken to avoid resetting states when upgrading chaincode. 275 276 .. _Stop-and-Start: 277 278 Stop and Start 279 ^^^^^^^^^^^^^^ 280 Note that ``stop`` and ``start`` lifecycle transactions have not yet been 281 implemented. However, you may stop a chaincode manually by removing the 282 chaincode container and the SignedCDS package from each of the endorsers. This 283 is done by deleting the chaincode's container on each of the hosts or virtual 284 machines on which the endorsing peer nodes are running, and then deleting 285 the SignedCDS from each of the endorsing peer nodes: 286 287 .. note:: TODO - in order to delete the CDS from the peer node, you would need 288 to enter the peer node's container, first. We really need to provide 289 a utility script that can do this. 290 291 .. code:: bash 292 293 docker rm -f <container id> 294 rm /var/hyperledger/production/chaincodes/<ccname>:<ccversion> 295 296 Stop would be useful in the workflow for doing upgrade in controlled manner, 297 where a chaincode can be stopped on a channel on all peers before issuing an 298 upgrade. 299 300 .. _CLI: 301 302 CLI 303 ^^^ 304 305 .. note:: We are assessing the need to distribute platform-specific binaries 306 for the Hyperledger Fabric ``peer`` binary. For the time being, you 307 can simply invoke the commands from within a running docker container. 308 309 To view the currently available CLI commands, execute the following command from 310 within a running ``fabric-peer`` Docker container: 311 312 .. code:: bash 313 314 docker run -it hyperledger/fabric-peer bash 315 # peer chaincode --help 316 317 Which shows output similar to the example below: 318 319 .. code:: bash 320 321 Usage: 322 peer chaincode [command] 323 324 Available Commands: 325 install Package the specified chaincode into a deployment spec and save it on the peer's path. 326 instantiate Deploy the specified chaincode to the network. 327 invoke Invoke the specified chaincode. 328 package Package the specified chaincode into a deployment spec. 329 query Query using the specified chaincode. 330 signpackage Sign the specified chaincode package 331 upgrade Upgrade chaincode. 332 333 Flags: 334 --cafile string Path to file containing PEM-encoded trusted certificate(s) for the ordering endpoint 335 -C, --chainID string The chain on which this command should be executed (default "testchainid") 336 -c, --ctor string Constructor message for the chaincode in JSON format (default "{}") 337 -E, --escc string The name of the endorsement system chaincode to be used for this chaincode 338 -l, --lang string Language the chaincode is written in (default "golang") 339 -n, --name string Name of the chaincode 340 -o, --orderer string Ordering service endpoint 341 -p, --path string Path to chaincode 342 -P, --policy string The endorsement policy associated to this chaincode 343 -t, --tid string Name of a custom ID generation algorithm (hashing and decoding) e.g. sha256base64 344 --tls Use TLS when communicating with the orderer endpoint 345 -u, --username string Username for chaincode operations when security is enabled 346 -v, --version string Version of the chaincode specified in install/instantiate/upgrade commands 347 -V, --vscc string The name of the verification system chaincode to be used for this chaincode 348 349 Global Flags: 350 --logging-level string Default logging level and overrides, see core.yaml for full syntax 351 --test.coverprofile string Done (default "coverage.cov") 352 353 Use "peer chaincode [command] --help" for more information about a command. 354 355 To facilitate its use in scripted applications, the ``peer`` command always 356 produces a non-zero return code in the event of command failure. 357 358 Example of chaincode commands: 359 360 .. code:: bash 361 362 peer chaincode install -n mycc -v 0 -p path/to/my/chaincode/v0 363 peer chaincode instantiate -n mycc -v 0 -c '{"Args":["a", "b", "c"]}' -C mychannel 364 peer chaincode install -n mycc -v 1 -p path/to/my/chaincode/v1 365 peer chaincode upgrade -n mycc -v 1 -c '{"Args":["d", "e", "f"]}' -C mychannel 366 peer chaincode query -C mychannel -n mycc -c '{"Args":["query","e"]}' 367 peer chaincode invoke -o orderer.example.com:7050 --tls $CORE_PEER_TLS_ENABLED --cafile $ORDERER_CA -C mychannel -n mycc -c '{"Args":["invoke","a","b","10"]}' 368 369 .. _System Chaincode: 370 371 System chaincode 372 ---------------- 373 System chaincode has the same programming model except that it runs within the 374 peer process rather than in an isolated container like normal chaincode. 375 Therefore, system chaincode is built into the peer executable and doesn't follow 376 the same lifecycle described above. In particular, **install**, **instantiate** 377 and **upgrade** do not apply to system chaincodes. 378 379 The purpose of system chaincode is to shortcut gRPC communication cost between 380 peer and chaincode, and tradeoff the flexibility in management. For example, a 381 system chaincode can only be upgraded with the peer binary. It must also 382 register with a `fixed set of parameters 383 <https://github.com/hyperledger/fabric/blob/master/core/scc/importsysccs.go>`_ 384 compiled in and doesn't have endorsement policies or endorsement policy 385 functionality. 386 387 System chaincode is used in Hyperledger Fabric to implement a number of 388 system behaviors so that they can be replaced or modified as appropriate 389 by a system integrator. 390 391 The current list of system chaincodes: 392 393 1. `LSCC <https://github.com/hyperledger/fabric/tree/master/core/scc/lscc>`_ 394 Lifecycle system chaincode handles lifecycle requests described above. 395 2. `CSCC <https://github.com/hyperledger/fabric/tree/master/core/scc/cscc>`_ 396 Configuration system chaincode handles channel configuration on the peer side. 397 3. `QSCC <https://github.com/hyperledger/fabric/tree/master/core/scc/qscc>`_ 398 Query system chaincode provides ledger query APIs such as getting blocks and 399 transactions. 400 4. `ESCC <https://github.com/hyperledger/fabric/tree/master/core/scc/escc>`_ 401 Endorsement system chaincode handles endorsement by signing the transaction 402 proposal response. 403 5. `VSCC <https://github.com/hyperledger/fabric/tree/master/core/scc/vscc>`_ 404 Validation system chaincode handles the transaction validation, including 405 checking endorsement policy and multiversioning concurrency control. 406 407 Care must be taken when modifying or replacing these system chaincodes, 408 especially LSCC, ESCC and VSCC since they are in the main transaction execution 409 path. It is worth noting that as VSCC validates a block before committing it to 410 the ledger, it is important that all peers in the channel compute the same 411 validation to avoid ledger divergence (non-determinism). So special care is 412 needed if VSCC is modified or replaced. 413 414 .. Licensed under Creative Commons Attribution 4.0 International License 415 https://creativecommons.org/licenses/by/4.0/