コード例 #1
0
ファイル: VarIntTest.cs プロジェクト: Tsunami-ide/Bitcoin
 public void TestShorts()
 {
     var a = new VarInt(64000);
     Assert.AreEqual(3, a.SizeInBytes);
     Assert.AreEqual(3, a.Encode().Length);
     Assert.AreEqual(64000, new VarInt(a.Encode(), 0).Value);
 }
コード例 #2
0
ファイル: VarIntTest.cs プロジェクト: Tsunami-ide/Bitcoin
 public void TestBytes()
 {
     var a = new VarInt(10);
     Assert.AreEqual(1, a.SizeInBytes);
     Assert.AreEqual(1, a.Encode().Length);
     Assert.AreEqual(10, new VarInt(a.Encode(), 0).Value);
 }
コード例 #3
0
ファイル: VarIntTest.cs プロジェクト: Tsunami-ide/Bitcoin
 public void TestInts()
 {
     var a = new VarInt(0xAABBCCDD);
     Assert.AreEqual(5, a.SizeInBytes);
     Assert.AreEqual(5, a.Encode().Length);
     var bytes = a.Encode();
     Assert.AreEqual(0xAABBCCDD, new VarInt(bytes, 0).Value);
 }
コード例 #4
0
ファイル: VarIntTest.cs プロジェクト: Tsunami-ide/Bitcoin
 public void TestLong()
 {
     var a = new VarInt(0xCAFEBABEDEADBEEF);
     Assert.AreEqual(9, a.SizeInBytes);
     Assert.AreEqual(9, a.Encode().Length);
     var bytes = a.Encode();
     Assert.AreEqual(0xCAFEBABEDEADBEEF, new VarInt(bytes, 0).Value);
 }
コード例 #5
0
ファイル: IBattleInfo.cs プロジェクト: PokeD/PokeD.Core
        public IBattleInfo FromReader(ProtobufDataReader reader)
        {
            Opponent_0 = reader.Read(Opponent_0);
            Opponent_1 = reader.Read(Opponent_1);
            Opponent_2 = reader.Read(Opponent_1);
            Opponent_3 = reader.Read(Opponent_1);
            Opponent_4 = reader.Read(Opponent_1);
            Opponent_5 = reader.Read(Opponent_1);

            return this;
        }
コード例 #6
0
		public void Write() {
			foreach(var number in Numbers) {
				using(MemoryStream stream = new MemoryStream()) {
					using(BinaryWriter writer = new BinaryWriter(stream)) {
						VarInt v = new VarInt(number.Item2);
						v.Write(writer);

						Assert.AreEqual(number.Item1, stream.ToArray());
					}
				}
			}
		}
コード例 #7
0
 public ClientSettings(
     [DataLengthConstraint(Max = 16)] Utf8String locale,
     sbyte viewDistance,
     VarInt chatMode,
     bool chatColors,
     byte displayedSkinParts,
     VarInt mainHand)
 {
     Locale             = locale ?? throw new ArgumentNullException(nameof(locale));
     ViewDistance       = viewDistance;
     ChatMode           = chatMode;
     ChatColors         = chatColors;
     DisplayedSkinParts = displayedSkinParts;
     MainHand           = mainHand;
 }
コード例 #8
0
ファイル: Inv.cs プロジェクト: xbluckly/bitcoin-lib
        public void ReadFromPayload(byte[] data, int offset)
        {
            Count = new VarInt(0);
            Count.ReadFromPayload(data, offset);
            Inventory = new Inventory[Count];

            //read all
            for (var x = 0; x < Count; x++)
            {
                var ni = new Inventory();
                ni.ReadFromPayload(data, offset + Count.Size + (36 * x));

                Inventory[x] = ni;
            }
        }
コード例 #9
0
        public AddressMessage(byte[] messagePayload)
            : base("addr", messagePayload)
        {
            int startIndex = 0;

            int addressesCount = VarInt.GetInt32(
                Payload,
                ref startIndex);

            for (int i = 0; i < addressesCount; i++)
            {
                NetworkAddresses.Add(
                    NetworkAddress.ParseAddress(
                        Payload, ref startIndex));
            }
        }
コード例 #10
0
ファイル: Addr.cs プロジェクト: xbluckly/bitcoin-lib
        public void ReadFromPayload(byte[] data, int offset)
        {
            IpCount = new VarInt(0);
            IpCount.ReadFromPayload(data, offset);

            var ipOffset = offset + IpCount.Size;

            Ips = new IP[IpCount];
            for (var x = 0; x < IpCount; x++)
            {
                var ip = new IP();
                ip.ReadFromPayload(data, ipOffset);
                Ips[x]    = ip;
                ipOffset += ip.Size;
            }
        }
コード例 #11
0
        public static int GetChunkDataLength <TPalette>(TPalette palette)
            where TPalette : IBlockPalette
        {
            int length = 0;

            length += sizeof(short);
            length += sizeof(byte);
            length += palette.GetEncodedSize();

            int longCount = GetUnderlyingDataLength(UnderlyingDataSize, palette.BitsPerBlock);

            length += VarInt.GetEncodedSize(longCount);
            length += longCount * sizeof(ulong);

            return(length);
        }
コード例 #12
0
        public GetDataMessage(List <Inventory> inventories)
            : base("getdata")
        {
            Inventories = inventories;

            List <byte> payload = new List <byte>();

            payload.AddRange(VarInt.GetBytes(Inventories.Count()));

            for (int i = 0; i < Inventories.Count(); i++)
            {
                payload.AddRange(Inventories.ElementAt(i).GetBytes());
            }

            Payload = payload.ToArray();
        }
コード例 #13
0
ファイル: O5MReader.cs プロジェクト: ringostarr80/O5M.NET
        private void ParseTagsData(
            byte[] data,
            OSMElement element,
            ref int bufferOffset
#if DEBUG
            , ElementDebugInfos debugInfos
#endif
            )
        {
            var unreadBytes = data.Length - bufferOffset;

            while (unreadBytes > 0)
            {
                if (data[bufferOffset] != 0)
                {
#if DEBUG
                    var keyValuePosition = (uint)bufferOffset + 1;
#endif
                    var storedPosition = VarInt.ParseUInt32(data, ref bufferOffset);
#if DEBUG
                    debugInfos.Add(keyValuePosition, "start of stored 'key/value'-pair (" + storedPosition + ").");
#endif
                    var tag = this._storedStringPairs[(int)storedPosition - 1];
                    element.Tags.Add(Encoding.UTF8.GetString(tag.Key), Encoding.UTF8.GetString(tag.Value));
                }
                else
                {
#if DEBUG
                    var keyValuePosition = (uint)bufferOffset + 1;
#endif
                    var tag = StringPair.ParseToByteArrayPair(data, ref bufferOffset);
#if DEBUG
                    debugInfos.Add(keyValuePosition, "start of raw 'key/value'-pair.");
#endif
                    if (tag.HasValue)
                    {
                        var tagValue = tag.Value;
                        element.Tags.Add(Encoding.UTF8.GetString(tagValue.Key), Encoding.UTF8.GetString(tagValue.Value));
                        if (tagValue.Key.Length + tagValue.Value.Length <= 250)
                        {
                            this._storedStringPairs.Insert(0, tagValue);
                        }
                    }
                }
                unreadBytes = data.Length - bufferOffset;
            }
        }
コード例 #14
0
ファイル: MinecraftPacket.cs プロジェクト: dskprt/nylium
        public MinecraftPacket(MinecraftClient client, Stream stream)
        {
            Client = client;
            Data   = new MinecraftStream((RecyclableMemoryStream)RMSManager.Get().GetStream(GetType().FullName));

            Length = Client.CompressionEnabled ? (int)stream.Length : new VarInt(stream).Value;

            long _pos = stream.Position;

            Id = new VarInt(stream).Value;

            byte[] data = new byte[Length - (stream.Position - _pos)];
            stream.Read(data, 0, data.Length);

            Data.Write(data);
            Data.Seek(0, SeekOrigin.Begin);
        }
コード例 #15
0
        public override ProtobufPacket ReadPacket(ProtobufDataReader reader)
        {
            EntityID    = reader.Read(EntityID);
            PlayerUUID  = reader.Read(PlayerUUID);
            PlayerName  = reader.Read(PlayerName);
            Data        = reader.Read(Data);
            X           = reader.Read(X);
            Y           = reader.Read(Y);
            Z           = reader.Read(Z);
            Yaw         = reader.Read(Yaw);
            Pitch       = reader.Read(Pitch);
            HeadPitch   = reader.Read(HeadPitch);
            CurrentItem = reader.Read(CurrentItem);
            Metadata    = reader.Read(Metadata);

            return(this);
        }
コード例 #16
0
        /// <summary>
        /// Tries to read a variable integer from the stream.
        /// </summary>
        /// <param name="output">A VarInt that will be set to the output.</param>
        /// <returns>A bool that indicates success.</returns>
        internal bool TryReadVarInt(out VarInt output)
        {
            bool returnValue = false;

            // Defaults
            output = null;

            try
            {
                output      = ReadVarInt();
                returnValue = true;
            }
            catch (Exception)
            { }

            return(returnValue);
        }
コード例 #17
0
ファイル: Reject.cs プロジェクト: xbluckly/bitcoin-lib
        public void ReadFromPayload(byte[] data, int offset)
        {
            MessageLength = new VarInt(0);
            MessageLength.ReadFromPayload(data, offset);

            Message = Encoding.ASCII.GetString(data, offset + MessageLength.Size, MessageLength);
            Code    = data[offset + MessageLength + MessageLength.Size];

            ReasonLength = new VarInt(0);
            ReasonLength.ReadFromPayload(data, offset + MessageLength + MessageLength.Size + 1);

            Reason = Encoding.ASCII.GetString(data, offset + MessageLength + MessageLength.Size + 1 + ReasonLength.Size, ReasonLength);
            var of = offset + MessageLength + MessageLength.Size + 1 + ReasonLength.Size + ReasonLength;

            Extra = new byte[data.Length - of]; // ew no length = we have to rely on the length of the buffer (reading more "Extra" than we should)
            Buffer.BlockCopy(data, of, Extra, 0, Extra.Length);
        }
コード例 #18
0
        public override void BitcoinSerializeToStream(Stream stream)
        {
            if (_scriptBytes != null)
            {
                Utilities.Uint64ToByteStreamLe(Value, stream);
                // TODO: Move script serialization into the Script class, where it belongs.
                Byte[] scriptLengthBytes = new VarInt((ulong)_scriptBytes.Length).Encode();
                stream.Write(scriptLengthBytes, 0, scriptLengthBytes.Length);
                stream.Write(_scriptBytes, 0, _scriptBytes.Length);
            }
            else
            {
#if (DEBUG)
                Console.WriteLine("Script Bytes were null so no script to serialize :(");
#endif
            }
        }
コード例 #19
0
        public VersionMessage(ShortNetworkAddress recipientAddress,
                              ShortNetworkAddress senderAddress)
        {
            Header           = new Header("version");
            ProtocolVersion  = 70002;
            Services         = 1;
            Timestamp        = BitcoinHelper.GetCurrentTimeStamp();
            RecipientAddress = recipientAddress;
            SenderAddress    = senderAddress;
            Nonce            = 0;
            UserAgent        = "/MikoleuszBlogBitcoinTinyClient:1.0/";
            UserAgentLength  = new VarInt(Convert.ToUInt64(UserAgent.Length));
            StartHeight      = 460650;
            Relay            = true;

            ComputeHeader();
        }
コード例 #20
0
        public override ProtobufPacket ReadPacket(ProtobufDataReader reader)
        {
            EntityID  = reader.Read(EntityID);
            Type      = reader.Read(Type);
            X         = reader.Read(X);
            Y         = reader.Read(Y);
            Z         = reader.Read(Z);
            Yaw       = reader.Read(Yaw);
            Pitch     = reader.Read(Pitch);
            HeadPitch = reader.Read(HeadPitch);
            VelocityX = reader.Read(VelocityX);
            VelocityY = reader.Read(VelocityY);
            VelocityZ = reader.Read(VelocityZ);
            Metadata  = reader.Read(Metadata);

            return(this);
        }
コード例 #21
0
        static private void Int64ToVarInt(ulong n, ref VarInt varint)
        {
            // Write an i64 as a varint. Results in 1-10 bytes on the wire.
            varint.count = 0;
            Debug.Assert(varint.bytes.Length >= 10);

            while (true)
            {
                if ((n & ~(ulong)0x7FL) == 0)
                {
                    varint.bytes[varint.count++] = (byte)n;
                    break;
                }
                varint.bytes[varint.count++] = (byte)((n & 0x7F) | 0x80);
                n >>= 7;
            }
        }
コード例 #22
0
#pragma warning disable CS0114 // '“UniversalContract.ReadWrite(Serialize)”隐藏继承的成员“SerializeObject.ReadWrite(Serialize)”。若要使当前成员重写该实现,请添加关键字 override。否则,添加关键字 new。
        public void ReadWrite(Serialize stream)
#pragma warning restore CS0114 // '“UniversalContract.ReadWrite(Serialize)”隐藏继承的成员“SerializeObject.ReadWrite(Serialize)”。若要使当前成员重写该实现,请添加关键字 override。否则,添加关键字 new。
        {
            var len = new VarInt((ulong)_DestBytes.Length);

            stream.ReadWrite(ref len);

            stream.ReadWrite(ref Upgradable);

            byte[] memo;
            byte[] abi;

            if (stream.Serializing)
            {
                stream.ReadWrite(new VarInt((ulong)Code.Length));
                stream.ReadWrite(ref Code);

                memo = Encoding.UTF8.GetBytes(Memo);
                stream.ReadWrite(new VarInt((ulong)memo.Length));
                stream.ReadWrite(ref memo);

                abi = Encoding.UTF8.GetBytes(Abi);
                stream.ReadWrite(new VarInt((ulong)abi.Length));
                stream.ReadWrite(ref abi);
            }
            else
            {
                var codeLen = new VarInt(0);
                stream.ReadWrite(ref codeLen);
                Code = new byte[codeLen.ToLong()];
                stream.ReadWrite(ref Code);

                var memoLen = new VarInt(0);
                stream.ReadWrite(ref memoLen);
                memo = new byte[codeLen.ToLong()];
                stream.ReadWrite(ref memo);

                var abiLen = new VarInt(0);
                stream.ReadWrite(ref abiLen);
                abi = new byte[codeLen.ToLong()];
                stream.ReadWrite(ref abi);

                Memo = Encoding.UTF8.GetString(memo);
                Abi  = Encoding.UTF8.GetString(abi);
            }
        }
コード例 #23
0
 public ClientPlayerBlockPlacement(
     VarInt hand,
     Position location,
     VarInt face,
     float cursorPositionX,
     float cursorPositionY,
     float cursorPositionZ,
     bool insideBlock)
 {
     Hand            = hand.AsEnum <HandId>();
     Location        = location;
     Face            = face.AsEnum <FaceDirection>();
     CursorPositionX = cursorPositionX;
     CursorPositionY = cursorPositionY;
     CursorPositionZ = cursorPositionZ;
     InsideBlock     = insideBlock;
 }
コード例 #24
0
        public GetDataMessage(NetworkMessage message)
            : base("getdata", message.Payload)
        {
            int startIndex = 0;

            int inventoryCount = VarInt.GetInt32(
                Payload,
                ref startIndex);

            for (int i = 0; i < inventoryCount; i += 1)
            {
                Inventories.Add(
                    Inventory.Parse(
                        Payload,
                        ref startIndex));
            }
        }
コード例 #25
0
        public void TestVarIntParseInt64()
        {
            using (var memoryStream = new MemoryStream()) {
                memoryStream.WriteByte(0xAC);
                memoryStream.WriteByte(0x02);
                memoryStream.Position = 0;
                var result = VarInt.ParseUInt64(memoryStream);
                Assert.AreEqual(300, result);

                memoryStream.Position = 0;
                memoryStream.WriteByte(0x96);
                memoryStream.WriteByte(0x01);
                memoryStream.Position = 0;
                result = VarInt.ParseUInt64(memoryStream);
                Assert.AreEqual(150, result);
            }
        }
コード例 #26
0
        private void NetworkLoop()
        {
            _server.Start();
            while (!TridentMc.Instance.State.IsShuttingDown)
            {
                Thread.Sleep(1);
                foreach (var session in Sessions)
                {
                    while (session.PacketBuffer.Count > 0)
                    {
                        var packet = session.PacketBuffer.Dequeue();

                        if (session.UsesCompression)
                        {
                            throw new NotYetImplemented("Compression isn't implemented yet");
                        }
                        else
                        {
                            var packetId = VarInt.Decode(packet, out packet);
                            Log.Debug("[{SessionId}] Packet {PacketId} with state being {State}", session.Id, packetId, session.ConnectionState);

                            var serverPacket = _packetManager.CreateServerPacket(session.ConnectionState, packetId, packet);
                            if (serverPacket == null)
                            {
                                Log.Debug("[{SessionId}] -> Unknown packet", session.Id);
                                session.Disconnect();
                                break;
                            }

                            Type     packetReceivedType = typeof(PacketReceived <>).MakeGenericType(serverPacket.GetType());
                            object[] args = { serverPacket, session };
                            TridentMc.Instance.EventManager.FireEvent((IEvent)Activator.CreateInstance(packetReceivedType, args));

                            if (serverPacket is IChangesState stateChangePacket)
                            {
                                Log.Debug("[{SessionId}] Changing state to {NewState}", session.Id, stateChangePacket.NextState);
                                session.ConnectionState = stateChangePacket.NextState;
                            }

                            serverPacket.Handle(session);
                        }
                    }
                }
            }
        }
コード例 #27
0
ファイル: O5MReader.cs プロジェクト: ringostarr80/O5M.NET
        private OSMWay ParseWayData(
            byte[] data
#if DEBUG
            , ElementDebugInfos debugInfos
#endif
            )
        {
            var bufferOffset = 0;

            var wayId  = VarInt.ParseInt64(data, ref bufferOffset) + this._lastWayId;
            var o5mWay = new OSMWay((ulong)wayId);

            this._lastWayId = (long)o5mWay.Id;

#if DEBUG
            this.ParseVersionData(data, o5mWay, ref bufferOffset, debugInfos);
#else
            this.ParseVersionData(data, o5mWay, ref bufferOffset);
#endif

            if (data[bufferOffset] > 0)
            {
                var referenceLength      = VarInt.ParseUInt64(data, ref bufferOffset);
                var referenceNodesBuffer = new byte[referenceLength];
                Array.Copy(data, bufferOffset, referenceNodesBuffer, 0, referenceNodesBuffer.Length);
                var referenceBufferOffset = 0;
                var bytesUnread           = referenceNodesBuffer.Length;
                while (bytesUnread > 0)
                {
                    var currentReferenceId = VarInt.ParseInt64(referenceNodesBuffer, ref referenceBufferOffset) + this._lastReferenceId;
                    o5mWay.NodeRefs.Add((ulong)currentReferenceId);
                    this._lastReferenceId = currentReferenceId;
                    bytesUnread           = referenceNodesBuffer.Length - referenceBufferOffset;
                }
                bufferOffset += (int)referenceLength;
            }

#if DEBUG
            this.ParseTagsData(data, o5mWay, ref bufferOffset, debugInfos);
#else
            this.ParseTagsData(data, o5mWay, ref bufferOffset);
#endif

            return(o5mWay);
        }
コード例 #28
0
        public static void ReceiveEncryptionResponse(Player player, GameStream stream)
        {
            VarInt secretLength = stream.ReadVarInt();

            byte[] sharedSecret = stream.ReadByteArray((int)secretLength.Value);
            VarInt tokenLength  = stream.ReadVarInt();

            byte[] verifyToken = stream.ReadByteArray((int)tokenLength.Value);

            var decryptedToken = Server.CryptoServerProvider.Decrypt(verifyToken, false);

            for (int i = 0; i < decryptedToken.Length; i++)
            {
                if (decryptedToken[i] != player.Stream.VerifyToken[i])
                {
                    Disconnect(player, stream, "Unable to authenticate");
                }
            }

            player.SharedToken = Server.CryptoServerProvider.Decrypt(sharedSecret, false);
            AsnKeyBuilder.AsnMessage encodedKey = AsnKeyBuilder.PublicKeyToX509(Server.ServerKey);
            byte[] shaData = Encoding.UTF8.GetBytes(Server.ID)
                             .Concat(player.SharedToken)
                             .Concat(encodedKey.GetBytes()).ToArray();
            string hash = Cryptography.JavaHexDigest(shaData);

            WebClient    webCLient = new WebClient();
            StreamReader webReader = new StreamReader(webCLient.OpenRead(
                                                          new Uri(string.Format(SessionChecker, player.Username, hash))
                                                          ));
            string response = webReader.ReadToEnd();

            webReader.Close();
            JToken json = JToken.Parse(response);

            if (string.IsNullOrEmpty(response))
            {
                Disconnect(player, stream, "Failed to verify username");
            }

            player.Stream            = new GameStream(new AesStream(player.Stream.BaseStream, player.SharedToken));
            player.UUID              = json["id"].Value <string>();
            player.EncryptionEnabled = true;
            SendSuccess(player, player.Stream);
        }
コード例 #29
0
        public override void BitcoinSerializeToStream(Stream stream)
        {
            Utilities.Uint32ToByteStreamLe(_version, stream);
            Byte[] inputCountBytes = new VarInt((ulong)_inputs.Count).Encode();
            stream.Write(inputCountBytes, 0, inputCountBytes.Length);
            foreach (var @in in _inputs)
            {
                @in.BitcoinSerializeToStream(stream);
            }

            Byte[] outputCountBytes = new VarInt((ulong)_outputs.Count).Encode();
            stream.Write(outputCountBytes, 0, outputCountBytes.Length);
            foreach (var @out in _outputs)
            {
                @out.BitcoinSerializeToStream(stream);
            }
            Utilities.Uint32ToByteStreamLe(_lockTime, stream);
        }
コード例 #30
0
        private static void Int32ToVarInt(uint n, ref VarInt varint)
        {
            // Write an i32 as a varint. Results in 1 - 5 bytes on the wire.
            varint.count = 0;
            Debug.Assert(varint.bytes.Length >= 5);

            while (true)
            {
                if ((n & ~0x7F) == 0)
                {
                    varint.bytes[varint.count++] = (byte)n;
                    break;
                }

                varint.bytes[varint.count++] = (byte)((n & 0x7F) | 0x80);
                n >>= 7;
            }
        }
コード例 #31
0
ファイル: Particle.cs プロジェクト: SharpenedMinecraft/SM1
        public static void SpawnParticle(int id, Vector3F Position, Vector3F Offset, Int32 ParticleCount, bool LongRange = false, float ParticleData = 0f, VarInt[] Data = null)
        {
            if (Data == null)
            {
                Data = new VarInt[0];
            }

            World.Players[0].Client.SendToAll(new SpawnParticlePacket(null)
            {
                ID            = id,
                LongRange     = LongRange,
                Position      = Position,
                Offset        = Offset,
                ParticleCount = ParticleCount,
                ParticleData  = ParticleData,
                Data          = Data
            });
        }
コード例 #32
0
        public void ReadWrite(ref UserId userId)
        {
            if (this.Serializing)
            {
                this.ReadWrite(userId);
            }
            else
            {
                var typeFlag = new VarInt();
                this.ReadWrite(ref typeFlag);

                var len = typeFlag.ToLong();

                if (SerializeFlag.FlagRegIDMin <= len && len <= SerializeFlag.FlagRegIDMax)
                {
                    RegId uid = new RegId();
                    this.ReadWriteAsCompactVarInt(ref uid.Height);
                    this.ReadWriteAsCompactVarInt(ref uid.Index);
                    uid.CompactIntoDest();
                    userId = uid;
                }
                else if (len == SerializeFlag.FlagKeyID)
                {
                    uint160 key = new uint160(0);
                    this.ReadWrite(ref key);
                    userId = new Wicc.Entities.KeyId(key);
                }
                else if (len == SerializeFlag.FlagPubKey)
                {
                    var bytes = new byte[len];
                    this.ReadWrite(ref bytes);
                    userId = new PubKeyId(bytes);
                }
                else if (len == SerializeFlag.FlagNullType)
                {
                    userId = new NullId();
                }
                else
                {
                    //TODO
                    throw new NullReferenceException();
                }
            }
        }
コード例 #33
0
        private static bool CheckHandshakeInfo(VarInt pro, string add, ushort port, VarInt next)
        {
            if (pro < 404)
            {
                return(false);           // First GemsCraft version
            }
            if (add != "localhost")
            {
                if (!IPAddress.TryParse(add, out _))
                {
                    return(false);
                }
            }

            if (port > 65535)
            {
                return(false);
            }
            if (pro < Protocol.Current.Protocol)
            {
                Logger.Write("Outdated Client");
                return(false);
            }

            if (pro > Protocol.Current.Protocol)
            {
                Logger.Write("Outdated Server");
                return(false);
            }

            if (port > 65535)
            {
                Logger.Write("Invalid Port");
                return(false);
            }

            if (next < 0 || next > 2)
            {
                Logger.Write("Invalid Session State");
                return(false);
            }

            return(true);
        }
コード例 #34
0
        public static Packet ReceivePacket(Socket tcp, int compressionThreshold)
        {
            Packet recPacket    = new Packet();
            int    PacketLength = VarInt.Read(tcp);

            recPacket.WriteBytes(ReceiveData(0, PacketLength, tcp));
            if (compressionThreshold > 0)
            {
                int DataLength = ReadVarInt(recPacket.Data);
                if (DataLength != 0) //如果是0的话就代表这个数据包没有被压缩
                {
                    byte[] uncompressed = ZlibUtils.Decompress(recPacket.Data.ToArray(), DataLength);
                    recPacket.Data.Clear();
                    recPacket.Data.AddRange(uncompressed);
                }
            }
            recPacket.ID = ReadVarInt(recPacket.Data);
            return(recPacket);
        }
コード例 #35
0
        public InvMessage(byte[] buffer)
            : base(
                "inv",
                buffer)
        {
            int startIndex = 0;

            int inventoryCount = VarInt.GetInt32(
                Payload,
                ref startIndex);

            for (int i = 0; i < inventoryCount; i++)
            {
                Inventories.Add(
                    Inventory.Parse(
                        Payload,
                        ref startIndex));
            }
        }
コード例 #36
0
        private static void Main(string[] args)
        {
            //Key Generation
            const string privKeyHex = "E9873D79C6D87DC0FB6A5778633389F4453213303DA61F20BD67FC233AA33262";
            BigInteger   privateKey = Hex.HexToBigInteger(privKeyHex);
            ECPoint      publicKey  = Secp256k1.G.Multiply(privateKey);
            string       bitcoinAddressUncompressed = publicKey.GetBitcoinAddress(false);
            string       bitcoinAddressCompressed   = publicKey.GetBitcoinAddress(compressed: true);

            Console.WriteLine("PrivateKey (Hex): {0}", privateKey.ToHex());
            Console.WriteLine("Address (Uncompressed): {0}", bitcoinAddressUncompressed);
            Console.WriteLine("Address (Compressed): {0}", bitcoinAddressCompressed);

            uint value = 268435263;

            var varInt = new VarInt(value);  //create VarInt from Integer

            Console.WriteLine("VarInt Internal Value: {0}", varInt.Value);
            Console.WriteLine("VarInt (hex): 0x{0:X}", varInt.Value);

            value = value ^ 2;

            byte[] varIntBytes = VarInt.Encode(value);
            Console.WriteLine("VarInt Static Encode & Decode test for value: {0}", value);
            Console.WriteLine("VarInt Encoded (hex): {0}", varIntBytes.ToHex());
            Console.WriteLine("Value Decoded: {0}", VarInt.Decode(varIntBytes));

            // encryption
            ECEncryption encryption = new ECEncryption();
            const string message    = "This is my encrypted message";

            byte[] encrypted        = encryption.Encrypt(publicKey, message);
            byte[] decrypted        = encryption.Decrypt(privateKey, encrypted);
            string decryptedMessage = Encoding.UTF8.GetString(decrypted);

            // signing
            MessageSignerVerifier messageSigner = new MessageSignerVerifier();
            SignedMessage         signedMessage = messageSigner.Sign(privateKey, "Test Message to sign, you can verify this on http://brainwallet.org/#verify");
            bool verified = messageSigner.Verify(signedMessage);

            Console.WriteLine("Press Any Key ...");
            Console.ReadKey();
        }
コード例 #37
0
        private static void Main(string[] args)
        {
            //Key Generation
            const string privKeyHex = "E9873D79C6D87DC0FB6A5778633389F4453213303DA61F20BD67FC233AA33262";
            BigInteger privateKey = Hex.HexToBigInteger(privKeyHex);
            ECPoint publicKey = Secp256k1.G.Multiply(privateKey);
            string bitcoinAddressUncompressed = publicKey.GetBitcoinAddress(false);
            string bitcoinAddressCompressed = publicKey.GetBitcoinAddress(compressed: true);

            Console.WriteLine("PrivateKey (Hex): {0}", privateKey.ToHex());
            Console.WriteLine("Address (Uncompressed): {0}", bitcoinAddressUncompressed);
            Console.WriteLine("Address (Compressed): {0}", bitcoinAddressCompressed);

            uint value = 268435263;

            var varInt = new VarInt(value);  //create VarInt from Integer
            Console.WriteLine("VarInt Internal Value: {0}", varInt.Value);
            Console.WriteLine("VarInt (hex): 0x{0:X}", varInt.Value);

            value = value ^ 2;

            byte[] varIntBytes = VarInt.Encode(value);
            Console.WriteLine("VarInt Static Encode & Decode test for value: {0}", value);
            Console.WriteLine("VarInt Encoded (hex): {0}", varIntBytes.ToHex());
            Console.WriteLine("Value Decoded: {0}", VarInt.Decode(varIntBytes));

            // encryption
            ECEncryption encryption = new ECEncryption();
            const string message = "This is my encrypted message";
            byte[] encrypted = encryption.Encrypt(publicKey, message);
            byte[] decrypted = encryption.Decrypt(privateKey, encrypted);
            string decryptedMessage = Encoding.UTF8.GetString(decrypted);

            // signing
            MessageSignerVerifier messageSigner = new MessageSignerVerifier();
            SignedMessage signedMessage = messageSigner.Sign(privateKey, "Test Message to sign, you can verify this on http://brainwallet.org/#verify");
            bool verified = messageSigner.Verify(signedMessage);

            Console.WriteLine("Press Any Key ...");
            Console.ReadKey();
        }
コード例 #38
0
 internal static void write(System.IO.MemoryStream data, int p)
 {
     var b = new VarInt((ulong)p).ToBytes();
     data.Write(b, 0, b.Length);
 }
コード例 #39
0
        public override ProtobufPacket ReadPacket(ProtobufDataReader reader)
        {
            PlayerId = reader.Read(PlayerId);

            return this;
        }
コード例 #40
0
ファイル: TradeAcceptPacket.cs プロジェクト: PokeD/PokeD.Core
        public override ProtobufPacket ReadPacket(ProtobufDataReader reader)
        {
            DestinationId = reader.Read(DestinationId);

            return this;
        }
コード例 #41
0
        public static void Main(string[] args)
        {
#if SAVE_ALL_TYPES
            List<string> fieldTypes = new List<string>();
#endif
            var generatorList = new List<ProtobufPacketGenerator>();


            // Those ID's are not supported and should be parsed manually.
            var bannedIDs = new int[] { 0x20, 0x22, 0x26, 0x34, 0x37, 0x38, 0x44, 0x45 };

            var protocols = GetProtocolTables();
            foreach (var protocol in protocols)
            {
                var className = $"{protocol.Name.Replace("-", "").Replace("_", "")}Packet";
                var id = new VarInt(int.Parse(protocol.GetAt(0, 0).Remove(0, 2), NumberStyles.AllowHexSpecifier));
                if (bannedIDs.Contains(id))
                    continue;

                var state = (State) Enum.Parse(typeof(State), protocol.GetAt(0, 1).ExceptBlanks());
                var boundTo = (BoundTo) Enum.Parse(typeof(BoundTo), protocol.GetAt(0, 2).ExceptBlanks());

                var builder = new ProtobufPacketGenerator(className, id, boundTo, state);

                for (int ix = 0; ix < protocol.Height; ix++)
                {
                    var fieldName = protocol.GetAt(ix, 3).Replace("-", "").ExceptBlanks();
                    if (fieldName == "nofields")
                        continue;

                    var fieldType = protocol.GetAt(ix, 4).Replace("-", "").ExceptBlanks();
                    var note = protocol.GetAt(ix, 5);

                    builder.AddField(fieldName, ReplaceTypes(fieldType));

#if SAVE_ALL_TYPES
                    if (!fieldTypes.Contains(fieldType))
                        fieldTypes.Add(fieldType);
#endif
                }

                generatorList.Add(builder);
            }

#if SAVE_ALL_TYPES
            var fieldTypesBuilder = new StringBuilder();
            foreach (string str in fieldTypes)
                fieldTypesBuilder.AppendLine(str);

            var fileTypeFile = FileSystemWrapper.OutputFolder.CreateFileAsync("FileTypes.txt", CreationCollisionOption.ReplaceExisting).Result;
            using (StreamWriter stream = new StreamWriter(fileTypeFile.OpenAsync(PCLStorage.FileAccess.ReadAndWrite).Result))
                stream.Write(fieldTypesBuilder.ToString());
#endif

            foreach (var generator in generatorList)
            {
                var folder = FileSystemWrapper.OutputFolder.CreateFolderAsync("Generated", CreationCollisionOption.OpenIfExists).Result;

                if (generator.BoundTo != BoundTo.NONE)
                    folder = folder.CreateFolderAsync(generator.BoundTo.ToString(), CreationCollisionOption.OpenIfExists).Result;
                if (generator.State != State.NONE)
                    folder = folder.CreateFolderAsync(generator.State.ToString(), CreationCollisionOption.OpenIfExists).Result;

                var classFile = folder.CreateFileAsync($"{generator.ClassName}.cs", CreationCollisionOption.ReplaceExisting).Result;
                using (StreamWriter stream = new StreamWriter(classFile.OpenAsync(PCLStorage.FileAccess.ReadAndWrite).Result))
                    stream.Write(generator.GenerateClass());
            }
        }