Exemple #1
0
        public void SalvarInfo(string id, Dictionary <string, string> vero)
        {
            var tx_id = client.NewTransactionProposalRequest();

            tx_id.Args = new List <string>()
            {
                id, Newtonsoft.Json.JsonConvert.SerializeObject(vero)
            };
            tx_id.ChaincodeID = new Hyperledger.Fabric.SDK.ChaincodeID()
            {
                Name = chaincode
            };
            tx_id.Fcn = "salvarInfo";

            var result = channel.SendTransactionProposal(tx_id);

            if (result.Count > 0)
            {
                //  return Newtonsoft.Json.JsonConvert.DeserializeObject<FabCarCollections>(System.Text.Encoding.UTF8.GetString(result[0].ChaincodeActionResponsePayload));
                Console.WriteLine(result[0].TransactionID);

                var eventHub = client.NewEventHub("event1", $"grpc://{Program.ServerIP}:7053");
                channel.AddEventHub(eventHub);

                eventHub.ConnectAsync(result[0].TransactionContext).Wait();
                var result2 = channel.SendTransaction(result);
                while (true)
                {
                    Console.Write($"\r{eventHub.Status}");
                    break;
                }
            }
            //return null;
        }
Exemple #2
0
        public void CreateCar(FabCarItem carItem)
        {
            // createCar chaincode function - requires 5 args, ex: args: ['CAR12', 'Honda', 'Accord', 'Black', 'Tom'],

            var tx_id = client.NewTransactionProposalRequest();

            tx_id.Args = new List <string>()
            {
                carItem.Key,
                carItem.Record.make,
                carItem.Record.model,
                carItem.Record.color,
                carItem.Record.owner,
            };
            tx_id.ChaincodeID = new Hyperledger.Fabric.SDK.ChaincodeID()
            {
                Name = chaincode
            };
            tx_id.Fcn = "createCar";

            var result = channel.SendTransactionProposal(tx_id);

            if (result.Count > 0)
            {
                //  return Newtonsoft.Json.JsonConvert.DeserializeObject<FabCarCollections>(System.Text.Encoding.UTF8.GetString(result[0].ChaincodeActionResponsePayload));
                Console.WriteLine(result[0].TransactionID);

                var eventHub = client.NewEventHub("event1", $"grpc://{Program.ServerIP}:7053");
                channel.AddEventHub(eventHub);

                eventHub.ConnectAsync(result[0].TransactionContext).Wait();
                var result2 = channel.SendTransaction(result);
                while (true)
                {
                    Console.Write($"\r{eventHub.Status}");
                    break;
                }
            }

            //return null;
        }
Exemple #3
0
        // ReSharper disable once UnusedMethodReturnValue.Local
        private static TransactionEvent MoveAmount(HFClient client, Channel channel, ChaincodeID chaincodeID, string from, string to, string moveAmount, IUser user)
        {
            List <ProposalResponse> successful = new List <ProposalResponse>();
            List <ProposalResponse> failed     = new List <ProposalResponse>();

            ///////////////
            // Send transaction proposal to all peers
            TransactionProposalRequest transactionProposalRequest = client.NewTransactionProposalRequest();

            transactionProposalRequest.SetChaincodeID(chaincodeID);
            transactionProposalRequest.SetFcn("move");
            transactionProposalRequest.SetArgs(from, to, moveAmount);
            transactionProposalRequest.SetProposalWaitTime(testConfig.GetProposalWaitTime());
            if (user != null)
            {
                // specific user use that
                transactionProposalRequest.SetUserContext(user);
            }

            Util.COut("sending transaction proposal to all peers with arguments: move(%s,%s,%s)", from, to, moveAmount);

            List <ProposalResponse> invokePropResp = channel.SendTransactionProposal(transactionProposalRequest);

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

            // Check that all the proposals are consistent with each other. We should have only one set
            // where all the proposals above are consistent.
            List <HashSet <ProposalResponse> > proposalConsistencySets = SDKUtils.GetProposalConsistencySets(invokePropResp);

            if (proposalConsistencySets.Count != 1)
            {
                Assert.Fail($"Expected only one set of consistent move proposal responses but got {proposalConsistencySets.Count}");
            }

            Util.COut("Received {0} transaction proposal responses. Successful+verified: {1} . Failed: {2}", invokePropResp.Count, successful.Count, failed.Count);
            if (failed.Count > 0)
            {
                ProposalResponse firstTransactionProposalResponse = failed.First();

                throw new ProposalException($"Not enough endorsers for invoke(move {from},{to},{moveAmount}):{firstTransactionProposalResponse.Status} endorser error:{firstTransactionProposalResponse.Message}. Was verified:{firstTransactionProposalResponse.IsVerified}");
            }

            Util.COut("Successfully received transaction proposal responses.");

            ////////////////////////////
            // Send transaction to orderer
            Util.COut("Sending chaincode transaction(move %s,%s,%s) to orderer.", from, to, moveAmount);
            if (user != null)
            {
                return(channel.SendTransaction(successful, user, testConfig.GetTransactionWaitTime() * 1000));
            }

            return(channel.SendTransaction(successful, testConfig.GetTransactionWaitTime() * 1000));
        }
        [Ignore] //Hostnames reported by service discovery won't work unless you edit hostfile
        public void Setup()
        {
            //Persistence is not part of SDK. Sample file store is for demonstration purposes only!
            //   MUST be replaced with more robust application implementation  (Database, LDAP)
            Util.COut("\n\n\nRUNNING: %s.\n", "ServiceDiscoveryIT");

            SampleStore sampleStore = new SampleStore(sampleStoreFile);

            //  SampleUser peerAdmin = sampleStore.getMember("admin", "peerOrg1");
            SampleUser user1  = sampleStore.GetMember("user1", "peerOrg1");
            HFClient   client = HFClient.Create();

            testConfig.GetIntegrationTestsSampleOrg("peerOrg1");
            client.CryptoSuite = Factory.GetCryptoSuite();
            client.UserContext = user1;
            Properties properties = testConfig.GetPeerProperties("peer0.org1.example.com");

            string protocol = testConfig.IsRunningFabricTLS() ? "grpcs:" : "grpc:";

            Properties sdprops = new Properties();

            //Create initial discovery peer.

            Peer    discoveryPeer = client.NewPeer("peer0.org1.example.com", protocol + "//localhost:7051", properties);
            Channel foo           = client.NewChannel("foo"); //create channel that will be discovered.

            foo.AddPeer(discoveryPeer, PeerOptions.CreatePeerOptions().SetPeerRoles(PeerRole.SERVICE_DISCOVERY, PeerRole.LEDGER_QUERY, PeerRole.EVENT_SOURCE, PeerRole.CHAINCODE_QUERY));

            // Need to provide client TLS certificate and key files when running mutual tls.
            if (testConfig.IsRunningFabricTLS())
            {
                sdprops.Add("org.hyperledger.fabric.sdk.discovery.default.clientCertFile", "fixture/sdkintegration/e2e-2Orgs/v1.2/crypto-config/peerOrganizations/org1.example.com/users/[email protected]/tls/client.crt".Locate());
                sdprops.Add("org.hyperledger.fabric.sdk.discovery.default.clientKeyFile", "fixture/sdkintegration/e2e-2Orgs/v1.2/crypto-config/peerOrganizations/org1.example.com/users/[email protected]/tls/client.key".Locate());

                // Need to do host name override for true tls in testing environment
                sdprops.Add("org.hyperledger.fabric.sdk.discovery.endpoint.hostnameOverride.localhost:7050", "orderer.example.com");
                sdprops.Add("org.hyperledger.fabric.sdk.discovery.endpoint.hostnameOverride.localhost:7051", "peer0.org1.example.com");
                sdprops.Add("org.hyperledger.fabric.sdk.discovery.endpoint.hostnameOverride.localhost:7056", "peer1.org1.example.com");
            }
            else
            {
                sdprops.Add("org.hyperledger.fabric.sdk.discovery.default.protocol", "grpc:");
            }

            foo.ServiceDiscoveryProperties = sdprops;

            string channel = foo.Serialize();

            // Next 3 lines are for testing purposes only!
            foo.Shutdown(false);
            foo = client.DeSerializeChannel(channel);
            foo.Initialize(); // initialize the channel.
            List <string> expect = new List <string>()
            {
                protocol + "//orderer.example.com:7050"
            };                                                                                  //discovered orderer

            foreach (Orderer orderer in foo.Orderers)
            {
                expect.Remove(orderer.Url);
            }

            Assert.IsTrue(expect.Count == 0);

            List <string> discoveredChaincodeNames = foo.GetDiscoveredChaincodeNames();

            Assert.IsTrue(discoveredChaincodeNames.Contains(CHAIN_CODE_NAME));

            ChaincodeID chaincodeID = new ChaincodeID();

            chaincodeID.Name = CHAIN_CODE_NAME;


            ///////////////
            // Send transaction proposal to all peers
            TransactionProposalRequest transactionProposalRequest = client.NewTransactionProposalRequest();

            transactionProposalRequest.SetChaincodeID(chaincodeID);
            transactionProposalRequest.SetChaincodeLanguage(CHAIN_CODE_LANG);
            transactionProposalRequest.SetFcn("move");
            transactionProposalRequest.SetProposalWaitTime(testConfig.GetProposalWaitTime());
            transactionProposalRequest.SetArgs("a", "b", "1");

            //Send proposal request discovering the what endorsers (peers) are needed.

            List <ProposalResponse> transactionPropResp = foo.SendTransactionProposalToEndorsers(transactionProposalRequest, DiscoveryOptions.CreateDiscoveryOptions().SetEndorsementSelector(ServiceDiscovery.ENDORSEMENT_SELECTION_RANDOM).SetForceDiscovery(true));

            Assert.IsFalse(transactionPropResp.Count == 0);

            transactionProposalRequest = client.NewTransactionProposalRequest();
            transactionProposalRequest.SetChaincodeID(chaincodeID);
            transactionProposalRequest.SetChaincodeLanguage(CHAIN_CODE_LANG);
            transactionProposalRequest.SetFcn("move");
            transactionProposalRequest.SetProposalWaitTime(testConfig.GetProposalWaitTime());
            transactionProposalRequest.SetArgs("a", "b", "1");

            //Send proposal request discovering the what endorsers (peers) are needed.
            transactionPropResp = foo.SendTransactionProposalToEndorsers(transactionProposalRequest, DiscoveryOptions.CreateDiscoveryOptions().IgnoreEndpoints("blah.blah.blah.com:90", "blah.com:80",
                                                                         // aka peer0.org1.example.com our discovery peer. Lets ignore it in endorsers selection and see if other discovered peer endorses.
                                                                                                                                                               "peer0.org1.example.com:7051")
                                                                         // if chaincode makes additional chaincode calls or uses collections you should add them with setServiceDiscoveryChaincodeInterests
                                                                         //         .setServiceDiscoveryChaincodeInterests(Channel.ServiceDiscoveryChaincodeCalls.createServiceDiscoveryChaincodeCalls("someOtherChaincodeName").addCollections("collection1", "collection2"))
                                                                         );
            Assert.AreEqual(transactionPropResp.Count, 1);
            ProposalResponse proposalResponse = transactionPropResp.First();
            Peer             peer             = proposalResponse.Peer;

            Assert.AreEqual(protocol + "//peer1.org1.example.com:7056", peer.Url); // not our discovery peer but the discovered one.

            string expectedTransactionId = null;

            StringBuilder evenTransactionId = new StringBuilder();

            foreach (ProposalResponse response in transactionPropResp)
            {
                expectedTransactionId = response.TransactionID;
                if (response.Status != ChaincodeResponse.ChaincodeResponseStatus.SUCCESS || !response.IsVerified)
                {
                    Assert.Fail("Failed status bad endorsement");
                }
            }

            //Send it to the orderer that was discovered.
            try
            {
                TransactionEvent transactionEvent = foo.SendTransaction(transactionPropResp);

                evenTransactionId.Length = 0;

                evenTransactionId.Append(transactionEvent.TransactionID);
            }
            catch (TransactionEventException e)
            {
                TransactionEvent te = e.TransactionEvent;
                if (te != null)
                {
                    throw new System.Exception($"Transaction with txid {te.TransactionID} failed. {e.Message}");
                }
            }
            catch (System.Exception e)
            {
                throw new System.Exception($"Test failed with {e.Message} exception {e}");
            }


            Assert.AreEqual(expectedTransactionId, evenTransactionId.ToString());
            Util.COut("That's all folks!");
        }
        private TransactionEvent MoveAmount(HFClient client, Channel channel, ChaincodeID chaincdeID, string moveAmount, IUser user)
        {
            try
            {
                List <ProposalResponse> successful = new List <ProposalResponse>();
                List <ProposalResponse> failed     = new List <ProposalResponse>();

                ///////////////
                // Send transaction proposal to all peers
                TransactionProposalRequest transactionProposalRequest = client.NewTransactionProposalRequest();
                transactionProposalRequest.ChaincodeID = chaincdeID;
                transactionProposalRequest.Fcn         = "move";
                transactionProposalRequest.SetArgs( //test using bytes .. end2end uses Strings.
                    "a".ToBytes(), "b".ToBytes(), moveAmount.ToBytes());
                transactionProposalRequest.ProposalWaitTime = testConfig.GetProposalWaitTime();
                if (user != null)
                {
                    // specific user use that
                    transactionProposalRequest.UserContext = user;
                }

                Util.COut("sending transaction proposal to all peers with arguments: move(a,b,{0})", moveAmount);

                List <ProposalResponse> invokePropResp = channel.SendTransactionProposal(transactionProposalRequest);
                foreach (ProposalResponse response in invokePropResp)
                {
                    if (response.Status == ChaincodeResponse.ChaincodeResponseStatus.SUCCESS)
                    {
                        Util.COut("Successful transaction proposal response Txid: {0} from peer {1}", response.TransactionID, response.Peer.Name);
                        successful.Add(response);
                    }
                    else
                    {
                        failed.Add(response);
                    }
                }

                Util.COut("Received {0} transaction proposal responses. Successful+verified: {1} . Failed: {2}", invokePropResp.Count, successful.Count, failed.Count);
                if (failed.Count > 0)
                {
                    ProposalResponse firstTransactionProposalResponse = failed.First();

                    throw new ProposalException($"Not enough endorsers for invoke(move a,b,{moveAmount}):{firstTransactionProposalResponse.Status} endorser error:{firstTransactionProposalResponse.Message}. Was verified:{firstTransactionProposalResponse.IsVerified}x");
                }

                Util.COut("Successfully received transaction proposal responses.");

                ////////////////////////////
                // Send transaction to orderer
                Util.COut("Sending chaincode transaction(move a,b,{0}) to orderer.", moveAmount);
                if (user != null)
                {
                    return(channel.SendTransaction(successful, user, testConfig.GetTransactionWaitTime() * 1000));
                }
                return(channel.SendTransaction(successful, testConfig.GetTransactionWaitTime() * 1000));
            }
            catch (System.Exception)
            {
                throw new TaskCanceledException();
            }
        }
        // ReSharper disable once UnusedMethodReturnValue.Local
        private TransactionEvent MoveAmount(HFClient client, Channel channel, ChaincodeID chaincdeID, string moveAmount, IUser user)
        {
            List <ProposalResponse> successful = new List <ProposalResponse>();
            List <ProposalResponse> failed     = new List <ProposalResponse>();

            ///////////////
            // Send transaction proposal to all peers
            TransactionProposalRequest transactionProposalRequest = client.NewTransactionProposalRequest();

            transactionProposalRequest.SetChaincodeID(chaincdeID);
            transactionProposalRequest.SetFcn("move");

            // Private data needs to be sent via Transient field to prevent identifiable
            //information being sent to the orderer.
            Dictionary <string, byte[]> transientMap = new Dictionary <string, byte[]>();

            transientMap["A"]          = "a".ToBytes(); //test using bytes .. end2end uses Strings.
            transientMap["B"]          = "b".ToBytes();
            transientMap["moveAmount"] = moveAmount.ToBytes();
            transactionProposalRequest.TransientMap = transientMap;



            transactionProposalRequest.SetProposalWaitTime(testConfig.GetProposalWaitTime());
            if (user != null)
            {
                // specific user use that
                transactionProposalRequest.SetUserContext(user);
            }

            Util.COut("sending transaction proposal to all peers with arguments: move(a,b,%s)", moveAmount);

            List <ProposalResponse> invokePropResp = channel.SendTransactionProposal(transactionProposalRequest);

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

            Util.COut("Received %d transaction proposal responses for moveAmount. Successful+verified: %d . Failed: %d", invokePropResp.Count, successful.Count, failed.Count);
            if (failed.Count > 0)
            {
                ProposalResponse firstTransactionProposalResponse = failed.First();

                throw new ProposalException($"Not enough endorsers for invoke(move a,b,{moveAmount}):{firstTransactionProposalResponse.Status} endorser error:{firstTransactionProposalResponse.Message}. Was verified:{firstTransactionProposalResponse.IsVerified}");
            }

            Util.COut("Successfully received transaction proposal responses.");

            ////////////////////////////
            // Send transaction to orderer
            Util.COut("Sending chaincode transaction(move a,b,%s) to orderer.", moveAmount);
            if (user != null)
            {
                return(channel.SendTransaction(successful, user));
            }

            return(channel.SendTransaction(successful));
        }
        // ReSharper disable once UnusedMethodReturnValue.Local
        private TransactionEvent SetAmount(HFClient client, Channel channel, ChaincodeID chaincdeID, int delta, IUser user)
        {
            List <ProposalResponse> successful = new List <ProposalResponse>();
            List <ProposalResponse> failed     = new List <ProposalResponse>();

            ///////////////
            // Send transaction proposal to all peers
            TransactionProposalRequest transactionProposalRequest = client.NewTransactionProposalRequest();

            transactionProposalRequest.SetChaincodeID(chaincdeID);
            transactionProposalRequest.SetFcn("set");


            Dictionary <string, byte[]> transientMap = new Dictionary <string, byte[]>();

            transientMap["A"]    = "a".ToBytes(); // test using bytes as args. End2end uses Strings.
            transientMap["AVal"] = "500".ToBytes();
            transientMap["B"]    = "b".ToBytes();
            string arg3 = "" + (200 + delta);

            transientMap["BVal"] = arg3.ToBytes();
            transactionProposalRequest.TransientMap = transientMap;

            transactionProposalRequest.SetProposalWaitTime(testConfig.GetProposalWaitTime());
            if (user != null)
            {
                // specific user use that
                transactionProposalRequest.SetUserContext(user);
            }

            List <ProposalResponse> invokePropResp = channel.SendTransactionProposal(transactionProposalRequest);

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

            Util.COut("Received %d transaction proposal responses for setAmount. Successful+verified: %d . Failed: %d", invokePropResp.Count, successful.Count, failed.Count);
            if (failed.Count > 0)
            {
                ProposalResponse firstTransactionProposalResponse = failed.First();
                throw new ProposalException($"Not enough endorsers for set(move a,b,{0}):{firstTransactionProposalResponse.Status} endorser error:{firstTransactionProposalResponse.Message}. Was verified:{firstTransactionProposalResponse.IsVerified}");
            }

            Util.COut("Successfully received transaction proposal responses for setAmount. Now sending to orderer.");

            ////////////////////////////
            // Send transaction to orderer

            if (user != null)
            {
                return(channel.SendTransaction(successful, user));
            }

            return(channel.SendTransaction(successful));
        }