Ejemplo n.º 1
0
 public PrivateDataIT()
 {
     chaincodeID         = new ChaincodeID();
     chaincodeID.Name    = CHAIN_CODE_NAME;
     chaincodeID.Version = CHAIN_CODE_VERSION;
     chaincodeID.Path    = CHAIN_CODE_PATH;
 }
Ejemplo n.º 2
0
        public static async Task <Handler> CreateAsync(ChaincodeID chaincodeId, IChaincodeAsync chaincode, CancellationToken token = default(CancellationToken))
        {
            Handler h = new Handler();

            h.chaincode = chaincode;
            h.State     = CCState.CREATED;
            await h.QueueOutboundChaincodeMessageAsync(NewRegisterChaincodeMessage(chaincodeId), token).ConfigureAwait(false);

            return(h);
        }
        public async Task <Response> HandleInvokeChaincode(
            string chaincodeName,
            IEnumerable <ByteString> args,
            string channelId,
            string txId
            )
        {
            var chaincodeId = new ChaincodeID {
                Name = chaincodeName
            };
            var inputArgs = new RepeatedField <ByteString>().Concat(args);

            var chaincodeInput = new ChaincodeInput();

            chaincodeInput.Args.AddRange(inputArgs);

            var payload = new ChaincodeSpec
            {
                ChaincodeId = chaincodeId,
                Input       = chaincodeInput
            };

            var response = await CreateMessageAndListen <ChaincodeMessage>(MessageMethod.InvokeChaincode,
                                                                           ChaincodeMessage.Types.Type.InvokeChaincode, payload, channelId, txId);

            if (response.Type == ChaincodeMessage.Types.Type.Completed)
            {
                return(Response.Parser.ParseFrom(response.Payload));
            }

            if (response.Type == ChaincodeMessage.Types.Type.Error)
            {
                throw new Exception(response.Payload.ToStringUtf8());
            }

            throw new Exception("Something went somewhere horribly wrong");
        }
Ejemplo n.º 4
0
        public async Task <IHandler> Start()
        {
            var url = ParseUrl(_chaincodeSettings.PeerAddress);

            // TODO: TLS Stuff?

            var handler = _handlerFactory.Create(url.Host, url.Port);

            var chaincodeId = new ChaincodeID {
                Name = _chaincodeSettings.ChaincodeIdName
            };

            _logger.LogInformation("Registering with peer " +
                                   $"{url.Host}:{url.Port} as chaincode " +
                                   $"{_chaincodeSettings.ChaincodeIdName}");

            await handler.Chat(new ChaincodeMessage
            {
                Type    = ChaincodeMessage.Types.Type.Register,
                Payload = chaincodeId.ToByteString()
            });

            return(handler);
        }
Ejemplo n.º 5
0
 private static ChaincodeMessage NewRegisterChaincodeMessage(ChaincodeID chaincodeId)
 {
     return(new ChaincodeMessage {
         Type = ChaincodeMessage.Types.Type.Register, Payload = chaincodeId.ToByteString()
     });
 }
Ejemplo n.º 6
0
        [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!");
        }
Ejemplo n.º 7
0
 public static T SetChaincodeID <T>(this T request, ChaincodeID chaincodeid) where T : TransactionRequest
 {
     request.ChaincodeID = chaincodeid;
     return(request);
 }
Ejemplo n.º 8
0
        private void QueryChaincodeForExpectedValue(HFClient client, Channel channel, string expect, ChaincodeID chaincdeID)
        {
            Util.COut("Now query chaincode {0} on channel {1} for the value of b expecting to see: {2}", chaincdeID, channel.Name, expect);
            List <ProposalResponse> queryProposals;
            QueryByChaincodeRequest queryByChaincodeRequest = client.NewQueryProposalRequest();

            queryByChaincodeRequest.SetFcn("query");
            queryByChaincodeRequest.ChaincodeID = chaincdeID;
            Dictionary <string, byte[]> tmap = new Dictionary <string, byte[]>();

            tmap["B"] = "b".ToBytes(); // test using bytes as args. End2end uses Strings.
            queryByChaincodeRequest.TransientMap = tmap;
            queryProposals = channel.QueryByChaincode(queryByChaincodeRequest);
            foreach (ProposalResponse proposalResponse in queryProposals)
            {
                if (!proposalResponse.IsVerified || proposalResponse.Status != ChaincodeResponse.ChaincodeResponseStatus.SUCCESS)
                {
                    Assert.Fail($"Failed query proposal from peer {proposalResponse.Peer.Name} status: {proposalResponse.Status}. Messages: {proposalResponse.Message}. Was verified : {proposalResponse.IsVerified}");
                }
                else
                {
                    string payload = proposalResponse.ProtoProposalResponse.Response.Payload.ToStringUtf8();
                    Util.COut("Query payload of b from peer {0} returned {1}", proposalResponse.Peer.Name, payload);
                    Assert.AreEqual(expect, payload, $"Failed compare on channel {channel.Name} chaincode id {chaincdeID} expected value:'{expect}', but got:'{payload}'");
                }
            }
        }
Ejemplo n.º 9
0
        // 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));
        }
Ejemplo n.º 10
0
        // 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));
        }
Ejemplo n.º 11
0
        public void TestHandlerStates()
        {
            CancellationToken token = default(CancellationToken);

            ChaincodeBaseAsync cb = new EmptyChaincode();

            ChaincodeID chaincodeId = new ChaincodeID {
                Name = "mycc"
            };
            Handler handler = Handler.CreateAsync(chaincodeId, cb).RunAndUnwrap();

            ChaincodeMessage msgReg = new ChaincodeMessage {
                Type = ChaincodeMessage.Types.Type.Registered
            };

            // Correct message
            handler.OnChaincodeMessageAsync(msgReg, token).RunAndUnwrap();
            Assert.AreEqual(CCState.ESTABLISHED, handler.State, "Not correct handler state");

            ChaincodeMessage msgReady = new ChaincodeMessage {
                Type = ChaincodeMessage.Types.Type.Ready
            };

            // Correct message
            handler.OnChaincodeMessageAsync(msgReady, token).RunAndUnwrap();
            Assert.AreEqual(CCState.READY, handler.State, "Not correct handler state");

            handler = Handler.CreateAsync(chaincodeId, cb).RunAndUnwrap();
            // Incorrect message
            handler.OnChaincodeMessageAsync(msgReady, token).RunAndUnwrap();
            Assert.AreEqual(CCState.CREATED, handler.State, "Not correct handler state");
            // Correct message
            handler.OnChaincodeMessageAsync(msgReg, token).RunAndUnwrap();
            Assert.AreEqual(CCState.ESTABLISHED, handler.State, "Not correct handler state");
            // Incorrect message
            handler.OnChaincodeMessageAsync(msgReg, token).RunAndUnwrap();
            Assert.AreEqual(CCState.ESTABLISHED, handler.State, "Not correct handler state");
            handler.OnChaincodeMessageAsync(msgReady, token).RunAndUnwrap();
            Assert.AreEqual(CCState.READY, handler.State, "Not correct handler state");

            // Unrelated message, do nothing
            ChaincodeMessage unkonwnMessage = new ChaincodeMessage {
                Type = ChaincodeMessage.Types.Type.PutState, ChannelId = "mychannel", Txid = "q", Payload = ByteString.CopyFromUtf8("")
            };

            handler.OnChaincodeMessageAsync(unkonwnMessage, token).RunAndUnwrap();
            Assert.AreEqual(CCState.READY, handler.State, "Not correct handler state");

            // KEEPALIVE message, do nothing
            ChaincodeMessage keepAliveMessage = new ChaincodeMessage {
                Type = ChaincodeMessage.Types.Type.Keepalive, ChannelId = "mychannel", Txid = "q", Payload = ByteString.CopyFromUtf8("")
            };

            handler.OnChaincodeMessageAsync(keepAliveMessage, token).RunAndUnwrap();
            Assert.AreEqual(CCState.READY, handler.State, "Not correct handler state");

            ChaincodeMessage errorMsg = new ChaincodeMessage {
                Type = ChaincodeMessage.Types.Type.Error, ChannelId = "mychannel", Txid = "q", Payload = ByteString.CopyFromUtf8("")
            };

            // Error message, except exception, no open communication
            try
            {
                handler.OnChaincodeMessageAsync(errorMsg, token).RunAndUnwrap();
                Assert.Fail("Expecting InvalidOperationException");
            }
            catch (InvalidOperationException)
            {
                //Ignore
            }

            Assert.AreEqual(CCState.READY, handler.State, "Not correct handler state");
        }