Exemple #1
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;
			}
		}
Exemple #2
0
 public void ReadWrite(BitcoinStream stream)
 {
     using(stream.NetworkFormatScope(true))
     {
         ReadWriteCore(stream);
     }
 }
Exemple #3
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;
			}
		}
Exemple #4
0
		public void Load(BitcoinStream stream)
		{
			using(@lock.LockWrite())
			{
				try
				{
					int height = 0;
					while(true)
					{
						uint256 id = null;
						stream.ReadWrite<uint256>(ref id);
						BlockHeader header = null;
						stream.ReadWrite(ref header);
						if(height == 0)
						{
							_BlocksByHeight.Clear();
							_BlocksById.Clear();
							_Tip = null;
							SetTipNoLock(new ChainedBlock(header, 0));
						}
						else
							SetTipNoLock(new ChainedBlock(header, id, Tip));
						height++;
					}
				}
				catch(EndOfStreamException)
				{
				}
			}
		}
		public void ReadWrite(BitcoinStream stream)
		{
			stream.ReadWrite(ref _chainHeight);
			stream.ReadWrite(ref _chainTipHash);
			stream.ReadWrite(ref _bitmap);
			stream.ReadWrite(ref _outputs);
		}
Exemple #6
0
		public void ReadWrite(BitcoinStream stream)
		{
			using(stream.SerializationTypeScope(SerializationType.Network))
			{
				ReadWriteCore(stream);
			}
		}
Exemple #7
0
		public void bloom_create_insert_serialize()
		{
			BloomFilter filter = new BloomFilter(3, 0.01, 0, BloomFlags.UPDATE_ALL);

			filter.Insert(ParseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8"));
			Assert.True(filter.Contains(ParseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8")), "BloomFilter doesn't contain just-inserted object!");
			// One bit different in first byte
			Assert.True(!filter.Contains(ParseHex("19108ad8ed9bb6274d3980bab5a85c048f0950c8")), "BloomFilter contains something it shouldn't!");

			filter.Insert(ParseHex("b5a2c786d9ef4658287ced5914b37a1b4aa32eee"));
			Assert.True(filter.Contains(ParseHex("b5a2c786d9ef4658287ced5914b37a1b4aa32eee")), "BloomFilter doesn't contain just-inserted object (2)!");

			filter.Insert(ParseHex("b9300670b4c5366e95b2699e8b18bc75e5f729c5"));
			Assert.True(filter.Contains(ParseHex("b9300670b4c5366e95b2699e8b18bc75e5f729c5")), "BloomFilter doesn't contain just-inserted object (3)!");


			var ms = new MemoryStream();
			BitcoinStream bitcoinStream = new BitcoinStream(ms, true);
			bitcoinStream.ReadWrite(filter);

			var expected = ParseHex("03614e9b050000000000000001");


			AssertEx.CollectionEquals(expected, ms.ToArray());
		}
Exemple #8
0
 public override void ReadWriteCore(BitcoinStream stream)
 {
     var old = stream.MaxArraySize;
     stream.MaxArraySize = 5000;
     stream.ReadWrite(ref inventory);
     stream.MaxArraySize = old;
 }
 public byte[] ToBytes()
 {
     var ms = new MemoryStream();
     var stream = new BitcoinStream(ms, true);
     ReadWrite(stream);
     return ms.ToArray();
 }
Exemple #10
0
 public void ReadWrite(BitcoinStream stream)
 {
     var len = new VarInt((ulong)_Bytes.Length);
      stream.ReadWrite(ref len);
     if(!stream.Serializing)
         _Bytes = new byte[len.ToLong()];
     stream.ReadWrite(ref _Bytes);
 }
Exemple #11
0
			public void ReadWrite(BitcoinStream stream)
			{
				stream.ReadWrite(ref _Address);
				stream.ReadWrite(ref source);
				stream.ReadWrite(ref nLastSuccess);
				stream.ReadWrite(ref nAttempts);

			}
Exemple #12
0
		public void ReadWrite(BitcoinStream stream)
		{
			if(Payload == null && stream.Serializing)
				throw new InvalidOperationException("Payload not affected");
			if(stream.Serializing || (!stream.Serializing && !_SkipMagic))
				stream.ReadWrite(ref magic);
			stream.ReadWrite(ref command);
			int length = 0;
			uint checksum = 0;
			bool hasChecksum = false;
			byte[] payloadBytes = stream.Serializing ? GetPayloadBytes(stream.ProtocolVersion, out length) : null;
			length = payloadBytes == null ? 0 : length;
			stream.ReadWrite(ref length);

			if(stream.ProtocolVersion >= ProtocolVersion.MEMPOOL_GD_VERSION)
			{
				if(stream.Serializing)
					checksum = Hashes.Hash256(payloadBytes, 0, length).GetLow32();
				stream.ReadWrite(ref checksum);
				hasChecksum = true;
			}
			if(stream.Serializing)
			{
				stream.ReadWrite(ref payloadBytes, 0, length);
			}
			else
			{
				if(length > 0x02000000) //MAX_SIZE 0x02000000 Serialize.h
				{
					throw new FormatException("Message payload too big ( > 0x02000000 bytes)");
				}

				payloadBytes = _Buffer == null || _Buffer.Length < length ? new byte[length] : _Buffer;
				stream.ReadWrite(ref payloadBytes, 0, length);

				if(hasChecksum)
				{
					if(!VerifyChecksum(checksum, payloadBytes, length))
					{
						if(NodeServerTrace.Trace.Switch.ShouldTrace(TraceEventType.Verbose))
							NodeServerTrace.Trace.TraceEvent(TraceEventType.Verbose, 0, "Invalid message checksum bytes");
						throw new FormatException("Message checksum invalid");
					}
				}
				BitcoinStream payloadStream = new BitcoinStream(payloadBytes);
				payloadStream.CopyParameters(stream);

				var payloadType = PayloadAttribute.GetCommandType(Command);
				var unknown = payloadType == typeof(UnknowPayload);
				if(unknown)
					NodeServerTrace.Trace.TraceEvent(TraceEventType.Warning, 0, "Unknown command received : " + Command);
				object payload = _PayloadObject;
				payloadStream.ReadWrite(payloadType, ref payload);
				if(unknown)
					((UnknowPayload)payload)._Command = Command;
				Payload = (Payload)payload;
			}
		}
Exemple #13
0
 public void ReadWrite(BitcoinStream stream)
 {
     if(stream.ProtocolVersion >= ProtocolVersion.CADDR_TIME_VERSION)
         stream.ReadWrite(ref time);
     stream.ReadWrite(ref service);
     stream.ReadWrite(ref ip);
     using(stream.BigEndianScope())
     {
         stream.ReadWrite(ref port);
     }
 }
Exemple #14
0
		public void ReadWrite(BitcoinStream stream)
		{
			 var len = new VarInt((ulong)_Bytes.Length);
			 stream.ReadWrite(ref len);
			 if(!stream.Serializing)
			 {
				 if(len.ToLong() > (uint)stream.MaxArraySize)
					 throw new ArgumentOutOfRangeException("Array size not big");
				 _Bytes = new byte[len.ToLong()];
			 }
			stream.ReadWrite(ref _Bytes);
		}
Exemple #15
0
			public void ReadWrite(BitcoinStream stream)
			{
				if(stream.Serializing)
				{
					var b = Value.ToBytes();
					stream.ReadWrite(ref b);
				}
				else
				{
					byte[] b = new byte[WIDTH_BYTE];
					stream.ReadWrite(ref b);
					_Value = new uint256(b);
				}
			}
Exemple #16
0
		public override void ReadWriteCore(BitcoinStream stream)
		{
			if(stream.Serializing)
			{
				var heardersOff = headers.Select(h => new BlockHeaderWithTxCount(h)).ToList();
				stream.ReadWrite(ref heardersOff);
			}
			else
			{
				headers.Clear();
				List<BlockHeaderWithTxCount> headersOff = new List<BlockHeaderWithTxCount>();
				stream.ReadWrite(ref headersOff);
				headers.AddRange(headersOff.Select(h => h._Header));
			}
		}
Exemple #17
0
		private AlertPayload[] ReadAlerts()
		{
			List<AlertPayload> alerts = new List<AlertPayload>();
			using(var fs = File.OpenRead("data/alertTests.raw"))
			{
				BitcoinStream stream = new BitcoinStream(fs, false);
				while(stream.Inner.Position != stream.Inner.Length)
				{
					AlertPayload payload = null;
					stream.ReadWrite(ref payload);
					alerts.Add(payload);
				}
			}
			return alerts.ToArray();
		}
Exemple #18
0
		public void ReadWrite(BitcoinStream stream)
		{
			stream.ReadWrite(ref _OutPoint);
			if(stream.Serializing)
			{
				TxOutCompressor compressor = new TxOutCompressor(_Out);
				stream.ReadWrite(ref compressor);
			}
			else
			{
				TxOutCompressor compressor = new TxOutCompressor();
				stream.ReadWrite(ref compressor);
				_Out = compressor.TxOut;
			}
		}
Exemple #19
0
		public void uitnSerializationTests()
		{
			MemoryStream ms = new MemoryStream();
			BitcoinStream stream = new BitcoinStream(ms, true);

			var v = new uint256("00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
			var vless = new uint256("00000000fffffffffffffffffffffffffffffffffffffffffffffffffffffffe");
			var vplus = new uint256("00000001ffffffffffffffffffffffffffffffffffffffffffffffffffffffff");

			stream.ReadWrite(ref v);
			Assert.NotNull(v);

			ms.Position = 0;
			stream = new BitcoinStream(ms, false);

			uint256 v2 = uint256.Zero;
			stream.ReadWrite(ref v2);
			Assert.Equal(v, v2);

			v2 = null;
			ms.Position = 0;
			stream.ReadWrite(ref v2);
			Assert.Equal(v, v2);

			List<uint256> vs = new List<uint256>()
			{
				v,vless,vplus
			};

			ms = new MemoryStream();
			stream = new BitcoinStream(ms, true);
			stream.ReadWrite(ref vs);
			Assert.True(vs.Count == 3);

			ms.Position = 0;
			stream = new BitcoinStream(ms, false);
			List<uint256> vs2 = new List<uint256>();
			stream.ReadWrite(ref vs2);
			Assert.True(vs2.SequenceEqual(vs));

			ms.Position = 0;
			vs2 = null;
			stream.ReadWrite(ref vs2);
			Assert.True(vs2.SequenceEqual(vs));
		}
Exemple #20
0
        public void bloom_create_insert_key()
        {
            string strSecret = "5Kg1gnAjaLfKiwhhPpGS3QfRg2m6awQvaj98JCZBZQ5SuS2F15C";
            BitcoinSecret vchSecret = Network.Main.CreateBitcoinSecret(strSecret);
            var pubkey = vchSecret.Key.PubKey;

            BloomFilter filter = new BloomFilter(2, 0.001, 0, BloomFlags.UPDATE_ALL);
            filter.Insert(pubkey.ToBytes());
            filter.Insert(pubkey.ID.ToBytes());

            var ms = new MemoryStream();
            BitcoinStream bitcoinStream = new BitcoinStream(ms, true);
            bitcoinStream.ReadWrite(filter);

            var expected = ParseHex("038fc16b080000000000000001");

            AssertEx.CollectionEquals(expected, ms.ToArray());
        }
Exemple #21
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);
			}
		}
Exemple #22
0
		public void ReadWrite(BitcoinStream stream)
		{
			if(stream.Serializing)
			{
				ulong n = _Value;
				byte[] tmp = new byte[(_Size * 8 + 6) / 7];
				int len = 0;
				while(true)
				{
					byte a = (byte)(n & 0x7F);
					byte b = (byte)(len != 0 ? 0x80 : 0x00);
					tmp[len] = (byte)(a | b);
					if(n <= 0x7F)
						break;
					n = (n >> 7) - 1;
					len++;
				}
				do
				{
					byte b = tmp[len];
					stream.ReadWrite(ref b);
				} while(len-- != 0);
			}
			else
			{
				ulong n = 0;
				while(true)
				{
					byte chData = 0;
					stream.ReadWrite(ref chData);
					ulong a = (n << 7);
					byte b = (byte)(chData & 0x7F);
					n = (a | b);
					if((chData & 0x80) != 0)
						n++;
					else
						break;
				}
				_Value = n;
			}
		}
		// serialization implementation
		#region IBitcoinSerializable Members

		public void ReadWrite(BitcoinStream stream)
		{
			stream.ReadWrite(ref _TransactionCount);
			stream.ReadWrite(ref _Hashes);
			byte[] vBytes = null;
			if(!stream.Serializing)
			{
				stream.ReadWriteAsVarString(ref vBytes);
				BitWriter writer = new BitWriter();
				for(int p = 0 ; p < vBytes.Length * 8 ; p++)
					writer.Write((vBytes[p / 8] & (1 << (p % 8))) != 0);
				_Flags = writer.ToBitArray();
			}
			else
			{
				vBytes = new byte[(_Flags.Length + 7) / 8];
				for(int p = 0 ; p < _Flags.Length ; p++)
					vBytes[p / 8] |= (byte)(ToByte(_Flags.Get(p)) << (p % 8));
				stream.ReadWriteAsVarString(ref vBytes);
			}
		}
Exemple #24
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);
				}
			}
		}
        private void ReadWrite(BitcoinStream stream)
        {
            if(stream.Serializing)
            {
                stream.ReadWrite((byte)0x32);
                stream.ReadWrite(Flags);
            }
            else
            {
                if(stream.Inner.ReadByte() != 0x32)
                    throw new FormatException("Invalid magic version");
                Flags = (byte)stream.Inner.ReadByte();
            }
            stream.ReadWrite(ref _Nonce);

            if(stream.Serializing)
            {
                uint256 txId = OutPoint.Hash;
                stream.ReadWrite(ref txId);
                uint index = OutPoint.N;
                stream.ReadWrite(ref index);
            }
            else
            {
                uint256 txId = new uint256();
                stream.ReadWrite(ref txId);
                uint index = 0;
                stream.ReadWrite(ref index);
                _OutPoint = new OutPoint(txId, index);
            }

            ulong amount = stream.Serializing ? (ulong)_Amount.Satoshi : 0;
            stream.ReadWrite(ref amount);
            _Amount = Money.Satoshis(amount);

            _Signature = stream.Serializing ? _Signature : new byte[8];
            stream.ReadWrite(ref _Signature);
        }
Exemple #26
0
		public void ReadWrite(BitcoinStream stream)
		{
			if(stream.Serializing)
			{
				uint o = (uint)(nHeight * 2 + (fCoinBase ? 1 : 0));
				stream.ReadWriteAsCompactVarInt(ref o);
				if(nHeight > 0)
					stream.ReadWriteAsCompactVarInt(ref nVersion);
				TxOutCompressor compressor = new TxOutCompressor(txout);
				stream.ReadWrite(ref compressor);
			}
			else
			{
				uint nCode = 0;
				stream.ReadWriteAsCompactVarInt(ref nCode);
				nHeight = nCode / 2;
				fCoinBase = (nCode & 1) != 0;
				if(nHeight > 0)
					stream.ReadWriteAsCompactVarInt(ref nVersion);
				TxOutCompressor compressor = new TxOutCompressor();
				stream.ReadWrite(ref compressor);
				txout = compressor.TxOut;
			}
		}
Exemple #27
0
 public void ReadWrite(BitcoinStream stream)
 {
     stream.ReadWrite(ref _height);
     stream.ReadWrite(ref _header);
 }
Exemple #28
0
		public static Message ReadNext(Stream stream, Network network, ProtocolVersion version, CancellationToken cancellationToken, byte[] buffer, out PerformanceCounter counter)
		{
			BitcoinStream bitStream = new BitcoinStream(stream, false)
			{
				ProtocolVersion = version,
				ReadCancellationToken = cancellationToken
			};

			if(!network.ReadMagic(stream, cancellationToken, true))
				throw new FormatException("Magic incorrect, the message comes from another network");

			Message message = new Message();
			message._Buffer = buffer;
			using(message.SkipMagicScope(true))
			{
				message.Magic = network.Magic;
				message.ReadWrite(bitStream);
			}
			counter = bitStream.Counter;
			return message;
		}
Exemple #29
0
 public void ReadWrite(BitcoinStream stream)
 {
     stream.ReadWriteC(ref _Fee);
     stream.ReadWrite(ref _LockTime);
     stream.ReadWriteC(ref _FulfillKey);
 }
Exemple #30
0
        protected virtual void BuildCoinbase()
        {
            // generate script parts
            var sigScriptInitial      = GenerateScriptSigInitial();
            var sigScriptInitialBytes = sigScriptInitial.ToBytes();

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

            // output transaction
            txOut = (coin.HasMasterNodes) ? CreateMasternodeOutputTransaction() : (coin.HasPayee ? CreatePayeeOutputTransaction() : CreateOutputTransaction());
            if (coin.HasCoinbasePayload)
            {
                //Build txOut with superblock and cold reward payees for DVT
                txOut = CreatePayloadOutputTransaction();
            }
            // build coinbase initial
            using (var stream = new MemoryStream())
            {
                var bs = new BitcoinStream(stream, true);

                // version
                bs.ReadWrite(ref txVersion);

                // // timestamp for POS coins
                if (isPoS && poolConfig.UseP2PK)
                {
                    var timestamp = BlockTemplate.CurTime;
                    bs.ReadWrite(ref timestamp);
                }

                // serialize (simulated) input transaction
                bs.ReadWriteAsVarInt(ref txInputCount);
                bs.ReadWrite(ref sha256Empty);
                bs.ReadWrite(ref txInPrevOutIndex);

                // signature script initial part
                bs.ReadWriteAsVarInt(ref sigScriptLength);
                bs.ReadWrite(ref sigScriptInitialBytes);

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

            // build coinbase final
            using (var stream = new MemoryStream())
            {
                var bs = new BitcoinStream(stream, true);

                // signature script final part
                bs.ReadWrite(ref scriptSigFinalBytes);

                // tx in sequence
                bs.ReadWrite(ref txInSequence);

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

                // misc
                bs.ReadWrite(ref txLockTime);

                // Extension point
                AppendCoinbaseFinal(bs);

                // done
                coinbaseFinal    = stream.ToArray();
                coinbaseFinalHex = coinbaseFinal.ToHexString();
            }
        }
Exemple #31
0
		private void PushDataToStream(byte[] data, Stream result)
		{
			var bitStream = new BitcoinStream(result, true);

			if(Code == OpcodeType.OP_0)
			{
				//OP_0 already pushed
				return;
			}

			if(OpcodeType.OP_1 <= Code && Code <= OpcodeType.OP_16)
			{
				//OP_1 to OP_16 already pushed
				return;
			}
			if(Code == OpcodeType.OP_1NEGATE)
			{
				//OP_1Negate already pushed
				return;
			}

			if(0x01 <= (byte)Code && (byte)Code <= 0x4b)
			{
				//Data length already pushed
			}
			else if(Code == OpcodeType.OP_PUSHDATA1)
			{
				bitStream.ReadWrite((byte)data.Length);
			}
			else if(Code == OpcodeType.OP_PUSHDATA2)
			{
				bitStream.ReadWrite((ushort)data.Length);
			}
			else if(Code == OpcodeType.OP_PUSHDATA4)
			{
				bitStream.ReadWrite((uint)data.Length);
			}
			else
				throw new NotSupportedException("Data length should not be bigger than 0xFFFFFFFF");
			result.Write(data, 0, data.Length);
		}
Exemple #32
0
        // select a block from the candidate blocks in vSortedByTimestamp, excluding
        // already selected blocks in vSelectedBlocks, and with timestamp up to
        // nSelectionIntervalStop.
        private bool SelectBlockFromCandidates(ChainedBlock[] sortedByTimestamp,
                                               Dictionary <uint256, ChainedBlock> mapSelectedBlocks,
                                               long nSelectionIntervalStop, ulong nStakeModifierPrev, out ChainedBlock pindexSelected, out BlockStake blockStakeSelected)
        {
            bool    fSelected = false;
            uint256 hashBest  = 0;

            pindexSelected     = null;
            blockStakeSelected = null;

            for (int i = 0; i < sortedByTimestamp.Length; i++)
            {
                var pindex = sortedByTimestamp[i];

                if (fSelected && pindex.Header.Time > nSelectionIntervalStop)
                {
                    break;
                }

                if (mapSelectedBlocks.ContainsKey(pindex.HashBlock))
                {
                    continue;
                }

                var blockStake = this.stakeChain.Get(pindex.HashBlock);

                // compute the selection hash by hashing its proof-hash and the
                // previous proof-of-stake modifier
                uint256 hashSelection;
                using (var ms = new MemoryStream())
                {
                    var serializer = new BitcoinStream(ms, true);
                    serializer.ReadWrite(blockStake.HashProof);
                    serializer.ReadWrite(nStakeModifierPrev);

                    hashSelection = Hashes.Hash256(ms.ToArray());
                }

                // the selection hash is divided by 2**32 so that proof-of-stake block
                // is always favored over proof-of-work block. this is to preserve
                // the energy efficiency property
                if (blockStake.IsProofOfStake())
                {
                    hashSelection >>= 32;
                }

                if (fSelected && hashSelection < hashBest)
                {
                    hashBest           = hashSelection;
                    pindexSelected     = pindex;
                    blockStakeSelected = blockStake;
                }
                else if (!fSelected)
                {
                    fSelected          = true;
                    hashBest           = hashSelection;
                    pindexSelected     = pindex;
                    blockStakeSelected = blockStake;
                }
            }

            //LogPrint("stakemodifier", "SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString());
            return(fSelected);
        }
Exemple #33
0
 public override void ReadWriteCore(BitcoinStream stream)
 {
     _uTxOutputs = new UTxOutputs();
     stream.ReadWrite(ref _uTxOutputs);
 }
 public void ReadWrite(BitcoinStream stream)
 {
     this.ReadWriteCalls++;
 }
Exemple #35
0
        public void ReadWrite(BitcoinStream stream)
        {
            lock (cs)
            {
                Check();
                if (!stream.Serializing)
                {
                    Clear();
                }
                stream.ReadWrite(ref nVersion);
                stream.ReadWrite(ref nKeySize);
                if (!stream.Serializing && nKeySize != 32)
                {
                    throw new FormatException("Incorrect keysize in addrman deserialization");
                }
                stream.ReadWrite(ref nKey);
                stream.ReadWrite(ref nNew);
                stream.ReadWrite(ref nTried);

                int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT ^ (1 << 30);
                stream.ReadWrite(ref nUBuckets);
                if (nVersion != 0)
                {
                    nUBuckets ^= (1 << 30);
                }
                if (!stream.Serializing)
                {
                    // Deserialize entries from the new table.
                    for (int n = 0; n < nNew; n++)
                    {
                        AddressInfo info = new AddressInfo();
                        info.ReadWrite(stream);
                        mapInfo.Add(n, info);
                        mapAddr[info.Address.Endpoint.Address] = n;
                        info.nRandomPos = vRandom.Count;
                        vRandom.Add(n);
                        if (nVersion != 1 || nUBuckets != ADDRMAN_NEW_BUCKET_COUNT)
                        {
                            // In case the new table data cannot be used (nVersion unknown, or bucket count wrong),
                            // immediately try to give them a reference based on their primary source address.
                            int nUBucket    = info.GetNewBucket(nKey);
                            int nUBucketPos = info.GetBucketPosition(nKey, true, nUBucket);
                            if (vvNew[nUBucket, nUBucketPos] == -1)
                            {
                                vvNew[nUBucket, nUBucketPos] = n;
                                info.nRefCount++;
                            }
                        }
                    }

                    nIdCount = nNew;

                    // Deserialize entries from the tried table.
                    int nLost = 0;
                    for (int n = 0; n < nTried; n++)
                    {
                        AddressInfo info = new AddressInfo();
                        info.ReadWrite(stream);
                        int nKBucket    = info.GetTriedBucket(nKey);
                        int nKBucketPos = info.GetBucketPosition(nKey, false, nKBucket);
                        if (vvTried[nKBucket, nKBucketPos] == -1)
                        {
                            info.nRandomPos = vRandom.Count;
                            info.fInTried   = true;
                            vRandom.Add(nIdCount);
                            mapInfo[nIdCount] = info;
                            mapAddr[info.Address.Endpoint.Address] = nIdCount;
                            vvTried[nKBucket, nKBucketPos]         = nIdCount;
                            nIdCount++;
                        }
                        else
                        {
                            nLost++;
                        }
                    }

                    nTried -= nLost;

                    // Deserialize positions in the new table (if possible).
                    for (int bucket = 0; bucket < nUBuckets; bucket++)
                    {
                        int nSize = 0;
                        stream.ReadWrite(ref nSize);
                        for (int n = 0; n < nSize; n++)
                        {
                            int nIndex = 0;
                            stream.ReadWrite(ref nIndex);
                            if (nIndex >= 0 && nIndex < nNew)
                            {
                                AddressInfo info        = mapInfo[nIndex];
                                int         nUBucketPos = info.GetBucketPosition(nKey, true, bucket);
                                if (nVersion == 1 && nUBuckets == ADDRMAN_NEW_BUCKET_COUNT && vvNew[bucket, nUBucketPos] == -1 && info.nRefCount < ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
                                {
                                    info.nRefCount++;
                                    vvNew[bucket, nUBucketPos] = nIndex;
                                }
                            }
                        }
                    }

                    // Prune new entries with refcount 0 (as a result of collisions).
                    int nLostUnk = 0;
                    foreach (var kv in mapInfo.ToList())
                    {
                        if (kv.Value.fInTried == false && kv.Value.nRefCount == 0)
                        {
                            Delete(kv.Key);
                            nLostUnk++;
                        }
                    }
                }
                else
                {
                    Dictionary <int, int> mapUnkIds = new Dictionary <int, int>();
                    int nIds = 0;
                    foreach (var kv in mapInfo)
                    {
                        mapUnkIds[kv.Key] = nIds;
                        AddressInfo info = kv.Value;
                        if (info.nRefCount != 0)
                        {
                            assert(nIds != nNew);                             // this means nNew was wrong, oh ow
                            info.ReadWrite(stream);
                            nIds++;
                        }
                    }
                    nIds = 0;
                    foreach (var kv in mapInfo)
                    {
                        AddressInfo info = kv.Value;
                        if (info.fInTried)
                        {
                            assert(nIds != nTried);                             // this means nTried was wrong, oh ow
                            info.ReadWrite(stream);
                            nIds++;
                        }
                    }

                    for (int bucket = 0; bucket < ADDRMAN_NEW_BUCKET_COUNT; bucket++)
                    {
                        int nSize = 0;
                        for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++)
                        {
                            if (vvNew[bucket, i] != -1)
                            {
                                nSize++;
                            }
                        }
                        stream.ReadWrite(ref nSize);
                        for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++)
                        {
                            if (vvNew[bucket, i] != -1)
                            {
                                int nIndex = mapUnkIds[vvNew[bucket, i]];
                                stream.ReadWrite(ref nIndex);
                            }
                        }
                    }
                }
                Check();
            }
        }
Exemple #36
0
        public void ReadWrite(BitcoinStream stream)
        {
            if (stream.Serializing)
            {
                uint nMaskSize = 0, nMaskCode = 0;
                this.CalcMaskSize(ref nMaskSize, ref nMaskCode);

                bool fFirst  = this.Outputs.Count > 0 && !this.IsNull(this.Outputs[0]);
                bool fSecond = this.Outputs.Count > 1 && !this.IsNull(this.Outputs[1]);
                uint nCode   = unchecked ((uint)(8 * (nMaskCode - (fFirst || fSecond ? 0 : 1)) + (this.CoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0)));

                // version
                stream.ReadWriteAsVarInt(ref this.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 < this.Outputs.Count; i++)
                    {
                        if (!this.IsNull(this.Outputs[2 + (int)b * 8 + (int)i]))
                        {
                            chAvail |= (byte)(1 << (int)i);
                        }
                    }

                    stream.ReadWrite(ref chAvail);
                }

                // txouts themself
                for (uint i = 0; i < this.Outputs.Count; i++)
                {
                    if (!this.IsNull(this.Outputs[(int)i]))
                    {
                        var compressedTx = new TxOutCompressor(this.Outputs[(int)i]);
                        stream.ReadWrite(ref compressedTx);
                    }
                }
                // coinbase height
                stream.ReadWriteAsVarInt(ref this.nHeight);

                if (stream.ConsensusFactory is PosConsensusFactory)
                {
                    stream.ReadWrite(ref this.fCoinStake);
                    stream.ReadWrite(ref this.nTime);
                }
            }
            else
            {
                uint nCode = 0;

                // version
                stream.ReadWriteAsVarInt(ref this.nVersion);

                //// header code
                stream.ReadWriteAsVarInt(ref nCode);
                this.CoinBase = (nCode & 1) != 0;

                var 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
                this.Outputs = Enumerable.Range(0, vAvail.Count).Select(_ => NullTxOut).ToList();
                for (uint i = 0; i < vAvail.Count; i++)
                {
                    if (vAvail[(int)i])
                    {
                        var compressed = new TxOutCompressor();
                        stream.ReadWrite(ref compressed);
                        this.Outputs[(int)i] = compressed.TxOut;
                    }
                }

                //// coinbase height
                stream.ReadWriteAsVarInt(ref this.nHeight);

                if (stream.ConsensusFactory is PosConsensusFactory)
                {
                    stream.ReadWrite(ref this.fCoinStake);
                    stream.ReadWrite(ref this.nTime);
                }

                this.Cleanup();
                this.UpdateValue();
            }
        }
 public override void ReadWriteCore(BitcoinStream stream)
 {
     stream.ReadWrite(ref _Data);
 }
Exemple #38
0
        public async Task <BroadcastResult> Broadcast(
            string cryptoCode,
            [ModelBinder(BinderType = typeof(DestinationModelBinder))]
            DerivationStrategyBase extPubKey)
        {
            var tx     = new Transaction();
            var stream = new BitcoinStream(Request.Body, false);

            tx.ReadWrite(stream);
            var network = GetNetwork(cryptoCode);
            var waiter  = this.Waiters.GetWaiter(network);

            if (!waiter.RPCAvailable)
            {
                throw RPCUnavailable();
            }
            var          repo  = RepositoryProvider.GetRepository(network);
            var          chain = ChainProvider.GetChain(network);
            RPCException rpcEx = null;

            try
            {
                await waiter.RPC.SendRawTransactionAsync(tx);

                return(new BroadcastResult(true));
            }
            catch (RPCException ex)
            {
                rpcEx = ex;
                Logs.Explorer.LogInformation($"{network.CryptoCode}: Transaction {tx.GetHash()} failed to broadcast (Code: {ex.RPCCode}, Message: {ex.RPCCodeMessage}, Details: {ex.Message} )");
                if (extPubKey != null && ex.Message.StartsWith("Missing inputs", StringComparison.OrdinalIgnoreCase))
                {
                    Logs.Explorer.LogInformation($"{network.CryptoCode}: Trying to broadcast unconfirmed of the wallet");
                    var transactions = GetAnnotatedTransactions(repo, chain, extPubKey);
                    foreach (var existing in transactions.UnconfirmedTransactions.Values)
                    {
                        try
                        {
                            await waiter.RPC.SendRawTransactionAsync(existing.Record.Transaction);
                        }
                        catch { }
                    }

                    try
                    {
                        await waiter.RPC.SendRawTransactionAsync(tx);

                        Logs.Explorer.LogInformation($"{network.CryptoCode}: Broadcast success");
                        return(new BroadcastResult(true));
                    }
                    catch (RPCException)
                    {
                        Logs.Explorer.LogInformation($"{network.CryptoCode}: Transaction {tx.GetHash()} failed to broadcast (Code: {ex.RPCCode}, Message: {ex.RPCCodeMessage}, Details: {ex.Message} )");
                    }
                }
                return(new BroadcastResult(false)
                {
                    RPCCode = rpcEx.RPCCode,
                    RPCCodeMessage = rpcEx.RPCCodeMessage,
                    RPCMessage = rpcEx.Message
                });
            }
        }
Exemple #39
0
 public override void ReadWriteCore(BitcoinStream stream)
 {
     stream.ReadWrite(ref this.inventory);
 }
		public void ReadWrite(BitcoinStream bitcoinStream)
		{
			bitcoinStream.ReadWrite(ref _proofBody);
			bitcoinStream.ReadWrite(ref _proofSignature);
		}
Exemple #41
0
        private static ulong ReadLEB128(BitcoinStream stream)
        {
            ulong value = 0;

            value = stream.ReadWrite((byte)0);
            if ((value & 128uL) == 0uL)
            {
                return(value);
            }
            value &= 127uL;
            ulong chunk = stream.ReadWrite((byte)0);

            value |= (chunk & 127uL) << 7;
            if ((chunk & 128uL) == 0uL)
            {
                return(value);
            }
            chunk  = stream.ReadWrite((byte)0);
            value |= (chunk & 127uL) << 14;
            if ((chunk & 128uL) == 0uL)
            {
                return(value);
            }
            chunk  = stream.ReadWrite((byte)0);
            value |= (chunk & 127uL) << 21;
            if ((chunk & 128uL) == 0uL)
            {
                return(value);
            }
            chunk  = stream.ReadWrite((byte)0);
            value |= (chunk & 127uL) << 28;
            if ((chunk & 128uL) == 0uL)
            {
                return(value);
            }
            chunk  = stream.ReadWrite((byte)0);
            value |= (chunk & 127uL) << 35;
            if ((chunk & 128uL) == 0uL)
            {
                return(value);
            }
            chunk  = stream.ReadWrite((byte)0);
            value |= (chunk & 127uL) << 42;
            if ((chunk & 128uL) == 0uL)
            {
                return(value);
            }
            chunk  = stream.ReadWrite((byte)0);
            value |= (chunk & 127uL) << 49;
            if ((chunk & 128uL) == 0uL)
            {
                return(value);
            }
            chunk  = stream.ReadWrite((byte)0);
            value |= (chunk & 127uL) << 56;
            if ((chunk & 128uL) == 0uL)
            {
                return(value);
            }
            chunk  = stream.ReadWrite((byte)0);
            value |= chunk << 63;
            if ((chunk & 18446744073709551614uL) != 0uL)
            {
                throw new FormatException("Invalid LEB128 number");
            }
            return(value);
        }
Exemple #42
0
        // Stratis kernel protocol
        // coinstake must meet hash target according to the protocol:
        // kernel (input 0) must meet the formula
        //     hash(nStakeModifier + txPrev.block.nTime + txPrev.nTime + txPrev.vout.hash + txPrev.vout.n + nTime) < bnTarget * nWeight
        // this ensures that the chance of getting a coinstake is proportional to the
        // amount of coins one owns.
        // The reason this hash is chosen is the following:
        //   nStakeModifier: scrambles computation to make it very difficult to precompute
        //                   future proof-of-stake
        //   txPrev.block.nTime: prevent nodes from guessing a good timestamp to
        //                       generate transaction for future advantage,
        //                       obsolete since v3
        //   txPrev.nTime: slightly scrambles computation
        //   txPrev.vout.hash: hash of txPrev, to reduce the chance of nodes
        //                     generating coinstake at the same time
        //   txPrev.vout.n: output number of txPrev, to reduce the chance of nodes
        //                  generating coinstake at the same time
        //   nTime: current timestamp
        //   block/tx hash should not be used here as they can be generated in vast
        //   quantities so as to generate blocks faster, degrading the system back into
        //   a proof-of-work situation.
        //
        private void CheckStakeKernelHashV2(ContextInformation context, ChainedBlock pindexPrev, uint nBits, uint nTimeBlockFrom,
                                            BlockStake prevBlockStake, UnspentOutputs txPrev, OutPoint prevout, uint nTimeTx)
        {
            if (nTimeTx < txPrev.Time)
            {
                ConsensusErrors.StakeTimeViolation.Throw();
            }

            // Base target
            var bnTarget = new Target(nBits).ToBigInteger();

            // Weighted target
            var nValueIn = txPrev._Outputs[prevout.N].Value.Satoshi;
            var bnWeight = BigInteger.ValueOf(nValueIn);

            bnTarget = bnTarget.Multiply(bnWeight);

            // todo: investigate this issue, is the convertion to uint256 similar to the c++ implementation
            //context.Stake.TargetProofOfStake =  Target.ToUInt256(bnTarget,);

            var     nStakeModifier       = prevBlockStake.StakeModifier;   //pindexPrev.Header.BlockStake.StakeModifier;
            uint256 bnStakeModifierV2    = prevBlockStake.StakeModifierV2; //pindexPrev.Header.BlockStake.StakeModifierV2;
            int     nStakeModifierHeight = pindexPrev.Height;
            var     nStakeModifierTime   = pindexPrev.Header.Time;

            // Calculate hash
            using (var ms = new MemoryStream())
            {
                var serializer = new BitcoinStream(ms, true);
                if (IsProtocolV3((int)nTimeTx))
                {
                    serializer.ReadWrite(bnStakeModifierV2);
                }
                else
                {
                    serializer.ReadWrite(nStakeModifier);
                    serializer.ReadWrite(nTimeBlockFrom);
                }

                serializer.ReadWrite(txPrev.Time);
                serializer.ReadWrite(prevout.Hash);
                serializer.ReadWrite(prevout.N);
                serializer.ReadWrite(nTimeTx);

                context.Stake.HashProofOfStake = Hashes.Hash256(ms.ToArray());
            }

            //LogPrintf("CheckStakeKernelHash() : using modifier 0x%016x at height=%d timestamp=%s for block from timestamp=%s\n",
            //	nStakeModifier, nStakeModifierHeight,
            //	DateTimeStrFormat(nStakeModifierTime),

            //	DateTimeStrFormat(nTimeBlockFrom));

            //LogPrintf("CheckStakeKernelHash() : check modifier=0x%016x nTimeBlockFrom=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
            //	nStakeModifier,
            //	nTimeBlockFrom, txPrev.nTime, prevout.n, nTimeTx,
            //	hashProofOfStake.ToString());

            // Now check if proof-of-stake hash meets target protocol
            var hashProofOfStakeTarget = new BigInteger(context.Stake.HashProofOfStake.ToBytes(false));

            if (hashProofOfStakeTarget.CompareTo(bnTarget) > 0)
            {
                ConsensusErrors.StakeHashInvalidTarget.Throw();
            }

            //  if (fDebug && !fPrintProofOfStake)
            //  {
            //		LogPrintf("CheckStakeKernelHash() : using modifier 0x%016x at height=%d timestamp=%s for block from timestamp=%s\n",
            //		nStakeModifier, nStakeModifierHeight,
            //		DateTimeStrFormat(nStakeModifierTime),

            //		DateTimeStrFormat(nTimeBlockFrom));

            //		LogPrintf("CheckStakeKernelHash() : pass modifier=0x%016x nTimeBlockFrom=%u nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
            //		nStakeModifier,
            //		nTimeBlockFrom, txPrev.nTime, prevout.n, nTimeTx,
            //		hashProofOfStake.ToString());
            //  }
        }
Exemple #43
0
 public virtual void ReadWriteCore(BitcoinStream stream)
 {
 }
Exemple #44
0
 public override void ReadWriteCore(BitcoinStream stream)
 {
     stream.ReadWrite(ref this.preferHeaderAndIDs);
     stream.ReadWrite(ref this.version);
 }
Exemple #45
0
 public void ReadWrite(BitcoinStream stream)
 {
     stream.ReadWriteAsVarString(ref _Data);
 }
Exemple #46
0
 public void ReadWrite(BitcoinStream stream)
 {
     stream.ReadWrite(ref _version);
     stream.ReadWrite(ref _height);
     stream.ReadWrite(ref _txOut);
 }
 public void ReadFeeEstimates(BitcoinStream stream)
 {
 }
Exemple #48
0
 public override void ReadWriteCore(BitcoinStream stream)
 {
     stream.ReadWrite(ref version);
     stream.ReadWrite(ref blockLocators);
     stream.ReadWrite(ref hashStop);
 }
Exemple #49
0
 public override void ReadWrite(BitcoinStream stream)
 {
     base.ReadWrite(stream);
     stream.ReadWrite(ref auxPow);
 }
 public void WriteFeeEstimates(BitcoinStream stream)
 {
 }
Exemple #51
0
        public void ReadWrite(BitcoinStream stream)
        {
            if ((this.Payload == null) && stream.Serializing)
            {
                throw new InvalidOperationException("Payload not affected");
            }

            if (stream.Serializing || (!stream.Serializing && !this.skipMagic))
            {
                stream.ReadWrite(ref this.magic);
            }

            stream.ReadWrite(ref this.command);
            int  length      = 0;
            uint checksum    = 0;
            bool hasChecksum = false;

            byte[] payloadBytes = stream.Serializing ? this.GetPayloadBytes(stream.ConsensusFactory, out length) : null;
            length = payloadBytes == null ? 0 : length;
            stream.ReadWrite(ref length);

            if (stream.ProtocolVersion >= ProtocolVersion.MEMPOOL_GD_VERSION)
            {
                if (stream.Serializing)
                {
                    checksum = Hashes.Hash256(payloadBytes, 0, length).GetLow32();
                }

                stream.ReadWrite(ref checksum);
                hasChecksum = true;
            }

            if (stream.Serializing)
            {
                stream.ReadWrite(ref payloadBytes, 0, length);
            }
            else
            {
                // MAX_SIZE 0x02000000 Serialize.h.
                if (length > 0x02000000)
                {
                    throw new FormatException("Message payload too big ( > 0x02000000 bytes)");
                }

                payloadBytes = new byte[length];
                stream.ReadWrite(ref payloadBytes, 0, length);

                if (hasChecksum)
                {
                    if (!VerifyChecksum(checksum, payloadBytes, length))
                    {
                        if (NodeServerTrace.Trace.Switch.ShouldTrace(TraceEventType.Verbose))
                        {
                            NodeServerTrace.Trace.TraceEvent(TraceEventType.Verbose, 0, "Invalid message checksum bytes");
                        }
                        throw new FormatException("Message checksum invalid");
                    }
                }

                using (var ms = new MemoryStream(payloadBytes))
                {
                    var payloadStream = new BitcoinStream(ms, false)
                    {
                        ConsensusFactory = stream.ConsensusFactory
                    };

                    payloadStream.CopyParameters(stream);

                    Type payloadType = this.payloadProvider.GetCommandType(this.Command);
                    bool unknown     = payloadType == typeof(UnknowPayload);
                    if (unknown)
                    {
                        NodeServerTrace.Trace.TraceEvent(TraceEventType.Warning, 0, "Unknown command received : " + this.Command);
                    }

                    object payload = this.payloadObject;
                    payloadStream.ReadWrite(payloadType, ref payload);
                    if (unknown)
                    {
                        ((UnknowPayload)payload).command = this.Command;
                    }

                    this.Payload = (Payload)payload;
                }
            }
        }
Exemple #52
0
 public override void ReadWriteCore(BitcoinStream stream)
 {
     stream.ReadWrite(ref this.addr_list);
 }
 // Write state of estimation data to a file
 public void Write(BitcoinStream stream)
 {
 }
Exemple #54
0
 public override void ReadWrite(BitcoinStream stream)
 {
     base.ReadWrite(stream);
 }
		public override void ReadWriteCore(BitcoinStream stream)
		{
			stream.ReadWrite(ref type);
			stream.ReadWrite(ref hash);
		}
Exemple #56
0
 public override void ReadWriteCore(BitcoinStream stream)
 {
     stream.ReadWrite(ref type);
     stream.ReadWrite(ref hash);
 }
Exemple #57
0
		internal byte[] ReadData(Stream stream)
		{
			uint len = 0;
			BitcoinStream bitStream = new BitcoinStream(stream, false);
			if(Code == 0)
				return new byte[0];

			if((byte)OpcodeType.OP_1 <= (byte)Code && (byte)Code <= (byte)OpcodeType.OP_16)
			{
				return new byte[] { (byte)(Code - OpcodeType.OP_1 + 1) };
			}

			if(Code == OpcodeType.OP_1NEGATE)
			{
				return new byte[] { 0x81 };
			}

			try
			{
				if(0x01 <= (byte)Code && (byte)Code <= 0x4b)
					len = (uint)Code;
				else if(Code == OpcodeType.OP_PUSHDATA1)
					len = bitStream.ReadWrite((byte)0);
				else if(Code == OpcodeType.OP_PUSHDATA2)
					len = bitStream.ReadWrite((ushort)0);
				else if(Code == OpcodeType.OP_PUSHDATA4)
					len = bitStream.ReadWrite((uint)0);
				else
				{
					IsInvalid = true;
					return new byte[0];
				}


				byte[] data = null;

				if(len <= MAX_SCRIPT_ELEMENT_SIZE) //Most of the time
				{
					data = new byte[len];
					var readen = stream.Read(data, 0, data.Length);
					if(readen != data.Length)
					{
						IsInvalid = true;
						return new byte[0];
					}
				}
				else //Mitigate against a big array allocation
				{
					List<byte> bytes = new List<byte>();
					for(int i = 0 ; i < len ; i++)
					{
						var b = stream.ReadByte();
						if(b < 0)
						{
							IsInvalid = true;
							return new byte[0];
						}
						bytes.Add((byte)b);
					}
					data = bytes.ToArray();
				}
				return data;

			}
			catch(EndOfStreamException)
			{
				IsInvalid = true;
				return new byte[0];
			}
		}
 public void ReadWrite(BitcoinStream stream)
 {
     stream.ReadWrite(ref _IndexesSalt);
     stream.ReadWrite(ref _FakeIndexes);
     stream.ReadWriteC(ref _Salts);
 }
 /// <summary>
 /// Does a readwrite to the stream of this persistence entry.
 /// </summary>
 /// <param name="stream">Stream to do readwrite to.</param>
 public void ReadWrite(BitcoinStream stream)
 {
     stream.ReadWrite(ref this.tx);
     stream.ReadWriteAsCompactVarInt(ref this.time);
     stream.ReadWriteAsCompactVarInt(ref this.feeDelta);
 }
Exemple #60
0
 public override void ReadWriteCore(BitcoinStream stream)
 {
     stream.ReadWrite(ref this.headers);
 }