Ejemplo n.º 1
0
        public void ReadWrite(BitcoinStream stream)
        {
            if (stream.Serializing)
            {
                stream.ReadWriteAsVarInt(ref this.height);
                stream.ReadWrite(ref this.isCoinbase);
                stream.ReadWrite(ref this.isCoinstake);
                stream.ReadWrite(ref this.time);

                stream.ReadWrite(ref this.txOut);

                // var compressedTx = new TxOutCompressor(this.txOut);
                // stream.ReadWrite(ref compressedTx);
            }
            else
            {
                stream.ReadWriteAsVarInt(ref this.height);
                stream.ReadWrite(ref this.isCoinbase);
                stream.ReadWrite(ref this.isCoinstake);
                stream.ReadWrite(ref this.time);

                stream.ReadWrite(ref this.txOut);

                // var compressed = new TxOutCompressor();
                // stream.ReadWrite(ref compressed);
                // this.txOut = compressed.TxOut;
            }
        }
Ejemplo n.º 2
0
 public override void ReadWrite(BitcoinStream stream)
 {
     stream.ReadWriteAsVarInt(ref TxType);
     stream.ReadWriteAsVarInt(ref Version);
     stream.ReadWriteAsCompactVarInt(ref ValidHeight);
     stream.ReadWrite(ref RegId);
     stream.ReadWrite(ref Script);
     stream.ReadWriteAsCompactVarInt(ref Fees);
     stream.ReadWrite(ref Signature);
 }
Ejemplo n.º 3
0
 public static void ReadWriteC(this BitcoinStream bs, ref Money[][] arr)
 {
     if (bs.Serializing)
     {
         if (arr == null)
         {
             uint o = 0;
             bs.ReadWriteAsVarInt(ref o);
             return;
         }
         var len = (uint)arr.Length;
         bs.ReadWriteAsVarInt(ref len);
         for (int i = 0; i < len; i++)
         {
             var subLen = (uint)arr[i].Length;
             bs.ReadWriteAsVarInt(ref subLen);
             for (int j = 0; j < subLen; j++)
             {
                 var n = arr[i][j];
                 bs.ReadWriteC(ref n);
             }
         }
     }
     else
     {
         uint len = 0;
         bs.ReadWriteAsVarInt(ref len);
         if (len == 0)
         {
             arr = null;
             return;
         }
         if (len > bs.MaxArraySize)
         {
             throw new ArgumentOutOfRangeException("Array is too big");
         }
         arr = new Money[len][];
         for (int i = 0; i < len; i++)
         {
             uint subLen = 0;
             bs.ReadWriteAsVarInt(ref subLen);
             if (subLen == 0)
             {
                 arr[i] = null;
                 return;
             }
             arr[i] = new Money[subLen];
             for (int j = 0; j < subLen; j++)
             {
                 bs.ReadWriteC(ref arr[i][j]);
             }
         }
     }
 }
 public override void ReadWrite(BitcoinStream stream)
 {
     stream.ReadWriteAsVarInt(ref TxType);
     stream.ReadWriteAsVarInt(ref Version);
     stream.ReadWriteAsCompactVarInt(ref ValidHeight);
     stream.ReadWrite(ref SrcId);
     stream.ReadWrite(ref DesId);
     stream.ReadWriteAsCompactVarInt(ref Fees);
     stream.ReadWriteAsCompactVarInt(ref Values);
     stream.ReadWrite(ref Contract);
     stream.ReadWrite(ref Signature);
 }
Ejemplo n.º 5
0
        protected virtual void BuildCoinbase()
        {
            var sigScriptInitial      = GenerateScriptSigInitial();
            var sigScriptInitialBytes = sigScriptInitial.ToBytes();

            var sigScriptLength = (uint)(
                sigScriptInitial.Length +
                extraNoncePlaceHolderLength +
                scriptSigFinalBytes.Length);

            txOut = CreateOutputTransaction();

            using (var stream = new MemoryStream())
            {
                var bs = new BitcoinStream(stream, true);

                bs.ReadWrite(ref txVersion);

                if (isPoS)
                {
                    var timestamp = BlockTemplate.CurTime;
                    bs.ReadWrite(ref timestamp);
                }

                bs.ReadWriteAsVarInt(ref txInputCount);
                bs.ReadWrite(ref sha256Empty);
                bs.ReadWrite(ref txInPrevOutIndex);

                bs.ReadWriteAsVarInt(ref sigScriptLength);
                bs.ReadWrite(ref sigScriptInitialBytes);

                coinbaseInitial    = stream.ToArray();
                coinbaseInitialHex = coinbaseInitial.ToHexString();
            }

            using (var stream = new MemoryStream())
            {
                var bs = new BitcoinStream(stream, true);

                bs.ReadWrite(ref scriptSigFinalBytes);

                bs.ReadWrite(ref txInSequence);

                var txOutBytes = SerializeOutputTransaction(txOut);
                bs.ReadWrite(ref txOutBytes);

                bs.ReadWrite(ref txLockTime);

                coinbaseFinal    = stream.ToArray();
                coinbaseFinalHex = coinbaseFinal.ToHexString();
            }
        }
Ejemplo n.º 6
0
        public override uint256 GetSignatureHash()
        {
            BitcoinStream stream = CreateHashWriter(HashVersion.Original);

            stream.ReadWriteAsVarInt(ref Version);
            stream.ReadWriteAsVarInt(ref TxType);
            stream.ReadWriteAsCompactVarInt(ref ValidHeight);
            stream.ReadWrite(ref RegId);
            stream.ReadWrite(ref Script);
            stream.ReadWriteAsCompactVarInt(ref Fees);

            return(GetHash(stream));
        }
Ejemplo n.º 7
0
    private byte[] SerializeOutputTransaction(Transaction tx)
    {
        var withDefaultWitnessCommitment = !string.IsNullOrEmpty(BlockTemplate.DefaultWitnessCommitment);

        var outputCount = (uint)tx.Outputs.Count;

        if (withDefaultWitnessCommitment)
        {
            outputCount++;
        }

        using (var stream = new MemoryStream())
        {
            var bs = new BitcoinStream(stream, true);

            // write output count
            bs.ReadWriteAsVarInt(ref outputCount);

            long   amount;
            byte[] raw;
            uint   rawLength;

            // serialize witness (segwit)
            if (withDefaultWitnessCommitment)
            {
                amount    = 0;
                raw       = BlockTemplate.DefaultWitnessCommitment.HexToByteArray();
                rawLength = (uint)raw.Length;

                bs.ReadWrite(ref amount);
                bs.ReadWriteAsVarInt(ref rawLength);
                bs.ReadWrite(ref raw);
            }

            // serialize outputs
            foreach (var output in tx.Outputs)
            {
                amount = output.Value.Satoshi;
                var outScript = output.ScriptPubKey;
                raw       = outScript.ToBytes(true);
                rawLength = (uint)raw.Length;

                bs.ReadWrite(ref amount);
                bs.ReadWriteAsVarInt(ref rawLength);
                bs.ReadWrite(ref raw);
            }

            return(stream.ToArray());
        }
    }
        public override void ReadWriteCore(BitcoinStream stream)
        {
            stream.ReadWrite(ref this.blockId);
            ulong indexes_size = (ulong)this.indices.Count;

            stream.ReadWriteAsVarInt(ref indexes_size);

            if (!stream.Serializing)
            {
                ulong i            = 0;
                ulong indicesCount = 0;
                while ((ulong)this.indices.Count < indexes_size)
                {
                    indicesCount = Math.Min(1000UL + (ulong)indicesCount, (ulong)indexes_size);
                    for (; i < indicesCount; i++)
                    {
                        ulong index = 0;
                        stream.ReadWriteAsVarInt(ref index);
                        if (index > int.MaxValue)
                        {
                            throw new FormatException("indexes overflowed 31-bits");
                        }

                        this.indices.Add((int)index);
                    }
                }

                int offset = 0;
                for (int ii = 0; ii < this.indices.Count; ii++)
                {
                    if ((ulong)(this.indices[ii]) + (ulong)(offset) > int.MaxValue)
                    {
                        throw new FormatException("indexes overflowed 31-bits");
                    }

                    this.indices[ii] = this.indices[ii] + offset;
                    offset           = this.indices[ii] + 1;
                }
            }
            else
            {
                for (int i = 0; i < this.indices.Count; i++)
                {
                    int index = this.indices[i] - (i == 0 ? 0 : (this.indices[i - 1] + 1));
                    stream.ReadWrite(ref index);
                }
            }
        }
Ejemplo n.º 9
0
 public void ReadWrite(BitcoinStream stream)
 {
     stream.ReadWriteAsVarInt(ref _OutputIndex);
     stream.ReadWrite(ref _Transaction);
     stream.ReadWrite(ref _MerkleProof);
     stream.ReadWriteC(ref _EscrowInitiatorKey);
 }
Ejemplo n.º 10
0
		private bool ReadScript(Script script)
		{
			try
			{
				var data = TxNullDataTemplate.Instance.ExtractScriptPubKeyParameters(script);
				if(data == null)
					return false;
				BitcoinStream stream = new BitcoinStream(data);
				ushort marker = 0;
				stream.ReadWrite(ref marker);
				if(marker != Tag)
					return false;
				stream.ReadWrite(ref _Version);
				if(_Version != 1)
					return false;

				ulong quantityCount = 0;
				stream.ReadWriteAsVarInt(ref quantityCount);
				Quantities = new ulong[quantityCount];

				for(ulong i = 0 ; i < quantityCount ; i++)
				{
					Quantities[i] = ReadLEB128(stream);
					if(Quantities[i] > MAX_QUANTITY)
						return false;
				}

				stream.ReadWriteAsVarString(ref _Metadata);
				return true;
			}
			catch(Exception)
			{
				return false;
			}
		}
Ejemplo n.º 11
0
        protected override void BuildCoinbase()
        {
            var script = TxIn.CreateCoinbase((int) BlockTemplate.Height).ScriptSig;

                        txOut = CreateOutputTransaction();

            using(var stream = new MemoryStream())
            {
                var bs = new BitcoinStream(stream, true);

                                bs.ReadWrite(ref txVersion);

                                bs.ReadWriteAsVarInt(ref txInputCount);
                bs.ReadWrite(ref sha256Empty);
                bs.ReadWrite(ref coinbaseIndex);
                bs.ReadWrite(ref script);
                bs.ReadWrite(ref coinbaseSequence);

                                var txOutBytes = SerializeOutputTransaction(txOut);
                bs.ReadWrite(ref txOutBytes);

                                bs.ReadWrite(ref txLockTime);

                                coinbaseInitial = stream.ToArray();
                coinbaseInitialHex = coinbaseInitial.ToHexString();
                coinbaseInitialHash = sha256D.Digest(coinbaseInitial);
            }
        }
Ejemplo n.º 12
0
            private static void WriteScriptCode(BitcoinStream stream, Script scriptCode)
            {
                int        nCodeSeparators = 0;
                var        reader          = scriptCode.CreateReader();
                OpcodeType opcode;

                while (reader.TryReadOpCode(out opcode))
                {
                    if (opcode == OpcodeType.OP_CODESEPARATOR)
                    {
                        nCodeSeparators++;
                    }
                }

                uint n = (uint)(scriptCode.Length - nCodeSeparators);

                stream.ReadWriteAsVarInt(ref n);

                reader = scriptCode.CreateReader();
                int itBegin = 0;

                while (reader.TryReadOpCode(out opcode))
                {
                    if (opcode == OpcodeType.OP_CODESEPARATOR)
                    {
                        stream.Inner.Write(scriptCode.ToBytes(true), itBegin, (int)(reader.Inner.Position - itBegin - 1));
                        itBegin = (int)reader.Inner.Position;
                    }
                }

                if (itBegin != scriptCode.Length)
                {
                    stream.Inner.Write(scriptCode.ToBytes(true), itBegin, (int)(reader.Inner.Position - itBegin));
                }
            }
Ejemplo n.º 13
0
    protected override void BuildCoinbase()
    {
        var script = TxIn.CreateCoinbase((int)BlockTemplate.Height).ScriptSig;

        // output transaction
        txOut = CreateOutputTransaction();

        using (var stream = new MemoryStream())
        {
            var bs = new BitcoinStream(stream, true);

            // version
            bs.ReadWrite(ref txVersion);

            // serialize (simulated) input transaction
            bs.ReadWriteAsVarInt(ref txInputCount);
            bs.ReadWrite(ref sha256Empty);
            bs.ReadWrite(ref coinbaseIndex);
            bs.ReadWrite(ref script);
            bs.ReadWrite(ref coinbaseSequence);

            // serialize output transaction
            var txOutBytes = SerializeOutputTransaction(txOut);
            bs.ReadWrite(ref txOutBytes);

            // misc
            bs.ReadWrite(ref txLockTime);

            // done
            coinbaseInitial     = stream.ToArray();
            coinbaseInitialHash = new byte[32];
            sha256D.Digest(coinbaseInitial, coinbaseInitialHash);
        }
    }
Ejemplo n.º 14
0
		private bool ReadData(byte[] data)
		{
			try
			{
				BitcoinStream stream = new BitcoinStream(data);
				ushort marker = 0;
				stream.ReadWrite(ref marker);
				if(marker != Tag)
					return false;
				stream.ReadWrite(ref _Version);
				if(_Version != 1)
					return false;

				ulong quantityCount = 0;
				stream.ReadWriteAsVarInt(ref quantityCount);
				Quantities = new ulong[quantityCount];

				for(ulong i = 0 ; i < quantityCount ; i++)
				{
					Quantities[i] = ReadLEB128(stream);
					if(Quantities[i] > MAX_QUANTITY)
						return false;
				}

				stream.ReadWriteAsVarString(ref _Metadata);
				if(stream.Inner.Position != data.Length)
					return false;
				return true;
			}
			catch(Exception)
			{
				return false;
			}
		}
Ejemplo n.º 15
0
            public QuorumCommitment(BinaryReader data)
            {
                QfcVersion = data.ReadUInt16();
                LlmqType   = data.ReadByte();
                QuorumHash = new uint256(data.ReadBytes(SpecialTransaction.SHA256_HASH_SIZE));
                var bs = new BitcoinStream(data.BaseStream, false);

                bs.ReadWriteAsVarInt(ref SignersSize);
                Signers = data.ReadBytes(((int)SignersSize + 7) / 8);
                bs.ReadWriteAsVarInt(ref ValidMembersSize);
                ValidMembers    = data.ReadBytes(((int)ValidMembersSize + 7) / 8);
                QuorumPublicKey = data.ReadBytes(SpecialTransaction.BLS_PUBLIC_KEY_SIZE);
                QuorumVvecHash  = new uint256(data.ReadBytes(SpecialTransaction.SHA256_HASH_SIZE));
                QuorumSig       = data.ReadBytes(SpecialTransaction.BLS_SIGNATURE_SIZE);
                Sig             = data.ReadBytes(SpecialTransaction.BLS_SIGNATURE_SIZE);
            }
Ejemplo n.º 16
0
        protected virtual byte[] SerializeBlock(byte[] header, byte[] coinbase)
        {
            var transactionCount     = (uint)BlockTemplate.Transactions.Length + 1; // +1 for prepended coinbase tx
            var rawTransactionBuffer = BuildRawTransactionBuffer();

            using (var stream = new MemoryStream())
            {
                var bs = new BitcoinStream(stream, true);

                bs.ReadWrite(ref header);
                bs.ReadWriteAsVarInt(ref transactionCount);
                bs.ReadWrite(ref coinbase);
                bs.ReadWrite(ref rawTransactionBuffer);

                // TODO: handle DASH coin masternode_payments

                // POS coins require a zero byte appended to block which the daemon replaces with the signature
                if (isPoS)
                {
                    bs.ReadWrite((byte)0);
                }

                return(stream.ToArray());
            }
        }
Ejemplo n.º 17
0
 public static void ReadWriteC(this BitcoinStream bs, ref PoupardSternProof proof)
 {
     if (bs.Serializing)
     {
         if (proof == null)
         {
             uint o = 0;
             bs.ReadWriteAsVarInt(ref o);
             return;
         }
         var len = (uint)proof.XValues.Length;
         bs.ReadWriteAsVarInt(ref len);
         for (int i = 0; i < len; i++)
         {
             var n = proof.XValues[i];
             bs.ReadWriteC(ref n);
         }
         var yvalue = proof.YValue;
         bs.ReadWriteC(ref yvalue);
     }
     else
     {
         uint len = 0;
         bs.ReadWriteAsVarInt(ref len);
         if (len == 0)
         {
             proof = null;
             return;
         }
         if (len > bs.MaxArraySize)
         {
             throw new ArgumentOutOfRangeException("Array is too big");
         }
         var xValues = new NTumbleBit.BouncyCastle.Math.BigInteger[len];
         for (int i = 0; i < len; i++)
         {
             NTumbleBit.BouncyCastle.Math.BigInteger b = null;
             bs.ReadWriteC(ref b);
             xValues[i] = b;
         }
         NTumbleBit.BouncyCastle.Math.BigInteger yValue = null;
         bs.ReadWriteC(ref yValue);
         proof = new PoupardSternProof(Tuple.Create(xValues, yValue));
     }
 }
Ejemplo n.º 18
0
 public static void ReadWriteC(this BitcoinStream bs, ref PermutationTestProof proof)
 {
     if (bs.Serializing)
     {
         if (proof == null)
         {
             uint o = 0;
             bs.ReadWriteAsVarInt(ref o);
             return;
         }
         var len = (uint)proof.Signatures.Length;
         bs.ReadWriteAsVarInt(ref len);
         for (int i = 0; i < len; i++)
         {
             var sig = proof.Signatures[i];
             bs.ReadWriteAsVarString(ref sig);
         }
     }
     else
     {
         uint len = 0;
         bs.ReadWriteAsVarInt(ref len);
         if (len == 0)
         {
             proof = null;
             return;
         }
         if (len > bs.MaxArraySize)
         {
             throw new ArgumentOutOfRangeException("Array is too big");
         }
         var signatures = new byte[len][];
         for (int i = 0; i < len; i++)
         {
             byte[] sig = null;
             bs.ReadWriteAsVarString(ref sig);
             signatures[i] = sig;
         }
         proof = new PermutationTestProof(signatures);
     }
 }
Ejemplo n.º 19
0
            public ProviderRegistrationTransaction(byte[] extraPayload) : base(extraPayload)
            {
                Type            = data.ReadUInt16();
                Mode            = data.ReadUInt16();
                CollateralHash  = new uint256(data.ReadBytes(SHA256_HASH_SIZE), true);
                CollateralIndex = data.ReadUInt32();
                IpAddress       = data.ReadBytes(IpAddressLength);
                Port            = BitConverter.ToUInt16(data.ReadBytes(2).Reverse().ToArray(), 0);
                KeyIdOwner      = new uint160(data.ReadBytes(PUBKEY_ID_SIZE), true);
                KeyIdOperator   = data.ReadBytes(BLS_PUBLIC_KEY_SIZE);
                KeyIdVoting     = new uint160(data.ReadBytes(PUBKEY_ID_SIZE), true);
                OperatorReward  = data.ReadUInt16();
                var bs = new BitcoinStream(data.BaseStream, false);

                bs.ReadWriteAsVarInt(ref ScriptPayoutSize);
                ScriptPayout = new Script(data.ReadBytes((int)ScriptPayoutSize));
                InputsHash   = new uint256(data.ReadBytes(SHA256_HASH_SIZE), true);
                bs.ReadWriteAsVarInt(ref PayloadSigSize);
                PayloadSig = data.ReadBytes((int)PayloadSigSize);
                MakeSureWeAreAtEndOfPayload();
            }
Ejemplo n.º 20
0
		public override void ReadWriteCore(BitcoinStream stream)
		{
			stream.ReadWrite(ref _BlockId);
			ulong indexes_size = (ulong)_Indices.Count;
			stream.ReadWriteAsVarInt(ref indexes_size);
			if(!stream.Serializing)
			{
				ulong i = 0;
				ulong indicesCount = 0;
				while((ulong)_Indices.Count < indexes_size)
				{
					indicesCount = Math.Min(1000UL + (ulong)indicesCount, (ulong)indexes_size);
					for(; i < indicesCount; i++)
					{
						ulong index = 0;
						stream.ReadWriteAsVarInt(ref index);
						if(index > Int32.MaxValue)
							throw new FormatException("indexes overflowed 31-bits");
						_Indices.Add((int)index);
					}
				}

				int offset = 0;
				for(var ii = 0; ii < _Indices.Count; ii++)
				{
					if((ulong)(_Indices[ii]) + (ulong)(offset) > Int32.MaxValue)
						throw new FormatException("indexes overflowed 31-bits");
					_Indices[ii] = _Indices[ii] + offset;
					offset = _Indices[ii] + 1;
				}
			}
			else
			{
				for(var i = 0; i < _Indices.Count; i++)
				{
					int index = _Indices[i] - (i == 0 ? 0 : (_Indices[i - 1] + 1));					
					stream.ReadWrite(ref index);
				}
			}
		}
Ejemplo n.º 21
0
            public override void ReadWrite(BitcoinStream stream)
            {
                if (!stream.Serializing)
                {
                    prevout = null;
                }
                stream.ReadWrite(ref prevout);
                stream.ReadWrite(ref scriptSig);
                stream.ReadWrite(ref nSequence);


                if (prevout.N == ANON_MARKER)
                {
                    uint stack_size = stream.Serializing ? (uint)data.Length : 0;
                    stream.ReadWriteAsVarInt(ref stack_size);

                    if (!stream.Serializing)
                    {
                        data = new byte[stack_size][];
                    }

                    for (int k = 0; k < stack_size; k++)
                    {
                        uint data_size = stream.Serializing ? (uint)data[k].Length : 0;
                        stream.ReadWriteAsVarInt(ref data_size);

                        byte[] data_stack = stream.Serializing ? data[k] : new byte[data_size];

                        if (data_size != 0)
                        {
                            stream.ReadWrite(ref data_stack);
                        }

                        if (!stream.Serializing)
                        {
                            data[k] = data_stack;
                        }
                    }
                }
            }
Ejemplo n.º 22
0
            public ProviderUpdateServiceTransaction(byte[] extraPayload) : base(extraPayload)
            {
                ProTXHash = new uint256(data.ReadBytes(SHA256_HASH_SIZE), true);
                IpAddress = data.ReadBytes(IpAddressLength);
                Port      = BitConverter.ToUInt16(data.ReadBytes(2).Reverse().ToArray(), 0);
                var bs = new BitcoinStream(data.BaseStream, false);

                bs.ReadWriteAsVarInt(ref ScriptOperatorPayoutSize);
                ScriptOperatorPayout = new Script(data.ReadBytes((int)ScriptOperatorPayoutSize));
                InputsHash           = new uint256(data.ReadBytes(SHA256_HASH_SIZE), true);
                PayloadSig           = data.ReadBytes(BLS_SIGNATURE_SIZE);
                MakeSureWeAreAtEndOfPayload();
            }
Ejemplo n.º 23
0
            public ProviderUpdateRegistrarTransaction(byte[] extraPayload) : base(extraPayload)
            {
                ProTXHash      = new uint256(data.ReadBytes(SHA256_HASH_SIZE), true);
                Mode           = data.ReadUInt16();
                PubKeyOperator = data.ReadBytes(BLS_PUBLIC_KEY_SIZE);
                KeyIdVoting    = new uint160(data.ReadBytes(PUBKEY_ID_SIZE), true);
                var bs = new BitcoinStream(data.BaseStream, false);

                bs.ReadWriteAsVarInt(ref ScriptPayoutSize);
                ScriptPayout = new Script(data.ReadBytes((int)ScriptPayoutSize));
                InputsHash   = new uint256(data.ReadBytes(SHA256_HASH_SIZE), true);
                if (data.BaseStream.Position < data.BaseStream.Length)
                {
                    bs.ReadWriteAsVarInt(ref PayloadSigSize);
                    PayloadSig = data.ReadBytes((int)PayloadSigSize);
                }
                else
                {
                    PayloadSig = new byte[0];
                }
                MakeSureWeAreAtEndOfPayload();
            }
Ejemplo n.º 24
0
        public void ReadWrite(BitcoinStream stream)
        {
            stream.ReadWrite(ref _Outpoint);
            stream.ReadWrite(ref _Output);
            stream.ReadWriteAsVarInt(ref _Confirmations);

            uint[] indexes = _KeyPath?.Indexes ?? new uint[0];
            stream.ReadWrite(ref indexes);
            if (!stream.Serializing)
            {
                _KeyPath = new KeyPath(indexes);
            }
        }
Ejemplo n.º 25
0
 public override void ReadWrite(BitcoinStream stream)
 {
     base.ReadWrite(stream);
     // Support for Dash 0.13 extraPayload for Special Transactions
     // https://github.com/dashpay/dips/blob/master/dip-0002-special-transactions.md
     if (DashVersion >= 3 && DashType != DashTransactionType.StandardTransaction)
     {
         // Extra payload size is VarInt
         uint extraPayloadSize = (uint)ExtraPayload.Length;
         stream.ReadWriteAsVarInt(ref extraPayloadSize);
         if (ExtraPayload.Length != extraPayloadSize)
         {
             ExtraPayload = new byte[extraPayloadSize];
         }
         stream.ReadWrite(ref ExtraPayload);
     }
 }
Ejemplo n.º 26
0
        protected byte[] SerializeBlock(byte[] header, byte[] coinbase, byte[] solution)
        {
            var transactionCount = (uint) BlockTemplate.Transactions.Length + 1;             var rawTransactionBuffer = BuildRawTransactionBuffer();

            using(var stream = new MemoryStream())
            {
                var bs = new BitcoinStream(stream, true);

                bs.ReadWrite(ref header);
                bs.ReadWrite(ref solution);
                bs.ReadWriteAsVarInt(ref transactionCount);
                bs.ReadWrite(ref coinbase);
                bs.ReadWrite(ref rawTransactionBuffer);

                return stream.ToArray();
            }
        }
Ejemplo n.º 27
0
        private bool ReadData(byte[] data)
        {
            try
            {
                using (var ms = new MemoryStream(data))
                {
                    var    stream = new BitcoinStream(ms, false);
                    ushort marker = 0;
                    stream.ReadWrite(ref marker);
                    if (marker != Tag)
                    {
                        return(false);
                    }
                    stream.ReadWrite(ref this._Version);
                    if (this._Version != 1)
                    {
                        return(false);
                    }

                    ulong quantityCount = 0;
                    stream.ReadWriteAsVarInt(ref quantityCount);
                    this.Quantities = new ulong[quantityCount];

                    for (ulong i = 0; i < quantityCount; i++)
                    {
                        this.Quantities[i] = ReadLEB128(stream);
                        if (this.Quantities[i] > MAX_QUANTITY)
                        {
                            return(false);
                        }
                    }

                    stream.ReadWriteAsVarString(ref this._Metadata);
                    if (stream.Inner.Position != data.Length)
                    {
                        return(false);
                    }
                    return(true);
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
Ejemplo n.º 28
0
        private byte[] SerializeBlock(Span <byte> header, Span <byte> coinbase, Span <byte> solution)
        {
            var transactionCount     = (uint)BlockTemplate.Transactions.Length + 1; // +1 for prepended coinbase tx
            var rawTransactionBuffer = BuildRawTransactionBuffer();

            using (var stream = new MemoryStream())
            {
                var bs = new BitcoinStream(stream, true);

                bs.ReadWrite(ref header);
                bs.ReadWrite(ref solution);
                bs.ReadWriteAsVarInt(ref transactionCount);
                bs.ReadWrite(ref coinbase);
                bs.ReadWrite(ref rawTransactionBuffer);

                return(stream.ToArray());
            }
        }
Ejemplo n.º 29
0
        private bool ReadScript(Script script)
        {
            var data = TxNullDataTemplate.Instance.ExtractScriptPubKeyParameters(script);

            if (data == null)
            {
                return(false);
            }
            BitcoinStream stream = new BitcoinStream(data);
            ushort        marker = 0;

            stream.ReadWrite(ref marker);
            if (marker != Tag)
            {
                return(false);
            }
            stream.ReadWrite(ref _Version);
            if (_Version != 1)
            {
                return(false);
            }

            ulong quantityCount = 0;

            stream.ReadWriteAsVarInt(ref quantityCount);
            Quantities = new ulong[quantityCount];
            try
            {
                for (ulong i = 0; i < quantityCount; i++)
                {
                    Quantities[i] = ReadLEB128(stream);
                    if (Quantities[i] > MAX_QUANTITY)
                    {
                        throw new FormatException();
                    }
                }
            }
            catch (FormatException)
            {
                return(false);
            }
            stream.ReadWriteAsVarString(ref _Metadata);
            return(true);
        }
Ejemplo n.º 30
0
 public void ReadWrite(BitcoinStream stream)
 {
     stream.ReadWriteAsVarInt(ref _Index);
     if (stream.Serializing)
     {
         byte[] assetId = Asset.Id.ToBytes();
         stream.ReadWrite(ref assetId);
         long quantity = Asset.Quantity;
         stream.ReadWrite(ref quantity);
     }
     else
     {
         byte[] assetId = new byte[20];
         stream.ReadWrite(ref assetId);
         long quantity = 0;
         stream.ReadWrite(ref quantity);
         Asset = new AssetMoney(new AssetId(assetId), quantity);
     }
 }
Ejemplo n.º 31
0
		public void ReadWrite(BitcoinStream stream)
		{
			stream.ReadWriteAsVarInt(ref _Index);
			if(stream.Serializing)
			{
				byte[] assetId = Asset.Id.ToBytes();
				stream.ReadWrite(ref assetId);
				long quantity = Asset.Quantity;
				stream.ReadWrite(ref quantity);
			}
			else
			{
				byte[] assetId = new byte[20];
				stream.ReadWrite(ref assetId);
				long quantity = 0;
				stream.ReadWrite(ref quantity);
				Asset = new AssetMoney(new AssetId(assetId), quantity);
			}
		}
Ejemplo n.º 32
0
        public byte[] ToBytes()
        {
            MemoryStream  ms     = new MemoryStream();
            BitcoinStream stream = new BitcoinStream(ms, true);

            stream.ReadWrite(Tag);
            stream.ReadWrite(ref _Version);
            var quantityCount = (uint)this.Quantities.Length;

            stream.ReadWriteAsVarInt(ref quantityCount);
            for (int i = 0; i < quantityCount; i++)
            {
                if (Quantities[i] > MAX_QUANTITY)
                {
                    throw new ArgumentOutOfRangeException("Quantity should not exceed " + Quantities[i]);
                }
                WriteLEB128(Quantities[i], stream);
            }
            stream.ReadWriteAsVarString(ref _Metadata);
            return(ms.ToArray());
        }
Ejemplo n.º 33
0
            public override void ReadWrite(BitcoinStream stream)
            {
                var isNewFormat = !stream.Serializing || (nSolutionSize != 0);

                stream.ReadWrite(ref nVersion);
                stream.ReadWrite(ref hashPrevBlock);
                stream.ReadWrite(ref hashMerkleRoot);
                stream.ReadWrite(ref hashReserved);
                stream.ReadWrite(ref nTime);
                stream.ReadWrite(ref nBits);
                stream.ReadWrite(ref nNonce);
                if (nSolutionSize > 0)
                {
                    stream.ReadWriteAsVarInt(ref nSolutionSize);

                    if (!stream.Serializing)
                    {
                        nSolution = new byte[nSolutionSize];
                    }
                    stream.ReadWrite(ref nSolution);
                }
            }
Ejemplo n.º 34
0
            public override void ReadWrite(BitcoinStream stream)
            {
                var isNewFormat = !stream.Serializing || (nSolutionSize != 0);

                stream.ReadWrite(ref nVersion);
                stream.ReadWrite(ref hashPrevBlock);
                stream.ReadWrite(ref hashMerkleRoot);
                if (isNewFormat)
                {
                    stream.ReadWrite(ref nHeight);
                    for (int i = 0; i < vReserved.Length; i++)
                    {
                        uint nReserved = 0;
                        stream.ReadWrite(ref nReserved);
                        vReserved[i] = nReserved;
                    }
                }
                stream.ReadWrite(ref nTime);
                stream.ReadWrite(ref nBits);
                if (isNewFormat)
                {
                    stream.ReadWrite(ref nNewNonce);
                    stream.ReadWriteAsVarInt(ref nSolutionSize);
                    if (nSolutionSize > 0)
                    {
                        if (!stream.Serializing)
                        {
                            nSolution = new byte[nSolutionSize];
                        }
                        stream.ReadWrite(ref nSolution);
                    }
                }
                else
                {
                    nNonce = nNewNonce.GetLow32();
                    stream.ReadWrite(ref nNonce);
                    nNewNonce = new uint256(nNonce);
                }
            }
Ejemplo n.º 35
0
		public byte[] ToBytes()
		{
			MemoryStream ms = new MemoryStream();
			BitcoinStream stream = new BitcoinStream(ms, true);
			stream.ReadWrite(Tag);
			stream.ReadWrite(ref _Version);
			var quantityCount = (uint)this.Quantities.Length;
			stream.ReadWriteAsVarInt(ref quantityCount);
			for(int i = 0 ; i < quantityCount ; i++)
			{
				if(Quantities[i] > MAX_QUANTITY)
					throw new ArgumentOutOfRangeException("Quantity should not exceed " + Quantities[i]);
				WriteLEB128(Quantities[i], stream);
			}
			stream.ReadWriteAsVarString(ref _Metadata);
			return ms.ToArray();
		}
Ejemplo n.º 36
0
		public override void ReadWriteCore(BitcoinStream stream)
		{
			stream.ReadWrite(ref _Header);
			stream.ReadWrite(ref _Nonce);

			var shorttxids_size = (uint)_ShortIds.Count;
			stream.ReadWriteAsVarInt(ref shorttxids_size);
			if(!stream.Serializing)
			{
				ulong i = 0;
				ulong shottxidsCount = 0;
				while(_ShortIds.Count < shorttxids_size)
				{
					shottxidsCount = Math.Min(1000UL + (ulong)shottxidsCount, (ulong)shorttxids_size);
					for(; i < shottxidsCount; i++)
					{
						uint lsb = 0;
						ushort msb = 0;
						stream.ReadWrite(ref lsb);
						stream.ReadWrite(ref msb);
						_ShortIds.Add(((ulong)(msb) << 32) | (ulong)(lsb));
					}
				}
			}
			else
			{
				for(var i = 0; i < _ShortIds.Count; i++)
				{
					uint lsb = (uint)(_ShortIds[i] & 0xffffffff);
					ushort msb = (ushort)((_ShortIds[i] >> 32) & 0xffff);
					stream.ReadWrite(ref lsb);
					stream.ReadWrite(ref msb);
				}
			}

			ulong txn_size = (ulong)PrefilledTransactions.Count;
			stream.ReadWriteAsVarInt(ref txn_size);

			if(!stream.Serializing)
			{
				ulong i = 0;
				ulong indicesCount = 0;
				while((ulong)PrefilledTransactions.Count < txn_size)
				{
					indicesCount = Math.Min(1000UL + (ulong)indicesCount, (ulong)txn_size);
					for(; i < indicesCount; i++)
					{
						ulong index = 0;
						stream.ReadWriteAsVarInt(ref index);
						if(index > Int32.MaxValue)
							throw new FormatException("indexes overflowed 32-bits");
						Transaction tx = null;
						stream.ReadWrite(ref tx);
						PrefilledTransactions.Add(new PrefilledTransaction()
						{
							Index = (int)index,
							Transaction = tx
						});
					}
				}

				int offset = 0;
				for(var ii = 0; ii < PrefilledTransactions.Count; ii++)
				{
					if((ulong)(PrefilledTransactions[ii].Index) + (ulong)(offset) > Int32.MaxValue)
						throw new FormatException("indexes overflowed 31-bits");
					PrefilledTransactions[ii].Index = PrefilledTransactions[ii].Index + offset;
					offset = PrefilledTransactions[ii].Index + 1;
				}
			}
			else
			{
				for(var i = 0; i < PrefilledTransactions.Count; i++)
				{
					uint index = checked((uint)(PrefilledTransactions[i].Index - (i == 0 ? 0 : (PrefilledTransactions[i - 1].Index + 1))));
					stream.ReadWriteAsVarInt(ref index);
					Transaction tx = PrefilledTransactions[i].Transaction;
					stream.ReadWrite(ref tx);
				}
			}

			if(!stream.Serializing)
				UpdateShortTxIDSelector();
		}
Ejemplo n.º 37
0
		public Script GetScript()
		{
			MemoryStream ms = new MemoryStream();
			BitcoinStream stream = new BitcoinStream(ms, true);
			stream.ReadWrite(Tag);
			stream.ReadWrite(ref _Version);
			var quantityCount = (uint)this.Quantities.Length;
			stream.ReadWriteAsVarInt(ref quantityCount);
			for(int i = 0 ; i < quantityCount ; i++)
			{
				if(Quantities[i] > MAX_QUANTITY)
					throw new ArgumentOutOfRangeException("Quantity should not exceed " + Quantities[i]);
				WriteLEB128(Quantities[i], stream);
			}
			stream.ReadWriteAsVarString(ref _Metadata);
			return TxNullDataTemplate.Instance.GenerateScriptPubKey(ms.ToArray());
		}
Ejemplo n.º 38
0
		public void ReadWrite(BitcoinStream stream)
		{
			if(stream.Serializing)
			{
				uint nMaskSize = 0, nMaskCode = 0;
				CalcMaskSize(ref nMaskSize, ref nMaskCode);
				bool fFirst = vout.Count > 0 && !vout[0].IsNull;
				bool fSecond = vout.Count > 1 && !vout[1].IsNull;
				uint nCode = unchecked((uint)(8 * (nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0)));
				// version
				stream.ReadWriteAsVarInt(ref nVersion);
				// size of header code
				stream.ReadWriteAsVarInt(ref nCode);
				// spentness bitmask
				for(uint b = 0 ; b < nMaskSize ; b++)
				{
					byte chAvail = 0;
					for(uint i = 0 ; i < 8 && 2 + b * 8 + i < vout.Count ; i++)
						if(!vout[2 + (int)b * 8 + (int)i].IsNull)
							chAvail |= (byte)(1 << (int)i);
					stream.ReadWrite(ref chAvail);
				}

				// txouts themself
				for(uint i = 0 ; i < vout.Count ; i++)
				{
					if(!vout[(int)i].IsNull)
					{
						var compressedTx = new TxOutCompressor(vout[(int)i]);
						stream.ReadWrite(ref compressedTx);
					}
				}
				// coinbase height
				stream.ReadWriteAsVarInt(ref nHeight);
			}
			else
			{
				uint nCode = 0;
				// version
				stream.ReadWriteAsVarInt(ref nVersion);
				//// header code
				stream.ReadWriteAsVarInt(ref nCode);
				fCoinBase = (nCode & 1) != 0;
				List<bool> vAvail = new List<bool>() { false, false };
				vAvail[0] = (nCode & 2) != 0;
				vAvail[1] = (nCode & 4) != 0;
				uint nMaskCode = unchecked((uint)((nCode / 8) + ((nCode & 6) != 0 ? 0 : 1)));
				//// spentness bitmask
				while(nMaskCode > 0)
				{
					byte chAvail = 0;
					stream.ReadWrite(ref chAvail);
					for(uint p = 0 ; p < 8 ; p++)
					{
						bool f = (chAvail & (1 << (int)p)) != 0;
						vAvail.Add(f);
					}
					if(chAvail != 0)
						nMaskCode--;
				}
				// txouts themself
				vout = Enumerable.Range(0, vAvail.Count).Select(_ => new TxOut()).ToList();
				for(uint i = 0 ; i < vAvail.Count ; i++)
				{
					if(vAvail[(int)i])
					{
						TxOutCompressor compressed = new TxOutCompressor();
						stream.ReadWrite(ref compressed);
						vout[(int)i] = compressed.TxOut;
					}
				}
				//// coinbase height
				stream.ReadWriteAsVarInt(ref nHeight);
				Cleanup();
				UpdateValue();
			}
		}