public TokenSaleContract(
     Web3 web3,
     IOptions <EthSettings> options,
     IFileRepository files,
     IOptions <GoogleDriveSettings> gdriveOptions,
     ILogger <TokenSaleContract> logger,
     IMemoryCache memoryCache)
 {
     _logger      = logger;
     _settings    = options.Value;
     _web3        = web3;
     _memoryCache = memoryCache;
     //string contentRootPath = hostingEnvironment.WebRootPath;
     using (var stream = new MemoryStream())
     {
         files.GetFileByName(gdriveOptions.Value.SaleContractFileName, stream);
         stream.Seek(0, SeekOrigin.Begin);
         (_saleContract, _saleContractABI) = LoadContractFromMetadata(web3, _settings.Network.ToString(), stream);
     }
     using (var stream = new MemoryStream())
     {
         files.GetFileByName(gdriveOptions.Value.TokenContractFileName, stream);
         stream.Seek(0, SeekOrigin.Begin);
         (_tokenContract, _) = LoadContractFromMetadata(web3, _settings.Network.ToString(), stream);
     }
 }
 public EthDepositsHistoryProvider(
     IBlockchainsProvider blockchainsProvider,
     EthSettings settings,
     AddressNormalizer addressNormalizer)
 {
     _addressNormalizer = addressNormalizer;
     _samuraiClient     = new SamuraiClient(settings.SamuraiUrl);
     _ethereum          = blockchainsProvider.GetEthereum();
 }
Exemple #3
0
        public EthHelper(EthSettings ethSettings, IEthClient ethClient, ILogger logger)
        {
            Guard.Argument(ethSettings, nameof(ethSettings)).NotNull();
            Guard.Argument(ethClient, nameof(ethClient)).NotNull();
            Guard.Argument(logger, nameof(logger)).NotNull();

            _ethSettings = ethSettings;
            _ethClient   = ethClient;
            _logger      = logger;
        }
        public ExchangerController(ApplicationDbContext dbContext, Web3 web3, IOptions <EthSettings> options, IHostingEnvironment hostingEnvironment)
        {
            _dbContext = dbContext;
            _web3      = web3;
            _options   = options.Value;

            string  contentRootPath = hostingEnvironment.WebRootPath;
            var     JSON            = System.IO.File.ReadAllText(contentRootPath + "/static/abi/CWTPTokenSale.json");
            dynamic jObject         = JsonConvert.DeserializeObject <dynamic>(JSON);

            _abi             = jObject.abi.ToString();
            _byteCode        = jObject.bytecode.ToString();
            _contractAddress = jObject.networks[_options.Network.ToString()].address;
        }
Exemple #5
0
 public ExchangerController(
     ApplicationDbContext dbContext,
     TokenSaleContract contract,
     IRateStore rateStore,
     IOptions <EthSettings> options,
     Crypto crypto,
     IEmailSender emailSender)
 {
     _dbContext   = dbContext;
     _contract    = contract;
     _options     = options.Value;
     _rateStore   = rateStore;
     _crypto      = crypto;
     _emailSender = emailSender;
 }
Exemple #6
0
        public EthService(IOptions <EthSettings> options, ICryptoService crypto, ILogger <EthService> logger)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            _logger = logger;
            _crypto = crypto ?? throw new ArgumentNullException(nameof(crypto));
            _opts   = options.Value;
            var account    = new Account(_opts.AppPrivateKey);
            var uri        = new Uri(_opts.NodeUrl ?? "http://localhost:8545");
            var authHeader = Convert.ToBase64String(Encoding.UTF8.GetBytes(uri.UserInfo));

            _client = new RpcClient(uri, new AuthenticationHeaderValue("Basic", authHeader));
            _web3   = new Web3(account, _client);

            var json = File.ReadAllText("Exchanger.json");

            _json = JsonConvert.DeserializeObject <JsonModel>(json);
        }
Exemple #7
0
        public void ConfigureServices(IServiceCollection services)
        {
            var origins = Configuration.GetValueAsArray("AllowedOrigins", ",");

            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder.WithOrigins(origins)
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

            services.AddControllers();

            Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration).CreateLogger();
            services.AddSingleton(Log.Logger);

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <ISystemDateTime, SystemDateTime>();

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(jwtOptions =>
            {
                jwtOptions.Authority = Configuration.GetValue("Authentication:Authority");
                jwtOptions.Events    = new JwtBearerEvents {
                };
                jwtOptions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidAudiences = Configuration.GetValueAsList("Authentication:Audiences", ","),
                    ValidIssuers   = Configuration.GetValueAsList("Authentication:Issuers", ","),
                };
            });

            var storageAccountConnectionString = Configuration.GetConnectionString("StorageAccount");

            services.AddSingleton <ITimestampQueueService>(new TimestampQueueService(storageAccountConnectionString, Log.Logger));

            var endpointUrl      = Configuration.GetValue("TransationDbEndpointUrl");
            var authorizationKey = Configuration.GetValue("TransationDbAuthorizationKey");

            services.AddSingleton <ITimestampRepository>(new TimestampRepository(endpointUrl, authorizationKey));
            services.AddSingleton <IUserRepository>(new UserRepository(endpointUrl, authorizationKey));
            services.AddSingleton <IKeyRepository>(new KeyRepository(endpointUrl, authorizationKey));
            services.AddSingleton <IPricePlanRepository>(new PricePlanRepository(endpointUrl, authorizationKey));
            services.AddSingleton <IAddressNonceRepository>(new AddressNonceRepository(endpointUrl, authorizationKey));
            services.AddSingleton <IPaymentRepository>(new PaymentRepository(endpointUrl, authorizationKey));
            services.AddSingleton <IPendingMembershipChangeRepository>(new PendingMembershipChangeRepository(endpointUrl, authorizationKey));
            services.AddSingleton <IInvoiceNumberRepository>(new InvoiceNumberRepository(endpointUrl, authorizationKey));

            var client = new SmtpClient(Configuration.GetValue("SMTPEmail:HostName"), int.Parse(Configuration.GetValue("SMTPEmail:Port")))
            {
                UseDefaultCredentials = false,
                Credentials           = new NetworkCredential(Configuration.GetValue("SMTPEmail:UserName"), Configuration.GetValue("SMTPEmailPassword")),
                DeliveryMethod        = SmtpDeliveryMethod.Network,
                EnableSsl             = true
            };

            services.AddSingleton <IEmailService>(new EmailService(client, Log.Logger));
            services.AddSingleton <IEthClient, EthClient>();
            services.AddSingleton <IFileHelper, FileHelper>();

            var basicAccountSecretKey   = Configuration.GetValue("NetheriumBasicAccountSecretKey");
            var premiumAccountSecretKey = Configuration.GetValue("NetheriumPremiumAccountSecretKey");
            var toAddress             = Configuration.GetValue("NetheriumAccount:ToAddress");
            var networkName           = Configuration.GetValue("NetheriumAccount:Network");
            var gasStationAPIEndpoint = Configuration.GetValue("NetheriumAccount:GasStationAPIEndpoint");

            var ethSetting = new EthSettings {
                ToAddress = toAddress, BasicAccountSecretKey = basicAccountSecretKey, PremiumAccountSecretKey = premiumAccountSecretKey, Network = networkName, GasStationAPIEndpoint = gasStationAPIEndpoint
            };

            services.AddSingleton <IEthHelper>(provider => new EthHelper(ethSetting, provider.GetService <IEthClient>(), provider.GetService <ILogger>()));

            var timeProofLoginUri = Configuration.GetValue("TimeProofLoginUri");

            services.AddSingleton <IEmailTemplateHelper>(new EmailTemplateHelper(timeProofLoginUri));

            var paymentApiKey = Configuration.GetValue("StripePaymentApiKey");
            var stripeClient  = new StripeClient(paymentApiKey);

            services.AddSingleton(new PaymentIntentService(stripeClient));
            services.AddSingleton(new CustomerService(stripeClient));
            services.AddSingleton(new PaymentMethodService(stripeClient));
            services.AddSingleton(new SetupIntentService(stripeClient));

            services.AddSingleton <IInvoiceHelper, InvoiceHelper>();
            services.AddSingleton <IPaymentService, StripePaymentService>();
            services.AddSingleton <IUserService, UserService>();
            services.AddSingleton <IUserSubscriptionService, UserSubscriptionService>();

            var nodeEndpoint = Configuration.GetValue("NetheriumAccount:NodeEndpoint");

            var basicAccountFromAddress = Configuration.GetValue("NetheriumAccount:BasicAccountFromAddress");
            var basicAccount            = new Nethereum.Web3.Accounts.Account(basicAccountSecretKey);
            var basicAccountWeb3        = new Web3(basicAccount, nodeEndpoint);

            basicAccount.NonceService = new InMemoryNonceService(basicAccountFromAddress, basicAccountWeb3.Client);

            var premiumAccountFromAddress = Configuration.GetValue("NetheriumAccount:PremiumAccountFromAddress");
            var premiumAccount            = new Nethereum.Web3.Accounts.Account(premiumAccountSecretKey);
            var premiumAccountWeb3        = new Web3(premiumAccount, nodeEndpoint);

            premiumAccount.NonceService = new InMemoryNonceService(premiumAccountFromAddress, premiumAccountWeb3.Client);

            services.AddSingleton <ITimestampService>(provider =>
                                                      new TimestampService(provider.GetService <ILogger>(),
                                                                           provider.GetService <ITimestampRepository>(),
                                                                           provider.GetService <IUserRepository>(),
                                                                           provider.GetService <IPricePlanRepository>(),
                                                                           provider.GetService <IEthHelper>(),
                                                                           provider.GetService <ITimestampQueueService>(),
                                                                           basicAccountWeb3,
                                                                           premiumAccountWeb3));
        }
Exemple #8
0
        private async Task SendRawTransaction(TimestampDao timestamp, IWeb3 web3, string secretKey, double estimateGasPrice, EthSettings ethSettings)
        {
            if (!Enum.TryParse(ethSettings.Network, true, out Chain networkChain))
            {
                networkChain = Chain.MainNet;
                _logger.Warning($"Unable to parse '{ethSettings.Network}' to type '{typeof(Chain)}', so setting default to '{networkChain}'.");
            }

            bool proofVerified = _ethHelper.VerifyStamp(timestamp);

            if (!proofVerified)
            {
                var message = $"Unable to verify the signature '{timestamp.Signature}'.";
                _logger.Warning(message);
                throw new TimestampException(message);
            }

            string proofStr = JsonConvert.SerializeObject(
                new
            {
                file      = timestamp.FileName,
                hash      = timestamp.FileHash,
                publicKey = timestamp.PublicKey,
                signature = timestamp.Signature
            });

            var txData = HexStringUTF8ConvertorExtensions.ToHexUTF8(proofStr);

            var fromAddress = web3.TransactionManager.Account.Address;
            var futureNonce = await web3.TransactionManager.Account.NonceService.GetNextNonceAsync();

            _logger.Information($"Signed transaction on chain: {networkChain}, To: {ethSettings.ToAddress}, Nonce: {futureNonce}, GasPrice: {estimateGasPrice}, From Address :{fromAddress}");

            var offlineTransactionSigner = new TransactionSigner();
            var encoded = offlineTransactionSigner.SignTransaction(
                secretKey,
                networkChain,
                ethSettings.ToAddress,
                Web3.Convert.ToWei(0, UnitConversion.EthUnit.Gwei),
                futureNonce,
                Web3.Convert.ToWei(estimateGasPrice, UnitConversion.EthUnit.Gwei),
                new BigInteger(100000),
                txData);

            var verified = offlineTransactionSigner.VerifyTransaction(encoded);

            if (!verified)
            {
                var message = $"Unable to verify the transaction for data '{txData}'.";
                _logger.Error(message);
                throw new TimestampException(message);
            }

            try
            {
                var txId = await web3.Eth.Transactions.SendRawTransaction.SendRequestAsync("0x" + encoded);

                timestamp.Address       = fromAddress;
                timestamp.Nonce         = (long)futureNonce.Value;
                timestamp.TransactionId = txId;
                timestamp.Network       = networkChain.ToString();
                timestamp.BlockNumber   = -1;

                if (string.IsNullOrWhiteSpace(txId))
                {
                    timestamp.Status = TimestampState.Failed;
                    var message = $"Transaction failed for an user '{timestamp.UserId}' with file name '{timestamp.FileName}'.";
                    _logger.Error(message);
                }
            }
            catch (RpcResponseException ex)
            {
                await web3.TransactionManager.Account.NonceService.ResetNonce();

                if (ex.Message.Contains("nonce too low", StringComparison.InvariantCultureIgnoreCase))
                {
                    throw new RpcClientNonceException(ex.Message);
                }
                else if (ex.Message.Contains("transaction underpriced", StringComparison.InvariantCultureIgnoreCase))
                {
                    throw new RpcClientUnderpricedException(ex.Message);
                }

                throw;
            }
        }