fabric-sdk-go client开发
1.代码结构图
2.prescription-client-config.yaml文件
1 name: "chaoyang-prescription-network" 2 description: "chao yang hospital prescription network" 3 version: 1.0.0 4 client: 5 organization: cyorg.bjgoodwill.com 6 logging: 7 level: info 8 cryptoconfig: 9 path: ${GOPATH}/src/github.com/prescriptionserver/client/go/crypto-config 10 #path: /opt/app/fabric/cli/user/cyorg.bjgoodwill.com/Admin-peer0cyorg.bjgoodwill..com 11 credentialStore: 12 path: /tmp/state-store 13 cryptoStore: 14 path: /tmp/msp 15 BCCSP: 16 security: 17 enabled: true 18 default: 19 provider: "SW" 20 hashAlgorithm: "SHA2" 21 softVerify: true 22 level: 256 23 tlsCerts: 24 systemCertPool: false 25 client: 26 key: 27 path: 28 #path: /opt/app/fabric/cli/user/cyorg.bjgoodwill.com/Admin-peer0.cyorg.bjgoodwill.com/tls/client.key 29 cert: 30 path: 31 #path: /opt/app/fabric/cli/user/cyorg.bjgoodwill.com/Admin-peer0.cyorg.bjgoodwill.com/tls/client.crt 32 channels: 33 prescriptionchannel: 34 peers: 35 peer0.cyorg.bjgoodwill.com: 36 endorsingPeer: true 37 chaincodeQuery: true 38 ledgerQuery: true 39 eventSource: true 40 policies: 41 queryChannelConfig: 42 minResponses: 1 43 maxTargets: 1 44 retryOpts: 45 attempts: 5 46 initialBackoff: 500ms 47 maxBackoff: 5s 48 backoffFactor: 2.0 49 50 prescriptionmultiorgchannel: 51 52 peers: 53 peer0.cyorg.bjgoodwill.com: 54 endorsingPeer: true 55 chaincodeQuery: true 56 ledgerQuery: true 57 eventSource: true 58 59 peer0.jhorg.bjgoodwill.com: 60 endorsingPeer: true 61 chaincodeQuery: true 62 ledgerQuery: true 63 eventSource: true 64 65 peer0.wjworg.bjgoodwill.com: 66 endorsingPeer: true 67 chaincodeQuery: true 68 ledgerQuery: true 69 eventSource: true 70 71 # [Optional]. The application can use these options to perform channel operations like retrieving channel 72 # config etc. 73 policies: 74 #[Optional] options for retrieving channel configuration blocks 75 queryChannelConfig: 76 #[Optional] min number of success responses (from targets/peers) 77 minResponses: 1 78 #[Optional] channel config will be retrieved for these number of random targets 79 maxTargets: 1 80 #[Optional] retry options for query config block 81 retryOpts: 82 #[Optional] number of retry attempts 83 attempts: 5 84 #[Optional] the back off interval for the first retry attempt 85 initialBackoff: 500ms 86 #[Optional] the maximum back off interval for any retry attempt 87 maxBackoff: 5s 88 #[Optional] he factor by which the initial back off period is exponentially incremented 89 backoffFactor: 2.0 90 91 organizations: 92 cyorg.bjgoodwill.com: 93 mspid: CYOrgMSP 94 cryptoPath: peerOrganizations/cyorg.bjgoodwill.com/users/Admin@cyorg.bjgoodwill.com/msp/ 95 #cryptoPath: msp/ 96 peers: 97 - peer0.cyorg.bjgoodwill.com 98 certificateAuthorities: 99 - ca.cyorg.bjgoodwill.com 100 101 jhorg.bjgoodwill.com: 102 mspid: JHOrgMSP 103 # This org's MSP store (absolute path or relative to client.cryptoconfig) 104 cryptoPath: peerOrganizations/jhorg.bjgoodwill.com/users/Admin@jhorg.bjgoodwill.com/msp 105 peers: 106 - peer0.jhorg.bjgoodwill.com 107 certificateAuthorities: 108 - ca.jhorg.bjgoodwill.com 109 110 wjworg.bjgoodwill.com: 111 mspid: WJWOrgMSP 112 # This org's MSP store (absolute path or relative to client.cryptoconfig) 113 cryptoPath: peerOrganizations/wjworg.bjgoodwill.com/users/Admin@wjworg.bjgoodwill.com/msp 114 peers: 115 - peer0.wjworg.bjgoodwill.com 116 certificateAuthorities: 117 - ca.wjworg.bjgoodwill.com 118 # Orderer Org name 119 ordererorg: 120 # Membership Service Provider ID for this organization 121 mspID: "PrescriptionOrdererMSP" 122 123 # Needed to load users crypto keys and certs for this org (absolute path or relative to global crypto path, DEV mode) 124 cryptoPath: ordererOrganizations/bjgoodwill.com/users/Admin@bjgoodwill.com/msp 125 126 orderers: 127 orderer.bjgoodwill.com: 128 url: grpc://192.168.229.136:7050 129 grpcOptions: 130 ssl-target-name-override: orderer.bjgoodwill.com 131 keep-alive-time: 0s 132 keep-alive-timeout: 20s 133 keep-alive-permit: false 134 fail-fast: false 135 allow-insecure: false 136 tlsCACerts: 137 path: ${GOPATH}/src/github.com/prescriptionserver/client/go/crypto-config/ordererOrganizations/bjgoodwill.com/tlsca/tlsca.bjgoodwill.com-cert.pem 138 #path: /opt/app/fabric/cli/user/member1.example.com/Admin-peer0.member1.example.com/tlsca.member1.example.com-cert.pem 139 peers: 140 peer0.cyorg.bjgoodwill.com: 141 url: grpc://192.168.229.138:7051 142 eventUrl: grpc://192.168.229.138:7053 143 grpcOptions: 144 ssl-target-name-override: peer0.cyorg.bjgoodwill.com 145 keep-alive-time: 0s 146 keep-alive-timeout: 20s 147 keep-alive-permit: false 148 fail-fast: false 149 allow-insecure: false 150 tlsCACerts: 151 path: ${GOPATH}/src/github.com/prescriptionserver/client/go/crypto-config/peerOrganizations/cyorg.bjgoodwill.com/tlsca/tlsca.cyorg.bjgoodwill.com-cert.pem 152 #path: /opt/app/fabric/cli/user/cyorg.bjgoodwill.com/Admin-peer0.cyorg.bjgoodwill.com/tls/ca.crt 153 154 peer0.jhorg.bjgoodwill.com: 155 url: peer0.jhorg.bjgoodwill.com:7051 156 eventUrl: peer0.jhorg.bjgoodwill.com:7053 157 grpcOptions: 158 ssl-target-name-override: peer0.jhorg.bjgoodwill.com 159 keep-alive-time: 0s 160 keep-alive-timeout: 20s 161 keep-alive-permit: false 162 fail-fast: false 163 allow-insecure: false 164 tlsCACerts: 165 path: ${GOPATH}/src/github.com/prescriptionserver/client/go/crypto-config/peerOrganizations/jhorg.bjgoodwill.com/tlsca/tlsca.jhorg.bjgoodwill.com-cert.pem 166 #path: /opt/app/fabric/cli/user/member1.example.com/Admin-peer0.member1.example.com/tls/ca.crt 167 168 peer0.wjworg.bjgoodwill.com: 169 url: peer0.wjworg.bjgoodwill.com:7051 170 eventUrl: peer0.wjworg.bjgoodwill.com:7053 171 grpcOptions: 172 ssl-target-name-override: peer0.wjworg.bjgoodwill.com 173 keep-alive-time: 0s 174 keep-alive-timeout: 20s 175 keep-alive-permit: false 176 fail-fast: false 177 allow-insecure: false 178 tlsCACerts: 179 path: ${GOPATH}/src/github.com/prescriptionserver/client/go/crypto-config/peerOrganizations/wjworg.bjgoodwill.com/tlsca/tlsca.wjworg.bjgoodwill.com-cert.pem 180 #path: /opt/app/fabric/cli/user/member1.example.com/Admin-peer0.member1.example.com/tls/ca.crt 181 certificateAuthorities: 182 ca.fbi.citizens.com: 183 url: https://192.168.229.138:7054 184 tlsCACerts: 185 # Comma-Separated list of paths 186 path: ${GOPATH}/src/github.com/prescriptionserver/client/go/crypto-config/peerOrganizations/cyorg.bjgoodwill.com/tlsca/tlsca.cyorg.bjgoodwill.com-cert.pem 187 # Client key and cert for SSL handshake with Fabric CA 188 client: 189 key: 190 path: ${GOPATH}/src/github.com/prescriptionserver/client/go/crypto-config/peerOrganizations/cyorg.bjgoodwill.com/users/User1@cyorg.bjgoodwill.com/tls/client.key 191 cert: 192 path: ${GOPATH}/src/github.com/prescriptionserver/client/go/crypto-config/peerOrganizations/cyorg.bjgoodwill.com/users/User1@cyorg.bjgoodwill.com/tls/client.crt 193 194 # Fabric-CA supports dynamic user enrollment via REST APIs. A "root" user, a.k.a registrar, is 195 # needed to enroll and invoke new users. 196 registrar: 197 enrollId: admin 198 enrollSecret: adminpw 199 # [Optional] The optional name of the CA. 200 caName: ca.cyorg.bjgoodwill.com 201 202 entityMatchers: 203 orderer: 204 - pattern: (\w*)orderer.bjgoodwill.com(\w*) 205 urlSubstitutionExp: grpc://orderer.bjgoodwill.com:7050 206 sslTargetOverrideUrlSubstitutionExp: orderer.bjgoodwill.com 207 mappedHost: orderer.bjgoodwill.com
3.prescriptionclient.yaml文件
1 prescriptionclient: 2 fabricsdk: 3 configfile: ./client/go/config/prescription-client-config.yaml 4 resmgmt: 5 orgname: cyorg.bjgoodwill.com 6 orgadmin: Admin 7 channel: 8 channelconfig: /src/github.com/prescriptionserver/client/go/channel-artifacts/prescription.tx 9 channelid: prescriptionchannel 10 username: User1 11 msp: 12 orgname: cyorg.bjgoodwill.com 13 mspid: CYOrgMSP 14 filepath: 15 configfilepath: ./client/go/config/prescriptionclient.yaml
4.config.go代码
1 package util 2 3 import ( 4 "encoding/json" 5 "io/ioutil" 6 "github.com/prescriptionserver/client/go/global" 7 "log" 8 ) 9 10 var prescriptionclientconfig []byte 11 12 type PrescriptionClientConfig struct { 13 PrescriptionClient PrescriptionClient `yaml:"prescriptionclient"` 14 } 15 type PrescriptionClient struct { 16 FabricSDK FabricSDK `yaml:"fabricsdk"` 17 ResMgmt ResMgmt `yaml:"resmgmt"` 18 Channel Channel `yaml:"channel"` 19 Msp Msp `yaml:"msp"` 20 FilePath FilePath `yaml:"filepath"` 21 } 22 type FabricSDK struct { 23 ConfigFile string `yaml:"configfile"` 24 } 25 type Channel struct { 26 ChannelConfig string `yaml:"channelconfig"` 27 ChannelID string `yaml:"channelid"` 28 UserName string `yaml:"username"` 29 } 30 type ResMgmt struct { 31 OrgName string `yaml:"orgname"` 32 OrgAdmin string `yaml:"orgadmin"` 33 } 34 type Msp struct { 35 OrgName string `yaml:"orgname"` 36 MSPID string `yaml:"mspid"` 37 } 38 type FilePath struct { 39 ConfigFilePath string `yaml:"configfilepath"` 40 } 41 42 func GetPrescriptionClientConfig() (pcc *PrescriptionClientConfig,err error) { 43 err = json.Unmarshal(prescriptionclientconfig,&pcc) 44 return pcc,err 45 } 46 func init() { 47 var err error 48 prescriptionclientconfig,err =ioutil.ReadFile(global.ConfigFile) 49 if err != nil{ 50 global.Logger.Errorf("prescriptionclient.yaml file get error: %v",err) 51 log.Fatalf("prescriptionclient.yaml file get error: %v",err) 52 } 53 }
5.ecslfabricsdk.go代码
1 package encapsulation 2 3 import ( 4 "github.com/hyperledger/fabric-sdk-go/pkg/fabsdk" 5 "sync" 6 "github.com/prescriptionserver/client/go/global" 7 "github.com/hyperledger/fabric-sdk-go/pkg/core/config" 8 "github.com/prescriptionserver/client/go/util" 9 "github.com/hyperledger/fabric-sdk-go/pkg/client/channel" 10 "github.com/hyperledger/fabric-sdk-go/pkg/client/event" 11 ) 12 13 type EcslFabricSDK struct { 14 sdk *fabsdk.FabricSDK 15 } 16 17 var ( 18 efsdk *EcslFabricSDK 19 once sync.Once 20 ) 21 22 func GetEcslFabricSDKInstance() (*EcslFabricSDK,error) { 23 var err error 24 once.Do(func() { 25 cf, e := util.GetPrescriptionClientConfig() 26 if e != nil{ 27 global.Logger.Errorf("load prescriptionclient.yaml file error: %v\n",err) 28 err=e 29 }else { 30 configProvider :=config.FromFile(cf.PrescriptionClient.FabricSDK.ConfigFile) 31 sdk,err :=fabsdk.New(configProvider) 32 if err != nil{ 33 global.Logger.Errorf("initialize fabsdk error: %v\n",err) 34 }else { 35 efsdk=&EcslFabricSDK{ 36 sdk:sdk, 37 } 38 err = nil 39 } 40 } 41 42 }) 43 return efsdk,err 44 } 45 func (efsdk *EcslFabricSDK) GetChannelAndEventClient(channelid string, 46 username string)(channelclient *channel.Client,eventclient *event.Client,err error) { 47 sdk, err := GetEcslFabricSDKInstance() 48 if err != nil{ 49 return nil,nil,err 50 } 51 clientcontext := sdk.sdk.ChannelContext(channelid, fabsdk.WithUser(username)) 52 channelclient,err = channel.New(clientcontext) 53 if err != nil{ 54 return channelclient,nil,err 55 } 56 eventclient,err =event.New(clientcontext) 57 return channelclient,eventclient,err 58 } 59 func (efsdk *EcslFabricSDK) GetChannelClient(channelid string, 60 username string) (channelclient *channel.Client,err error) { 61 sdk, err := GetEcslFabricSDKInstance() 62 if err != nil{ 63 return nil,err 64 } 65 clientcontext :=sdk.sdk.ChannelContext(channelid,fabsdk.WithUser(username)) 66 channelclient,err =channel.New(clientcontext) 67 return channelclient,err 68 } 69 func (efsdk *EcslFabricSDK) Close() { 70 if efsdk != nil{ 71 efsdk.sdk.Close() 72 efsdk= nil 73 } 74 }
6.ecslresmgmt.go代码
1 package encapsulation 2 3 import ( 4 "github.com/hyperledger/fabric-sdk-go/pkg/client/resmgmt" 5 "errors" 6 "github.com/hyperledger/fabric-sdk-go/pkg/fabsdk" 7 "log" 8 "github.com/prescriptionserver/client/go/global" 9 "github.com/prescriptionserver/client/go/util" 10 "os" 11 mspc "github.com/hyperledger/fabric-sdk-go/pkg/client/msp" 12 msp2 "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/msp" 13 "github.com/hyperledger/fabric-sdk-go/pkg/common/errors/retry" 14 "strings" 15 "github.com/hyperledger/fabric-sdk-go/third_party/github.com/hyperledger/fabric/protos/peer" 16 "github.com/hyperledger/fabric-sdk-go/pkg/fab/ccpackager/gopackager" 17 "github.com/hyperledger/fabric-sdk-go/third_party/github.com/hyperledger/fabric/common/cauthdsl" 18 ) 19 20 type EcslResmgmtClient struct { 21 OrgName string 22 OrgAdmin string 23 ConfigFile string 24 initialized bool 25 resMgmtClient *resmgmt.Client 26 efsdk *EcslFabricSDK 27 } 28 29 func (e *EcslResmgmtClient) Initialize() error { 30 if e.OrgAdmin=="" || e.OrgName=="" || e.ConfigFile==""{ 31 return errors.New("orgname or orgadmin or configfile is not null") 32 } 33 if e.initialized{ 34 global.Logger.Error("ecslresmgmtclient initialize again !") 35 return nil 36 } 37 sdk,err := GetEcslFabricSDKInstance() 38 if err != nil{ 39 return err 40 } 41 e.efsdk=sdk 42 log.Printf("ecsl fabric sdk created") 43 resourceManagerClientContext := e.efsdk.sdk.Context(fabsdk.WithUser(e.OrgAdmin),fabsdk.WithOrg(e.OrgName)) 44 if err != nil{ 45 return err 46 } 47 resMgmtClient,err:=resmgmt.New(resourceManagerClientContext) 48 if err != nil{ 49 return err 50 } 51 e.resMgmtClient =resMgmtClient 52 e.initialized=true 53 return nil 54 } 55 func (e *EcslResmgmtClient) CreateChannel(channelid string,targetpeerendpoint string, 56 orgname string,orgadmin string,ordererid string) error { 57 if channelid == "" || targetpeerendpoint==""{ 58 return errors.New("channeldid or target peer endpoint is not null") 59 } 60 if e.ChannelExists(channelid,targetpeerendpoint){ 61 return errors.New("channelid already exists") 62 } 63 if e.initialized == false{ 64 err :=e.Initialize() 65 if err != nil{ 66 return err 67 } 68 } 69 cf,err:= util.GetPrescriptionClientConfig() 70 if err != nil{ 71 return err 72 } 73 mspclient ,err:= mspc.New(e.efsdk.sdk.Context(),mspc.WithOrg(orgname)) 74 if err != nil{ 75 return err 76 } 77 adminidentity,err := mspclient.GetSigningIdentity(orgadmin) 78 if err != nil{ 79 return err 80 } 81 req:=resmgmt.SaveChannelRequest{ 82 ChannelID:channelid, 83 ChannelConfigPath:os.Getenv("GOPATH") + cf.PrescriptionClient.Channel.ChannelConfig, 84 SigningIdentities:[]msp2.SigningIdentity{adminidentity}, 85 } 86 response, err := e.resMgmtClient.SaveChannel(req,resmgmt.WithOrdererEndpoint(ordererid)) 87 if err != nil || response.TransactionID == ""{ 88 return err 89 } 90 log.Println("channel created success") 91 return nil 92 } 93 func (e *EcslResmgmtClient) JoinChannel(channelid string,ordererid string) error{ 94 if channelid =="" || ordererid==""{ 95 return errors.New("join channel ordererid or channelid is not null") 96 } 97 if e.initialized == false{ 98 err:=e.Initialize() 99 if err != nil{ 100 return err 101 } 102 } 103 err := e.resMgmtClient.JoinChannel(channelid, resmgmt.WithRetry(retry.DefaultResMgmtOpts), 104 resmgmt.WithOrdererEndpoint(ordererid)) 105 return err 106 } 107 func (e *EcslResmgmtClient) IsInitialized() bool { 108 return e.initialized 109 } 110 func (e *EcslResmgmtClient) ChannelExists(channelid string, targetpeerendpoint ...string) bool { 111 if e.initialized ==false{ 112 err:=e.Initialize() 113 if err != nil{ 114 global.Logger.Errorf("channel exists error: %v\n",err) 115 return false 116 } 117 }else { 118 response, err := e.resMgmtClient.QueryChannels(resmgmt.WithTargetEndpoints(targetpeerendpoint...)) 119 if err != nil{ 120 global.Logger.Errorf("channel exists function query channels error: %v\n",err) 121 return false 122 } 123 if response != nil{ 124 for _,channel:=range response.Channels{ 125 if channel.ChannelId == channelid{ 126 return true 127 } 128 } 129 } 130 } 131 return false 132 } 133 func (e *EcslResmgmtClient) ChaincodeInstallExists(chaincodeid string,peerendpoint string) bool { 134 if chaincodeid =="" || peerendpoint==""{ 135 global.Logger.Error("chaincodeexists function chaincodeid or peerendpoint is not null \n") 136 return false 137 } 138 if e.initialized==false{ 139 err :=e.Initialize() 140 if err != nil{ 141 global.Logger.Errorf("resmgmt initialize error: %v\n",err) 142 return false 143 } 144 } 145 ccinsqes, err := e.resMgmtClient.QueryInstalledChaincodes(resmgmt.WithTargetEndpoints(peerendpoint)) 146 if err != nil || ccinsqes==nil{ 147 global.Logger.Errorf("resmgmt query installed chaincodes error : %v\n",err) 148 return false 149 } 150 for _,cc :=range ccinsqes.Chaincodes{ 151 if strings.EqualFold(cc.Name,chaincodeid){ 152 return true 153 } 154 } 155 return false 156 } 157 func (e *EcslResmgmtClient) ChaincodeInstantiatedExists(chaincodeid string,peerendpoint string) bool { 158 if chaincodeid =="" || peerendpoint==""{ 159 global.Logger.Error("chaincodeexists function chaincodeid or peerendpoint is not null \n") 160 return false 161 } 162 if e.initialized==false{ 163 err :=e.Initialize() 164 if err != nil{ 165 global.Logger.Errorf("resmgmt initialize error: %v\n",err) 166 return false 167 } 168 } 169 ccinstqes, err := e.resMgmtClient.QueryInstantiatedChaincodes(chaincodeid, 170 resmgmt.WithTargetEndpoints(peerendpoint)) 171 if err != nil ||ccinstqes == nil{ 172 global.Logger.Errorf("chaincodeinstantiatedexists resmgmt query instantiated chaincodes error : %v\n",err) 173 return false 174 } 175 for _,cc :=range ccinstqes.Chaincodes{ 176 if strings.EqualFold(cc.Name,chaincodeid){ 177 return true 178 } 179 } 180 return false 181 } 182 func (e *EcslResmgmtClient) GetInstantiatedChaincodes(channelid string, 183 peerendpoint string) ([]*peer.ChaincodeInfo,error) { 184 if channelid =="" || peerendpoint==""{ 185 global.Logger.Error("getchaincodes function channelid or peerendpoint is not null \n") 186 return nil,errors.New("getchaincodes function channelid or peerendpoint is not null") 187 } 188 if e.initialized==false{ 189 err :=e.Initialize() 190 if err != nil{ 191 global.Logger.Errorf("getchaincodesresmgmt initialize error: %v\n",err) 192 return nil,err 193 } 194 } 195 ccinstqes, err := e.resMgmtClient.QueryInstantiatedChaincodes(channelid, 196 resmgmt.WithTargetEndpoints(peerendpoint)) 197 if err != nil ||ccinstqes == nil{ 198 return nil,err 199 } 200 return ccinstqes.Chaincodes,nil 201 } 202 func (e *EcslResmgmtClient) GetInstalledChaincodes( 203 peerendpoint string) ([]*peer.ChaincodeInfo,error) { 204 if peerendpoint==""{ 205 global.Logger.Error("getchaincodes function peerendpoint is not null \n") 206 return nil,errors.New("getchaincodes function peerendpoint is not null") 207 } 208 if e.initialized==false{ 209 err :=e.Initialize() 210 if err!= nil{ 211 global.Logger.Errorf("getchaincodesresmgmt initialize error: %v\n",err) 212 return nil,err 213 } 214 } 215 ccinsqes, err := e.resMgmtClient.QueryInstalledChaincodes(resmgmt.WithTargetEndpoints(peerendpoint)) 216 if err != nil || ccinsqes==nil{ 217 global.Logger.Errorf("getchaincodes resmgmt query installed chaincodes error : %v\n",err) 218 return nil,err 219 } 220 return ccinsqes.Chaincodes,nil 221 } 222 func (e *EcslResmgmtClient) InstallChaincode(chaincodeid string,chaincodepath string, 223 chaincodeversion string,peerendpoint string) error { 224 if chaincodeid =="" ||chaincodepath==""||chaincodeversion==""||peerendpoint==""{ 225 return errors.New("install chaincode function with chaincodeid or"+ 226 " chaincodepath or chaincodeversion or peerendpoit is not null \n") 227 } 228 if e.initialized==false{ 229 err :=e.Initialize() 230 if err != nil{ 231 global.Logger.Errorf("installchaincode resmgmt initialize error: %v\n",err) 232 return err 233 } 234 } 235 ccpkg,err :=gopackager.NewCCPackage(chaincodepath,os.Getenv("GOPATH")) 236 if err != nil{ 237 return err 238 } 239 if e.ChaincodeInstallExists(chaincodeid,peerendpoint){ 240 return errors.New("chaincodeid install already exists") 241 } 242 insccreq:=resmgmt.InstallCCRequest{ 243 Name:chaincodeid, 244 Path:chaincodepath, 245 Version:chaincodeversion, 246 Package:ccpkg, 247 } 248 _,err = e.resMgmtClient.InstallCC(insccreq, resmgmt.WithRetry(retry.DefaultResMgmtOpts), 249 resmgmt.WithTargetEndpoints(peerendpoint)) 250 return err 251 } 252 func (e *EcslResmgmtClient) InstantiatedChaincode(chaincodeid string,channelid string, 253 chaincodeversion string,peerendpoint string,orgmspid string) error { 254 if chaincodeid =="" ||channelid==""||chaincodeversion==""||peerendpoint==""{ 255 return errors.New("instantiated chaincode function with chaincodeid or"+ 256 " channelid or chaincodeversion or peerendpoit or orgmspid is not null \n") 257 } 258 if e.initialized==false{ 259 err :=e.Initialize() 260 if err != nil{ 261 global.Logger.Errorf("installchaincode resmgmt initialize error: %v\n",err) 262 return err 263 } 264 } 265 if e.ChaincodeInstantiatedExists(chaincodeid,peerendpoint){ 266 return errors.New("chaincode instantiated already exists") 267 } 268 ccpolicy :=cauthdsl.SignedByMspMember(orgmspid) 269 instccreq:=resmgmt.InstantiateCCRequest{ 270 Name:chaincodeid, 271 Path:os.Getenv("GOPATH"), 272 Version:chaincodeversion, 273 Args:[][]byte{[]byte("init"),[]byte("init")}, 274 Policy:ccpolicy, 275 } 276 resp, err := e.resMgmtClient.InstantiateCC(channelid, instccreq) 277 if err != nil{ 278 return err 279 } 280 if resp.TransactionID==""{ 281 return errors.New("failed to instanitated chaincode") 282 } 283 return nil 284 } 285 func (e *EcslResmgmtClient) Close() { 286 if e != nil{ 287 e.efsdk.Close() 288 } 289 }
7.clientglobal.go代码
1 package global 2 3 import "github.com/hyperledger/fabric/common/flogging" 4 5 6 var( 7 Logger =flogging.MustGetLogger("PrescriptionChaincode") 8 ) 9 10 const ( 11 ConfigFile="./client/go/config/prescriptionclient.yaml" 12 )
8.prescriptionclientinvoke.go代码
1 package operation 2 3 import ( 4 "github.com/prescriptionserver/client/go/clientmodel" 5 "errors" 6 "encoding/json" 7 "github.com/prescriptionserver/client/go/encapsulation" 8 "strings" 9 "github.com/hyperledger/fabric-sdk-go/pkg/client/channel" 10 "log" 11 "time" 12 "fmt" 13 ) 14 15 type PrescriptionClientInvoke struct { 16 ChannelID string 17 UserName string 18 ChaincodeID string 19 EventID string 20 } 21 22 func (pc *PrescriptionClientInvoke) Publish(blockchain clientmodel.PrescriptionBlockchain) (string,error) { 23 if pc.ChannelID ==""||pc.ChaincodeID ==""||pc.UserName==""{ 24 return "",errors.New("client publish function channelid or username or chaincode is not null") 25 } 26 var args []string 27 args = append(args,"publish") 28 if blockchain.PrescriptionID=="" || blockchain.PrescriptionSummary==""{ 29 return "",errors.New("prescription block chain entity is not nil") 30 } 31 bytes, err := json.Marshal(blockchain) 32 if err != nil{ 33 return "",err 34 } 35 transientdatamap := make(map[string][]byte) 36 transientdatamap["result"]=[]byte("transient data in prescription invoke publish") 37 ecslsdk ,err:= encapsulation.GetEcslFabricSDKInstance() 38 if err != nil{ 39 return "",err 40 } 41 //defer ecslsdk.Close() 42 channelclient, eventclient, err := ecslsdk.GetChannelAndEventClient(pc.ChannelID, pc.UserName) 43 if err != nil{ 44 return "" ,err 45 } 46 eventid:="" 47 if strings.TrimSpace(pc.EventID)==""{ 48 eventid="eventPrescriptionInvokePublish" 49 }else { 50 eventid=pc.EventID 51 } 52 registration, chanevent, err := eventclient.RegisterChaincodeEvent(pc.ChaincodeID, eventid) 53 if err != nil{ 54 return "",err 55 } 56 defer eventclient.Unregister(registration) 57 chlreq := channel.Request{ 58 ChaincodeID:pc.ChaincodeID, 59 Fcn:args[0], 60 Args:[][]byte{bytes}, 61 TransientMap:transientdatamap, 62 } 63 response, err := channelclient.Execute(chlreq) 64 if err != nil{ 65 return "",nil 66 } 67 select { 68 case ccevent:=<-chanevent: 69 log.Printf("received cc event: %v\n",ccevent) 70 case <-time.After(time.Second * 20): 71 return "",fmt.Errorf("publish did not receive cc event for eventid: %s",eventid) 72 } 73 return string(response.TransactionID),nil 74 } 75 func (pc *PrescriptionClientInvoke) Endorse(pid string,prpdid string, 76 prpwid string) (string,error) { 77 if pc.ChannelID ==""||pc.ChaincodeID ==""||pc.UserName==""{ 78 return "",errors.New("client endorse function channelid or username or chaincode is not null") 79 } 80 if strings.TrimSpace(pid)=="" || strings.TrimSpace(prpdid)=="" || strings.TrimSpace(prpwid) ==""{ 81 return "",errors.New("client endorse function pid or prpdid or prpwid is not null") 82 } 83 var args []string 84 args=append(args,"endorse") 85 args=append(args,pid) 86 args=append(args,prpdid) 87 args=append(args,prpwid) 88 transientdatamap :=make(map[string][]byte) 89 transientdatamap["result"]=[]byte("transient data in prescription invoke endorse") 90 ecslsdk,err :=encapsulation.GetEcslFabricSDKInstance() 91 if err != nil{ 92 return "",err 93 } 94 channelclient, eventclient, err := ecslsdk.GetChannelAndEventClient(pc.ChannelID, pc.UserName) 95 if err != nil{ 96 return "", nil 97 } 98 eventid:="" 99 if strings.TrimSpace(pc.EventID)==""{ 100 eventid="eventPrescriptionInvokeEndorse" 101 }else { 102 eventid=pc.EventID 103 } 104 registration, chanevent, err := eventclient.RegisterChaincodeEvent(pc.ChaincodeID, eventid) 105 if err != nil{ 106 return "", nil 107 } 108 defer eventclient.Unregister(registration) 109 chlreq :=channel.Request{ 110 ChaincodeID:pc.ChaincodeID, 111 Fcn:args[0], 112 Args:[][]byte{[]byte(args[1]),[]byte(args[2]),[]byte(args[3])}, 113 TransientMap:transientdatamap, 114 } 115 response, err := channelclient.Execute(chlreq) 116 if err != nil{ 117 return "", nil 118 } 119 select { 120 case ccevent := <-chanevent: 121 log.Printf("received cc event: %v\n", ccevent) 122 case <-time.After(time.Second * 20): 123 return "", fmt.Errorf("endorse did not receive cc event for eventid: %s", eventid) 124 } 125 return string(response.TransactionID), nil 126 //defer ecslsdk.Close() 127 128 } 129 func (pc *PrescriptionClientInvoke) Accept(pid string,rpdid string,rpwid string) (string,error) { 130 if pc.ChannelID ==""||pc.ChaincodeID ==""||pc.UserName==""{ 131 return "",errors.New("client publish function channelid or username or chaincode is not null") 132 } 133 if strings.TrimSpace(pid)=="" || strings.TrimSpace(rpdid)=="" || strings.TrimSpace(rpwid) ==""{ 134 return "",errors.New("client accept function pid or rpdid or rpwid is not null") 135 } 136 var args []string 137 args=append(args,"accept") 138 args=append(args,pid) 139 args=append(args,rpdid) 140 args=append(args,rpwid) 141 ecslsdk,err:=encapsulation.GetEcslFabricSDKInstance() 142 if err != nil{ 143 return "", nil 144 } 145 channelclient, eventclient, err := ecslsdk.GetChannelAndEventClient(pc.ChannelID, pc.UserName) 146 if err != nil{ 147 return "", nil 148 } 149 eventid :="" 150 if strings.TrimSpace(pc.EventID)==""{ 151 eventid="eventPrescriptionInvokeAccept" 152 }else { 153 eventid=pc.EventID 154 } 155 registration, chanevent, err := eventclient.RegisterChaincodeEvent(pc.ChaincodeID, eventid) 156 if err != nil{ 157 return "", nil 158 } 159 defer eventclient.Unregister(registration) 160 transientdatamap := make(map[string][]byte) 161 transientdatamap["result"]=[]byte("transient data in prescription invoke accept") 162 chlreq:=channel.Request{ 163 ChaincodeID:pc.ChaincodeID, 164 Fcn:args[0], 165 Args:[][]byte{[]byte(args[1]),[]byte(args[2]),[]byte(args[3])}, 166 TransientMap:transientdatamap, 167 } 168 response, err := channelclient.Execute(chlreq) 169 if err != nil{ 170 return "", nil 171 } 172 select { 173 case ccevent:=<-chanevent: 174 log.Printf("received cc event: %v\n",ccevent) 175 case <-time.After(time.Second*20): 176 return "", fmt.Errorf("accept did not receive cc event for eventid: %s", eventid) 177 } 178 return string(response.TransactionID),nil 179 }
9.prescriptionclientquery.go代码
1 package operation 2 3 import ( 4 "github.com/prescriptionserver/client/go/clientmodel" 5 "errors" 6 "strings" 7 "github.com/prescriptionserver/client/go/encapsulation" 8 "github.com/hyperledger/fabric-sdk-go/pkg/client/channel" 9 "encoding/json" 10 ) 11 12 type PrescriptionClientQuery struct { 13 ChannelID string 14 ChaincodeID string 15 UserName string 16 } 17 18 func (pcq *PrescriptionClientQuery) GetPbcnByPid(pid string) (pbcn clientmodel.PrescriptionBlockchain, 19 err error) { 20 if pcq.ChannelID ==""||pcq.ChaincodeID ==""||pcq.UserName==""{ 21 return pbcn,errors.New("client getpbcnbypid function channelid or username or chaincode is not null") 22 } 23 if strings.TrimSpace(pid) ==""{ 24 return pbcn,errors.New("client getpbcnbypid function pid is not null") 25 } 26 efsdk,err :=encapsulation.GetEcslFabricSDKInstance() 27 if err != nil{ 28 return pbcn,err 29 } 30 channelclient, err := efsdk.GetChannelClient(pcq.ChannelID, pcq.UserName) 31 if err != nil{ 32 return pbcn,err 33 } 34 var args []string 35 args = append(args,"getpbcnbyprescriptionid") 36 args=append(args,pid) 37 chlreq := channel.Request{ 38 ChaincodeID:pcq.ChaincodeID, 39 Fcn:args[0], 40 Args:[][]byte{[]byte(args[1])}, 41 } 42 response, err := channelclient.Query(chlreq) 43 if err != nil{ 44 return pbcn,err 45 } 46 err = json.Unmarshal(response.Payload, &pbcn) 47 return pbcn,err 48 } 49 func (pcq *PrescriptionClientQuery) GetPbcnsByOpdid(opdid string) (pbcns []clientmodel.PrescriptionBlockchain,err error) { 50 if pcq.ChannelID ==""||pcq.ChaincodeID ==""||pcq.UserName==""{ 51 return pbcns,errors.New("client getpbcnbyopdid function channelid or username or chaincode is not null") 52 } 53 if strings.TrimSpace(opdid) ==""{ 54 return pbcns,errors.New("client getpbcnbyopdid function opdid is not null") 55 } 56 efsdk,err :=encapsulation.GetEcslFabricSDKInstance() 57 if err != nil{ 58 return pbcns,err 59 } 60 channelclient, err := efsdk.GetChannelClient(pcq.ChannelID, pcq.UserName) 61 if err != nil{ 62 return pbcns,err 63 } 64 var args []string 65 args = append(args,"getpbcnbyopdid") 66 args=append(args,opdid) 67 chlreq := channel.Request{ 68 ChaincodeID:pcq.ChaincodeID, 69 Fcn:args[0], 70 Args:[][]byte{[]byte(args[1])}, 71 } 72 response, err := channelclient.Query(chlreq) 73 if err != nil{ 74 return pbcns,err 75 } 76 err = json.Unmarshal(response.Payload, &pbcns) 77 return pbcns,err 78 } 79 func (pcq *PrescriptionClientQuery) GetPbcnsByPrpdid(prpdid string) ( 80 pbcns []clientmodel.PrescriptionBlockchain,err error) { 81 if pcq.ChannelID ==""||pcq.ChaincodeID ==""||pcq.UserName==""{ 82 return pbcns,errors.New("client getpbcnbyprpdid function channelid or username or chaincode is not null") 83 } 84 if strings.TrimSpace(prpdid) ==""{ 85 return pbcns,errors.New("client getpbcnbyprpdid function prpdid is not null") 86 } 87 efsdk,err :=encapsulation.GetEcslFabricSDKInstance() 88 if err != nil{ 89 return pbcns,err 90 } 91 channelclient, err := efsdk.GetChannelClient(pcq.ChannelID, pcq.UserName) 92 if err != nil{ 93 return pbcns,err 94 } 95 var args []string 96 args = append(args,"getpbcnbyprpdid") 97 args=append(args,prpdid) 98 chlreq := channel.Request{ 99 ChaincodeID:pcq.ChaincodeID, 100 Fcn:args[0], 101 Args:[][]byte{[]byte(args[1])}, 102 } 103 response, err := channelclient.Query(chlreq) 104 if err != nil{ 105 return pbcns,err 106 } 107 err = json.Unmarshal(response.Payload, &pbcns) 108 return pbcns,err 109 } 110 func (pcq *PrescriptionClientQuery) GetPbcnsByState(state string) ( 111 pbcns []clientmodel.PrescriptionBlockchain,err error) { 112 if pcq.ChannelID ==""||pcq.ChaincodeID ==""||pcq.UserName==""{ 113 return pbcns,errors.New("client getpbcnbystatefunction channelid or username or chaincode is not null") 114 } 115 if strings.TrimSpace(state) ==""{ 116 return pbcns,errors.New("client getpbcnbystate function state is not null") 117 } 118 efsdk,err :=encapsulation.GetEcslFabricSDKInstance() 119 if err != nil{ 120 return pbcns,err 121 } 122 channelclient, err := efsdk.GetChannelClient(pcq.ChannelID, pcq.UserName) 123 if err != nil{ 124 return pbcns,err 125 } 126 var args []string 127 args = append(args,"getpbcnbystate") 128 args=append(args,state) 129 chlreq := channel.Request{ 130 ChaincodeID:pcq.ChaincodeID, 131 Fcn:args[0], 132 Args:[][]byte{[]byte(args[1])}, 133 } 134 response, err := channelclient.Query(chlreq) 135 if err != nil{ 136 return pbcns,err 137 } 138 err = json.Unmarshal(response.Payload, &pbcns) 139 return pbcns,err 140 } 141 func (pcq *PrescriptionClientQuery) GetPbcnsByPtnid(ptnid string) ( 142 pbcns []clientmodel.PrescriptionBlockchain,err error) { 143 if pcq.ChannelID ==""||pcq.ChaincodeID ==""||pcq.UserName==""{ 144 return pbcns,errors.New("client getpbcnbyptnid function channelid or username or chaincode is not null") 145 } 146 if strings.TrimSpace(ptnid) ==""{ 147 return pbcns,errors.New("client getpbcnbyptnid function ptnid is not null") 148 } 149 efsdk,err :=encapsulation.GetEcslFabricSDKInstance() 150 if err != nil{ 151 return pbcns,err 152 } 153 channelclient, err := efsdk.GetChannelClient(pcq.ChannelID, pcq.UserName) 154 if err != nil{ 155 return pbcns,err 156 } 157 var args []string 158 args = append(args,"getpbcnbyptnid") 159 args=append(args,ptnid) 160 chlreq := channel.Request{ 161 ChaincodeID:pcq.ChaincodeID, 162 Fcn:args[0], 163 Args:[][]byte{[]byte(args[1])}, 164 } 165 response, err := channelclient.Query(chlreq) 166 if err != nil{ 167 return pbcns,err 168 } 169 err = json.Unmarshal(response.Payload, &pbcns) 170 return pbcns,err 171 } 172 func (pcq *PrescriptionClientQuery) GetPbcnsByRpdid(rpdid string) ( 173 pbcns []clientmodel.PrescriptionBlockchain,err error) { 174 if pcq.ChannelID ==""||pcq.ChaincodeID ==""||pcq.UserName==""{ 175 return pbcns,errors.New("client getpbcnbyrpdid function channelid or username or chaincode is not null") 176 } 177 if strings.TrimSpace(rpdid) ==""{ 178 return pbcns,errors.New("client getpbcnbyrpdid function rpdid is not null") 179 } 180 efsdk,err :=encapsulation.GetEcslFabricSDKInstance() 181 if err != nil{ 182 return pbcns,err 183 } 184 channelclient, err := efsdk.GetChannelClient(pcq.ChannelID, pcq.UserName) 185 if err != nil{ 186 return pbcns,err 187 } 188 var args []string 189 args = append(args,"getpbcnbyrpdid") 190 args=append(args,rpdid) 191 chlreq := channel.Request{ 192 ChaincodeID:pcq.ChaincodeID, 193 Fcn:args[0], 194 Args:[][]byte{[]byte(args[1])}, 195 } 196 response, err := channelclient.Query(chlreq) 197 if err != nil{ 198 return pbcns,err 199 } 200 err = json.Unmarshal(response.Payload, &pbcns) 201 return pbcns,err 202 } 203 func (pcq *PrescriptionClientQuery) GetPbcnsByHndt(hospitalno string,daytime string) ( 204 pbcns []clientmodel.PrescriptionBlockchain,err error) { 205 if pcq.ChannelID ==""||pcq.ChaincodeID ==""||pcq.UserName==""{ 206 return pbcns,errors.New("client getpbcnbyhndt function channelid or username or chaincode is not null") 207 } 208 if strings.TrimSpace(hospitalno) =="" || strings.TrimSpace(daytime)==""{ 209 return pbcns,errors.New("client getpbcnbyhndt function hospitalno or daytime is not null") 210 } 211 efsdk,err :=encapsulation.GetEcslFabricSDKInstance() 212 if err != nil{ 213 return pbcns,err 214 } 215 channelclient, err := efsdk.GetChannelClient(pcq.ChannelID, pcq.UserName) 216 if err != nil{ 217 return pbcns,err 218 } 219 var args []string 220 args = append(args,"getpbcnbyhndt") 221 args=append(args,hospitalno) 222 args=append(args,daytime) 223 chlreq := channel.Request{ 224 ChaincodeID:pcq.ChaincodeID, 225 Fcn:args[0], 226 Args:[][]byte{[]byte(args[1]),[]byte(args[2])}, 227 } 228 response, err := channelclient.Query(chlreq) 229 if err != nil{ 230 return pbcns,err 231 } 232 err = json.Unmarshal(response.Payload, &pbcns) 233 return pbcns,err 234 } 235 func (pcq *PrescriptionClientQuery) GetHistoryByPid(pid string) ( 236 pbcn clientmodel.PrescriptionBlockchain,err error) { 237 if pcq.ChannelID ==""||pcq.ChaincodeID ==""||pcq.UserName==""{ 238 return pbcn,errors.New("client gethistorybypid function channelid or username or chaincode is not null") 239 } 240 if strings.TrimSpace(pid) ==""{ 241 return pbcn,errors.New("client gethistorybypid function pid is not null") 242 } 243 efsdk,err :=encapsulation.GetEcslFabricSDKInstance() 244 if err != nil{ 245 return pbcn,err 246 } 247 channelclient, err := efsdk.GetChannelClient(pcq.ChannelID, pcq.UserName) 248 if err != nil{ 249 return pbcn,err 250 } 251 var args []string 252 args = append(args,"gethistorybypid") 253 args=append(args,pid) 254 chlreq := channel.Request{ 255 ChaincodeID:pcq.ChaincodeID, 256 Fcn:args[0], 257 Args:[][]byte{[]byte(args[1])}, 258 } 259 response, err := channelclient.Query(chlreq) 260 if err != nil{ 261 return pbcn,err 262 } 263 err = json.Unmarshal(response.Payload, &pbcn) 264 return pbcn,err 265 } 266 func (pcq *PrescriptionClientQuery) GetResultByQueryString(query string) ( 267 pbcns string,err error) { 268 if pcq.ChannelID ==""||pcq.ChaincodeID ==""||pcq.UserName==""{ 269 return pbcns,errors.New("client getresultbyquerystring function channelid or username or chaincode is not null") 270 } 271 if strings.TrimSpace(query) ==""{ 272 return pbcns,errors.New("client getresultbyquerystring function query is not null") 273 } 274 efsdk,err :=encapsulation.GetEcslFabricSDKInstance() 275 if err != nil{ 276 return pbcns,err 277 } 278 channelclient, err := efsdk.GetChannelClient(pcq.ChannelID, pcq.UserName) 279 if err != nil{ 280 return pbcns,err 281 } 282 var args []string 283 args = append(args,"getresultbyquerystring") 284 args=append(args,query) 285 chlreq := channel.Request{ 286 ChaincodeID:pcq.ChaincodeID, 287 Fcn:args[0], 288 Args:[][]byte{[]byte(args[1])}, 289 } 290 response, err := channelclient.Query(chlreq) 291 if err != nil{ 292 return pbcns,err 293 } 294 pbcns = string(response.Payload) 295 return pbcns,err 296 }
10.prescription.go部份代码
1 package clientmodel 2 3 type PrescriptionBlockchain struct { 4 PrescriptionID string `json:"PrescriptionID"` 5 HospitalNO string `json:"HospitalNO"` 6 PatientID string `json:"PatientID"` 7 GenerationTime string `json:"GenerationTime"` 8 PrescriptionSummary string `json:"PrescriptionSummary"` 9 OpenPrescriptionDeptID string `json:"OpenPrescriptionDeptID"` 10 OpenPrescriptionDoctorID string `json:"OpenPrescriptionDoctorID"` 11 PendingReceivePrescriptionDeptID string `json:"PendingReceivePrescriptionDeptID"` 12 PendingReceivePrescriptionWorkID string `json:"PendingReceivePrescriptionWorkID"` 13 ReceivingPrescriptionDeptID string `json:"ReceivingPrescriptionDeptID"` 14 ReceivingPrescriptionWorkID string `json:"ReceivingPrescriptionWorkID"` 15 State string `json:"State"` 16 History []HistoryItem `json:"History"` 17 } 18 type HistoryItem struct { 19 TxId string `json:"TxId"` 20 PrescriptionBlockchain PrescriptionBlockchain `json:"PrescriptionBlockchain"` 21 }
7.终于写的差不多了,后边还有前端,和elasticsearch数据处理,^_^最讨厌写前端呀,改了几个ecslresmgmt.go的错误