fabric2.x running example

fabric2.x running
Install the fabric environment

There are many installation tutorials on the Internet, and 2.2 is now commonly used

start network
cd /home/xx/go/src/github.com/hyperledger/fabric/scripts/fabric-samples
cd test-network
./network.sh up
Components of the test network

Every node and user that interacts with the Fabric network needs to belong to an organization or federation that is a member of the network. The test network has two federation members, Org1 and Org2. The network also includes an orderer organization that maintains the network's ordering service.

Nodes are the fundamental building blocks of any Fabric network. Nodes store the blockchain ledger and verify transactions before committing to the ledger. Nodes run smart contracts that contain business logic for managing assets on the blockchain ledger.

Ordering services allow nodes to focus on validating transactions and committing them to the ledger. After the orderers receive endorsed transactions from clients, they agree on the order of the transactions and then add them to the block. The blocks are then distributed to regular nodes, which add the blocks to the blockchain ledger. Orderers also operate system channels that define the functionality of the Fabric network, such as how blocks are generated and which versions of Fabric a node can use. System channels define which organizations are members of the federation.

docker ps -a
create channel

A channel is a dedicated communication layer between members of a particular network. Channels can only be used by organizations invited to the channel and are not visible to other members of the network. Each channel has a separate blockchain ledger. Create a channel with the default name mychannel

./network.sh createChannel

Channels with custom names can also be created using channel flags. For example, the following command will create a channel named channel1.

./network.sh createChannel -c channel1

If you want to start a network and create a channel in one step, you can use both the up and createChannel modes:

./network.sh up createChannel
Start the chaincode on the channel

After a channel is created, smart contracts can be used to interact with the channel ledger. Smart contracts contain business logic for managing assets on the blockchain ledger. Applications run by network members can invoke smart contracts to create assets on the ledger, as well as change and transfer those assets. Applications can also query smart contracts to read data on the ledger.

To ensure that transactions are valid, transactions created using smart contracts often need to be signed by multiple organizations before being committed to the channel ledger. Multisig is an integral part of Fabric's trust model. Requiring multiple endorsements for a transaction prevents an organization on a channel from tampering with its node's ledger or using non-consented business logic. To sign a transaction, each organization needs to invoke and execute a smart contract on its node, which then signs the output of the transaction. If the output is consistent and has been signed by enough organizations, the transaction can be committed to the ledger. The set organization's policy that specifies which smart contracts need to execute on the channel is called the endorsement policy and is set for each chaincode as part of the chaincode definition.

In Fabric, smart contracts are deployed on the network in packages called chaincodes. Chaincode is installed on an organization's nodes and then deployed to a channel where it can be used to endorse transactions and interact with the blockchain ledger. Before deploying chaincode to a channel, channel members need to agree on a chaincode definition that establishes chaincode governance. When the desired number of organizations agree, the chaincode definition can be committed to the channel and the chaincode can be used.

The chain code needs to be placed in the /home/blockchain/go/src/github.com/hyperledger/fabric/scripts/fabric-samples directory

Pay attention to the fabric2.x version when the chain code imports shim and peer

"github.com/hyperledger/fabric-chaincode-go/shim"
sc "github.com/hyperledger/fabric-protos-go/peer"
./network.sh deployCC -ccn car_demo -ccp ../car_demo/chaincode-go -ccl go
./network.sh deployCC -ccn cbc -ccp ../cbc/chaincode-go -ccl go
  • -ccn : to specify the chain code name
  • -ccl : for the specified chain code language
Use the terminal command line to interact with the network

After starting the test network, you can use the peer cli client to interact with the network. Through the peer cli client, you can call deployed smart contracts, update channels, or install and deploy new smart contracts.

First make sure that the operation directory is the test-netwok directory

pwd

Execute the command to add the cli client to the environment variable

export PATH=${PWD}/../bin:$PATH

You also need to set FABRIC_CFG_PATH in the fabric-samples codebase to point to the core.yaml file in it:

export FABRIC_CFG_PATH=$PWD/../config/

Set environment variables that allow org1 to operate peer cli:

export CORE_PEER_TLS_ENABLED=true
export CORE_PEER_LOCALMSPID="Org1MSP"
export CORE_PEER_TLS_ROOTCERT_FILE=${
    
    PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt
export CORE_PEER_MSPCONFIGPATH=${
    
    PWD}/organizations/peerOrganizations/org1.example.com/users/[email protected]/msp
export CORE_PEER_ADDRESS=localhost:7051

CORE_PEER_TLS_ROOTCERT_FILEAnd CORE_PEER_MSPCONFIGPATHthe environment variable points to organizationsthe cryptographic material in Org1's folder.

Execute the following command to initialize the ledger with some assets: Note that the parameter after -n is changed to the chaincode name

peer chaincode invoke -o localhost:7050 --ordererTLSHostnameOverride orderer.example.com --tls --cafile ${
    
    PWD}/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -C mychannel -n car_demo --peerAddresses localhost:7051 --tlsRootCertFiles ${
    
    PWD}/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt --peerAddresses localhost:9051 --tlsRootCertFiles ${
    
    PWD}/organizations/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt -c '{"function":"initLedger","Args":[]}'

Execute the following command to query the list of vehicles in the channel ledger:

peer chaincode query -C mychannel -n car_demo -c '{"Args":["queryAllCars"]}'
peer chaincode query -C mychannel -n cbc -c '{"Args":["RegisterUser","Alice"]}'

peer chaincode query -C mychannel -n abe_lightweight -c '{"Args":["RegisterUser","Alice"]}'
Use the application to interact with the network
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"

	"github.com/hyperledger/fabric-sdk-go/pkg/core/config"
	"github.com/hyperledger/fabric-sdk-go/pkg/gateway"
	"github.com/robfig/cron"
)

func main() {
    
    

	err := os.RemoveAll("./keystore")
	err = os.RemoveAll("./wallet")
	if err != nil {
    
    
		log.Fatal(err)
	}
	log.Println("============ application-golang starts ============")

	err = os.Setenv("DISCOVERY_AS_LOCALHOST", "true")
	if err != nil {
    
    
		log.Fatalf("Error setting DISCOVERY_AS_LOCALHOST environemnt variable: %v", err)
	}

	wallet, err := gateway.NewFileSystemWallet("wallet")
	if err != nil {
    
    
		log.Fatalf("Failed to create wallet: %v", err)
	}

	if !wallet.Exists("appUser") {
    
    
		err = populateWallet(wallet)
		if err != nil {
    
    
			log.Fatalf("Failed to populate wallet contents: %v", err)
		}
	}

	ccpPath := filepath.Join(
		"..",
		"..",
		"test-network",
		"organizations",
		"peerOrganizations",
		"org1.example.com",
		"connection-org1.yaml",
	)

	gw, err := gateway.Connect(
		gateway.WithConfig(config.FromFile(filepath.Clean(ccpPath))),
		gateway.WithIdentity(wallet, "appUser"),
	)
	if err != nil {
    
    
		log.Fatalf("Failed to connect to gateway: %v", err)
	}
	defer gw.Close()

	network, err := gw.GetNetwork("mychannel")//链接到channel
	if err != nil {
    
    
		log.Fatalf("Failed to get network: %v", err)
	}
	contract := network.GetContract("test") //获得智能合约

	log.Println("--> Submit Transaction: RegisterUser, function creates the initial set of assets on the ledger")

	result, err := contract.SubmitTransaction("RegisterUser""Alice") //提交交易
	print(result)
	if err != nil {
    
    
		log.Fatalf("Failed to Submit transaction: %v", err)
	}
	log.Println(string(result))

}

func populateWallet(wallet *gateway.Wallet) error {
    
    
	log.Println("============ Populating wallet ============")
	credPath := filepath.Join(
		"..",
		"..",
		"test-network",
		"organizations",
		"peerOrganizations",
		"org1.example.com",
		"users",
		"[email protected]",
		"msp",
	)

	certPath := filepath.Join(credPath, "signcerts", "[email protected]")
	// read the certificate pem
	cert, err := ioutil.ReadFile(filepath.Clean(certPath))
	if err != nil {
    
    
		return err
	}

	keyDir := filepath.Join(credPath, "keystore")
	// there's a single file in this dir containing the private key
	files, err := ioutil.ReadDir(keyDir)
	if err != nil {
    
    
		return err
	}
	if len(files) != 1 {
    
    
		return fmt.Errorf("keystore folder should have contain one file")
	}
	keyPath := filepath.Join(keyDir, files[0].Name())
	key, err := ioutil.ReadFile(filepath.Clean(keyPath))
	if err != nil {
    
    
		return err
	}

	identity := gateway.NewX509Identity("Org1MSP", string(cert), string(key))

	return wallet.Put("appUser", identity)
}
close the network
./network.sh down
Tips

Note that depending on the version of the package may cause an error

Guess you like

Origin blog.csdn.net/weixin_44233803/article/details/123165669