private kList GetFileList(Safe.SharedObjects shared) { var list = new kList(); list.AddColumn("Name", 30, ColumnAlignment.Left); list.AddColumn("Size", 7, ColumnAlignment.Right); if (shared.VolumeMgr != null) { Volume volume = shared.VolumeMgr.CurrentVolume; if (volume != null) { list.Title = "Volume " + shared.VolumeMgr.GetVolumeBestIdentifier(volume); foreach (FileInfo info in volume.GetFileList()) { list.AddItem(info.Name, info.Size); } int freeSpace = volume.GetFreeSpace(); list.Footer = "Free space remaining: " + (freeSpace > -1 ? freeSpace.ToString() : " infinite"); } } return list; }
public Client() { InitializeComponent(); this.client.Connected += new EventHandler<NetSocketConnectedEventArgs>(client_Connected); this.client.DataArrived += new EventHandler<NetSockDataArrivalEventArgs>(client_DataArrived); this.client.Disconnected += new EventHandler<NetSocketDisconnectedEventArgs>(client_Disconnected); this.client.ErrorReceived += new EventHandler<NetSockErrorReceivedEventArgs>(client_ErrorReceived); this.client.StateChanged += new EventHandler<NetSockStateChangedEventArgs>(client_StateChanged); this.SafeCall = new Safe(Log_Local); }
public async Task CreateSafe(SafeViewModel viewModel) { string userId = _identityResolver.GetCurrentUserId(); var safe = new Safe() { SubjectName = viewModel.SubjectName, AdministratorId = userId, CreatedById = userId }; _dbContext.Safes.Add(safe); await _dbContext.SaveChangesAsync(); }
public void OpenSafe(Safe safe, Owner owner) { safe.PickLocker(this); Jewels safeContents = safe.Open(writtenDownCombination); ReturnContents(safeContents, owner); }
/// <summary> /// 取得组在某个页面下是否有子项 /// </summary> /// <param name="pid"></param> /// <param name="aid"></param> /// <returns></returns> private IList<MR_PageInfo> GetChild(int pid, int gid, ref Safe.Base.Contract.IDbHelper dbhelper) { StringBuilder sb = new StringBuilder(); sb.Append("SELECT R_PageInfo.* FROM R_PageInfo LEFT JOIN R_GroupRight on R_GroupRight.PID = R_PageInfo.PID WHERE R_GroupRight.GID=@gid and R_PageInfo.ParentID=@pid "); DataTable dt = dbhelper.ExecuteFillDataTable(sb.ToString(), new SqlParameter("@gid", gid), new SqlParameter("@pid", pid)); if (dt == null) return null; if (dt.Rows.Count == 0) return null; return Safe.Base.Utility.ModelConvertHelper<MR_PageInfo>.ToModels(dt); }
private kList GetVolumeList(Safe.SharedObjects shared) { var list = new kList { Title = "Volumes" }; list.AddColumn("ID", 6, ColumnAlignment.Left); list.AddColumn("Name", 24, ColumnAlignment.Left); list.AddColumn("Size", 7, ColumnAlignment.Right); if (shared.VolumeMgr == null) return list; foreach (KeyValuePair<int, Volume> kvp in shared.VolumeMgr.Volumes) { Volume volume = kvp.Value; string id = kvp.Key.ToString() + (shared.VolumeMgr.VolumeIsCurrent(volume) ? "*" : ""); string size = volume.Capacity.ToString(); list.AddItem(id, volume.Name, size); } return list; }
private void GetChilds(int adminId, int parentID, bool incluedChild, ref IList<MR_PageInfo> result, ref Safe.Base.Contract.IDbHelper dbhelper) { StringBuilder sb = new StringBuilder(); sb.Append("select a.*,b.btnrightexp from r_pageinfo as a left join r_adminright as b on a.pid=b.pid where b.aid=@aid and a.parentID=@parentID order by a.Queue asc, b.ClickTimes desc"); SqlParameter[] sqlparams = new SqlParameter[]{ new SqlParameter("@aid",adminId), new SqlParameter("@parentID",parentID) }; DataTable tbl = SQLHelpers.TcAdmin().ExecuteFillDataTable(sb.ToString(), sqlparams); result = Safe.Base.Utility.ModelConvertHelper<MR_PageInfo>.ToModels(tbl); //该结点的子节点 if (incluedChild && result != null) { foreach (MR_PageInfo tmpc in result) { IList<MR_PageInfo> childs = null; GetChilds(adminId, tmpc.PID, incluedChild, ref childs, ref dbhelper); tmpc.Childs = childs.ToList(); } } }
protected override string parseValue(string s) { Value = Safe.Run(() => DateTime.Parse(s, UseCulture.Invariant), DateTime.MaxValue); return(ValueAsString); }
public static async Task <Dictionary <BitcoinAddress, List <BalanceOperation> > > QueryOperationsPerSafeAddressesAsync(QBitNinjaClient client, Safe safe, int minUnusedKeys = 7, HdPathType?hdPathType = null) { if (hdPathType == null) { var t1 = QueryOperationsPerSafeAddressesAsync(client, safe, minUnusedKeys, HdPathType.Receive); var t2 = QueryOperationsPerSafeAddressesAsync(client, safe, minUnusedKeys, HdPathType.Change); var t3 = QueryOperationsPerSafeAddressesAsync(client, safe, minUnusedKeys, HdPathType.NonHardened); await Task.WhenAll(t1, t2, t3).ConfigureAwait(false); Dictionary <BitcoinAddress, List <BalanceOperation> > operationsPerReceiveAddresses = await t1.ConfigureAwait(false); Dictionary <BitcoinAddress, List <BalanceOperation> > operationsPerChangeAddresses = await t2.ConfigureAwait(false); Dictionary <BitcoinAddress, List <BalanceOperation> > operationsPerNonHardenedAddresses = await t3.ConfigureAwait(false); var operationsPerAllAddresses = new Dictionary <BitcoinAddress, List <BalanceOperation> >(); foreach (var elem in operationsPerReceiveAddresses) { operationsPerAllAddresses.Add(elem.Key, elem.Value); } foreach (var elem in operationsPerChangeAddresses) { operationsPerAllAddresses.Add(elem.Key, elem.Value); } foreach (var elem in operationsPerNonHardenedAddresses) { operationsPerAllAddresses.Add(elem.Key, elem.Value); } return(operationsPerAllAddresses); } var addresses = safe.GetFirstNAddresses(minUnusedKeys, hdPathType.GetValueOrDefault()); //var addresses = FakeData.FakeSafe.GetFirstNAddresses(minUnusedKeys); var operationsPerAddresses = new Dictionary <BitcoinAddress, List <BalanceOperation> >(); var unusedKeyCount = 0; foreach (var elem in await QueryOperationsPerAddressesAsync(client, addresses).ConfigureAwait(false)) { operationsPerAddresses.Add(elem.Key, elem.Value); if (elem.Value.Count == 0) { unusedKeyCount++; } } Debug.WriteLine($"{operationsPerAddresses.Count} {hdPathType} keys are processed."); var startIndex = minUnusedKeys; while (unusedKeyCount < minUnusedKeys) { addresses = new List <BitcoinAddress>(); for (int i = startIndex; i < startIndex + minUnusedKeys; i++) { addresses.Add(safe.GetAddress(i, hdPathType.GetValueOrDefault())); //addresses.Add(FakeData.FakeSafe.GetAddress(i)); } foreach (var elem in await QueryOperationsPerAddressesAsync(client, addresses).ConfigureAwait(false)) { operationsPerAddresses.Add(elem.Key, elem.Value); if (elem.Value.Count == 0) { unusedKeyCount++; } } Debug.WriteLine($"{operationsPerAddresses.Count} {hdPathType} keys are processed."); startIndex += minUnusedKeys; } return(operationsPerAddresses); }
public int IndexOf(T item) { return(Safe.Run(() => list.IndexOf(item), -1)); }
public T Get(int idx) { return(Safe.Run(() => this[idx], DefaultValue())); }
public int FindLastIndex(Predicate <T> match) { return(Safe.Run(() => list.FindLastIndex(match), -1)); }
public void CopyTo(T[] array, int arrayIndex) { Safe.Run(() => list.CopyTo(array, arrayIndex)); }
public bool Contains(T item) { return(Safe.Run(() => list.Contains(item), false)); }
public static void CreateJsonFile(string password, string fileDirectory, Network network, out Mnemonic mnemonic, out Safe safe) { mnemonic = null; safe = null; bool shouldContinue = true; string fileName = string.Empty; while (shouldContinue) { Console.WriteLine("Please Enter .json file name:\n"); try { fileName = Console.ReadLine(); safe = Safe.Create(out mnemonic, password, string.Format(@"{0}\{1}", fileDirectory, fileName), network); shouldContinue = false; } catch (Exception) { Console.WriteLine("File with that name already exist!\n"); } } }
public static Assembly AssemblyByName(string name) { return(Safe.Run(() => Assembly.Load(name), (Assembly)null)); }
public static Dictionary <BitcoinAddress, List <BalanceOperation> > QueryOperationsPerSafeAddresses(Safe safe, int minUnusedKeys = 7, HdPathType?hdPathType = null) { if (hdPathType == null) { Dictionary <BitcoinAddress, List <BalanceOperation> > operationsPerReceiveAddresses = QueryOperationsPerSafeAddresses(safe, 7, HdPathType.Receive); Dictionary <BitcoinAddress, List <BalanceOperation> > operationsPerChangeAddresses = QueryOperationsPerSafeAddresses(safe, 7, HdPathType.Change); var operationsPerAllAddresses = new Dictionary <BitcoinAddress, List <BalanceOperation> >(); foreach (var elem in operationsPerReceiveAddresses) { operationsPerAllAddresses.Add(elem.Key, elem.Value); } foreach (var elem in operationsPerChangeAddresses) { operationsPerAllAddresses.Add(elem.Key, elem.Value); } return(operationsPerAllAddresses); } var addresses = safe.GetFirstNAddresses(minUnusedKeys, hdPathType.GetValueOrDefault()); //var addresses = FakeData.FakeSafe.GetFirstNAddresses(minUnusedKeys); var operationsPerAddresses = new Dictionary <BitcoinAddress, List <BalanceOperation> >(); var unusedKeyCount = 0; foreach (var elem in QueryOperationsPerAddresses(addresses)) { operationsPerAddresses.Add(elem.Key, elem.Value); if (elem.Value.Count == 0) { unusedKeyCount++; } } WriteLine($"{operationsPerAddresses.Count} {hdPathType} keys are processed."); var startIndex = minUnusedKeys; while (unusedKeyCount < minUnusedKeys) { addresses = new List <BitcoinAddress>(); for (int i = startIndex; i < startIndex + minUnusedKeys; i++) { addresses.Add(safe.GetAddress(i, hdPathType.GetValueOrDefault())); //addresses.Add(FakeData.FakeSafe.GetAddress(i)); } foreach (var elem in QueryOperationsPerAddresses(addresses)) { operationsPerAddresses.Add(elem.Key, elem.Value); if (elem.Value.Count == 0) { unusedKeyCount++; } } WriteLine($"{operationsPerAddresses.Count} {hdPathType} keys are processed."); startIndex += minUnusedKeys; } return(operationsPerAddresses); }
public bool Authenticate() { registryKey = Registry.CurrentUser.OpenSubKey(Params.ProductName, true); if (registryKey == null) { registryKey = Registry.CurrentUser.CreateSubKey(Params.ProductName); registryKey.SetValue(Params.RegisterCode, ""); registryKey.SetValue(Params.EndDate, ""); registryKey.SetValue(Params.LastedDate, ""); registryKey.SetValue(Params.SalesNumber, ""); //CreateSubKey(""); return(false); } string salesNumber = registryKey.GetValue(Params.SalesNumber, "").ToString().Trim(); if (string.IsNullOrEmpty(salesNumber)) { return(false); } SalesNumber = Decrpyt(salesNumber); RegisterCode = registryKey.GetValue(Params.RegisterCode, "").ToString().Trim(); string databegin = registryKey.GetValue(Params.BeginDate, "").ToString().Trim(); if (string.IsNullOrEmpty(databegin)) { //CreateSubKey(); return(false); } string dateLasted = registryKey.GetValue(Params.LastedDate, "").ToString().Trim(); if (!string.IsNullOrEmpty(RegisterCode) && !string.IsNullOrEmpty(dateLasted)) { DateTime dtLasted; if (!DateTime.TryParse(this.Decrpyt(dateLasted), out dtLasted)) { //CreateSubKey(); registryKey.SetValue(Params.RegisterCode, ""); registryKey.SetValue(Params.EndDate, ""); registryKey.SetValue(Params.LastedDate, ""); return(false); } DateTime dtNow = DateTime.Now; //DateTime dtLasted = DateTime.Parse(dateLasted); TimeSpan tUsedCount = dtNow - dtLasted; if (Convert.ToInt32(tUsedCount.TotalDays) < 0) { //CreateSubKey(); registryKey.SetValue(Params.RegisterCode, ""); registryKey.SetValue(Params.EndDate, ""); registryKey.SetValue(Params.LastedDate, ""); return(false); } } BeginDate = Decrpyt(databegin); MachineCode = registryKey.GetValue(Params.MachineCode, "").ToString().Trim(); if (string.IsNullOrEmpty(MachineCode)) { //CreateSubKey(); return(false); } //如果机器码不符合规范,则重新生成机器码 if (MachineCode.Length != 48) { //CreateSubKey(); return(false); } var date1 = DateTime.Parse(BeginDate); var date = (date1.Year.ToString() + convertDateString(date1.Month) + convertDateString(date1.Day)).Substring(2); string tmpMachineCode = Safe.DesEncrypt(date + CpuId + SalesNumber, sKey);// MD5Encrpty(BeginDate + CpuId); if (!string.Equals(tmpMachineCode, MachineCode)) { var time = DateTime.Now.ToString(); BeginDate = Encrpyt(time); //SalesNumber = Encrpyt(salesNumber); var now = (DateTime.Now.Year.ToString() + convertDateString(DateTime.Now.Month) + convertDateString(DateTime.Now.Day)).Substring(2); MachineCode = Safe.DesEncrypt(now + CpuId + SalesNumber, sKey).Replace("-", "");// MD5Encrpty(time + CpuId); //MachineCode = MD5Encrpty(time + CpuId); registryKey.SetValue(Params.BeginDate, BeginDate); //registryKey.SetValue(Params.SalesNumber, SalesNumber); registryKey.SetValue(Params.MachineCode, MachineCode); return(false); } if (string.IsNullOrEmpty(RegisterCode)) { return(false); } if (RegisterCode.Length != 16) { return(false); } EndDate = registryKey.GetValue(Params.EndDate, "").ToString().Trim(); return(OnAuthenticate()); }
public static void Main(string[] args) { //args = new string[] { "help" }; //args = new string[] { "generate-wallet" }; //args = new string[] { "generate-wallet", "wallet-file=test2.json" }; ////math super cool donate beach mobile sunny web board kingdom bacon crisp ////no password //args = new string[] { "recover-wallet", "wallet-file=test5.json" }; //args = new string[] { "show-balances", "wallet-file=test5.json" }; //args = new string[] { "receive", "wallet-file=test4.json" }; //args = new string[] { "show-history", "wallet-file=test.json" }; //args = new string[] { "send", "btc=0.001", "address=mq6fK8fkFyCy9p53m4Gf4fiX2XCHvcwgi1", "wallet-file=test.json" }; //args = new string[] { "send", "btc=all", "address=mzz63n3n89KVeHQXRqJEVsQX8MZj5zeqCw", "wallet-file=test4.json" }; // Load config file // It also creates it with default settings if doesn't exist Config.Load(); if (args.Length == 0) { DisplayHelp(); Exit(color: ConsoleColor.Green); } var command = args[0]; if (!Commands.Contains(command)) { WriteLine("Wrong command is specified."); DisplayHelp(); } foreach (var arg in args.Skip(1)) { if (!arg.Contains('=')) { Exit($"Wrong argument format specified: {arg}"); } } #region HelpCommand if (command == "help") { AssertArgumentsLength(args.Length, 1, 1); DisplayHelp(); } #endregion #region GenerateWalletCommand if (command == "generate-wallet") { AssertArgumentsLength(args.Length, 1, 2); var walletFilePath = GetWalletFilePath(args); AssertWalletNotExists(walletFilePath); string pw; string pwConf; do { // 1. Get password from user WriteLine("Choose a password:"******"Confirm password:"******"Passwords do not match. Try again!"); } } while (pw != pwConf); // 3. Create wallet Mnemonic mnemonic; Safe safe = Safe.Create(out mnemonic, pw, walletFilePath, Config.Network); // If no exception thrown the wallet is successfully created. WriteLine(); WriteLine("Wallet is successfully created."); WriteLine($"Wallet file: {walletFilePath}"); // 4. Display mnemonic WriteLine(); WriteLine("Write down the following mnemonic words."); WriteLine("With the mnemonic words AND your password you can recover this wallet by using the recover-wallet command."); WriteLine(); WriteLine("-------"); WriteLine(mnemonic); WriteLine("-------"); } #endregion #region RecoverWalletCommand if (command == "recover-wallet") { AssertArgumentsLength(args.Length, 1, 2); var walletFilePath = GetWalletFilePath(args); AssertWalletNotExists(walletFilePath); WriteLine($"Your software is configured using the Bitcoin {Config.Network} network."); WriteLine("Provide your mnemonic words, separated by spaces:"); var mnemonicString = ReadLine(); AssertCorrectMnemonicFormat(mnemonicString); var mnemonic = new Mnemonic(mnemonicString); WriteLine("Provide your password. Please note the wallet cannot check if your password is correct or not. If you provide a wrong password a wallet will be recovered with your provided mnemonic AND password pair:"); var password = PasswordConsole.ReadPassword(); Safe safe = Safe.Recover(mnemonic, password, walletFilePath, Config.Network); // If no exception thrown the wallet is successfully recovered. WriteLine(); WriteLine("Wallet is successfully recovered."); WriteLine($"Wallet file: {walletFilePath}"); } #endregion #region ShowBalancesCommand if (command == "show-balances") { AssertArgumentsLength(args.Length, 1, 2); var walletFilePath = GetWalletFilePath(args); Safe safe = DecryptWalletByAskingForPassword(walletFilePath); if (Config.ConnectionType == ConnectionType.Http) { // 0. Query all operations, grouped by addresses Dictionary <BitcoinAddress, List <BalanceOperation> > operationsPerAddresses = QueryOperationsPerSafeAddresses(safe, 7); // 1. Get all address history record with a wrapper class var addressHistoryRecords = new List <AddressHistoryRecord>(); foreach (var elem in operationsPerAddresses) { foreach (var op in elem.Value) { addressHistoryRecords.Add(new AddressHistoryRecord(elem.Key, op)); } } // 2. Calculate wallet balances Money confirmedWalletBalance; Money unconfirmedWalletBalance; GetBalances(addressHistoryRecords, out confirmedWalletBalance, out unconfirmedWalletBalance); // 3. Group all address history records by addresses var addressHistoryRecordsPerAddresses = new Dictionary <BitcoinAddress, HashSet <AddressHistoryRecord> >(); foreach (var address in operationsPerAddresses.Keys) { var recs = new HashSet <AddressHistoryRecord>(); foreach (var record in addressHistoryRecords) { if (record.Address == address) { recs.Add(record); } } addressHistoryRecordsPerAddresses.Add(address, recs); } // 4. Calculate address balances WriteLine(); WriteLine("---------------------------------------------------------------------------"); WriteLine("Address\t\t\t\t\tConfirmed\tUnconfirmed"); WriteLine("---------------------------------------------------------------------------"); foreach (var elem in addressHistoryRecordsPerAddresses) { Money confirmedBalance; Money unconfirmedBalance; GetBalances(elem.Value, out confirmedBalance, out unconfirmedBalance); if (confirmedBalance != Money.Zero || unconfirmedBalance != Money.Zero) { WriteLine($"{elem.Key.ToString()}\t{confirmedBalance.ToDecimal(MoneyUnit.BTC).ToString("0.#############################")}\t\t{unconfirmedBalance.ToDecimal(MoneyUnit.BTC).ToString("0.#############################")}"); } } WriteLine("---------------------------------------------------------------------------"); WriteLine($"Confirmed Wallet Balance: {confirmedWalletBalance.ToDecimal(MoneyUnit.BTC).ToString("0.#############################")}btc"); WriteLine($"Unconfirmed Wallet Balance: {unconfirmedWalletBalance.ToDecimal(MoneyUnit.BTC).ToString("0.#############################")}btc"); WriteLine("---------------------------------------------------------------------------"); } else if (Config.ConnectionType == ConnectionType.FullNode) { throw new NotImplementedException(); } else { Exit("Invalid connection type."); } } #endregion #region ShowHistoryCommand if (command == "show-history") { AssertArgumentsLength(args.Length, 1, 2); var walletFilePath = GetWalletFilePath(args); Safe safe = DecryptWalletByAskingForPassword(walletFilePath); if (Config.ConnectionType == ConnectionType.Http) { // 0. Query all operations, grouped our used safe addresses Dictionary <BitcoinAddress, List <BalanceOperation> > operationsPerAddresses = QueryOperationsPerSafeAddresses(safe); WriteLine(); WriteLine("---------------------------------------------------------------------------"); WriteLine("Date\t\t\tAmount\t\tConfirmed\tTransaction Id"); WriteLine("---------------------------------------------------------------------------"); Dictionary <uint256, List <BalanceOperation> > operationsPerTransactions = GetOperationsPerTransactions(operationsPerAddresses); // 3. Create history records from the transactions // History records is arbitrary data we want to show to the user var txHistoryRecords = new List <Tuple <DateTimeOffset, Money, int, uint256> >(); foreach (var elem in operationsPerTransactions) { var amount = Money.Zero; foreach (var op in elem.Value) { amount += op.Amount; } var firstOp = elem.Value.First(); txHistoryRecords .Add(new Tuple <DateTimeOffset, Money, int, uint256>( firstOp.FirstSeen, amount, firstOp.Confirmations, elem.Key)); } // 4. Order the records by confirmations and time (Simply time does not work, because of a QBitNinja bug) var orderedTxHistoryRecords = txHistoryRecords .OrderByDescending(x => x.Item3) // Confirmations .ThenBy(x => x.Item1); // FirstSeen foreach (var record in orderedTxHistoryRecords) { // Item2 is the Amount if (record.Item2 > 0) { ForegroundColor = ConsoleColor.Green; } else if (record.Item2 < 0) { ForegroundColor = ConsoleColor.Red; } WriteLine($"{record.Item1.DateTime}\t{record.Item2}\t{record.Item3 > 0}\t\t{record.Item4}"); ResetColor(); } } else if (Config.ConnectionType == ConnectionType.FullNode) { throw new NotImplementedException(); } else { Exit("Invalid connection type."); } } #endregion #region ReceiveCommand if (command == "receive") { AssertArgumentsLength(args.Length, 1, 2); var walletFilePath = GetWalletFilePath(args); Safe safe = DecryptWalletByAskingForPassword(walletFilePath); if (Config.ConnectionType == ConnectionType.Http) { Dictionary <BitcoinAddress, List <BalanceOperation> > operationsPerReceiveAddresses = QueryOperationsPerSafeAddresses(safe, 7, HdPathType.Receive); WriteLine("---------------------------------------------------------------------------"); WriteLine("Unused Receive Addresses"); WriteLine("---------------------------------------------------------------------------"); foreach (var elem in operationsPerReceiveAddresses) { if (elem.Value.Count == 0) { WriteLine($"{elem.Key.ToString()}"); } } } else if (Config.ConnectionType == ConnectionType.FullNode) { throw new NotImplementedException(); } else { Exit("Invalid connection type."); } } #endregion #region SendCommand if (command == "send") { AssertArgumentsLength(args.Length, 3, 4); var walletFilePath = GetWalletFilePath(args); BitcoinAddress addressToSend; try { string address = GetArgumentValue(args, argName: "address", required: true); addressToSend = BitcoinAddress.Create(address, Config.Network); } catch (Exception ex) { Exit(ex.ToString()); throw ex; } Safe safe = DecryptWalletByAskingForPassword(walletFilePath); if (Config.ConnectionType == ConnectionType.Http) { Dictionary <BitcoinAddress, List <BalanceOperation> > operationsPerAddresses = QueryOperationsPerSafeAddresses(safe, 7); // 1. Gather all the not empty private keys WriteLine("Finding not empty private keys..."); var operationsPerNotEmptyPrivateKeys = new Dictionary <BitcoinExtKey, List <BalanceOperation> >(); foreach (var elem in operationsPerAddresses) { var balance = Money.Zero; foreach (var op in elem.Value) { balance += op.Amount; } if (balance > Money.Zero) { var secret = safe.FindPrivateKey(elem.Key); operationsPerNotEmptyPrivateKeys.Add(secret, elem.Value); } } // 2. Get the script pubkey of the change. WriteLine("Select change address..."); Script changeScriptPubKey = null; Dictionary <BitcoinAddress, List <BalanceOperation> > operationsPerChangeAddresses = QueryOperationsPerSafeAddresses(safe, minUnusedKeys: 1, hdPathType: HdPathType.Change); foreach (var elem in operationsPerChangeAddresses) { if (elem.Value.Count == 0) { changeScriptPubKey = safe.FindPrivateKey(elem.Key).ScriptPubKey; } } if (changeScriptPubKey == null) { throw new ArgumentNullException(); } // 3. Gather coins can be spend WriteLine("Gathering unspent coins..."); Dictionary <Coin, bool> unspentCoins = GetUnspentCoins(operationsPerNotEmptyPrivateKeys.Keys); // 4. Get the fee WriteLine("Calculating transaction fee..."); Money fee; try { var txSizeInBytes = 250; using var client = new HttpClient(); const string request = @"https://bitcoinfees.earn.com/api/v1/fees/recommended"; var result = client.GetAsync(request, HttpCompletionOption.ResponseContentRead).Result; var json = JObject.Parse(result.Content.ReadAsStringAsync().Result); var fastestSatoshiPerByteFee = json.Value <decimal>("fastestFee"); fee = new Money(fastestSatoshiPerByteFee * txSizeInBytes, MoneyUnit.Satoshi); } catch { Exit("Couldn't calculate transaction fee, try it again later."); throw new Exception("Can't get tx fee"); } WriteLine($"Fee: {fee.ToDecimal(MoneyUnit.BTC).ToString("0.#############################")}btc"); // 5. How much money we can spend? Money availableAmount = unspentCoins.Sum(x => x.Key.Amount); // 6. How much to spend? Money amountToSend = null; string amountString = GetArgumentValue(args, argName: "btc", required: true); if (string.Equals(amountString, "all", StringComparison.OrdinalIgnoreCase)) { amountToSend = availableAmount; amountToSend -= fee; } else { amountToSend = ParseBtcString(amountString); } // 7. Do some checks if (amountToSend < Money.Zero || availableAmount < amountToSend + fee) { Exit("Not enough coins."); } decimal feePc = Math.Round((100 * fee.ToDecimal(MoneyUnit.BTC)) / amountToSend.ToDecimal(MoneyUnit.BTC)); if (feePc > 1) { WriteLine(); WriteLine($"The transaction fee is {feePc.ToString("0.#")}% of your transaction amount."); WriteLine($"Sending:\t {amountToSend.ToDecimal(MoneyUnit.BTC).ToString("0.#############################")}btc"); WriteLine($"Fee:\t\t {fee.ToDecimal(MoneyUnit.BTC).ToString("0.#############################")}btc"); ConsoleKey response = GetYesNoAnswerFromUser(); if (response == ConsoleKey.N) { Exit("User interruption."); } } var totalOutAmount = amountToSend + fee; // 8. Select coins WriteLine("Selecting coins..."); var coinsToSpend = new HashSet <Coin>(); var unspentConfirmedCoins = new List <Coin>(); var unspentUnconfirmedCoins = new List <Coin>(); foreach (var elem in unspentCoins) { if (elem.Value) { unspentConfirmedCoins.Add(elem.Key); } else { unspentUnconfirmedCoins.Add(elem.Key); } } bool haveEnough = SelectCoins(ref coinsToSpend, totalOutAmount, unspentConfirmedCoins); if (!haveEnough) { haveEnough = SelectCoins(ref coinsToSpend, totalOutAmount, unspentUnconfirmedCoins); } if (!haveEnough) { throw new Exception("Not enough funds."); } // 9. Get signing keys var signingKeys = new HashSet <ISecret>(); foreach (var coin in coinsToSpend) { foreach (var elem in operationsPerNotEmptyPrivateKeys) { if (elem.Key.ScriptPubKey == coin.ScriptPubKey) { signingKeys.Add(elem.Key); } } } // 10. Build the transaction WriteLine("Signing transaction..."); var builder = new TransactionBuilder(); var tx = builder .AddCoins(coinsToSpend) .AddKeys(signingKeys.ToArray()) .Send(addressToSend, amountToSend) .SetChange(changeScriptPubKey) .SendFees(fee) .BuildTransaction(true); if (!builder.Verify(tx)) { Exit("Couldn't build the transaction."); } WriteLine($"Transaction Id: {tx.GetHash()}"); var qBitClient = new QBitNinjaClient(Config.Network); // QBit's success response is buggy so let's check manually, too BroadcastResponse broadcastResponse; var success = false; var tried = 0; var maxTry = 7; do { tried++; WriteLine($"Try broadcasting transaction... ({tried})"); broadcastResponse = qBitClient.Broadcast(tx).Result; var getTxResp = qBitClient.GetTransaction(tx.GetHash()).Result; if (getTxResp == null) { Thread.Sleep(3000); continue; } else { success = true; break; } } while (tried <= maxTry); if (!success) { if (broadcastResponse.Error != null) { WriteLine($"Error code: {broadcastResponse.Error.ErrorCode} Reason: {broadcastResponse.Error.Reason}"); } Exit($"The transaction might not have been successfully broadcasted. Please check the Transaction ID in a block explorer.", ConsoleColor.Blue); } Exit("Transaction is successfully propagated on the network.", ConsoleColor.Green); } else if (Config.ConnectionType == ConnectionType.FullNode) { throw new NotImplementedException(); } else { Exit("Invalid connection type."); } } #endregion Exit(color: ConsoleColor.Green); }
public void BuyOwnSafe(string producent, LicenseWarrantyEnum licenseWarranty = LicenseWarrantyEnum.OneYearWarranty) { this.safe = new Safe(producent, licenseWarranty); }
public static string Name <TClass>(Expression <Action <TClass> > e) => Safe.Run(() => Name(e?.Body), string.Empty);
private kList GetFileList(Safe.SharedObjects shared) { var list = new kList(); list.AddColumn("Name", 30, ColumnAlignment.Left); list.AddColumn("Size", 7, ColumnAlignment.Right); if (shared.VolumeMgr != null) { Volume volume = shared.VolumeMgr.CurrentVolume; if (volume != null) { list.Title = "Volume " + shared.VolumeMgr.GetVolumeBestIdentifier(volume); foreach (KeyValuePair<string, VolumeFile> pair in volume.FileList) { list.AddItem(pair.Key, pair.Value.Size); } long freeSpace = volume.FreeSpace; list.Footer = "Free space remaining: " + (freeSpace != Volume.INFINITE_CAPACITY ? freeSpace.ToString() : " infinite"); } } return list; }
public static string Name <TClass, TResult>(Expression <Func <TClass, TResult> > e) => Safe.Run(() => Name(e?.Body), string.Empty);
public override void Execute(Safe.SafeSharedObjects shared) { Execute(shared as SharedObjects); }
public void MaxAmountTest() { Network network = Network.TestNet; SafeAccount account = new SafeAccount(1); string path = Path.Combine(Helpers.CommittedWalletsFolderPath, $"Sending{network}.json"); const string password = ""; Safe safe = Safe.Load(password, path); Assert.Equal(network, safe.Network); Debug.WriteLine($"Unique Safe ID: {safe.UniqueId}"); // create walletjob WalletJob walletJob = new WalletJob(Helpers.SocksPortHandler, Helpers.ControlPortClient, safe, trackDefaultSafe: false, accountsToTrack: account); // note some event WalletJob.ConnectedNodeCountChanged += delegate { if (WalletJob.MaxConnectedNodeCount == WalletJob.ConnectedNodeCount) { Debug.WriteLine( $"{nameof(WalletJob.MaxConnectedNodeCount)} reached: {WalletJob.MaxConnectedNodeCount}"); } else { Debug.WriteLine($"{nameof(WalletJob.ConnectedNodeCount)}: {WalletJob.ConnectedNodeCount}"); } }; walletJob.StateChanged += delegate { Debug.WriteLine($"{nameof(walletJob.State)}: {walletJob.State}"); }; // start syncing var cts = new CancellationTokenSource(); var walletJobTask = walletJob.StartAsync(cts.Token); Task reportTask = Helpers.ReportAsync(cts.Token, walletJob); try { // wait until blocks are synced while (walletJob.State <= WalletState.SyncingMemPool) { Task.Delay(1000).Wait(); } var receive = walletJob.GetUnusedScriptPubKeys(AddressType.Pay2WitnessPublicKeyHash, account, HdPathType.Receive).FirstOrDefault(); IDictionary <Coin, bool> unspentCoins; var bal = walletJob.GetBalance(out unspentCoins, account); var res = walletJob.BuildTransactionAsync(receive, Money.Zero, FeeType.Low, account, allowUnconfirmed: true).Result; Assert.True(res.Success); Assert.True(res.FailingReason == ""); Debug.WriteLine($"Fee: {res.Fee}"); Debug.WriteLine($"FeePercentOfSent: {res.FeePercentOfSent} %"); Debug.WriteLine($"SpendsUnconfirmed: {res.SpendsUnconfirmed}"); Debug.WriteLine($"Transaction: {res.Transaction}"); var foundReceive = false; Assert.InRange(res.Transaction.Outputs.Count, 1, 2); foreach (var output in res.Transaction.Outputs) { if (output.ScriptPubKey == receive) { foundReceive = true; Assert.True(bal.Confirmed + bal.Unconfirmed - res.Fee == output.Value); } } Assert.True(foundReceive); var txProbArrived = false; var prevCount = walletJob.Tracker.TrackedTransactions.Count; walletJob.Tracker.TrackedTransactions.CollectionChanged += delegate { var actCount = walletJob.Tracker.TrackedTransactions.Count; // if arrived if (actCount > prevCount) { txProbArrived = true; } else { prevCount = actCount; } }; var sendRes = walletJob.SendTransactionAsync(res.Transaction).Result; Assert.True(sendRes.Success); Assert.True(sendRes.FailingReason == ""); while (txProbArrived == false) { Debug.WriteLine("Waiting for transaction..."); Task.Delay(1000).Wait(); } Debug.WriteLine("TrackedTransactions collection changed"); Assert.True(walletJob.Tracker.TrackedTransactions.Any(x => x.Transaction.GetHash() == res.Transaction.GetHash())); Debug.WriteLine("Transaction arrived"); } finally { cts.Cancel(); Task.WhenAll(reportTask, walletJobTask).Wait(); } }
private void Delete(int PID, int GID, Safe.Base.Contract.IDbHelper dbhelper) { IList<MR_PageInfo> childs = GetChild(PID, GID, ref dbhelper); if (childs != null) { foreach (MR_PageInfo tmp in childs) { Delete(tmp.PID, GID, dbhelper); } } string cmdText = "delete from R_GroupRight where GID=@GID and PID=@PID"; SqlParameter[] parameters = { new SqlParameter("@GID", GID), new SqlParameter("@PID", PID) }; dbhelper.ExecuteNonQuery(cmdText, parameters); }
public void SendsFailGracefullyTest() { Network network = Network.TestNet; SafeAccount account = new SafeAccount(1); string path = Path.Combine(Helpers.CommittedWalletsFolderPath, $"Sending{network}.json"); const string password = ""; Safe safe = Safe.Load(password, path); Assert.Equal(network, safe.Network); Debug.WriteLine($"Unique Safe ID: {safe.UniqueId}"); // create walletjob WalletJob walletJob = new WalletJob(Helpers.SocksPortHandler, Helpers.ControlPortClient, safe, trackDefaultSafe: false, accountsToTrack: account); // note some event WalletJob.ConnectedNodeCountChanged += delegate { if (WalletJob.MaxConnectedNodeCount == WalletJob.ConnectedNodeCount) { Debug.WriteLine( $"{nameof(WalletJob.MaxConnectedNodeCount)} reached: {WalletJob.MaxConnectedNodeCount}"); } else { Debug.WriteLine($"{nameof(WalletJob.ConnectedNodeCount)}: {WalletJob.ConnectedNodeCount}"); } }; walletJob.StateChanged += delegate { Debug.WriteLine($"{nameof(walletJob.State)}: {walletJob.State}"); }; // start syncing var cts = new CancellationTokenSource(); var walletJobTask = walletJob.StartAsync(cts.Token); Task reportTask = Helpers.ReportAsync(cts.Token, walletJob); try { // wait until blocks are synced while (walletJob.State <= WalletState.SyncingMemPool) { Task.Delay(1000).Wait(); } var history = walletJob.GetSafeHistory(account); foreach (var record in history) { Debug.WriteLine($"{record.TransactionId} {record.Amount} {record.Confirmed}"); } var receive = walletJob.GetUnusedScriptPubKeys(AddressType.Pay2WitnessPublicKeyHash, account, HdPathType.Receive).FirstOrDefault(); IDictionary <Coin, bool> unspentCoins; var bal = walletJob.GetBalance(out unspentCoins, account); // Not enough fee Money amountToSend = (bal.Confirmed + bal.Unconfirmed) - new Money(1m, MoneyUnit.Satoshi); var res = walletJob.BuildTransactionAsync(receive, amountToSend, FeeType.Low, account, allowUnconfirmed: true).Result; Assert.True(res.Success == false); Assert.True(res.FailingReason != ""); Debug.WriteLine($"Expected FailingReason: {res.FailingReason}"); // That's not how you spend all amountToSend = (bal.Confirmed + bal.Unconfirmed); res = walletJob.BuildTransactionAsync(receive, amountToSend, FeeType.Low, account, allowUnconfirmed: true).Result; Assert.True(res.Success == false); Assert.True(res.FailingReason != ""); Debug.WriteLine($"Expected FailingReason: {res.FailingReason}"); // Too much amountToSend = (bal.Confirmed + bal.Unconfirmed) + new Money(1, MoneyUnit.BTC); res = walletJob.BuildTransactionAsync(receive, amountToSend, FeeType.Low, account, allowUnconfirmed: true).Result; Assert.True(res.Success == false); Assert.True(res.FailingReason != ""); Debug.WriteLine($"Expected FailingReason: {res.FailingReason}"); // Minus amountToSend = new Money(-1m, MoneyUnit.BTC); res = walletJob.BuildTransactionAsync(receive, amountToSend, FeeType.Low, account, allowUnconfirmed: true).Result; Assert.True(res.Success == false); Assert.True(res.FailingReason != ""); Debug.WriteLine($"Expected FailingReason: {res.FailingReason}"); // Default account is disabled amountToSend = (bal.Confirmed + bal.Unconfirmed) / 2; Assert.ThrowsAsync <NotSupportedException>(async() => await walletJob.BuildTransactionAsync(receive, amountToSend, FeeType.Low, allowUnconfirmed: true).ConfigureAwait(false)).ContinueWith(t => {}).Wait(); // No such account amountToSend = (bal.Confirmed + bal.Unconfirmed) / 2; Assert.ThrowsAsync <NotSupportedException>(async() => await walletJob.BuildTransactionAsync(receive, amountToSend, FeeType.Low, new SafeAccount(23421), allowUnconfirmed: true).ConfigureAwait(false)).ContinueWith(t => { }).Wait(); } finally { cts.Cancel(); Task.WhenAll(reportTask, walletJobTask).Wait(); } }
private void GetChilds(int groupId, int parentID, bool incluedChild, ref IList<MR_PageInfo> result, ref Safe.Base.Contract.IDbHelper dbhelper) { StringBuilder sb = new StringBuilder(); sb.Append("select a.*,b.btnrightexp from r_pageinfo as a left join R_GroupRight as b on a.pid=b.pid where b.gid=@gid and a.parentID=@parentID"); SqlParameter[] sqlparams = new SqlParameter[]{ new SqlParameter("@gid",groupId ), new SqlParameter("@parentID",parentID) }; DataTable tbl = SQLHelpers.TcAdmin().ExecuteFillDataTable(sb.ToString(), sqlparams); IList<MR_PageInfo> tmp = Safe.Base.Utility.ModelConvertHelper<MR_PageInfo>.ToModels(tbl); //该结点的子节点 if (tmp != null) { foreach (MR_PageInfo tmpc in tmp) { if (!result.Contains(tmpc)) { result.Add(tmpc); if (incluedChild) GetChilds(groupId, tmpc.PID, incluedChild, ref result, ref dbhelper); } } } }
private void UpdateSeries(IDictionary <string, float> sensors) { if (!m_startTime.HasValue) { m_startTime = DateTime.Now; } var isCelcius = sensors[SensorsKeys.Celcius] > 0; m_seriesData[SensorsKeys.Temperature].SetLastValueFormat(isCelcius ? "{0} °C" : "{0} °F"); m_seriesData[SensorsKeys.TemperatureSet].SetLastValueFormat(isCelcius ? "{0} °C" : "{0} °F"); var now = DateTime.Now; var xValue = now.ToOADate(); var xAxisMax = now.AddSeconds(1).ToOADate(); foreach (var kvp in m_seriesData) { var sensorName = kvp.Key; var data = kvp.Value; var readings = sensorName == SensorsKeys.Power ? sensors[SensorsKeys.OutputCurrent] * sensors[SensorsKeys.OutputVoltage] : sensors[sensorName]; var interpolatedValue = Interpolate(readings, data.InterpolationLimits); var point = new DataPoint(); if (Math.Abs(readings) > 0.001) { var roundedValue = (float)Math.Round(readings, 3); point.XValue = xValue; point.YValues = new double[] { interpolatedValue }; point.Tag = point.Label = roundedValue.ToString(CultureInfo.InvariantCulture); point.MarkerSize = 7; point.MarkerStyle = MarkerStyle.Circle; data.SetLastValue(roundedValue); } else { point.IsEmpty = true; data.SetLastValue(null); } data.Seires.Points.Add(point); } if (m_isRecording) { m_lineBuilder.Clear(); m_lineBuilder.Append((now - m_recordStartTime).TotalSeconds.ToString(CultureInfo.InvariantCulture)); m_lineBuilder.Append(","); var values = m_seriesData.Values .Where(x => x.CheckBox.Checked) .Select(x => x.LastValue.HasValue ? x.LastValue.Value.ToString(CultureInfo.InvariantCulture) : string.Empty); m_lineBuilder.Append(string.Join(",", values)); var ex = Safe.Execute(() => { m_fileWriter.WriteLine(m_lineBuilder.ToString()); m_fileWriter.Flush(); }); if (ex != null) { InfoBox.Show("Recording was stopped because of error:\n" + ex.Message); RecordButton.PerformClick(); } } foreach (var series in MainChart.Series) { while (series.Points.Count > MaxItems) { series.Points.RemoveAt(0); } if (series.Points.Count > 0) { var lastPoint = series.Points[series.Points.Count - 1]; if (lastPoint.IsEmpty) { continue; } if (series.Points.Count > 1) { var preLastPoint = series.Points[series.Points.Count - 2]; preLastPoint.Label = null; preLastPoint.MarkerSize = 0; } } } var points = MainChart.Series.SelectMany(x => x.Points).Where(x => !x.IsEmpty).ToArray(); var minDate = DateTime.FromOADate(points.Min(x => x.XValue)); var maxDate = DateTime.FromOADate(points.Max(x => x.XValue)); var range = maxDate - minDate; var framesCount = Math.Floor(range.TotalSeconds / m_timeFrame.TotalSeconds); MainChartScrollBar.Maximum = (int)(framesCount * 30); if (IsTracking) { MainChartScrollBar.Value = MainChartScrollBar.Maximum; ScrollChart(true); } MainChart.ChartAreas[0].AxisX.Minimum = m_startTime.Value.AddSeconds(-5).ToOADate(); MainChart.ChartAreas[0].AxisX.Maximum = xAxisMax; }
public override void AddTo(Safe.SafeSharedObjects shared) { AddTo(shared as SharedObjects); }
public string RegisterUserInfo(BusRouteRquest requestinfo) { System.Object lockThis = new System.Object(); lock (lockThis) { try { WcfServiceBusPlanning.DAL.UserInfo userinfodal = new WcfServiceBusPlanning.DAL.UserInfo(); WcfServiceBusPlanning.Model.UserInfo userinfo = new WcfServiceBusPlanning.Model.UserInfo(); userinfo.Contact = requestinfo.Contact; userinfo.StartName = requestinfo.StartName; userinfo.EndName = requestinfo.EndName; userinfo.DragPoints = requestinfo.DragPoints; userinfo.RegDate = DateTime.Now; Safe safe = new Safe(); userinfo.IP = safe.ClientIp(); //userinfo.Email = "*****@*****.**"; //userinfo.Name = "zhouyong"; //userinfo.Pwd = "123456"; long userid = userinfodal.InsertUserInfo(userinfo); List<WcfServiceBusPlanning.Model.RouteInfo> routeinfoList = new List<WcfServiceBusPlanning.Model.RouteInfo>(); string routeinfostr = requestinfo.RouteInfo;//"113.947187,22.747208;113.946796,22.747468;113.945736,22.748288;113.945405,22.748578;113.943763,22.750241;113.943563,22.750461;113.943483,22.750562;113.943373,22.750482;113.943463,22.750402;113.943462,22.750402;113.943613,22.750221;113.945195,22.748579;113.945666,22.748168;113.946276,22.747678;113.946676,22.747388;113.947627,22.746759;113.948267,22.74638;113.948387,22.74632;113.948647,22.746191;113.949147,22.745942;113.950357,22.745396;113.951337,22.74504;113.951696,22.744922;113.954034,22.744305;113.954384,22.744238;113.954454,22.744218;113.955103,22.744123;113.955363,22.744085;113.955752,22.744029;113.956151,22.743952;113.95709,22.743791;113.957339,22.743743;113.957928,22.743629;113.958208,22.743562;113.958427,22.743514;113.958917,22.7434;113.959116,22.743342;113.959276,22.743294;113.960364,22.742927;113.960544,22.742849;113.961062,22.742625;113.961232,22.742557;113.962619,22.741836;"; WcfServiceBusPlanning.DAL.RouteInfo routeinfodal = new WcfServiceBusPlanning.DAL.RouteInfo(); string[] routeinfo = routeinfostr.Split(';'); for (int i = 0; i < routeinfo.Length - 1; i++) { string[] lnglat = routeinfo[i].Split(','); routeinfoList.Add(new WcfServiceBusPlanning.Model.RouteInfo() { RouteIndex = i + 1, UserID = userid, Lng = Convert.ToDouble(lnglat[0]), Lat = Convert.ToDouble(lnglat[1]) }); } routeinfodal.InsertRouteInfos(routeinfoList); } catch (Exception ex) { string abc = ex.Message; return "0"; } return "1"; } }