Exemplo n.º 1
0
        public void CastTest2()
        {
            LockTime lt1 = new LockTime(10);
            LockTime lt2 = new LockTime(uint.MaxValue);

            uint ui1 = lt1;
            uint ui2 = lt2;

            Assert.Equal(10U, ui1);
            Assert.Equal(uint.MaxValue, ui2);

            ushort us1 = (ushort)lt1;
            ushort us2 = (ushort)lt2;

            Assert.Equal((ushort)10, us1);
            Assert.Equal(unchecked ((ushort)uint.MaxValue), us2);

            byte b1 = (byte)lt1;
            byte b2 = (byte)lt2;

            Assert.Equal((byte)10, b1);
            Assert.Equal(unchecked ((byte)uint.MaxValue), b2);

            int i1 = (int)lt1;
            int i2 = (int)lt2;

            Assert.Equal(10, i1);
            Assert.Equal(unchecked ((int)uint.MaxValue), i2);

            LockTime lt3 = new LockTime(1551017858U);
            DateTime dt  = (DateTime)lt3;

            Assert.Equal(new DateTime(2019, 2, 24, 14, 17, 38), dt);
        }
Exemplo n.º 2
0
        public void IsSameTypeTest(uint ltVal, long value, bool expected)
        {
            LockTime lt     = new LockTime(ltVal);
            bool     actual = lt.IsSameType(value);

            Assert.Equal(expected, actual);
        }
Exemplo n.º 3
0
        public void GetHashCodeTest()
        {
            int expected = 1250U.GetHashCode();
            int actual   = new LockTime(1250).GetHashCode();

            Assert.Equal(expected, actual);
        }
Exemplo n.º 4
0
            private void SerializeTxn(BitcoinStream stream)
            {
                var version = this.Version;

                stream.ReadWrite(ref version);

                // POS Timestamp
                var time = this.Time;

                stream.ReadWrite(ref time);

                TxInList vin = this.Inputs;

                stream.ReadWrite(ref vin);
                vin.Transaction = this;

                TxOutList vout = this.Outputs;

                stream.ReadWrite(ref vout);
                vout.Transaction = this;

                LockTime lockTime = this.LockTime;

                stream.ReadWriteStruct(ref lockTime);
            }
Exemplo n.º 5
0
        public void IncrementTest(LockTime lt, LockTime expected, LockTime unChanged)
        {
            LockTime actual = lt.Increment();

            Assert.Equal(expected, actual);
            Assert.Equal(unChanged, lt);
        }
Exemplo n.º 6
0
        public void ComparisonOperator_WithIntTest(LockTime lt, int i, ValueCompareResult expected)
        {
            Assert.Equal(expected.Bigger, lt > i);
            Assert.Equal(expected.Bigger, lt > (long)i);
            Assert.Equal(expected.Bigger, i < lt);
            Assert.Equal(expected.Bigger, (long)i < lt);

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

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

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

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

            Assert.Equal(!expected.Equal, lt != i);
            Assert.Equal(!expected.Equal, i != lt);
            Assert.Equal(!expected.Equal, lt != (long)i);
            Assert.Equal(!expected.Equal, (long)i != lt);
        }
Exemplo n.º 7
0
        /// <summary>
        /// </summary>
        /// <param name="target"></param>
        /// <param name="script"></param>
        /// <returns></returns>
        public VerifyResult VerifyLockTime(LockTime target, string script)
        {
            Guard.Argument(target, nameof(target)).NotDefault();
            Guard.Argument(script, nameof(script)).NotNull().NotEmpty().NotWhiteSpace();
            var sc1 = new Script(Op.GetPushOp(target.Value), OpcodeType.OP_CHECKLOCKTIMEVERIFY);
            var sc2 = new Script(script);

            if (!sc1.ToString().Equals(sc2.ToString()))
            {
                return(VerifyResult.UnableToVerify);
            }
            var tx = NBitcoin.Network.Main.CreateTransaction();

            tx.Outputs.Add(new TxOut {
                ScriptPubKey = new Script(script)
            });
            var spending = NBitcoin.Network.Main.CreateTransaction();

            spending.LockTime = new LockTime(DateTimeOffset.Now);
            spending.Inputs.Add(new TxIn(tx.Outputs.AsCoins().First().Outpoint, new Script()));
            spending.Inputs[0].Sequence = 1;
            return(spending.Inputs.AsIndexedInputs().First().VerifyScript(tx.Outputs[0])
                ? VerifyResult.Succeed
                : VerifyResult.UnableToVerify);
        }
Exemplo n.º 8
0
        public void CastTest()
        {
            byte     b       = 10;
            ushort   us      = 10;
            uint     ui      = 10;
            int      i       = 10;
            int      negi    = -10;
            DateTime dt      = new DateTime(2019, 2, 24, 14, 17, 38);
            DateTime smallDt = new DateTime(1985, 11, 5, 0, 53, 19); //499999999

            LockTime lt1 = b;
            LockTime lt2 = us;
            LockTime lt3 = ui;
            LockTime lt4 = (LockTime)i;
            LockTime lt5 = (LockTime)dt;
            LockTime lt6 = (LockTime)negi;
            LockTime lt7 = (LockTime)smallDt;

            Helper.ComparePrivateField(lt1, "value", 10U);
            Helper.ComparePrivateField(lt2, "value", 10U);
            Helper.ComparePrivateField(lt3, "value", 10U);
            Helper.ComparePrivateField(lt4, "value", 10U);
            Helper.ComparePrivateField(lt5, "value", 1551017858U);
            Helper.ComparePrivateField(lt5, "value", 1551017858U);
            Helper.ComparePrivateField(lt5, "value", 1551017858U);
            Helper.ComparePrivateField(lt6, "value", (uint)negi);
            Helper.ComparePrivateField(lt7, "value", uint.MaxValue);
        }
Exemplo n.º 9
0
            private void DeserializeTxn(BitcoinStream stream)
            {
                UInt32 nVersionTemp = 0;

                stream.ReadWrite(ref nVersionTemp);

                // POS time stamp
                UInt32 nTimeTemp = 0;

                stream.ReadWrite(ref nTimeTemp);

                TxInList  vinTemp  = null;
                TxOutList voutTemp = null;

                // Try to read the vin.
                stream.ReadWrite(ref vinTemp);
                vinTemp.Transaction = this;
                // Assume a normal vout follows.
                stream.ReadWrite(ref voutTemp);
                voutTemp.Transaction = this;

                LockTime lockTimeTemp = LockTime.Zero;

                stream.ReadWriteStruct(ref lockTimeTemp);

                this.Version = nVersionTemp;
                this.Time    = nTimeTemp;              // POS Timestamp
                vinTemp.ForEach(i => this.Inputs.Add(i));
                voutTemp.ForEach(i => this.Outputs.Add(i));
                this.LockTime = lockTimeTemp;
            }
Exemplo n.º 10
0
        public SignaturesRequest CreateSignatureRequest(Script cashoutDestination, FeeRate feeRate)
        {
            if (cashoutDestination == null)
            {
                throw new ArgumentNullException(nameof(cashoutDestination));
            }
            if (feeRate == null)
            {
                throw new ArgumentNullException(nameof(feeRate));
            }
            AssertState(PromiseClientStates.WaitingSignatureRequest);

            Transaction cashout = new Transaction();

            cashout.AddInput(new TxIn(InternalState.EscrowedCoin.Outpoint, Script.Empty));
            cashout.AddOutput(new TxOut(Money.Zero, cashoutDestination));
            var fee = feeRate.GetFee(cashout.GetVirtualSize());

            cashout.Outputs[0].Value = InternalState.EscrowedCoin.Amount - fee;


            List <HashBase> hashes   = new List <HashBase>();
            LockTime        lockTime = new LockTime(0);

            for (int i = 0; i < Parameters.RealTransactionCount; i++)
            {
                RealHash h = new RealHash(cashout, InternalState.EscrowedCoin);
                h.LockTime = lockTime;
                lockTime++;
                hashes.Add(h);
            }

            for (int i = 0; i < Parameters.FakeTransactionCount; i++)
            {
                FakeHash h = new FakeHash(Parameters);
                h.Salt = new uint256(RandomUtils.GetBytes(32));
                hashes.Add(h);
            }

            _Hashes = hashes.ToArray();
            NBitcoin.Utils.Shuffle(_Hashes, RandomUtils.GetInt32());
            for (int i = 0; i < _Hashes.Length; i++)
            {
                _Hashes[i].Index = i;
            }
            var     fakeIndices = _Hashes.OfType <FakeHash>().Select(h => h.Index).ToArray();
            uint256 indexSalt   = null;
            var     request     = new SignaturesRequest
            {
                Hashes          = _Hashes.Select(h => h.GetHash()).ToArray(),
                FakeIndexesHash = PromiseUtils.HashIndexes(ref indexSalt, fakeIndices),
            };

            InternalState.IndexSalt   = indexSalt;
            InternalState.Cashout     = cashout.Clone();
            InternalState.Status      = PromiseClientStates.WaitingCommitments;
            InternalState.FakeIndexes = fakeIndices;
            return(request);
        }
Exemplo n.º 11
0
        public void Equals_EdgeTest()
        {
            LockTime lt   = new LockTime(100);
            object   sObj = "LockTime!";

            Assert.False(lt.Equals(sObj));
            Assert.False(lt.Equals(null));
        }
Exemplo n.º 12
0
 public WalletCreateFundedPSBTResponse WalletCreateFundedPSBT(
     TxIn[] inputs,
     Tuple <Dictionary <BitcoinAddress, Money>, Dictionary <string, string> > outputs,
     LockTime locktime,
     FundRawTransactionOptions options = null,
     bool bip32derivs = false
     )
 => WalletCreateFundedPSBTAsync(inputs, outputs, locktime, options, bip32derivs).GetAwaiter().GetResult();
Exemplo n.º 13
0
        public void TryRead_Fail_NullStreamTest()
        {
            bool b = LockTime.TryRead(null, out LockTime actual, out string error);

            Assert.False(b);
            Assert.Equal("Stream can not be null.", error);
            Helper.ComparePrivateField(actual, "value", 0U);
        }
Exemplo n.º 14
0
        public void CompareTo_EdgeTest()
        {
            LockTime lt   = new LockTime(100);
            object   nObj = null;
            object   sObj = "LockTime!";

            Assert.Equal(1, lt.CompareTo(nObj));
            Assert.Throws <ArgumentException>(() => lt.CompareTo(sObj));
        }
Exemplo n.º 15
0
        public void WriteToStreamTest(byte[] expected, uint value)
        {
            LockTime   lt     = new LockTime(value);
            FastStream stream = new FastStream();

            lt.WriteToStream(stream);

            Assert.Equal(expected, stream.ToByteArray());
        }
Exemplo n.º 16
0
        /// <summary>
        /// Initializes a new instance of <see cref="Transaction"/> using given parameters.
        /// </summary>
        /// <exception cref="ArgumentNullException"/>
        /// <param name="ver">Version</param>
        /// <param name="txIns">List of inputs</param>
        /// <param name="txOuts">List of outputs</param>
        /// <param name="lt">LockTime</param>
        /// <param name="witnesses">[Default value = null] List of witnesses (default is null).</param>
        public Transaction(int ver, TxIn[] txIns, TxOut[] txOuts, LockTime lt, Witness[] witnesses = null)
        {
            Version   = ver;
            TxInList  = txIns;
            TxOutList = txOuts;
            LockTime  = lt;

            WitnessList = witnesses;
        }
Exemplo n.º 17
0
        public void Create()
        {
            // create the first part.
            using (var stream = new MemoryStream())
            {
                stream.WriteValueU32(Version.LittleEndian());     // write version

                if (PoolConfig.Coin.Options.IsProofOfStakeHybrid) // if coin is a proof-of-stake coin
                {
                    stream.WriteValueU32(BlockTemplate.CurTime);  // include time-stamp in the transaction.
                }
                // write transaction input
                stream.WriteBytes(Serializers.VarInt(InputsCount));
                stream.WriteBytes(Inputs.First().PreviousOutput.Hash.Bytes);
                stream.WriteValueU32(Inputs.First().PreviousOutput.Index.LittleEndian());

                // write signature script lenght
                var signatureScriptLenght = (UInt32)(Inputs.First().SignatureScript.Initial.Length + ExtraNonce.ExtraNoncePlaceholder.Length + Inputs.First().SignatureScript.Final.Length);


                stream.WriteBytes(Serializers.VarInt(signatureScriptLenght).ToArray());

                stream.WriteBytes(Inputs.First().SignatureScript.Initial);

                Initial = stream.ToArray();
            }

            /*  The generation transaction must be split at the extranonce (which located in the transaction input
             *  scriptSig). Miners send us unique extranonces that we use to join the two parts in attempt to create
             *  a valid share and/or block. */

            // create the second part.
            using (var stream = new MemoryStream())
            {
                // transaction input
                stream.WriteBytes(Inputs.First().SignatureScript.Final);

                stream.WriteValueU32(Inputs.First().Sequence);

                // transaction inputs end here.

                // transaction output
                var outputBuffer = Outputs.GetBuffer();
                stream.WriteBytes(outputBuffer);
                // transaction output ends here.

                stream.WriteValueU32(LockTime.LittleEndian());

                if (PoolConfig.Coin.Options.TxMessageSupported)
                {
                    stream.WriteBytes(TxMessage);
                }

                Final = stream.ToArray();
            }
        }
Exemplo n.º 18
0
        public void TryReadTest(byte[] data, uint expected)
        {
            FastStreamReader stream = new FastStreamReader(data);
            bool             b      = LockTime.TryRead(stream, out LockTime actual, out string error);

            Assert.True(b);
            Assert.Null(error);
            Helper.ComparePrivateField(stream, "position", 4);
            Helper.ComparePrivateField(actual, "value", expected);
        }
Exemplo n.º 19
0
        public void Comparison_WithInt_EqualTest(int c, int i, bool expected)
        {
            LockTime lt = new LockTime(c);

            Assert.Equal(expected, lt == i);
            Assert.Equal(!expected, lt != i);

            Assert.Equal(expected, i == lt);
            Assert.Equal(!expected, i != lt);
        }
Exemplo n.º 20
0
 private string ToString(LockTime locktime)
 {
     if (locktime.IsHeightLock)
     {
         return($"at block {locktime.Height}");
     }
     else
     {
         return($"the {locktime.Date:f}");
     }
 }
Exemplo n.º 21
0
        public void TryRead_Fail_SmallStreamTest()
        {
            FastStreamReader stream = new FastStreamReader(new byte[3] {
                1, 2, 3
            });
            bool b = LockTime.TryRead(stream, out LockTime actual, out string error);

            Assert.False(b);
            Assert.Equal(Err.EndOfStream, error);
            Helper.ComparePrivateField(actual, "value", 0U);
        }
 private byte[] SerializeWithoutWitness()
 {
     return(ByteArray.ConcatArrays(
                Version.ToByteArray(false),
                TxInCount.Bytes,
                SerializeTxIns(),
                TxOutCount.Bytes,
                SerializeTxOuts(),
                LockTime.ToByteArray(false)
                ));
 }
Exemplo n.º 23
0
        public LockTime GetTumblerLockTime()
        {
            var periods  = GetPeriods();
            var lockTime = new LockTime(periods.ClientCashout.End + SafetyPeriodDuration);

            if (lockTime.IsTimeLock)
            {
                throw new InvalidOperationException("Invalid cycle");
            }
            return(lockTime);
        }
Exemplo n.º 24
0
 public PuzzlePaymentRequest(Puzzle puzzle, Money amount, LockTime escrowDate)
 {
     if (puzzle == null)
     {
         throw new ArgumentNullException(nameof(puzzle));
     }
     Amount        = amount ?? throw new ArgumentNullException(nameof(amount));
     EscrowDate    = escrowDate;
     RsaPubKeyHash = puzzle.RsaPubKey.GetHash();
     PuzzleValue   = puzzle.PuzzleValue;
 }
Exemplo n.º 25
0
 public WalletCreateFundedPSBTResponse WalletCreateFundedPSBT(
     TxIn[] inputs,
     Dictionary <string, string> outputs,
     LockTime locktime,
     FundRawTransactionOptions options = null,
     bool bip32derivs = false
     ) => WalletCreateFundedPSBT(
     inputs,
     Tuple.Create <Dictionary <BitcoinAddress, Money>, Dictionary <string, string> >(null, outputs),
     locktime,
     options,
     bip32derivs);
Exemplo n.º 26
0
        public void CastDateTimeTest()
        {
            LockTime lt1 = 0;
            LockTime lt2 = uint.MaxValue;

            DateTime actual1  = (DateTime)lt1;
            DateTime actual2  = (DateTime)lt2;
            DateTime expected = new DateTime(1970, 1, 1, 0, 0, 0);

            Assert.Equal(expected, actual1);
            Assert.Equal(expected, actual2);
        }
 public byte[] Serialize()
 {
     return(ByteArray.ConcatArrays(
                Version.ToByteArray(false),
                GetFlag(),
                TxInCount.Bytes,
                SerializeTxIns(),
                TxOutCount.Bytes,
                SerializeTxOuts(),
                GetWitness(),
                LockTime.ToByteArray(false)
                ));
 }
Exemplo n.º 28
0
        public byte[] UntrustedHashSign(KeyPath keyPath, UserPin pin, LockTime lockTime, SigHash sigHashType)
        {
            MemoryStream data = new MemoryStream();

            byte[] path = Serializer.Serialize(keyPath);
            BufferUtils.WriteBuffer(data, path);

            var pinBytes = pin == null ? new byte[0] : pin.ToBytes();

            data.WriteByte((byte)pinBytes.Length);
            BufferUtils.WriteBuffer(data, pinBytes);
            BufferUtils.WriteUint32BE(data, (uint)lockTime);
            data.WriteByte((byte)sigHashType);
            return(CreateAPDU(LedgerWalletConstants.LedgerWallet_CLA, LedgerWalletConstants.LedgerWallet_INS_HASH_SIGN, (byte)0x00, (byte)0x00, data.ToArray()));
        }
Exemplo n.º 29
0
        public void ComparisonOperator_SameTypeTest(LockTime lt1, LockTime lt, ValueCompareResult expected)
        {
            Assert.Equal(expected.Bigger, lt1 > lt);
            Assert.Equal(expected.BiggerEqual, lt1 >= lt);
            Assert.Equal(expected.Smaller, lt1 < lt);
            Assert.Equal(expected.SmallerEqual, lt1 <= lt);

            Assert.Equal(expected.Equal, lt1 == lt);
            Assert.Equal(!expected.Equal, lt1 != lt);

            Assert.Equal(expected.Equal, lt1.Equals(lt));
            Assert.Equal(expected.Equal, lt1.Equals((object)lt));

            Assert.Equal(expected.Compare, lt1.CompareTo(lt));
            Assert.Equal(expected.Compare, lt1.CompareTo((object)lt));
        }
Exemplo n.º 30
0
    public void GetLockTimeBasedOnDistributionTest()
    {
        var lockTimeSelector = new LockTimeSelector(new Random());

        uint     tipHeight = 600_000;
        LockTime lockTime  = lockTimeSelector.GetLockTimeBasedOnDistribution(tipHeight);

        if (lockTime.Value == 0)
        {
            Assert.Equal(LockTime.Zero, lockTime);
        }
        else
        {
            Assert.InRange(lockTime.Value, tipHeight - 99, tipHeight + 1);
        }
    }
Exemplo n.º 31
0
		private void BIP65_testsCore(LockTime target, LockTime now, bool expectedResult)
		{
			Transaction tx = new Transaction();
			tx.Outputs.Add(new TxOut()
			{
				ScriptPubKey = new Script(Op.GetPushOp(target.Value), OpcodeType.OP_CHECKLOCKTIMEVERIFY)
			});

			Transaction spending = new Transaction();
			spending.LockTime = now;
			spending.Inputs.Add(new TxIn(tx.Outputs.AsCoins().First().Outpoint, new Script()));
			spending.Inputs[0].Sequence = 1;

			Assert.Equal(expectedResult, spending.Inputs.AsIndexedInputs().First().VerifyScript(tx.Outputs[0].ScriptPubKey));

			spending.Inputs[0].Sequence = uint.MaxValue;
			Assert.Equal(false, spending.Inputs.AsIndexedInputs().First().VerifyScript(tx.Outputs[0].ScriptPubKey));
		}