/// <summary> /// Returns a multi-line hexadecimal dump of the specified {@link ByteBuf} that is easy to read by humans, /// starting at the given {@code offset} using the given {@code length}. /// </summary> public static string PrettyHexDump(IByteBuffer buffer, int offset, int length) => HexUtil.DoPrettyHexDump(buffer, offset, length);
/// <summary> /// Appends the prettified multi-line hexadecimal dump of the specified {@link ByteBuf} to the specified /// {@link StringBuilder} that is easy to read by humans, starting at the given {@code offset} using /// the given {@code length}. /// </summary> public static void AppendPrettyHexDump(StringBuilder dump, IByteBuffer buf, int offset, int length) => HexUtil.DoAppendPrettyHexDump(dump, buf, offset, length);
/// <summary> /// Returns a <a href="http://en.wikipedia.org/wiki/Hex_dump">hex dump</a> /// of the specified buffer's sub-region. /// </summary> public static string HexDump(IByteBuffer buffer, int fromIndex, int length) => HexUtil.DoHexDump(buffer, fromIndex, length);
/// <summary> /// Returns a <a href="http://en.wikipedia.org/wiki/Hex_dump">hex dump</a> /// of the specified buffer's sub-region. /// </summary> public static string HexDump(byte[] array, int fromIndex, int length) => HexUtil.DoHexDump(array, fromIndex, length);
public static AppOptions ParseProcessArgs(string[] args) { var opts = new AppOptions(); // Parse process arguments. var processArgs = ProcessArgs.Parse(args); opts.EntryContractName = null; opts.EntryContractFunctionName = null; if (!string.IsNullOrWhiteSpace(processArgs.Entry)) { var entryParts = processArgs.Entry.Split('.', 2, StringSplitOptions.RemoveEmptyEntries); opts.EntryContractName = entryParts[0]; if (entryParts.Length > 1) { opts.EntryContractFunctionName = entryParts[1]; } } string workspaceDir; if (!string.IsNullOrEmpty(processArgs.Directory)) { workspaceDir = processArgs.Directory.Replace('\\', '/'); } else if (!string.IsNullOrEmpty(processArgs.SingleFile)) { // If workspace is not provided, derive a determistic temp directory for the single file. workspaceDir = Path.Combine(Path.GetTempPath(), HexUtil.GetHexFromBytes(SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(processArgs.SingleFile)))); Directory.CreateDirectory(workspaceDir); workspaceDir = workspaceDir.Replace('\\', '/'); } else { throw new Exception("A directory or single file for debugging must be specified."); } string outputDir = workspaceDir + "/" + GENERATED_DATA_DIR; opts.SourceOutputDir = outputDir + "/src"; opts.BuildOutputDir = outputDir + "/build"; opts.SolCompilationSourcePath = workspaceDir; if (!string.IsNullOrEmpty(processArgs.SingleFile)) { // Normalize file path. opts.SingleFile = processArgs.SingleFile.Replace('\\', '/'); // Check if provided file is inside the workspace directory. if (opts.SingleFile.StartsWith(workspaceDir, StringComparison.OrdinalIgnoreCase)) { opts.SingleFile = opts.SingleFile.Substring(workspaceDir.Length).Trim('/'); } else { // File is outside of workspace so setup special pathing. opts.SolCompilationSourcePath = opts.SingleFile; } } return(opts); }
/// <summary> /// Builds a transaction that sends value from one address to another. /// Change is spent to the source address, if necessary. /// </summary> /// <param name="request"></param> /// <param name="feeFactor"></param> /// <returns></returns> /// <exception cref="BusinessException"></exception> public async Task <BuildTransactionResponse> BuildSingleTransactionAsync(BuildSingleTransactionRequest request, decimal feeFactor) { if (string.IsNullOrWhiteSpace(request.FromAddress)) { throw new BusinessException(ErrorReason.BadRequest, "FromAddress missing"); } if (string.IsNullOrWhiteSpace(request.ToAddress)) { throw new BusinessException(ErrorReason.BadRequest, "ToAddress missing"); } if (!long.TryParse(request.Amount, out var amount) || amount <= 0) { throw new BusinessException(ErrorReason.BadRequest, $"Invalid amount {amount}"); } var feePerKb = await _feeService.GetFeePerKb(); if (TransactionRules.IsDustAmount(amount, Transaction.PayToPubKeyHashPkScriptSize, new Amount(feePerKb))) { throw new BusinessException(ErrorReason.AmountTooSmall, "Amount is dust"); } const int outputVersion = 0; const int lockTime = 0; const int expiry = 0; // Number of outputs newly build tx will contain, // not including the change address const int numOutputs = 1; // Lykke api doesn't have option to specify a change address. var changeAddress = Address.Decode(request.FromAddress); var toAddress = Address.Decode(request.ToAddress); var allInputs = (await GetUtxosForAddress(request.FromAddress)).ToList(); long estFee = 0; long totalSpent = 0; var consumedInputs = new List <Transaction.Input>(); bool HasEnoughInputs(out long fee) { var calculateWithChange = false; while (true) { var changeCount = calculateWithChange ? 1 : 0; fee = _feeService.CalculateFee(feePerKb, consumedInputs.Count, numOutputs + changeCount, feeFactor); var estAmount = amount + (request.IncludeFee ? 0 : fee); if (totalSpent < estAmount) { return(false); } if (totalSpent == estAmount) { return(true); } if (totalSpent > estAmount && calculateWithChange) { return(true); } // Loop one more time but make sure change is accounted for this time. if (totalSpent > estAmount) { calculateWithChange = true; } } } // Accumulate inputs until we have enough to cover the cost // of the amount + fee foreach (var input in allInputs) { consumedInputs.Add(input); totalSpent += input.InputAmount; if (HasEnoughInputs(out estFee)) { break; } } // If all inputs do not have enough value to fund the transaction. if (totalSpent < amount + (request.IncludeFee ? 0 : estFee)) { throw new BusinessException(ErrorReason.NotEnoughBalance, "Address balance too low"); } // The fee either comes from the change or the sent amount var send = amount - (request.IncludeFee ? estFee : 0); var change = (totalSpent - amount) - (request.IncludeFee ? 0 : estFee); // If all inputs do not have enough value to fund the transaction, throw error. if (request.IncludeFee && estFee > amount) { throw new BusinessException(ErrorReason.AmountTooSmall, "Amount not enough to include fee"); } // If all inputs do not have enough value to fund the transaction, throw error. if (totalSpent < amount + (request.IncludeFee ? 0 : estFee)) { throw new BusinessException(ErrorReason.NotEnoughBalance, "Address balance too low"); } // Build outputs to address + change address. // If any of the outputs is zero value, exclude it. For example, if there is no change. var outputs = new[] { new Transaction.Output(send, outputVersion, toAddress.BuildScript().Script), new Transaction.Output(change, outputVersion, changeAddress.BuildScript().Script) }.Where(o => o.Amount != 0).ToArray(); var newTx = new Transaction( Transaction.SupportedVersion, consumedInputs.ToArray(), outputs, lockTime, expiry ); await _spentOutputRepository.InsertSpentOutputsAsync(request.OperationId, consumedInputs.Select(p => new Output(p.PreviousOutpoint.Hash.ToString(), p.PreviousOutpoint.Index))); return(new BuildTransactionResponse { TransactionContext = HexUtil.FromByteArray(newTx.Serialize()) }); }
/// <summary> /// Format the raw text into an easier (aka faster) format to parse. /// * Process \n such that they are removed and 'new lines' created /// * Break down the text into lines that fit the requested width /// </summary> /// <param name="text">The raw text to parse</param> private void format(string text) { //Debug.Log("Formatting: " + text); _guiStyle = new GUIStyle(); int endIndex; _line = new StringBuilder(); _fLine = new FormattedLine(); addLineHeight(false); _lineLength = 0; _lineHeight = 0.0f; StringBuilder word = new StringBuilder(); _sequence = new Sequence(); _nextSequence = new Sequence(); for (int letterIndex = 0; letterIndex < text.Length; letterIndex++) { int currentLetterIndex = letterIndex; if (text[letterIndex] == '\\' && text.Length > letterIndex + 1 && text[letterIndex + 1] == '\\') { // Escaped '\' word.Append("\\"); letterIndex++; // Skip the second '\' } else if (text[letterIndex] == '\n') { // New line addWordToLine(word.ToString()); createNewLine(); word.Length = 0; } else if (text[letterIndex] == ' ' && word.Length != 0) { // Reached a word boundary addWordToLine(word.ToString()); word.Length = 0; word.Append(' '); } else if (text[letterIndex] == '[' && text.Length > letterIndex + 1 && text[letterIndex + 1] == '[') { // Escaped '[' word.Append("[["); letterIndex++; // Skip the second '[' } else if (text[letterIndex] == '[' && text.Length > letterIndex + 1 && (endIndex = text.IndexOf(']', letterIndex)) != -1) { // Command addWordToLine(word.ToString()); word.Length = 0; string command = text.Substring(letterIndex + 1, endIndex - letterIndex - 1); letterIndex += command.Length + 1; string[] commandList = command.Split(' '); for (int commandIndex = 0; commandIndex < commandList.Length; commandIndex++) { command = commandList[commandIndex].ToUpper(); if (command.IsEqual("NL") || command.IsEqual("NEWLINE")) { createNewLine(); } else if (command.IsEqual("BC") || command.IsEqual("BACKCOLOR")) //if (command == "BC" || command == "BACKCOLOR") { // Background Color if (commandList.Length > commandIndex + 1) { commandIndex++; Color color; if (commandList[commandIndex] == "?") { _nextSequence.Add(new BackColor(_guiStyle.normal.background)); addCommandToLine("BC " + commandList[commandIndex]); } else if (HexUtil.HexToColor(commandList[commandIndex], out color)) { _nextSequence.Add(new BackColor(commandList[commandIndex])); addCommandToLine("BC " + commandList[commandIndex]); } else { Debug.LogError("The 'BackColor' command requires a color parameter of RRGGBBAA or '?'."); } } else { Debug.LogError("The 'BackColor' command requires a color parameter of RRGGBBAA or '?'."); } } else if (command.IsEqual("C") || command.IsEqual("COLOR")) { // Color if (commandList.Length > commandIndex + 1) { commandIndex++; Color color; if (commandList[commandIndex] == "?" || HexUtil.HexToColor(commandList[commandIndex], out color)) { _nextSequence.Add(new FontColor(color)); addCommandToLine("C " + commandList[commandIndex]); } else { Debug.LogError("The 'color' command requires a color parameter of RRGGBBAA or '?'."); } } else { Debug.LogError("The 'color' command requires a color parameter of RRGGBBAA:\n" + text); } } else if (command.IsEqual("F") || command.IsEqual("FONT")) { // Font if (commandList.Length > commandIndex + 1) { commandIndex++; Font font = (Font)fontTable[commandList[commandIndex]]; if (font == null) { Debug.LogError("The font '" + commandList[commandIndex] + "' does not exist within Assets/Resources/Fonts/"); } else { _guiStyle.font = font; // Update the font to properly measure text addCommandToLine("F " + commandList[commandIndex]); _nextSequence.Add(new CustomFont(font)); } if (commandList.Length > commandIndex + 1) { commandIndex++; int fontSize; if (System.Int32.TryParse(commandList[commandIndex], out fontSize)) { addCommandToLine("FS " + commandList[commandIndex]); _nextSequence.Add(new FontSize(fontSize)); _guiStyle.fontSize = fontSize; // Update the size to properly measure text } else { Debug.LogError("The font size '" + commandList[commandIndex] + "' is not a valid integer"); } } } else { Debug.LogError("The 'font' command requires a font name parameter and an optional font size parameter."); } } else if (command.IsEqual("FA") || command.IsEqual("FONTATTRIBUTE")) { // Font Attribute if (commandList.Length > commandIndex + 1) { commandIndex++; string attribute = commandList[commandIndex].ToUpper(); switch (attribute) { case "U": case "UNDERLINE": attribute = "U"; _nextSequence.underline = true; break; case "-U": case "-UNDERLINE": attribute = "-U"; _nextSequence.underline = false; break; case "S": case "STRIKETHROUGH": attribute = "S"; Debug.Log("strike ? " + _nextSequence.txt); _nextSequence.strikeThrough = true; break; case "-S": case "-STRIKETHROUGH": attribute = "-S"; _nextSequence.strikeThrough = false; break; default: attribute = ""; Debug.LogError("The 'font attribute' command requires a font parameter of U (underline on), -U (underline off), S (strikethrough on) or -S (strikethrough off)."); break; } if (attribute.Length != 0) { addCommandToLine("FA " + attribute); } } else { Debug.LogError("The 'font attribute' command requires a font parameter of U (underline on), -U (underline off), S (strikethrough on) or -S (strikethrough off)."); } } else if (command.IsEqual("FS") || command.IsEqual("FONTSIZE")) { // Font Size if (commandList.Length > commandIndex + 1) { commandIndex++; int fontSize; if (System.Int32.TryParse(commandList[commandIndex], out fontSize)) { addCommandToLine("FS " + commandList[commandIndex]); _nextSequence.Add(new FontSize(fontSize)); _guiStyle.fontSize = fontSize; // Update the size to properly measure text } else { Debug.LogError("The font size '" + commandList[commandIndex] + "' is not a valid integer"); } } else { Debug.LogError("The 'font size' command requires a font size parameter."); } } else if (command.IsEqual("H") || command.IsEqual("HYPERLINK")) { // Hyperlink on if (commandList.Length > commandIndex + 1) { commandIndex++; addCommandToLine("H " + commandList[commandIndex]); _nextSequence.hyperlinkId = HYPERLINK_TAG + commandList[commandIndex]; } else { Debug.LogError("The 'hyperlink' command requires an hyperlink id parameter."); } } else if (command.IsEqual("-H") || command.IsEqual("-HYPERLINK")) { // Hyperlink off addCommandToLine("-H"); _nextSequence.hyperlinkId = ""; } else if (command.IsEqual("HA") || command.IsEqual("HALIGN")) { // Horizontal line alignment if (commandList.Length > commandIndex + 1) { commandIndex++; string alignment = commandList[commandIndex].ToUpper(); switch (alignment) { case "L": case "LEFT": alignment = "L"; _fLine.alignement = TextAlignment.Left; break; case "R": case "RIGHT": alignment = "R"; _fLine.alignement = TextAlignment.Right; break; case "C": case "CENTER": alignment = "C"; _fLine.alignement = TextAlignment.Center; break; default: alignment = ""; Debug.LogError("The 'HAlign' command requires an alignment parameter of L (left), R (right), or C (center)."); break; } if (alignment.Length != 0) { addCommandToLine("HA " + alignment); } } else { Debug.LogError("The 'HAlign' command requires an alignment parameter of L (left), R (right), or C (center)."); } } else if (command.IsEqual("S") || command.IsEqual("SPACE")) { // Space (pixels) if (commandList.Length > commandIndex + 1) { commandIndex++; int spaceSize; if (System.Int32.TryParse(commandList[commandIndex], out spaceSize)) { addCommandToLine("S " + commandList[commandIndex]); _nextSequence.Add(new AddSpace(spaceSize)); _lineLength += spaceSize; } else { Debug.LogError("The space size '" + commandList[commandIndex] + "' is not a valid integer"); } } else { Debug.LogError("The 'space' command requires a pixel count parameter."); } } else if (command.IsEqual("VA") || command.IsEqual("VALIGN")) { // Vertical alignment if (commandList.Length > commandIndex + 1) { commandIndex++; string alignment = commandList[commandIndex].ToUpper(); switch (alignment) { case "?": alignment = "?"; _nextSequence.alignBottom = false; break; case "B": case "BOTTOM": alignment = "B"; _nextSequence.alignBottom = true; break; default: alignment = ""; Debug.LogError("The 'VAlign' command requires an alignment parameter of ? (default) or B (bottom)."); break; } if (alignment.Length != 0) { addCommandToLine("VA " + alignment); } } else { Debug.LogError("The 'VAlign' command requires an alignment parameter of ? (default) or B (bottom)."); } } else { //Pass through any invalid commands or let words with brackets with out using double bracket //and decide what to do with it later invalidCommand = true; } } if (invalidCommand) { addCommandToLine(string.Format("{0}", text.Substring(currentLetterIndex + 1, endIndex - currentLetterIndex - 1))); //Debug.Log(string.Format("Invalid Command: {0}", commandList[commandIndex])); invalidCommand = false; } addSequenceToLine(); } else { // Add letter to the word word.Append(text[letterIndex]); } } addWordToLine(word.ToString()); addLineToLines(); }
protected override void EndProcessing() { if (GlobalVariables.AccountKeys == null || GlobalVariables.AccountKeys.Length == 0) { Host.UI.WriteErrorLine($"No accounts are loaded. Use '{CmdLetExtensions.GetCmdletName<NewAccountsCommand>()}' to generate accounts."); return; } string filePath; if (Path.IsPathRooted(FilePath)) { filePath = Path.GetFullPath(FilePath); } else { filePath = Path.GetFullPath(Path.Join(SessionState.Path.CurrentLocation.Path, FilePath)); } if (EncryptData && (Password == null || Password.Length == 0)) { Host.UI.WriteErrorLine($"No '{nameof(Password)}' parameter is provided. To write without encryption set the '{nameof(EncryptData)}' parameter to false"); return; } if ((Password != null && Password.Length > 0) && !EncryptData) { Host.UI.WriteErrorLine($"The '{nameof(EncryptData)}' parameter is set to false but the '{nameof(Password)}' parameter is provided. Pick one."); return; } var accounts = GlobalVariables.AccountKeys; var accountArrayHex = accounts .Select(a => new[] { a.Address.ToString(hexPrefix: true), HexUtil.GetHexFromBytes(a.Account.ToPrivateKeyArray(), hexPrefix: true) }) .ToArray(); JObject dataObj = new JObject(); if (EncryptData) { Password.MakeReadOnly(); var accountJson = JsonConvert.SerializeObject(accountArrayHex, Formatting.Indented); var encrypedAccountsString = AesUtil.EncryptString(accountJson, Marshal.PtrToStringAuto(Marshal.SecureStringToBSTR(Password))); Password.Dispose(); dataObj[LocalAccountsUtil.JSON_ENCRYPTED_ACCOUNTS_KEY] = encrypedAccountsString; } else { dataObj[LocalAccountsUtil.JSON_ACCOUNTS_KEY] = JArray.FromObject(accountArrayHex); } if (File.Exists(filePath)) { var choices = new Collection <ChoiceDescription>(new[] { new ChoiceDescription("&Cancel"), new ChoiceDescription("&Overwrite") }); var overwrite = Host.UI.PromptForChoice($"File already exists at {filePath}", "Continue and overwite existing file?", choices, 0); if (overwrite != 1) { Host.UI.WriteErrorLine("Accounts not saved to file."); return; } } var dataJson = dataObj.ToString(Formatting.Indented); File.WriteAllText(filePath, dataJson); if (EncryptData) { Host.UI.WriteLine($"Wrote {accounts.Length} encrypted accounts to: {filePath}"); } else { Host.UI.WriteLine($"Wrote {accounts.Length} unencrypted accounts to: {filePath}"); } }
protected override void EndProcessing() { string filePath; if (Path.IsPathRooted(FilePath)) { filePath = Path.GetFullPath(FilePath); } else { filePath = Path.GetFullPath(Path.Join(SessionState.Path.CurrentLocation.Path, FilePath)); } if (!File.Exists(filePath)) { Host.UI.WriteErrorLine($"File does not exist at: {filePath}"); return; } var fileContent = File.ReadAllText(filePath); var dataJson = JObject.Parse(fileContent); string[][] accountArrayHex; if (dataJson.TryGetValue(LocalAccountsUtil.JSON_ENCRYPTED_ACCOUNTS_KEY, out var token)) { if (Password.Length == 0) { Host.UI.WriteErrorLine($"No password parameter specified and accounts are encryped in file {FilePath}"); return; } else { Password.MakeReadOnly(); } var encrypedAccounts = token.Value <string>(); string decrypedContent; try { decrypedContent = AesUtil.DecryptString(encrypedAccounts, Marshal.PtrToStringAuto(Marshal.SecureStringToBSTR(Password))); Password.Dispose(); } catch (Exception ex) { Host.UI.WriteErrorLine(ex.ToString()); Host.UI.WriteErrorLine("Failed to decrypt account data. Incorrect password?"); return; } accountArrayHex = JsonConvert.DeserializeObject <string[][]>(decrypedContent); } else { if (Password != null && Password.Length > 0) { Host.UI.WriteErrorLine($"Password parameter specified but accounts are encryped in file {FilePath}"); return; } accountArrayHex = dataJson[LocalAccountsUtil.JSON_ACCOUNTS_KEY].ToObject <string[][]>(); } var accounts = accountArrayHex .Select(a => EthereumEcdsa.Create(HexUtil.HexToBytes(a[1]), EthereumEcdsaKeyType.Private)) .Select(a => (a.EcdsaKeyPairToAddress(), a)) .ToArray(); GlobalVariables.AccountKeys = accounts; Host.UI.WriteLine($"Loaded {accounts.Length} accounts from {filePath}"); }