Ejemplo n.º 1
0
        public static void PositiveHexTests(string decodedAsHexString, string encoded)
        {
            var decoded = Hexadecimal.Decode(decodedAsHexString);

            var encodeResult = Base58.Encode(decoded);

            Assert.Equal(encoded, encodeResult);

            var decodeResult = Base58.Decode(encoded);

            Assert.Equal(decoded, decodeResult);
        }
Ejemplo n.º 2
0
        public void Data()
        {
            var recount = JsonSerializer.Deserialize <Recount>(raw, JsonDefaultSettings.Options);

            var dataRaw = "2PUvrcNWrVPFZ8TMZhjsX61ef85RcEqG3nQSor17XbtMZbkd9Tsj9SATPRK2KyFFGHsSMGjD8D7H2bqLgvmuP1sZjeE78Yx3qTttmjwb4sVCsF2uKkhAXF76T84ZHFg6fSRcoM88ABrSyYDDsuzUx6KM5rLSttnY3KDbio5GT2Bsg2daLrojJ";
            var data    = Base58.Decode(dataRaw);

            Console.WriteLine(BitConverter.ToString(data));
            Console.WriteLine(BitConverter.ToString(recount.GetData()));

            Assert.IsTrue(data.SequenceEqual(recount.GetData()));
        }
Ejemplo n.º 3
0
        public static NebAccount FromAddress(string address)
        {
            var acc = new NebAccount();

            if (!IsValidAddress(address, AddressType.Normal))
            {
                throw new ArgumentException("Invalid Account Address");
            }

            acc.m_address = Base58.Decode(address);
            return(acc);
        }
Ejemplo n.º 4
0
        public void TestAccountProperties()
        {
            String publicKey  = "8LbAU5BSrGkpk5wbjLMNjrbc9VzN9KBBYv9X8wGpmAJT";
            String privateKey = "CMLwxbMZJMztyTJ6Zkos66cgU7DybfFJfyJtTVpme54t";
            String address    = "3MzZCGFyuxgC4ZmtKRS7vpJTs75ZXdkbp1K";

            PrivateKeyAccount account = PrivateKeyAccount.CreateFromPrivateKey(privateKey, AddressEncoding.TestNet);

            CollectionAssert.AreEqual(Base58.Decode(privateKey), account.PrivateKey);
            CollectionAssert.AreEqual(Base58.Decode(publicKey), account.PublicKey);
            Assert.AreEqual(address, account.Address);
        }
Ejemplo n.º 5
0
        /// <summary>
        ///   Encrypt data as CMS protected data.
        /// </summary>
        /// <param name="keyName">
        ///   The key name to protect the <paramref name="plainText"/> with.
        /// </param>
        /// <param name="plainText">
        ///   The data to protect.
        /// </param>
        /// <param name="cancel">
        ///   Is used to stop the task.  When cancelled, the <see cref="TaskCanceledException"/> is raised.
        /// </param>
        /// <returns>
        ///   A task that represents the asynchronous operation. The task's result is
        ///   the cipher text of the <paramref name="plainText"/>.
        /// </returns>
        /// <remarks>
        ///   Cryptographic Message Syntax (CMS), aka PKCS #7 and
        ///   <see href="https://tools.ietf.org/html/rfc5652">RFC 5652</see>,
        ///   describes an encapsulation syntax for data protection. It
        ///   is used to digitally sign, digest, authenticate, and/or encrypt
        ///   arbitrary message content.
        /// </remarks>
        public async Task <byte[]> CreateProtectedDataAsync(
            string keyName,
            byte[] plainText,
            CancellationToken cancel = default(CancellationToken))
        {
            // Identify the recipient by the Subject Key ID.

            // TODO: Need a method to just the get BC public key
            // Get the BC key pair for the named key.
            var ekey = await Store.TryGetAsync(keyName, cancel).ConfigureAwait(false);

            if (ekey == null)
            {
                throw new KeyNotFoundException($"The key '{keyName}' does not exist.");
            }
            AsymmetricCipherKeyPair kp = null;

            UseEncryptedKey(ekey, key =>
            {
                kp = this.GetKeyPairFromPrivateKey(key);
            });

            // Add recipient type based on key type.
            var edGen = new CmsEnvelopedDataGenerator();

            if (kp.Private is RsaPrivateCrtKeyParameters)
            {
                edGen.AddKeyTransRecipient(kp.Public, Base58.Decode(ekey.Id));
            }
            else if (kp.Private is ECPrivateKeyParameters)
            {
                var cert = await CreateBCCertificateAsync(keyName, cancel).ConfigureAwait(false);

                edGen.AddKeyAgreementRecipient(
                    agreementAlgorithm: CmsEnvelopedDataGenerator.ECDHSha1Kdf,
                    senderPrivateKey: kp.Private,
                    senderPublicKey: kp.Public,
                    recipientCert: cert,
                    cekWrapAlgorithm: CmsEnvelopedDataGenerator.Aes256Wrap
                    );
            }
            else
            {
                throw new NotSupportedException($"The key type {kp.Private.GetType().Name} is not supported.");
            }

            // Generate the protected data.
            var ed = edGen.Generate(
                new CmsProcessableByteArray(plainText),
                CmsEnvelopedDataGenerator.Aes256Cbc);

            return(ed.GetEncoded());
        }
Ejemplo n.º 6
0
        public void Base58_Decode()
        {
            // Arrange
            var test = "2NXDA7BcYgm9Sfmth7KzYhxPqrw4Qpuz";

            // Act
            var decoding = Base58.Decode(test);
            var result   = Encoding.ASCII.GetString(decoding);

            // Asset
            Assert.AreEqual(result, "Base58 Unit Test Decode");
        }
Ejemplo n.º 7
0
        public static void PositiveTests(string decoded, string encoded)
        {
            var decodedBytes = Encoding.UTF8.GetBytes(decoded);

            var encodeResult = Base58.Encode(decodedBytes);

            Assert.Equal(encoded, encodeResult);

            var decodeResult = Base58.Decode(encoded);

            Assert.Equal(decodedBytes, decodeResult);
        }
Ejemplo n.º 8
0
        public void Base58_Full()
        {
            // Arrange
            var test = RandomString(_rand.Next(1, 30));

            // Act
            var encodig  = Base58.Encode(Encoding.ASCII.GetBytes(test));
            var decoding = Base58.Decode(encodig);
            var result   = Encoding.ASCII.GetString(decoding);

            // Asset
            Assert.AreEqual(test, result);
        }
Ejemplo n.º 9
0
 private byte[] Decode(EncodingNames fromEnc, string input)
 {
     return(fromEnc switch
     {
         EncodingNames.Base16 => Base16.Decode(input),
         EncodingNames.Base43 => Base43.Decode(input),
         EncodingNames.Base58 => Base58.Decode(input),
         EncodingNames.Base58Check => Base58.DecodeWithChecksum(input),
         EncodingNames.Base64 => Convert.FromBase64String(input),
         EncodingNames.UTF8 => Encoding.UTF8.GetBytes(input),
         EncodingNames.Unicode => Encoding.Unicode.GetBytes(input),
         _ => throw new ArgumentException("undefined encoding.")
     });
Ejemplo n.º 10
0
        public ObjectResult Get(string id)
        {
            logger.LogDebug("Consuntado último bloque");
            var query = new BlockQuery(node.Blockchain);
            var block = query.Execute(Base58.Decode(id));

            if (block == null)
            {
                return(NotFound("No tengo ningún bloque con ese hash"));
            }

            return(Ok(block));
        }
Ejemplo n.º 11
0
        public static byte[] CalculateGenerationSignature(string prevGenSig, string prevGenratorAddress)
        {
            if (string.IsNullOrWhiteSpace(prevGenSig) || string.IsNullOrWhiteSpace(prevGenratorAddress))
            {
                return(HashHelper.EmptyHash());
            }

            var genSigSeed = new List <byte>();

            genSigSeed.AddRange(Base16.Decode(prevGenSig));
            genSigSeed.AddRange(Base58.Decode(prevGenratorAddress));
            return(Sha3Helper.Hash(genSigSeed.ToArray()));
        }
Ejemplo n.º 12
0
        static PrivateKeyAccount GetAccount(string seed, bool base58)
        {
            //var seed = Base58.Decode("2PLzSeA7TSYAehA5y1Qj1U5GZw9nQaHVLy2MbBwM6cCtqSS26hL6PrNNDg6k25kaWygaeEcX6KfzwPkNc9G1zLbF");
            //var recipient = "3Mr2S13RUQzn2peQMZjf7bTrjkkUqtJaYEa";

            // create account
            var seedBytes = Encoding.UTF8.GetBytes(seed);

            if (base58)
            {
                seedBytes = Base58.Decode(seed);
            }
            return(PrivateKeyAccount.CreateFromSeed(seedBytes, AddressEncoding.TestNet));
        }
        /*public static byte[] AES256Decrypt(this byte[] block, byte[] key)
         * {
         *  using (var aes = Aes.Create())
         *  {
         *      aes.Key = key;
         *      aes.Mode = CipherMode.ECB;
         *      aes.Padding = PaddingMode.None;
         *      using (ICryptoTransform decryptor = aes.CreateDecryptor())
         *      {
         *          return decryptor.TransformFinalBlock(block, 0, block.Length);
         *      }
         *  }
         * }
         *
         * public static byte[] AES256Encrypt(this byte[] block, byte[] key)
         * {
         *  using (Aes aes = Aes.Create())
         *  {
         *      aes.Key = key;
         *      aes.Mode = CipherMode.ECB;
         *      aes.Padding = PaddingMode.None;
         *      using (ICryptoTransform encryptor = aes.CreateEncryptor())
         *      {
         *          return encryptor.TransformFinalBlock(block, 0, block.Length);
         *      }
         *  }
         * }
         *
         * public static byte[] AesDecrypt(this byte[] data, byte[] key, byte[] iv)
         * {
         *  if (data == null || key == null || iv == null) throw new ArgumentNullException();
         *  if (data.Length % 16 != 0 || key.Length != 32 || iv.Length != 16) throw new ArgumentException();
         *  using (Aes aes = Aes.Create())
         *  {
         *      aes.Padding = PaddingMode.None;
         *      using (ICryptoTransform decryptor = aes.CreateDecryptor(key, iv))
         *      {
         *          return decryptor.TransformFinalBlock(data, 0, data.Length);
         *      }
         *  }
         * }
         *
         * public static byte[] AesEncrypt(this byte[] data, byte[] key, byte[] iv)
         * {
         *  if (data == null || key == null || iv == null) throw new ArgumentNullException();
         *  if (data.Length % 16 != 0 || key.Length != 32 || iv.Length != 16) throw new ArgumentException();
         *  using (Aes aes = Aes.Create())
         *  {
         *      aes.Padding = PaddingMode.None;
         *      using (ICryptoTransform encryptor = aes.CreateEncryptor(key, iv))
         *      {
         *          return encryptor.TransformFinalBlock(data, 0, data.Length);
         *      }
         *  }
         * }
         *
         * internal static byte[] ToAesKey(this string password)
         * {
         *  using (var sha256 = SHA256.Create())
         *  {
         *      byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
         *      byte[] passwordHash = sha256.ComputeHash(passwordBytes);
         *      byte[] passwordHash2 = sha256.ComputeHash(passwordHash);
         *      Array.Clear(passwordBytes, 0, passwordBytes.Length);
         *      Array.Clear(passwordHash, 0, passwordHash.Length);
         *      return passwordHash2;
         *  }
         * }
         *
         * internal static byte[] ToAesKey(this SecureString password)
         * {
         *  using (var sha256 = SHA256.Create())
         *  {
         *      byte[] passwordBytes = password.ToArray();
         *      byte[] passwordHash = sha256.ComputeHash(passwordBytes);
         *      byte[] passwordHash2 = sha256.ComputeHash(passwordHash);
         *      Array.Clear(passwordBytes, 0, passwordBytes.Length);
         *      Array.Clear(passwordHash, 0, passwordHash.Length);
         *      return passwordHash2;
         *  }
         * }
         *
         */

        public static byte[] Base58CheckDecode(this string input)
        {
            byte[] buffer = Base58.Decode(input);
            if (buffer.Length < 4)
            {
                throw new FormatException();
            }
            byte[] expected_checksum = buffer.Sha256(0, (uint)(buffer.Length - 4)).SHA256();
            expected_checksum = expected_checksum.Take(4).ToArray();
            var src_checksum = buffer.Skip(buffer.Length - 4).ToArray();

            Throw.If(!src_checksum.SequenceEqual(expected_checksum), "WIF checksum failed");
            return(buffer.Take(buffer.Length - 4).ToArray());
        }
Ejemplo n.º 14
0
        public static bool AddressVerify(string accountAddress)
        {
            try
            {
                var bytes = Base58.Decode(accountAddress);

                if (bytes.Length != 28)
                {
                    return(false);
                }

                var prefixBytes = new byte[4];
                Array.Copy(bytes, 0, prefixBytes, 0, 4);

                if (BitConverter.IsLittleEndian)
                {
                    Array.Reverse(prefixBytes);
                }

                var prefixValue = BitConverter.ToInt32(prefixBytes, 0);

                if (GlobalParameters.IsTestnet)
                {
                    if (prefixValue != testnetPrefix)
                    {
                        return(false);
                    }
                }
                else
                {
                    if (prefixValue != mainnetPrefix)
                    {
                        return(false);
                    }
                }

                //var prefix = bytes[prefixLen];
                var checksum = new byte[4];
                var data     = new byte[bytes.Length - 4];
                Array.Copy(bytes, 0, data, 0, bytes.Length - 4);
                Array.Copy(bytes, bytes.Length - checksum.Length, checksum, 0, checksum.Length);

                var newChecksum = HashHelper.DoubleHash(data).Take(4);
                return(BitConverter.ToInt32(checksum, 0) == BitConverter.ToInt32(newChecksum.ToArray(), 0));
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 15
0
 private static byte[] Base58CheckDecode(this string input)
 {
     byte[] buffer = Base58.Decode(input);
     if (buffer.Length < 4)
     {
         throw new FormatException();
     }
     byte[] checksum = buffer.Sha256(0, buffer.Length - 4).Sha256();
     if (!buffer.Skip(buffer.Length - 4).SequenceEqual(checksum.Take(4)))
     {
         throw new FormatException();
     }
     return(buffer.Take(buffer.Length - 4).ToArray());
 }
Ejemplo n.º 16
0
        public static UInt160 GetPublicKeyHashFromAddress(string address)
        {
            System.Security.Cryptography.SHA256 sha256 = System.Security.Cryptography.SHA256.Create();
            var alldata = Base58.Decode(address);
            var data    = alldata.Take(alldata.Length - 4).ToArray();
            var hash    = sha256.ComputeHash(data);

            hash = sha256.ComputeHash(hash);
            var hashbts     = hash.Take(4).ToArray();
            var datahashbts = alldata.Skip(alldata.Length - 4).ToArray();
            var pkhash      = data.Skip(1).ToArray();

            return(new UInt160(pkhash));
        }
Ejemplo n.º 17
0
        public void Base58Tests()
        {
            var bytes = new byte[Address.PublicKeyLength];
            var rnd   = new Random(39545);

            rnd.NextBytes(bytes);

            var base58 = Base58.Encode(bytes);

            var output = Base58.Decode(base58);

            Assert.IsTrue(output.Length == bytes.Length);
            Assert.IsTrue(output.SequenceEqual(bytes));
        }
Ejemplo n.º 18
0
        public void TestCanMineForBasicNoncedValue()
        {
            var snoop = new Rapper(420, "snoop dogg");

            var mined_snoop = Miner.Mine(snoop, 3, CancellationToken.None);

            Assert.AreEqual(mined_snoop.Value.Name, "snoop dogg");
            Assert.AreEqual(mined_snoop.Value.Level, 420);
            Assert.AreEqual(mined_snoop.Nonce, 1347);

            var mined_dag = IpfsDagSerialization.MapToDag(mined_snoop);

            Assert.True(Miner.FoundGoldenNonce(Base58.Decode(mined_dag.Hash), 3));
        }
Ejemplo n.º 19
0
        public static bool AddressVerify(string accountAddress)
        {
            var bytes = Base58.Decode(accountAddress);
            //var prefix = bytes[prefixLen];
            var checksum = new byte[4];
            var data     = new byte[bytes.Length - 4];

            Array.Copy(bytes, 0, data, 0, bytes.Length - 4);
            Array.Copy(bytes, bytes.Length - checksum.Length, checksum, 0, checksum.Length);

            var newChecksum = HashHelper.DoubleHash(data).Take(4);

            return(BitConverter.ToInt32(checksum, 0) == BitConverter.ToInt32(newChecksum.ToArray(), 0));
        }
Ejemplo n.º 20
0
        public override byte[] Serialize()
        {
            var addressBytes   = Base58.Decode(WalletAddress);
            var minerTypeBytes = (byte)MinerType;
            var serialNoBytes  = Encoding.UTF8.GetBytes(SerialNo);

            var data = new List <byte>();

            data.AddRange(addressBytes);
            data.Add(minerTypeBytes);
            data.AddRange(serialNoBytes);

            return(data.ToArray());
        }
Ejemplo n.º 21
0
        public bool AddressVerify()
        {
            var bytes = Base58.Decode("fiiimB6yxbLHKU2YuLhSDSjiB5mdWXt51duHBi");
            //var prefix = bytes[prefixLen];
            var checksum = new byte[4];
            var data     = new byte[bytes.Length - 4];

            Array.Copy(bytes, 0, data, 0, bytes.Length - 4);
            Array.Copy(bytes, bytes.Length - checksum.Length, checksum, 0, checksum.Length);

            var newChecksum = HashHelper.DoubleHash(data).Take(4);

            return(BitConverter.ToInt32(checksum, 0) == BitConverter.ToInt32(newChecksum.ToArray(), 0));
        }
Ejemplo n.º 22
0
        public override byte[] Serialize()
        {
            byte[] addressBytes     = Base58.Decode(WalletAddress);
            byte[] serialNoBytes    = Encoding.UTF8.GetBytes(SerialNo);
            byte[] serialNoLenBytes = BitConverter.GetBytes(serialNoBytes.Length);
            byte[] nameBytes        = Encoding.UTF8.GetBytes(Name);

            List <byte> data = new List <byte>();

            data.AddRange(addressBytes);
            data.AddRange(serialNoLenBytes);
            data.AddRange(serialNoBytes);
            data.AddRange(nameBytes);
            return(data.ToArray());
        }
Ejemplo n.º 23
0
        public static void ValidChecksummedBase58(string value)
        {
            var valueBytes = Base58.Decode(value);

            Assert.True(Checksum.Verify(valueBytes));

            // Clear checksum before WriteSum
            for (var i = valueBytes.Length - Checksum.SumLength; i < valueBytes.Length; i++)
            {
                valueBytes[i] = 0;
            }

            Checksum.WriteSum(valueBytes);
            Assert.True(Checksum.Verify(valueBytes));
        }
Ejemplo n.º 24
0
        /// <summary>
        /// возврат твитов по адресу
        /// </summary>
        /// <param name="alias"></param>
        /// <returns></returns>
        public List <TweetModel> getTweetByAddressAsync(string address)
        {
            List <jsonModel> listjson = new List <jsonModel>();

            using (var webClient = new WebClient())
            {
                listjson = json.deserializeModel <List <jsonModel> >(webClient.DownloadString($"{nodeString}/addresses/data/{address}"));
            }

            List <TweetModel> t_hash = new List <TweetModel>();

            bool ishashValue = true;
            int  i           = 0;
            var  adressByte  = Encoding.UTF8.GetBytes(address);
            //получаем хэш адреса первый
            var hashedAddress = SHA256.ComputeHash(adressByte, 0, adressByte.Length);

            while (true)
            {
                if (listjson.FirstOrDefault(x => x.key == BitConverter.ToString(hashedAddress).Replace("-", "")) != null)
                {
                    string value = listjson.FirstOrDefault(x => x.key == BitConverter.ToString(hashedAddress).Replace("-", "")).value;
                    try
                    {
                        string has123h = Encoding.Unicode.GetString(Base58.Decode(value));
                        string text    = ipfs.FileSystem.ReadAllTextAsync(convertXXXL(BitConverter.ToString(Base58.Decode(value)))).Result;
                        t_hash.Add(new TweetModel()
                        {
                            id    = i,
                            hash  = hashedAddress,
                            value = text
                        });
                        hashedAddress = SHA256.ComputeHash(hashedAddress, 0, hashedAddress.Length);
                        ishashValue   = true;
                    }
                    catch (Exception ex)
                    {
                        hashedAddress = SHA256.ComputeHash(hashedAddress, 0, hashedAddress.Length);
                    }
                }
                else
                {
                    break;
                }
                i++;
            }
            return(t_hash);
        }
Ejemplo n.º 25
0
        public void TestAccountCreation()
        {
            String            seed    = "health lazy lens fix dwarf salad breeze myself silly december endless rent faculty report beyond";
            PrivateKeyAccount account = PrivateKeyAccount.CreateFromSeed(seed, AddressEncoding.TestNet);

            byte[]            seed2    = Encoding.UTF8.GetBytes(seed);
            PrivateKeyAccount account2 = PrivateKeyAccount.CreateFromSeed(seed2, AddressEncoding.TestNet);

            CollectionAssert.AreEqual(Base58.Decode("CMLwxbMZJMztyTJ6Zkos66cgU7DybfFJfyJtTVpme54t"), account.PrivateKey);
            CollectionAssert.AreEqual(Base58.Decode("8LbAU5BSrGkpk5wbjLMNjrbc9VzN9KBBYv9X8wGpmAJT"), account.PublicKey);
            Assert.AreEqual("3MzZCGFyuxgC4ZmtKRS7vpJTs75ZXdkbp1K", account.Address);

            CollectionAssert.AreEqual(Base58.Decode("CMLwxbMZJMztyTJ6Zkos66cgU7DybfFJfyJtTVpme54t"), account2.PrivateKey);
            CollectionAssert.AreEqual(Base58.Decode("8LbAU5BSrGkpk5wbjLMNjrbc9VzN9KBBYv9X8wGpmAJT"), account2.PublicKey);
            Assert.AreEqual("3MzZCGFyuxgC4ZmtKRS7vpJTs75ZXdkbp1K", account2.Address);
        }
Ejemplo n.º 26
0
        public override ThirdpartyUserToken GetUserToken(HttpContext ctx)
        {
            string          cipher_openid = ctx.Request.Query["openid"];
            string          cipher_token  = ctx.Request.Query["token"];
            DesEncodeDecode des           = new DesEncodeDecode(this.Config.Secret);

            byte[] bytes_openid    = des.DesEncrypt(Base58.Decode(cipher_openid));
            byte[] bytes_token     = des.DesEncrypt(Base58.Decode(cipher_token));
            ThirdpartyUserToken ut = new ThirdpartyUserToken
            {
                AccessToken = Encoding.UTF8.GetString(bytes_token),
                OpenID      = Encoding.UTF8.GetString(bytes_openid)
            };

            return(ut);
        }
Ejemplo n.º 27
0
        public static void ParseWIF()
        {
            Console.WriteLine("Input WIF:");
            string wif = Console.ReadLine();

            var wifBytes = Base58.Decode(wif);
            var wifHex   = wifBytes.BytesToHex();

            Console.WriteLine("wif hex(len={0}):\n{1}", wifHex.Length / 2, wifHex);

            var head       = wifHex.Substring(0, 2);
            var privateKey = wifHex.Substring(2, wifHex.Length - 12);
            var tail       = wifHex.Substring(wifHex.Length - 10, 2);
            var wifHash    = wifHex.Substring(wifHex.Length - 8, 8);

            Console.WriteLine("Split wif hex:");
            Console.WriteLine("{0} {1} {2} {3}", head, privateKey, tail, wifHash);

            Console.WriteLine("private key(len={0}):\n{1}", privateKey.Length / 2, privateKey);

            var currWifHashBytes    = sha256.ComputeHash(sha256.ComputeHash((head + privateKey + tail).HexToBytes()));
            var currentWifhashShort = currWifHashBytes.BytesToHex().Substring(0, 8);

            Console.WriteLine("Hash of leading 34 bytes:{0}, expected:{1}", currentWifhashShort, wifHash);

            var publicKey = GetPublicKeyFromPrivatekey(privateKey);

            Console.WriteLine("public key hex:\n{0}", publicKey);

            var addrScript = "21" + publicKey + "ac";

            Console.WriteLine("addrscript:\n{0}", addrScript);

            var scriptHash = GetScriptHash(addrScript);

            Console.WriteLine("scripthash:\n{0}", scriptHash);

            var scriptHashHashBytes = sha256.ComputeHash(sha256.ComputeHash(("17" + scriptHash).HexToBytes()));
            var scriptHashHash      = scriptHashHashBytes.BytesToHex();
            var scriptHashDecode    = "17" + scriptHash + scriptHashHash.Substring(0, 8);

            Console.WriteLine("scriptHashDecode:\n{0}", scriptHashDecode);

            var addr = Base58.Encode(scriptHashDecode.HexToBytes());

            Console.WriteLine("addr:\n{0}", addr);
        }
Ejemplo n.º 28
0
 public static UInt160 ToScriptHash(string address)
 {
     byte[] data = Base58.Decode(address);
     if (data.Length != 25)
     {
         throw new FormatException();
     }
     if (data[0] != CoinVersion)
     {
         throw new FormatException();
     }
     if (!data.Take(21).Sha256().Sha256().Take(4).SequenceEqual(data.Skip(21)))
     {
         throw new FormatException();
     }
     return(new UInt160(data.Skip(1).Take(20).ToArray()));
 }
Ejemplo n.º 29
0
        public static byte[] GetPublicKeyHashFromAddress_WithoutCheck(string address)
        {
            var alldata = Base58.Decode(address);

            if (alldata.Length != 25)
            {
                throw new Exception("error length.");
            }
            if (alldata[0] != 0x17)
            {
                throw new Exception("not a address");
            }
            var data   = alldata.Take(alldata.Length - 4).ToArray();
            var pkhash = data.Skip(1).ToArray();

            return(pkhash);
        }
Ejemplo n.º 30
0
 public Account(NetworkType network, string base58PublicKey, string base58Address)
 {
     this.network = network;
     if (base58PublicKey != null)
     {
         publicKey = Base58.Decode(base58PublicKey);
         address   = PublicKeyToAddress(publicKey, network);
     }
     else
     {
         address = Base58.Decode(base58Address);
         if (!CheckAddress())
         {
             throw new VException("invalid address");
         }
     }
 }