Пример #1
0
        private void ExecuteNonQuery(string command, string connectionString, object parameters = null)
        {
            using var connection = new NpgsqlConnection(connectionString);
            RetryUtils.Exec(() => connection.Open());

            connection.Execute(command, param: parameters);
        }
Пример #2
0
        private Node CreateNodeDb(Node node)
        {
            using var connection = new NpgsqlConnection(connectionString);
            RetryUtils.Exec(() => connection.Open());
            using var transaction = connection.BeginTransaction();

            string insertOrUpdate =
                "INSERT INTO Node " +
                "  (host, port, username, password, nodestatus, remarks) " +
                "  VALUES (@host, @port, @username, @password, @nodestatus, @remarks)" +
                "  ON CONFLICT (host, port) DO NOTHING " +
                "  RETURNING *"
            ;

            var now = clock.UtcNow();

            var insertedNode = connection.Query <Node>(insertOrUpdate,
                                                       new
            {
                host       = node.Host.ToLower(),
                port       = node.Port,
                username   = node.Username,
                password   = node.Password,
                nodestatus = node.Status,
                remarks    = node.Remarks
            },
                                                       transaction
                                                       ).SingleOrDefault();

            transaction.Commit();

            return(insertedNode);
        }
        private NpgsqlConnection GetDbConnection()
        {
            var connection = new NpgsqlConnection(connectionString);

            RetryUtils.Exec(() => connection.Open());

            return(connection);
        }
        public static void EmptyRepository(string connectionString)
        {
            using var connection = new NpgsqlConnection(connectionString);
            RetryUtils.Exec(() => connection.Open());
            string cmdText =
                "TRUNCATE Tx, Block, TxMempoolDoubleSpendAttempt, TxBlockDoubleSpend, TxBlock, TxInput";

            connection.Execute(cmdText, null);
        }
Пример #5
0
        public void CreateVersionTable(string connectionString)
        {
            using var connection = new NpgsqlConnection(connectionString);
            RetryUtils.Exec(() => connection.Open());

            string createVersionTable = @"
      CREATE TABLE Version (
		      versionId		SERIAL		NOT NULL,
		      projectName		VARCHAR(256) NOT NULL,
		      updating			INTEGER			NOT NULL,
	       creationDate			TIMESTAMP NOT NULL,
	
		      PRIMARY KEY (versionid)
      );
      ALTER TABLE Version ADD CONSTRAINT version_versionIdAndProjectName UNIQUE (versionId,projectName);";

            connection.Execute(createVersionTable, null);
        }
Пример #6
0
        public void ExecuteFileScript(string connectionString, string filepath, System.Text.Encoding encoding, int commandTimeout, bool createDB = false)
        {
            using var connection = new NpgsqlConnection(connectionString);
            string command = File.ReadAllText(filepath, encoding);

            RetryUtils.Exec(() => connection.Open());

            if (createDB) // create database cannot run inside a transaction block
            {
                connection.Execute(command, commandTimeout: commandTimeout);
            }
            else
            {
                using var transaction = connection.BeginTransaction();
                connection.Execute(command, transaction: transaction, commandTimeout: commandTimeout);
                transaction.Commit();
            }
        }
Пример #7
0
        public void GetCurrentVersion(string projectName, string connectionString, out int currentVersion, out bool updating)
        {
            using var connection = new NpgsqlConnection(connectionString);

            try
            {
                // check if Version table exists (it is possible, that user doesn't have rights to access user_tables
                if (ExistsVersionTable(connectionString))
                {
                    RetryUtils.Exec(() => connection.Open());
                    string selectCommand = $"SELECT max(versionid) versionid, max(updating) updating FROM Version WHERE upper(projectname) = upper('{ projectName }') group by versionid having max(versionid) = (select max(versionid) from Version WHERE upper(projectname) = upper('{ projectName }'))";
                    var    version       = connection.QueryFirstOrDefault <Version>(selectCommand);

                    if (version == null)
                    {
                        // Version table has no rows
                        currentVersion = -1;
                        updating       = false;
                    }
                    else
                    {
                        currentVersion = version.VersionId;
                        updating       = version.Updating == 1;
                    }
                }
                else
                {
                    // Version table does not exist
                    currentVersion = -1;
                    updating       = false;
                }
            }
            catch (Exception e)
            {
                currentVersion = -1;
                updating       = false;
                throw e;
            }
        }
        /// <summary>
        /// Deletes node data directory (if exists) and start new instance of bitcoind
        /// </summary>
        public BitcoindProcess(string hostIp, string bitcoindFullPath, string dataDir, int p2pPort, int rpcPort, string zmqIp, int zmqPort, ILoggerFactory loggerFactory, bool emptyDataDir = true)
        {
            this.Host        = hostIp;
            this.P2Port      = p2pPort;
            this.RpcPort     = rpcPort;
            this.RpcUser     = "******";
            this.RpcPassword = "******";
            this.ZmqIp       = zmqIp;
            this.ZmqPort     = zmqPort;
            this.logger      = loggerFactory.CreateLogger <BitcoindProcess>();


            if (!ArePortsAvailable(p2pPort, rpcPort))
            {
                throw new Exception(
                          "Can not start a new instance of bitcoind. Specified ports are already in use. There might be an old version of bitcoind still running. Terminate it manually and try again-");
            }

            if (emptyDataDir)
            {
                if (Directory.Exists(dataDir))
                {
                    var regtest = Path.Combine(dataDir, "regtest");
                    if (Directory.Exists(regtest))
                    {
                        logger.LogInformation($"Old regtest directory exists. Removing it: {regtest}");
                        Directory.Delete(regtest, true);
                    }
                }
                else
                {
                    Directory.CreateDirectory(dataDir);
                }
            }
            else
            {
                if (!Directory.Exists(dataDir))
                {
                    throw new Exception("Data directory does not exists. Can not start new instance of bitcoind");
                }
            }


            // use StartupInfo.ArgumentList instead of StartupInfo.Arguments to avoid problems with spaces in data dir
            var argumentList = new List <string>(defaultParams.Split(" ").ToList());

            argumentList.Add($"-port={p2pPort}");
            argumentList.Add($"-rpcport={rpcPort}");
            argumentList.Add($"-datadir={dataDir}");
            argumentList.Add($"-rpcuser={RpcUser}");
            argumentList.Add($"-rpcpassword={RpcPassword}");
            argumentList.Add($"-zmqpubhashblock=tcp://{ZmqIp}:{zmqPort}");
            argumentList.Add($"-zmqpubinvalidtx=tcp://{ZmqIp}:{zmqPort}");
            argumentList.Add($"-zmqpubdiscardedfrommempool=tcp://{ZmqIp}:{zmqPort}");
            argumentList.Add($"-invalidtxsink=ZMQ");

            logger.LogInformation($"Starting {bitcoindFullPath} {string.Join(" ",argumentList.ToArray())}");

            var localProcess = new Process();
            var startInfo    = new ProcessStartInfo(bitcoindFullPath);

            foreach (var arg in argumentList)
            {
                startInfo.ArgumentList.Add(arg);
            }

            localProcess.StartInfo = startInfo;
            try
            {
                if (!localProcess.Start())
                {
                    throw new Exception($"Can not invoke {bitcoindFullPath}");
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"Can not invoke {bitcoindFullPath}. {ex.Message}", ex);
            }

            this.process = localProcess;
            string bestBlockhash = null;


            var rpcClient = new RpcClient(RpcClientFactory.CreateAddress(Host, rpcPort),
                                          new System.Net.NetworkCredential(RpcUser, RpcPassword), loggerFactory.CreateLogger <RpcClient>());

            try
            {
                RetryUtils.Exec(() => { bestBlockhash = rpcClient.GetBestBlockHashAsync().Result; }, 10, 100);
            }
            catch (Exception e)
            {
                logger.LogError($"Can not connect to test node {e.Message}");
                throw new Exception($"Can not connect to test node", e);
            }

            this.RpcClient = rpcClient;
            if (emptyDataDir)
            {
                var height = rpcClient.GetBlockHeaderAsync(bestBlockhash).Result.Height;
                if (height != 0)
                {
                    throw new Exception(
                              "The node that was just started does not have an empty chain. Can not proceed. Terminate the instance manually. ");
                }
            }

            logger.LogInformation($"Started bitcoind process pid={localProcess.Id } rpcPort={rpcPort}, p2pPort={P2Port}, dataDir={dataDir}");
        }