/// <summary> /// Base constructor /// </summary> public Simulation() { // Seeds the random object this.randomObject = new Random(0); this.snapshotCache = new SnapshotCache(10); this.currentState = null; }
private void SendPingMessage() { TrimmedBlock block; using (SnapshotCache snapshot = Blockchain.Singleton.GetSnapshot()) { block = NativeContract.Ledger.GetTrimmedBlock(snapshot, NativeContract.Ledger.CurrentHash(snapshot)); } foreach (KeyValuePair <IActorRef, TaskSession> item in sessions) { var node = item.Key; var session = item.Value; if (session.ExpireTime < TimeProvider.Current.UtcNow || (block.Index >= session.LastBlockIndex && TimeProvider.Current.UtcNow.ToTimestampMS() - PingCoolingOffPeriod >= block.Timestamp)) { if (session.InvTasks.Remove(MemPoolTaskHash)) { node.Tell(Message.Create(MessageCommand.Mempool)); } node.Tell(Message.Create(MessageCommand.Ping, PingPayload.Create(Blockchain.Singleton.Height))); session.ExpireTime = TimeProvider.Current.UtcNow.AddMilliseconds(PingCoolingOffPeriod); } } }
public AssetDescriptor(UInt160 asset_id) { using SnapshotCache snapshot = Blockchain.Singleton.GetSnapshot(); var contract = NativeContract.ContractManagement.GetContract(snapshot, asset_id); if (contract is null) { throw new ArgumentException(); } byte[] script; using (ScriptBuilder sb = new ScriptBuilder()) { sb.EmitDynamicCall(asset_id, "decimals"); sb.EmitDynamicCall(asset_id, "symbol"); script = sb.ToArray(); } using ApplicationEngine engine = ApplicationEngine.Run(script, snapshot, gas: 0_10000000); if (engine.State.HasFlag(VMState.FAULT)) { throw new ArgumentException(); } this.AssetId = asset_id; this.AssetName = contract.Manifest.Name; this.Symbol = engine.ResultStack.Pop().GetString(); this.Decimals = (byte)engine.ResultStack.Pop().GetInteger(); }
/// <summary> /// Base constructor /// </summary> public Simulation() { int seed = Math.Abs((int)(DateTime.Now.Ticks)); System.Console.WriteLine("Seeding simulation random object - seed = "+seed.ToString()); this.randomObject = new Random(seed); this.snapshotCache = new SnapshotCache(10); this.currentState = null; }
private static async Task SetSnapshotsOnCache(SnapshotCache cache, ILogger logger, FabricClient client) { var snapshots = await GetSnapshots(logger, client); lock (cache) { foreach (var snapshot in snapshots) { cache.SetSnapshot(snapshot.Key, snapshot.Value); } } }
/// <summary> /// Constructor for the Simulator /// </summary> /// <param name="name"> /// A <see cref="String"/> /// </param> public Simulation(String name) { this.name = name; this.parameters = new SimulationParameters(); this.SimulationResults = new Results(); this.listener = null; // Seeds the random object this.randomObject = new Random(0); this.snapshotCache = new SnapshotCache(10); this.currentState = null; }
/// <summary> /// Constructor for the Simulator /// </summary> /// <param name="name"> /// A <see cref="String"/> /// </param> public Simulation(String name) { this.name = name; this.parameters = new SimulationParameters(); this.SimulationResults = new Results(); this.listener = null; // Seeds the random object based on the time int seed = Math.Abs((int)(DateTime.Now.Ticks)); System.Console.WriteLine("Seeding simulation random object - seed = "+seed.ToString()); this.randomObject = new Random(seed); this.snapshotCache = new SnapshotCache(10); this.currentState = null; }
public async Task NoSnapshot_GetResponseForFetch_ReturnsEmpty( DiscoveryRequest requests0, DiscoveryRequest requests1, DiscoveryRequest requests2) { // Arrange var cache = new SnapshotCache(true, new NullLogger()); // Act var result = await cache.Fetch(requests0); // Assert Assert.Null(result); }
public async Task NoSnapshot_GetResponseForStream_ReturnsUnresolvedTask( DiscoveryRequest requests0, DiscoveryRequest requests1, DiscoveryRequest requests2) { // Arrange var cache = new SnapshotCache(true, new NullLogger()); // Act var resultTask = cache.CreateWatch(requests0); // Assert await Task.Delay(100); Assert.False(resultTask.Response.IsCompleted); }
public async Task Snapshot_GetResponseForStream_ReturnsResolvedTask( DiscoveryRequest requests0, DiscoveryRequest requests1, DiscoveryRequest requests2) { // Arrange var cache = new SnapshotCache(true, new NullLogger()); cache.SetSnapshot("node1", BuildSnapshot("2")); // Act var result = await cache.CreateWatch(requests0).Response; // Assert Assert.NotNull(result); Assert.Equal("2", result.VersionInfo); Assert.Equal(requests0.TypeUrl, result.TypeUrl); }
public async Task Snapshot_GetResponseForWithTheSameVersionStream_ReturnsNotResolvedTask( DiscoveryRequest requests0, DiscoveryRequest requests1, DiscoveryRequest requests2) { // Arrange var cache = new SnapshotCache(true, new NullLogger()); cache.SetSnapshot("node1", BuildSnapshot("2")); // Act var resultTask = cache.CreateWatch(requests2); // Assert await Task.Delay(100); Assert.False(resultTask.Response.IsCompleted); }
static async Task MaintainSnapshotCache(FabricClient client, SnapshotCache cache, ILogger logger, CancellationToken cancellationToken) { async void Handler(object sender, EventArgs args) { await SetSnapshotsOnCache(cache, logger, client); } long?regitrationId = null; cancellationToken.Register(async() => { client.ServiceManager.ServiceNotificationFilterMatched -= Handler; if (regitrationId.HasValue) { await client.ServiceManager.UnregisterServiceNotificationFilterAsync(regitrationId.Value); } }); client.ServiceManager.ServiceNotificationFilterMatched += Handler; regitrationId = await client.ServiceManager.RegisterServiceNotificationFilterAsync(new ServiceNotificationFilterDescription(new Uri("fabric:"), true, false)); await SetSnapshotsOnCache(cache, logger, client); }
public void BlockPersistAndReverificationWillAbandonTxAsBalanceTransfered() { using SnapshotCache snapshot = Blockchain.Singleton.GetSnapshot(); BigInteger balance = NativeContract.GAS.BalanceOf(snapshot, senderAccount); ApplicationEngine engine = ApplicationEngine.Create(TriggerType.Application, null, snapshot, null, long.MaxValue); NativeContract.GAS.Burn(engine, UInt160.Zero, balance); NativeContract.GAS.Mint(engine, UInt160.Zero, 70, true); long txFee = 1; AddTransactionsWithBalanceVerify(70, txFee, snapshot); _unit.SortedTxCount.Should().Be(70); var block = new Block { Transactions = _unit.GetSortedVerifiedTransactions().Take(10).ToArray() }; // Simulate the transfer process in tx by burning the balance UInt160 sender = block.Transactions[0].Sender; ApplicationEngine applicationEngine = ApplicationEngine.Create(TriggerType.All, block, snapshot, block, (long)balance); NativeContract.GAS.Burn(applicationEngine, sender, NativeContract.GAS.BalanceOf(snapshot, sender)); NativeContract.GAS.Mint(applicationEngine, sender, txFee * 30, true); // Set the balance to meet 30 txs only // Persist block and reverify all the txs in mempool, but half of the txs will be discarded _unit.UpdatePoolForBlockPersisted(block, snapshot); _unit.SortedTxCount.Should().Be(30); _unit.UnverifiedSortedTxCount.Should().Be(0); // Revert the balance NativeContract.GAS.Burn(applicationEngine, sender, txFee * 30); NativeContract.GAS.Mint(applicationEngine, sender, balance, true); }
public static void Main(string[] args) { var cancelationTokenSource = new CancellationTokenSource(); var logger = new ConsoleLogger(); var cache = new SnapshotCache(true, logger); var watcher = new SnapshotFileWatcher(s => cache.SetSnapshot("envoy1", s)); Console.WriteLine("Configuration loaded from files"); watcher.Start(); Console.WriteLine("File watcher started"); var services = new Services(cache, logger, cancelationTokenSource.Token); Server server = new Server { Services = { ClusterDiscoveryService.BindService(services.ClusterService), EndpointDiscoveryService.BindService(services.EndpointService), ListenerDiscoveryService.BindService(services.ListenerService), RouteDiscoveryService.BindService(services.RouteService), AggregatedDiscoveryService.BindService(services.AggregatedService) }, Ports = { new ServerPort("0.0.0.0", Port, ServerCredentials.Insecure) } }; server.Start(); Console.WriteLine($"Server listening on port {Port.ToString()}"); Console.WriteLine("Press any key to stop the server..."); Console.ReadKey(); cancelationTokenSource.Cancel(); server.ShutdownAsync().Wait(); }
public ControlPlane(StatelessServiceContext context) : base(context) { logger = new ConsoleLogger(); cache = new SnapshotCache(true, logger); }
private void Persist(Block block) { using (SnapshotCache snapshot = system.GetSnapshot()) { List <ApplicationExecuted> all_application_executed = new List <ApplicationExecuted>(); using (ApplicationEngine engine = ApplicationEngine.Create(TriggerType.OnPersist, null, snapshot, block)) { engine.LoadScript(onPersistScript); if (engine.Execute() != VMState.HALT) { throw new InvalidOperationException(); } ApplicationExecuted application_executed = new ApplicationExecuted(engine); Context.System.EventStream.Publish(application_executed); all_application_executed.Add(application_executed); } DataCache clonedSnapshot = snapshot.CreateSnapshot(); // Warning: Do not write into variable snapshot directly. Write into variable clonedSnapshot and commit instead. foreach (Transaction tx in block.Transactions) { using (ApplicationEngine engine = ApplicationEngine.Create(TriggerType.Application, tx, clonedSnapshot, block, tx.SystemFee)) { engine.LoadScript(tx.Script); if (engine.Execute() == VMState.HALT) { clonedSnapshot.Commit(); } else { clonedSnapshot = snapshot.CreateSnapshot(); } ApplicationExecuted application_executed = new ApplicationExecuted(engine); Context.System.EventStream.Publish(application_executed); all_application_executed.Add(application_executed); } } using (ApplicationEngine engine = ApplicationEngine.Create(TriggerType.PostPersist, null, snapshot, block)) { engine.LoadScript(postPersistScript); if (engine.Execute() != VMState.HALT) { throw new InvalidOperationException(); } ApplicationExecuted application_executed = new ApplicationExecuted(engine); Context.System.EventStream.Publish(application_executed); all_application_executed.Add(application_executed); } foreach (IPersistencePlugin plugin in Plugin.PersistencePlugins) { plugin.OnPersist(block, snapshot, all_application_executed); } snapshot.Commit(); List <Exception> commitExceptions = null; foreach (IPersistencePlugin plugin in Plugin.PersistencePlugins) { try { plugin.OnCommit(block, snapshot); } catch (Exception ex) { if (plugin.ShouldThrowExceptionFromCommit(ex)) { if (commitExceptions == null) { commitExceptions = new List <Exception>(); } commitExceptions.Add(ex); } } } if (commitExceptions != null) { throw new AggregateException(commitExceptions); } system.MemPool.UpdatePoolForBlockPersisted(block, snapshot); } extensibleWitnessWhiteList = null; block_cache.Remove(block.PrevHash); Context.System.EventStream.Publish(new PersistCompleted { Block = block }); if (system.HeaderCache.TryRemoveFirst(out Header header)) { Debug.Assert(header.Index == block.Index); } }
static void TraceBlock(Uri uri, Block block, ProtocolSettings settings, IConsole console, UInt256?txHash = null) { IReadOnlyStore roStore = block.Index > 0 ? new StateServiceStore(uri, block.Index - 1) : NullStore.Instance; using var store = new MemoryTrackingStore(roStore); using var snapshot = new SnapshotCache(store.GetSnapshot()); using (var engine = ApplicationEngine.Create(TriggerType.OnPersist, null, snapshot, block, settings, 0)) { using var sb = new ScriptBuilder(); sb.EmitSysCall(ApplicationEngine.System_Contract_NativeOnPersist); engine.LoadScript(sb.ToArray()); if (engine.Execute() != VMState.HALT) { throw new InvalidOperationException("NativeOnPersist operation failed", engine.FaultException); } } var clonedSnapshot = snapshot.CreateSnapshot(); for (int i = 0; i < block.Transactions.Length; i++) { Transaction tx = block.Transactions[i]; using var engine = GetEngine(tx, clonedSnapshot); if (engine is TraceApplicationEngine) { console.Out.WriteLine($"Tracing Transaction #{i} ({tx.Hash})"); } else { console.Out.WriteLine($"Executing Transaction #{i} ({tx.Hash})"); } engine.LoadScript(tx.Script); if (engine.Execute() == VMState.HALT) { clonedSnapshot.Commit(); } else { clonedSnapshot = snapshot.CreateSnapshot(); } } ApplicationEngine GetEngine(Transaction tx, DataCache snapshot) { if (txHash == null || txHash == tx.Hash) { var path = SysIO.Path.Combine(Environment.CurrentDirectory, $"{tx.Hash}.neo-trace"); var sink = new TraceDebugStream(SysIO.File.OpenWrite(path)); return(new TraceApplicationEngine(sink, TriggerType.Application, tx, snapshot, block, settings, tx.SystemFee)); } else { return(ApplicationEngine.Create(TriggerType.Application, tx, snapshot, block, settings, tx.SystemFee)); } } }