时间:2023-06-10 19:24:01 | 来源:网站运营
时间:2023-06-10 19:24:01 来源:网站运营
超级漂亮的网上花店html静态页面:这是刚学习的时候使用dreamweaver设计的页面,纯css+jspkg目录是fabric go sdk的主要实现,doc文档介绍了不同目录所提供的功能,以及给出了接口调用样例:
fabsdk包
import "github.com/hyperledger/fabric go sdk/pkg/core/config"import "github.com/hyperledger/fabric go sdk/pkg/fabsdk"sdk, err := fabsdk.New(config.FromFile(c.ConfigPath))if err != nil { log.Panicf("failed to create fabric sdk: %s", err)}
fabsdk.WithOrg("Org1")
和fabsdk.WithUser("Admin")
指定Org1的Admin账户,使用sdk.Context
创建clientProvider
,然后通过resmgmt.New
创建fabric-SDK-GO资源管理客户端。import "github.com/hyperledger/fabric go sdk/pkg/client/resmgmt"rcp := sdk.Context(fabsdk.WithUser("Admin"), fabsdk.WithOrg("Org1"))rc, err := resmgmt.New(rcp)if err != nil { log.Panicf("failed to create resource client: %s", err)}
import "github.com/hyperledger/fabric go sdk/pkg/client/channel"ccp := sdk.ChannelContext(ChannelID, fabsdk.WithUser("User1"))cc, err := channel.New(ccp)if err != nil { log.Panicf("failed to create channel client: %s", err)}
方法二:// New creates a new Client instance mspClient, err := mspclient.New(sdk.Context(), mspclient.WithOrg(info.OrgName)) if err != nil { return fmt.Errorf("根据指定的 OrgName 创建 Org MSP 客户端实例失败: %v", err) } // Returns: signing identity adminIdentity, err := mspClient.GetSigningIdentity(info.OrgAdmin) if err != nil { return fmt.Errorf("获取指定id的签名标识失败: %v", err) } // SaveChannelRequest holds parameters for save channel request channelReq := resmgmt.SaveChannelRequest{ChannelID:info.ChannelID, ChannelConfigPath:info.ChannelConfig, SigningIdentities:[]msp.SigningIdentity{adminIdentity}} // save channel response with transaction ID _, err = resMgmtClient.SaveChannel(channelReq, resmgmt.WithRetry(retry.DefaultResMgmtOpts), resmgmt.WithOrdererEndpoint(info.OrdererOrgName)) if err != nil { return fmt.Errorf("创建应用通道失败: %v", err) } fmt.Println("通道已成功创建,")
// allows for peers to join existing channel with optional custom options (specific peers, filtered peers). If peer(s) are not specified in options it will default to all peers that belong to client's MSP. err = info.OrgResMgmt.JoinChannel( info.ChannelID, resmgmt.WithRetry(retry.DefaultResMgmtOpts), resmgmt.WithOrdererEndpoint(info.OrdererOrgName) ) if err != nil { return fmt.Errorf("Peers加入通道失败: %v", err) } fmt.Println("peers 已成功加入通道.")
fmt.Println("开始安装链码......") // creates new go lang chaincode package ccPkg, err := gopackager.NewCCPackage(info.ChaincodePath, info.ChaincodeGoPath) if err != nil { return nil, fmt.Errorf("创建链码包失败: %v", err) } // contains install chaincode request parameters installCCReq := resmgmt.InstallCCRequest{Name: info.ChaincodeID, Path: info.ChaincodePath, Version: ChaincodeVersion, Package: ccPkg} /*可以制定安装在哪个peer节点上 reqPeers := resmgmt.WithTargetEndpoints("peer0.org1.example.com") resps, err := rc.InstallCC(req, reqPeers) */ // allows administrators to install chaincode onto the filesystem of a peer _, err = info.OrgResMgmt.InstallCC(installCCReq, resmgmt.WithRetry(retry.DefaultResMgmtOpts)) if err != nil { return nil, fmt.Errorf("安装链码失败: %v", err) } fmt.Println("指定的链码安装成功")
// endorser policyorg1OrOrg2 := "OR('Org1MSP.member','Org2MSP.member')"ccPolicy, err := cauthdsl.FromString(org1OrOrg2)if err != nil { return errors.WithMessage(err, "gen policy from string error")}// new requestargs := packArgs([]string{"init", "a", "100", "b", "200"})req := resmgmt.InstantiateCCRequest{ Name: c.CCID, Path: c.CCPath, Version: v, Args: args, Policy: ccPolicy,}// send request and handle responsereqPeers := resmgmt.WithTargetEndpoints("peer0.org1.example.com")resp, err := rc.InstantiateCC(ChannelID, req, reqPeers)if err != nil { return errors.WithMessage(err, "instantiate chaincode error")}
方法二:// returns a policy that requires one valid ccPolicy := policydsl.SignedByAnyMember([]string{"org1.kevin.kongyixueyuan.com"}) instantiateCCReq := resmgmt.InstantiateCCRequest{Name: info.ChaincodeID, Path: info.ChaincodePath, Version: ChaincodeVersion, Args: [][]byte{[]byte("init")}, Policy: ccPolicy} // instantiates chaincode with optional custom options (specific peers, filtered peers, timeout). If peer(s) are not specified _, err = info.OrgResMgmt.InstantiateCC(info.ChannelID, instantiateCCReq, resmgmt.WithRetry(retry.DefaultResMgmtOpts)) if err != nil { return nil, fmt.Errorf("实例化链码失败: %v", err) } fmt.Println("链码实例化成功")
// endorser policyorg1AndOrg2 := "AND('Org1MSP.member','Org2MSP.member')"ccPolicy, err := c.genPolicy(org1AndOrg2)if err != nil { return errors.WithMessage(err, "gen policy from string error")}// new requestargs := packArgs([]string{"init", "a", "100", "b", "200"})req := resmgmt.UpgradeCCRequest{ Name: c.CCID, Path: c.CCPath, Version: v, Args: args, Policy: ccPolicy,}// send request and handle responsereqPeers := resmgmt.WithTargetEndpoints("peer0.org1.example.com")resp, err := rc.UpgradeCC(ChannelID, req, reqPeers)if err != nil { return errors.WithMessage(err, "instantiate chaincode error")}
// new channel request for invokeargs := packArgs([]string{"a", "b", "10"})req := channel.Request{ ChaincodeID: c.CCID, Fcn: "invoke", Args: args,}// send request and handle response// peers is neededreqPeers := channel.WithTargetEndpoints("peer0.org1.example.com")resp, err := cc.Execute(req, reqPeers)if err != nil { return errors.WithMessage(err, "invoke chaincode error")}log.Printf("invoke chaincode tx: %s", resp.TransactionID)
// new channel request for queryreq := channel.Request{ ChaincodeID: c.CCID, Fcn: "query", Args: packArgs([]string{keys}),}// send request and handle responsereqPeers := channel.WithTargetEndpoints(peer)resp, err := cc.Query(req, reqPeers)if err != nil { return errors.WithMessage(err, "query chaincode error")}log.Printf("query chaincode tx: %s", resp.TransactionID)log.Printf("result: %v", string(resp.Payload))
/** author: liuhui*/package sdkInitimport ( "fmt" "github.com/astaxie/beego/logs" mspclient "github.com/hyperledger/fabric-sdk-go/pkg/client/msp" "github.com/hyperledger/fabric-sdk-go/pkg/client/resmgmt" "github.com/hyperledger/fabric-sdk-go/pkg/common/errors/retry" "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/msp" "github.com/hyperledger/fabric-sdk-go/pkg/core/config" "github.com/hyperledger/fabric-sdk-go/pkg/fabsdk" "github.com/hyperledger/fabric-sdk-go/pkg/client/channel" "github.com/hyperledger/fabric-sdk-go/pkg/fab/ccpackager/gopackager" "github.com/hyperledger/fabric-sdk-go/third_party/github.com/hyperledger/fabric/common/policydsl")const ChaincodeVersion = "1.0"//initialized fabric sdkfunc SetupSDK(ConfigFile string, initialized bool) (*fabsdk.FabricSDK, error) { if initialized { //logs.Error("Fabric SDK has been initialized") return nil, fmt.Errorf("Fabric SDK has been initialized") } sdk, err := fabsdk.New(config.FromFile(ConfigFile)) if err != nil { //logs.Error("Instantiation Fabric SDK failed") return nil, fmt.Errorf("Instantiation Fabric SDK failed: %v", err) } logs.Informational("Fabric SDK is initialized successfully") return sdk, nil}// create channel and join peersfunc CreateChannel(sdk *fabsdk.FabricSDK, info *InitInfo) error { clientContext := sdk.Context(fabsdk.WithUser(info.OrgAdmin), fabsdk.WithOrg(info.OrgName)) if clientContext == nil { return fmt.Errorf("Failed to create client context based on organization name and administrator user") } // New returns a resource management client instance. resMgmtClient, err := resmgmt.New(clientContext) if err != nil { return fmt.Errorf("Failed to create resource management client by client context: %v", err) } // New creates a new Client instance mspClient, err := mspclient.New(sdk.Context(), mspclient.WithOrg(info.OrgName)) if err != nil { return fmt.Errorf("Failed to create Org MSP client by specified OrgName: %v", err) } // Returns: signing identity adminIdentity, err := mspClient.GetSigningIdentity(info.OrgAdmin) if err != nil { return fmt.Errorf("Failed to get the signature of the specified ID: %v", err) } // SaveChannelRequest holds parameters for save channel request channelReq := resmgmt.SaveChannelRequest{ChannelID: info.ChannelID, ChannelConfigPath: info.ChannelConfig, SigningIdentities: []msp.SigningIdentity{adminIdentity}} // save channel response with transaction ID _, err = resMgmtClient.SaveChannel(channelReq, resmgmt.WithRetry(retry.DefaultResMgmtOpts), resmgmt.WithOrdererEndpoint(info.OrdererOrgName)) if err != nil { return fmt.Errorf("Failed to create channle: %v", err) } logs.Informational("Create channel successful") info.OrgResMgmt = resMgmtClient // allows for peers to join existing channel with optional custom options (specific peers, filtered peers). If peer(s) are not specified in options it will default to all peers that belong to client's MSP. err = info.OrgResMgmt.JoinChannel(info.ChannelID, resmgmt.WithRetry(retry.DefaultResMgmtOpts), resmgmt.WithOrdererEndpoint(info.OrdererOrgName)) if err != nil { return fmt.Errorf("Peers failed to join channel: %v", err) } logs.Informational("Peers join channel successful") return nil}//install and instantiate chaincodefunc InstallAndInstantiateCC(sdk *fabsdk.FabricSDK, info *InitInfo) (*channel.Client, error) { logs.Informational("Start to install chaincode") // creates new go lang chaincode package ccPkg, err := gopackager.NewCCPackage(info.ChaincodePath, info.ChaincodeGoPath) if err != nil { return nil, fmt.Errorf("Failed to create chaincode package: %v", err) } // contains install chaincode request parameters installCCReq := resmgmt.InstallCCRequest{Name: info.ChaincodeID, Path: info.ChaincodePath, Version: ChaincodeVersion, Package: ccPkg} // allows administrators to install chaincode onto the filesystem of a peer _, err = info.OrgResMgmt.InstallCC(installCCReq, resmgmt.WithRetry(retry.DefaultResMgmtOpts)) if err != nil { return nil, fmt.Errorf("Failed to install chaincode: %v", err) } logs.Informational("Install chaincode successful") logs.Informational("Start to instantiate chaincode") // returns a policy that requires one valid ccPolicy := policydsl.SignedByAnyMember([]string{"org1.institution.com"}) instantiateCCReq := resmgmt.InstantiateCCRequest{Name: info.ChaincodeID, Path: info.ChaincodePath, Version: ChaincodeVersion, Args: [][]byte{[]byte("init")}, Policy: ccPolicy} // instantiates chaincode with optional custom options (specific peers, filtered peers, timeout). If peer(s) are not specified _, err = info.OrgResMgmt.InstantiateCC(info.ChannelID, instantiateCCReq, resmgmt.WithRetry(retry.DefaultResMgmtOpts)) if err != nil { return nil, fmt.Errorf("Failed to instantiate chaincode: %v", err) } logs.Informational("Instantiate chaincode successful") clientChannelContext := sdk.ChannelContext(info.ChannelID, fabsdk.WithUser(info.UserName), fabsdk.WithOrg(info.OrgName)) // returns a Client instance. Channel client can query chaincode, execute chaincode and register/unregister for chaincode events on specific channel. channelClient, err := channel.New(clientChannelContext) if err != nil { return nil, fmt.Errorf("Failed to create channel context: %v", err) } logs.Informational("Create channel client successful ,you can use it to execute transactions.") return channelClient, nil}func ChannelClient(sdk *fabsdk.FabricSDK, info *InitInfo) (*channel.Client,error){ clientChannelContext := sdk.ChannelContext(info.ChannelID, fabsdk.WithUser(info.UserName), fabsdk.WithOrg(info.OrgName)) // returns a Client instance. Channel client can query chaincode, execute chaincode and register/unregister for chaincode events on specific channel. channelClient, err := channel.New(clientChannelContext) if err != nil { return nil, fmt.Errorf("Failed to create channel context: %v", err) } logs.Informational("Create channel client successful ,you can use it to execute transactions.") return channelClient, nil}
(2)调用客户端package mainimport ( "github.com/astaxie/beego" "github.com/astaxie/beego/logs" _ "github.com/lib/pq" "jingjinjiapi/controllers" _ "jingjinjiapi/routers" "jingjinjiapi/sdkInit" "os")const ( //config of SDK configFile = "config.yaml" //mark whehter the client is initialized initialized = false //the chaincode id EduCC = "educc" DOC_TYPE = "insObj")func main() { //setting loggers level and location logs.SetLogger("file", `{"filename":"logs/jingjinji_beego.log"}`) logs.SetLevel(logs.LevelInformational) logs.Info("setting logs level : information") //initialized the information of sdk initInfo := &sdkInit.InitInfo{ ChannelID: "institutionchannel", ChannelConfig: os.Getenv("GOPATH") + "/src/jingjinjiapi/fixtures/artifacts/channel.tx", OrgAdmin: "Admin", OrgName: "Org1", OrdererOrgName: "orderer.institution.com", ChaincodeID: EduCC, ChaincodeGoPath: os.Getenv("GOPATH"), ChaincodePath: "jingjinjiapi/chaincode/", UserName: "User1", } var serviceSetup controllers.ServiceSetup //initialize SDK,use the function:fabsdk.new sdk, err := sdkInit.SetupSDK(configFile, initialized) if err != nil { logs.Error(err.Error()) return } //free the resource until the main program finish defer sdk.Close() flag := false if flag{ //create channel and add the peer node to the channel err = sdkInit.CreateChannel(sdk, initInfo) if err != nil { logs.Error(err.Error()) return } //install chaincode and instantiate chaincode channelClient, err := sdkInit.InstallAndInstantiateCC(sdk, initInfo) if err != nil { logs.Error(err.Error()) return } serviceSetup.ChaincodeID = EduCC serviceSetup.Client = channelClient }else{ channelClient, err := sdkInit.ChannelClient(sdk,initInfo) if err != nil { logs.Error(err.Error()) return } serviceSetup.ChaincodeID = EduCC serviceSetup.Client = channelClient } logs.Informational(serviceSetup) //===========================================// //start Testing ............................................. //start service beego.Router("/v1/institution", &controllers.InstitutionController{Setup: &serviceSetup})}
关键词:静态,漂亮,超级