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