private void OutputMessage(OutputMsg msg) { switch (msg) { case OutputMsg.Account_Locked: // tell user account is locked loginLabelTxt.Text = msg.ToString().Replace("_", " "); loginLabelTxt.Foreground = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 255, 0, 0)); break; case OutputMsg.Welcome_Back: // greet user with welcome msg loginLabelTxt.Text = msg.ToString().Replace("_", " ") + " " + username + "!"; loginLabelTxt.Foreground = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 0, 0, 224)); break; case OutputMsg.Invalid_Login_Attempt: // give error msg to user loginLabelTxt.Text = msg.ToString().Replace("_", " "); loginLabelTxt.Foreground = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 153, 0, 204)); break; } Speak(); }
private void WriteMsgLine(string msg) { App.Current.Dispatcher.BeginInvoke(new Action(() => { if (OutputMsg.Length > 10000) { OutputMsg.Clear(); } OutputMsg.AppendLine(msg + "\t" + DateTime.Now.ToString("ss-fff")); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("OutputMsg")); })); }
public TransactionMsg CreateNewTransactionMsg(List <UtxoMsg> utxos, Dictionary <string, long> receiverIdAndValues) { var outputDac = new OutputDac(); var accountDac = new AccountDac(); var transaction = new TransactionMsg(); transaction.Timestamp = Time.EpochTime; transaction.Locktime = 0; foreach (var utxo in utxos) { var account = accountDac.SelectById(utxo.AccountId); if (account == null || account.WatchedOnly) { //TODO: throw exception; return(null); } var privateKey = account.PrivateKey; var inputMsg = new InputMsg(); inputMsg.OutputTransactionHash = utxo.TransactionHash; inputMsg.OutputIndex = utxo.OutputIndex; inputMsg.UnlockScript = Script.BuildUnlockScript(utxo.TransactionHash, utxo.OutputIndex, Base16.Decode(privateKey), Base16.Decode(account.PublicKey)); inputMsg.Size = inputMsg.UnlockScript.Length; transaction.Inputs.Add(inputMsg); outputDac.UpdateSpentStatus(utxo.TransactionHash, utxo.OutputIndex); } int index = 0; foreach (var key in receiverIdAndValues.Keys) { var value = receiverIdAndValues[key]; var outputMsg = new OutputMsg(); outputMsg.Index = index; outputMsg.Amount = value; outputMsg.LockScript = Script.BuildLockScipt(key); outputMsg.Size = outputMsg.LockScript.Length; transaction.Outputs.Add(outputMsg); index++; } transaction.Hash = transaction.GetHash(); return(transaction); }
public OutputMsg GetOutputMsg(string outputTxHash, int outputIndex, out long blockHeight) { OutputMsg msg = null; long height; foreach (var root in this.RootList) { msg = this.getOutputMsg(root, outputTxHash, outputIndex, out height); if (msg != null) { blockHeight = height; return(msg); } } blockHeight = -1; return(null); }
public static Output ConvertToEntiry(this OutputMsg outputMsg, TransactionMsg transaction, BlockMsg blockMsg) { Output output = new Output(); output.Amount = outputMsg.Amount; output.BlockHash = blockMsg.Header.Hash; output.Index = outputMsg.Index; output.LockScript = outputMsg.LockScript; output.Size = outputMsg.Size; output.Index = transaction.Outputs.IndexOf(outputMsg); output.TransactionHash = transaction.Hash; output.Spent = false; output.IsDiscarded = false; var receiverId = AccountIdHelper.CreateAccountAddressByPublicKeyHash( Base16.Decode( Script.GetPublicKeyHashFromLockScript(outputMsg.LockScript) )); output.ReceiverId = receiverId; return(output); }
public static void ExecFilters(string[] args, OutputMsg output, int noLinesToSkipAtStart, string[] lines = null) { UseConsole = false; UseLines = false; int argsCount = 0; StreamReader sr = null; OutputMsg Output = null; if (output == null) { UseConsole = true; Output = OutputX; } else { Output = output; } if (!UseConsole) { if (lines != null) { UseLines = true; Lines = lines; LinesIndex = 0; } else { //Last parameter is source file path string SrcFilePath = ""; if (args.Count() < 1) { Output("No source file"); return; } else { SrcFilePath = args[args.Count() - 1]; argsCount = 1; sr = null; if (File.Exists(SrcFilePath))// only executes if the file at pathtofile exists//you need to add the using System.IO reference at the top of te code to use this { if (SrcFilePath != "") { sr = File.OpenText(SrcFilePath); } } if (sr == null) { Output("File not found)"); return; } } } } string lineToStartAfter = ""; bool started = true; List <string> linesToSkipStartingWith = new List <string>(); List <string> linesToSkipContaining = new List <string>(); string lineToStopAt = ""; int NoLinesToSkipAtStart = noLinesToSkipAtStart; Output("__CLEAR__"); if (args[1].ToLower() == "help") { Output("Usage: filter [LinesToSkip] [LinesContainingToStartAt] [LinesContainingToStopAt]"); Output("[..] are optional args."); Output("The second arg requires the first arg to be present"); Output("The third arg requires the first and second args to be present"); Output("args are either single item or a comma separated list"); Output("Single filter lists have @ as prefix"); Output("If any spaces, arg should be in double quotes. (Whole arg not individual, comma sperated items.)"); Output("LinesToSkip: + or no prefix: Any line STARTING with one of these filters is skipped."); Output(" + prefix is optional for lines starting with filters."); Output(" Alternative is any filter with - prefix "); Output(" - prefix: Any line CONTAINING that filter is skipped."); Output("LinesContainingToStartAt: Lines at start are skipped until first line after line containing one of these filters."); Output("LinesContainingToStopAt: Lines at end are skipped from first line (that line inluded) containing one of these filters."); return; } if (args.Length > argsCount++) { if (args[0].Length > 0) { if (args[0][0] == '@') { // If string starts with @ then use whole argumenet as one (can therefore have a comma) linesToSkipStartingWith = new List <string> { args[0].Substring(1) }; } else { linesToSkipStartingWith = (args[0].Split(new string[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries)).ToList(); } } } //Skip lines: //Starting with is default. + prefix = starting with - prefix is contains linesToSkipContaining = (from f in linesToSkipStartingWith where f[0] == '-' select f).ToList(); linesToSkipStartingWith = (from f in linesToSkipStartingWith where f[0] != '-' select f).ToList(); for (int i = 0; i < linesToSkipStartingWith.Count(); i++) { if (linesToSkipStartingWith[i][0] == '+') { linesToSkipStartingWith[i] = linesToSkipStartingWith[i].Substring(1); } } if (args.Length > argsCount++) { if (args[1].Length > 0) { // If string starts with @ then use whole argumenet as one (can therefore have a comma) lineToStartAfter = args[1]; } } if (lineToStartAfter.Count() > 0) { started = false; } if (args.Length > argsCount++) { if (args[2].Length > 0) { lineToStopAt = args[2]; } } int skipstart = NoLinesToSkipAtStart; bool stop = false; string line; while (((line = ReadLine(sr)) != null) && (!stop)) { if (skipstart-- > 0) { Output(line); continue; } //Skip lines until //Doesn't include start line if (!started) { if (line.ToLower().Contains(lineToStartAfter.ToLower())) { started = true; } continue; } bool skip = false; //Lines to filter out starting with filter foreach (var f in linesToSkipStartingWith) { if (line.Length >= f.Length) { if (line.ToLower().Substring(0, f.Length) == f.ToLower()) { skip = true; break; } } } if (skip) { continue; } skip = false; //Lines to filter out containing filter foreach (var f in linesToSkipContaining) { if (line.Length >= f.Length) { if (line.ToLower().Contains(f.ToLower())) { skip = true; break; } } } if (skip) { continue; } //Doesn't include stop line if (line.ToLower().Contains(lineToStopAt.ToLower())) { stop = true; break; } Output(line); } }
public IRpcMethodResult EstimateTxFeeForSendToAddress(string toAddress, long amount, string comment, string commentTo, bool deductFeeFromAmount) { try { EstimateTxFeeOM result = new EstimateTxFeeOM(); var utxoComponent = new UtxoComponent(); var txComponent = new TransactionComponent(); var settingComponent = new SettingComponent(); var addressBookComponent = new AddressBookComponent(); var accountComponent = new AccountComponent(); if (!AccountIdHelper.AddressVerify(toAddress)) { throw new CommonException(ErrorCode.Service.Transaction.TO_ADDRESS_INVALID); } var setting = settingComponent.GetSetting(); var utxos = utxoComponent.GetAllConfirmedOutputs(); var tx = new TransactionMsg(); var totalSize = tx.Serialize().Length; var output = new OutputMsg(); output.Amount = amount; output.Index = 0; output.LockScript = Script.BuildLockScipt(toAddress); output.Size = output.LockScript.Length; tx.Outputs.Add(output); totalSize += output.Serialize().Length; var blockComponent = new BlockComponent(); var lastBlockHeight = blockComponent.GetLatestHeight(); var totalInput = 0L; var index = 0; double totalAmount = amount; double totalFee = setting.FeePerKB * ((double)totalSize / 1024.0); while (index < utxos.Count) { var account = accountComponent.GetAccountById(utxos[index].AccountId); if (account != null && !string.IsNullOrWhiteSpace(account.PrivateKey)) { var utxoTX = txComponent.GetTransactionMsgByHash(utxos[index].TransactionHash); Block utxoBlock = blockComponent.GetBlockEntiytByHash(utxos[index].BlockHash); if (utxoTX == null || utxoBlock == null) { index++; continue; } if (!utxoBlock.IsVerified) { index++; continue; } if (Time.EpochTime < utxoTX.Locktime) { index++; continue; } if (utxoTX.InputCount == 1 && utxoTX.Inputs[0].OutputTransactionHash == Base16.Encode(HashHelper.EmptyHash())) { var blockHeight = utxoBlock.Height; if (lastBlockHeight - blockHeight < 100L) { index++; continue; } } var input = new InputMsg(); input.OutputTransactionHash = utxos[index].TransactionHash; input.OutputIndex = utxos[index].OutputIndex; input.UnlockScript = Script.BuildUnlockScript(input.OutputTransactionHash, input.OutputIndex, Base16.Decode(decryptPrivateKey(account.PrivateKey)), Base16.Decode(account.PublicKey)); input.Size = input.UnlockScript.Length; tx.Inputs.Add(input); var size = input.Serialize().Length; totalSize += size; totalFee += setting.FeePerKB * ((double)size / 1024.0); totalInput += utxos[index].Amount; } else { index++; continue; } if (!deductFeeFromAmount) { totalAmount = amount + totalFee; } if (totalInput >= (long)Math.Ceiling(totalAmount)) { var size = output.Serialize().Length; if ((totalInput - (long)Math.Ceiling(totalAmount)) > (setting.FeePerKB * (double)size / 1024.0)) { totalSize += size; totalFee += setting.FeePerKB * ((double)size / 1024.0); } break; } index++; } if (totalInput < totalAmount) { throw new CommonException(ErrorCode.Service.Transaction.BALANCE_NOT_ENOUGH); } if (deductFeeFromAmount) { output.Amount -= (long)Math.Ceiling(totalFee); if (output.Amount <= 0) { throw new CommonException(ErrorCode.Service.Transaction.SEND_AMOUNT_LESS_THAN_FEE); } } result.totalFee = Convert.ToInt64(totalFee); result.totalSize = Convert.ToInt32(totalSize); return(Ok(result)); } catch (CommonException ce) { return(Error(ce.ErrorCode, ce.Message, ce)); } catch (Exception ex) { return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex)); } }
public IRpcMethodResult SendMany(string fromAccount, SendManyOutputIM[] receivers, string[] feeDeductAddresses) { try { string result = null; var utxoComponent = new UtxoComponent(); var txComponent = new TransactionComponent(); var settingComponent = new SettingComponent(); var addressBookComponent = new AddressBookComponent(); var accountComponent = new AccountComponent(); var transactionCommentComponent = new TransactionCommentComponent(); var blockComponent = new BlockComponent(); var lastBlockHeight = blockComponent.GetLatestHeight(); var setting = settingComponent.GetSetting(); var utxos = utxoComponent.GetAllConfirmedOutputs(); var tx = new TransactionMsg(); double totalOutput = 0; var totalSize = tx.Serialize().Length; if (receivers == null || receivers.Length == 0) { throw new CommonException(ErrorCode.Service.Transaction.TO_ADDRESS_INVALID); } foreach (var receiver in receivers) { if (!AccountIdHelper.AddressVerify(receiver.address)) { throw new CommonException(ErrorCode.Service.Transaction.TO_ADDRESS_INVALID); } var output = new OutputMsg(); output.Amount = receiver.amount; output.Index = tx.Outputs.Count; output.LockScript = Script.BuildLockScipt(receiver.address); output.Size = output.LockScript.Length; tx.Outputs.Add(output); totalSize += output.Serialize().Length; totalOutput += receiver.amount; } foreach (var address in feeDeductAddresses) { if (receivers.Where(r => r.address == address).Count() == 0) { throw new CommonException(ErrorCode.Service.Transaction.FEE_DEDUCT_ADDRESS_INVALID); } } var totalInput = 0L; var index = 0; double totalFee = setting.FeePerKB * ((double)totalSize / 1024.0); double totalAmount = totalOutput; while (index < utxos.Count) { var account = accountComponent.GetAccountById(utxos[index].AccountId); if (account != null && !string.IsNullOrWhiteSpace(account.PrivateKey)) { var utxoTX = txComponent.GetTransactionMsgByHash(utxos[index].TransactionHash); Block utxoBlock = blockComponent.GetBlockEntiytByHash(utxos[index].BlockHash); if (utxoTX == null || utxoBlock == null) { index++; continue; } if (!utxoBlock.IsVerified) { index++; continue; } if (Time.EpochTime < utxoTX.Locktime) { index++; continue; } if (utxoTX.InputCount == 1 && utxoTX.Inputs[0].OutputTransactionHash == Base16.Encode(HashHelper.EmptyHash())) { var blockHeight = utxoBlock.Height; if (lastBlockHeight - blockHeight < 100L) { index++; continue; } } var input = new InputMsg(); input.OutputTransactionHash = utxos[index].TransactionHash; input.OutputIndex = utxos[index].OutputIndex; input.UnlockScript = Script.BuildUnlockScript(input.OutputTransactionHash, input.OutputIndex, Base16.Decode(decryptPrivateKey(account.PrivateKey)), Base16.Decode(account.PublicKey)); input.Size = input.UnlockScript.Length; tx.Inputs.Add(input); var size = input.Serialize().Length; totalSize += size; totalFee += setting.FeePerKB * ((double)size / 1024.0); totalInput += utxos[index].Amount; } else { index++; continue; } if (feeDeductAddresses == null || feeDeductAddresses.Length == 0) { totalAmount = totalOutput + totalFee; } if (totalInput >= (long)Math.Ceiling(totalAmount)) { var size = tx.Outputs[0].Serialize().Length; if ((totalInput - (long)Math.Ceiling(totalAmount)) > (setting.FeePerKB * (double)size / 1024.0)) { totalSize += size; totalFee += setting.FeePerKB * ((double)size / 1024.0); if (feeDeductAddresses == null || feeDeductAddresses.Length == 0) { totalAmount = totalOutput + totalFee; } var newAccount = accountComponent.GenerateNewAccount(); if (setting.Encrypt) { if (!string.IsNullOrWhiteSpace(_cache.Get <string>("WalletPassphrase"))) { newAccount.PrivateKey = AES128.Encrypt(newAccount.PrivateKey, _cache.Get <string>("WalletPassphrase")); accountComponent.UpdatePrivateKeyAr(newAccount); } else { throw new CommonException(ErrorCode.Service.Wallet.WALLET_HAS_BEEN_LOCKED); } } var newOutput = new OutputMsg(); newOutput.Amount = totalInput - (long)Math.Ceiling(totalAmount); newOutput.Index = tx.Outputs.Count; newOutput.LockScript = Script.BuildLockScipt(newAccount.Id); newOutput.Size = newOutput.LockScript.Length; tx.Outputs.Add(newOutput); } break; } index++; } if (totalInput < totalAmount) { throw new CommonException(ErrorCode.Service.Transaction.BALANCE_NOT_ENOUGH); } if (feeDeductAddresses != null && feeDeductAddresses.Length > 0) { var averageFee = totalFee / feeDeductAddresses.Length; for (int i = 0; i < receivers.Length; i++) { if (feeDeductAddresses.Contains(receivers[i].address)) { tx.Outputs[i].Amount -= (long)Math.Ceiling(averageFee); if (tx.Outputs[i].Amount <= 0) { throw new CommonException(ErrorCode.Service.Transaction.SEND_AMOUNT_LESS_THAN_FEE); } } } } tx.Timestamp = Time.EpochTime; tx.Hash = tx.GetHash(); txComponent.AddTransactionToPool(tx); Startup.P2PBroadcastTransactionAction(tx.Hash); result = tx.Hash; for (int i = 0; i < receivers.Length; i++) { var receiver = receivers[i]; if (!string.IsNullOrWhiteSpace(receiver.tag)) { addressBookComponent.SetTag(receiver.address, receiver.tag); } if (!string.IsNullOrWhiteSpace(receiver.comment)) { transactionCommentComponent.Add(tx.Hash, i, receiver.comment); } } return(Ok(result)); } catch (CommonException ce) { return(Error(ce.ErrorCode, ce.Message, ce)); } catch (Exception ex) { return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex)); } }
/// <summary> /// 创建新的区块 /// </summary> /// <param name="minerName"></param> /// <param name="generatorId"></param> /// <param name="accountId"></param> /// <returns></returns> public BlockMsg CreateNewBlock(string minerName, string generatorId, string remark = null, string accountId = null) { var accountDac = new AccountDac(); var blockDac = new BlockDac(); var outputDac = new OutputDac(); var txDac = new TransactionDac(); var txPool = TransactionPool.Instance; var transactionMsgs = new List <TransactionMsg>(); long lastBlockHeight = -1; string lastBlockHash = Base16.Encode(HashHelper.EmptyHash()); long lastBlockBits = -1; string lastBlockGenerator = null; //获取最后一个区块 var blockEntity = blockDac.SelectLast(); if (blockEntity != null) { lastBlockHeight = blockEntity.Height; lastBlockHash = blockEntity.Hash; lastBlockBits = blockEntity.Bits; lastBlockGenerator = blockEntity.GeneratorId; } long totalSize = 0; long maxSize = BlockSetting.MAX_BLOCK_SIZE - (1 * 1024); var poolItemList = txPool.MainPool.OrderByDescending(t => t.FeeRate).ToList(); var index = 0; while (totalSize < maxSize && index < poolItemList.Count) { var tx = poolItemList[index].Transaction; if (tx != null && transactionMsgs.Where(t => t.Hash == tx.Hash).Count() == 0) { if (txDac.SelectByHash(tx.Hash) == null) { transactionMsgs.Add(tx); totalSize += tx.Size; } else { txPool.RemoveTransaction(tx.Hash); } } else { break; } index++; } var minerAccount = accountDac.SelectDefaultAccount(); if (accountId != null) { var account = accountDac.SelectById(accountId); if (account != null && !string.IsNullOrWhiteSpace(account.PrivateKey)) { minerAccount = account; } } var minerAccountId = minerAccount.Id; BlockMsg newBlockMsg = new BlockMsg(); BlockHeaderMsg headerMsg = new BlockHeaderMsg(); headerMsg.Hash = Base16.Encode(HashHelper.EmptyHash()); headerMsg.GeneratorId = generatorId; newBlockMsg.Header = headerMsg; headerMsg.Height = lastBlockHeight + 1; headerMsg.PreviousBlockHash = lastBlockHash; if (headerMsg.Height == 0) { minerAccountId = BlockSetting.GenesisBlockReceiver; remark = BlockSetting.GenesisBlockRemark; } long totalAmount = 0; long totalFee = 0; foreach (var tx in transactionMsgs) { long totalInputsAmount = 0L; long totalOutputAmount = 0L; foreach (var input in tx.Inputs) { var utxo = outputDac.SelectByHashAndIndex(input.OutputTransactionHash, input.OutputIndex); if (utxo != null) { totalInputsAmount += utxo.Amount; } } foreach (var output in tx.Outputs) { totalOutputAmount += output.Amount; } totalAmount += totalOutputAmount; totalFee += (totalInputsAmount - totalOutputAmount); } //var work = new POW(headerMsg.Height); BlockMsg prevBlockMsg = null; BlockMsg prevStepBlockMsg = null; if (blockEntity != null) { prevBlockMsg = this.convertEntityToBlockMsg(blockEntity); } if (headerMsg.Height >= POC.DIFFIUCLTY_ADJUST_STEP) { prevStepBlockMsg = this.GetBlockMsgByHeight(headerMsg.Height - POC.DIFFIUCLTY_ADJUST_STEP - 1); } var newBlockReward = POC.GetNewBlockReward(headerMsg.Height); headerMsg.Bits = POC.CalculateBaseTarget(headerMsg.Height, prevBlockMsg, prevStepBlockMsg); headerMsg.TotalTransaction = transactionMsgs.Count + 1; var coinbaseTxMsg = new TransactionMsg(); coinbaseTxMsg.Timestamp = Time.EpochTime; coinbaseTxMsg.Locktime = 0; var coinbaseInputMsg = new InputMsg(); coinbaseTxMsg.Inputs.Add(coinbaseInputMsg); coinbaseInputMsg.OutputIndex = 0; coinbaseInputMsg.OutputTransactionHash = Base16.Encode(HashHelper.EmptyHash()); coinbaseInputMsg.UnlockScript = Script.BuildMinerScript(minerName, remark); coinbaseInputMsg.Size = coinbaseInputMsg.UnlockScript.Length; var coinbaseOutputMsg = new OutputMsg(); coinbaseTxMsg.Outputs.Add(coinbaseOutputMsg); coinbaseOutputMsg.Amount = newBlockReward + totalFee; coinbaseOutputMsg.LockScript = Script.BuildLockScipt(minerAccountId); coinbaseOutputMsg.Size = coinbaseOutputMsg.LockScript.Length; coinbaseOutputMsg.Index = 0; coinbaseTxMsg.Hash = coinbaseTxMsg.GetHash(); newBlockMsg.Transactions.Insert(0, coinbaseTxMsg); foreach (var tx in transactionMsgs) { newBlockMsg.Transactions.Add(tx); } headerMsg.PayloadHash = newBlockMsg.GetPayloadHash(); var dsa = ECDsa.ImportPrivateKey(Base16.Decode(minerAccount.PrivateKey)); var signResult = dsa.SingnData(Base16.Decode(headerMsg.PayloadHash)); headerMsg.BlockSignature = Base16.Encode(signResult); headerMsg.BlockSigSize = headerMsg.BlockSignature.Length; headerMsg.TotalTransaction = newBlockMsg.Transactions.Count; return(newBlockMsg); }
private async void button2_ClickAsync(object sender, RoutedEventArgs e) { button2.IsEnabled = false; // 读取内容 var list = new List <PersonFileDto>(); ExcelPackage.LicenseContext = LicenseContext.NonCommercial; try { using (var package = new ExcelPackage(new FileInfo(FilePath.Text))) { var sheet = package.Workbook.Worksheets.First(); int startRowNumber = sheet.Dimension.Start.Row + 2; int endRowNumber = sheet.Dimension.End.Row; // 循环获取整个Excel数据表数据 for (int i = startRowNumber; i <= endRowNumber; i++) { var fulltime = sheet.Cells[i, 12].Text?.Trim(); var birthday = sheet.Cells[i, 8].Text?.Trim(); var getBirthday = false; DateTime date = DateTime.Today; if (birthday != null) { getBirthday = DateTime.TryParseExact(birthday, "yyyy/M/d", CultureInfo.InvariantCulture, DateTimeStyles.None, out date); } var contractType = sheet.Cells[i, 9].Text?.Trim(); var contactRole = sheet.Cells[i, 15].Text?.Trim(); byte contactRoleIntValue = 9; switch (contactRole) { case "安全生产分管领导": contactRoleIntValue = 1; break; case "安监机构负责人": contactRoleIntValue = 2; break; case "本部门负责安全生产领导": contactRoleIntValue = 3; break; case "安全生产工作联系人": contactRoleIntValue = 4; break; default: break; } byte contractTypeIntValue = 0; switch (contractType) { case "派遣制": contractTypeIntValue = 1; break; case "合作单位": contractTypeIntValue = 2; break; default: break; } var personFile = new PersonFileDto { ProvinceName = sheet.Cells[i, 2].Text?.Trim(), CityName = sheet.Cells[i, 3].Text?.Trim(), OrgName = sheet.Cells[i, 4].Text?.Trim(), RealName = sheet.Cells[i, 5].Text?.Trim(), Sex = sheet.Cells[i, 6].Text?.Trim(), Position = sheet.Cells[i, 7].Text?.Trim(), Birthday = getBirthday ? date : DateTime.Today, ContractType = contractTypeIntValue, Number = sheet.Cells[i, 10].Text?.Trim(), Education = sheet.Cells[i, 11].Text?.Trim(), IsFulltime = (byte)(fulltime == "是" ? 1 : 0), Phone = sheet.Cells[i, 13].Text?.Trim(), Email = sheet.Cells[i, 14].Text?.Trim(), ContactRole = contactRoleIntValue, //InternalPhone = sheet.Cells[i, 16].Text?.Trim(), //PublicPhone = sheet.Cells[i, 17].Text?.Trim(), IsPartTime = 0 }; list.Add(personFile); } } } catch (Exception exp) { Console.WriteLine(exp.Message); System.Windows.MessageBox.Show("解析错误,请选择相对应的表格"); } OutputMsg.AppendText("读取表格数据完成,准备入库!"); // 入库 var helper = new WorkSafetyDBHelper(Dispatcher, OutputMsg); await helper.InsertPersonFileAsync(list); button2.IsEnabled = true; }
public TransactionMsg CreateNewTransactionMsg(string senderAccountId, Dictionary <string, long> receiverIdAndValues, long fee) { var outputDac = new OutputDac(); var accountDac = new AccountDac(); var account = accountDac.SelectById(senderAccountId); if (account == null || account.WatchedOnly) { //TODO: throw exception; return(null); } var balance = UtxoSet.Instance.GetAccountBlanace(senderAccountId, true); long totalOutput = fee; long totalInput = 0; foreach (var key in receiverIdAndValues.Keys) { totalOutput += receiverIdAndValues[key]; } if (totalOutput > balance) { //TODO: throw exception return(null); } var transaction = new TransactionMsg(); transaction.Timestamp = Time.EpochTime; transaction.Locktime = 0; var outputs = outputDac.SelectUnspentByReceiverId(senderAccountId); foreach (var output in outputs) { var inputMsg = new InputMsg(); inputMsg.OutputTransactionHash = output.TransactionHash; inputMsg.OutputIndex = output.Index; inputMsg.UnlockScript = Script.BuildUnlockScript(output.TransactionHash, output.Index, Base16.Decode(account.PrivateKey), Base16.Decode(account.PublicKey)); inputMsg.Size = inputMsg.UnlockScript.Length; transaction.Inputs.Add(inputMsg); outputDac.UpdateSpentStatus(output.TransactionHash, output.Index); totalInput += output.Amount; if (totalInput >= totalOutput) { break; } } int index = 0; foreach (var key in receiverIdAndValues.Keys) { var value = receiverIdAndValues[key]; var outputMsg = new OutputMsg(); outputMsg.Index = index; outputMsg.Amount = value; outputMsg.LockScript = Script.BuildLockScipt(key); outputMsg.Size = outputMsg.LockScript.Length; transaction.Outputs.Add(outputMsg); index++; } if (totalInput > totalOutput) { var value = totalInput - totalOutput; var outputMsg = new OutputMsg(); outputMsg.Index = index; outputMsg.Amount = value; outputMsg.LockScript = Script.BuildLockScipt(senderAccountId); outputMsg.Size = outputMsg.LockScript.Length; transaction.Outputs.Add(outputMsg); index++; } transaction.Hash = transaction.GetHash(); return(transaction); }
public BlockMsg CreateNewBlock(string minerName, string accountId = null) { var accountDac = new AccountDac(); var blockDac = new BlockDac(); var outputDac = new OutputDac(); var txDac = new TransactionDac(); var txPool = TransactionPool.Instance; var transactionMsgs = new List <TransactionMsg>(); long lastBlockHeight = -1; string lastBlockHash = Base16.Encode(HashHelper.EmptyHash()); long lastBlockBits = -1; var blockEntity = blockDac.SelectLast(); if (blockEntity != null) { lastBlockHeight = blockEntity.Height; lastBlockHash = blockEntity.Hash; lastBlockBits = blockEntity.Bits; } long totalSize = 0; long maxSize = BlockSetting.MAX_BLOCK_SIZE - (500 * 1024); var poolItemList = txPool.MainPool.OrderByDescending(t => t.FeeRate).ToList(); var index = 0; while (totalSize < maxSize && index < poolItemList.Count) { var tx = poolItemList[index].Transaction; if (tx != null && transactionMsgs.Where(t => t.Hash == tx.Hash).Count() == 0) { if (txDac.SelectByHash(tx.Hash) == null) { transactionMsgs.Add(tx); totalSize += tx.Size; } else { txPool.RemoveTransaction(tx.Hash); } } else { break; } index++; } var minerAccount = accountDac.SelectDefaultAccount(); if (accountId != null) { var account = accountDac.SelectById(accountId); if (account != null && !string.IsNullOrWhiteSpace(account.PrivateKey)) { minerAccount = account; } } BlockMsg newBlockMsg = new BlockMsg(); BlockHeaderMsg headerMsg = new BlockHeaderMsg(); newBlockMsg.Header = headerMsg; headerMsg.Height = lastBlockHeight + 1; headerMsg.PreviousBlockHash = lastBlockHash; long totalAmount = 0; long totalFee = 0; foreach (var tx in transactionMsgs) { long totalInputsAmount = 0L; long totalOutputAmount = 0L; foreach (var input in tx.Inputs) { var utxo = outputDac.SelectByHashAndIndex(input.OutputTransactionHash, input.OutputIndex); if (utxo != null) { totalInputsAmount += utxo.Amount; } } foreach (var output in tx.Outputs) { totalOutputAmount += output.Amount; } totalAmount += totalOutputAmount; totalFee += (totalInputsAmount - totalOutputAmount); } var work = new POW(headerMsg.Height); BlockMsg previous4032Block = null; if (headerMsg.Height > POW.DiffiucltyAdjustStep) { previous4032Block = this.GetBlockMsgByHeight(headerMsg.Height - POW.DiffiucltyAdjustStep); } var newBlockReward = work.GetNewBlockReward(); headerMsg.Bits = work.CalculateNextWorkTarget(lastBlockHeight, lastBlockBits, previous4032Block); headerMsg.TotalTransaction = transactionMsgs.Count + 1; var coinbaseTxMsg = new TransactionMsg(); coinbaseTxMsg.Timestamp = Time.EpochTime; coinbaseTxMsg.Locktime = 0; var coinbaseInputMsg = new InputMsg(); coinbaseTxMsg.Inputs.Add(coinbaseInputMsg); coinbaseInputMsg.OutputIndex = 0; coinbaseInputMsg.OutputTransactionHash = Base16.Encode(HashHelper.EmptyHash()); coinbaseInputMsg.UnlockScript = Script.BuildMinerScript(minerName); coinbaseInputMsg.Size = coinbaseInputMsg.UnlockScript.Length; var coinbaseOutputMsg = new OutputMsg(); coinbaseTxMsg.Outputs.Add(coinbaseOutputMsg); coinbaseOutputMsg.Amount = newBlockReward + totalFee; coinbaseOutputMsg.LockScript = Script.BuildLockScipt(minerAccount.Id); coinbaseOutputMsg.Size = coinbaseOutputMsg.LockScript.Length; coinbaseOutputMsg.Index = 0; coinbaseTxMsg.Hash = coinbaseTxMsg.GetHash(); newBlockMsg.Transactions.Insert(0, coinbaseTxMsg); foreach (var tx in transactionMsgs) { newBlockMsg.Transactions.Add(tx); } return(newBlockMsg); }
/// <summary> /// 创建新的区块 /// </summary> /// <param name="minerName"></param> /// <param name="generatorId"></param> /// <param name="accountId"></param> /// <returns></returns> public BlockMsg CreateNewBlock(string minerName, string generatorId, string remark = null, string accountId = null) { var accountDac = AccountDac.Default; var blockDac = BlockDac.Default; var txDac = TransactionDac.Default; var txPool = TransactionPool.Instance; var txComponent = new TransactionComponent(); var transactionMsgs = new List <TransactionMsg>(); long lastBlockHeight = -1; string lastBlockHash = Base16.Encode(HashHelper.EmptyHash()); long lastBlockBits = -1; string lastBlockGenerator = null; //获取最后一个区块 var blockEntity = blockDac.SelectLast(); if (blockEntity != null) { lastBlockHeight = blockEntity.Header.Height; lastBlockHash = blockEntity.Header.Hash; lastBlockBits = blockEntity.Header.Bits; lastBlockGenerator = blockEntity.Header.GeneratorId; } long totalSize = 0; long totalInput = 0; long totalOutput = 0; long totalAmount = 0; long totalFee = 0; long maxSize = Consensus.BlockSetting.MAX_BLOCK_SIZE - (1 * 1024); //获取待打包的交易 var txs = txPool.GetTxsWithoutRepeatCost(10, maxSize); var hashIndexs = new List <string>(); foreach (var tx in txs) { totalSize += tx.Size; totalInput += tx.InputCount; totalOutput += tx.OutputCount; hashIndexs.AddRange(tx.Inputs.Select(x => $"{x.OutputTransactionHash}_{x.OutputIndex}")); long totalOutputAmount = tx.Outputs.Sum(x => x.Amount); totalAmount += totalOutputAmount; } var utxos = UtxoSetDac.Default.Get(hashIndexs); var totalInputAmount = utxos.Sum(x => x.Amount); totalFee = totalInputAmount - totalAmount; transactionMsgs.AddRange(txs); var accounts = AccountDac.Default.SelectAll(); var minerAccount = accounts.OrderBy(x => x.Timestamp).FirstOrDefault(); if (accountId != null) { var account = accounts.FirstOrDefault(x => x.Id == accountId); if (account != null && !string.IsNullOrWhiteSpace(account.PrivateKey)) { minerAccount = account; } } var minerAccountId = minerAccount.Id; BlockMsg newBlockMsg = new BlockMsg(); BlockHeaderMsg headerMsg = new BlockHeaderMsg(); headerMsg.Hash = Base16.Encode(HashHelper.EmptyHash()); headerMsg.GeneratorId = generatorId; newBlockMsg.Header = headerMsg; headerMsg.Height = lastBlockHeight + 1; headerMsg.PreviousBlockHash = lastBlockHash; if (headerMsg.Height == 0) { minerAccountId = Consensus.BlockSetting.GenesisBlockReceiver; remark = Consensus.BlockSetting.GenesisBlockRemark; } BlockMsg prevBlockMsg = null; BlockMsg prevStepBlockMsg = null; if (blockEntity != null) { prevBlockMsg = blockEntity; } if (headerMsg.Height >= POC.DIFFIUCLTY_ADJUST_STEP) { var prevStepHeight = 0L; if (!GlobalParameters.IsTestnet && headerMsg.Height <= POC.DIFFICULTY_CALCULATE_LOGIC_ADJUST_HEIGHT) { prevStepHeight = headerMsg.Height - POC.DIFFIUCLTY_ADJUST_STEP - 1; } else { prevStepHeight = headerMsg.Height - POC.DIFFIUCLTY_ADJUST_STEP; } prevStepBlockMsg = blockDac.SelectByHeight(prevStepHeight); } var newBlockReward = POC.GetNewBlockReward(headerMsg.Height); headerMsg.Bits = POC.CalculateBaseTarget(headerMsg.Height, prevBlockMsg, prevStepBlockMsg); headerMsg.TotalTransaction = transactionMsgs.Count + 1; var coinbaseTxMsg = new TransactionMsg(); coinbaseTxMsg.Timestamp = Time.EpochTime; coinbaseTxMsg.Locktime = 0; var coinbaseInputMsg = new InputMsg(); coinbaseTxMsg.Inputs.Add(coinbaseInputMsg); coinbaseInputMsg.OutputIndex = 0; coinbaseInputMsg.OutputTransactionHash = Base16.Encode(HashHelper.EmptyHash()); coinbaseInputMsg.UnlockScript = Script.BuildMinerScript(minerName, remark); coinbaseInputMsg.Size = coinbaseInputMsg.UnlockScript.Length; var coinbaseOutputMsg = new OutputMsg(); coinbaseTxMsg.Outputs.Add(coinbaseOutputMsg); coinbaseOutputMsg.Amount = newBlockReward + totalFee; coinbaseOutputMsg.LockScript = Script.BuildLockScipt(minerAccountId); coinbaseOutputMsg.Size = coinbaseOutputMsg.LockScript.Length; coinbaseOutputMsg.Index = 0; if (newBlockReward < 0 || totalFee < 0 || coinbaseOutputMsg.Amount < 0) { LogHelper.Warn($"newBlockReward:{newBlockReward}"); LogHelper.Warn($"totalFee:{totalFee}"); LogHelper.Warn($"coinbaseOutputMsg.Amount:{coinbaseOutputMsg.Amount}"); throw new CommonException(ErrorCode.Engine.Transaction.Verify.COINBASE_OUTPUT_AMOUNT_ERROR); } coinbaseTxMsg.Hash = coinbaseTxMsg.GetHash(); newBlockMsg.Transactions.Insert(0, coinbaseTxMsg); foreach (var tx in transactionMsgs) { newBlockMsg.Transactions.Add(tx); } headerMsg.PayloadHash = newBlockMsg.GetPayloadHash(); LogHelper.Warn($"{headerMsg.Height}::{headerMsg.PayloadHash}"); LogHelper.Warn($"PayloadHash::{headerMsg.PayloadHash}"); LogHelper.Warn($"BlockSignature::{headerMsg.BlockSignature}"); LogHelper.Warn($"miner::{minerName}"); headerMsg.BlockSignature = Base16.Encode(HashHelper.EmptyHash()); headerMsg.BlockSigSize = headerMsg.BlockSignature.Length; headerMsg.TotalTransaction = newBlockMsg.Transactions.Count; return(newBlockMsg); }