【Hyperledger Fabric入门】(一) 快速运行一个简单的Fabric网络2

本文在Ubuntu18.04运行,fabric版本为2.3.0。本文篇幅较长,因此分为两篇。快速运行一个简单的Fabric网络1详见:link

目录

      • 3. Orderer节点的启动
      • 4. Peer节点的启动
      • 5. 创建通道
      • 6. Chaincode的部署和调用

3. Orderer节点的启动

Orderer节点负责交易的打包和区块的生成。Orderer节点的配置信息通常放在环境变量或者配置文件中,本例中的配置信息统一放在配置文件中。fabric源码提供了Orderer启动所用到的配置文件的实例,将实力配置文件复制到Orderer的文件夹下面稍加修改即可使用。
复制fabric-samples里面的模板配置文件orderer.yaml到Orderer文件夹下面。
修改模板配置文件。修改后的配置文件中发生变化的内容如下:

# Copyright IBM Corp. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
#

---
################################################################################
#
#   Orderer Configuration
#
#   - This controls the type and configuration of the orderer.
#
################################################################################
General:
    # Listen address: The IP on which to bind to listen.
    ListenAddress: 192.168.178.128

    # Listen port: The port on which to bind to listen.
    ListenPort: 7050

    # TLS: TLS settings for the GRPC server.
    TLS:
        # Require server-side TLS
        Enabled: false
        # PrivateKey governs the file location of the private key of the TLS certificate.
        PrivateKey: ../fabricconfig/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/server.key
        # Certificate governs the file location of the server TLS certificate.
        Certificate: ../fabricconfig/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/server.crt
        # RootCAs contains a list of additional root certificates used for verifying certificates
        # of other orderer nodes during outbound connections.
        # It is not required to be set, but can be used to augment the set of TLS CA certificates
        # available from the MSPs of each channel’s configuration.
        RootCAs:
          - ../fabricconfig/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/ca.crt
        # Require client certificates / mutual TLS for inbound connections.
    # LogLevel: debug
    # LogFormat: '%{color}%{time:2021-02-09 16:52:00.000 MST} [%{module}] %{shortfunc} -> %{level:.4s} %{id:03x}%{color:reset} %{message}'
    BootstrapMethod: file
    #BootstrapProfile: TestOrgsOrdererGenesis
    BootstrapFile: /home/yulin/blockchain/fabric/Hyperledger/order/orderer.genesis.block

    # LocalMSPDir is where to find the private crypto material needed by the
    # orderer. It is set relative here as a default for dev environments but
    # should be changed to the real location in production.
    LocalMSPDir: ../fabricconfig/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/msp

    # LocalMSPID is the identity to register the local MSP material with the MSP
    # manager. IMPORTANT: The local MSP ID of an orderer needs to match the MSP
    # ID of one of the organizations defined in the orderer system channel's
    # /Channel/Orderer configuration. The sample organization defined in the
    # sample configuration provided has an MSP ID of "SampleOrg".
    LocalMSPID: OrdererMSP

    # Enable an HTTP service for Go "pprof" profiling as documented at:
    # https://golang.org/pkg/net/http/pprof
    Profile:
        Enabled: false
        Address: 0.0.0.0:6060

    # BCCSP configures the blockchain crypto service providers.
    BCCSP:
        # Default specifies the preferred blockchain crypto service provider
        # to use. If the preferred provider is not available, the software
        # based provider ("SW") will be used.
        # Valid providers are:
        #  - SW: a software based crypto provider
        #  - PKCS11: a CA hardware security module crypto provider.
        Default: SW

        # SW configures the software based blockchain crypto provider.
        SW:
            # TODO: The default Hash and Security level needs refactoring to be
            # fully configurable. Changing these defaults requires coordination
            # SHA2 is hardcoded in several places, not only BCCSP
            Hash: SHA2
            Security: 256
            # Location of key store. If this is unset, a location will be
            # chosen using: 'LocalMSPDir'/keystore
            FileKeyStore:
                KeyStore:

################################################################################
#
#   SECTION: File Ledger
#
#   - This section applies to the configuration of the file ledger.
#
################################################################################
FileLedger:

    # Location: The directory to store the blocks in.
    Location: /home/yulin/blockchain/fabric/Hyperledger/order/production/orderer

#RAMLedger:
    #HistorySize: 1000
################################################################################
#
#   Debug Configuration
#
#   - This controls the debugging options for the orderer
#
################################################################################
Debug:

    # BroadcastTraceDir when set will cause each request to the Broadcast service
    # for this orderer to be written to a file in this directory
    BroadcastTraceDir:

    # DeliverTraceDir when set will cause each request to the Deliver service
    # for this orderer to be written to a file in this directory
    DeliverTraceDir:

################################################################################
#
#   Metrics Configuration
#
#   - This configures metrics collection for the orderer
#
################################################################################
Metrics:
    # The metrics provider is one of statsd, prometheus, or disabled
    Provider: disabled

    # The statsd configuration
    Statsd:
      # network type: tcp or udp
      Network: udp

      # the statsd server address
      Address: 127.0.0.1:8125

      # The interval at which locally cached counters and gauges are pushed
      # to statsd; timings are pushed immediately
      WriteInterval: 30s

      # The prefix is prepended to all emitted statsd metrics
      Prefix:

要注意配置文件中的相关路径的设置。
在配置文件orderer.yaml所在的目录执行如下命令启动orderer:

$ orderer start
2021-02-09 17:14:14.942 CST [localconfig] completeInitialization -> INFO 001 General.Authentication.TimeWindow unset, setting to 15m0s
2021-02-09 17:14:14.943 CST [localconfig] completeInitialization -> INFO 002 Kafka.Retry.ShortInterval unset, setting to 1m0s
2021-02-09 17:14:14.943 CST [localconfig] completeInitialization -> INFO 003 Kafka.Retry.ShortTotal unset, setting to 10m0s
2021-02-09 17:14:14.943 CST [localconfig] completeInitialization -> INFO 004 Kafka.Retry.LongInterval unset, setting to 10m0s
2021-02-09 17:14:14.943 CST [localconfig] completeInitialization -> INFO 005 Kafka.Retry.LongTotal unset, setting to 12h0m0s
2021-02-09 17:14:14.943 CST [localconfig] completeInitialization -> INFO 006 Kafka.Retry.NetworkTimeouts.DialTimeout unset, setting to 30s
2021-02-09 17:14:14.943 CST [localconfig] completeInitialization -> INFO 007 Kafka.Retry.NetworkTimeouts.ReadTimeout unset, setting to 30s
2021-02-09 17:14:14.943 CST [localconfig] completeInitialization -> INFO 008 Kafka.Retry.NetworkTimeouts.WriteTimeout unset, setting to 30s
2021-02-09 17:14:14.943 CST [localconfig] completeInitialization -> INFO 009 Kafka.Retry.Metadata.RetryBackoff unset, setting to 250ms
2021-02-09 17:14:14.943 CST [localconfig] completeInitialization -> INFO 00a Kafka.Retry.Metadata.RetryMax unset, setting to 3
2021-02-09 17:14:14.943 CST [localconfig] completeInitialization -> INFO 00b Kafka.Retry.Producer.RetryBackoff unset, setting to 100ms
2021-02-09 17:14:14.943 CST [localconfig] completeInitialization -> INFO 00c Kafka.Retry.Producer.RetryMax unset, setting to 3
2021-02-09 17:14:14.943 CST [localconfig] completeInitialization -> INFO 00d Kafka.Retry.Consumer.RetryBackoff unset, setting to 2s
2021-02-09 17:14:14.943 CST [localconfig] completeInitialization -> INFO 00e Kafka.Version unset, setting to 0.10.2.0
2021-02-09 17:14:14.943 CST [orderer.common.server] prettyPrintStruct -> INFO 00f Orderer config values:
	General.ListenAddress = "127.0.0.1"
	General.ListenPort = 7050
	General.TLS.Enabled = false
	General.TLS.PrivateKey = "/home/yulin/blockchain/fabric/Hyperledger/fabricconfig/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/server.key"
	General.TLS.Certificate = "/home/yulin/blockchain/fabric/Hyperledger/fabricconfig/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/server.crt"
	General.TLS.RootCAs = [/home/yulin/blockchain/fabric/Hyperledger/fabricconfig/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/ca.crt]
	General.TLS.ClientAuthRequired = false
	General.TLS.ClientRootCAs = []
	General.TLS.TLSHandshakeTimeShift = 0s
	General.Cluster.ListenAddress = ""
	General.Cluster.ListenPort = 0
	General.Cluster.ServerCertificate = ""
	General.Cluster.ServerPrivateKey = ""
	General.Cluster.ClientCertificate = ""
	General.Cluster.ClientPrivateKey = ""
	General.Cluster.RootCAs = []
	General.Cluster.DialTimeout = 5s
	General.Cluster.RPCTimeout = 7s
	General.Cluster.ReplicationBufferSize = 20971520
	General.Cluster.ReplicationPullTimeout = 5s
	General.Cluster.ReplicationRetryTimeout = 5s
	General.Cluster.ReplicationBackgroundRefreshInterval = 5m0s
	General.Cluster.ReplicationMaxRetries = 12
	General.Cluster.SendBufferSize = 10
	General.Cluster.CertExpirationWarningThreshold = 168h0m0s
	General.Cluster.TLSHandshakeTimeShift = 0s
	General.Keepalive.ServerMinInterval = 0s
	General.Keepalive.ServerInterval = 0s
	General.Keepalive.ServerTimeout = 0s
	General.ConnectionTimeout = 0s
	General.GenesisMethod = ""
	General.GenesisFile = ""
	General.BootstrapMethod = "file"
	General.BootstrapFile = "/home/yulin/blockchain/fabric/Hyperledger/order/orderer.genesis.block"
	General.Profile.Enabled = false
	General.Profile.Address = "0.0.0.0:6060"
	General.LocalMSPDir = "/home/yulin/blockchain/fabric/Hyperledger/fabricconfig/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/msp"
	General.LocalMSPID = "OrdererMSP"
	General.BCCSP.Default = "SW"
	General.BCCSP.SW.Security = 256
	General.BCCSP.SW.Hash = "SHA2"
	General.BCCSP.SW.FileKeystore.KeyStorePath = ""
	General.Authentication.TimeWindow = 15m0s
	General.Authentication.NoExpirationChecks = false
	FileLedger.Location = "/home/yulin/blockchain/fabric/Hyperledger/order/production/orderer"
	FileLedger.Prefix = ""
	Kafka.Retry.ShortInterval = 1m0s
	Kafka.Retry.ShortTotal = 10m0s
	Kafka.Retry.LongInterval = 10m0s
	Kafka.Retry.LongTotal = 12h0m0s
	Kafka.Retry.NetworkTimeouts.DialTimeout = 30s
	Kafka.Retry.NetworkTimeouts.ReadTimeout = 30s
	Kafka.Retry.NetworkTimeouts.WriteTimeout = 30s
	Kafka.Retry.Metadata.RetryMax = 3
	Kafka.Retry.Metadata.RetryBackoff = 250ms
	Kafka.Retry.Producer.RetryMax = 3
	Kafka.Retry.Producer.RetryBackoff = 100ms
	Kafka.Retry.Consumer.RetryBackoff = 2s
	Kafka.Verbose = false
	Kafka.Version = 0.10.2.0
	Kafka.TLS.Enabled = false
	Kafka.TLS.PrivateKey = ""
	Kafka.TLS.Certificate = ""
	Kafka.TLS.RootCAs = []
	Kafka.TLS.ClientAuthRequired = false
	Kafka.TLS.ClientRootCAs = []
	Kafka.TLS.TLSHandshakeTimeShift = 0s
	Kafka.SASLPlain.Enabled = false
	Kafka.SASLPlain.User = ""
	Kafka.SASLPlain.Password = ""
	Kafka.Topic.ReplicationFactor = 0
	Debug.BroadcastTraceDir = ""
	Debug.DeliverTraceDir = ""
	Consensus = <nil>
	Operations.ListenAddress = ""
	Operations.TLS.Enabled = false
	Operations.TLS.PrivateKey = ""
	Operations.TLS.Certificate = ""
	Operations.TLS.RootCAs = []
	Operations.TLS.ClientAuthRequired = false
	Operations.TLS.ClientRootCAs = []
	Operations.TLS.TLSHandshakeTimeShift = 0s
	Metrics.Provider = "disabled"
	Metrics.Statsd.Network = "udp"
	Metrics.Statsd.Address = "127.0.0.1:8125"
	Metrics.Statsd.WriteInterval = 30s
	Metrics.Statsd.Prefix = ""
	ChannelParticipation.Enabled = false
	ChannelParticipation.MaxRequestBodySize = 0
	Admin.ListenAddress = ""
	Admin.TLS.Enabled = false
	Admin.TLS.PrivateKey = ""
	Admin.TLS.Certificate = ""
	Admin.TLS.RootCAs = []
	Admin.TLS.ClientAuthRequired = false
	Admin.TLS.ClientRootCAs = []
	Admin.TLS.TLSHandshakeTimeShift = 0s
2021-02-09 17:14:14.999 CST [blkstorage] NewProvider -> INFO 010 Creating new file ledger directory at /home/yulin/blockchain/fabric/Hyperledger/order/production/orderer/chains
2021-02-09 17:14:15.019 CST [orderer.common.server] Main -> INFO 011 Bootstrapping the system channel
2021-02-09 17:14:15.022 CST [blkstorage] newBlockfileMgr -> INFO 012 Getting block information from block storage
2021-02-09 17:14:15.041 CST [orderer.common.server] initializeBootstrapChannel -> INFO 013 Initialized the system channel 'mychannel' from bootstrap block
2021-02-09 17:14:15.045 CST [orderer.common.server] extractSystemChannel -> INFO 014 Found system channel config block, number: 0
2021-02-09 17:14:15.047 CST [orderer.common.server] selectClusterBootBlock -> INFO 015 Cluster boot block is bootstrap (genesis) block; Blocks Header.Number system-channel=0, bootstrap=0
2021-02-09 17:14:15.050 CST [orderer.common.server] Main -> INFO 016 Starting with system channel: mychannel, consensus type: solo
2021-02-09 17:14:15.050 CST [certmonitor] trackCertExpiration -> INFO 017 The enrollment certificate will expire on 2031-02-04 12:08:00 +0000 UTC
2021-02-09 17:14:15.058 CST [orderer.consensus.solo] HandleChain -> WARN 018 Use of the Solo orderer is deprecated and remains only for use in test environments but may be removed in the future.
2021-02-09 17:14:15.059 CST [orderer.commmon.multichannel] initSystemChannel -> INFO 019 Starting system channel 'mychannel' with genesis block hash f6355426e46d155a023ed5f077afe82f1b4d267b667df52e18409c753e209f91 and orderer type solo
2021-02-09 17:14:15.060 CST [orderer.common.server] Main -> INFO 01a Starting orderer:
 Version: 2.3.0
 Commit SHA: ec81f3e74
 Go version: go1.14.12
 OS/Arch: linux/amd64
2021-02-09 17:14:15.060 CST [orderer.common.server] Main -> INFO 01b Beginning to serve requests

4. Peer节点的启动

Peer模块是Fabric的核心节点,所有的交易数据经过Orderer排序打包之后由Peer模块存储在区块链中。所有的Chaincode也是由Peer模块打包并且激活的。Peer模块的配置信息同意由环境变量和配置文件组成,本例中采用配置文件的方式来配置peer节点的参数。先创建一个Peer文件夹。将fabric-samples里面的模板配置文件core.yaml到Peer文件夹下面,对其稍作修改即可使用。
修改后Peer模块配置文件中变化的内容如下所示:

# Copyright IBM Corp. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
#

###############################################################################
#
#    Peer section
#
###############################################################################
peer:

    # The peer id provides a name for this peer instance and is used when
    # naming docker resources.
    id: peer0.org1.emanple.com

    # The networkId allows for logical separation of networks and is used when
    # naming docker resources.
    networkId: dev

    # The Address at local network interface this Peer will listen on.
    # By default, it will listen on all network interfaces
    listenAddress: 0.0.0.0:7051

    # The endpoint this peer uses to listen for inbound chaincode connections.
    # If this is commented-out, the listen address is selected to be
    # the peer's address (see below) with port 7052
    chaincodeListenAddress: 0.0.0.0:7052

    # The endpoint the chaincode for this peer uses to connect to the peer.
    # If this is not specified, the chaincodeListenAddress address is selected.
    # And if chaincodeListenAddress is not specified, address is selected from
    # peer address (see below). If specified peer address is invalid then it
    # will fallback to the auto detected IP (local IP) regardless of the peer
    # addressAutoDetect value.
    # chaincodeAddress: 0.0.0.0:7052

    # When used as peer config, this represents the endpoint to other peers
    # in the same organization. For peers in other organization, see
    # gossip.externalEndpoint for more info.
    # When used as CLI config, this means the peer's endpoint to interact with
    address: peer0.org1.example.com:7051

    # Whether the Peer should programmatically determine its address
    # This case is useful for docker containers.
    # When set to true, will override peer address.
    addressAutoDetect: false

    # Gossip related configuration
    gossip:
        # Bootstrap set to initialize gossip with.
        # This is a list of other peers that this peer reaches out to at startup.
        # Important: The endpoints here have to be endpoints of peers in the same
        # organization, because the peer would refuse connecting to these endpoints
        # unless they are in the same organization as the peer.
        bootstrap: 127.0.0.1:7051

        # NOTE: orgLeader and useLeaderElection parameters are mutual exclusive.
        # Setting both to true would result in the termination of the peer
        # since this is undefined state. If the peers are configured with
        # useLeaderElection=false, make sure there is at least 1 peer in the
        # organization that its orgLeader is set to true.

        # Defines whenever peer will initialize dynamic algorithm for
        # "leader" selection, where leader is the peer to establish
        # connection with ordering service and use delivery protocol
        # to pull ledger blocks from ordering service.
        useLeaderElection: true
        # Statically defines peer to be an organization "leader",
        # where this means that current peer will maintain connection
        # with ordering service and disseminate block across peers in
        # its own organization. Multiple peers or all peers in an organization
        # may be configured as org leaders, so that they all pull
        # blocks directly from ordering service.
        orgLeader: false

        # Interval for membershipTracker polling
        membershipTrackerInterval: 5s

        # Overrides the endpoint that the peer publishes to peers
        # in its organization. For peers in foreign organizations
        # see 'externalEndpoint'
        endpoint:
        # Maximum count of blocks stored in memory
        maxBlockCountToStore: 100
        # Max time between consecutive message pushes(unit: millisecond)
        maxPropagationBurstLatency: 10ms
        # Max number of messages stored until a push is triggered to remote peers
        maxPropagationBurstSize: 10
        # Number of times a message is pushed to remote peers
        propagateIterations: 1
        # Number of peers selected to push messages to
        propagatePeerNum: 3
        # Determines frequency of pull phases(unit: second)
        # Must be greater than digestWaitTime + responseWaitTime
        pullInterval: 4s
        # Number of peers to pull from
        pullPeerNum: 3
        # Determines frequency of pulling state info messages from peers(unit: second)
        requestStateInfoInterval: 4s
        # Determines frequency of pushing state info messages to peers(unit: second)
        publishStateInfoInterval: 4s
        # Maximum time a stateInfo message is kept until expired
        stateInfoRetentionInterval:
        # Time from startup certificates are included in Alive messages(unit: second)
        publishCertPeriod: 10s
        # Should we skip verifying block messages or not (currently not in use)
        skipBlockVerification: false
        # Dial timeout(unit: second)
        dialTimeout: 3s
        # Connection timeout(unit: second)
        connTimeout: 2s
        # Buffer size of received messages
        recvBuffSize: 20
        # Buffer size of sending messages
        sendBuffSize: 200
        # Time to wait before pull engine processes incoming digests (unit: second)
        # Should be slightly smaller than requestWaitTime
        digestWaitTime: 1s
        # Time to wait before pull engine removes incoming nonce (unit: milliseconds)
        # Should be slightly bigger than digestWaitTime
        requestWaitTime: 1500ms
        # Time to wait before pull engine ends pull (unit: second)
        responseWaitTime: 2s
        # Alive check interval(unit: second)
        aliveTimeInterval: 5s
        # Alive expiration timeout(unit: second)
        aliveExpirationTimeout: 25s
        # Reconnect interval(unit: second)
        reconnectInterval: 25s
        # Max number of attempts to connect to a peer
        maxConnectionAttempts: 120
        # Message expiration factor for alive messages
        msgExpirationFactor: 20
        # This is an endpoint that is published to peers outside of the organization.
        # If this isn't set, the peer will not be known to other organizations.
        externalEndpoint: peer0.org1.example.com:7051
        # Leader election service configuration
        election:
            # Longest time peer waits for stable membership during leader election startup (unit: second)
            startupGracePeriod: 15s
            # Interval gossip membership samples to check its stability (unit: second)
            membershipSampleInterval: 1s
            # Time passes since last declaration message before peer decides to perform leader election (unit: second)
            leaderAliveThreshold: 10s
            # Time between peer sends propose message and declares itself as a leader (sends declaration message) (unit: second)
            leaderElectionDuration: 5s

        pvtData:
            pushAckTimeout: 3s
            maxPeerCount: 3

        # Gossip state transfer related configuration
        state:
            # indicates whenever state transfer is enabled or not
            # default value is true, i.e. state transfer is active
            # and takes care to sync up missing blocks allowing
            # lagging peer to catch up to speed with rest network
            enabled: false
            # checkInterval interval to check whether peer is lagging behind enough to
            # request blocks via state transfer from another peer.
            checkInterval: 10s
            # responseTimeout amount of time to wait for state transfer response from
            # other peers
            responseTimeout: 3s
            # batchSize the number of blocks to request via state transfer from another peer
            batchSize: 10
            # blockBufferSize reflects the size of the re-ordering buffer
            # which captures blocks and takes care to deliver them in order
            # down to the ledger layer. The actual buffer size is bounded between
            # 0 and 2*blockBufferSize, each channel maintains its own buffer
            blockBufferSize: 20
            # maxRetries maximum number of re-tries to ask
            # for single state transfer request
            maxRetries: 3

    # TLS Settings
    tls:
        # Require server-side TLS
        enabled:  false
        # Require client certificates / mutual TLS for inbound connections.
        # Note that clients that are not configured to use a certificate will
        # fail to connect to the peer.
        clientAuthRequired: false
        # X.509 certificate used for TLS server
        cert:
            file: ../fabricconfig/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/server.crt
        # Private key used for TLS server
        key:
            file: ../fabricconfig/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/server.key
        # rootcert.file represents the trusted root certificate chain used for verifying certificates
        # of other nodes during outbound connections.
        # It is not required to be set, but can be used to augment the set of TLS CA certificates
        # available from the MSPs of each channel’s configuration.
        rootcert:
            file: ../fabricconfig/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
        # If mutual TLS is enabled, clientRootCAs.files contains a list of additional root certificates
        # used for verifying certificates of client connections.
        # It augments the set of TLS CA certificates available from the MSPs of each channel’s configuration.
        # Minimally, set your organization's TLS CA root certificate so that the peer can receive join channel requests.

    fileSystemPath: /home/yulin/blockchain/fabric/Hyperledger/peer/production

    # BCCSP (Blockchain crypto provider): Select which crypto implementation or
    # library to use
    BCCSP:
        Default: SW
        # Settings for the SW crypto provider (i.e. when DEFAULT: SW)
        SW:
            # TODO: The default Hash and Security level needs refactoring to be
            # fully configurable. Changing these defaults requires coordination
            # SHA2 is hardcoded in several places, not only BCCSP
            Hash: SHA2
            Security: 256
            # Location of Key Store
            FileKeyStore:
                # If "", defaults to 'mspConfigPath'/keystore
                KeyStore:

    # Path on the file system where peer will find MSP local configurations
    mspConfigPath: ../fabricconfig/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/msp

    # Identifier of the local MSP
    # ----!!!!IMPORTANT!!!-!!!IMPORTANT!!!-!!!IMPORTANT!!!!----
    # Deployers need to change the value of the localMspId string.
    # In particular, the name of the local MSP ID of a peer needs
    # to match the name of one of the MSPs in each of the channel
    # that this peer is a member of. Otherwise this peer's messages
    # will not be identified as valid by other nodes.
    localMspId: Org1MSP

    profile:
        enabled:     false
        listenAddress: 0.0.0.0:6060

    # Handlers defines custom handlers that can filter and mutate
    # objects passing within the peer, such as:
    #   Auth filter - reject or forward proposals from clients
    #   Decorators  - append or mutate the chaincode input passed to the chaincode
    #   Endorsers   - Custom signing over proposal response payload and its mutation
    # Valid handler definition contains:
    #   - A name which is a factory method name defined in
    #     core/handlers/library/library.go for statically compiled handlers
    #   - library path to shared object binary for pluggable filters
    # Auth filters and decorators are chained and executed in the order that
    # they are defined. For example:
    # authFilters:
    #   -
    #     name: FilterOne
    #     library: /opt/lib/filter.so
    #   -
    #     name: FilterTwo
    # decorators:
    #   -
    #     name: DecoratorOne
    #   -
    #     name: DecoratorTwo
    #     library: /opt/lib/decorator.so
    # Endorsers are configured as a map that its keys are the endorsement system chaincodes that are being overridden.
    # Below is an example that overrides the default ESCC and uses an endorsement plugin that has the same functionality
    # as the default ESCC.
    # If the 'library' property is missing, the name is used as the constructor method in the builtin library similar
    # to auth filters and decorators.
    # endorsers:
    #   escc:
    #     name: DefaultESCC
    #     library: /etc/hyperledger/fabric/plugin/escc.so
    handlers:
        authFilters:
          -
            name: DefaultAuth
          -
            name: ExpirationCheck    # This filter checks identity x509 certificate expiration
        decorators:
          -
            name: DefaultDecorator

###############################################################################
#
#    VM section
#
###############################################################################
vm:

    # Endpoint of the vm management system.  For docker can be one of the following in general
    # unix:///var/run/docker.sock
    # http://localhost:2375
    # https://localhost:2376
    endpoint: unix:///var/run/docker.sock

    # settings for docker vms
    docker:
        tls:
            enabled: false
            ca:
                file: docker/ca.crt
            cert:
                file: docker/tls.crt
            key:
                file: docker/tls.key

        # Enables/disables the standard out/err from chaincode containers for
        # debugging purposes
        attachStdout: false

        # Parameters on creating docker container.
        # Container may be efficiently created using ipam & dns-server for cluster
        # NetworkMode - sets the networking mode for the container. Supported
        # standard values are: `host`(default),`bridge`,`ipvlan`,`none`.
        # Dns - a list of DNS servers for the container to use.
        # Note:  `Privileged` `Binds` `Links` and `PortBindings` properties of
        # Docker Host Config are not supported and will not be used if set.
        # LogConfig - sets the logging driver (Type) and related options
        # (Config) for Docker. For more info,
        # https://docs.docker.com/engine/admin/logging/overview/
        # Note: Set LogConfig using Environment Variables is not supported.
        hostConfig:
            NetworkMode: host
            Dns:
               # - 192.168.0.1
            LogConfig:
                Type: json-file
                Config:
                    max-size: "50m"
                    max-file: "5"
            Memory: 2147483648

###############################################################################
#
#    Chaincode section
#
###############################################################################
chaincode:

    # The id is used by the Chaincode stub to register the executing Chaincode
    # ID with the Peer and is generally supplied through ENV variables
    # the `path` form of ID is provided when installing the chaincode.
    # The `name` is used for all other requests and can be any string.
    id:
        path:
        name:

    # Generic builder environment, suitable for most chaincode types
    builder: $(DOCKER_NS)/fabric-ccenv:$(TWO_DIGIT_VERSION)

    # Enables/disables force pulling of the base docker images (listed below)
    # during user chaincode instantiation.
    # Useful when using moving image tags (such as :latest)
    pull: false

    golang:
        # golang will never need more than baseos
        runtime: $(DOCKER_NS)/fabric-baseos:$(TWO_DIGIT_VERSION)

        # whether or not golang chaincode should be linked dynamically
        dynamicLink: false

    java:
        # This is an image based on java:openjdk-8 with addition compiler
        # tools added for java shim layer packaging.
        # This image is packed with shim layer libraries that are necessary
        # for Java chaincode runtime.
        runtime: $(DOCKER_NS)/fabric-javaenv:$(TWO_DIGIT_VERSION)

    node:
        # This is an image based on node:$(NODE_VER)-alpine
        runtime: $(DOCKER_NS)/fabric-nodeenv:$(TWO_DIGIT_VERSION)

    # List of directories to treat as external builders and launchers for
    # chaincode. The external builder detection processing will iterate over the
    # builders in the order specified below.
    externalBuilders: []
        # - path: /path/to/directory
        #   name: descriptive-builder-name
        #   propagateEnvironment:
        #      - ENVVAR_NAME_TO_PROPAGATE_FROM_PEER
        #      - GOPROXY

    # The maximum duration to wait for the chaincode build and install process
    # to complete.
    installTimeout: 300s

    # Timeout duration for starting up a container and waiting for Register
    # to come through.
    startuptimeout: 300s

    # Timeout duration for Invoke and Init calls to prevent runaway.
    # This timeout is used by all chaincodes in all the channels, including
    # system chaincodes.
    # Note that during Invoke, if the image is not available (e.g. being
    # cleaned up when in development environment), the peer will automatically
    # build the image, which might take more time. In production environment,
    # the chaincode image is unlikely to be deleted, so the timeout could be
    # reduced accordingly.
    executetimeout: 30s

    # There are 2 modes: "dev" and "net".
    # In dev mode, user runs the chaincode after starting peer from
    # command line on local machine.
    # In net mode, peer will run chaincode in a docker container.
    mode: dev

    # keepalive in seconds. In situations where the communication goes through a
    # proxy that does not support keep-alive, this parameter will maintain connection
    # between peer and chaincode.
    # A value <= 0 turns keepalive off
    keepalive: 0

    # enabled system chaincodes
    system:
        _lifecycle: enable
        cscc: enable
        lscc: enable
        qscc: enable

    # Logging section for the chaincode container
    logging:
      # Default level for all loggers within the chaincode container
      level:  info
      # Override default level for the 'shim' logger
      shim:   warning
      # Format for the chaincode container logs
      format: '%{color}%{time:2006-01-02 15:04:05.000 MST} [%{module}] %{shortfunc} -> %{level:.4s} %{id:03x}%{color:reset} %{message}'

###############################################################################
#
#    Ledger section - ledger configuration encompasses both the blockchain
#    and the state
#
###############################################################################
ledger:

  blockchain:

  state:
    # stateDatabase - options are "goleveldb", "CouchDB"
    # goleveldb - default state database stored in goleveldb.
    # CouchDB - store state database in CouchDB
    stateDatabase: goleveldb
    # Limit on the number of records to return per query
    totalQueryLimit: 100000
    couchDBConfig:
       # It is recommended to run CouchDB on the same server as the peer, and
       # not map the CouchDB container port to a server port in docker-compose.
       # Otherwise proper security must be provided on the connection between
       # CouchDB client (on the peer) and server.
       couchDBAddress: 127.0.0.1:5984
       # This username must have read and write authority on CouchDB
       username:
       # The password is recommended to pass as an environment variable
       # during start up (eg CORE_LEDGER_STATE_COUCHDBCONFIG_PASSWORD).
       # If it is stored here, the file must be access control protected
       # to prevent unintended users from discovering the password.
       password:
       # Number of retries for CouchDB errors
       maxRetries: 3
       # Number of retries for CouchDB errors during peer startup.
       # The delay between retries doubles for each attempt.
       # Default of 10 retries results in 11 attempts over 2 minutes.
       maxRetriesOnStartup: 10
       # CouchDB request timeout (unit: duration, e.g. 20s)
       requestTimeout: 35s
       # Limit on the number of records per each CouchDB query
       # Note that chaincode queries are only bound by totalQueryLimit.
       # Internally the chaincode may execute multiple CouchDB queries,
       # each of size internalQueryLimit.
       internalQueryLimit: 1000
       # Limit on the number of records per CouchDB bulk update batch
       maxBatchUpdateSize: 1000
       # Warm indexes after every N blocks.
       # This option warms any indexes that have been
       # deployed to CouchDB after every N blocks.
       # A value of 1 will warm indexes after every block commit,
       # to ensure fast selector queries.
       # Increasing the value may improve write efficiency of peer and CouchDB,
       # but may degrade query response time.
       warmIndexesAfterNBlocks: 1
       # Create the _global_changes system database
       # This is optional.  Creating the global changes database will require
       # additional system resources to track changes and maintain the database
       createGlobalChangesDB: false
       # CacheSize denotes the maximum mega bytes (MB) to be allocated for the in-memory state
       # cache. Note that CacheSize needs to be a multiple of 32 MB. If it is not a multiple
       # of 32 MB, the peer would round the size to the next multiple of 32 MB.
       # To disable the cache, 0 MB needs to be assigned to the cacheSize.
       cacheSize: 64

  history:
    # enableHistoryDatabase - options are true or false
    # Indicates if the history of key updates should be stored.
    # All history 'index' will be stored in goleveldb, regardless if using
    # CouchDB or alternate database for the state.
    enableHistoryDatabase: true

###############################################################################
#
#    Metrics section
#
###############################################################################
metrics:
    # metrics provider is one of statsd, prometheus, or disabled
    provider: disabled

    # statsd configuration
    statsd:
        # network type: tcp or udp
        network: udp

        # statsd server address
        address: 127.0.0.1:8125

        # the interval at which locally cached counters and gauges are pushed
        # to statsd; timings are pushed immediately
        writeInterval: 10s

        # prefix is prepended to all emitted statsd metrics
        prefix:

在配置文件core.yaml所在文件夹中执行以下命令启动peer节点:

$ export set FABRIC_CFG_PATH=/~/blockchain/fabric/Hyperledger/peer
$ peer node start >> log_peer.log 2>&1 &

在log_peer.log文件中

2021-02-09 17:56:42.049 CST [nodeCmd] serve -> INFO 001 Starting peer:
 Version: 2.3.0
 Commit SHA: ec81f3e74
 Go version: go1.14.12
 OS/Arch: linux/amd64
 Chaincode:
  Base Docker Label: org.hyperledger.fabric
  Docker Namespace: hyperledger
2021-02-09 17:56:42.050 CST [peer] getLocalAddress -> INFO 002 Auto-detected peer address: 172.17.0.1:7051
2021-02-09 17:56:42.051 CST [peer] getLocalAddress -> INFO 003 Returning peer0.org1.example.com:7051
2021-02-09 17:56:42.051 CST [common.deliverevents] load -> WARN 004 `peer.authentication.timewindow` not set; defaulting to 15m0s
2021-02-09 17:56:42.331 CST [certmonitor] trackCertExpiration -> INFO 005 The enrollment certificate will expire on 2031-02-04 12:08:00 +0000 UTC
2021-02-09 17:56:42.337 CST [gossip.privdata] loadPrivDataConfig -> WARN 006 Configuration key peer.gossip.pvtData.reconcileSleepInterval isn't set, defaulting to 1m0s
2021-02-09 17:56:42.340 CST [gossip.privdata] loadPrivDataConfig -> WARN 007 Configuration key peer.gossip.pvtData.reconcileBatchSize isn't set, defaulting to 10
2021-02-09 17:56:42.341 CST [ledgermgmt] NewLedgerMgr -> INFO 008 Initializing LedgerMgr
2021-02-09 17:56:42.514 CST [leveldbhelper] openDBAndCheckFormat -> INFO 009 DB is empty Setting db format as 2.0
2021-02-09 17:56:42.522 CST [blkstorage] NewProvider -> INFO 00a Creating new file ledger directory at /home/yulin/blockchain/fabric/Hyperledger/peer/production/ledgersData/chains/chains
2021-02-09 17:56:42.590 CST [leveldbhelper] openDBAndCheckFormat -> INFO 00b DB is empty Setting db format as 2.0
2021-02-09 17:56:42.774 CST [leveldbhelper] openDBAndCheckFormat -> INFO 00c DB is empty Setting db format as 2.0
2021-02-09 17:56:42.786 CST [ledgermgmt] NewLedgerMgr -> INFO 00d Initialized LedgerMgr
2021-02-09 17:56:42.790 CST [gossip.service] loadGossipConfig -> WARN 00e Configuration key peer.gossip.pvtData.transientstoreMaxBlockRetention isn't set, defaulting to 1000
2021-02-09 17:56:42.799 CST [gossip.service] New -> INFO 00f Initialize gossip with endpoint peer0.org1.example.com:7051
2021-02-09 17:56:42.802 CST [gossip.gossip] New -> INFO 010 Creating gossip service with self membership of Endpoint: peer0.org1.example.com:7051, InternalEndpoint: peer0.org1.example.com:7051, PKI-ID: 848f9e371f1d4cd7521c1e3517cc8eec6ddc8f09602abc2ed9a630c4622d9ab6, Metadata: 
2021-02-09 17:56:42.803 CST [lifecycle] InitializeLocalChaincodes -> INFO 011 Initialized lifecycle cache with 0 already installed chaincodes
2021-02-09 17:56:42.807 CST [nodeCmd] computeChaincodeEndpoint -> INFO 012 Entering computeChaincodeEndpoint with peerHostname: peer0.org1.example.com
2021-02-09 17:56:42.807 CST [nodeCmd] computeChaincodeEndpoint -> INFO 013 Exit with ccEndpoint: peer0.org1.example.com:7052
2021-02-09 17:56:42.808 CST [sccapi] DeploySysCC -> INFO 014 deploying system chaincode 'lscc'
2021-02-09 17:56:42.813 CST [gossip.gossip] start -> INFO 015 Gossip instance peer0.org1.example.com:7051 started
2021-02-09 17:56:42.830 CST [sccapi] DeploySysCC -> INFO 016 deploying system chaincode 'cscc'
2021-02-09 17:56:42.830 CST [sccapi] DeploySysCC -> INFO 017 deploying system chaincode 'qscc'
2021-02-09 17:56:42.830 CST [sccapi] DeploySysCC -> INFO 018 deploying system chaincode '_lifecycle'
2021-02-09 17:56:42.830 CST [nodeCmd] serve -> INFO 019 Deployed system chaincodes
2021-02-09 17:56:42.830 CST [nodeCmd] serve -> INFO 01a Starting peer with ID=[peer0.org1.emanple.com], network ID=[dev], address=[peer0.org1.example.com:7051]
2021-02-09 17:56:42.830 CST [nodeCmd] serve -> INFO 01b Started peer with ID=[peer0.org1.emanple.com], network ID=[dev], address=[peer0.org1.example.com:7051]
2021-02-09 17:56:42.830 CST [kvledger] LoadPreResetHeight -> INFO 01c Loading prereset height from path [/home/yulin/blockchain/fabric/Hyperledger/peer/production/ledgersData/chains]
2021-02-09 17:56:42.830 CST [blkstorage] preResetHtFiles -> INFO 01d No active channels passed

5. 创建通道

启动完orderer和peer节点之后,现在可以创建通道了,本文均在peer文件夹下进行,创建通道的过程一共分为三个步骤:
第一步:创建通道。

$ export set CORE_PEER_LOCALMSPID="Org1MSP"
$ export set CORE_PEER_MSPCONFIGPATH=/home/yulin/blockchain/fabric/Hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
$ peer channel create -t 50s -o orderer.example.com:7050 -c mychannel -f ../order/mychannel.tx
2021-02-10 19:30:52.830 CST [channelCmd] InitCmdFactory -> INFO 001 Endorser and orderer connections initialized
2021-02-10 19:30:53.103 CST [cli.common] readBlock -> INFO 002 Received block: 0

遇到了错误:
2021-02-10 18:34:12.743 UTC [channelCmd] InitCmdFactory -> INFO 001 Endorser and orderer connections initialized
Error: got unexpected status: FORBIDDEN – config update for existing channel did not pass initial checks: implicit policy evaluation failed - 0 sub-policies were satisfied, but this policy requires 1 of the ‘Writers’ sub-policies to be satisfied: permission denied

解决办法:
原因就是创建创世块文件时channelID与创建通道文件channelID相同,故只需要在生成通道文件的时候修改。停止并删除容器,把容器挂载的卷也删除否则仍然存在错误,删除通过命令configtxgen 生成的 *.tx 文件,再通过命令configtxgen重新生成。

创建通道完成之后,会在执行命令额当前目录生成名为“mychannel.block”的通道初始块。
第二步:让已经运行的Peer模块加入通道。

$ export set CORE_PEER_LOCALMSPID="Org1MSP"
$ export set CORE_PEER_ADDRESS=peer0.org1.example.com:7051
$ export set CORE_PEER_MSPCONFIGPATH=/home/yulin/blockchain/fabric/Hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
$ peer channel join -b mychannel.block
2021-02-10 19:43:22.714 CST [channelCmd] InitCmdFactory -> INFO 001 Endorser and orderer connections initialized
2021-02-10 19:43:22.926 CST [channelCmd] executeJoin -> INFO 002 Successfully submitted proposal to join channel

第三步:更新锚节点。

$ peer channel update -o orderer.example.com:7050 -c mychannel -f ../order/Org1MSPanchors.tx
2021-02-10 19:46:05.061 CST [channelCmd] InitCmdFactory -> INFO 001 Endorser and orderer connections initialized
2021-02-10 19:46:05.150 CST [channelCmd] update -> INFO 002 Successfully submitted channel update

peer节点端:
【Hyperledger Fabric入门】(一) 快速运行一个简单的Fabric网络2_第1张图片

6. Chaincode的部署和调用

现在部署一个chaincode来测试Peer节点和Orderer节点的部署是否正确。这里采用fabric源码自带的例子来作为测试chaincode。
chaincode相关的测试一共有四个步骤:
第一步:部署chaincode代码。

$ peer chaincode install -n r_test_cc6 -v 2.3.0 -p /home/yulin/go/src/github.com/hyperledger/fabric-samples/chaincode/fabcar/go

在这里插入图片描述
第二步:实例化chaincode代码。

$ peer chaincode instantiate -o om:7050 -C mychannel -n r_test_cc6 -v 2.3.0 -c '{"Args":["init","a","100","b","200"]}' -P "OR ('Org1MSP.menber','Org2MSP.menber')"

第三步:通过chaincode写入数据。

$ peer chaincode invoke -o orderer.example.com:7050 -C mychannel -n r_test_cc6 -v 2.3.0 -c '{"Args":["invoke","a","b","1"]}'

第四步:通过chaincode查询数据。

peer chaincode query -C mychannel -n r_test_cc6 -v 2.3.0 -c '{"Args":["query","a"]}'

你可能感兴趣的:(区块链,区块链,hyperledger,fabric)