/// <summary> /// Decode a bytejail ID into a byte array. /// </summary> /// <param name="encodedPublicKey">The bytejail ID.</param> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="CorruptIdentityException"></exception> /// <returns>A 32 byte array.</returns> public static byte[] DecodeBytejailPublicKey(string encodedPublicKey) { if (encodedPublicKey == null) { throw new ArgumentNullException("encodedPublicKey", "encodedPublicKey cannot be null"); } try { var raw = Base58CheckEncoding.DecodePlain(encodedPublicKey); var version = ArrayHelper.SubArray(raw, 0, 1); if (!version.SequenceEqual(new[] { BytejailVersionPrefix })) { throw new FormatException("invalid version"); } var publicKey = ArrayHelper.SubArray(raw, 1, 32); var checksum = CalculateBytejailChecksum(new[] { BytejailVersionPrefix }, publicKey); var givenChecksum = ArrayHelper.SubArray(raw, 33); if (!checksum.SequenceEqual(givenChecksum)) { throw new CorruptIdentityException("the given identity seems to be an invalid bytejail ID"); } return(publicKey); } catch (FormatException) { throw new CorruptIdentityException("the given identity seems to be an invalid bytejail ID"); } }
public void DecodeInvalidChar() { Assert.Throws <FormatException>(() => { Base58CheckEncoding.DecodePlain("ab0"); }); }
public static IPrivateKey FromWif(string wif) { var fullBuffer = Base58CheckEncoding.DecodePlain(wif); Assert.Equal(0x80, fullBuffer.First(), string.Format("Expected version {0}, instead got {1}", 0x80, fullBuffer.First())); var buffer = fullBuffer.Slice(0, fullBuffer.Length - 4); var checksum = fullBuffer.Slice(fullBuffer.Length - 4); fullBuffer.Clear(); var firstChecksum = SHA256.Create().HashAndDispose(buffer); var secondChecksum = SHA256.Create().HashAndDispose(firstChecksum); firstChecksum.Clear(); var newChecksum = secondChecksum.Slice(0, 4); secondChecksum.Clear(); if (!checksum.DeepEqual(newChecksum)) { throw new InvalidOperationException("Checksum did not match"); } checksum.Clear(); newChecksum.Clear(); var key = buffer.Slice(1, 32); buffer.Clear(); var result = FromBuffer(key); key.Clear(); return(result); }
public async Task TestReplaceKeysStartWorksForEmptyJson() { var result = await Signus.ReplaceKeysStartAsync(wallet, _did, "{}"); Assert.IsNotNull(result); Assert.AreEqual(32, Base58CheckEncoding.DecodePlain(result).Length); }
public ActionResult UnsafeTransaction(TransactionCreateModel model) { if (model.Priv == null) { return(Json(_api.Api.SendTransaction(new CreateTransactionModel(model)))); } else { byte[] Private; try { Private = Base58CheckEncoding.DecodePlain(model.Priv); } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.Forbidden; return(Json(ex.Message, JsonRequestBehavior.AllowGet)); } try { return(Json(_api.Api.SendTransaction(new CreateTransactionModel(model), Private))); } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.Forbidden; return(Json(ex.Message, JsonRequestBehavior.AllowGet)); } } }
public static IPublicKey FromPublicKeyString(string publicKey, string addressPrefix = null) { try { if (addressPrefix.IsNull()) { addressPrefix = ChainConfig.AddressPrefix; } var prefix = publicKey.Substring(0, addressPrefix.Length); Assert.Equal( addressPrefix, prefix, string.Format("Expecting key to begin with {0}, instead got {1}", addressPrefix, prefix) ); publicKey = publicKey.Substring(addressPrefix.Length); var key = Base58CheckEncoding.DecodePlain(publicKey); var checksum = key.Slice(key.Length - 4); var buffer = key.Slice(0, key.Length - 4); key.Clear(); var hash = RIPEMD160.Create().HashAndDispose(buffer); var newChecksum = hash.Slice(0, 4); hash.Clear(); if (!checksum.DeepEqual(newChecksum)) { throw new InvalidOperationException("Checksum did not match"); } var result = FromBuffer(buffer); buffer.Clear(); return(result); } catch { return(null); } }
/// <summary> /// Try to recognize the identity format. /// </summary> /// <param name="encodedPublicKey">A base58 encoded public identity.</param> /// <param name="validate">If true, the key will also be validated.</param> /// <exception cref="ArgumentNullException"></exception> /// <returns>The KeyType.</returns> public static KeyType TryRecognizeIdentityFormat(string encodedPublicKey, bool validate = true) { var type = KeyType.Unknown; if (encodedPublicKey == null) { throw new ArgumentNullException("encodedPublicKey", "encodedPublicKey cannot be null"); } try { var raw = Base58CheckEncoding.DecodePlain(encodedPublicKey); switch (raw.Length) { case 33: // miniLock type = validate ? (DecodeMiniLockPublicKey(encodedPublicKey).Length == PublicKeyBytes ? KeyType.MiniLock : KeyType.Invalid) : KeyType.MiniLock; break; case 37: // curvelock or bytejail if (ArrayHelper.SubArray(raw, 0, 1).SequenceEqual(new[] { CurveLockVersionPrefix })) { // CurveLock type = validate ? (DecodeCurveLockPublicKey(encodedPublicKey).Length == PublicKeyBytes ? KeyType.CurveLock : KeyType.Invalid) : KeyType.CurveLock; } else { if (ArrayHelper.SubArray(raw, 0, 1).SequenceEqual(new[] { BytejailVersionPrefix })) { // bytejail type = validate ? (DecodeBytejailPublicKey(encodedPublicKey).Length == PublicKeyBytes ? KeyType.Bytejail : KeyType.Invalid) : KeyType.Bytejail; } } break; default: type = KeyType.Unknown; break; } } catch (Exception) { type = KeyType.Invalid; } return(type); }
public async Task TestCreateKeyWorksForSeed() { var paramJson = string.Format("{{\"seed\":\"{0}\"}}", MY1_SEED); var senderVk = await Crypto.CreateKeyAsync(wallet, paramJson); Assert.AreEqual(32, Base58CheckEncoding.DecodePlain(senderVk).Length); }
public async Task TestCreateMyDidWorksForEmptyJson() { var result = await Signus.CreateAndStoreMyDidAsync(wallet, "{}"); Assert.IsNotNull(result); Assert.AreEqual(16, Base58CheckEncoding.DecodePlain(result.Did).Length); Assert.AreEqual(32, Base58CheckEncoding.DecodePlain(result.VerKey).Length); }
public void EncodePlan_And_DecodePlain_ByteString() { var bs = ByteString.CopyFromUtf8("test byte string"); var encodeMessage = Base58CheckEncoding.EncodePlain(bs); var decodeMessage = Base58CheckEncoding.DecodePlain(encodeMessage); var bs1 = ByteString.CopyFrom(decodeMessage); bs.ShouldBe(bs1); }
public void Decode() { foreach (var tuple in _testCases) { var text = tuple.Item1; var expectedBytes = tuple.Item2; var actualBytes = Base58CheckEncoding.DecodePlain(text); Assert.AreEqual(BitConverter.ToString(expectedBytes), BitConverter.ToString(actualBytes)); } }
public void EncodePlain_And_DecodePlain_Address() { var address = Address.Generate(); var data = address.DumpByteArray(); var enCode = Base58CheckEncoding.EncodePlain(data); enCode.ShouldNotBe(string.Empty); var deCode = Base58CheckEncoding.DecodePlain(enCode); deCode.ShouldBe(data); }
public void EncodePlain_And_DecodePlain_Address() { var address = Address.FromBase58("2DZER7qHVwv3PUMFsHuQaQbE4wDFsCRzJsxLwYEk8rgM3HVn1S"); var data = address.ToByteArray(); var enCode = Base58CheckEncoding.EncodePlain(data); enCode.ShouldNotBe(string.Empty); var deCode = Base58CheckEncoding.DecodePlain(enCode); deCode.ShouldBe(data); }
//public ApiResult<object> UnsafeTransaction(TransactionCreateModel<string> model) //{ // ApiResult<object> Res = new ApiResult<object>() { Result = null}; // byte[] Private; // try // { // Private = Base58CheckEncoding.DecodePlain(model.Priv); // } // catch (Exception) // { // Private = new byte[64]; // } // byte[] Source; // if (model.Source != null) // { // try // { // Source = Base58CheckEncoding.DecodePlain(model.Source); // } // catch (Exception) // { // Res.Message = "Source is incorrect"; // return Res; // } // } // else // { // Source = new byte[32]; // } // if (model.Amount == null) // { // model.Amount = "0,0"; // } // else // { // model.Amount = model.Amount.Replace(".", ",").Replace(" ", ""); // } // if (model.Fee == null) // { // model.Fee = "0,9"; // } // else // { // model.Fee = model.Fee.Replace(".", ",").Replace(" ", ""); // } // Transaction Trans = new Transaction // { // Source = Source // }; // WalletTransactionsCountGetResult TransactionId = _connect.WalletTransactionsCountGet(Trans.Source); // if (TransactionId.Status.Code == 0) // { // Trans.Id = TransactionId.LastTransactionInnerId + 1; // } // byte[] PervStr = NumbToByte(Trans.Id, 6); // if (model.Smart != null && model.Smart.Code != null) // { // byte[] ByteC = Source; // ConcatByteAr(ref ByteC, PervStr); // SmartContractCompileResult ByteCodes = _connect.SmartContractCompile(model.Smart.Code); // if (ByteCodes.Status.Code == 0) // { // foreach (ByteCodeObject item in ByteCodes.ByteCodeObjects) // { // ConcatByteAr(ref ByteC, item.ByteCode); // } // } // Trans.Target = Blake2s.Blake2S.ComputeHash(ByteC); // } // else // { // try // { // Trans.Target = Base58CheckEncoding.DecodePlain(model.Target); // } // catch (Exception) // { // Res.Message = "Target is incorrect"; // return Res; // } // } // string[] ArStrAmmount = model.Amount.Split(','); // Trans.Amount = new Amount // { // Integral = Convert.ToInt32(ArStrAmmount[0]) // }; // if (ArStrAmmount.Length > 1) // Trans.Amount.Fraction = (long)(ValidDouble("0." + ArStrAmmount[1]) * Math.Pow(10, 18)); // Trans.Balance = new Amount { Fraction = 0, Integral = 0 }; // Trans.Currency = 1; // Trans.TimeCreation = DateTime.Now.Ticks; // FeeRes F = Fee(ValidDouble(model.Fee)); // string FeeIntegral = Convert.ToString(F.Exp, 2); // while (FeeIntegral.Length < 5) // { // FeeIntegral = "0" + FeeIntegral; // } // string FeeFraction = Convert.ToString(F.Mantic, 2); // while (FeeFraction.Length < 10) // { // FeeFraction = "0" + FeeFraction; // } // string FeeBits = "0" + FeeIntegral + FeeFraction; // Trans.Fee = new AmountCommission { Commission = Convert.ToInt16(BitsToNumb(FeeBits)) }; // ConcatByteAr(ref PervStr, Trans.Source); // ConcatByteAr(ref PervStr, Trans.Target); // ConcatByteAr(ref PervStr, NumbToByte(Convert.ToInt32(ArStrAmmount[0]), 4)); // if (ArStrAmmount.Length > 1) // ConcatByteAr(ref PervStr, BitConverter.GetBytes(Trans.Amount.Fraction)); // else // ConcatByteAr(ref PervStr, new byte[8]); // ConcatByteAr(ref PervStr, ReverceByteAr(BitsToBytes(FeeBits))); // ConcatByteAr(ref PervStr, new byte[1] { Convert.ToByte(Trans.Currency) }); // if (model.Smart == null && model.UserData == null) // { // ConcatByteAr(ref PervStr, new byte[1]); // } // else if(model.Smart != null) // { // ConcatByteAr(ref PervStr, new byte[1] { 1 }); // byte[] UserFilds = new byte[0]; // Trans.SmartContract = new SmartContractInvocation(); // ConcatByteAr(ref UserFilds, new byte[3] { 11, 0, 1 }); // if (model.Smart.Method == null) // { // ConcatByteAr(ref UserFilds, new byte[4]); // } // else // { // Trans.SmartContract.Method = model.Smart.Method; // byte[] Method = new byte[model.Smart.Method.Length]; // for (int i = 0; i < model.Smart.Method.Length; i++) // { // Method[i] = Convert.ToByte(model.Smart.Method[i]); // } // ConcatByteAr(ref UserFilds, ReverceByteAr(NumbToByte(model.Smart.Method.Length, 4))); // ConcatByteAr(ref UserFilds, Method); // } // ConcatByteAr(ref UserFilds, new byte[4] { 15, 0, 2, 12 }); // if (model.Smart.Params == null) // { // ConcatByteAr(ref UserFilds, new byte[4]); // } // else // { // ConcatByteAr(ref UserFilds, ReverceByteAr(NumbToByte(model.Smart.Params.Count, 4))); // Trans.SmartContract.Params = new List<Variant>(); // foreach (ParamsCreateModel item in model.Smart.Params) // { // switch (item.Key) // { // case "STRING": // ConcatByteAr(ref UserFilds, new byte[3] { 11, 0, 17 }); // ConcatByteAr(ref UserFilds, ReverceByteAr(NumbToByte(item.Value.Length, 4))); // byte[] Params = new byte[item.Value.Length + 1]; // for (int i = 0; i < item.Value.Length; i++) // { // Params[i] = Convert.ToByte(item.Value[i]); // } // ConcatByteAr(ref UserFilds, Params); // Trans.SmartContract.Params.Add(new Variant { V_string = item.Value }); // break; // case "DOUBLE": // ConcatByteAr(ref UserFilds, new byte[3] { 4, 0, 15 }); // ConcatByteAr(ref UserFilds, ReverceByteAr(BitConverter.GetBytes(Double.Parse(item.Value)))); // ConcatByteAr(ref UserFilds, new byte[1]); // Trans.SmartContract.Params.Add(new Variant { V_double = Double.Parse(item.Value) }); // break; // case "INT": // ConcatByteAr(ref UserFilds, new byte[3] { 8, 0, 9 }); // ConcatByteAr(ref UserFilds, ReverceByteAr(NumbToByte(int.Parse(item.Value), 4))); // ConcatByteAr(ref UserFilds, new byte[1]); // Trans.SmartContract.Params.Add(new Variant { V_int = int.Parse(item.Value) }); // break; // case "BOOL": // ConcatByteAr(ref UserFilds, new byte[3] { 2, 0, 3 }); // ConcatByteAr(ref UserFilds, new byte[1]); // if (bool.Parse(item.Value)) // { // UserFilds[UserFilds.Length - 1] = 1; // } // ConcatByteAr(ref UserFilds, new byte[1]); // Trans.SmartContract.Params.Add(new Variant { V_boolean = bool.Parse(item.Value) }); // break; // } // } // } // ConcatByteAr(ref UserFilds, new byte[8] { 15, 0, 3, 11, 0, 0, 0, 0 }); // ConcatByteAr(ref UserFilds, new byte[4] { 2, 0, 4, 0 }); // if (model.Smart.ForgetNewState) // { // UserFilds[UserFilds.Length - 1] = 1; // Trans.SmartContract.ForgetNewState = true; // } // if (model.Smart.Code != null) // { // ConcatByteAr(ref UserFilds, new byte[3] { 12, 0, 5 }); // ConcatByteAr(ref UserFilds, new byte[3] { 11, 0, 1 }); // Trans.SmartContract.SmartContractDeploy = new SmartContractDeploy // { // SourceCode = model.Smart.Code, // ByteCodeObjects = new List<ByteCodeObject>() // }; // ConcatByteAr(ref UserFilds, ReverceByteAr(NumbToByte(model.Smart.Code.Length, 4))); // byte[] Code = new byte[model.Smart.Code.Length]; // for (int i = 0; i < model.Smart.Code.Length; i++) // { // Code[i] = Convert.ToByte(model.Smart.Code[i]); // } // ConcatByteAr(ref UserFilds, Code); // ConcatByteAr(ref UserFilds, new byte[4] { 15, 0, 2, 12 }); // SmartContractCompileResult CompiledByteCode = _connect.SmartContractCompile(model.Smart.Code); // if (CompiledByteCode.Status.Code > 0) // { // return null; // } // else // { // ConcatByteAr(ref UserFilds, ReverceByteAr(NumbToByte(CompiledByteCode.ByteCodeObjects.Count, 4))); // foreach (ByteCodeObject item in CompiledByteCode.ByteCodeObjects) // { // ConcatByteAr(ref UserFilds, new byte[3] { 11, 0, 1 }); // ConcatByteAr(ref UserFilds, ReverceByteAr(NumbToByte(item.Name.Length, 4))); // byte[] Bytes = new byte[item.Name.Length]; // for (int i = 0; i < item.Name.Length; i++) // { // Bytes[i] = Convert.ToByte(item.Name[i]); // } // ConcatByteAr(ref UserFilds, Bytes); // ConcatByteAr(ref UserFilds, new byte[3] { 11, 0, 2 }); // ConcatByteAr(ref UserFilds, ReverceByteAr(NumbToByte(item.ByteCode.Length, 4))); // Bytes = new byte[item.ByteCode.Length]; // for (int i = 0; i < item.ByteCode.Length; i++) // { // Bytes[i] = Convert.ToByte(item.ByteCode[i]); // } // ConcatByteAr(ref UserFilds, Bytes); // Trans.SmartContract.SmartContractDeploy.ByteCodeObjects.Add(new ByteCodeObject // { // Name = item.Name, // ByteCode = item.ByteCode // }); // } // ConcatByteAr(ref UserFilds, new byte[1]); // } // ConcatByteAr(ref UserFilds, new byte[15] { 11, 0, 3, 0, 0, 0, 0, 8, 0, 4, 0, 0, 0, 0, 0 }); // } // ConcatByteAr(ref UserFilds, new byte[1]); // ConcatByteAr(ref PervStr, NumbToByte(UserFilds.Length, 4)); // ConcatByteAr(ref PervStr, UserFilds); // } // else if (model.UserData != null) // { // byte[] UserFilds = new byte[1] {1}; // ConcatByteAr(ref UserFilds, NumbToByte(model.UserData.Length, 4)); // byte[] ufb = new byte[model.UserData.Length]; // for (int i = 0; i < model.UserData.Length; i++) // { // ufb[i] = Convert.ToByte(model.UserData[i]); // } // ConcatByteAr(ref UserFilds, ufb); // ConcatByteAr(ref PervStr, UserFilds); // Trans.UserFields = ufb; // } // if (model.Priv != null) // { // Rebex.Security.Cryptography.Ed25519 o = new Rebex.Security.Cryptography.Ed25519(); // o.FromPrivateKey(Private); // Trans.Signature = o.SignMessage(PervStr); // } // string Ar16 = "0123456789ABCDEF"; // string Hex = ""; // foreach (var i in PervStr) // { // Hex += Ar16[i >> 4]; // Hex += Ar16[i & 15]; // } // TransactionFlowResult TransRes = _connect.TransactionFlow(Trans); // if (TransRes.Status.Code > 0) // { // Res.Message = TransRes.Status.Message; // } // else // { // Res.Result = TransRes; // } // return Res; //} //public ApiResult<PervStrModel> CreatePervStr(TransactionCreateModel<string> model) //{ // ApiResult<PervStrModel> Res = new ApiResult<PervStrModel>(); // byte[] Source; // try // { // Source = Base58CheckEncoding.DecodePlain(model.Source); // } // catch (Exception) // { // Res.Message = "Source is incorrect"; // return Res; // } // if (model.Amount == null) // { // model.Amount = "0,0"; // } // else // { // model.Amount = model.Amount.Replace(".", ",").Replace(" ", ""); // } // if (model.Fee == null) // { // Res.Message = "Fee is not found"; // return Res; // } // else // { // model.Fee = model.Fee.Replace(".", ",").Replace(" ", ""); // } // PervStrModel ResPervStr = new PervStrModel // { // Source = model.Source // }; // WalletTransactionsCountGetResult TransactionId = _connect.WalletTransactionsCountGet(Source); // if (TransactionId.Status.Code == 0) // { // ResPervStr.Id = TransactionId.LastTransactionInnerId + 1; // } // byte[] PervStr = NumbToByte(ResPervStr.Id, 6); // byte[] Target; // if (model.Smart != null && model.Smart.Code != null) // { // byte[] ByteC = Source; // ConcatByteAr(ref ByteC, PervStr); // SmartContractCompileResult ByteCodes = _connect.SmartContractCompile(model.Smart.Code); // if (ByteCodes.Status.Code == 0) // { // foreach (ByteCodeObject item in ByteCodes.ByteCodeObjects) // { // ConcatByteAr(ref ByteC, item.ByteCode); // } // } // Target = Blake2s.Blake2S.ComputeHash(ByteC); // ResPervStr.Target = Base58CheckEncoding.EncodePlain(Target); // } // else // { // ResPervStr.Target = model.Target; // try // { // Target = Base58CheckEncoding.DecodePlain(ResPervStr.Target); // } // catch (Exception) // { // Res.Message = "Target is incorrect"; // return Res; // } // } // ResPervStr.Amount = model.Amount; // string[] ArStrAmmount = model.Amount.Split(','); // FeeRes F = Fee(Convert.ToDouble(model.Fee.Replace(',','.'))); // string FeeIntegral = Convert.ToString(F.Exp, 2); // while (FeeIntegral.Length < 5) // { // FeeIntegral = "0" + FeeIntegral; // } // string FeeFraction = Convert.ToString(F.Mantic, 2); // while (FeeFraction.Length < 10) // { // FeeFraction = "0" + FeeFraction; // } // string FeeBits = "0" + FeeIntegral + FeeFraction; // ResPervStr.Fee = BitsToNumb(FeeBits).ToString(); // ConcatByteAr(ref PervStr, Source); // ConcatByteAr(ref PervStr, Target); // ConcatByteAr(ref PervStr, NumbToByte(Convert.ToInt32(ArStrAmmount[0]), 4)); // if (ArStrAmmount.Length > 1) // ConcatByteAr(ref PervStr, NumbToByte(Convert.ToInt64(Convert.ToDecimal("0." + ArStrAmmount[1]) * 1000000000000000000), 8)); // else // ConcatByteAr(ref PervStr, new byte[8]); // ConcatByteAr(ref PervStr, ReverceByteAr(BitsToBytes(FeeBits))); // ConcatByteAr(ref PervStr, new byte[1] { 1 }); // var Trans = new Transaction{ // SmartContract = new SmartContractInvocation { // } // }; // if (model.Smart == null) // { // ConcatByteAr(ref PervStr, new byte[1]); // } // else // { // ConcatByteAr(ref PervStr, new byte[1] { 1 }); // byte[] UserFilds = new byte[0]; // ResPervStr.Smart = new ContSmart(); // ConcatByteAr(ref UserFilds, new byte[3] { 11, 0, 1 }); // if (model.Smart.Method == null) // { // ConcatByteAr(ref UserFilds, new byte[4]); // } // else // { // ResPervStr.Smart.Method = model.Smart.Method; // byte[] Method = new byte[model.Smart.Method.Length]; // for (int i = 0; i < model.Smart.Method.Length; i++) // { // Method[i] = Convert.ToByte(model.Smart.Method[i]); // } // ConcatByteAr(ref UserFilds, ReverceByteAr(NumbToByte(model.Smart.Method.Length, 4))); // ConcatByteAr(ref UserFilds, Method); // } // ConcatByteAr(ref UserFilds, new byte[4] { 15, 0, 2, 12 }); // if (model.Smart.Params == null) // { // ConcatByteAr(ref UserFilds, new byte[4]); // } // else // { // ConcatByteAr(ref UserFilds, ReverceByteAr(NumbToByte(model.Smart.Params.Count, 4))); // ResPervStr.Smart.Params = new List<ParamsCreateModel>(); // foreach (ParamsCreateModel item in model.Smart.Params) // { // byte[] Params; // switch (item.Key) // { // case "STRING": // ConcatByteAr(ref UserFilds, new byte[3] { 11, 0, 17 }); // ConcatByteAr(ref UserFilds, ReverceByteAr(NumbToByte(item.Value.Length, 4))); // Params = new byte[item.Value.Length + 1]; // for (int i = 0; i < item.Value.Length; i++) // { // Params[i] = Convert.ToByte(item.Value[i]); // } // ConcatByteAr(ref UserFilds, Params); // ResPervStr.Smart.Params.Add(item); // break; // case "DOUBLE": // ConcatByteAr(ref UserFilds, new byte[3] { 4, 0, 15 }); // ConcatByteAr(ref UserFilds, ReverceByteAr(BitConverter.GetBytes(Double.Parse(item.Value)))); // ConcatByteAr(ref UserFilds, new byte[1]); // ResPervStr.Smart.Params.Add(item); // break; // case "INT": // ConcatByteAr(ref UserFilds, new byte[3] { 8, 0, 9 }); // ConcatByteAr(ref UserFilds, ReverceByteAr(NumbToByte(int.Parse(item.Value), 4))); // ConcatByteAr(ref UserFilds, new byte[1]); // ResPervStr.Smart.Params.Add(item); // break; // case "BOOL": // ConcatByteAr(ref UserFilds, new byte[3] { 2, 0, 3 }); // ConcatByteAr(ref UserFilds, new byte[1]); // if (bool.Parse(item.Value)) // { // UserFilds[UserFilds.Length - 1] = 1; // } // ConcatByteAr(ref UserFilds, new byte[1]); // ResPervStr.Smart.Params.Add(item); // break; // } // } // } // ConcatByteAr(ref UserFilds, new byte[8] { 15, 0, 3, 11, 0, 0, 0, 0 }); // ConcatByteAr(ref UserFilds, new byte[4] { 2, 0, 4, 0 }); // if (model.Smart.ForgetNewState) // { // UserFilds[UserFilds.Length - 1] = 1; // ResPervStr.Smart.ForgetNewState = true; // } // if (model.Smart.Code != null) // { // ConcatByteAr(ref UserFilds, new byte[3] { 12, 0, 5 }); // ConcatByteAr(ref UserFilds, new byte[3] { 11, 0, 1 }); // ResPervStr.Smart.Deploy = new Deploy // { // Code = model.Smart.Code // }; // ConcatByteAr(ref UserFilds, ReverceByteAr(NumbToByte(model.Smart.Code.Length, 4))); // byte[] Code = new byte[model.Smart.Code.Length]; // for (int i = 0; i < model.Smart.Code.Length; i++) // { // Code[i] = Convert.ToByte(model.Smart.Code[i]); // } // ConcatByteAr(ref UserFilds, Code); // ConcatByteAr(ref UserFilds, new byte[4] { 15, 0, 2, 12 }); // SmartContractCompileResult CompiledByteCode = _connect.SmartContractCompile(model.Smart.Code); // if (CompiledByteCode.Status.Code > 0) // { // Res.Message = CompiledByteCode.Status.Message; // return Res; // } // else // { // ConcatByteAr(ref UserFilds, ReverceByteAr(NumbToByte(CompiledByteCode.ByteCodeObjects.Count, 4))); // foreach (ByteCodeObject item in CompiledByteCode.ByteCodeObjects) // { // ConcatByteAr(ref UserFilds, new byte[3] { 11, 0, 1 }); // ConcatByteAr(ref UserFilds, ReverceByteAr(NumbToByte(item.Name.Length, 4))); // byte[] Bytes = new byte[item.Name.Length]; // for (int i = 0; i < item.Name.Length; i++) // { // Bytes[i] = Convert.ToByte(item.Name[i]); // } // ConcatByteAr(ref UserFilds, Bytes); // ConcatByteAr(ref UserFilds, new byte[3] { 11, 0, 2 }); // ConcatByteAr(ref UserFilds, ReverceByteAr(NumbToByte(item.ByteCode.Length, 4))); // Bytes = new byte[item.ByteCode.Length]; // for (int i = 0; i < item.ByteCode.Length; i++) // { // Bytes[i] = Convert.ToByte(item.ByteCode[i]); // } // ConcatByteAr(ref UserFilds, Bytes); // ConcatByteAr(ref UserFilds, new byte[1]); // } // } // ConcatByteAr(ref UserFilds, new byte[15] { 11, 0, 3, 0, 0, 0, 0, 8, 0, 4, 0, 0, 0, 0, 0}); // } // ConcatByteAr(ref UserFilds, new byte[1]); // ConcatByteAr(ref PervStr, NumbToByte(UserFilds.Length, 4)); // ConcatByteAr(ref PervStr, UserFilds); // } // string Ar16 = "0123456789ABCDEF"; // ResPervStr.Priv = ""; // foreach (var i in PervStr) // { // ResPervStr.Priv += Ar16[i >> 4]; // ResPervStr.Priv += Ar16[i & 15]; // } // Res.Result = ResPervStr; // return Res; //} //public ApiResult<bool> Send(PervStrModel model) //{ // ApiResult<bool> Res = new ApiResult<bool> // { // Result = false // }; // Transaction Trans = new Transaction // { // Id = model.Id, // TimeCreation = DateTime.Now.Ticks, // Balance = new Amount { Integral = 0, Fraction = 0 }, // Currency = 1, // Fee = new AmountCommission { Commission = Convert.ToInt16(model.Fee) }, // Signature = new byte[64] // }; // if (model.Priv == null) // { // Res.Message = "Signature is not found"; // return Res; // } // else // { // string Ar16 = "0123456789ABCDEF"; // for (int i = 0; i < model.Priv.Length; i++) // { // for (int j = 0; j < Ar16.Length; j++) // { // if (Ar16[j] == model.Priv[i]) // { // Trans.Signature[i / 2] += Convert.ToByte(j * 16); // } // if (Ar16[j] == model.Priv[i + 1]) // { // Trans.Signature[i / 2] += Convert.ToByte(j); // } // } // i++; // } // } // try // { // Trans.Source = Base58CheckEncoding.DecodePlain(model.Source); // } // catch (Exception) // { // Res.Message = "Source is incorrect"; // return Res; // } // try // { // Trans.Target = Base58CheckEncoding.DecodePlain(model.Target); // } // catch (Exception) // { // Res.Message = "Target is incorrect"; // return Res; // } // if (model.Amount == null) // { // Trans.Amount = new Amount { Integral = 0, Fraction = 0 }; // } // else // { // model.Amount = model.Amount.Replace(".", ",").Replace(" ", ""); // string[] ArStrAmmount = model.Amount.Split(','); // Trans.Amount = new Amount // { // Integral = Convert.ToInt32(ArStrAmmount[0]) // }; // if (ArStrAmmount.Length > 1) // { // Trans.Amount.Fraction = Convert.ToInt64(Convert.ToDecimal("0." + ArStrAmmount[1]) * 1000000000000000000); // } // } // if (model.Smart != null) // { // Trans.SmartContract = new SmartContractInvocation // { // ForgetNewState = model.Smart.ForgetNewState // }; // if (model.Smart.Deploy == null) // { // Trans.SmartContract.Method = model.Smart.Method; // if (model.Smart.Params != null) // { // Trans.SmartContract.Params = new List<Variant>(); // foreach (var item in model.Smart.Params) // { // switch (item.Key) // { // case "STRING": // Trans.SmartContract.Params.Add(new Variant { V_string = item.Value }); // break; // case "DOUBLE": // Trans.SmartContract.Params.Add(new Variant { V_double = Convert.ToDouble(item.Value) }); // break; // } // } // } // } // else // { // Trans.SmartContract.SmartContractDeploy = new SmartContractDeploy // { // SourceCode = model.Smart.Deploy.Code // }; // SmartContractCompileResult ByteCodes = _connect.SmartContractCompile(model.Smart.Deploy.Code); // if (ByteCodes.Status.Code > 0) // { // Res.Message = ByteCodes.Status.Message; // return Res; // } // Trans.SmartContract.SmartContractDeploy.ByteCodeObjects = new List<ByteCodeObject>(); // foreach (ByteCodeObject item in ByteCodes.ByteCodeObjects) // { // Trans.SmartContract.SmartContractDeploy.ByteCodeObjects.Add(new ByteCodeObject // { // Name = item.Name, // ByteCode = item.ByteCode // }); // } // } // } // TransactionFlowResult TransRes = _connect.TransactionFlow(Trans); // if (TransRes.Status.Code > 0) // { // Res.Message = TransRes.Status.Message; // } // else // { // Res.Result = true; // } // return Res; //} public ApiResult <List <SmartContractInfo> > SmartContract(string Key) { ApiResult <List <SmartContractInfo> > Res = new ApiResult <List <SmartContractInfo> > { Result = null }; byte[] Public; try { Public = Base58CheckEncoding.DecodePlain(Key); } catch (Exception) { Res.Message = "Public key is not valid"; return(Res); } SmartContractDataResult Smart = _connect.SmartContractDataGet(Public); if (Smart.Status.Code > 0) { Res.Message = Smart.Status.Message; return(Res); } Res.Result = new List <SmartContractInfo>(); foreach (SmartContractMethod item in Smart.Methods) { SmartContractInfo Info = new SmartContractInfo { ReturnType = item.ReturnType, Name = item.Name, Arguments = new List <SmartArgument>() }; foreach (SmartContractMethodArgument i in item.Arguments) { Info.Arguments.Add(new SmartArgument { Name = i.Name, Type = i.Type }); } Res.Result.Add(Info); } return(Res); }
public void Encode_And_Decode_Address() { var address = Address.FromBase58("xFqJD9R33mQBQPr1hCFUZMayXFQ577j34MPyUdXzbPpAYufG2"); var data = address.ToByteArray(); var enCode = Base58CheckEncoding.Encode(data); enCode.ShouldNotBe(string.Empty); var deCode = Base58CheckEncoding.Decode(enCode); deCode.ShouldBe(data); var deCode1 = Base58CheckEncoding.DecodePlain(enCode); deCode1.ShouldNotBe(data); }
public ApiResult <BalanceCS> Balance(string Public) { ApiResult <BalanceCS> Res = new ApiResult <BalanceCS> { Result = null }; byte[] PublicKey; try { PublicKey = Base58CheckEncoding.DecodePlain(Public); } catch (Exception) { Res.Message = "PublicKey error"; return(Res); } WalletBalanceGetResult Balance = _connect.WalletBalanceGet(PublicKey); if (Balance.Status.Code > 0 && Balance.Status.Message != "Not found") { Res.Message = Balance.Status.Message; return(Res); } TokenBalancesResult Tokens = _connect.TokenBalancesGet(PublicKey); if (Tokens.Status.Code > 0 && Balance.Status.Message != "Not found") { Res.Message = Tokens.Status.Message; return(Res); } Res.Result = new BalanceCS { CS = $"{Balance.Balance.Integral}.{FractionToStr(Balance.Balance.Fraction)}", Tokens = Tokens.Balances.Select(BalanceTokenModel).ToList(), PublicKey = Public }; return(Res); }
/// <summary> /// Decode a miniLock ID into a byte array. /// </summary> /// <param name="encodedPublicKey">The miniLock ID.</param> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="CorruptIdentityException"></exception> /// <returns>A 32 byte array.</returns> public static byte[] DecodeMiniLockPublicKey(string encodedPublicKey) { if (encodedPublicKey == null) { throw new ArgumentNullException("encodedPublicKey", "encodedPublicKey cannot be null"); } var raw = Base58CheckEncoding.DecodePlain(encodedPublicKey); var publicKey = ArrayHelper.SubArray(raw, 0, 32); var checksum = ArrayHelper.SubArray(raw, 32); // validate the checksum if (!checksum.SequenceEqual(Blake2S.Hash(publicKey, (byte[])null, 1))) { throw new CorruptIdentityException("the given identity seems to be an invalid miniLock ID"); } return(publicKey); }
public void EncodePlain_And_DecodePlain_Hash() { var hash = HashHelper.ComputeFrom("hash"); var data = hash.ToByteArray(); var bytes = new byte[] { 0 }; var enCode = Base58CheckEncoding.EncodePlain(data); enCode.ShouldNotBe(string.Empty); var deCode = Base58CheckEncoding.DecodePlain(enCode); deCode.ShouldBe(data); Base58CheckEncoding.EncodePlain(bytes).ShouldBe("1"); Should.Throw <FormatException>(() => { Base58CheckEncoding.DecodePlain(bytes.ToString()); }); Should.Throw <FormatException>(() => { Base58CheckEncoding.Decode(enCode); }); }
/// <inheritdoc/> public async Task <byte[]> UploadAsync(byte[] data) { if (uploadClient != null) { RestRequest request = new RestRequest("/api/v0/add", Method.POST); request.AddDecompressionMethod(System.Net.DecompressionMethods.None); request.AddFile("file", data, "file", "application/octet-stream"); IRestResponse response = await uploadClient.ExecutePostTaskAsync(request); if (response.ErrorException != null) { // TODO: throw some kind of custom exception on unsuccessful upload throw new Exception(); } string hash = JsonConvert.DeserializeObject <UploadResponse>(response.Content).Hash; return(Base58CheckEncoding.DecodePlain(hash).Skip(2).ToArray()); } return(null); }
public ActionResult Balance(string Id = "") { Response.Headers.Add("content-type", "application/json"); byte[] Key; try { Key = Base58CheckEncoding.DecodePlain(Id); } catch (Exception) { Response.StatusCode = (int)HttpStatusCode.Forbidden; return(Json("PublicKey is invalid", JsonRequestBehavior.AllowGet)); } try { return(Json(_api.Api.Balance(Key), JsonRequestBehavior.AllowGet)); } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.Forbidden; return(Json(ex.Message, JsonRequestBehavior.AllowGet)); } }
public ActionResult SmartContract(string Id) { byte[] Public; try { Public = Base58CheckEncoding.DecodePlain(Id); } catch (Exception) { Response.StatusCode = (int)HttpStatusCode.Forbidden; return(Json("PublicKey is invalid", JsonRequestBehavior.AllowGet)); } try { return(Json(_api.Api.SmartContract(Public), JsonRequestBehavior.AllowGet)); } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.Forbidden; return(Json(ex.Message, JsonRequestBehavior.AllowGet)); } }
public string Decode(FileStream source, string fileName) { string decodedString; using (var reader = new StreamReader(source)) { decodedString = reader.ReadToEnd(); } source.Close(); var decoded = Base58CheckEncoding.DecodePlain(decodedString); var result = new FileStream(fileName + "1", FileMode.Create); using (var writer = new BinaryWriter(result)) { writer.Write(decoded); } result.Close(); return(fileName + "1"); }
public static IPublicKey FromPublicKeyString(string publicKey, string addressPrefix = null) { try { if (addressPrefix.IsNull()) { addressPrefix = ChainConfig.AddressPrefix; } var prefix = publicKey.Substring(0, addressPrefix.Length); Assert.Equal( addressPrefix, prefix, string.Format("Expecting key to begin with {0}, instead got {1}", addressPrefix, prefix) ); publicKey = publicKey.Substring(addressPrefix.Length); var buffer = Base58CheckEncoding.DecodePlain(publicKey); var result = FromBuffer(buffer); buffer.Clear(); return(result); } catch { return(null); } }
public void DecodeInvalidChar() { Base58CheckEncoding.DecodePlain("ab0"); }
public async Task TestCreateKeyWorksForSeed() { var senderVk = await Crypto.CreateKeyAsync(wallet, MY1_IDENTITY_KEY_JSON); Assert.AreEqual(32, Base58CheckEncoding.DecodePlain(senderVk).Length); }
public async Task TestCreateKeyWorksWithoutSeed() { var senderVk = await Crypto.CreateKeyAsync(wallet, "{}"); Assert.AreEqual(32, Base58CheckEncoding.DecodePlain(senderVk).Length); }
public PublicKey(string b58String) { this.bytes = Base58CheckEncoding.DecodePlain(b58String); }
private void bStart_Click(object sender, RoutedEventArgs e) { if (starting) { return; } if ((string)lMiningStatus.Content == "Mining is ON") { stopIxiMiner(); enableControls(); } else { if (tbPoolURL.Text == "") { log("Please enter Pool URL."); bStart.Content = FindResource("toggle_disabled"); lMiningStatus.Content = "Mining is OFF"; return; } if (tbWalletAddress.Text == "") { log("Please enter IxiCash Wallet Address."); bStart.Content = FindResource("toggle_disabled"); lMiningStatus.Content = "Mining is OFF"; return; } var t = this; string poolUrl = tbPoolURL.Text; string walletAddress = tbWalletAddress.Text; string hasher = (string)((System.Windows.Controls.ComboBoxItem)cbHasher.SelectedItem).Content; string intensity = sIntensity.Value.ToString(); if (!Address.validateChecksum(Base58CheckEncoding.DecodePlain(walletAddress))) { log("Invalid IxiCash Wallet Address."); bStart.Content = FindResource("toggle_disabled"); lMiningStatus.Content = "Mining is OFF"; return; } settings["PoolURL"] = poolUrl; settings["WalletAddress"] = walletAddress; settings["Hasher"] = hasher; settings["Intensity"] = intensity; saveSettings(); new Thread(() => { if (starting) { return; } starting = true; try { t.Dispatcher.Invoke(() => { disableControls(); }); fetchIxiMiner(); startIxiMiner(poolUrl, walletAddress, hasher, intensity); } catch (Exception ex) { log("Exception occured while starting the miner: " + ex.ToString()); t.Dispatcher.Invoke(() => { enableControls(); }); } starting = false; }).Start(); } }
public Transaction CreateTransaction(CreateTransactionModel model) { if (model.Source.Length != 32) { throw new Exception("The length of the Source is not equal to 32"); } WalletDataGetResult WalletData = _connect.WalletDataGet(model.Source); if (WalletData.Status.Code > 0) { throw new Exception(WalletData.Status.Message); } Transaction Res = new Transaction { Id = WalletData.WalletData.LastTransactionId + 1, Source = model.Source, Amount = AmountConvert(model.Amount), Fee = AmountCommissionEncode(model.Fee), UserFields = model.UserData }; if (model.SmartContract.Code == null) { if (model.Target.Length != 32) { throw new Exception("The length of the Target is not equal to 32"); } Res.Target = model.Target; } else { Res.SmartContract = new SmartContractInvocation(); byte[] ByteC = Res.Source; ConcatByteAr(ref ByteC, NumbToByte(Res.Id, 6)); SmartContractCompileResult ByteCodes = _connect.SmartContractCompile(model.SmartContract.Code); if (ByteCodes.Status.Code > 0) { throw new Exception(ByteCodes.Status.Message); } foreach (ByteCodeObject item in ByteCodes.ByteCodeObjects) { ConcatByteAr(ref ByteC, item.ByteCode); } Res.Target = Blake2s.Blake2S.ComputeHash(ByteC); Res.SmartContract.SmartContractDeploy = new SmartContractDeploy { SourceCode = model.SmartContract.Code, ByteCodeObjects = ByteCodes.ByteCodeObjects }; } if (model.SmartContract.Method != null) { Res.SmartContract = new SmartContractInvocation { Method = model.SmartContract.Method, Params = new List <Variant>() }; if (model.SmartContract.Params != null) { foreach (API_Variant i in model.SmartContract.Params) { Res.SmartContract.Params.Add(VariantConvert(i)); } } } if (Res.SmartContract != null) { Res.SmartContract.ForgetNewState = model.SmartContract.ForgetNewState; } if (model.UsedContracts != null) { Res.UsedContracts = new List <byte[]>(); foreach (string i in model.UsedContracts) { Res.UsedContracts.Add(Base58CheckEncoding.DecodePlain(i)); } } return(Res); }