Beispiel #1
0
        private static void Main(string[] args)
        {
            Task.Run(() =>
            {
                try
                {
                    // initialize settings
                    Init();

                    Console.WriteLine($"Take it easy, the console will display important messages, actually, it's running!! :)");

                    ConnectionFactory factory = new ConnectionFactory();
                    factory.UserName          = Settings.RabbitMQUsername;
                    factory.Password          = Settings.RabbitMQPassword;
                    factory.HostName          = Settings.RabbitMQHostname;
                    factory.Port = Settings.RabbitMQPort;
                    factory.RequestedHeartbeat     = 60;
                    factory.DispatchConsumersAsync = true;

                    var connection = factory.CreateConnection();
                    var channel    = connection.CreateModel();

                    channel.QueueDeclare(queue: Settings.ContractDeploymentQueueName,
                                         durable: true,
                                         exclusive: false,
                                         autoDelete: false,
                                         arguments: null);

                    channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);

                    var consumer       = new AsyncEventingBasicConsumer(channel);
                    consumer.Received += async(model, ea) =>
                    {
                        ContractDeploymentResult result = new ContractDeploymentResult
                        {
                            IsSucceded = true,
                            ResultId   = (int)ContractDeploymentResultEnum.Success
                        };

                        // forced-to-disposal
                        TransactionReceipt receipt = null;
                        Contract contract          = null;
                        ContractDeploymentDataHelper contractDeploymentDataHelper = null;

                        try
                        {
                            byte[] body = ea.Body;

                            var message = Encoding.UTF8.GetString(body);

                            var decrypted = string.Empty;
                            decrypted     = NETCore.Encrypt.EncryptProvider.AESDecrypt(message, secret);

                            var obj_decrypted = JsonConvert.DeserializeObject <ContractDeploymentMessage>(decrypted);

                            Console.WriteLine($">> Contract ABI: {blockchainInfo.ContractABI}");
                            Console.WriteLine($">> Contract ByteCode: {blockchainInfo.ContractByteCode}");
                            Console.WriteLine($">> Master Address: {blockchainInfo.MasterAddress}");

                            var gasDeploy = await web3.Eth.DeployContract.EstimateGasAsync(blockchainInfo.ContractABI, blockchainInfo.ContractByteCode, blockchainInfo.MasterAddress, new object[] { });
                            Console.WriteLine($">> Deploying contract using: {gasDeploy.Value} gas");

                            var transaction_hash = await web3.Eth.DeployContract.SendRequestAsync(blockchainInfo.ContractByteCode, blockchainInfo.MasterAddress, gasDeploy, new HexBigInteger(0));
                            Console.WriteLine($">> Transaction hash processed: {transaction_hash}");

                            contract = new Contract()
                            {
                                name             = obj_decrypted.name,
                                description      = obj_decrypted.description,
                                address          = string.Empty,
                                status           = string.Empty,
                                transaction_hash = transaction_hash
                            };

                            contractDeploymentDataHelper = new ContractDeploymentDataHelper(mongoDBConnectionInfo);

                            await contractDeploymentDataHelper.RegisterContractAsync(contract);
                            Console.WriteLine($">> Contract registered successfully in database");

                            receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transaction_hash);

                            while (receipt == null)
                            {
                                Console.WriteLine($">> Receipt not ready for contract transaction hash: {transaction_hash}");
                                Thread.Sleep(1000);
                                receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transaction_hash);
                            }

                            if (receipt.Status.Value != null)
                            {
                                var status = StatusString(receipt.Status.Value);

                                contractDeploymentDataHelper = new ContractDeploymentDataHelper(mongoDBConnectionInfo);
                                contract = contractDeploymentDataHelper.GetContract(transaction_hash);

                                contract.address = receipt.ContractAddress;
                                contract.status  = status;
                                await contractDeploymentDataHelper.UpdateContractAsync(contract);
                                Console.WriteLine($">> Contract updated successfully: {transaction_hash}");

                                channel.BasicAck(ea.DeliveryTag, false);
                                Console.WriteLine($">> Acknowledgement completed, delivery tag: {ea.DeliveryTag}");
                            }
                        }
                        catch (Exception ex)
                        {
                            if (ex is BusinessException)
                            {
                                result.IsSucceded = false;
                                result.ResultId   = ((BusinessException)ex).ResultId;

                                string message = EnumDescription.GetEnumDescription((ContractDeploymentResultEnum)result.ResultId);
                                Console.WriteLine($">> Message information: {message}");
                            }
                            else
                            {
                                web3 = new Web3(account, new RpcClient(new Uri(blockchainInfo.RPCUrl), null, null, new HttpClientHandler()
                                {
                                    MaxConnectionsPerServer = 10, UseProxy = false
                                }));

                                Console.WriteLine($">> Exception: {ex.Message}, StackTrace: {ex.StackTrace}");

                                if (ex.InnerException != null)
                                {
                                    Console.WriteLine($">> Inner Exception Message: {ex.InnerException.Message}, Inner Exception StackTrace: {ex.InnerException.StackTrace}");
                                }
                            }
                        }
                        finally
                        {
                            receipt  = null;
                            contract = null;
                            contractDeploymentDataHelper.Dispose();
                        }
                    };

                    String consumerTag = channel.BasicConsume(Settings.ContractDeploymentQueueName, false, consumer);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($">> Exception: {ex.Message}, StackTrace: {ex.StackTrace}");

                    if (ex.InnerException != null)
                    {
                        Console.WriteLine($">> Inner Exception Message: {ex.InnerException.Message}, Inner Exception StackTrace: {ex.InnerException.StackTrace}");
                    }
                }
            });

            // handle Control+C or Control+Break
            Console.CancelKeyPress += (o, e) =>
            {
                Console.WriteLine("Exit");

                // allow the manin thread to continue and exit...
                waitHandle.Set();
            };

            // wait
            waitHandle.WaitOne();
        }
        public async Task <IActionResult> Post([FromBody] ContractDeploymentRequest model)
        {
            // non-forced-to-disposal
            ContractDeploymentResult result = new ContractDeploymentResult
            {
                IsSucceded = true,
                ResultId   = (int)ContractDeploymentResultEnum.Success
            };

            // forced-to-disposal
            KeyVaultConnectionInfo keyVaultConnectionInfo = null;

            try
            {
                if (string.IsNullOrEmpty(model.Name))
                {
                    throw new BusinessException((int)ContractDeploymentResultEnum.FailedEmptyName);
                }

                if (string.IsNullOrEmpty(model.Description))
                {
                    throw new BusinessException((int)ContractDeploymentResultEnum.FailedEmptyDescription);
                }

                keyVaultConnectionInfo = new KeyVaultConnectionInfo()
                {
                    CertificateName    = Settings.KeyVaultCertificateName,
                    ClientId           = Settings.KeyVaultClientId,
                    ClientSecret       = Settings.KeyVaultClientSecret,
                    KeyVaultIdentifier = Settings.KeyVaultIdentifier
                };

                using (MessageQueueHelper messageQueueHelper = new MessageQueueHelper())
                {
                    ContractDeploymentMessage contractDeploymentMessage = new ContractDeploymentMessage()
                    {
                        name        = model.Name,
                        description = model.Description
                    };

                    await messageQueueHelper.QueueMessageAsync(contractDeploymentMessage, Settings.ContractDeploymentQueueName, keyVaultConnectionInfo);
                }
            }
            catch (Exception ex)
            {
                result.IsSucceded = false;

                if (ex is BusinessException)
                {
                    result.ResultId = ((BusinessException)ex).ResultId;
                }
                else
                {
                    result.ResultId = (int)ContractDeploymentResultEnum.Failed;

                    this.logger.LogError($">> Exception: {ex.Message}, StackTrace: {ex.StackTrace}");

                    if (ex.InnerException != null)
                    {
                        this.logger.LogError($">> Inner Exception Message: {ex.InnerException.Message}, Inner Exception StackTrace: {ex.InnerException.StackTrace}");
                    }
                }
            }
            finally
            {
                keyVaultConnectionInfo = null;

                GC.Collect();
            }

            string message = EnumDescription.GetEnumDescription((ContractDeploymentResultEnum)result.ResultId);

            this.logger.LogInformation($">> Message information: {message}");

            return((result.IsSucceded) ? (ActionResult) new OkObjectResult(new { message = message }) : (ActionResult) new BadRequestObjectResult(new { message = message }));
        }