public static void Run()
        {
            var doc       = JObject.Parse(_docJson);
            var frame     = JObject.Parse(_frameJson);
            var opts      = new JsonLdOptions();
            var flattened = JsonLdProcessor.Frame(doc, frame, opts);

            Console.WriteLine(flattened);

            /*
             *
             * Output:
             * {
             *  "@context": . . .,
             *  "@graph": [
             *      {
             *          "@id": "_:b0",
             *          "@type": "Person",
             *          "image": "http://manu.sporny.org/images/manu.png",
             *          "name": "Manu Sporny",
             *          "homepage": "http://manu.sporny.org/"
             *      }
             *  ]
             * }
             *
             */
        }
        public static IEnumerable <VerificationMethod> FindVerificationMethods(DidDocument didDocument, string proofPurpose, IDocumentLoader documentLoader)
        {
            var processorOptions = new JsonLdProcessorOptions {
                DocumentLoader = documentLoader.Load
            };

            processorOptions.ExpandContext = Constants.SECURITY_CONTEXT_V2_URL;

            var result = JsonLdProcessor.Frame(
                input: didDocument,
                frame: new JObject
            {
                { "@context", Constants.SECURITY_CONTEXT_V2_URL },
                { "@explicit", true },
                { proofPurpose, new JObject {
                      { "@embed", "@always" }
                  } }
            },
                options: processorOptions);

            if (result[proofPurpose] == null || !(result[proofPurpose] is JArray purposes))
            {
                throw new Exception($"No verification keys found for prupose `{proofPurpose}`");
            }

            return(purposes.Select(x => new VerificationMethod(x as JObject)).ToList());
        }
Esempio n. 3
0
    public static void Main(string[] args)
    {
        String sparql = File.ReadAllText("../query.sparql");
        //Console.WriteLine(sparql);
        var parameters = new Dictionary <string, string>();

        parameters["query"]  = sparql;
        parameters["format"] = "text/turtle";

        var                 client      = new HttpClient();
        StringContent       queryString = new StringContent(sparql);
        HttpResponseMessage resp        = client.PostAsync("http://virhp07.libris.kb.se/sparql", new FormUrlEncodedContent(parameters)).Result;

        Console.WriteLine("Hello Mono World" + resp.StatusCode);
        var turtle = resp.Content.ReadAsStringAsync().Result;

        Console.WriteLine(turtle);
        var options = new JsonLdOptions()
        {
            format = "text/turtle"
        };

        options.SetUseNativeTypes(true);
        var expanded    = JsonLdProcessor.FromRDF(turtle, options);
        var context     = File.ReadAllText("../context.jsonld");
        var compOptions = new JsonLdOptions();

        compOptions.SetEmbed(true);
        var compacted = JsonLdProcessor.Frame(expanded, context, compOptions);

        Console.WriteLine(turtle);
        Console.WriteLine(expanded);
        Console.WriteLine(compacted);
    }
        public override async Task <ValidationResult> ValidateAsync(JToken proof, ProofOptions options)
        {
            var result = await base.ValidateAsync(proof, options);

            var verificationMethodId = Options.VerificationMethod["id"].ToString();
            var controllerId         = Controller ?? GetVerificationMethod() ??
                                       throw new ProofValidationException("Controller or VerificationMethod not found");

            var framed = JsonLdProcessor.Frame(
                controllerId,
                new JObject
            {
                { "@context", Constants.SECURITY_CONTEXT_V2_URL },
                { "id", controllerId },
                { Term, new JObject
                  {
                      { "@embed", "@never" },
                      { "id", verificationMethodId }
                  } }
            },
                options.GetProcessorOptions());

            if (framed[Term] is JArray keys && keys.Any(x => x.ToString() == verificationMethodId))
            {
                result.Controller = framed["id"].ToString();
                return(result);
            }

            throw new ProofValidationException($"Verification method '{verificationMethodId}' not authorized " +
                                               $"by controller for proof purpose '{Term}'.");
        }
        public JToken CreateProof(CreateProofOptions options, JsonLdProcessorOptions processorOptions)
        {
            var(document, proofs) = options.Document.GetProofs(processorOptions);
            var proof = new BbsBlsSignature2020(proofs.FirstOrDefault() ?? throw new Exception("Proof not found"));

            proof.Context = Constants.SECURITY_CONTEXT_V2_URL;

            var signature    = Convert.FromBase64String(proof.ProofValue);
            var derivedProof = JsonLdProcessor.Compact(new BbsBlsSignatureProof2020(), Constants.SECURITY_CONTEXT_V2_URL, processorOptions);

            var documentStatements = BbsBlsSignature2020Suite.CreateVerifyDocumentData(document, processorOptions);
            var proofStatements    = BbsBlsSignature2020Suite.CreateVerifyProofData(proof, processorOptions);

            var transformedInputDocumentStatements = documentStatements.Select(TransformBlankNodeToId).ToArray();

            var compactInputDocument = Helpers.FromRdf(transformedInputDocumentStatements);

            var revealDocument           = JsonLdProcessor.Frame(compactInputDocument, options.ProofRequest, processorOptions);
            var revealDocumentStatements = BbsBlsSignature2020Suite.CreateVerifyDocumentData(revealDocument, processorOptions);

            var numberOfProofStatements = proofStatements.Count();

            var proofRevealIndicies    = EnumerableFromInt(numberOfProofStatements).ToArray();
            var documentRevealIndicies = revealDocumentStatements.Select(x => Array.IndexOf(transformedInputDocumentStatements, x) + numberOfProofStatements).ToArray();

            if (documentRevealIndicies.Count() != revealDocumentStatements.Count())
            {
                throw new Exception("Some statements in the reveal document not found in original proof");
            }

            var revealIndicies = proofRevealIndicies.Concat(documentRevealIndicies);

            derivedProof["nonce"] = options.Nonce ?? Guid.NewGuid().ToString();

            //Combine all the input statements that
            //were originally signed to generate the proof
            var allInputStatements = proofStatements.Concat(documentStatements);

            var verificationMethod = BbsBlsSignature2020Suite.GetVerificationMethod(proofs.First(), processorOptions);

            var outputProof = BbsProvider.CreateProof(new CreateProofRequest(
                                                          publicKey: verificationMethod.ToBlsKeyPair().GeyBbsKeyPair((uint)allInputStatements.Count()),
                                                          messages: GetProofMessages(allInputStatements.ToArray(), revealIndicies).ToArray(),
                                                          signature: signature,
                                                          blindingFactor: null,
                                                          nonce: derivedProof["nonce"].ToString()));

            // Set the proof value on the derived proof
            derivedProof["proofValue"] = Convert.ToBase64String(outputProof);

            // Set the relevant proof elements on the derived proof from the input proof
            derivedProof["verificationMethod"] = proof["verificationMethod"];
            derivedProof["proofPurpose"]       = proof["proofPurpose"];
            derivedProof["created"]            = proof["created"];

            revealDocument["proof"] = derivedProof;

            return(revealDocument);
        }
Esempio n. 6
0
        private static void Example3()
        {
            var data = new Graph();

            data.Assert("http://person.com#bob", "http://schema.com#employer", "http://person.com#acme");
            data.Assert("http://person.com#bob", "http://schema.com#name", "http://person.com#bob/name");
            data.Assert("http://person.com#bob/name", "http://schema.com#first", GraphObject.FromData("Bob"));
            data.Assert("http://person.com#bob/name", "http://schema.com#second", GraphObject.FromData("Dylan"));

            Console.WriteLine(JsonLdProcessor.Frame(new Context {
                Base = "http://schema.com#"
            }, data, "http://person.com#bob"));
        }
Esempio n. 7
0
        public void Save(IGraph g, TextWriter output)
        {
            JToken flattened = MakeExpandedForm(g);

            if (Frame == null)
            {
                output.Write(flattened);
            }
            else
            {
                JObject framed    = JsonLdProcessor.Frame(flattened, Frame, new JsonLdOptions());
                JObject compacted = JsonLdProcessor.Compact(framed, framed["@context"], new JsonLdOptions());
                output.Write(compacted);
            }
        }
        /// <inheritdoc />
        protected override IVerifyData CreateVerifyData(JObject proof, ProofOptions options)
        {
            var originalProof = options.AdditonalData["originalDocument"]["proof"].DeepClone() as JObject;

            originalProof["type"] = "BbsBlsSignature2020";

            var processorOptions = options.GetProcessorOptions();

            var proofStatements    = Helpers.CanonizeProofStatements(originalProof, processorOptions, Constants.SECURITY_CONTEXT_V3_URL);
            var documentStatements = Helpers.CanonizeStatements(options.Input, processorOptions);

            var numberOfProofStatements = proofStatements.Count();

            // if RevealDocument is present, this is a proof derivation
            // apply transformation of blank node to urn:bnid format
            if (RevealDocument != null)
            {
                var transformedInputDocumentStatements = documentStatements.Select(TransformBlankNodeToId).ToArray();
                var compactInputDocument = Helpers.FromRdf(transformedInputDocumentStatements);

                var revealDocument           = JsonLdProcessor.Frame(compactInputDocument, RevealDocument, processorOptions);
                var revealDocumentStatements = Helpers.CanonizeStatements(revealDocument, processorOptions);

                options.AdditonalData["revealDocument"] = revealDocument;

                var documentRevealIndicies = revealDocumentStatements.Select(x => Array.IndexOf(transformedInputDocumentStatements, x) + numberOfProofStatements).ToArray();

                if (documentRevealIndicies.Count() != revealDocumentStatements.Count())
                {
                    throw new Exception("Some statements in the reveal document not found in original proof");
                }

                var proofRevealIndicies = new int[numberOfProofStatements].Select((_, x) => x).ToArray();
                var revealIndicies      = proofRevealIndicies.Concat(documentRevealIndicies);

                options.AdditonalData["revealIndicies"] = new JArray(revealIndicies.ToArray());
            }
            else
            {
                // it's proof verification, apply transform id to blank node
                documentStatements = documentStatements.Select(TransformIdToBlankNode);
            }

            var allInputStatements = proofStatements.Concat(documentStatements);

            return((StringArray)allInputStatements.ToArray());
        }
Esempio n. 9
0
        private T Deserialize <T>(JToken jsonLd, JToken context, JObject frame)
        {
            if (context == null)
            {
                return(jsonLd.ToObject <T>(this.jsonSerializer));
            }

            if (frame == null)
            {
                return(JsonLdProcessor.Compact(jsonLd, context, new JsonLdOptions()).ToObject <T>(this.jsonSerializer));
            }

            frame["@context"] = context;
            var framed = JsonLdProcessor.Frame(jsonLd, frame, new JsonLdOptions());

            return(framed["@graph"].Single().ToObject <T>(this.jsonSerializer));
        }
Esempio n. 10
0
        private static void Example1()
        {
            var g = new Graph();

            g.Assert("http://orders.com#order123", "http://schema.orders.com#address", "http://orders.com#address123");
            g.Assert("http://orders.com#order123", "http://schema.orders.com#payment", "http://orders.com#payment123");
            g.Assert("http://orders.com#address123", "http://schema.orders.com#street", GraphObject.FromData("101 108th"));
            g.Assert("http://orders.com#payment123", "http://schema.orders.com#name", GraphObject.FromData("Arthur Dexter Bradley"));
            g.Assert("http://orders.com#payment123", "http://schema.orders.com#number", GraphObject.FromData("1234-1234-1234-1234"));
            g.Assert("http://orders.com#address123", "http://schema.orders.com#city", GraphObject.FromData("Bellevue"));
            g.Assert("http://orders.com#address123", "http://schema.orders.com#state", GraphObject.FromData("WA"));

            var g2 = new Graph();

            g2.Assert("http://orders.com#payment123", "http://schema.orders.com#ccv", GraphObject.FromData("123"));
            g2.Assert("http://orders.com#payment123", "http://schema.orders.com#expiry", GraphObject.FromData("20/05"));
            g2.Assert("http://orders.com#address123", "http://schema.orders.com#zip", GraphObject.FromData("98004"));

            g.Merge(g2);

            var context = new Context
            {
                Base  = "http://schema.orders.com#",
                Terms =
                {
                    { "o", new Context.TermDefinition {
                          Id = "http://orders.com#"
                      } }
                }
            };

            var obj = JsonLdProcessor.Frame(context, g, "http://orders.com#order123");

            Console.WriteLine(obj);

            var graph = JsonLdProcessor.CreateGraph(obj);

            foreach (var triple in graph.GetTriples())
            {
                Console.WriteLine($"<{triple.Subject}> <{triple.Predicate}> {triple.Object} .");
            }
        }
Esempio n. 11
0
        public static JObject JsonFromGraph(IGraph graph, string rootType, JToken context)
        {
            System.IO.StringWriter stringWriter = new System.IO.StringWriter();
            IRdfWriter             rdfWriter    = new JsonLdWriter();

            rdfWriter.Save(graph, stringWriter);
            stringWriter.Flush();

            JObject frame = new JObject();

            frame.Add("@context", context);
            frame.Add("@type", rootType);
            //frame.Add("@embed", false);

            JToken  flattened = JToken.Parse(stringWriter.ToString());
            JObject framed    = JsonLdProcessor.Frame(flattened, frame, new JsonLdOptions());
            JObject compacted = JsonLdProcessor.Compact(framed, context, new JsonLdOptions());

            return(compacted);
        }
Esempio n. 12
0
        public static string CreateJson(IGraph graph, JToken frame = null)
        {
            System.IO.StringWriter writer    = new System.IO.StringWriter();
            IRdfWriter             rdfWriter = new JsonLdWriter();

            rdfWriter.Save(graph, writer);
            writer.Flush();

            if (frame == null)
            {
                return(writer.ToString());
            }
            else
            {
                JToken  flattened = JToken.Parse(writer.ToString());
                JObject framed    = JsonLdProcessor.Frame(flattened, frame, new JsonLdOptions());
                JObject compacted = JsonLdProcessor.Compact(framed, frame["@context"], new JsonLdOptions());

                return(compacted.ToString());
            }
        }
        protected VerificationMethod GetVerificationMethod(JObject proof, ProofOptions options)
        {
            var verificationMethod = proof["verificationMethod"] ?? throw new Exception("No 'verificationMethod' found in proof.");

            var verificationMethodId = verificationMethod.Type switch
            {
                JTokenType.String => verificationMethod.ToString(),
                JTokenType.Object => verificationMethod["id"]?.ToString() ?? throw new Exception("Verification Method found, but it's 'id' property was empty"),
                      _ => throw new Exception($"Invalid verification method type: {verificationMethod.Type}")
            };
            var processorOptions = options.GetProcessorOptions();

            processorOptions.ExpandContext = Constants.SECURITY_CONTEXT_V2_URL;

            var result = JsonLdProcessor.Frame(
                verificationMethodId,
                new JObject
            {
                { "@context", Constants.SECURITY_CONTEXT_V2_URL },
                { "@embed", "@always" },
                { "id", verificationMethod }
            },
                processorOptions);

            if (result == null || result["id"] == null)
            {
                throw new Exception($"Verification method {verificationMethod} not found.");
            }

            if (result["revoked"] != null)
            {
                throw new Exception("The verification method has been revoked.");
            }

            return(new VerificationMethod(result));
        }
Esempio n. 14
0
        public IEnumerator <object[]> GetEnumerator()
        {
            foreach (string manifest in manifests)
            {
                JToken manifestJson;

                manifestJson = GetJson(manifest);

                foreach (JObject testcase in manifestJson["sequence"])
                {
                    Func <JToken>   run;
                    ConformanceCase newCase = new ConformanceCase();

                    newCase.input   = GetJson(testcase["input"]);
                    newCase.context = GetJson(testcase["context"]);
                    newCase.frame   = GetJson(testcase["frame"]);

                    var options = new JsonLdOptions("http://json-ld.org/test-suite/tests/" + (string)testcase["input"]);

                    var testType = (JArray)testcase["@type"];

                    if (testType.Any((s) => (string)s == "jld:NegativeEvaluationTest"))
                    {
                        newCase.error = testcase["expect"];
                    }
                    else if (testType.Any((s) => (string)s == "jld:PositiveEvaluationTest"))
                    {
                        if (testType.Any((s) => new List <string> {
                            "jld:ToRDFTest", "jld:NormalizeTest"
                        }.Contains((string)s)))
                        {
                            newCase.output = File.ReadAllText(Path.Combine("W3C", (string)testcase["expect"]));
                        }
                        else if (testType.Any((s) => (string)s == "jld:FromRDFTest"))
                        {
                            newCase.input  = File.ReadAllText(Path.Combine("W3C", (string)testcase["input"]));
                            newCase.output = GetJson(testcase["expect"]);
                        }
                        else
                        {
                            newCase.output = GetJson(testcase["expect"]);
                        }
                    }
                    else
                    {
                        throw new Exception("Expecting either positive or negative evaluation test.");
                    }

                    JToken optionToken;
                    JToken value;

                    if (testcase.TryGetValue("option", out optionToken))
                    {
                        JObject optionDescription = (JObject)optionToken;

                        if (optionDescription.TryGetValue("compactArrays", out value))
                        {
                            options.SetCompactArrays((bool)value);
                        }
                        if (optionDescription.TryGetValue("base", out value))
                        {
                            options.SetBase((string)value);
                        }
                        if (optionDescription.TryGetValue("expandContext", out value))
                        {
                            newCase.context = GetJson(testcase["option"]["expandContext"]);
                            options.SetExpandContext((JObject)newCase.context);
                        }
                        if (optionDescription.TryGetValue("produceGeneralizedRdf", out value))
                        {
                            options.SetProduceGeneralizedRdf((bool)value);
                        }
                        if (optionDescription.TryGetValue("useNativeTypes", out value))
                        {
                            options.SetUseNativeTypes((bool)value);
                        }
                        if (optionDescription.TryGetValue("useRdfType", out value))
                        {
                            options.SetUseRdfType((bool)value);
                        }
                    }

                    if (testType.Any((s) => (string)s == "jld:CompactTest"))
                    {
                        run = () => JsonLdProcessor.Compact(newCase.input, newCase.context, options);
                    }
                    else if (testType.Any((s) => (string)s == "jld:ExpandTest"))
                    {
                        run = () => JsonLdProcessor.Expand(newCase.input, options);
                    }
                    else if (testType.Any((s) => (string)s == "jld:FlattenTest"))
                    {
                        run = () => JsonLdProcessor.Flatten(newCase.input, newCase.context, options);
                    }
                    else if (testType.Any((s) => (string)s == "jld:FrameTest"))
                    {
                        run = () => JsonLdProcessor.Frame(newCase.input, newCase.frame, options);
                    }
                    else if (testType.Any((s) => (string)s == "jld:NormalizeTest"))
                    {
                        run = () => new JValue(
                            RDFDatasetUtils.ToNQuads((RDFDataset)JsonLdProcessor.Normalize(newCase.input, options)).Replace("\n", "\r\n")
                            );
                    }
                    else if (testType.Any((s) => (string)s == "jld:ToRDFTest"))
                    {
                        options.format = "application/nquads";
                        run            = () => new JValue(
                            ((string)JsonLdProcessor.ToRDF(newCase.input, options)).Replace("\n", "\r\n")
                            );
                    }
                    else if (testType.Any((s) => (string)s == "jld:FromRDFTest"))
                    {
                        options.format = "application/nquads";
                        run            = () => JsonLdProcessor.FromRDF(newCase.input, options);
                    }
                    else
                    {
                        run = () => { throw new Exception("Couldn't find a test type, apparently."); };
                    }

                    if ((string)manifestJson["name"] == "Remote document")
                    {
                        Func <JToken> innerRun = run;
                        run = () =>
                        {
                            var remoteDoc = options.documentLoader.LoadDocument("https://json-ld.org/test-suite/tests/" + (string)testcase["input"]);
                            newCase.input = remoteDoc.Document;
                            options.SetBase(remoteDoc.DocumentUrl);
                            options.SetExpandContext((JObject)remoteDoc.Context);
                            return(innerRun());
                        };
                    }

                    if (testType.Any((s) => (string)s == "jld:NegativeEvaluationTest"))
                    {
                        Func <JToken> innerRun = run;
                        run = () =>
                        {
                            try
                            {
                                return(innerRun());
                            }
                            catch (JsonLdError err)
                            {
                                JObject result = new JObject();
                                result["error"] = err.Message;
                                return(result);
                            }
                        };
                    }

                    newCase.run = run;

                    yield return(new object[] { manifest + (string)testcase["@id"], (string)testcase["name"], newCase });
                }
            }
        }
Esempio n. 15
0
        private static void ExampleSchemaNet()
        {
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore,
                TypeNameHandling  = TypeNameHandling.Auto
            };

            var context = new Context
            {
                Base  = "http://schema.org",
                Terms = { { "o", new Context.TermDefinition {
                                Id = "http://orders.com"
                            } } }
            };

            var graph = new Graph();
            var joe   = new Person()
            {
                Id         = new Uri("http://schema.org/Person#1234567890"),
                Name       = "Joe",
                FamilyName = "Smith",
                Gender     = GenderType.Female
            };

            // add Joe to graph
            graph.Merge(JsonLdProcessor.CreateGraph(joe));

            var sarah = new Person()
            {
                Id         = new Uri("http://schema.org/Person#0987654321"),
                Name       = "Sarah",
                FamilyName = "Smith",
                Gender     = GenderType.Female
            };

            // add Sarah to graph
            graph.Merge(JsonLdProcessor.CreateGraph(sarah));

            // add spouse relationships between the 2 Person objects
            // NOTE: This uses the JsonLd.Id and context to create Uris and validates that Spouse is actual property on the source object
            graph.Assert(joe, "Spouse", sarah);
            graph.Assert(sarah, "Spouse", joe);

            // dump triples
            Console.WriteLine("---triples---- ");
            foreach (var triple in graph.GetTriples())
            {
                Console.WriteLine($"  {triple}");
            }

            // dump joe nodes as JsObject
            var jsJoe = JsonLdProcessor.Frame(context, graph, "http://schema.org/Person#1234567890");

            Console.WriteLine("---JSObject ---- ");
            Console.WriteLine(jsJoe);

            // get joe as Person object
            var joe2 = JsonLdProcessor.AsObject <Person>(context, graph, "http://schema.org/Person#1234567890");

            Console.WriteLine("---POCO object---- ");
            Console.WriteLine(JsonConvert.SerializeObject(joe2, Formatting.Indented));

            // Get joe as Person object
            var sarah2 = JsonLdProcessor.AsObject <Person>(context, graph, "http://schema.org/Person#0987654321");

            Console.WriteLine("---POCO object---- ");
            Console.WriteLine(JsonConvert.SerializeObject(sarah2, Formatting.Indented));
        }