Example #1
0
        public void Cast_FromNumberTest()
        {
            ulong  ul   = 0x1122334455667788U;
            uint   ui   = 0x11223344U;
            ushort us   = 0x1122;
            byte   b    = 0x01;
            long   l    = 0x1122334455667788;
            int    i    = 0x11223344;
            int    negi = -1;
            long   negl = -1L;

            CompactInt c1 = ul;
            CompactInt c2 = ui;
            CompactInt c3 = us;
            CompactInt c4 = b;
            CompactInt c5 = (CompactInt)l;
            CompactInt c6 = (CompactInt)i;
            CompactInt c7 = (CompactInt)negi;
            CompactInt c8 = (CompactInt)negl;

            Helper.ComparePrivateField(c1, "value", ul);
            Helper.ComparePrivateField(c2, "value", (ulong)ui);
            Helper.ComparePrivateField(c3, "value", (ulong)us);
            Helper.ComparePrivateField(c4, "value", (ulong)b);
            Helper.ComparePrivateField(c5, "value", (ulong)l);
            Helper.ComparePrivateField(c6, "value", (ulong)i);
            Helper.ComparePrivateField(c7, "value", (ulong)negi);
            Helper.ComparePrivateField(c8, "value", (ulong)negl);
        }
Example #2
0
        public void Comparison_BigSmall_EqualIntTest()
        {
            CompactInt ci = new CompactInt(1);
            int        i  = 1;

            Assert.False(ci > i);
            Assert.True(ci >= i);
            Assert.False(ci > (long)i);
            Assert.True(ci >= (long)i);

            Assert.False(i > ci);
            Assert.True(i >= ci);
            Assert.False((long)i > ci);
            Assert.True((long)i >= ci);

            Assert.False(ci < i);
            Assert.True(ci <= i);
            Assert.False(ci < (long)i);
            Assert.True(ci <= (long)i);

            Assert.False(i < ci);
            Assert.True(i <= ci);
            Assert.False((long)i < ci);
            Assert.True((long)i <= ci);
        }
Example #3
0
        public void Cast_ToNumberTest()
        {
            CompactInt c1 = new CompactInt(10);
            CompactInt c2 = new CompactInt(ulong.MaxValue);

            ulong  ul1 = c1;
            ulong  ul2 = c2;
            uint   ui1 = (uint)c1;
            uint   ui2 = (uint)c2;
            ushort us1 = (ushort)c1;
            ushort us2 = (ushort)c2;
            byte   b1  = (byte)c1;
            byte   b2  = (byte)c2;
            long   l1  = (long)c1;
            long   l2  = (long)c2;
            int    i1  = (int)c1;
            int    i2  = (int)c2;

            Assert.Equal(10U, ul1);
            Assert.Equal(ulong.MaxValue, ul2);
            Assert.Equal((uint)10, ui1);
            Assert.Equal(unchecked ((uint)ulong.MaxValue), ui2);
            Assert.Equal((ushort)10, us1);
            Assert.Equal(unchecked ((ushort)ulong.MaxValue), us2);
            Assert.Equal((byte)10, b1);
            Assert.Equal(unchecked ((byte)ulong.MaxValue), b2);
            Assert.Equal(10L, l1);
            Assert.Equal(unchecked ((long)ulong.MaxValue), l2);
            Assert.Equal(10, i1);
            Assert.Equal(unchecked ((int)ulong.MaxValue), i2);
        }
Example #4
0
        public void GetHashCodeTest()
        {
            int expected = 1250UL.GetHashCode();
            int actual   = new CompactInt(1250).GetHashCode();

            Assert.Equal(expected, actual);
        }
Example #5
0
        public void ComparisonOperator_WithIntTest(CompactInt ci, int i, ValueCompareResult expected)
        {
            Assert.Equal(expected.Bigger, ci > i);
            Assert.Equal(expected.Bigger, ci > (long)i);
            Assert.Equal(expected.Bigger, i < ci);
            Assert.Equal(expected.Bigger, (long)i < ci);

            Assert.Equal(expected.BiggerEqual, ci >= i);
            Assert.Equal(expected.BiggerEqual, ci >= (long)i);
            Assert.Equal(expected.BiggerEqual, i <= ci);
            Assert.Equal(expected.BiggerEqual, (long)i <= ci);

            Assert.Equal(expected.Smaller, ci < i);
            Assert.Equal(expected.Smaller, ci < (long)i);
            Assert.Equal(expected.Smaller, i > ci);
            Assert.Equal(expected.Smaller, (long)i > ci);

            Assert.Equal(expected.SmallerEqual, ci <= i);
            Assert.Equal(expected.SmallerEqual, ci <= (long)i);
            Assert.Equal(expected.SmallerEqual, i >= ci);
            Assert.Equal(expected.SmallerEqual, (long)i >= ci);

            Assert.Equal(expected.Equal, ci == i);
            Assert.Equal(expected.Equal, i == ci);
            Assert.Equal(expected.Equal, ci == (long)i);
            Assert.Equal(expected.Equal, (long)i == ci);

            Assert.Equal(!expected.Equal, ci != i);
            Assert.Equal(!expected.Equal, i != ci);
            Assert.Equal(!expected.Equal, ci != (long)i);
            Assert.Equal(!expected.Equal, (long)i != ci);
        }
Example #6
0
        public Response <IOperation[]> Read(string hex)
        {
            Response <IOperation[]> resp = new Response <IOperation[]>();

            if (!Base16.IsValid(hex))
            {
                resp.Errors.Add("Invalid base-16 string.");
            }
            else
            {
                byte[]     data   = Base16.ToByteArray(hex);
                int        offset = 0;
                CompactInt len    = new CompactInt(data.Length);
                data = len.ToByteArray().ConcatFast(data);

                Script scr = new Helper();
                if (scr.TryDeserialize(data, ref offset, out string error))
                {
                    resp.Result = scr.OperationList;
                }
                else
                {
                    resp.Errors.Add(error);
                }
            }

            return(resp);
        }
Example #7
0
        /// <inheritdoc/>
        public bool TryDeserialize(FastStreamReader stream, out string error)
        {
            if (!CompactInt.TryRead(stream, out CompactInt count, out error))
            {
                return(false);
            }

            // A quick check to avoid data loss during cast below
            if (count > int.MaxValue)
            {
                error = "Item count is too big.";
                return(false);
            }
            Items = new PushDataOp[(int)count];
            for (int i = 0; i < Items.Length; i++)
            {
                PushDataOp temp = new PushDataOp();
                if (!temp.TryReadWitness(stream, out error))
                {
                    return(false);
                }
                Items[i] = temp;
            }

            error = null;
            return(true);
        }
Example #8
0
        public void Constructor_FromIntTest()
        {
            CompactInt zeroI = new CompactInt(0);
            CompactInt zeroL = new CompactInt(0L);

            Helper.ComparePrivateField(zeroI, "value", 0UL);
            Helper.ComparePrivateField(zeroL, "value", 0UL);

            CompactInt cI = new CompactInt(123);
            CompactInt cL = new CompactInt((long)123);

            Helper.ComparePrivateField(cI, "value", 123UL);
            Helper.ComparePrivateField(cL, "value", 123UL);

            CompactInt maxI = new CompactInt(int.MaxValue);
            CompactInt maxL = new CompactInt(long.MaxValue);

            Helper.ComparePrivateField(maxI, "value", (ulong)int.MaxValue);
            Helper.ComparePrivateField(maxL, "value", (ulong)long.MaxValue);

            int  negI = -1;
            long negL = -1;

            Assert.Throws <ArgumentOutOfRangeException>(() => new CompactInt(negI));
            Assert.Throws <ArgumentOutOfRangeException>(() => new CompactInt(negL));
        }
Example #9
0
        private void SetFields()
        {
            CompactInt temp   = new CompactInt(10000 /*coin.ScriptSigMaxLength*/);
            int        opSize = new Outpoint().Size;

            MinSize = opSize + 1 + 0 + sizeof(uint);
            MaxSize = opSize + temp.ToByteArray().Length + 10000 + sizeof(uint);
        }
Example #10
0
        public void TryRead_Fail_NullStreamTest()
        {
            bool b = CompactInt.TryRead(null, out CompactInt actual, out string error);

            Assert.False(b);
            Assert.Equal("Stream can not be null.", error);
            Helper.ComparePrivateField(actual, "value", 0UL);
        }
Example #11
0
        /// <summary>
        /// Converts this instance into its byte array representation.
        /// </summary>
        /// <exception cref="ArgumentNullException"/>
        /// <returns>An array of bytes.</returns>
        public virtual byte[] Serialize()
        {
            byte[] result = ToByteArray();

            CompactInt lengthOrCount = new CompactInt(IsWitness ? OperationList.Length : result.Length);

            return(lengthOrCount.ToByteArray().ConcatFast(result));
        }
Example #12
0
        public void CompareToTest()
        {
            CompactInt ci   = new CompactInt(1);
            object     nObj = null;
            object     sObj = "CompactInt!";

            Assert.Equal(1, ci.CompareTo(nObj));
            Assert.Throws <ArgumentException>(() => ci.CompareTo(sObj));
        }
Example #13
0
        public void Equals_ObjectTest()
        {
            CompactInt ci   = new CompactInt(100);
            object     sObj = "CompactInt!";
            object     nl   = null;

            Assert.False(ci.Equals(sObj));
            Assert.False(ci.Equals(nl));
        }
Example #14
0
        public void TryReadTest(byte[] data, int finalPos, ulong expected)
        {
            FastStreamReader stream = new FastStreamReader(data);
            bool             b      = CompactInt.TryRead(stream, out CompactInt actual, out string error);

            Assert.True(b);
            Assert.Null(error);
            Helper.ComparePrivateField(stream, "position", finalPos);
            Helper.ComparePrivateField(actual, "value", expected);
        }
Example #15
0
        public void TryRead_FailTest(byte[] data, int finalPos, string expError)
        {
            FastStreamReader stream = new FastStreamReader(data);
            bool             b      = CompactInt.TryRead(stream, out CompactInt actual, out string error);

            Assert.False(b);
            Assert.Equal(expError, error);
            Helper.ComparePrivateField(stream, "position", finalPos);
            Helper.ComparePrivateField(actual, "value", 0UL);
        }
        public Transaction(uint ver, ulong txInCount, TxIn[] txIns, ulong txOutCount, TxOut[] txOuts, uint lockTime)
        {
            Version    = ver;
            TxInCount  = new CompactInt(txInCount);
            TxInList   = txIns;
            TxOutCount = new CompactInt(txOutCount);
            TxOutList  = txOuts;
            LockTime   = lockTime;

            Flag = 0;
        }
        public Transaction(uint ver, ulong txInCount, TxIn[] txIns, ulong txOutCount, TxOut[] txOuts, uint lockTime, Witness[] witnesses)
        {
            Version    = ver;
            TxInCount  = new CompactInt(txInCount);
            TxInList   = txIns;
            TxOutCount = new CompactInt(txOutCount);
            TxOutList  = txOuts;
            LockTime   = lockTime;

            Flag        = 1;
            WitnessList = witnesses;
        }
Example #18
0
        public void WriteToStreamTest(byte[] data, int finalOffset, ulong val)
        {
            CompactInt ci     = new CompactInt(val);
            FastStream stream = new FastStream(10);

            ci.WriteToStream(stream);

            byte[] actual   = stream.ToByteArray();
            byte[] expected = new byte[finalOffset];
            Buffer.BlockCopy(data, 0, expected, 0, finalOffset);

            Assert.Equal(expected, actual);
        }
Example #19
0
        public void Comparison_WithInt_EqualTest(int c, int i, bool expected)
        {
            CompactInt ci = new CompactInt(c);

            Assert.Equal(expected, ci == i);
            Assert.Equal(expected, ci == (long)i);
            Assert.Equal(!expected, ci != i);
            Assert.Equal(!expected, ci != (long)i);

            Assert.Equal(expected, i == ci);
            Assert.Equal(expected, (long)i == ci);
            Assert.Equal(!expected, i != ci);
            Assert.Equal(!expected, (long)i != ci);
        }
Example #20
0
        public void AddSerializedSizeTest(ulong val, int init, int expected)
        {
            var ci      = new CompactInt(val);
            var counter = new SizeCounter(init);

            ci.AddSerializedSize(counter);

            var stream = new FastStream(10);

            ci.WriteToStream(stream);
            Assert.Equal(expected, stream.GetSize() + init);

            Assert.Equal(expected, counter.Size);
        }
Example #21
0
        public void AddCompactIntCountTest(int init, int add)
        {
            var counter = new SizeCounter(init);

            counter.AddCompactIntCount(add);

            var ci     = new CompactInt(add);
            var stream = new FastStream(9);

            ci.WriteToStream(stream);
            int expected = stream.GetSize() + init;

            Assert.Equal(expected, counter.Size);
        }
Example #22
0
        /// <inheritdoc/>
        public override void Serialize(FastStream stream)
        {
            CompactInt count = new CompactInt(Headers.Length);

            count.WriteToStream(stream);
            foreach (var hd in Headers)
            {
                hd.SerializeHeader(stream);
                // Block serialization of header doesn't add tx count since there is no need for it.
                // However, in a header payload (for unknown reason) one extra byte indicating zero tx count
                // is added to each block header.
                stream.Write((byte)0);
            }
        }
Example #23
0
        /// <summary>
        /// Check whether an output amount is considered dust for a given transaction relay fee.
        /// Transactions with dust outputs are rejected by mempool.
        /// </summary>
        /// <param name="amount">Output amount</param>
        /// <param name="scriptSize">Size of the output script in bytes</param>
        /// <param name="relayFeePerKb">Mempool relay fee/kB</param>
        /// <returns>Whether the output is dust</returns>
        public static bool IsDustAmount(Amount amount, int scriptSize, Amount relayFeePerKb)
        {
            // Calculate the total (estimated) cost to the network.  This is
            // calculated using the serialize size of the output plus the serial
            // size of a transaction input which redeems it.  The output is assumed
            // to be compressed P2PKH as this is the most common script type.  Use
            // the average size of a compressed P2PKH redeem input (165) rather than
            // the largest possible (Transaction.RedeemPayToPubKeyHashInputSize).
            var totalSize = 8 + 2 + CompactInt.SerializeSize((ulong)scriptSize) + scriptSize + 165;

            // Dust is defined as an output value where the total cost to the network
            // (output size + input size) is greater than 1/3 of the relay fee.
            return(amount * 1000 / (3 * totalSize) < relayFeePerKb);
        }
Example #24
0
        public void Comparison_EqualTest()
        {
            CompactInt first  = new CompactInt(1);
            CompactInt second = new CompactInt(1);

            Assert.False(first > second);
            Assert.True(first >= second);
            Assert.False(second < first);
            Assert.True(second <= first);
            Assert.True(first == second);
            Assert.False(first != second);
            Assert.Equal(0, first.CompareTo(second));
            Assert.Equal(0, first.CompareTo((object)second));
            Assert.True(first.Equals(second));
            Assert.True(first.Equals((object)second));
        }
Example #25
0
 /// <inheritdoc/>
 public void Serialize(FastStream stream)
 {
     if (Items == null || Items.Length == 0)
     {
         stream.Write((byte)0);
     }
     else
     {
         CompactInt count = new CompactInt(Items.Length);
         count.WriteToStream(stream);
         foreach (var item in Items)
         {
             item.WriteToWitnessStream(stream);
         }
     }
 }
Example #26
0
        public void ComparisonOperator_SameTypeTest(CompactInt ci1, CompactInt ci2, ValueCompareResult expected)
        {
            Assert.Equal(expected.Bigger, ci1 > ci2);
            Assert.Equal(expected.BiggerEqual, ci1 >= ci2);
            Assert.Equal(expected.Smaller, ci1 < ci2);
            Assert.Equal(expected.SmallerEqual, ci1 <= ci2);

            Assert.Equal(expected.Equal, ci1 == ci2);
            Assert.Equal(!expected.Equal, ci1 != ci2);

            Assert.Equal(expected.Equal, ci1.Equals(ci2));
            Assert.Equal(expected.Equal, ci1.Equals((object)ci2));

            Assert.Equal(expected.Compare, ci1.CompareTo(ci2));
            Assert.Equal(expected.Compare, ci1.CompareTo((object)ci2));
        }
Example #27
0
        public void ComparisonTest()
        {
            CompactInt big   = new CompactInt(1);
            CompactInt small = new CompactInt(0);

            Assert.True(big > small);
            Assert.True(big >= small);
            Assert.True(small < big);
            Assert.True(small <= big);
            Assert.False(big == small);
            Assert.True(big != small);
            Assert.Equal(1, big.CompareTo(small));
            Assert.Equal(1, big.CompareTo((object)small));
            Assert.Equal(-1, small.CompareTo(big));
            Assert.Equal(-1, small.CompareTo((object)big));
            Assert.False(big.Equals(small));
            Assert.False(big.Equals((object)small));
        }
Example #28
0
        public void Constructor_FromUIntTest()
        {
            CompactInt zeroUI = new CompactInt(0U);
            CompactInt zeroUL = new CompactInt(0UL);

            Helper.ComparePrivateField(zeroUI, "value", 0UL);
            Helper.ComparePrivateField(zeroUL, "value", 0UL);

            CompactInt cUI = new CompactInt(123U);
            CompactInt cUL = new CompactInt(123UL);

            Helper.ComparePrivateField(cUI, "value", 123UL);
            Helper.ComparePrivateField(cUL, "value", 123UL);

            CompactInt maxUI = new CompactInt(uint.MaxValue);
            CompactInt maxUL = new CompactInt(ulong.MaxValue);

            Helper.ComparePrivateField(maxUI, "value", (ulong)uint.MaxValue);
            Helper.ComparePrivateField(maxUL, "value", ulong.MaxValue);
        }
Example #29
0
        /// <summary>
        /// Estimates the signed serialize size of an unsigned transaction, assuming all
        /// inputs spend P2PKH outputs.  The estimate is a worst case, so the actual
        /// serialize size after signing should always be less than or equal to this value.
        /// </summary>
        /// <param name="inputCount">Number of P2PKH outputs the transaction will redeem</param>
        /// <param name="outputs">Transaction output array</param>
        /// <param name="addChangeOutput">Add the serialize size for an additional P2PKH change output</param>
        /// <returns>Estimated signed serialize size of the transaction</returns>
        public static int EstimateSerializeSize(int inputCount, Output[] outputs, bool addChangeOutput)
        {
            if (outputs == null)
            {
                throw new ArgumentNullException(nameof(outputs));
            }

            var changeSize  = 0;
            var outputCount = outputs.Length;

            if (addChangeOutput)
            {
                changeSize = PayToPubKeyHashOutputSize;
                outputCount++;
            }

            return
                (12 + (2 * CompactInt.SerializeSize((ulong)inputCount)) + CompactInt.SerializeSize((ulong)outputCount) +
                 inputCount * RedeemPayToPubKeyHashInputSize +
                 outputs.Sum(o => o.SerializeSize) +
                 changeSize);
        }
Example #30
0
        /// <inheritdoc/>
        public override bool TryDeserialize(FastStreamReader stream, out string error)
        {
            if (stream is null)
            {
                error = "Stream can not be null.";
                return(false);
            }

            if (!CompactInt.TryRead(stream, out CompactInt count, out error))
            {
                return(false);
            }

            Headers = new Block[count];
            for (int i = 0; i < (int)count; i++)
            {
                Block temp = new Block();
                if (!temp.TryDeserializeHeader(stream, out error))
                {
                    return(false);
                }
                Headers[i] = temp;

                if (!stream.TryReadByte(out byte zero))
                {
                    error = Err.EndOfStream;
                    return(false);
                }
                if (zero != 0)
                {
                    error = "Transaction count in a headers message must be zero.";
                    return(false);
                }
            }

            error = null;
            return(true);
        }