public void VerityCSVLoading() { ICSVLoader loader = new CSVLoader( Mock <IFileReader>(mock => { mock.Setup(m => m.ReadFileLines(It.IsAny <string>())) .Returns(MockCSVData); }) ); IEnumerable <CryptoData> dataList = loader.ParseFileAndReturnData(); int returnCount = 0; IEnumerator <CryptoData> listReader = dataList.GetEnumerator(); while (listReader.MoveNext()) { CryptoData dataItem = listReader.Current; Assert.True(dataItem.Unix > 0); Assert.True(dataItem.Date != default); Assert.NotEmpty(dataItem.Symbol); Assert.True(dataItem.Open > 0); Assert.True(dataItem.High > 0); Assert.True(dataItem.Low > 0); Assert.True(dataItem.Close > 0); Assert.True(dataItem.VolumeBTC > 0); Assert.True(dataItem.VolumeUSDT > 0); ++returnCount; } Assert.Equal(12, returnCount); }
static public string CryptoDirChecker(CryptoData cdata) { string _dir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile); string dir = string.Empty; List <string> cdirs = new List <string> { cdata.Dir, cdata.Dir.ToLower() }; bool flg = false; _DIRs.ForEach(delegate(string DIR) { cdirs.ForEach(delegate(string cdir) { string dir_ = _dir + DIR + cdir; //Console.WriteLine (dir_); if (!flg && Directory.Exists(dir_)) { dir = dir_; flg = true; } }); }); if (dir == string.Empty) { Console.WriteLine("Please Run Wallet."); Environment.Exit(100); } return(dir + Path.DirectorySeparatorChar); }
static public void ConfigWriter(CryptoData cdata, string confgiPath) { string filedata = string.Empty; string tmpFile = cdata.Nmae.ToLower() + ".conf"; cdata.Data.ForEach(delegate(string item) { filedata += item + Environment.NewLine; }); if (File.Exists(tmpFile)) { File.Delete(tmpFile); } Encoding enc = new UTF8Encoding(false); using (FileStream fs = new FileStream(tmpFile, FileMode.Create)) { using (StreamWriter sw = new StreamWriter(fs, enc)) { sw.Write(filedata); } } Console.WriteLine("Created temporarily."); Console.WriteLine("Copy?[y/n]"); string yn = Console.ReadLine(); if (yn.ToLower() == "y") { File.Copy(cdata.Nmae.ToLower() + ".conf", confgiPath); } }
private void CreateCrypto(QuotationModel quotation) { CryptoModel cryptoDTO = new CryptoModel(quotation); CryptoData cryptoData = Mapper.Map <CryptoData>(cryptoDTO); CryptoRepository.Create(cryptoData); }
private static SqlParameter MapCryptoDataToSqlParameter(CryptoData cryptoData) { DataTable table = new(); foreach (string column in new[] { "Id", "Unix", "Date", "Symbol", "Open", "High", "Low", "Close", "VolumeBTC", "VolumeUSDT" }) { table.Columns.Add(column); } DataRow row = table.NewRow(); row["Id"] = cryptoData.Id; row["Unix"] = cryptoData.Unix; row["Date"] = cryptoData.Date; row["Symbol"] = cryptoData.Symbol; row["Open"] = cryptoData.Open; row["High"] = cryptoData.High; row["Low"] = cryptoData.Low; row["Close"] = cryptoData.Close; row["VolumeBTC"] = cryptoData.VolumeBTC; row["VolumeUSDT"] = cryptoData.VolumeUSDT; table.Rows.Add(row); return(new SqlParameter("@cryptodata", table) { SqlDbType = SqlDbType.Structured, TypeName = "[dbo].[CryptoDataInput]" }); }
public CryptoData Create(CryptoData crypto) { var newCrypto = DB.Cryptos.Add(crypto); DB.SaveChanges(); return(newCrypto.Entity); }
public async Task <string> DecryptWithKey(CryptoData data) { var ciphertextBlob = GenerateStreamFromBase64String(data.Key); var plainText = await DecryptDataKey(ciphertextBlob); var protector = dataProtectionProvider.CreateProtector(GetBase64StringFromStream(plainText)); return(protector.Unprotect(data.Encrypted)); }
/// <summary> /// Download history values of crypto (from last updated value) /// </summary> /// <param name="cryptoTicker">Crypto ticker</param> /// <returns>Task</returns> internal async Task DownloadCryptoHistory(CryptoTicker cryptoTicker) { InfluxConfig config = GetSecretToken(); InfluxDbData.Repository <CryptoData> repo = new(new InfluxContext(config.Url, config.Token)); List <CryptoData> lastRecords = await repo.GetLastWrittenRecordsTime(new DataSourceIdentification(organizationId, bucketCrypto)).ConfigureAwait(false); CryptoData lastTickerRecord = lastRecords.SingleOrDefault(r => r.Ticker == cryptoTicker.ToString()); CryptoDataDownloader dataDownloader = new CryptoDataDownloader(repo, new DataSourceIdentification(organizationId, bucketCrypto)); await dataDownloader.CryptoDownload(cryptoTicker, lastTickerRecord?.Time).ConfigureAwait(false); }
public override void WriteInfoXml(XmlWriter writer) { byte[] hmacContentBytes = GetHmacContentBytes(); CryptoData hmacResult = Cryptographer.Hmac(AppSharedSecret, hmacContentBytes); writer.WriteStartElement("appserver2"); writer.WriteStartElement("hmacSig"); writer.WriteAttributeString("algName", hmacResult.Algorithm); writer.WriteValue(hmacResult.Value); // HMAC of content writer.WriteEndElement(); // hmacSig writer.WriteRaw(Encoding.UTF8.GetString(hmacContentBytes)); writer.WriteEndElement(); // appserver2 }
public static CryptoData Hash(byte[] data) { using (SHA256 sha = SHA256.Create()) { byte[] hash = sha.ComputeHash(data); CryptoData cryptoData = new CryptoData { Algorithm = HealthVaultConstants.Cryptography.HashAlgorithm, Value = Convert.ToBase64String(hash) }; return(cryptoData); } }
public void Pack(BinaryWriter writer) { writer.WriteString16L("1802"); // Unused value writer.Write(ByteSize); writer.Write((uint)AuthType); writer.Write(AuthFlags); writer.Write(ConnectionSequenceNumber); writer.WriteString16L(Account); if ((AuthFlags & 0x00000002) != 0) { writer.WriteString16L(AccountToLogonAs); } CryptoData.Pack(writer); ExtraData.Pack(writer); }
public static CryptoData Hmac(string keyMaterial, byte[] data) { using (HMAC hmac = new HMACSHA256(Convert.FromBase64String(keyMaterial))) { byte[] hash = hmac.ComputeHash(data); CryptoData cryptoData = new CryptoData { Algorithm = HealthVaultConstants.Cryptography.HmacAlgorithm, Value = Convert.ToBase64String(hash) }; return(cryptoData); } }
static public string ConfigChecker(CryptoData cdata, string dir) { string confpath = dir + cdata.Nmae.ToLower() + ".conf"; if (File.Exists(confpath)) { if (File.Exists(confpath + ".old")) { Console.WriteLine("Deleted: " + confpath + ".old"); File.Delete(confpath + ".old"); } Console.WriteLine("Backupd: " + confpath); File.Move(confpath, confpath + ".old"); } return(confpath); }
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> result) { var message = await result; data = store.Create(message.Text); if (message.Text.Contains("convertion")) { await this.SendChangePreferenceMessageAsync(context); } else if (data.Currencies.Count > 0 || message.Text.ToLower().Contains("ajout")) { await this.SendCurrentCurrencies(context); } else { await this.SendAddCurrency(context); } }
static async Task MainAsync(string[] args) { string dirpass = string.Empty; string configFile = string.Empty; string dirs, confgiPath; CryptoData cdata = await CryptoSelecter(); Console.WriteLine("###############################"); cdata.view(); dirs = CryptoDirChecker(cdata); Console.WriteLine("Dir: " + dirs); Console.WriteLine("###############################"); confgiPath = ConfigChecker(cdata, dirs); Console.WriteLine("###############################"); ConfigWriter(cdata, confgiPath); Console.WriteLine("###############################"); BootstrapCopy(dirs); Console.WriteLine("###############################"); Console.WriteLine("Done."); }
static public async Task <CryptoData> CryptoSelecter() { CryptoListJsonModel cljm = await CryptoListGetter(); CryptoData cdata = null; string readStr; Console.WriteLine("Plse Type Crypto Code(BTC, LTC, ZNY ..etc):"); readStr = Console.ReadLine(); cljm.SupportList.ForEach(delegate(CryptoData item) { if (item.Code.ToUpper() == readStr.ToUpper()) { cdata = item; } }); if (cdata == null) { Console.WriteLine("Sorry. Not Support."); Environment.Exit(100); } return(cdata); }
public void InitializeTest() { _connection = Substitute.For <IConnectionInternal>(); _serviceLocator = Substitute.For <IServiceLocator>(); _serviceLocator.GetInstance <HealthVaultConfiguration>() .Returns(new HealthVaultConfiguration { MasterApplicationId = Guid.NewGuid(), RequestTimeToLiveDuration = new TimeSpan(hours: 0, minutes: 1, seconds: 5) }); _serviceLocator.GetInstance <SdkTelemetryInformation>() .Returns( new SdkTelemetryInformation() { Category = "test", FileVersion = "test", OsInformation = "test" }); ICryptographer mockCryptographer = Substitute.For <ICryptographer>(); CryptoData mockCryptoData = new CryptoData() { Algorithm = "some", Value = "some" }; mockCryptographer.Hmac(Arg.Any <string>(), Arg.Any <byte[]>()) .Returns(mockCryptoData); mockCryptographer.Hash(Arg.Any <byte[]>()) .Returns(mockCryptoData); _serviceLocator.GetInstance <ICryptographer>().Returns(mockCryptographer); _connection.SessionCredential.Returns( new SessionCredential() { SharedSecret = "someSharedSecret", Token = "someToken" }); }
public void Unpack(BinaryReader reader) { var temp1 = reader.ReadString16L(); // Unused value #if NETWORKVALIDATION if (temp1 != "1802") { throw new Exception("Recieved value different from static on LoginRequest, expected: 1802, actual " + temp1); } #endif ByteSize = reader.ReadUInt32(); AuthType = (AuthType)reader.ReadUInt32(); AuthFlags = reader.ReadUInt32(); ConnectionSequenceNumber = reader.ReadUInt32(); Account = reader.ReadString16L(); if ((AuthFlags & 0x00000002) != 0) { AccountToLogonAs = reader.ReadString16L(); } CryptoData.Unpack(reader); ExtraData.Unpack(reader); }
public static extern SafeCertStoreHandle PFXImportCertStore(ref CryptoData pPfx, [MarshalAs(UnmanagedType.LPWStr)] string szPassword, PfxImportFlags dwFlags);
public Task <int> DeleteItemAsync(CryptoData item) { return(_database.DeleteAsync(item)); }
public Task <string> DecryptWithKey(CryptoData data) { return(service.DecryptWithKey(data)); }
public Task <int> SaveItemAsync(CryptoData item) { return(_database.InsertOrReplaceAsync(item)); }
private string FormatCurrency(CryptoData cryptoData) { string currency = cryptoData.ParentEntity.ProductInformation.Currency; return(FormatCurrency(cryptoData.Rate, currency)); }
static IList <SafeCertContextHandle> GetCertificatesFromPfx(byte[] pfxBytes, string password, PfxImportFlags pfxImportFlags) { // Marshal PFX bytes into native data structure var pfxData = new CryptoData { cbData = pfxBytes.Length, pbData = Marshal.AllocHGlobal(pfxBytes.Length) }; Marshal.Copy(pfxBytes, 0, pfxData.pbData, pfxBytes.Length); var certificates = new List <SafeCertContextHandle>(); try { using (var memoryStore = PFXImportCertStore(ref pfxData, password, pfxImportFlags)) { if (memoryStore.IsInvalid) { throw new CryptographicException(Marshal.GetLastWin32Error()); } var certificatesToImport = GetCertificatesToImport(pfxBytes, password); foreach (var certificate in certificatesToImport) { var thumbprint = CalculateThumbprint(certificate); // Marshal PFX bytes into native data structure var thumbprintData = new CryptoData { cbData = thumbprint.Length, pbData = Marshal.AllocHGlobal(thumbprint.Length) }; Marshal.Copy(thumbprint, 0, thumbprintData.pbData, thumbprint.Length); var certificateHandle = CertFindCertificateInStore(memoryStore, CertificateEncodingType.Pkcs7OrX509AsnEncoding, IntPtr.Zero, CertificateFindType.Sha1Hash, ref thumbprintData, IntPtr.Zero); if (certificateHandle == null || certificateHandle.IsInvalid) { throw new Exception("Could not find certificate"); } certificates.Add(certificateHandle); Marshal.FreeHGlobal(thumbprintData.pbData); } return(certificates); } } catch (Exception ex) { throw new Exception("Could not read PFX", ex); } finally { Marshal.FreeHGlobal(pfxData.pbData); } }
internal async Task <DataWrapper <InvoiceResponse> > CreateInvoiceCore(Invoice invoice, StoreData store, string serverUrl) { var derivationStrategies = store.GetDerivationStrategies(_NetworkProvider).Where(c => _ExplorerClients.IsAvailable(c.Network.CryptoCode)).ToList(); if (derivationStrategies.Count == 0) { throw new BitpayHttpException(400, "No derivation strategy are available now for this store"); } var entity = new InvoiceEntity { InvoiceTime = DateTimeOffset.UtcNow }; entity.SetDerivationStrategies(derivationStrategies); var storeBlob = store.GetStoreBlob(); Uri notificationUri = Uri.IsWellFormedUriString(invoice.NotificationURL, UriKind.Absolute) ? new Uri(invoice.NotificationURL, UriKind.Absolute) : null; if (notificationUri == null || (notificationUri.Scheme != "http" && notificationUri.Scheme != "https")) //TODO: Filer non routable addresses ? { notificationUri = null; } EmailAddressAttribute emailValidator = new EmailAddressAttribute(); entity.ExpirationTime = entity.InvoiceTime.AddMinutes(storeBlob.InvoiceExpiration); entity.MonitoringExpiration = entity.ExpirationTime + TimeSpan.FromMinutes(storeBlob.MonitoringExpiration); entity.OrderId = invoice.OrderId; entity.ServerUrl = serverUrl; entity.FullNotifications = invoice.FullNotifications || invoice.ExtendedNotifications; entity.ExtendedNotifications = invoice.ExtendedNotifications; entity.NotificationURL = notificationUri?.AbsoluteUri; entity.BuyerInformation = Map <Invoice, BuyerInformation>(invoice); //Another way of passing buyer info to support FillBuyerInfo(invoice.Buyer, entity.BuyerInformation); if (entity?.BuyerInformation?.BuyerEmail != null) { if (!EmailValidator.IsEmail(entity.BuyerInformation.BuyerEmail)) { throw new BitpayHttpException(400, "Invalid email"); } entity.RefundMail = entity.BuyerInformation.BuyerEmail; } entity.ProductInformation = Map <Invoice, ProductInformation>(invoice); entity.RedirectURL = invoice.RedirectURL ?? store.StoreWebsite; entity.Status = "new"; entity.SpeedPolicy = ParseSpeedPolicy(invoice.TransactionSpeed, store.SpeedPolicy); var queries = derivationStrategies .Select(derivationStrategy => (Wallet: _WalletProvider.GetWallet(derivationStrategy.Network), DerivationStrategy: derivationStrategy.DerivationStrategyBase, Network: derivationStrategy.Network, RateProvider: _RateProviders.GetRateProvider(derivationStrategy.Network, false), FeeRateProvider: _FeeProviderFactory.CreateFeeProvider(derivationStrategy.Network))) .Where(_ => _.Wallet != null && _.FeeRateProvider != null && _.RateProvider != null) .Select(_ => { return(new { network = _.Network, getFeeRate = _.FeeRateProvider.GetFeeRateAsync(), getRate = storeBlob.ApplyRateRules(_.Network, _.RateProvider).GetRateAsync(invoice.Currency), getAddress = _.Wallet.ReserveAddressAsync(_.DerivationStrategy) }); }); bool legacyBTCisSet = false; var cryptoDatas = new Dictionary <string, CryptoData>(); foreach (var q in queries) { CryptoData cryptoData = new CryptoData(); cryptoData.CryptoCode = q.network.CryptoCode; cryptoData.FeeRate = (await q.getFeeRate); cryptoData.TxFee = GetTxFee(storeBlob, cryptoData.FeeRate); // assume price for 100 bytes cryptoData.Rate = await q.getRate; cryptoData.DepositAddress = (await q.getAddress).ToString(); #pragma warning disable CS0618 if (q.network.IsBTC) { legacyBTCisSet = true; entity.TxFee = cryptoData.TxFee; entity.Rate = cryptoData.Rate; entity.DepositAddress = cryptoData.DepositAddress; } #pragma warning restore CS0618 cryptoDatas.Add(cryptoData.CryptoCode, cryptoData); } if (!legacyBTCisSet) { // Legacy Bitpay clients expect information for BTC information, even if the store do not support it #pragma warning disable CS0618 var btc = _NetworkProvider.BTC; var feeProvider = _FeeProviderFactory.CreateFeeProvider(btc); var rateProvider = storeBlob.ApplyRateRules(btc, _RateProviders.GetRateProvider(btc, false)); if (feeProvider != null && rateProvider != null) { var gettingFee = feeProvider.GetFeeRateAsync(); var gettingRate = rateProvider.GetRateAsync(invoice.Currency); entity.TxFee = GetTxFee(storeBlob, await gettingFee); entity.Rate = await gettingRate; } #pragma warning restore CS0618 } entity.SetCryptoData(cryptoDatas); entity.PosData = invoice.PosData; entity = await _InvoiceRepository.CreateInvoiceAsync(store.Id, entity, _NetworkProvider); _EventAggregator.Publish(new Events.InvoiceEvent(entity, 1001, "invoice_created")); var resp = entity.EntityToDTO(_NetworkProvider); return(new DataWrapper <InvoiceResponse>(resp) { Facade = "pos/invoice" }); }
internal async Task <DataWrapper <InvoiceResponse> > CreateInvoiceCore(Invoice invoice, StoreData store, string serverUrl, double expiryMinutes = 15) { var derivationStrategy = store.DerivationStrategy; var entity = new InvoiceEntity { InvoiceTime = DateTimeOffset.UtcNow, DerivationStrategy = derivationStrategy ?? throw new BitpayHttpException(400, "This store has not configured the derivation strategy") }; var storeBlob = store.GetStoreBlob(); Uri notificationUri = Uri.IsWellFormedUriString(invoice.NotificationURL, UriKind.Absolute) ? new Uri(invoice.NotificationURL, UriKind.Absolute) : null; if (notificationUri == null || (notificationUri.Scheme != "http" && notificationUri.Scheme != "https")) //TODO: Filer non routable addresses ? { notificationUri = null; } EmailAddressAttribute emailValidator = new EmailAddressAttribute(); entity.ExpirationTime = entity.InvoiceTime.AddMinutes(expiryMinutes); entity.MonitoringExpiration = entity.ExpirationTime + TimeSpan.FromMinutes(storeBlob.MonitoringExpiration); entity.OrderId = invoice.OrderId; entity.ServerUrl = serverUrl; entity.FullNotifications = invoice.FullNotifications; entity.NotificationURL = notificationUri?.AbsoluteUri; entity.BuyerInformation = Map <Invoice, BuyerInformation>(invoice); //Another way of passing buyer info to support FillBuyerInfo(invoice.Buyer, entity.BuyerInformation); if (entity?.BuyerInformation?.BuyerEmail != null) { if (!EmailValidator.IsEmail(entity.BuyerInformation.BuyerEmail)) { throw new BitpayHttpException(400, "Invalid email"); } entity.RefundMail = entity.BuyerInformation.BuyerEmail; } entity.ProductInformation = Map <Invoice, ProductInformation>(invoice); entity.RedirectURL = invoice.RedirectURL ?? store.StoreWebsite; entity.Status = "new"; entity.SpeedPolicy = ParseSpeedPolicy(invoice.TransactionSpeed, store.SpeedPolicy); var queries = storeBlob.GetSupportedCryptoCurrencies() .Select(n => _NetworkProvider.GetNetwork(n)) .Where(n => n != null) .Select(network => { return(new { network = network, getFeeRate = _FeeProviderFactory.CreateFeeProvider(network).GetFeeRateAsync(), getRate = _RateProvider.GetRateAsync(invoice.Currency), getAddress = _Wallet.ReserveAddressAsync(ParseDerivationStrategy(derivationStrategy, network)) }); }); var cryptoDatas = new Dictionary <string, CryptoData>(); foreach (var q in queries) { CryptoData cryptoData = new CryptoData(); cryptoData.CryptoCode = q.network.CryptoCode; cryptoData.FeeRate = (await q.getFeeRate); cryptoData.TxFee = storeBlob.NetworkFeeDisabled ? Money.Zero : cryptoData.FeeRate.GetFee(100); // assume price for 100 bytes cryptoData.Rate = await q.getRate; cryptoData.DepositAddress = (await q.getAddress).ToString(); #pragma warning disable CS0618 if (q.network.CryptoCode == "BTC") { entity.TxFee = cryptoData.TxFee; entity.Rate = cryptoData.Rate; entity.DepositAddress = cryptoData.DepositAddress; } #pragma warning restore CS0618 cryptoDatas.Add(cryptoData.CryptoCode, cryptoData); } entity.SetCryptoData(cryptoDatas); entity.PosData = invoice.PosData; entity = await _InvoiceRepository.CreateInvoiceAsync(store.Id, entity, _NetworkProvider); _Watcher.Watch(entity.Id); var resp = entity.EntityToDTO(_NetworkProvider); return(new DataWrapper <InvoiceResponse>(resp) { Facade = "pos/invoice" }); }
public static extern SafeCertContextHandle CertFindCertificateInStore(SafeCertStoreHandle hCertStore, CertificateEncodingType dwCertEncodingType, IntPtr notUsed, CertificateFindType dwFindType, ref CryptoData pvFindPara, IntPtr pPrevCertContext);
public static extern bool CertCompareCertificateName(CertificateEncodingType dwCertEncodingType, ref CryptoData pCertName1, ref CryptoData pCertName2);
public void Update(CryptoData crypto) { DB.Cryptos.Update(crypto); DB.SaveChanges(); }