Esempio n. 1
0
        internal WalletContainer(DBConnection conn, HDWallet wallet, ProcessBlocksInfo processBlocksInfo = null) : base(conn, processBlocksInfo, wallet)
        {
            this.LockUpdateWallet = new DBLock();
            this.ReaderCount      = 0;

            this.Conn = conn;
        }
Esempio n. 2
0
        /// <summary>
        /// To harness the advantages of segwit, while being compatible with old software, P2W over P2SH is allowed. For old node, it will look like a normal P2SH payment.
        /// </summary>
        public void P2W_Over_P2SH(string seed0, string seed1, string seed2, string seed3)
        {
            //http://n.bitcoin.ninja/checkscript   <----- really useful

            //You can transform any P2W* to a P2W*over P2SH by:
            //-Replacing the ScriptPubKey by its P2SH equivalent.
            //-The former ScriptPubKey will be placed as the only push in the scriptSig in the spending transaction,
            //-All other data will be pushed in the witness of the spending transaction.
            //-Don’t worry, if this sound complicated, the TransactionBuilder will allow you to abstract the plumbing effectively.
            //https://programmingblockchain.gitbooks.io/programmingblockchain/content/other_types_of_ownership/p2wsh_pay_to_witness_script_hash.html
            var key = new Key();

            Console.WriteLine(key.PubKey.ScriptPubKey.WitHash.ScriptPubKey);
            Console.WriteLine();

            HDWallet walletAlice   = new HDWallet(seed1); //signer 1
            HDWallet walletBob     = new HDWallet(seed0); //signer 2
            HDWallet walletSatoshi = new HDWallet(seed2); //does not sign
            HDWallet walletNico    = new HDWallet(seed3);
            uint     path          = 0;

            Key bob     = walletBob.GetPrivateKey(path).PrivateKey;
            Key alice   = walletAlice.GetPrivateKey(path).PrivateKey;
            Key satoshi = walletSatoshi.GetPrivateKey(path).PrivateKey;

            Script scriptPubKey = PayToMultiSigTemplate.Instance
                                  .GenerateScriptPubKey(2, new[] { bob.PubKey, alice.PubKey, satoshi.PubKey });

            Console.WriteLine("Script " + scriptPubKey);
            Console.WriteLine("With P2SH Payment: " + scriptPubKey.PaymentScript);
            Console.WriteLine(scriptPubKey.PaymentScript.Hash.GetAddress(Network.Main));
        }
Esempio n. 3
0
        public void GeneratePubkeyTest()
        {
            string[] mnemonicEn = { "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "about" };
            HDWallet hdWallet   = new HDWallet(mnemonicEn, "TREZOR");

            ExtPubkey pubkey = hdWallet.GeneratePubkey(CfdNetworkType.Mainnet);

            Assert.Equal("xpub661MyMwAqRbcGB88KaFbLGiYAat55APKhtWg4uYMkXAmfuSTbq2QYsn9sKJCj1YqZPafsboef4h4YbXXhNhPwMbkHTpkf3zLhx7HvFw1NDy",
                         pubkey.ToString());

            pubkey = hdWallet.GeneratePubkey(CfdNetworkType.Testnet);
            Assert.Equal("tpubD6NzVbkrYhZ4XyJymmEgYC3uVhyj4YtPFX6yRTbW6RvfRC7Ag3sVhKSz7MNzFWW5MJ7aVBKXCAX7En296EYdpo43M4a4LaeaHuhhgHToSJF",
                         pubkey.ToString());

            ExtPubkey child = hdWallet.GeneratePubkey(CfdNetworkType.Mainnet, "0/44");

            Assert.Equal("xpub6AhtoXYBDLLhLk2eqd5jg72MJw53Vet7EYYt3B5MyxU4hMvfhnm9Tf83kwN1aV5j6g9smszDdCg8dt4uguGHivB75PvNxPkdmecoAqqn7Hm",
                         child.ToString());

            ExtPubkey child11 = hdWallet.GeneratePubkey(CfdNetworkType.Mainnet, 0);
            ExtPubkey child12 = child11.DerivePubkey(44);

            Assert.Equal(child.ToString(), child12.ToString());

            ExtPubkey child2 = hdWallet.GeneratePubkey(CfdNetworkType.Mainnet, new uint[] { 0, 44 });

            Assert.Equal(child.ToString(), child2.ToString());

            child = hdWallet.GeneratePubkey(CfdNetworkType.Mainnet, "0'/44'");
            Assert.Equal("xpub6Bc3MkV9ZCh8ipiRMK4pbhBs3JwuFcG4vp4CvJmVQKDVcpsQzizhL2DErc5DHMQuKwBxTg1jLP6PCqriLmLsJzjB2kD9TE9hvqxQ4yLKtcV",
                         child.ToString());

            child2 = hdWallet.GeneratePubkey(CfdNetworkType.Mainnet, new[] { 0x80000000, 44 + 0x80000000 });
            Assert.Equal(child.ToString(), child2.ToString());
        }
Esempio n. 4
0
        public void MultiSig(string seed0, string seed1, string seed2, string seed3)
        {
            //https://programmingblockchain.gitbooks.io/programmingblockchain/content/other_types_of_ownership/multi_sig.html
            HDWallet       walletAlice   = new HDWallet(seed1); //signer 1
            HDWallet       walletBob     = new HDWallet(seed0); //signer 2
            HDWallet       walletSatoshi = new HDWallet(seed2); //does not sign
            HDWallet       walletNico    = new HDWallet(seed3);
            uint           path          = 0;
            ExtPubKey      keyBob        = walletBob.GetPublicKey(path);
            ExtPubKey      keyAlice      = walletAlice.GetPublicKey(path);
            ExtPubKey      keySatoshi    = walletAlice.GetPublicKey(path);
            BitcoinAddress addressNico   = walletNico.GetBitcoinAddress(path); //recipient of transaction

            Console.WriteLine("Generate a script to receive coins, it will require 2 of 3 signatures to spend.");
            var scriptPubKey = PayToMultiSigTemplate.Instance.GenerateScriptPubKey(2, new[] { keyBob.PubKey, keyAlice.PubKey, keySatoshi.PubKey });

            Console.WriteLine(scriptPubKey);

            Console.WriteLine("Received coins in a transaction");
            var received = new Transaction();

            received.Outputs.Add(new TxOut(Money.Coins(1.0m), scriptPubKey));
            Coin coin = received.Outputs.AsCoins().First();
            //Nico's wallet.

            //use the transaction builder to build an unsigned transaction to Nico.
            TransactionBuilder builder  = new TransactionBuilder();
            Transaction        unsigned = builder.AddCoins(coin).Send(addressNico, Money.Coins(1.0m)).BuildTransaction(sign: false);

            Helpers.ChangeColor();
            Console.WriteLine(unsigned);
            Helpers.ResetColor();
            Console.WriteLine("Alice signs transaction:");
            //Key alice = walletAlice.GetPrivateKey().PrivateKey;
            Transaction aliceSigned = builder.AddCoins(coin).AddKeys(walletAlice.GetPrivateKey(path)).SignTransaction(unsigned);

            Helpers.ChangeColor();
            Console.WriteLine(aliceSigned);
            Console.WriteLine("Script sig, one 0 should be replaced with a hash sig");
            Helpers.ResetColor();
            Console.WriteLine("Bob signs transaction:");
            //At this line, SignTransaction(unSigned) has the identical functionality with the SignTransaction(aliceSigned).
            //It's because unsigned transaction has already been signed by Alice privateKey from above.
            Transaction bobSigned = builder.AddCoins(coin).AddKeys(walletBob.GetPrivateKey(path)).SignTransaction(aliceSigned);

            Helpers.ChangeColor();
            Console.WriteLine(bobSigned);
            Helpers.ResetColor();

            Console.WriteLine("Combine Signatures");
            Transaction fullySigned = builder.AddCoins(coin).CombineSignatures(aliceSigned, bobSigned);

            Helpers.ChangeColor();
            Console.WriteLine(fullySigned.ToString());
            Helpers.ResetColor();
        }
Esempio n. 5
0
        public void SegwitAddressTest(string seed)
        {
            HDWallet walletAlice = new HDWallet(seed);
            uint     path        = 0;
            Segwit   segwit      = new Segwit(NBitcoin.Network.Main);

            //var segwitAddress = segwit.GetSegwitAddress(walletAlice.GetPrivateKey(path));

            //Console.WriteLine("Segwit Address:\t" + segwitAddress.ToString());
        }
Esempio n. 6
0
        /// <summary>
        /// NEW!!  So far alright?
        /// </summary>
        public void SegwitTestNet()
        {
            //The faucet: https://testnet.manu.backend.hamburg/faucet
            //https://bitcoin.stackexchange.com/questions/59231/how-to-sign-a-segwit-transaction-via-nbitcoin
            var           net      = NBitcoin.Network.TestNet;
            BlockExplorer explorer = new BlockExplorer("https://testnet.blockexplorer.com/");
            HDWallet      wallet   = new HDWallet("seed12345678ryan12345678", net);
            uint          path     = 0;
            var           extkey   = wallet.GetPrivateKey(path);
            Key           k        = extkey.PrivateKey;

            //This gives you a Bech32 address (currently not really interoperable in wallets, so you need to convert it into P2SH)
            var address = k.PubKey.WitHash.GetAddress(net);

            var p2sh = address.GetScriptAddress();
            //p2sh is now an interoperable P2SH segwit address

            //SENT TO: 2NGSoYM3yLi9SXvZc5yYcSwHWyCWzgBrP9X
            //TXID 1397a4cc480879eae604ce871c47a4d690c6ea6a6dcfd7e38d95f31b81593556

            var response = explorer.GetUnspent(p2sh.ToString());
            List <ExplorerUnspent> unspent      = response.Convert <List <ExplorerUnspent> >();
            List <Transaction>     transactions = new List <Transaction>();

            foreach (var item in unspent)
            {
                string           txcontent  = "{\"txid\":\"6636b3fedb57be81232f92f80fa8d3df9a0f07305af2c7f705a7f353e516b1d7\",\"version\":1,\"locktime\":0,\"vin\":[{\"txid\":\"50b7d9a5fa1281e7020fa8a152835756e0d57d6b4d634b4251ab500e8630bc3e\",\"vout\":1,\"scriptSig\":{\"asm\":\"0014a16f4ba22e84c364ec4f8fe19d8a48762156b41e\",\"hex\":\"160014a16f4ba22e84c364ec4f8fe19d8a48762156b41e\"},\"sequence\":4294967295,\"n\":0,\"addr\":\"2N9viNVJ5MsAM8MXdUuATDwKeMjMLQkaXyR\",\"valueSat\":193987962850,\"value\":1939.8796285,\"doubleSpentTxID\":null}],\"vout\":[{\"value\":\"2.00000000\",\"n\":0,\"scriptPubKey\":{\"hex\":\"a9142f672b3ea4af55d9da43e507e3c060d2e34521ba87\",\"asm\":\"OP_HASH160 2f672b3ea4af55d9da43e507e3c060d2e34521ba OP_EQUAL\",\"addresses\":[\"2MwZsLbuB328gxHRfr1VDrfDrK6aWicQcAW\"],\"type\":\"scripthash\"},\"spentTxId\":null,\"spentIndex\":null,\"spentHeight\":null},{\"value\":\"1937.87862850\",\"n\":1,\"scriptPubKey\":{\"hex\":\"a914859695c2cb37ee30bf6a18943c8c27a3ac0e6faa87\",\"asm\":\"OP_HASH160 859695c2cb37ee30bf6a18943c8c27a3ac0e6faa OP_EQUAL\",\"addresses\":[\"2N5RaFdK3rgsNayXnkTQaSLKVBB3brW7G4m\"],\"type\":\"scripthash\"},\"spentTxId\":\"892e6facc4fc596852d41af367dd41f7a7ec1b11a319a202bc0d4c5b8f792f2f\",\"spentIndex\":0,\"spentHeight\":1255964}],\"blockhash\":\"000000000007dbc3ffd03559f2192b299bc0c20aa0aea8e1939f2731e01103e8\",\"blockheight\":1255946,\"confirmations\":123,\"time\":1514228293,\"blocktime\":1514228293,\"valueOut\":1939.8786285,\"size\":138,\"valueIn\":1939.8796285,\"fees\":0.001}";
                ExplorerResponse txResponse = explorer.GetTransaction(item.txid);
                RawFormat        format     = RawFormat.Satoshi;
                var tx = Transaction.Parse(txResponse.data, format, net);
                transactions.Add(tx);
            }
            //For spending, it works the same as a a normal P2SH
            //You need to get the ScriptCoin, the RedeemScript of you script coin should be k.PubKey.WitHash.ScriptPubKey.            var redeemScript = k.PubKey.WitHash.ScriptPubKey;
            var         redeemScript = k.PubKey.WitHash.ScriptPubKey;
            Transaction received     = transactions[0];
            ScriptCoin  coin         = received.Outputs.AsCoins().First().ToScriptCoin(redeemScript);
            //1397a4cc480879eae604ce871c47a4d690c6ea6a6dcfd7e38d95f31b81593556

            BitcoinAddress     destination = BitcoinAddress.Create("2N8hwP1WmJrFF5QWABn38y63uYLhnJYJYTF"); //the faucet return address
            TransactionBuilder builder     = new TransactionBuilder();

            builder.AddCoins(coin);
            builder.AddKeys(k);
            builder.Send(destination, Money.Coins(1.99m));
            builder.SendFees(Money.Coins(0.001m));
            builder.SetChange(p2sh);
            var signedTx = builder.BuildTransaction(true);

            Console.WriteLine(signedTx.ToHex());
            string x = ";;";
            //Assert.True(builder.Verify(signedTx));
        }
Esempio n. 7
0
        public void ConvertMnemonicToEntropyTest()
        {
            string   mnemonicEn = "horn tenant knee talent sponsor spell gate clip pulse soap slush warm silver nephew swap uncle crack brave";
            ByteData entropy    = HDWallet.ConvertMnemonicToEntropy(mnemonicEn, "en");

            Assert.Equal("6d9be1ee6ebd27a258115aad99b7317b9c8d28b6d76431c3", entropy.ToHexString());

            string[] mnemonicWords = HDWallet.ConvertEntropyToMnemonic(entropy, "en");
            string   mnemonic      = string.Join(' ', mnemonicWords);

            Assert.Equal(mnemonicEn, mnemonic);
        }
Esempio n. 8
0
        public void GetMnemonicWordlistTest()
        {
            string[] enWords = HDWallet.GetMnemonicWordlist();
            Assert.NotNull(enWords);
            Assert.Equal(2048, enWords.Length);
            Assert.Equal("ability", enWords[1]);

            string[] jpWords = HDWallet.GetMnemonicWordlist("jp");
            Assert.NotNull(jpWords);
            Assert.Equal(2048, jpWords.Length);
            Assert.Equal("あいさつ", jpWords[1]);
        }
Esempio n. 9
0
        public void P2WPKH()
        {
            //https://programmingblockchain.gitbooks.io/programmingblockchain/content/other_types_of_ownership/p2wpkh_pay_to_witness_public_key_hash.html
            HDWallet hdWallet   = new HDWallet(_seed);
            uint     path       = 0;
            var      privateKey = hdWallet.GetPrivateKey();
            var      pubKey     = hdWallet.GetPublicKey(path);

            Console.WriteLine("In NBitcoin, spending a P2WPKH output is no different from spending a normal P2PKH. To get the ScriptPubKey from a public key simply use PubKey.WitHash instead of PubKey.Hash");
            var publicKeyWitnessHash = pubKey.PubKey.WitHash;

            Console.WriteLine(publicKeyWitnessHash.GetAddress(NBitcoin.Network.Main));
            //var address = hdWallet.GetBitcoinAddress(path);
            //Console.WriteLine(address.ToString());
        }
Esempio n. 10
0
        public void ConvertMnemonicToSeedTest()
        {
            string   mnemonicEn = "horn tenant knee talent sponsor spell gate clip pulse soap slush warm silver nephew swap uncle crack brave";
            HDWallet enWallet   = HDWallet.ConvertMnemonicToSeed(mnemonicEn, "TREZOR", "en");

            Assert.Equal("fd579828af3da1d32544ce4db5c73d53fc8acc4ddb1e3b251a31179cdb71e853c56d2fcb11aed39898ce6c34b10b5382772db8796e52837b54468aeb312cfc3d",
                         enWallet.GetSeed().ToHexString());

            // https://iancoleman.io/bip39/#japanese
            string   mnemonicJp = "まぜる むかし じぶん そえん くつした このよ とおる えもじ おじさん ねむたい しいん せすじ のれん ゆうめい ときおり";
            HDWallet jpWallet   = HDWallet.ConvertMnemonicToSeed(mnemonicJp, "", "jp");

            Assert.Equal("4d2cd52f3ad39dc913d5a90e91163d7af4c9f11d727b273be269a404d2a23546243f8adb5009200d037900c76a3a8fc69c13afaa8084c4c85d3515232785fd54",
                         jpWallet.GetSeed().ToHexString());
        }
        internal ProcessBlocksInfo(DBConnection conn, ProcessBlocksInfo processBlocksInfo, HDWallet wallet = null)
        {
            this.NewTip               = null;
            this.PrevTip              = null;
            this.MustCommit           = false;
            this.Conn                 = conn;
            this.Wallet               = wallet;
            this.LockProcessBlocks    = processBlocksInfo?.LockProcessBlocks ?? new DBLock();
            this.Outputs              = TempTable.Create <TempOutput>();
            this.PrevOuts             = TempTable.Create <TempPrevOut>();
            this.ParticipatingWallets = new List <string>();

            this.AddressesOfInterest    = processBlocksInfo?.AddressesOfInterest ?? new WalletAddressLookup(conn, wallet?.WalletId);
            this.TransactionsOfInterest = processBlocksInfo?.TransactionsOfInterest ?? new WalletTransactionLookup(conn, wallet?.WalletId);
        }
Esempio n. 12
0
        public void HDWalletTest(string seed0, string seed1, string seed2, string seed3)
        {
            //https://programmingblockchain.gitbooks.io/programmingblockchain/content/other_types_of_ownership/p2sh_pay_to_script_hash.html
            HDWallet walletAlice   = new HDWallet(seed1); //signer 1
            HDWallet walletBob     = new HDWallet(seed0); //signer 2
            HDWallet walletSatoshi = new HDWallet(seed2); //does not sign
            HDWallet walletNico    = new HDWallet(seed3);
            uint     path          = 0;

            ExtKey    bobPrivKey = walletBob.GetPrivateKey(path);
            ExtPubKey keyBob     = walletBob.GetPublicKey(path);

            Console.WriteLine("Gen Pub Address:\t" + keyBob.PubKey.GetAddress(Network.Main));
            Console.WriteLine("Gen Prv Address:\t" + bobPrivKey.PrivateKey.PubKey.GetAddress(Network.Main));
            Console.WriteLine("Gen Add Address:\t" + walletBob.GetBitcoinAddress(path));
            //ExtPubKey keyAlice = walletAlice.GetPublicKey(path);
            //ExtPubKey keySatoshi = walletAlice.GetPublicKey(path);
            Console.WriteLine();
        }
Esempio n. 13
0
        /// <summary>
        /// Important: P2PK
        /// </summary>
        public void P2PK_H()
        {
            //https://programmingblockchain.gitbooks.io/programmingblockchain/content/other_types_of_ownership/p2pk[h]_pay_to_public_key_[hash].html
            HDWallet hdWallet   = new HDWallet(_seed);
            uint     path       = 0;
            var      privateKey = hdWallet.GetPrivateKey();
            var      pubKey     = hdWallet.GetPublicKey(path);

            Console.WriteLine("We learned that a Bitcoin Address was the hash of a public key:");
            var publicKeyHash = pubKey.PubKey.Hash;

            Console.WriteLine(publicKeyHash.GetAddress(NBitcoin.Network.Main));
            var address = hdWallet.GetBitcoinAddress(path);

            Console.WriteLine(address.ToString());
            //var bitcoinAddress = publicKeyHash.GetAddress(Network.Main);
            //Console.WriteLine(publicKeyHash); // 41e0d7ab8af1ba5452b824116a31357dc931cf28
            //Console.WriteLine(bitcoinAddress); // 171LGoEKyVzgQstGwnTHVh3TFTgo5PsqiY

            Console.ReadLine();
        }
Esempio n. 14
0
        public void ConstructorTest()
        {
            ByteData entropy   = new ByteData("6d9be1ee6ebd27a258115aad99b7317b9c8d28b6d76431c3");
            HDWallet hdWallet1 = new HDWallet(entropy, "TREZOR", "en");

            Assert.Equal("fd579828af3da1d32544ce4db5c73d53fc8acc4ddb1e3b251a31179cdb71e853c56d2fcb11aed39898ce6c34b10b5382772db8796e52837b54468aeb312cfc3d",
                         hdWallet1.GetSeed().ToHexString());

            string   mnemonicEn = "horn tenant knee talent sponsor spell gate clip pulse soap slush warm silver nephew swap uncle crack brave";
            HDWallet hdWallet2  = new HDWallet(mnemonicEn, "TREZOR");

            Assert.Equal(hdWallet1.GetSeed().ToHexString(),
                         hdWallet2.GetSeed().ToHexString());
            Assert.True(hdWallet1.Equals(hdWallet2));

            string[] mnemonicWords = mnemonicEn.Split(' ');
            HDWallet hdWallet3     = new HDWallet(mnemonicWords, "TREZOR");

            Assert.Equal(hdWallet2.GetSeed().ToHexString(),
                         hdWallet3.GetSeed().ToHexString());
        }
Esempio n. 15
0
        public void GeneratePrivkeyTest()
        {
            string[] mnemonicEn = { "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "abandon", "about" };
            HDWallet hdWallet   = new HDWallet(mnemonicEn, "TREZOR");

            ExtPrivkey privkey = hdWallet.GeneratePrivkey(CfdNetworkType.Mainnet);

            Assert.Equal("xprv9s21ZrQH143K3h3fDYiay8mocZ3afhfULfb5GX8kCBdno77K4HiA15Tg23wpbeF1pLfs1c5SPmYHrEpTuuRhxMwvKDwqdKiGJS9XFKzUsAF",
                         privkey.ToString());

            privkey = hdWallet.GeneratePrivkey(CfdNetworkType.Testnet);
            Assert.Equal("tprv8ZgxMBicQKsPeWHBt7a68nPnvgTnuDhUgDWC8wZCgA8GahrQ3f3uWpq7wE7Uc1dLBnCe1hhCZ886K6ND37memRDWqsA9HgSKDXtwh2Qxo6J",
                         privkey.ToString());

            ExtPrivkey child = hdWallet.GeneratePrivkey(CfdNetworkType.Mainnet, "0/44");

            Assert.Equal("xprv9wiYQ21HNxnQ8FxBjbYjJy5ckuEZ6CAFsKdHEnfkRcw5pZbXAFSturoZugNE6ZpVSu6kdrYw752chFPAbPMXZ62ZLfYwLMHdzMVXqwnfRFn",
                         child.ToString());

            ExtPrivkey child11 = hdWallet.GeneratePrivkey(CfdNetworkType.Mainnet, 0);
            ExtPrivkey child12 = child11.DerivePrivkey(44);

            Assert.Equal(child.ToString(), child12.ToString());

            ExtPrivkey child2 = hdWallet.GeneratePrivkey(CfdNetworkType.Mainnet, new uint[] { 0, 44 });

            Assert.Equal(child.ToString(), child2.ToString());

            child = hdWallet.GeneratePrivkey(CfdNetworkType.Mainnet, "0'/44'");
            Assert.Equal("xprv9xcgxExFiq8qWLdxFHXpEZF8VH7Qr9YDZb8c7vMsqygWk2YGTBgSnDtm1LESskfAJqGMWkWWGagNCSbHdVgA8EFxSbfAQTKSD1z4iJ8qHtq",
                         child.ToString());

            child11 = hdWallet.GeneratePrivkey(CfdNetworkType.Mainnet, 0x80000000);
            child12 = child11.DerivePrivkey(44 + 0x80000000);
            Assert.Equal(child.ToString(), child12.ToString());

            child2 = hdWallet.GeneratePrivkey(CfdNetworkType.Mainnet, new[] { 0x80000000, 44 + 0x80000000 });
            Assert.Equal(child.ToString(), child2.ToString());
        }
Esempio n. 16
0
        public ExtKey GetKey(uint path, string seed)
        {
            var wallet = new HDWallet(seed);

            return(wallet.GetPrivateKey(path));
        }
Esempio n. 17
0
        public void P2WSH(string seed0, string seed1, string seed2, string seed3)
        {
https:      //programmingblockchain.gitbooks.io/programmingblockchain/content/other_types_of_ownership/p2wsh_pay_to_witness_script_hash.html
            var key = new Key();

            Console.WriteLine(key.PubKey.ScriptPubKey.WitHash.ScriptPubKey);
            Console.WriteLine();

            HDWallet walletAlice   = new HDWallet(seed1); //signer 1
            HDWallet walletBob     = new HDWallet(seed0); //signer 2
            HDWallet walletSatoshi = new HDWallet(seed2); //does not sign
            HDWallet walletNico    = new HDWallet(seed3);
            uint     path          = 0;

            Key bob     = walletBob.GetPrivateKey(path).PrivateKey;
            Key alice   = walletAlice.GetPrivateKey(path).PrivateKey;
            Key satoshi = walletSatoshi.GetPrivateKey(path).PrivateKey;

            Script scriptPubKey = PayToMultiSigTemplate.Instance
                                  .GenerateScriptPubKey(2, new[] { bob.PubKey, alice.PubKey, satoshi.PubKey });

            Console.WriteLine("Script " + scriptPubKey);
            Console.WriteLine("With P2SH Payment: " + scriptPubKey.PaymentScript);
            Console.WriteLine(scriptPubKey.PaymentScript.Hash.GetAddress(Network.Main));
            Console.WriteLine();
            //Set up a new transaction to use this address
            //var redeemAddress = scriptPubKey.PaymentScript.Hash.GetAddress(Network.Main);
            Script redeemScript = PayToMultiSigTemplate.Instance
                                  .GenerateScriptPubKey(2, new[] { bob.PubKey, alice.PubKey, satoshi.PubKey });

            Console.WriteLine(redeemScript.Hash); //redeemScript.Hash is NOT the bitcoin address
            Transaction received = new Transaction();

            //Pay to the script hash
            received.Outputs.Add(new TxOut(Money.Coins(1.0m), redeemScript.WitHash.ScriptPubKey));
            //Warning: Warning: The payment is sent to redeemScript.Hash and not to redeemScript!

            //to spend what they have, any owner will need to create script coin.
            ScriptCoin         coin     = received.Outputs.AsCoins().First().ToScriptCoin(redeemScript);
            TransactionBuilder builder  = new TransactionBuilder();
            Transaction        unsigned = builder.AddCoins(coin).Send(walletNico.GetBitcoinAddress(path), Money.Coins(1.0m)).BuildTransaction(sign: false);

            Helpers.ChangeColor();
            Console.WriteLine(unsigned);
            Helpers.ResetColor();
            Console.WriteLine("Alice signs transaction:");
            //Key alice = walletAlice.GetPrivateKey().PrivateKey;
            Transaction aliceSigned = builder.AddCoins(coin).AddKeys(alice).SignTransaction(unsigned);

            Helpers.ChangeColor();
            Console.WriteLine(aliceSigned);
            Console.WriteLine("Script sig, one 0 should be replaced with a hash sig");
            Helpers.ResetColor();
            Console.WriteLine("Bob signs transaction:");
            //At this line, SignTransaction(unSigned) has the identical functionality with the SignTransaction(aliceSigned).
            //It's because unsigned transaction has already been signed by Alice privateKey from above.
            Transaction bobSigned = builder.AddCoins(coin).AddKeys(bob).SignTransaction(aliceSigned);

            Helpers.ChangeColor();
            Console.WriteLine(bobSigned);
            Helpers.ResetColor();

            Console.WriteLine("Combine Signatures");
            Transaction fullySigned = builder.AddCoins(coin).CombineSignatures(aliceSigned, bobSigned);

            Helpers.ChangeColor();
            Console.WriteLine(fullySigned.ToString());
            Helpers.ResetColor();

            Console.WriteLine();
        }
Esempio n. 18
0
        public void LogMetrics(SQLiteWalletRepository repo, DBConnection conn, ChainedHeader header, HDWallet wallet)
        {
            // Write some metrics to file.
            if (repo.WriteMetricsToFile)
            {
                string fixedWidth(object val, int width)
                {
                    return(string.Format($"{{0,{width}}}", val));
                }

                var lines = new List <string>();

                lines.Add($"--- Date/Time: {(DateTime.Now.ToString())}, Block Height: { (header?.Height) } ---");

                var processCnt    = fixedWidth(this.ProcessCount, 5);
                var processTime   = fixedWidth(((double)this.ProcessTime / 10_000_000).ToString("N06"), 8);
                var processAvgSec = fixedWidth(((double)this.ProcessTime / this.ProcessCount / 10_000_000).ToString("N06"), 8);

                var scanCnt    = fixedWidth(this.BlockCount, 5);
                var scanTime   = fixedWidth(((double)this.BlockTime / 10_000_000).ToString("N06"), 8);
                var scanAvgSec = fixedWidth(((double)this.BlockTime / this.BlockCount / 10_000_000).ToString("N06"), 8);

                var readCnt    = fixedWidth(this.ReadCount, 5);
                var readTime   = fixedWidth(((double)this.ReadTime / 10_000_000).ToString("N06"), 8);
                var readAvgSec = fixedWidth(((double)this.ReadTime / this.ReadCount / 10_000_000).ToString("N06"), 8);

                var commitTime   = fixedWidth(((double)this.CommitTime / 10_000_000).ToString("N06"), 8);
                var commitAvgSec = fixedWidth(((double)this.CommitTime / this.ProcessCount / 10_000_000).ToString("N06"), 8);

                lines.Add($"{fixedWidth("Blocks Scanned", -20)  }: Time={scanTime   }, Count={scanCnt   }, AvgSec={scanAvgSec}");
                lines.Add($"{fixedWidth("-Blocks Read", -20)     }: Time={readTime   }, Count={readCnt   }, AvgSec={readAvgSec}");
                lines.Add($"{fixedWidth("Blocks Processed", -20)}: Time={processTime}, Count={processCnt}, AvgSec={processAvgSec}");

                foreach ((string cmdName, DBCommand cmd) in conn.Commands.Select(kv => (kv.Key, kv.Value)))
                {
                    var key    = fixedWidth($"-{cmdName}", -20);
                    var time   = fixedWidth(((double)cmd.ProcessTime / 10_000_000).ToString("N06"), 8);
                    var count  = fixedWidth(cmd.ProcessCount, 5);
                    var avgsec = (cmd.ProcessCount == 0) ? null : fixedWidth(((double)cmd.ProcessTime / cmd.ProcessCount / 10_000_000).ToString("N06"), 8);

                    lines.Add($"{key}: Time={time}, Count={count}, AvgSec={avgsec}");
                }

                lines.Add($"{fixedWidth("-Commit", -20)}: Time={commitTime}, Count={processCnt}, AvgSec={commitAvgSec}");

                lines.Add("");

                this.BlockCount   = 0;
                this.BlockTime    = 0;
                this.ProcessCount = 0;
                this.ProcessTime  = 0;
                this.ReadCount    = 0;
                this.ReadTime     = 0;
                this.CommitTime   = 0;

                foreach (var kv in conn.Commands)
                {
                    kv.Value.ProcessCount = 0;
                    kv.Value.ProcessTime  = 0;
                }

                if (wallet != null)
                {
                    File.AppendAllLines(System.IO.Path.Combine(this.Path, $"Metrics_{ wallet.Name }.txt"), lines);
                }
                else
                {
                    File.AppendAllLines(System.IO.Path.Combine(this.Path, "Metrics.txt"), lines);
                }
            }
        }