Example #1
0
        public void StakeSegwitBlock_UsingOnlySegwitUTXOs()
        {
            using (NodeBuilder builder = NodeBuilder.Create(this))
            {
                // Even though we are mining, we still want to use PoS consensus rules.
                Network  network = KnownNetworks.StraxRegTest;
                CoreNode node    = builder.CreateStratisPosNode(network).WithWallet().Start();

                var address = BitcoinWitPubKeyAddress.Create(node.FullNode.WalletManager().GetUnusedAddress().Bech32Address, network);

                // A P2WPKH scriptPubKey - so that funds get mined into the node's wallet as segwit UTXOs
                var script = address.ScriptPubKey;

                // Need the premine to be past coinbase maturity so that we can stake with it.
                var            miner = node.FullNode.NodeService <IPowMining>() as PowMining;
                int            minStakeConfirmations = ((PosConsensusOptions)network.Consensus.Options).GetStakeMinConfirmations(0, network);
                List <uint256> res = miner.GenerateBlocks(new ReserveScript(script), (ulong)minStakeConfirmations + 2, int.MaxValue);

                var cancellationToken = new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token;
                TestBase.WaitLoop(() => node.CreateRPCClient().GetBlockCount() >= (minStakeConfirmations + 2), cancellationToken: cancellationToken);
                TestBase.WaitLoop(() => node.FullNode.WalletManager().WalletTipHeight >= (minStakeConfirmations + 2), cancellationToken: cancellationToken);

                var scriptPubKeys = node.FullNode.WalletManager().GetAccounts(node.WalletName).SelectMany(a => a.GetCombinedAddresses()).SelectMany(b => b.Transactions).Select(c => c.ScriptPubKey);

                // The wallet must have correctly determined that the block rewards have been mined into addresses it is aware of.
                Assert.NotEmpty(scriptPubKeys);

                // Check that every UTXO in the wallet has a Segwit scriptPubKey.
                foreach (Script scriptPubKey in scriptPubKeys)
                {
                    Assert.True(scriptPubKey.IsScriptType(ScriptType.P2WPKH));
                }

                // Now need to start staking.
                var staker = node.FullNode.NodeService <IPosMinting>() as PosMinting;

                staker.Stake(new List <WalletSecret>()
                {
                    new WalletSecret()
                    {
                        WalletName = node.WalletName, WalletPassword = node.WalletPassword
                    }
                });

                // Wait for the chain height to increase.
                TestBase.WaitLoop(() => node.CreateRPCClient().GetBlockCount() >= (minStakeConfirmations + 3), cancellationToken: cancellationToken);

                // Get the last staked block.
                Block block = node.FullNode.ChainIndexer.Tip.Block;

                // Confirm that the staked block is Segwit-ted.
                Script commitment = WitnessCommitmentsRule.GetWitnessCommitment(node.FullNode.Network, block);

                // We presume that the consensus rules are checking the actual validity of the commitment, we just ensure that it exists here.
                Assert.NotNull(commitment);
            }
        }
Example #2
0
        public void CheckSegwitP2PSerialisationForWitnessNode()
        {
            using (NodeBuilder builder = NodeBuilder.Create(this))
            {
                CoreNode node     = builder.CreateStratisPosNode(KnownNetworks.StraxRegTest).Start();
                CoreNode listener = builder.CreateStratisPosNode(KnownNetworks.StraxRegTest).Start();

                IConnectionManager listenerConnMan = listener.FullNode.NodeService <IConnectionManager>();
                listenerConnMan.Parameters.TemplateBehaviors.Add(new TestBehavior());

                // The listener node will have default settings, i.e. it should ask for witness data in P2P messages.
                Assert.True(listenerConnMan.Parameters.Services.HasFlag(NetworkPeerServices.NODE_WITNESS));

                TestHelper.Connect(listener, node);

                // Mine a Segwit block on the first node.
                var            script     = new Key().PubKey.WitHash.ScriptPubKey;
                var            miner      = node.FullNode.NodeService <IPowMining>() as PowMining;
                List <uint256> res        = miner.GenerateBlocks(new ReserveScript(script), 1, int.MaxValue);
                Block          block      = node.FullNode.ChainIndexer.GetHeader(res.First()).Block;
                Script         commitment = WitnessCommitmentsRule.GetWitnessCommitment(node.FullNode.Network, block);
                Assert.NotNull(commitment);

                var cancellationToken = new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token;
                TestBase.WaitLoop(() => listener.CreateRPCClient().GetBlockCount() >= 1, cancellationToken: cancellationToken);

                // We need to capture a message on the witness-enabled destination node and see that it contains a block serialised with witness data.
                INetworkPeer connectedPeer = listenerConnMan.ConnectedPeers.FindByEndpoint(node.Endpoint);
                TestBehavior testBehavior  = connectedPeer.Behavior <TestBehavior>();

                var blockMessages = testBehavior.receivedMessageTracker["block"];
                var blockReceived = blockMessages.First();

                var receivedBlock   = blockReceived.Message.Payload as BlockPayload;
                var parsedBlock     = receivedBlock.Obj;
                var nonWitnessBlock = parsedBlock.WithOptions(listener.FullNode.Network.Consensus.ConsensusFactory, TransactionOptions.None);

                Assert.True(parsedBlock.GetSerializedSize() > nonWitnessBlock.GetSerializedSize());
            }
        }
Example #3
0
        public void StakeSegwitBlock()
        {
            using (NodeBuilder builder = NodeBuilder.Create(this))
            {
                // Even though we are mining, we still want to use PoS consensus rules.
                Network  network = KnownNetworks.StraxRegTest;
                CoreNode node    = builder.CreateStratisPosNode(network).WithWallet().Start();

                // Need the premine to be past coinbase maturity so that we can stake with it.
                RPCClient rpc = node.CreateRPCClient();
                int       minStakeConfirmations = ((PosConsensusOptions)network.Consensus.Options).GetStakeMinConfirmations(0, network);
                rpc.Generate(minStakeConfirmations + 2);

                var cancellationToken = new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token;
                TestBase.WaitLoop(() => node.CreateRPCClient().GetBlockCount() >= (minStakeConfirmations + 2), cancellationToken: cancellationToken);

                // Now need to start staking.
                var staker = node.FullNode.NodeService <IPosMinting>() as StraxMinting;

                staker.Stake(new List <WalletSecret>()
                {
                    new WalletSecret()
                    {
                        WalletName = node.WalletName, WalletPassword = node.WalletPassword
                    }
                });

                // Wait for the chain height to increase.
                TestBase.WaitLoop(() => node.CreateRPCClient().GetBlockCount() >= (minStakeConfirmations + 3), cancellationToken: cancellationToken);

                // Get the last staked block.
                Block block = node.FullNode.ChainIndexer.Tip.Block;

                // Confirm that the staked block is Segwit-ted.
                Script commitment = WitnessCommitmentsRule.GetWitnessCommitment(node.FullNode.Network, block);

                // We presume that the consensus rules are checking the actual validity of the commitment, we just ensure that it exists here.
                Assert.NotNull(commitment);
            }
        }
Example #4
0
        public void MineSegwitBlock()
        {
            using (NodeBuilder builder = NodeBuilder.Create(this))
            {
                // Even though we are mining, we still want to use PoS consensus rules.
                CoreNode node = builder.CreateStratisPosNode(KnownNetworks.StraxRegTest).Start();

                // Create a Segwit P2WPKH scriptPubKey.
                var script = new Key().PubKey.WitHash.ScriptPubKey;

                var            miner = node.FullNode.NodeService <IPowMining>() as PowMining;
                List <uint256> res   = miner.GenerateBlocks(new ReserveScript(script), 1, int.MaxValue);

                // Retrieve mined block.
                Block block = node.FullNode.ChainIndexer.GetHeader(res.First()).Block;

                // Confirm that the mined block is Segwit-ted.
                Script commitment = WitnessCommitmentsRule.GetWitnessCommitment(node.FullNode.Network, block);

                // We presume that the consensus rules are checking the actual validity of the commitment, we just ensure that it exists here.
                Assert.NotNull(commitment);
            }
        }
 /// <summary>
 /// Adds the coinbase commitment to the coinbase transaction according to  https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki.
 /// </summary>
 /// <param name="block">The new block that is being mined.</param>
 /// <seealso cref="https://github.com/bitcoin/bitcoin/blob/master/src/validation.cpp"/>
 public void AddOrUpdateCoinbaseCommitmentToBlock(Block block)
 {
     WitnessCommitmentsRule.ClearWitnessCommitment(this.Network, block);
     WitnessCommitmentsRule.CreateWitnessCommitment(this.Network, block);
 }
Example #6
0
        public void CheckSegwitP2PSerialisationForNonWitnessNode()
        {
            using (NodeBuilder builder = NodeBuilder.Create(this))
            {
                // We have to name the networks differently because the NBitcoin network registration won't allow two identical networks to coexist otherwise.
                var network = new StraxRegTest();
                network.SetPrivatePropertyValue("Name", "StraxRegTestWithDeployments");
                Assert.NotNull(network.Consensus.BIP9Deployments[2]);

                var networkNoBIP9 = new StraxRegTest();
                networkNoBIP9.SetPrivatePropertyValue("Name", "StraxRegTestWithoutDeployments");
                Assert.NotNull(networkNoBIP9.Consensus.BIP9Deployments[2]);

                // Remove BIP9 deployments (i.e. segwit).
                for (int i = 0; i < networkNoBIP9.Consensus.BIP9Deployments.Length; i++)
                {
                    networkNoBIP9.Consensus.BIP9Deployments[i] = null;
                }

                // Ensure the workaround had the desired effect.
                Assert.Null(networkNoBIP9.Consensus.BIP9Deployments[2]);
                Assert.NotNull(network.Consensus.BIP9Deployments[2]);

                // Explicitly use new & separate instances of StratisRegTest because we modified the BIP9 deployments on one instance.
                CoreNode node     = builder.CreateStratisPosNode(network).Start();
                CoreNode listener = builder.CreateStratisPosNode(networkNoBIP9).Start();

                // Sanity check.
                Assert.Null(listener.FullNode.Network.Consensus.BIP9Deployments[2]);
                Assert.NotNull(node.FullNode.Network.Consensus.BIP9Deployments[2]);

                // By disabling Segwit on the listener node we also prevent the WitnessCommitments rule from rejecting the mining node's blocks once we modify the listener's peer services.

                IConnectionManager listenerConnMan = listener.FullNode.NodeService <IConnectionManager>();
                listenerConnMan.Parameters.TemplateBehaviors.Add(new TestBehavior());

                // Override the listener node's default settings, so that it will not ask for witness data in P2P messages.
                listenerConnMan.Parameters.Services &= ~NetworkPeerServices.NODE_WITNESS;

                TestHelper.Connect(listener, node);

                // Mine a Segwit block on the first node. It should have commitment data as its settings have not been modified.
                var            script     = new Key().PubKey.WitHash.ScriptPubKey;
                var            miner      = node.FullNode.NodeService <IPowMining>() as PowMining;
                List <uint256> res        = miner.GenerateBlocks(new ReserveScript(script), 1, int.MaxValue);
                Block          block      = node.FullNode.ChainIndexer.GetHeader(res.First()).Block;
                Script         commitment = WitnessCommitmentsRule.GetWitnessCommitment(node.FullNode.Network, block);
                Assert.NotNull(commitment);

                // The listener should sync the mined block without validation failures.
                var cancellationToken = new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token;
                TestBase.WaitLoop(() => listener.CreateRPCClient().GetBlockCount() >= 1, cancellationToken: cancellationToken);

                // We need to capture a message on the non-witness-enabled destination node and see that it contains a block serialised without witness data.
                INetworkPeer connectedPeer = listenerConnMan.ConnectedPeers.FindByEndpoint(node.Endpoint);
                TestBehavior testBehavior  = connectedPeer.Behavior <TestBehavior>();

                var blockMessages = testBehavior.receivedMessageTracker["block"];
                var blockReceived = blockMessages.First();

                var receivedBlock = blockReceived.Message.Payload as BlockPayload;
                var parsedBlock   = receivedBlock.Obj;

                // The block mined on the mining node (witness) should be bigger than the one received by the listener (no witness).
                Assert.True(block.GetSerializedSize() > parsedBlock.GetSerializedSize());

                // Reserialise the received block without witness data (this should have no effect on its size).
                var nonWitnessBlock = parsedBlock.WithOptions(listener.FullNode.Network.Consensus.ConsensusFactory, TransactionOptions.None);

                // We received a block without witness data in the first place.
                Assert.True(parsedBlock.GetSerializedSize() == nonWitnessBlock.GetSerializedSize());
            }
        }