public void StoreTest()
 {
     ConfigStore store = CreateConfigStore();
     AddressManager mgr = new AddressManager(store); 
     ConfigStore actual = mgr.Store;
     Assert.Equal(mgr.Store, actual);
 }
Example #2
0
		public ContactInfoService(IOrderManager orderManager, IReferenceManagement referenceManagement)
		{
			if (orderManager == null) throw new ArgumentNullException("orderManager");

			_orderManager = orderManager;
			_addressManager = new AddressManager(referenceManagement);
		}
Example #3
0
		public DVSUserManagementService(IUsersManagement userManager, IReferenceManagement referenceManager, IDVSUserManager dvsUserManager)
		{
			_userManager = userManager;
			_referenceManager = referenceManager;
			_dvsUserManager = dvsUserManager;
			_addressManager = new AddressManager(referenceManager);
		}
Example #4
0
        public ConfigStore(string connectString, TimeSpan timeout)
        {
            if (string.IsNullOrEmpty(connectString))
            {
                throw new ArgumentException("connectString");
            }
            if (timeout.Ticks <= 0)
            {
                throw new ArgumentException("timeout");
            }

            m_timeout = timeout;
            m_connectString = connectString;
            m_domains = new DomainManager(this);
            m_addresses = new AddressManager(this);
            m_certificates = new CertificateManager(this);
            m_anchors = new AnchorManager(this);
            m_dnsRecords = new DnsRecordManager(this);
            m_administrators = new AdministratorManager(this);
            m_properties = new PropertyManager(this);
            m_blobs = new NamedBlobManager(this);
            m_Mdns = new MdnManager(this);
            m_bundles = new BundleManager(this);
            m_certPolicies = new CertPolicyManager(this, new CertPolicyParseValidator());
            m_certPolicyGroups = new CertPolicyGroupManager(this);
        }
		public static void SetAddrman(NodeBehaviorsCollection behaviors, AddressManager addrman)
		{
			if (behaviors == null) throw new ArgumentNullException("behaviors");
			var behavior = behaviors.Find<AddressManagerBehavior>();
			if(behavior == null) 
			{
				// FIXME: Please take a look at this
				behavior = new AddressManagerBehavior(addrman);
				behaviors.Add(behavior);
			}
			behavior.AddressManager = addrman;
		}
Example #6
0
		public AppraisalCompanyService(IAppraisalCompanyManagement appraisalCompanyManagement,
			IAppraiserManagement appraisalCompanyAdminManagement,
			IFeeManager feeManager,
			StatusHistoryManager statusHistoryManager,
			IReferenceManagement referenceManagement,
			ICryptographicProvider cryptographicProvider,
			IGeocodingDataService geocodingService)
		{
			_appraisalCompanyManagement = appraisalCompanyManagement;
			_appraisalCompanyAdminManagement = appraisalCompanyAdminManagement;
			_feeManager = feeManager;
			_referenceManagement = referenceManagement;
			_cryptographicProvider = cryptographicProvider;
			_addressManager = new AddressManager(referenceManagement);
			_phoneManager = new PhoneManager();
			_statusHistoryManager = statusHistoryManager;
			_geocodingDataService = geocodingService;
		}
Example #7
0
		public OrderManager(IOrderRepository orderRepository,
												IClientUserRepository clientUserRepository,
												IReferenceManagement referenceManagement,
												IAppraiserManagement appraiserManagement,
												IConfigurationHelper configurationHelper,
												IAppraiserOrderRepository appraiserOrderRepository,
												IChangeTrackingRepository changeTrackingRepository,
												IOrderHistoryManager orderHistoryManager,
												IOrderDocumentsRepository orderDocumentsRepository
)
		{
			_orderRepository = ValidationUtil.CheckOnNullAndThrowIfNull(orderRepository);
			_clientUserRepository = ValidationUtil.CheckOnNullAndThrowIfNull(clientUserRepository);
			_referenceManagement = ValidationUtil.CheckOnNullAndThrowIfNull(referenceManagement);
			_appraiserManagement = ValidationUtil.CheckOnNullAndThrowIfNull(appraiserManagement);
			_configurationHelper = ValidationUtil.CheckOnNullAndThrowIfNull(configurationHelper);
			_appraiserOrderRepository = ValidationUtil.CheckOnNullAndThrowIfNull(appraiserOrderRepository);
			_addressManager = new AddressManager(_referenceManagement);
			_changeTrackingRepository = ValidationUtil.CheckOnNullAndThrowIfNull(changeTrackingRepository);
			_orderHistoryManager = ValidationUtil.CheckOnNullAndThrowIfNull(orderHistoryManager);
			_orderDocumentsRepository = ValidationUtil.CheckOnNullAndThrowIfNull(orderDocumentsRepository);
		}
Example #8
0
		public OrderService(IOrderRepository orderRepository,
			IReferenceManagement referenceManagement,
			IGeocodingDataService geocodingDataService, ITaskManager taskManager, IOrderManager orderManager,
			IAppraisalFormsService appFormsService, IClientDashboardService dashboarService, IConfigurationHelper configurationHelper,
			ICryptographicProvider cryptographicProvider, IDocumentService documentService, IReportManager reportManager, ISecurityContext securityContext,
			IOrderDocumentsRepository orderDocumentsRepository)
		{
			_orderRepository = ValidationUtil.CheckOnNullAndThrowIfNull(orderRepository);
			_referenceManager = ValidationUtil.CheckOnNullAndThrowIfNull(referenceManagement);
			_geocodingDataService = ValidationUtil.CheckOnNullAndThrowIfNull(geocodingDataService);
			_taskManager = ValidationUtil.CheckOnNullAndThrowIfNull(taskManager);
			_orderManager = ValidationUtil.CheckOnNullAndThrowIfNull(orderManager);
			_appFormsService = ValidationUtil.CheckOnNullAndThrowIfNull(appFormsService);
			_dashboarService = ValidationUtil.CheckOnNullAndThrowIfNull(dashboarService);
			_configurationHelper = ValidationUtil.CheckOnNullAndThrowIfNull(configurationHelper);
			_cryptographicProvider = ValidationUtil.CheckOnNullAndThrowIfNull(cryptographicProvider);
			_documentService = ValidationUtil.CheckOnNullAndThrowIfNull(documentService);
			_reportManager = ValidationUtil.CheckOnNullAndThrowIfNull(reportManager);
			_securityContext = ValidationUtil.CheckOnNullAndThrowIfNull(securityContext);
			_orderDocumentsRepository = ValidationUtil.CheckOnNullAndThrowIfNull(orderDocumentsRepository);

			_addressManager = new AddressManager(_referenceManager);
			_dateTimeManager = new DateTimeManager(_referenceManager);
		}
Example #9
0
        public void CanDiscoverPeers()
        {
            int SERVER_COUNT = 4;

            int FIRST_SERVER  = 0;
            int SECOND_SERVER = 1;
            int LAST_SERVER   = 2;
            int NEW_SERVER    = 3;

            var ToBeConnected  = new List <NodeServer>();
            var ToBeDiscovered = new List <Node>();

            WithServerSet(SERVER_COUNT, servers =>
            {
                servers.SeedServerIndex = LAST_SERVER;                 //TODO

                ToBeConnected.Add(servers[FIRST_SERVER]);
                ToBeConnected.Add(servers[SECOND_SERVER]);
                ToBeConnected.Add(servers[LAST_SERVER]);

                ToBeDiscovered.Add(Handshake(servers[FIRST_SERVER], servers[SECOND_SERVER]));
                Trace.Information("Handshake First -> Second");

                ToBeDiscovered.Add(Handshake(servers[SECOND_SERVER], servers[LAST_SERVER]));
                Trace.Information("Handshake Second -> Last");

                #region Setup Parameters for NodeGroup

                AddressManager addressManager = new AddressManager();
                addressManager.PeersToFind    = ToBeConnected.Count * 2;              // nodes answer to GetAddr with random nodes, so keep trying until we get all expected items

                NodeConnectionParameters parameters = new NodeConnectionParameters();
                parameters.TemplateBehaviors.Add(new AddressManagerBehavior(addressManager));

                parameters.AddressFrom = servers[NEW_SERVER].ExternalEndpoint;                 //TODO

                NodesGroup nodesGroup            = new NodesGroup(servers.Network, parameters);
                nodesGroup.AllowSameGroup        = true;                //TODO
                nodesGroup.MaximumNodeConnection = ToBeConnected.Count; //TODO

                #endregion

                nodesGroup.Connect();

                AutoResetEvent waitForDiscoveredAll = new AutoResetEvent(false);
                var discoveredAll = false;

                nodesGroup.ConnectedNodes.Added += (object sender, NodeEventArgs e) =>
                {
                    Console.WriteLine($"\n\n\nPeer found: {e.Node.Peer.Endpoint}\n\n\n");

                    Node node = ToBeDiscovered.Find(n => n.MyVersion.AddressFrom.Equals(e.Node.Peer.Endpoint));

                    if (node != null && ToBeDiscovered.Contains(node))
                    {
                        ToBeDiscovered.Remove(node);

                        if (ToBeDiscovered.Count == 0)
                        {
                            discoveredAll = true;
                            waitForDiscoveredAll.Set();
                        }
                    }
                };

                Assert.True(waitForDiscoveredAll.WaitOne(30000));
                Assert.True(discoveredAll);
            });
        }
Example #10
0
        private void BroadcastTransaction(Action <BroadcastHub> actionSender, Action actionReceiver)
        {
            WithServerSet(2, servers =>
            {
                WithBlockChains(2, null, blockChains =>
                {
                    AutoResetEvent waitForConnection = new AutoResetEvent(false);
                    bool connected = false;

                    servers.SeedServerIndex = 0;

                    AddressManager serverAddressManager = new AddressManager();
                    serverAddressManager.Add(
                        new NetworkAddress(servers[0].ExternalEndpoint),
                        servers[0].ExternalEndpoint.Address
                        );
                    serverAddressManager.Connected(new NetworkAddress(servers[0].ExternalEndpoint));

                    NodeConnectionParameters serverParameters = new NodeConnectionParameters();
                    serverParameters.TemplateBehaviors.Add(new AddressManagerBehavior(serverAddressManager));
                    serverParameters.TemplateBehaviors.Add(new BroadcastHubBehavior());
                    serverParameters.TemplateBehaviors.Add(new SPVBehavior(blockChains[0], BroadcastHub.GetBroadcastHub(serverParameters.TemplateBehaviors)));

                    blockChains[0].OnAddedToMempool += transaction => {
                        Trace.Information("-- Transaction Received (node server)");
                        actionReceiver();
                    };

                    servers[0].InboundNodeConnectionParameters = serverParameters;

                    #region NodeGroup

                    AddressManager addressManager = new AddressManager();
                    addressManager.PeersToFind    = 1;
                    NodeConnectionParameters nodesGroupParameters = new NodeConnectionParameters();
                    nodesGroupParameters.AddressFrom = servers[1].ExternalEndpoint;
                    nodesGroupParameters.TemplateBehaviors.Add(new AddressManagerBehavior(addressManager));
                    nodesGroupParameters.TemplateBehaviors.Add(new BroadcastHubBehavior());
                    nodesGroupParameters.TemplateBehaviors.Add(new SPVBehavior(blockChains[1], BroadcastHub.GetBroadcastHub(nodesGroupParameters.TemplateBehaviors)));

                    blockChains[1].OnAddedToMempool += transaction =>
                    {
                        Trace.Information("-- Transaction Received (node group)");
                    };

                    NodesGroup nodesGroup            = new NodesGroup(servers.Network, nodesGroupParameters);
                    nodesGroup.AllowSameGroup        = true;
                    nodesGroup.MaximumNodeConnection = 1;
                    nodesGroup.ConnectedNodes.Added += (object sender, NodeEventArgs e) =>
                    {
                        Trace.Information("-- Node added to node group");
                        connected = true;
                        waitForConnection.Set();
                    };
                    nodesGroup.Connect();

                    #endregion

                    Assert.True(waitForConnection.WaitOne(10000));                     //TODO: use reset events instead of sleep
                    Assert.True(connected);

                    actionSender(BroadcastHub.GetBroadcastHub(nodesGroup.NodeConnectionParameters));

                    Trace.Information("-- Done");
                });
            });
        }
        public async Task TestServicesAsync(string networkString)
        {
            await RuntimeParams.LoadAsync();

            var network          = Network.GetNetwork(networkString);
            var blocksToDownload = new List <uint256>();

            if (network == Network.Main)
            {
                blocksToDownload.Add(new uint256("00000000000000000037c2de35bd85f3e57f14ddd741ce6cee5b28e51473d5d0"));
                blocksToDownload.Add(new uint256("000000000000000000115315a43cb0cdfc4ea54a0e92bed127f4e395e718d8f9"));
                blocksToDownload.Add(new uint256("00000000000000000011b5b042ad0522b69aae36f7de796f563c895714bbd629"));
            }
            else if (network == Network.TestNet)
            {
                blocksToDownload.Add(new uint256("0000000097a664c4084b49faa6fd4417055cb8e5aac480abc31ddc57a8208524"));
                blocksToDownload.Add(new uint256("000000009ed5b82259ecd2aa4cd1f119db8da7a70e7ea78d9c9f603e01f93bcc"));
                blocksToDownload.Add(new uint256("00000000e6da8c2da304e9f5ad99c079df2c3803b49efded3061ecaf206ddc66"));
            }
            else
            {
                throw new NotSupportedNetworkException(network);
            }
            var dataDir = Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.GetCallerFileName());

            BitcoinStore bitcoinStore = new BitcoinStore();
            await bitcoinStore.InitializeAsync(Path.Combine(dataDir, EnvironmentHelpers.GetMethodName()), network);

            var            addressManagerFolderPath = Path.Combine(dataDir, "AddressManager");
            var            addressManagerFilePath   = Path.Combine(addressManagerFolderPath, $"AddressManager{network}.dat");
            var            blocksFolderPath         = Path.Combine(dataDir, "Blocks", network.ToString());
            var            connectionParameters     = new NodeConnectionParameters();
            AddressManager addressManager           = null;

            try
            {
                addressManager = await NBitcoinHelpers.LoadAddressManagerFromPeerFileAsync(addressManagerFilePath);

                Logger.LogInfo($"Loaded {nameof(AddressManager)} from `{addressManagerFilePath}`.");
            }
            catch (DirectoryNotFoundException)
            {
                addressManager = new AddressManager();
            }
            catch (FileNotFoundException)
            {
                addressManager = new AddressManager();
            }
            catch (OverflowException)
            {
                File.Delete(addressManagerFilePath);
                addressManager = new AddressManager();
            }
            catch (FormatException)
            {
                File.Delete(addressManagerFilePath);
                addressManager = new AddressManager();
            }

            connectionParameters.TemplateBehaviors.Add(new AddressManagerBehavior(addressManager));
            connectionParameters.TemplateBehaviors.Add(bitcoinStore.CreateUntrustedP2pBehavior());

            using var nodes = new NodesGroup(network, connectionParameters, requirements: Constants.NodeRequirements);

            KeyManager           keyManager    = KeyManager.CreateNew(out _, "password");
            WasabiSynchronizer   syncer        = new WasabiSynchronizer(network, bitcoinStore, new Uri("http://localhost:12345"), Global.Instance.TorSocks5Endpoint);
            ServiceConfiguration serviceConfig = new ServiceConfiguration(50, 2, 21, 50, new IPEndPoint(IPAddress.Loopback, network.DefaultPort), Money.Coins(Constants.DefaultDustThreshold));
            CachedBlockProvider  blockProvider = new CachedBlockProvider(
                new P2pBlockProvider(nodes, null, syncer, serviceConfig, network),
                new FileSystemBlockRepository(blocksFolderPath, network));

            using Wallet wallet = Wallet.CreateAndRegisterServices(
                      network,
                      bitcoinStore,
                      keyManager,
                      syncer,
                      nodes,
                      dataDir,
                      new ServiceConfiguration(50, 2, 21, 50, new IPEndPoint(IPAddress.Loopback, network.DefaultPort), Money.Coins(Constants.DefaultDustThreshold)),
                      syncer,
                      blockProvider);
            Assert.True(Directory.Exists(blocksFolderPath));

            try
            {
                var mempoolTransactionAwaiter = new EventsAwaiter <SmartTransaction>(
                    h => bitcoinStore.MempoolService.TransactionReceived += h,
                    h => bitcoinStore.MempoolService.TransactionReceived -= h,
                    3);

                var nodeConnectionAwaiter = new EventsAwaiter <NodeEventArgs>(
                    h => nodes.ConnectedNodes.Added += h,
                    h => nodes.ConnectedNodes.Added -= h,
                    3);

                nodes.Connect();

                var downloadTasks = new List <Task <Block> >();
                using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(4));
                foreach (var hash in blocksToDownload)
                {
                    downloadTasks.Add(blockProvider.GetBlockAsync(hash, cts.Token));
                }

                await nodeConnectionAwaiter.WaitAsync(TimeSpan.FromMinutes(3));

                var i         = 0;
                var hashArray = blocksToDownload.ToArray();
                foreach (var block in await Task.WhenAll(downloadTasks))
                {
                    Assert.True(File.Exists(Path.Combine(blocksFolderPath, hashArray[i].ToString())));
                    i++;
                }

                await mempoolTransactionAwaiter.WaitAsync(TimeSpan.FromMinutes(1));
            }
            finally
            {
                // So next test will download the block.
                foreach (var hash in blocksToDownload)
                {
                    await blockProvider.BlockRepository.RemoveAsync(hash, CancellationToken.None);
                }
                if (wallet is { })
Example #12
0
		public AddressManagerBehavior(AddressManager manager)
		{
			if(manager == null)
				throw new ArgumentNullException("manager");
			_AddressManager = manager;
		}
Example #13
0
		public static void SetAddrman(Node node, AddressManager addrman)
		{
			if(node == null)
				throw new ArgumentNullException("node");
			SetAddrman(node.Behaviors, addrman);
		}
        /// <summary>
        ///  Adds a new address to be used for this order but does not save it to the database until the order is completed
        ///  to prevent unused records from being added.
        /// </summary>
        protected void AddOrderBtn_Click(object sender, EventArgs e)
        {
            try
            {
                string          addressLine1, addressLine2, city, zipOrPostcode, countyStateProvince, country;
                bool            addOrder = true;
                long            vehicleAvailableID, locationID, addressID;
                DateTime        hireStart, hireEnd;
                CustomerManager customer = null;
                AddressManager  address;

                addressLine1 = addressLine1Txt.Text;
                addressLine2 = addressLine2Txt.Text;

                if (Variables.CheckAlphaNumericCharacters(cityTxt.Text) && cityTxt.Text != "")
                {
                    city = cityTxt.Text;
                }
                else
                {
                    city               = "";
                    addOrder           = false;
                    inputErrorLbl.Text = inputErrorLbl.Text + "<br />" + "Please enter a valid city.";
                }

                if (Variables.CheckAlphaNumericCharacters(zipOrPostcodeTxt.Text) == true && zipOrPostcodeTxt.Text != "")
                {
                    zipOrPostcode = zipOrPostcodeTxt.Text;
                }
                else
                {
                    zipOrPostcode      = "";
                    addOrder           = false;
                    inputErrorLbl.Text = inputErrorLbl.Text + "<br />" + "Invalid zip or postcode.";
                }

                countyStateProvince = countyStateProvinceTxt.Text;

                country = Variables.GetCountryByCode(Request["countryDdl"]);
                if (country == "")
                {
                    addOrder           = false;
                    inputErrorLbl.Text = inputErrorLbl.Text + "<br />" + "Please enter a country.";
                }

                AddressValid addressSuccess = GetAddress(false);

                if (addressSuccess.addOrder == true && addOrder == true)
                {
                    vehicleAvailableID = Convert.ToInt32(Request.QueryString["VehicleAvailableID"]);
                    locationID         = Convert.ToInt32(Request.QueryString["LocationID"]);
                    hireStart          = Convert.ToDateTime(Request.QueryString["StartDateTime"]);
                    hireEnd            = Convert.ToDateTime(Request.QueryString["EndDateTime"]);

                    //AddressManager.AddNewAddress(1, addressSuccess.addressLine1, addressSuccess.addressLine2, addressSuccess.city
                    //    , addressSuccess.zipOrPostcode, addressSuccess.countyStateProvince, addressSuccess.country);

                    if (customersInCompanyDdl.SelectedValue != "")
                    {
                        if (Session["LoggedInType"].ToString() == "Customer")
                        {
                            customer = CustomerManager.GetCustomers().Where(x => x.UserName.Equals(Session["UserName"].ToString(), StringComparison.OrdinalIgnoreCase)).SingleOrDefault();
                        }
                        else if (Session["LoggedInType"].ToString() == "Company")
                        {
                            CompanyManager company;
                            company = CompanyManager.GetCompanies().Where(x => x.UserName.Equals(Session["UserName"].ToString(), StringComparison.OrdinalIgnoreCase)).SingleOrDefault();

                            customer = CustomerManager.GetCustomers().Where(x => x.CustomerID.ToString() == customersInCompanyDdl.SelectedValue.Split(',')[0]).SingleOrDefault();
                        }

                        if (addressSuccess.existingAddress == null)
                        {
                            addressID = AddressManager.GetLastAddedAddress();

                            address = new AddressManager(addressID + 1, 1, addressSuccess.addressLine1, addressSuccess.addressLine2, addressSuccess.city
                                                         , addressSuccess.zipOrPostcode, addressSuccess.countyStateProvince, addressSuccess.country);
                        }
                        else
                        {
                            address = addressSuccess.existingAddress;
                        }

                        StoreSessionVariables(address, vehicleAvailableID, locationID, hireStart, hireEnd, customer.CustomerID, false);
                        Response.Redirect("~/ReviewOrder", false);

                        orderCreatedLbl.Text = "Order Created";
                    }
                    else
                    {
                        inputErrorLbl.Text = "Please select a customer to book for";
                    }
                }
            }
            catch (Exception ex)
            {
                generalErrorLbl.Text = "An error has occured saying: " + ex.Message + " Please contact your system administrator.";
            }
        }
Example #15
0
        public void CanStressAddrManager()
        {
            Exception exception   = null;
            var       addrmanager = new AddressManager();
            Random    randl       = new Random();

            for (int i = 0; i < 30; i++)
            {
                NetworkAddress address       = RandomNetworkAddress(randl);
                IPAddress      addressSource = RandomAddress(randl);
                address.Ago = TimeSpan.FromMinutes(5.0);
                addrmanager.Add(address, addressSource);
            }

            addrmanager.DebugMode = true;
            var threads =
                Enumerable
                .Range(0, 20)
                .Select(t => new Thread(() =>
            {
                try
                {
                    Random rand = new Random(t);
                    for (int i = 0; i < 50; i++)
                    {
                        NetworkAddress address  = RandomNetworkAddress(rand);
                        IPAddress addressSource = RandomAddress(rand);
                        var operation           = rand.Next(0, 7);
                        switch (operation)
                        {
                        case 0:
                            addrmanager.Attempt(address);
                            break;

                        case 1:
                            addrmanager.Add(address, addressSource);
                            break;

                        case 2:
                            addrmanager.Select();
                            break;

                        case 3:
                            addrmanager.GetAddr();
                            break;

                        case 4:
                            {
                                var several = addrmanager.GetAddr();
                                addrmanager.Good(several.Length == 0 ? address : several[0]);
                            }
                            break;

                        case 5:
                            addrmanager.Connected(address);
                            break;

                        case 6:
                            addrmanager.ToBytes();
                            break;

                        default:
                            throw new NotSupportedException();
                        }
                    }
                }
                catch (Exception ex)
                {
                    exception = ex;
                    throw;
                }
            })).ToArray();

            foreach (var t in threads)
            {
                t.Start();
            }
            foreach (var t in threads)
            {
                t.Join();
            }

            Assert.True(addrmanager.nNew != 0);
            Assert.True(addrmanager.nTried != 0);
            Assert.True(addrmanager.GetAddr().Length != 0);
            Assert.Null(exception);
        }
Example #16
0
        private static long Dispose = 0;         // To detect redundant calls

        public static async Task DisposeAsync()
        {
            var compareRes = Interlocked.CompareExchange(ref Dispose, 1, 0);

            if (compareRes == 1)
            {
                while (Interlocked.Read(ref Dispose) != 2)
                {
                    await Task.Delay(50);
                }
                return;
            }
            else if (compareRes == 2)
            {
                return;
            }

            try
            {
                await DisposeInWalletDependentServicesAsync();

                if (RpcServer != null)
                {
                    RpcServer.Stop();
                    Logger.LogInfo($"{nameof(RpcServer)} is stopped.", nameof(Global));
                }

                if (UpdateChecker != null)
                {
                    await UpdateChecker?.StopAsync();

                    Logger.LogInfo($"{nameof(UpdateChecker)} is stopped.", nameof(Global));
                }

                if (Synchronizer != null)
                {
                    await Synchronizer?.StopAsync();

                    Logger.LogInfo($"{nameof(Synchronizer)} is stopped.", nameof(Global));
                }

                if (AddressManagerFilePath != null)
                {
                    IoHelpers.EnsureContainingDirectoryExists(AddressManagerFilePath);
                    if (AddressManager != null)
                    {
                        AddressManager?.SavePeerFile(AddressManagerFilePath, Config.Network);
                        Logger.LogInfo($"{nameof(AddressManager)} is saved to `{AddressManagerFilePath}`.", nameof(Global));
                    }
                }

                if (Nodes != null)
                {
                    Nodes?.Disconnect();
                    while (Nodes.ConnectedNodes.Any(x => x.IsConnected))
                    {
                        await Task.Delay(50);
                    }
                    Nodes?.Dispose();
                    Logger.LogInfo($"{nameof(Nodes)} are disposed.", nameof(Global));
                }

                if (RegTestMemPoolServingNode != null)
                {
                    RegTestMemPoolServingNode.Disconnect();
                    Logger.LogInfo($"{nameof(RegTestMemPoolServingNode)} is disposed.", nameof(Global));
                }

                if (TorManager != null)
                {
                    await TorManager?.StopAsync();

                    Logger.LogInfo($"{nameof(TorManager)} is stopped.", nameof(Global));
                }

                if (AsyncMutex.IsAny)
                {
                    try
                    {
                        await AsyncMutex.WaitForAllMutexToCloseAsync();

                        Logger.LogInfo($"{nameof(AsyncMutex)}(es) are stopped.", nameof(Global));
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError($"Error during stopping {nameof(AsyncMutex)}: {ex}", nameof(Global));
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogWarning(ex, nameof(Global));
            }
            finally
            {
                Interlocked.Exchange(ref Dispose, 2);
            }
        }
Example #17
0
        public void Listen(ConcurrentChain chain = null)
        {
            ListenerTrace.Info($"Connecting to node {_Configuration.Indexer.Node}");
            var ip = Utils.ParseIpEndpoint(_Configuration.Indexer.Node, Configuration.Indexer.Network.DefaultPort);

            ListenerTrace.Info($"Connecting to node ip {ip.ToString()}");
            var node = Node.Connect(Configuration.Indexer.Network, ip);

            ListenerTrace.Info($"Connected, trying handshake...");
            node.VersionHandshake();
            ListenerTrace.Info($"Hanshaked");
            node.Disconnect();

            _Chain   = new ConcurrentChain(_Configuration.Indexer.Network);
            _Indexer = Configuration.Indexer.CreateIndexer();
            if (chain == null)
            {
                chain = new ConcurrentChain(_Configuration.Indexer.Network);
            }
            _Chain = chain;
            ListenerTrace.Info("Fetching headers from " + _Chain.Tip.Height + " (from azure)");
            var client = Configuration.Indexer.CreateIndexerClient();

            client.SynchronizeChain(chain);
            ListenerTrace.Info("Headers fetched tip " + _Chain.Tip.Height);

            _Disposables.Add(_IndexerScheduler = new CustomThreadPoolTaskScheduler(50, 100, "Indexing Threads"));
            _Indexer.TaskScheduler             = _IndexerScheduler;

            _Group = new NodesGroup(Configuration.Indexer.Network);
            _Disposables.Add(_Group);
            _Group.AllowSameGroup        = true;
            _Group.MaximumNodeConnection = 2;
            AddressManager addrman = new AddressManager();

            addrman.Add(new NetworkAddress(ip), IPAddress.Parse("127.0.0.1"));

            _Group.NodeConnectionParameters.TemplateBehaviors.Add(new AddressManagerBehavior(addrman)
            {
                Mode = AddressManagerBehaviorMode.None
            });
            _Group.NodeConnectionParameters.TemplateBehaviors.Add(new ChainBehavior(_Chain)
            {
                SkipPoWCheck = true
            });
            _Group.NodeConnectionParameters.TemplateBehaviors.Add(new Behavior(this));



            ListenerTrace.Info("Fetching wallet rules...");
            _Wallets = _Configuration.Indexer.CreateIndexerClient().GetAllWalletRules();
            ListenerTrace.Info("Wallet rules fetched");

            ListenerTrace.Info("Fetching wallet subscriptions...");
            _Subscriptions = new SubscriptionCollection(_Configuration.GetSubscriptionsTable().Read());
            ListenerTrace.Info("Subscriptions fetched");
            _Group.Connect();

            ListenerTrace.Info("Fetching transactions to broadcast...");

            _Disposables.Add(
                Configuration
                .Topics
                .BroadcastedTransactions
                .CreateConsumer("listener", true)
                .EnsureSubscriptionExists()
                .OnMessage((tx, ctl) =>
            {
                uint256 hash = null;
                var repo     = Configuration.Indexer.CreateIndexerClient();
                var rejects  = Configuration.GetRejectTable();
                try
                {
                    hash          = tx.Transaction.GetHash();
                    var indexedTx = repo.GetTransaction(hash);
                    ListenerTrace.Info("Broadcasting " + hash);
                    var reject = rejects.ReadOne(hash.ToString());
                    if (reject != null)
                    {
                        ListenerTrace.Info("Abort broadcasting of rejected");
                        return;
                    }

                    if (_Broadcasting.Count > 1000)
                    {
                        _Broadcasting.Clear();
                    }

                    _Broadcasting.TryAdd(hash, tx.Transaction);
                    if (indexedTx == null || !indexedTx.BlockIds.Any(id => Chain.Contains(id)))
                    {
                        var unused = SendMessageAsync(tx.Transaction);
                    }
                    var reschedule = new[]
                    {
                        TimeSpan.FromMinutes(5),
                        TimeSpan.FromMinutes(10),
                        TimeSpan.FromHours(1),
                        TimeSpan.FromHours(6),
                        TimeSpan.FromHours(24),
                    };
                    if (tx.Tried <= reschedule.Length - 1)
                    {
                        ctl.RescheduleIn(reschedule[tx.Tried]);
                        tx.Tried++;
                    }
                }
                catch (Exception ex)
                {
                    if (!_Disposed)
                    {
                        LastException = ex;
                        ListenerTrace.Error("Error for new broadcasted transaction " + hash, ex);
                        throw;
                    }
                }
            }));
            ListenerTrace.Info("Transactions to broadcast fetched");

            _Disposables.Add(_Configuration
                             .Topics
                             .SubscriptionChanges
                             .EnsureSubscriptionExists()
                             .AddUnhandledExceptionHandler(ExceptionOnMessagePump)
                             .OnMessage(c =>
            {
                using (_SubscriptionSlimLock.LockWrite())
                {
                    if (c.Added)
                    {
                        _Subscriptions.Add(c.Subscription);
                    }
                    else
                    {
                        _Subscriptions.Remove(c.Subscription.Id);
                    }
                }
            }));

            _Disposables.Add(_Configuration
                             .Topics
                             .SendNotifications
                             .AddUnhandledExceptionHandler(ExceptionOnMessagePump)
                             .OnMessageAsync((n, act) =>
            {
                return(SendAsync(n, act).ContinueWith(t =>
                {
                    if (!_Disposed)
                    {
                        if (t.Exception != null)
                        {
                            LastException = t.Exception;
                        }
                    }
                }));
            }, new OnMessageOptions()
            {
                MaxConcurrentCalls = 1000,
                AutoComplete       = true,
                AutoRenewTimeout   = TimeSpan.Zero
            }));

            _Disposables.Add(Configuration
                             .Topics
                             .AddedAddresses
                             .CreateConsumer("updater", true)
                             .EnsureSubscriptionExists()
                             .AddUnhandledExceptionHandler(ExceptionOnMessagePump)
                             .OnMessage(evt =>
            {
                if (evt == null)
                {
                    return;
                }
                ListenerTrace.Info("New wallet rule");
                using (_WalletsSlimLock.LockWrite())
                {
                    foreach (var address in evt)
                    {
                        _Wallets.Add(address.CreateWalletRuleEntry());
                    }
                }
            }));
        }
Example #18
0
        public void Start()
        {
            this.logger.LogTrace("()");

            this.parameters.UserAgent = $"{this.NodeSettings.Agent}:{this.GetVersion()}";
            this.parameters.Version   = this.NodeSettings.ProtocolVersion;

            if (this.connectionManagerSettings.Connect.Count == 0)
            {
                NodeConnectionParameters cloneParameters = this.parameters.Clone();
                cloneParameters.TemplateBehaviors.Add(new ConnectionManagerBehavior(false, this, this.loggerFactory));
                this.DiscoveredNodeGroup = CreateNodeGroup(cloneParameters, this.discoveredNodeRequiredService);
                this.DiscoveredNodeGroup.CustomGroupSelector = WellKnownGroupSelectors.ByNetwork; // It is the default, but I want to use it.
            }
            else
            {
                NodeConnectionParameters cloneParameters = this.parameters.Clone();
                cloneParameters.TemplateBehaviors.Add(new ConnectionManagerBehavior(false, this, this.loggerFactory));
                cloneParameters.TemplateBehaviors.Remove <AddressManagerBehavior>();

                var addrman = new AddressManager();
                addrman.Add(this.connectionManagerSettings.Connect.Select(c => new NetworkAddress(c)).ToArray(), IPAddress.Loopback);

                var addrmanBehavior = new AddressManagerBehavior(addrman)
                {
                    PeersToDiscover = 10
                };
                addrmanBehavior.Mode = AddressManagerBehaviorMode.None;
                cloneParameters.TemplateBehaviors.Add(addrmanBehavior);

                this.ConnectNodeGroup = CreateNodeGroup(cloneParameters, NodeServices.Nothing);
                this.ConnectNodeGroup.MaximumNodeConnection = this.connectionManagerSettings.Connect.Count;
                this.ConnectNodeGroup.CustomGroupSelector   = WellKnownGroupSelectors.ByEndpoint;
            }

            {
                NodeConnectionParameters cloneParameters = this.parameters.Clone();
                cloneParameters.TemplateBehaviors.Add(new ConnectionManagerBehavior(false, this, this.loggerFactory));
                cloneParameters.TemplateBehaviors.Remove <AddressManagerBehavior>();
                var addrman = new AddressManager();
                addrman.Add(this.connectionManagerSettings.AddNode.Select(c => new NetworkAddress(c)).ToArray(), IPAddress.Loopback);
                var addrmanBehavior = new AddressManagerBehavior(addrman)
                {
                    PeersToDiscover = 10
                };
                addrmanBehavior.Mode = AddressManagerBehaviorMode.AdvertizeDiscover;
                cloneParameters.TemplateBehaviors.Add(addrmanBehavior);

                this.AddNodeNodeGroup = CreateNodeGroup(cloneParameters, NodeServices.Nothing);
                this.AddNodeNodeGroup.MaximumNodeConnection = this.connectionManagerSettings.AddNode.Count;
                this.AddNodeNodeGroup.CustomGroupSelector   = WellKnownGroupSelectors.ByEndpoint;
            }

            // Related the groups to each other to prevent duplicate connections.
            RelatedNodesGroups relGroups = new RelatedNodesGroups();

            relGroups.Register("Discovered", this.DiscoveredNodeGroup);
            relGroups.Register("Connect", this.ConnectNodeGroup);
            relGroups.Register("AddNode", this.AddNodeNodeGroup);
            this.DiscoveredNodeGroup?.Connect();
            this.ConnectNodeGroup?.Connect();
            this.AddNodeNodeGroup?.Connect();

            StringBuilder logs = new StringBuilder();

            logs.AppendLine("Node listening on:");
            foreach (NodeServerEndpoint listen in this.connectionManagerSettings.Listen)
            {
                NodeConnectionParameters cloneParameters = this.parameters.Clone();
                var server = new NodeServer(this.Network)
                {
                    LocalEndpoint    = listen.Endpoint,
                    ExternalEndpoint = this.connectionManagerSettings.ExternalEndpoint
                };

                this.Servers.Add(server);
                cloneParameters.TemplateBehaviors.Add(new ConnectionManagerBehavior(true, this, this.loggerFactory)
                {
                    Whitelisted = listen.Whitelisted
                });

                server.InboundNodeConnectionParameters = cloneParameters;
                server.Listen();

                logs.Append(listen.Endpoint.Address + ":" + listen.Endpoint.Port);
                if (listen.Whitelisted)
                {
                    logs.Append(" (whitelisted)");
                }
                logs.AppendLine();
            }
            this.logger.LogInformation(logs.ToString());

            this.logger.LogTrace("(-)");
        }
Example #19
0
        public static void Initialize(Config config)
        {
            WalletService  = null;
            ChaumianClient = null;

            Config = Guard.NotNull(nameof(config), config);

            string blindingPubKeyFile = Path.Combine(DataDir, $"BlindingPubKey{Network}.json");

            if (File.Exists(blindingPubKeyFile))
            {
                string blindingPubKeyJson = "";
                blindingPubKeyJson = File.ReadAllText(blindingPubKeyFile);
                BlindingPubKey     = BlindingRsaPubKey.CreateFromJson(blindingPubKeyJson);
            }
            else
            {
                if (Network == Network.Main)
                {
                    BlindingPubKey = new BlindingRsaPubKey(new BigInteger("16421152619146079007287475569112871971988560541093277613438316709041030720662622782033859387192362542996510605015506477964793447620206674394713753349543444988246276357919473682408472170521463339860947351211455351029147665615454176157348164935212551240942809518428851690991984017733153078846480521091423447691527000770982623947706172997649440619968085147635776736938871139581019988225202983052255684151711253254086264386774936200194229277914886876824852466823571396538091430866082004097086602287294474304344865162932126041736158327600847754258634325228417149098062181558798532036659383679712667027126535424484318399849"), new BigInteger("65537"));
                }
                else
                {
                    BlindingPubKey = new BlindingRsaPubKey(new BigInteger("19473594448380717274202325076521698699373476167359253614775896809797414915031772455344343455269320444157176520539924715307970060890094127521516100754263825112231545354422893125394219335109864514907655429499954825469485252969706079992227103439161156022844535556626007277544637236136559868400854764962522288139619969507311597914908752685925185380735570791798593290356424409633800092336087046668579610273133131498947353719917407262847070395909920415822288443947309434039008038907229064999576278651443575362470457496666718250346530518268694562965606704838796709743032825816642704620776596590683042135764246115456630753521"), new BigInteger("65537"));
                }
                Directory.CreateDirectory(DataDir);
                File.WriteAllText(blindingPubKeyFile, BlindingPubKey.ToJson());
            }

            var addressManagerFolderPath = Path.Combine(DataDir, "AddressManager");

            AddressManagerFilePath = Path.Combine(addressManagerFolderPath, $"AddressManager{Network}.dat");
            var blocksFolderPath     = Path.Combine(DataDir, $"Blocks{Network}");
            var connectionParameters = new NodeConnectionParameters();

            AddressManager = null;
            try
            {
                AddressManager = AddressManager.LoadPeerFile(AddressManagerFilePath);
                Logger.LogInfo <AddressManager>($"Loaded {nameof(AddressManager)} from `{AddressManagerFilePath}`.");
            }
            catch (DirectoryNotFoundException ex)
            {
                Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} did not exist at `{AddressManagerFilePath}`. Initializing new one.");
                Logger.LogTrace <AddressManager>(ex);
                AddressManager = new AddressManager();
            }
            catch (FileNotFoundException ex)
            {
                Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} did not exist at `{AddressManagerFilePath}`. Initializing new one.");
                Logger.LogTrace <AddressManager>(ex);
                AddressManager = new AddressManager();
            }

            connectionParameters.TemplateBehaviors.Add(new AddressManagerBehavior(AddressManager));
            MemPoolService = new MemPoolService();
            connectionParameters.TemplateBehaviors.Add(new MemPoolBehavior(MemPoolService));

            Nodes = new NodesGroup(Network, connectionParameters,
                                   new NodeRequirement
            {
                RequiredServices = NodeServices.Network,
                MinVersion       = Constants.ProtocolVersion_WITNESS_VERSION
            });

            var indexFilePath = Path.Combine(DataDir, $"Index{Network}.dat");

            IndexDownloader = new IndexDownloader(Network, indexFilePath, Config.GetCurrentBackendUri());

            Nodes.Connect();
            Logger.LogInfo("Start connecting to nodes...");

            IndexDownloader.Synchronize(requestInterval: TimeSpan.FromSeconds(21));
            Logger.LogInfo("Start synchronizing filters...");
        }
    private Vivina.Erp.DataClasses.Address LoadPostalCode(string postalCode)
    {
        Vivina.Erp.DataClasses.Address address = null;
        if (!String.IsNullOrEmpty(postalCode))
        {
            var manager = new AddressManager(this);
            address = manager.GetAddress(postalCode.Replace("-", ""));

            if (address != null)
            {
                txtNeighborhood.Text = address.Neighborhood;
                txtCity.Text = address.City;
                txtAddress.Text = address.Name;
                cboStates.SelectedValue = address.StateId;
                ViewState["NeighborhoodId"] = address.NeighborhoodId;
                ViewState["CityId"] = address.CityId;
                ViewState["StateId"] = address.StateId;
                ViewState["addressExists"] = true;
            }
        }
        else
        {
            ViewState["addressExists"] = false;
            txtNeighborhood.Text = String.Empty;
            txtCity.Text = String.Empty;
            txtAddress.Text = String.Empty;
            txtNumber.Text = String.Empty;
            cboStates.ClearSelection();

        }
        EnableValidators(true);
        return address;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        //
        // Save the Address
        //

        if (IsPostBack && !ScriptManager.GetCurrent(Page).IsInAsyncPostBack &&
            !String.IsNullOrEmpty(txtAddress.Text) && !String.IsNullOrEmpty(txtPostalCode.Text))
        {
            var manager = new AddressManager(this);
            City city = manager.SaveCity(txtCity.Text.ToUpper(), cboStates.SelectedValue);
            Neighborhood neighborhood = manager.SaveNeighborhood(txtNeighborhood.Text.ToUpper(), city.CityId);
            manager.SaveAddress(PostalCode, txtAddress.Text.ToUpper(), neighborhood.NeighborhoodId);
        }


        if (ScriptManager.GetCurrent(Page) != null)
            ScriptManager.GetCurrent(Page).Scripts.Add(new ScriptReference("~/App_shared/address/address.ascx.js"));

        //btnCorreios.Visible = btnGoogle.Visible = Page.User.IsAuthenticated;

        lblTitle.Text = FieldsetTitle;
       // btnGoogle.Attributes["onclick"] = "top.InfoControl.Address.ShowMap('" + txtPostalCode.ClientID + "');";
        if (!Required)
            addressPanel.Style.Add("display", "none");

        EnableValidators(Required);
    }
Example #22
0
 public AddressLogic(TestContext context)
 {
     Address_Manager = new AddressManager(context);
 }
Example #23
0
        public async Task TestServicesAsync(string networkString)
        {
            var network          = Network.GetNetwork(networkString);
            var blocksToDownload = new HashSet <uint256>();

            if (network == Network.Main)
            {
                blocksToDownload.Add(new uint256("00000000000000000037c2de35bd85f3e57f14ddd741ce6cee5b28e51473d5d0"));
                blocksToDownload.Add(new uint256("000000000000000000115315a43cb0cdfc4ea54a0e92bed127f4e395e718d8f9"));
                blocksToDownload.Add(new uint256("00000000000000000011b5b042ad0522b69aae36f7de796f563c895714bbd629"));
            }
            else if (network == Network.TestNet)
            {
                blocksToDownload.Add(new uint256("0000000097a664c4084b49faa6fd4417055cb8e5aac480abc31ddc57a8208524"));
                blocksToDownload.Add(new uint256("000000009ed5b82259ecd2aa4cd1f119db8da7a70e7ea78d9c9f603e01f93bcc"));
                blocksToDownload.Add(new uint256("00000000e6da8c2da304e9f5ad99c079df2c3803b49efded3061ecaf206ddc66"));
            }
            else
            {
                throw new NotSupportedException(network.ToString());
            }

            var            addressManagerFolderPath = Path.Combine(Global.Instance.DataDir, "AddressManager");
            var            addressManagerFilePath   = Path.Combine(addressManagerFolderPath, $"AddressManager{network}.dat");
            var            blocksFolderPath         = Path.Combine(Global.Instance.DataDir, "Blocks", network.ToString());
            var            connectionParameters     = new NodeConnectionParameters();
            AddressManager addressManager           = null;

            try
            {
                addressManager = AddressManager.LoadPeerFile(addressManagerFilePath);
                Logger.LogInfo <AddressManager>($"Loaded {nameof(AddressManager)} from `{addressManagerFilePath}`.");
            }
            catch (DirectoryNotFoundException ex)
            {
                Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} did not exist at `{addressManagerFilePath}`. Initializing new one.");
                Logger.LogTrace <AddressManager>(ex);
                addressManager = new AddressManager();
            }
            catch (FileNotFoundException ex)
            {
                Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} did not exist at `{addressManagerFilePath}`. Initializing new one.");
                Logger.LogTrace <AddressManager>(ex);
                addressManager = new AddressManager();
            }

            connectionParameters.TemplateBehaviors.Add(new AddressManagerBehavior(addressManager));
            var memPoolService = new MemPoolService();

            connectionParameters.TemplateBehaviors.Add(new MemPoolBehavior(memPoolService));

            var nodes = new NodesGroup(network, connectionParameters, requirements: Helpers.Constants.NodeRequirements);

            BitcoinStore bitcoinStore = new BitcoinStore();
            await bitcoinStore.InitializeAsync(Path.Combine(Global.Instance.DataDir, nameof(TestServicesAsync)), network);

            KeyManager         keyManager    = KeyManager.CreateNew(out _, "password");
            WasabiSynchronizer syncer        = new WasabiSynchronizer(network, bitcoinStore, new Uri("http://localhost:12345"), Global.Instance.TorSocks5Endpoint);
            WalletService      walletService = new WalletService(
                bitcoinStore,
                keyManager,
                syncer,
                new CcjClient(syncer, network, keyManager, new Uri("http://localhost:12345"), Global.Instance.TorSocks5Endpoint),
                memPoolService,
                nodes,
                Global.Instance.DataDir,
                new ServiceConfiguration(50, 2, 21, 50, new IPEndPoint(IPAddress.Loopback, network.DefaultPort), Money.Coins(0.0001m)));

            Assert.True(Directory.Exists(blocksFolderPath));

            try
            {
                nodes.ConnectedNodes.Added         += ConnectedNodes_Added;
                nodes.ConnectedNodes.Removed       += ConnectedNodes_Removed;
                memPoolService.TransactionReceived += MemPoolService_TransactionReceived;

                nodes.Connect();
                // Using the interlocked, not because it makes sense in this context, but to
                // set an example that these values are often concurrency sensitive
                var times = 0;
                while (Interlocked.Read(ref _nodeCount) < 3)
                {
                    if (times > 4200)                     // 7 minutes
                    {
                        throw new TimeoutException($"Connection test timed out.");
                    }
                    await Task.Delay(100);

                    times++;
                }

                times = 0;
                while (Interlocked.Read(ref _mempoolTransactionCount) < 3)
                {
                    if (times > 3000)                     // 3 minutes
                    {
                        throw new TimeoutException($"{nameof(MemPoolService)} test timed out.");
                    }
                    await Task.Delay(100);

                    times++;
                }

                foreach (var hash in blocksToDownload)
                {
                    using (var cts = new CancellationTokenSource(TimeSpan.FromMinutes(3)))
                    {
                        var block = await walletService.GetOrDownloadBlockAsync(hash, cts.Token);

                        Assert.True(File.Exists(Path.Combine(blocksFolderPath, hash.ToString())));
                        Logger.LogInfo <P2pTests>($"Full block is downloaded: {hash}.");
                    }
                }
            }
            finally
            {
                nodes.ConnectedNodes.Added         -= ConnectedNodes_Added;
                nodes.ConnectedNodes.Removed       -= ConnectedNodes_Removed;
                memPoolService.TransactionReceived -= MemPoolService_TransactionReceived;

                // So next test will download the block.
                foreach (var hash in blocksToDownload)
                {
                    await walletService?.DeleteBlockAsync(hash);
                }
                if (walletService != null)
                {
                    await walletService.StopAsync();
                }

                if (Directory.Exists(blocksFolderPath))
                {
                    Directory.Delete(blocksFolderPath, recursive: true);
                }

                IoHelpers.EnsureContainingDirectoryExists(addressManagerFilePath);
                addressManager?.SavePeerFile(addressManagerFilePath, network);
                Logger.LogInfo <P2pTests>($"Saved {nameof(AddressManager)} to `{addressManagerFilePath}`.");
                nodes?.Dispose();

                await syncer?.StopAsync();
            }
        }
Example #24
0
 public AddressController(W4rtaDBContext context)
 {
     this.context   = context;
     addressManager = new AddressManager(this.context);
 }
        public void Start()
        {
            this.parameters.UserAgent = "StratisBitcoin:" + GetVersion();
            this.parameters.Version   = this.NodeSettings.ProtocolVersion;
            if (this.connectionManagerSettings.Connect.Count == 0)
            {
                NodeConnectionParameters cloneParameters = this.parameters.Clone();
                cloneParameters.TemplateBehaviors.Add(new ConnectionManagerBehavior(false, this));
                this.DiscoveredNodeGroup = CreateNodeGroup(cloneParameters, this.discoveredNodeRequiredService);
                this.DiscoveredNodeGroup.CustomGroupSelector = WellKnownGroupSelectors.ByNetwork;                 //is the default, but I want to use it
                this.DiscoveredNodeGroup.Connect();
            }
            else
            {
                NodeConnectionParameters cloneParameters = this.parameters.Clone();
                cloneParameters.TemplateBehaviors.Add(new ConnectionManagerBehavior(false, this));
                cloneParameters.TemplateBehaviors.Remove <AddressManagerBehavior>();
                var addrman = new AddressManager();
                addrman.Add(this.connectionManagerSettings.Connect.Select(c => new NetworkAddress(c)).ToArray(), IPAddress.Loopback);
                var addrmanBehavior = new AddressManagerBehavior(addrman);
                addrmanBehavior.Mode = AddressManagerBehaviorMode.None;
                cloneParameters.TemplateBehaviors.Add(addrmanBehavior);

                this.ConnectNodeGroup = CreateNodeGroup(cloneParameters, NodeServices.Nothing);
                this.ConnectNodeGroup.MaximumNodeConnection = this.connectionManagerSettings.Connect.Count;
                this.ConnectNodeGroup.CustomGroupSelector   = WellKnownGroupSelectors.ByEndpoint;
                this.ConnectNodeGroup.Connect();
            }

            {
                NodeConnectionParameters cloneParameters = this.parameters.Clone();
                cloneParameters.TemplateBehaviors.Add(new ConnectionManagerBehavior(false, this));
                cloneParameters.TemplateBehaviors.Remove <AddressManagerBehavior>();
                var addrman = new AddressManager();
                addrman.Add(this.connectionManagerSettings.AddNode.Select(c => new NetworkAddress(c)).ToArray(), IPAddress.Loopback);
                var addrmanBehavior = new AddressManagerBehavior(addrman);
                addrmanBehavior.Mode = AddressManagerBehaviorMode.AdvertizeDiscover;
                cloneParameters.TemplateBehaviors.Add(addrmanBehavior);

                this.AddNodeNodeGroup = CreateNodeGroup(cloneParameters, NodeServices.Nothing);
                this.AddNodeNodeGroup.MaximumNodeConnection = this.connectionManagerSettings.AddNode.Count;
                this.AddNodeNodeGroup.CustomGroupSelector   = WellKnownGroupSelectors.ByEndpoint;
                this.AddNodeNodeGroup.Connect();
            }

            StringBuilder logs = new StringBuilder();

            logs.AppendLine("Node listening on:");
            foreach (NodeServerEndpoint listen in this.connectionManagerSettings.Listen)
            {
                NodeConnectionParameters cloneParameters = this.parameters.Clone();
                var server = new NodeServer(this.Network);

                server.LocalEndpoint    = listen.Endpoint;
                server.ExternalEndpoint = this.connectionManagerSettings.ExternalEndpoint;
                this.Servers.Add(server);
                cloneParameters.TemplateBehaviors.Add(new ConnectionManagerBehavior(true, this)
                {
                    Whitelisted = listen.Whitelisted
                });
                server.InboundNodeConnectionParameters = cloneParameters;
                server.Listen();
                logs.Append(listen.Endpoint.Address + ":" + listen.Endpoint.Port);
                if (listen.Whitelisted)
                {
                    logs.Append(" (whitelisted)");
                }
                logs.AppendLine();
            }
            Logs.ConnectionManager.LogInformation(logs.ToString());
        }
Example #26
0
        public static void InitializeNoWallet()
        {
            WalletService  = null;
            ChaumianClient = null;

            AppDomain.CurrentDomain.ProcessExit += async(s, e) => await TryDesperateDequeueAllCoinsAsync();

            Console.CancelKeyPress += async(s, e) =>
            {
                e.Cancel = true;
                Logger.LogWarning("Process was signaled for killing.", nameof(Global));
                await TryDesperateDequeueAllCoinsAsync();

                Dispatcher.UIThread.Post(() =>
                {
                    Application.Current.MainWindow.Close();
                });
            };

            var addressManagerFolderPath = Path.Combine(DataDir, "AddressManager");

            AddressManagerFilePath = Path.Combine(addressManagerFolderPath, $"AddressManager{Network}.dat");
            var blocksFolderPath     = Path.Combine(DataDir, $"Blocks{Network}");
            var connectionParameters = new NodeConnectionParameters();

            AddressManager = null;
            TorManager     = null;

            TorManager = new TorProcessManager(Config.GetTorSocks5EndPoint(), TorLogsFile);
            TorManager.Start(false, DataDir);
            var fallbackRequestTestUri = new Uri(Config.GetFallbackBackendUri(), "/api/software/versions");

            TorManager.StartMonitor(TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(7), DataDir, fallbackRequestTestUri);

            Logger.LogInfo <TorProcessManager>($"{nameof(TorProcessManager)} is initialized.");

            var needsToDiscoverPeers = true;

            if (Network == Network.RegTest)
            {
                AddressManager = new AddressManager();
                Logger.LogInfo <AddressManager>($"Fake {nameof(AddressManager)} is initialized on the RegTest.");
            }
            else
            {
                try
                {
                    AddressManager       = AddressManager.LoadPeerFile(AddressManagerFilePath);
                    needsToDiscoverPeers = AddressManager.Count < 200;
                    Logger.LogInfo <AddressManager>($"Loaded {nameof(AddressManager)} from `{AddressManagerFilePath}`.");
                }
                catch (DirectoryNotFoundException ex)
                {
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} did not exist at `{AddressManagerFilePath}`. Initializing new one.");
                    Logger.LogTrace <AddressManager>(ex);
                    AddressManager = new AddressManager();
                }
                catch (FileNotFoundException ex)
                {
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} did not exist at `{AddressManagerFilePath}`. Initializing new one.");
                    Logger.LogTrace <AddressManager>(ex);
                    AddressManager = new AddressManager();
                }
                catch (OverflowException ex)
                {
                    // https://github.com/zkSNACKs/WalletWasabi/issues/712
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} has thrown `{nameof(OverflowException)}`. Attempting to autocorrect.");
                    File.Delete(AddressManagerFilePath);
                    Logger.LogTrace <AddressManager>(ex);
                    AddressManager = new AddressManager();
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} autocorrection is successful.");
                }
                catch (FormatException ex)
                {
                    // https://github.com/zkSNACKs/WalletWasabi/issues/880
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} has thrown `{nameof(FormatException)}`. Attempting to autocorrect.");
                    File.Delete(AddressManagerFilePath);
                    Logger.LogTrace <AddressManager>(ex);
                    AddressManager = new AddressManager();
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} autocorrection is successful.");
                }
            }

            var addressManagerBehavior = new AddressManagerBehavior(AddressManager);

            addressManagerBehavior.Mode = needsToDiscoverPeers ? AddressManagerBehaviorMode.Discover : AddressManagerBehaviorMode.None;
            connectionParameters.TemplateBehaviors.Add(addressManagerBehavior);
            MemPoolService = new MemPoolService();
            connectionParameters.TemplateBehaviors.Add(new MemPoolBehavior(MemPoolService));

            if (Network == Network.RegTest | Network.Name == "chaincoin-reg")             //todopw: extend
            {
                Nodes = new NodesGroup(Network, requirements: Constants.NodeRequirements);
                try
                {
                    // todopw: extend
                    Node node;
                    if (Network.Name == "chaincoin-reg")
                    {
                        node = Node.Connect(NBitcoin.Altcoins.Chaincoin.Instance.Regtest, new IPEndPoint(IPAddress.Loopback, 18444));
                    }
                    else
                    {
                        node = Node.Connect(Network.RegTest, new IPEndPoint(IPAddress.Loopback, 18444));
                    }
                    Nodes.ConnectedNodes.Add(node);

                    RegTestMemPoolServingNode = Node.Connect(Network.RegTest, new IPEndPoint(IPAddress.Loopback, 18444));

                    RegTestMemPoolServingNode.Behaviors.Add(new MemPoolBehavior(MemPoolService));
                }
                catch (SocketException ex)
                {
                    Logger.LogError(ex, nameof(Global));
                }
            }
            else
            {
                Nodes = new NodesGroup(Network, connectionParameters, requirements: Constants.NodeRequirements);

                RegTestMemPoolServingNode = null;
            }

            // todopw: Error UpdateChecker just chc - No connection could be made because the target machine actively refused it 127.0.0.1:37127
            Synchronizer = new WasabiSynchronizer(Network, IndexFilePath, Config.GetCurrentBackendUri(), Config.GetTorSocks5EndPoint());

            UpdateChecker = new UpdateChecker(Synchronizer.WasabiClient);

            Nodes.Connect();
            Logger.LogInfo("Start connecting to nodes...");

            if (!(RegTestMemPoolServingNode is null))
            {
                RegTestMemPoolServingNode.VersionHandshake();
                Logger.LogInfo("Start connecting to mempool serving regtest node...");
            }

            var requestInterval = TimeSpan.FromSeconds(30);

            if (Network == Network.RegTest || Network.Name == "chaincoin-reg")              // todopw: extend
            {
                requestInterval = TimeSpan.FromSeconds(5);
            }
            Synchronizer.Start(requestInterval, TimeSpan.FromMinutes(5), 1000);
            Logger.LogInfo("Start synchronizing filters...");
        }
        public void Get_RoutedAddress()
        {
            InitAddressRecords();
            DomainManager dMgr = new DomainManager(CreateConfigStore());
            Domain domain = new Domain("address1.domain1.com");
            domain.Status = EntityStatus.Enabled;
            dMgr.Add(domain);

            string addressType = "Undeliverable";
            AddressManager aMgr = new AddressManager(CreateConfigStore());
            MailAddress address = new MailAddress("*****@*****.**");
            aMgr.Add(address, EntityStatus.Enabled, addressType);
            //
            // [email protected] aready exists
            //

            AddressManager mgr = CreateManager();

            string[] emailAddresses = new[] { "*****@*****.**" };

            IEnumerable<Address> actual = mgr.Get(emailAddresses, true, EntityStatus.Enabled);
            Assert.Equal(1, actual.Count());


            for (int t = 0; t < actual.Count(); t++)
            {
                Assert.True(emailAddresses.Any(e => e.Equals(actual.ToArray()[t].EmailAddress, StringComparison.OrdinalIgnoreCase)));
                Assert.Equal(EntityStatus.Enabled, actual.ToArray()[t].Status);
                Assert.Equal(addressType, actual.ToArray()[t].Type);
            }





            actual = mgr.Get(emailAddresses, EntityStatus.Enabled);
            Assert.Equal(1, actual.Count());


            for (int t = 0; t < actual.Count(); t++)
            {
                Assert.True(emailAddresses.Any(e => e.Equals(actual.ToArray()[t].EmailAddress, StringComparison.OrdinalIgnoreCase)));
                Assert.Equal(EntityStatus.Enabled, actual.ToArray()[t].Status);
                Assert.Equal(addressType, actual.ToArray()[t].Type);
            }




            actual = mgr.Get(emailAddresses, true);
            Assert.Equal(1, actual.Count());


            for (int t = 0; t < actual.Count(); t++)
            {
                Assert.True(emailAddresses.Any(e => e.Equals(actual.ToArray()[t].EmailAddress, StringComparison.OrdinalIgnoreCase)));
                Assert.Equal(EntityStatus.Enabled, actual.ToArray()[t].Status);
                Assert.Equal(addressType, actual.ToArray()[t].Type);
            }




            actual = mgr.Get(emailAddresses);
            Assert.Equal(1, actual.Count());


            for (int t = 0; t < actual.Count(); t++)
            {
                Assert.True(emailAddresses.Any(e => e.Equals(actual.ToArray()[t].EmailAddress, StringComparison.OrdinalIgnoreCase)));
                Assert.Equal(EntityStatus.Enabled, actual.ToArray()[t].Status);
                Assert.Equal(addressType, actual.ToArray()[t].Type);
            }



        }
Example #28
0
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            bool nameAvailable = true;
            Site currentSite   = null;
            if (!string.IsNullOrEmpty(lblSiteId.Text))
            {
                currentSite = SiteManager.GetSiteById(lblSiteId.Text);
            }

            Site site = SiteManager.GetSiteByName(txtSiteName.Text);
            if (site != null)
            {
                if (currentSite != null)
                {
                    if (site != null && site.Id != currentSite.Id)
                    {
                        nameAvailable = false;
                        ((IFeedback)Page.Master).ShowFeedback(Feedback.Actions.Error, "Site " + txtSiteName.Text + " already exists");
                    }
                }
                else //new site
                {
                    nameAvailable = false;
                    ((IFeedback)Page.Master).ShowFeedback(Feedback.Actions.Error, "Region " + txtSiteName.Text + " already exists");
                }
            }

            if (nameAvailable)
            {
                // Figure out the address.
                Address physicalAddress = CreatePhysicalAddressFromFields();
                //if (physicalAddress == null)
                //    physicalAddress = new Address();
                Address postalAddress = CreatePostalAddressFromFields();
                //if (postalAddress == null)
                //    postalAddress = new Address();

                if (currentSite == null)
                {
                    // Create a new site.
                    currentSite      = new Site();
                    currentSite.Name = txtSiteName.Text;
                    // Just get the first available site type. We don't use site types at the moment.
                    currentSite.SiteType        = SiteManager.GetAllSiteTypes()[0];
                    currentSite.PhoneNumber     = txtPhoneNumber.Text;
                    currentSite.AltPhoneNumber  = txtAltPhoneNumber.Text;
                    currentSite.Email           = txtEmail.Text;
                    currentSite.Region          = (Region)regions[cmbRegions.SelectedIndex];
                    currentSite.PhysicalAddress = physicalAddress;
                    currentSite.PostalAddress   = postalAddress;
                    SiteManager.CreateSite(currentSite);
                    lblSiteId.Text = SiteManager.GetSiteByName(currentSite.Name).Id;
                    RefreshData(SiteManager.GetSiteByName(currentSite.Name).Id);
                    btnUpdate.Text = UpdateSite;

                    ((IFeedback)Master).QueueFeedback(BusiBlocksConstants.Blocks.Administration.LongName,
                                                      currentSite.GetType().Name, Feedback.Actions.Created, currentSite.Name);

                    Navigation.Admin_ManageLocations().Redirect(this);
                }
                else
                {
                    if (physicalAddress != null)
                    {
                        if (currentSite.PhysicalAddress == null)
                        {
                            currentSite.PhysicalAddress = new Address();
                        }

                        currentSite.PhysicalAddress.Address1 = physicalAddress.Address1;
                        currentSite.PhysicalAddress.Address2 = physicalAddress.Address2;
                        currentSite.PhysicalAddress.Suburb   = physicalAddress.Suburb;
                        currentSite.PhysicalAddress.Postcode = physicalAddress.Postcode;
                        currentSite.PhysicalAddress.State    = physicalAddress.State;

                        if (string.IsNullOrEmpty(currentSite.PhysicalAddress.Id))
                        {
                            AddressManager.CreateAddress(currentSite.PhysicalAddress);
                        }
                        else
                        {
                            AddressManager.UpdateAddress(currentSite.PhysicalAddress);
                        }
                    }
                    else if (physicalAddress == null && currentSite.PhysicalAddress != null)
                    {
                        // Delete the address.
                        AddressManager.DeleteAddress(currentSite.PhysicalAddress);
                        currentSite.PhysicalAddress = null;
                    }

                    if (postalAddress != null)
                    {
                        if (currentSite.PostalAddress == null)
                        {
                            currentSite.PostalAddress = new Address();
                        }

                        currentSite.PostalAddress.Address1 = postalAddress.Address1;
                        currentSite.PostalAddress.Address2 = postalAddress.Address2;
                        currentSite.PostalAddress.Suburb   = postalAddress.Suburb;
                        currentSite.PostalAddress.Postcode = postalAddress.Postcode;
                        currentSite.PostalAddress.State    = postalAddress.State;

                        if (string.IsNullOrEmpty(currentSite.PostalAddress.Id))
                        {
                            AddressManager.CreateAddress(currentSite.PostalAddress);
                        }
                        else
                        {
                            AddressManager.UpdateAddress(currentSite.PostalAddress);
                        }
                    }
                    else if (postalAddress == null && currentSite.PostalAddress != null)
                    {
                        // Delete the address.
                        AddressManager.DeleteAddress(currentSite.PostalAddress);
                        currentSite.PostalAddress = null;
                    }

                    currentSite.Name           = txtSiteName.Text;
                    currentSite.PhoneNumber    = txtPhoneNumber.Text;
                    currentSite.AltPhoneNumber = txtAltPhoneNumber.Text;
                    currentSite.Email          = txtEmail.Text;
                    currentSite.Region         = (Region)regions[cmbRegions.SelectedIndex];
                    SiteManager.UpdateSite(currentSite);

                    ((IFeedback)Master).QueueFeedback(BusiBlocksConstants.Blocks.Administration.LongName,
                                                      currentSite.GetType().Name, Feedback.Actions.Saved, currentSite.Name);

                    Navigation.Admin_ManageLocations().Redirect(this);
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
            ((IFeedback)Master).SetException(GetType(), ex);
        }
    }
Example #29
0
        public static void InitializeNoWallet()
        {
            WalletService  = null;
            ChaumianClient = null;

            AppDomain.CurrentDomain.ProcessExit += async(s, e) => await TryDesperateDequeueAllCoinsAsync();

            Console.CancelKeyPress += async(s, e) =>
            {
                e.Cancel = true;
                Logger.LogWarning("Process was signaled for killing.", nameof(Global));
                await TryDesperateDequeueAllCoinsAsync();

                Dispatcher.UIThread.Post(() =>
                {
                    Application.Current.MainWindow.Close();
                });
            };

            var addressManagerFolderPath = Path.Combine(DataDir, "AddressManager");

            AddressManagerFilePath = Path.Combine(addressManagerFolderPath, $"AddressManager{Network}.dat");
            var blocksFolderPath     = Path.Combine(DataDir, $"Blocks{Network}");
            var connectionParameters = new NodeConnectionParameters();

            AddressManager = null;
            TorManager     = null;

            TorManager = new TorProcessManager(Config.GetTorSocks5EndPoint(), TorLogsFile);
            TorManager.Start(false, DataDir);

            Logger.LogInfo <TorProcessManager>($"{nameof(TorProcessManager)} is initialized.");

            if (Network == Network.RegTest)
            {
                AddressManager = new AddressManager();
                Logger.LogInfo <AddressManager>($"Fake {nameof(AddressManager)} is initialized on the RegTest.");
            }
            else
            {
                try
                {
                    AddressManager = AddressManager.LoadPeerFile(AddressManagerFilePath);
                    Logger.LogInfo <AddressManager>($"Loaded {nameof(AddressManager)} from `{AddressManagerFilePath}`.");
                }
                catch (DirectoryNotFoundException ex)
                {
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} did not exist at `{AddressManagerFilePath}`. Initializing new one.");
                    Logger.LogTrace <AddressManager>(ex);
                    AddressManager = new AddressManager();
                }
                catch (FileNotFoundException ex)
                {
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} did not exist at `{AddressManagerFilePath}`. Initializing new one.");
                    Logger.LogTrace <AddressManager>(ex);
                    AddressManager = new AddressManager();
                }
            }

            connectionParameters.TemplateBehaviors.Add(new AddressManagerBehavior(AddressManager));
            MemPoolService = new MemPoolService();
            connectionParameters.TemplateBehaviors.Add(new MemPoolBehavior(MemPoolService));

            if (Network == Network.RegTest)
            {
                Nodes = new NodesGroup(Network,
                                       requirements: new NodeRequirement
                {
                    RequiredServices = NodeServices.Network,
                    MinVersion       = Constants.ProtocolVersion_WITNESS_VERSION
                });
                Nodes.ConnectedNodes.Add(Node.Connect(Network.RegTest, new IPEndPoint(IPAddress.Loopback, 18444)));

                RegTestMemPoolServingNode = Node.Connect(Network.RegTest, new IPEndPoint(IPAddress.Loopback, 18444));
                RegTestMemPoolServingNode.Behaviors.Add(new MemPoolBehavior(MemPoolService));
            }
            else
            {
                Nodes = new NodesGroup(Network, connectionParameters,
                                       new NodeRequirement
                {
                    RequiredServices = NodeServices.Network,
                    MinVersion       = Constants.ProtocolVersion_WITNESS_VERSION
                });

                RegTestMemPoolServingNode = null;
            }

            IndexDownloader = new IndexDownloader(Network, IndexFilePath, Config.GetCurrentBackendUri(), Config.GetTorSocks5EndPoint());

            UpdateChecker = new UpdateChecker(IndexDownloader.WasabiClient);

            Nodes.Connect();
            Logger.LogInfo("Start connecting to nodes...");

            if (!(RegTestMemPoolServingNode is null))
            {
                RegTestMemPoolServingNode.VersionHandshake();
                Logger.LogInfo("Start connecting to mempool serving regtest node...");
            }

            IndexDownloader.Synchronize(requestInterval: TimeSpan.FromSeconds(21));
            Logger.LogInfo("Start synchronizing filters...");
        }
Example #30
0
        private static async Task <AddressManagerBehavior> InitializeAddressManagerBehaviorAsync()
        {
            var needsToDiscoverPeers = true;

            if (Network == Network.RegTest)
            {
                AddressManager = new AddressManager();
                Logger.LogInfo <AddressManager>($"Fake {nameof(AddressManager)} is initialized on the RegTest.");
            }
            else
            {
                try
                {
                    AddressManager = await NBitcoinHelpers.LoadAddressManagerFromPeerFileAsync(AddressManagerFilePath);

                    // The most of the times we don't need to discover new peers. Instead, we can connect to
                    // some of those that we already discovered in the past. In this case we assume that we
                    // assume that discovering new peers could be necessary if out address manager has less
                    // than 500 addresses. A 500 addresses could be okay because previously we tried with
                    // 200 and only one user reported he/she was not able to connect (there could be many others,
                    // of course).
                    // On the other side, increasing this number forces users that do not need to discover more peers
                    // to spend resources (CPU/bandwith) to discover new peers.
                    needsToDiscoverPeers = Config.UseTor == true || AddressManager.Count < 500;
                    Logger.LogInfo <AddressManager>($"Loaded {nameof(AddressManager)} from `{AddressManagerFilePath}`.");
                }
                catch (DirectoryNotFoundException ex)
                {
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} did not exist at `{AddressManagerFilePath}`. Initializing new one.");
                    Logger.LogTrace <AddressManager>(ex);
                    AddressManager = new AddressManager();
                }
                catch (FileNotFoundException ex)
                {
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} did not exist at `{AddressManagerFilePath}`. Initializing new one.");
                    Logger.LogTrace <AddressManager>(ex);
                    AddressManager = new AddressManager();
                }
                catch (OverflowException ex)
                {
                    // https://github.com/zkSNACKs/WalletWasabi/issues/712
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} has thrown `{nameof(OverflowException)}`. Attempting to autocorrect.");
                    File.Delete(AddressManagerFilePath);
                    Logger.LogTrace <AddressManager>(ex);
                    AddressManager = new AddressManager();
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} autocorrection is successful.");
                }
                catch (FormatException ex)
                {
                    // https://github.com/zkSNACKs/WalletWasabi/issues/880
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} has thrown `{nameof(FormatException)}`. Attempting to autocorrect.");
                    File.Delete(AddressManagerFilePath);
                    Logger.LogTrace <AddressManager>(ex);
                    AddressManager = new AddressManager();
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} autocorrection is successful.");
                }
            }

            var addressManagerBehavior = new AddressManagerBehavior(AddressManager)
            {
                Mode = needsToDiscoverPeers ? AddressManagerBehaviorMode.Discover : AddressManagerBehaviorMode.None
            };

            return(addressManagerBehavior);
        }
Example #31
0
        public static void Extract()
        {
            using (var spinner = new ConsoleSpinner())
            {
                spinner.Start();

                System.Diagnostics.Stopwatch stopwatch  = new System.Diagnostics.Stopwatch();
                System.Diagnostics.Stopwatch stopwatch2 = new System.Diagnostics.Stopwatch();
                stopwatch.Start();

                writeConsole("#####################################");
                writeConsole("######                         ######");
                writeConsole("######  Start Extract Address  ######");
                writeConsole("######                         ######");
                writeConsole("#####################################");
                writeConsole("-------------------------------------");
                writeConsole();

                using (DataTable dtProvince = db.getDataProvince())
                {
                    using (DataTable dtYears = db.getYearCreateAddress())
                    {
                        DataTable      dt;
                        DataTable      dtAddress;
                        string         _year;
                        AddressManager _ex = new AddressManager(dtProvince);
                        foreach (DataRow _dr in dtYears.Rows)
                        {
                            stopwatch2.Start();

                            try
                            {
                                _year     = Convert.ToString(_dr["years"]);
                                dtAddress = db.getDataAddress(_year);

                                writeConsole(string.Format("=> GetAddress from year : {0}", _dr["years"]), consoleType.info);
                                writeConsole(string.Format("=> Total Rows : {0}", dtAddress.Rows.Count.ToString("n0")), consoleType.info);
                                writeConsole(string.Format("=>> GetAddress Success : {0}", stopwatch2.Elapsed), consoleType.warn);
                                writeConsole();

                                if (dtAddress != null && dtAddress.Rows.Count > 0)
                                {
                                    writeConsole(string.Format("=>> Start Extract Address   : {0}", stopwatch2.Elapsed));
                                    dt = _ex.eXtract(dtAddress, _year);
                                    writeConsole(string.Format("=>> Extract Address Success : {0}", stopwatch2.Elapsed), consoleType.warn);
                                    writeConsole();

                                    writeConsole(string.Format("=>> Start Clear Exists Data   : {0}", stopwatch2.Elapsed));
                                    db.clearExistsDataIn_TbExtract(dt);
                                    writeConsole(string.Format("=>> Clear Exists Data Success : {0}", stopwatch2.Elapsed), consoleType.warn);
                                    writeConsole();

                                    writeConsole(string.Format("=>> Start Insert into DB   : {0}", stopwatch2.Elapsed));
                                    db.insertBulkToImportDB("tempAddress", dt);
                                    writeConsole(string.Format("=>> Insert into DB Success : {0}", stopwatch2.Elapsed), consoleType.warn);
                                    writeConsole();

                                    dt.Dispose();
                                }
                                dtAddress.Dispose();

                                writeConsole("=>>> Success \\(^.^)/", consoleType.success);
                            }
                            catch (Exception ex)
                            {
                                writeConsole("=>>> Error /(-_-\")\\ ", consoleType.error);
                                writeConsole(string.Format("=>>> : {0}", ex.Message), consoleType.error);
                            }

                            writeConsole("-------------------------------------");
                            writeConsole();

                            stopwatch2.Stop();
                            stopwatch2.Reset();

                            //break;
                        }
                    }
                }

                stopwatch.Stop();
                writeConsole("-------------------------------------");
                writeConsole(string.Format("### Time elapsed: {0} ###", stopwatch.Elapsed));
            }

            Console.ReadLine();
        }
Example #32
0
        public P2pNetwork(Network network, EndPoint fullnodeP2pEndPoint, EndPoint?torSocks5EndPoint, string workDir, BitcoinStore bitcoinStore)
        {
            Network             = network;
            FullnodeP2PEndPoint = fullnodeP2pEndPoint;
            TorSocks5EndPoint   = torSocks5EndPoint;
            WorkDir             = workDir;
            BitcoinStore        = bitcoinStore;

            var userAgent            = Constants.UserAgents.RandomElement();
            var connectionParameters = new NodeConnectionParameters {
                UserAgent = userAgent
            };

            connectionParameters.TemplateBehaviors.Add(BitcoinStore.CreateUntrustedP2pBehavior());

            AddressManagerFilePath = Path.Combine(WorkDir, $"AddressManager{Network}.dat");
            var needsToDiscoverPeers = true;

            if (Network == Network.RegTest)
            {
                AddressManager = new AddressManager();
                Logger.LogInfo($"Fake {nameof(AddressManager)} is initialized on the {Network.RegTest}.");
            }
            else
            {
                try
                {
                    AddressManager = AddressManager.LoadPeerFile(AddressManagerFilePath);

                    // Most of the times we do not need to discover new peers. Instead, we can connect to
                    // some of those that we already discovered in the past. In this case we assume that
                    // discovering new peers could be necessary if our address manager has less
                    // than 500 addresses. 500 addresses could be okay because previously we tried with
                    // 200 and only one user reported he/she was not able to connect (there could be many others,
                    // of course).
                    // On the other side, increasing this number forces users that do not need to discover more peers
                    // to spend resources (CPU/bandwidth) to discover new peers.
                    needsToDiscoverPeers = TorSocks5EndPoint is not null || AddressManager.Count < 500;
                    Logger.LogInfo($"Loaded {nameof(AddressManager)} from `{AddressManagerFilePath}`.");
                }
                catch (DirectoryNotFoundException ex)
                {
                    Logger.LogInfo($"{nameof(AddressManager)} did not exist at `{AddressManagerFilePath}`. Initializing new one.");
                    Logger.LogTrace(ex);
                    AddressManager = new AddressManager();
                }
                catch (FileNotFoundException ex)
                {
                    Logger.LogInfo($"{nameof(AddressManager)} did not exist at `{AddressManagerFilePath}`. Initializing new one.");
                    Logger.LogTrace(ex);
                    AddressManager = new AddressManager();
                }
                catch (OverflowException ex)
                {
                    // https://github.com/zkSNACKs/WalletWasabi/issues/712
                    Logger.LogInfo($"{nameof(AddressManager)} has thrown `{nameof(OverflowException)}`. Attempting to autocorrect.");
                    File.Delete(AddressManagerFilePath);
                    Logger.LogTrace(ex);
                    AddressManager = new AddressManager();
                    Logger.LogInfo($"{nameof(AddressManager)} autocorrection is successful.");
                }
                catch (FormatException ex)
                {
                    // https://github.com/zkSNACKs/WalletWasabi/issues/880
                    Logger.LogInfo($"{nameof(AddressManager)} has thrown `{nameof(FormatException)}`. Attempting to autocorrect.");
                    File.Delete(AddressManagerFilePath);
                    Logger.LogTrace(ex);
                    AddressManager = new AddressManager();
                    Logger.LogInfo($"{nameof(AddressManager)} autocorrection is successful.");
                }
            }

            var addressManagerBehavior = new AddressManagerBehavior(AddressManager)
            {
                Mode = needsToDiscoverPeers ? AddressManagerBehaviorMode.Discover : AddressManagerBehaviorMode.None
            };

            connectionParameters.TemplateBehaviors.Add(addressManagerBehavior);

            if (Network == Network.RegTest)
            {
                Nodes = new NodesGroup(Network, requirements: Constants.NodeRequirements);
            }
            else
            {
                var maximumNodeConnection       = 12;
                var bestEffortEndpointConnector = new BestEffortEndpointConnector(maximumNodeConnection / 2);
                connectionParameters.EndpointConnector = bestEffortEndpointConnector;
                if (TorSocks5EndPoint is not null)
                {
                    connectionParameters.TemplateBehaviors.Add(new SocksSettingsBehavior(TorSocks5EndPoint, onlyForOnionHosts: false, networkCredential: null, streamIsolation: true));
                }
                var nodes = new NodesGroup(Network, connectionParameters, requirements: Constants.NodeRequirements);
                nodes.ConnectedNodes.Added   += ConnectedNodes_OnAddedOrRemoved;
                nodes.ConnectedNodes.Removed += ConnectedNodes_OnAddedOrRemoved;
                nodes.MaximumNodeConnection   = maximumNodeConnection;

                Nodes = nodes;
            }
        }
 private void CreateCompanyAddress()
 {
     AddressManager.CreateCompanyAddress(SelectedCategoryId, Name, Account);
     this.Close();
 }
 public AddressController(AddressManager am)
 {
     _addressManager = am;
 }
 public TriggerManager(AddressManager address, Offsets offsets)
 {
     _offsets = offsets;
     _address = address;
 }
Example #36
0
        public static void InitializeNoWallet()
        {
            WalletService  = null;
            ChaumianClient = null;

            AppDomain.CurrentDomain.ProcessExit += async(s, e) => await TryDesperateDequeueAllCoinsAsync();

            Console.CancelKeyPress += async(s, e) =>
            {
                e.Cancel = true;
                Logger.LogWarning("Process was signaled for killing.", nameof(Global));
                await TryDesperateDequeueAllCoinsAsync();

                Dispatcher.UIThread.Post(() =>
                {
                    Application.Current.MainWindow.Close();
                });
            };

            var addressManagerFolderPath = Path.Combine(DataDir, "AddressManager");

            AddressManagerFilePath = Path.Combine(addressManagerFolderPath, $"AddressManager{Network}.dat");
            var blocksFolderPath     = Path.Combine(DataDir, $"Blocks{Network}");
            var connectionParameters = new NodeConnectionParameters();

            AddressManager = null;
            TorManager     = null;

            TorManager = new TorProcessManager(Config.GetTorSocks5EndPoint(), TorLogsFile);
            TorManager.Start(false, DataDir);
            var fallbackRequestTestUri = new Uri(Config.GetFallbackBackendUri(), "/api/software/versions");

            TorManager.StartMonitor(TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(7), DataDir, fallbackRequestTestUri);

            Logger.LogInfo <TorProcessManager>($"{nameof(TorProcessManager)} is initialized.");

            var needsToDiscoverPeers = true;

            if (Network == Network.RegTest)
            {
                AddressManager = new AddressManager();
                Logger.LogInfo <AddressManager>($"Fake {nameof(AddressManager)} is initialized on the RegTest.");
            }
            else
            {
                try
                {
                    AddressManager = AddressManager.LoadPeerFile(AddressManagerFilePath);

                    // The most of the times we don't need to discover new peers. Instead, we can connect to
                    // some of those that we already discovered in the past. In this case we assume that we
                    // assume that discovering new peers could be necessary if out address manager has less
                    // than 500 addresses. A 500 addresses could be okay because previously we tried with
                    // 200 and only one user reported he/she was not able to connect (there could be many others,
                    // of course).
                    // On the other side, increasing this number forces users that do not need to discover more peers
                    // to spend resources (CPU/bandwith) to discover new peers.
                    needsToDiscoverPeers = AddressManager.Count < 500;
                    Logger.LogInfo <AddressManager>($"Loaded {nameof(AddressManager)} from `{AddressManagerFilePath}`.");
                }
                catch (DirectoryNotFoundException ex)
                {
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} did not exist at `{AddressManagerFilePath}`. Initializing new one.");
                    Logger.LogTrace <AddressManager>(ex);
                    AddressManager = new AddressManager();
                }
                catch (FileNotFoundException ex)
                {
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} did not exist at `{AddressManagerFilePath}`. Initializing new one.");
                    Logger.LogTrace <AddressManager>(ex);
                    AddressManager = new AddressManager();
                }
                catch (OverflowException ex)
                {
                    // https://github.com/zkSNACKs/WalletWasabi/issues/712
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} has thrown `{nameof(OverflowException)}`. Attempting to autocorrect.");
                    File.Delete(AddressManagerFilePath);
                    Logger.LogTrace <AddressManager>(ex);
                    AddressManager = new AddressManager();
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} autocorrection is successful.");
                }
                catch (FormatException ex)
                {
                    // https://github.com/zkSNACKs/WalletWasabi/issues/880
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} has thrown `{nameof(FormatException)}`. Attempting to autocorrect.");
                    File.Delete(AddressManagerFilePath);
                    Logger.LogTrace <AddressManager>(ex);
                    AddressManager = new AddressManager();
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} autocorrection is successful.");
                }
            }

            var addressManagerBehavior = new AddressManagerBehavior(AddressManager)
            {
                Mode = needsToDiscoverPeers ? AddressManagerBehaviorMode.Discover : AddressManagerBehaviorMode.None
            };

            connectionParameters.TemplateBehaviors.Add(addressManagerBehavior);
            MemPoolService = new MemPoolService();
            connectionParameters.TemplateBehaviors.Add(new MemPoolBehavior(MemPoolService));

            if (Network == Network.RegTest)
            {
                Nodes = new NodesGroup(Network, requirements: Constants.NodeRequirements);
                try
                {
                    Node node = Node.Connect(Network.RegTest, new IPEndPoint(IPAddress.Loopback, 18444));
                    Nodes.ConnectedNodes.Add(node);

                    RegTestMemPoolServingNode = Node.Connect(Network.RegTest, new IPEndPoint(IPAddress.Loopback, 18444));

                    RegTestMemPoolServingNode.Behaviors.Add(new MemPoolBehavior(MemPoolService));
                }
                catch (SocketException ex)
                {
                    Logger.LogError(ex, nameof(Global));
                }
            }
            else
            {
                Nodes = new NodesGroup(Network, connectionParameters, requirements: Constants.NodeRequirements);

                RegTestMemPoolServingNode = null;
            }

            Synchronizer = new WasabiSynchronizer(Network, IndexFilePath, Config.GetCurrentBackendUri(), Config.GetTorSocks5EndPoint());

            UpdateChecker = new UpdateChecker(Synchronizer.WasabiClient);

            Nodes.Connect();
            Logger.LogInfo("Start connecting to nodes...");

            if (!(RegTestMemPoolServingNode is null))
            {
                RegTestMemPoolServingNode.VersionHandshake();
                Logger.LogInfo("Start connecting to mempool serving regtest node...");
            }

            var requestInterval = TimeSpan.FromSeconds(30);

            if (Network == Network.RegTest)
            {
                requestInterval = TimeSpan.FromSeconds(5);
            }
            Synchronizer.Start(requestInterval, TimeSpan.FromMinutes(5), 1000);
            Logger.LogInfo("Start synchronizing filters...");
        }
Example #37
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!\n");

            using (var context = DbContextFactory.Create())   //no 'NEW' b/c of static class
            {
                Console.WriteLine("Test");
            }

            //ADDRESS HANDLING ------------------------------------
            AddressManager addrmgr = new AddressManager();

            var newAddress = new Address
            {
                Street      = "3001 Hilltop Dr",
                City        = "Novi",
                State       = "Mi",
                Zip         = 48335,
                Addresstype = Address.AddressTypes.SHIPPING
            };
            //CREATE ADDRESS:
            //addrmgr.CreateAddress(newAddress);

            /*
             * Address updateAddress = new Address
             * {
             *  CustomerDetails = {Id = 1},
             *  Id = 2,
             *  Street = "8 Eight Lane",
             *  City = "Maui",
             *  State = "Hi",
             *  Zip = 98765,
             *  Addresstype = Address.AddressTypes.SHIPPING
             * };*/

            //UPDATE ADDRESS:
            //addrmgr.UpdateAddress(updateAddress);

            //REMOVE ADDRESS:
            //addrmgr.RemoveAddress(8);

            //RETRIEVE ADDRESS (ex; by customer Id
            //var addrrr = addrmgr.GetAddress(4);
            //Console.WriteLine(addrrr.First().Id);


            //PRODUCT HANDLING ------------------------------------------

            Product updateProd = new Product
            {
                Id    = 3,
                Name  = "Widget 5000 Updated",
                Price = 42.99
            };

            Product newProd2 = new Product
            {
                Name  = "Widget B",
                Price = 5.00
            };

            ProductManager prodmgr = new ProductManager();

            //----RETRIEVE PRODUCT
            //var prod = prodmgr.GetProduct(1);
            //Console.WriteLine(prod.Name);

            //----UPDATE PRODUCT
            //prodmgr.UpdateProduct(updateProd);

            //----CREATE PRODUCT
            //prodmgr.CreateProduct(newProd2);

            //xxxx REMOVE PRODUCT - constraints <----- RETURN TO THIS
            //prodmgr.RemoveProduct(7);


            //SHIPPING METHOD HANDLING ------------------------------------------

            ShippingMethod updateMethod = new ShippingMethod
            {
                Id      = 2,
                Method  = "2nd Day",
                Carrier = "Fedex"
            };

            ShippingMethod newMethod1 = new ShippingMethod
            {
                Carrier = "UPS",
                Method  = "Overnight"
            };

            ShipMethodManager shipmgr = new ShipMethodManager();

            //----RETRIEVE SHIPMETHOD
            //var m = shipmgr.GetShipMethod(1);
            //Console.WriteLine(m.Method);

            //----UPDATE SHIPMETHOD
            //shipmgr.UpdateShipMethod(updateMethod);

            //-----CREATE SHIPMETHOD
            //shipmgr.CreateShipMethod(newMethod1);

            //xxxx REMOVE SHIPMETHOD -> dependencies <----- RETURN TO THIS
            //shipmgr.RemoveShipMethod(3);


            //CUSTOMER HANDLING ------------------------------------------

            CustomerManager custmgr = new CustomerManager();

            //----RETRIEVE CUSTOMER - ok
            //var cust = custmgr.GetCustomer(2);
            //Console.WriteLine(cust.Name);

            Customer updatedCustomer = new Customer
            {
                Id   = 2,
                Name = "My New Customer LLC"
            };

            Customer newCustomer = new Customer
            {
                Name      = "Smart Data Systems",
                Addresses = new List <Address>
                {
                    new Address
                    {
                        Street      = "8571 Gander Creek Dr",
                        City        = "Miamisburg",
                        State       = "OH",
                        Zip         = 45342,
                        Addresstype = Address.AddressTypes.SHIPPING
                    },
                    new Address
                    {
                        Street      = "8570 Gander Creek Dr",
                        City        = "Miamisburg",
                        State       = "OH",
                        Zip         = 45342,
                        Addresstype = Address.AddressTypes.BILLING
                    },
                }
            };



            //UPDATE CUSTOMER - ok
            //custmgr.UpdateCustomer(updatedCustomer);

            //CREATE CUSTOMER - ok
            //custmgr.CreateCustomer(newCustomer);

            //REMOVE CUSTOMER -> dependencies... this is odd... but it works...
            //custmgr.RemoveCustomer(7);

            //LINE ITEM HANDLING ------------------------------------------

            // LineItem updatedLine = new LineItem
            //{ Id = 9, ProductDetails = new Product { Id = 2 }, Quantity = 100, Discount = 0.05, OrderDetailsId = 3};

            // LineItem newLine = new LineItem
            //{ ProductDetails = new Product { Id = 2 }, Quantity = 2, Discount = 0.05, OrderDetailsId = 2 };

            LineItemManager linemgr = new LineItemManager();

            //RETRIEVE LINE - ok
            //linemgr.GetLineItem(4);

            //UPDATE LINE - ok
            //linemgr.UpdateLineItem(updatedLine);

            //CREATE LINE
            //linemgr.CreateLineItem(newLine);

            //REMOVE LINE
            //linemgr.RemoveLineItem(2);

            //ORDER HANDLING ----------------------------------------------------------

            OrderManager ordermgr = new OrderManager();

            var newOrder = new OrderDetails
            {
                OrderDate         = DateTime.Now.ToString("yyyy-MM-dd"),
                CustomerDetailsId = 2,
                Shipmethod        =
                {
                    Id      =     1,
                    Carrier = "UPS",
                    Method  = "Overnight"
                },
                Lineitems = new LineItem[]
                {
                    new LineItem {
                        ProductDetailsId = 6, Quantity = 22,
                        Discount         = 0
                    },
                    new LineItem {
                        ProductDetailsId = 5, Quantity = 1,
                        Discount         = 0
                    }
                },
                OrderStatus = OrderDetails.ShippingStatus.PROCESSING
            };

            //CREATE ORDER
            //This should take CUSTOMER ID, SHIPPING DETAILS, ARRAY OF LINE ITEMS & CREATE ORDER
            //ordermgr.CreateOrder(newOrder);

            OrderDetails updatedOrder = new OrderDetails
            {
                Id          = 3,
                Lineitems   = null,
                Shipmethod  = { Id = 1 },
                OrderStatus = OrderDetails.ShippingStatus.COMPLETED
            };

            //UPDATE ORDER
            //ordermgr.UpdateOrder(updatedOrder);

            //RETRIEVE ORDER - per ID (one at a time)
            //var ord = ordermgr.GetOrder(1);


            //Retrieval variables
            int id = 1;

            OrderDetails.ShippingStatus orderstatus = OrderDetails.ShippingStatus.PROCESSING;

            //RETRIEVE ORDERS FOR CUSTOMER (+ filter param?)
            //IQueryable<CustomerOrders> returnorders =

            ordermgr.GetCustomerOrders(id, orderstatus);

            //Retrieve Status


            //CREATE ORDER
            //This should take CUSTOMER ID, SHIPPING DETAILS, ARRAY OF LINE ITEMS & CREATE ORDER
            //ordermgr.CreateOrder(newOrder);

            //CANCEL ORDER / flag it
            //ordermgr.CancelOrder(1);
        } //end Main
Example #38
0
		public static void SetAddrman(NodeConnectionParameters parameters, AddressManager addrman)
		{
			if(parameters == null)
				throw new ArgumentNullException("parameters");
			SetAddrman(parameters.TemplateBehaviors, addrman);
		}
Example #39
0
		public ClientCompanyProfileService(IClientCompanyManagement clientCompanyManagement, IClientCompanyIdentityGenerator clientCompanyIdentityGenerator, AddressManager addressManager)
		{
			_clientCompanyManagement = ValidationUtil.CheckOnNullAndThrowIfNull(clientCompanyManagement);
			_clientCompanyIdentityGenerator = ValidationUtil.CheckOnNullAndThrowIfNull(clientCompanyIdentityGenerator);
			_addressManager = ValidationUtil.CheckOnNullAndThrowIfNull(addressManager);
		}
Example #40
0
 public ImportAddressToWatchController(AddressManager addressManger, MessageBoxService msgBox)
 {
     this.ImportCommand  = new DelegateCommand(ImportAddress);
     this.MsgBox         = msgBox;
     this.AddressManager = addressManger;
 }
        public async Task StartAsync()
        {
            if (_Disposed)
            {
                throw new ObjectDisposedException(nameof(NBxplorerInitializer));
            }
            _Starting.Reset();
            try
            {
                if (_Network.IsRegTest)
                {
                    if (await _RPC.GetBlockCountAsync() < 100)
                    {
                        Logs.Configuration.LogInformation($"Less than 100 blocks, mining some block for regtest");
                        await _RPC.GenerateAsync(101);
                    }
                    else
                    {
                        var header = await _RPC.GetBlockHeaderAsync(await _RPC.GetBestBlockHashAsync());

                        if ((DateTimeOffset.UtcNow - header.BlockTime) > TimeSpan.FromSeconds(24 * 60 * 60))
                        {
                            Logs.Configuration.LogInformation($"It has been a while nothing got mined on regtest... mining 10 blocks");
                            await _RPC.GenerateAsync(10);
                        }
                    }
                }

                var cachePath = Path.Combine(_Configuration.DataDir, "chain.dat");
                if (_Configuration.CacheChain && File.Exists(cachePath))
                {
                    Logs.Configuration.LogInformation($"Loading chain from cache...");
                    _Chain.Load(File.ReadAllBytes(cachePath));
                    Logs.Configuration.LogInformation($"Height: " + _Chain.Height);
                }

                var heightBefore = _Chain.Height;
                Logs.Configuration.LogInformation($"Loading chain from node...");
                using (var node = Node.Connect(_Network.Network, _Configuration.NodeEndpoint))
                {
                    var cts = new CancellationTokenSource();
                    cts.CancelAfter(5000);
                    node.VersionHandshake(cts.Token);
                    node.SynchronizeChain(_Chain);
                }
                Logs.Configuration.LogInformation("Height: " + _Chain.Height);

                if (_Configuration.CacheChain && heightBefore != _Chain.Height)
                {
                    Logs.Configuration.LogInformation($"Saving chain to cache...");
                    var ms = new MemoryStream();
                    _Chain.WriteTo(ms);
                    File.WriteAllBytes(cachePath, ms.ToArray());
                    Logs.Configuration.LogInformation($"Saved");
                }


                AddressManager manager = new AddressManager();
                manager.Add(new NetworkAddress(_Configuration.NodeEndpoint), IPAddress.Loopback);
                NodesGroup group = new NodesGroup(_Network.Network, new NodeConnectionParameters()
                {
                    Services          = NodeServices.Nothing,
                    IsRelay           = true,
                    TemplateBehaviors =
                    {
                        new AddressManagerBehavior(manager)
                        {
                            PeersToDiscover = 1,
                            Mode            = AddressManagerBehaviorMode.None
                        },
                        new ExplorerBehavior(_Repository, _Chain, _Invoker, _Events)
                        {
                            StartHeight = _Configuration.StartHeight
                        },
                        new ChainBehavior(_Chain)
                        {
                            CanRespondToGetHeaders = false
                        }
                    }
                });
                group.AllowSameGroup        = true;
                group.MaximumNodeConnection = 1;
                group.Connect();
                _Group = group;
            }
            finally { _Starting.Set(); }
        }
Example #42
0
        public void CanHandshakeWithSeveralTemplateBehaviors()
        {
            using (var builder = NodeBuilderEx.Create())
            {
                var node = builder.CreateNode(true);
                node.Generate(101);
                AddressManager manager = new AddressManager();
                manager.Add(new NetworkAddress(node.NodeEndpoint), IPAddress.Loopback);

                var        chain = new SlimChain(builder.Network.GenesisHash);
                NodesGroup group = new NodesGroup(builder.Network, new NodeConnectionParameters()
                {
                    Services          = NodeServices.Nothing,
                    IsRelay           = true,
                    TemplateBehaviors =
                    {
                        new AddressManagerBehavior(manager)
                        {
                            PeersToDiscover = 1,
                            Mode            = AddressManagerBehaviorMode.None
                        },
                        new SlimChainBehavior(chain),
                        new PingPongBehavior()
                    }
                });
                group.AllowSameGroup        = true;
                group.MaximumNodeConnection = 1;
                var connecting = WaitConnected(group);
                try
                {
                    group.Connect();
                    connecting.GetAwaiter().GetResult();
                    Eventually(() =>
                    {
                        Assert.Equal(101, chain.Height);
                    });
                    var ms = new MemoryStream();
                    chain.Save(ms);

                    var chain2 = new SlimChain(chain.Genesis);
                    ms.Position = 0;
                    chain2.Load(ms);
                    Assert.Equal(chain.Tip, chain2.Tip);

                    using (var fs = new FileStream("test.slim.dat", FileMode.Create, FileAccess.Write, FileShare.None, 1024 * 1024))
                    {
                        chain.Save(fs);
                        fs.Flush();
                    }

                    chain.ResetToGenesis();
                    using (var fs = new FileStream("test.slim.dat", FileMode.Open, FileAccess.Read, FileShare.None, 1024 * 1024))
                    {
                        chain.Load(fs);
                    }
                    Assert.Equal(101, chain2.Height);
                    chain.ResetToGenesis();
                }
                finally
                {
                    group.Disconnect();
                }
            }
        }
Example #43
0
        /// <summary>
        /// Connect the wallet with the given connection parameters
        /// </summary>
        /// <param name="group">The group to use</param>
        public void Connect(NodesGroup group)
        {
            if (group == null)
            {
                throw new ArgumentNullException("group");
            }
            if (State != WalletState.Created)
            {
                throw new InvalidOperationException("The wallet is already connecting or connected");
            }
            var parameters = group.NodeConnectionParameters;

            group.Requirements.MinVersion        = ProtocolVersion.PROTOCOL_VERSION;
            group.Requirements.RequiredServices |= NodeServices.Network;

            var chain = parameters.TemplateBehaviors.Find <ChainBehavior>();

            if (chain == null)
            {
                chain = new ChainBehavior(new ConcurrentChain(_Parameters.Network));
                parameters.TemplateBehaviors.Add(chain);
            }
            if (chain.Chain.Genesis.HashBlock != _Parameters.Network.GetGenesis().GetHash())
            {
                throw new InvalidOperationException("ChainBehavior with invalid network chain detected");
            }

            var addrman = parameters.TemplateBehaviors.Find <AddressManagerBehavior>();

            if (addrman == null)
            {
                addrman = new AddressManagerBehavior(new AddressManager());
                parameters.TemplateBehaviors.Add(addrman);
            }

            var tracker = parameters.TemplateBehaviors.Find <TrackerBehavior>();

            if (tracker == null)
            {
                tracker = new TrackerBehavior(new Tracker(), chain.Chain);
                parameters.TemplateBehaviors.Add(tracker);
            }

            _Chain           = chain.Chain;
            _AddressManager  = addrman.AddressManager;
            _Tracker         = tracker.Tracker;
            _TrackerBehavior = tracker;
            _Group           = group;
            if (AddKnownScriptToTracker())
            {
                _Group.Purge("Bloom filter renew");
            }
            _State = WalletState.Disconnected;
            _Group.Connect();
            _Group.ConnectedNodes.Added   += ConnectedNodes_Added;
            _Group.ConnectedNodes.Removed += ConnectedNodes_Added;
            foreach (var node in _Group.ConnectedNodes)
            {
                node.Behaviors.Find <TrackerBehavior>().Scan(_ScanLocation, Created);
            }
        }
Example #44
0
        public void ShouldSyncBlockChainAgainstLocal()
        {
            var network = new TestNetwork();

            network.AddSeed(new NetworkAddress(new IPEndPoint(IPAddress.Parse("192.168.2.101"), 9999)));

            var p = new TestTransactionPool();

            p.Add("t1", 1);
            p.Add("t2", 0);
            p.Spend("t2", "t1", 0);

            p.Render();

            var genesisBlock = new TestBlock(p.TakeOut("t1").Value);
            var block1       = new TestBlock(p.TakeOut("t2").Value);

            block1.Parent = genesisBlock;

            genesisBlock.Render();
            block1.Render();

            WithBlockChains(1, genesisBlock.Value.Key, blockChains =>
            {
                //	blockChains[0].HandleNewBlock(genesisBlock.Value.Value);
                //	blockChains[0].HandleNewBlock(block1.Value.Value);


                AutoResetEvent waitForConnection = new AutoResetEvent(false);
                bool connected = false;

                blockChains[0].OnAddedToStore += transaction =>
                {
                    Trace.Information("-- Transaction Received (node server)");
                    //	actionReceiver();
                };

                AddressManager addressManager = new AddressManager();
                addressManager.PeersToFind    = 1;
                NodeConnectionParameters nodesGroupParameters = new NodeConnectionParameters();
//				nodesGroupParameters.AddressFrom = servers[1].ExternalEndpoint;
                nodesGroupParameters.TemplateBehaviors.Add(new AddressManagerBehavior(addressManager));
                nodesGroupParameters.TemplateBehaviors.Add(new ChainBehavior(blockChains[0]));
                nodesGroupParameters.TemplateBehaviors.Add(new BroadcastHubBehavior());
                nodesGroupParameters.TemplateBehaviors.Add(new SPVBehavior(blockChains[0], BroadcastHub.GetBroadcastHub(nodesGroupParameters.TemplateBehaviors)));

                NodesGroup nodesGroup            = new NodesGroup(network, nodesGroupParameters);
                nodesGroup.AllowSameGroup        = true;
                nodesGroup.MaximumNodeConnection = 1;
                nodesGroup.ConnectedNodes.Added += (object sender, NodeEventArgs e) =>
                {
                    Trace.Information("-- Node added to node group");
                    connected = true;
                    waitForConnection.Set();
                };
                nodesGroup.Connect();


                Assert.True(waitForConnection.WaitOne(10000));                 //TODO: use reset events instead of sleep
                Assert.True(connected);



                //TODO
                Thread.Sleep(40000);



                //					actionSender(BroadcastHub.GetBroadcastHub(nodesGroup.NodeConnectionParameters));

                Trace.Information("-- Done");
            });
        }
Example #45
0
        public AddressItem Address([System.Web.Http.FromBody] AddressItem addressItem)
        {
            var address = new AddressManager();

            return(address.Add(addressItem));
        }
Example #46
0
        public static async Task InitializeNoWalletAsync()
        {
            WalletService  = null;
            ChaumianClient = null;
            AddressManager = null;
            TorManager     = null;

            #region ConfigInitialization

            Config = new Config(Path.Combine(DataDir, "Config.json"));
            await Config.LoadOrCreateDefaultFileAsync();

            Logger.LogInfo <Config>("Config is successfully initialized.");

            #endregion ConfigInitialization

            BitcoinStore = new BitcoinStore();
            var bstoreInitTask = BitcoinStore.InitializeAsync(Path.Combine(DataDir, "BitcoinStore"), Network);
            var hwiInitTask    = HwiProcessManager.InitializeAsync(DataDir, Network);

            var addressManagerFolderPath = Path.Combine(DataDir, "AddressManager");
            AddressManagerFilePath = Path.Combine(addressManagerFolderPath, $"AddressManager{Network}.dat");
            var blocksFolderPath     = Path.Combine(DataDir, $"Blocks{Network}");
            var connectionParameters = new NodeConnectionParameters();

            if (Config.UseTor.Value)
            {
                Synchronizer = new WasabiSynchronizer(Network, BitcoinStore, () => Config.GetCurrentBackendUri(), Config.GetTorSocks5EndPoint());
            }
            else
            {
                Synchronizer = new WasabiSynchronizer(Network, BitcoinStore, Config.GetFallbackBackendUri(), null);
            }

            UpdateChecker = new UpdateChecker(Synchronizer.WasabiClient);

            #region ProcessKillSubscription

            AppDomain.CurrentDomain.ProcessExit += async(s, e) => await TryDesperateDequeueAllCoinsAsync();

            Console.CancelKeyPress += async(s, e) =>
            {
                e.Cancel = true;
                Logger.LogWarning("Process was signaled for killing.", nameof(Global));

                KillRequested = true;
                await TryDesperateDequeueAllCoinsAsync();

                Dispatcher.UIThread.PostLogException(() =>
                {
                    Application.Current?.MainWindow?.Close();
                });
            };

            #endregion ProcessKillSubscription

            #region TorProcessInitialization

            if (Config.UseTor.Value)
            {
                TorManager = new TorProcessManager(Config.GetTorSocks5EndPoint(), TorLogsFile);
            }
            else
            {
                TorManager = TorProcessManager.Mock();
            }
            TorManager.Start(false, DataDir);

            var fallbackRequestTestUri = new Uri(Config.GetFallbackBackendUri(), "/api/software/versions");
            TorManager.StartMonitor(TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(7), DataDir, fallbackRequestTestUri);

            Logger.LogInfo <TorProcessManager>($"{nameof(TorProcessManager)} is initialized.");

            #endregion TorProcessInitialization

            #region AddressManagerInitialization

            var needsToDiscoverPeers = true;
            if (Network == Network.RegTest)
            {
                AddressManager = new AddressManager();
                Logger.LogInfo <AddressManager>($"Fake {nameof(AddressManager)} is initialized on the RegTest.");
            }
            else
            {
                try
                {
                    AddressManager = AddressManager.LoadPeerFile(AddressManagerFilePath);

                    // The most of the times we don't need to discover new peers. Instead, we can connect to
                    // some of those that we already discovered in the past. In this case we assume that we
                    // assume that discovering new peers could be necessary if out address manager has less
                    // than 500 addresses. A 500 addresses could be okay because previously we tried with
                    // 200 and only one user reported he/she was not able to connect (there could be many others,
                    // of course).
                    // On the other side, increasing this number forces users that do not need to discover more peers
                    // to spend resources (CPU/bandwith) to discover new peers.
                    needsToDiscoverPeers = Config.UseTor == true || AddressManager.Count < 500;
                    Logger.LogInfo <AddressManager>($"Loaded {nameof(AddressManager)} from `{AddressManagerFilePath}`.");
                }
                catch (DirectoryNotFoundException ex)
                {
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} did not exist at `{AddressManagerFilePath}`. Initializing new one.");
                    Logger.LogTrace <AddressManager>(ex);
                    AddressManager = new AddressManager();
                }
                catch (FileNotFoundException ex)
                {
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} did not exist at `{AddressManagerFilePath}`. Initializing new one.");
                    Logger.LogTrace <AddressManager>(ex);
                    AddressManager = new AddressManager();
                }
                catch (OverflowException ex)
                {
                    // https://github.com/zkSNACKs/WalletWasabi/issues/712
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} has thrown `{nameof(OverflowException)}`. Attempting to autocorrect.");
                    File.Delete(AddressManagerFilePath);
                    Logger.LogTrace <AddressManager>(ex);
                    AddressManager = new AddressManager();
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} autocorrection is successful.");
                }
                catch (FormatException ex)
                {
                    // https://github.com/zkSNACKs/WalletWasabi/issues/880
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} has thrown `{nameof(FormatException)}`. Attempting to autocorrect.");
                    File.Delete(AddressManagerFilePath);
                    Logger.LogTrace <AddressManager>(ex);
                    AddressManager = new AddressManager();
                    Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} autocorrection is successful.");
                }
            }

            var addressManagerBehavior = new AddressManagerBehavior(AddressManager)
            {
                Mode = needsToDiscoverPeers ? AddressManagerBehaviorMode.Discover : AddressManagerBehaviorMode.None
            };
            connectionParameters.TemplateBehaviors.Add(addressManagerBehavior);

            #endregion AddressManagerInitialization

            #region MempoolInitialization

            MemPoolService = new MemPoolService();
            connectionParameters.TemplateBehaviors.Add(new MemPoolBehavior(MemPoolService));

            #endregion MempoolInitialization

            #region HwiProcessInitialization

            try
            {
                await hwiInitTask;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, nameof(Global));
            }

            #endregion HwiProcessInitialization

            #region BitcoinStoreInitialization

            await bstoreInitTask;

            #endregion BitcoinStoreInitialization

            #region P2PInitialization

            if (Network == Network.RegTest)
            {
                Nodes = new NodesGroup(Network, requirements: Constants.NodeRequirements);
                try
                {
                    Node node = await Node.ConnectAsync(Network.RegTest, new IPEndPoint(IPAddress.Loopback, 18444));

                    Nodes.ConnectedNodes.Add(node);

                    RegTestMemPoolServingNode = await Node.ConnectAsync(Network.RegTest, new IPEndPoint(IPAddress.Loopback, 18444));

                    RegTestMemPoolServingNode.Behaviors.Add(new MemPoolBehavior(MemPoolService));
                }
                catch (SocketException ex)
                {
                    Logger.LogError(ex, nameof(Global));
                }
            }
            else
            {
                if (Config.UseTor is true)
                {
                    // onlyForOnionHosts: false - Connect to clearnet IPs through Tor, too.
                    connectionParameters.TemplateBehaviors.Add(new SocksSettingsBehavior(Config.GetTorSocks5EndPoint(), onlyForOnionHosts: false, networkCredential: null, streamIsolation: true));
                    // allowOnlyTorEndpoints: true - Connect only to onions and don't connect to clearnet IPs at all.
                    // This of course makes the first setting unneccessary, but it's better if that's around, in case someone wants to tinker here.
                    connectionParameters.EndpointConnector = new DefaultEndpointConnector(allowOnlyTorEndpoints: Network == Network.Main);

                    await AddKnownBitcoinFullNodeAsHiddenServiceAsync(AddressManager);
                }
                Nodes = new NodesGroup(Network, connectionParameters, requirements: Constants.NodeRequirements);

                RegTestMemPoolServingNode = null;
            }

            Nodes.Connect();
            Logger.LogInfo("Start connecting to nodes...");

            if (RegTestMemPoolServingNode != null)
            {
                RegTestMemPoolServingNode.VersionHandshake();
                Logger.LogInfo("Start connecting to mempool serving regtest node...");
            }

            #endregion P2PInitialization

            #region SynchronizerInitialization

            var requestInterval = TimeSpan.FromSeconds(30);
            if (Network == Network.RegTest)
            {
                requestInterval = TimeSpan.FromSeconds(5);
            }

            int maxFiltSyncCount = Network == Network.Main ? 1000 : 10000;             // On testnet, filters are empty, so it's faster to query them together

            Synchronizer.Start(requestInterval, TimeSpan.FromMinutes(5), maxFiltSyncCount);
            Logger.LogInfo("Start synchronizing filters...");

            #endregion SynchronizerInitialization

            Initialized = true;
        }
        public String ApplyBudgetTemplate(Budget budget, Int32 budgetDocumentTemplateId)
        {
            var addressManager = new AddressManager(this);

            DocumentTemplate documentTemplate = new CompanyManager(this).GetDocumentTemplate(budgetDocumentTemplateId);

            string template = documentTemplate == null ? GetTempBudgetTemplate() : documentTemplate.Content;
            bool isRtf = documentTemplate.FileName.EndsWith("rtf", StringComparison.OrdinalIgnoreCase);

            var stringBuilder = new StringBuilder(template);
            var tempStringBuilder = new StringBuilder();

            if (budget.BudgetItems == null)
                budget = GetBudget(budget.BudgetId, budget.CompanyId);

            stringBuilder.Replace("[NumeroDoOrcamento]", budget.BudgetCode);
            stringBuilder.Replace("[DataEmissao]", budget.ModifiedDate.ToShortDateString() +
                (isRtf ? "<br />".ToRtf() : "<br />"));

            //header with informations of current date 
            string header = budget.Company.LegalEntityProfile.Address.State + " , " + DateTime.Now.ToLongDateString().Split(',').ElementAt(1);
            stringBuilder.Replace("[Cabecalho]", header);



            #region CompanyInformations

            stringBuilder.Replace("[NomeDaEmpresa]", budget.Company.LegalEntityProfile.CompanyName);
            stringBuilder.Replace("[TelefoneDaEmpresa]", budget.Company.LegalEntityProfile.Phone);

            stringBuilder.Replace("[Endereco-Empresa]", budget.Company.LegalEntityProfile.Address.Name.ToCapitalize());

            stringBuilder.Replace("[Endereco-Complemento-Empresa]", String.Empty);

            if (!String.IsNullOrEmpty(budget.Company.LegalEntityProfile.AddressComp))
                stringBuilder.Replace("[Endereco-Complemento-Empresa]", budget.Company.LegalEntityProfile.AddressComp.ToCapitalize());

            stringBuilder.Replace("[Endereco-Numero-Empresa]", budget.Company.LegalEntityProfile.AddressNumber);
            stringBuilder.Replace("[Endereco-Cep-Empresa]", budget.Company.LegalEntityProfile.PostalCode);
            stringBuilder.Replace("[Endereco-Cidade-Empresa]", budget.Company.LegalEntityProfile.Address.City.ToCapitalize());
            stringBuilder.Replace("[Endereco-Estado-Empresa]", addressManager.GetAcronymState(budget.Company.LegalEntityProfile.Address.State));
            stringBuilder.Replace("[Endereco-Bairro-Empresa]", budget.Company.LegalEntityProfile.Address.Neighborhood.ToCapitalize());

            #endregion

            //Customer
            if (budget.CustomerId.HasValue || !String.IsNullOrEmpty(budget.CustomerName))
            {
                #region Customer Data

                stringBuilder.Replace("[NomeDoCliente]", String.IsNullOrEmpty(budget.CustomerName)
                                                             ? budget.Customer.Name
                                                             : budget.CustomerName);

                stringBuilder.Replace("[EmailDoClente]", budget.Customer != null
                                                             ? budget.Customer.Email
                                                             : budget.CustomerMail);

                stringBuilder.Replace("[TelefoneDoCliente]", String.IsNullOrEmpty(budget.CustomerPhone)
                                                                 ? budget.Customer.Phone
                                                                 : budget.CustomerPhone);

                #endregion



                if (budget.Customer != null)
                {
                    #region Customer Address

                    if (budget.Customer.Address != null)
                    {
                        stringBuilder.Replace("[EnderecoDoCliente]", String.Empty);

                        if (!String.IsNullOrEmpty(budget.Customer.Address.Name))
                            stringBuilder.Replace("[EnderecoDoCliente]", budget.Customer.Address.Name.ToCapitalize());

                        stringBuilder.Replace("[Endereco-Complemento]", String.Empty);

                        if (!String.IsNullOrEmpty(budget.Customer.AddressComp))
                            stringBuilder.Replace("[Endereco-Complemento]", budget.Customer.AddressComp.ToCapitalize());

                        stringBuilder.Replace("[Endereco-Bairro]", String.Empty);

                        if (!String.IsNullOrEmpty(budget.Customer.Address.Neighborhood))
                            stringBuilder.Replace("[Endereco-Bairro]", budget.Customer.Address.Neighborhood.ToCapitalize());

                        stringBuilder.Replace("[Endereco-Cidade]", String.Empty);

                        if (!String.IsNullOrEmpty(budget.Customer.Address.City))
                            stringBuilder.Replace("[Endereco-Cidade]", budget.Customer.Address.City.ToCapitalize());

                        stringBuilder.Replace("[Endereco-Numero]", String.Empty);

                        if (!String.IsNullOrEmpty(budget.Customer.AddressNumber))
                            stringBuilder.Replace("[Endereco-Numero]", budget.Customer.AddressNumber);

                        stringBuilder.Replace("[Endereco-Cep]", String.Empty);

                        if (!String.IsNullOrEmpty(budget.Customer.Address.PostalCode))
                            stringBuilder.Replace("[Endereco-Cep]", budget.Customer.Address.PostalCode);

                        stringBuilder.Replace("[Endereco-Estado]", addressManager.GetAcronymState(budget.Company.LegalEntityProfile.Address.State));
                    }

                    #endregion


                    string phone2 = "", phone3 = "";
                    if (budget.Customer.LegalEntityProfile != null)
                    {
                        phone2 = budget.Customer.LegalEntityProfile.Phone2;
                        phone3 = budget.Customer.LegalEntityProfile.Phone3;
                    }

                    stringBuilder.Replace("[Telefone2]", phone2);
                    stringBuilder.Replace("[Telefone3]", phone3);



                    stringBuilder.Replace("[CNPJ]", budget.Customer.LegalEntityProfile != null
                                                        ? "CNPJ: " + budget.Customer.LegalEntityProfile.CNPJ
                                                        : String.Empty);

                    stringBuilder.Replace("[CPF]", budget.Customer.Profile != null
                                                       ? "CPF: " + budget.Customer.Profile.CPF
                                                       : String.Empty);

                    stringBuilder.Replace("[IE]", budget.Customer.LegalEntityProfile != null
                                                      ? "IE: " + budget.Customer.LegalEntityProfile.IE
                                                      : String.Empty);

                    stringBuilder.Replace("[RG]", budget.Customer.Profile != null
                                                      ? "RG: " + budget.Customer.Profile.RG
                                                      : String.Empty);
                }
                else
                {
                    stringBuilder.Replace("[EnderecoDoCliente]", String.Empty);
                    stringBuilder.Replace("[Endereco-Complemento]", String.Empty);
                    stringBuilder.Replace("[Endereco-Numero]", String.Empty);
                    stringBuilder.Replace("[Endereco-Cep]", String.Empty);
                    stringBuilder.Replace("[Endereco-Cidade]", String.Empty);
                    stringBuilder.Replace("[Endereco-Estado]", String.Empty);
                    stringBuilder.Replace("[Telefone2]", String.Empty);
                    stringBuilder.Replace("[Telefone3]", String.Empty);
                }
            }

            #region BudgetItems

            tempStringBuilder = new StringBuilder();

            //Header


            //Body
            Int32 itemCount = 0;
            Decimal totalValue = Decimal.Zero;
            foreach (BudgetItem item in GetBudgetItemByBudget(budget.BudgetId, budget.CompanyId))
            {
                itemCount++;

                string itemName = item.SpecialProductName;

                tempStringBuilder.AppendFormat(@"
				<fieldset>
					<table>
						<tr>
							<td style='white-space:nowrap; width:1%;' width='1%'>Código:</td>
							<td class='code' colspan='2'>{0}</td>
						</tr>
						<tr>
							<td style='white-space:nowrap'>Qtd:</td>
							<td class='qtd' colspan='2'>{1}</td>
						</tr>
						<tr>
							<td style='white-space:nowrap'>Desc:</td>
							<td class='description' colspan='2'>{2}</td>
						</tr>
						<tr>
							<td style='white-space:nowrap'>Vlr Unit:</td>
							<td>{3}</td>
							<td style='text-align:right'>Valor: {4}</td>
						</tr>
					</table>
				</fieldset>", item.ProductCode + " | " + itemName,
                              item.Quantity,
                              item.ProductDescription,
                              item.UnitPrice.Value.ToString("c"),
                              (item.Quantity * item.UnitPrice.Value).ToString("c"));

                totalValue += (item.Quantity * item.UnitPrice.Value);
            }

            // Subtotal
            tempStringBuilder.AppendFormat(@"<table width='100%'><tr>
											 <td style='white-space:nowrap'><b>Subtotal (R$):&nbsp;</b></td>
											 <td style='white-space:nowrap; text-align:right'>{0}<td>
											 </tr>", totalValue);

            // AdditionalCost
            if (budget.AdditionalCost.HasValue)
            {
                tempStringBuilder.AppendFormat(@"<tr>
												 <td style='white-space:nowrap'><b>Adicional (R$):&nbsp;</b></td>
												 <td style='white-space:nowrap; text-align:right'>{0}<td>
												 </tr>", budget.AdditionalCost.Value.ToString("c"));
                totalValue += budget.AdditionalCost.Value;
            }

            // Discount
            if (budget.Discount.HasValue)
            {
                tempStringBuilder.AppendFormat(@"<tr>
												 <td style='white-space:nowrap'><b>Desconto (R$):&nbsp;</b></td>
												 <td style='white-space:nowrap; text-align:right'>{0}<td>
												 </tr>", budget.Discount.Value.ToString("c"));
                totalValue -= budget.Discount.Value;
            }

            //Footer
            tempStringBuilder.AppendFormat(@"<tr>
													<td style='white-space:nowrap'><b>Valor Total da Proposta (R$):&nbsp;&nbsp;&nbsp;</b></td>		
													<td style='white-space:nowrap; text-align:right'>&nbsp;&nbsp;<b>{0}<b></td>
												</tr>
												<tr>
													<td style='white-space:nowrap;  text-align:center' colspan='2'><b>({1})<b></td>
												</tr>
											</table>", totalValue.ToString("c"), totalValue.AtFull().ToUpper());

            stringBuilder.Replace("[Items]", isRtf ? tempStringBuilder.ToString().ToRtf() : tempStringBuilder.ToString());

            stringBuilder.Replace("[TotalDaProposta]", totalValue.ToString());
            stringBuilder.Replace("[ValorTotalPorExtenso]", totalValue.AtFull().ToUpper());

            #endregion

            #region Others

            stringBuilder.Replace("[Contato]", budget.ContactName);
            stringBuilder.Replace("[DataEntrega]", budget.DeliveryDate);
            stringBuilder.Replace("[Garantia]", budget.Warranty);

            stringBuilder.Replace("[Validade]", budget.ExpirationDate.ToString());
            stringBuilder.Replace("[FormaPagamento]", budget.PaymentMethod);
            stringBuilder.Replace("[Observacao]", budget.Observation);

            stringBuilder.Replace("[Vendedor]", budget.Employee.Profile.AbreviatedName);
            stringBuilder.Replace("[EmailVendedor]", budget.Employee.Profile.Email);
            stringBuilder.Replace("[FormaEntrega]", budget.DeliveryDescription);
            stringBuilder.Replace("[Pintura/Tratamento]", budget.Treatment);

            #endregion


            return stringBuilder.ToString();
        }