fabric-gosdk

 

package demo

import (
"fmt"
"github.com/hyperledger/fabric-sdk-go/pkg/client/event"
"log"
"testing"
"time"

"github.com/hyperledger/fabric-sdk-go/pkg/client/channel"
"github.com/hyperledger/fabric-sdk-go/pkg/core/config"
"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
)

const (
org1CfgPath = "./org1-config.yaml"
ChannelID = "jackchannel"

peer0Org1 = "peer0.org1.example.com"
peer0Org2 = "peer0.org2.example.com"
ccID = "mycc"
)

/*
./byfn.sh generate -c jackchannel
./byfn.sh -m up -c jackchannel
*/
func TestDemo(t *testing.T) {
sdk, err := fabsdk.New(config.FromFile(org1CfgPath))
if err != nil {
log.Panicf("failed to create fabric sdk: %s", err)
}

ccp := sdk.ChannelContext(ChannelID, fabsdk.WithUser("User1"))
cc, err := channel.New(ccp)
if err != nil {
log.Panicf("failed to create channel client: %s", err)
}

ec, err := event.New(ccp, event.WithBlockEvents())
if err != nil {
log.Panicf("failed to create channel client: %s", err)
}

eventID := ".*"
reg, notifier, err := ec.RegisterChaincodeEvent(ccID, eventID)
if err != nil {
t.Fatalf("Failed to register cc event: %s", err)
}
defer ec.Unregister(reg)

query(cc)
execute2(cc)
time.Sleep(5 * time.Second)
query(cc)
for {
select {
case ccEvent := <-notifier:
t.Logf("Received CC event: %#v\n", ccEvent)
t.Log(string(ccEvent.Payload))
case <-time.After(time.Second * 5):
t.Fatalf("Did NOT receive CC event for eventId(%s)\n", eventID)
}
}
}


func query(cc *channel.Client) {
// new channel request for query
req := channel.Request{
ChaincodeID: ccID,
Fcn: "query",
Args: packArgs([]string{"a"}),
}
// send request and handle response
reqPeers := channel.WithTargetEndpoints(peer0Org1)

response, err := cc.Query(req, reqPeers)
if err != nil {
fmt.Printf("failed to query chaincode: %s\n", err)
}

if len(response.Payload) > 0 {
fmt.Printf("chaincode query success,the value is %s\n", string(response.Payload))
}
}

func execute(cc *channel.Client) {
args := packArgs([]string{"a", "b", "10"})
req := channel.Request{
ChaincodeID: ccID,
Fcn: "invoke",
Args: args,
}
peers := []string{peer0Org1, peer0Org2}
reqPeers := channel.WithTargetEndpoints(peers...)
response, err := cc.Execute(req, reqPeers)
if err != nil {
fmt.Printf("failed to Execute chaincode: %s\n", err)
}
fmt.Printf("Execute chaincode success,txId:%s\n", response.TransactionID)
}

func execute2(cc *channel.Client) {
args := packArgs([]string{"a", "b", "10"})
req := channel.Request{
ChaincodeID: ccID,
Fcn: "finish",
Args: args,
}
peers := []string{peer0Org1, peer0Org2}
reqPeers := channel.WithTargetEndpoints(peers...)
response, err := cc.Execute(req, reqPeers)
if err != nil {
fmt.Printf("failed to Execute chaincode: %s\n", err)
}
fmt.Printf("Execute chaincode success,txId:%s\n", response.TransactionID)
}

func packArgs(paras []string) [][]byte {
var args [][]byte
for _, k := range paras {
args = append(args, []byte(k))
}
return args
}



#
# Copyright SecureKey Technologies Inc. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
#
#
# The network connection profile provides client applications the information about the target
# blockchain network that are necessary for the applications to interact with it. These are all
# knowledge that must be acquired from out-of-band sources. This file provides such a source.
#

# copied from fabric-sdk-go/test/fixtures/config/config_e2e_pkcs11.yaml

#
# Schema version of the content. Used by the SDK to apply the corresponding parsing rules.
#
version: 1.0.0

#
# The client section used by GO SDK.
#
client:
# Which organization does this application instance belong to? The value must be the name of an org
# defined under "organizations"
organization: Org1
logging:
# Develope can using debug to get more information
# level: debug
level: info
cryptoconfig:
path: /Users/jalyzhang/Documents/t2/untitled29/fabric-samples/first-network/crypto-config
# Some SDKs support pluggable KV stores, the properties under "credentialStore"
# are implementation specific
credentialStore:
# [Optional]. Used by user store. Not needed if all credentials are embedded in configuration
# and enrollments are performed elswhere.
path: "/tmp/examplestore"


# [Optional] BCCSP config for the client. Used by GO SDK.
BCCSP:
security:
enabled: true
default:
provider: "SW"
hashAlgorithm: "SHA2"
softVerify: true
level: 256

tlsCerts:
# [Optional]. Use system certificate pool when connecting to peers, orderers (for negotiating TLS) Default: false
systemCertPool: true
# [Optional]. Client key and cert for TLS handshake with peers and orderers
client:
# 使用byfn中User1@org1的证书
keyfile: /Users/jalyzhang/Documents/t2/untitled29/fabric-samples/first-network/crypto-config/peerOrganizations/org1.example.com/users/User1@org1.example.com/tls/client.key
certfile: /Users/jalyzhang/Documents/t2/untitled29/fabric-samples/first-network/crypto-config/peerOrganizations/org1.example.com/users/User1@org1.example.com/tls/client.cert



################################## General part ##################################


#
# [Optional]. But most apps would have this section so that channel objects can be constructed
# based on the content below. If an app is creating channels, then it likely will not need this
# section.
#
channels:
# name of the channel
jackchannel:
# Required. list of orderers designated by the application to use for transactions on this
# channel. This list can be a result of access control ("org1" can only access "ordererA"), or
# operational decisions to share loads from applications among the orderers. The values must
# be "names" of orgs defined under "organizations/peers"
# deprecated: not recommended, to override any orderer configuration items, entity matchers should be used.
# orderers:
# - orderer.example.com

# 不要缺少当前channel的orderer节点
orderers:
- orderer.example.com

# Required. list of peers from participating orgs
peers:
peer0.org1.example.com:
# [Optional]. will this peer be sent transaction proposals for endorsement? The peer must
# have the chaincode installed. The app can also use this property to decide which peers
# to send the chaincode install request. Default: true
endorsingPeer: true

# [Optional]. will this peer be sent query proposals? The peer must have the chaincode
# installed. The app can also use this property to decide which peers to send the
# chaincode install request. Default: true
chaincodeQuery: true

# [Optional]. will this peer be sent query proposals that do not require chaincodes, like
# queryBlock(), queryTransaction(), etc. Default: true
ledgerQuery: true

# [Optional]. will this peer be the target of the SDK's listener registration? All peers can
# produce events but the app typically only needs to connect to one to listen to events.
# Default: true
eventSource: true

# Add other peers in mychannel for byfn
peer1.org1.example.com:
endorsingPeer: true
chaincodeQuery: true
ledgerQuery: true
eventSource: true

peer0.org2.example.com:
endorsingPeer: true
chaincodeQuery: true
ledgerQuery: true
eventSource: true

peer1.org2.example.com:
endorsingPeer: true
chaincodeQuery: true
ledgerQuery: true
eventSource: true

# [Optional]. The application can use these options to perform channel operations like retrieving channel
# config etc.
policies:
#[Optional] options for retrieving channel configuration blocks
queryChannelConfig:
#[Optional] min number of success responses (from targets/peers)
minResponses: 1
#[Optional] channel config will be retrieved for these number of random targets
maxTargets: 1
#[Optional] retry options for query config block
retryOpts:
#[Optional] number of retry attempts
attempts: 5
#[Optional] the back off interval for the first retry attempt
initialBackoff: 500ms
#[Optional] the maximum back off interval for any retry attempt
maxBackoff: 5s
#[Optional] he factor by which the initial back off period is exponentially incremented
backoffFactor: 2.0

#
# list of participating organizations in this network
#
organizations:
Org1:
mspid: Org1MSP
# set msp files path
cryptoPath: /Users/jalyzhang/Documents/t2/untitled29/fabric-samples/first-network/crypto-config/peerOrganizations/org1.example.com/users/{username}@org1.example.com/msp

# Add peers for org1
peers:
- peer0.org1.example.com
- peer1.org1.example.com


# the profile will contain public information about organizations other than the one it belongs to.
# These are necessary information to make transaction lifecycles work, including MSP IDs and
# peers with a public URL to send transaction proposals. The file will not contain private
# information reserved for members of the organization, such as admin key and certificate,
# fabric-ca registrar enroll ID and secret, etc.
Org2:
mspid: Org2MSP
cryptoPath: /Users/jalyzhang/Documents/t2/untitled29/fabric-samples/first-network/crypto-config/peerOrganizations/org2.example.com/users/{username}@org2.example.com/msp

# Add peers for org2
peers:
- peer0.org2.example.com
- peer1.org2.example.com


# Orderer Org name
ordererorg:
# Membership Service Provider ID for this organization
mspID: OrdererMSP
cryptoPath: /Users/jalyzhang/Documents/t2/untitled29/fabric-samples/first-network/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp


#
# List of orderers to send transaction and channel create/update requests to. For the time
# being only one orderer is needed. If more than one is defined, which one get used by the
# SDK is implementation specific. Consult each SDK's documentation for its handling of orderers.
#
orderers:
orderer.example.com:
# [Optional] Default: Infer from hostname
url: grpcs://172.16.5.4:7050

# these are standard properties defined by the gRPC library
# they will be passed in as-is to gRPC client constructor
#TODO to be moved to high level, common for all grpc connections
grpcOptions:
ssl-target-name-override: orderer.example.com
keep-alive-time: 0s
keep-alive-timeout: 20s
keep-alive-permit: false
fail-fast: false

#will be taken into consideration if address has no protocol defined, if true then grpc or else grpcs
allow-insecure: false

tlsCACerts:
# Certificate location absolute path
# Replace to orderer cert path
path: /Users/jalyzhang/Documents/t2/untitled29/fabric-samples/first-network/crypto-config/ordererOrganizations/example.com/tlsca/tlsca.example.com-cert.pem

#
# List of peers to send various requests to, including endorsement, query
# and event listener registration.
#
peers:
peer0.org1.example.com:
# this URL is used to send endorsement and query requests
# [Optional] Default: Infer from hostname
# 表明使用grpcs协议,设置IP和端口号,使用域名会无法连接
# url: grpcs://peer0.org1.example.com:7051
url: grpcs://172.16.5.4:7051

#TODO to be moved to high level, common for all grpc connections
grpcOptions:
ssl-target-name-override: peer0.org1.example.com
keep-alive-time: 0s
keep-alive-timeout: 20s
keep-alive-permit: false
fail-fast: false

#will be taken into consideration if address has no protocol defined, if true then grpc or else grpcs
allow-insecure: false

tlsCACerts:
# Certificate location absolute path
path: /Users/jalyzhang/Documents/t2/untitled29/fabric-samples/first-network/crypto-config/peerOrganizations/org1.example.com/tlsca/tlsca.org1.example.com-cert.pem

peer0.org2.example.com:
# Replace the port
url: grpcs://172.16.5.4:9051
grpcOptions:
ssl-target-name-override: peer0.org2.example.com
keep-alive-time: 0s
keep-alive-timeout: 20s
keep-alive-permit: false
fail-fast: false

#will be taken into consideration if address has no protocol defined, if true then grpc or else grpcs
allow-insecure: false
tlsCACerts:
path: /Users/jalyzhang/Documents/t2/untitled29/fabric-samples/first-network/crypto-config/peerOrganizations/org2.example.com/tlsca/tlsca.org2.example.com-cert.pem
posted @ 2022-03-02 10:39  zJanly  阅读(203)  评论(0编辑  收藏  举报