Beispiel #1
0
 public ToolLinker(ILogger logger)
 {
     this.State = new PersistentState<List<ToolPair>>(logger, "Tools.json");
     this.KnownTools = new Trie();
     this.Tools = new Dictionary<string, ToolState>();
     this.Deserialize();
 }
Beispiel #2
0
 public AlarmHelper(long gid, float value)
 {
     this.gid        = gid;
     this.value      = value;
     this.message    = "";
     this.persistent = PersistentState.Persistent;
 }
Beispiel #3
0
        public void VM_Throws_Exception_CanCatch()
        {
            SmartContractCompilationResult compilationResult = SmartContractCompiler.CompileFile("SmartContracts/ThrowExceptionContract.cs");
            Assert.True(compilationResult.Success);

            byte[] contractCode = compilationResult.Compilation;

            var gasLimit = (Gas)100;
            var gasMeter = new GasMeter(gasLimit);
            var persistenceStrategy = new MeteredPersistenceStrategy(this.repository, gasMeter, this.keyEncodingStrategy);
            var persistentState = new PersistentState(persistenceStrategy,
                TestAddress.ToUint160(this.network), this.network);
            var internalTxExecutorFactory = new InternalTransactionExecutorFactory(this.keyEncodingStrategy, this.loggerFactory, this.network);
            var vm = new ReflectionVirtualMachine(internalTxExecutorFactory, this.loggerFactory);

            var context = new SmartContractExecutionContext(
                new Block(0, TestAddress),
                new Message(TestAddress, TestAddress, 0, gasLimit),
                TestAddress.ToUint160(this.network),
                1,
                new object[] { }
            );

            var result = vm.ExecuteMethod(
                contractCode,
                "ThrowException",
                context,
                gasMeter, persistentState, 
                this.repository);

            Assert.Equal(typeof(Exception), result.ExecutionException.GetType());
        }
Beispiel #4
0
        public RaftEngine(RaftEngineOptions raftEngineOptions)
        {
            _raftEngineOptions = raftEngineOptions;
            EngineStatistics   = new RaftEngineStatistics(this);
            Debug.Assert(raftEngineOptions.Stopwatch != null);

            _log = LogManager.GetLogger(raftEngineOptions.Name + "." + GetType().FullName);

            _eventLoopCancellationTokenSource = new CancellationTokenSource();

            Name            = raftEngineOptions.Name;
            PersistentState = new PersistentState(raftEngineOptions.Name, raftEngineOptions.StorageOptions, _eventLoopCancellationTokenSource.Token)
            {
                CommandSerializer = new JsonCommandSerializer()
            };

            _currentTopology = PersistentState.GetCurrentTopology();

            //warm up to make sure that the serializer don't take too long and force election timeout
            PersistentState.CommandSerializer.Serialize(new NopCommand());

            var thereAreOthersInTheCluster = CurrentTopology.QuorumSize > 1;

            if (thereAreOthersInTheCluster == false && CurrentTopology.IsVoter(Name))
            {
                PersistentState.UpdateTermTo(this, PersistentState.CurrentTerm + 1);// restart means new term
                SetState(RaftEngineState.Leader);
            }
            else
            {
                SetState(RaftEngineState.Follower);
            }

            _eventLoopTask = Task.Factory.StartNew(EventLoop, TaskCreationOptions.LongRunning);
        }
Beispiel #5
0
        async void Start()
        {
            _playerInfo = new PlayerInfo(MaxHitPoints);

            _shipInfo              = new ShipInfo();
            _shipInfo.Speed        = Speed;
            _shipInfo.WeaponDamage = WeaponDamage;
            _shipInfo.WeaponPlaces = new Vector3[4] {
                new Vector3(-0.6f, 0f, 0.5f),
                new Vector3(0.6f, 0f, 0.5f),
                new Vector3(-0.35f, 0f, 0.3f),
                new Vector3(0.35f, 0f, 0.3f)
            };
            _shipInfo.WeaponShootingFrequency = WeaponShootingFrequency;
            _shipInfo.Position.Value          = new Vector3(0f, 0f, 0f);
            _shipInfo.Active = true;

            _levelInfo = PersistentState.Get().CurrentLevelInfo;

            LevelGenerator.GenerateAsteroids(_levelInfo, out _asteroids);

            await System.Threading.Tasks.Task.Yield();

            MessageBroker.Default.Publish(SharedMessage.Create(this, SharedMessage.MessageType.INIT_PLAYER, _playerInfo));
            MessageBroker.Default.Publish(SharedMessage.Create(this, SharedMessage.MessageType.INIT_LEVEL, _levelInfo));
            MessageBroker.Default.Publish(SharedMessage.Create(this, SharedMessage.MessageType.INIT_ASTEROIDS, _asteroids));
            MessageBroker.Default.Publish(SharedMessage.Create(this, SharedMessage.MessageType.INIT_SHIP, _shipInfo));
        }
Beispiel #6
0
        public void CanProperlySnapshot()
        {
            using (var state = new PersistentState("self", StorageEnvironmentOptions.CreateMemoryOnly(), CancellationToken.None)
            {
                CommandSerializer = new JsonCommandSerializer()
            })
            {
                state.UpdateTermTo(null, 1);
                state.AppendToLeaderLog(new NopCommand());
                for (int i = 0; i < 5; i++)
                {
                    state.AppendToLeaderLog(new DictionaryCommand.Set
                    {
                        Key   = i.ToString(),
                        Value = i
                    });
                }

                state.MarkSnapshotFor(6, 1, 5);

                state.AppendToLeaderLog(new DictionaryCommand.Set
                {
                    Key   = "1",
                    Value = 4
                });

                var lastLogEntry = state.LastLogEntry();

                Assert.Equal(7, lastLogEntry.Index);
            }
        }
Beispiel #7
0
    public void CreateCatIsContract()
    {
        var result = Create <Cat>(0, new object[] { CatCounter });

        UpdateLastCreatedCat(result.NewContractAddress);
        PersistentState.SetBool("IsContract", PersistentState.IsContract(result.NewContractAddress));
    }
Beispiel #8
0
        private void LoadState(Guid?seedId = null)
        {
            using (var tx = _env.BeginReadOnlyTransaction())
            {
                LoadLastTermAndIndex(tx);

                // snapshot
                Snapshot ss;
                if (TryGetLastSnapshot(out ss))
                {
                    LogOffset = ss.LastIncludedIndex + 1;
                }

                // state
                _state = new PersistentState(seedId);
                Bufferable val;
                if (tx.TryGet(_stateDb, StateDbKeys.Id, out val))
                {
                    _state.Id = val;

                    if (tx.TryGet(_stateDb, StateDbKeys.CurrentTerm, out val)) // this should be always TRUE
                    {
                        _state.CurrentTerm = val;
                    }

                    if (tx.TryGet(_stateDb, StateDbKeys.LastVotedFor, out val))
                    {
                        Guid g = val;
                        _state.LastVotedForId = g == Guid.Empty ? (Guid?)null : g;
                    }
                }
            }

            TheTrace.TraceInformation($"Seed Id was {seedId} and now {_state.Id}");
        }
Beispiel #9
0
        public void SmartContracts_GasInjector_MultipleParamConstructorGasInjectedSuccess()
        {
            SmartContractCompilationResult compilationResult =
                SmartContractCompiler.Compile(TestMultipleConstructorSource);

            Assert.True(compilationResult.Success);
            byte[] originalAssemblyBytes = compilationResult.Compilation;

            var gasLimit                  = (Gas)500000;
            var gasMeter                  = new GasMeter(gasLimit);
            var persistenceStrategy       = new MeteredPersistenceStrategy(this.repository, gasMeter, new BasicKeyEncodingStrategy());
            var persistentState           = new PersistentState(persistenceStrategy, TestAddress.ToUint160(this.network), this.network);
            var internalTxExecutorFactory = new InternalTransactionExecutorFactory(this.keyEncodingStrategy, this.loggerFactory, this.network);
            var vm = new ReflectionVirtualMachine(internalTxExecutorFactory, this.loggerFactory);
            var executionContext = new SmartContractExecutionContext(new Block(0, TestAddress), new Message(TestAddress, TestAddress, 0, (Gas)500000), TestAddress.ToUint160(this.network), 1, new[] { "Tset Owner" });

            var result = vm.Create(
                originalAssemblyBytes,
                executionContext,
                gasMeter, persistentState, repository);

            // Constructor: 15
            // Property setter: 12
            // Storage: 150
            Assert.Equal((Gas)177, result.GasConsumed);
        }
Beispiel #10
0
        public void TestGasInjector_OutOfGasFails()
        {
            SmartContractCompilationResult compilationResult = SmartContractCompiler.CompileFile("SmartContracts/OutOfGasTest.cs");

            Assert.True(compilationResult.Success);

            byte[] originalAssemblyBytes = compilationResult.Compilation;

            var gasLimit                  = (Gas)500000;
            var gasMeter                  = new GasMeter(gasLimit);
            var persistenceStrategy       = new MeteredPersistenceStrategy(this.repository, gasMeter, this.keyEncodingStrategy);
            var persistentState           = new PersistentState(persistenceStrategy, TestAddress.ToUint160(this.network), this.network);
            var internalTxExecutorFactory =
                new InternalTransactionExecutorFactory(this.keyEncodingStrategy, this.loggerFactory, this.network);
            var vm = new ReflectionVirtualMachine(internalTxExecutorFactory, this.loggerFactory);

            var executionContext = new SmartContractExecutionContext(new Block(0, TestAddress), new Message(TestAddress, TestAddress, 0, (Gas)500000), TestAddress.ToUint160(this.network), 1);

            var result = vm.ExecuteMethod(
                originalAssemblyBytes,
                "UseAllGas",
                executionContext,
                gasMeter, persistentState, repository);

            Assert.NotNull(result.ExecutionException);
            Assert.Equal((Gas)0, gasMeter.GasAvailable);
            Assert.Equal(gasLimit, result.GasConsumed);
            Assert.Equal(gasLimit, gasMeter.GasConsumed);
        }
Beispiel #11
0
        public static void HandleUpgrade()
        {
            var old = Filesystem.OldStateFile;

            if (File.Exists(old))
            {
                PersistentState state = new PersistentState(old);

                if (!state.HasEliteCmdrName())
                {
                    CheapHackController hack = new CheapHackController(
                        new EliteJournalParser(Filesystem.GuessJournalPath()),
                        state);
                    hack.Run();

                    if (!state.HasEliteCmdrName())
                    {
                        MessageBox.Show("Picard is exiting without saving.");
                        Application.Exit();
                        return;
                    }
                }

                state.StateFile = Filesystem.GetStatePath(
                    state.CurrentState.EliteCmdrName);
                state.Persist();
                File.Delete(old);
                MessageBox.Show("Your Picard state file has been upgraded.", "Multi-Commander Support!!");
            }
        }
    public void LoadGame()
    {
        PersistentState newState = loadGame.InstantiateState();

        newState.LoadProgress(savedGamePath);
        loadGame.BeginPlay();
    }
        public void SmartContractList_CanAccessValueUsingIndexTest()
        {
            var listName = "testList";

            var source = new MemoryDictionarySource();
            var root   = new ContractStateRoot(source);

            IContractState       state = root.StartTracking();
            IPersistenceStrategy persistenceStrategy = new PersistenceStrategy(state);
            var persistentState = new PersistentState(
                persistenceStrategy,
                this.contractPrimitiveSerializer,
                uint160.One);

            var list = new SmartContractList <string>(persistentState, listName);

            Assert.Equal((uint)0, list.Count);

            // Set a value in the list
            list.Add("Test");
            list.Add("Test2");

            var testItem  = list.GetValue(0);
            var testItem2 = list.GetValue(1);

            var firstItemHash  = $"{listName}[0]";
            var secondItemHash = $"{listName}[1]";

            var item  = persistentState.GetString(firstItemHash);
            var item2 = persistentState.GetString(secondItemHash);

            Assert.Equal(testItem, item);
            Assert.Equal(testItem2, item2);
        }
        public void SmartContractList_ListHasValueTest()
        {
            var listName = "testList";

            var source = new MemoryDictionarySource();
            var root   = new ContractStateRoot(source);

            IContractState       state = root.StartTracking();
            IPersistenceStrategy persistenceStrategy = new PersistenceStrategy(state);

            var persistentState = new PersistentState(
                persistenceStrategy,
                this.contractPrimitiveSerializer,
                uint160.One);

            var list = new SmartContractList <string>(persistentState, listName);

            Assert.Equal((uint)0, list.Count);

            var testItem = "Test";

            list.Add(testItem);
            var item1 = list.GetValue(0);

            Assert.Equal(testItem, item1);
        }
Beispiel #15
0
        private void SnapshotAndTruncateLog(long to, ManualResetEventSlim allowFurtherModifications)
        {
            var task = new Task(() =>
            {
                OnSnapshotCreationStarted();
                try
                {
                    var currentTerm = PersistentState.CurrentTerm;
                    _log.Info("Starting to create snapshot up to {0} in term {1}", to, currentTerm);
                    StateMachine.CreateSnapshot(to, currentTerm, allowFurtherModifications);
                    PersistentState.MarkSnapshotFor(to, currentTerm,
                                                    Options.MaxLogLengthBeforeCompaction - (Options.MaxLogLengthBeforeCompaction / 8));

                    _log.Info("Finished creating snapshot for {0} in term {1}", to, currentTerm);

                    OnSnapshotCreationEnded();
                }
                catch (Exception e)
                {
                    _log.Error("Failed to create snapshot", e);
                    OnSnapshotCreationError(e);
                }
                finally
                {
                    Interlocked.Exchange(ref _snapshottingTask, null);
                }
            });

            if (Interlocked.CompareExchange(ref _snapshottingTask, task, null) != null)
            {
                allowFurtherModifications.Set();
                return;
            }
            task.Start();
        }
        public NormalRunController(
            InaraApi api,
            PersistentState state,
            EliteJournalParser logs,
            DataMangler dm)
        {
            this.api   = api;
            this.state = state;
            this.logs  = logs;
            this.dm    = dm;

            MaterialTypeLookup = dm.MaterialTypeLookup;

            MaterialTypes = new List <string>(dm.MaterialTypes);
            MaterialTypes.Add("Grand");

            MaterialOrder = new List <string>(dm.MaterialOrder);
            foreach (var type in MaterialTypes)
            {
                MaterialOrder.Add(type + " Total");
            }

            form                   = new MatUpdateForm(MaterialOrder);
            form.ReloadMats       += OnReloadMats;
            form.PostAndSave      += OnPostAndSave;
            form.CloseWithoutSave += OnCloseWithoutSave;
            form.Activated        += ReloadMatsIfNecessary;
        }
Beispiel #17
0
        public void Follower_as_a_single_node_becomes_leader_automatically()
        {
            var hub = new InMemoryTransportHub();
            var storageEnvironmentOptions = StorageEnvironmentOptions.CreateMemoryOnly();

            storageEnvironmentOptions.OwnsPagers = false;

            var raftEngineOptions = new RaftEngineOptions(
                new NodeConnectionInfo {
                Name = "node1"
            },
                storageEnvironmentOptions,
                hub.CreateTransportFor("node1"),
                new DictionaryStateMachine()
                )
            {
                ElectionTimeout  = 1000,
                HeartbeatTimeout = 1000 / 6
            };

            PersistentState.ClusterBootstrap(raftEngineOptions);
            storageEnvironmentOptions.OwnsPagers = true;

            using (var raftNode = new RaftEngine(raftEngineOptions))
            {
                Assert.Equal(RaftEngineState.Leader, raftNode.State);
            }
        }
        public async void LoadStoredState()
        {
            // (We can't call SessionState from inside a constructor)
            // Check to see whether editor prefs exist of our persistent state
            // If it does, load that now and clear the state
            string persistentState = SessionState.GetString(PersistentStateKey, string.Empty);

            if (!string.IsNullOrEmpty(persistentState))
            {
                state = JsonUtility.FromJson <PersistentState>(persistentState);
                // If we got this far we know we were successful
                Result = CreateResult.Successful;
                // If we were interrupted during script creation, move to profile creation
                switch (Stage)
                {
                case CreationStage.CreatingExtensionService:
                    await ResumeAssetCreationProcessAfterReload();

                    break;
                }
            }
            else
            {
                // Otherwise create a default state
                CreateDefaultState();
            }
        }
Beispiel #19
0
 internal void UpdateCurrentTerm(long term, string leader)
 {
     PersistentState.UpdateTermTo(this, term);
     SetState(RaftEngineState.Follower);
     _log.Debug("UpdateCurrentTerm() setting new leader : {0}", leader ?? "no leader currently");
     CurrentLeader = leader;
 }
Beispiel #20
0
        public void Dispose()
        {
            _eventLoopCancellationTokenSource.Cancel();
            _eventLoopTask.Wait(500);

            PersistentState.Dispose();
        }
Beispiel #21
0
        public SettingsForm(PersistentState state, InternetStreamingStatistics _internetStreamingStatistics)
        {
            if (null == state)
            {
                throw new ArgumentNullException("state");
            }
            State = state;
            InitializeComponent();

            var userGraphValues = (PersistentState.UserCalculatedAttribute[])Enum.GetValues(typeof(PersistentState.UserCalculatedAttribute));

            comboBoxEditUserGraph.Properties.Items.AddRange(userGraphValues);

            comboBoxEditTemp.Properties.Items.AddRange(Enum.GetValues(typeof(TemperatureUnit)));
            comboBoxEditPress.Properties.Items.AddRange(Enum.GetValues(typeof(PressureUnit)));
            comboBoxEditSpeed.Properties.Items.AddRange(Enum.GetValues(typeof(SpeedUnit)));

            SetValuesFromState();


            //rp
            //MessageBox.Show("statistic___ sended: "+_internetStreamingStatistics.m_StreamingServers[0].GetSendetPacekets() + " received" + _internetStreamingStatistics.m_StreamingServers[0].GetReadedPacekets() );
            label_statistic_incomming_packets.Text = "" + _internetStreamingStatistics.m_StreamingServers[0].GetReadedPacekets();
            label_statistic_sendet_packets.Text    = "" + _internetStreamingStatistics.m_StreamingServers[0].GetSendetPacekets();
        }
Beispiel #22
0
        // ------------------------------
        // internal
        // ------------------------------
        /// <summary>
        /// Commit()時に処理が必要なentityがGCされないようにする.
        /// </summary>
        internal void MaintainStrongReference(object entity, PersistentState state)
        {
            switch (state)
            {
            /// インスタンスが削除されても復元可能なもの
            case PersistentState.Hollow:
            case PersistentState.Discarded:
            case PersistentState.Latest: {
                var ent = AsEntity(entity);
                if (!ent.IsExtendedDataDirty && !ent.IsExtendedObjectDataDirty)
                {
                    _strongReferenced.Remove(entity);
                }
                break;
            }

            /// インスタンスが削除されると復元できないもの
            case PersistentState.Removed:
            case PersistentState.Updated:
            case PersistentState.New: {
                _strongReferenced.Add(entity);
                break;
            }

            /// 管理対象外
            case PersistentState.Transient: {
                /// do nothing
                break;
            }
            }
        }
        /// <summary>
        /// Creates a server entry creator.
        /// </summary>
        public NewServerEntry()
        {
            // Load the XAML.
            AvaloniaXamlLoader.Load(this);
            this.inputs             = this.Get <StackPanel>("Inputs");
            this.serverNameInput    = this.Get <TextBox>("ServerNameInput");
            this.serverAddressInput = this.Get <TextBox>("ServerAddressInput");
            this.addButton          = this.Get <RoundedButton>("AddButton");
            this.cancelButton       = this.Get <ImageButton>("CancelButton");

            // Connect the inputs.
            this.addButton.ButtonPressed += (sender, args) =>
            {
                if (this.addingOpen)
                {
                    // Add the entry if the inputs are valid.
                    if (this.addButton.Active)
                    {
                        // Add the entry.
                        PersistentState.AddServerEntry(this.serverNameInput.Text.Trim(),
                                                       this.serverAddressInput.Text.Trim());

                        // Clear the inputs.
                        this.serverNameInput.Text    = "";
                        this.serverAddressInput.Text = "";

                        // Close adding.
                        this.addingOpen = false;
                        this.Update();
                    }
                }
                else
                {
                    // Open adding.
                    this.addingOpen = true;
                    this.Update();
                }
            };
            this.cancelButton.ButtonPressed += (sender, args) =>
            {
                // Clear the inputs.
                this.serverNameInput.Text    = "";
                this.serverAddressInput.Text = "";

                // Close adding.
                this.addingOpen = false;
                this.Update();
            };
            this.serverNameInput.PropertyChanged += (sender, args) =>
            {
                this.Update();
            };
            this.serverAddressInput.PropertyChanged += (sender, args) =>
            {
                this.Update();
            };

            // Update the initial display.
            this.Update();
        }
Beispiel #24
0
    public int Start(Address sendTo)
    {
        int result = (int)Call(sendTo, this.Balance / 2, "Call1").ReturnValue;

        PersistentState.SetInt32(Key, result);
        return(result);
    }
Beispiel #25
0
        public void ApplyCommits(long from, long to)
        {
            Debug.Assert(to >= from);
            foreach (var entry in PersistentState.LogEntriesAfter(from, to))
            {
                try
                {
                    var oldCommitIndex = CommitIndex;
                    var command        = PersistentState.CommandSerializer.Deserialize(entry.Data);

                    StateMachine.Apply(entry, command);

                    Debug.Assert(entry.Index == StateMachine.LastAppliedIndex);
                    if (_log.IsDebugEnabled)
                    {
                        _log.Debug("Committing entry #{0}", entry.Index);
                    }

                    var tcc = command as TopologyChangeCommand;
                    if (tcc != null)
                    {
                        if (_log.IsInfoEnabled)
                        {
                            _log.Info("ApplyCommits for TopologyChangedCommand, tcc.Requested = {0}, Name = {1}",
                                      tcc.Requested, Name);
                        }

                        // StartTopologyChange(tcc); - not sure why it was needed, see RavenDB-3808 for details
                        CommitTopologyChange(tcc);
                    }

                    OnCommitIndexChanged(oldCommitIndex, CommitIndex);
                    OnCommitApplied(command);
                }
                catch (Exception e)
                {
                    _log.Error("Failed to apply commit", e);
                    throw;
                }
            }

            if (StateMachine.SupportSnapshots == false)
            {
                return;
            }

            var commitedEntriesCount = PersistentState.GetCommitedEntriesCount(to);

            if (commitedEntriesCount >= Options.MaxLogLengthBeforeCompaction)
            {
                // we need to pass this to the state machine so it can signal us
                // when it is fine to continue modifications again, otherwise
                // we might start the snapshot in a different term / index than we
                // are actually saying we did.
                var allowFurtherModifications = new ManualResetEventSlim();
                SnapshotAndTruncateLog(to, allowFurtherModifications);
                allowFurtherModifications.Wait(CancellationToken);
            }
        }
Beispiel #26
0
        public AuthenticationController(InaraApi api, PersistentState state)
        {
            this.api   = api;
            this.state = state;

            form = new WelcomeLoginForm();
            form.TryAuthentication += OnTryAuthentication;
        }
 private void CreateDefaultState()
 {
     state             = new PersistentState();
     state.ServiceName = "NewService";
     state.UsesProfile = true;
     state.Stage       = CreationStage.SelectNameAndPlatform;
     state.Platforms   = SupportedPlatforms.LinuxStandalone | SupportedPlatforms.MacStandalone | SupportedPlatforms.WindowsStandalone | SupportedPlatforms.WindowsUniversal;
 }
Beispiel #28
0
 public void Danger__CutLogAtPosition(long postion)
 {
     PersistentState.AppendToLog(this, new List <LogEntry>(), postion);
     if (postion < StateMachine.LastAppliedIndex)
     {
         StateMachine.Danger__SetLastApplied(postion);
     }
 }
 // ========================================
 // constructor
 // ========================================
 internal PersistenceMaintainer(
     EntityInterceptor entityInterceptor, EntityContainer container, PersistentState state
     )
 {
     _entityInterceptor = entityInterceptor;
     _container         = container;
     _state             = state;
 }
        private Dictionary <string, byte[]> _extendedObjectData; /// lazy

        // ========================================
        // constructor
        // ========================================
        public EntityInterceptor(
            Type type, EntityContainer container, PersistentState state
            )
        {
            _type                  = type;
            _container             = container;
            _persistenceMaintainer = new PersistenceMaintainer(this, container, state);
        }