Example #1
0
 public void ChaincodeEndorsementPolicy(ChaincodeEndorsementPolicy policy)
 {
     if (policy != null)
     {
         chaincodePolicy = policy.ChaincodeEndorsementPolicyAsBytes;
     }
 }
        public void TestPolicyCtorByteArray()
        {
            byte[] testInput = "this is a test".ToBytes();
            ChaincodeEndorsementPolicy fakePolicy = new ChaincodeEndorsementPolicy();

            fakePolicy.FromBytes(testInput);
            CollectionAssert.AreEqual(fakePolicy.ChaincodeEndorsementPolicyAsBytes, testInput);
        }
        public void TestPolicyCtorValidFile()
        {
            string policyFile = "Resources/policyBitsAdmin".Locate();
            ChaincodeEndorsementPolicy policy = new ChaincodeEndorsementPolicy();

            policy.FromFile(policyFile);
            byte[] policyBits = File.ReadAllBytes(policyFile);
            CollectionAssert.AreEqual(policyBits, policy.ChaincodeEndorsementPolicyAsBytes);
        }
        public void TestBadYaml()
        {
            try
            {
                ChaincodeEndorsementPolicy itTestPolicy = new ChaincodeEndorsementPolicy();
                itTestPolicy.FromYamlFile("fixture/sample_chaincode_endorsement_policies/badusertestCCEPPolicy.yaml".Locate());

                Assert.Fail("Expected ChaincodeEndorsementPolicyParseException");
            }
            catch (ChaincodeEndorsementPolicyParseException)
            {
            }
            catch (System.Exception)
            {
                Assert.Fail("Expected ChaincodeEndorsementPolicyParseException");
            }
        }
        public void TestSDKIntegrationYaml()
        {
            ChaincodeEndorsementPolicy itTestPolicy = new ChaincodeEndorsementPolicy();

            itTestPolicy.FromYamlFile("Fixture/sdkintegration/chaincodeendorsementpolicy.yaml".Locate());
            SignaturePolicyEnvelope sigPolEnv      = SignaturePolicyEnvelope.Parser.ParseFrom(itTestPolicy.ChaincodeEndorsementPolicyAsBytes);
            List <MSPPrincipal>     identitiesList = sigPolEnv.Identities.ToList();

            foreach (MSPPrincipal ident in identitiesList)
            {
                MSPPrincipal mspPrincipal = MSPPrincipal.Parser.ParseFrom(ident.Principal);
                MSPPrincipal.Types.Classification principalClassification = mspPrincipal.PrincipalClassification;
                Assert.AreEqual(principalClassification.ToString(), MSPPrincipal.Types.Classification.Role.ToString());
                MSPRole mspRole = MSPRole.Parser.ParseFrom(ident.Principal);
                string  iden    = mspRole.MspIdentifier;
                Assert.IsTrue("Org1MSP".Equals(iden) || "Org2MSP".Equals(iden));
                Assert.IsTrue(mspRole.Role == MSPRole.Types.MSPRoleType.Admin || mspRole.Role == MSPRole.Types.MSPRoleType.Member);
            }

            SignaturePolicy rule = sigPolEnv.Rule;

            SignaturePolicy.TypeOneofCase typeCase = rule.TypeCase;
            Assert.AreEqual(SignaturePolicy.TypeOneofCase.NOutOf, typeCase);
        }
Example #6
0
        // ReSharper disable once UnusedMethodReturnValue.Local
        private static ChaincodeID DeployChaincode(HFClient client, Channel channel, string ccName, string ccPath, string ccVersion)
        {
            Util.COut("deployChaincode - enter");
            ChaincodeID chaincodeID = null;

            try
            {
                string channelName = channel.Name;
                Util.COut("deployChaincode - channelName = " + channelName);

                IReadOnlyList <Orderer> orderers = channel.Orderers;
                List <ProposalResponse> responses;
                List <ProposalResponse> successful = new List <ProposalResponse>();
                List <ProposalResponse> failed     = new List <ProposalResponse>();

                chaincodeID = new ChaincodeID().SetName(ccName).SetVersion(ccVersion).SetPath(ccPath);

                ////////////////////////////
                // Install Proposal Request
                //
                Util.COut("Creating install proposal");

                InstallProposalRequest installProposalRequest = client.NewInstallProposalRequest();
                installProposalRequest.SetChaincodeID(chaincodeID);

                ////For GO language and serving just a single user, chaincodeSource is mostly likely the users GOPATH
                installProposalRequest.SetChaincodeSourceLocation(Path.Combine(TEST_FIXTURES_PATH, "sdkintegration/gocc/sample1").Locate());

                installProposalRequest.SetChaincodeVersion(ccVersion);

                Util.COut("Sending install proposal");

                ////////////////////////////
                // only a client from the same org as the peer can issue an install request
                int numInstallProposal = 0;

                IReadOnlyList <Peer> peersFromOrg = channel.Peers;
                numInstallProposal = numInstallProposal + peersFromOrg.Count;
                responses          = client.SendInstallProposal(installProposalRequest, peersFromOrg);

                foreach (ProposalResponse response in responses)
                {
                    if (response.Status == ChaincodeResponse.ChaincodeResponseStatus.SUCCESS)
                    {
                        Util.COut("Successful install proposal response Txid: {0} from peer {1}", response.TransactionID, response.Peer.Name);
                        successful.Add(response);
                    }
                    else
                    {
                        failed.Add(response);
                    }
                }

                Util.COut("Received {0} install proposal responses. Successful+verified: {1} . Failed: {2}", numInstallProposal, successful.Count, failed.Count);

                if (failed.Count > 0)
                {
                    ProposalResponse first = failed.First();
                    Assert.Fail($"Not enough endorsers for install : {successful.Count}.  {first.Message}");
                }

                ///////////////
                //// Instantiate chaincode.
                //
                // From the docs:
                // The instantiate transaction invokes the lifecycle System Chaincode (LSCC) to create and initialize a chaincode on a channel
                // After being successfully instantiated, the chaincode enters the active state on the channel and is ready to process any transaction proposals of type ENDORSER_TRANSACTION

                InstantiateProposalRequest instantiateProposalRequest = client.NewInstantiationProposalRequest();
                instantiateProposalRequest.SetProposalWaitTime(testConfig.GetProposalWaitTime());
                instantiateProposalRequest.SetChaincodeID(chaincodeID);
                instantiateProposalRequest.SetFcn("init");
                instantiateProposalRequest.SetArgs("a", "500", "b", "999");

                Dictionary <string, byte[]> tm = new Dictionary <string, byte[]>();
                tm.Add("HyperLedgerFabric", "InstantiateProposalRequest:JavaSDK".ToBytes());
                tm.Add("method", "InstantiateProposalRequest".ToBytes());
                instantiateProposalRequest.SetTransientMap(tm);

                /*
                 * policy OR(Org1MSP.member, Org2MSP.member) meaning 1 signature from someone in either Org1 or Org2
                 * See README.md Chaincode endorsement policies section for more details.
                 */
                ChaincodeEndorsementPolicy chaincodeEndorsementPolicy = new ChaincodeEndorsementPolicy();
                chaincodeEndorsementPolicy.FromYamlFile(Path.Combine(TEST_FIXTURES_PATH, "sdkintegration/chaincodeendorsementpolicy.yaml").Locate());
                instantiateProposalRequest.SetChaincodeEndorsementPolicy(chaincodeEndorsementPolicy);

                Util.COut("Sending instantiateProposalRequest to all peers...");
                successful.Clear();
                failed.Clear();

                responses = channel.SendInstantiationProposal(instantiateProposalRequest);

                foreach (ProposalResponse response in responses)
                {
                    if (response.IsVerified && response.Status == ChaincodeResponse.ChaincodeResponseStatus.SUCCESS)
                    {
                        successful.Add(response);
                        Util.COut("Succesful instantiate proposal response Txid:{0} from peer {1}", response.TransactionID, response.Peer.Name);
                    }
                    else
                    {
                        failed.Add(response);
                    }
                }

                Util.COut("Received {0} instantiate proposal responses. Successful+verified: {1} . Failed: {2}", responses.Count, successful.Count, failed.Count);
                if (failed.Count > 0)
                {
                    ProposalResponse first = failed.First();
                    Assert.Fail($"Not enough endorsers for instantiate :{successful.Count} endorser failed with {first.Message}. Was verified:{first.IsVerified}");
                }

                ///////////////
                // Send instantiate transaction to orderer
                Util.COut("Sending instantiateTransaction to orderer...");
                Util.COut("calling get...");
                TransactionEvent evnt = channel.SendTransaction(successful, orderers, 30 * 1000);
                Util.COut("get done...");

                Assert.IsTrue(evnt.IsValid); // must be valid to be here.
                Util.COut("Finished instantiate transaction with transaction id {0}", evnt.TransactionID);
            }
            catch (System.Exception e)
            {
                Util.COut("Caught an exception running channel {0}", channel.Name);
                Assert.Fail($"Test failed with error : {e.Message}");
            }

            return(chaincodeID);
        }
        public void TestPolicyCtorFile()
        {
            ChaincodeEndorsementPolicy policy = new ChaincodeEndorsementPolicy();

            policy.FromFile("/does/not/exists");
        }
        public void TestPolicyCtor()
        {
            ChaincodeEndorsementPolicy nullPolicy = new ChaincodeEndorsementPolicy();

            Assert.IsNull(nullPolicy.ChaincodeEndorsementPolicyAsBytes);
        }
        // Disable MethodLength as this method is for instructional purposes and hence
        // we don't want to split it into smaller pieces
        // CHECKSTYLE:OFF: MethodLength
        private void RunChannel(HFClient client, Channel channel, SampleOrg sampleOrg, int delta)
        {
            string channelName = channel.Name;

            try
            {
                client.UserContext = sampleOrg.GetUser(TESTUSER_1_NAME);

                //This is for testing only and can be ignored.
                TestUtils.TestUtils.TestRemovingAddingPeersOrderers(client, channel);

                //            final boolean changeContext = false; // BAR_CHANNEL_NAME.equals(channel.getName()) ? true : false;
                bool changeContext = BAR_CHANNEL_NAME.Equals(channel.Name);

                Util.COut("Running Channel {0} with a delta {1}", channelName, delta);

                Util.COut("ChaincodeID: {0}", chaincodeID);
                ////////////////////////////
                // Send Query Proposal to all peers see if it's what we expect from end of End2endIT
                //
                QueryChaincodeForExpectedValue(client, channel, "" + (300 + delta), chaincodeID);

                //Set user context on client but use explicit user contest on each call.
                if (changeContext)
                {
                    client.UserContext = sampleOrg.GetUser(TESTUSER_1_NAME);
                }

                // exercise v1 of chaincode

                MoveAmount(client, channel, chaincodeID, "25", changeContext ? sampleOrg.PeerAdmin : null);


                WaitOnFabric();
                client.UserContext = sampleOrg.GetUser(TESTUSER_1_NAME);

                QueryChaincodeForExpectedValue(client, channel, "" + (325 + delta), chaincodeID);

                //////////////////
                // Start of upgrade first must install it.

                client.UserContext = sampleOrg.PeerAdmin;
                ///////////////
                ////
                InstallProposalRequest installProposalRequest = client.NewInstallProposalRequest();
                installProposalRequest.ChaincodeID = chaincodeID;
                ////For GO language and serving just a single user, chaincodeSource is mostly likely the users GOPATH
                installProposalRequest.ChaincodeSourceLocation = Path.Combine(TEST_FIXTURES_PATH, CHAIN_CODE_FILEPATH).Locate();

                installProposalRequest.ChaincodeVersion  = CHAIN_CODE_VERSION_11;
                installProposalRequest.ProposalWaitTime  = DEPLOYWAITTIME;
                installProposalRequest.ChaincodeLanguage = CHAIN_CODE_LANG;

                if (changeContext)
                {
                    installProposalRequest.UserContext = sampleOrg.PeerAdmin;
                }

                Util.COut("Sending install proposal for channel: {0}", channel.Name);

                ////////////////////////////
                // only a client from the same org as the peer can issue an install request
                int numInstallProposal = 0;

                List <ProposalResponse> responses;
                List <ProposalResponse> successful   = new List <ProposalResponse>();
                List <ProposalResponse> failed       = new List <ProposalResponse>();
                IReadOnlyList <Peer>    peersFromOrg = channel.Peers;
                numInstallProposal = numInstallProposal + peersFromOrg.Count;

                responses = client.SendInstallProposal(installProposalRequest, peersFromOrg);

                foreach (ProposalResponse response in responses)
                {
                    if (response.Status == ChaincodeResponse.ChaincodeResponseStatus.SUCCESS)
                    {
                        Util.COut("Successful install proposal response Txid: {0} from peer {1}", response.TransactionID, response.Peer.Name);
                        successful.Add(response);
                    }
                    else
                    {
                        failed.Add(response);
                    }
                }

                Util.COut("Received {0} install proposal responses. Successful+verified: {1} . Failed: {2}", numInstallProposal, successful.Count, failed.Count);

                if (failed.Count > 0)
                {
                    ProposalResponse first = failed.First();
                    Assert.Fail($"Not enough endorsers for install : {successful.Count}.  {first.Message}");
                }

                //////////////////
                // Upgrade chaincode to ***double*** our move results.

                if (changeContext)
                {
                    installProposalRequest.UserContext = sampleOrg.PeerAdmin;
                }

                UpgradeProposalRequest upgradeProposalRequest = client.NewUpgradeProposalRequest();
                upgradeProposalRequest.ChaincodeID      = chaincodeID_11;
                upgradeProposalRequest.ProposalWaitTime = testConfig.GetProposalWaitTime();
                upgradeProposalRequest.Fcn  = "init";
                upgradeProposalRequest.Args = new List <string>(); // no arguments don't change the ledger see chaincode.

                ChaincodeEndorsementPolicy chaincodeEndorsementPolicy;

                chaincodeEndorsementPolicy = new ChaincodeEndorsementPolicy();
                chaincodeEndorsementPolicy.FromYamlFile(Path.Combine(TEST_FIXTURES_PATH, "sdkintegration/chaincodeendorsementpolicy.yaml").Locate());

                upgradeProposalRequest.ChaincodeEndorsementPolicy = chaincodeEndorsementPolicy;
                Dictionary <string, byte[]> tmap = new Dictionary <string, byte[]>();
                tmap.Add("test", "data".ToBytes());
                upgradeProposalRequest.SetTransientMap(tmap);

                if (changeContext)
                {
                    upgradeProposalRequest.UserContext = sampleOrg.PeerAdmin;
                }

                Util.COut("Sending upgrade proposal");

                List <ProposalResponse> responses2;

                responses2 = channel.SendUpgradeProposal(upgradeProposalRequest);

                successful.Clear();
                failed.Clear();
                foreach (ProposalResponse response in responses2)
                {
                    if (response.Status == ChaincodeResponse.ChaincodeResponseStatus.SUCCESS)
                    {
                        Util.COut("Successful upgrade proposal response Txid: {0} from peer {1}", response.TransactionID, response.Peer.Name);
                        successful.Add(response);
                    }
                    else
                    {
                        failed.Add(response);
                    }
                }

                Util.COut("Received {0} upgrade proposal responses. Successful+verified: {1} . Failed: {2}", channel.Peers.Count, successful.Count, failed.Count);

                if (failed.Count > 0)
                {
                    ProposalResponse first = failed.First();
                    Assert.Fail($"Not enough endorsers for upgrade : {successful.Count}.  {first.Message}");
                }

                if (changeContext)
                {
                    channel.SendTransaction(successful, sampleOrg.PeerAdmin, testConfig.GetTransactionWaitTime() * 1000);
                }
                else
                {
                    channel.SendTransaction(successful, testConfig.GetTransactionWaitTime() * 1000);
                }

                WaitOnFabric(10000);

                Util.COut("Chaincode has been upgraded to version {0}", CHAIN_CODE_VERSION_11);

                //Check to see if peers have new chaincode and old chaincode is gone.

                client.UserContext = sampleOrg.PeerAdmin;
                foreach (Peer peer in channel.Peers)
                {
                    if (!CheckInstalledChaincode(client, peer, CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_VERSION_11))
                    {
                        Assert.Fail($"Peer {peer.Name} is missing chaincode name:{CHAIN_CODE_NAME}, path:{CHAIN_CODE_PATH}, version: {CHAIN_CODE_VERSION_11}");
                    }

                    //should be instantiated too..
                    if (!CheckInstantiatedChaincode(channel, peer, CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_VERSION_11))
                    {
                        Assert.Fail($"Peer {peer.Name} is missing instantiated chaincode name:{CHAIN_CODE_NAME}, path:{CHAIN_CODE_PATH}, version: {CHAIN_CODE_VERSION_11}");
                    }

                    if (CheckInstantiatedChaincode(channel, peer, CHAIN_CODE_NAME, CHAIN_CODE_PATH, CHAIN_CODE_VERSION))
                    {
                        Assert.Fail($"Peer {peer.Name} is missing instantiated chaincode name:{CHAIN_CODE_NAME}, path:{CHAIN_CODE_PATH}, version: {CHAIN_CODE_VERSION}");
                    }
                }

                client.UserContext = sampleOrg.GetUser(TESTUSER_1_NAME);

                //Check if we still get the same value on the ledger
                Util.COut("delta is {0}", delta);
                QueryChaincodeForExpectedValue(client, channel, "" + (325 + delta), chaincodeID);

                MoveAmount(client, channel, chaincodeID_11, "50", changeContext ? sampleOrg.PeerAdmin : null); // really move 100
            }
            catch (TransactionEventException t)
            {
                TransactionEvent te = t.TransactionEvent;
                if (te != null)
                {
                    Assert.Fail($"Transaction with txid {te.TransactionID} failed. {t.Message}");
                }
            }
            catch (System.Exception e)
            {
                Assert.Fail($"Test failed with {e.GetType().Name} exception {e.Message}");
            }

            WaitOnFabric(10000);
            QueryChaincodeForExpectedValue(client, channel, "" + (425 + delta), chaincodeID_11);
            Util.COut("Running for Channel {0} done", channelName);
        }
Example #10
0
 public static T SetChaincodeEndorsementPolicy <T>(this T request, ChaincodeEndorsementPolicy policy) where T : TransactionRequest
 {
     request.ChaincodeEndorsementPolicy = policy;
     return(request);
 }