public static string ToHumanKey(byte[] key) { if (key.Length == Address.PublicKeyLength) { return(new Address(key).Text); } if (key.Length > Address.PublicKeyLength) { var address = key.Take(Address.PublicKeyLength).ToArray(); var temp = key.Skip(Address.PublicKeyLength).ToArray(); var rest = DecodeKey(temp); if (rest != null) { return($"{ToHumanKey(address)}.{rest}"); } } { var rest = DecodeKey(key); if (rest != null) { return(rest); } } return("0x" + Base16.Encode(key)); }
internal static void Receive(TcpReceiveState e, PoolCommand cmd) { var msg = new NonceDataMsg(); int index = 0; msg.Deserialize(cmd.Payload, ref index); var miner = PoolCache.WorkingMiners.FirstOrDefault(m => m.ClientAddress == e.Address); if (miner == null) { RejectCommand.Send(e); return; } var data = POC.CalculateScoopData(miner.WalletAddress, msg.MaxNonce, miner.CheckScoopNumber); if (Base16.Encode(data) == Base16.Encode(msg.ScoopData)) { miner.IsConnected = true; miner.ConnectedTime = Time.EpochTime; miner.LatestHeartbeatTime = Time.EpochTime; LoginCommand.SendLoginResult(e, true); LogHelper.Info(miner.ClientAddress + " login success"); StartCommand.Send(e); } else { LoginCommand.SendLoginResult(e, false); RejectCommand.Send(e); LogHelper.Info(miner.ClientAddress + " login fail"); } }
/// <summary> /// To signed some type of data /// </summary> /// <param name="data">String with the data you want to sign</param> /// <param name="callback"></param> /// <param name="platform"></param> /// <param name="signature"></param> public void SignData(string data, Action <bool, string, string, string> callback = null, PlatformKind platform = PlatformKind.Phantasma, SignatureKind signature = SignatureKind.Ed25519) { if (!Enabled) { callback(true, "not logged in", "", ""); return; } if (data == null) { callback(true, "invalid data, sorry :(", "", ""); return; } if (data.Length >= 1024) { callback(true, "data too big, sorry :(", "", ""); return; } var dataConverted = Base16.Encode(Encoding.UTF8.GetBytes(data)); SendLinkRequest($"signData/{dataConverted}/{signature}/{platform}", (result) => { var success = result.GetBool("success"); if (success) { var random = result.GetString("random"); var signedData = result.GetString("signature"); callback?.Invoke(false, signedData, random, dataConverted); } else { var msg = result.GetString("message"); callback?.Invoke(true, "transaction rejected: " + msg, "", ""); } }); }
public IRpcMethodResult GenerateNewBlock(string minerName, string address = null, int format = 0) { try { var block = new BlockComponent().CreateNewBlock(minerName, address); if (block != null) { if (format == 0) { var bytes = block.Serialize(); var result = Base16.Encode(bytes); return(Ok(result)); } else { return(Ok(block)); } } else { return(Ok()); } } catch (CommonException ce) { return(Error(ce.ErrorCode, ce.Message, ce)); } catch (Exception ex) { return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex)); } }
public string AsString() { switch (this.Type) { case VMType.String: return((string)Data); case VMType.Number: return(((BigInteger)Data).ToString()); case VMType.Bytes: return(Base16.Encode((byte[])Data)); case VMType.Enum: return(((uint)Data).ToString()); case VMType.Object: return("Interop:" + Data.GetType().Name); case VMType.Bool: return(((bool)Data) ? "true" : "false"); case VMType.Timestamp: var date = (DateTime)(Timestamp)Data; return(date.ToString(TimeFormat)); default: throw new Exception("Invalid cast"); } }
public IRpcMethodResult GetBlock(string blockHash, int format = 0) { try { var blockComponent = new BlockComponent(); var block = blockComponent.GetBlockMsgByHash(blockHash); if (block != null) { if (format == 0) { var bytes = block.Serialize(); var result = Base16.Encode(bytes); return(Ok(result)); } else { return(Ok(block)); } } else { return(Ok()); } } catch (CommonException ce) { return(Error(ce.ErrorCode, ce.Message, ce)); } catch (Exception ex) { return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex)); } }
public void CustomCtor() { var encoder = new Base16(new Base16Alphabet("abcdefghijklmnop")); var result = encoder.Encode(new byte[] { 0, 1, 16, 128, 255 }); Assert.AreEqual("aaabbaiapp", result); }
public static bool VerifyLockScriptByUnlockScript(string transactionHash, int outputIndex, string lockScript, string unlockScript) { var data = new List <byte>(); data.AddRange(Base16.Decode(transactionHash)); var indexBytes = BitConverter.GetBytes(outputIndex); if (BitConverter.IsLittleEndian) { Array.Reverse(indexBytes); } data.AddRange(indexBytes); var parameters = unlockScript.Split("[ALL] "); var dsa = ECDsa.ImportPublicKey(Base16.Decode(parameters[1])); var signatureResult = dsa.VerifyData(data.ToArray(), Base16.Decode(parameters[0])); if (signatureResult) { var publicKeyHash = GetPublicKeyHashFromLockScript(lockScript); return(Base16.Encode(HashHelper.Hash160(Base16.Decode(parameters[1]))) == publicKeyHash); } else { return(false); } }
public static string BuildUnlockScript(string transactionHash, int outputIndex, byte[] privateKey, byte[] publicKey) { var data = new List <byte>(); data.AddRange(Base16.Decode(transactionHash)); var indexBytes = BitConverter.GetBytes(outputIndex); if (BitConverter.IsLittleEndian) { Array.Reverse(indexBytes); } data.AddRange(indexBytes); using (var dsa = ECDsa.ImportPrivateKey(privateKey)) { if (Base16.Encode(dsa.PublicKey) != Base16.Encode(publicKey)) { throw new CommonException(ErrorCode.Engine.Transaction.Verify.PRIVATE_KEY_IS_ERROR); } var signature = dsa.SingnData(data.ToArray()); return(string.Format( UNLOCK_SCRIPT_TEMPLATE, Base16.Encode(signature), Base16.Encode(dsa.PublicKey) )); } }
public Account ImportObservedAccount(string publicKeyText) { var dac = new AccountDac(); var publicKey = Base16.Decode(publicKeyText); var id = AccountIdHelper.CreateAccountAddress(publicKey); Account account = dac.SelectById(id); if (account == null) { account = new Account(); account.Id = AccountIdHelper.CreateAccountAddress(publicKey); account.PrivateKey = null; account.PublicKey = Base16.Encode(publicKey); account.Balance = 0; account.IsDefault = false; account.WatchedOnly = true; dac.Insert(account); UtxoSet.Instance.AddAccountId(account.Id); } return(account); }
public void Encode_Range() { Action TestCase(int testNumber, byte[] bytes, int offset, int length, bool toUpper, string expected, Type expectedExceptionType = null) => () => { new TestCaseRunner($"No.{testNumber}") .Run(() => Base16.Encode(bytes, offset, length, toUpper)) .Verify(expected, expectedExceptionType); }; var rndBytes = Rand.Bytes(); new[] { TestCase(0, null, 0, 0, false, null, typeof(ArgumentNullException)), TestCase(1, Bytes(), 0, 0, false, ""), TestCase(2, Bytes(0x0f), 0, 1, false, "0f"), TestCase(3, Bytes(0x0f, 0xf0), 0, 2, false, "0ff0"), TestCase(4, Bytes(0x0f, 0xf0), 0, 2, true, "0FF0"), TestCase(10, Bytes(0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef), 0, 8, false, "0123456789abcdef"), TestCase(11, Bytes(0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef), 0, 8, true, "0123456789ABCDEF"), TestCase(20, Bytes(0x0f, 0xf0), -1, 0, true, null, typeof(ArgumentOutOfRangeException)), TestCase(21, Bytes(0x0f, 0xf0), 0, -1, true, null, typeof(ArgumentOutOfRangeException)), TestCase(22, Bytes(0x0f, 0xf0), 2, 0, true, ""), TestCase(23, Bytes(0x0f, 0xf0), 1, 1, true, "F0"), TestCase(24, Bytes(0x0f, 0xf0), 1, 2, true, null, typeof(ArgumentOutOfRangeException)), TestCase(50, rndBytes, 0, rndBytes.Length, false, BitConverter.ToString(rndBytes).Replace("-", "").ToLowerInvariant()), TestCase(51, rndBytes, 0, rndBytes.Length, true, BitConverter.ToString(rndBytes).Replace("-", "").ToUpperInvariant()), }.Run(); }
private string GetHash() { var bytes = new List <byte>(); var indexBytes = BitConverter.GetBytes(Index); var amountBytes = BitConverter.GetBytes(Amount); var sizeBytes = BitConverter.GetBytes(Size); var scriptBytes = Encoding.UTF8.GetBytes(LockScript); if (BitConverter.IsLittleEndian) { Array.Reverse(indexBytes); Array.Reverse(amountBytes); Array.Reverse(sizeBytes); } bytes.AddRange(indexBytes); bytes.AddRange(amountBytes); bytes.AddRange(sizeBytes); bytes.AddRange(scriptBytes); return(Base16.Encode( HashHelper.Hash( bytes.ToArray() ))); }
public Account ImportAccount(string privateKeyText) { var dac = AccountDac.Default; byte[] privateKey = Base16.Decode(privateKeyText); byte[] publicKey; using (var dsa = ECDsa.ImportPrivateKey(privateKey)) { publicKey = dsa.PublicKey; } var id = AccountIdHelper.CreateAccountAddress(publicKey); Account account = dac.SelectById(id); if (account == null) { account = new Account(); account.Id = AccountIdHelper.CreateAccountAddress(publicKey); account.PrivateKey = Base16.Encode(privateKey); account.PublicKey = Base16.Encode(publicKey); account.Balance = 0; account.IsDefault = false; account.WatchedOnly = false; AccountDac.Default.Insert(account); } return(account); }
public TransactionMsg() { this.Version = Int32.Parse(Resource.MsgVersion); this.Inputs = new List <InputMsg>(); this.Outputs = new List <OutputMsg>(); this.Hash = Base16.Encode(HashHelper.EmptyHash()); }
public override void Deserialize(byte[] bytes, ref int index) { var txHashBytes = new byte[32]; var outputIndexBytes = new byte[4]; var sizeBytes = new byte[4]; Array.Copy(bytes, index, txHashBytes, 0, txHashBytes.Length); index += txHashBytes.Length; this.OutputTransactionHash = Base16.Encode(txHashBytes); Array.Copy(bytes, index, outputIndexBytes, 0, outputIndexBytes.Length); index += outputIndexBytes.Length; Array.Copy(bytes, index, sizeBytes, 0, sizeBytes.Length); index += sizeBytes.Length; if (BitConverter.IsLittleEndian) { Array.Reverse(outputIndexBytes); Array.Reverse(sizeBytes); } this.OutputIndex = BitConverter.ToInt32(outputIndexBytes, 0); this.Size = BitConverter.ToInt32(sizeBytes, 0); var scriptBytes = new byte[Size]; Array.Copy(bytes, index, scriptBytes, 0, this.Size); this.UnlockScript = Encoding.UTF8.GetString(scriptBytes); index += Size; }
public string GetMiningWorkResult(BlockMsg block) { var listBytes = new List <Byte>(); listBytes.AddRange(Base16.Decode(block.Header.PayloadHash)); listBytes.AddRange(BitConverter.GetBytes(block.Header.Height)); var genHash = Sha3Helper.Hash(listBytes.ToArray()); //POC.CalculateScoopData(block.Header., block.Header.Nonce); var blockData = new List <byte>(); foreach (var tx in block.Transactions) { blockData.AddRange(tx.Serialize()); } var nonceBytes = BitConverter.GetBytes(block.Header.Nonce); if (BitConverter.IsLittleEndian) { Array.Reverse(nonceBytes); } blockData.AddRange(nonceBytes); var result = Base16.Encode( HashHelper.Hash( blockData.ToArray() )); return(result); }
private static Hash SendTransfer(JSONRPC_Client rpc, Logger logger, string nexusName, string host, PhantasmaKeys from, Address to, BigInteger amount) { Throw.IfNull(rpc, nameof(rpc)); Throw.IfNull(logger, nameof(logger)); var script = ScriptUtils.BeginScript().AllowGas(from.Address, Address.Null, 1, 9999).TransferTokens("SOUL", from.Address, to, amount).SpendGas(from.Address).EndScript(); var tx = new Transaction(nexusName, "main", script, Timestamp.Now + TimeSpan.FromMinutes(30)); tx.Sign(from); var bytes = tx.ToByteArray(true); //log.Debug("RAW: " + Base16.Encode(bytes)); var response = rpc.SendRequest(logger, host, "sendRawTransaction", Base16.Encode(bytes)); if (response == null) { logger.Error($"Error sending {amount} {DomainSettings.FuelTokenSymbol} from {from.Address} to {to}..."); return(Hash.Null); } if (response.HasNode("error")) { var error = response.GetString("error"); logger.Error("Error: " + error); return(Hash.Null); } var hash = response.Value; return(Hash.Parse(hash)); }
public string GetHash() { var bytes = new List <byte>(); var previousBlockHashBytes = new byte[32]; var bitsBytes = new byte[8]; var nonceBytes = new byte[8]; var timestampBytes = new byte[8]; previousBlockHashBytes = Base16.Decode(PreviousBlockHash); bitsBytes = BitConverter.GetBytes(Bits); nonceBytes = BitConverter.GetBytes(Nonce); timestampBytes = BitConverter.GetBytes(Timestamp); if (BitConverter.IsLittleEndian) { Array.Reverse(bitsBytes); Array.Reverse(nonceBytes); Array.Reverse(timestampBytes); } bytes.AddRange(previousBlockHashBytes); bytes.AddRange(bitsBytes); bytes.AddRange(nonceBytes); bytes.AddRange(timestampBytes); return(Base16.Encode( HashHelper.Hash( bytes.ToArray() ))); }
public static string CalculateHash(string value) { var input = Encoding.UTF8.GetBytes(value); var output = CalculateHash(input); return(Base16.Encode(output)); }
public static BigInteger ConvertByesToBigInteger(byte[] bytes) { if (bytes.Length > 0) { var text = Base16.Encode(bytes); if (text.Length % 2 != 0) { text = "0" + text; } var firstByte = Convert.ToByte(text.Substring(0, 2), 16); if (firstByte > 0x7f) { text = "00" + text; } var value = BigInteger.Parse(text, NumberStyles.AllowHexSpecifier); return(value); } else { return(BigInteger.Zero); } }
public void Encode_Stream(Base16 encoder, byte[] input, string expectedOutput) { using var inputStream = new MemoryStream(input); using var writer = new StringWriter(); encoder.Encode(inputStream, writer); Assert.AreEqual(expectedOutput, writer.ToString()); }
/// <summary> /// Process received data. Corresponding async results are searched and marked as done. /// </summary> /// <param name="receivedDataBuffer">Received data buffer</param> /// <param name="receivedByteCount">Number of bytes received</param> public void ProcessReceivedData(byte[] receivedDataBuffer, int receivedByteCount) { Logger.Debug("{0} bytes received.", receivedByteCount); int oldLength = _receivedBytes.Length; Array.Resize(ref _receivedBytes, _receivedBytes.Length + receivedByteCount); Array.Copy(receivedDataBuffer, 0, _receivedBytes, oldLength, receivedByteCount); while (_receivedBytes.Length >= 4) { ushort firstTlvLength = Util.GetTlvLength(_receivedBytes); if (firstTlvLength > _receivedBytes.Length) { break; } byte[] data = new byte[firstTlvLength]; Array.Copy(_receivedBytes, 0, data, 0, firstTlvLength); if (!ProcessPdu(data)) { Logger.Warn("Could not get payload from response PDU: " + Base16.Encode(data)); } // remove already handled data byte[] newResultData = new byte[_receivedBytes.Length - firstTlvLength]; Array.Copy(_receivedBytes, firstTlvLength, newResultData, 0, newResultData.Length); _receivedBytes = newResultData; } }
private static Register ConvertFieldToContract(CodeGenerator output, Scope scope, Expression expression) { var literal = expression as LiteralExpression; if (literal == null) { throw new CompilerException("nft argument is not a literal value"); } var module = scope.Module.FindModule(literal.value); var abi = module.abi; if (module.Kind == ModuleKind.NFT) { var nftStandard = NFTUtils.GetNFTStandard(); if (!abi.Implements(nftStandard)) { throw new CompilerException($"nft {literal.value} not does implement NFT standard"); } } var reg = Compiler.Instance.AllocRegister(output, expression); var abiBytes = module.abi.ToByteArray(); output.AppendLine(expression, $"LOAD {reg} 0x{Base16.Encode(abiBytes)} // abi"); output.AppendLine(expression, $"PUSH {reg}"); output.AppendLine(expression, $"LOAD {reg} 0x{Base16.Encode(module.script)} // script"); // output.AppendLine(expression, $"PUSH {reg}"); return(reg); }
public void ECDsaSecP256k1() { var address = "0x66571c32d77c4852be4c282eb952ba94efbeac20"; var key = "6f6784731c4e526c97fa6a97b6f22e96f307588c5868bc2c545248bc31207eb1"; Assert.IsTrue(key.Length == 64); var curve = ECCurve.Secp256k1; var privateKey = key.HexToByteArray(); var pKey = ECCurve.Secp256k1.G * privateKey; var publicKey = pKey.EncodePoint(true).ToArray(); var uncompressedPublicKey = pKey.EncodePoint(false).Skip(1).ToArray(); var kak = new Phantasma.Ethereum.Util.Sha3Keccack().CalculateHash(uncompressedPublicKey); var Address = "0x" + Base16.Encode(kak.Skip(12).ToArray()).ToLower(); Console.WriteLine("Address: " + Address); Console.WriteLine("address: " + address); Assert.IsTrue(Address == address); var msgBytes = Encoding.ASCII.GetBytes("Phantasma"); var signature = CryptoExtensions.SignECDsa(msgBytes, privateKey, publicKey, ECDsaCurve.Secp256k1); Assert.IsNotNull(signature); var signatureUncompressed = CryptoExtensions.SignECDsa(msgBytes, privateKey, uncompressedPublicKey, ECDsaCurve.Secp256k1); Assert.IsNotNull(signatureUncompressed); Assert.IsTrue(CryptoExtensions.VerifySignatureECDsa(msgBytes, signature, publicKey, ECDsaCurve.Secp256k1)); Assert.IsTrue(CryptoExtensions.VerifySignatureECDsa(msgBytes, signature, uncompressedPublicKey, ECDsaCurve.Secp256k1)); }
public Account GenerateNewAccount(bool isAddtoCache = true) { var dac = AccountDac.Default; byte[] privateKey; byte[] publicKey; using (var dsa = ECDsa.GenerateNewKeyPair()) { privateKey = dsa.PrivateKey; publicKey = dsa.PublicKey; } var id = AccountIdHelper.CreateAccountAddress(publicKey); if (dac.IsExisted(id)) { throw new Exception("Account id is existed"); } Account account = new Account(); account.Id = id; account.PrivateKey = Base16.Encode(privateKey); account.PublicKey = Base16.Encode(publicKey); account.Balance = 0; account.IsDefault = false; account.WatchedOnly = false; AccountDac.Default.Insert(account); return(account); }
public override string ToString() { switch (this.Type) { case VMType.None: return("Null"); case VMType.Struct: return("[Struct]"); case VMType.Bytes: return($"[Bytes] => {Base16.Encode(((byte[])Data))}"); case VMType.Number: return($"[Number] => {((BigInteger)Data)}"); case VMType.Timestamp: return($"[Time] => {((DateTime)((Timestamp)Data)).ToString(TimeFormat)}"); case VMType.String: return($"[String] => {((string)Data)}"); case VMType.Bool: return($"[Bool] => {((bool)Data)}"); case VMType.Enum: return($"[Enum] => {((uint)Data)}"); case VMType.Object: return($"[Object] => {(Data == null? "null" : Data.GetType().Name)}"); default: return("Unknown"); } }
public void TestDecodeBytes() { var bytes = Rfc1751.Decode("TROD MUTE TAIL WARM CHAR KONG HAAG CITY BORE O TEAL AWL", out var parityError); Assert.Equal("EFF81F9BFBC65350920CDD7416DE8009", Base16.Encode(bytes.Span)); Assert.False(parityError); }
public IRpcMethodResult SignMessage(string address, string message) { try { var account = new AccountComponent().GetAccountById(address); if (account == null || string.IsNullOrWhiteSpace(account.PrivateKey)) { throw new CommonException(ErrorCode.Service.Account.ACCOUNT_NOT_FOUND); } ECDsa dsa = ECDsa.ImportPrivateKey(Base16.Decode(DecryptPrivateKey(account.PrivateKey))); var signResult = Base16.Encode(dsa.SingnData(Encoding.UTF8.GetBytes(message))); var result = new { signature = signResult, publicKey = account.PublicKey }; 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 override void Deserialize(byte[] bytes, ref int index) { var namelengthBytes = new byte[4]; Array.Copy(bytes, index, namelengthBytes, 0, namelengthBytes.Length); if (BitConverter.IsLittleEndian) { Array.Reverse(namelengthBytes); } nameLength = BitConverter.ToInt32(namelengthBytes, 0); index += 4; var nameBytes = new byte[nameLength]; Array.Copy(bytes, index, nameBytes, 0, nameBytes.Length); Name = Encoding.UTF8.GetString(nameBytes); index += nameBytes.Length; var publicKeyLengthBytes = new byte[4]; Array.Copy(bytes, index, publicKeyLengthBytes, 0, publicKeyLengthBytes.Length); if (BitConverter.IsLittleEndian) { Array.Reverse(publicKeyLengthBytes); } publicKeyLength = BitConverter.ToInt32(publicKeyLengthBytes, 0); index += 4; var publicKeyBytes = new byte[publicKeyLength]; Array.Copy(bytes, index, publicKeyBytes, 0, publicKeyBytes.Length); PublicKey = Base16.Encode(publicKeyBytes); index += publicKeyBytes.Length; var signatureLengthBytes = new byte[4]; Array.Copy(bytes, index, signatureLengthBytes, 0, signatureLengthBytes.Length); if (BitConverter.IsLittleEndian) { Array.Reverse(signatureLengthBytes); } var signatureLength = BitConverter.ToInt32(signatureLengthBytes, 0); index += 4; var signatureBytes = new byte[signatureLength]; Array.Copy(bytes, index, signatureBytes, 0, signatureBytes.Length); index += signatureBytes.Length; Signature = Base16.Encode(signatureBytes); }
public static void Encode(string input, string expected) { var bytes = Encoding.UTF8.GetBytes(input); var base16 = new char[Base16.GetEncodedLength(bytes.Length)]; Base16.Encode(bytes, base16); Assert.Equal(expected, new string(base16)); }