搭建一个Fabric

一.生成Fabric需要的证书文件
1. mkdir -p /opt/hyperledger/fabricconfig
2.生成配置文件crypto-config.yaml,放入上述文件夹中

OrdererOrgs:
  - Name: Orderer
    Domain: qklszzn.com
    Specs:
      - Hostname: orderer


PeerOrgs:
  - Name: Org1
    Domain: org1.qklszzn.com

    Template:
      Count: 3
    Users:
      Count: 3


  - Name: Org2
    Domain: org2.qklszzn.com
    Template:
      Count: 2
    Users:
      Count: 2


3.cd /opt/hyperledger/fabricconfig
cryptogen generate --config=crypto-config.yaml --output ./crypto-config #生成证书

二、配置域名
vim /etc/hosts
192.168.1.174 orderer.qklszzn.com
192.168.1.174 peer0.org1.qklszzn.com
192.168.1.174 peer1.org1.qklszzn.com
192.168.1.174 peer3.org1.qklszzn.com
192.168.1.174 peer0.org2.qklszzn.com
192.168.1.174 peer1.org2.qklszzn.com


三、创世块生成
账本第一个区块是个例外,该区块不存储交易数据而是存储配置信息。通常将账本的第一个区块成为创始块。configtxgen专门负责生成创始块和Channel
mkdir -p /opt/hyperledger/order/
将configtx.yaml放入其中

Profiles:
    TestTwoOrgsOrdererGenesis:
        Orderer:
            <<: *OrdererDefaults
            Organizations:
                - *OrdererOrg
        Consortiums:
          SampleConsortium:
            Organizations:
                - *Org1
                - *Org2
    TestTwoOrgsChannel:
        Consortium: SampleConsortium
        Application:
            <<: *ApplicationDefaults
            Organizations:
                - *Org1
                - *Org2
Organizations:
    - &OrdererOrg
        Name: OrdererOrg
        ID: OrdererMSP
        MSPDir: /opt/hyperledger/fabricconfig/crypto-config/ordererOrganizations/qklszzn.com/msp
    - &Org1
        Name: Org1MSP
        ID: Org1MSP
        MSPDir: /opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/msp
        AnchorPeers:
            - Host: peer0.org1.qklszzn.com
              Port: 7051
    - &Org2
        Name: Org2MSP
        ID: Org2MSP
        MSPDir: /opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org2.qklszzn.com/msp
        AnchorPeers:
            - Host: peer0.org2.qklszzn.com
              Port: 7051
Orderer: &OrdererDefaults
    OrdererType: solo
    Addresses:
        - orderer.qklszzn.com:7050
    BatchTimeout: 2s
    BatchSize:
        MaxMessageCount: 10
        AbsoluteMaxBytes: 98MB
        PreferredMaxBytes: 512KB
    Kafka:
        Brokers:
            - 127.0.0.1:9092
    Organizations:

Application: &ApplicationDefaults
    Organizations:

cd /opt/hyperledger/order
系统创始块的生成
configtxgen -profile TestTwoOrgsOrdererGenesis -outputBlock ./orderer.genesis.block
创建Channel初始块
configtxgen -profile TestTwoOrgsChannel -outputCreateChannelTx ./roberttestchannel.tx -channelID roberttestchannel
生成锚点更新文件
configtxgen -profile TestTwoOrgsChannel -outputAnchorPeersUpdate ./Org1MSPanchors.tx -channelID roberttestchannel -asOrg Org1MSP
configtxgen -profile TestTwoOrgsChannel -outputAnchorPeersUpdate ./Org2MSPanchors.tx -channelID roberttestchannel -asOrg Org2MSP

四、启动Order
cd /opt/hyperledger/order
将orderer.yaml放入其中

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

---
################################################################################
#
#   Orderer Configuration
#
#   - This controls the type and configuration of the orderer.
#
################################################################################
General:

    # Ledger Type: The ledger type to provide to the orderer.
    # Two non-production ledger types are provided for test purposes only:
    #  - ram: An in-memory ledger whose contents are lost on restart.
    #  - json: A simple file ledger that writes blocks to disk in JSON format.
    # Only one production ledger type is provided:
    #  - file: A production file-based ledger.
    LedgerType: file

    # Listen address: The IP on which to bind to listen.
    ListenAddress: 0.0.0.0

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

    # TLS: TLS settings for the GRPC server.
    TLS:
        Enabled: false
        PrivateKey: /opt/hyperledger/fabricconfig/crypto-config/ordererOrganizations/qklszzn.com/orderers/orderer.qklszzn.com/tls/server.key
        Certificate: /opt/hyperledger/fabricconfig/crypto-config/ordererOrganizations/qklszzn.com/orderers/orderer.qklszzn.com/tls/server.crt
        RootCAs:
          - /opt/hyperledger/fabricconfig/crypto-config/ordererOrganizations/qklszzn.com/orderers/orderer.qklszzn.com/tls/ca.crt
        ClientAuthRequired: false
        ClientRootCAs:

    # Keepalive settings for the GRPC server.
    Keepalive:
        # ServerMinInterval is the minimum permitted time between client pings.
        # If clients send pings more frequently, the server will
        # disconnect them.
        ServerMinInterval: 60s
        # ServerInterval is the time between pings to clients.
        ServerInterval: 7200s
        # ServerTimeout is the duration the server waits for a response from
        # a client before closing the connection.
        ServerTimeout: 20s

    # Log Level: The level at which to log. This accepts logging specifications
    # per: fabric/docs/Setup/logging-control.md
    LogLevel: debug

    # Log Format:  The format string to use when logging.  Especially useful to disable color logging
    LogFormat: '%{color}%{time:2006-01-02 15:04:05.000 MST} [%{module}] %{shortfunc} -> %{level:.4s} %{id:03x}%{color:reset} %{message}'

    # Genesis method: The method by which the genesis block for the orderer
    # system channel is specified. Available options are "provisional", "file":
    #  - provisional: Utilizes a genesis profile, specified by GenesisProfile,
    #                 to dynamically generate a new genesis block.
    #  - file: Uses the file provided by GenesisFile as the genesis block.
    GenesisMethod: file

    # Genesis profile: The profile to use to dynamically generate the genesis
    # block to use when initializing the orderer system channel and
    # GenesisMethod is set to "provisional". See the configtx.yaml file for the
    # descriptions of the available profiles. Ignored if GenesisMethod is set to
    # "file".
    GenesisProfile: TestOrgsOrdererGenesis

    # Genesis file: The file containing the genesis block to use when
    # initializing the orderer system channel and GenesisMethod is set to
    # "file". Ignored if GenesisMethod is set to "provisional".
    GenesisFile: /opt/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: /opt/hyperledger/fabricconfig/crypto-config/ordererOrganizations/qklszzn.com/orderers/orderer.qklszzn.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 "DEFAULT".
    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:

    # Authentication contains configuration parameters related to authenticating
    # client messages
    Authentication:
        # the acceptable difference between the current server time and the
        # client's time as specified in a client request message
        TimeWindow: 15m

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

    # Location: The directory to store the blocks in.
    # NOTE: If this is unset, a new temporary location will be chosen every time
    # the orderer is restarted, using the prefix specified by Prefix.
    Location: /opt/hyperledger/order/production/orderer

    # The prefix to use when generating a ledger directory in temporary space.
    # Otherwise, this value is ignored.
    Prefix: hyperledger-fabric-ordererledger

################################################################################
#
#   SECTION: RAM Ledger
#
#   - This section applies to the configuration of the RAM ledger.
#
################################################################################
RAMLedger:

    # History Size: The number of blocks that the RAM ledger is set to retain.
    # WARNING: Appending a block to the ledger might cause the oldest block in
    # the ledger to be dropped in order to limit the number total number blocks
    # to HistorySize. For example, if history size is 10, when appending block
    # 10, block 0 (the genesis block!) will be dropped to make room for block 10.
    HistorySize: 1000

################################################################################
#
#   SECTION: Kafka
#
#   - This section applies to the configuration of the Kafka-based orderer, and
#     its interaction with the Kafka cluster.
#
################################################################################
Kafka:

    # Retry: What do if a connection to the Kafka cluster cannot be established,
    # or if a metadata request to the Kafka cluster needs to be repeated.
    Retry:
        # When a new channel is created, or when an existing channel is reloaded
        # (in case of a just-restarted orderer), the orderer interacts with the
        # Kafka cluster in the following ways:
        # 1. It creates a Kafka producer (writer) for the Kafka partition that
        # corresponds to the channel.
        # 2. It uses that producer to post a no-op CONNECT message to that
        # partition
        # 3. It creates a Kafka consumer (reader) for that partition.
        # If any of these steps fail, they will be re-attempted every
        # <ShortInterval> for a total of <ShortTotal>, and then every
        # <LongInterval> for a total of <LongTotal> until they succeed.
        # Note that the orderer will be unable to write to or read from a
        # channel until all of the steps above have been completed successfully.
        ShortInterval: 5s
        ShortTotal: 10m
        LongInterval: 5m
        LongTotal: 12h
        # Affects the socket timeouts when waiting for an initial connection, a
        # response, or a transmission. See Config.Net for more info:
        # https://godoc.org/github.com/Shopify/sarama#Config
        NetworkTimeouts:
            DialTimeout: 10s
            ReadTimeout: 10s
            WriteTimeout: 10s
        # Affects the metadata requests when the Kafka cluster is in the middle
        # of a leader election.See Config.Metadata for more info:
        # https://godoc.org/github.com/Shopify/sarama#Config
        Metadata:
            RetryBackoff: 250ms
            RetryMax: 3
        # What to do if posting a message to the Kafka cluster fails. See
        # Config.Producer for more info:
        # https://godoc.org/github.com/Shopify/sarama#Config
        Producer:
            RetryBackoff: 100ms
            RetryMax: 3
        # What to do if reading from the Kafka cluster fails. See
        # Config.Consumer for more info:
        # https://godoc.org/github.com/Shopify/sarama#Config
        Consumer:
            RetryBackoff: 2s

    # Verbose: Enable logging for interactions with the Kafka cluster.
    Verbose: false

    # TLS: TLS settings for the orderer's connection to the Kafka cluster.
    TLS:

      # Enabled: Use TLS when connecting to the Kafka cluster.
      Enabled: false

      # PrivateKey: PEM-encoded private key the orderer will use for
      # authentication.
      PrivateKey:
        # As an alternative to specifying the PrivateKey here, uncomment the
        # following "File" key and specify the file name from which to load the
        # value of PrivateKey.
        #File: path/to/PrivateKey

      # Certificate: PEM-encoded signed public key certificate the orderer will
      # use for authentication.
      Certificate:
        # As an alternative to specifying the Certificate here, uncomment the
        # following "File" key and specify the file name from which to load the
        # value of Certificate.
        #File: path/to/Certificate

      # RootCAs: PEM-encoded trusted root certificates used to validate
      # certificates from the Kafka cluster.
      RootCAs:
        # As an alternative to specifying the RootCAs here, uncomment the
        # following "File" key and specify the file name from which to load the
        # value of RootCAs.
        #File: path/to/RootCAs

    # Kafka protocol version used to communicate with the Kafka cluster brokers
    # (defaults to 0.10.2.0 if not specified)
    Version:

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


在此目录下,orderer start

五、启动Peer
mkdir -p /opt/hyperledger/peer/
cd /opt/hyperledger/peer/
将core.yaml放入其中

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

###############################################################################
#
#    LOGGING section
#
###############################################################################
logging:

    # Default logging levels are specified here.

    # Valid logging levels are case-insensitive strings chosen from

    #     CRITICAL | ERROR | WARNING | NOTICE | INFO | DEBUG

    # The overall default logging level can be specified in various ways,
    # listed below from strongest to weakest:
    #
    # 1. The --logging-level=<level> command line option overrides all other
    #    default specifications.
    #
    # 2. The environment variable CORE_LOGGING_LEVEL otherwise applies to
    #    all peer commands if defined as a non-empty string.
    #
    # 3. The value of `level` that directly follows in this file.
    #
    # If no overall default level is provided via any of the above methods,
    # the peer will default to INFO (the value of defaultLevel in
    # common/flogging/logging.go)

    # Default for all modules running within the scope of a peer.
    # Note: this value is only used when --logging-level or CORE_LOGGING_LEVEL
    #       are not set
    peer:       debug

    # The overall default values mentioned above can be overridden for the
    # specific components listed in the override section below.

    # Override levels for various peer modules. These levels will be
    # applied once the peer has completely started. They are applied at this
    # time in order to be sure every logger has been registered with the
    # logging package.
    # Note: the modules listed below are the only acceptable modules at this
    #       time.
    cauthdsl:   warning
    gossip:     warning
    grpc:       error
    ledger:     info
    msp:        warning
    policies:   warning
    # Message format for the peer logs
    format: '%{color}%{time:2006-01-02 15:04:05.000 MST} [%{module}] %{shortfunc} -> %{level:.4s} %{id:03x}%{color:reset} %{message}'

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

    # The Peer id is used for identifying this Peer instance.
    id: peer0.org1.qklszzn.com

    # The networkId allows for logical seperation of networks
    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 listenAddress.
    # 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.qklszzn.com:7051

    # Whether the Peer should programmatically determine its address
    # This case is useful for docker containers.
    addressAutoDetect: false

    # Setting for runtime.GOMAXPROCS(n). If n < 1, it does not change the
    # current setting
    gomaxprocs: -1

    # Keepalive settings for peer server and clients
    keepalive:
        # MinInterval is the minimum permitted time between client pings.
        # If clients send pings more frequently, the peer server will
        # disconnect them
        minInterval: 60s
        # Client keepalive settings for communicating with other peer nodes
        client:
            # Interval is the time between pings to peer nodes.  This must
            # greater than or equal to the minInterval specified by peer
            # nodes
            interval: 60s
            # Timeout is the duration the client waits for a response from
            # peer nodes before closing the connection
            timeout: 20s
        # DeliveryClient keepalive settings for communication with ordering
        # nodes.
        deliveryClient:
            # Interval is the time between pings to ordering nodes.  This must
            # greater than or equal to the minInterval specified by ordering
            # nodes.
            interval: 60s
            # Timeout is the duration the client waits for a response from
            # ordering nodes before closing the connection
            timeout: 20s


    # 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. It is recommended to
        # use leader election for large networks of peers.
        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
        orgLeader: false

        # 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)
        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)
        digestWaitTime: 1s
        # Time to wait before pull engine removes incoming nonce (unit: second)
        requestWaitTime: 1s
        # 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
        # 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.qklszzn.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:
            # pullRetryThreshold determines the maximum duration of time private data corresponding for a given block
            # would be attempted to be pulled from peers until the block would be committed without the private data
            # pullRetryThreshold: 60s
            # As private data enters the transient store, it is associated with the peer's ledger's height at that time.
            # transientstoreMaxBlockRetention defines the maximum difference between the current ledger's height upon commit,
            # and the private data residing inside the transient store that is guaranteed not to be purged.
            # Private data is purged from the transient store when blocks with sequences that are multiples
            # of transientstoreMaxBlockRetention are committed.
            # transientstoreMaxBlockRetention: 1000
            # pushAckTimeout is the maximum time to wait for an acknowledgement from each peer
            # at private data push at endorsement time.
            # pushAckTimeout: 3s
            maxPeers: 3
            minAck: 3

    # EventHub related configuration
    events:
        # The address that the Event service will be enabled on the peer
        address: 0.0.0.0:7053

        # total number of events that could be buffered without blocking send
        buffersize: 100

        # timeout duration for producer to send an event.
        # if < 0, if buffer full, unblocks immediately and not send
        # if 0, if buffer full, will block and guarantee the event will be sent out
        # if > 0, if buffer full, blocks till timeout
        timeout: 10ms

        # timewindow is the acceptable difference between the peer's current
        # time and the client's time as specified in a registration event
        timewindow: 15m

        # Keepalive settings for peer server and clients
        # keepalive:
        #     # MinInterval is the minimum permitted time in seconds which clients
        #     # can send keepalive pings.  If clients send pings more frequently,
        #     # the events server will disconnect them
        #     minInterval: 60s

    # TLS Settings
    # Note that peer-chaincode connections through chaincodeListenAddress is
    # not mutual TLS auth. See comments on chaincodeListenAddress for more info
    tls:
        # Require server-side TLS
        enabled:  false
        # Require client certificates / mutual TLS.
        # 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: /opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/peers/peer0.org1.qklszzn.com/tls/server.crt
        # Private key used for TLS server (and client if clientAuthEnabled
        # is set to true
        key:
            file: /opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/peers/peer0.org1.qklszzn.com/tls/server.key
        # Trusted root certificate chain for tls.cert
        rootcert:
            file: /opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/peers/peer0.org1.qklszzn.com/tls/ca.crt
        serverhostoverride:
        # Set of root certificate authorities used to verify client certificates
        # clientRootCAs:
        #     files:
        #       - tls/ca.crt
        # # Private key used for TLS when making client connections.  If
        # # not set, peer.tls.key.file will be used instead
        # clientKey:
        #     file:
        # # X.509 certificate used for TLS when making client connections.
        # # If not set, peer.tls.cert.file will be used instead
        # clientCert:
        #     file:

    # Authentication contains configuration parameters related to authenticating
    # client messages
    authentication:
    #     # the acceptable difference between the current server time and the
    #     # client's time as specified in a client request message
        timewindow: 15m

    # Path on the file system where peer will store data (eg ledger). This
    # location must be access control protected to prevent unintended
    # modification that might corrupt the peer operations.
    fileSystemPath: /opt/hyperledger/peer/production

    # BCCSP (Blockchain crypto provider): Select which crypto implementation or
    # library to use
    BCCSP:
        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
                # TODO: Ensure this is read with fabric/core/config.GetPath() once ready
                KeyStore:

    # Path on the file system where peer will find MSP local configurations
    mspConfigPath: /opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/peers/peer0.org1.qklszzn.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

    # Delivery service related config
    # deliveryclient:
    #     # It sets the total time the delivery service may spend in reconnection
    #     # attempts until its retry logic gives up and returns an error
    #     reconnectTotalTimeThreshold: 3600s

    # Type for the local MSP - by default it's of type bccsp
    # localMspType: bccsp

    # Used with Go profiling tools only in none production environment. In
    # production, it should be disabled (eg enabled: false)
    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
    # 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
    handlers:
        authFilters:
          -
            name: DefaultAuth
        decorators:
          -
            name: DefaultDecorator

    # Number of goroutines that will execute transaction validation in parallel.
    # By default, the peer chooses the number of CPUs on the machine. Set this
    # variable to override that choice.
    # NOTE: overriding this value might negatively influence the performance of
    # the peer so please change this value only if you know what you're doing
    # validatorPoolSize:

###############################################################################
#
#    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:
    peerAddress:
    # 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:$(ARCH)-$(PROJECT_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: $(BASE_DOCKER_NS)/fabric-baseos:$(ARCH)-$(BASE_VERSION)

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

    car:
        # car may need more facilities (JVM, etc) in the future as the catalog
        # of platforms are expanded.  For now, we can just use baseos
        runtime: $(BASE_DOCKER_NS)/fabric-baseos:$(ARCH)-$(BASE_VERSION)

    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.
        Dockerfile:  |
            from $(DOCKER_NS)/fabric-javaenv:$(ARCH)-$(PROJECT_VERSION)

    node:
        # need node.js engine at runtime, currently available in baseimage
        # but not in baseos
        runtime: $(BASE_DOCKER_NS)/fabric-baseimage:$(ARCH)-$(BASE_VERSION)

    # Timeout duration for starting up a container and waiting for Register
    # to come through. 1sec should be plenty for chaincode unit tests
    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: net

    # keepalive in seconds. In situations where the communiction 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

    # system chaincodes whitelist. To add system chaincode "myscc" to the
    # whitelist, add "myscc: enable" to the list below, and register in
    # chaincode/importsysccs.go
    system:
        cscc: enable
        lscc: enable
        escc: enable
        vscc: enable
        qscc: enable
        rscc: disable

    # System chaincode plugins: in addition to being imported and compiled
    # into fabric through core/chaincode/importsysccs.go, system chaincodes
    # can also be loaded as shared objects compiled as Go plugins.
    # See examples/plugins/scc for an example.
    # Like regular system chaincodes, plugins must also be white listed in the
    # chaincode.system section above.
    # systemPlugins:
      # example configuration:
      # - enabled: true
      #   name: myscc
      #   path: /opt/lib/myscc.so
      #   invokableExternal: true
      #   invokableCC2CC: true

    # Logging section for the chaincode container
    logging:
      # Default level for all loggers within the chaincode container
      level:  info
      # Override default level for the 'shim' module
      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 encompases 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
    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 LEDGER_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
       maxRetriesOnStartup: 10
       # CouchDB request timeout (unit: duration, e.g. 20s)
       requestTimeout: 35s
       # Limit on the number of records to return per query
       queryLimit: 10000
       # 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

  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:
#         # enable or disable metrics server
#         enabled: false

#         # when enable metrics server, must specific metrics reporter type
#         # currently supported type: "statsd","prom"
#         reporter: statsd

#         # determines frequency of report metrics(unit: second)
#         interval: 1s

#         statsdReporter:

#               # statsd server address to connect
#               address: 0.0.0.0:8125

#               # determines frequency of push metrics to statsd server(unit: second)
#               flushInterval: 2s

#               # max size bytes for each push metrics request
#               # intranet recommend 1432 and internet recommend 512
#               flushBytes: 1432

#         promReporter:

#               # prometheus http server listen address for pull metrics
#               listenAddress: 0.0.0.0:8080


在此目录下,
export set FABRIC_CFG_PATH=/opt/hyperledger/peer
peer node start >> log_peer.log 2>&1 &


六,创建通道
1.创建通道
cd /opt/hyperledger/order
export set CORE_PEER_LOCALMSPID=Org1MSP
export set CORE_PEER_MSPCONFIGPATH=/opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/users/Admin@org1.qklszzn.com/msp
peer channel create -t 50 -o orderer.qklszzn.com:7050 -c roberttestchannel -f /opt/hyperledger/order/roberttestchannel.tx #如果已经创建过,可以直接删除本目录下的production文件夹
2.让已经运行的peer模块加入通道
export set CORE_PEER_LOCALMSPID=Org1MSP
export set CORE_PEER_ADDRESS=peer0.org1.qklszzn.com:7051
export set CORE_PEER_MSPCONFIGPATH=/opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/users/Admin@org1.qklszzn.com/msp
peer channel join -b /opt/hyperledger/order/roberttestchannel.block

#peer channel list 查看运行的peer加入的通道

3. 更新锚节点
export set CORE_PEER_LOCALMSPID=Org1MSP
export set CORE_PEER_ADDRESS=peer0.org1.qklszzn.com:7051
export set CORE_PEER_MSPCONFIGPATH=/opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/users/Admin@org1.qklszzn.com/msp
peer channel update -o orderer.qklszzn.com:7050 -c roberttestchannel -f /opt/hyperledger/order/Org1MSPanchors.tx

七、链代码
1.部署链代码
export set CORE_PEER_LOCALMSPID=Org1MSP
export set CORE_PEER_ADDRESS=peer0.org1.qklszzn.com:7051
export set CORE_PEER_MSPCONFIGPATH=/opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/users/Admin@org1.qklszzn.com/msp
#第一次部署要先切换路径 cd /opt/hyperledger/peer/production/chaincodes
peer chaincode install -n r_test_cc6 -v 1.0 -p github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02 
2.实例化Chaincode
export set CORE_PEER_LOCALMSPID=Org1MSP
export set CORE_PEER_ADDRESS=peer0.org1.qklszzn.com:7051
export set CORE_PEER_MSPCONFIGPATH=/opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/users/Admin@org1.qklszzn.com/msp 
peer chaincode instantiate -o orderer.qklszzn.com:7050 -C roberttestchannel -n r_test_cc6 -v 1.0 -c '{"Args":["init","a","100","b","200"]}' -P "OR ('Org1MSP.member','Org2MSP.member')" #如果失败改core.yaml中chaincode mode改dev为net,dev模式不可执行此操作
3.写入数据
export set CORE_PEER_LOCALMSPID=Org1MSP
export set CORE_PEER_ADDRESS=peer0.org1.qklszzn.com:7051
export set CORE_PEER_MSPCONFIGPATH=/opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/users/Admin@org1.qklszzn.com/msp
peer chaincode invoke -o orderer.qklszzn.com:7050 -C roberttestchannel -n r_test_cc6 -c '{"Args":["invoke","a","b","1"]}'
4.查询
export set CORE_PEER_LOCALMSPID=Org1MSP
export set CORE_PEER_ADDRESS=peer0.org1.qklszzn.com:7051
export set CORE_PEER_MSPCONFIGPATH=/opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/users/Admin@org1.qklszzn.com/msp
peer chaincode query -C roberttestchannel -n r_test_cc6 -c '{"Args":["query","a"]}'

5.在容器之外运行链代码
a.执行上述1,2,两步。注意此时mode为net
b.改core.yaml中mode为dev,重启peer
c.运行
export set CORE_PEER_ADDRESS=peer0.org1.qklszzn.com:7051
export set CORE_CHAINCODE_ID_NAME=r_test_cc6:1.0
export set CORE_CHAINCODE_LOGGING_LEVEL=debug
export set CORE_CHAINCODE_LOGGING_SHIM=debug
go build simplechaincode.go
./chaincode_example02 -peer.address=peer0.org1.qklszzn.com:7052
d.调用
export set CORE_PEER_LOCALMSPID=Org1MSP
export set CORE_PEER_ADDRESS=peer0.org1.qklszzn.com:7051
export set CORE_PEER_MSPCONFIGPATH=/opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/users/Admin@org1.qklszzn.com/msp
peer chaincode query -C roberttestchannel -n r_test_cc6 -c '{"Args":["query","a"]}'

Fabric-ca


1. 初始化
fabric-ca-server init -b admin:adminpw 初始化服务器
2. 启动
fabric-ca-server start -H /opt/hyperledger/fabric-ca-server/ --boot admin:adminpw  

3.客户端
应该需要注意版本,不确定是否需要和Fabric版本号一致
a.登记账号
fabric-ca-client enroll -u http://admin:adminpw@localhost:7054 #管理员账号,默认配置文件在/home/dev/.fabric-ca-client/
b.注册新账号
fabric-ca-client register --id.name peer2 --id.type peer --id.affiliation org1.department1 --id.secret peer2wd -u http://localhost:7054

b.载入账号信息
fabric-ca-client enroll -M fabric-test2/msp -u http://peer2:peer2wd@localhost:7054 #相对路径会放到/home/dev/.fabric-ca-client/下
c.获取CA服务器的证书
fabric-ca-client getcacert -u http://localhost:7054 -M fabric-test2/msp

4.绑定fabric-ca-server到现有组织
在server端配置文件fabric-ca-server-config.yaml中,修改如下
ca:
  name: ca-org1
  keyfile: /opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/ca/4b8bd336425aa326d300ee953b38cdf720fbfd2757cac5dff0f9b971d00c560c_sk
  certfile: /opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/ca/ca.org1.qklszzn.com-cert.pem
  chainfile: ca-chain.pem
注:如果在配置路径中 *_sk文件有多个,则选用最后生成的那个文件
6.通过客户端从已绑定的fabric-ca-server中生成账号
a.环境
mkdir -p /opt/hyperledger/fabric-client
export FABRIC_CA_CLIENT_HOME=/opt/hyperledger/fabric-client
b.获取管理员的证书文件
fabric-ca-client enroll -u http://admin:adminpw@localhost:7054 -M /opt/hyperledger/fabric-client/
c.注册账号
fabric-ca-client register --id.name usertest --id.type user --id.affiliation org1.department1 --id.secret user2wd -u http://localhost:7054
d.载入账号,将上一步注册的账号usertest加载到本地,需要首先在本地创建要给目录用来存放从服务器下载的证书,目录可以是任何目录。
mkdir -p /opt/hyperledger/qklszznuser
fabric-ca-client enroll -u http://usertest:user2wd@localhost:7054 -M /opt/hyperledger/qklszznuser/msp
e.复制管理员签名和公用TLS证书文件。
mkdir -p /opt/hyperledger/qklszznuser/msp/admincerts
进入上述目录
cp /opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/users/Admin@org1.qklszzn.com/msp/signcerts/* .

mkdir -p /opt/hyperledger/qklszznuser/tls
进入上述目录
cp /opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/peers/peer0.org1.qklszzn.com/tls/* .

调试chaincode两种方式
1.docker外运行
2.在IDE中调试

 

Fabric2.1部署链码

第一步链码
go mod init
go mod tidy
go mod vendor

第二步
cd /opt/hyperledger
export set FABRIC_CFG_PATH=/opt/hyperledger/peer
peer lifecycle chaincode package fabcar1.tar.gz --path /home/dev/go/src/myp/my02 --lang golang --label fabcar1_1

第三步
export set CORE_PEER_LOCALMSPID=Org1MSP
export set CORE_PEER_MSPCONFIGPATH=/opt/hyperledger/fabricconfig/crypto-config/peerOrganizations/org1.qklszzn.com/users/Admin@org1.qklszzn.com/msp
export set CORE_PEER_ADDRESS=peer0.org1.qklszzn.com:7051

peer lifecycle chaincode install fabcar1.tar.gz
peer lifecycle chaincode queryinstalled 查询确认一下

第四步
export CC_PACKAGE_ID=fabcar1_1:473a4c1e9a41f78575817e9b8da796be244e74039f6af0bb00f8e3b8a14e7327

peer lifecycle chaincode approveformyorg -o orderer.qklszzn.com:7050 --channelID roberttestchannel --init-required --name fabcar2 --version 1.0 --package-id $CC_PACKAGE_ID --sequence 1 
查询确认
peer lifecycle chaincode checkcommitreadiness --channelID roberttestchannel --init-required --name fabcar2 --version 1.0 --sequence 1 
第五步
peer lifecycle chaincode commit -o orderer.qklszzn.com:7050 --channelID roberttestchannel --init-required --name fabcar2 --version 1.0 --sequence 1  --peerAddresses peer0.org1.qklszzn.com:7051
查询

peer lifecycle chaincode querycommitted --channelID roberttestchannel
peer lifecycle chaincode querycommitted --channelID roberttestchannel --name fabcar2 

第六步

peer chaincode invoke -o orderer.qklszzn.com:7050 --isInit  -C roberttestchannel -n fabcar2 --peerAddresses peer0.org1.qklszzn.com:7051   -c '{"Args":["Init","a","100","b","100"]}' --waitForEvent
执行不了,改core.yaml中 addressAutoDetect: true

查询
peer chaincode query -C roberttestchannel -n fabcar2 -c '{"Args":["query","a"]}'
执行
peer chaincode invoke -o orderer.qklszzn.com:7050 -C roberttestchannel -n fabcar2 -c '{"Args":["invoke","a","b","1"]}'

 

升级链码

流程和上述过程唯一不同的是第四步version,sequence, package-id变化,注意升级链码也需要执行init函数

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值