github.com/hechain20/hechain@v0.0.0-20220316014945-b544036ba106/integration/pvtdata/implicit_coll_test.go (about)

     1  /*
     2  Copyright hechain All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package pvtdata
     8  
     9  import (
    10  	"encoding/base64"
    11  	"encoding/json"
    12  	"fmt"
    13  	"path/filepath"
    14  	"time"
    15  
    16  	"github.com/hechain20/hechain/integration/chaincode/kvexecutor"
    17  	"github.com/hechain20/hechain/integration/nwo"
    18  	"github.com/hechain20/hechain/integration/nwo/commands"
    19  	. "github.com/onsi/ginkgo"
    20  	. "github.com/onsi/gomega"
    21  	"github.com/onsi/gomega/gbytes"
    22  	"github.com/onsi/gomega/gexec"
    23  
    24  	"github.com/tedsuo/ifrit"
    25  )
    26  
    27  var _ bool = Describe("Pvtdata dissemination for implicit collection", func() {
    28  	var (
    29  		network       *nwo.Network
    30  		process       ifrit.Process
    31  		orderer       *nwo.Orderer
    32  		testChaincode chaincode
    33  	)
    34  
    35  	BeforeEach(func() {
    36  		By("setting up the network")
    37  		network = initThreeOrgsSetup(false)
    38  
    39  		By("disabling pvtdata pull/dissemination/reconciliation on all peers except for enabling dissemination on org1 peers")
    40  		for _, p := range network.Peers {
    41  			core := network.ReadPeerConfig(p)
    42  			core.Peer.Gossip.PvtData.PullRetryThreshold = 0
    43  			core.Peer.Gossip.PvtData.ReconciliationEnabled = false
    44  			// set timeout and reconnect interval to prevent test flake
    45  			core.Peer.Gossip.DialTimeout = 5 * time.Second
    46  			core.Peer.Gossip.ConnTimeout = 5 * time.Second
    47  			core.Peer.Gossip.ReconnectInterval = 7 * time.Second
    48  			if p.Organization == "Org1" {
    49  				// enable dissemination on org1 peers
    50  				core.Peer.Gossip.PvtData.ImplicitCollDisseminationPolicy.RequiredPeerCount = 1
    51  				core.Peer.Gossip.PvtData.ImplicitCollDisseminationPolicy.MaxPeerCount = 3
    52  				core.Peer.Gossip.PvtData.PushAckTimeout = 10 * time.Second
    53  			} else {
    54  				// disable dissemination on non-org1 peers
    55  				core.Peer.Gossip.PvtData.ImplicitCollDisseminationPolicy.RequiredPeerCount = 0
    56  				core.Peer.Gossip.PvtData.ImplicitCollDisseminationPolicy.MaxPeerCount = 0
    57  			}
    58  			network.WritePeerConfig(p, core)
    59  		}
    60  
    61  		By("starting the network")
    62  		process, orderer = startNetwork(network)
    63  
    64  		By("deploying new lifecycle chaincode")
    65  		testChaincode = chaincode{
    66  			Chaincode: nwo.Chaincode{
    67  				Name:        "kvexecutor",
    68  				Version:     "1.0",
    69  				Path:        components.Build("github.com/hechain20/hechain/integration/chaincode/kvexecutor/cmd"),
    70  				Lang:        "binary",
    71  				PackageFile: filepath.Join(network.RootDir, "kvexecutor.tar.gz"),
    72  				Label:       "kvexecutor",
    73  				Sequence:    "1",
    74  			},
    75  			isLegacy: false,
    76  		}
    77  		nwo.EnableCapabilities(network, channelID, "Application", "V2_0", orderer, network.Peers...)
    78  
    79  		By("verifying org1.peer0 discovers all peers to ensure that gossip has been initialized")
    80  		discoverAllPeers(network, network.Peer("Org1", "peer0"), channelID, 3, 5*time.Second)
    81  
    82  		By("verifying org1.peer1 discovers all peers to ensure that gossip has been initialized")
    83  		discoverAllPeers(network, network.Peer("Org1", "peer1"), channelID, 3, 5*time.Second)
    84  
    85  		By("deploying chaincode to all peers")
    86  		deployChaincode(network, orderer, testChaincode)
    87  	})
    88  
    89  	AfterEach(func() {
    90  		testCleanup(network, process)
    91  	})
    92  
    93  	It("disseminates pvtdata of implicit collection for the peer's own org but not implicit collection for another org", func() {
    94  		org1peer0 := network.Peer("Org1", "peer0")
    95  		org1peer1 := network.Peer("Org1", "peer1")
    96  		org2peer0 := network.Peer("Org2", "peer0")
    97  		org2peer1 := network.Peer("Org2", "peer1")
    98  
    99  		By("writing private data to org1's and org2's implicit collections")
   100  		writeInput := []kvexecutor.KVData{
   101  			{Collection: "_implicit_org_Org1MSP", Key: "org1_key1", Value: "org1_value1"},
   102  			{Collection: "_implicit_org_Org2MSP", Key: "org2_key1", Value: "org2_value1"},
   103  		}
   104  		writeImplicitCollection(network, orderer, testChaincode.Name, writeInput, org1peer0, org2peer0)
   105  
   106  		By("querying org1.peer0 for _implicit_org_Org1MSP collection data, expecting pvtdata")
   107  		readInput1 := []kvexecutor.KVData{{Collection: "_implicit_org_Org1MSP", Key: "org1_key1"}}
   108  		expectedMsg1, err := json.Marshal(writeInput[:1])
   109  		Expect(err).NotTo(HaveOccurred())
   110  		readImplicitCollection(network, org1peer0, testChaincode.Name, readInput1, string(expectedMsg1), true)
   111  
   112  		// org1.peer1 should have _implicit_org_Org1MSP pvtdata because dissemination is enabled on org1 peers
   113  		By("querying org1.peer1 for _implicit_org_Org1MSP collection data, expecting pvtdata")
   114  		readImplicitCollection(network, org1peer1, testChaincode.Name, readInput1, string(expectedMsg1), true)
   115  
   116  		By("querying org2.peer0 for _implicit_org_Org1MSP collection data, expecting error")
   117  		readImplicitCollection(network, org2peer0, testChaincode.Name, readInput1,
   118  			"private data matching public hash version is not available", false)
   119  
   120  		By("querying org2.peer1 for _implicit_org_Org1MSP collection data, expecting error")
   121  		readImplicitCollection(network, org2peer1, testChaincode.Name, readInput1,
   122  			"private data matching public hash version is not available", false)
   123  
   124  		By("querying org2.peer0 for _implicit_org_Org2MSP collection data, expecting pvtdata")
   125  		readInput2 := []kvexecutor.KVData{{Collection: "_implicit_org_Org2MSP", Key: "org2_key1"}}
   126  		expectedMsg2, err := json.Marshal(writeInput[1:])
   127  		Expect(err).NotTo(HaveOccurred())
   128  		readImplicitCollection(network, org2peer0, testChaincode.Name, readInput2, string(expectedMsg2), true)
   129  
   130  		// org2.peer1 should have no _implicit_org_Org2MSP pvtdata because pull/dissemination/reconciliation are disabled on org2 peers
   131  		By("querying org2.peer1 for _implicit_org_Org2MSP collection data, expecting error")
   132  		readImplicitCollection(network, org2peer1, testChaincode.Name, readInput2,
   133  			"private data matching public hash version is not available", false)
   134  
   135  		By("querying org1.peer0 for _implicit_org_Org2MSP collection data, expecting error")
   136  		readImplicitCollection(network, org1peer0, testChaincode.Name, readInput2,
   137  			"private data matching public hash version is not available", false)
   138  
   139  		By("querying org1.peer1 for _implicit_org_Org2MSP collection data, expecting error")
   140  		readImplicitCollection(network, org1peer1, testChaincode.Name, readInput2,
   141  			"private data matching public hash version is not available", false)
   142  	})
   143  })
   144  
   145  func writeImplicitCollection(n *nwo.Network, orderer *nwo.Orderer, chaincodeName string, writeInput []kvexecutor.KVData, peers ...*nwo.Peer) {
   146  	writeInputBytes, err := json.Marshal(writeInput)
   147  	Expect(err).NotTo(HaveOccurred())
   148  	writeInputBase64 := base64.StdEncoding.EncodeToString(writeInputBytes)
   149  
   150  	peerAddresses := make([]string, 0)
   151  	for _, peer := range peers {
   152  		peerAddresses = append(peerAddresses, n.PeerAddress(peer, nwo.ListenPort))
   153  	}
   154  	command := commands.ChaincodeInvoke{
   155  		ChannelID:     channelID,
   156  		Orderer:       n.OrdererAddress(orderer, nwo.ListenPort),
   157  		Name:          chaincodeName,
   158  		Ctor:          fmt.Sprintf(`{"Args":["readWriteKVs","%s","%s"]}`, "", writeInputBase64),
   159  		PeerAddresses: peerAddresses,
   160  		WaitForEvent:  true,
   161  	}
   162  	invokeChaincode(n, peers[0], command)
   163  	nwo.WaitUntilEqualLedgerHeight(n, channelID, nwo.GetLedgerHeight(n, peers[0], channelID), n.Peers...)
   164  }
   165  
   166  func readImplicitCollection(n *nwo.Network, peer *nwo.Peer, chaincodeName string, readInput []kvexecutor.KVData, expectedMsg string, expectSuccess bool) {
   167  	readInputBytes, err := json.Marshal(readInput)
   168  	Expect(err).NotTo(HaveOccurred())
   169  	readInputBase64 := base64.StdEncoding.EncodeToString(readInputBytes)
   170  
   171  	command := commands.ChaincodeQuery{
   172  		ChannelID: channelID,
   173  		Name:      chaincodeName,
   174  		Ctor:      fmt.Sprintf(`{"Args":["readWriteKVs","%s","%s"]}`, readInputBase64, ""),
   175  	}
   176  	queryChaincode(n, peer, command, expectedMsg, expectSuccess)
   177  }
   178  
   179  func invokeChaincode(n *nwo.Network, peer *nwo.Peer, command commands.ChaincodeInvoke) {
   180  	sess, err := n.PeerUserSession(peer, "User1", command)
   181  	Expect(err).NotTo(HaveOccurred())
   182  	Eventually(sess, n.EventuallyTimeout).Should(gexec.Exit(0))
   183  	Expect(sess.Err).To(gbytes.Say("Chaincode invoke successful."))
   184  }
   185  
   186  func queryChaincode(n *nwo.Network, peer *nwo.Peer, command commands.ChaincodeQuery, expectedMessage string, expectSuccess bool) {
   187  	sess, err := n.PeerUserSession(peer, "User1", command)
   188  	Expect(err).NotTo(HaveOccurred())
   189  	if expectSuccess {
   190  		Eventually(sess, n.EventuallyTimeout).Should(gexec.Exit(0))
   191  		Expect(sess).To(gbytes.Say(expectedMessage))
   192  	} else {
   193  		Eventually(sess, n.EventuallyTimeout).Should(gexec.Exit())
   194  		Expect(sess.Err).To(gbytes.Say(expectedMessage))
   195  	}
   196  }
   197  
   198  func discoverAllPeers(n *nwo.Network, peer *nwo.Peer, channelID string, retries int, retryInterval time.Duration) {
   199  	var discoveredPeers []nwo.DiscoveredPeer
   200  	numPeers := len(n.Peers)
   201  	for i := 0; i < retries; i++ {
   202  		discoveredPeers = nwo.DiscoverPeers(n, peer, "User1", channelID)()
   203  		if len(discoveredPeers) == numPeers || i == retries-1 {
   204  			break
   205  		}
   206  		time.Sleep(retryInterval)
   207  	}
   208  	Expect(discoveredPeers).To(HaveLen(numPeers))
   209  }