Exemplo n.º 1
0
        public static TransactionProposal createInvokerProposal(TransRequest request, TransactionHeader transactionHeader)
        {
            var args = new RepeatedField <ByteString>();

            args.Add(Util.ConvertToByteString(request.Fcn));
            foreach (var item in request.Args)
            {
                args.Add(Util.ConvertToByteString(item));
            }
            var ccis = new ChaincodeSpec()
            {
                Type        = ChaincodeSpec.Types.Type.Undefined,
                ChaincodeId = new ChaincodeID()
                {
                    Name = request.ChaincodeId
                },
                Input = new ChaincodeInput()
                {
                    Args = args,
                }
            };
            var proposal = CreateChaincodeProposalWithTxIDNonceAndTransient(ccis, transactionHeader, request.TransientMap);
            var tp       = new TransactionProposal()
            {
                TxnID    = transactionHeader.Id,
                Proposal = proposal
            };

            return(tp);
        }
Exemplo n.º 2
0
        public virtual async Task <Response> InvokeChaincodeAsync(string channelId, string txId, string chaincodeName, List <byte[]> args, CancellationToken token = default(CancellationToken))
        {
            try
            {
                // create invocation specification of the chaincode to invoke
                ChaincodeSpec invocationSpec = new ChaincodeSpec {
                    ChaincodeId = new ChaincodeID {
                        Name = chaincodeName
                    }, Input = new ChaincodeInput {
                        Args = { args.Select(ByteString.CopyFrom) }
                    }
                };
                // invoke other chaincode
                ByteString payload = await InvokeChaincodeSupportAsync(NewInvokeChaincodeMessage(channelId, txId, invocationSpec.ToByteString()), token).ConfigureAwait(false);

                // response message payload should be yet another chaincode
                // message (the actual response message)
                ChaincodeMessage responseMessage = ChaincodeMessage.Parser.ParseFrom(payload);
                // the actual response message must be of type COMPLETED
                logger.Debug($"[{txId},-8]{responseMessage.Type} response received from other chaincode.");
                if (responseMessage.Type == ChaincodeMessage.Types.Type.Completed)
                {
                    // success
                    return(ToChaincodeResponse(Protos.Peer.ProposalResponsePackage.Response.Parser.ParseFrom(responseMessage.Payload)));
                }

                // error
                return(NewErrorChaincodeResponse(responseMessage.Payload.ToStringUtf8()));
            }
            catch (Exception e)
            {
                throw new InvalidOperationException(e.Message, e);
            }
        }
Exemplo n.º 3
0
        public void TestProposalBuilderWithOutMetaInf()
        {
            InstallProposalBuilder installProposalBuilder = InstallProposalBuilder.Create();

            installProposalBuilder.ChaincodeLanguage(TransactionRequest.Type.GO_LANG);
            installProposalBuilder.ChaincodePath("github.com/example_cc");
            installProposalBuilder.ChaincodeSource(SAMPLE_GO_CC.Locate());
            installProposalBuilder.ChaincodeName("example_cc.go");
            installProposalBuilder.ChaincodeVersion("1");

            Channel            channel            = hfclient.NewChannel("testProposalBuilderWithOutMetaInf");
            TransactionContext transactionContext = new TransactionContext(channel, TestUtils.TestUtils.GetMockUser("rick", "rickORG"), Factory.Instance.GetCryptoSuite());

            installProposalBuilder.Context(transactionContext);

            Proposal proposal = installProposalBuilder.Build(); // Build it get the proposal. Then unpack it to see if it's what we expect.
            ChaincodeProposalPayload chaincodeProposalPayload = ChaincodeProposalPayload.Parser.ParseFrom(proposal.Payload);
            ChaincodeInvocationSpec  chaincodeInvocationSpec  = ChaincodeInvocationSpec.Parser.ParseFrom(chaincodeProposalPayload.Input);
            ChaincodeSpec            chaincodeSpec            = chaincodeInvocationSpec.ChaincodeSpec;
            ChaincodeInput           input = chaincodeSpec.Input;

            ChaincodeDeploymentSpec chaincodeDeploymentSpec = ChaincodeDeploymentSpec.Parser.ParseFrom(input.Args[1]);
            ByteString    codePackage = chaincodeDeploymentSpec.CodePackage;
            List <string> tarBytesToEntryArrayList = TestUtils.TestUtils.TarBytesToEntryArrayList(codePackage.ToByteArray());

            List <string> expect = new List <string>()
            {
                "src/github.com/example_cc/example_cc.go"
            };

            CollectionAssert.AreEquivalent(expect, tarBytesToEntryArrayList, "Tar in Install Proposal's codePackage does not have expected entries. ");
        }
Exemplo n.º 4
0
        private static Proposal CreateChaincodeProposalWithTxIDNonceAndTransient(ChaincodeSpec ccis, TransactionHeader transactionHeader, Dictionary <string, string> transientMap)
        {
            var ccHdrExt = new ChaincodeHeaderExtension()
            {
                ChaincodeId = ccis.ChaincodeId
            };
            var ccHdrExtBytes = Util.Marshal(ccHdrExt);
            var cis           = new ChaincodeInvocationSpec()
            {
                ChaincodeSpec = ccis
            };

            var cisBytes      = Util.Marshal(cis);
            var ccPropPayload = new ChaincodeProposalPayload()
            {
                Input        = cisBytes,
                TransientMap = Util.ConvertMapField(transientMap)
            };
            var ccPropPayloadBytes = Util.Marshal(ccPropPayload);
            var timestamp          = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime(DateTime.UtcNow);

            // TODO: epoch is now set to zero. This must be changed once we
            // get a more appropriate mechanism to handle it in.
            ulong epoch = 0;
            var   hdr   = new Header()
            {
                ChannelHeader = Util.Marshal(new ChannelHeader()
                {
                    Type      = (int)HeaderType.EndorserTransaction,
                    TxId      = transactionHeader.Id,
                    Timestamp = timestamp,
                    ChannelId = transactionHeader.ChannelID,
                    Extension = ccHdrExtBytes,
                    Epoch     = epoch
                }),
                SignatureHeader = Util.Marshal(new SignatureHeader()
                {
                    Nonce   = transactionHeader.Nonce,
                    Creator = transactionHeader.Creator
                })
            };
            var hdrBytes = Util.Marshal(hdr);
            var prop     = new Proposal()
            {
                Header  = hdrBytes,
                Payload = ccPropPayloadBytes
            };

            return(prop);
        }
        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");
        }
Exemplo n.º 6
0
        public static ChaincodeDeploymentSpec CreateDeploymentSpec(ChaincodeSpec.Types.Type ccType, string name, string chaincodePath,
                                                                   string chaincodeVersion, List <string> args,
                                                                   byte[] codePackage)
        {
            Protos.Peer.ChaincodeID chaincodeID = new Protos.Peer.ChaincodeID
            {
                Name    = name,
                Version = chaincodeVersion
            };
            if (chaincodePath != null)
            {
                chaincodeID.Path = chaincodePath;
            }
            if (args == null)
            {
                args = new List <string>();
            }
            // build chaincodeInput
            List <ByteString> argList        = args.Select(ByteString.CopyFromUtf8).ToList();
            ChaincodeInput    chaincodeInput = new ChaincodeInput();

            chaincodeInput.Args.AddRange(argList);

            // Construct the ChaincodeSpec
            ChaincodeSpec chaincodeSpec = new ChaincodeSpec {
                ChaincodeId = chaincodeID, Input = chaincodeInput, Type = ccType
            };

            if (isDebugLevel)
            {
                StringBuilder sb = new StringBuilder(1000);
                sb.Append("ChaincodeDeploymentSpec chaincode cctype: ")
                .Append(ccType.ToString())
                .Append(", name:")
                .Append(chaincodeID.Name)
                .Append(", path: ")
                .Append(chaincodeID.Path)
                .Append(", version: ")
                .Append(chaincodeID.Version);

                string sep = "";
                sb.Append(" args(");

                foreach (ByteString x in argList)
                {
                    sb.Append(sep).Append("\"").Append(x.ToStringUtf8().LogString()).Append("\"");
                    sep = ", ";
                }
                sb.Append(")");
                logger.Debug(sb.ToString());
            }

            ChaincodeDeploymentSpec spec = new ChaincodeDeploymentSpec {
                ChaincodeSpec = chaincodeSpec, ExecEnv = ChaincodeDeploymentSpec.Types.ExecutionEnvironment.Docker
            };

            if (codePackage != null)
            {
                spec.CodePackage = ByteString.CopyFrom(codePackage);
            }
            return(spec);
        }
Exemplo n.º 7
0
        private ChaincodeInvocationSpec CreateChaincodeInvocationSpec(Protos.Peer.ChaincodeID ccodeID, ChaincodeSpec.Types.Type langType)
        {
            List <ByteString> allArgs = new List <ByteString>();

            if (argList != null && argList.Count > 0)
            {
                // If we already have an argList then the Builder subclasses have already set the arguments
                // for chaincodeInput. Accept the list and pass it on to the chaincodeInput builder
                // TODO need to clean this logic up so that common protobuf struct builds are in one place
                allArgs = argList;
            }
            else if (request != null)
            {
                // if argList is empty and we have a Request, build the chaincodeInput args array from the Request args and argbytes lists
                allArgs.Add(ByteString.CopyFromUtf8(request.Fcn));
                List <string> args = request.Args;
                if (args != null && args.Count > 0)
                {
                    foreach (string arg in args)
                    {
                        allArgs.Add(ByteString.CopyFromUtf8(arg));
                    }
                }

                // TODO currently assume that chaincodeInput args are strings followed by byte[].
                // Either agree with Fabric folks that this will always be the case or modify all Builders to expect
                // a List of Objects and determine if each list item is a string or a byte array
                List <byte[]> argBytes = request.ArgsBytes;
                if (argBytes != null && argBytes.Count > 0)
                {
                    foreach (byte[] arg in argBytes)
                    {
                        allArgs.Add(ByteString.CopyFrom(arg));
                    }
                }
            }

            if (IS_DEBUG_LEVEL)
            {
                StringBuilder logout = new StringBuilder(1000);

                logout.Append($"ChaincodeInvocationSpec type: {langType.ToString()}, chaincode name: {ccodeID.Name}, chaincode path: {ccodeID.Path}, chaincode version: {ccodeID.Version}");

                string sep = "";
                logout.Append(" args(");

                foreach (ByteString x in allArgs)
                {
                    logout.Append(sep).Append("\"").Append(x.ToStringUtf8().LogString()).Append("\"");
                    sep = ", ";
                }

                logout.Append(")");

                logger.Debug(logout.ToString);
            }

            ChaincodeInput chaincodeInput = new ChaincodeInput();

            chaincodeInput.Args.AddRange(allArgs);
            ChaincodeSpec chaincodeSpec = new ChaincodeSpec {
                Type = langType, ChaincodeId = ccodeID, Input = chaincodeInput
            };

            return(new ChaincodeInvocationSpec {
                ChaincodeSpec = chaincodeSpec
            });
        }