public KeyTool(DataFolder dataFolder)
 {
     this.dataFolder = dataFolder;
 }
 public ChainRepository(DataFolder dataFolder, ILoggerFactory loggerFactory)
     : this(dataFolder.ChainPath, loggerFactory)
 {
 }
Exemple #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DnsSeedServer"/> class with the port to listen on.
        /// </summary>
        /// <param name="client">The UDP client to use to receive DNS requests and send DNS responses.</param>
        /// <param name="masterFile">The initial DNS masterfile.</param>
        /// <param name="asyncLoopFactory">The async loop factory.</param>
        /// <param name="loggerFactory">The logger factory.</param>
        /// <param name="dateTimeProvider">The <see cref="DateTime"/> provider.</param>
        /// <param name="dataFolders">The data folders of the system.</param>
        public DnsSeedServer(IUdpClient client, IMasterFile masterFile, IAsyncLoopFactory asyncLoopFactory, INodeLifetime nodeLifetime, ILoggerFactory loggerFactory, IDateTimeProvider dateTimeProvider, DnsSettings dnsSettings, DataFolder dataFolders)
        {
            Guard.NotNull(client, nameof(client));
            Guard.NotNull(masterFile, nameof(masterFile));
            Guard.NotNull(asyncLoopFactory, nameof(asyncLoopFactory));
            Guard.NotNull(nodeLifetime, nameof(nodeLifetime));
            Guard.NotNull(loggerFactory, nameof(loggerFactory));
            Guard.NotNull(dateTimeProvider, nameof(dateTimeProvider));
            Guard.NotNull(dnsSettings, nameof(dnsSettings));
            Guard.NotNull(dataFolders, nameof(dataFolders));

            this.udpClient        = client;
            this.masterFile       = masterFile;
            this.asyncLoopFactory = asyncLoopFactory;
            this.nodeLifetime     = nodeLifetime;
            this.logger           = loggerFactory.CreateLogger(this.GetType().FullName);
            this.dateTimeProvider = dateTimeProvider;
            this.dnsSettings      = dnsSettings;
            this.dataFolders      = dataFolders;
            this.metrics          = new DnsMetric();
        }
 public AppsFeature(ILoggerFactory loggerFactory, IAppsStore appsStore, IAppsHost appsHost, DataFolder dataFolder)
 {
     this.appsStore  = appsStore;
     this.appsHost   = appsHost;
     this.dataFolder = dataFolder;
     this.logger     = loggerFactory.CreateLogger("Impleum.Bitcoin.Fullnode");
 }
        public async Task WhenDnsServerListening_AndDnsRequestReceivedRepeatedly_ThenResponsesReturnedInRoundRobinOrder_Async()
        {
            // Arrange.
            Queue <CancellationTokenSource> sources = new Queue <CancellationTokenSource>();
            Queue <byte[]>    responses             = new Queue <byte[]>();
            Mock <IUdpClient> udpClient             = new Mock <IUdpClient>();

            udpClient.Setup(c => c.ReceiveAsync()).ReturnsAsync(new Tuple <IPEndPoint, byte[]>(new IPEndPoint(IPAddress.Loopback, 80), this.GetDnsRequest()));
            udpClient.Setup(c => c.SendAsync(It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <IPEndPoint>())).Callback <byte[], int, IPEndPoint>((p, s, ip) =>
            {
                // One response at a time.
                responses.Enqueue(p);
                CancellationTokenSource source = sources.Dequeue();
                source.Cancel();
            }).ReturnsAsync(1);

            DnsSeedMasterFile masterFile = new DnsSeedMasterFile();

            masterFile.Add(new IPAddressResourceRecord(new Domain("google.com"), IPAddress.Parse("192.168.0.1")));
            masterFile.Add(new IPAddressResourceRecord(new Domain("google.com"), IPAddress.Parse("192.168.0.2")));
            masterFile.Add(new IPAddressResourceRecord(new Domain("google.com"), IPAddress.Parse("192.168.0.3")));
            masterFile.Add(new IPAddressResourceRecord(new Domain("google.com"), IPAddress.Parse("192.168.0.4")));

            IAsyncLoopFactory asyncLoopFactory = new Mock <IAsyncLoopFactory>().Object;
            INodeLifetime     nodeLifetime     = new Mock <INodeLifetime>().Object;
            DnsSettings       dnsSettings      = new Mock <DnsSettings>().Object;

            dnsSettings.DnsHostName   = "host.example.com";
            dnsSettings.DnsNameServer = "ns1.host.example.com";
            dnsSettings.DnsMailBox    = "*****@*****.**";
            DataFolder dataFolder = CreateDataFolder(this);

            Mock <ILogger>        logger        = new Mock <ILogger>();
            Mock <ILoggerFactory> loggerFactory = new Mock <ILoggerFactory>();

            loggerFactory.Setup <ILogger>(f => f.CreateLogger(It.IsAny <string>())).Returns(logger.Object);

            IDateTimeProvider dateTimeProvider = new Mock <IDateTimeProvider>().Object;

            // Act (Part 1).
            DnsSeedServer server = new DnsSeedServer(udpClient.Object, masterFile, asyncLoopFactory, nodeLifetime, loggerFactory.Object, dateTimeProvider, dnsSettings, dataFolder);

            try
            {
                CancellationTokenSource source = new CancellationTokenSource();
                sources.Enqueue(source);
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected.
            }

            // Assert (Part 1).
            responses.Count.Should().Be(1);
            byte[]    response    = responses.Dequeue();
            IResponse dnsResponse = Response.FromArray(response);

            dnsResponse.AnswerRecords.Count.Should().Be(4);
            dnsResponse.AnswerRecords[0].Should().BeOfType <IPAddressResourceRecord>();

            ((IPAddressResourceRecord)dnsResponse.AnswerRecords[0]).IPAddress.ToString().Should().Be("192.168.0.1");

            while (responses.Count > 0)
            {
                // Consume queue completely.
                responses.Dequeue();
            }

            // Act (Part 2).
            try
            {
                CancellationTokenSource source = new CancellationTokenSource();
                sources.Enqueue(source);
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected.
            }

            // Assert (Part 2).
            responses.Count.Should().Be(1);
            response    = responses.Dequeue();
            dnsResponse = Response.FromArray(response);

            dnsResponse.AnswerRecords.Count.Should().Be(4);
            dnsResponse.AnswerRecords[0].Should().BeOfType <IPAddressResourceRecord>();

            ((IPAddressResourceRecord)dnsResponse.AnswerRecords[0]).IPAddress.ToString().Should().Be("192.168.0.2");

            while (responses.Count > 0)
            {
                // Consume queue completely.
                responses.Dequeue();
            }

            // Act (Part 3).
            try
            {
                CancellationTokenSource source = new CancellationTokenSource();
                sources.Enqueue(source);
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected.
            }

            // Assert (Part 3).
            responses.Count.Should().Be(1);
            response    = responses.Dequeue();
            dnsResponse = Response.FromArray(response);

            dnsResponse.AnswerRecords.Count.Should().Be(4);
            dnsResponse.AnswerRecords[0].Should().BeOfType <IPAddressResourceRecord>();

            ((IPAddressResourceRecord)dnsResponse.AnswerRecords[0]).IPAddress.ToString().Should().Be("192.168.0.3");

            while (responses.Count > 0)
            {
                // Consume queue completely.
                responses.Dequeue();
            }

            // Act (Part 4).
            try
            {
                CancellationTokenSource source = new CancellationTokenSource();
                sources.Enqueue(source);
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected.
            }

            // Assert (Part 4).
            responses.Count.Should().Be(1);
            response    = responses.Dequeue();
            dnsResponse = Response.FromArray(response);

            dnsResponse.AnswerRecords.Count.Should().Be(4);
            dnsResponse.AnswerRecords[0].Should().BeOfType <IPAddressResourceRecord>();

            ((IPAddressResourceRecord)dnsResponse.AnswerRecords[0]).IPAddress.ToString().Should().Be("192.168.0.4");

            while (responses.Count > 0)
            {
                // Consume queue completely.
                responses.Dequeue();
            }

            // Act (Part 5).
            try
            {
                CancellationTokenSource source = new CancellationTokenSource();
                sources.Enqueue(source);
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected.
            }

            // Assert (Part 5).
            responses.Count.Should().Be(1);
            response    = responses.Dequeue();
            dnsResponse = Response.FromArray(response);

            dnsResponse.AnswerRecords.Count.Should().Be(4);
            dnsResponse.AnswerRecords[0].Should().BeOfType <IPAddressResourceRecord>();

            // This should start back at the beginning again.
            ((IPAddressResourceRecord)dnsResponse.AnswerRecords[0]).IPAddress.ToString().Should().Be("192.168.0.1");

            while (responses.Count > 0)
            {
                // Consume queue completely.
                responses.Dequeue();
            }
        }
        public void PeerConnectorDiscovery_DoesNotConnectTo_NodeInSameNetworkGroup_WithIpRangeFilteringEnabled()
        {
            DataFolder peerFolder         = CreateDataFolder(this);
            var        peerAddressManager = new PeerAddressManager(DateTimeProvider.Default, peerFolder, this.extendedLoggerFactory, new SelfEndpointTracker(this.extendedLoggerFactory));

            // IpRangeFiltering enabled by default.
            var nodeSettings = new NodeSettings(this.Network, args: new[] { "-IpRangeFiltering" });

            var connectionManagerSettingsExisting = new ConnectionManagerSettings(nodeSettings);
            Mock <INetworkPeerFactory> networkPeerFactoryExisting = new Mock <INetworkPeerFactory>();

            Mock <IConnectionManager> connectionManagerExisting = new Mock <IConnectionManager>();

            connectionManagerExisting.SetupGet(np => np.Parameters).Returns(this.networkPeerParameters);
            connectionManagerExisting.SetupGet(np => np.ConnectedPeers).Returns(new NetworkPeerCollection());

            var peerConnector = new PeerConnectorConnectNode(this.asyncLoopFactory, DateTimeProvider.Default, this.extendedLoggerFactory, this.Network, networkPeerFactoryExisting.Object, this.nodeLifetime, nodeSettings, connectionManagerSettingsExisting, peerAddressManager, new SelfEndpointTracker(this.extendedLoggerFactory));

            peerConnector.Initialize(connectionManagerExisting.Object);

            // Peer 1.
            IPAddress originalAddressPeer1 = IPAddress.Parse("::ffff:57.48.183.81"); // ipv4
            var       endpointPeer1        = new IPEndPoint(originalAddressPeer1, 80);

            peerAddressManager.AddPeer(endpointPeer1, IPAddress.Loopback);
            bool connectedToThisPeer = ConnectToPeer(peerAddressManager, networkPeerFactoryExisting, connectionManagerSettingsExisting, peerConnector, endpointPeer1, connectionManagerExisting);

            Assert.True(connectedToThisPeer);

            // Peer 2 has different network group to Peer 1.
            IPAddress addressInDifferentNetworkGroupPeer2 = IPAddress.Parse("99be:f5c5:adc2:525c:f6d7:7b30:5336:5a0f"); // ipv6
            var       endpointPeer2 = new IPEndPoint(addressInDifferentNetworkGroupPeer2, 80);

            peerAddressManager.AddPeer(endpointPeer2, IPAddress.Loopback);
            connectedToThisPeer = ConnectToPeer(peerAddressManager, networkPeerFactoryExisting, connectionManagerSettingsExisting, peerConnector, endpointPeer2, connectionManagerExisting);
            Assert.True(connectedToThisPeer); // Different network group: connects.

            // Peer 3 in same network group as Peer 2.
            IPAddress addressInSameNetworkGroupPeer3 = IPAddress.Parse("99be:f5c5:adc2:525c:db45:d36e:ce01:a394"); // ipv6
            var       endpointPeer3 = new IPEndPoint(addressInSameNetworkGroupPeer3, 80);

            peerAddressManager.AddPeer(endpointPeer3, IPAddress.Loopback);
            connectedToThisPeer = ConnectToPeer(peerAddressManager, networkPeerFactoryExisting, connectionManagerSettingsExisting, peerConnector, endpointPeer3, connectionManagerExisting);
            Assert.False(connectedToThisPeer); // Same network group: does not connect.

            // Peer 4 has different network group to Peer 1.
            IPAddress addressInDifferentNetworkGroupPeer4 = IPAddress.Parse("::ffff:58.48.183.81"); // ipv4
            var       endpointPeer4 = new IPEndPoint(addressInDifferentNetworkGroupPeer4, 80);

            peerAddressManager.AddPeer(endpointPeer4, IPAddress.Loopback);
            connectedToThisPeer = ConnectToPeer(peerAddressManager, networkPeerFactoryExisting, connectionManagerSettingsExisting, peerConnector, endpointPeer4, connectionManagerExisting);
            Assert.True(connectedToThisPeer); // Different network group: connects.

            // Peer 5 has same network group as Peer 1.
            IPAddress addressInSameNetworkGroupPeer5 = IPAddress.Parse("::ffff:57.48.183.82"); // ipv4
            var       endpointPeer5 = new IPEndPoint(addressInSameNetworkGroupPeer5, 80);

            peerAddressManager.AddPeer(endpointPeer5, IPAddress.Loopback);
            connectedToThisPeer = ConnectToPeer(peerAddressManager, networkPeerFactoryExisting, connectionManagerSettingsExisting, peerConnector, endpointPeer5, connectionManagerExisting);
            Assert.False(connectedToThisPeer); // Same network group: does not connect.
        }
Exemple #7
0
 public RocksdbKeyValueRepository(DataFolder dataFolder, DataStoreSerializer dataStoreSerializer) : this(dataFolder.KeyValueRepositoryPath, dataStoreSerializer)
 {
 }
Exemple #8
0
        public static string GetX1WalletMetaDataFilepath(this string walletName, Network network, DataFolder dataFolder)
        {
            if (string.IsNullOrWhiteSpace(walletName))
            {
                throw new ArgumentNullException(nameof(walletName));
            }

            var    fileName = $"{walletName}.{network.CoinTicker}{X1WalletMetadataFile.FileExtension}";
            string filePath = Path.Combine(dataFolder.WalletPath, fileName);

            return(filePath);
        }
 public BlockRepository(Network network, DataFolder dataFolder, IDateTimeProvider dateTimeProvider, ILoggerFactory loggerFactory)
     : this(network, dataFolder.BlockPath, dateTimeProvider, loggerFactory)
 {
 }
Exemple #10
0
 public LevelDbBlockRepository(Network network, DataFolder dataFolder,
                               ILoggerFactory loggerFactory, DataStoreSerializer dataStoreSerializer)
     : this(network, dataFolder.BlockPath, loggerFactory, dataStoreSerializer)
 {
 }
Exemple #11
0
 public DBreezeCoinView(Network network, DataFolder dataFolder)
     : this(network, dataFolder.CoinViewPath)
 {
 }
        public void WalletStore_GetAccountHistory()
        {
            DataFolder dataFolder = CreateDataFolder(this);

            WalletStore store = new WalletStore(this.Network, dataFolder, new Types.Wallet {
                Name = "wallet1", EncryptedSeed = "EncryptedSeed1"
            });

            string script = null;

            script = new Key().PubKey.GetAddress(this.Network).ScriptPubKey.ToString();

            TransactionOutputData trx = null;
            ulong index = 20;
            ulong time  = 2000;
            var   dt    = DateTimeOffset.Now;

            // unconfirmed spent
            trx = Create(new OutPoint(new uint256(index++), 10), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.BlockHeight = null; trx.SpendingDetails.BlockHeight = null; trx.IsColdCoinStake = true; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index++), 10), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.BlockHeight = null; trx.SpendingDetails.BlockHeight = null; trx.IsColdCoinStake = true; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index++), 10), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.BlockHeight = null; trx.SpendingDetails.BlockHeight = null; trx.IsColdCoinStake = false; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index++), 10), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.BlockHeight = null; trx.SpendingDetails.BlockHeight = null; trx.IsColdCoinStake = false; store.InsertOrUpdate(trx);
            // with 4 outputs
            trx = Create(new OutPoint(new uint256(index++), 00), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.BlockHeight = null; trx.SpendingDetails.BlockHeight = null; trx.IsColdCoinStake = false; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index), 0001), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.BlockHeight = null; trx.SpendingDetails.BlockHeight = null; trx.IsColdCoinStake = false; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index), 0002), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.BlockHeight = null; trx.SpendingDetails.BlockHeight = null; trx.IsColdCoinStake = false; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index), 0003), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.BlockHeight = null; trx.SpendingDetails.BlockHeight = null; trx.IsColdCoinStake = false; store.InsertOrUpdate(trx);

            // unconfirmed unspent
            trx = Create(new OutPoint(new uint256(index++), 10), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.BlockHeight = null; trx.SpendingDetails = null; trx.IsColdCoinStake = true; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index++), 10), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.BlockHeight = null; trx.SpendingDetails = null; trx.IsColdCoinStake = true; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index++), 10), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.BlockHeight = null; trx.SpendingDetails = null; trx.IsColdCoinStake = false; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index++), 10), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.BlockHeight = null; trx.SpendingDetails = null; trx.IsColdCoinStake = false; store.InsertOrUpdate(trx);
            // with 4 outputs
            trx = Create(new OutPoint(new uint256(index++), 00), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.BlockHeight = null; trx.SpendingDetails = null; trx.IsColdCoinStake = true; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index), 0001), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.BlockHeight = null; trx.SpendingDetails = null; trx.IsColdCoinStake = true; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index), 0002), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.BlockHeight = null; trx.SpendingDetails = null; trx.IsColdCoinStake = false; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index), 0003), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.BlockHeight = null; trx.SpendingDetails = null; trx.IsColdCoinStake = false; store.InsertOrUpdate(trx);

            // confirmed spent
            trx = Create(new OutPoint(new uint256(index++), 10), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.IsColdCoinStake = true; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index++), 10), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.IsColdCoinStake = true; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index++), 10), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.IsColdCoinStake = false; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index++), 10), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.IsColdCoinStake = false; store.InsertOrUpdate(trx);
            // with 4 outputs
            trx = Create(new OutPoint(new uint256(index++), 00), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.IsColdCoinStake = false; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index), 0001), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.IsColdCoinStake = false; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index), 0002), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.IsColdCoinStake = false; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index), 0003), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.IsColdCoinStake = false; store.InsertOrUpdate(trx);

            // confirmed unspent
            trx = Create(new OutPoint(new uint256(index++), 10), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.SpendingDetails = null; trx.IsColdCoinStake = true; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index++), 10), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.SpendingDetails = null; trx.IsColdCoinStake = true; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index++), 10), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.SpendingDetails = null; trx.IsColdCoinStake = false; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index++), 10), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.SpendingDetails = null; trx.IsColdCoinStake = false; store.InsertOrUpdate(trx);
            // with 4 outputs
            trx = Create(new OutPoint(new uint256(index++), 00), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.SpendingDetails = null; trx.IsColdCoinStake = true; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index), 0001), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.SpendingDetails = null; trx.IsColdCoinStake = true; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index), 0002), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.SpendingDetails = null; trx.IsColdCoinStake = false; store.InsertOrUpdate(trx);
            trx = Create(new OutPoint(new uint256(index), 0003), script, 2); trx.SpendingDetails.CreationTime = dt.AddMinutes(time--); trx.SpendingDetails = null; trx.IsColdCoinStake = false; store.InsertOrUpdate(trx);

            var res = store.GetAccountHistory(2, false);

            res.Should().HaveCount(22);
            res = store.GetAccountHistory(2, true);
            res.Should().HaveCount(15);
        }
        public void WalletStore_GetBalanceForAddress_And_GetBalanceForAccount()
        {
            DataFolder dataFolder = CreateDataFolder(this);

            WalletStore store = new WalletStore(this.Network, dataFolder, new Types.Wallet {
                Name = "wallet1", EncryptedSeed = "EncryptedSeed1"
            });

            // Create some temp data
            for (int indexAddress = 0; indexAddress < 3; indexAddress++)
            {
                var scriptInsert = new Key().PubKey.GetAddress(this.Network).ScriptPubKey.ToString();
                for (int indexTrx = 0; indexTrx < 5; indexTrx++)
                {
                    store.InsertOrUpdate(Create(new OutPoint(new uint256((ulong)indexTrx), indexAddress), scriptInsert));
                }
            }

            string script = null;

            for (int accountIndex = 0; accountIndex < 2; accountIndex++)
            {
                script = new Key().PubKey.GetAddress(this.Network).ScriptPubKey.ToString();

                TransactionOutputData trx = null;

                // spent
                trx = Create(new OutPoint(new uint256(21), accountIndex * 10), script, 2); store.InsertOrUpdate(trx);
                trx = Create(new OutPoint(new uint256(22), accountIndex * 10), script, 2); trx.IsColdCoinStake = true; store.InsertOrUpdate(trx);
                trx = Create(new OutPoint(new uint256(23), accountIndex * 10), script, 2); trx.IsColdCoinStake = true; trx.BlockHeight = null; store.InsertOrUpdate(trx);

                // cold stake unspent spend
                trx = Create(new OutPoint(new uint256(3), accountIndex * 10), script, 2); trx.IsColdCoinStake = true; trx.SpendingDetails = null; store.InsertOrUpdate(trx);
                trx = Create(new OutPoint(new uint256(4), accountIndex * 10), script, 2); trx.IsColdCoinStake = true; trx.SpendingDetails = null; store.InsertOrUpdate(trx);

                // cold stake unspent spend unconfirmed
                trx = Create(new OutPoint(new uint256(5), accountIndex * 10), script, 2); trx.IsColdCoinStake = true; trx.BlockHeight = null; trx.SpendingDetails = null; store.InsertOrUpdate(trx);
                trx = Create(new OutPoint(new uint256(6), accountIndex * 10), script, 2); trx.IsColdCoinStake = true; trx.BlockHeight = null; trx.SpendingDetails = null; store.InsertOrUpdate(trx);

                // unspent spend
                trx = Create(new OutPoint(new uint256(7), accountIndex * 10), script, 2); trx.IsColdCoinStake = false; trx.SpendingDetails = null; store.InsertOrUpdate(trx);
                trx = Create(new OutPoint(new uint256(8), accountIndex * 10), script, 2); trx.IsColdCoinStake = null; trx.SpendingDetails = null; store.InsertOrUpdate(trx);

                // unspent spend unconfirmed
                trx = Create(new OutPoint(new uint256(9), accountIndex * 10), script, 2); trx.IsColdCoinStake = false; trx.BlockHeight = null; trx.SpendingDetails = null; store.InsertOrUpdate(trx);
                trx = Create(new OutPoint(new uint256(10), accountIndex * 10), script, 2); trx.IsColdCoinStake = null; trx.BlockHeight = null; trx.SpendingDetails = null; store.InsertOrUpdate(trx);
            }

            var findforAddress = script;
            var res            = store.GetBalanceForAddress(findforAddress, false);

            res.AmountConfirmed.Should().Be(20);
            res.AmountUnconfirmed.Should().Be(20);

            res = store.GetBalanceForAddress(findforAddress, true);
            res.AmountConfirmed.Should().Be(10);
            res.AmountUnconfirmed.Should().Be(10);

            res = store.GetBalanceForAccount(2, false);
            res.AmountConfirmed.Should().Be(40);
            res.AmountUnconfirmed.Should().Be(40);

            res = store.GetBalanceForAccount(2, true);
            res.AmountConfirmed.Should().Be(20);
            res.AmountUnconfirmed.Should().Be(20);
        }
        private WalletTransactionHandlerTestContext SetupWallet(FeeRate feeRate = null, int coinBaseBlocks = 1)
        {
            DataFolder dataFolder = CreateDataFolder(this);

            IWalletRepository walletRepository = new SQLiteWalletRepository(this.LoggerFactory.Object, dataFolder, this.Network, DateTimeProvider.Default, new ScriptAddressReader())
            {
                TestMode = true
            };

            var walletFeePolicy = new Mock <IWalletFeePolicy>();

            walletFeePolicy.Setup(w => w.GetFeeRate(FeeType.Low.ToConfirmations()))
            .Returns(feeRate ?? new FeeRate(20000));

            var chain = new ChainIndexer(this.Network);

            var walletManager = new WalletManager(this.LoggerFactory.Object, this.Network, chain,
                                                  new WalletSettings(NodeSettings.Default(this.Network)), dataFolder,
                                                  walletFeePolicy.Object, new Mock <IAsyncProvider>().Object, new NodeLifetime(), DateTimeProvider.Default, this.scriptAddressReader, walletRepository);

            var reserveUtxoService = new ReserveUtxoService(this.loggerFactory, new Mock <ISignals>().Object);

            var walletTransactionHandler = new WalletTransactionHandler(this.LoggerFactory.Object, walletManager, walletFeePolicy.Object, this.Network, this.standardTransactionPolicy, reserveUtxoService);

            walletManager.Start();

            var walletReference = new WalletAccountReference
            {
                AccountName = "account1",
                WalletName  = "myWallet1"
            };

            Wallet wallet = WalletTestsHelpers.GenerateBlankWallet(walletReference.WalletName, "password", walletRepository);

            (ExtKey ExtKey, string ExtPubKey)accountKeys = WalletTestsHelpers.GenerateAccountKeys(wallet, "password", $"m/44'/{this.Network.Consensus.CoinType}'/0'");

            var account = wallet.AddNewAccount(accountKeys.ExtKey.Neuter(), accountName: walletReference.AccountName);

            var destinationAddress = account.ExternalAddresses.Skip(1).First();

            (PubKey PubKey, BitcoinPubKeyAddress Address)destinationKeys = (destinationAddress.Pubkey.GetDestinationPublicKeys(this.Network).First(), new BitcoinPubKeyAddress(destinationAddress.Address, this.Network));

            HdAddress address = account.ExternalAddresses.ElementAt(0);

            TransactionData addressTransaction = null;

            if (coinBaseBlocks != 0)
            {
                WalletTestsHelpers.AddBlocksWithCoinbaseToChain(wallet.Network, chain, address, coinBaseBlocks);
                addressTransaction = address.Transactions.First();
            }

            return(new WalletTransactionHandlerTestContext
            {
                Wallet = wallet,
                AccountKeys = accountKeys,
                DestinationKeys = destinationKeys,
                AddressTransaction = addressTransaction,
                WalletTransactionHandler = walletTransactionHandler,
                WalletReference = walletReference
            });
        }
Exemple #15
0
 public static string GetFilePath(string fileName, DataFolder folderPath, DataFormat format)
 {
     return(Path.Combine(
                GetFolderPath(folderPath),
                $"{fileName}.{format.ToString().ToLowerInvariant()}"));
 }
 public ChainRepository(DataFolder dataFolder, ILoggerFactory loggerFactory, DBreezeSerializer dBreezeSerializer)
     : this(dataFolder.ChainPath, loggerFactory, dBreezeSerializer)
 {
 }
 /// <summary>
 /// Initializes a new instance of the object.
 /// </summary>
 /// <param name="network">Specification of the network the node runs on - RegTest/TestNet/MainNet.</param>
 /// <param name="folder"><see cref="RocksDbProvenBlockHeaderRepository"/> folder path to the DBreeze database files.</param>
 /// <param name="loggerFactory">Factory to create a logger for this type.</param>
 /// <param name="dataStoreSerializer">The serializer to use for <see cref="IBitcoinSerializable"/> objects.</param>
 public RocksDbProvenBlockHeaderRepository(Network network, DataFolder folder, ILoggerFactory loggerFactory,
                                           DataStoreSerializer dataStoreSerializer)
     : this(network, folder.ProvenBlockHeaderPath, loggerFactory, dataStoreSerializer)
 {
 }
Exemple #18
0
        public RPCMiddleware(RequestDelegate next, IRPCAuthorization authorization, ILoggerFactory loggerFactory, IHttpContextFactory httpContextFactory, DataFolder dataFolder)
        {
            Guard.NotNull(next, nameof(next));
            Guard.NotNull(authorization, nameof(authorization));

            this.next               = next;
            this.authorization      = authorization;
            this.logger             = loggerFactory.CreateLogger(this.GetType().FullName);
            this.httpContextFactory = httpContextFactory;
            this.dataFolder         = dataFolder;
        }
Exemple #19
0
 public PollsRepository(DataFolder dataFolder, ILoggerFactory loggerFactory, DBreezeSerializer dBreezeSerializer, ChainIndexer chainIndexer, NodeSettings nodeSettings)
     : this(dataFolder.PollsPath, loggerFactory, dBreezeSerializer, chainIndexer, nodeSettings)
 {
 }
        public void StoringDepositsWhenWalletBalanceInSufficientSucceedsWithSuspendStatus()
        {
            var dataFolder = new DataFolder(CreateTestDir(this));

            this.Init(dataFolder);
            this.AddFunding();
            this.AppendBlocks(WithdrawalTransactionBuilder.MinConfirmations);

            MultiSigAddress multiSigAddress = this.wallet.MultiSigAddress;

            using (ICrossChainTransferStore crossChainTransferStore = this.CreateStore())
            {
                crossChainTransferStore.Initialize();
                crossChainTransferStore.Start();

                Assert.Equal(this.ChainIndexer.Tip.HashBlock, crossChainTransferStore.TipHashAndHeight.HashBlock);
                Assert.Equal(this.ChainIndexer.Tip.Height, crossChainTransferStore.TipHashAndHeight.Height);

                BitcoinAddress address1 = (new Key()).PubKey.Hash.GetAddress(this.network);
                BitcoinAddress address2 = (new Key()).PubKey.Hash.GetAddress(this.network);

                var deposit1 = new Deposit(0, new Money(160m, MoneyUnit.BTC), address1.ToString(), crossChainTransferStore.NextMatureDepositHeight, 1);
                var deposit2 = new Deposit(1, new Money(100m, MoneyUnit.BTC), address2.ToString(), crossChainTransferStore.NextMatureDepositHeight, 1);

                MaturedBlockDepositsModel[] blockDeposits = new[] { new MaturedBlockDepositsModel(
                                                                        new MaturedBlockInfoModel()
                    {
                        BlockHash   = 1,
                        BlockHeight = crossChainTransferStore.NextMatureDepositHeight
                    },
                                                                        new[] { deposit1, deposit2 }) };

                crossChainTransferStore.RecordLatestMatureDepositsAsync(blockDeposits).GetAwaiter().GetResult();

                ICrossChainTransfer[] transfers = crossChainTransferStore.GetAsync(new uint256[] { 0, 1 }).GetAwaiter().GetResult().ToArray();

                Transaction[] transactions = transfers.Select(t => t.PartialTransaction).ToArray();

                Assert.Equal(2, transactions.Length);

                // Transactions[0] inputs.
                Assert.Equal(2, transactions[0].Inputs.Count);
                Assert.Equal(this.fundingTransactions[0].GetHash(), transactions[0].Inputs[0].PrevOut.Hash);
                Assert.Equal((uint)0, transactions[0].Inputs[0].PrevOut.N);
                Assert.Equal(this.fundingTransactions[0].GetHash(), transactions[0].Inputs[1].PrevOut.Hash);
                Assert.Equal((uint)1, transactions[0].Inputs[1].PrevOut.N);

                // Transaction[0] outputs.
                Assert.Equal(3, transactions[0].Outputs.Count);

                // Transaction[0] output value - change.
                Assert.Equal(new Money(9.99m, MoneyUnit.BTC), transactions[0].Outputs[0].Value);
                Assert.Equal(multiSigAddress.ScriptPubKey, transactions[0].Outputs[0].ScriptPubKey);

                // Transaction[0] output value - recipient 1.
                Assert.Equal(new Money(160m, MoneyUnit.BTC), transactions[0].Outputs[1].Value);
                Assert.Equal(address1.ScriptPubKey, transactions[0].Outputs[1].ScriptPubKey);

                // Transaction[0] output value - op_return.
                Assert.Equal(new Money(0m, MoneyUnit.BTC), transactions[0].Outputs[2].Value);
                new OpReturnDataReader(this.loggerFactory, this.network).TryGetTransactionId(transactions[0], out string actualDepositId);
                Assert.Equal(deposit1.Id.ToString(), actualDepositId);

                Assert.Null(transactions[1]);

                Assert.Equal(2, transfers.Length);
                Assert.Equal(CrossChainTransferStatus.Partial, transfers[0].Status);
                Assert.Equal(deposit1.Amount, new Money(transfers[0].DepositAmount));
                Assert.Equal(address1.ScriptPubKey, transfers[0].DepositTargetAddress);
                Assert.Equal(CrossChainTransferStatus.Suspended, transfers[1].Status);

                // Add more funds and resubmit the deposits.
                AddFundingTransaction(new Money[] { Money.COIN * 1000 });
                crossChainTransferStore.RecordLatestMatureDepositsAsync(blockDeposits).GetAwaiter().GetResult();
                transfers    = crossChainTransferStore.GetAsync(new uint256[] { 0, 1 }).GetAwaiter().GetResult().ToArray();
                transactions = transfers.Select(t => t.PartialTransaction).ToArray();

                // Transactions[1] inputs.
                Assert.Equal(2, transactions[1].Inputs.Count);
                Assert.Equal(this.fundingTransactions[1].GetHash(), transactions[1].Inputs[0].PrevOut.Hash);
                Assert.Equal((uint)0, transactions[1].Inputs[0].PrevOut.N);

                // Transaction[1] outputs.
                Assert.Equal(3, transactions[1].Outputs.Count);

                // Transaction[1] output value - change.
                Assert.Equal(new Money(969.99m, MoneyUnit.BTC), transactions[1].Outputs[0].Value);
                Assert.Equal(multiSigAddress.ScriptPubKey, transactions[1].Outputs[0].ScriptPubKey);

                // Transaction[1] output value - recipient 2.
                Assert.Equal(new Money(100m, MoneyUnit.BTC), transactions[1].Outputs[1].Value);
                Assert.Equal(address2.ScriptPubKey, transactions[1].Outputs[1].ScriptPubKey);

                // Transaction[1] output value - op_return.
                Assert.Equal(new Money(0m, MoneyUnit.BTC), transactions[1].Outputs[2].Value);
                new OpReturnDataReader(this.loggerFactory, this.network).TryGetTransactionId(transactions[1], out string actualDepositId2);
                Assert.Equal(deposit2.Id.ToString(), actualDepositId2);

                Assert.Equal(2, transfers.Length);
                Assert.Equal(CrossChainTransferStatus.Partial, transfers[1].Status);
                Assert.Equal(deposit2.Amount, new Money(transfers[1].DepositAmount));
                Assert.Equal(address2.ScriptPubKey, transfers[1].DepositTargetAddress);

                (Money confirmed, Money unconfirmed)spendable = this.wallet.GetSpendableAmount();

                Assert.Equal(new Money(979.98m, MoneyUnit.BTC), spendable.unconfirmed);
            }
        }
Exemple #21
0
 public FasterCoindb(Network network, DataFolder dataFolder, IDateTimeProvider dateTimeProvider, ILoggerFactory loggerFactory, INodeStats nodeStats, DBreezeSerializer dBreezeSerializer)
     : this(network, dataFolder.CoindbPath, dateTimeProvider, loggerFactory, nodeStats, dBreezeSerializer)
 {
 }
        public void StoreMergesSignaturesAsExpected()
        {
            var dataFolder = new DataFolder(CreateTestDir(this));

            this.Init(dataFolder);
            this.AddFunding();
            this.AppendBlocks(WithdrawalTransactionBuilder.MinConfirmations);

            using (ICrossChainTransferStore crossChainTransferStore = this.CreateStore())
            {
                crossChainTransferStore.Initialize();
                crossChainTransferStore.Start();

                Assert.Equal(this.ChainIndexer.Tip.HashBlock, crossChainTransferStore.TipHashAndHeight.HashBlock);
                Assert.Equal(this.ChainIndexer.Tip.Height, crossChainTransferStore.TipHashAndHeight.Height);

                BitcoinAddress address = (new Key()).PubKey.Hash.GetAddress(this.network);

                var deposit = new Deposit(0, new Money(160m, MoneyUnit.BTC), address.ToString(), crossChainTransferStore.NextMatureDepositHeight, 1);

                MaturedBlockDepositsModel[] blockDeposits = new[] { new MaturedBlockDepositsModel(
                                                                        new MaturedBlockInfoModel()
                    {
                        BlockHash   = 1,
                        BlockHeight = crossChainTransferStore.NextMatureDepositHeight
                    },
                                                                        new[] { deposit }) };

                crossChainTransferStore.RecordLatestMatureDepositsAsync(blockDeposits).GetAwaiter().GetResult();

                ICrossChainTransfer crossChainTransfer = crossChainTransferStore.GetAsync(new[] { deposit.Id }).GetAwaiter().GetResult().SingleOrDefault();

                Assert.NotNull(crossChainTransfer);

                Transaction transaction = crossChainTransfer.PartialTransaction;

                Assert.True(crossChainTransferStore.ValidateTransaction(transaction));

                // Create a separate instance to generate another transaction.
                Transaction transaction2;
                var         newTest     = new CrossChainTransferStoreTests(this.network);
                var         dataFolder2 = new DataFolder(CreateTestDir(this));

                newTest.federationKeys = this.federationKeys;
                newTest.SetExtendedKey(1);
                newTest.Init(dataFolder2);

                // Clone chain
                for (int i = 1; i <= this.ChainIndexer.Height; i++)
                {
                    ChainedHeader header = this.ChainIndexer.GetHeader(i);
                    Block         block  = this.blockDict[header.HashBlock];
                    newTest.AppendBlock(block);
                }

                using (ICrossChainTransferStore crossChainTransferStore2 = newTest.CreateStore())
                {
                    crossChainTransferStore2.Initialize();
                    crossChainTransferStore2.Start();

                    Assert.Equal(newTest.ChainIndexer.Tip.HashBlock, crossChainTransferStore2.TipHashAndHeight.HashBlock);
                    Assert.Equal(newTest.ChainIndexer.Tip.Height, crossChainTransferStore2.TipHashAndHeight.Height);

                    crossChainTransferStore2.RecordLatestMatureDepositsAsync(blockDeposits).GetAwaiter().GetResult();

                    ICrossChainTransfer crossChainTransfer2 = crossChainTransferStore2.GetAsync(new[] { deposit.Id }).GetAwaiter().GetResult().SingleOrDefault();

                    Assert.NotNull(crossChainTransfer2);

                    transaction2 = crossChainTransfer2.PartialTransaction;

                    Assert.True(crossChainTransferStore2.ValidateTransaction(transaction2));
                }

                // Merges the transaction signatures.
                crossChainTransferStore.MergeTransactionSignaturesAsync(deposit.Id, new[] { transaction2 }).GetAwaiter().GetResult();

                // Test the outcome.
                crossChainTransfer = crossChainTransferStore.GetAsync(new[] { deposit.Id }).GetAwaiter().GetResult().SingleOrDefault();

                Assert.NotNull(crossChainTransfer);
                Assert.Equal(CrossChainTransferStatus.FullySigned, crossChainTransfer.Status);

                // Should be returned as signed.
                Transaction signedTransaction = crossChainTransferStore.GetTransactionsByStatusAsync(CrossChainTransferStatus.FullySigned).GetAwaiter().GetResult().Values.SingleOrDefault();

                Assert.NotNull(signedTransaction);

                // Check ths signature.
                Assert.True(crossChainTransferStore.ValidateTransaction(signedTransaction, true));
            }
        }
        public async Task WhenDnsServerListening_AndDnsRequestReceived_ThenDnsServerSuccessfullyProcessesRequest_Async()
        {
            // Arrange.
            bool startedListening       = false;
            bool sentResponse           = false;
            Mock <IUdpClient> udpClient = new Mock <IUdpClient>();

            udpClient.Setup(c => c.StartListening(It.IsAny <int>())).Callback(() => startedListening = true);
            udpClient.Setup(c => c.ReceiveAsync()).ReturnsAsync(new Tuple <IPEndPoint, byte[]>(new IPEndPoint(IPAddress.Loopback, 80), this.GetDnsRequest()));
            udpClient.Setup(c => c.SendAsync(It.IsAny <byte[]>(), It.IsAny <int>(), It.IsAny <IPEndPoint>())).Callback <byte[], int, IPEndPoint>((p, s, ip) => sentResponse = true).ReturnsAsync(1);

            Mock <IMasterFile> masterFile = new Mock <IMasterFile>();

            masterFile.Setup(m => m.Get(It.IsAny <Question>())).Returns(new List <IResourceRecord>()
            {
                new IPAddressResourceRecord(Domain.FromString("google.com"), IPAddress.Loopback)
            });

            IAsyncLoopFactory asyncLoopFactory = new Mock <IAsyncLoopFactory>().Object;
            INodeLifetime     nodeLifetime     = new Mock <INodeLifetime>().Object;
            DnsSettings       dnsSettings      = new Mock <DnsSettings>().Object;

            dnsSettings.DnsHostName   = "host.example.com";
            dnsSettings.DnsNameServer = "ns1.host.example.com";
            dnsSettings.DnsMailBox    = "*****@*****.**";
            DataFolder dataFolder = CreateDataFolder(this);

            Mock <ILogger> logger          = new Mock <ILogger>();
            bool           receivedRequest = false;

            logger.Setup(l => l.Log(LogLevel.Trace, It.IsAny <EventId>(), It.IsAny <FormattedLogValues>(), It.IsAny <Exception>(), It.IsAny <Func <object, Exception, string> >())).Callback <LogLevel, EventId, object, Exception, Func <object, Exception, string> >((level, id, state, e, f) =>
            {
                // Don't reset if we found the trace message we were looking for
                if (!receivedRequest)
                {
                    // Not yet set, check trace message
                    receivedRequest = state.ToString().StartsWith("DNS request received");
                }
            });
            Mock <ILoggerFactory> loggerFactory = new Mock <ILoggerFactory>();

            loggerFactory.Setup <ILogger>(f => f.CreateLogger(It.IsAny <string>())).Returns(logger.Object);

            IDateTimeProvider dateTimeProvider = new Mock <IDateTimeProvider>().Object;

            // Act.
            CancellationTokenSource source = new CancellationTokenSource(2000);
            DnsSeedServer           server = new DnsSeedServer(udpClient.Object, masterFile.Object, asyncLoopFactory, nodeLifetime, loggerFactory.Object, dateTimeProvider, dnsSettings, dataFolder);

            try
            {
                await server.ListenAsync(53, source.Token);
            }
            catch (OperationCanceledException)
            {
                // Expected
            }

            // Assert.
            server.Should().NotBeNull();
            startedListening.Should().BeTrue();
            receivedRequest.Should().BeTrue();
            sentResponse.Should().BeTrue();
            server.Metrics.DnsRequestCountSinceStart.Should().BeGreaterThan(0);
            server.Metrics.DnsRequestFailureCountSinceStart.Should().Be(0);
            server.Metrics.DnsServerFailureCountSinceStart.Should().Be(0);
            server.Metrics.CurrentSnapshot.DnsRequestCountSinceLastPeriod.Should().BeGreaterThan(0);
            server.Metrics.CurrentSnapshot.DnsRequestFailureCountSinceLastPeriod.Should().Be(0);
            server.Metrics.CurrentSnapshot.DnsServerFailureCountSinceLastPeriod.Should().Be(0);
            server.Metrics.CurrentSnapshot.DnsRequestElapsedTicksSinceLastPeriod.Should().BeGreaterThan(0);
            server.Metrics.CurrentSnapshot.LastDnsRequestElapsedTicks.Should().BeGreaterThan(0);
        }
        public void StoredPartialTransactionsTriggerSignatureRequest()
        {
            var dataFolder = new DataFolder(CreateTestDir(this));

            this.Init(dataFolder);
            this.AddFunding();
            this.AppendBlocks(WithdrawalTransactionBuilder.MinConfirmations);

            MultiSigAddress multiSigAddress = this.wallet.MultiSigAddress;

            using (ICrossChainTransferStore crossChainTransferStore = this.CreateStore())
            {
                crossChainTransferStore.Initialize();
                crossChainTransferStore.Start();

                Assert.Equal(this.ChainIndexer.Tip.HashBlock, crossChainTransferStore.TipHashAndHeight.HashBlock);
                Assert.Equal(this.ChainIndexer.Tip.Height, crossChainTransferStore.TipHashAndHeight.Height);

                BitcoinAddress address1 = (new Key()).PubKey.Hash.GetAddress(this.network);
                BitcoinAddress address2 = (new Key()).PubKey.Hash.GetAddress(this.network);

                var deposit1 = new Deposit(0, new Money(160m, MoneyUnit.BTC), address1.ToString(), crossChainTransferStore.NextMatureDepositHeight, 1);
                var deposit2 = new Deposit(1, new Money(60m, MoneyUnit.BTC), address2.ToString(), crossChainTransferStore.NextMatureDepositHeight, 1);

                MaturedBlockDepositsModel[] blockDeposits = new[] { new MaturedBlockDepositsModel(
                                                                        new MaturedBlockInfoModel()
                    {
                        BlockHash   = 1,
                        BlockHeight = crossChainTransferStore.NextMatureDepositHeight
                    },
                                                                        new[] { deposit1, deposit2 }) };

                crossChainTransferStore.RecordLatestMatureDepositsAsync(blockDeposits).GetAwaiter().GetResult();

                Dictionary <uint256, Transaction> transactions = crossChainTransferStore.GetTransactionsByStatusAsync(
                    CrossChainTransferStatus.Partial).GetAwaiter().GetResult();

                var requester = new PartialTransactionRequester(this.loggerFactory, crossChainTransferStore, this.asyncLoopFactory,
                                                                this.nodeLifetime, this.connectionManager, this.federationGatewaySettings);

                var peerEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("1.2.3.4"), 5);
                var peer         = Substitute.For <INetworkPeer>();
                peer.RemoteSocketAddress.Returns(peerEndPoint.Address);
                peer.RemoteSocketPort.Returns(peerEndPoint.Port);
                peer.PeerEndPoint.Returns(peerEndPoint);
                peer.IsConnected.Returns(true);

                var peers = new NetworkPeerCollection();
                peers.Add(peer);

                this.federationGatewaySettings.FederationNodeIpEndPoints.Returns(new[] { peerEndPoint });

                this.connectionManager.ConnectedPeers.Returns(peers);

                requester.Start();

                Thread.Sleep(100);

                peer.Received().SendMessageAsync(Arg.Is <RequestPartialTransactionPayload>(o =>
                                                                                           o.DepositId == 0 && o.PartialTransaction.GetHash() == transactions[0].GetHash())).GetAwaiter().GetResult();

                peer.DidNotReceive().SendMessageAsync(Arg.Is <RequestPartialTransactionPayload>(o =>
                                                                                                o.DepositId == 1 && o.PartialTransaction.GetHash() == transactions[1].GetHash())).GetAwaiter().GetResult();
            }
        }
 /// <summary>
 /// Initializes a new instance of the object.
 /// </summary>
 /// <param name="network">Specification of the network the node runs on - regtest/testnet/mainnet.</param>
 /// <param name="dataFolder">Information about path locations to important folders and files on disk.</param>
 /// <param name="loggerFactory">Factory to be used to create logger for the puller.</param>
 public DBreezeCoinView(Network network, DataFolder dataFolder, ILoggerFactory loggerFactory)
     : this(network, dataFolder.CoinViewPath, loggerFactory)
 {
 }
Exemple #26
0
        /// <summary>
        /// Extends the logging rules in the "NLog.config" with xServer log settings rules.
        /// </summary>
        /// <param name="settings">xServer log settings to extend the rules from the configuration file, or null if no extension is required.</param>
        /// <param name="dataFolder">Data folder to determine path to log files.</param>
        private static void AddFilters(LogSettings settings = null, DataFolder dataFolder = null)
        {
            if (settings == null)
            {
                return;
            }

            logSettings = settings;
            folder      = dataFolder;

            // If we use "debug*" targets, which are defined in "NLog.config", make sure they log into the correct log folder in data directory.
            List <Target> debugTargets = LogManager.Configuration.AllTargets.Where(t => (t.Name != null) && t.Name.StartsWith("debug")).ToList();

            foreach (Target debugTarget in debugTargets)
            {
                FileTarget debugFileTarget = debugTarget is AsyncTargetWrapper ? (FileTarget)((debugTarget as AsyncTargetWrapper).WrappedTarget) : (FileTarget)debugTarget;
                string     currentFile     = debugFileTarget.FileName.Render(new LogEventInfo {
                    TimeStamp = DateTime.UtcNow
                });
                debugFileTarget.FileName = Path.Combine(folder.LogPath, Path.GetFileName(currentFile));

                if (debugFileTarget.ArchiveFileName != null)
                {
                    string currentArchive = debugFileTarget.ArchiveFileName.Render(new LogEventInfo {
                        TimeStamp = DateTime.UtcNow
                    });
                    debugFileTarget.ArchiveFileName = Path.Combine(folder.LogPath, currentArchive);
                }
            }

            // Remove rule that forbids logging before the logging is initialized.
            LoggingRule nullPreInitRule = null;

            foreach (LoggingRule rule in LogManager.Configuration.LoggingRules)
            {
                if (rule.Final && rule.NameMatches("*") && (rule.Targets.Count > 0) && (rule.Targets[0].Name == "null"))
                {
                    nullPreInitRule = rule;
                    break;
                }
            }

            LogManager.Configuration.LoggingRules.Remove(nullPreInitRule);

            // Configure main file target, configured using command line or node configuration file settings.
            var mainTarget = new FileTarget
            {
                Name             = "main",
                FileName         = Path.Combine(folder.LogPath, "xserver.txt"),
                ArchiveFileName  = Path.Combine(folder.LogPath, "xserver-${date:universalTime=true:format=yyyy-MM-dd}.txt"),
                ArchiveNumbering = ArchiveNumberingMode.Sequence,
                ArchiveEvery     = FileArchivePeriod.Day,
                MaxArchiveFiles  = 7,
                Layout           = "[${longdate:universalTime=true} ${threadid}${mdlc:item=id}] ${level:uppercase=true}: ${callsite} ${message}",
                Encoding         = Encoding.UTF8
            };

            LogManager.Configuration.AddTarget(mainTarget);

            // Default logging level is Info for all components.
            var defaultRule = new LoggingRule($"{nameof(x42)}.*", settings.LogLevel, mainTarget);

            if (settings.DebugArgs.Any() && settings.DebugArgs[0] != "1")
            {
                lock (KeyCategories)
                {
                    var usedCategories = new HashSet <string>(StringComparer.Ordinal);

                    // Increase selected categories to Debug.
                    foreach (string key in settings.DebugArgs)
                    {
                        if (!KeyCategories.TryGetValue(key.Trim(), out string category))
                        {
                            // Allow direct specification - e.g. "-debug=x42.Server.
                            category = key.Trim();
                        }

                        if (!usedCategories.Contains(category))
                        {
                            usedCategories.Add(category);
                            var rule = new LoggingRule(category, settings.LogLevel, mainTarget);
                            LogManager.Configuration.LoggingRules.Add(rule);
                        }
                    }
                }
            }

            LogManager.Configuration.LoggingRules.Add(defaultRule);

            // Apply new rules.
            LogManager.ReconfigExistingLoggers();
        }
        public void FundTransaction_Given__a_wallet_has_enough_inputs__When__adding_inputs_to_an_existing_transaction__Then__the_transaction_is_funded_successfully()
        {
            DataFolder dataFolder = CreateDataFolder(this);

            Wallet wallet = WalletTestsHelpers.GenerateBlankWallet("myWallet1", "password");

            (ExtKey ExtKey, string ExtPubKey)accountKeys = WalletTestsHelpers.GenerateAccountKeys(wallet, "password", "m/44'/0'/0'");
            (PubKey PubKey, BitcoinPubKeyAddress Address)spendingKeys     = WalletTestsHelpers.GenerateAddressKeys(wallet, accountKeys.ExtPubKey, "0/0");
            (PubKey PubKey, BitcoinPubKeyAddress Address)destinationKeys1 = WalletTestsHelpers.GenerateAddressKeys(wallet, accountKeys.ExtPubKey, "0/1");
            (PubKey PubKey, BitcoinPubKeyAddress Address)destinationKeys2 = WalletTestsHelpers.GenerateAddressKeys(wallet, accountKeys.ExtPubKey, "0/2");
            (PubKey PubKey, BitcoinPubKeyAddress Address)destinationKeys3 = WalletTestsHelpers.GenerateAddressKeys(wallet, accountKeys.ExtPubKey, "0/3");

            var address = new HdAddress
            {
                Index        = 0,
                HdPath       = $"m/44'/0'/0'/0/0",
                Address      = spendingKeys.Address.ToString(),
                Pubkey       = spendingKeys.PubKey.ScriptPubKey,
                ScriptPubKey = spendingKeys.Address.ScriptPubKey,
                Transactions = new List <TransactionData>()
            };

            // wallet with 4 coinbase outputs of 50 = 200 Bitcoin
            var chain = new ConcurrentChain(wallet.Network);

            WalletTestsHelpers.AddBlocksWithCoinbaseToChain(wallet.Network, chain, address, 4);

            wallet.AccountsRoot.ElementAt(0).Accounts.Add(new HdAccount
            {
                Index             = 0,
                Name              = "account1",
                HdPath            = "m/44'/0'/0'",
                ExtendedPubKey    = accountKeys.ExtPubKey,
                ExternalAddresses = new List <HdAddress> {
                    address
                },
                InternalAddresses = new List <HdAddress>()
            });

            var walletFeePolicy = new Mock <IWalletFeePolicy>();

            walletFeePolicy.Setup(w => w.GetFeeRate(FeeType.Low.ToConfirmations())).Returns(new FeeRate(20000));
            var overrideFeeRate = new FeeRate(20000);

            var walletManager = new WalletManager(this.LoggerFactory.Object, Network.Main, chain, NodeSettings.Default(), new Mock <WalletSettings>().Object,
                                                  dataFolder, walletFeePolicy.Object, new Mock <IAsyncLoopFactory>().Object, new NodeLifetime(), DateTimeProvider.Default);
            var walletTransactionHandler = new WalletTransactionHandler(this.LoggerFactory.Object, walletManager, walletFeePolicy.Object, Network.Main);

            walletManager.Wallets.Add(wallet);

            var walletReference = new WalletAccountReference
            {
                AccountName = "account1",
                WalletName  = "myWallet1"
            };

            // create a trx with 3 outputs 50 + 50 + 49 = 149 BTC
            var context = new TransactionBuildContext(walletReference,
                                                      new[]
            {
                new Recipient {
                    Amount = new Money(50, MoneyUnit.BTC), ScriptPubKey = destinationKeys1.PubKey.ScriptPubKey
                },
                new Recipient {
                    Amount = new Money(50, MoneyUnit.BTC), ScriptPubKey = destinationKeys2.PubKey.ScriptPubKey
                },
                new Recipient {
                    Amount = new Money(49, MoneyUnit.BTC), ScriptPubKey = destinationKeys3.PubKey.ScriptPubKey
                }
            }
                                                      .ToList(), "password")
            {
                MinConfirmations = 0,
                FeeType          = FeeType.Low
            };

            Transaction fundTransaction = walletTransactionHandler.BuildTransaction(context);

            Assert.Equal(4, fundTransaction.Inputs.Count);  // 4 inputs
            Assert.Equal(4, fundTransaction.Outputs.Count); // 3 outputs with change

            // remove the change output
            fundTransaction.Outputs.Remove(fundTransaction.Outputs.First(f => f.ScriptPubKey == context.ChangeAddress.ScriptPubKey));
            // remove 3 inputs they will be added back by fund transaction
            fundTransaction.Inputs.RemoveAt(3);
            fundTransaction.Inputs.RemoveAt(2);
            fundTransaction.Inputs.RemoveAt(1);
            Assert.Single(fundTransaction.Inputs); // 4 inputs

            Transaction fundTransactionClone = fundTransaction.Clone();
            var         fundContext          = new TransactionBuildContext(walletReference, new List <Recipient>(), "password")
            {
                MinConfirmations = 0,
                FeeType          = FeeType.Low
            };

            fundContext.OverrideFeeRate = overrideFeeRate;
            walletTransactionHandler.FundTransaction(fundContext, fundTransaction);

            foreach (TxIn input in fundTransactionClone.Inputs) // all original inputs are still in the trx
            {
                Assert.Contains(fundTransaction.Inputs, a => a.PrevOut == input.PrevOut);
            }

            Assert.Equal(4, fundTransaction.Inputs.Count);  // we expect 4 inputs
            Assert.Equal(4, fundTransaction.Outputs.Count); // we expect 4 outputs
            Assert.Equal(new Money(200, MoneyUnit.BTC) - fundContext.TransactionFee, fundTransaction.TotalOut);

            Assert.Contains(fundTransaction.Outputs, a => a.ScriptPubKey == destinationKeys1.PubKey.ScriptPubKey);
            Assert.Contains(fundTransaction.Outputs, a => a.ScriptPubKey == destinationKeys2.PubKey.ScriptPubKey);
            Assert.Contains(fundTransaction.Outputs, a => a.ScriptPubKey == destinationKeys3.PubKey.ScriptPubKey);
        }
Exemple #28
0
 /// <summary>
 /// Extends the logging rules in the "NLog.config" with xServer log settings rules.
 /// </summary>
 /// <param name="loggerFactory">Not used.</param>
 /// <param name="settings">xServer log settings to extend the rules from the configuration file, or null if no extension is required.</param>
 /// <param name="dataFolder">Data folder to determine path to log files.</param>
 public static void AddFilters(this ILoggerFactory loggerFactory, LogSettings settings, DataFolder dataFolder)
 {
     AddFilters(settings, dataFolder);
 }
 private static void Save2_MouseClicked(Button button)
 {
     ActiveSave           = 2;
     StoryTracker.Profile = DataFolder.GetPlayerProfile(ActiveSave);
     StoryTracker.ResumeFromSavePoint();
 }
        private WalletTransactionHandlerTestContext SetupWallet()
        {
            DataFolder dataFolder = CreateDataFolder(this);

            Wallet wallet = WalletTestsHelpers.GenerateBlankWallet("myWallet1", "password");

            (ExtKey ExtKey, string ExtPubKey)accountKeys = WalletTestsHelpers.GenerateAccountKeys(wallet, "password", "m/44'/0'/0'");
            (PubKey PubKey, BitcoinPubKeyAddress Address)spendingKeys    = WalletTestsHelpers.GenerateAddressKeys(wallet, accountKeys.ExtPubKey, "0/0");
            (PubKey PubKey, BitcoinPubKeyAddress Address)destinationKeys = WalletTestsHelpers.GenerateAddressKeys(wallet, accountKeys.ExtPubKey, "0/1");

            var address = new HdAddress
            {
                Index        = 0,
                HdPath       = $"m/44'/0'/0'/0/0",
                Address      = spendingKeys.Address.ToString(),
                Pubkey       = spendingKeys.PubKey.ScriptPubKey,
                ScriptPubKey = spendingKeys.Address.ScriptPubKey,
                Transactions = new List <TransactionData>()
            };

            var chain = new ChainIndexer(wallet.Network);

            WalletTestsHelpers.AddBlocksWithCoinbaseToChain(wallet.Network, chain, address);
            TransactionData addressTransaction = address.Transactions.First();

            wallet.AccountsRoot.ElementAt(0).Accounts.Add(new HdAccount
            {
                Index             = 0,
                Name              = "account1",
                HdPath            = "m/44'/0'/0'",
                ExtendedPubKey    = accountKeys.ExtPubKey,
                ExternalAddresses = new List <HdAddress> {
                    address
                },
                InternalAddresses = new List <HdAddress>()
            });

            var walletFeePolicy = new Mock <IWalletFeePolicy>();

            walletFeePolicy.Setup(w => w.GetFeeRate(FeeType.Low.ToConfirmations()))
            .Returns(new FeeRate(20000));

            var walletManager = new WalletManager(this.LoggerFactory.Object, this.Network, chain,
                                                  new WalletSettings(NodeSettings.Default(this.Network)), dataFolder,
                                                  walletFeePolicy.Object, new Mock <IAsyncProvider>().Object, new NodeLifetime(), DateTimeProvider.Default, this.scriptAddressReader);
            var walletTransactionHandler =
                new WalletTransactionHandler(this.LoggerFactory.Object, walletManager, walletFeePolicy.Object, this.Network, this.standardTransactionPolicy);

            walletManager.Wallets.Add(wallet);

            var walletReference = new WalletAccountReference
            {
                AccountName = "account1",
                WalletName  = "myWallet1"
            };

            return(new WalletTransactionHandlerTestContext
            {
                Wallet = wallet,
                AccountKeys = accountKeys,
                DestinationKeys = destinationKeys,
                AddressTransaction = addressTransaction,
                WalletTransactionHandler = walletTransactionHandler,
                WalletReference = walletReference
            });
        }