github.com/kaituanwang/hyperledger@v2.0.1+incompatible/docs/source/build_network.rst (about)

     1  Building Your First Network
     2  ===========================
     3  
     4  .. note:: These instructions have been verified to work against the
     5            latest stable Docker images and the pre-compiled
     6            setup utilities within the supplied tar file. If you run
     7            these commands with images or tools from the current master
     8            branch, it is possible that you will see configuration and panic
     9            errors.
    10  
    11  The build your first network (BYFN) scenario provisions a sample Hyperledger
    12  Fabric network consisting of two organizations, each maintaining two peer
    13  nodes. It also will deploy a Raft ordering service by default.
    14  
    15  Install prerequisites
    16  ---------------------
    17  
    18  Before we begin, if you haven't already done so, you may wish to check that
    19  you have all the :doc:`prereqs` installed on the platform(s) on which you'll be
    20  developing blockchain applications and/or operating Hyperledger Fabric.
    21  
    22  You will also need to :doc:`install`. You will notice that there are a number of
    23  samples included in the ``fabric-samples`` repository. We will be using the
    24  ``first-network`` sample. Let's open that sub-directory now.
    25  
    26  .. code:: bash
    27  
    28    cd fabric-samples/first-network
    29  
    30  .. note:: The supplied commands in this documentation **MUST** be run from your
    31            ``first-network`` sub-directory of the ``fabric-samples`` repository
    32            clone.  If you elect to run the commands from a different location,
    33            the various provided scripts will be unable to find the binaries.
    34  
    35  Want to run it now?
    36  -------------------
    37  
    38  We provide a fully annotated script --- ``byfn.sh`` --- that leverages these Docker
    39  images to quickly bootstrap a Hyperledger Fabric network that by default is
    40  comprised of four peers representing two different organizations, and a Raft ordering
    41  service. It will also launch a container to run a scripted execution that will join
    42  peers to a channel, deploy a chaincode and drive execution of transactions
    43  against the deployed chaincode.
    44  
    45  Here's the help text for the ``byfn.sh`` script:
    46  
    47  .. code:: bash
    48  
    49    Usage:
    50    byfn.sh <mode> [-c <channel name>] [-t <timeout>] [-d <delay>] [-f <docker-compose-file>] [-s <dbtype>] [-l <language>] [-o <consensus-type>] [-i <imagetag>] [-v]"
    51      <mode> - one of 'up', 'down', 'restart', 'generate' or 'upgrade'"
    52        - 'up' - bring up the network with docker-compose up"
    53        - 'down' - clear the network with docker-compose down"
    54        - 'restart' - restart the network"
    55        - 'generate' - generate required certificates and genesis block"
    56        - 'upgrade'  - upgrade the network from version 1.3.x to 1.4.0"
    57      -c <channel name> - channel name to use (defaults to \"mychannel\")"
    58      -t <timeout> - CLI timeout duration in seconds (defaults to 10)"
    59      -d <delay> - delay duration in seconds (defaults to 3)"
    60      -f <docker-compose-file> - specify which docker-compose file use (defaults to docker-compose-cli.yaml)"
    61      -s <dbtype> - the database backend to use: goleveldb (default) or couchdb"
    62      -l <language> - the chaincode language: golang (default), javascript, or java"
    63      -a - launch certificate authorities (no certificate authorities are launched by default)
    64      -n - do not deploy chaincode (abstore chaincode is deployed by default)
    65      -i <imagetag> - the tag to be used to launch the network (defaults to \"latest\")"
    66      -v - verbose mode"
    67    byfn.sh -h (print this message)"
    68  
    69    Typically, one would first generate the required certificates and
    70    genesis block, then bring up the network. e.g.:"
    71  
    72      byfn.sh generate -c mychannel"
    73      byfn.sh up -c mychannel -s couchdb"
    74      byfn.sh up -c mychannel -s couchdb -i 1.4.0"
    75      byfn.sh up -l javascript"
    76      byfn.sh down -c mychannel"
    77      byfn.sh upgrade -c mychannel"
    78  
    79    Taking all defaults:"
    80    	byfn.sh generate"
    81    	byfn.sh up"
    82    	byfn.sh down"
    83  
    84  If you choose not to supply a flag, the script will use default values.
    85  
    86  Generate Network Artifacts
    87  ^^^^^^^^^^^^^^^^^^^^^^^^^^
    88  
    89  Ready to give it a go? Okay then! Execute the following command:
    90  
    91  .. code:: bash
    92  
    93    ./byfn.sh generate
    94  
    95  You will see a brief description as to what will occur, along with a yes/no command line
    96  prompt. Respond with a ``y`` or hit the return key to execute the described action.
    97  
    98  .. code:: bash
    99  
   100    Generating certs and genesis block for channel 'mychannel' with CLI timeout of '10' seconds and CLI delay of '3' seconds
   101    Continue? [Y/n] y
   102    proceeding ...
   103    /Users/xxx/dev/fabric-samples/bin/cryptogen
   104  
   105    ##########################################################
   106    ##### Generate certificates using cryptogen tool #########
   107    ##########################################################
   108    org1.example.com
   109    2017-06-12 21:01:37.334 EDT [bccsp] GetDefault -> WARN 001 Before using BCCSP, please call InitFactories(). Falling back to bootBCCSP.
   110    ...
   111  
   112    /Users/xxx/dev/fabric-samples/bin/configtxgen
   113    ##########################################################
   114    #########  Generating Orderer Genesis block ##############
   115    ##########################################################
   116    2017-06-12 21:01:37.558 EDT [common/configtx/tool] main -> INFO 001 Loading configuration
   117    2017-06-12 21:01:37.562 EDT [msp] getMspConfig -> INFO 002 intermediate certs folder not found at [/Users/xxx/dev/byfn/crypto-config/ordererOrganizations/example.com/msp/intermediatecerts]. Skipping.: [stat /Users/xxx/dev/byfn/crypto-config/ordererOrganizations/example.com/msp/intermediatecerts: no such file or directory]
   118    ...
   119    2017-06-12 21:01:37.588 EDT [common/configtx/tool] doOutputBlock -> INFO 00b Generating genesis block
   120    2017-06-12 21:01:37.590 EDT [common/configtx/tool] doOutputBlock -> INFO 00c Writing genesis block
   121  
   122    #################################################################
   123    ### Generating channel configuration transaction 'channel.tx' ###
   124    #################################################################
   125    2017-06-12 21:01:37.634 EDT [common/configtx/tool] main -> INFO 001 Loading configuration
   126    2017-06-12 21:01:37.644 EDT [common/configtx/tool] doOutputChannelCreateTx -> INFO 002 Generating new channel configtx
   127    2017-06-12 21:01:37.645 EDT [common/configtx/tool] doOutputChannelCreateTx -> INFO 003 Writing new channel tx
   128  
   129    #################################################################
   130    #######    Generating anchor peer update for Org1MSP   ##########
   131    #################################################################
   132    2017-06-12 21:01:37.674 EDT [common/configtx/tool] main -> INFO 001 Loading configuration
   133    2017-06-12 21:01:37.678 EDT [common/configtx/tool] doOutputAnchorPeersUpdate -> INFO 002 Generating anchor peer update
   134    2017-06-12 21:01:37.679 EDT [common/configtx/tool] doOutputAnchorPeersUpdate -> INFO 003 Writing anchor peer update
   135  
   136    #################################################################
   137    #######    Generating anchor peer update for Org2MSP   ##########
   138    #################################################################
   139    2017-06-12 21:01:37.700 EDT [common/configtx/tool] main -> INFO 001 Loading configuration
   140    2017-06-12 21:01:37.704 EDT [common/configtx/tool] doOutputAnchorPeersUpdate -> INFO 002 Generating anchor peer update
   141    2017-06-12 21:01:37.704 EDT [common/configtx/tool] doOutputAnchorPeersUpdate -> INFO 003 Writing anchor peer update
   142  
   143  This first step generates all of the certificates and keys for our various
   144  network entities, the ``genesis block`` used to bootstrap the ordering service,
   145  and a collection of configuration transactions required to configure a
   146  :ref:`Channel`.
   147  
   148  Bring Up the Network
   149  ^^^^^^^^^^^^^^^^^^^^
   150  
   151  Next, you can bring the network up with one of the following commands:
   152  
   153  .. code:: bash
   154  
   155    ./byfn.sh up
   156  
   157  The above command will compile Golang chaincode images and spin up the corresponding
   158  containers. Go is the default chaincode language, however there is also support
   159  for `Node.js <https://hyperledger.github.io/fabric-chaincode-node/>`_ and `Java <https://hyperledger.github.io/fabric-chaincode-java/>`_
   160  chaincode. If you'd like to run through this tutorial with node chaincode, pass
   161  the following command instead:
   162  
   163  .. code:: bash
   164  
   165    # we use the -l flag to specify the chaincode language
   166    # forgoing the -l flag will default to Golang
   167  
   168    ./byfn.sh up -l javascript
   169  
   170  .. note:: For more information on the Node.js shim, please refer to its
   171            `documentation <https://hyperledger.github.io/fabric-chaincode-node/{BRANCH}/api/fabric-shim.ChaincodeInterface.html>`_.
   172  
   173  .. note:: For more information on the Java shim, please refer to its
   174            `documentation <https://hyperledger.github.io/fabric-chaincode-java/{BRANCH}/api/org/hyperledger/fabric/shim/Chaincode.html>`_.
   175  
   176  Тo make the sample run with Java chaincode, you have to specify ``-l java`` as follows:
   177  
   178  .. code:: bash
   179  
   180    ./byfn.sh up -l java
   181  
   182  .. note:: Do not run both of these commands. Only one language can be tried unless
   183            you bring down and recreate the network between.
   184  
   185  You will be prompted as to whether you wish to continue or abort.
   186  Respond with a ``y`` or hit the return key:
   187  
   188  .. code:: bash
   189  
   190    Starting for channel 'mychannel' with CLI timeout of '10' seconds and CLI delay of '3' seconds
   191    Continue? [Y/n]
   192    proceeding ...
   193    Creating network "net_byfn" with the default driver
   194    Creating peer0.org1.example.com
   195    Creating peer1.org1.example.com
   196    Creating peer0.org2.example.com
   197    Creating orderer.example.com
   198    Creating peer1.org2.example.com
   199    Creating cli
   200  
   201  
   202     ____    _____      _      ____    _____
   203    / ___|  |_   _|    / \    |  _ \  |_   _|
   204    \___ \    | |     / _ \   | |_) |   | |
   205     ___) |   | |    / ___ \  |  _ <    | |
   206    |____/    |_|   /_/   \_\ |_| \_\   |_|
   207  
   208    Channel name : mychannel
   209    Creating channel...
   210  
   211  The logs will continue from there. This will launch all of the containers, and
   212  then drive a complete end-to-end application scenario. Upon successful
   213  completion, it should report the following in your terminal window:
   214  
   215  .. code:: bash
   216  
   217      Query Result: 90
   218      2017-05-16 17:08:15.158 UTC [main] main -> INFO 008 Exiting.....
   219      ===================== Query successful on peer1.org2 on channel 'mychannel' =====================
   220  
   221      ===================== All GOOD, BYFN execution completed =====================
   222  
   223  
   224       _____   _   _   ____
   225      | ____| | \ | | |  _ \
   226      |  _|   |  \| | | | | |
   227      | |___  | |\  | | |_| |
   228      |_____| |_| \_| |____/
   229  
   230  You can scroll through these logs to see the various transactions. If you don't
   231  get this result, then jump down to the :ref:`Troubleshoot` section and let's see
   232  whether we can help you discover what went wrong.
   233  
   234  Bring Down the Network
   235  ^^^^^^^^^^^^^^^^^^^^^^
   236  
   237  Finally, let's bring it all down so we can explore the network setup one step
   238  at a time. The following will kill your containers, remove the crypto material
   239  and four artifacts, and delete the chaincode images from your Docker Registry:
   240  
   241  .. code:: bash
   242  
   243    ./byfn.sh down
   244  
   245  Once again, you will be prompted to continue, respond with a ``y`` or hit the return key:
   246  
   247  .. code:: bash
   248  
   249    Stopping with channel 'mychannel' and CLI timeout of '10'
   250    Continue? [Y/n] y
   251    proceeding ...
   252    WARNING: The CHANNEL_NAME variable is not set. Defaulting to a blank string.
   253    WARNING: The TIMEOUT variable is not set. Defaulting to a blank string.
   254    Removing network net_byfn
   255    468aaa6201ed
   256    ...
   257    Untagged: dev-peer1.org2.example.com-mycc-1.0:latest
   258    Deleted: sha256:ed3230614e64e1c83e510c0c282e982d2b06d148b1c498bbdcc429e2b2531e91
   259    ...
   260  
   261  If you'd like to learn more about the underlying tooling and bootstrap mechanics,
   262  continue reading.  In these next sections we'll walk through the various steps
   263  and requirements to build a fully-functional Hyperledger Fabric network.
   264  
   265  .. note:: The manual steps outlined below assume that the ``FABRIC_LOGGING_SPEC`` in
   266            the ``cli`` container is set to ``DEBUG``. You can set this by modifying
   267            the ``docker-compose-cli.yaml`` file in the ``first-network`` directory.
   268            e.g.
   269  
   270            .. code::
   271  
   272              cli:
   273                container_name: cli
   274                image: hyperledger/fabric-tools:$IMAGE_TAG
   275                tty: true
   276                stdin_open: true
   277                environment:
   278                  - GOPATH=/opt/gopath
   279                  - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
   280                  - FABRIC_LOGGING_SPEC=DEBUG
   281                  #- FABRIC_LOGGING_SPEC=INFO
   282  
   283  Crypto Generator
   284  ----------------
   285  
   286  We will use the ``cryptogen`` tool to generate the cryptographic material
   287  (x509 certs and signing keys) for our various network entities.  These certificates are
   288  representative of identities, and they allow for sign/verify authentication to
   289  take place as our entities communicate and transact.
   290  
   291  How does it work?
   292  ^^^^^^^^^^^^^^^^^
   293  
   294  Cryptogen consumes a file --- ``crypto-config.yaml`` --- that contains the network
   295  topology and allows us to generate a set of certificates and keys for both the
   296  Organizations and the components that belong to those Organizations.  Each
   297  Organization is provisioned a unique root certificate (``ca-cert``) that binds
   298  specific components (peers and orderers) to that Org.  By assigning each
   299  Organization a unique CA certificate, we are mimicking a typical network where
   300  a participating :ref:`Member` would use its own Certificate Authority.
   301  Transactions and communications within Hyperledger Fabric are signed by an
   302  entity's private key (``keystore``), and then verified by means of a public
   303  key (``signcerts``).
   304  
   305  You will notice a ``count`` variable within this file. We use this to specify
   306  the number of peers per Organization; in our case there are two peers per Org.
   307  We won't delve into the minutiae of `x.509 certificates and public key
   308  infrastructure <https://en.wikipedia.org/wiki/Public_key_infrastructure>`_
   309  right now. If you're interested, you can peruse these topics on your own time.
   310  
   311  After we run the ``cryptogen`` tool, the generated certificates and keys will be
   312  saved to a folder titled ``crypto-config``. Note that the ``crypto-config.yaml``
   313  file lists five orderers as being tied to the orderer organization. While the
   314  ``cryptogen`` tool will create certificates for all five of these orderers. These orderers
   315  will be used in a etcdraft ordering service implementation and be used to create the
   316  system channel and ``mychannel``.
   317  
   318  Configuration Transaction Generator
   319  -----------------------------------
   320  
   321  The ``configtxgen`` tool is used to create four configuration artifacts:
   322  
   323    * orderer ``genesis block``,
   324    * channel ``configuration transaction``,
   325    * and two ``anchor peer transactions`` - one for each Peer Org.
   326  
   327  Please see :doc:`commands/configtxgen` for a complete description of this tool's functionality.
   328  
   329  The orderer block is the :ref:`Genesis-Block` for the ordering service, and the
   330  channel configuration transaction file is broadcast to the orderer at :ref:`Channel` creation
   331  time.  The anchor peer transactions, as the name might suggest, specify each
   332  Org's :ref:`Anchor-Peer` on this channel.
   333  
   334  How does it work?
   335  ^^^^^^^^^^^^^^^^^
   336  
   337  Configtxgen consumes a file - ``configtx.yaml`` - that contains the definitions
   338  for the sample network. There are three members - one Orderer Org (``OrdererOrg``)
   339  and two Peer Orgs (``Org1`` & ``Org2``) each managing and maintaining two peer nodes.
   340  This file also specifies a consortium - ``SampleConsortium`` - consisting of our
   341  two Peer Orgs.  Pay specific attention to the "Profiles" section at the bottom of
   342  this file. You will notice that we have several unique profiles. A few are worth
   343  noting:
   344  
   345  * ``SampleMultiNodeEtcdRaft``: generates the genesis block for a Raft ordering
   346    service. Only used if you issue the ``-o`` flag and specify ``etcdraft``.
   347  
   348  * ``TwoOrgsChannel``: generates the genesis block for our channel, ``mychannel``.
   349  
   350  These headers are important, as we will pass them in as arguments when we create
   351  our artifacts.
   352  
   353  .. note:: Notice that our ``SampleConsortium`` is defined in
   354            the system-level profile and then referenced by
   355            our channel-level profile.  Channels exist within
   356            the purview of a consortium, and all consortia
   357            must be defined in the scope of the network at
   358            large.
   359  
   360  This file also contains two additional specifications that are worth
   361  noting. Firstly, we specify the anchor peers for each Peer Org
   362  (``peer0.org1.example.com`` & ``peer0.org2.example.com``).  Secondly, we point to
   363  the location of the MSP directory for each member, in turn allowing us to store the
   364  root certificates for each Org in the orderer genesis block.  This is a critical
   365  concept. Now any network entity communicating with the ordering service can have
   366  its digital signature verified.
   367  
   368  Run the tools
   369  -------------
   370  
   371  You can manually generate the certificates/keys and the various configuration
   372  artifacts using the ``configtxgen`` and ``cryptogen`` commands. Alternately,
   373  you could try to adapt the byfn.sh script to accomplish your objectives.
   374  
   375  Manually generate the artifacts
   376  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   377  
   378  You can refer to the ``generateCerts`` function in the byfn.sh script for the
   379  commands necessary to generate the certificates that will be used for your
   380  network configuration as defined in the ``crypto-config.yaml`` file. However,
   381  for the sake of convenience, we will also provide a reference here.
   382  
   383  First let's run the ``cryptogen`` tool.  Our binary is in the ``bin``
   384  directory, so we need to provide the relative path to where the tool resides.
   385  
   386  .. code:: bash
   387  
   388      ../bin/cryptogen generate --config=./crypto-config.yaml
   389  
   390  You should see the following in your terminal:
   391  
   392  .. code:: bash
   393  
   394    org1.example.com
   395    org2.example.com
   396  
   397  The certs and keys (i.e. the MSP material) will be output into a directory - ``crypto-config`` -
   398  at the root of the ``first-network`` directory.
   399  
   400  Next, we need to tell the ``configtxgen`` tool where to look for the
   401  ``configtx.yaml`` file that it needs to ingest.  We will tell it look in our
   402  present working directory:
   403  
   404  .. code:: bash
   405  
   406      export FABRIC_CFG_PATH=$PWD
   407  
   408  Then, we'll invoke the ``configtxgen`` tool to create the orderer genesis block:
   409  
   410  .. code:: bash
   411  
   412    ../bin/configtxgen -profile SampleMultiNodeEtcdRaft -channelID byfn-sys-channel -outputBlock ./channel-artifacts/genesis.block
   413  
   414  .. note:: The orderer genesis block and the subsequent artifacts we are about to create
   415            will be output into the ``channel-artifacts`` directory at the root of the
   416            ``first-network`` directory. The `channelID` in the above command is the
   417            name of the system channel.
   418  
   419  .. _createchanneltx:
   420  
   421  Create a Channel Configuration Transaction
   422  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   423  
   424  Next, we need to create the channel transaction artifact. Be sure to replace ``$CHANNEL_NAME`` or
   425  set ``CHANNEL_NAME`` as an environment variable that can be used throughout these instructions:
   426  
   427  .. code:: bash
   428  
   429      # The channel.tx artifact contains the definitions for our sample channel
   430  
   431      export CHANNEL_NAME=mychannel  && ../bin/configtxgen -profile TwoOrgsChannel -outputCreateChannelTx ./channel-artifacts/channel.tx -channelID $CHANNEL_NAME
   432  
   433  Note that the ``TwoOrgsChannel`` profile will use the ordering service
   434  configuration you specified when creating the genesis block for the network.
   435  
   436  You should see an output similar to the following in your terminal:
   437  
   438  .. code:: bash
   439  
   440    2017-10-26 19:24:05.324 EDT [common/tools/configtxgen] main -> INFO 001 Loading configuration
   441    2017-10-26 19:24:05.329 EDT [common/tools/configtxgen] doOutputChannelCreateTx -> INFO 002 Generating new channel configtx
   442    2017-10-26 19:24:05.329 EDT [common/tools/configtxgen] doOutputChannelCreateTx -> INFO 003 Writing new channel tx
   443  
   444  Next, we will define the anchor peer for Org1 on the channel that we are
   445  constructing. Again, be sure to replace ``$CHANNEL_NAME`` or set the environment
   446  variable for the following commands.  The terminal output will mimic that of the
   447  channel transaction artifact:
   448  
   449  .. code:: bash
   450  
   451      ../bin/configtxgen -profile TwoOrgsChannel -outputAnchorPeersUpdate ./channel-artifacts/Org1MSPanchors.tx -channelID $CHANNEL_NAME -asOrg Org1MSP
   452  
   453  Now, we will define the anchor peer for Org2 on the same channel:
   454  
   455  .. code:: bash
   456  
   457      ../bin/configtxgen -profile TwoOrgsChannel -outputAnchorPeersUpdate ./channel-artifacts/Org2MSPanchors.tx -channelID $CHANNEL_NAME -asOrg Org2MSP
   458  
   459  Start the network
   460  -----------------
   461  
   462  .. note:: If you ran the ``byfn.sh`` example above previously, be sure that you
   463            have brought down the test network before you proceed (see
   464            `Bring Down the Network`_).
   465  
   466  We will leverage a script to spin up our network. The
   467  docker-compose file references the images that we have previously downloaded,
   468  and bootstraps the orderer with our previously generated ``genesis.block``.
   469  
   470  We want to go through the commands manually in order to expose the
   471  syntax and functionality of each call.
   472  
   473  First let's start our network:
   474  
   475  .. code:: bash
   476  
   477      docker-compose -f docker-compose-cli.yaml -f docker-compose-etcdraft2.yaml up -d
   478  
   479  If you want to see the realtime logs for your network, then do not supply the ``-d`` flag.
   480  If you let the logs stream, then you will need to open a second terminal to execute the CLI calls.
   481  
   482  .. _peerenvvars:
   483  
   484  Create & Join Channel
   485  ^^^^^^^^^^^^^^^^^^^^^
   486  
   487  Recall that we created the channel configuration transaction using the
   488  ``configtxgen`` tool in the :ref:`createchanneltx` section, above. You can
   489  repeat that process to create additional channel configuration transactions,
   490  using the same or different profiles in the ``configtx.yaml`` that you pass
   491  to the ``configtxgen`` tool. Then you can repeat the process defined in this
   492  section to establish those other channels in your network.
   493  
   494  We will enter the CLI container using the ``docker exec`` command:
   495  
   496  .. code:: bash
   497  
   498          docker exec -it cli bash
   499  
   500  If successful you should see the following:
   501  
   502  .. code:: bash
   503  
   504          bash-5.0#
   505  
   506  For the following CLI commands against ``peer0.org1.example.com`` to work, we need
   507  to preface our commands with the four environment variables given below.  These
   508  variables for ``peer0.org1.example.com`` are baked into the CLI container,
   509  therefore we can operate without passing them. **HOWEVER**, if you want to send
   510  calls to other peers or the orderer, keep the CLI container defaults targeting
   511  ``peer0.org1.example.com``, but override the environment variables as seen in the
   512  example below when you make any CLI calls:
   513  
   514  .. code:: bash
   515  
   516      # Environment variables for PEER0
   517  
   518      CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
   519      CORE_PEER_ADDRESS=peer0.org1.example.com:7051
   520      CORE_PEER_LOCALMSPID="Org1MSP"
   521      CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
   522  
   523  Next, we are going to pass in the generated channel configuration transaction
   524  artifact that we created in the :ref:`createchanneltx` section (we called
   525  it ``channel.tx``) to the orderer as part of the create channel request.
   526  
   527  We specify our channel name with the ``-c`` flag and our channel configuration
   528  transaction with the ``-f`` flag. In this case it is ``channel.tx``, however
   529  you can mount your own configuration transaction with a different name.  Once again
   530  we will set the ``CHANNEL_NAME`` environment variable within our CLI container so that
   531  we don't have to explicitly pass this argument. Channel names must be all lower
   532  case, less than 250 characters long and match the regular expression
   533  ``[a-z][a-z0-9.-]*``.
   534  
   535  .. code:: bash
   536  
   537          export CHANNEL_NAME=mychannel
   538  
   539          # the channel.tx file is mounted in the channel-artifacts directory within your CLI container
   540          # as a result, we pass the full path for the file
   541          # we also pass the path for the orderer ca-cert in order to verify the TLS handshake
   542          # be sure to export or replace the $CHANNEL_NAME variable appropriately
   543  
   544          peer channel create -o orderer.example.com:7050 -c $CHANNEL_NAME -f ./channel-artifacts/channel.tx --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
   545  
   546  .. note:: Notice the ``--cafile`` that we pass as part of this command.  It is
   547            the local path to the orderer's root cert, allowing us to verify the
   548            TLS handshake.
   549  
   550  This command returns a genesis block - ``<CHANNEL_NAME.block>`` - which we will use to join the channel.
   551  It contains the configuration information specified in ``channel.tx``  If you have not
   552  made any modifications to the default channel name, then the command will return you a
   553  proto titled ``mychannel.block``.
   554  
   555  .. note:: You will remain in the CLI container for the remainder of
   556            these manual commands. You must also remember to preface all commands
   557            with the corresponding environment variables when targeting a peer other than
   558            ``peer0.org1.example.com``.
   559  
   560  Now let's join ``peer0.org1.example.com`` to the channel.
   561  
   562  .. code:: bash
   563  
   564          # By default, this joins ``peer0.org1.example.com`` only
   565          # the <CHANNEL_NAME.block> was returned by the previous command
   566          # if you have not modified the channel name, you will join with mychannel.block
   567          # if you have created a different channel name, then pass in the appropriately named block
   568  
   569           peer channel join -b mychannel.block
   570  
   571  You can make other peers join the channel as necessary by making appropriate
   572  changes in the four environment variables we used in the :ref:`peerenvvars`
   573  section, above.
   574  
   575  Rather than join every peer, we will simply join ``peer0.org2.example.com`` so that
   576  we can properly update the anchor peer definitions in our channel.  Since we are
   577  overriding the default environment variables baked into the CLI container, this full
   578  command will be the following:
   579  
   580  .. code:: bash
   581  
   582    CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp CORE_PEER_ADDRESS=peer0.org2.example.com:9051 CORE_PEER_LOCALMSPID="Org2MSP" CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt peer channel join -b mychannel.block
   583  
   584  Alternatively, you could choose to set these environment variables individually
   585  rather than passing in the entire string.  Once they've been set, you simply need
   586  to issue the ``peer channel join`` command again and the CLI container will act
   587  on behalf of ``peer0.org2.example.com``.
   588  
   589  Update the anchor peers
   590  ^^^^^^^^^^^^^^^^^^^^^^^
   591  
   592  The following commands are channel updates and they will propagate to the definition
   593  of the channel.  In essence, we adding additional configuration information on top
   594  of the channel's genesis block.  Note that we are not modifying the genesis block, but
   595  simply adding deltas into the chain that will define the anchor peers.
   596  
   597  Update the channel definition to define the anchor peer for Org1 as ``peer0.org1.example.com``:
   598  
   599  .. code:: bash
   600  
   601    peer channel update -o orderer.example.com:7050 -c $CHANNEL_NAME -f ./channel-artifacts/Org1MSPanchors.tx --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
   602  
   603  Now update the channel definition to define the anchor peer for Org2 as ``peer0.org2.example.com``.
   604  Identically to the ``peer channel join`` command for the Org2 peer, we will need to
   605  preface this call with the appropriate environment variables.
   606  
   607  .. code:: bash
   608  
   609    CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp CORE_PEER_ADDRESS=peer0.org2.example.com:9051 CORE_PEER_LOCALMSPID="Org2MSP" CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt peer channel update -o orderer.example.com:7050 -c $CHANNEL_NAME -f ./channel-artifacts/Org2MSPanchors.tx --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
   610  
   611  .. _install-define-chaincode:
   612  
   613  Install and define a chaincode
   614  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   615  
   616  .. note:: We will utilize a simple existing chaincode. To learn how to write
   617            your own chaincode, see the :doc:`chaincode4ade` tutorial.
   618  
   619  .. note:: These instructions use the Fabric chaincode lifecycle introduced in
   620            the v2.0 release. If you would like to use the previous lifecycle to
   621            install and instantiate a chaincode, visit the v1.4 version of the
   622            `Building your first network tutorial <https://hyperledger-fabric.readthedocs.io/en/release-1.4/build_network.html>`__.
   623  
   624  Applications interact with the blockchain ledger through ``chaincode``.
   625  Therefore we need to install a chaincode on every peer that will execute and
   626  endorse our transactions. However, before we can interact with our chaincode,
   627  the members of the channel need to agree on a chaincode definition that
   628  establishes chaincode governance.
   629  
   630  We need to package the chaincode before it can be installed on our peers. For
   631  each package you create, you need to provide a chaincode package label as a
   632  description of the chaincode. Use the following commands to package a sample
   633  Go, Node.js or Java chaincode.
   634  
   635  **Golang**
   636  
   637  .. code:: bash
   638  
   639      # before packaging Golang chaincode, vendoring Go dependencies is required like the following commands.
   640      cd /opt/gopath/src/github.com/hyperledger/fabric-samples/chaincode/abstore/go
   641      GO111MODULE=on go mod vendor
   642      cd -
   643  
   644      # this packages a Golang chaincode.
   645      # make note of the --lang flag to indicate "golang" chaincode
   646      # for go chaincode --path takes the relative path from $GOPATH/src
   647      # The --label flag is used to create the package label
   648      peer lifecycle chaincode package mycc.tar.gz --path github.com/hyperledger/fabric-samples/chaincode/abstore/go/ --lang golang --label mycc_1
   649  
   650  **Node.js**
   651  
   652  .. code:: bash
   653  
   654      # this packages a Node.js chaincode
   655      # make note of the --lang flag to indicate "node" chaincode
   656      # for node chaincode --path takes the absolute path to the node.js chaincode
   657      # The --label flag is used to create the package label
   658      peer lifecycle chaincode package mycc.tar.gz --path /opt/gopath/src/github.com/hyperledger/fabric-samples/chaincode/abstore/javascript/ --lang node --label mycc_1
   659  
   660  **Java**
   661  
   662  .. code:: bash
   663  
   664      # this packages a java chaincode
   665      # make note of the --lang flag to indicate "java" chaincode
   666      # for java chaincode --path takes the absolute path to the java chaincode
   667      # The --label flag is used to create the package label
   668      peer lifecycle chaincode package mycc.tar.gz --path /opt/gopath/src/github.com/hyperledger/fabric-samples/chaincode/abstore/java/ --lang java --label mycc_1
   669  
   670  Each of the above commands will create a chaincode package named ``mycc.tar.gz``,
   671  which we can use to install the chaincode on our peers. Issue the following
   672  command to install the package on peer0 of Org1.
   673  
   674  .. code:: bash
   675  
   676      # this command installs a chaincode package on your peer
   677      peer lifecycle chaincode install mycc.tar.gz
   678  
   679  A successful install command will return a chaincode package identifier. You
   680  should see output similar to the following:
   681  
   682  .. code:: bash
   683  
   684      2019-03-13 13:48:53.691 UTC [cli.lifecycle.chaincode] submitInstallProposal -> INFO 001 Installed remotely: response:<status:200 payload:"\nEmycc_1:3a8c52d70c36313cfebbaf09d8616e7a6318ababa01c7cbe40603c373bcfe173" >
   685      2019-03-13 13:48:53.691 UTC [cli.lifecycle.chaincode] submitInstallProposal -> INFO 002 Chaincode code package identifier: mycc_1:3a8c52d70c36313cfebbaf09d8616e7a6318ababa01c7cbe40603c373bcfe173
   686  
   687  You can also find the chaincode package identifier by querying your peer for
   688  information about the packages you have installed.
   689  
   690  .. code:: bash
   691  
   692      # this returns the details of the chaincode packages installed on your peers
   693      peer lifecycle chaincode queryinstalled
   694  
   695  The command above will return the same package identifier as the install command.
   696  You should see output similar to the following:
   697  
   698  .. code:: bash
   699  
   700        Get installed chaincodes on peer:
   701        Package ID: mycc_1:3a8c52d70c36313cfebbaf09d8616e7a6318ababa01c7cbe40603c373bcfe173, Label: mycc_1
   702  
   703  We are going to need the package ID for future commands, so let's go ahead and
   704  save it as an environment variable. Paste the package ID returned by the
   705  `peer lifecycle chaincode queryinstalled` command into the command below. The
   706  package ID may not be the same for all users, so you need to complete this step
   707  using the package ID returned from your console.
   708  
   709  .. code:: bash
   710  
   711     # Save the package ID as an environment variable.
   712  
   713     CC_PACKAGE_ID=mycc_1:3a8c52d70c36313cfebbaf09d8616e7a6318ababa01c7cbe40603c373bcfe173
   714  
   715  The endorsement policy of ``mycc`` will be set to require endorsements from a
   716  peer in both Org1 and Org2. Therefore, we also need to install the chaincode on
   717  a peer in Org2.
   718  
   719  Modify the following four environment variables to issue the install command
   720  as Org2:
   721  
   722  .. code:: bash
   723  
   724     # Environment variables for PEER0 in Org2
   725  
   726     CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp
   727     CORE_PEER_ADDRESS=peer0.org2.example.com:9051
   728     CORE_PEER_LOCALMSPID="Org2MSP"
   729     CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt
   730  
   731  Now install the chaincode package onto peer0 of Org2. The following command
   732  will install the chaincode and return same identifier as the install command we
   733  issued as Org1.
   734  
   735  .. code:: bash
   736  
   737      # this installs a chaincode package on your peer
   738      peer lifecycle chaincode install mycc.tar.gz
   739  
   740  After you install the package, you need to approve a chaincode definition
   741  for your organization. The chaincode definition includes the important
   742  parameters of chaincode governance, including the chaincode name and version.
   743  The definition also includes the package identifier used to associate the
   744  chaincode package installed on your peers with a chaincode definition approved
   745  by your organization.
   746  
   747  Because we set the environment variables to operate as Org2, we can use the
   748  following command to approve a definition of the ``mycc`` chaincode for
   749  Org2. The approval is distributed to peers within each organization, so
   750  the command does not need to target every peer within an organization.
   751  
   752  .. code:: bash
   753  
   754      # this approves a chaincode definition for your org
   755      # make note of the --package-id flag that provides the package ID
   756      # use the --init-required flag to request the ``Init`` function be invoked to initialize the chaincode
   757      peer lifecycle chaincode approveformyorg --channelID $CHANNEL_NAME --name mycc --version 1.0 --init-required --package-id $CC_PACKAGE_ID --sequence 1 --tls true --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
   758  
   759  We could have provided a ``--signature-policy`` or ``--channel-config-policy``
   760  argument to the command above to set the chaincode endorsement policy. The
   761  endorsement policy specifies how many peers belonging to different channel
   762  members need to validate a transaction against a given chaincode. Because we did
   763  not set a policy, the definition of ``mycc`` will use the default endorsement
   764  policy, which requires that a transaction be endorsed by a majority of channel
   765  members present when the transaction is submitted. This implies that if new
   766  organizations are added to or removed from the channel, the endorsement policy
   767  is updated automatically to require more or fewer endorsements. In this tutorial,
   768  the default policy will require an endorsement from a peer belonging to Org1
   769  **AND** Org2 (i.e. two endorsements). See the :doc:`endorsement-policies`
   770  documentation for more details on policy implementation.
   771  
   772  All organizations need to agree on the definition before they can use the
   773  chaincode. Modify the following four environment variables to operate as Org1:
   774  
   775  .. code:: bash
   776  
   777      # Environment variables for PEER0
   778  
   779      CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
   780      CORE_PEER_ADDRESS=peer0.org1.example.com:7051
   781      CORE_PEER_LOCALMSPID="Org1MSP"
   782      CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
   783  
   784  You can now approve a definition for the ``mycc`` chaincode as Org1. Chaincode is
   785  approved at the organization level. You can issue the command once even if you
   786  have multiple peers.
   787  
   788  .. code:: bash
   789  
   790      # this defines a chaincode for your org
   791      # make note of the --package-id flag that provides the package ID
   792      # use the --init-required flag to request the Init function be invoked to initialize the chaincode
   793      peer lifecycle chaincode approveformyorg --channelID $CHANNEL_NAME --name mycc --version 1.0 --init-required --package-id $CC_PACKAGE_ID --sequence 1 --tls true --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
   794  
   795  Once a sufficient number of channel members have approved a chaincode definition,
   796  one member can commit the definition to the channel. By default a majority of
   797  channel members need to approve a definition before it can be committed. It is
   798  possible to check whether the chaincode definition is ready to be committed and
   799  view the current approvals by organization by issuing the following query:
   800  
   801  .. code:: bash
   802  
   803      # the flags used for this command are identical to those used for approveformyorg
   804      # except for --package-id which is not required since it is not stored as part of
   805      # the definition
   806      peer lifecycle chaincode checkcommitreadiness --channelID $CHANNEL_NAME --name mycc --version 1.0 --init-required --sequence 1 --tls true --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem --output json
   807  
   808  The command will produce as output a JSON map showing if the organizations in the
   809  channel have approved the chaincode definition provided in the checkcommitreadiness
   810  command. In this case, given that both organizations have approved, we obtain:
   811  
   812  .. code:: bash
   813  
   814      {
   815              "Approvals": {
   816                      "Org1MSP": true,
   817                      "Org2MSP": true
   818              }
   819      }
   820  
   821  Since both channel members have approved the definition, we can now commit it to
   822  the channel using the following command. You can issue this command as either
   823  Org1 or Org2. Note that the transaction targets peers in Org1 and Org2 to
   824  collect endorsements.
   825  
   826  .. code:: bash
   827  
   828      # this commits the chaincode definition to the channel
   829      peer lifecycle chaincode commit -o orderer.example.com:7050 --channelID $CHANNEL_NAME --name mycc --version 1.0 --sequence 1 --init-required --tls true --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem --peerAddresses peer0.org1.example.com:7051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt --peerAddresses peer0.org2.example.com:9051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt
   830  
   831  Invoking the chaincode
   832  ^^^^^^^^^^^^^^^^^^^^^^
   833  
   834  After a chaincode definition has been committed to a channel, we are ready to
   835  invoke the chaincode and start interacting with the ledger. We requested the
   836  execution of the ``Init`` function in the chaincode definition using the
   837  ``--init-required`` flag. As a result, we need to pass the ``--isInit`` flag to
   838  its first invocation and supply the arguments to the ``Init`` function. Issue the
   839  following command to initialize the chaincode and put the initial data on the
   840  ledger.
   841  
   842  .. code:: bash
   843  
   844      # be sure to set the -C and -n flags appropriately
   845      # use the --isInit flag if you are invoking an Init function
   846      peer chaincode invoke -o orderer.example.com:7050 --isInit --tls true --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C $CHANNEL_NAME -n mycc --peerAddresses peer0.org1.example.com:7051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt --peerAddresses peer0.org2.example.com:9051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt -c '{"Args":["Init","a","100","b","100"]}' --waitForEvent
   847  
   848  The first invoke will start the chaincode container. We may need to wait for the
   849  container to start. Node.js images will take longer.
   850  
   851  Query
   852  ^^^^^
   853  
   854  Let's query the chaincode to make sure that the container was properly started
   855  and the state DB was populated. The syntax for query is as follows:
   856  
   857  .. code:: bash
   858  
   859    # be sure to set the -C and -n flags appropriately
   860  
   861    peer chaincode query -C $CHANNEL_NAME -n mycc -c '{"Args":["query","a"]}'
   862  
   863  Invoke
   864  ^^^^^^
   865  
   866  Now let’s move ``10`` from ``a`` to ``b``. This transaction will cut a new block
   867  and update the state DB. The syntax for invoke is as follows:
   868  
   869  .. code:: bash
   870  
   871    # be sure to set the -C and -n flags appropriately
   872    peer chaincode invoke -o orderer.example.com:7050 --tls true --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C $CHANNEL_NAME -n mycc --peerAddresses peer0.org1.example.com:7051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt --peerAddresses peer0.org2.example.com:9051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt -c '{"Args":["invoke","a","b","10"]}' --waitForEvent
   873  
   874  Query
   875  ^^^^^
   876  
   877  Let's confirm that our previous invocation executed properly. We initialized the
   878  key ``a`` with a value of ``100`` and just removed ``10`` with our previous
   879  invocation. Therefore, a query against ``a`` should return ``90``. The syntax
   880  for query is as follows.
   881  
   882  .. code:: bash
   883  
   884    # be sure to set the -C and -n flags appropriately
   885  
   886    peer chaincode query -C $CHANNEL_NAME -n mycc -c '{"Args":["query","a"]}'
   887  
   888  We should see the following:
   889  
   890  .. code:: bash
   891  
   892     Query Result: 90
   893  
   894  Install the chaincode on an additional peer
   895  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   896  
   897  If you want additional peers to interact with the ledger, then you will need to
   898  join them to the channel and install the same chaincode package on the peers.
   899  You only need to approve the chaincode definition once from your organization.
   900  A chaincode container will be launched for each peer as soon as they try to
   901  interact with that specific chaincode. Again, be cognizant of the fact that the
   902  Node.js images will be slower to build and start upon the first invoke.
   903  
   904  We will install the chaincode on a third peer, peer1 in Org2. Modify the
   905  following four environment variables to issue the install command against peer1
   906  in Org2:
   907  
   908  .. code:: bash
   909  
   910     # Environment variables for PEER1 in Org2
   911  
   912     CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp
   913     CORE_PEER_ADDRESS=peer1.org2.example.com:10051
   914     CORE_PEER_LOCALMSPID="Org2MSP"
   915     CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer1.org2.example.com/tls/ca.crt
   916  
   917  Now install the ``mycc`` package on peer1 of Org2:
   918  
   919  .. code:: bash
   920  
   921      # this command installs a chaincode package on your peer
   922      peer lifecycle chaincode install mycc.tar.gz
   923  
   924  Query
   925  ^^^^^
   926  
   927  Let's confirm that we can issue the query to Peer1 in Org2. We initialized the
   928  key ``a`` with a value of ``100`` and just removed ``10`` with our previous
   929  invocation. Therefore, a query against ``a`` should still return ``90``.
   930  
   931  Peer1 in Org2 must first join the channel before it can respond to queries. The
   932  channel can be joined by issuing the following command:
   933  
   934  .. code:: bash
   935  
   936    CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp CORE_PEER_ADDRESS=peer1.org2.example.com:10051 CORE_PEER_LOCALMSPID="Org2MSP" CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer1.org2.example.com/tls/ca.crt peer channel join -b mychannel.block
   937  
   938  After the join command returns, the query can be issued. The syntax for query is
   939  as follows.
   940  
   941  .. code:: bash
   942  
   943    # be sure to set the -C and -n flags appropriately
   944  
   945    peer chaincode query -C $CHANNEL_NAME -n mycc -c '{"Args":["query","a"]}'
   946  
   947  We should see the following:
   948  
   949  .. code:: bash
   950  
   951     Query Result: 90
   952  
   953  If you received an error, it may be because it takes a few seconds for the
   954  peer to join and catch up to the current blockchain height. You may
   955  re-query as needed. Feel free to perform additional invokes as well.
   956  
   957  .. _behind-scenes:
   958  
   959  What's happening behind the scenes?
   960  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   961  
   962  .. note:: These steps describe the scenario in which
   963            ``script.sh`` is run by './byfn.sh up'.  Clean your network
   964            with ``./byfn.sh down`` and ensure
   965            this command is active.  Then use the same
   966            docker-compose prompt to launch your network again
   967  
   968  -  A script - ``script.sh`` - is baked inside the CLI container. The
   969     script drives the ``createChannel`` command against the supplied channel name
   970     and uses the channel.tx file for channel configuration.
   971  
   972  -  The output of ``createChannel`` is a genesis block -
   973     ``<your_channel_name>.block`` - which gets stored on the peers' file systems and contains
   974     the channel configuration specified from channel.tx.
   975  
   976  -  The ``joinChannel`` command is exercised for all four peers, which takes as
   977     input the previously generated genesis block.  This command instructs the
   978     peers to join ``<your_channel_name>`` and create a chain starting with ``<your_channel_name>.block``.
   979  
   980  -  Now we have a channel consisting of four peers, and two
   981     organizations.  This is our ``TwoOrgsChannel`` profile.
   982  
   983  -  ``peer0.org1.example.com`` and ``peer1.org1.example.com`` belong to Org1;
   984     ``peer0.org2.example.com`` and ``peer1.org2.example.com`` belong to Org2
   985  
   986  -  These relationships are defined through the ``crypto-config.yaml`` and
   987     the MSP path is specified in our docker compose.
   988  
   989  -  The anchor peers for Org1MSP (``peer0.org1.example.com``) and
   990     Org2MSP (``peer0.org2.example.com``) are then updated.  We do this by passing
   991     the ``Org1MSPanchors.tx`` and ``Org2MSPanchors.tx`` artifacts to the ordering
   992     service along with the name of our channel.
   993  
   994  -  A chaincode - **abstore** - is packaged and installed on ``peer0.org1.example.com``
   995     and ``peer0.org2.example.com``
   996  
   997  -  The chaincode is then separately approved by Org1 and Org2, and then committed
   998     on the channel. Since an endorsement policy was not specified, the channel's
   999     default endorsement policy of a majority of organizations will get utilized,
  1000     meaning that any transaction must be endorsed by a peer tied to Org1 and Org2.
  1001  
  1002  -  The chaincode Init is then called which starts the container for the target peer,
  1003     and initializes the key value pairs associated with the chaincode.  The initial
  1004     values for this example are ["a","100" "b","200"]. This first invoke results
  1005     in a container by the name of ``dev-peer0.org2.example.com-mycc-1.0`` starting.
  1006  
  1007  -  A query against the value of "a" is issued to ``peer0.org2.example.com``.
  1008     A container for Org2 peer0 by the name of ``dev-peer0.org2.example.com-mycc-1.0``
  1009     was started when the chaincode was initialized. The result of the query is
  1010     returned. No write operations have occurred, so a query against "a" will
  1011     still return a value of "100".
  1012  
  1013  -  An invoke is sent to ``peer0.org1.example.com`` and ``peer0.org2.example.com``
  1014     to move "10" from "a" to "b"
  1015  
  1016  -  A query is sent to ``peer0.org2.example.com`` for the value of "a". A
  1017     value of 90 is returned, correctly reflecting the previous
  1018     transaction during which the value for key "a" was modified by 10.
  1019  
  1020  -  The chaincode - **abstore** - is installed on ``peer1.org2.example.com``
  1021  
  1022  -  A query is sent to ``peer1.org2.example.com`` for the value of "a". This starts a
  1023     third chaincode container by the name of ``dev-peer1.org2.example.com-mycc-1.0``. A
  1024     value of 90 is returned, correctly reflecting the previous
  1025     transaction during which the value for key "a" was modified by 10.
  1026  
  1027  What does this demonstrate?
  1028  ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1029  
  1030  Chaincode **MUST** be installed on a peer in order for it to
  1031  successfully perform read/write operations against the ledger.
  1032  Furthermore, a chaincode container is not started for a peer until an ``init`` or
  1033  traditional transaction - read/write - is performed against that chaincode (e.g. query for
  1034  the value of "a"). The transaction causes the container to start. Also,
  1035  all peers in a channel maintain an exact copy of the ledger which
  1036  comprises the blockchain to store the immutable, sequenced record in
  1037  blocks, as well as a state database to maintain a snapshot of the current state.
  1038  This includes those peers that do not have chaincode installed on them
  1039  (like ``peer1.org1.example.com`` in the above example) . Finally, the chaincode is accessible
  1040  after it is installed (like ``peer1.org2.example.com`` in the above example) because its
  1041  definition has already been committed on the channel.
  1042  
  1043  How do I see these transactions?
  1044  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1045  
  1046  Check the logs for the CLI Docker container.
  1047  
  1048  .. code:: bash
  1049  
  1050          docker logs -f cli
  1051  
  1052  You should see the following output:
  1053  
  1054  .. code:: bash
  1055  
  1056        2017-05-16 17:08:01.366 UTC [msp] GetLocalMSP -> DEBU 004 Returning existing local MSP
  1057        2017-05-16 17:08:01.366 UTC [msp] GetDefaultSigningIdentity -> DEBU 005 Obtaining default signing identity
  1058        2017-05-16 17:08:01.366 UTC [msp/identity] Sign -> DEBU 006 Sign: plaintext: 0AB1070A6708031A0C08F1E3ECC80510...6D7963631A0A0A0571756572790A0161
  1059        2017-05-16 17:08:01.367 UTC [msp/identity] Sign -> DEBU 007 Sign: digest: E61DB37F4E8B0D32C9FE10E3936BA9B8CD278FAA1F3320B08712164248285C54
  1060        Query Result: 90
  1061        2017-05-16 17:08:15.158 UTC [main] main -> INFO 008 Exiting.....
  1062        ===================== Query successful on peer1.org2 on channel 'mychannel' =====================
  1063  
  1064        ===================== All GOOD, BYFN execution completed =====================
  1065  
  1066  
  1067         _____   _   _   ____
  1068        | ____| | \ | | |  _ \
  1069        |  _|   |  \| | | | | |
  1070        | |___  | |\  | | |_| |
  1071        |_____| |_| \_| |____/
  1072  
  1073  You can scroll through these logs to see the various transactions.
  1074  
  1075  How can I see the chaincode logs?
  1076  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1077  
  1078  You can inspect the individual chaincode containers to see the separate
  1079  transactions executed against each container. Use the following command to find
  1080  the list of running containers to find your chaincode containers:
  1081  
  1082  .. code:: bash
  1083  
  1084      $ docker ps -a
  1085      CONTAINER ID        IMAGE                                                                                                                                                                 COMMAND                  CREATED              STATUS              PORTS                                NAMES
  1086      7aa7d9e199f5        dev-peer1.org2.example.com-mycc_1-27ef99cb3cbd1b545063f018f3670eddc0d54f40b2660b8f853ad2854c49a0d8-2eba360c66609a3ba78327c2c86bc3abf041c78f5a35553191a1acf1efdd5a0d   "chaincode -peer.add…"   About a minute ago   Up About a minute                                        dev-peer1.org2.example.com-mycc_1-27ef99cb3cbd1b545063f018f3670eddc0d54f40b2660b8f853ad2854c49a0d8
  1087      82ce129c0fe6        dev-peer0.org2.example.com-mycc_1-27ef99cb3cbd1b545063f018f3670eddc0d54f40b2660b8f853ad2854c49a0d8-1297906045aa77086daba21aba47e8eef359f9498b7cb2b010dff3e2a354565a   "chaincode -peer.add…"   About a minute ago   Up About a minute                                        dev-peer0.org2.example.com-mycc_1-27ef99cb3cbd1b545063f018f3670eddc0d54f40b2660b8f853ad2854c49a0d8
  1088      eaef1a8f7acf        dev-peer0.org1.example.com-mycc_1-27ef99cb3cbd1b545063f018f3670eddc0d54f40b2660b8f853ad2854c49a0d8-00d8dbefd85a4aeb9428b7df95df9744be1325b2a60900ac7a81796e67e4280a   "chaincode -peer.add…"   2 minutes ago        Up 2 minutes                                             dev-peer0.org1.example.com-mycc_1-27ef99cb3cbd1b545063f018f3670eddc0d54f40b2660b8f853ad2854c49a0d8
  1089      da403175b785        hyperledger/fabric-tools:latest                                                                                                                                       "/bin/bash"              4 minutes ago        Up 4 minutes                                             cli
  1090      c62a8d03818f        hyperledger/fabric-peer:latest                                                                                                                                        "peer node start"        4 minutes ago        Up 4 minutes        7051/tcp, 0.0.0.0:9051->9051/tcp     peer0.org2.example.com
  1091      06593c4f3e53        hyperledger/fabric-peer:latest                                                                                                                                        "peer node start"        4 minutes ago        Up 4 minutes        0.0.0.0:7051->7051/tcp               peer0.org1.example.com
  1092      4ddc928ebffe        hyperledger/fabric-orderer:latest                                                                                                                                     "orderer"                4 minutes ago        Up 4 minutes        0.0.0.0:7050->7050/tcp               orderer.example.com
  1093      6d79e95ec059        hyperledger/fabric-peer:latest                                                                                                                                        "peer node start"        4 minutes ago        Up 4 minutes        7051/tcp, 0.0.0.0:10051->10051/tcp   peer1.org2.example.com
  1094      6aad6b40fd30        hyperledger/fabric-peer:latest                                                                                                                                        "peer node start"        4 minutes ago        Up 4 minutes        7051/tcp, 0.0.0.0:8051->8051/tcp     peer1.org1.example.com
  1095  
  1096  The chaincode containers are the images starting with `dev-peer`. You can then
  1097  use the container ID to find the logs from each chaincode container.
  1098  
  1099  .. code:: bash
  1100  
  1101          $ docker logs 7aa7d9e199f5
  1102          ABstore Init
  1103          Aval = 100, Bval = 100
  1104          ABstore Invoke
  1105          Aval = 90, Bval = 110
  1106  
  1107          $ docker logs eaef1a8f7acf
  1108          ABstore Init
  1109          Aval = 100, Bval = 100
  1110          ABstore Invoke
  1111          Query Response:{"Name":"a","Amount":"100"}
  1112          ABstore Invoke
  1113          Aval = 90, Bval = 110
  1114          ABstore Invoke
  1115          Query Response:{"Name":"a","Amount":"90"}
  1116  
  1117  You can also see the peer logs to view chaincode invoke messages
  1118  and block commit messages:
  1119  
  1120  .. code:: bash
  1121  
  1122            $ docker logs peer0.org1.example.com
  1123  
  1124  Understanding the Docker Compose topology
  1125  -----------------------------------------
  1126  
  1127  The BYFN sample offers us two flavors of Docker Compose files, both of which
  1128  are extended from the ``docker-compose-base.yaml`` (located in the ``base``
  1129  folder).  Our first flavor, ``docker-compose-cli.yaml``, provides us with a
  1130  CLI container, along with an orderer, four peers.  We use this file
  1131  for the entirety of the instructions on this page.
  1132  
  1133  .. note:: the remainder of this section covers a docker-compose file designed for the
  1134            SDK.  Refer to the `Node SDK <https://github.com/hyperledger/fabric-sdk-node>`__
  1135            repo for details on running these tests.
  1136  
  1137  The second flavor, ``docker-compose-e2e.yaml``, is constructed to run end-to-end tests
  1138  using the Node.js SDK.  Aside from functioning with the SDK, its primary differentiation
  1139  is that there are containers for the fabric-ca servers.  As a result, we are able
  1140  to send REST calls to the organizational CAs for user registration and enrollment.
  1141  
  1142  If you want to use the ``docker-compose-e2e.yaml`` without first running the
  1143  byfn.sh script, then we will need to make four slight modifications.
  1144  We need to point to the private keys for our Organization's CA's.  You can locate
  1145  these values in your crypto-config folder.  For example, to locate the private
  1146  key for Org1 we would follow this path - ``crypto-config/peerOrganizations/org1.example.com/ca/``.
  1147  The private key is a long hash value followed by ``_sk``.  The path for Org2
  1148  would be - ``crypto-config/peerOrganizations/org2.example.com/ca/``.
  1149  
  1150  In the ``docker-compose-e2e.yaml`` update the FABRIC_CA_SERVER_TLS_KEYFILE variable
  1151  for ca0 and ca1.  You also need to edit the path that is provided in the command
  1152  to start the ca server.  You are providing the same private key twice for each
  1153  CA container.
  1154  
  1155  Using CouchDB
  1156  -------------
  1157  
  1158  The state database can be switched from the default (goleveldb) to CouchDB.
  1159  The same chaincode functions are available with CouchDB, however, there is the
  1160  added ability to perform rich and complex queries against the state database
  1161  data content contingent upon the chaincode data being modeled as JSON.
  1162  
  1163  To use CouchDB instead of the default database (goleveldb), follow the same
  1164  procedures outlined earlier for generating the artifacts, except when starting
  1165  the network pass ``docker-compose-couch.yaml`` as well:
  1166  
  1167  .. code:: bash
  1168  
  1169      docker-compose -f docker-compose-cli.yaml -f docker-compose-couch.yaml -f docker-compose-etcdraft2.yaml up -d
  1170  
  1171  **abstore** should now work using CouchDB underneath.
  1172  
  1173  .. note::  If you choose to implement mapping of the fabric-couchdb container
  1174             port to a host port, please make sure you are aware of the security
  1175             implications. Mapping of the port in a development environment makes the
  1176             CouchDB REST API available, and allows the
  1177             visualization of the database via the CouchDB web interface (Fauxton).
  1178             Production environments would likely refrain from implementing port mapping in
  1179             order to restrict outside access to the CouchDB containers.
  1180  
  1181  You can use **abstore** chaincode against the CouchDB state database
  1182  using the steps outlined above, however in order to exercise the CouchDB query
  1183  capabilities you will need to use a chaincode that has data modeled as JSON.
  1184  The sample chaincode **marbles02** has been written to demostrate the queries
  1185  you can issue from your chaincode if you are using a CouchDB database. You can
  1186  locate the **marbles02** chaincode in the ``fabric/examples/chaincode/go``
  1187  directory.
  1188  
  1189  We will follow the same process to create and join the channel as outlined in the
  1190  :ref:`peerenvvars` section above.  Once you have joined your peer(s) to the
  1191  channel, use the following steps to interact with the **marbles02** chaincode:
  1192  
  1193  
  1194  - Package and install the chaincode on ``peer0.org1.example.com``:
  1195  
  1196  .. code:: bash
  1197  
  1198         # before packaging Golang chaincode, vendoring Go dependencies is required like the following commands.
  1199         cd /opt/gopath/src/github.com/hyperledger/fabric-samples/chaincode/marbles02/go
  1200         GO111MODULE=on go mod vendor
  1201         cd -
  1202  
  1203         # packages and installs the Golang chaincode
  1204         peer lifecycle chaincode package marbles.tar.gz --path github.com/hyperledger/fabric-samples/chaincode/marbles02/go/ --lang golang --label marbles_1
  1205         peer lifecycle chaincode install marbles.tar.gz
  1206  
  1207  The install command will return a chaincode packageID that you will use to
  1208  approve a chaincode definition.
  1209  
  1210  .. code:: bash
  1211  
  1212        2019-04-08 20:10:32.568 UTC [cli.lifecycle.chaincode] submitInstallProposal -> INFO 001 Installed remotely: response:<status:200 payload:"\nJmarbles_1:cfb623954827aef3f35868764991cc7571b445a45cfd3325f7002f14156d61ae\022\tmarbles_1" >
  1213        2019-04-08 20:10:32.568 UTC [cli.lifecycle.chaincode] submitInstallProposal -> INFO 002 Chaincode code package identifier: marbles_1:cfb623954827aef3f35868764991cc7571b445a45cfd3325f7002f14156d61ae
  1214  
  1215  - Save the packageID as an environment variable so you can pass it to future
  1216    commands:
  1217  
  1218    .. code:: bash
  1219  
  1220        CC_PACKAGE_ID=marbles_1:3a8c52d70c36313cfebbaf09d8616e7a6318ababa01c7cbe40603c373bcfe173
  1221  
  1222  - Approve a chaincode definition as Org1:
  1223  
  1224  .. code:: bash
  1225  
  1226         # be sure to modify the $CHANNEL_NAME variable accordingly for the command
  1227  
  1228         peer lifecycle chaincode approveformyorg --channelID $CHANNEL_NAME --name marbles --version 1.0 --package-id $CC_PACKAGE_ID --sequence 1 --tls true --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
  1229  
  1230  - Install the chaincode on ``peer0.org2.example.com``:
  1231  
  1232  .. code:: bash
  1233  
  1234        CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp
  1235        CORE_PEER_ADDRESS=peer0.org2.example.com:9051
  1236        CORE_PEER_LOCALMSPID="Org2MSP"
  1237        CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt
  1238        peer lifecycle chaincode install marbles.tar.gz
  1239  
  1240  - Approve a chaincode definition as Org2, and then commit the definition to the
  1241    channel:
  1242  
  1243  .. code:: bash
  1244  
  1245         # be sure to modify the $CHANNEL_NAME variable accordingly for the command
  1246  
  1247         peer lifecycle chaincode approveformyorg --channelID $CHANNEL_NAME --name marbles --version 1.0 --package-id $CC_PACKAGE_ID --sequence 1 --tls true --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem
  1248         peer lifecycle chaincode commit -o orderer.example.com:7050 --channelID $CHANNEL_NAME --name marbles --version 1.0 --sequence 1 --tls true --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem --peerAddresses peer0.org1.example.com:7051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt --peerAddresses peer0.org2.example.com:9051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt
  1249  
  1250  - We can now create some marbles. The first invoke of the chaincode will start
  1251    the chaincode container. You may need to wait for the container to start.
  1252  
  1253  .. code:: bash
  1254  
  1255         # be sure to modify the $CHANNEL_NAME variable accordingly
  1256  
  1257         peer chaincode invoke -o orderer.example.com:7050 --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C $CHANNEL_NAME -n marbles --peerAddresses peer0.org1.example.com:7051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt --peerAddresses peer0.org2.example.com:9051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt -c '{"Args":["initMarble","marble1","blue","35","tom"]}'
  1258  
  1259  Once the container has started, you can issue additional commands to create
  1260  some marbles and move them around:
  1261  
  1262  .. code:: bash
  1263  
  1264          # be sure to modify the $CHANNEL_NAME variable accordingly
  1265  
  1266          peer chaincode invoke -o orderer.example.com:7050 --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C $CHANNEL_NAME -n marbles --peerAddresses peer0.org1.example.com:7051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt --peerAddresses peer0.org2.example.com:9051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt -c '{"Args":["initMarble","marble2","red","50","tom"]}'
  1267          peer chaincode invoke -o orderer.example.com:7050 --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C $CHANNEL_NAME -n marbles --peerAddresses peer0.org1.example.com:7051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt --peerAddresses peer0.org2.example.com:9051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt -c '{"Args":["initMarble","marble3","blue","70","tom"]}'
  1268          peer chaincode invoke -o orderer.example.com:7050 --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C $CHANNEL_NAME -n marbles --peerAddresses peer0.org1.example.com:7051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt --peerAddresses peer0.org2.example.com:9051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt -c '{"Args":["transferMarble","marble2","jerry"]}'
  1269          peer chaincode invoke -o orderer.example.com:7050 --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C $CHANNEL_NAME -n marbles --peerAddresses peer0.org1.example.com:7051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt --peerAddresses peer0.org2.example.com:9051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt -c '{"Args":["transferMarblesBasedOnColor","blue","jerry"]}'
  1270          peer chaincode invoke -o orderer.example.com:7050 --tls --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C $CHANNEL_NAME -n marbles --peerAddresses peer0.org1.example.com:7051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt --peerAddresses peer0.org2.example.com:9051 --tlsRootCertFiles /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt -c '{"Args":["delete","marble1"]}'
  1271  
  1272  -  If you chose to map the CouchDB ports in docker-compose, you can now view
  1273     the state database through the CouchDB web interface (Fauxton) by opening
  1274     a browser and navigating to the following URL:
  1275  
  1276     ``http://localhost:5984/_utils``
  1277  
  1278  You should see a database named ``mychannel`` (or your unique channel name) and
  1279  the documents inside it.
  1280  
  1281  .. note:: For the below commands, be sure to update the $CHANNEL_NAME variable appropriately.
  1282  
  1283  You can run regular queries from the CLI (e.g. reading ``marble2``):
  1284  
  1285  .. code:: bash
  1286  
  1287        peer chaincode query -C $CHANNEL_NAME -n marbles -c '{"Args":["readMarble","marble2"]}'
  1288  
  1289  The output should display the details of ``marble2``:
  1290  
  1291  .. code:: bash
  1292  
  1293         Query Result: {"color":"red","docType":"marble","name":"marble2","owner":"jerry","size":50}
  1294  
  1295  You can retrieve the history of a specific marble - e.g. ``marble1``:
  1296  
  1297  .. code:: bash
  1298  
  1299        peer chaincode query -C $CHANNEL_NAME -n marbles -c '{"Args":["getHistoryForMarble","marble1"]}'
  1300  
  1301  The output should display the transactions on ``marble1``:
  1302  
  1303  .. code:: bash
  1304  
  1305        Query Result: [{"TxId":"1c3d3caf124c89f91a4c0f353723ac736c58155325f02890adebaa15e16e6464", "Value":{"docType":"marble","name":"marble1","color":"blue","size":35,"owner":"tom"}},{"TxId":"755d55c281889eaeebf405586f9e25d71d36eb3d35420af833a20a2f53a3eefd", "Value":{"docType":"marble","name":"marble1","color":"blue","size":35,"owner":"jerry"}},{"TxId":"819451032d813dde6247f85e56a89262555e04f14788ee33e28b232eef36d98f", "Value":}]
  1306  
  1307  You can also perform rich queries on the data content, such as querying marble fields by owner ``jerry``:
  1308  
  1309  .. code:: bash
  1310  
  1311        peer chaincode query -C $CHANNEL_NAME -n marbles -c '{"Args":["queryMarblesByOwner","jerry"]}'
  1312  
  1313  The output should display the two marbles owned by ``jerry``:
  1314  
  1315  .. code:: bash
  1316  
  1317         Query Result: [{"Key":"marble2", "Record":{"color":"red","docType":"marble","name":"marble2","owner":"jerry","size":50}},{"Key":"marble3", "Record":{"color":"blue","docType":"marble","name":"marble3","owner":"jerry","size":70}}]
  1318  
  1319  
  1320  Why CouchDB
  1321  -------------
  1322  CouchDB is a kind of NoSQL solution. It is a document-oriented database where document fields are stored as key-value maps. Fields can be either a simple key-value pair, list, or map.
  1323  In addition to keyed/composite-key/key-range queries which are supported by LevelDB, CouchDB also supports full data rich queries capability, such as non-key queries against the whole blockchain data,
  1324  since its data content is stored in JSON format and fully queryable. Therefore, CouchDB can meet chaincode, auditing, reporting requirements for many use cases that not supported by LevelDB.
  1325  
  1326  CouchDB can also enhance the security for compliance and data protection in the blockchain. As it is able to implement field-level security through the filtering and masking of individual attributes within a transaction, and only authorizing the read-only permission if needed.
  1327  
  1328  A Note on Data Persistence
  1329  --------------------------
  1330  
  1331  If data persistence is desired on the peer container or the CouchDB container,
  1332  one option is to mount a directory in the docker-host into a relevant directory
  1333  in the container. For example, you may add the following two lines in
  1334  the peer container specification in the ``docker-compose-base.yaml`` file:
  1335  
  1336  .. code:: bash
  1337  
  1338         volumes:
  1339          - /var/hyperledger/peer0:/var/hyperledger/production
  1340  
  1341  For the CouchDB container, you may add the following two lines in the CouchDB
  1342  container specification:
  1343  
  1344  .. code:: bash
  1345  
  1346         volumes:
  1347          - /var/hyperledger/couchdb0:/opt/couchdb/data
  1348  
  1349  .. _Troubleshoot:
  1350  
  1351  Troubleshooting
  1352  ---------------
  1353  
  1354  -  Always start your network fresh.  Use the following command
  1355     to remove artifacts, crypto, containers and chaincode images:
  1356  
  1357     .. code:: bash
  1358  
  1359        ./byfn.sh down
  1360  
  1361     .. note:: You **will** see errors if you do not remove old containers
  1362               and images.
  1363  
  1364  -  If you see Docker errors, first check your docker version (:doc:`prereqs`),
  1365     and then try restarting your Docker process.  Problems with Docker are
  1366     oftentimes not immediately recognizable.  For example, you may see errors
  1367     resulting from an inability to access crypto material mounted within a
  1368     container.
  1369  
  1370     If they persist remove your images and start from scratch:
  1371  
  1372     .. code:: bash
  1373  
  1374         docker rm -f $(docker ps -aq)
  1375         docker rmi -f $(docker images -q)
  1376  
  1377  -  If you see errors on your create, approve, commit, invoke or query commands,
  1378     make sure you have properly updated the channel name and chaincode name.
  1379     There are placeholder values in the supplied sample commands.
  1380  
  1381  -  If you see the below error:
  1382  
  1383     .. code:: bash
  1384  
  1385         Error: Error endorsing chaincode: rpc error: code = 2 desc = Error installing chaincode code mycc:1.0(chaincode /var/hyperledger/production/chaincodes/mycc.1.0 exits)
  1386  
  1387     You likely have chaincode images (e.g. ``dev-peer1.org2.example.com-mycc-1.0`` or
  1388     ``dev-peer0.org1.example.com-mycc-1.0``) from prior runs. Remove them and try
  1389     again.
  1390  
  1391     .. code:: bash
  1392  
  1393         docker rmi -f $(docker images | grep peer[0-9]-peer[0-9] | awk '{print $3}')
  1394  
  1395  -  If you see something similar to the following:
  1396  
  1397     .. code:: bash
  1398  
  1399        Error connecting: rpc error: code = 14 desc = grpc: RPC failed fast due to transport failure
  1400        Error: rpc error: code = 14 desc = grpc: RPC failed fast due to transport failure
  1401  
  1402     Make sure you are running your network against the "1.0.0" images that have
  1403     been retagged as "latest".
  1404  
  1405  -  If you see the below error:
  1406  
  1407     .. code:: bash
  1408  
  1409       [configtx/tool/localconfig] Load -> CRIT 002 Error reading configuration: Unsupported Config Type ""
  1410       panic: Error reading configuration: Unsupported Config Type ""
  1411  
  1412     Then you did not set the ``FABRIC_CFG_PATH`` environment variable properly.  The
  1413     configtxgen tool needs this variable in order to locate the configtx.yaml.  Go
  1414     back and execute an ``export FABRIC_CFG_PATH=$PWD``, then recreate your
  1415     channel artifacts.
  1416  
  1417  -  To cleanup the network, use the ``down`` option:
  1418  
  1419     .. code:: bash
  1420  
  1421         ./byfn.sh down
  1422  
  1423  -  If you see an error stating that you still have "active endpoints", then prune
  1424     your Docker networks.  This will wipe your previous networks and start you with a
  1425     fresh environment:
  1426  
  1427     .. code:: bash
  1428  
  1429          docker network prune
  1430  
  1431     You will see the following message:
  1432  
  1433     .. code:: bash
  1434  
  1435        WARNING! This will remove all networks not used by at least one container.
  1436        Are you sure you want to continue? [y/N]
  1437  
  1438     Select ``y``.
  1439  
  1440  -  If you see an error similar to the following:
  1441  
  1442     .. code:: bash
  1443  
  1444        /bin/bash: ./scripts/script.sh: /bin/bash^M: bad interpreter: No such file or directory
  1445  
  1446     Ensure that the file in question (**script.sh** in this example) is encoded
  1447     in the Unix format. This was most likely caused by not setting
  1448     ``core.autocrlf`` to ``false`` in your Git configuration (see
  1449     :ref:`windows-extras`). There are several ways of fixing this. If you have
  1450     access to the vim editor for instance, open the file:
  1451  
  1452     .. code:: bash
  1453  
  1454        vim ./fabric-samples/first-network/scripts/script.sh
  1455  
  1456     Then change its format by executing the following vim command:
  1457  
  1458     .. code:: bash
  1459  
  1460        :set ff=unix
  1461  
  1462  .. note:: If you continue to see errors, share your logs on the
  1463            **fabric-questions** channel on
  1464            `Hyperledger Rocket Chat <https://chat.hyperledger.org/home>`__
  1465            or on `StackOverflow <https://stackoverflow.com/questions/tagged/hyperledger-fabric>`__.
  1466  
  1467  .. Licensed under Creative Commons Attribution 4.0 International License
  1468     https://creativecommons.org/licenses/by/4.0/