Esempio n. 1
0
        public override string ToString()
        {
            var branch      = Branch == Branch.Left ? "left" : "right";
            var encodedHash = HexEncoder.Encode(Hash);

            return($"{branch}:{encodedHash}");
        }
Esempio n. 2
0
        public void Proof()
        {
            var mt = new MerkleTree();

            foreach (var i in Enumerable.Range(0, 10))
            {
                mt.AddLeaf(sha256($"test{i}"));
            }
            Assert.Equal(5, mt.Levels);

            foreach (var i in Enumerable.Range(0, 10))
            {
                var proof   = mt.GetProof(i);
                var receipt = proof.ToReceipt();
                receipt.AddAnchor("BTCOpReturn", "ae125");
                var jo = (JObject)JsonConvert.DeserializeObject(receipt.ToJson());
                Assert.Equal(receipt.Context, jo["@context"]);
                Assert.Equal(HexEncoder.Encode(receipt.TargetHash), (string)(jo["targetHash"]));
                Assert.Equal(HexEncoder.Encode(receipt.MerkleRoot), (string)(jo["merkleRoot"]));
                Assert.Equal(receipt.Type, jo["type"]);
                Assert.Equal("ChainpointSHA256v2", receipt.Type);
                var rproof = (JArray)jo["proof"];
                var j      = 0;
                foreach (var p in proof)
                {
                    var branch = (p.Branch == Branch.Left) ? "left" : "right";
                    var rp     = rproof[j++];
                    Assert.Equal(HexEncoder.Encode(p.Hash), (string)(rp[branch]));
                }
                Assert.True((bool)mt.ValidateProof(proof, sha256($"test{i}")));
            }
        }
Esempio n. 3
0
        public object ToJson()
        {
            var branch      = Branch == Branch.Left ? "left" : "right";
            var encodedHash = HexEncoder.Encode(Hash);

            return($"{{ \"{branch}\":\"{encodedHash}\"}}");
        }
Esempio n. 4
0
            public void WhenDelimiterSet_ThenReturnEncodedWithDelimiter(char delimiter, string expected)
            {
                var sut = new HexEncoder(delimiter);

                var result = sut.Encode("John");

                Assert.That(result, Is.EqualTo(expected));
            }
Esempio n. 5
0
        /// <inheritdoc />
        public string GetFilePath(IMediaFileSystem fileSystem, Guid itemGuid, Guid propertyGuid, string filename, string previous = null)
        {
            // assumes that cuid and puid keys can be trusted - and that a single property type
            // for a single content cannot store two different files with the same name
            var directory = HexEncoder.Encode(GuidUtils.Combine(itemGuid, propertyGuid).ToByteArray() /*'/', 2, 4*/); // could use ext to fragment path eg 12/e4/f2/...

            return(Path.Combine(directory, filename).Replace('\\', '/'));
        }
Esempio n. 6
0
        public static string ToHex(this byte[] bytes, bool upperCase = false)
        {
            if (bytes == null)
            {
                return(string.Empty);
            }

            return(upperCase ? HEX_UPPERCASE.Encode(bytes) : HEX.Encode(bytes));
        }
Esempio n. 7
0
        public void ToHexStringWithSeparatorCreatesCorrectValue()
        {
            var buffer = new byte[255];
            var random = new Random();

            random.NextBytes(buffer);

            var expected = ToHexString(buffer, '/', 2, 4);
            var actual   = HexEncoder.Encode(buffer, '/', 2, 4);

            Assert.AreEqual(expected, actual);
        }
Esempio n. 8
0
        public void HexEncoderOutputIsCorrect()
        {
            byte[] hash = Hash();
            var    sb   = new StringBuilder(hash.Length * 2);

            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("x2"));
            }

            string expected = sb.ToString();
            string actual   = HexEncoder.Encode(hash);

            Assert.Equal(expected, actual);
        }
Esempio n. 9
0
        public void ToHexStringCreatesCorrectValue()
        {
            var buffer = new byte[255];
            var random = new Random();

            random.NextBytes(buffer);

            var sb = new StringBuilder(buffer.Length * 2);

            for (var i = 0; i < buffer.Length; i++)
            {
                sb.Append(buffer[i].ToString("X2"));
            }

            var expected = sb.ToString();

            var actual = HexEncoder.Encode(buffer);

            Assert.AreEqual(expected, actual);
        }
Esempio n. 10
0
        static bool GetNextValue(string charset, Encoder encoder, HexEncoder hex, char[] chars, ref int index,
                                 ref byte[] bytes, ref byte[] encoded, int maxLength, out string value)
        {
            int length = chars.Length - index;

            if (length < maxLength)
            {
                switch (GetEncodeMethod(chars, index, length))
                {
                case EncodeMethod.Quote:
                    value  = MimeUtils.Quote(new string (chars, index, length));
                    index += length;
                    return(false);

                case EncodeMethod.None:
                    value  = new string (chars, index, length);
                    index += length;
                    return(false);
                }
            }

            length = Math.Min(maxLength, length);
            int ratio, count, n;

            do
            {
                count = encoder.GetByteCount(chars, index, length, true);
                if (count > maxLength && length > 1)
                {
                    ratio   = (int)Math.Round((double)count / (double)length);
                    length -= Math.Max((count - maxLength) / ratio, 1);
                    continue;
                }

                if (bytes.Length < count)
                {
                    Array.Resize <byte> (ref bytes, count);
                }

                count = encoder.GetBytes(chars, index, length, bytes, 0, true);

                // Note: the first chunk needs to be encoded in order to declare the charset
                if (index > 0 || charset == "us-ascii")
                {
                    var method = GetEncodeMethod(bytes, count);

                    if (method == EncodeMethod.Quote)
                    {
                        value  = MimeUtils.Quote(Encoding.ASCII.GetString(bytes, 0, count));
                        index += length;
                        return(false);
                    }

                    if (method == EncodeMethod.None)
                    {
                        value  = Encoding.ASCII.GetString(bytes, 0, count);
                        index += length;
                        return(false);
                    }
                }

                n = hex.EstimateOutputLength(count);
                if (encoded.Length < n)
                {
                    Array.Resize <byte> (ref encoded, n);
                }

                // only the first value gets a charset declaration
                int charsetLength = index == 0 ? charset.Length + 2 : 0;

                n = hex.Encode(bytes, 0, count, encoded);
                if (n > 3 && (charsetLength + n) > maxLength)
                {
                    int x = 0;

                    for (int i = n - 1; i >= 0 && charsetLength + i >= maxLength; i--)
                    {
                        if (encoded[i] == (byte)'%')
                        {
                            x--;
                        }
                        else
                        {
                            x++;
                        }
                    }

                    ratio   = (int)Math.Round((double)count / (double)length);
                    length -= Math.Max(x / ratio, 1);
                    continue;
                }

                if (index == 0)
                {
                    value = charset + "''" + Encoding.ASCII.GetString(encoded, 0, n);
                }
                else
                {
                    value = Encoding.ASCII.GetString(encoded, 0, n);
                }
                index += length;
                return(true);
            } while (true);
        }
Esempio n. 11
0
        /// <summary>
        /// Checks if two NamesTable are equals, if not, prints the values that do not appear in both of them
        /// </summary>
        /// <param name="tableNumberTwo">a table of entries</param>
        /// <returns>true of false if table is identical</returns>
        public bool CompareTablesAndPrintResults(NamesTable tableNumberTwo)
        {
            // Check if tree root identical
            if (HexEncoder.Encode(tableHashTree.MerkleRootHash) ==
                HexEncoder.Encode(tableNumberTwo.tableHashTree.MerkleRootHash))
            {
                Console.WriteLine("Tables are identical");
                return(true);
            }

            // If you're here, the tables aren't identical

            int       currIndex  = tableOfEntries.Count / 2;
            int       lowerLimit = 0;
            int       upperLimit = tableOfEntries.Count - 1;
            string    direction;
            Proof     currProof, myProof;
            ArrayList currProofStr, myProofStr;

            while (true)
            {
                try
                {
                    // If GetProof throws exception, value is not in table
                    currProof = tableNumberTwo.tableHashTree.GetProof(ToBytes(tableOfEntries[currIndex].ToString()));
                }
                catch
                {
                    Console.WriteLine("The entry \"" +
                                      tableOfEntries[currIndex].ToString() +
                                      "\" is not in the other table");
                    return(false);
                }

                // this is a failsafe, should never be true
                if (currIndex == 0)
                {
                    break;
                }

                //Console.WriteLine("Checking index number " + currIndex);

                // Getting proof for my table
                myProof = tableHashTree.GetProof(ToBytes(tableOfEntries[currIndex].ToString()));

                // Parsing proofs from both tables
                currProofStr = ParseProof(currProof);
                myProofStr   = ParseProof(myProof);

                // finding different hashes in the Proof and setting the direction to continue
                for (int i = 0; i < currProofStr.Count; i++)
                {
                    i++;

                    if (!(currProofStr[i].Equals(myProofStr[i])))
                    {
                        direction = myProofStr[i - 1].ToString().Replace(" ", string.Empty);

                        if (direction.Equals("right"))  // Going right
                        {
                            lowerLimit = currIndex;

                            currIndex = ((lowerLimit + upperLimit) / 2);
                            if (((lowerLimit + upperLimit) % 2) == 1)
                            {
                                currIndex++;
                            }
                        }
                        else    // Going left
                        {
                            upperLimit = currIndex;
                            currIndex  = (lowerLimit + upperLimit) / 2;
                        }

                        break;
                    }
                }
            }

            return(false);
        }
Esempio n. 12
0
        public void TestEncodeLower()
        {
            IEncoder encoder = new HexEncoder(false);

            Assert.AreEqual(testhexStringLowercase, encoder.Encode(testTytes));
        }
Esempio n. 13
0
        public void TestEncodeUpper()
        {
            IEncoder encoder = new HexEncoder(true);

            Assert.AreEqual(testhexStringUppercase, encoder.Encode(testTytes));
        }
 public void ShouldEncodeToUppercase()
 {
     var encoder = new HexEncoder();
     var encoded = encoder.Encode(new byte[] {0x66, 0xff, 0x00, 0x44});
     Assert.AreEqual("66FF0044", encoded);
 }
Esempio n. 15
0
        public void Example()
        {
            var tree = new MerkleTree();

            tree.AddLeave(new[] {
                HexEncoder.Decode("e1566f09e0deea437826514431be6e4bdb4fe10aa54d75aecf0b4cdc1bc4320c"),
                HexEncoder.Decode("2f7f9092b2d6c5c17cfe2bcf33fc38a41f2e4d4485b198c2b1074bba067e7168"),
                HexEncoder.Decode("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"),
                HexEncoder.Decode("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
            });

            var root = HexEncoder.Encode(tree.MerkleRootHash);

            Console.WriteLine(root);

            // 740c08b74d31bb77fd9806e4f6159d88dfd012acf8984bd41b4b4c9cbd7aa358

            var proof = tree.GetProof(1);

            Console.WriteLine(proof.ToJson());

            /*
             * [{
             *      "left": "e1566f09e0deea437826514431be6e4bdb4fe10aa54d75aecf0b4cdc1bc4320c"
             * },{
             *      "right":"2dba5dbc339e7316aea2683faf839c1b7b1ee2313db792112588118df066aa35"
             * }]"
             */

            var hash    = HexEncoder.Decode("2f7f9092b2d6c5c17cfe2bcf33fc38a41f2e4d4485b198c2b1074bba067e7168");
            var isValid = tree.ValidateProof(proof, hash);

            Console.WriteLine(isValid);             // true

            var receipt = proof.ToReceipt();

            receipt.AddBitcoinAnchor("780b4cdc16f09e0deebce156a434320c2654fe10aa54d75ae14431be6e4bdbcf");
            Console.WriteLine(receipt.ToJson());

            /*
             * {
             * "@context":"https://w3id.org/chainpoint/v2",
             * "type":"ChainpointSHA256v2",
             * "targetHash":"2f7f9092b2d6c5c17cfe2bcf33fc38a41f2e4d4485b198c2b1074bba067e7168",
             * "merkleRoot":"740c08b74d31bb77fd9806e4f6159d88dfd012acf8984bd41b4b4c9cbd7aa358",
             * "proof":[
             *        {
             *               "left":"e1566f09e0deea437826514431be6e4bdb4fe10aa54d75aecf0b4cdc1bc4320c"
             *        },
             *        {
             *               "right":"2dba5dbc339e7316aea2683faf839c1b7b1ee2313db792112588118df066aa35"
             *        }
             * ],
             * "anchors":[
             *        {
             *               "type":"BTCOpReturn",
             *               "sourceId":"780b4cdc16f09e0deebce156a434320c2654fe10aa54d75ae14431be6e4bdbcf"
             *        }
             * ]
             * }
             */
        }
Esempio n. 16
0
 public string ToHexStringEncoder() => HexEncoder.Encode(_buffer);
Esempio n. 17
0
 public int EncodeToBuffer() => HexEncoder.Encode(bytes, charBuffer);
Esempio n. 18
0
 public string Encode() => HexEncoder.Encode(bytes);
Esempio n. 19
0
        public void TwoItems()
        {
            var mt = new MerkleTree();

            mt.AddLeaf(sha256("test1"));
            mt.AddLeaf(sha256("test2"));
            Assert.Equal <string>("587b1fe3afa386ce7cf9e99cf6f3b7f6a78a3c1ca6a549bbd467c992e482dc56", HexEncoder.Encode(mt.MerkleRootHash));
        }