Пример #1
0
        /// <summary>
        /// From ~(a||b) to ~a&~b and ~(a&b) to ~a||~b (vice-versa)
        /// </summary>
        /// <param name="blockWithNestedContent"></param>
        /// <returns>The block passed to this method</returns>
        public override Block Translate()
        {
            if (FirstBlock == null && (FirstBlock = SecondBlock) == null)
            {
                ThrowErrorOnFirstCheck();
            }

            Block blockWithNestedContent = FirstBlock;

            if (blockWithNestedContent.ContentType == ContentType.Nested)
            {
                blockWithNestedContent.SetNegation(!blockWithNestedContent.IsNegated);
                BlockIterator.ForEach(blockWithNestedContent.GetContent() as Block, (currentBlock) =>
                {
                    switch (currentBlock.ContentType)
                    {
                    case ContentType.Logic:
                        (currentBlock.GetContent() as PropositionalLogic).Invert();
                        break;

                    default:
                        currentBlock.SetNegation(!currentBlock.IsNegated);
                        break;
                    }
                });
            }
            return(blockWithNestedContent);
        }
Пример #2
0
        /// <summary>
        /// Since this clause is full of disjunctions, might as well flatten them
        /// </summary>
        private void Flatten()
        {
            bool anyChanges = true;

            while (anyChanges)
            {
                anyChanges = false;
                BlockIterator.TerminableForEach(RootBlock, (currentBlock) =>
                {
                    if (currentBlock.ContentType == ContentType.Nested)
                    {
                        Block next = currentBlock.NextBlock,
                        current    = currentBlock.Isolate(true).GetContent() as Block;
                        anyChanges = true;

                        next.ExtendFront(current);
                        if (currentBlock.Equals(RootBlock))
                        {
                            RootBlock = current;
                        }

                        return(false);
                    }

                    return(true);
                });
            }
        }
Пример #3
0
        private void IterateThroughBlockLists(Block block)
        {
            BlockIterator.ForEach(block, (currentBlock) =>
            {
                // recursion for removal of deep nesting
                object content = currentBlock.GetContent();
                if (content is Block)
                {
                    IterateThroughBlockLists(content as Block);
                    return;
                }

                // we do not want any logic in here
                if (content is PropositionalLogic)
                {
                    return;
                }

                // definitely a string, containing a symbol
                string value = content as string;
                if (!UniqueValues.Contains(value))
                {
                    UniqueValues.Add(value);
                }
            });
        }
 void IteratorUpdate()
 {
     iterator++;
     if (iterator >= SIZE)
     {
         BlockIterator++;
         if (BlockIterator >= BLOCK_SIZE)
         {
             //end experiment screen
             Debug.Log("END EXPERIMENT!");
             Output.Close();
             Application.Quit();
         }
         else
         {
             //end block screen
             Pause         = true;
             isPaused.text = "Paused = True";
             if (blockList[BlockIterator].ChairSetups.Length > blockList[BlockIterator].BallSetups.Length)
             {
                 SIZE = blockList[BlockIterator].ChairSetups.Length;
             }
             else
             {
                 SIZE = blockList[BlockIterator].BallSetups.Length;
             }
             iterator      = 0;
             TxtBlock.text = "Block Set: " + BlockIterator.ToString();
         }
     }
     Trial.text = "Trial Number: " + iterator.ToString();
 }
Пример #5
0
        /// <summary>
        /// Check clause (a&b) against one model (row) in truth table
        /// </summary>
        /// <param name="rootBlock"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        private bool CheckClauseAgainstModel(Block rootBlock, Model model)
        {
            bool   result     = false;
            string logic      = "";
            bool   firstValue = true;

            BlockIterator.ForEach(rootBlock, (block) =>
            {
                switch (block.ContentType)
                {
                case ContentType.Normal:
                    bool blockValue = model.GetTruthBlock(block.GetContent(true).ToString());

                    if (block.IsNegated)
                    {
                        blockValue = !blockValue;
                    }

                    // if else
                    if (firstValue)
                    {
                        result     = blockValue;
                        firstValue = false;
                        return;
                    }
                    result = Verify(result, logic, blockValue);

                    break;

                case ContentType.Logic:
                    logic = block.GetContent(true).ToString();
                    break;

                case ContentType.Nested:
                    bool nestedBlockValue = CheckClauseAgainstModel(block.GetContent() as Block, model);

                    if (block.IsNegated)
                    {
                        nestedBlockValue = !nestedBlockValue;
                    }

                    // if else
                    if (firstValue)
                    {
                        result     = nestedBlockValue;
                        firstValue = false;
                        return;
                    }
                    result = Verify(result, logic, nestedBlockValue);

                    break;
                }
            });

            return(result);
        }
Пример #6
0
        public HornClauses(List <Block> clauses) : this()
        {
            foreach (var clause in clauses)
            {
                if (clause.NextBlock == clause && clause.PreviousBlock == clause)
                {
                    Facts.Add(clause.GetContent(true).ToString());
                    continue;
                }

                // safe against nested symbols inside clause or multiple clauses pointing at 1 symbol
                var symbol    = clause.PreviousBlock.GetContent(true).ToString();
                var unvisited = new List <Block> {
                    clause
                };
                if (!Implications.ContainsKey(symbol))
                {
                    Implications.Add(symbol, new List <List <string> >());
                }

                // if a horn clause is pointing at the same symbol as some other horn clauses,
                // add current clause's requirements to a new list instead of combining them together
                Implications[symbol].Add(new List <string>());

                // recursion using while loop, flatten down all nested symbols (if any)
                // as well as pushing clause's requirements for future reference
                while (unvisited.Count != 0)
                {
                    BlockIterator.TerminableForEach(unvisited[0], (block) =>
                    {
                        switch (block.ContentType)
                        {
                        case ContentType.Logic:
                            if ((block.GetContent() as PropositionalLogic).IsImplication)
                            {
                                return(false);
                            }
                            break;

                        case ContentType.Normal:
                            Implications[symbol].Last().Add(block.GetContent(true).ToString());
                            break;

                        case ContentType.Nested:
                            unvisited.Add(block.GetContent() as Block);
                            break;
                        }
                        return(true);
                    });

                    unvisited.RemoveAt(0);
                }
            }
        }
Пример #7
0
 /// <summary>
 /// Traverse through the list, regardless of parentheses
 /// </summary>
 protected int Traverse(Action <Block, int> action, Block rootBlock = null, int index = 0)
 {
     BlockIterator.ForEach(rootBlock ?? RootBlock, (currentBlock) =>
     {
         if (currentBlock.ContentType == ContentType.Nested)
         {
             index = Traverse(action, currentBlock.GetContent() as Block, index);
             return;
         }
         action.Invoke(currentBlock, index++);
     });
     return(index);
 }
Пример #8
0
        /// <summary>
        /// Only a||(b&c) <=> (a||b)&(a||c) is available to prioritize CNF over DNF
        /// </summary>
        /// <param name="logicBlock"></param>
        /// <returns>A block containing nested contents, which are distributed from original one</returns>
        public override Block Translate()
        {
            if (FirstBlock == null || Logic == null || SecondBlock == null)
            {
                ThrowErrorOnFirstCheck();
            }

            bool isFirstNormal  = FirstBlock.ContentType == ContentType.Normal,
                 isSecondNormal = SecondBlock.ContentType == ContentType.Normal;

            // from left to right instead of expanding from the least to the most symbols
            // no point in taking a&b or similars into consideration
            if (!isFirstNormal || !isSecondNormal)
            {
                var logic = Logic.ToString();

                // swap places: (a&b)||c into c||(a&b) locally
                if (isSecondNormal)
                {
                    (FirstBlock, SecondBlock) = (SecondBlock, FirstBlock);
                }

                // a&(b||c) like
                if (FirstBlock.ContentType == ContentType.Normal)
                {
                    return(Distribute(
                               FirstBlock.IsNegated,
                               FirstBlock.GetContent(true).ToString(),
                               SecondBlock.GetContent() as Block));
                }

                // (a||b)&(c||d) like
                if (FirstBlock.ContentType == ContentType.Nested)
                {
                    BlockIterator.ForEach(FirstBlock.GetContent() as Block, (currentBlock) =>
                    {
                        if (currentBlock.ContentType == ContentType.Normal)
                        {
                            Distribute(
                                currentBlock.IsNegated,
                                currentBlock.GetContent(true).ToString(),
                                SecondBlock.GetContent() as Block
                                );
                        }
                    });
                    return(FirstBlock.GetContent() as Block);
                }
            }

            return(ConcatStoredBlocks());
        }
Пример #9
0
        /// <summary>
        /// Distribute content to nested block using given logic (under assumption that nested block
        /// contains no more nested contents)
        /// <para>E.g: a&(b||c) <=> (a&b)||(a&c)</para>
        /// </summary>
        /// <param name="content"></param>
        /// <param name="logic"></param>
        /// <param name="nested"></param>
        /// <returns></returns>
        private Block Distribute(bool isNegated, string content, Block nested)
        {
            // with a||(b&c)
            // isNegated = false, content = a, logic = ||, nested = b&c
            BlockIterator.ForEach(nested, (currentBlock) =>
            {
                if (currentBlock.ContentType != ContentType.Logic)
                {
                    var block = new Block(content, isNegated);                              // a (or ~a)
                    block.InsertBack(new Block(Logic))                                      // connective
                    .InsertBack(new Block(currentBlock.GetContent(true).ToString()));       // b or c in (b||c)

                    currentBlock.SetContent(block);
                }
            });
            return(nested);
        }
Пример #10
0
        private static Block ReorderClause(Block clause)
        {
            var blockList = new BlockIterator(clause).GetIterator();

            for (int i = 0, len = blockList.Count; i < len; ++i)
            {
                if (blockList[i].ContentType == ContentType.Logic)
                {
                    continue;
                }

                Block  minBlock = null;
                string min      = "";
                int    cache    = -1;
                for (int j = i; j < len; ++j)
                {
                    var currentBlock = blockList[j];
                    if (currentBlock.ContentType == ContentType.Nested)
                    {
                        blockList[j].SetContent(ReorderClause(currentBlock.GetContent() as Block));
                    }

                    if (currentBlock.ContentType != ContentType.Logic)
                    {
                        string symbol = currentBlock.GetContent(true).ToString();
                        if (minBlock == null || StringComparer(symbol, min))
                        {
                            min      = symbol;
                            minBlock = currentBlock;
                            cache    = j;
                        }
                    }
                }

                if (cache != -1 && cache != i)
                {
                    // swapping order
                    blockList[cache] = blockList[i];
                    blockList[i]     = minBlock;
                    blockList[i].Swap(blockList[cache]);
                }
            }
            return(blockList[0]);
        }
Пример #11
0
        /// <summary>
        /// Represent the whole linked list as a string again
        /// </summary>
        /// <returns>A string in form of ~a& to represent a certain part of the list</returns>
        public override string ToString()
        {
            string result = "";

            if (NextBlock == null && PreviousBlock == null)
            {
                return((IsNegated ? PropositionalLogic.NEGATION : "") + GetContent(true));
            }

            // forward iterate through the list from this block onwards
            BlockIterator.ForEach(this, (currentBlock) =>
            {
                // one block of content is pushed into the result (no whitespaces in between)
                result +=
                    (currentBlock.IsNegated ? PropositionalLogic.NEGATION : "") +
                    currentBlock.GetContent(true);
            });

            return(result);
        }
Пример #12
0
        public void TestGuaranteeCNF()
        {
            Assert.DoesNotThrow(() =>
            {
                foreach (var clause in StartingClauses)
                {
                    var block = new ClauseRephraser().RephraseIntoBlock(clause);
                    BlockIterator.ForEach(block, (currentBlock) =>
                    {
                        // all normal clauses contain only disjunction
                        // conjunction only appears when concatenating two or more clauses
                        if (currentBlock.ContentType == ContentType.Logic)
                            Assert.AreEqual(
                                (currentBlock.GetContent() as PropositionalLogic).IsDisjunction,
                                true
                            );
                    });
                }
            });

        }
    void RecordTrial()
    {
        if (Output == null)
        {
            Output = File.CreateText(FilePath);
            Output.WriteLine(FilePath);
            Output.WriteLine("Subject ID: " + SettingsSingleton.instance.ParticipantID);
            Output.WriteLine("\nChair type, 0 = empty chair, 1 = avatar");
            Output.WriteLine("Negative Ball Rotation, is a ball on the left\n");
            Output.WriteLine("Block Number,Trial Number,Chair Type,Chair Rotation,Ball Distance,Ball Rotation,Input,Response Time, Was Correct, Distance From Table");

            Debug.Log("Output was null, attempted file creation");
            return;
        }
        float  mathStuff = Mathf.Abs(playerCam.transform.position.z) - Mathf.Abs(Table.transform.localScale.x / 2);
        bool   wasCorrect;
        string WCString;

        if ((blockList[BlockIterator].BallSetups[iterator][1] > 0 && InputRecorder == "Right") || (blockList[BlockIterator].BallSetups[iterator][1] < 0 && InputRecorder == "Left"))
        {
            wasCorrect = true; WCString = "True";
        }
        else if (InputRecorder != "Left" && InputRecorder != "Right")
        {
            wasCorrect = false; WCString = "";
        }
        else
        {
            wasCorrect = false; WCString = "False";
        }

        string WriteMe = BlockIterator.ToString() + ',' + iterator.ToString() + ',' + blockList[BlockIterator].ChairSetups[iterator][0].ToString() + ','
                         + blockList[BlockIterator].ChairSetups[iterator][1].ToString() + ',' + blockList[BlockIterator].BallSetups[iterator][0].ToString() + ','
                         + blockList[BlockIterator].BallSetups[iterator][1].ToString() + ',' + InputRecorder.ToString() + ',' + ResponseTime.ToString()
                         + ',' + WCString + ',' + mathStuff;

        Output.WriteLine(WriteMe);
    }
Пример #14
0
        public override IEnumerable <PendingSwap> Update()
        {
            lock (String.Intern("PendingSetCurrentHeight_" + "neo"))
            {
                var result = new List <PendingSwap>();
                try
                {
                    var _interopBlockHeight = BigInteger.Parse(OracleReader.GetCurrentHeight("neo", "neo"));

                    // initial start, we have to verify all processed swaps
                    if (initialStart)
                    {
                        Logger.Debug($"Read all neo blocks now.");
                        // TODO check if quick sync nodes are configured, if so use quick sync
                        // we need to find a better solution for that though
                        var allInteropBlocks = OracleReader.ReadAllBlocks("neo", "neo");

                        Logger.Debug($"Found {allInteropBlocks.Count} blocks");

                        foreach (var block in allInteropBlocks)
                        {
                            try
                            {
                                ProcessBlock(block, result);
                            }
                            catch (Exception e)
                            {
                                Logger.Debug($"Block {block.Hash} was not processed correctly: " + e);
                            }
                        }

                        initialStart = false;

                        Logger.Debug($"QuickSync: " + quickSync);
                        // quick sync is only done once after startup
                        if (quickSync)
                        {
                            // if quick sync is active, we can use a specific plugin installed on the nodes (EventTracker)
                            try
                            {
                                var blockIds = neoAPI.GetSwapBlocks("ed07cffad18f1308db51920d99a2af60ac66a7b3", LocalAddress, _interopBlockHeight.ToString());
                                Logger.Debug($"Found {blockIds.Count} blocks to process ");
                                List <InteropBlock> blockList = new List <InteropBlock>();
                                foreach (var entry in blockIds)
                                {
                                    //logger.Debug($"read block {entry.Value}");
                                    var url = DomainExtensions.GetOracleBlockURL("neo", "neo", PBigInteger.Parse(entry.Value.ToString()));
                                    blockList.Add(OracleReader.Read <InteropBlock>(DateTime.Now, url));
                                }

                                // get blocks and order them for processing
                                var blocksToProcess = blockList.Where(x => blockIds.ContainsKey(x.Hash.ToString()))
                                                      .Select(x => new { block = x, id = blockIds[x.Hash.ToString()] })
                                                      .OrderBy(x => x.id);

                                Logger.Debug($"blocks to process: {blocksToProcess.Count()}");

                                foreach (var entry in blocksToProcess.OrderBy(x => x.id))
                                {
                                    Logger.Debug($"process block {entry.id}");
                                    ProcessBlock(entry.block, result);
                                    OracleReader.SetCurrentHeight("neo", "neo", _interopBlockHeight.ToString());
                                    _interopBlockHeight = BigInteger.Parse(entry.id.ToString());
                                }
                            }
                            catch (Exception e)
                            {
                                Logger.Error("Inital start failed: " + e.ToString());
                            }
                        }

                        // return after the initial start to be able to process all swaps that happend in the mean time.
                        return(result);
                    }

                    var blockIterator   = new BlockIterator(neoAPI);
                    var blockDifference = blockIterator.currentBlock - _interopBlockHeight;
                    var batchCount      = (blockDifference > 8) ? 8 : blockDifference; //TODO make it a constant, should be no more than 8

                    while (blockIterator.currentBlock > _interopBlockHeight)
                    {
                        if (_resyncBlockIds.Any())
                        {
                            for (var i = 0; i < _resyncBlockIds.Count; i++)
                            {
                                var blockId = _resyncBlockIds.ElementAt(i);
                                if (blockId > _interopBlockHeight)
                                {
                                    Logger.Debug($"NeoInterop: Update() resync block {blockId} higher than current interop height, can't resync.");
                                    _resyncBlockIds.RemoveAt(i);
                                    continue;
                                }

                                try
                                {
                                    Logger.Debug($"NeoInterop: Update() resync block {blockId} now.");
                                    var interopBlock = GetInteropBlock(blockId);
                                    ProcessBlock(interopBlock, result);
                                }
                                catch (Exception e)
                                {
                                    Logger.Error($"NeoInterop: Update() resync block {blockId} failed: " + e);
                                }
                                _resyncBlockIds.RemoveAt(i);
                            }
                        }

                        Logger.Debug($"Swaps: Current Neo chain height: {blockIterator.currentBlock}, interop: {_interopBlockHeight}, delta: {blockIterator.currentBlock - _interopBlockHeight}");
                        blockDifference = blockIterator.currentBlock - _interopBlockHeight;
                        batchCount      = (blockDifference > 8) ? 8 : blockDifference;

                        if (batchCount > 1)
                        {
                            List <Task <InteropBlock> > taskList = CreateTaskList(batchCount);

                            foreach (var task in taskList)
                            {
                                task.Start();
                            }

                            Task.WaitAll(taskList.ToArray());

                            foreach (var task in taskList)
                            {
                                var block = task.Result;

                                ProcessBlock(block, result);
                            }

                            OracleReader.SetCurrentHeight("neo", "neo", _interopBlockHeight.ToString());
                            _interopBlockHeight += batchCount;
                        }
                        else
                        {
                            var interopBlock = GetInteropBlock(_interopBlockHeight);

                            ProcessBlock(interopBlock, result);

                            OracleReader.SetCurrentHeight("neo", "neo", _interopBlockHeight.ToString());
                            _interopBlockHeight++;
                        }
                    }
                }
                catch (Exception e)
                {
                    Logger.Error("Neo block sync failed: " + e);
                }
                return(result);
            }
        }
    // Use this for initialization
    void Start()
    {
        //set forcedHeight
        ForcedHeightAdjustment           = SettingsSingleton.instance.Cal_H / 100;
        fixationCross.transform.position = new Vector3(0, (SettingsSingleton.instance.EyeHeight / 100) + .06f, 0);
        float Yscale = 0;

        //set avatar display
        if (SettingsSingleton.instance.isFemale)
        {
            Destroy(MaleAva);
            Yscale = (FemAva.transform.localScale.y) + (.1f * (SettingsSingleton.instance.EyeHeight / 100 - 1.5f));
            FemAva.transform.localScale = new Vector3(FemAva.transform.localScale.x, Yscale, FemAva.transform.localScale.z);
        }
        else
        {
            Destroy(FemAva);
            Yscale = (FemAva.transform.localScale.y) + (.1f * (SettingsSingleton.instance.EyeHeight / 100 - 1.2f));
            MaleAva.transform.localScale = new Vector3(MaleAva.transform.localScale.x, Yscale, MaleAva.transform.localScale.z);
        }

        ReadINI();
        if (ForcePlayerPosition)
        {
            player.transform.position = new Vector3(Player_Chair.transform.position.x, ForcedHeightAdjustment, Player_Chair.transform.position.z);
        }
        if (blockList[BlockIterator].ChairSetups.Length > blockList[BlockIterator].BallSetups.Length)
        {
            SIZE = blockList[BlockIterator].ChairSetups.Length;
        }
        else
        {
            SIZE = blockList[BlockIterator].BallSetups.Length;
        }
        BLOCK_SIZE = blockList.Length;

        // Set files paths
        string temp = System.DateTime.Now.ToString();

        temp             = temp.Replace("/", "_").Replace(":", "-");
        FilePath         = "Subject_" + SettingsSingleton.instance.ParticipantID + "_" + FilePath + "_" + temp + ".csv";
        TrialListingFile = "Subject_" + SettingsSingleton.instance.ParticipantID + "_" + TrialListingFile + "_" + temp + ".csv";

        RecordTrial();
        WriteTrialList();

        //initialize variables for later use
        ResponseTime  = 0;
        TrialTimer    = 0;
        Pause         = true;
        isPaused.text = "Paused = True";
        TxtBlock.text = "Block Set: " + BlockIterator.ToString();
        Trial.text    = "Trial Number: " + iterator.ToString();

        Chair_Table_Distance = Player_Chair.transform.position.z - (Table.transform.localScale.x / 2);
        RunningTrial         = false;

        //set table location
        //set player chair location
        Player_Chair.transform.RotateAround(Table.transform.position, Vector3.up, 0);
        Player_Chair.transform.LookAt(new Vector3(Table.transform.position.x, Player_Chair.transform.position.y, Table.transform.position.z));
    }
Пример #16
0
        static void Main()
        {
            string fileName = null;

            do
            {
                Console.Write("Enter whitelist file name or NEO address: ");
                fileName = Console.ReadLine();

                if (!fileName.Contains("."))
                {
                    break;
                }

                if (File.Exists(fileName))
                {
                    break;
                }
            } while (true);

            List <string> lines;

            if (fileName.Contains("."))
            {
                lines = File.ReadAllLines(fileName).ToList();
            }
            else
            {
                lines = new List <string>()
                {
                    fileName
                };
            }

            var ext             = Path.GetExtension(fileName);
            var result_filename = fileName.Replace(ext, "_result" + ext);

            if (File.Exists(result_filename))
            {
                var finishedLines     = File.ReadAllLines(result_filename);
                var finishedAddresses = new HashSet <string>();
                foreach (var entry in finishedLines)
                {
                    var temp = entry.Split(',');
                    for (int i = 1; i < temp.Length; i++)
                    {
                        finishedAddresses.Add(temp[i]);
                    }
                }

                var previousTotal = lines.Count;

                lines = lines.Where(x => !finishedAddresses.Contains(x)).ToList();

                var skippedTotal = previousTotal - lines.Count;

                Console.WriteLine($"Skipping {skippedTotal} addresses...");
            }

            int done = 0;

            //var api = NeoDB.ForMainNet();
            var api = new RemoteRPCNode(10332, "http://neoscan.io", CronNodesKind.CRON_GLOBAL);
            //var api = new CustomRPCNode();
            var bi = new BlockIterator(api);

            api.SetLogger(x =>
            {
                ColorPrint(ConsoleColor.DarkGray, x);
            });

            string privateKey;

            byte[] scriptHash = null;

            do
            {
                Console.Write("Enter WIF private key: ");
                privateKey = Console.ReadLine();

                if (privateKey.Length == 52)
                {
                    break;
                }
            } while (true);

            var keys = KeyPair.FromWIF(privateKey);

            Console.WriteLine("Public address: " + keys.address);

            do
            {
                Console.Write("Enter contract script hash or token symbol: ");
                var temp = Console.ReadLine();

                scriptHash = CronAPI.GetScriptHashFromSymbol(temp);

                if (scriptHash == null && temp.Length == 40)
                {
                    scriptHash = CronAPI.GetScriptHashFromString(temp);
                }
            } while (scriptHash == null);


            var token = new NEP5(api, scriptHash);

            Console.WriteLine($"Starting whitelisting of {token.Name} addresses...");

            var batch = new List <string>();

            foreach (var temp in lines)
            {
                var address = temp.Trim();
                if (!address.IsValidAddress())
                {
                    ColorPrint(ConsoleColor.Yellow, "Invalid address: " + address);
                    continue;
                }

                batch.Add(address);

                if (batch.Count < 5)
                {
                    continue;
                }

                Console.WriteLine($"New address batch...");

                var scripts = new List <object>();

                var batchContent = "";

                foreach (var entry in batch)
                {
                    Console.WriteLine($"\t{entry}");

                    if (batchContent.Length > 0)
                    {
                        batchContent += ",";
                    }

                    batchContent += entry;

                    var hash = entry.GetScriptHashFromAddress();
                    scripts.Add(hash);
                }


                Console.WriteLine($"Sending batch to contract...");
                Transaction tx = null;

                int failCount = 0;
                int failLimit = 20;
                do
                {
                    int tryCount = 0;
                    int tryLimit = 3;
                    do
                    {
                        tx = api.CallContract(keys, token.ScriptHash, "whitelistAdd", scripts.ToArray());
                        Thread.Sleep(1000);

                        if (tx != null)
                        {
                            break;
                        }

                        Console.WriteLine("Tx failed, retrying...");

                        tryCount++;
                    } while (tryCount < tryLimit);


                    if (tx != null)
                    {
                        break;
                    }
                    else
                    {
                        Console.WriteLine("Changing RPC server...");
                        Thread.Sleep(2000);
                        api.rpcEndpoint = null;
                        failCount++;
                    }
                } while (failCount < failLimit);

                if (failCount >= failLimit || tx == null)
                {
                    ColorPrint(ConsoleColor.Red, "Try limit reached, internal problem maybe?");
                    break;
                }

                Console.WriteLine("Unconfirmed transaction: " + tx.Hash);

                api.WaitForTransaction(bi, keys, tx);

                ColorPrint(ConsoleColor.Green, "Confirmed transaction: " + tx.Hash);

                File.AppendAllText(result_filename, $"{tx.Hash},{batchContent}\n");

                done += batch.Count;
                batch.Clear();
            }

            Console.WriteLine($"Activated {done} addresses.");

            Console.WriteLine("Finished.");
            Console.ReadLine();
        }
Пример #17
0
        static void Main()
        {
            string fileName;

            do
            {
                Console.Write("Enter whitelist file name or CRON address: ");
                fileName = Console.ReadLine();

                if (!fileName.Contains("."))
                {
                    break;
                }

                if (File.Exists(fileName))
                {
                    break;
                }
            } while (true);

            List <string> lines;

            if (fileName.Contains("."))
            {
                lines = File.ReadAllLines(fileName).ToList();
            }
            else
            {
                lines = new List <string>()
                {
                    fileName
                };
            }

            if (File.Exists(result_fileName))
            {
                var finishedLines     = File.ReadAllLines(result_fileName);
                var finishedAddresses = new HashSet <string>();
                foreach (var entry in finishedLines)
                {
                    var temp = entry.Split(',');
                    finishedAddresses.Add(temp[0]);
                }

                var previousTotal = lines.Count;

                lines = lines.Where(x => !finishedAddresses.Contains(x)).ToList();

                var skippedTotal = previousTotal - lines.Count;

                Console.WriteLine($"Skipping {skippedTotal} addresses...");
            }

            throw new Exception("TODO:// specify port and url!!!");
            var api = new RemoteRPCNode(0, null, CronNodesKind.CRON_GLOBAL);
            var bi  = new BlockIterator(api);

            api.SetLogger(x =>
            {
                ColorPrint(ConsoleColor.DarkGray, x);
            });

            string privateKey;

            byte[] scriptHash = null;

            do
            {
                Console.Write("Enter WIF private key: ");
                privateKey = Console.ReadLine();

                if (privateKey.Length == 52)
                {
                    break;
                }
            } while (true);

            var keys = KeyPair.FromWIF(privateKey);

            Console.WriteLine("Public address: " + keys.address);

            do
            {
                Console.Write("Enter contract script hash or token symbol: ");
                var temp = Console.ReadLine();

                scriptHash = CronAPI.GetScriptHashFromSymbol(temp);

                if (scriptHash == null && temp.Length == 40)
                {
                    scriptHash = CronAPI.GetScriptHashFromString(temp);
                }
            } while (scriptHash == null);


            var token = new NEP5(api, scriptHash);

            decimal amount;

            Console.WriteLine($"Write amount of {token.Symbol} to distribute to each address:");
            do
            {
                if (decimal.TryParse(Console.ReadLine(), out amount) && amount > 0)
                {
                    break;
                }
            } while (true);

            int skip = 0;
            int done = 0;

            Console.WriteLine($"Initializing {token.Name} airdrop...");

            var srcBalance = token.BalanceOf(keys);

            Console.WriteLine($"Balance of {keys.address} is {srcBalance} {token.Symbol}");

            var minimum = lines.Count * amount;

            if (srcBalance < minimum)
            {
                ColorPrint(ConsoleColor.Red, $"Error: For this Airdrop you need at least {minimum} {token.Symbol} at {keys.address}");
                Console.ReadLine();
                return;
            }

            foreach (var temp in lines)
            {
                var address = temp.Trim();
                if (!address.IsValidAddress())
                {
                    skip++;
                    ColorPrint(ConsoleColor.Yellow, "Invalid address: " + address);
                    continue;
                }

                var hash    = address.GetScriptHashFromAddress();
                var balance = token.BalanceOf(hash);

                Console.WriteLine($"Found {address}: {balance} {token.Symbol}");

                Console.WriteLine($"Sending {token.Symbol} to  {address}");
                Transaction tx = null;

                int failCount = 0;
                int failLimit = 20;
                do
                {
                    int tryCount = 0;
                    int tryLimit = 3;
                    do
                    {
                        tx = token.Transfer(keys, address, amount);
                        Thread.Sleep(1000);

                        if (tx != null)
                        {
                            break;
                        }

                        Console.WriteLine("Tx failed, retrying...");

                        tryCount++;
                    } while (tryCount < tryLimit);


                    if (tx != null)
                    {
                        break;
                    }
                    else
                    {
                        Console.WriteLine("Changing RPC server...");
                        Thread.Sleep(2000);
                        api.rpcEndpoint = null;
                        failCount++;
                    }
                } while (failCount < failLimit);

                if (failCount >= failLimit || tx == null)
                {
                    ColorPrint(ConsoleColor.Red, "Try limit reached, internal problem maybe?");
                    break;
                }

                Console.WriteLine("Unconfirmed transaction: " + tx.Hash);

                api.WaitForTransaction(bi, keys, tx);

                ColorPrint(ConsoleColor.Green, "Confirmed transaction: " + tx.Hash);

                File.AppendAllText(result_fileName, $"{address},{tx.Hash}\n");

                done++;
            }

            Console.WriteLine($"Skipped {skip} invalid addresses.");
            Console.WriteLine($"Airdropped {amount} {token.Symbol} to {done} addresses.");

            Console.WriteLine("Finished.");
            Console.ReadLine();
        }
Пример #18
0
        public Message Parse(string message)
        {
            // Validate if data has a valid message structure.
            if (!this.validator.Validate(message))
            {
                var exception = new ParserException("Invalid message.");
                exception.Data["Swift.Validator.Errors"] = string.Join(Environment.NewLine, this.validator.Errors);

                throw exception;
            }

            BasicHeader basicHeader = null;
            ApplicationHeader applicationHeader = null;
            UserHeader userHeader = null;
            TextBlock text = null;
            Trailer trailer = null;

            // Iterate through all blocks.
            // Instantiate the specific block when available.
            // Each instance will self validate.
            var iterator = new BlockIterator(message);
            foreach (var block in iterator)
            {
                switch (block.BlockId)
                {
                    case "1":
                        basicHeader = new BasicHeader(block.Value);
                        break;
                    case "2":
                        applicationHeader = new ApplicationHeader(block.Value);
                        break;
                    case "3":
                        userHeader = new UserHeader(block.Value);
                        break;
                    case "4":
                        text = new TextBlock(block.Value);
                        break;
                    case "5":
                        trailer = new Trailer(block.Value);
                        break;
                }
            }

            // A message is composed of these blocks.
            return new Message(basicHeader, applicationHeader, userHeader, text, trailer);
        }
Пример #19
0
        /// <summary>
        /// Remove any symbols inside clause, guarantee to also remove its trailing connective.
        /// <para>Eg: a||b||c into b||c if removing a or a||c if removing b</para>
        /// </summary>
        /// <param name="clauses"></param>
        /// <param name="symbol"></param>
        /// <returns></returns>
        private List <Block> RemoveSymbol(List <Block> clauses, Block symbol, bool newList = true)
        {
            // must specify a fresh copy on demand here because blocks are also objects
            // that have memory addresses
            var result = !newList ? clauses :
                         clauses.Select((b) => ClauseParser.Parse(b.ToString())).ToList();

            string rawSymbol = symbol.GetContent(true).ToString();

            for (int i = 0; i < result.Count; ++i)
            {
                var root = result[i];
                if (root == null)
                {
                    continue;
                }

                // remove either a symbol or the whole rootBlock
                BlockIterator.TerminableForEach(root, (currentBlock) =>
                {
                    if (currentBlock.GetContent(true).ToString() == rawSymbol)
                    {
                        // remove the whole clause if it contains the exact content of the symbol
                        // passed through in this method
                        // (true in a disjunctive clause means true as a whole)
                        if (currentBlock.IsNegated == symbol.IsNegated)
                        {
                            result.RemoveAt(i--);
                            return(false);
                        }

                        // remove only this symbol if it does not have the same negation
                        // because when this happens, the symbol within stored list turns out to be false
                        // which is removable in a sea of disjunctions
                        bool isEOL          = currentBlock.NextBlock == root;
                        var unaffectedBlock = isEOL ?
                                              currentBlock.PreviousBlock.PreviousBlock :
                                              currentBlock.NextBlock.NextBlock;

                        // block list contains only 1 block
                        if (unaffectedBlock == currentBlock)
                        {
                            currentBlock.Isolate(true);
                            result[i] = null;
                            return(false);
                        }

                        if (isEOL)
                        {
                            // a||b into b if remove a
                            unaffectedBlock.RemoveBack(true);
                            unaffectedBlock.RemoveBack(true);
                        }
                        else
                        {
                            // a||b||c into a||c if remove b
                            unaffectedBlock.RemoveFront(true);
                            unaffectedBlock.RemoveFront(true);
                        }

                        if (root == currentBlock)
                        {
                            result[i] = unaffectedBlock;
                            return(false);
                        }
                    }
                    return(true);
                });
            }

            return(result);
        }