private void OnVideoPlayerPrepared(object sender, EventArgs e) { model.IsPrepared = true; SetBusy(false); model.Duration = TimeSpan.FromMilliseconds(nativePlayer.Duration); model.CurrentPosition = TimeSpan.Zero; model.DisplaySeekbar = true; Prepared?.Invoke(this, EventArgs.Empty); if (Mute) { model.IsMute = true; SetVolume(); } else { model.IsMute = false; SetVolume(); } if (AutoPlay) { model.IsPlaying = true; model.IsPrepared = true; nativePlayer.Play(); } }
private void BtnOK_Click(object sender, RoutedEventArgs e) { try { if (string.IsNullOrEmpty(txtVariable.Text)) { throw new Exception("You must set a variable name."); } if (txtVariable.Text.Contains(@"\s+")) { throw new Exception("Variable names cannot contain whitespace."); } if (Regex.IsMatch(txtVariable.Text, "var", RegexOptions.IgnoreCase) || Regex.IsMatch(txtVariable.Text, "string", RegexOptions.IgnoreCase) || Regex.IsMatch(txtVariable.Text, "stringbuilder", RegexOptions.IgnoreCase)) { throw new Exception("Invalid variable name."); } Prepared?.Invoke(this, new PrepareEventArgs { VariableName = txtVariable.Text, UseVar = chkImplicit.IsChecked != default ? (bool)chkImplicit.IsChecked : true, UseAppendLine = chkAppendLine.IsChecked != default ? (bool)chkAppendLine.IsChecked : false, LeftPadding = txtPadding.Text.Length, Cancelled = false, Object = (bool)rString.IsChecked ? OutputType.String : OutputType.StringBuilder }); DialogResult = true; Close(); }
public async Task ODataOrderingNonExistingPropertiesThrows() { await Prepared.ConfigureAwait(false); 0.Awaiting(async _ => await QueryInstallations("select=Name,TotallyNotAProperty").ConfigureAwait(false)) .Should().Throw <ODataException>(); }
/// <summary> /// ICADプロセス開始完了イベントを実行する /// </summary> /// <param name="sender">イベント呼び出し元オブジェクト</param> /// <param name="e">e</param> private void Command_ICADStarted(object sender, EventArgs e) { if (!(_iCadStartingForm == null || _iCadStartingForm.IsDisposed)) { _iCadStartingForm.Close(); } Prepared?.Invoke(this, new EventArgs()); }
public async Task ODataNameOfInstallation() { await Prepared.ConfigureAwait(false); var lst = await QueryInstallations("select=Name,Id").ConfigureAwait(false); lst.Should().BeEquivalentTo(TestSource.Installations, cfg => cfg.ExcludingMissingMembers()); }
public async Task ObservingThoughApiWorks() { await Prepared.ConfigureAwait(false); var builder = new HubConnectionBuilder() .WithUrl($"http://test{LiveHub.Route}", cfg => cfg.HttpMessageHandlerFactory = _ => Server.CreateHandler()) ; var hubConnection = builder.Build(); await hubConnection.StartAsync(); var obs = hubConnection.Observe <ChangeData>(nameof(LiveHub.Observe)); const int takeCount = 10; var sem = new SemaphoreSlim(2); // Coordinate progress between produced data and listener var obsTask = obs .TraceTest(Output) .Take(takeCount) .Select((v, idx) => new { v, idx }) // Start a new producer whenever we have received 5 items .Do(x => { if (x.idx % 5 == 0) { sem.Release(); } }) .TraceTest(Output) .Select(x => x.v) .ToListAsync(CancellationToken); var pushTask = TestSource.ProduceData( // Wait for sem for each batch of data sem.ObserveRelease().Take(2).Select(_ => DateTime.UtcNow) .TraceTest(Output) ) .TraceTest(Output) .SelectMany(x => x) .TraceTest(Output) .ToListAsync(CancellationToken); // All ready, start pusing sem.Release(); var observedChanges = await obsTask.ConfigureAwait(false); var observed = observedChanges.Select(c => c.Entity).ToList(); var pushed = await pushTask.ConfigureAwait(false); var expect = pushed.Take(takeCount); observed.Should().BeEquivalentTo(expect, cfg => cfg.Excluding(x => x.Installation).Excluding(x => x.Signal)); // Reception should contained interleaved data observed.Select(x => x.InstallationId) .Should().NotBeAscendingInOrder() .And.NotBeDescendingInOrder(); }
public void PrepareAudio() { try { // 一开始应该是false的 _isPrepared = false; File dir = new File(_mDirString); if (!dir.Exists()) { dir.Mkdirs(); } string fileNameString = GeneralFileName(); using (var file = new File(dir, fileNameString)) { _mCurrentFilePathString = file.AbsolutePath; _mRecorder = new MediaRecorder(); // 设置输出文件 _mRecorder.SetOutputFile(file.AbsolutePath); } //设置meidaRecorder的音频源是麦克风 _mRecorder.SetAudioSource(AudioSource.Mic); // 设置文件音频的输出格式为amr _mRecorder.SetOutputFormat(OutputFormat.RawAmr); // 设置音频的编码格式为amr _mRecorder.SetAudioEncoder(AudioEncoder.AmrNb); //设置录音声道 _mRecorder.SetAudioChannels(1); //设置编码比特率 _mRecorder.SetAudioEncodingBitRate(1); //设置编码采样率 _mRecorder.SetAudioSamplingRate(8000); // 严格遵守google官方api给出的mediaRecorder的状态流程图 try { _mRecorder.Prepare(); } catch (IOException e) { Debug.WriteLine("录音未成功,请重试" + e.Message); } _mRecorder.Start(); // 准备结束 _isPrepared = true; // 已经准备好了,可以录制了 Prepared?.Invoke(this, new EventArgs()); } catch (IllegalStateException e) { e.PrintStackTrace(); } catch (IOException e) { e.PrintStackTrace(); } }
public StateFixture() { f = new Final(); h = new Hnv(); pd = new Prepared(); ppd = new PrePrepared(); vcd = new ViewChanged(); v = new View(); }
/// <summary> /// Loads the input sources. /// </summary> public async void LoadInputSources() { using (State.BusyScope()) { Emitter.Publish(CommonLocalised.CheckingActiveSQLInstance, DateTime.Now.AsUKDatetime()); await Prepared.Refresh(); } }
public virtual BaseBuilder AddValues(string key, params string[] values) { if (Prepared.Any((x) => x.Key == key)) { Prepared.First((x) => x.Key == key).AddValue(values); } return(this); }
public void Handle(CoreProjectionStatusMessage.Prepared message) { var command = new Prepared { Id = message.ProjectionId.ToString("N"), SourceDefinition = message.SourceDefinition, }; _writer.PublishCommand("$prepared", command); }
protected async Task <IList <Installation> > QueryInstallations(string args) { await Prepared.ConfigureAwait(false); return(await Client.GetJsonAsync <List <Installation> >( new Uri(Server.BaseAddress, $"/odata/Installation?${args}"), JsonSerializer, CancellationToken ).ConfigureAwait(false)); }
public virtual BaseBuilder AddStatement(RawStatement statement) { if (!Prepared.Any((x) => x.Key == statement.Key)) { int indicies = GetIndicies(statement.Query, out string query); Prepared.Add(new PreparedStatements(statement.Key, query, indicies, new List <string>())); } return(this); }
public static void Prepare() { if (Preparing?.Invoke() == false) { return; } moduleName = moduleName ?? Process.GetCurrentProcess().MainModule.ModuleName; var intPtr = Win32ApiWrapper.GetModuleHandle(moduleName); kbhHook = Win32ApiWrapper.SetWindowsHookEx(WinApiConsts.HookType.WH_KEYBOARD_LL, hook, intPtr, 0); Prepared?.BeginInvoke(kbhHook != 0, null, null); }
public async Task GetTurbinesByIdReturnsExpectedParquet() { await Prepared.ConfigureAwait(false); var server = Server; var got = await SendAsyncParquet <Installation>( new Uri(server.BaseAddress, $"{InstallationXController.RoutePrefix}/{InstallationXController.AllRoute}") .GetRequest()) .ConfigureAwait(false); got.Should().BeEquivalentTo(TestSource.Installations, cfg => cfg.ExcludingMissingMembers() // Currently Guid is not serialized :( .Excluding(x => x.Id)); }
public async Task GetTurbinesByIdReturnsExpectedJson(int index) { await Prepared.ConfigureAwait(false); var client = await Client.ConfigureAwait(false); var i = TestSource.Installations.Skip(index).First(); var got = await client.GetJsonAsync <Installation>( new Uri(Server.BaseAddress, $"{InstallationXController.RoutePrefix}/{i.Id}"), JsonSerializer, CancellationToken ); var expected = new Installation(i.Id, i.Name, i.InstallationPeriod.From, i.InstallationPeriod.To); got.Should().BeEquivalentTo(expected); }
public override void OnCompositionComplete() { base.OnCompositionComplete(); ShowConsoleCommand = CommandFactory.Create(ShowConsole, () => true); ClearCommand = CommandFactory.Create(Clear, () => true); SaveCommand = CommandFactory.Create(Save, () => true); PrepareCommand = CommandFactory.Create(ManagePreparation, () => true); SelectInputFileCommand = CommandFactory.Create(LoadInputFile, () => Prepared.IsValidSQLInstance); LoadInputSourcesCommand = CommandFactory.Create(LoadInputSources, () => true); ExportToFileCommand = CommandFactory.Create <int>(ExportToFile, () => true); SelectProvidersCommand = CommandFactory.Create(SelectProviders, () => Prepared.IsValid()); ApplyProvidersFilterCommand = CommandFactory.Create(ApplyFilter, () => true); SelectRulesCommand = CommandFactory.Create(SelectRules, () => Prepared.IsValid() && Providers.IsValid()); RunCommand = CommandFactory.Create(Run, OKToRun); }
/// <summary> /// Load an input file /// the interaction state will become 'is busy' /// </summary> public async void LoadInputFile() { using (State.BusyScope()) { Emitter.Publish(CommonLocalised.LineDivider); Emitter.Publish(CommonLocalised.CommencingSelectFormat, DateTime.Now.AsUKDatetime()); Emitter.Publish(CommonLocalised.LineDivider); await Bulk.Import( Prepared.SQLInstance, Prepared.DBName, Prepared.DBUser, Prepared.DBPassword, () => FileSelector.GetFileName <IManageRunPreparation>(), x => Challenge.GetResponse(x)); await Prepared.Refresh(); } }
private void Process(Entry ntry) { Debug.WriteLine($"Interpreting block block.id={ntry.Block}"); var state = FindOrCreateState(ntry); var node = ntry.Block.Node; var round = ntry.Block.Round; var hash = ntry.Block.Hash; var out_ = new List <IMessage> { new PrePrepare(hash, node, round, 0) }; if (ntry.Deps.Length > 0) { if (state.Delay == null) { state.Delay = new Dictionary <ulong, ulong>(); } foreach (var dep in ntry.Deps) { state.Delay[dep.Node] = Util.Diff(round, dep.Round) * 10; } } var tval = 10UL; if (state.Delay.Count > Quorum2f1) { var vals = new ulong[state.Delay.Count]; var i = 0; foreach (KeyValuePair <ulong, ulong> item in state.Delay) { vals[i] = item.Value; i++; } Array.Sort(vals); var xval = vals[Quorum2f]; if (xval > tval) { tval = xval; } } else { foreach (KeyValuePair <ulong, ulong> item in state.Delay) { var val = item.Value; if (val > tval) { tval = val; } } } state.Timeout = tval; var tround = round + tval; foreach (var xnode in Nodes) { if (!state.Timeouts.ContainsKey(tround) || state.Timeouts[tround] == null) { state.Timeouts[tround] = new List <Timeout>(); } state.Timeouts[tround].Add(new Timeout(xnode, round, 0)); } if (state.Timeouts.ContainsKey(round)) { foreach (var tmout in state.Timeouts[round]) { if (state.Data.ContainsKey(new Final(tmout.Node, tmout.Round))) { continue; } uint v = 0; var skey = new View(tmout.Node, tmout.Round); if (state.Data.ContainsKey(skey)) { v = (uint)state.Data[skey]; } if (v > tmout.View) { continue; } var hval = ""; var skey2 = new Prepared(tmout.Node, tmout.Round, tmout.View); if (state.Data.ContainsKey(skey2)) { hval = (string)state.Data[skey2]; } if (state.Data == null) { state.Data = new StateKV { { skey, v + 1 } }; } else { state.Data[skey] = v + 1; } out_.Add(new ViewChange(hval, tmout.Node, tmout.Round, node, tmout.View + 1)); } } var idx = out_.Count; var processed = new Dictionary <IMessage, bool>(); out_.AddRange(ProcessMessages(state, processed, node, node, ntry.Block, out_.GetRange(0, idx))); foreach (var dep in ntry.Deps) { Debug.WriteLine($"Processing block dep block.id={dep}"); List <IMessage> output = new List <IMessage>(); if (Statess.ContainsKey(dep) && Statess[dep] != null) { output = Statess[dep].GetOutPut(); } out_.AddRange(ProcessMessages(state, processed, dep.Node, node, ntry.Block, output)); } state.Out = out_; Statess[ntry.Block] = state; }
public void Prepare(GameObject entity) { OnPrepare(entity); Prepared?.Invoke(this); }
/// <summary> /// Ok to run. /// </summary> /// <returns></returns> private bool OKToRun() { return(Prepared.IsValid() && Providers.IsValid() && RuleSet.IsValid()); }
public void OnPrepare() { Prepared?.Invoke(this, EventArgs.Empty); }
/// <summary> /// /// </summary> /// <param name="entry"></param> private void Process(Entry entry) { _logger.Here().Debug("Interpreting block block.id: {@BlockID}", entry.Block); var state = FindOrCreateState(entry); var node = entry.Block.Node; var round = entry.Block.Round; var hash = entry.Block.Hash; var outMessages = new List <IMessage> { new PrePrepare(hash, node, round, 0) }; if (entry.Deps.Any()) { state.Delay ??= new Dictionary <ulong, ulong>(); foreach (var dep in entry.Deps) { state.Delay[dep.Node] = Util.Diff(round, dep.Round) * 10; } } var timeOutVal = 10UL; if (state.Delay.Count > Quorum2f1) { var timeOutValues = new ulong[state.Delay.Count]; var i = 0; foreach (var item in state.Delay) { timeOutValues[i] = item.Value; i++; } Array.Sort(timeOutValues); var xval = timeOutValues[Quorum2f]; if (xval > timeOutVal) { timeOutVal = xval; } } else { foreach (var val in state.Delay.Select(item => item.Value).Where(val => val > timeOutVal)) { timeOutVal = val; } } state.Timeout = timeOutVal; var timeoutRound = round + timeOutVal; foreach (var nextNode in Nodes) { if (!state.Timeouts.ContainsKey(timeoutRound) || state.Timeouts[timeoutRound] == null) { state.Timeouts[timeoutRound] = new List <Timeout>(); } state.Timeouts[timeoutRound].Add(new Timeout(nextNode, round, 0)); } if (state.Timeouts.ContainsKey(round)) { foreach (var tmout in state.Timeouts[round]) { if (state.Data.ContainsKey(new Final(tmout.Node, tmout.Round))) { continue; } uint v = 0; var skey = new View(tmout.Node, tmout.Round); if (state.Data.ContainsKey(skey)) { v = (uint)state.Data[skey]; } if (v > tmout.View) { continue; } var hval = ""; var skey2 = new Prepared(tmout.Node, tmout.Round, tmout.View); if (state.Data.ContainsKey(skey2)) { hval = (string)state.Data[skey2]; } if (state.Data == null) { state.Data = new StateKV { { skey, v + 1 } }; } else { state.Data[skey] = v + 1; } outMessages.Add(new ViewChange(hval, tmout.Node, tmout.Round, node, tmout.View + 1)); } } var idx = outMessages.Count; var processed = new Dictionary <IMessage, bool>(); outMessages.AddRange(ProcessMessages(state, processed, node, node, entry.Block, outMessages.GetRange(0, idx))); foreach (var dep in entry.Deps) { _logger.Here().Debug("Processing block dep block.id: {@BlockID}", dep); var output = new List <IMessage>(); if (Statess.ContainsKey(dep) && Statess[dep] != null) { output = Statess[dep].GetOutPut(); } outMessages.AddRange(ProcessMessages(state, processed, dep.Node, node, entry.Block, output)); } state.Out = outMessages; Statess[entry.Block] = state; }
protected override void PrepareDbContext(TestDbContext context) { _scaffold.Run(context); Prepared?.Invoke(); }
/// <summary> /// /// </summary> /// <param name="s"></param> /// <param name="sender"></param> /// <param name="receiver"></param> /// <param name="origin"></param> /// <param name="msg"></param> /// <returns></returns> /// <exception cref="Exception"></exception> private IMessage ProcessMessage(State s, ulong sender, ulong receiver, Block origin, IMessage msg) { _logger.Here().Debug("State: {@State}, Sender: {@Sender}, Receiver: {@Receiver}, Origin: {@Origin}, Message: {@Message}", s, sender.ToString(), receiver.ToString(), origin, msg); var(node, round) = msg.NodeRound(); if (s.Data.ContainsKey(new Final(node, round))) { _logger.Here().Debug("State contains final, node: {@Node}, round: {@Round}", node, round); return(null); } var v = s.GetView(node, round); _logger.Here().Debug("Processing message from block block.id: {@BlockID}, message: {@Message}", origin, msg); switch (msg) { case PrePrepare m: if (v != m.View) { return(null); } var pp = new PrePrepared(node, round, m.View); if (s.Data.ContainsKey(pp)) { return(null); } var size = sender > receiver ? sender : receiver; // var b = s.GetBitSet(NodeCount, m); var b = s.GetBitSet((int)size, m); b.SetPrepare(sender); b.SetPrepare(receiver); if (s.Data == null) { s.Data = new StateKV { { pp, m } }; } else { s.Data[pp] = m; } _logger.Here().Debug("PrePrepare, node: {@Node}, round: {@Round}, sender: {@Sender}, hash: {@Hash}", node.ToString(), round.ToString(), receiver.ToString(), m.Hash); return(new Prepare(m.Hash, node, round, receiver, m.View)); case Prepare m: if (v > m.View) { return(null); } if (v < m.View) { // b = s.GetBitSet(NodeCount, m.Pre()); b = s.GetBitSet((int)sender, m.Pre()); b.SetPrepare(m.Sender); return(null); } // b = s.GetBitSet(NodeCount, m.Pre()); b = s.GetBitSet((int)sender, m.Pre()); b.SetPrepare(m.Sender); _logger.Here().Debug("Prepare count: {@PrepareCount}", b.PrepareCount()); if (b.PrepareCount() != Quorum2f1) { return(null); } if (b.HasCommit(receiver)) { return(null); } b.SetCommit(receiver); var p = new Prepared(node, round, m.View); if (s.Data.ContainsKey(p)) { return(new Commit(m.Hash, node, round, receiver, m.View)); } if (s.Data == null) { s.Data = new StateKV() { { p, m.Hash } }; } else { s.Data[p] = m.Hash; } _logger.Here().Debug("Prepare, node: {@Node}, round: {@Round}, sender: {@Sender}, hash: {@Hash}", node.ToString(), round.ToString(), receiver.ToString(), m.Hash); return(new Commit(m.Hash, node, round, receiver, m.View)); case Commit m: if (v < m.View) { return(null); } // b = s.GetBitSet(NodeCount, m.Pre()); b = s.GetBitSet((int)sender, m.Pre()); b.SetCommit(m.Sender); _logger.Here().Debug("Commit count: {@CommitCount}", b.CommitCount()); if (b.CommitCount() != Quorum2f1) { return(null); } var nr = new NodeRound(node, round); if (s.Final.ContainsKey(nr)) { return(null); } if (s.Final == null) { s.Final = new Dictionary <NodeRound, string>() { { nr, m.Hash } }; } else { s.Final[nr] = m.Hash; } _logger.Here().Debug("Deliver, node: {@Node}, round: {@Round}, hash: {@Hash}", node.ToString(), round.ToString(), m.Hash); Deliver(node, round, m.Hash); return(null); case ViewChange m: if (v > m.View) { return(null); } Dictionary <ulong, string> vcs; var key = new ViewChanged(node, round, v); if (s.Data.ContainsKey(key)) { var val = s.Data[key]; vcs = (Dictionary <ulong, string>)val; } else { vcs = new Dictionary <ulong, string>(); if (s.Data == null) { s.Data = new StateKV() { { key, vcs } }; } else { s.Data[key] = vcs; } } vcs[m.Sender] = m.Hash; if (vcs.Count != Quorum2f1) { return(null); } s.Data[new View(node, round)] = m.View; var hash = ""; foreach (var hval in vcs.Select(item => item.Value).Where(hval => hval != "")) { if (hash != "" && hval != hash) { _logger.Here().Debug("Got multiple hashes in a view change node.id: {@Node}, round: {Round}, hash={@Hash} hash.alt={@HashAlt}", node.ToString(), round.ToString(), hash, hval); } hash = hval; } _logger.Here().Debug("ViewChange, node: {@Node}, round: {@Round}, sender: {@Sender}, hash: {@Hash}", node.ToString(), round.ToString(), receiver.ToString(), m.Hash); return(new NewView(hash, node, round, receiver, m.View)); case NewView m: if (v > m.View) { return(null); } var viewKey = new Hnv(node, round, m.View); if (s.Data.ContainsKey(viewKey)) { return(null); } s.Data ??= new StateKV(); s.Data[new View(node, round)] = m.View; var tval = origin.Round + s.Timeout + 5; if (!s.Timeouts.ContainsKey(tval)) { s.Timeouts[tval] = new List <Timeout>(); } s.Timeouts[tval].Add(new Timeout(node, round, m.View)); s.Data[viewKey] = true; _logger.Here().Debug("NewView -> PrePrepare, node: {@Node}, round: {@Round}, hash: {@Hash}", node.ToString(), round.ToString(), m.Hash); return(new PrePrepare(m.Hash, node, round, m.View)); default: throw new Exception($"blockmania: unknown message kind to process: {msg.Kind()}"); } }
internal void OnPrepare() { Prepared?.Invoke(this, EventArgs.Empty); }
public RotationAnonymousInnerClass(Prepared <Key> outerInstance, Org.Neo4j.Kernel.impl.store.kvstore.RotationState.Rotation <Key> prepareRotation) : base(prepareRotation) { this.outerInstance = outerInstance; }
private void ProcessEvent() { while (m_Session != null) { try { m_Session.GetEvent(1, out IMFMediaEvent _event);//requests events and returns immediately _event.GetType(out MediaEventType eventtype); switch (eventtype) { case MediaEventType.MESessionEnded: State = PlaybackState.Stopped; Ended?.Invoke(this, new StoppedEventArgs()); break; case MediaEventType.MESessionPaused: Paused?.Invoke(this, new PausedEventArgs(GetPosition())); break; case MediaEventType.MESessionStopped: Stopped?.Invoke(this, new StoppedEventArgs()); break; case MediaEventType.MESessionStarted: Started.Invoke(this, new EventArgs()); break; case MediaEventType.MESessionTopologyStatus: //topology loaded Guid guidManager = typeof(IAudioSessionManager).GUID; (new MMDeviceEnumeratorComObject() as IMMDeviceEnumerator). GetDefaultAudioEndpoint(CoreAudioApi.DataFlow.Render, CoreAudioApi.Role.Multimedia, out IMMDevice endoint); endoint.Activate(ref guidManager, ClsCtx.ALL, IntPtr.Zero, out object _manager); IAudioSessionManager manager = _manager as IAudioSessionManager; manager.GetSimpleAudioVolume(Guid.Empty, 0, out m_Volume); m_Session.GetClock(out m_Clock); Guid guid_ratecontrol = typeof(IMFRateControl).GUID; Guid MF_RATE_CONTROL_SERVICE = Guid.Parse("866fa297-b802-4bf8-9dc9-5e3b6a9f53c9"); MediaFoundationInterop.MFGetService(m_Session, ref MF_RATE_CONTROL_SERVICE, ref guid_ratecontrol, out object _control); //gets rate control m_Rate = _control as IMFRateControl; IsPrepared = true; Prepared?.Invoke(this, new EventArgs()); break; } _event = null; } catch (COMException e) { if (e.HResult == MediaFoundationErrors.MF_E_NO_EVENTS_AVAILABLE) { continue; } else { throw e; } } catch (ThreadAbortException) { break; } } }
private IMessage ProcessMessage(State s, ulong sender, ulong receiver, BlockID origin, IMessage msg) { var(node, round) = msg.NodeRound(); if (s.Data.ContainsKey(new Final(node, round))) { return(null); } var v = s.GetView(node, round); Debug.WriteLine($"Processing message from block block.id={origin} message={msg}"); switch (msg) { case PrePrepare m: if (v != m.View) { return(null); } var pp = new PrePrepared(node, round, m.View); if (s.Data.ContainsKey(pp)) { return(null); } ulong size = sender > receiver ? sender : receiver; // var b = s.GetBitSet(NodeCount, m); var b = s.GetBitSet((int)size, m); b.SetPrepare(sender); b.SetPrepare(receiver); if (s.Data == null) { s.Data = new StateKV() { { pp, m } }; } else { s.Data[pp] = m; } return(new Prepare(m.Hash, node, round, receiver, m.View)); case Prepare m: if (v > m.View) { return(null); } if (v < m.View) { // b = s.GetBitSet(NodeCount, m.Pre()); b = s.GetBitSet((int)sender, m.Pre()); b.SetPrepare(m.Sender); return(null); } // b = s.GetBitSet(NodeCount, m.Pre()); b = s.GetBitSet((int)sender, m.Pre()); b.SetPrepare(m.Sender); Debug.WriteLine($"Prepare count == {b.PrepareCount()}"); if (b.PrepareCount() != Quorum2f1) { return(null); } if (b.HasCommit(receiver)) { return(null); } b.SetCommit(receiver); var p = new Prepared(node, round, m.View); if (!s.Data.ContainsKey(p)) { if (s.Data == null) { s.Data = new StateKV() { { p, m.Hash } }; } else { s.Data[p] = m.Hash; } } return(new Commit(m.Hash, node, round, receiver, m.View)); case Commit m: if (v < m.View) { return(null); } // b = s.GetBitSet(NodeCount, m.Pre()); b = s.GetBitSet((int)sender, m.Pre()); b.SetCommit(m.Sender); Debug.WriteLine($"Commit count == {b.CommitCount()}"); if (b.CommitCount() != Quorum2f1) { return(null); } var nr = new NodeRound(node, round); if (s.Final.ContainsKey(nr)) { return(null); } if (s.Final == null) { s.Final = new Dictionary <NodeRound, string>() { { nr, m.Hash } }; } else { s.Final[nr] = m.Hash; } Deliver(node, round, m.Hash); return(null); case ViewChange m: if (v > m.View) { return(null); } Dictionary <ulong, string> vcs; var key = new ViewChanged(node, round, v); if (s.Data.ContainsKey(key)) { var val = s.Data[key]; vcs = (Dictionary <ulong, string>)val; } else { vcs = new Dictionary <ulong, string>(); if (s.Data == null) { s.Data = new StateKV() { { key, vcs } }; } else { s.Data[key] = vcs; } } vcs[m.Sender] = m.Hash; if (vcs.Count != Quorum2f1) { return(null); } s.Data[new View(node, round)] = m.View; var hash = ""; foreach (KeyValuePair <ulong, string> item in vcs) { var hval = item.Value; if (hval != "") { if (hash != "" && hval != hash) { Console.WriteLine($"Got multiple hashes in a view change node.id={node} round={round} hash={hash} hash.alt={hval}"); } hash = hval; } } return(new NewView(hash, node, round, receiver, m.View)); case NewView m: if (v > m.View) { return(null); } var viewKey = new Hnv(node, round, m.View); if (s.Data.ContainsKey(viewKey)) { return(null); } if (s.Data == null) { s.Data = new StateKV(); } s.Data[new View(node, round)] = m.View; var tval = origin.Round + s.Timeout + 5; if (!s.Timeouts.ContainsKey(tval)) { s.Timeouts[tval] = new List <Timeout>(); } s.Timeouts[tval].Add(new Timeout(node, round, m.View)); s.Data[viewKey] = true; return(new PrePrepare(m.Hash, node, round, m.View)); default: throw new Exception($"blockmania: unknown message kind to process: {msg.Kind()}"); } }
protected void OnPrepared(Order order, ProcessState modificationType) { Prepared?.Invoke(this, new PreparedEventArgs(order, modificationType)); }