Esempio n. 1
0
        private void AddInputs(Transaction transaction, ExtPubKey pubKey, List <Coin> coins, int addressNumber, ref int index, Money money)
        {
            Base58CheckEncoder base58CheckEncoder = new Base58CheckEncoder();
            var    bytes = base58CheckEncoder.DecodeData(pubKey.GetWif(Network.Main).ToString());
            string hex   = BitConverter.ToString(bytes).Replace("-", "").ToLower();

            Money spentMoney = Money.Zero;

            for (int i = 0; i < coins.Count; i++)
            {
                transaction.AddInput(new TxIn(coins[i].Outpoint));
                var s = "01ff4c53ff" + hex + "0000"
                        + (addressNumber > 9 ? addressNumber.ToString() : "0" + addressNumber) + "00";
                transaction.Inputs[i + index].ScriptSig = new Script(s);

                spentMoney += coins[i].Amount;

                if (spentMoney >= money)
                {
                    if (spentMoney - money > 0)
                    {
                        transaction.AddOutput(spentMoney - money, pubKey.Derive(0).Derive((uint)addressNumber).PubKey.Hash);
                    }

                    index = i + 1;
                    return;
                }
            }

            index = coins.Count;
        }
Esempio n. 2
0
 static Encoders()
 {
     ASCII       = new ASCIIEncoder();
     Hex         = new HexEncoder();
     Base58      = new Base58Encoder();
     Base58Check = new Base58CheckEncoder();
     Base64      = new Base64Encoder();
 }
Esempio n. 3
0
 static Encoders()
 {
     Base64 = new Base64Encoder();
     Base58Check = new Base58CheckEncoder();
     Base58 = new Base58Encoder();
     Hex = new HexEncoder();
     ASCII = new ASCIIEncoder();
 }
Esempio n. 4
0
        private Key PrivateKeyParse(string privateKey)
        {
            byte[] privKeyPrefix   = new byte[] { (128) };
            byte[] prefixedPrivKey = Helper.Concat(privKeyPrefix, Encoders.Hex.DecodeData(privateKey));

            byte[] privKeySuffix   = new byte[] { (1) };
            byte[] suffixedPrivKey = Helper.Concat(prefixedPrivKey, privKeySuffix);

            Base58CheckEncoder base58Check    = new Base58CheckEncoder();
            string             privKeyEncoded = base58Check.EncodeData(suffixedPrivKey);

            return(Key.Parse(privKeyEncoded, Network.Main));
        }
Esempio n. 5
0
        public void CreateFromHash()
        {
            using (var sha = new SHA256Managed())
            {
                byte[] privateKey      = sha.ComputeHash(Encoding.UTF8.GetBytes("some_random_text"));
                byte[] prefixedPrivKey = Helper.Concat(new byte[] { (128) }, privateKey);

                Base58CheckEncoder base58Check    = new Base58CheckEncoder();
                string             privKeyEncoded = base58Check.EncodeData(prefixedPrivKey);
                Console.WriteLine($"Private key (Base58): {privKeyEncoded}");

                Key privKey = Key.Parse(privKeyEncoded, Network.Main);
            }
        }
Esempio n. 6
0
        public void GetDecimalPrivFromWif()
        {
            Base58CheckEncoder base58Check = new Base58CheckEncoder();

            byte[] privKeyPrefixed = base58Check.DecodeData("5KV7hnn73NJCumzmviZ6UpjC68dw86r3WSG4DvuaTgw4968rZuo");
            Assert.AreEqual(128, privKeyPrefixed[0]); // 0x80

            // Dropping first byte
            byte[] privateKey = privKeyPrefixed.Skip(1).ToArray();

            // Encode to hex to print
            string privHex = Encoders.Hex.EncodeData(privateKey);

            Assert.AreEqual("dbdd1a034b5ac2f2cfa1ef09daf032dee9015586427d4cbd6f810a32ea45173a", privHex);
        }
Esempio n. 7
0
        private void SetData(byte[] vchData)
        {
            this.vchData    = vchData;
            this.vchVersion = _Network.GetVersionBytes(Type);
            if (_Network.useGroestlHash == false)
            {
                wifData = Encoders.Base58Check.EncodeData(vchVersion.Concat(vchData).ToArray());
            }
            else
            {
                //Using Groestl hashing
                wifData = Base58CheckEncoder.EncodeGroestlData(vchVersion.Concat(vchData).ToArray());
            }

            if (!IsValid)
            {
                throw new FormatException("Invalid " + this.GetType().Name);
            }
        }
Esempio n. 8
0
        private static CoinKeyPair _P2PkhGenerator()
        {
regenerate:
            var priv = _NewPrivKey();
            var privKey = priv.Item1;
            var wif     = priv.Item2;
            var pub     = _PrivToPubKey(privKey);

            var pkHash          = new Ripemd160Managed().ComputeHash(new SHA256Managed().ComputeHash(pub));
            var pkHashVersioned = new byte[20 + 1];

            pkHashVersioned[0] = 0x00;
            Array.Copy(pkHash, 0, pkHashVersioned, 1, 20);
            var addr = new Base58CheckEncoder().Encode(pkHashVersioned);

            // Some addresses ends up to be 26 chars while most are 27 chars long.
            // For stability reason, 26 chars long addresses are filtered out and the program would redo the generation.
            if (addr.Length != 27)
            {
                goto regenerate;
            }
            return(new CoinKeyPair(wif, addr));
        }
Esempio n. 9
0
        private static byte[] DecodeBase58Check(string base58encoded)
        {
            Base58CheckEncoder cj = new Base58CheckEncoder();

            return(cj.DecodeData(base58encoded));
        }
Esempio n. 10
0
        public string CreateOutTransactionElectrum(string redeemScript, string xpubkey1, string xpubkey2, decimal amount1, decimal amount2)
        {
            if (amount1 <= 0m && amount2 <= 0m)
            {
                throw new ArgumentException("Amount is less or equal zero");
            }

            Script scriptPubKey;

            try
            {
                scriptPubKey = new Script(redeemScript);
            }
            catch (Exception e)
            {
                throw new ArgumentException("Redeem script is incorrect");
            }

            ExtPubKey xpubKey1;
            ExtPubKey xpubKey2;

            try
            {
                xpubKey1 = ExtPubKey.Parse(xpubkey1, Network.Main);
                xpubKey2 = ExtPubKey.Parse(xpubkey2, Network.Main);
            }
            catch (Exception e)
            {
                throw new ArgumentException("Extended public key is incorrect");
            }

            decimal estimateFeeSize = 400m;
            var     fee             = this.Fee(estimateFeeSize);

            if (fee == null)
            {
                throw new Exception("Cannot get fee");
            }

            var pubKeys = scriptPubKey.GetDestinationPublicKeys();

            var index1 = this.FindPubKey(xpubKey1, pubKeys[0]);
            var index2 = this.FindPubKey(xpubKey2, pubKeys[1]);

            var unspentCoins = GetUnspentCoins(scriptPubKey);

            var t = new Transaction();

            t.AddOutput(Money.Coins(amount1) - fee / 2, pubKeys[0].Hash);
            t.AddOutput(Money.Coins(amount2) - fee / 2, pubKeys[1].Hash);

            Base58CheckEncoder base58CheckEncoder = new Base58CheckEncoder();
            var    bytes1 = base58CheckEncoder.DecodeData(xpubKey1.GetWif(Network.Main).ToString());
            string hex1   = BitConverter.ToString(bytes1).Replace("-", "").ToLower();

            var    bytes2 = base58CheckEncoder.DecodeData(xpubKey2.GetWif(Network.Main).ToString());
            string hex2   = BitConverter.ToString(bytes2).Replace("-", "").ToLower();

            // special script sig in electrum have to contain these magic vars
            var s = "0001ff01ff4cad524c53ff" + hex1 + "0000"
                    + (index1 > 9 ? index1.ToString() : "0" + index1) + "00" + "4c53ff" + hex2 + "0000"
                    + (index2 > 9 ? index2.ToString() : "0" + index2) + "00" + "52ae";

            int   i          = 0;
            Money spendMoney = Money.Zero;

            foreach (var coin in unspentCoins)
            {
                t.AddInput(new TxIn(coin.Key.Outpoint));
                t.Inputs[i].ScriptSig = new Script(s);
                i++;

                spendMoney += coin.Key.Amount;
                if (spendMoney >= Money.Coins(amount1) + Money.Coins(amount2))
                {
                    if (spendMoney > Money.Coins(amount1) + Money.Coins(amount2))
                    {
                        t.AddOutput(spendMoney - (Money.Coins(amount1) + Money.Coins(amount2)), scriptPubKey.Hash);
                    }

                    spendMoney = null;
                    break;
                }
            }

            if (spendMoney == null)
            {
                return(t.ToHex().Replace("b64cb40001ff01ff4cad524c53ff", "b40001ff01ff4cad524c53ff"));
            }

            return(null);
        }
Esempio n. 11
0
        public void CreateManually()
        {
            Console.WriteLine();
            // Priv key length
            int KEY_SIZE = 32;

            // Max priv key value
            // 115792089237316195423570985008687907852837564279074904382605163141518161494337
            uint256 N = uint256.Parse("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");

            // Randomizer
            Random rand = new Random();

            byte[] privateKey = new byte[KEY_SIZE];

            // Generate a valid random value
            uint256 candidateKey;

            do
            {
                rand.NextBytes(privateKey);
                candidateKey = new uint256(privateKey, false);
            } while (!(candidateKey > 0 && candidateKey < N));
            Console.WriteLine($"Private key (hex)       : { Encoders.Hex.EncodeData(privateKey) }");

            // Base58
            byte[] privKeyPrefix   = new byte[] { (128) }; // Base58 prefix for private key, 0x80 in hex
            byte[] prefixedPrivKey = Helper.Concat(privKeyPrefix, privateKey);

            Base58CheckEncoder base58Check = new Base58CheckEncoder();

            string privKeyEncoded = string.Empty;

            {
                privKeyEncoded = base58Check.EncodeData(prefixedPrivKey);
            }
            // or
            {
                var hash1    = NBitcoin.Crypto.Hashes.SHA256(prefixedPrivKey);
                var hash2    = NBitcoin.Crypto.Hashes.SHA256(hash1);
                var checksum = hash2.Take(4).ToArray();
                var prefixedPrivKeyChecksum = Helper.Concat(prefixedPrivKey, checksum);

                Base58Encoder base58 = new Base58Encoder();
                privKeyEncoded = base58.EncodeData(prefixedPrivKeyChecksum);
            }

            Assert.DoesNotThrow(() => {
                Key.Parse(privKeyEncoded, Network.Main);
            });
            Console.WriteLine($"Private key (Base58)    : {privKeyEncoded}");

            // Compressed private key
            byte[] privKeySuffix            = new byte[] { (1) }; // Suffix for compressed private key, 0x01 in hex
            byte[] suffixedPrivKey          = Helper.Concat(prefixedPrivKey, privKeySuffix);
            string compressedPrivKeyEncoded = base58Check.EncodeData(suffixedPrivKey);

            Assert.DoesNotThrow(() => {
                Key.Parse(compressedPrivKeyEncoded, Network.Main);
            });
            Console.WriteLine($"Private key (Comp.)     : {compressedPrivKeyEncoded}");

            // P2PK private key
            byte[] p2pkhPrivKeySuffix            = new byte[] { (16) }; // 0x10 in hex
            byte[] suffixedP2pkhPrivKey          = Helper.Concat(prefixedPrivKey, p2pkhPrivKeySuffix);
            string compressedP2pkhPrivKeyEncoded = base58Check.EncodeData(suffixedP2pkhPrivKey);

            Console.WriteLine($"Private key (P2PKH)     : {compressedP2pkhPrivKeyEncoded}");
        }
 public ByteBase58CheckConverter() : base()
 {
     _base58CheckEncoder = new Base58CheckEncoder();
     _network            = Network.Main;
 }