Exemple #1
0
 public override void TakeSnapshot(StateSnapshot ss)
 {
     // write identifier 6 to indicate that this is a DelayedVolatileRead
     ss.WriteInt(6);
     ss.WriteGuid(srcValue);
     ss.WriteGuid(destValue);
 }
Exemple #2
0
		protected override StateSnapshot DoSnapshot(StateSnapshot initial)
		{
			var retval = initial;
			var entry = new StateSnapshot.FieldEntry();
			entry.Name = "m_functionMetadatas";
			entry.Type = m_functionMetadatas.GetType();
			entry.Attrib = null;
			entry.Value = m_functionMetadatas.ToDictionary(kv => kv.Key, kv => kv.Value);
			retval.Fields.Add(entry);
			return retval;
		}
        /// <summary>
        /// connect was selected in the context menu
        /// </summary>
        /// <param name="sender">ignored</param>
        /// <param name="e">ignored</param>
        private void m_menu_connect_Click(object sender, EventArgs e)
        {
            // connect only, if we are disconnected
            StateSnapshot ss = m_vpn.State.CreateSnapshot();

            if (ss.ConnectionState == VPNConnectionState.Stopped ||
                ss.ConnectionState == VPNConnectionState.Error)
            {
                Connect();
            }
        }
Exemple #4
0
        public static string GenerateTag <T>(StateSnapshot snapshot = null) where T : ProfileBehavior
        {
            var result = string.Empty;
            var s      = snapshot ?? StateSnapshot.Create();

            if (s == null)
            {
                return(result);
            }

            var stateDict = s.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToDictionary(k => k.Name, v => v.GetValue(s));

            result += $@"     <{typeof(T).Name.TrimEnd("Tag")} questId=""{s.QuestId}"" stepId=""{s.QuestStep}"" ";

            foreach (var propertyInfo in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                var xmlAttributes = propertyInfo.GetCustomAttributes <XmlAttributeAttribute>();
                var attName       = xmlAttributes.LastOrDefault()?.Name ?? string.Empty;

                if (string.IsNullOrEmpty(attName) || IgnoreXmlAttributeNames.Contains(attName))
                {
                    continue;
                }

                var valueMatch = stateDict.FirstOrDefault(i
                                                          => string.Equals(propertyInfo.Name.ToLowerInvariant(), i.Key.ToLowerInvariant(), StringComparison.InvariantCultureIgnoreCase) ||
                                                          string.Equals(attName, i.Key.ToLowerInvariant(), StringComparison.InvariantCultureIgnoreCase));

                var value = valueMatch.Value ?? GetDefaultValue(propertyInfo);
                if (value == null)
                {
                    continue;
                }

                if (IsNumericType(propertyInfo.PropertyType) && !propertyInfo.Name.Contains("Id"))
                {
                    value   = Math.Round((decimal)Convert.ChangeType(value, typeof(decimal)), 3, MidpointRounding.AwayFromZero);
                    result += $@"{attName}=""{value:0.##}"" ";
                }
                else
                {
                    if (propertyInfo.PropertyType == typeof(bool))
                    {
                        value = value.ToString().ToLowerInvariant();
                    }

                    result += $@"{attName}=""{value}"" ";
                }
            }

            result += $@" worldSnoId=""{s.WorldSnoId}"" levelAreaSnoId=""{s.LevelAreaSnoId}"" />";
            return(result);
        }
Exemple #5
0
		protected override void DoSerialize(Stream ostream, StateSnapshot oldSnapshot)
		{
			var oldDict = (Dictionary<string,FunctionMetadata>)oldSnapshot.Fields.First(field => field.Name == "m_functionMetadatas").Value;
			foreach (var k in m_functionMetadatas.Keys.Except(oldDict.Keys))
			{
				var newEntry = m_functionMetadatas[k];

				var writer = new BinaryWriter(ostream);
				writer.Write((char)0xD9);
				writer.Write(newEntry.Name);
				writer.Write(newEntry.HostClass);
				writer.Write(newEntry.MethodName);
			}
		}
Exemple #6
0
        /// <summary>
        /// Reverts the state to a previous snapshot.
        /// </summary>
        private void Rollback(StateSnapshot snapshot)
        {
            this.intermediateState = snapshot.ContractState;

            // Reset the nonce
            this.Nonce = snapshot.Nonce;

            // Rollback internal transfers
            this.internalTransfers.Clear();
            this.internalTransfers.AddRange(snapshot.InternalTransfers);

            // Rollback logs
            this.LogHolder.Clear();
            this.LogHolder.AddRawLogs(snapshot.Logs);
        }
Exemple #7
0
        public static string GenerateMarkerTags <T>(Func <TrinityMarker, bool> markerSelector = null) where T : ProfileBehavior
        {
            var sb = new StringBuilder();
            var s  = StateSnapshot.Create();

            foreach (var marker in Core.Markers.Where(a => markerSelector?.Invoke(a) ?? true))
            {
                s.UpdateForMarker(marker);
                var actorMsg = s.ActorId != 0 ? $"Actor={s.ActorName} ({s.ActorId}) " : string.Empty;
                sb.AppendLine($"     <!-- {marker.NameHash} {marker.MarkerType} Distance={marker.Distance} TextureId={marker.TextureId} WorldSnoId={marker.WorldSnoId} {actorMsg}-->");
                sb.AppendLine(GenerateTag <T>(s));
                sb.AppendLine(Environment.NewLine);
            }
            return(sb.ToString());
        }
Exemple #8
0
        private StateTransitionResult ApplyCall(CallMessage message, byte[] contractCode)
        {
            if (this.GasRemaining < message.GasLimit || this.GasRemaining < GasPriceList.BaseCost)
            {
                return(StateTransitionResult.Fail((Gas)0, StateTransitionErrorKind.InsufficientGas));
            }

            var gasMeter = new GasMeter(message.GasLimit);

            gasMeter.Spend((Gas)GasPriceList.BaseCost);

            if (message.Method.Name == null)
            {
                return(StateTransitionResult.Fail(gasMeter.GasConsumed, StateTransitionErrorKind.NoMethodName));
            }

            StateSnapshot stateSnapshot = this.TakeSnapshot();

            IContractState state = this.CreateIntermediateState();

            string type = state.GetContractType(message.To);

            ISmartContractState smartContractState = this.CreateSmartContractState(gasMeter, message.To, message, state);

            VmExecutionResult result = this.Vm.ExecuteMethod(smartContractState, message.Method, contractCode, type);

            this.GasRemaining -= gasMeter.GasConsumed;

            bool revert = result.ExecutionException != null;

            if (revert)
            {
                this.Rollback(stateSnapshot);

                return(StateTransitionResult.Fail(
                           gasMeter.GasConsumed,
                           result.ExecutionException));
            }

            state.Commit();
            this.GasRemaining -= gasMeter.GasConsumed;

            return(StateTransitionResult.Ok(
                       gasMeter.GasConsumed,
                       message.To,
                       result.Result
                       ));
        }
Exemple #9
0
        /// <summary>
        /// Disconnects from the OpenVPN Service.
        /// </summary>
        /// <seealso cref="Connect"/>
        public override void Disconnect()
        {
            StateSnapshot ss = State.CreateSnapshot();

            if (ss.ConnectionState == VPNConnectionState.Stopped ||
                State.ConnectionState == VPNConnectionState.Error)
            {
                State.ChangeState(VPNConnectionState.Stopped);
                return;
            }
            State.ChangeState(VPNConnectionState.Stopping);

            var del = new UtilsHelper.Action(killConnection);

            del.BeginInvoke(null, null);
        }
        /// <summary>
        /// display buttons and text as needed
        /// </summary>
        /// <param name="ss">new State</param>
        private void setState(StateSnapshot ss)
        {
            bool   showConnect       = true;// If false then show Disconnect
            bool   showConnectEnable = true;
            String ip = null;

            switch (ss.ConnectionState)
            {
            case VPNConnectionState.Initializing:
                pbStatus.Image = Properties.Resources.STATE_Initializing;
                showConnect    = false;
                break;

            case VPNConnectionState.Running:
                pbStatus.Image = Properties.Resources.STATE_Running;
                showConnect    = false;
                ip             = m_config.VPNConnection.IP;
                break;

            case VPNConnectionState.Stopped:
                pbStatus.Image = Properties.Resources.STATE_Stopped;
                break;

            case VPNConnectionState.Stopping:
                showConnectEnable = false;
                pbStatus.Image    = Properties.Resources.STATE_Stopping;
                break;

            case VPNConnectionState.Error:
            default:
                pbStatus.Image = Properties.Resources.STATE_Error;
                break;
            }
            if (showConnect)
            {
                btnConnect.Image = Properties.Resources.BUTTON_Connect;
                toolTip.SetToolTip(btnConnect, ProgramVPN.res.GetString("QUICKINFO_Connect"));
            }
            else
            {
                toolTip.SetToolTip(btnConnect, ProgramVPN.res.GetString("QUICKINFO_Disconnect"));
                btnConnect.Image = Properties.Resources.BUTTON_Disconnect;
            }
            btnConnect.Enabled = showConnectEnable;
            llIP.SetIP(ip);
        }
Exemple #11
0
        public static string GenerateActorTags <T>(Func <TrinityActor, bool> actorSelector) where T : ProfileBehavior
        {
            var sb = new StringBuilder();
            var s  = StateSnapshot.Create();

            foreach (var actor in Core.Actors.Actors.Where(a => !a.IsMe && actorSelector(a)).OrderBy(a => a.Distance))
            {
                s.UpdateForActor(actor);
                var minimapEntry = Core.Minimap.MinimapIcons.FirstOrDefault(m => m.Position.Distance(actor.Position) < 5f);
                var minimapMsg   = minimapEntry != null ? $"MinimapName={minimapEntry.Name} " : string.Empty;
                var markerMsg    = !string.IsNullOrEmpty(s.MarkerName) ? $"Marker={s.MarkerName} ({s.MarkerHash}, {s.MarkerType}) " : string.Empty;
                sb.AppendLine($"     <!-- {actor.Name} ({actor.ActorSnoId}) {actor.ActorSnoId} Distance={actor.Distance} Type={actor.Type} Anim={actor.Animation} {minimapMsg}{markerMsg}-->");
                sb.AppendLine(GenerateTag <T>(s));
                sb.AppendLine(Environment.NewLine);
            }
            return(sb.ToString());
        }
Exemple #12
0
        private StateTransitionResult ApplyCreate(object[] parameters, byte[] code, BaseMessage message, string type = null)
        {
            if (this.GasRemaining < message.GasLimit || this.GasRemaining < GasPriceList.BaseCost)
            {
                return(StateTransitionResult.Fail((Gas)0, StateTransitionErrorKind.InsufficientGas));
            }

            StateSnapshot stateSnapshot = this.TakeSnapshot();

            var gasMeter = new GasMeter(message.GasLimit);

            gasMeter.Spend((Gas)GasPriceList.BaseCost);

            uint160 address = this.GetNewAddress();

            // Begin tracking the new intermediate state. We need to keep this reference around
            // for the scope of the transaction, so we can commit it later.
            IContractState state = this.CreateIntermediateState();

            state.CreateAccount(address);

            ISmartContractState smartContractState = this.CreateSmartContractState(gasMeter, address, message, state);

            VmExecutionResult result = this.Vm.Create(state, smartContractState, code, parameters, type);

            this.GasRemaining -= gasMeter.GasConsumed;

            bool revert = result.ExecutionException != null;

            if (revert)
            {
                this.Rollback(stateSnapshot);

                return(StateTransitionResult.Fail(
                           gasMeter.GasConsumed,
                           result.ExecutionException));
            }

            state.Commit();

            return(StateTransitionResult.Ok(
                       gasMeter.GasConsumed,
                       address,
                       result.Result
                       ));
        }
Exemple #13
0
 public StateSnapshot(IComputed <T> computed, StateSnapshot <T> lastSnapshot)
 {
     Computed = computed;
     if (computed.HasValue)
     {
         LastValueComputed = computed;
         UpdateCount       = 1 + lastSnapshot.UpdateCount;
         FailureCount      = lastSnapshot.FailureCount;
         RetryCount        = 0;
     }
     else
     {
         LastValueComputed = lastSnapshot.LastValueComputed;
         UpdateCount       = 1 + lastSnapshot.UpdateCount;
         FailureCount      = 1 + lastSnapshot.FailureCount;
         RetryCount        = 1 + lastSnapshot.RetryCount;
     }
 }
        public async Task Resume()
        {
            try
            {
                if (_suspendState == null)
                {
                    logger.Info("Restore state not found");
                    return;
                }

                var restoreState = _suspendState;
                _suspendState = null;

                activeTaskCts.Dispose();
                activeTaskCts = new CancellationTokenSource();

                logger.Info("Waiting async Op completion");
                await AsyncOperationCompletions().WithoutException(logger);

                using (await asyncOpSerializer.LockAsync(activeTaskCts.Token))
                {
                    /*Acquire lock prior to proceeding. Async ops may still be terminating.
                     * Not applicable to real life scenarios. Applicable to integration tests*/
                }
                logger.Info("Async Ops completed");

                ClosePlayer();
                player.Dispose();

                // Propagate closures & disposals... or InitAvoc() may fail on MuseM in PreapareAsync().
                await Task.Yield();

                player = new ESPlayer.ESPlayer();

                OpenPlayer();

                await RestoreStateSnapshot(restoreState, activeTaskCts.Token).ConfigureAwait(false);
            }
            catch (Exception e)
                when(!(e is OperationCanceledException))
                {
                    logger.Error(e);
                }
        }
		public static void Aggregate(this StateSnapshot agg, StateSnapshot rhs)
		{
			agg.Rev = Math.Max(agg.Rev, rhs.Rev);
			agg.Timestamp = agg.Timestamp.Join(rhs.Timestamp);

			if (agg.TypeName != rhs.TypeName)
				throw new PatchException(string.Format("Find inconsistant type during aggregation: expecting {0}, got {1}", agg.TypeName, rhs.TypeName));

			if (agg.Fields.Count != rhs.Fields.Count)
				throw new PatchException(string.Format("Inconsistant number of fields: expecting {0}, got {1}", agg.Fields.Count, rhs.Fields.Count));

			var fpairSeq =	from a in agg.Fields
							join b in rhs.Fields
							on a.Name equals b.Name select new FieldEntryPair(a,b);

			foreach (var fpair in fpairSeq)
			{
				if (0 == (fpair.First.Attrib.PatchKind & FieldPatchCompatibility.CommutativeDelta))
					continue;

				if (fpair.First.Type != fpair.Second.Type)
					throw new PatchException(string.Format("Inconsistant field type found: expecting {0}, got {1}", fpair.First.Type.Name, fpair.Second.Type.Name));

				var type = fpair.First.Type;

				if (type == typeof(int))
				{
					Accumulate(ref fpair.First.Value, (int)fpair.Second.Value);
				}
				else if (type == typeof(float))
				{
					Accumulate(ref fpair.First.Value, (float)fpair.Second.Value);
				}
				else if (type == typeof(string))
				{
					throw new NotImplementedException();
				}
				else
					throw new PatchException(string.Format("Non-Primitive type found as a field of a state: state {0}, field {1}", agg.TypeName, fpair.First.Name));
			}
		}
Exemple #16
0
 public StateSnapshot(StateSnapshot <T> prevSnapshot, IComputed <T> computed)
 {
     State              = prevSnapshot.State;
     Computed           = computed;
     WhenUpdatingSource = TaskSource.New <Unit>(true);
     WhenUpdatedSource  = TaskSource.New <Unit>(true);
     if (computed.HasValue)
     {
         LatestNonErrorComputed = computed;
         UpdateCount            = 1 + prevSnapshot.UpdateCount;
         ErrorCount             = prevSnapshot.ErrorCount;
         RetryCount             = 0;
     }
     else
     {
         LatestNonErrorComputed = prevSnapshot.LatestNonErrorComputed;
         UpdateCount            = 1 + prevSnapshot.UpdateCount;
         ErrorCount             = 1 + prevSnapshot.ErrorCount;
         RetryCount             = 1 + prevSnapshot.RetryCount;
     }
 }
        private async Task RestoreStateSnapshot(StateSnapshot restorePoint, CancellationToken token)
        {
            logger.Info($"Restoring to State/Position {restorePoint.State}/{restorePoint.Position}");

            // Push stream configurations, if any
            SetPlayerConfiguration();
            if (!AllStreamsHaveConfiguration)
            {
                logger.Info($"Not all streams have configuration");
                return;
            }

            // Try starting. Suspend in paused/idle is ignored. If configurations exist, start.
            _dataClock.Clock = restorePoint.Position;

            if (false == await ExecutePreparePlayback(token))
            {
                return;
            }

            Play();
            SubscribeBufferingEvent();
        }
Exemple #18
0
		public StateSnapshot Snapshot( IHTimestamp overridingTS)
		{
			var retval = new StateSnapshot(StateId, GetType().AssemblyQualifiedName, overridingTS, Rev);

			if (m_patchMethod == StatePatchMethod.Customized)
			{
				return DoSnapshot(retval);
			}

			foreach (var fi in GetFields())
			{
				var fval = fi.GetValue(this);
				retval.Fields.Add(new StateSnapshot.FieldEntry() {
					Name = fi.Name,
					Value = fval,
					Type = fi.FieldType,
					Attrib = fi.GetCustomAttributes(typeof(StateFieldAttribute), false).FirstOrDefault() as StateFieldAttribute
				});
			}
			return retval;
		}
Exemple #19
0
		protected virtual void DoSerialize(Stream ostream, StateSnapshot oldSnapshot) { throw new NotImplementedException(); }
Exemple #20
0
 public abstract void TakeSnapshot(StateSnapshot ss);
Exemple #21
0
 public override void TakeSnapshot(StateSnapshot ss)
 {
     // write identifier 3 to indicate that this is a DelayedUnlock
     ss.WriteInt(3);
     ss.WriteGuid(obj);
 }
Exemple #22
0
 public virtual void DoTimeStep(CellInstance cell,ComponentWorldStateBase compData, StateSnapshot state, double time, double timeStep)
 {
 }
Exemple #23
0
 public override void InitializeInEnvironment(CellInstance cell, StateSnapshot state)
 {
     ComponentType.InitializeInEnvironment(cell, this, state);
 }
Exemple #24
0
 public override void DoTimeStep(CellInstance cell, ComponentWorldStateBase compData, StateSnapshot state, double time, double timeStep)
 {
     //nothing to do there
 }
Exemple #25
0
        //update output (ie set values in simulator)
        private void updateOutput(CellInstance cell, StateSnapshot state)
        {
            SpeciesReference speciesRef = this.getSpeciesReference(0, ComponentLinkType.Output);
            NutrientField attractant = state.SimulationEnvironment.GetNutrientFieldObject(nutrientIndex);

            float amount = attractant.GetNutrientLevel(cell.CellInstanceSpatialContext.Position);

            cell.setSpeciesAmountInSimulation(speciesRef.species.ID,amount / 10 );
            cell.setSpeciesAmount(speciesRef.species.ID, amount / 10);
        }
Exemple #26
0
 // Dump the data structure to the snapshot
 public override void TakeSnapshot(StateSnapshot ss)
 {
     // write identifier 8 to indicate that this is a DelayedWait
     ss.WriteInt(8);
     ss.WriteInt(lockCount);
     ss.WriteGuid(obj);
 }
		protected override void DoSerialize(Stream ostream, StateSnapshot oldSnapshot)
		{
			var oldDict = ((_StateRef[])oldSnapshot.Fields.First(field => field.Name == "m_nativeStates").Value)
				.ToDictionary(kv => kv.sid, kv => kv.refType);

			foreach (var newEntry in m_nativeStates.Keys.Except(oldDict.Keys).Select( k => m_nativeStates[k] ))
			{
				var writer = new BinaryWriter(ostream);
				writer.Write(MAGICBYTE);
				writer.Write(newEntry.StateId.ToUlong());
				writer.Write(newEntry.GetType().ToString());
			}
		}
Exemple #28
0
 public override void TakeSnapshot(StateSnapshot ss)
 {
     // write identifier 1 to indicate that this is a DelayedWrite
     ss.WriteInt(1);
     ss.WriteGuid(srcValue);
     ss.WriteGuid(destValue);
 }
			public Present(StateSnapshot[] accounts, AABB worldBox)
			{
				m_accounts = accounts;
				m_worldbox = worldBox;
			}
Exemple #30
0
        /// <summary>
        /// Execute a timestep, manipulating data accordingly
        /// </summary>
        /// <param name="cell">The cell to which this component belongs</param>
        /// <param name="state">The current environment state</param>
        /// <param name="time">Simulation time</param>
        /// <param name="timeStep">Simulation time step</param>
        public override void DoTimeStep(CellInstance cell, ComponentWorldStateBase compData,StateSnapshot state, double time, double timeStep)
        {
            FlagellaWorldState flage = (FlagellaWorldState)compData;

            //NutrientField attractant = state.SimulationEnvironment.GetNutrientFieldObject(attractantIndex);
            //NutrientField repellent = state.SimulationEnvironment.GetNutrientFieldObject(repellentIndex);
            float valueFromCircuit = (float)cell.getLocalSimulationSpeciesAmount(getSpeciesReference(0, ComponentLinkType.Input).species.ID);

            if (flage.TumbleState)
            {
                flage.TumbleCounter += (float)timeStep;

                //end of tumble
                if (flage.TumbleCounter > tumbleDuration)
                {
                    cell.CellInstanceSpatialContext.Reorientate(new Vector3((float)(cell.GetRandomObject().NextDouble() * 2 - 1),
                                                             (float)(cell.GetRandomObject().NextDouble() * 2 - 1),
                                                             (float)(cell.GetRandomObject().NextDouble() * 2 - 1)));

                    flage.TumbleState = false;
                    //up to 50% varience in next tumble duration
                    flage.TumbleCounter = 0.0f + tumbleDuration*0.5f*(float)cell.GetRandomObject().NextDouble();

                }

            }
            else
            {

                flage.TumbleUpdateCounter += (float)timeStep;

                //Randomly decide whether or not to tumble according to some likelihood
                if (flage.TumbleUpdateCounter > 1.0f / TumbleUpdateFrequency)
                {
                    float val = flage.TumbleLikelihood - (float)cell.GetRandomObject().NextDouble();

                    if (flage.TumbleLikelihood - (float)cell.GetRandomObject().NextDouble() > 0)
                    {
                        //tumble
                        flage.TumbleState = true;
                    }

                    flage.TumbleUpdateCounter = 0.0f;
                }

                flage.SampleCounter += (float)timeStep;

                //propel cell forward
                cell.CellInstanceSpatialContext.Accelerate(new Vector3(
                    cell.CellInstanceSpatialContext.Orientation.x * motiveStength * (float)timeStep,
                    cell.CellInstanceSpatialContext.Orientation.y * motiveStength * (float)timeStep,
                    cell.CellInstanceSpatialContext.Orientation.z * motiveStength * (float)timeStep));

                if (flage.SampleCounter > 0.4f)
                {
                    /*
                    if (!flage.FirstSampleTaken)
                    {
                        //flage.FirstSample = attractant.GetNutrientLevel(cell.CellInstanceSpatialContext.Position);
                        flage.FirstSample = valueFromCircuit;
                        flage.FirstSampleTaken = true;
                    }*/
                }

                if (flage.SampleCounter > 0.8f)
                {

                   // float SecondSample = attractant.GetNutrientLevel(cell.CellInstanceSpatialContext.Position);
                    /*
                    float SecondSample = valueFromCircuit;

                    if (SecondSample > flage.FirstSample)
                    {
                        //continue going straight
                        flage.TumbleLikelihood = 0.001f;

                    }
                    else
                    {
                        //tumble
                        flage.TumbleLikelihood = 0.995f;

                    }*/

                    if (valueFromCircuit > 1.0f)
                    {
                        flage.TumbleLikelihood = 0.90f;
                    }
                    else
                    {
                        flage.TumbleLikelihood = 0.1f;
                    }

                    flage.SampleCounter = 0.0f;
                   // flage.FirstSampleTaken = false;

                }

            }
        }
Exemple #31
0
 public override void DoTimeStep(CellInstance cell, ComponentWorldStateBase compData, StateSnapshot state, double time, double timeStep)
 {
     updateOutput(cell, state);
 }
Exemple #32
0
		protected virtual StateSnapshot DoSnapshot(StateSnapshot initial) { throw new NotImplementedException(); }
Exemple #33
0
 public override void InitializeInEnvironment(CellInstance cell, ComponentWorldStateBase compData, StateSnapshot state)
 {
     cell.CellInstanceSpatialContext.Mass = mass;
     cell.CellInstanceSpatialContext.Radius = radius;
 }
Exemple #34
0
 public override void TakeSnapshot(StateSnapshot ss)
 {
     throw new Exception("Should not be called");
 }
Exemple #35
0
 public override void DoTimeStep(CellInstance cell, StateSnapshot state, double time, double timeStep)
 {
     ComponentType.DoTimeStep(cell, this, state, time, timeStep);
 }
 internal void ResetSnapshot()
 {
     _snapshot = null;
     _snapshotReplay = false;
 }
Exemple #37
0
 public virtual void InitializeInEnvironment(CellInstance cell, ComponentWorldStateBase compData, StateSnapshot state)
 {
 }
Exemple #38
0
        public void SimpleStateTests()
        {
            // Create a state fresh.
            State state = new State();

            // Create a state snapshot of the blank state
            StateSnapshot cleanSnapshot    = state.Snapshot();
            StateSnapshot modifiedSnapshot = null;

            // Create an account and assert it should be blank.
            Address address  = new Address(0);
            Address address2 = new Address(1);

            // This loop is made to 1) test clean state and 2) modified state, test modifications. 3) do the same edits using snapshots and verify those work too, then finally 4) test with committing changes between.
            for (int i = 0; i < 4; i++)
            {
                // 1) VERIFY CLEAN VARIABLES
                Assert.True(state.GetAccount(address).IsBlank); // account is blank at first
                Assert.Equal(0, state.GetBalance(address));
                Assert.Equal(0, state.GetBalance(address2));
                Assert.Empty(state.GetCodeSegment(address));        // empty code segment at first
                Assert.Equal(0, state.GetStorageData(address, 0));  // storage has no values, should all be 0.
                Assert.Equal(0, state.GetStorageData(address2, 0)); // storage has no values, should all be 0.
                Assert.Equal(0, state.GetNonce(address));           // nonce is 0 by default
                Assert.Equal(0, state.GetNonce(address2));          // nonce is 0 by default
                Assert.Equal(0, state.TransactionRefunds);
                Assert.False(state.GetAccount(address).IsDirty);

                // 2) SET SOME VARIABLES
                if (modifiedSnapshot == null)
                {
                    state.SetBalance(address, 100);
                    state.TransferBalance(address, address2, 25); // address1 is now 75, address 2 is 25
                    state.SetCodeSegment(address, new byte[] { 77 });
                    state.SetStorageData(address, 0, 555555);
                    state.SetStorageData(address2, 0, 2);
                    state.SetStorageData(address, 0, 1);
                    state.SetNonce(address2, 777);
                    state.ModifyBalanceDelta(address2, 5); // address2 += 5, now 30
                    state.IncrementNonce(address2);
                    state.AddGasRefund(50);
                    state.AddGasRefund(49);

                    // Create a modified state snapshot.
                    modifiedSnapshot = state.Snapshot();
                }
                else
                {
                    // This commits changes before reverting so it shouldn't have any affect.
                    if (i == 3)
                    {
                        state.CommitChanges();
                    }

                    // Revert to our modified snapshot.
                    state.Revert(modifiedSnapshot);

                    // This pushes all changes to the trie, accounts will no longer be 'dirty' (marked as having uncommitted changes).
                    if (i == 2)
                    {
                        state.CommitChanges();
                    }
                }

                // 3) VERIFY MODIFIED VARIABLES
                Assert.False(state.GetAccount(address).IsBlank);
                Assert.Equal(75, state.GetBalance(address));
                Assert.Equal(30, state.GetBalance(address2));
                Assert.True(state.GetCodeSegment(address).ValuesEqual(new byte[] { 77 }));
                Assert.Equal(1, state.GetStorageData(address, 0));       // storage value should be 1 for first address
                Assert.Equal(2, state.GetStorageData(address2, 0));      // storage value should be 2 for second address
                Assert.Equal(0, state.GetNonce(address));                // nonce is 0 by default
                Assert.Equal(778, state.GetNonce(address2));             // we set this nonce so we verify value
                Assert.Equal(99, state.TransactionRefunds);
                Assert.Equal(i != 2, state.GetAccount(address).IsDirty); // on this iteration the account will have been commited so it's clean, on other iteration it's dirty. (Note: i == 3 looks the same, but it commits after snap shot, and before revert, so it still has dirty state).

                // Reset storage data and verify
                state.ResetStorageData(address);
                Assert.Equal(0, state.GetStorageData(address, 0)); // storage has no values, should all be 0.


                // 4) REVERT STATE TO CLEAN STATE.

                // This commits changes before reverting so it shouldn't have any affect.
                if (i == 3)
                {
                    state.CommitChanges();
                }

                // Revert to our clean snapshot.
                state.Revert(cleanSnapshot);

                // This pushes all changes to the trie, accounts will no longer be 'dirty' (marked as having uncommitted changes).
                if (i == 2)
                {
                    state.CommitChanges();
                }
            }
        }
Exemple #39
0
		public StatePatch Serialize(StateSnapshot oldSnapshot, IHEvent expectingEvent)
		{
			var ostream = new MemoryStream();
			Serialize(ostream, oldSnapshot);
			ostream.Close();

			var patch = new StatePatch( this.GetPatchFlag(),
				 oldSnapshot.Timestamp.Event,
				 expectingEvent,
				 ostream.ToArray() );
			return patch;
		}
Exemple #40
0
		public void Serialize(Stream ostream, StateSnapshot oldSnapshot)
		{
			if (m_patchMethod == StatePatchMethod.Auto)
			{
				StatePatchUtils.GeneratePatch(ostream, this.Snapshot(), oldSnapshot, null);
			}
			else
			{
				DoSerialize(ostream, oldSnapshot);
			}

		}
        /////////////////////////////////////////
        // Network/Packet Reading & Processing //
        /////////////////////////////////////////

        internal void SetSnapshot()
        {
            _snapshot = new StateSnapshot(this);
            _snapshot.Snap();
            _snapshotReplay = false;
        }
Exemple #42
0
 public override void InitializeInEnvironment(CellInstance cell, ComponentWorldStateBase compData, StateSnapshot state)
 {
     updateOutput(cell, state);
 }
		protected override StateSnapshot DoSnapshot(StateSnapshot initial)
		{
			var retval = initial;
			var entry = new StateSnapshot.FieldEntry();
			entry.Name = "m_nativeStates";
			entry.Type = typeof(_StateRef[]);
			entry.Attrib = null;
			entry.Value = m_nativeStates.Select(kv =>
				new _StateRef() { sid = kv.Value.StateId, refType = kv.Value.GetType().ToString() }).ToArray();
			retval.Fields.Add(entry);
			return retval;
		}
Exemple #44
0
		private StateSnapshot DoAggregateDistributedDelta(IEnumerable<Spacetime> spacetimes, TStateId stateId, StateSnapshot seed)
		{
			foreach (var spacetime in spacetimes.Skip(1))
			{
				var state = spacetime.ExportStateSnapshot(stateId);
				seed.Aggregate(state);
			}

			return seed;
		}
Exemple #45
0
        private void setState(StateSnapshot ss)
        {
            string text = ss.VPNState[1];

            text = ProgramVPN.res.GetString("VPNSTATE_" + text);
            if (text != null)
            {
                if (text.StartsWith("VPNSTATE_",
                                    StringComparison.OrdinalIgnoreCase))
                {
                    text = ss.VPNState[1];
                }

                lblVPNState.Text = text;
            }
            else
            {
                lblVPNState.Text = "";
            }

            llIP.SetIP(m_config.VPNConnection.IP);
            lblVPNState.Left = llIP.Left - lblVPNState.Width - 16;
            llIP.SetIP(m_config.VPNConnection.IP);

            if (ss.ConnectionState != lastConnectionState)
            {
                lastConnectionState = ss.ConnectionState;
                switch (ss.ConnectionState)
                {
                case VPNConnectionState.Initializing:
                    lstLog.Items.Clear();
                    lblState.Text  = ProgramVPN.res.GetString("STATE_Initializing");
                    pbStatus.Image = Properties.Resources.STATE_Initializing;
                    toolTip.SetToolTip(btnConnect,
                                       ProgramVPN.res.GetString("QUICKINFO_Disconnect"));
                    btnConnect.Image   = Properties.Resources.BUTTON_Disconnect;
                    btnConnect.Enabled = true;
                    break;

                case VPNConnectionState.Running:
                    lblState.Text  = ProgramVPN.res.GetString("STATE_Connected");
                    pbStatus.Image = Properties.Resources.STATE_Running;
                    toolTip.SetToolTip(btnConnect,
                                       ProgramVPN.res.GetString("QUICKINFO_Disconnect"));
                    btnConnect.Image   = Properties.Resources.BUTTON_Disconnect;
                    btnConnect.Enabled = true;
                    if (m_isTemporary)
                    {
                        m_isTemporary = false;
                        Hide();
                    }
                    break;

                case VPNConnectionState.Stopped:
                    lblState.Text  = ProgramVPN.res.GetString("STATE_Stopped");
                    pbStatus.Image = Properties.Resources.STATE_Stopped;
                    toolTip.SetToolTip(btnConnect,
                                       ProgramVPN.res.GetString("QUICKINFO_Connect"));
                    btnConnect.Image   = Properties.Resources.BUTTON_Connect;
                    btnConnect.Enabled = true;
                    lblVPNState.Text   = "";
                    break;

                case VPNConnectionState.Stopping:
                    lblState.Text  = ProgramVPN.res.GetString("STATE_Stopping");
                    pbStatus.Image = Properties.Resources.STATE_Stopping;
                    toolTip.SetToolTip(btnConnect,
                                       ProgramVPN.res.GetString("QUICKINFO_Connect"));
                    btnConnect.Image   = Properties.Resources.BUTTON_Connect;
                    btnConnect.Enabled = false;
                    break;

                case VPNConnectionState.Error:
                default:
                    lblState.Text  = ProgramVPN.res.GetString("STATE_Error");
                    pbStatus.Image = Properties.Resources.STATE_Error;
                    toolTip.SetToolTip(btnConnect,
                                       ProgramVPN.res.GetString("QUICKINFO_Connect"));
                    btnConnect.Image   = Properties.Resources.BUTTON_Connect;
                    btnConnect.Enabled = true;
                    lblVPNState.Text   = "";
                    break;
                }
            }
        }
Exemple #46
0
        public static EVMExecutionResult CreateContract(State state, EVMMessage message)
        {
            // If this message to create didn't come from the transaction origin, we increment nonce
            if (state.CurrentTransaction.GetSenderAddress() != message.Sender)
            {
                state.IncrementNonce(message.Sender);
            }

            BigInteger newNonce = state.GetNonce(message.Sender) - 1;

            message.To = Address.MakeContractAddress(message.Sender, newNonce);

            // If we're past the byzantium fork, we want to make sure the nonce is 0 and there is no code (making sure the address we're creating doesn't already exist). Otherwise we fail out.
            if (state.Configuration.Version >= EthereumRelease.Byzantium)
            {
                byte[] existingCode = state.GetCodeSegment(message.To);
                if (state.GetNonce(message.To) > 0 || existingCode.Length > 0)
                {
                    return(new EVMExecutionResult(null, null, 0, false));
                }
            }

            // If this is an existing account, remove existing values attached to it.
            BigInteger balance = state.GetBalance(message.To);

            if (balance > 0)
            {
                state.SetBalance(message.To, balance);
                state.SetNonce(message.To, 0);
                state.SetCodeSegment(message.To, Array.Empty <byte>());
            }

            // Obtain our code from our message data
            byte[] code = message.Data;

            // Set our message data to a blank array
            message.Data = Array.Empty <byte>();

            // Back up the state.
            StateSnapshot snapshot = state.Snapshot();

            // If spurious dragon version
            if (state.Configuration.Version >= EthereumRelease.SpuriousDragon)
            {
                state.SetNonce(message.To, 1);
            }
            else
            {
                state.SetNonce(message.To, 0);
            }

            // Execute our message
            EVMExecutionResult result = Execute(state, message, code);

            // If we should revert
            if (!result.Succeeded)
            {
                // Revert our changes
                state.Revert(snapshot);

                // Return our execution result
                return(result);
            }
            else
            {
                // If we have no return data, our return data is the To address.
                if (result.ReturnData.Length == 0)
                {
                    // Record an exception here (although this is technically not an exception, it is acceptable behavior, but in any real world case, this is undesirable, so we warn of it).
                    state.Configuration.DebugConfiguration?.RecordException(new Exception("Contract deployment ended up deploying a contract which is zero bytes in size."), false);

                    // Return early to avoid processing more code.
                    return(new EVMExecutionResult(result.EVM, message.To.ToByteArray(), result.RemainingGas, true));
                }

                // Obtain our code
                code = result.ReturnData.ToArray();

                // Calculate cost based off every byte in our contract
                BigInteger remainingGas = result.RemainingGas;
                BigInteger extraGasCost = result.ReturnData.Length * GasDefinitions.GAS_CONTRACT_BYTE;

                // Verify we have enough gas to create the contract, and we pass the the size constraint for contracts introduced in spurious dragon.
                bool passSizeContraint = (state.Configuration.Version < EthereumRelease.SpuriousDragon || code.Length <= EVMDefinitions.MAX_CONTRACT_SIZE);

                // Allow contract to be over the size limit if the debug/testing option for it has been set
                if (!passSizeContraint && state.Configuration.DebugConfiguration.IsContractSizeCheckDisabled)
                {
                    passSizeContraint = true;
                }

                if (result.RemainingGas < extraGasCost || !passSizeContraint)
                {
                    // Store our code length
                    var codeSize = code.Length;

                    // Set our code array as blank
                    code = Array.Empty <byte>();

                    // If we are past homestead, we revert here.
                    if (state.Configuration.Version >= EthereumRelease.Homestead)
                    {
                        // Report an exception here.
                        string exceptionMessage = null;
                        if (!passSizeContraint)
                        {
                            exceptionMessage = $"Out of gas: Contract size of {codeSize} bytes exceeds the maximum contract size of {EVMDefinitions.MAX_CONTRACT_SIZE} bytes.";
                        }
                        else
                        {
                            exceptionMessage = $"Out of gas: Not enough gas to pay for the cost-per-byte of deployed contract. Gas: {result.RemainingGas} / Cost: {extraGasCost}";
                        }

                        // Record an exception here.
                        state.Configuration.DebugConfiguration?.RecordException(new Exception(exceptionMessage), false);

                        // Revert our changes
                        state.Revert(snapshot);

                        // Return our execution result
                        return(new EVMExecutionResult(result.EVM, null, 0, false));
                    }
                }
                else
                {
                    // We could pay for the creation, remove the gas cost from our remaining gas.
                    remainingGas -= extraGasCost;
                }

                // Set our code segment.
                state.SetCodeSegment(message.To, code);

                // Return our result
                return(new EVMExecutionResult(result.EVM, message.To.ToByteArray(), remainingGas, true));
            }
        }