예제 #1
0
        /**
         * Utility method for outputting proofs in a formatted textual
         * representation.
         * 
         * @param aProof
         * @return a String representation of the Proof.
         */
        public static String printProof(Proof aProof)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("Proof, Answer Bindings: ");
            sb.Append(aProof.getAnswerBindings());
            sb.Append("\n");

            List<ProofStep> steps = aProof.getSteps();

            int maxStepWidth = "Step".Length;
            int maxProofWidth = "Proof".Length;
            int maxJustificationWidth = "Justification".Length;

            // Calculate the maximum width for each column in the proof
            foreach (ProofStep step in steps)
            {
                String sn = "" + step.getStepNumber();
                if (sn.Length > maxStepWidth)
                {
                    maxStepWidth = sn.Length;
                }
                if (step.getProof().Length > maxProofWidth)
                {
                    maxProofWidth = step.getProof().Length;
                }
                if (step.getJustification().Length > maxJustificationWidth)
                {
                    maxJustificationWidth = step.getJustification().Length;
                }
            }

            // Give a little extra padding
            maxStepWidth += 1;
            maxProofWidth += 1;
            maxJustificationWidth += 1;

            String f = "|%-" + maxStepWidth + "s| %-" + maxProofWidth + "s|%-"
                    + maxJustificationWidth + "s|\n";

            int barWidth = 5 + maxStepWidth + maxProofWidth + maxJustificationWidth;
            StringBuilder bar = new StringBuilder();
            for (int i = 0; i < barWidth; i++)
            {
                bar.Append("-");
            }
            bar.Append("\n");

            sb.Append(bar);
            sb.Append(String.Format(f, "Step", "Proof", "Justification"));
            sb.Append(bar);
            foreach (ProofStep step in steps)
            {
                sb.Append(String.Format(f, "" + step.getStepNumber(), step
                        .getProof(), step.getJustification()));
            }
            sb.Append(bar);

            return sb.ToString();
        }
예제 #2
0
        /// <summary>
        /// Gets the proof document for the endpoint of the specified JobId and Pin.
        /// </summary>
        /// <param name="id">The Job Id</param>
        /// <param name="pin">The EndPoint Pin</param>
        /// <returns>the proof document for the endpoint of the specified JobId and Pin.</returns>
        public Proof GetProof(int id, string pin)
        {
            if (id == 0)
            {
                throw new Exception("Id must be greater than zero");
            }
            var resource = string.Format("Proof/{0}/{1}", id, pin);

            return(Proof.FromString(CallWithRetry(resource, "GET"), _interfaceFormat));
        }
예제 #3
0
        private bool VerifyResponse(Transcript transcript, Proof proof)
        {
            // After all the public nonces have been committed, a challenge can be
            // generated based on transcript state. Since challenges are deterministic
            // outputs of a hash function which depends on the prover commitments, the
            // verifier obtains the same challenge and then accepts if the responses
            // satisfy the verification equation.
            var challenge = transcript.GenerateChallenge();

            return(Statement.CheckVerificationEquation(proof.PublicNonces, challenge, proof.Responses));
        }
예제 #4
0
        private VerifyResponse CommitToNonces(Transcript transcript, Proof proof)
        {
            // After all the statements have been committed, the public nonces are
            // added to the transcript. This is done separately from the statement
            // commitments because the prover derives these based on the compound
            // statements, and the verifier must add data to the transcript in the
            // same order as the prover.
            transcript.CommitPublicNonces(proof.PublicNonces);

            return(() => VerifyResponse(transcript, proof));
        }
예제 #5
0
 public override int GetHashCode()
 {
     unchecked
     {
         int hashCode = Index.GetHashCode();
         hashCode = (hashCode * 397) ^ PreviousBlockHash.GetHashCode();
         hashCode = (hashCode * 397) ^ Proof.GetHashCode();
         hashCode = (hashCode * 397) ^ Timestamp.GetHashCode();
         hashCode = (hashCode * 397) ^ Transactions.GetHashCode();
         return(hashCode);
     }
 }
예제 #6
0
        public static void Verify(Proof proof, Item item, Root root)
        {
            if (!entryDigest(item).ContentEqual(proof?.Leaf?.ToByteArray()))
            {
                throw new VerificationException("Proof does not verify!");
            }

            verifyInclusion(proof);

            if (root != null && root.Index > 0)
            {
                verifyConsistency(proof, root);
            }
        }
예제 #7
0
 public void Read(IReader reader)
 {
     Version         = reader.read_u16();
     Height          = reader.read_u64();
     Previous        = Hash.Hash.Readnew(reader);
     Timestamp       = reader.read_i64().FromUnixTime();
     UtxoRoot        = Hash.Hash.Readnew(reader);
     RangeProofRoot  = Hash.Hash.Readnew(reader);
     KernelRoot      = Hash.Hash.Readnew(reader);
     Nonce           = reader.read_u64();
     Difficulty      = Difficulty.Readnew(reader);
     TotalDifficulty = Difficulty.Readnew(reader);
     Pow             = Proof.Readnew(reader);
 }
예제 #8
0
        public void ProofJsonToObject()
        {
            Proof expected = GetProofObject();
            Proof result   = parser.ParseJsonToObject <Proof>(GetProofJson());

            Assert.AreEqual(expected.a, result.a);
            Assert.AreEqual(expected.ap, result.ap);
            Assert.AreEqual(expected.Ps, result.Ps);
            helper.CompareList <string>(expected.tr, result.tr);
            helper.CompareList <string>(expected.D, result.D);
            helper.CompareList <string>(expected.r, result.r);
            helper.CompareList <string>(expected.ta, result.ta);
            helper.CompareList <string>(expected.tc, result.tc);
        }
        /// <summary>
        /// Method to Get the Particular Record from Database
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public Proof GetSingleRecordDetail(int Id)
        {
            Proof obj = new Proof();

            string strQuery = "";

            strQuery = strQuery + System.Environment.NewLine + "SELECT		M.ID	        AS Id,";
            strQuery = strQuery + System.Environment.NewLine + "			M.NAME	        AS Name,";
            strQuery = strQuery + System.Environment.NewLine + "			M.IS_ACTIVE     AS IsActive";
            strQuery = strQuery + System.Environment.NewLine + "FROM		PROOF_MASTER M";
            strQuery = strQuery + System.Environment.NewLine + "WHERE		M.ID = "+ Id.ToString();

            obj = Db.DapperGet <Proof>(strQuery);

            return(obj);
        }
        internal override byte[] GenerateBytes()
        {
            var builder = new FlatBufferBuilder(1);


            // create vectors
            var signatureVector = SecretProofTransactionBuffer.CreateSignatureVector(builder, new byte[64]);
            var signerVector    = SecretProofTransactionBuffer.CreateSignerVector(builder, GetSigner());
            var feeVector       = SecretProofTransactionBuffer.CreateMaxFeeVector(builder, MaxFee?.ToUInt8Array());
            var deadlineVector  =
                SecretProofTransactionBuffer.CreateDeadlineVector(builder, Deadline.Ticks.ToUInt8Array());
            var secretVector = SecretLockTransactionBuffer.CreateSecretVector(builder, Secret.DecodeHexString());
            var proofVector  = SecretProofTransactionBuffer.CreateProofVector(builder, Proof.DecodeHexString());
            var version      = int.Parse(NetworkType.GetValueInByte().ToString("X") + "0" + Version.ToString("X"),
                                         NumberStyles.HexNumber);
            var recipientVector = SecretProofTransactionBuffer.CreateRecipientVector(builder, Recipient.GetBytes());

            int totalSize = GetSerializedSize();


            SecretProofTransactionBuffer.StartSecretProofTransactionBuffer(builder);
            SecretProofTransactionBuffer.AddSize(builder, (uint)totalSize);
            SecretProofTransactionBuffer.AddSignature(builder, signatureVector);
            SecretProofTransactionBuffer.AddSigner(builder, signerVector);
            SecretProofTransactionBuffer.AddVersion(builder, (uint)version);
            SecretProofTransactionBuffer.AddType(builder, TransactionType.GetValue());
            SecretProofTransactionBuffer.AddMaxFee(builder, feeVector);
            SecretProofTransactionBuffer.AddDeadline(builder, deadlineVector);
            SecretProofTransactionBuffer.AddHashAlgorithm(builder, HashType.GetValueInByte());
            SecretProofTransactionBuffer.AddRecipient(builder, recipientVector);
            SecretProofTransactionBuffer.AddSecret(builder, secretVector);
            SecretProofTransactionBuffer.AddProofSize(builder, Convert.ToUInt16(Proof.DecodeHexString().Length));
            SecretProofTransactionBuffer.AddProof(builder, proofVector);

            var codedSecretProof = SecretProofTransactionBuffer.EndSecretProofTransactionBuffer(builder);

            builder.Finish(codedSecretProof.Value);

            var output = new SecretProofTransactionSchema().Serialize(builder.SizedByteArray());

            if (output.Length != totalSize)
            {
                throw new SerializationException("Serialized form has incorrect length");
            }

            return(output);
        }
예제 #11
0
        /// <summary>
        /// first method to call - Initializes the ProverProof by generating the PresentationProof
        /// </summary>
        /// <param name="ip">IssuerParameter from the Issuer of the given token</param>
        /// <param name="attributes">Attributes which are included in the given token</param>
        /// <param name="proofRequirements">Necessary informations for creating the proofs (e.g. disclosedAttributes)</param>
        /// <param name="tokenWithKey">Token for which the proof will be done</param>
        /// <param name="supportedDateAttributes">If there is a RangeProof done, all date attributes where treated and formated especially</param>
        /// <param name="devicePresentationContext">If there was a device involved during the token generation, the context from the device is needed to generate the
        /// PresentationProof as well</param>
        /// <returns>returns the proof for the given token as json object or an error</returns>
        public string Init(IssuerParameters ip, List <BasicClaim> attributes, ProofRequirements proofRequirements,
                           UProveKeyAndToken tokenWithKey, List <string> supportedDateAttributes,
                           IDevicePresentationContext devicePresentationContext)
        {
            try
            {
                LogService.Log(LogService.LogType.Info, "ProverProof - init called");
                this.ip = ip;
                this.proofRequirements = proofRequirements;
                ci.CreateBase64ForAttributeList(attributes, supportedDateAttributes, out rangeProofProperties);
                attributesToInclude = ci.ConvertAttributeListToBase64ByteArray(attributes);

                pppp = new ProverPresentationProtocolParameters(this.ip, proofRequirements.disclosedAttributes,
                                                                proofRequirements.message, tokenWithKey, attributesToInclude);
                pppp.Committed = proofRequirements.committedAttributes;

                //// TODO
                //// if a scope is defined, we use the first attribute to derive a scope exclusive pseudonym
                //pppp.PseudonymAttributeIndex = (proofRequirements.scope == null ? 0 : 1);
                //pppp.PseudonymScope = proofRequirements.scope;

                // add device presentation context to the provers presentation context
                if (this.ip.IsDeviceSupported && devicePresentationContext != null)
                {
                    pppp.SetDeviceData(proofRequirements.deviceMessage, devicePresentationContext);
                }

                // generate proof
                PresentationProof pProof = PresentationProof.Generate(pppp, out cpv);
                LogService.Log(LogService.LogType.Info, "ProverProof - init presentation proof generated");

                proof = parser.ParseJsonToObject <Proof>(this.ip.Serialize <PresentationProof>(pProof));
                proof.requirements = proofRequirements;

                string proofJson = parser.ParseObjectToJson(proof);
                LogService.Log(LogService.LogType.Info, "ProverProof - proof created: " + proofJson);

                return(proofJson);
            }
            catch (Exception e)
            {
                LogService.Log(LogService.LogType.FatalError, "ProverProof - Error during prover setup.", e);
                throw new CommunicationException("ProverProof - Error during ProverProof init; " + e);
            }
        }
예제 #12
0
파일: NamesTable.cs 프로젝트: fubrak/Merkle
        /// <summary>
        /// parses a Proof of Merkle table to a list of strings
        /// </summary>
        /// <param name="proof"></param>
        /// <returns>ArrayList with all the strings</returns>
        private static ArrayList ParseProof(Proof proof)
        {
            var temptext = proof.ToJson();

            var charsToRemove = new string[] { "[", "]", ",", "{", "}", ":" };

            foreach (var c in charsToRemove)
            {
                temptext = temptext.Replace(c, string.Empty);
            }
            temptext = temptext.Replace("\"", " ");

            ArrayList tempend = new ArrayList(temptext.Split("  "));

            tempend.RemoveRange(0, 1);

            return(tempend);
        }
예제 #13
0
        public static BlockHeader Default()
        {
            var proofSize = Global.Proofsize();

            return(new BlockHeader
            {
                Version = 1,
                Height = 0,
                Previous = Hash.Hash.ZERO_HASH(),
                Timestamp = DateTime.UtcNow.PrecisionSeconds(),
                Difficulty = Difficulty.From_num(Consensus.MinimumDifficulty),
                TotalDifficulty = Difficulty.From_num(Consensus.MinimumDifficulty),
                UtxoRoot = Hash.Hash.ZERO_HASH(),
                RangeProofRoot = Hash.Hash.ZERO_HASH(),
                KernelRoot = Hash.Hash.ZERO_HASH(),
                Nonce = 0,
                Pow = Proof.Zero(proofSize)
            });
        }
        /// <summary>
        /// Method to Save the Entry
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int SaveData(Proof obj)
        {
            int Id = 0;

            List <SqlParameter> parameters = new List <SqlParameter>();

            parameters.Add(new SqlParameter("@ID", obj.Id));
            parameters.Add(new SqlParameter("@NAME", obj.Name));
            parameters.Add(new SqlParameter("@IS_ACTIVE", obj.IsActive));

            DataTable dt = Db.GetDataTable("SAVE_UPDATE_PROOF_MASTER", parameters);

            if (dt.Rows.Count > 0)
            {
                Id = Convert.ToInt32(dt.Rows[0][0]);
            }

            return(Id);
        }
예제 #15
0
        public void CanProveAndVerifyMAC()
        {
            // The coordinator generates a composed private key called CoordinatorSecretKey
            // and derives from that the coordinator's public parameters called CoordinatorParameters.
            var rnd                   = new SecureRandom();
            var coordinatorKey        = new CoordinatorSecretKey(rnd);
            var coordinatorParameters = coordinatorKey.ComputeCoordinatorParameters();

            // A blinded amount is known as an `attribute`. In this case the attribute Ma is the
            // value 10000 blinded with a random `blindingFactor`. This attribute is sent to
            // the coordinator.
            var amount = new Scalar(10_000);
            var r      = rnd.GetScalar();
            var Ma     = amount * Generators.G + r * Generators.Gh;

            // The coordinator generates a MAC and a proof that the MAC was generated using the
            // coordinator's secret key. The coordinator sends the pair (MAC + proofOfMac) back
            // to the client.
            var t   = rnd.GetScalar();
            var mac = MAC.ComputeMAC(coordinatorKey, Ma, t);

            var coordinatorKnowledge = ProofSystem.IssuerParameters(mac, Ma, coordinatorKey);
            var proofOfMac           = ProofSystem.Prove(coordinatorKnowledge, rnd);

            // The client receives the MAC and the proofOfMac which let the client know that the MAC
            // was generated with the coordinator's secret key.
            var clientStatement = ProofSystem.IssuerParameters(coordinatorParameters, mac, Ma);
            var isValidProof    = ProofSystem.Verify(clientStatement, proofOfMac);

            Assert.True(isValidProof);

            var corruptedResponses = new ScalarVector(proofOfMac.Responses.Reverse());
            var invalidProofOfMac  = new Proof(proofOfMac.PublicNonces, corruptedResponses);

            isValidProof = ProofSystem.Verify(clientStatement, invalidProofOfMac);
            Assert.False(isValidProof);

            var corruptedPublicNonces = new GroupElementVector(proofOfMac.PublicNonces.Reverse());

            invalidProofOfMac = new Proof(corruptedPublicNonces, proofOfMac.Responses);
            isValidProof      = ProofSystem.Verify(clientStatement, invalidProofOfMac);
            Assert.False(isValidProof);
        }
예제 #16
0
        private void Button3_Click(object sender, EventArgs e)
        {
            Program.m_mainform.AddNewGjalZs();

            using (var context = new CaseContext())
            {
                Case  @case = context.Cases.Find(AppConfig.getAppConfig().caseId_selected_working);
                Proof proof = new Proof()
                {
                    Case = @case,
                };
                @case.Proofs.Add(proof);

                context.SaveChanges();
            }

            this.Close();
            AppConfig.AppConfigAddAdvinceClear();
            AppContext.setInstanceNull();
        }
예제 #17
0
        private static void verifyInclusion(Proof proof)
        {
            var at = proof.At;
            var i  = proof.Index;

            if (i > at || (at > 0 && proof.InclusionPath.Count == 0))
            {
                throw new VerificationException("Inclusion proof does not verify!");
            }

            byte[] finalArray = proof.Leaf.ToByteArray();

            foreach (var inclusionArray in proof.InclusionPath)
            {
                using (var stream = new MemoryStream())
                {
                    stream.WriteByte(node_prefix);

                    if (i % 2 == 0 && i != at)
                    {
                        stream.Write(finalArray);
                        stream.Write(inclusionArray.ToByteArray());
                    }
                    else
                    {
                        stream.Write(inclusionArray.ToByteArray());
                        stream.Write(finalArray);
                    }

                    finalArray = stream.ToArray().SHAHash();
                }

                i  /= 2;
                at /= 2;
            }

            if (at != i || !finalArray.ContentEqual(proof.Root.ToByteArray()))
            {
                throw new VerificationException("Inclusion proof does not verify!");
            }
        }
        public IHttpActionResult PostImage(string id, Proof proof)
        {
            try
            {
                proof.Employee_id = DatabaseAction.GetEmployeeID(id);

                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }
                db.Proofs.Add(proof);
                db.SaveChanges();
                DatabaseAction.ConvertImage1(DatabaseAction.GetEmployeeID(id));
                return(Ok());
            }
            catch (Exception ex)
            {
                LogFile.WriteLog(ex);
                return(BadRequest());
            }
        }
        public IHttpActionResult AddProof(string id, Proof proof)
        {
            try
            {
                proof.Employee_id = DatabaseAction.GetEmployeeID(id);
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                db.Proofs.Add(proof);
                db.SaveChanges();
                return(Ok("Employee proof Details Successfully Added"));
            }

            catch (Exception ex)
            {
                LogFile.WriteLog(ex);
                return(BadRequest());
            }
        }
예제 #20
0
        public void IsSynced()
        {
            ClientConfiguration config = _client.Configuration;

            Assert.That(!config.HasChanged());

            uint  requestCount   = 1;
            bool  autoUpdateList = false;
            Proof proof          = Proof.None;
            uint  maxAttempts    = 1;
            uint  signatureCount = 0;

            config.RequestCount   = requestCount;
            config.AutoUpdateList = autoUpdateList;
            config.Proof          = proof;
            config.MaxAttempts    = maxAttempts;
            config.SignatureCount = signatureCount;

            Assert.That(config.HasChanged());
            _client.Eth1.GetChainId();
            Assert.That(!config.HasChanged());
        }
예제 #21
0
        public static bool Verify(Proof proof, byte[] leaf, Root prevRoot)
        {
            if (proof == null || !leaf.SequenceEqual(proof.Leaf.ToByteArray()))
            {
                return(false);
            }

            var path = FromSlice(proof.InclusionPath);
            var rt   = proof.Root.ToByteArray();
            var lf   = proof.Leaf.ToByteArray();

            bool verifiedInclusion = Inclusion.VerifyPath(
                path,
                proof.At,
                proof.Index,
                rt,
                lf
                );

            if (!verifiedInclusion)
            {
                return(false);
            }

            // we cannot check consistency when the previous root is not provided
            if (prevRoot.Index == 0 && prevRoot.Root_.Length == 0)
            {
                return(true);
            }

            path = FromSlice(proof.ConsistencyPath);

            var firstRoot  = prevRoot.Root_.ToByteArray();
            var secondRoot = proof.Root.ToByteArray();

            return(Consistency.VerifyPath(path, proof.At, prevRoot.Index, secondRoot, firstRoot));
        }
예제 #22
0
        private void FormGjglZzxxEdit_Load(object sender, EventArgs e)
        {
            AppConfig ac = AppConfig.getAppConfig();

            using (CaseContext caseContext = new CaseContext())
            {
                Proof proofInfo = caseContext.Proofs.FirstOrDefault(p => p.ProofId == ac.proofId_selected);
                if (proofInfo == null)
                {
                    MessageBox.Show("该证据不存在,无法继续进行编辑!");
                    this.Close();
                    return;
                }
                this.Proof = proofInfo;
                //对要编辑的页面进行初始化,这是页面上的数据是从数据库里面取出来的
                textBox1.Text  = this.Proof.ProofName;
                textBox2.Text  = this.Proof.ProofSerialNum;
                textBox6.Text  = this.Proof.PhoneNum;
                textBox3.Text  = this.Proof.phoneNum2;
                textBox4.Text  = this.Proof.Holder;
                comboBox2.Text = this.Proof.ProofType;
                textBox8.Text  = this.Proof.note;
            }
        }
예제 #23
0
        internal static void AddTree(this Subproof p, Tree t)
        {
            if (t == null)
            {
                throw new ArgumentNullException();
            }
            if (t.State != TreeState.Closed)
            {
                throw new InvalidOperationException();
            }

            if (t.decomposed == null)
            {
                // Something got a contradiction here, find out what
                List <WFF> all = t.getAllSentences();
                WFF        c1  = null;
                WFF        c2  = null;
                for (int a = 0; a < all.Count; a++)
                {
                    if (all[a] is Negation)
                    {
                        Negation n = (Negation)all[a];
                        if (n.inner is Identity)
                        {
                            Identity i = (Identity)n.inner;
                            if (i.left.Equals(i.right))
                            {
                                c1 = all[a];
                                break;
                            }
                        }
                    }
                    else if (all[a] is Contradiction)
                    {
                        c1 = all[a];
                        break;
                    }

                    bool found = false;
                    for (int b = a + 1; b < all.Count; b++)
                    {
                        if (all[a].Equals(all[b].GetNegation()) || all[b].Equals(all[a].GetNegation()))
                        {
                            c1    = all[a];
                            c2    = all[b];
                            found = true;
                            break;
                        }
                    }

                    if (found)
                    {
                        break;
                    }
                }

                Proof p1 = p.Find(c1);
                if (p1 == null)
                {
                    throw new InvalidOperationException("p1");
                }

                if (c2 == null)
                {
                    p.steps.Add(new ProofLine(new Contradiction(), Rule.ContradictionIntro, p1));
                }
                else
                {
                    Proof p2 = p.Find(c2);
                    if (p2 == null)
                    {
                        throw new InvalidOperationException("p2");
                    }

                    p.steps.Add(new ProofLine(new Contradiction(), Rule.ContradictionIntro, p1, p2));
                }

                return;
            }

            Proof d = p.Find(t.decomposed);

            if (t.decomposed is Biconditional)
            {
                // Add the steps for Equiv
                Biconditional b   = (Biconditional)t.decomposed;
                Disjunction   equ = new Disjunction(
                    new Conjunction(b.left, b.right),
                    new Conjunction(b.left.GetNegation(), b.right.GetNegation()));
                ProofLine equp = new ProofLine(equ, Rule.Equivalence, d);
                p.steps.Add(equp);

                ProofLine plleft = new ProofLine(equ.disjuncts[0], Rule.Assumption);
                Subproof  left   = new Subproof();
                left.parent = p;
                left.assumptions.Add(plleft);
                left.steps.Add(new ProofLine(b.left, Rule.AndElim, plleft));
                left.steps.Add(new ProofLine(b.right, Rule.AndElim, plleft));
                AddTree(left, t.children[0]);
                p.steps.Add(left);

                ProofLine plright = new ProofLine(equ.disjuncts[1], Rule.Assumption);
                Subproof  right   = new Subproof();
                right.parent = p;
                right.assumptions.Add(plright);
                right.steps.Add(new ProofLine(b.left.GetNegation(), Rule.AndElim, plright));
                right.steps.Add(new ProofLine(b.right.GetNegation(), Rule.AndElim, plright));
                AddTree(right, t.children[1]);
                p.steps.Add(right);

                p.steps.Add(new ProofLine(new Contradiction(), Rule.OrElim, equp, left, right));
            }
            else if (t.decomposed is Conditional)
            {
                // Add the steps for Impl
                Conditional c    = (Conditional)t.decomposed;
                Disjunction imp  = new Disjunction(c.antecedent.GetNegation(), c.consequent);
                ProofLine   impp = new ProofLine(imp, Rule.Implication, d);
                p.steps.Add(impp);

                Proof[] steps = new Proof[t.children.Length + 1];
                steps[0] = impp;
                for (int a = 0; a < t.children.Length; a++)
                {
                    steps[a + 1] = new Subproof();
                    Subproof s = (Subproof)steps[a + 1];
                    s.parent = p;
                    s.assumptions.Add(new ProofLine(t.children[a].sentences[0], Rule.Assumption));
                    AddTree(s, t.children[a]);
                    p.steps.Add(s);
                }
                p.steps.Add(new ProofLine(new Contradiction(), Rule.OrElim, steps));
            }
            else if (t.decomposed is Conjunction)
            {
                foreach (WFF f in t.children[0].sentences)
                {
                    p.steps.Add(new ProofLine(f, Rule.AndElim, d));
                }
                AddTree(p, t.children[0]);
            }
            else if (t.decomposed is Disjunction)
            {
                Proof[] steps = new Proof[t.children.Length + 1];
                steps[0] = d;
                for (int a = 0; a < t.children.Length; a++)
                {
                    steps[a + 1] = new Subproof();
                    Subproof s = (Subproof)steps[a + 1];
                    s.parent = p;
                    s.assumptions.Add(new ProofLine(t.children[a].sentences[0], Rule.Assumption));
                    AddTree(s, t.children[a]);
                    p.steps.Add(s);
                }
                p.steps.Add(new ProofLine(new Contradiction(), Rule.OrElim, steps));
            }
            else if (t.decomposed is Existential)
            {
                Subproof sub = new Subproof();
                sub.parent = p;
                sub.assumptions.Add(new ProofLine(t.children[0].sentences[0], Rule.Assumption));
                AddTree(sub, t.children[0]);
                p.steps.Add(sub);
                p.steps.Add(new ProofLine(new Contradiction(), Rule.ExistentialElim, d, sub));
            }
            else if (t.decomposed is Identity)
            {
                // Need to add some way to find the other source
                foreach (WFF f in t.children[0].sentences)
                {
                    p.steps.Add(new ProofLine(f, Rule.EqualsElim, d));
                }
                AddTree(p, t.children[0]);
            }
            else if (t.decomposed is Negation)
            {
                Negation n = (Negation)t.decomposed;
                if (n.inner is Biconditional)
                {
                    // I really hope there is a better way for this one
                    // Add the steps for DeM and Equiv
                    Biconditional b   = (Biconditional)n.inner;
                    ProofLine     equ = new ProofLine(new Negation(new Conjunction(new Disjunction(b.left.GetNegation(), b.right), new Disjunction(b.left, b.right.GetNegation()))), Rule.Equivalence, d);
                    p.steps.Add(equ);

                    ProofLine dem = new ProofLine(new Disjunction(new Negation(new Disjunction(b.left.GetNegation(), b.right)), new Negation(new Disjunction(b.left, b.right.GetNegation()))), Rule.DeMorgans, equ);
                    p.steps.Add(dem);

                    Subproof left = new Subproof();
                    left.parent = p;
                    ProofLine plleft = new ProofLine(new Negation(new Disjunction(b.left.GetNegation(), b.right)), Rule.Assumption);
                    left.assumptions.Add(plleft);
                    ProofLine demleft = new ProofLine(new Conjunction(b.left, b.right.GetNegation()), Rule.DeMorgans, plleft);
                    left.steps.Add(demleft);
                    left.steps.Add(new ProofLine(b.left, Rule.AndElim, demleft));
                    left.steps.Add(new ProofLine(b.right.GetNegation(), Rule.AndElim, demleft));
                    AddTree(left, t.children[1]);
                    p.steps.Add(left);

                    Subproof right = new Subproof();
                    right.parent = p;
                    ProofLine plright = new ProofLine(new Negation(new Disjunction(b.left, b.right.GetNegation())), Rule.Assumption);
                    right.assumptions.Add(plright);
                    ProofLine demright = new ProofLine(new Conjunction(b.left.GetNegation(), b.right), Rule.DeMorgans, plright);
                    right.steps.Add(demright);
                    right.steps.Add(new ProofLine(b.left.GetNegation(), Rule.AndElim, demright));
                    right.steps.Add(new ProofLine(b.right, Rule.AndElim, demright));
                    AddTree(right, t.children[0]);
                    p.steps.Add(right);

                    p.steps.Add(new ProofLine(new Contradiction(), Rule.OrElim, dem, left, right));
                }
                else if (n.inner is Conditional)
                {
                    // Add the steps for DeM and Impl
                    Conditional c   = (Conditional)n.inner;
                    ProofLine   imp = new ProofLine(new Negation(new Disjunction(c.antecedent.GetNegation(), c.consequent)), Rule.Implication, d);
                    p.steps.Add(imp);

                    ProofLine dem = new ProofLine(new Conjunction(c.antecedent, c.consequent.GetNegation()), Rule.DeMorgans, imp);
                    p.steps.Add(dem);

                    p.steps.Add(new ProofLine(c.antecedent, Rule.AndElim, dem));
                    p.steps.Add(new ProofLine(c.consequent.GetNegation(), Rule.AndElim, dem));

                    AddTree(p, t.children[0]);
                }
                else if (n.inner is Conjunction)
                {
                    // Add the steps for DeM
                    Conjunction i   = (Conjunction)n.inner;
                    List <WFF>  neg = new List <WFF>();
                    foreach (WFF f in i.conjuncts)
                    {
                        neg.Add(f.GetNegation());
                    }
                    Disjunction dem  = new Disjunction(neg.ToArray());
                    ProofLine   demp = new ProofLine(dem, Rule.DeMorgans, d);
                    p.steps.Add(demp);

                    Proof[] steps = new Proof[t.children.Length + 1];
                    steps[0] = demp;
                    for (int a = 0; a < t.children.Length; a++)
                    {
                        steps[a + 1] = new Subproof();
                        Subproof s = (Subproof)steps[a + 1];
                        s.parent = p;
                        s.assumptions.Add(new ProofLine(t.children[a].sentences[0], Rule.Assumption));
                        AddTree(s, t.children[a]);
                        p.steps.Add(s);
                    }
                    p.steps.Add(new ProofLine(new Contradiction(), Rule.OrElim, steps));
                }
                else if (n.inner is Disjunction)
                {
                    // Add the steps for DeM
                    Disjunction i   = (Disjunction)n.inner;
                    List <WFF>  neg = new List <WFF>();
                    foreach (WFF f in i.disjuncts)
                    {
                        neg.Add(f.GetNegation());
                    }
                    Conjunction dem = new Conjunction(neg.ToArray());

                    ProofLine demp = new ProofLine(dem, Rule.DeMorgans, d);
                    p.steps.Add(demp);

                    foreach (WFF f in t.children[0].sentences)
                    {
                        p.steps.Add(new ProofLine(f, Rule.AndElim, demp));
                    }
                    AddTree(p, t.children[0]);
                }
                else if (n.inner is Existential)
                {
                    // Add the steps for DeM
                    p.steps.Add(new ProofLine(t.children[0].sentences[0], Rule.DeMorgans, d));
                    AddTree(p, t.children[0]);
                }
                else if (n.inner is Negation)
                {
                    p.steps.Add(new ProofLine(t.children[0].sentences[0], Rule.NotElim, d));
                    AddTree(p, t.children[0]);
                }
                else if (n.inner is Universal)
                {
                    // Add the steps for DeM
                    p.steps.Add(new ProofLine(t.children[0].sentences[0], Rule.DeMorgans, d));
                    AddTree(p, t.children[0]);
                }
            }
            else if (t.decomposed is Universal)
            {
                foreach (WFF f in t.children[0].sentences)
                {
                    p.steps.Add(new ProofLine(f, Rule.UniversalElim, d));
                }
                AddTree(p, t.children[0]);
            }
        }
예제 #24
0
 public static bool Verify(Statement statement, Proof proof)
 {
     return(ProofSystem.Verify(new Transcript(Array.Empty <byte>()), new[] { statement }, new[] { proof }));
 }
예제 #25
0
        private void Button3_Click(object sender, EventArgs e)
        {
            ////方法1修改config的数据库路径
            //XmlDocument doc = new XmlDocument();
            ////获得配置文件的全路径
            //string strFileName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName+".config";
            //MessageBox.Show(strFileName);
            //doc.Load(strFileName);
            ////找出名称为“add”的所有元素
            //XmlNodeList nodes = doc.GetElementsByTagName("add");
            //XmlAttribute att;
            //for (int i = 0; i < nodes.Count; i++)
            //{
            //    //获得将当前元素的key属性
            //    att = nodes[i].Attributes["name"];
            //    //根据元素的第一个属性来判断当前的元素是不是目标元素
            //    if (att != null && att.Value == "sqlite_connection_string")
            //    {
            //        //对目标元素中的第二个属性赋值
            //        att = nodes[i].Attributes["connectionString"];
            //        string strConn = "Data Source=" + Program.m_mainform.g_workPath + "\\midwxtrans.db;Pooling=true;FailIfMissing=false";
            //        att.Value = strConn;
            //        break;
            //    }
            //}
            ////保存上面的修改
            //doc.Save(strFileName);

            //FieldInfo fieldInfo = typeof(ConfigurationManager).GetField("sqlite_connection_string", BindingFlags.NonPublic | BindingFlags.Static);
            //if (fieldInfo != null) fieldInfo.SetValue(null, 0);

            ////方法2修改config的数据库路径,均不能正常工作
            ////读app.config中的connectionStrings
            //ModifyAppConfig mac = new ModifyAppConfig();
            //string strConnStrings = mac.GetConnectionStringsConfig("sqlite_connection_string");
            ////重写app.config中的connectionStrings
            //ModifyAppConfig mac1 = new ModifyAppConfig();//"D:\手机取证工作路径设置\案件20190707093739\HONORV2020190701094546\AppData\Weixin\ca9529dc14475dbcc7e8553e77ad7d0b"
            //string strConn = "Data Source=" + Program.m_mainform.g_workPath + "\\midwxtrans.db;Pooling=true;FailIfMissing=false";
            //mac1.UpdateConnectionStringsConfig("sqlite_connection_string", strConn, "System.Data.SQLite.EF6");
            //strConnStrings = mac1.GetConnectionStringsConfig("sqlite_connection_string");

            Program.m_mainform.AddNewGjalZs();

            using (var context = new CaseContext())
            {
                Case  @case = context.Cases.Find(AppConfig.getAppConfig().caseId_selected_working);
                Proof proof = new Proof()
                {
                    Case           = @case,
                    ProofName      = textBox1.Text,
                    ProofSerialNum = textBox2.Text,
                    PhoneNum       = textBox6.Text,
                    phoneNum2      = textBox3.Text,
                    Holder         = textBox4.Text,
                    ProofType      = comboBox2.Text,
                    note           = textBox8.Text,
                };
                @case.Proofs.Add(proof);

                context.SaveChanges();
            }

            this.Close();
            AppConfig.AppConfigAddAdvinceClear();
            AppContext.setInstanceNull();
        }
예제 #26
0
 public static Proof <Q> AndElimR <P, Q>(Proof <And <P, Q> > pAndQ)
 {
     return(new Proof <Q>());
 }
예제 #27
0
 public static Proof <And <P, Q> > AndIntro <P, Q>(Proof <P> p, Proof <Q> q)
 {
     return(new Proof <And <P, Q> >());
 }
예제 #28
0
 public SuchThat(A val, Proof <P> proof)
 {
     this.val = val;
 }
예제 #29
0
        private void bParse_Click(object sender, EventArgs e)
        {
            premises            = new List <WFF>();
            rtbPremisesOut.Text = "";
            foreach (string l in rtbPremisesIn.Text.Trim().Split('\n'))
            {
                if (l.Length < 1)
                {
                    continue;
                }

                WFF f = Parser.parseString(l.Trim());
                if (f != null)
                {
                    premises.Add(f);
                    rtbPremisesOut.AppendText(f + "\n");
                }
                else
                {
                    MessageBox.Show(string.Format("Error parsing premise {{{0}}}", l.Trim()));
                    rtbPremisesOut.Text = "";
                    return;
                }
            }

            conclusion = Parser.parseString(rtbConclusionIn.Text);
            if (conclusion == null)
            {
                MessageBox.Show(string.Format("Error parsing conclusion {{{0}}}", rtbConclusionIn.Text));
                rtbPremisesOut.Text = "";
                return;
            }
            rtbConclusionOut.Text = String.Format("{0}", conclusion);

            List <WFF> sentences = new List <WFF>(premises);

            sentences.Add(conclusion.GetNegation());

            worker = new Worker <Tree>(
                () =>
            {
                Tree t = new Tree(sentences);
                t.Satisfy();

                return(t);
            });
            worker.WorkFinished += workComplete;

            tree  = null;
            proof = null;

            setStatus("Initialized");

            setEnabled(bParse, true);
            setEnabled(bSatisfy, true);
            setEnabled(bStop, false);
            setEnabled(bShowTree, false);
            setEnabled(bShowProof, false);
            setEnabled(bSaveTree, false);
            setEnabled(bSaveProof, false);

            setTab(1);
        }
예제 #30
0
        /**
         * Utility method for outputting proofs in a formatted textual
         * representation.
         *
         * @param proof
         * @return a String representation of the Proof.
         */
        public static String printProof(Proof proof)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("Proof, Answer Bindings: ");
            var d = proof.getAnswerBindings();

            foreach (var kv in d)
            {
                sb.AppendFormat("{0}->{1}\n", kv.Key, kv.Value);
            }
            sb.Append("\n");

            List <ProofStep> steps = proof.getSteps();

            int maxStepWidth          = "Step".Length;
            int maxProofWidth         = "Proof".Length;
            int maxJustificationWidth = "Justification".Length;

            // Calculate the maximum width for each column in the proof
            foreach (ProofStep step in steps)
            {
                String sn = "" + step.getStepNumber();
                if (sn.Length > maxStepWidth)
                {
                    maxStepWidth = sn.Length;
                }
                if (step.getProof().Length > maxProofWidth)
                {
                    maxProofWidth = step.getProof().Length;
                }
                if (step.getJustification().Length > maxJustificationWidth)
                {
                    maxJustificationWidth = step.getJustification().Length;
                }
            }

            // Give a little extra padding
            maxStepWidth          += 1;
            maxProofWidth         += 1;
            maxJustificationWidth += 1;

            String f = "|{0," + maxStepWidth + "}| {1," + maxProofWidth + "}| {2," + maxJustificationWidth + "}|\n";

            int           barWidth = 5 + maxStepWidth + maxProofWidth + maxJustificationWidth;
            StringBuilder bar      = new StringBuilder();

            for (int i = 0; i < barWidth; i++)
            {
                bar.Append("-");
            }
            bar.Append("\n");

            sb.Append(bar);
            sb.Append(String.Format(f, "Step", "Proof", "Justification"));
            sb.Append(bar);
            foreach (ProofStep step in steps)
            {
                sb.AppendFormat(f, step.getStepNumber(), step
                                .getProof(), step.getJustification());
            }
            sb.Append(bar);
            return(sb.ToString());
        }
예제 #31
0
        private static void verifyConsistency(Proof proof, Root root)
        {
            var proofIndex = proof.At;
            var rootIndex  = root.Index;

            var firstHash  = root.Root_.ToByteArray();
            var secondHash = proof.Root.ToByteArray();

            if (rootIndex == proofIndex && firstHash.ContentEqual(secondHash) && proof.ConsistencyPath.Count == 0)
            {
                return;
            }

            if (rootIndex >= proofIndex || proof.ConsistencyPath.Count == 0)
            {
                throw new VerificationException("Consistency proof does not verify!");
            }

            var consistencyHashes = new List <byte[]>();

            if (isPowerOfTwo(rootIndex + 1))
            {
                consistencyHashes.Add(firstHash);
            }

            foreach (var historyEntry in proof.ConsistencyPath)
            {
                consistencyHashes.Add(historyEntry.ToByteArray());
            }

            var fn = rootIndex;
            var sn = proofIndex;

            while (fn % 2 == 1)
            {
                fn >>= 1;
                sn >>= 1;
            }

            var fr = consistencyHashes[0];
            var sr = consistencyHashes[0];

            for (int step = 1; step < consistencyHashes.Count; step++)
            {
                if (sn == 0)
                {
                    throw new VerificationException("Consistency proof does not verify!");
                }

                using (var srStream = new MemoryStream())
                {
                    srStream.WriteByte(node_prefix);

                    var stepHash = consistencyHashes[step];

                    if (fn % 2 == 1 || fn == sn)
                    {
                        using (var fnStream = new MemoryStream())
                        {
                            fnStream.WriteByte(node_prefix);
                            fnStream.Write(stepHash);
                            fnStream.Write(fr);

                            fr = fnStream.ToArray().SHAHash();

                            srStream.Write(stepHash);
                            srStream.Write(sr);

                            sr = srStream.ToArray().SHAHash();
                        }

                        while (fn % 2 == 0 && fn != 0)
                        {
                            fn >>= 1;
                            sn >>= 1;
                        }
                    }
                    else
                    {
                        srStream.Write(sr);
                        srStream.Write(stepHash);
                        sr = srStream.ToArray().SHAHash();
                    }
                }

                fn >>= 1;
                sn >>= 1;
            }

            if (!fr.ContentEqual(firstHash) || !sr.ContentEqual(secondHash) || sn != 0)
            {
                throw new VerificationException("Consistency proof does not verify!");
            }
        }