### Go Chaincode Main Function Source: https://github.com/yeasy/blockchain_guide/blob/master/11_app_dev/chaincode_example01.md This Go code snippet shows the main function for the SimpleChaincode. It initializes and starts the chaincode using the shim package. Error handling is included for the startup process. ```go func main() { err := shim.Start(new(SimpleChaincode)) if err != nil { fmt.Printf("Error starting Simple chaincode: %s", err) } } ``` -------------------------------- ### Start Fabric CA Server Source: https://github.com/yeasy/blockchain_guide/blob/master/09_fabric_deploy/install_docker.md Defines the default command to execute when the container starts. It initiates the fabric-ca-server with basic authentication credentials ('admin:adminpw'). ```dockerfile CMD ["bash", "-c", "fabric-ca-server start -b admin:adminpw"] ``` -------------------------------- ### Build Hyperledger Fabric Orderer Image Source: https://github.com/yeasy/blockchain_guide/blob/master/09_fabric_deploy/install_docker.md This Dockerfile builds the Hyperledger fabric-orderer image based on the fabric-base image. It exposes the orderer port and installs the orderer component using Go install. The default command starts the orderer service. ```dockerfile # https://github.com/yeasy/docker-hyperledger-fabric-orderer # # Dockerfile for Hyperledger fabric-orderer image. FROM yeasy/hyperledger-fabric-base:2.0.0 LABEL maintainer "Baohua Yang " EXPOSE 7050 ENV ORDERER_GENERAL_LOCALMSPDIR $FABRIC_CFG_PATH/msp ENV ORDERER_GENERAL_LISTENADDRESS 0.0.0.0 # ENV CONFIGTX_ORDERER_ORDERERTYPE=etcdraft RUN mkdir -p $FABRIC_CFG_PATH $ORDERER_GENERAL_LOCALMSPDIR # Install fabric orderer RUN CGO_CFLAGS=" " go install -tags "" -ldflags "$LD_FLAGS" github.com/hyperledger/fabric/cmd/orderer && go clean CMD ["orderer", "start"] ``` -------------------------------- ### Install and Build eventsclient Tool Source: https://github.com/yeasy/blockchain_guide/blob/master/10_fabric_op/events.md Installs and builds the eventsclient Go tool, which is used to listen for Fabric network events. Ensure your Go environment is set up correctly. ```bash cd $GOPATH/src/hyperledger/fabric/examples/events/eventsclient go install && go clean ``` -------------------------------- ### Chaincode Packaging Implementation Flow Source: https://github.com/yeasy/blockchain_guide/blob/master/10_fabric_op/chaincode.md Illustrates the Go code flow for packaging chaincode, including initialization, spec generation, deployment spec creation, and envelope construction. ```go // Initializes the command factory, not requiring endorser or orderer for local packaging. cmdFactory, err := InitCmdFactory(false, false) // Parses arguments and generates ChaincodeSpec. chaincodeSpec, err := getChaincodeSpec(cmdFactory) // Constructs ChaincodeDeploymentSpec and calls getChaincodeInstallPackage. cds := &pb.ChaincodeDeploymentSpec{ChaincodeSpec: chaincodeSpec} installPackage, err := getChaincodeInstallPackage(cds, instantiatePolicy, signatureSet) // Creates an Envelope with ChaincodePackage type. envelope, err := proto.Marshal(&pb.Envelope{Payload: installPackage, Header: header}) // Writes the serialized Envelope to a file. err = ioutil.WriteFile(outputFile, envelope, 0644) ``` -------------------------------- ### Build Hyperledger Fabric Peer Image Source: https://github.com/yeasy/blockchain_guide/blob/master/09_fabric_deploy/install_docker.md This Dockerfile creates the Hyperledger fabric-peer image, also based on the fabric-base image. It exposes the peer port and installs the peer command-line utility. The default command initiates the peer node startup. ```dockerfile # https://github.com/yeasy/docker-hyperledger-fabric-peer # # Dockerfile for Hyperledger peer image. This actually follow yeasy/hyperledger-fabric # image and add default start cmd. # Data is stored under /var/hyperledger/production FROM yeasy/hyperledger-fabric-base:2.0.0 LABEL maintainer "Baohua Yang " # Peer EXPOSE 7051 # ENV CORE_PEER_MSPCONFIGPATH $FABRIC_CFG_PATH/msp # Install fabric peer RUN CGO_CFLAGS=" " go install -tags "" -ldflags "$LD_FLAGS" github.com/hyperledger/fabric/cmd/peer && go clean # First need to manually create a chain with `peer channel create -c test_chain`, then join with `peer channel join -b test_chain.block`. CMD ["peer","node","start"] ``` -------------------------------- ### Build Hyperledger Fabric Base Image Source: https://github.com/yeasy/blockchain_guide/blob/master/09_fabric_deploy/install_docker.md This snippet shows the Dockerfile instructions for creating the base Hyperledger Fabric image. It clones the fabric repository, sets up configuration paths, installs essential binaries like configtxgen and cryptogen, and configures environment variables. ```dockerfile RUN cd $GOPATH/src/github.com/hyperledger && wget https://github.com/hyperledger/fabric/archive/v${PROJECT_VERSION}-beta.zip && unzip v${PROJECT_VERSION}-beta.zip && rm v${PROJECT_VERSION}-beta.zip && mv fabric-${PROJECT_VERSION}-beta fabric && echo "* hard nofile 65536" >> /etc/security/limits.conf && echo "* soft nofile 65536" >> /etc/security/limits.conf && cp -r $FABRIC_ROOT/sampleconfig/* $FABRIC_CFG_PATH/ # Add external farbric chaincode dependencies RUN go get github.com/hyperledger/fabric-chaincode-go/shim && go get github.com/hyperledger/fabric-protos-go/peer # Install configtxgen, cryptogen, configtxlator, discover and idemixgen RUN cd $FABRIC_ROOT/ && CGO_CFLAGS=" " go install -tags "" github.com/hyperledger/fabric/cmd/configtxgen && CGO_CFLAGS=" " go install -tags "" github.com/hyperledger/fabric/cmd/cryptogen && CGO_CFLAGS=" " go install -tags "" github.com/hyperledger/fabric/cmd/configtxlator && CGO_CFLAGS=" " go install -tags "" -ldflags "-X github.com/hyperledger/fabric/cmd/discover/metadata.Version=2.0.0" github.com/hyperledger/fabric/cmd/discover #&& CGO_CFLAGS=" " go install -tags "" -ldflags "-X github.com/hyperledger/fabric/cmd/token/metadata.Version=2.0.0" github.com/hyperledger/fabric/cmd/token && CGO_CFLAGS=" " go install -tags "" github.com/hyperledger/fabric/cmd/idemixgen # The data and config dir, can map external one with -v VOLUME /var/hyperledger # Temporarily fix the `go list` complain problem, which is required in chaincode packaging, see core/chaincode/platforms/golang/platform.go#GetDepoymentPayload ENV GOROOT=/usr/local/go WORKDIR $FABRIC_ROOT # This is only a workaround for current hard-coded problem when using as the fabric-baseimage. RUN ln -s $GOPATH /opt/gopath LABEL org.hyperledger.fabric.version=${PROJECT_VERSION} org.hyperledger.fabric.base.version=${BASEIMAGE_RELEASE} ``` -------------------------------- ### Package Chaincode Command Source: https://github.com/yeasy/blockchain_guide/blob/master/10_fabric_op/chaincode.md Command to package chaincode with options for full package format, signing, and instantiate policy. The output is a packaged file ready for installation. ```bash $ peer chaincode package \ -n test_cc -p github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02 \ -v 1.0 \ -s \ -S \ -i "AND('Org1.admin')" \ ccpack.out ``` -------------------------------- ### Clone and Build Fabric CA Source: https://github.com/yeasy/blockchain_guide/blob/master/09_fabric_deploy/install_docker.md Clones the fabric-ca source code from a specified version, unzips it, and then builds and installs the fabric-ca-server and fabric-ca-client binaries. It uses Go build flags for static linking and metadata. ```dockerfile RUN cd $GOPATH/src/github.com/hyperledger \ && wget https://github.com/hyperledger/fabric-ca/archive/v${PROJECT_VERSION}.zip \ && unzip v${PROJECT_VERSION}.zip \ && rm v${PROJECT_VERSION}.zip \ && mv fabric-ca-${PROJECT_VERSION} fabric-ca \ # This will install fabric-ca-server and fabric-ca-client into $GOPATH/bin/ && go install -ldflags "-X github.com/hyperledger/fabric-ca/lib/metadata.Version=$PROJECT_VERSION -linkmode external -extldflags '-static -lpthread'" github.com/hyperledger/fabric-ca/cmd/... \ # Copy example ca and key files #&& cp $FABRIC_CA_ROOT/images/fabric-ca/payload/*.pem $FABRIC_CA_HOME/ \ && go clean ``` -------------------------------- ### 编译和安装 Go 本地软件包 - go install Source: https://github.com/yeasy/blockchain_guide/blob/master/appendix/golang/tools.md go install 命令用于编译本地 Go 软件包,并将编译好的二进制文件安装到 `$GOPATH/bin` 目录下。它等价于先执行 `go build` 命令,然后执行复制命令。 ```bash $ go install ``` -------------------------------- ### Install Packaged Chaincode Source: https://github.com/yeasy/blockchain_guide/blob/master/10_fabric_op/chaincode.md Command to install a previously packaged chaincode using the generated package file. This simplifies the installation process. ```bash $ peer chaincode install ccpack.out ``` -------------------------------- ### Build Hyperledger Fabric CA Image Source: https://github.com/yeasy/blockchain_guide/blob/master/09_fabric_deploy/install_docker.md This Dockerfile constructs the Hyperledger fabric-ca image using a golang:1.13 base. It sets up environment variables for fabric-ca configuration paths and installs the fabric-ca server and client binaries. This image provides certificate issuance capabilities. ```dockerfile # https://github.com/yeasy/docker-hyperledger-fabric-ca # # Dockerfile for Hyperledger fabric-ca image. # If you need a peer node to run, please see the yeasy/hyperledger-peer image. # Workdir is set to $GOPATH/src/github.com/hyperledger/fabric-ca # More usage information, please see https://github.com/yeasy/docker-hyperledger-fabric-ca. FROM golang:1.13 LABEL maintainer "Baohua Yang " ENV PROJECT_VERSION 2.0.0 # ca-server and ca-client will check the following env in order, to get the home cfg path ENV FABRIC_CA_HOME /etc/hyperledger/fabric-ca-server ENV FABRIC_CA_SERVER_HOME /etc/hyperledger/fabric-ca-server ENV FABRIC_CA_CLIENT_HOME $HOME/.fabric-ca-client ENV CA_CFG_PATH /etc/hyperledger/fabric-ca # This is to simplify this Dockerfile ENV FABRIC_CA_ROOT $GOPATH/src/github.com/hyperledger/fabric-ca # Usually the binary will be installed into $GOPATH/bin, but we add local build path, too ENV PATH=$FABRIC_CA_ROOT/bin:$PATH #ARG FABRIC_CA_DYNAMIC_LINK=false ``` -------------------------------- ### Install yq for Configuration Source: https://github.com/yeasy/blockchain_guide/blob/master/09_fabric_deploy/install_docker.md Downloads and installs 'yq', a command-line YAML processor, into the Go binary path. This tool is used to modify the fabric-ca configuration files. ```dockerfile RUN wget -O /go/bin/yq https://github.com/mikefarah/yq/releases/download/2.4.1/yq_linux_amd64 \ && chmod a+x /go/bin/yq ``` -------------------------------- ### 启动 Cello 服务 (Make) Source: https://github.com/yeasy/blockchain_guide/blob/master/17_baas/cello.md 运行 `make start` 命令来启动 Cello 的所有核心组件服务,包括 dashboard、restserver、watchdog、mongo 和 nginx。 ```bash $ make start ``` -------------------------------- ### Install Dependencies for Fabric CA Build Source: https://github.com/yeasy/blockchain_guide/blob/master/09_fabric_deploy/install_docker.md Installs necessary packages 'libtool' and 'unzip' required for building the Hyperledger Fabric CA from source. It also clears the apt cache to reduce image size. ```dockerfile RUN apt-get update \ && apt-get install -y libtool unzip \ && rm -rf /var/cache/apt ``` -------------------------------- ### Install docker-compose using pip | Bash Source: https://github.com/yeasy/blockchain_guide/blob/master/09_fabric_deploy/install_docker.md This sequence installs the 'pip' package manager and then uses it to install the 'docker-compose' tool. docker-compose is essential for defining and running multi-container Docker applications, recommended for version 1.10.0 or higher. ```bash $ sudo aptitude install python-pip $ sudo pip install docker-compose>=1.10.0 ``` -------------------------------- ### 使用 go clean 清理 Go 项目 Source: https://github.com/yeasy/blockchain_guide/blob/master/appendix/golang/tools.md go clean 命令用于清理 Go 项目,删除编译生成的二进制文件和临时文件。它支持 `-i` 参数删除 go install 安装的文件,`-n` 和 `-x` 参数打印删除命令而不执行或同时打印执行过程,以及 `-r` 参数递归清除依赖包。 ```bash $ go clean ``` -------------------------------- ### 安装 Cello Master 节点依赖 (Make) Source: https://github.com/yeasy/blockchain_guide/blob/master/17_baas/cello.md 使用 `make setup` 命令快速配置 Master 节点,包括安装 Docker 环境、创建数据库目录和安装必要的软件包。这是运行 Cello 服务的前提。 ```bash $ make setup ``` -------------------------------- ### List Installed and Instantiated Chaincodes Source: https://github.com/yeasy/blockchain_guide/blob/master/10_fabric_op/chaincode.md The 'peer chaincode list' command helps query the status of chaincodes on a peer node. Use the '--installed' flag to see all chaincodes installed on the peer, and '--instantiated' with '-C ' to view chaincodes that have been deployed to a specific channel. ```bash peer chaincode list \ --installed \ Get installed chaincodes on peer: Name: exp02, Version: 1.0, Path: examples/chaincode/go/chaincode_example02, Id: 08ca675c39a8bae2631847a521fc92e12969fe122bd4a9df0a707cf1059e8730 ``` ```bash peer chaincode list \ --instantiated \ -C ${APP_CHANNEL} Get instantiated chaincodes on channel businesschannel: Name: exp02, Version: 1.0, Path: examples/chaincode/go/chaincode_example02, Escc: escc, Vscc: vscc ``` -------------------------------- ### Dockerfile for Hyperledger Fabric Base Image Source: https://github.com/yeasy/blockchain_guide/blob/master/09_fabric_deploy/install_docker.md This Dockerfile defines the build process for the fabric-base image, which is essential for Go chaincode containers. It's based on the golang:1.13 image and installs various development tools, dependencies, and Hyperledger Fabric utilities like configtxgen, cryptogen, etc. It also sets up environment variables for Fabric versions and paths. ```dockerfile # https://github.com/yeasy/docker-hyperledger-fabric-base # # Dockerfile for Hyperledger fabric base image. # If you only need quickly deploy a fabric network, please see # * yeasy/hyperledger-fabric-peer # * yeasy/hyperledger-fabric-orderer # * yeasy/hyperledger-fabric-ca # Workdir is set to $GOPATH/src/github.com/hyperledger/fabric # Data is stored under /var/hyperledger/production FROM golang:1.13 LABEL maintainer "Baohua Yang " ENV DEBIAN_FRONTEND noninteractive # Only useful for this Dockerfile ENV FABRIC_ROOT=$GOPATH/src/github.com/hyperledger/fabric ENV CHAINTOOL_RELEASE=1.1.3 # version for the base images (baseos, baseimage, ccenv, etc.) ENV BASEIMAGE_RELEASE=0.4.18 # BASE_VERSION is used in metadata.Version as major version ENV BASE_VERSION=2.0.0 # PROJECT_VERSION is required in core.yaml for fabric-baseos and fabric-ccenv ENV PROJECT_VERSION=2.0.0 # generic golang cc builder environment (core.yaml): builder: $(DOCKER_NS)/fabric-ccenv:$(ARCH)-$(PROJECT_VERSION) ENV DOCKER_NS=hyperledger # for golang or car's baseos for cc runtime: $(BASE_DOCKER_NS)/fabric-baseos:$(ARCH)-$(BASEIMAGE_RELEASE) ENV BASE_DOCKER_NS=hyperledger ENV LD_FLAGS "-X github.com/hyperledger/fabric/common/metadata.Version=${PROJECT_VERSION} \ -X github.com/hyperledger/fabric/common/metadata.BaseDockerLabel=org.hyperledger.fabric \ -X github.com/hyperledger/fabric/common/metadata.DockerNamespace=hyperledger \ -X github.com/hyperledger/fabric/common/metadata.BaseDockerNamespace=hyperledger" # -X github.com/hyperledger/fabric/common/metadata.Experimental=true \ # -linkmode external -extldflags '-static -lpthread'" # Peer config path ENV FABRIC_CFG_PATH=/etc/hyperledger/fabric RUN mkdir -p /var/hyperledger/production \ $GOPATH/src/github.com/hyperledger \ $FABRIC_CFG_PATH \ /chaincode/input \ /chaincode/output # Install development dependencies RUN apt-get update \ && apt-get install -y apt-utils python-dev \ && apt-get install -y libsnappy-dev zlib1g-dev libbz2-dev libyaml-dev libltdl-dev libtool \ && apt-get install -y python-pip \ && apt-get install -y vim tree jq unzip \ && rm -rf /var/cache/apt # Install chaintool #RUN curl -L https://github.com/hyperledger/fabric-chaintool/releases/download/v0.10.3/chaintool > /usr/local/bin/chaintool \ RUN curl -fL https://nexus.hyperledger.org/content/repositories/releases/org/hyperledger/fabric/hyperledger-fabric/chaintool-${CHAINTOOL_RELEASE}/hyperledger-fabric-chaintool-${CHAINTOOL_RELEASE}.jar > /usr/local/bin/chaintool \ && chmod a+x /usr/local/bin/chaintool # install gotools RUN go get github.com/golang/protobuf/protoc-gen-go \ && go get github.com/maxbrunsfeld/counterfeiter \ && go get github.com/axw/gocov/... && go get github.com/AlekSi/gocov-xml \ && go get golang.org/x/tools/cmd/goimports \ && go get golang.org/x/lint/golint \ && go get github.com/estesp/manifest-tool \ && go get github.com/client9/misspell/cmd/misspell \ && go get github.com/estesp/manifest-tool \ && go get github.com/onsi/ginkgo/ginkgo ``` -------------------------------- ### Discover Tool Config Subcommand Example Source: https://github.com/yeasy/blockchain_guide/blob/master/10_fabric_op/discover.md Example of using the `config` subcommand of the `discover` tool to query channel configuration information. This command fetches details about organizations' MSPs and ordering service configurations for the 'businesschannel'. ```bash $ discover \ --peerTLSCA tls/ca.crt \ --userKey msp/keystore/f76cf3c92dac81103c82d5490c417ac0123c279f93213f65947d8cc69e11fbc5_sk \ --userCert msp/signcerts/Admin@org1.example.com-cert.pem \ --MSP Org1MSP \ --tlsCert tls/client.crt \ --tlsKey tls/client.key \ config \ --server peer0.org1.example.com:7051 \ --channel businesschannel ``` -------------------------------- ### Build Docker Images from Source | Bash Source: https://github.com/yeasy/blockchain_guide/blob/master/09_fabric_deploy/install_docker.md This command initiates the build process for multiple Docker images, including essential Fabric components like fabric-baseos, fabric-peer, and fabric-tools, directly from the source code. The generated images will have version and snapshot tags. ```bash $ make docker ``` -------------------------------- ### Create Directories for Fabric CA Source: https://github.com/yeasy/blockchain_guide/blob/master/09_fabric_deploy/install_docker.md Creates essential directories for Hyperledger Fabric CA server and client, including GOPATH and configuration paths. ```dockerfile RUN mkdir -p $GOPATH/src/github.com/hyperledger \ $FABRIC_CA_SERVER_HOME \ $FABRIC_CA_CLIENT_HOME \ $CA_CFG_PATH \ /var/hyperledger/fabric-ca-server ``` -------------------------------- ### Run gRPC Server Source: https://github.com/yeasy/blockchain_guide/blob/master/appendix/grpc.md Command to compile and run the Go gRPC server. This starts the server process, making it ready to accept client connections. ```sh go run server/server.go ``` -------------------------------- ### Install Chaincode Command Source: https://github.com/yeasy/blockchain_guide/blob/master/10_fabric_op/chaincode_v2.md Example command to install a chaincode package to a specified peer node. This involves setting the CORE_PEER_ADDRESS environment variable and using the 'peer chaincode install' command with chaincode name, version, and path. ```bash $ CORE_PEER_ADDRESS=peer.your_domain.com:7051 $ peer chaincode install \ -n test_cc \ -v 1.0 \ -p github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02 ``` -------------------------------- ### Start Peer Node in Hyperledger Fabric Source: https://github.com/yeasy/blockchain_guide/blob/master/09_fabric_deploy/start_local.md This snippet demonstrates how to start a Peer node in Hyperledger Fabric. Prerequisites include a core.yaml configuration file and necessary MSP/TLS directories. The command utilizes environment variables for configuration, and successful startup is indicated by log messages showing the peer's version and network address. ```bash $ peer node start UTC [ledgermgmt] initialize -> INFO 002 Starting peer: Version: 2.0.0 Commit SHA: development build Go version: go1.13.4 OS/Arch: linux/amd64 Chaincode: Base Docker Namespace: hyperledger Base Docker Label: org.hyperledger.fabric Docker Namespace: hyperledger" ... UTC [nodeCmd] serve -> INFO 01e Started peer with ID=[name:"peer0.org1.example.com" ], network ID=[dev], address=[peer0.org1.example.com:7051] ... ``` -------------------------------- ### Install Go gRPC Plugin and Dependencies Source: https://github.com/yeasy/blockchain_guide/blob/master/appendix/grpc.md Command to install the protoc-gen-go plugin and the Go protobuf library. This is necessary for compiling .proto files for Go projects using gRPC. ```sh go get -u github.com/golang/protobuf/{protoc-gen-go,proto} ``` -------------------------------- ### Start Fabric Event Listener with TLS Configuration Source: https://github.com/yeasy/blockchain_guide/blob/master/10_fabric_op/events.md Starts the eventsclient tool to listen for filtered network events on a specified channel with TLS enabled. This command requires environment variables for server URL, channel ID, and TLS certificates. ```bash eventsclient \ -server=${PEER_URL} \ -channelID=${APP_CHANNEL} \ -filtered=true \ -tls=true \ -clientKey=${TLS_CLIENT_KEY} \ -clientCert=${TLS_CLIENT_CERT} \ -rootCert=${TLS_CA_CERT} ``` -------------------------------- ### Download Docker Compose Files Source: https://github.com/yeasy/blockchain_guide/blob/master/09_fabric_deploy/start_docker.md Clones the `docker-compose-files` repository to obtain Fabric network configuration templates. This is the initial step to set up a Fabric network using containerization. It requires `git` to be installed. ```shell git clone https://github.com/yeasy/docker-compose-files cd docker-compose-files/hyperledger_fabric ``` -------------------------------- ### Start and Test Fabric Network (Raft Mode) Source: https://github.com/yeasy/blockchain_guide/blob/master/09_fabric_deploy/start_docker.md Starts a Hyperledger Fabric network using Docker Compose with the Raft ordering service mode and executes a comprehensive test suite. This command automates configuration generation, network startup, channel operations, chaincode tests, and network shutdown. It relies on a `Makefile` with predefined targets. ```bash HLF_MODE=raft make test ``` -------------------------------- ### Deploy Chaincode via REST API (JSON) Source: https://github.com/yeasy/blockchain_guide/blob/master/11_app_dev/chaincode_example01.md This JSON object represents a request to deploy the chaincode using a REST API. It specifies the deployment type, the chaincode path (currently supporting GitHub directories), constructor message with the function to initialize and its arguments, and the secure context for the user. ```json { "jsonrpc": "2.0", "method": "deploy", "params": { "type": 1, "chaincodeID": { "path": "https://github.com/ibm-blockchain/learn-chaincode/finished" }, "ctorMsg": { "function": "init", "args": [ "hi there" ] }, "secureContext": "jim" }, "id": 1 } ``` -------------------------------- ### Go module 获取和更新依赖 Source: https://github.com/yeasy/blockchain_guide/blob/master/appendix/golang/package.md 使用 go get 命令获取或更新依赖模块,并自动更新 go.mod 文件。'go get -u @' 用于获取指定版本,'go get -u all' 用于更新所有模块。go build -mod=readonly 编译时避免修改 go.mod,go build -mod=vendor 使用 vendor 目录编译。 ```bash go get -u @ go get -u all go build -mod=readonly go build -mod=vendor go list -m -u all go get -u ``` -------------------------------- ### 安装和使用 godoc - Go 语言文档工具 Source: https://github.com/yeasy/blockchain_guide/blob/master/appendix/golang/tools.md godoc 是一个强大的工具,可以以 web 服务的方式提供软件包的文档,并支持 Go 语言 playground。它可以通过 go get 命令安装,并可以通过命令行参数配置端口、开启索引和 playground 功能。常用于本地快速启动一个包含本地软件包文档和 playground 的网站。 ```bash $ go get golang.org/x/tools/cmd/godoc ``` ```bash $ godoc package [name ...] ``` ```bash $ godoc -http=:6060 -index -play ``` -------------------------------- ### 安装 govendor 工具 Source: https://github.com/yeasy/blockchain_guide/blob/master/appendix/golang/package.md 使用 go get 命令安装 govendor 工具,用于 Go 项目的第三方依赖管理。该工具将依赖包统一存放在 vendor 目录下。 ```bash go get -u -v github.com/kardianos/govendor ``` -------------------------------- ### Raft Leader Election Example (Python) Source: https://context7.com/yeasy/blockchain_guide/llms.txt A simplified Python implementation illustrating the Raft consensus algorithm's leader election process. It defines node states (Follower, Candidate, Leader) and simulates the steps a candidate takes to become a leader by requesting votes from peers. This code focuses on the election mechanism and assumes network communication is handled externally. ```python # Raft leader election example class RaftNode: FOLLOWER = 1 CANDIDATE = 2 LEADER = 3 def __init__(self, node_id, peers): self.node_id = node_id self.peers = peers self.state = self.FOLLOWER self.current_term = 0 self.voted_for = None self.log = [] def start_election(self): self.current_term += 1 self.state = self.CANDIDATE self.voted_for = self.node_id votes = 1 for peer in self.peers: if peer.request_vote(self.current_term, self.node_id, len(self.log)): votes += 1 if votes > (len(self.peers) + 1) / 2: self.become_leader() else: self.state = self.FOLLOWER def become_leader(self): self.state = self.LEADER # Start sending heartbeats self.send_heartbeats() def request_vote(self, term, candidate_id, log_length): if term > self.current_term and log_length >= len(self.log): self.current_term = term self.voted_for = candidate_id return True return False def append_entries(self, term, leader_id, entries): if term >= self.current_term: self.current_term = term self.state = self.FOLLOWER self.log.extend(entries) return True return False # Usage example nodes = [RaftNode(i, []) for i in range(5)] for node in nodes: node.peers = [n for n in nodes if n != node] # Simulate leader election nodes[0].start_election() ``` -------------------------------- ### Example Directory Structure of Generated Identities Source: https://github.com/yeasy/blockchain_guide/blob/master/09_fabric_deploy/start_local.md Example output from the 'tree' command showing the directory structure of identity files generated by cryptogen. It illustrates the organization of certificates and keys for orderer and peer organizations. ```bash tree -L 4 crypto-config crypto-config |-- ordererOrganizations | `-- example.com | |-- ca | | |-- 293def0fc6d07aab625308a3499cd97f8ffccbf9e9769bf4107d6781f5e8072b_sk | | `-- ca.example.com-cert.pem | |-- msp | | |-- admincerts/ | | |-- cacerts/ | | `-- tlscacerts/ | |-- orderers | | `-- orderer0.example.com/ | | `-- orderer1.example.com/ | | `-- orderer2.example.com/ | |-- tlsca | | |-- 2be5353baec06ca695f7c3b04ca0932912601a4411939bfcfd44af18274d5a65_sk | | `-- tlsca.example.com-cert.pem | `-- users | `-- Admin@example.com/ `-- peerOrganizations |-- org1.example.com | |-- ca | | |-- 501c5f828f58dfa3f7ee844ea4cdd26318256c9b66369727afe8437c08370aee_sk | | `-- ca.org1.example.com-cert.pem | |-- msp | | |-- admincerts/ | | |-- cacerts/ | | `-- tlscacerts/ | |-- peers | | |-- peer0.org1.example.com/ | | `-- peer1.org1.example.com/ | |-- tlsca | | |-- 592a08f84c99d6f083b3c5b9898b2ca4eb5fbb9d1e255f67df1fa14c123e4368_sk | | `-- tlsca.org1.example.com-cert.pem | `-- users | |-- Admin@org1.example.com/ | `-- User1@org1.example.com/ `-- org2.example.com |-- ca | |-- 86d97f9eb601868611eab5dc7df88b1f6e91e129160651e683162b958a728162_sk | `-- ca.org2.example.com-cert.pem |-- msp | |-- admincerts/ | |-- cacerts/ | `-- tlscacerts/ |-- peers | |-- peer0.org2.example.com/ | `-- peer1.org2.example.com/ |-- tlsca | |-- 4b87c416978970948dffadd0639a64a2b03bc89f910cb6d087583f210fb2929d_sk | `-- tlsca.org2.example.com-cert.pem `-- users |-- Admin@org2.example.com/ `-- User1@org2.example.com/ ``` -------------------------------- ### 安装 dep 工具 Source: https://github.com/yeasy/blockchain_guide/blob/master/appendix/golang/package.md 通过 go get 命令安装 dep 工具,这是 Go 团队开发的用于简化第三方依赖管理的实验性工具。dep 将依赖存放在 vendor 目录下,并使用 Gopkg.toml 和 Gopkg.lock 文件进行追踪。 ```bash go get -v -u github.com/golang/dep/cmd/dep ``` -------------------------------- ### Start Orderer Node in Hyperledger Fabric Source: https://github.com/yeasy/blockchain_guide/blob/master/09_fabric_deploy/start_local.md This snippet shows how to start an Orderer node for Hyperledger Fabric. It requires specific configuration files like orderer.yaml, MSP and TLS directories, and the system channel's genesis block. The command uses environment variables for configuration and outputs logs indicating successful service startup. ```bash $ orderer start [orderer/common/server] prettyPrintStruct -> INFO 002 Orderer config values: General.LedgerType = "file" General.ListenAddress = "0.0.0.0" General.ListenPort = 7050 General.TLS.Enabled = true ... [orderer/common/server] Start -> INFO 007 Beginning to serve requests ... ``` -------------------------------- ### gRPC Server Implementation in Go Source: https://github.com/yeasy/blockchain_guide/blob/master/appendix/grpc.md A complete Go program that implements a gRPC server. It defines the server logic for the SayHello method, registers it with the gRPC server, and starts listening for incoming requests. ```go package main import ( "context" "fmt" "log" "net" "google.golang.org/grpc" pb "hello/hello" ) const ( port = ":50051" ) type server struct{ } // 这里实现服务端接口中的方法。 func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { log.Printf("Received: %v\n", in.GetName()) return &pb.HelloReply{Message: "Hello " + in.GetName()}, } // 创建并启动一个 gRPC 服务的过程:创建监听套接字、创建服务端、注册服务、启动服务端。 func main() { lis, err := net.Listen("tcp", port) if err != nil { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer() pb.RegisterGreeterServer(s, &server{}) fmt.Printf("Starting listen on port: %s", port) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } } ``` -------------------------------- ### 安装和使用 golint - Go 代码风格检查 Source: https://github.com/yeasy/blockchain_guide/blob/master/appendix/golang/tools.md golint 是一个 Go 代码风格检查工具,用于打印出不符合 Go 语言推荐风格的代码。可以通过 `go get` 命令安装。使用时,指定软件包路径即可,`...` 用于递归检查子目录。 ```bash $ go get -u github.com/golang/lint/golint ``` ```bash $ golint $GOPATH/src/github.com/hyperledger/fabric/... ``` -------------------------------- ### Fabric cryptogen Configuration Example Source: https://github.com/yeasy/blockchain_guide/blob/master/09_fabric_deploy/start_local.md Example YAML configuration file for the Fabric cryptogen tool, defining orderer and peer organizations, their domains, CAs, node counts, and user counts. This file is essential for generating network identities. ```yaml OrdererOrgs: - Name: Orderer Domain: example.com CA: Country: US Province: California Locality: San Francisco Specs: - Hostname: orderer0 - Hostname: orderer1 - Hostname: orderer2 PeerOrgs: - Name: Org1 Domain: org1.example.com EnableNodeOUs: true CA: Country: US Province: California Locality: San Francisco Template: Count: 2 Users: Count: 1 - Name: Org2 Domain: org2.example.com EnableNodeOUs: true CA: Country: US Province: California Locality: San Francisco Template: Count: 2 Users: Count: 1 ``` -------------------------------- ### Package Chaincode for Deployment Source: https://github.com/yeasy/blockchain_guide/blob/master/10_fabric_op/chaincode_v2.md This command packages chaincode into a deployable .tar.gz file. It requires the path to the chaincode, the language it's written in (defaults to golang), and a label for the package. The output is a compressed archive ready for installation. ```bash peer lifecycle chaincode package test_cc.tar.gz \ -p \ -l golang \ --label testcc_v1.0 test_cc.tar.gz ``` -------------------------------- ### Ethereum Smart Contract Deployment and Interaction (JavaScript & Solidity) Source: https://context7.com/yeasy/blockchain_guide/llms.txt Illustrates deploying and interacting with Solidity smart contracts on Ethereum using Geth and Web3. Includes contract compilation, deployment, private chain initialization, and method calls/transactions. Requires Geth client and Solidity compiler. ```solidity // testContract.sol - Simple multiplication contract pragma solidity ^0.4.0; contract testContract { function multiply(uint a) returns(uint d) { d = a * 7; } } ``` ```javascript // Compile contract // $ solc --bin --abi testContract.sol // Deploy in Geth console > personal.unlockAccount(eth.accounts[0]) > code = "0x6060604052341561000c57fe5b5b60a58061001b6000396000f300..." > abi = [{"constant":false,"inputs":[{"name":"a","type":"uint256"}],"name":"multiply","outputs":[{"name":"d","type":"uint256"}],"payable":false,"type":"function"}] > myContract = eth.contract(abi) > contract = myContract.new({from:eth.accounts[0], data:code, gas:1000000}) // Wait for mining, then interact > miner.start(1) // ... wait for transaction confirmation ... > miner.stop() // Call contract methods > contract.multiply.call(10) 70 // Send transaction to contract > contract.multiply.sendTransaction(10, {from:eth.accounts[0]}) "0xa019c2e5367b3ad2bbfa427b046ab65c81ce2590672a512cc973b84610eee53e" // Initialize private chain // $ geth --datadir ./data init genesis.json // $ geth --identity "TestNode" --rpc --rpcport "8545" --datadir ./data --port "30303" --nodiscover console // genesis.json configuration { "config": { "chainId": 22, "homesteadBlock": 0, "eip155Block": 0, "eip158Block": 0 }, "alloc": {}, "coinbase": "0x0000000000000000000000000000000000000000", "difficulty": "0x400", "gasLimit": "0x2fefd8", "nonce": "0x0000000000000038" } ``` -------------------------------- ### Upgrade Chaincode to a New Version Source: https://github.com/yeasy/blockchain_guide/blob/master/10_fabric_op/chaincode.md The 'peer chaincode upgrade' command allows updating an existing chaincode to a new version without losing its current state. This process involves installing the new version and then executing the upgrade command, which starts a new container for the updated chaincode. ```bash peer chaincode install \ -n test_cc \ -v 1.1 \ -p github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02_new ``` ```bash peer chaincode upgrade \ -o orderer0:7050 \ -n test_cc \ -C ${APP_CHANNEL} \ -v 1.1 \ -c '{"Args":["re-init","c","60"]}' \ -P "${policy}" \ --collections-config "${collection_config}" \ --tls \ --cafile ${ORDERER_TLS_CA} ``` -------------------------------- ### Go module 初始化 Source: https://github.com/yeasy/blockchain_guide/blob/master/appendix/golang/package.md 使用 go mod init 命令初始化 Go module,创建 go.mod 文件来管理项目依赖。module 是 Go 1.11 版本引入的官方依赖管理方案。 ```bash go mod init ``` -------------------------------- ### Go gRPC Client Usage Example Source: https://github.com/yeasy/blockchain_guide/blob/master/appendix/grpc.md This Go program demonstrates how to use a generated gRPC client. It sets up a connection to the server, creates a client instance, and calls the 'SayHello' method, printing the server's response. It handles command-line arguments for the name to greet and sets a timeout for the request. ```go package main import ( "context" "log" "os" "time" "google.golang.org/grpc" pb "hello/hello" ) const ( address = "localhost:50051" defaultName = "world" ) func main() { // Set up a connection to the server. conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock()) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() c := pb.NewGreeterClient(conn) // Contact the server and print out its response. name := defaultName if len(os.Args) > 1 { name = os.Args[1] } ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name}) if err != nil { log.Fatalf("could not greet: %v", err) } log.Printf("Greeting: %s", r.GetMessage()) } ``` -------------------------------- ### 编译并运行 Go 程序 - go run Source: https://github.com/yeasy/blockchain_guide/blob/master/appendix/golang/tools.md go run 命令用于编译并直接运行一个 Go 主程序包。该程序包必须包含一个 `main` 函数作为入口点。它适用于快速执行单个 Go 文件或包含 `main` 包的项目。 ```bash $ go run . ``` -------------------------------- ### govendor 初始化和管理依赖 Source: https://github.com/yeasy/blockchain_guide/blob/master/appendix/golang/package.md govendor 提供了多种命令来管理 Go 项目的依赖。'init' 初始化 vendor 目录,'list' 列出依赖,'add' 添加依赖,'update' 更新依赖,'remove' 删除依赖,'status' 查看包状态,'fetch' 获取依赖,'sync' 同步依赖,'get' 拉取依赖。 ```bash govendor init govendor list govendor add +external govendor add PKG_PATH govendor update govendor remove govendor status govendor fetch govendor sync govendor get ``` -------------------------------- ### Go module 子命令 Source: https://github.com/yeasy/blockchain_guide/blob/master/appendix/golang/package.md Go module 提供了一系列子命令来操作依赖。'download' 下载依赖到缓存,'edit' 编辑 go.mod 文件,'graph' 查看依赖结构,'init' 初始化,'tidy' 整理依赖,'vendor' 复制依赖到 vendor 目录,'verify' 校验依赖,'why' 解释依赖原因。 ```bash go mod download go mod edit go mod graph go mod init go mod tidy go mod vendor go mod verify go mod why ``` -------------------------------- ### Install Chaincode Package on Peer Node Source: https://github.com/yeasy/blockchain_guide/blob/master/10_fabric_op/chaincode.md This command installs a chaincode package onto a specified Peer node. It bundles the chaincode source code and environment into a Chaincode Install Package (CIP) and sends it to the Peer. This operation interacts only with the Peer node, does not modify the ledger, and does not generate transactions. The executor typically needs to be an administrator of the Peer node. ```bash CORE_PEER_ADDRESS=peer.your_domain.com:7051 \ peer chaincode install \ -n test_cc \ -v 1.0 \ -p github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02 ``` -------------------------------- ### Set Working Directory Source: https://github.com/yeasy/blockchain_guide/blob/master/09_fabric_deploy/install_docker.md Sets the working directory to $FABRIC_CA_ROOT, which is the root directory of the fabric-ca project. ```dockerfile WORKDIR $FABRIC_CA_ROOT ``` -------------------------------- ### Expose Fabric CA Port Source: https://github.com/yeasy/blockchain_guide/blob/master/09_fabric_deploy/install_docker.md Exposes port 7054, which is the default port for the fabric-ca-server service to accept incoming connections. ```dockerfile EXPOSE 7054 ```