目录
- 一、准备peer1
- 1.1、注册peer1
- 1.2、登记peer1
- 1.3、登记peer1的tls
- 二、启动peer1
- 三、添加peer1到应用通道
- 四、链码安装和调用
书接上回,在 Fabric二进制建链的基础上,继续通过二进制命令行的方式,添加一个新的对等节点peer1。
一、准备peer1
新增peer1的目录:
mkdir -p ~/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com
1.1、注册peer1
注册新对等节点peer1:
fabric-ca-client register --caname ca-org1 --id.name peer1 --id.secret peer1pw --id.type peer --tls.certfiles /home/songzehao/fabric/ca-cert.pem
日志:
2023/11/01 13:58:50 [INFO] Configuration file location: /home/songzehao/fabric/fabric-ca-client/fabric-ca-client-config.yaml
2023/11/01 13:58:50 [INFO] TLS Enabled
2023/11/01 13:58:50 [INFO] TLS Enabled
Password: peer1pw
1.2、登记peer1
登记新对等节点peer1:
fabric-ca-client enroll -u https://peer1:peer1pw@192.168.3.128:7054 --caname ca-org1 -M /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/msp --tls.certfiles /home/songzehao/fabric/ca-cert.pem
为peer1拷贝msp配置:
cp /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/msp/config.yaml /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/msp/config.yaml
日志:
2023/11/01 13:59:17 [INFO] TLS Enabled
2023/11/01 13:59:17 [INFO] generating key: &{A:ecdsa S:256}
2023/11/01 13:59:17 [INFO] encoded CSR
2023/11/01 13:59:17 [INFO] Stored client certificate at /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/msp/signcerts/cert.pem
2023/11/01 13:59:17 [INFO] Stored root CA certificate at /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/msp/cacerts/192-168-3-128-7054-ca-org1.pem
2023/11/01 13:59:17 [INFO] Stored Issuer public key at /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/msp/IssuerPublicKey
2023/11/01 13:59:17 [INFO] Stored Issuer revocation public key at /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/msp/IssuerRevocationPublicKey
1.3、登记peer1的tls
登记peer1的tls:
fabric-ca-client enroll -u https://peer1:peer1pw@192.168.3.128:7054 --caname ca-org1 -M /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/tls --enrollment.profile tls --csr.hosts 192.168.3.128 --tls.certfiles /home/songzehao/fabric/ca-cert.pem
为方便查看名称,重命名tls相关文件名:
cp /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/tls/tlscacerts/* /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/tls/ca.crt
cp /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/tls/signcerts/* /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/tls/server.crt
cp /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/tls/keystore/* /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/tls/server.key
日志:
2023/11/01 13:59:50 [INFO] TLS Enabled
2023/11/01 13:59:50 [INFO] generating key: &{A:ecdsa S:256}
2023/11/01 13:59:50 [INFO] encoded CSR
2023/11/01 13:59:50 [INFO] Stored client certificate at /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/tls/signcerts/cert.pem
2023/11/01 13:59:50 [INFO] Stored TLS root CA certificate at /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/tls/tlscacerts/tls-192-168-3-128-7054-ca-org1.pem
2023/11/01 13:59:50 [INFO] Stored Issuer public key at /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/tls/IssuerPublicKey
2023/11/01 13:59:50 [INFO] Stored Issuer revocation public key at /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/tls/IssuerRevocationPublicKey
二、启动peer1
更改peer1节点的配置文件。最终的core.yaml:
# 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: peer1.org1.example.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 interfaceslistenAddress: 0.0.0.0:7053# 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 7052chaincodeListenAddress: 0.0.0.0:7055# 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: 192.168.3.128:7055# 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 withaddress: 0.0.0.0:7053# 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# Keepalive settings for peer server and clientskeepalive:# Interval is the duration after which if the server does not see# any activity from the client it pings the client to see if it's aliveinterval: 7200s# Timeout is the duration the server waits for a response# from the client after sending a ping before closing the connectiontimeout: 20s# MinInterval is the minimum permitted time between client pings.# If clients send pings more frequently, the peer server will# disconnect themminInterval: 60s# Client keepalive settings for communicating with other peer nodesclient:# Interval is the time between pings to peer nodes. This must# greater than or equal to the minInterval specified by peer# nodesinterval: 60s# Timeout is the duration the client waits for a response from# peer nodes before closing the connectiontimeout: 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 connectiontimeout: 20s# Gossip related configurationgossip:# 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: 192.168.3.128:7053# 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: false# 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: true# Interval for membershipTracker pollingmembershipTrackerInterval: 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 memorymaxBlockCountToStore: 10# Max time between consecutive message pushes(unit: millisecond)maxPropagationBurstLatency: 10ms# Max number of messages stored until a push is triggered to remote peersmaxPropagationBurstSize: 10# Number of times a message is pushed to remote peerspropagateIterations: 1# Number of peers selected to push messages topropagatePeerNum: 3# Determines frequency of pull phases(unit: second)# Must be greater than digestWaitTime + responseWaitTimepullInterval: 4s# Number of peers to pull frompullPeerNum: 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 expiredstateInfoRetentionInterval:# 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 messagesrecvBuffSize: 20# Buffer size of sending messagessendBuffSize: 200# Time to wait before pull engine processes incoming digests (unit: second)# Should be slightly smaller than requestWaitTimedigestWaitTime: 1s# Time to wait before pull engine removes incoming nonce (unit: milliseconds)# Should be slightly bigger than digestWaitTimerequestWaitTime: 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 peermaxConnectionAttempts: 120# Message expiration factor for alive messagesmsgExpirationFactor: 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:# Leader election service configurationelection:# 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: 5spvtData:# 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 datapullRetryThreshold: 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# Block to live pulling margin, used as a buffer# to prevent peer from trying to pull private data# from peers that is soon to be purged in next N blocks.# This helps a newly joined peer catch up to current# blockchain height quicker.btlPullMargin: 10# the process of reconciliation is done in an endless loop, while in each iteration reconciler tries to# pull from the other peers the most recent missing blocks with a maximum batch size limitation.# reconcileBatchSize determines the maximum batch size of missing private data that will be reconciled in a# single iteration.reconcileBatchSize: 10# reconcileSleepInterval determines the time reconciler sleeps from end of an iteration until the beginning# of the next reconciliation iteration.reconcileSleepInterval: 1m# reconciliationEnabled is a flag that indicates whether private data reconciliation is enable or not.reconciliationEnabled: true# skipPullingInvalidTransactionsDuringCommit is a flag that indicates whether pulling of invalid# transaction's private data from other peers need to be skipped during the commit time and pulled# only through reconciler.skipPullingInvalidTransactionsDuringCommit: false# implicitCollectionDisseminationPolicy specifies the dissemination policy for the peer's own implicit collection.# When a peer endorses a proposal that writes to its own implicit collection, below values override the default values# for disseminating private data.# Note that it is applicable to all channels the peer has joined. The implication is that requiredPeerCount has to# be smaller than the number of peers in a channel that has the lowest numbers of peers from the organization.implicitCollectionDisseminationPolicy:# requiredPeerCount defines the minimum number of eligible peers to which the peer must successfully# disseminate private data for its own implicit collection during endorsement. Default value is 0.requiredPeerCount: 0# maxPeerCount defines the maximum number of eligible peers to which the peer will attempt to# disseminate private data for its own implicit collection during endorsement. Default value is 1.maxPeerCount: 1# Gossip state transfer related configurationstate:# 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 networkenabled: 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 peersresponseTimeout: 3s# batchSize the number of blocks to request via state transfer from another peerbatchSize: 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 bufferblockBufferSize: 20# maxRetries maximum number of re-tries to ask# for single state transfer requestmaxRetries: 3# TLS Settingstls:# Require server-side TLSenabled: true# 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 servercert:file: /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/tls/server.crt# Private key used for TLS server (and client if clientAuthEnabled# is set to truekey:file: /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/tls/server.key# Trusted root certificate chain for tls.certrootcert:file: /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/tls/ca.crt# Set of root certificate authorities used to verify client certificatesclientRootCAs:files:- /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/tls/ca.crt# Private key used for TLS when making client connections. If# not set, peer.tls.key.file will be used insteadclientKey:file:# X.509 certificate used for TLS when making client connections.# If not set, peer.tls.cert.file will be used insteadclientCert:file:# Authentication contains configuration parameters related to authenticating# client messagesauthentication:# the acceptable difference between the current server time and the# client's time as specified in a client request messagetimewindow: 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: /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/hyperledger/production# BCCSP (Blockchain crypto provider): Select which crypto implementation or# library to useBCCSP: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 BCCSPHash: SHA2Security: 256# Location of Key StoreFileKeyStore:# If "", defaults to 'mspConfigPath'/keystoreKeyStore:# Settings for the PKCS#11 crypto provider (i.e. when DEFAULT: PKCS11)PKCS11:# Location of the PKCS11 module libraryLibrary:# Token LabelLabel:# User PINPin:Hash:Security:# Path on the file system where peer will find MSP local configurationsmspConfigPath: /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.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# CLI common client config optionsclient:# connection timeoutconnTimeout: 3s# Delivery service related configdeliveryclient:# It sets the total time the delivery service may spend in reconnection# attempts until its retry logic gives up and returns an errorreconnectTotalTimeThreshold: 3600s# It sets the delivery service <-> ordering service node connection timeoutconnTimeout: 3s# It sets the delivery service maximal delay between consecutive retriesreConnectBackoffThreshold: 3600s# A list of orderer endpoint addresses which should be overridden# when found in channel configurations.addressOverrides:# - from:# to:# caCertsFile:# - from:# to:# caCertsFile:# Type for the local MSP - by default it's of type bccsplocalMspType: bccsp# Used with Go profiling tools only in none production environment. In# production, it should be disabled (eg enabled: false)profile:enabled: falselistenAddress: 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.sohandlers:authFilters:-name: DefaultAuth-name: ExpirationCheck # This filter checks identity x509 certificate expirationdecorators:-name: DefaultDecoratorendorsers:escc:name: DefaultEndorsementlibrary:validators:vscc:name: DefaultValidationlibrary:# library: /etc/hyperledger/fabric/plugin/escc.so# 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 doingvalidatorPoolSize:# The discovery service is used by clients to query information about peers,# such as - which peers have joined a certain channel, what is the latest# channel config, and most importantly - given a chaincode and a channel,# what possible sets of peers satisfy the endorsement policy.discovery:enabled: true# Whether the authentication cache is enabled or not.authCacheEnabled: true# The maximum size of the cache, after which a purge takes placeauthCacheMaxSize: 1000# The proportion (0 to 1) of entries that remain in the cache after the cache is purged due to overpopulationauthCachePurgeRetentionRatio: 0.75# Whether to allow non-admins to perform non channel scoped queries.# When this is false, it means that only peer admins can perform non channel scoped queries.orgMembersAllowedAccess: false# Limits is used to configure some internal resource limits.limits:# Concurrency limits the number of concurrently running requests to a service on each peer.# Currently this option is only applied to endorser service and deliver service.# When the property is missing or the value is 0, the concurrency limit is disabled for the service.concurrency:# endorserService limits concurrent requests to endorser service that handles chaincode deployment, query and invocation,# including both user chaincodes and system chaincodes.endorserService: 2500# deliverService limits concurrent event listeners registered to deliver service for blocks and transaction events.deliverService: 2500###############################################################################
#
# 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:2376endpoint: unix:///var/run/docker.sock# settings for docker vmsdocker:tls:enabled: falseca:file: docker/ca.crtcert:file: docker/tls.crtkey:file: docker/tls.key# Enables/disables the standard out/err from chaincode containers for# debugging purposesattachStdout: 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: hostDns:# - 192.168.0.1LogConfig:Type: json-fileConfig: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 typesbuilder: $(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: falsegolang:# golang will never need more than baseosruntime: $(DOCKER_NS)/fabric-baseos:$(TWO_DIGIT_VERSION)# whether or not golang chaincode should be linked dynamicallydynamicLink: falsejava:# 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)-alpineruntime: $(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: net# 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 offkeepalive: 0# enabled system chaincodessystem:_lifecycle: enablecscc: enablelscc: enableescc: enablevscc: enableqscc: enable# Logging section for the chaincode containerlogging:# Default level for all loggers within the chaincode containerlevel: info# Override default level for the 'shim' loggershim: warning# Format for the chaincode container logsformat: '%{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 CouchDBstateDatabase: goleveldb# Limit on the number of records to return per querytotalQueryLimit: 100000couchDBConfig:# 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: 192.168.3.128:5986# This username must have read and write authority on CouchDBusername:# 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 errorsmaxRetries: 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 batchmaxBatchUpdateSize: 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 databasecreateGlobalChangesDB: 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: 64history:# 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: truepvtdataStore:# the maximum db batch size for converting# the ineligible missing data entries to eligible missing data entriescollElgProcMaxDbBatchSize: 5000# the minimum duration (in milliseconds) between writing# two consecutive db batches for converting the ineligible missing data entries to eligible missing data entriescollElgProcDbBatchesInterval: 1000###############################################################################
#
# Operations section
#
###############################################################################
operations:# host and port for the operations serverlistenAddress: 192.168.3.128:9445# TLS configuration for the operations endpointtls:# TLS enabledenabled: false# path to PEM encoded server certificate for the operations servercert:file:# path to PEM encoded server key for the operations serverkey:file:# most operations service endpoints require client authentication when TLS# is enabled. clientAuthRequired requires client certificate authentication# at the TLS layer to access all resources.clientAuthRequired: false# paths to PEM encoded ca certificates to trust for client authenticationclientRootCAs:files: []###############################################################################
#
# Metrics section
#
###############################################################################
metrics:# metrics provider is one of statsd, prometheus, or disabledprovider: disabled# statsd configurationstatsd:# network type: tcp or udpnetwork: udp# statsd server addressaddress: 192.168.3.128:8127# the interval at which locally cached counters and gauges are pushed# to statsd; timings are pushed immediatelywriteInterval: 10s# prefix is prepended to all emitted statsd metricsprefix:
启动peer1:
peer node start
日志:
2023-11-01 14:05:14.370 CST [nodeCmd] serve -> INFO 001 Starting peer:Version: 2.2.0Commit SHA: 5ea85bc54Go version: go1.14.4OS/Arch: linux/amd64Chaincode:Base Docker Label: org.hyperledger.fabricDocker Namespace: hyperledger
2023-11-01 14:05:14.371 CST [peer] getLocalAddress -> INFO 002 Auto-detected peer address: 192.168.3.128:7051
2023-11-01 14:05:14.371 CST [peer] getLocalAddress -> INFO 003 Returning 192.168.3.128:7051
2023-11-01 14:05:14.375 CST [nodeCmd] initGrpcSemaphores -> INFO 004 concurrency limit for endorser service is 2500
2023-11-01 14:05:14.375 CST [nodeCmd] initGrpcSemaphores -> INFO 005 concurrency limit for deliver service is 2500
2023-11-01 14:05:14.375 CST [nodeCmd] serve -> INFO 006 Starting peer with TLS enabled
2023-11-01 14:05:14.400 CST [ledgermgmt] NewLedgerMgr -> INFO 007 Initializing LedgerMgr
2023-11-01 14:05:14.416 CST [leveldbhelper] openDBAndCheckFormat -> INFO 008 DB is empty Setting db format as 2.0
2023-11-01 14:05:14.426 CST [blkstorage] NewProvider -> INFO 009 Creating new file ledger directory at /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/hyperledger/production/ledgersData/chains/chains
2023-11-01 14:05:14.432 CST [leveldbhelper] openDBAndCheckFormat -> INFO 00a DB is empty Setting db format as 2.0
2023-11-01 14:05:14.448 CST [leveldbhelper] openDBAndCheckFormat -> INFO 00b DB is empty Setting db format as 2.0
2023-11-01 14:05:14.459 CST [ledgermgmt] NewLedgerMgr -> INFO 00c Initialized LedgerMgr
2023-11-01 14:05:14.466 CST [gossip.service] New -> INFO 00d Initialize gossip with endpoint 192.168.3.128:7051
2023-11-01 14:05:14.466 CST [gossip.gossip] New -> INFO 00e Creating gossip service with self membership of Endpoint: 192.168.3.128:7051, InternalEndpoint: 192.168.3.128:7051, PKI-ID: c4ed8c02f6d405ef18af1dee58b19a712a572de390f71b9ac57812aab8522838, Metadata:
2023-11-01 14:05:14.467 CST [gossip.gossip] start -> INFO 00f Gossip instance 192.168.3.128:7051 started
2023-11-01 14:05:14.467 CST [lifecycle] InitializeLocalChaincodes -> INFO 010 Initialized lifecycle cache with 0 already installed chaincodes
2023-11-01 14:05:14.468 CST [nodeCmd] computeChaincodeEndpoint -> INFO 011 Entering computeChaincodeEndpoint with peerHostname: 192.168.3.128
2023-11-01 14:05:14.468 CST [nodeCmd] computeChaincodeEndpoint -> INFO 012 Exit with ccEndpoint: 192.168.3.128:7055
2023-11-01 14:05:14.473 CST [sccapi] DeploySysCC -> INFO 013 deploying system chaincode 'lscc'
2023-11-01 14:05:14.474 CST [sccapi] DeploySysCC -> INFO 014 deploying system chaincode 'cscc'
2023-11-01 14:05:14.474 CST [sccapi] DeploySysCC -> INFO 015 deploying system chaincode 'qscc'
2023-11-01 14:05:14.474 CST [sccapi] DeploySysCC -> INFO 016 deploying system chaincode '_lifecycle'
2023-11-01 14:05:14.474 CST [nodeCmd] serve -> INFO 017 Deployed system chaincodes
2023-11-01 14:05:14.474 CST [discovery] NewService -> INFO 018 Created with config TLS: true, authCacheMaxSize: 1000, authCachePurgeRatio: 0.750000
2023-11-01 14:05:14.474 CST [nodeCmd] registerDiscoveryService -> INFO 019 Discovery service activated
2023-11-01 14:05:14.474 CST [nodeCmd] serve -> INFO 01a Starting peer with ID=[peer1.org1.example.com], network ID=[dev], address=[192.168.3.128:7051]
2023-11-01 14:05:14.475 CST [nodeCmd] serve -> INFO 01b Started peer with ID=[peer1.org1.example.com], network ID=[dev], address=[192.168.3.128:7051]
2023-11-01 14:05:14.475 CST [kvledger] LoadPreResetHeight -> INFO 01c Loading prereset height from path [/home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/hyperledger/production/ledgersData/chains]
2023-11-01 14:05:14.475 CST [blkstorage] preResetHtFiles -> INFO 01d No active channels passed
2023-11-01 14:05:14.480 CST [comm.grpc.server] 1 -> INFO 01e unary call completed grpc.service=gossip.Gossip grpc.method=Ping grpc.request_deadline=2023-11-01T14:05:16.479+08:00 grpc.peer_address=192.168.3.128:58740 grpc.peer_subject="CN=peer1,OU=peer,O=Hyperledger,ST=North Carolina,C=US" grpc.code=OK grpc.call_duration=251.779µs
2023-11-01 14:05:14.483 CST [gossip.comm] GossipStream -> INFO 01f Peer c4ed8c02f6d405ef18af1dee58b19a712a572de390f71b9ac57812aab8522838 (192.168.3.128:58740) probed us
2023-11-01 14:05:14.483 CST [comm.grpc.server] 1 -> INFO 020 streaming call completed grpc.service=gossip.Gossip grpc.method=GossipStream grpc.request_deadline=2023-11-01T14:05:24.481+08:00 grpc.peer_address=192.168.3.128:58740 grpc.peer_subject="CN=peer1,OU=peer,O=Hyperledger,ST=North Carolina,C=US" grpc.code=OK grpc.call_duration=2.216018ms
2023-11-01 14:05:14.487 CST [comm.grpc.server] 1 -> INFO 021 unary call completed grpc.service=gossip.Gossip grpc.method=Ping grpc.request_deadline=2023-11-01T14:05:16.486+08:00 grpc.peer_address=192.168.3.128:58742 grpc.peer_subject="CN=peer1,OU=peer,O=Hyperledger,ST=North Carolina,C=US" grpc.code=OK grpc.call_duration=69.837µs
2023-11-01 14:05:14.489 CST [comm.grpc.server] 1 -> INFO 022 streaming call completed grpc.service=gossip.Gossip grpc.method=GossipStream grpc.peer_address=192.168.3.128:58742 grpc.peer_subject="CN=peer1,OU=peer,O=Hyperledger,ST=North Carolina,C=US" error="rpc error: code = Canceled desc = context canceled" grpc.code=Canceled grpc.call_duration=1.502701ms
配置环境变量,下面需要使用peer1节点的信息:
export CORE_PEER_TLS_ROOTCERT_FILE=/home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/tls/ca.crt
export CORE_PEER_ADDRESS=192.168.3.128:7053
三、添加peer1到应用通道
从orderer0上拉取应用通道的最早区块:
peer channel fetch oldest /home/songzehao/fabric/config/channel-artifacts/channel1_oldest.block -c channel1 -o 192.168.3.128:7050 --tls --cafile /home/songzehao/fabric/organizations/ordererOrganizations/org1.example.com/orderers/orderer0.org1.example.com/msp/tlscacerts/tlsca.org1.example.com-cert.pem
日志:
2023-11-01 14:06:36.958 CST [channelCmd] InitCmdFactory -> INFO 001 Endorser and orderer connections initialized
2023-11-01 14:06:36.960 CST [cli.common] readBlock -> INFO 002 Received block: 0
peer1加入应用通道:
peer channel join -b /home/songzehao/fabric/config/channel-artifacts/channel1_oldest.block
日志:
2023-11-01 14:06:41.566 CST [channelCmd] InitCmdFactory -> INFO 001 Endorser and orderer connections initialized
2023-11-01 14:06:41.595 CST [channelCmd] executeJoin -> INFO 002 Successfully submitted proposal to join channel
查看到已加入:
peer channel list
日志:
2023-11-01 14:06:47.135 CST [channelCmd] InitCmdFactory -> INFO 001 Endorser and orderer connections initialized
Channels peers has joined:
channel1
获取应用通道最近的配置块:
peer channel fetch config /home/songzehao/fabric/config/channel-artifacts/config_block_v2.pb -c channel1 -o 192.168.3.128:7050 --tls --cafile /home/songzehao/fabric/organizations/ordererOrganizations/org1.example.com/orderers/orderer0.org1.example.com/msp/tlscacerts/tlsca.org1.example.com-cert.pem
日志:
2023-11-01 14:09:13.616 CST [channelCmd] InitCmdFactory -> INFO 001 Endorser and orderer connections initialized
2023-11-01 14:09:13.617 CST [cli.common] readBlock -> INFO 002 Received block: 7
2023-11-01 14:09:13.618 CST [channelCmd] fetch -> INFO 003 Retrieving last config block: 1
2023-11-01 14:09:13.619 CST [cli.common] readBlock -> INFO 004 Received block: 1
protobuf序列化(编码)后的.pb
配置文件,转化为.json
格式:
configtxlator proto_decode --input /home/songzehao/fabric/config/channel-artifacts/config_block_v2.pb --type common.Block --output /home/songzehao/fabric/config/channel-artifacts/config_block_v2.json
抽取配置部分的json,得到原始配置:
jq .data.data[0].payload.data.config /home/songzehao/fabric/config/channel-artifacts/config_block_v2.json > /home/songzehao/fabric/config/channel-artifacts/Org1MSPconfig_v2.json
进一步追加锚节点peer0/peer1信息到Org1MSP的values
部分,得到更改后配置:
jq '.channel_group.groups.Application.groups.Org1MSP.values += {"AnchorPeers":{"mod_policy": "Admins","value":{"anchor_peers": [{"host": "192.168.3.128","port": 7051},{"host": "192.168.3.128","port": 7053}]},"version": "0"}}' /home/songzehao/fabric/config/channel-artifacts/Org1MSPconfig_v2.json > /home/songzehao/fabric/config/channel-artifacts/Org1MSPmodified_config_v2.json
protobuf编码原始配置:
configtxlator proto_encode --input /home/songzehao/fabric/config/channel-artifacts/Org1MSPconfig_v2.json --type common.Config --output /home/songzehao/fabric/config/channel-artifacts/original_config_v2.pb
protobuf编码更改后配置:
configtxlator proto_encode --input /home/songzehao/fabric/config/channel-artifacts/Org1MSPmodified_config_v2.json --type common.Config --output /home/songzehao/fabric/config/channel-artifacts/modified_config_v2.pb
计算更改前后的配置差异,得到.pb
的差异配置:
configtxlator compute_update --channel_id channel1 --original /home/songzehao/fabric/config/channel-artifacts/original_config_v2.pb --updated /home/songzehao/fabric/config/channel-artifacts/modified_config_v2.pb --output /home/songzehao/fabric/config/channel-artifacts/config_update_v2.pb
protobuf解码为.json
格式:
configtxlator proto_decode --input /home/songzehao/fabric/config/channel-artifacts/config_update_v2.pb --type common.ConfigUpdate --output /home/songzehao/fabric/config/channel-artifacts/config_update_v2.json
追加.json
格式的差异文件内容到新包装后的.json
文件:
echo '{"payload":{"header":{"channel_header":{"channel_id":"channel1", "type":2}},"data":{"config_update":'$(cat /home/songzehao/fabric/config/channel-artifacts/config_update_v2.json)'}}}' | jq . > /home/songzehao/fabric/config/channel-artifacts/config_update_in_envelope_v2.json
编码为Envelope
类型的新的交易文件:
configtxlator proto_encode --input /home/songzehao/fabric/config/channel-artifacts/config_update_in_envelope_v2.json --type common.Envelope --output /home/songzehao/fabric/config/channel-artifacts/Org1MSPanchors_v2.tx
提交更新通道配置交易:
peer channel update -o 192.168.3.128:7050 -c channel1 -f /home/songzehao/fabric/config/channel-artifacts/Org1MSPanchors_v2.tx --tls --cafile /home/songzehao/fabric/organizations/ordererOrganizations/org1.example.com/orderers/orderer0.org1.example.com/msp/tlscacerts/tlsca.org1.example.com-cert.pem
日志:
2023-11-01 14:10:21.695 CST [channelCmd] InitCmdFactory -> INFO 001 Endorser and orderer connections initialized
2023-11-01 14:10:21.703 CST [channelCmd] update -> INFO 002 Successfully submitted channel update
四、链码安装和调用
进行链码安装:
peer lifecycle chaincode install ~/fabric/config/basic.tar.gz
日志:
2023-11-01 14:11:17.497 CST [cli.lifecycle.chaincode] submitInstallProposal -> INFO 001 Installed remotely: response:<status:200 payload:"\nJbasic_1.0:67b9d7ef205254d9b8ff59e5904d1d18a27f74d7d1679abe0e7ccde064826773\022\tbasic_1.0" >
2023-11-01 14:11:17.497 CST [cli.lifecycle.chaincode] submitInstallProposal -> INFO 002 Chaincode code package identifier: basic_1.0:67b9d7ef205254d9b8ff59e5904d1d18a27f74d7d1679abe0e7ccde064826773
查看已安装的链码:
peer lifecycle chaincode queryinstalled
日志:
Installed chaincodes on peer:
Package ID: basic_1.0:67b9d7ef205254d9b8ff59e5904d1d18a27f74d7d1679abe0e7ccde064826773, Label: basic_1.0
批准链码定义(sequence = 2):
peer lifecycle chaincode approveformyorg -o 192.168.3.128:7050 --channelID channel1 --name basic --version 1.0 --package-id basic_1.0:67b9d7ef205254d9b8ff59e5904d1d18a27f74d7d1679abe0e7ccde064826773 --sequence 2 --tls --cafile /home/songzehao/fabric/organizations/ordererOrganizations/org1.example.com/orderers/orderer0.org1.example.com/msp/tlscacerts/tlsca.org1.example.com-cert.pem
日志:
2023-11-01 14:12:31.806 CST [chaincodeCmd] ClientWait -> INFO 001 txid [e3beb98cd01305a543057210937f2fdd0a721359fefc201208412c50b189bf8e] committed with status (VALID) at
检查新的链码容器是否已启动:
$ docker ps --no-trunc
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
8f32629f486bd59da877d286d14cf75b6ed20f69f89c88eb5e219bbe851fac52 dev-peer1.org1.example.com-basic_1.0-67b9d7ef205254d9b8ff59e5904d1d18a27f74d7d1679abe0e7ccde064826773-4e7281a5808a69aaf1cae9bf3e0f20a09a18e8aede126cd8ba67309e90470668 "/root/chaincode-java/start --peerAddress 192.168.3.128:7055" 2 minutes ago Up 2 minutes dev-peer1.org1.example.com-basic_1.0-67b9d7ef205254d9b8ff59e5904d1d18a27f74d7d1679abe0e7ccde064826773
8d14f50cb83dd1956e48b6bdab88f03be34611d93512f7ff394282b6ce380837 dev-peer0.org1.example.com-basic_1.0-67b9d7ef205254d9b8ff59e5904d1d18a27f74d7d1679abe0e7ccde064826773-4ae135e5fa18d99cbd8dc7e8907079b31a3f779d0137e69204d3307d30236441 "/root/chaincode-java/start --peerAddress 192.168.3.128:7052" 2 hours ago Up 2 hours dev-peer0.org1.example.com-basic_1.0-67b9d7ef205254d9b8ff59e5904d1d18a27f74d7d1679abe0e7ccde064826773
检查提交就绪状态:
peer lifecycle chaincode checkcommitreadiness --channelID channel1 --name basic --version 1.0 --sequence 2 --output json
日志:
{"approvals": {"Org1MSP": true}
}
提交到peer1:
peer lifecycle chaincode commit -o 192.168.3.128:7050 --channelID channel1 --name basic --peerAddresses 192.168.3.128:7051 --tlsRootCertFiles /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt --version 1.0 --sequence 2 --tls --cafile /home/songzehao/fabric/organizations/ordererOrganizations/org1.example.com/orderers/orderer0.org1.example.com/msp/tlscacerts/tlsca.org1.example.com-cert.pem
日志:
2023-11-01 14:16:19.702 CST [chaincodeCmd] ClientWait -> INFO 001 txid [b55d20d771b23b28709411be71c0a6cb43818f6d6e885de81d65bc76493896dd] committed with status (VALID) at 192.168.3.128:7051
检查提交状态:
peer lifecycle chaincode querycommitted --channelID channel1 --name basic --tls --cafile /home/songzehao/fabric/organizations/ordererOrganizations/org1.example.com/orderers/orderer0.org1.example.com/msp/tlscacerts/tlsca.org1.example.com-cert.pem
日志:
Committed chaincode definition for chaincode 'basic' on channel 'channel1':
Version: 1.0, Sequence: 2, Endorsement Plugin: escc, Validation Plugin: vscc, Approvals: [Org1MSP: true]
查询初始化后的资产(调用链码的GetAllAssets方法):
不用再在peer1初始化链码,否则报错Error: endorsement failure during invoke. response: status:500 message:"error in simulation: transaction returned with failure: Asset asset1 already exists"
。
peer chaincode invoke -o 192.168.3.128:7050 -C channel1 -n basic --peerAddresses 192.168.3.128:7053 --tlsRootCertFiles /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/tls/ca.crt --tls --cafile /home/songzehao/fabric/organizations/ordererOrganizations/org1.example.com/orderers/orderer0.org1.example.com/msp/tlscacerts/tlsca.org1.example.com-cert.pem -c '{"function":"GetAllAssets","Args":[]}'
日志:
2023-11-01 14:17:43.996 CST [chaincodeCmd] chaincodeInvokeOrQuery -> INFO 001 Chaincode invoke successful. result: status:200 payload:"[{\"appraisedValue\":300,\"assetID\":\"asset1\",\"color\":\"blue\",\"owner\":\"Tomoko\",\"size\":5},{\"appraisedValue\":400,\"assetID\":\"asset2\",\"color\":\"red\",\"owner\":\"Brad\",\"size\":5},{\"appraisedValue\":500,\"assetID\":\"asset3\",\"color\":\"green\",\"owner\":\"Jin Soo\",\"size\":10},{\"appraisedValue\":600,\"assetID\":\"asset4\",\"color\":\"yellow\",\"owner\":\"Max\",\"size\":10},{\"appraisedValue\":700,\"assetID\":\"asset5\",\"color\":\"black\",\"owner\":\"Adrian\",\"size\":15},{\"appraisedValue\":700,\"assetID\":\"asset6\",\"color\":\"white\",\"owner\":\"Michel\",\"size\":15},{\"appraisedValue\":800,\"assetID\":\"asset7\",\"color\":\"pink\",\"owner\":\"Jay\",\"size\":18}]"
发交易,新增资产(调用链码的初始化方法CreateAsset):
peer chaincode invoke -o 192.168.3.128:7050 -C channel1 -n basic --peerAddresses 192.168.3.128:7053 --tlsRootCertFiles /home/songzehao/fabric/organizations/peerOrganizations/org1.example.com/peers/peer1.org1.example.com/tls/ca.crt --tls --cafile /home/songzehao/fabric/organizations/ordererOrganizations/org1.example.com/orderers/orderer0.org1.example.com/msp/tlscacerts/tlsca.org1.example.com-cert.pem -c '{"function":"CreateAsset","Args":["asset8", "gold", "27", "Song", "127"]}'
日志:
2023-11-01 14:19:13.120 CST [chaincodeCmd] chaincodeInvokeOrQuery -> INFO 001 Chaincode invoke successful. result: status:200 payload:"{\"owner\":\"Song\",\"color\":\"gold\",\"size\":27,\"appraisedValue\":127,\"assetID\":\"asset8\"}"