/// <summary> /// Create a new Chain instance consisting of a single genesis header. /// </summary> /// <param name="genesisBlock">The genesis header.</param> /// <returns>The Chain instance.</returns> public static Chain CreateForGenesisBlock(ChainedHeader genesisBlock) { var chainBuilder = new ChainBuilder(); chainBuilder.AddBlock(genesisBlock); return(chainBuilder.ToImmutable()); }
public void TakeWhileAsyncDecorator_Tests() { var count = 0; var notification = new TestChainBuilderNotifier(); var services = new ChainBuilderSetupServices(notification); var chain = new ChainBuilder <int>().TakeWhile(m => Task.FromResult(m <= 2)).Handler(m => count++).BuildFunc(services); // The notification is disposed when the Take handler has processed 2 messages, trying to process the 3rd Assert.False(notification.IsDisposed); Assert.Equal(0, count); chain(1, CancellationToken.None); chain(2, CancellationToken.None); // 2 should be skipped taken Assert.Equal(2, count); chain(3, CancellationToken.None); Assert.True(notification.IsDisposed); chain(4, CancellationToken.None); // Skip the rest - still 2 Assert.Equal(2, count); }
public void FirstDecorator_Tests() { var count = 0; var notification = new TestChainBuilderNotifier(); var services = new ChainBuilderSetupServices(notification); var chain = new ChainBuilder <int>().First(m => m == 2).Handler(m => count++).BuildFunc(services); // The notification is disposed when the Take handler has processed 2 messages, trying to process the 3rd Assert.False(notification.IsDisposed); Assert.Equal(0, count); chain(1, CancellationToken.None); Assert.Equal(0, count); chain(2, CancellationToken.None); Assert.Equal(1, count); chain(3, CancellationToken.None); Assert.True(notification.IsDisposed); chain(4, CancellationToken.None); // Skip the rest - still 2 Assert.Equal(1, count); }
public void TestBlocks() { var fakeHeaders = new FakeHeaders(); var header0 = fakeHeaders.GenesisChained(); var header1 = fakeHeaders.NextChained(); var chainBuilder = new ChainBuilder(); // verify block list with 0 blocks var chainEmpty = chainBuilder.ToImmutable(); Assert.AreEqual(0, chainEmpty.Blocks.Count); // verify block list with 1 block chainBuilder.AddBlock(header0); var chain0 = chainBuilder.ToImmutable(); CollectionAssert.AreEqual(new[] { header0 }, chain0.Blocks); // verify block list with 2 blocks chainBuilder.AddBlock(header1); var chain1 = chainBuilder.ToImmutable(); CollectionAssert.AreEqual(new[] { header0, header1 }, chain1.Blocks); }
private static void FromSetExpression(ChainBuilder chain, object[] expression, string sourceFile, int lineNumber) { if (expression.Length < 4 || !expression[2].Equals("=") || !(expression[1] is string name)) { throw new SyntaxError( $"A set command has the format [set name = value], which doesn't match the expression {Writer.TermToString(expression)}.", sourceFile, lineNumber); } if (DefinitionStream.IsGlobalVariableName(name)) { chain.AddStep(new AssignmentStep(StateVariableName.Named(name), FunctionalExpressionParser.FromTuple(chain.CanonicalizeArglist(expression), 3, sourceFile, lineNumber), null)); } else if (DefinitionStream.IsLocalVariableName(name)) { chain.AddStep(new AssignmentStep(chain.GetLocal(name), FunctionalExpressionParser.FromTuple(chain.CanonicalizeArglist(expression), 3, sourceFile, lineNumber), null)); } else { throw new SyntaxError( $"A set command can only update a variable; it can't update {expression[1]}", sourceFile, lineNumber); } }
public Chains(ChainBuilder builder, List <Action <ChainBuilder, Dictionary <Type, object> > > chainRegistrations) { foreach (var chainRegistration in chainRegistrations) { chainRegistration(builder, chains); } }
public void TestToBuilder() { var fakeHeaders = new FakeHeaders(); var header0 = fakeHeaders.GenesisChained(); var header1 = fakeHeaders.NextChained(); var chainBuilder = new ChainBuilder(); // verify to builder with 0 blocks var chainEmpty = chainBuilder.ToImmutable(); var chainBuilderEmpty = chainEmpty.ToBuilder(); Assert.AreEqual(0, chainBuilderEmpty.Blocks.Count); Assert.AreEqual(0, chainBuilderEmpty.BlocksByHash.Count); // verify to builder with 1 block chainBuilder.AddBlock(header0); var chain0 = chainBuilder.ToImmutable(); var chainBuilder0 = chain0.ToBuilder(); CollectionAssert.AreEqual(new[] { header0 }, chainBuilder0.Blocks); CollectionAssert.AreEquivalent(new Dictionary <UInt256, ChainedHeader> { { header0.Hash, header0 } }, chainBuilder0.BlocksByHash); // verify to builder with 2 blocks chainBuilder.AddBlock(header1); var chain1 = chainBuilder.ToImmutable(); var chainBuilder1 = chain1.ToBuilder(); CollectionAssert.AreEqual(new[] { header0, header1 }, chainBuilder1.Blocks); CollectionAssert.AreEquivalent(new Dictionary <UInt256, ChainedHeader> { { header0.Hash, header0 }, { header1.Hash, header1 } }, chainBuilder1.BlocksByHash); }
public void TestNavigateTowardsEmpty() { // create chain var fakeHeaders = new FakeHeaders(); var header0 = fakeHeaders.GenesisChained(); var header1 = fakeHeaders.NextChained(); var header2 = fakeHeaders.NextChained(); var chainEmpty = new ChainBuilder().ToImmutable(); var chain = new ChainBuilder(new[] { header0, header1, header2 }).ToImmutable(); // verify chaining to empty does nothing Assert.AreEqual(0, chainEmpty.NavigateTowards(chainEmpty).Count()); Assert.AreEqual(0, chain.NavigateTowards(chainEmpty).Count()); // verify path from empty chain to chain CollectionAssert.AreEqual( new[] { Tuple.Create(+1, header0), Tuple.Create(+1, header1), Tuple.Create(+1, header2) } , chainEmpty.NavigateTowards(chain).ToList()); }
public void SelectManyDecorator_Test() { var count = 0; var notification = new TestChainBuilderNotifier(); var services = new ChainBuilderSetupServices(notification); var builder = new ChainBuilder <OuterMessage>(); builder.SelectMany(m => m.Messages).Skip(2).Take(2).Handler(m => count++); var chain = builder.BuildFunc(services); Assert.False(notification.IsDisposed); Assert.Equal(0, count); chain( new OuterMessage { Messages = new[] { 1, 2, 3 } }, CancellationToken.None); Assert.False(notification.IsDisposed); Assert.Equal(1, count); chain( new OuterMessage { Messages = new[] { 4, 5, 6 } }, CancellationToken.None); Assert.Equal(2, count); Assert.True(notification.IsDisposed); }
public void TestLastBlock() { var fakeHeaders = new FakeHeaders(); var header0 = fakeHeaders.GenesisChained(); var header1 = fakeHeaders.NextChained(); var chainBuilder = new ChainBuilder(); // verify last block with 0 blocks var chainEmpty = chainBuilder.ToImmutable(); Assert.IsNull(chainEmpty.LastBlock); // verify last block with 1 block chainBuilder.AddBlock(header0); var chain0 = chainBuilder.ToImmutable(); Assert.AreEqual(header0, chain0.LastBlock); // verify last block with 2 blocks chainBuilder.AddBlock(header1); var chain1 = chainBuilder.ToImmutable(); Assert.AreEqual(header1, chain1.LastBlock); }
public void TestTotalWork() { var fakeHeaders = new FakeHeaders(); var header0 = fakeHeaders.GenesisChained(); var header1 = fakeHeaders.NextChained(); var totalWork0 = DataCalculator.CalculateWork(header0); var totalWork1 = totalWork0 + DataCalculator.CalculateWork(header1); var chainBuilder = new ChainBuilder(); // verify total work with 0 blocks var chainEmpty = chainBuilder.ToImmutable(); Assert.AreEqual(0, chainEmpty.TotalWork); // verify total work with 1 block chainBuilder.AddBlock(header0); var chain0 = chainBuilder.ToImmutable(); Assert.AreEqual(totalWork0.ToBigInteger(), chain0.TotalWork); // verify total work with 2 blocks chainBuilder.AddBlock(header1); var chain1 = chainBuilder.ToImmutable(); Assert.AreEqual(totalWork1.ToBigInteger(), chain1.TotalWork); }
public void TestHeight() { var fakeHeaders = new FakeHeaders(); var header0 = fakeHeaders.GenesisChained(); var header1 = fakeHeaders.NextChained(); var chainBuilder = new ChainBuilder(); // verify height with 0 blocks var chainEmpty = chainBuilder.ToImmutable(); Assert.AreEqual(-1, chainEmpty.Height); // verify height with 1 block chainBuilder.AddBlock(header0); var chain0 = chainBuilder.ToImmutable(); Assert.AreEqual(0, chain0.Height); // verify height with 2 blocks chainBuilder.AddBlock(header1); var chain1 = chainBuilder.ToImmutable(); Assert.AreEqual(1, chain1.Height); }
public void TestNavigateTowardsFunc() { // create chains var fakeHeaders = new FakeHeaders(); var header0 = fakeHeaders.GenesisChained(); var header1 = fakeHeaders.NextChained(); var header2 = fakeHeaders.NextChained(); var header3 = fakeHeaders.NextChained(); var chain0 = new ChainBuilder(new[] { header0, }).ToImmutable(); var chain1 = new ChainBuilder(new[] { header0, header1, }).ToImmutable(); var chain2 = new ChainBuilder(new[] { header0, header1, header2 }).ToImmutable(); var chain3 = new ChainBuilder(new[] { header0, header1, header2, header3 }).ToImmutable(); // the list of target chains to use, stays 1 ahead and then catches up with chain 3 var targetStack = new Stack <Chain>(new[] { chain1, chain2, chain3, chain3 }.Reverse()); // verify navigating towards an updating chain CollectionAssert.AreEqual( new[] { Tuple.Create(+1, header1), Tuple.Create(+1, header2), Tuple.Create(+1, header3) } , chain0.NavigateTowards(() => targetStack.Pop()).ToList()); // verify all targets used Assert.AreEqual(0, targetStack.Count); }
private bool LoadTimelineDiff(CueFile cueFile, bool save = true) { if (save) { timeline.Export(); } timeline.DeleteAllTargets(); timeline.RemoveAllRepeaters(); foreach (Cue cue in cueFile.cues) { timeline.AddTargetFromAction(timeline.GetTargetDataForCue(cue)); } if (cueFile.NRCueData != null) { if (cueFile.NRCueData.pathBuilderNoteData.Count == cueFile.NRCueData.pathBuilderNoteCues.Count) { for (int i = 0; i < cueFile.NRCueData.pathBuilderNoteCues.Count; ++i) { var data = timeline.GetTargetDataForCue(cueFile.NRCueData.pathBuilderNoteCues[i]); data.pathBuilderData = cueFile.NRCueData.pathBuilderNoteData[i]; data.pathBuilderData.parentNotes.Add(data); //Recalculate the notes, and remove any identical enties that would have been loaded through the cues ChainBuilder.CalculateChainNotes(data); foreach (TargetData genData in data.pathBuilderData.generatedNotes) { var foundData = timeline.FindTargetData(genData.time, genData.behavior, genData.handType); if (foundData != null) { timeline.DeleteTargetFromAction(foundData); } } timeline.AddTargetFromAction(data); //Generate the notes, so the song is complete ChainBuilder.GenerateChainNotes(data); } } if (Timeline.audioLoaded) { foreach (var section in cueFile.NRCueData.repeaterSections) { timeline.AddRepeaterSectionFromAction(section); } } else { timeline.loadRepeaterSectionAfterAudio = cueFile.NRCueData.repeaterSections; } } return(true); }
internal static void FromCoolExpression(ChainBuilder chain, object[] expression, string sourceFile, int lineNumber) { if (expression.Length > 2) { throw new ArgumentCountException("cool", 1, expression.Skip(1).ToArray()); } var duration = 1; if (expression.Length == 2) { if (int.TryParse(expression[1] as string, out var d)) { duration = d; } else { throw new SyntaxError( $"Argument to cool must be an integer constant, but got {expression[1]}", sourceFile, lineNumber); } } chain.AddStep(new CoolStep(duration, null)); }
public void CommitTransaction(ChainBuilder chain, ImmutableSortedDictionary <UInt256, UnspentTx> .Builder unspentTransactions, ImmutableDictionary <int, IImmutableList <SpentTx> > .Builder blockSpentTxes, long chainVersion, long unspentTxesVersion, long blockSpentTxesVersion) { this.semaphore.Do(() => { if (chain != null && this.chainVersion != chainVersion || unspentTransactions != null && unspentTxesVersion != this.unspentTxesVersion || blockSpentTxes != null && blockSpentTxesVersion != this.blockSpentTxesVersion) { throw new InvalidOperationException(); } if (chain != null) { this.chain = chain.ToImmutable().ToBuilder(); this.chainVersion++; } if (unspentTransactions != null) { this.unspentTransactions = unspentTransactions.ToImmutable().ToBuilder(); this.unspentTxesVersion++; } if (blockSpentTxes != null) { this.blockSpentTxes = blockSpentTxes.ToImmutable().ToBuilder(); this.blockSpentTxesVersion++; } }); }
/// <summary> /// Emits code to load a reference to a variable onto an evaluation stack. Supports operators chaining. /// </summary> /// <param name="codeGenerator"></param> private PhpTypeCode EmitNodeReadRef(CodeGenerator codeGenerator) { ChainBuilder chain = codeGenerator.ChainBuilder; LocalBuilder local = codeGenerator.IL.DeclareLocal(typeof(object)); // Case 3: a_[x]_[x] never reached Debug.Assert(chain.IsArrayItem == false, "ReadRef access shouldn't be set to array subchain nodes"); // Case 4,5 never reached // 4: a[x]->... // 5: ...->a[]->... Debug.Assert(chain.IsMember == false); // 1, 2, 6, 7 if (this.isMemberOf != null) { // last node of the field chain // // 6 , 7: ...->a[]_[]_ , ...->a_[]_ chain.Create(); chain.Begin(); if (this.isMemberOf is FunctionCall) { chain.LoadAddressOfFunctionReturnValue = true; } chain.SetObjectForLazyEmit(this); // let's emit the array subchain followed by the GetArrayItemRef: chain.IsArrayItem = true; chain.IsLastMember = false; chain.Lengthen(); // for own [] chain.EmitGetArrayItemRef(array, index); chain.IsArrayItem = false; chain.EndRef(); return(PhpTypeCode.PhpReference); } // 1, 2 if (array is ItemUse || array is DirectStFldUse || array is IndirectStFldUse) { // we are at the beginning of the field chain // // 2: a[]_[]_ chain.Create(); chain.Begin(); chain.IsArrayItem = true; chain.IsLastMember = true; chain.Lengthen(); chain.EmitGetArrayItemRef(array, index); chain.IsArrayItem = false; chain.EndRef(); return(PhpTypeCode.PhpReference); } // no chains // // 1: a_[x]_ return(chain.EmitGetItemRef((SimpleVarUse)array, index)); }
public MemoryChainStateStorage(Chain chain = null, ImmutableSortedDictionary <UInt256, UnspentTx> unspentTransactions = null, ImmutableDictionary <int, IImmutableList <SpentTx> > blockSpentTxes = null) { this.chain = chain != null?chain.ToBuilder() : new ChainBuilder(); this.unspentTransactions = unspentTransactions != null?unspentTransactions.ToBuilder() : ImmutableSortedDictionary.CreateBuilder <UInt256, UnspentTx>(); this.blockSpentTxes = blockSpentTxes != null?blockSpentTxes.ToBuilder() : ImmutableDictionary.CreateBuilder <int, IImmutableList <SpentTx> >(); }
public void UniqueProperty_IfInputPropertyNameNotEqualDepartureOrArrival_ThrowException(string propertyName) { var build = new ChainBuilder(new List <TravelCard>()); listOfStrings.Add("a"); Assert.That(() => build.UniqueProperty(listOfStrings, propertyName), Throws.Exception); }
public void RecalculatePathbuilderData() { if (data.behavior != TargetBehavior.NR_Pathbuilder) { return; } ChainBuilder.CalculateChainNotes(data); }
public void TestAddBlockConfirmingTx() { // create tx spending a previous output that exists var decodedTx = Transaction.Create( 0, ImmutableArray.Create(new TxInput(UInt256.One, 0, ImmutableArray <byte> .Empty, 0)), ImmutableArray.Create(new TxOutput(0, ImmutableArray <byte> .Empty)), 0); var tx = decodedTx.Transaction; // create prev output tx var unspentTx = new UnspentTx(tx.Inputs[0].PrevTxHash, 0, 1, 0, false, new OutputStates(1, OutputState.Unspent)); var txOutput = new TxOutput(0, ImmutableArray <byte> .Empty); // create a fake chain var fakeHeaders = new FakeHeaders(); var genesisHeader = fakeHeaders.GenesisChained(); // create a block confirming the tx var block = Block.Create(RandomData.RandomBlockHeader().With(PreviousBlock: genesisHeader.Hash), ImmutableArray.Create(tx)); var chainedHeader = new ChainedHeader(block.Header, 1, 0, DateTimeOffset.Now); // mock core storage with chained header var coreStorage = new Mock <ICoreStorage>(); var initialChain = new ChainBuilder().ToImmutable(); coreStorage.Setup(x => x.TryReadChain(null, out initialChain)).Returns(true); coreStorage.Setup(x => x.TryGetChainedHeader(chainedHeader.Hash, out chainedHeader)).Returns(true); // mock chain state with prev output var chainState = new Mock <IChainState>(); chainState.Setup(x => x.TryGetUnspentTx(tx.Inputs[0].PrevTxHash, out unspentTx)).Returns(true); chainState.Setup(x => x.TryGetUnspentTxOutput(tx.Inputs[0].PrevTxOutputKey, out txOutput)).Returns(true); // mock core daemon for chain state retrieval var coreDaemon = new Mock <ICoreDaemon>(); coreDaemon.Setup(x => x.GetChainState()).Returns(chainState.Object); using (var unconfirmedTxesBuilder = new UnconfirmedTxesBuilder(coreDaemon.Object, coreStorage.Object, storageManager)) { // add the tx Assert.IsTrue(unconfirmedTxesBuilder.TryAddTransaction(decodedTx)); // add the block unconfirmedTxesBuilder.AddBlock(genesisHeader, Enumerable.Empty <BlockTx>()); unconfirmedTxesBuilder.AddBlock(chainedHeader, block.BlockTxes); // verify the confirmed tx was removed UnconfirmedTx unconfirmedTx; Assert.IsFalse(unconfirmedTxesBuilder.TryGetTransaction(tx.Hash, out unconfirmedTx)); Assert.IsNull(unconfirmedTx); // verify the confirmed tx was de-indexed against its input Assert.AreEqual(0, unconfirmedTxesBuilder.GetTransactionsSpending(tx.Inputs[0].PrevTxOutputKey).Count); } }
internal static void FromOnceExpression(ChainBuilder chain, object[] expression) { if (expression.Length != 1) { throw new ArgumentCountException("once", 0, expression.Skip(1).ToArray()); } chain.AddStep(new CoolStep(int.MaxValue, null)); }
public async Task <List <StoriesDescriptionResponse> > GetBestStories() { var chain = new ChainBuilder <BestStoriesChainParameters, List <StoriesDescriptionResponse> >() .Then(new StoriesIDsChain(_storiesAcl)) .Then(new StoriesDescriptionChain(_storiesAcl)) .Build(); return(await chain.Execute(new BestStoriesChainParameters { StoriesDescriptionResponseList = new List <StoriesDescriptionResponse>() })); }
internal override PhpTypeCode EmitEnsure(CodeGenerator /*!*/ codeGenerator, ChainBuilder /*!*/ chain) { // unknown property of a known type reported as an error during analysis Debug.Assert(!property.IsUnknown || property.DeclaringType.IsUnknown || !property.DeclaringType.IsDefinite); // we're only interested in a directly accessible property return(chain.EmitEnsureStaticProperty((runtimeVisibilityCheck) ? null : property, typeRef, propertyName, chain.IsArrayItem)); }
/// <summary> /// Sets up a message handler chain for the bus publisher /// </summary> /// <typeparam name="TMessageType">The message type</typeparam> /// <param name="options">The options</param> /// <param name="configureMessageHandlerChain">The action called to setup the message handler chain</param> /// <returns>Bus options</returns> public static BusOptions <TMessageType> UseSubscriptionChain <TMessageType>( this BusOptions <TMessageType> options, Action <ChainBuilder <MessageAndHandler <TMessageType> > > configureMessageHandlerChain) { var builder = new ChainBuilder <MessageAndHandler <TMessageType> >(); configureMessageHandlerChain(builder); return(UseSubscriptionChain(options, builder)); }
public PruningWorker(WorkerConfig workerConfig, ICoreDaemon coreDaemon, IStorageManager storageManager, ChainStateWorker chainStateWorker) : base("PruningWorker", workerConfig.initialNotify, workerConfig.minIdleTime, workerConfig.maxIdleTime) { this.coreDaemon = coreDaemon; this.storageManager = storageManager; this.chainStateWorker = chainStateWorker; this.prunedChain = new ChainBuilder(); this.Mode = PruningMode.None; }
/// <summary> /// Sets up a message handler chain for the bus publisher /// </summary> /// <typeparam name="TMessageType">The message type</typeparam> /// <param name="options">The options</param> /// <param name="configureMessageHandlerChain">The action called to setup the message handler chain</param> /// <returns>Bus options</returns> public static BusOptions <TMessageType> UseSubscriptionChain <TMessageType>( this BusOptions <TMessageType> options, Action <ChainBuilder <MessageAndHandler <TMessageType> >, Func <MessageAndHandler <TMessageType>, CancellationToken, Task> > configureMessageHandlerChain) { var builder = new ChainBuilder <MessageAndHandler <TMessageType> >(); configureMessageHandlerChain(builder, PublishToSubscription.PublishAsync); return(UseSubscriptionChain(options, builder)); }
private void OnBeatLengthChanged(QNT_Duration newBeatLength) { if (!data.supportsBeatLength) { return; } if (data.behavior == TargetBehavior.NR_Pathbuilder) { ChainBuilder.GenerateChainNotes(data); } }
/// <summary> /// Initializes a new instance of the <see cref="ParallelMessageHandlerChainPublisher{TMessageType}"/> class. /// </summary> /// <param name="ChainBuilder"> /// The message handler chain builder /// </param> public ParallelMessageHandlerChainPublisher(ChainBuilder <MessageAndHandler <TMessageType> > ChainBuilder) { ChainBuilder.Handler(this.PublishAsync); var subscriptionNotification = new ChainBuilderNotifier(); var services = new ChainBuilderSetupServices(subscriptionNotification); this.publisher = ChainBuilder.BuildFunc(services); var chain = new Chain <MessageAndHandler <TMessageType> >(this.publisher); subscriptionNotification.Notify(chain); }
public TestBlocks(TestBlocks parent) { this.random = parent.random; this.txManager = parent.txManager; this.coinbasePrivateKey = parent.coinbasePrivateKey; this.coinbasePublicKey = parent.coinbasePublicKey; this.miner = parent.miner; this.rules = parent.rules; this.blocks = parent.blocks.ToImmutable().ToBuilder(); this.chain = parent.chain.ToImmutable().ToBuilder(); }
private static void Main() { var chain = new ChainBuilder<ChainCommand>() .Add<Command1>() .Add<Command2>(() => new Command2("Test")) .Build(); chain.Execute(null); var command1 = new Command1(); var command2 = new Command2("Test"); command1.NextInChain = command2; command1.Execute(null); Console.WriteLine("Press enter to quit."); Console.ReadLine(); }
public override bool TryGetMember(GetMemberBinder binder, out object result) { result = new ChainBuilder(this, Session, binder.Name); return true; }
internal abstract PhpTypeCode EmitEnsure(CodeGenerator/*!*/ codeGenerator, ChainBuilder/*!*/ chain);
internal override PhpTypeCode EmitEnsure(CodeGenerator/*!*/ codeGenerator, ChainBuilder/*!*/ chain) { // unknown property of a known type reported as an error during analysis Debug.Assert(!property.IsUnknown || property.DeclaringType.IsUnknown || !property.DeclaringType.IsDefinite); // we're only interested in a directly accessible property return chain.EmitEnsureStaticProperty((runtimeVisibilityCheck) ? null : property, typeName, propertyName, chain.IsArrayItem); }
internal override PhpTypeCode EmitEnsure(CodeGenerator/*!*/ codeGenerator, ChainBuilder chain) { return chain.EmitEnsureStaticProperty(typeName, null, fieldNameExpr, chain.IsArrayItem); }