Exemple #1
0
        private void InitializeCollateralChecker([CallerMemberName] string callingMethod = "")
        {
            var loggerFactory = new LoggerFactory();
            IHttpClientFactory clientFactory = new Bitcoin.Controllers.HttpClientFactory();

            Network network = CirrusNetwork.NetworksSelector.Regtest();

            this.collateralFederationMembers = new List <CollateralFederationMember>()
            {
                new CollateralFederationMember(new PubKey("036317d97f911ce899fd0a360866d19f2dca5252c7960d4652d814ab155a8342de"), false, new Money(100), "addr1"),
                new CollateralFederationMember(new PubKey("02a08d72d47b3103261163c15aa2f6b0d007e1872ad9f5fddbfbd27bdb738156e9"), false, new Money(500), "addr2"),
                new CollateralFederationMember(new PubKey("03634c79d4e8e915cfb9f7bbef57bed32d715150836b7845b1a14c93670d816ab6"), false, new Money(100_000), "addr3")
            };

            List <IFederationMember> federationMembers = (network.Consensus.Options as PoAConsensusOptions).GenesisFederationMembers;

            federationMembers.Clear();
            federationMembers.AddRange(this.collateralFederationMembers);

            var dataFolder = TestBase.CreateTestDir(callingMethod);
            FederatedPegSettings fedPegSettings = FedPegTestsHelper.CreateSettings(network, KnownNetworks.StraxRegTest, dataFolder, out NodeSettings nodeSettings);

            var counterChainSettings = new CounterChainSettings(nodeSettings, new CounterChainNetworkWrapper(Networks.Strax.Regtest()));
            var asyncMock            = new Mock <IAsyncProvider>();

            asyncMock.Setup(a => a.RegisterTask(It.IsAny <string>(), It.IsAny <Task>()));

            ISignals signals            = new Signals(loggerFactory, new DefaultSubscriptionErrorHandler(loggerFactory));
            var      dbreezeSerializer  = new DBreezeSerializer(network.Consensus.ConsensusFactory);
            var      asyncProvider      = new AsyncProvider(loggerFactory, signals);
            var      finalizedBlockRepo = new FinalizedBlockInfoRepository(new LevelDbKeyValueRepository(nodeSettings.DataFolder, dbreezeSerializer), asyncProvider);

            finalizedBlockRepo.LoadFinalizedBlockInfoAsync(network).GetAwaiter().GetResult();

            var chainIndexerMock = new Mock <ChainIndexer>();
            var header           = new BlockHeader();

            chainIndexerMock.Setup(x => x.Tip).Returns(new ChainedHeader(header, header.GetHash(), 0));
            var fullNode = new Mock <IFullNode>();

            IFederationManager federationManager = new FederationManager(fullNode.Object, network, nodeSettings, signals, counterChainSettings);
            var votingManager     = new VotingManager(federationManager, new Mock <IPollResultExecutor>().Object, new Mock <INodeStats>().Object, nodeSettings.DataFolder, dbreezeSerializer, signals, finalizedBlockRepo, network);
            var federationHistory = new FederationHistory(federationManager, votingManager);

            votingManager.Initialize(federationHistory);

            fullNode.Setup(x => x.NodeService <VotingManager>(It.IsAny <bool>())).Returns(votingManager);

            federationManager.Initialize();

            this.collateralChecker = new CollateralChecker(clientFactory, counterChainSettings, federationManager, signals, network, asyncMock.Object, (new Mock <INodeLifetime>()).Object);
        }
        public async Task FinalizedHeightSavedOnDiskAsync()
        {
            string dir = CreateTestDir(this);

            using (var repo = new FinalizedBlockInfoRepository(dir, this.loggerFactory))
            {
                repo.SaveFinalizedBlockHashAndHeight(uint256.One, 777);
            }

            using (var repo = new FinalizedBlockInfoRepository(dir, this.loggerFactory))
            {
                await repo.LoadFinalizedBlockInfoAsync(this.Network);

                Assert.Equal(777, repo.GetFinalizedBlockInfo().Height);
            }
        }
        public PoATestsBase(TestPoANetwork network = null)
        {
            this.loggerFactory     = new LoggerFactory();
            this.signals           = new Signals.Signals(this.loggerFactory, null);
            this.network           = network == null ? new TestPoANetwork() : network;
            this.consensusOptions  = this.network.ConsensusOptions;
            this.dBreezeSerializer = new DBreezeSerializer(this.network.Consensus.ConsensusFactory);

            this.ChainIndexer = new ChainIndexer(this.network);
            IDateTimeProvider timeProvider = new DateTimeProvider();

            this.consensusSettings = new ConsensusSettings(NodeSettings.Default(this.network));

            this.federationManager = CreateFederationManager(this, this.network, this.loggerFactory, this.signals);

            this.chainIndexerMock = new Mock <ChainIndexer>();
            var header = new BlockHeader();

            this.chainIndexerMock.Setup(x => x.Tip).Returns(new ChainedHeader(header, header.GetHash(), 0));
            this.slotsManager = new SlotsManager(this.network, this.federationManager, this.chainIndexerMock.Object, this.loggerFactory);

            this.poaHeaderValidator = new PoABlockHeaderValidator(this.loggerFactory);
            this.asyncProvider      = new AsyncProvider(this.loggerFactory, this.signals, new Mock <INodeLifetime>().Object);

            var dataFolder         = new DataFolder(TestBase.CreateTestDir(this));
            var finalizedBlockRepo = new FinalizedBlockInfoRepository(new KeyValueRepository(dataFolder, this.dBreezeSerializer), this.loggerFactory, this.asyncProvider);

            finalizedBlockRepo.LoadFinalizedBlockInfoAsync(this.network).GetAwaiter().GetResult();

            this.resultExecutorMock = new Mock <IPollResultExecutor>();

            this.votingManager = new VotingManager(this.federationManager, this.loggerFactory, this.slotsManager, this.resultExecutorMock.Object, new NodeStats(timeProvider, this.loggerFactory),
                                                   dataFolder, this.dBreezeSerializer, this.signals, finalizedBlockRepo, this.network);

            this.votingManager.Initialize();

            this.chainState = new ChainState();


            this.rulesEngine = new PoAConsensusRuleEngine(this.network, this.loggerFactory, new DateTimeProvider(), this.ChainIndexer, new NodeDeployments(this.network, this.ChainIndexer),
                                                          this.consensusSettings, new Checkpoints(this.network, this.consensusSettings), new Mock <ICoinView>().Object, this.chainState, new InvalidBlockHashStore(timeProvider),
                                                          new NodeStats(timeProvider, this.loggerFactory), this.slotsManager, this.poaHeaderValidator, this.votingManager, this.federationManager, this.asyncProvider, new ConsensusRulesContainer());

            List <ChainedHeader> headers = ChainedHeadersHelper.CreateConsecutiveHeaders(50, null, false, null, this.network);

            this.currentHeader = headers.Last();
        }
        public static IFederationManager CreateFederationManager(object caller, Network network, LoggerFactory loggerFactory, ISignals signals)
        {
            string dir = TestBase.CreateTestDir(caller);

            var dbreezeSerializer = new DBreezeSerializer(network.Consensus.ConsensusFactory);

            var nodeSettings = new NodeSettings(network, args: new string[] { $"-datadir={dir}" });

            Key federationKey = new Mnemonic("lava frown leave wedding virtual ghost sibling able mammal liar wide wisdom").DeriveExtKey().PrivateKey;

            new KeyTool(nodeSettings.DataFolder).SavePrivateKey(federationKey);

            var consensusManager = new Mock <IConsensusManager>();

            consensusManager.Setup(c => c.Tip).Returns(new ChainedHeader(network.GetGenesis().Header, network.GenesisHash, 0));

            var fullNode = new Mock <IFullNode>();

            fullNode.Setup(x => x.NodeService <IConsensusManager>(false)).Returns(consensusManager.Object);

            var counterChainSettings = new CounterChainSettings(nodeSettings, new CounterChainNetworkWrapper(new StraxRegTest()));

            var federationManager  = new FederationManager(counterChainSettings, fullNode.Object, network, nodeSettings, loggerFactory, signals);
            var asyncProvider      = new AsyncProvider(loggerFactory, signals, new Mock <INodeLifetime>().Object);
            var finalizedBlockRepo = new FinalizedBlockInfoRepository(new KeyValueRepository(nodeSettings.DataFolder, dbreezeSerializer), loggerFactory, asyncProvider);

            finalizedBlockRepo.LoadFinalizedBlockInfoAsync(network).GetAwaiter().GetResult();

            var chainIndexerMock = new Mock <ChainIndexer>();
            var header           = new BlockHeader();

            chainIndexerMock.Setup(x => x.Tip).Returns(new ChainedHeader(header, header.GetHash(), 0));
            var slotsManager  = new SlotsManager(network, federationManager, chainIndexerMock.Object, loggerFactory);
            var votingManager = new VotingManager(federationManager, loggerFactory, slotsManager,
                                                  new Mock <IPollResultExecutor>().Object, new Mock <INodeStats>().Object, nodeSettings.DataFolder, dbreezeSerializer, signals, finalizedBlockRepo, network);

            votingManager.Initialize();
            fullNode.Setup(x => x.NodeService <VotingManager>(It.IsAny <bool>())).Returns(votingManager);
            federationManager.Initialize();

            return(federationManager);
        }
        public async Task FinalizedHeightSavedOnDiskAsync()
        {
            string dir       = CreateTestDir(this);
            var    kvRepo    = new LevelDbKeyValueRepository(dir, new DataStoreSerializer(this.Network.Consensus.ConsensusFactory));
            var    asyncMock = new Mock <IAsyncProvider>();

            asyncMock.Setup(a => a.RegisterTask(It.IsAny <string>(), It.IsAny <Task>()));

            using (var repo = new FinalizedBlockInfoRepository(kvRepo, this.loggerFactory, asyncMock.Object))
            {
                repo.SaveFinalizedBlockHashAndHeight(uint256.One, 777);
            }

            using (var repo = new FinalizedBlockInfoRepository(kvRepo, this.loggerFactory, asyncMock.Object))
            {
                await repo.LoadFinalizedBlockInfoAsync(this.Network);

                Assert.Equal(777, repo.GetFinalizedBlockInfo().Height);
            }
        }
        private VotingManager InitializeVotingManager(NodeSettings nodeSettings)
        {
            var dbreezeSerializer  = new DBreezeSerializer(this.network.Consensus.ConsensusFactory);
            var asyncProvider      = new AsyncProvider(this.loggerFactory, this.signals, new Mock <INodeLifetime>().Object);
            var finalizedBlockRepo = new FinalizedBlockInfoRepository(new KeyValueRepository(nodeSettings.DataFolder, dbreezeSerializer), this.loggerFactory, asyncProvider);

            finalizedBlockRepo.LoadFinalizedBlockInfoAsync(this.network).GetAwaiter().GetResult();

            var chainIndexerMock = new Mock <ChainIndexer>();
            var header           = new BlockHeader();

            chainIndexerMock.Setup(x => x.Tip).Returns(new ChainedHeader(header, header.GetHash(), 0));

            var slotsManager  = new SlotsManager(this.network, this.federationManager, chainIndexerMock.Object, this.loggerFactory);
            var votingManager = new VotingManager(this.federationManager, this.loggerFactory, slotsManager, new Mock <IPollResultExecutor>().Object, new Mock <INodeStats>().Object, nodeSettings.DataFolder, dbreezeSerializer, this.signals, finalizedBlockRepo, this.network);

            votingManager.Initialize();

            return(votingManager);
        }
        public async Task FinalizedHeightCantBeDecreasedAsync()
        {
            string dir    = CreateTestDir(this);
            var    kvRepo = new KeyValueRepository(dir, new DBreezeSerializer(this.Network));

            using (var repo = new FinalizedBlockInfoRepository(kvRepo, this.loggerFactory))
            {
                repo.SaveFinalizedBlockHashAndHeight(uint256.One, 777);
                repo.SaveFinalizedBlockHashAndHeight(uint256.One, 555);

                Assert.Equal(777, repo.GetFinalizedBlockInfo().Height);
            }

            using (var repo = new FinalizedBlockInfoRepository(kvRepo, this.loggerFactory))
            {
                await repo.LoadFinalizedBlockInfoAsync(this.Network);

                Assert.Equal(777, repo.GetFinalizedBlockInfo().Height);
            }
        }
        public async Task FinalizedHeightCantBeDecreasedAsync()
        {
            string dir       = CreateTestDir(this);
            var    kvRepo    = new LevelDbKeyValueRepository(dir, new DBreezeSerializer(this.Network.Consensus.ConsensusFactory));
            var    asyncMock = new Mock <IAsyncProvider>();

            asyncMock.Setup(a => a.RegisterTask(It.IsAny <string>(), It.IsAny <Task>()));

            using (var repo = new FinalizedBlockInfoRepository(kvRepo, asyncMock.Object))
            {
                repo.Initialize(new ChainedHeader(this.Network.GetGenesis().Header, this.Network.GetGenesis().GetHash(), 0));
                repo.SaveFinalizedBlockHashAndHeight(uint256.One, 777);
                repo.SaveFinalizedBlockHashAndHeight(uint256.One, 555);

                Assert.Equal(777, repo.GetFinalizedBlockInfo().Height);
            }

            using (var repo = new FinalizedBlockInfoRepository(kvRepo, asyncMock.Object))
            {
                await repo.LoadFinalizedBlockInfoAsync(this.Network);

                Assert.Equal(777, repo.GetFinalizedBlockInfo().Height);
            }
        }
        public static (IFederationManager federationManager, IFederationHistory federationHistory) CreateFederationManager(object caller, Network network, LoggerFactory loggerFactory, ISignals signals)
        {
            string dir = TestBase.CreateTestDir(caller);

            var dbreezeSerializer = new DBreezeSerializer(network.Consensus.ConsensusFactory);

            var nodeSettings = new NodeSettings(network, args: new string[] { $"-datadir={dir}" });

            Key federationKey = new Mnemonic("lava frown leave wedding virtual ghost sibling able mammal liar wide wisdom").DeriveExtKey().PrivateKey;

            new KeyTool(nodeSettings.DataFolder).SavePrivateKey(federationKey);

            var consensusManager = new Mock <IConsensusManager>();

            consensusManager.Setup(c => c.Tip).Returns(new ChainedHeader(network.GetGenesis().Header, network.GenesisHash, 0));

            var fullNode = new Mock <IFullNode>();

            fullNode.Setup(x => x.NodeService <IConsensusManager>(false)).Returns(consensusManager.Object);

            var counterChainSettings = new CounterChainSettings(nodeSettings, new CounterChainNetworkWrapper(new StraxRegTest()));

            var federationManager  = new FederationManager(fullNode.Object, network, nodeSettings, signals, counterChainSettings);
            var asyncProvider      = new AsyncProvider(loggerFactory, signals);
            var finalizedBlockRepo = new FinalizedBlockInfoRepository(new LevelDbKeyValueRepository(nodeSettings.DataFolder, dbreezeSerializer), asyncProvider);

            finalizedBlockRepo.LoadFinalizedBlockInfoAsync(network).GetAwaiter().GetResult();

            var chainIndexerMock = new Mock <ChainIndexer>();
            var header           = new BlockHeader();

            chainIndexerMock.Setup(x => x.Tip).Returns(new ChainedHeader(header, header.GetHash(), 0));
            var votingManager = new VotingManager(federationManager, new Mock <IPollResultExecutor>().Object,
                                                  new Mock <INodeStats>().Object, nodeSettings.DataFolder, dbreezeSerializer, signals, finalizedBlockRepo, network);

            var federationHistory = new Mock <IFederationHistory>();

            federationHistory.Setup(x => x.GetFederationMemberForBlock(It.IsAny <ChainedHeader>())).Returns <ChainedHeader>((chainedHeader) =>
            {
                List <IFederationMember> members = ((PoAConsensusOptions)network.Consensus.Options).GenesisFederationMembers;
                return(members[chainedHeader.Height % members.Count]);
            });

            federationHistory.Setup(x => x.GetFederationMemberForBlock(It.IsAny <ChainedHeader>(), It.IsAny <List <IFederationMember> >())).Returns <ChainedHeader, List <IFederationMember> >((chainedHeader, members) =>
            {
                members = members ?? ((PoAConsensusOptions)network.Consensus.Options).GenesisFederationMembers;
                return(members[chainedHeader.Height % members.Count]);
            });

            federationHistory.Setup(x => x.GetFederationForBlock(It.IsAny <ChainedHeader>())).Returns <ChainedHeader>((chainedHeader) =>
            {
                return(((PoAConsensusOptions)network.Consensus.Options).GenesisFederationMembers);
            });

            federationHistory
            .Setup(x => x.GetFederationMemberForTimestamp(It.IsAny <uint>(), It.IsAny <PoAConsensusOptions>()))
            .Returns <uint, PoAConsensusOptions>((headerUnixTimestamp, poAConsensusOptions) =>
            {
                List <IFederationMember> federationMembers = poAConsensusOptions.GenesisFederationMembers;

                uint roundTime = (uint)(federationMembers.Count * poAConsensusOptions.TargetSpacingSeconds);

                // Time when current round started.
                uint roundStartTimestamp = (headerUnixTimestamp / roundTime) * roundTime;

                // Slot number in current round.
                int currentSlotNumber = (int)((headerUnixTimestamp - roundStartTimestamp) / poAConsensusOptions.TargetSpacingSeconds);

                return(federationMembers[currentSlotNumber]);
            });

            votingManager.Initialize(federationHistory.Object);
            fullNode.Setup(x => x.NodeService <VotingManager>(It.IsAny <bool>())).Returns(votingManager);
            federationManager.Initialize();

            return(federationManager, federationHistory.Object);
        }