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