github.com/osdi23p228/fabric@v0.0.0-20221218062954-77808885f5db/integration/lifecycle/lifecycle_suite_test.go (about) 1 /* 2 Copyright IBM Corp All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package lifecycle 8 9 import ( 10 "context" 11 "crypto/tls" 12 "encoding/json" 13 "fmt" 14 "io/ioutil" 15 "path/filepath" 16 "syscall" 17 "testing" 18 "time" 19 20 pcommon "github.com/hyperledger/fabric-protos-go/common" 21 pb "github.com/hyperledger/fabric-protos-go/peer" 22 "github.com/osdi23p228/fabric/bccsp/sw" 23 "github.com/osdi23p228/fabric/common/flogging" 24 "github.com/osdi23p228/fabric/integration" 25 "github.com/osdi23p228/fabric/integration/nwo" 26 "github.com/osdi23p228/fabric/integration/nwo/commands" 27 ic "github.com/osdi23p228/fabric/internal/peer/chaincode" 28 "github.com/osdi23p228/fabric/internal/peer/common" 29 "github.com/osdi23p228/fabric/internal/pkg/comm" 30 "github.com/osdi23p228/fabric/msp" 31 "github.com/osdi23p228/fabric/protoutil" 32 . "github.com/onsi/ginkgo" 33 . "github.com/onsi/gomega" 34 "github.com/onsi/gomega/gbytes" 35 "github.com/onsi/gomega/gexec" 36 "github.com/pkg/errors" 37 "github.com/tedsuo/ifrit" 38 ) 39 40 func TestLifecycle(t *testing.T) { 41 RegisterFailHandler(Fail) 42 RunSpecs(t, "Lifecycle Suite") 43 } 44 45 var ( 46 buildServer *nwo.BuildServer 47 components *nwo.Components 48 ) 49 50 var _ = SynchronizedBeforeSuite(func() []byte { 51 buildServer = nwo.NewBuildServer() 52 buildServer.Serve() 53 54 components = buildServer.Components() 55 payload, err := json.Marshal(components) 56 Expect(err).NotTo(HaveOccurred()) 57 58 return payload 59 }, func(payload []byte) { 60 err := json.Unmarshal(payload, &components) 61 Expect(err).NotTo(HaveOccurred()) 62 63 flogging.SetWriter(GinkgoWriter) 64 }) 65 66 var _ = SynchronizedAfterSuite(func() { 67 }, func() { 68 buildServer.Shutdown() 69 }) 70 71 func StartPort() int { 72 return integration.LifecyclePort.StartPortForNode() 73 } 74 75 func RunQueryInvokeQuery(n *nwo.Network, orderer *nwo.Orderer, chaincodeName string, initialQueryResult int, peers ...*nwo.Peer) { 76 if len(peers) == 0 { 77 peers = n.PeersWithChannel("testchannel") 78 } 79 80 addresses := make([]string, len(peers)) 81 for i, peer := range peers { 82 addresses[i] = n.PeerAddress(peer, nwo.ListenPort) 83 } 84 85 By("querying the chaincode") 86 sess, err := n.PeerUserSession(peers[0], "User1", commands.ChaincodeQuery{ 87 ChannelID: "testchannel", 88 Name: chaincodeName, 89 Ctor: `{"Args":["query","a"]}`, 90 }) 91 ExpectWithOffset(1, err).NotTo(HaveOccurred()) 92 EventuallyWithOffset(1, sess, n.EventuallyTimeout).Should(gexec.Exit(0)) 93 ExpectWithOffset(1, sess).To(gbytes.Say(fmt.Sprint(initialQueryResult))) 94 95 By("invoking the chaincode") 96 sess, err = n.PeerUserSession(peers[0], "User1", commands.ChaincodeInvoke{ 97 ChannelID: "testchannel", 98 Orderer: n.OrdererAddress(orderer, nwo.ListenPort), 99 Name: chaincodeName, 100 Ctor: `{"Args":["invoke","a","b","10"]}`, 101 PeerAddresses: addresses, 102 WaitForEvent: true, 103 }) 104 ExpectWithOffset(1, err).NotTo(HaveOccurred()) 105 EventuallyWithOffset(1, sess, n.EventuallyTimeout).Should(gexec.Exit(0)) 106 ExpectWithOffset(1, sess.Err).To(gbytes.Say("Chaincode invoke successful. result: status:200")) 107 108 By("querying the chaincode") 109 sess, err = n.PeerUserSession(peers[0], "User1", commands.ChaincodeQuery{ 110 ChannelID: "testchannel", 111 Name: chaincodeName, 112 Ctor: `{"Args":["query","a"]}`, 113 }) 114 ExpectWithOffset(1, err).NotTo(HaveOccurred()) 115 EventuallyWithOffset(1, sess, n.EventuallyTimeout).Should(gexec.Exit(0)) 116 ExpectWithOffset(1, sess).To(gbytes.Say(fmt.Sprint(initialQueryResult - 10))) 117 } 118 119 func RestartNetwork(process *ifrit.Process, network *nwo.Network) { 120 (*process).Signal(syscall.SIGTERM) 121 Eventually((*process).Wait(), network.EventuallyTimeout).Should(Receive()) 122 networkRunner := network.NetworkGroupRunner() 123 *process = ifrit.Invoke(networkRunner) 124 Eventually((*process).Ready(), network.EventuallyTimeout).Should(BeClosed()) 125 } 126 127 func LoadLocalMSPAt(dir, id, mspType string) (msp.MSP, error) { 128 if mspType != "bccsp" { 129 return nil, errors.Errorf("invalid msp type, expected 'bccsp', got %s", mspType) 130 } 131 conf, err := msp.GetLocalMspConfig(dir, nil, id) 132 if err != nil { 133 return nil, err 134 } 135 ks, err := sw.NewFileBasedKeyStore(nil, filepath.Join(dir, "keystore"), true) 136 if err != nil { 137 return nil, err 138 } 139 cryptoProvider, err := sw.NewDefaultSecurityLevelWithKeystore(sw.NewDummyKeyStore()) 140 if err != nil { 141 return nil, err 142 } 143 thisMSP, err := msp.NewBccspMspWithKeyStore(msp.MSPv1_0, ks, cryptoProvider) 144 if err != nil { 145 return nil, err 146 } 147 err = thisMSP.Setup(conf) 148 if err != nil { 149 return nil, err 150 } 151 return thisMSP, nil 152 } 153 154 func Signer(dir string) (msp.SigningIdentity, []byte) { 155 MSP, err := LoadLocalMSPAt(dir, "Org1MSP", "bccsp") 156 Expect(err).To(BeNil()) 157 Expect(MSP).NotTo(BeNil()) 158 Expect(err).To(BeNil(), "failed getting signer for %s", dir) 159 signer, err := MSP.GetDefaultSigningIdentity() 160 Expect(err).To(BeNil()) 161 Expect(signer).NotTo(BeNil()) 162 serialisedSigner, err := signer.Serialize() 163 Expect(err).To(BeNil()) 164 Expect(serialisedSigner).NotTo(BeNil()) 165 166 return signer, serialisedSigner 167 } 168 169 func SignedProposal(channel, chaincode string, signer msp.SigningIdentity, serialisedSigner []byte, args ...string) (*pb.SignedProposal, *pb.Proposal, string) { 170 byteArgs := make([][]byte, 0, len(args)) 171 for _, arg := range args { 172 byteArgs = append(byteArgs, []byte(arg)) 173 } 174 175 prop, txid, err := protoutil.CreateChaincodeProposalWithTxIDAndTransient( 176 pcommon.HeaderType_ENDORSER_TRANSACTION, 177 channel, 178 &pb.ChaincodeInvocationSpec{ 179 ChaincodeSpec: &pb.ChaincodeSpec{ 180 Type: pb.ChaincodeSpec_GOLANG, 181 ChaincodeId: &pb.ChaincodeID{ 182 Name: chaincode, 183 }, 184 Input: &pb.ChaincodeInput{ 185 Args: byteArgs, 186 }, 187 }, 188 }, 189 serialisedSigner, 190 "", 191 nil, 192 ) 193 Expect(err).NotTo(HaveOccurred()) 194 Expect(prop).NotTo(BeNil()) 195 196 signedProp, err := protoutil.GetSignedProposal(prop, signer) 197 Expect(err).NotTo(HaveOccurred()) 198 Expect(signedProp).NotTo(BeNil()) 199 200 return signedProp, prop, txid 201 } 202 203 func grpcClient(tlsRootCertFile string) *comm.GRPCClient { 204 caPEM, res := ioutil.ReadFile(tlsRootCertFile) 205 Expect(res).To(BeNil()) 206 207 gClient, err := comm.NewGRPCClient(comm.ClientConfig{ 208 Timeout: 3 * time.Second, 209 KaOpts: comm.DefaultKeepaliveOptions, 210 SecOpts: comm.SecureOptions{ 211 UseTLS: true, 212 ServerRootCAs: [][]byte{caPEM}, 213 }, 214 }) 215 Expect(err).NotTo(HaveOccurred()) 216 Expect(gClient).NotTo(BeNil()) 217 218 return gClient 219 } 220 221 func EndorserClient(address, tlsRootCertFile string) pb.EndorserClient { 222 peerClient := &common.PeerClient{ 223 CommonClient: common.CommonClient{ 224 GRPCClient: grpcClient(tlsRootCertFile), 225 Address: address, 226 }, 227 } 228 229 ec, err := peerClient.Endorser() 230 Expect(err).NotTo(HaveOccurred()) 231 Expect(ec).NotTo(BeNil()) 232 233 return ec 234 } 235 236 func OrdererClient(address, tlsRootCertFile string) common.BroadcastClient { 237 ordererClient := &common.OrdererClient{ 238 CommonClient: common.CommonClient{ 239 GRPCClient: grpcClient(tlsRootCertFile), 240 Address: address, 241 }, 242 } 243 244 bc, err := ordererClient.Broadcast() 245 Expect(err).NotTo(HaveOccurred()) 246 Expect(bc).NotTo(BeNil()) 247 248 return &common.BroadcastGRPCClient{Client: bc} 249 } 250 251 func DeliverClient(address, tlsRootCertFile string) pb.DeliverClient { 252 peerClient := &common.PeerClient{ 253 CommonClient: common.CommonClient{ 254 GRPCClient: grpcClient(tlsRootCertFile), 255 Address: address, 256 }, 257 } 258 259 pd, err := peerClient.PeerDeliver() 260 Expect(err).NotTo(HaveOccurred()) 261 Expect(pd).NotTo(BeNil()) 262 263 return pd 264 } 265 266 func CommitTx(network *nwo.Network, env *pcommon.Envelope, peer *nwo.Peer, dc pb.DeliverClient, oc common.BroadcastClient, signer msp.SigningIdentity, txid string) error { 267 var cancelFunc context.CancelFunc 268 ctx, cancelFunc := context.WithTimeout(context.Background(), 10*time.Second) 269 defer cancelFunc() 270 271 dg := ic.NewDeliverGroup([]pb.DeliverClient{dc}, []string{network.PeerAddress(peer, nwo.ListenPort)}, signer, tls.Certificate{}, "testchannel", txid) 272 273 err := dg.Connect(ctx) 274 Expect(err).NotTo(HaveOccurred()) 275 276 err = oc.Send(env) 277 Expect(err).NotTo(HaveOccurred()) 278 279 return dg.Wait(ctx) 280 } 281 282 // GenerateOrgUpdateMeterials generates the necessary configtx and 283 // crypto materials for a new org's peers to join a network 284 func GenerateOrgUpdateMaterials(n *nwo.Network, peers ...*nwo.Peer) { 285 orgUpdateNetwork := *n 286 orgUpdateNetwork.Peers = peers 287 orgUpdateNetwork.Templates = &nwo.Templates{ 288 ConfigTx: nwo.OrgUpdateConfigTxTemplate, 289 Crypto: nwo.OrgUpdateCryptoTemplate, 290 Core: n.Templates.CoreTemplate(), 291 } 292 293 orgUpdateNetwork.GenerateConfigTxConfig() 294 for _, peer := range peers { 295 orgUpdateNetwork.GenerateCoreConfig(peer) 296 } 297 298 orgUpdateNetwork.GenerateCryptoConfig() 299 sess, err := orgUpdateNetwork.Cryptogen(commands.Generate{ 300 Config: orgUpdateNetwork.CryptoConfigPath(), 301 Output: orgUpdateNetwork.CryptoPath(), 302 }) 303 Expect(err).NotTo(HaveOccurred()) 304 Eventually(sess, orgUpdateNetwork.EventuallyTimeout).Should(gexec.Exit(0)) 305 306 // refresh TLSCACertificates ca-certs.pem so that it includes 307 // the newly generated cert 308 n.ConcatenateTLSCACertificates() 309 }