public override void Initialize (NodeBuilder[] builders, TreePadOption[] options)
		{
			base.Initialize (builders, options);

			Clear ();
			LoadTree (ConnectionContextService.DatabaseConnections);
		}
Exemplo n.º 2
0
        public override IReadOnlyList <INode> GetNodes(ISqlLoader loader, IGeneratorOption option, MethodInfo mi)
        {
            var parameters = BuildHelper.GetParameters(option, mi);
            var keys       = BuildHelper.GetKeyParameters(parameters);
            var tableName  = table ??
                             (type != null ? BuildHelper.GetTableNameOfType(option, type) : null) ??
                             BuildHelper.GetReturnTableName(option, mi);

            if (String.IsNullOrEmpty(tableName))
            {
                throw new BuilderException($"Table name resolve failed. type=[{mi.DeclaringType.FullName}], method=[{mi.Name}]");
            }

            var sql = new StringBuilder();

            sql.Append("SELECT * FROM ");
            sql.Append(tableName);
            BuildHelper.AddCondition(sql, keys.Count > 0 ? keys : parameters);

            var tokenizer = new SqlTokenizer(sql.ToString());
            var builder   = new NodeBuilder(tokenizer.Tokenize());

            return(builder.Build());
        }
Exemplo n.º 3
0
        public void Mempool_SendPosTransaction_WithElapsedLockTime_ShouldBeAcceptedByMempool()
        {
            // See CheckFinalTransaction_WithElapsedLockTime_ReturnsTrueAsync for the 'unit test' version

            var network = new StratisRegTest();

            using (NodeBuilder builder = NodeBuilder.Create(this))
            {
                CoreNode stratisSender = builder.CreateStratisPosNode(network).WithReadyBlockchainData(ReadyBlockchain.StratisRegTest10Miner).Start();

                TestHelper.MineBlocks(stratisSender, 5);

                // Send coins to the receiver.
                var context = WalletTests.CreateContext(network, new WalletAccountReference(WalletName, Account), Password, new Key().PubKey.GetAddress(network).ScriptPubKey, Money.COIN * 100, FeeType.Medium, 1);

                Transaction trx = stratisSender.FullNode.WalletTransactionHandler().BuildTransaction(context);

                // Treat the locktime as absolute, not relative.
                trx.Inputs.First().Sequence = new Sequence(Sequence.SEQUENCE_LOCKTIME_DISABLE_FLAG);

                // Set the nLockTime to be behind the current tip so that locktime has elapsed.
                trx.LockTime = new LockTime(stratisSender.FullNode.ChainIndexer.Height - 1);

                // Sign trx again after changing the nLockTime.
                trx = context.TransactionBuilder.SignTransaction(trx);

                // Enable standard policy relay.
                stratisSender.FullNode.NodeService <MempoolSettings>().RequireStandard = true;

                var broadcaster = stratisSender.FullNode.NodeService <IBroadcasterManager>();

                broadcaster.BroadcastTransactionAsync(trx);

                TestBase.WaitLoop(() => stratisSender.CreateRPCClient().GetRawMempool().Length == 1);
            }
        }
        public void BannedNode_Tries_ToConnect_ItFails_ToEstablishConnection()
        {
            // TS105_Connectivity_PreventConnectingToBannedNodes.

            using (NodeBuilder builder = NodeBuilder.Create(this))
            {
                CoreNode node1 = builder.CreateStratisPosNode(this.posNetwork, "conn-5-node1").Start();
                CoreNode node2 = builder.CreateStratisPosNode(this.posNetwork, "conn-5-node2").Start();

                node1 = BanNode(node1, node2);

                // Here we have to use the RPC client directly so that we can get the exception.
                Action connectAction = () => node1.CreateRPCClient().AddNode(node2.Endpoint, true);
                connectAction.Should().Throw <RPCException>().WithMessage("Internal error");

                node1.FullNode.ConnectionManager.ConnectedPeers.Should().BeEmpty();

                node1 = RemoveBan(node1, node2);

                TestHelper.Connect(node1, node2);

                node1.FullNode.ConnectionManager.ConnectedPeers.Should().NotBeEmpty();
            }
        }
Exemplo n.º 5
0
        private void PreviewExtrudes(bool showDragAxis)
        {
            var extrudeSize = _globalExtrudeSize;

            InitSession();

            Ensure.IsNotNull(_sketchNode);
            var results = BuildAutoFaces(_sketchNode);

            foreach (var node in results)
            {
                if (showDragAxis)
                {
                    var nb = new NodeBuilder(node);
                    BuildDragAxis(nb.Shape, extrudeSize);
                }
                var extrudeBuilder = BuildExtrudeBuilder(new SceneSelectedEntity(node)
                {
                    ShapeType = TopAbsShapeEnum.TopAbs_FACE
                });                                                                                                                 //node);
                _extrudesList[extrudeBuilder.Node.Index] = extrudeBuilder.Node;
            }
            UpdateView();
        }
Exemplo n.º 6
0
        public void BlockStoreCanReorg()
        {
            using (NodeBuilder builder = NodeBuilder.Create(this))
            {
                CoreNode stratisNodeSync = builder.CreateStratisPowNode(this.network).WithReadyBlockchainData(ReadyBlockchain.BitcoinRegTest10Miner).Start();
                CoreNode stratisNode1    = builder.CreateStratisPowNode(this.network).WithReadyBlockchainData(ReadyBlockchain.BitcoinRegTest10Listener).Start();
                CoreNode stratisNode2    = builder.CreateStratisPowNode(this.network).WithReadyBlockchainData(ReadyBlockchain.BitcoinRegTest10Listener).Start();

                // Sync both nodes.
                TestHelper.ConnectAndSync(stratisNodeSync, stratisNode1);
                TestHelper.ConnectAndSync(stratisNodeSync, stratisNode2);

                // Remove node 2.
                TestHelper.Disconnect(stratisNodeSync, stratisNode2);

                // Mine some more with node 1
                TestHelper.MineBlocks(stratisNode1, 10);

                // Wait for node 1 to sync
                TestHelper.WaitLoop(() => stratisNode1.FullNode.GetBlockStoreTip().Height == 20);
                TestHelper.WaitLoop(() => stratisNode1.FullNode.GetBlockStoreTip().HashBlock == stratisNodeSync.FullNode.GetBlockStoreTip().HashBlock);

                // Remove node 1.
                TestHelper.Disconnect(stratisNodeSync, stratisNode1);

                // Mine a higher chain with node 2.
                TestHelper.MineBlocks(stratisNode2, 20);
                TestHelper.WaitLoop(() => stratisNode2.FullNode.GetBlockStoreTip().Height == 30);

                // Add node 2.
                TestHelper.Connect(stratisNodeSync, stratisNode2);

                // Node2 should be synced.
                TestHelper.WaitLoop(() => TestHelper.AreNodesSynced(stratisNode2, stratisNodeSync));
            }
        }
        public void TestRpcSendToAddressIsSuccessful()
        {
            using (NodeBuilder builder = NodeBuilder.Create(this))
            {
                Network network = new BitcoinRegTest();
                var     node    = builder.CreateStratisPowNode(network).WithReadyBlockchainData(ReadyBlockchain.BitcoinRegTest150Miner).Start();

                RPCClient rpcClient = node.CreateRPCClient();

                var alice        = new Key().GetBitcoinSecret(network);
                var aliceAddress = alice.GetAddress();
                rpcClient.WalletPassphrase("password", 60);
                var txid = rpcClient.SendToAddress(aliceAddress, Money.Coins(1.0m));
                rpcClient.SendCommand(RPCOperations.walletlock);

                // Check the hash calculated correctly.
                var tx = rpcClient.GetRawTransaction(txid);
                Assert.Equal(txid, tx.GetHash());

                // Check the output is the right amount.
                var coin = tx.Outputs.AsCoins().First(c => c.ScriptPubKey == aliceAddress.ScriptPubKey);
                Assert.Equal(coin.Amount, Money.Coins(1.0m));
            }
        }
Exemplo n.º 8
0
        private NodeBuilder BuildCircleInDocument(Document previewDocument, bool animation)
        {
            var sketchBuilder = new SketchCreator(previewDocument);

            //var nodeBuilder = new NodeBuilder(sketchBuilder.CurrentSketch);
            //nodeBuilder[0].TransformedAxis3D = normalOnPlane;

            ////Document.Root.Get<ShapeFunctionsInterface.Interpreters.DocumentContextInterpreter>().ActiveSketch
            var circleCenterPoint = Points[0];

            Ensure.IsNotNull(circleCenterPoint);
            var firstPointBuilder = sketchBuilder.GetPoint(circleCenterPoint).Node;

            var builder = new NodeBuilder(previewDocument, FunctionNames.Circle);

            builder[0].Reference = firstPointBuilder;
            builder[1].Real      = circleRadius > 0.0 ? circleRadius : Points[1].Distance(Points[0]);
            if (animation)
            {
                builder.EnableSelection = false;
            }
            builder.ExecuteFunction();
            return(builder);
        }
        public void CanGetGenesisFromRPC()
        {
            using (NodeBuilder builder = NodeBuilder.Create(this))
            {
                CoreNode node = builder.CreateBitcoinCoreNode(version: BitcoinCoreVersion15).Start();

                RPCClient rpcClient = node.CreateRPCClient();

                RPCResponse response      = rpcClient.SendCommand(RPCOperations.getblockhash, 0);
                string      actualGenesis = (string)response.Result;
                Assert.Equal(this.regTest.GetGenesis().GetHash().ToString(), actualGenesis);
                Assert.Equal(this.regTest.GetGenesis().GetHash(), rpcClient.GetBestBlockHash());

                CoreNode sfn = builder.CreateStratisPowNode(this.regTest).Start();
                TestHelper.ConnectAndSync(node, sfn);

                rpcClient = sfn.CreateRPCClient();

                response      = rpcClient.SendCommand(RPCOperations.getblockhash, 0);
                actualGenesis = (string)response.Result;
                Assert.Equal(this.regTest.GetGenesis().GetHash().ToString(), actualGenesis);
                Assert.Equal(this.regTest.GetGenesis().GetHash(), rpcClient.GetBestBlockHash());
            }
        }
Exemplo n.º 10
0
        public ServerTester(string directory)
        {
            SetEnvironment();
            try
            {
                var rootTestData = "TestData";
                directory  = Path.Combine(rootTestData, directory);
                _Directory = directory;
                if (!Directory.Exists(rootTestData))
                {
                    Directory.CreateDirectory(rootTestData);
                }

                var cryptoSettings = new NBXplorerNetworkProvider(NetworkType.Regtest).GetFromCryptoCode(CryptoCode);
                NodeBuilder = NodeBuilder.Create(nodeDownloadData, Network, directory);

                Explorer = NodeBuilder.CreateNode();
                foreach (var node in NodeBuilder.Nodes)
                {
                    node.WhiteBind  = true;
                    node.CookieAuth = cryptoSettings.SupportCookieAuthentication;
                }
                NodeBuilder.StartAll();
                Explorer.CreateRPCClient().EnsureGenerate(Network.Consensus.CoinbaseMaturity + 1);

                datadir = Path.Combine(directory, "explorer");
                DeleteFolderRecursive(datadir);
                StartNBXplorer();
                this.Client.WaitServerStarted();
            }
            catch
            {
                Dispose();
                throw;
            }
        }
Exemplo n.º 11
0
        public void ConfigureTestEnvironment()
        {
            _document = TestUtils.DefaultsSetup();
            _document.Root.Set <DocumentContextInterpreter>();

            _testBoxBuilder = new NodeBuilder(_document, FunctionNames.Box1P);
            _testBoxBuilder[0].TransformedPoint3D = new Point3D(0, 0, 0);
            _testBoxBuilder[1].Real = 10;
            _testBoxBuilder[2].Real = 10;
            _testBoxBuilder[3].Real = 10;
            Assert.IsTrue(_testBoxBuilder.ExecuteFunction(), "Failed to create the test box");

            _boxRightFace = new SceneSelectedEntity(_testBoxBuilder.Node)
            {
                ShapeCount = 1,
                ShapeType  = TopAbsShapeEnum.TopAbs_FACE
            };

            _boxBottomFace = new SceneSelectedEntity(_testBoxBuilder.Node)
            {
                ShapeCount = 6,
                ShapeType  = TopAbsShapeEnum.TopAbs_FACE
            };
        }
Exemplo n.º 12
0
        public override Task <Tuple <Address, TaskCompletionSource <IAssociationEventListener> > > Listen()
        {
            var listenAddress    = NodeBuilder.BuildNode().Host(Settings.Hostname).WithPort(Settings.Port);
            var newServerChannel = NewServer(listenAddress);

            newServerChannel.Open();

            //Block reads until a handler actor is registered
            //TODO
            ConnectionGroup.TryAdd(newServerChannel);
            ServerChannel = newServerChannel;

            var addr = NodeToAddress(newServerChannel.Local, SchemeIdentifier, System.Name, Settings.Hostname);

            if (addr == null)
            {
                throw new HeliosNodeException("Unknown local address type {0}", newServerChannel.Local);
            }
            LocalAddress = addr;
            AssociationListenerPromise.Task.ContinueWith(result => ServerChannel.BeginReceive(),
                                                         TaskContinuationOptions.AttachedToParent & TaskContinuationOptions.ExecuteSynchronously);

            return(Task.Run(() => Tuple.Create(addr, AssociationListenerPromise)));
        }
Exemplo n.º 13
0
        protected void UpdateShapeSelection()
        {
            if (SelectedNodes.Count < 2)
            {
                return;
            }
            InitSession();

            Builder = new NodeBuilder(Document, _functionName);


            Builder[0].Reference = SelectedNodes[0];
            Builder[1].Reference = SelectedNodes[1];

            if (Builder.ExecuteFunction())
            {
                Document.Root.Remove(Builder.Node.Index);
                CommitFinal("Apply Mirror");
                UpdateView();
                RebuildTreeView();
            }

            BackToNeutralModifier();
        }
Exemplo n.º 14
0
        public async Task AddAnAddressBookEntry()
        {
            using (NodeBuilder builder = NodeBuilder.Create(this))
            {
                // Arrange.
                CoreNode node = builder.CreateStratisPosNode(this.network).Start();

                // Act.
                AddressBookEntryModel newEntry = await $"http://localhost:{node.ApiPort}/api"
                                                 .AppendPathSegment("addressbook/address")
                                                 .PostJsonAsync(new { label = "label1", address = "TQNyrEPc4qHxWN96dBAjncBeB2ghJPqYVu" })
                                                 .ReceiveJson <AddressBookEntryModel>();

                // Assert.
                // Check the address is in the address book.
                AddressBookModel addressBook = await $"http://localhost:{node.ApiPort}/api"
                                               .AppendPathSegment("addressbook")
                                               .GetJsonAsync <AddressBookModel>();

                addressBook.Addresses.Should().ContainSingle();
                addressBook.Addresses.Single().Label.Should().Be("label1");
                addressBook.Addresses.Single().Address.Should().Be("TQNyrEPc4qHxWN96dBAjncBeB2ghJPqYVu");
            }
        }
        public async Task Can_ClearAll_Banned_PeersAsync()
        {
            using (var builder = NodeBuilder.Create(this))
            {
                var network = new StratisRegTest();

                var nodeA = builder.CreateStratisPosNode(network).Start();

                var nodeB_Ip        = "127.0.0.2";
                var nodeB_IpAddress = IPAddress.Parse(nodeB_Ip);
                var nodeB_EndPoint  = new IPEndPoint(nodeB_IpAddress, 0);

                var nodeAaddressManager = nodeA.FullNode.NodeService <IPeerAddressManager>();
                nodeAaddressManager.AddPeer(new IPEndPoint(nodeB_IpAddress, 0), IPAddress.Loopback);

                var peerBanning = nodeA.FullNode.NodeService <IPeerBanning>();
                peerBanning.BanAndDisconnectPeer(nodeB_EndPoint);
                Assert.True(peerBanning.IsBanned(nodeB_EndPoint));

                await $"http://localhost:{nodeA.ApiPort}/api".AppendPathSegment("network/clearbanned").PostJsonAsync(null);

                Assert.False(peerBanning.IsBanned(nodeB_EndPoint));
            }
        }
        public void MiningAndPropagatingPOW_MineBlockCheckPeerHasNewBlock()
        {
            using (NodeBuilder builder = NodeBuilder.Create(this))
            {
                CoreNode miner   = builder.CreateStratisPowNode(this.regTest).WithReadyBlockchainData(ReadyBlockchain.BitcoinRegTest10Miner).Start();
                CoreNode syncerA = builder.CreateStratisPowNode(this.regTest).Start();
                CoreNode syncerB = builder.CreateStratisPowNode(this.regTest).Start();
                CoreNode syncerC = builder.CreateStratisPowNode(this.regTest).Start();

                // Connect miner to all 3 syncers.
                TestHelper.Connect(miner, syncerA);
                TestHelper.Connect(miner, syncerB);
                TestHelper.Connect(miner, syncerC);

                // Ensure miner has 3 connections.
                TestBase.WaitLoop(() => miner.FullNode.ConnectionManager.ConnectedPeers.Count() == 3);

                TestBase.WaitLoop(() => TestHelper.AreNodesSynced(miner, syncerA));
                TestBase.WaitLoop(() => TestHelper.AreNodesSynced(miner, syncerB));
                TestBase.WaitLoop(() => TestHelper.AreNodesSynced(miner, syncerC));

                Assert.True(new[] { syncerA, syncerB, syncerC }.All(n => n.FullNode.ConsensusManager().Tip.Height == 10));
            }
        }
Exemplo n.º 17
0
        private static void Main(string[] args)
        {
            var host         = IPAddress.Loopback;
            var port         = 9991;
            var bootstrapper =
                new ClientBootstrap()
                .SetTransport(TransportType.Tcp).Build();

            TimeClient = bootstrapper.NewConnection(Node.Empty(), NodeBuilder.BuildNode().Host(host).WithPort(port));
            TimeClient.OnConnection += (address, connection) =>
            {
                Console.WriteLine("Confirmed connection with host.");
                connection.BeginReceive(ReceivedCallback);
            };
            TimeClient.OnDisconnection += (address, reason) => Console.WriteLine("Disconnected.");

            Console.Title = string.Format("TimeClient {0}", Process.GetCurrentProcess().Id);
            LoopConnect();
            Console.WriteLine("Requesting time from server...");
            Console.WriteLine("Printing every 1/1000 received messages");
            LoopWrite();
            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }
Exemplo n.º 18
0
        public void CanBackupWallet()
        {
            using (NodeBuilder builder = NodeBuilder.Create(this))
            {
                CoreNode node = builder.CreateBitcoinCoreNode(version: BitcoinCoreVersion15).Start();

                RPCClient rpcClient = node.CreateRPCClient();

                string buildOutputDir = Path.GetDirectoryName(".");
                string filePath       = Path.Combine(buildOutputDir, "wallet_backup.dat");
                try
                {
                    rpcClient.BackupWallet(filePath);
                    Assert.True(File.Exists(filePath));
                }
                finally
                {
                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath);
                    }
                }
            }
        }
Exemplo n.º 19
0
        public void DummyNetworkInterfaceOnlyOut()
        {
            var network = new DummyNetworkInterface();
            var builder = new NodeBuilder();

            builder.UseNetwork(network);
            builder.UseTransient <SimpleDummyMiddleware>();
            var node = builder.Build();

            var model = new InMemoryNodeContract(MethodBase.GetCurrentMethod().Name, new byte[10]);

            _rand.NextBytes(model.RawData);

            node.SendAsync(new InMemoryNodeContract()).Wait();
            Assert.AreEqual(network.OutDatas.Count(), 1);

            var outData = network.OutDatas.First();

            Assert.AreEqual(outData.Destination.Port, 9999);
            Assert.AreEqual(outData.Source.Port, 8888);
            var state = outData.State as InMemoryNodeContract;

            Assert.IsNotNull(state);
        }
Exemplo n.º 20
0
        public static void BuildRectangle(Document document, Node sketchNode, Point3D point1, Point3D point2, Point3D point3, Point3D point4)
        {
            var point1Builder = Point(document, sketchNode, point1);
            var point2Builder = Point(document, sketchNode, point2);
            var point3Builder = Point(document, sketchNode, point3);
            var point4Builder = Point(document, sketchNode, point4);
            var lineBuilder   = new NodeBuilder(document, FunctionNames.LineTwoPoints);

            lineBuilder[0].Reference = point1Builder.Node;
            lineBuilder[1].Reference = point2Builder.Node;
            lineBuilder.ExecuteFunction();
            lineBuilder = new NodeBuilder(document, FunctionNames.LineTwoPoints);
            lineBuilder[0].Reference = point2Builder.Node;
            lineBuilder[1].Reference = point3Builder.Node;
            lineBuilder.ExecuteFunction();
            lineBuilder = new NodeBuilder(document, FunctionNames.LineTwoPoints);
            lineBuilder[0].Reference = point3Builder.Node;
            lineBuilder[1].Reference = point4Builder.Node;
            lineBuilder.ExecuteFunction();
            lineBuilder = new NodeBuilder(document, FunctionNames.LineTwoPoints);
            lineBuilder[0].Reference = point4Builder.Node;
            lineBuilder[1].Reference = point1Builder.Node;
            lineBuilder.ExecuteFunction();
        }
Exemplo n.º 21
0
        public void LegacyNodesConnectsToProvenHeaderEnabledNode_AndLastOneIsDisconnectedToReserveSlot()
        {
            using (NodeBuilder builder = NodeBuilder.Create(this).WithLogsEnabled())
            {
                // Create separate network parameters for this test.
                CoreNode phEnabledNode = this.CreateNode(builder, "ph-enabled", ProtocolVersion.PROVEN_HEADER_VERSION, new NodeConfigParameters {
                    { "maxoutboundconnections", "3" }
                }).Start();
                CoreNode legacyNode1 = this.CreateNode(builder, "legacy1", ProtocolVersion.ALT_PROTOCOL_VERSION).Start();
                CoreNode legacyNode2 = this.CreateNode(builder, "legacy2", ProtocolVersion.ALT_PROTOCOL_VERSION).Start();
                CoreNode legacyNode3 = this.CreateNode(builder, "legacy3", ProtocolVersion.ALT_PROTOCOL_VERSION).Start();

                TestHelper.Connect(phEnabledNode, legacyNode1);
                TestHelper.Connect(phEnabledNode, legacyNode2);
                TestHelper.Connect(phEnabledNode, legacyNode3);

                // TODO: ProvenHeadersReservedSlotsBehavior kicks in only during peer discovery, so it doesn't trigger when we have an inbound connection or
                // when we are using addnode/connect.
                // We need to configure a peers.json file or mock the PeerDiscovery to let phEnabledNode try to connect to legacyNode1, legacyNode2 and legacyNode3
                // With a maxoutboundconnections = 3, we expect the 3rd peer being disconnected to reserve a slot for a ph enabled node.

                // Assert.Equal(phEnabledNode.FullNode.ConnectionManager.ConnectedPeers.Count() == 2);
            }
        }
Exemplo n.º 22
0
        public void SendAndReceiveCorrectly()
        {
            using (NodeBuilder builder = NodeBuilder.Create(this))
            {
                CoreNode scSender   = builder.CreateSmartContractPowNode();
                CoreNode scReceiver = builder.CreateSmartContractPowNode();

                builder.StartAll();

                scSender.NotInIBD();
                scReceiver.NotInIBD();

                Mnemonic  mnemonic1           = scSender.FullNode.WalletManager().CreateWallet(Password, WalletName);
                Mnemonic  mnemonic2           = scReceiver.FullNode.WalletManager().CreateWallet(Password, WalletName);
                HdAddress addr                = scSender.FullNode.WalletManager().GetUnusedAddress(new WalletAccountReference(WalletName, AccountName));
                Features.Wallet.Wallet wallet = scSender.FullNode.WalletManager().GetWalletByName(WalletName);
                Key key = wallet.GetExtendedPrivateKeyForAddress(Password, addr).PrivateKey;

                scSender.SetDummyMinerSecret(new BitcoinSecret(key, scSender.FullNode.Network));
                var maturity = (int)scSender.FullNode.Network.Consensus.CoinbaseMaturity;
                scSender.GenerateStratisWithMiner(maturity + 5);
                // wait for block repo for block sync to work

                TestHelper.WaitLoop(() => TestHelper.IsNodeSynced(scSender));

                // the mining should add coins to the wallet
                var total = scSender.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Sum(s => s.Transaction.Amount);
                Assert.Equal(Money.COIN * (maturity + 5) * 50, total);

                // sync both nodes
                scSender.CreateRPCClient().AddNode(scReceiver.Endpoint, true);
                TestHelper.WaitLoop(() => TestHelper.AreNodesSynced(scReceiver, scSender));

                // send coins to the receiver
                HdAddress sendto         = scReceiver.FullNode.WalletManager().GetUnusedAddress(new WalletAccountReference(WalletName, AccountName));
                var       txBuildContext = new TransactionBuildContext(scSender.FullNode.Network)
                {
                    AccountReference = new WalletAccountReference(WalletName, AccountName),
                    MinConfirmations = maturity,
                    FeeType          = FeeType.Medium,
                    WalletPassword   = Password,
                    Recipients       = new[] { new Recipient {
                                                   Amount = Money.COIN * 100, ScriptPubKey = sendto.ScriptPubKey
                                               } }.ToList()
                };

                Transaction trx = (scSender.FullNode.NodeService <IWalletTransactionHandler>() as SmartContractWalletTransactionHandler).BuildTransaction(txBuildContext);

                // broadcast to the other node
                scSender.FullNode.NodeService <SmartContractWalletController>().SendTransaction(new SendTransactionRequest(trx.ToHex()));

                // wait for the trx to arrive
                TestHelper.WaitLoop(() => scReceiver.CreateRPCClient().GetRawMempool().Length > 0);
                TestHelper.WaitLoop(() => scReceiver.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Any());

                var receivetotal = scReceiver.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Sum(s => s.Transaction.Amount);
                Assert.Equal(Money.COIN * 100, receivetotal);
                Assert.Null(scReceiver.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).First().Transaction.BlockHeight);

                // generate two new blocks do the trx is confirmed
                scSender.AddToStratisMempool(scSender.FullNode.Network.CreateTransaction(trx.ToBytes()));
                scSender.GenerateStratisWithMiner(1);

                // wait for block repo for block sync to work
                TestHelper.WaitLoop(() => TestHelper.IsNodeSynced(scSender));
                TestHelper.WaitLoop(() => TestHelper.AreNodesSynced(scReceiver, scSender));

                TestHelper.WaitLoop(() => maturity + 6 == scReceiver.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).First().Transaction.BlockHeight);
            }
        }
Exemplo n.º 23
0
        public void SendAndReceiveSmartContractTransactionsUsingController()
        {
            using (NodeBuilder builder = NodeBuilder.Create(this))
            {
                CoreNode scSender   = builder.CreateSmartContractPowNode();
                CoreNode scReceiver = builder.CreateSmartContractPowNode();

                builder.StartAll();

                scSender.NotInIBD();
                scReceiver.NotInIBD();

                scSender.FullNode.WalletManager().CreateWallet(Password, WalletName);
                scReceiver.FullNode.WalletManager().CreateWallet(Password, WalletName);
                HdAddress addr = scSender.FullNode.WalletManager().GetUnusedAddress(new WalletAccountReference(WalletName, AccountName));
                Features.Wallet.Wallet wallet = scSender.FullNode.WalletManager().GetWalletByName(WalletName);
                Key key = wallet.GetExtendedPrivateKeyForAddress(Password, addr).PrivateKey;

                scSender.SetDummyMinerSecret(new BitcoinSecret(key, scSender.FullNode.Network));
                scReceiver.SetDummyMinerSecret(new BitcoinSecret(key, scReceiver.FullNode.Network));
                var maturity = (int)scSender.FullNode.Network.Consensus.CoinbaseMaturity;
                scSender.GenerateStratisWithMiner(maturity + 5);
                TestHelper.WaitLoop(() => TestHelper.IsNodeSynced(scSender));

                var total = scSender.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Sum(s => s.Transaction.Amount);
                Assert.Equal(Money.COIN * (maturity + 5) * 50, total);

                SmartContractsController       senderSmartContractsController = scSender.FullNode.NodeService <SmartContractsController>();
                SmartContractWalletController  senderWalletController         = scSender.FullNode.NodeService <SmartContractWalletController>();
                SmartContractCompilationResult compilationResult = SmartContractCompiler.CompileFile("SmartContracts/StorageDemo.cs");
                Assert.True(compilationResult.Success);

                var buildRequest = new BuildCreateContractTransactionRequest
                {
                    AccountName  = AccountName,
                    GasLimit     = "10000",
                    GasPrice     = "1",
                    ContractCode = compilationResult.Compilation.ToHexString(),
                    FeeAmount    = "0.001",
                    Password     = Password,
                    WalletName   = WalletName,
                    Sender       = addr.Address
                };

                JsonResult result   = (JsonResult)senderSmartContractsController.BuildCreateSmartContractTransaction(buildRequest);
                var        response = (BuildCreateContractTransactionResponse)result.Value;
                scSender.CreateRPCClient().AddNode(scReceiver.Endpoint, true);

                SmartContractSharedSteps.SendTransactionAndMine(scSender, scReceiver, senderWalletController, response.Hex);

                var receiptStorage = scReceiver.FullNode.NodeService <ISmartContractReceiptStorage>();
                Assert.NotNull(receiptStorage.GetReceipt(response.TransactionId));

                // Check wallet history is updating correctly
                result = (JsonResult)senderWalletController.GetHistory(new WalletHistoryRequest
                {
                    AccountName = AccountName,
                    WalletName  = WalletName
                });
                var walletHistoryModel = (WalletHistoryModel)result.Value;
                Assert.Single(walletHistoryModel.AccountsHistoryModel.First().TransactionsHistory.Where(x => x.Type == TransactionItemType.Send));

                string storageRequestResult = (string)((JsonResult)senderSmartContractsController.GetStorage(new GetStorageRequest
                {
                    ContractAddress = response.NewContractAddress.ToString(),
                    StorageKey = "TestSave",
                    DataType = SmartContractDataType.String
                })).Value;
                Assert.Equal("Hello, smart contract world!", storageRequestResult);

                string ownerRequestResult = (string)((JsonResult)senderSmartContractsController.GetStorage(new GetStorageRequest
                {
                    ContractAddress = response.NewContractAddress.ToString(),
                    StorageKey = "Owner",
                    DataType = SmartContractDataType.Address
                })).Value;
                Assert.NotEmpty(ownerRequestResult);

                string counterRequestResult = (string)((JsonResult)senderSmartContractsController.GetStorage(new GetStorageRequest
                {
                    ContractAddress = response.NewContractAddress.ToString(),
                    StorageKey = "Counter",
                    DataType = SmartContractDataType.Int
                })).Value;
                Assert.Equal("12345", counterRequestResult);

                var callRequest = new BuildCallContractTransactionRequest
                {
                    AccountName     = AccountName,
                    GasLimit        = "10000",
                    GasPrice        = "1",
                    Amount          = "0",
                    MethodName      = "Increment",
                    ContractAddress = response.NewContractAddress,
                    FeeAmount       = "0.001",
                    Password        = Password,
                    WalletName      = WalletName,
                    Sender          = addr.Address
                };
                result = (JsonResult)senderSmartContractsController.BuildCallSmartContractTransaction(callRequest);
                var callResponse = (BuildCallContractTransactionResponse)result.Value;

                SmartContractSharedSteps.SendTransactionAndMine(scSender, scReceiver, senderWalletController, callResponse.Hex);

                counterRequestResult = (string)((JsonResult)senderSmartContractsController.GetStorage(new GetStorageRequest
                {
                    ContractAddress = response.NewContractAddress.ToString(),
                    StorageKey = "Counter",
                    DataType = SmartContractDataType.Int
                })).Value;
                Assert.Equal("12346", counterRequestResult);

                // Check wallet history again
                result = (JsonResult)senderWalletController.GetHistory(new WalletHistoryRequest
                {
                    AccountName = AccountName,
                    WalletName  = WalletName
                });
                walletHistoryModel = (WalletHistoryModel)result.Value;
                Assert.Equal(2, walletHistoryModel.AccountsHistoryModel.First().TransactionsHistory.Where(x => x.Type == TransactionItemType.Send).Count());

                // Check receipts
                var receiptResponse = (JsonResult)senderSmartContractsController.GetReceipt(callResponse.TransactionId.ToString());
                var receiptModel    = (ReceiptModel)receiptResponse.Value;
                Assert.True(receiptModel.Successful);
            }
        }
Exemplo n.º 24
0
        public void SendAndReceiveSmartContractTransactions()
        {
            using (NodeBuilder builder = NodeBuilder.Create(this))
            {
                CoreNode scSender   = builder.CreateSmartContractPowNode();
                CoreNode scReceiver = builder.CreateSmartContractPowNode();

                builder.StartAll();

                scSender.NotInIBD();
                scReceiver.NotInIBD();

                scSender.FullNode.WalletManager().CreateWallet(Password, WalletName);
                scReceiver.FullNode.WalletManager().CreateWallet(Password, WalletName);
                HdAddress addr = scSender.FullNode.WalletManager().GetUnusedAddress(new WalletAccountReference(WalletName, AccountName));
                Features.Wallet.Wallet wallet = scSender.FullNode.WalletManager().GetWalletByName(WalletName);
                Key key = wallet.GetExtendedPrivateKeyForAddress(Password, addr).PrivateKey;

                scSender.SetDummyMinerSecret(new BitcoinSecret(key, scSender.FullNode.Network));
                var maturity = (int)scSender.FullNode.Network.Consensus.CoinbaseMaturity;
                scSender.GenerateStratisWithMiner(maturity + 5);

                // Wait for block repo for block sync to work.
                TestHelper.WaitLoop(() => TestHelper.IsNodeSynced(scSender));

                // The mining should add coins to the wallet.
                var total = scSender.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Sum(s => s.Transaction.Amount);
                Assert.Equal(Money.COIN * (maturity + 5) * 50, total);

                // Create a token contract
                ulong gasPrice  = 1;
                int   vmVersion = 1;
                Gas   gasLimit  = (Gas)2000;
                SmartContractCompilationResult compilationResult = SmartContractCompiler.CompileFile("SmartContracts/TransferTest.cs");
                Assert.True(compilationResult.Success);

                var contractCarrier = SmartContractCarrier.CreateContract(vmVersion, compilationResult.Compilation, gasPrice, gasLimit);

                var contractCreateScript = new Script(contractCarrier.Serialize());
                var txBuildContext       = new TransactionBuildContext(scSender.FullNode.Network)
                {
                    AccountReference = new WalletAccountReference(WalletName, AccountName),
                    MinConfirmations = maturity,
                    FeeType          = FeeType.High,
                    WalletPassword   = Password,
                    Recipients       = new[] { new Recipient {
                                                   Amount = 0, ScriptPubKey = contractCreateScript
                                               } }.ToList()
                };

                Transaction transferContractTransaction = (scSender.FullNode.NodeService <IWalletTransactionHandler>() as SmartContractWalletTransactionHandler).BuildTransaction(txBuildContext);

                // Broadcast the token transaction to the network
                scSender.FullNode.NodeService <IBroadcasterManager>().BroadcastTransactionAsync(transferContractTransaction);

                // Wait for the token transaction to be picked up by the mempool
                TestHelper.WaitLoop(() => scSender.CreateRPCClient().GetRawMempool().Length > 0);

                // Mine the token transaction and wait for it sync
                scSender.GenerateStratisWithMiner(1);
                TestHelper.WaitLoop(() => TestHelper.IsNodeSynced(scSender));

                // Sync to the receiver node
                scSender.CreateRPCClient().AddNode(scReceiver.Endpoint, true);
                TestHelper.WaitLoop(() => TestHelper.AreNodesSynced(scReceiver, scSender));

                // Ensure that boths nodes has the contract
                ContractStateRepositoryRoot senderState      = scSender.FullNode.NodeService <ContractStateRepositoryRoot>();
                ContractStateRepositoryRoot receiverState    = scReceiver.FullNode.NodeService <ContractStateRepositoryRoot>();
                IAddressGenerator           addressGenerator = scSender.FullNode.NodeService <IAddressGenerator>();

                uint160 tokenContractAddress = addressGenerator.GenerateAddress(transferContractTransaction.GetHash(), 0);
                Assert.NotNull(senderState.GetCode(tokenContractAddress));
                Assert.NotNull(receiverState.GetCode(tokenContractAddress));
                scSender.FullNode.MempoolManager().Clear();

                // Create a transfer token contract
                compilationResult = SmartContractCompiler.CompileFile("SmartContracts/TransferTest.cs");
                Assert.True(compilationResult.Success);
                contractCarrier      = SmartContractCarrier.CreateContract(vmVersion, compilationResult.Compilation, gasPrice, gasLimit);
                contractCreateScript = new Script(contractCarrier.Serialize());
                txBuildContext       = new TransactionBuildContext(scSender.FullNode.Network)
                {
                    AccountReference = new WalletAccountReference(WalletName, AccountName),
                    MinConfirmations = maturity,
                    FeeType          = FeeType.High,
                    WalletPassword   = Password,
                    Recipients       = new[] { new Recipient {
                                                   Amount = 0, ScriptPubKey = contractCreateScript
                                               } }.ToList()
                };

                // Broadcast the token transaction to the network
                transferContractTransaction = (scSender.FullNode.NodeService <IWalletTransactionHandler>() as SmartContractWalletTransactionHandler).BuildTransaction(txBuildContext);
                scSender.FullNode.NodeService <IBroadcasterManager>().BroadcastTransactionAsync(transferContractTransaction);

                // Wait for the token transaction to be picked up by the mempool
                TestHelper.WaitLoop(() => scSender.CreateRPCClient().GetRawMempool().Length > 0);
                scSender.GenerateStratisWithMiner(1);

                // Ensure the node is synced
                TestHelper.WaitLoop(() => TestHelper.IsNodeSynced(scSender));

                // Ensure both nodes are synced with each other
                TestHelper.WaitLoop(() => TestHelper.AreNodesSynced(scReceiver, scSender));

                // Ensure that boths nodes has the contract
                senderState          = scSender.FullNode.NodeService <ContractStateRepositoryRoot>();
                receiverState        = scReceiver.FullNode.NodeService <ContractStateRepositoryRoot>();
                tokenContractAddress = addressGenerator.GenerateAddress(transferContractTransaction.GetHash(), 0);
                Assert.NotNull(senderState.GetCode(tokenContractAddress));
                Assert.NotNull(receiverState.GetCode(tokenContractAddress));
                scSender.FullNode.MempoolManager().Clear();

                // Create a call contract transaction which will transfer funds
                contractCarrier = SmartContractCarrier.CallContract(1, tokenContractAddress, "Test", gasPrice, gasLimit);
                Script contractCallScript = new Script(contractCarrier.Serialize());
                txBuildContext = new TransactionBuildContext(scSender.FullNode.Network)
                {
                    AccountReference = new WalletAccountReference(WalletName, AccountName),
                    MinConfirmations = maturity,
                    FeeType          = FeeType.High,
                    WalletPassword   = Password,
                    Recipients       = new[] { new Recipient {
                                                   Amount = 1000, ScriptPubKey = contractCallScript
                                               } }.ToList()
                };

                // Broadcast the token transaction to the network
                transferContractTransaction = (scSender.FullNode.NodeService <IWalletTransactionHandler>() as SmartContractWalletTransactionHandler).BuildTransaction(txBuildContext);
                scSender.FullNode.NodeService <IBroadcasterManager>().BroadcastTransactionAsync(transferContractTransaction);
                TestHelper.WaitLoop(() => scSender.CreateRPCClient().GetRawMempool().Length > 0);

                // Mine the transaction
                scSender.GenerateStratisWithMiner(1);

                // Ensure the nodes are synced
                TestHelper.WaitLoop(() => TestHelper.IsNodeSynced(scSender));
                TestHelper.WaitLoop(() => TestHelper.AreNodesSynced(scReceiver, scSender));

                // The balance should now reflect the transfer
                Assert.Equal((ulong)900, senderState.GetCurrentBalance(tokenContractAddress));
            }
        }
Exemplo n.º 25
0
 public ForEachBuilder(BuilderBase <TModel> builder, NodeBuilder attributeBuilder) : base(builder, attributeBuilder)
 {
 }
Exemplo n.º 26
0
        public void TestWithoutTor()
        {
            // Workaround for segwit not correctly activating
            Network.RegTest.Consensus.BIP9Deployments[BIP9Deployments.Segwit] = new BIP9DeploymentsParameters(1, 0, DateTime.Now.AddDays(50).ToUnixTimestamp());

            NodeBuilder builder = NodeBuilder.Create(version: "0.15.1");

            HttpClient client = null;

            var coreNode = GetCoreNode(builder);

            coreNode.Start();

            // Replicate portions of BreezeServer's Program.cs. Maybe refactor it into a class/function in future
            var serviceProvider = new ServiceCollection()
                                  .AddLogging()
                                  .AddSingleton <Breeze.BreezeServer.Services.ITumblerService, Breeze.BreezeServer.Services.TumblerService>()
                                  .BuildServiceProvider();

            serviceProvider
            .GetService <ILoggerFactory>()
            .AddConsole(LogLevel.Debug);

            // Skip the registration code - that can be tested separately

            string configPath = Path.Combine(coreNode.DataFolder, "breeze.conf");

            File.WriteAllLines(configPath, this.breezeServerConfig);

            BreezeConfiguration config = new BreezeConfiguration(configPath);

            var    coreRpc             = coreNode.CreateRPCClient();
            string ntbServerConfigPath = Path.Combine(coreNode.DataFolder, "server.config");

            File.WriteAllLines(ntbServerConfigPath, GetNTBServerConfig(coreRpc));

            // We need to start up the masternode prior to creating the SBFN instance so that
            // we have the URI available for starting the TumbleBit feature
            // TODO: Also need to see if NTB interactive console interferes with later parts of the test
            new Thread(delegate()
            {
                Thread.CurrentThread.IsBackground = true;
                // By instantiating the TumblerService directly the registration logic is skipped
                var tumbler = serviceProvider.GetService <Breeze.BreezeServer.Services.ITumblerService>();
                tumbler.StartTumbler(config, false, "server.config", Path.GetFullPath(coreNode.DataFolder), false);
            }).Start();

            // Wait for URI file to be written out by the TumblerService
            while (!File.Exists(Path.Combine(coreNode.DataFolder, "uri.txt")))
            {
                Thread.Sleep(1000);
            }

            Console.WriteLine("* URI file detected *");
            Thread.Sleep(5000);

            var serverAddress = File.ReadAllText(Path.Combine(coreNode.DataFolder, "uri.txt"));

            // Not used for this test
            ConfigurationOptionWrapper <object> registrationStoreDirectory = new ConfigurationOptionWrapper <object>("RegistrationStoreDirectory", "");

            // Force SBFN to connect to the server
            ConfigurationOptionWrapper <object> masternodeUri = new ConfigurationOptionWrapper <object>("MasterNodeUri", serverAddress);

            ConfigurationOptionWrapper <object>[] configurationOptions = { registrationStoreDirectory, masternodeUri };

            CoreNode node1 = builder.CreateStratisPowNode(true, fullNodeBuilder =>
            {
                fullNodeBuilder
                .UsePowConsensus()
                .UseBlockStore()
                .UseMempool()
                .UseBlockNotification()
                .UseTransactionNotification()
                .AddMining()
                .UseWallet()
                .UseWatchOnlyWallet()
                .UseApi()
                .AddRPC()
                .UseTumbleBit(configurationOptions);
            });

            // Logging for NTB client code
            ConsoleLoggerProcessor loggerProcessor = new ConsoleLoggerProcessor();

            Logs.Configure(new FuncLoggerFactory(i => new CustomerConsoleLogger(i, Logs.SupportDebug(true), false, loggerProcessor)), node1.DataFolder);

            var apiSettings = node1.FullNode.NodeService <ApiSettings>();

            // Create the source and destination wallets
            var wm1 = node1.FullNode.NodeService <IWalletManager>() as WalletManager;

            //var wm2 = node2.FullNode.NodeService<IWalletManager>() as WalletManager;
            wm1.CreateWallet("TumbleBit1", "alice");
            wm1.CreateWallet("TumbleBit1", "bob");

            // Mined coins only mature after 100 blocks on regtest
            // Additionally, we need to force Segwit to activate in order for NTB to work correctly
            coreRpc.Generate(450);

            var rpc1 = node1.CreateRPCClient();

            coreRpc.AddNode(node1.Endpoint, false);
            rpc1.AddNode(coreNode.Endpoint, false);

            var amount      = new Money(5.0m, MoneyUnit.BTC);
            var destination = wm1.GetUnusedAddress(new WalletAccountReference("alice", "account 0"));

            coreRpc.SendToAddress(BitcoinAddress.Create(destination.Address, Network.RegTest), amount);

            Console.WriteLine("Waiting for transaction to propagate and finalise");
            Thread.Sleep(5000);

            coreRpc.Generate(1);

            // Wait for SBFN to sync with the core node
            TestHelper.WaitLoop(() => rpc1.GetBestBlockHash() == coreRpc.GetBestBlockHash());

            // Test implementation note: the coins do not seem to immediately appear in the wallet.
            // This is possibly some sort of race condition between the wallet manager and block generation/sync.
            // This extra delay seems to ensure that the coins are definitely in the wallet by the time the
            // transaction count gets logged to the console below.

            // Wait instead of generating a block
            Thread.Sleep(5000);

            //var log = node1.FullNode.NodeService<ILogger>();
            Console.WriteLine("Number of wallet transactions: " + wm1.GetSpendableTransactionsInWallet("alice").Count());

            // Connect to server and start tumbling
            using (client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // Sample returned output
                // {"tumbler":"ctb://<onionaddress>.onion?h=<confighash>","denomination":"0.01000000","fee":"0.00010000","network":"RegTest","estimate":"22200"}

                var connectContent = new StringContent(new ConnectRequest {
                    OriginWalletName = "alice"
                }.ToString(), Encoding.UTF8, "application/json");
                var connectResponse = client.PostAsync(apiSettings.ApiUri + "api/TumbleBit/connect", connectContent).GetAwaiter().GetResult();
                var tumbleContent   = new StringContent(new TumbleRequest {
                    OriginWalletName = "alice", OriginWalletPassword = "******", DestinationWalletName = "bob"
                }.ToString(), Encoding.UTF8, "application/json");
                var tumbleResponse = client.PostAsync(apiSettings.ApiUri + "api/TumbleBit/tumble", tumbleContent).GetAwaiter().GetResult();

                // Note that the TB client takes about 30 seconds to completely start up, as it has to check the server parameters and
                // RSA key proofs

                //Assert.StartsWith("[{\"", tumbleResponse);
            }

            HdAccount alice;
            HdAccount bob;

            // TODO: Move forward specific numbers of blocks and check interim states? TB tests already do that
            for (int i = 0; i < 200; i++)
            {
                Console.WriteLine("Wallet balance height: " + node1.FullNode.Chain.Height);

                alice = wm1.GetWalletByName("alice").GetAccountByCoinType("account 0", (CoinType)Network.RegTest.Consensus.CoinType);

                Console.WriteLine("(A) Confirmed: " + alice.GetSpendableAmount().ConfirmedAmount.ToString());
                Console.WriteLine("(A) Unconfirmed: " + alice.GetSpendableAmount().UnConfirmedAmount.ToString());

                bob = wm1.GetWalletByName("bob").GetAccountByCoinType("account 0", (CoinType)Network.RegTest.Consensus.CoinType);

                Console.WriteLine("(B) Confirmed: " + bob.GetSpendableAmount().ConfirmedAmount.ToString());
                Console.WriteLine("(B) Unconfirmed: " + bob.GetSpendableAmount().UnConfirmedAmount.ToString());

                coreRpc.Generate(1);
                builder.SyncNodes();

                // Try to ensure the invalid phase error does not occur
                // (seems to occur when the server has not yet processed a new block and the client has)
                TestHelper.WaitLoop(() => rpc1.GetBestBlockHash() == coreRpc.GetBestBlockHash());

                var mempool   = node1.FullNode.NodeService <MempoolManager>();
                var mempoolTx = mempool.GetMempoolAsync().Result;
                if (mempoolTx.Count > 0)
                {
                    Console.WriteLine("--- Mempool contents ---");
                    foreach (var tx in mempoolTx)
                    {
                        var hex = mempool.GetTransaction(tx).Result;
                        Console.WriteLine(tx + " ->");
                        Console.WriteLine(hex);
                        Console.WriteLine("---");
                    }
                }

                Thread.Sleep(20000);
            }

            // Check destination wallet for tumbled coins

            // TODO: Need to amend TumblerService so that it can be shut down within the test

            if (client != null)
            {
                client.Dispose();
                client = null;
            }

            if (builder != null)
            {
                builder.Dispose();
            }
        }
 protected override void BeforeTest()
 {
     this.builder = NodeBuilder.Create(caller: this.CurrentTest.DisplayName);
 }
 private void BuildNode(WorkflowDefinitionBuilder workflowBuilder, NodeBuilder nodeBuilder, WorkflowDefinitionModel node)
 {
     nodeBuilder.BuildSubWorkflow(BuildWorkflowDefinition(workflowBuilder, node));
 }
Exemplo n.º 29
0
 protected override void BeforeTest()
 {
     this.nodeBuilder = NodeBuilder.Create(Path.Combine(this.GetType().Name, this.CurrentTest.DisplayName));
     this.network     = new BitcoinRegTest();
 }
Exemplo n.º 30
0
		public NodeBuilder CreateNode(string nodeName)
		{
			var node = new NodeBuilder(this, nodeName, _nodes.Count);
			_nodes.Add(node);
			return node;
		}
Exemplo n.º 31
0
		public void AddError(NodeBuilder node, string reason)
		{
			string errorMessage = node.Name + ": " + reason;
			_errors.Add(errorMessage);
		}
Exemplo n.º 32
0
        public void TestMultiClientWithoutTor(int numClients)
        {
            // Workaround for segwit not correctly activating
            Network.RegTest.Consensus.BIP9Deployments[BIP9Deployments.Segwit] = new BIP9DeploymentsParameters(1, 0, DateTime.Now.AddDays(50).ToUnixTimestamp());

            NodeBuilder builder = NodeBuilder.Create(version: "0.15.1");

            CoreNode coreNode = GetCoreNode(builder);

            coreNode.Start();

            // Replicate portions of BreezeServer's Program.cs. Maybe refactor it into a class/function in future
            var serviceProvider = new ServiceCollection()
                                  .AddLogging()
                                  .AddSingleton <Breeze.BreezeServer.Services.ITumblerService, Breeze.BreezeServer.Services.TumblerService>()
                                  .BuildServiceProvider();

            serviceProvider
            .GetService <ILoggerFactory>()
            .AddConsole(LogLevel.Debug);

            // Skip the registration code - that can be tested separately

            string configPath = Path.Combine(coreNode.DataFolder, "breeze.conf");

            File.WriteAllLines(configPath, this.breezeServerConfig);

            BreezeConfiguration config = new BreezeConfiguration(configPath);

            var    coreRpc             = coreNode.CreateRPCClient();
            string ntbServerConfigPath = Path.Combine(coreNode.DataFolder, "server.config");

            File.WriteAllLines(ntbServerConfigPath, GetNTBServerConfig(coreRpc));

            // We need to start up the masternode prior to creating the SBFN instance so that
            // we have the URI available for starting the TumbleBit feature
            // TODO: Also need to see if NTB interactive console interferes with later parts of the test
            new Thread(delegate()
            {
                Thread.CurrentThread.IsBackground = true;
                // By instantiating the TumblerService directly the registration logic is skipped
                var tumbler = serviceProvider.GetService <Breeze.BreezeServer.Services.ITumblerService>();
                tumbler.StartTumbler(config, false, "server.config", Path.GetFullPath(coreNode.DataFolder), false);
            }).Start();

            // Wait for URI file to be written out by the TumblerService
            while (!File.Exists(Path.Combine(coreNode.DataFolder, "uri.txt")))
            {
                Thread.Sleep(1000);
            }

            Console.WriteLine("* URI file detected *");
            Thread.Sleep(5000);

            var serverAddress = File.ReadAllText(Path.Combine(coreNode.DataFolder, "uri.txt"));

            // Not used for this test
            ConfigurationOptionWrapper <object> registrationStoreDirectory = new ConfigurationOptionWrapper <object>("RegistrationStoreDirectory", "");

            // Force SBFN to use the temporary hidden service to connect to the server
            ConfigurationOptionWrapper <object> masternodeUri = new ConfigurationOptionWrapper <object>("MasterNodeUri", serverAddress);

            ConfigurationOptionWrapper <object>[] configurationOptions = { registrationStoreDirectory, masternodeUri };

            List <CoreNode> clientNodes = new List <CoreNode>();

            int apiPortNum = 37229;

            for (int i = 0; i < numClients; i++)
            {
                var temp = builder.CreateStratisPowNode(false, fullNodeBuilder =>
                {
                    fullNodeBuilder
                    .UsePowConsensus()
                    .UseBlockStore()
                    .UseMempool()
                    .UseBlockNotification()
                    .UseTransactionNotification()
                    .AddMining()
                    .UseWallet()
                    .UseWatchOnlyWallet()
                    .UseApi()
                    .AddRPC()
                    .UseTumbleBit(configurationOptions);
                });

                temp.ConfigParameters.AddOrReplace("apiuri", $"http://localhost:{apiPortNum}");

                clientNodes.Add(temp);

                apiPortNum++;
            }

            foreach (var node in clientNodes)
            {
                node.Start();
            }

            // Create the source and destination wallets for nodes
            for (int i = 0; i < numClients; i++)
            {
                var wm1 = clientNodes[i].FullNode.NodeService <IWalletManager>() as WalletManager;
                wm1.CreateWallet("TumbleBit1", $"alice{i}");
                wm1.CreateWallet("TumbleBit1", $"bob{i}");
            }

            // Mined coins only mature after 100 blocks on regtest
            // Additionally, we need to force Segwit to activate in order for NTB to work correctly
            coreRpc.Generate(450);

            while (coreRpc.GetBlockCount() < 450)
            {
                Thread.Sleep(100);
            }

            for (int i = 0; i < numClients; i++)
            {
                coreRpc.AddNode(clientNodes[i].Endpoint, false);
                var rpc = clientNodes[i].CreateRPCClient();
                rpc.AddNode(coreNode.Endpoint, false);

                for (int j = 0; j < numClients; j++)
                {
                    if (i != j)
                    {
                        rpc.AddNode(clientNodes[j].Endpoint, false);
                    }
                }
            }

            for (int i = 0; i < numClients; i++)
            {
                var wm1          = clientNodes[i].FullNode.NodeService <IWalletManager>() as WalletManager;
                var destination1 = wm1.GetUnusedAddress(new WalletAccountReference($"alice{i}", "account 0"));
                coreRpc.SendToAddress(BitcoinAddress.Create(destination1.Address, Network.RegTest), new Money(5.0m, MoneyUnit.BTC));
            }

            clientNodes[0].FullNode.Settings.Logger.LogInformation("Waiting for transactions to propagate and finalise");
            Thread.Sleep(5000);

            coreRpc.Generate(1);

            // Wait for SBFN clients to sync with the core node
            foreach (var node in clientNodes)
            {
                TestHelper.WaitLoop(() => node.CreateRPCClient().GetBestBlockHash() == coreRpc.GetBestBlockHash());
            }

            // Test implementation note: the coins do not seem to immediately appear in the wallet.
            // This is possibly some sort of race condition between the wallet manager and block generation/sync.
            // This extra delay seems to ensure that the coins are definitely in the wallet by the time the
            // transaction count gets logged to the console below.

            // Wait instead of generating a block
            Thread.Sleep(5000);

            for (int i = 0; i < numClients; i++)
            {
                var wm1 = clientNodes[i].FullNode.NodeService <IWalletManager>() as WalletManager;
                //logger1.LogError($"({i}) Number of wallet transactions: " + wm1.GetSpendableTransactionsInWallet($"alice{i}").Count());

                // Connect each client to server and start tumbling
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var apiSettings1   = clientNodes[i].FullNode.NodeService <ApiSettings>();
                    var connectContent = new StringContent(new ConnectRequest {
                        OriginWalletName = $"alice{i}"
                    }.ToString(), Encoding.UTF8, "application/json");
                    var connectResponse = client.PostAsync(apiSettings1.ApiUri + "api/TumbleBit/connect", connectContent).GetAwaiter().GetResult();
                    var tumbleContent   = new StringContent(new TumbleRequest {
                        OriginWalletName = $"alice{i}", OriginWalletPassword = "******", DestinationWalletName = $"bob{i}"
                    }.ToString(), Encoding.UTF8, "application/json");
                    var tumbleResponse = client.PostAsync(apiSettings1.ApiUri + "api/TumbleBit/tumble", tumbleContent).GetAwaiter().GetResult();

                    // Note that the TB client takes about 30 seconds to completely start up, as it has to check the server parameters and RSA key proofs
                }

                clientNodes[i].FullNode.Settings.Logger.LogInformation($"Client ({i}) About to start tumbling loop");
            }

            while (true)
            {
                for (int i = 0; i < numClients; i++)
                {
                    clientNodes[i].FullNode.Settings.Logger.LogInformation($"Wallet {i} balance height: " + clientNodes[i].FullNode.Chain.Height);

                    var wm1 = clientNodes[i].FullNode.NodeService <IWalletManager>() as WalletManager;

                    HdAccount alice1 = wm1.GetWalletByName($"alice{i}").GetAccountByCoinType("account 0", (CoinType)Network.RegTest.Consensus.CoinType);

                    clientNodes[i].FullNode.Settings.Logger.LogInformation($"(A{i}) Confirmed: " + alice1.GetSpendableAmount().ConfirmedAmount.ToString());
                    clientNodes[i].FullNode.Settings.Logger.LogInformation($"(A{i}) Unconfirmed: " + alice1.GetSpendableAmount().UnConfirmedAmount.ToString());

                    HdAccount bob1 = wm1.GetWalletByName($"bob{i}").GetAccountByCoinType("account 0", (CoinType)Network.RegTest.Consensus.CoinType);

                    clientNodes[i].FullNode.Settings.Logger.LogInformation($"(B{i}) Confirmed: " + bob1.GetSpendableAmount().ConfirmedAmount.ToString());
                    clientNodes[i].FullNode.Settings.Logger.LogInformation($"(B{i}) Unconfirmed: " + bob1.GetSpendableAmount().UnConfirmedAmount.ToString());

                    clientNodes[i].FullNode.Settings.Logger.LogInformation("===");
                }

                coreRpc.Generate(1);

                // Try to ensure the invalid phase error does not occur
                // (seems to occur when the server has not yet processed a new block and the client has)
                //TestHelper.WaitLoop(() => rpc1.GetBestBlockHash() == coreRpc.GetBestBlockHash());
                //TestHelper.WaitLoop(() => rpc2.GetBestBlockHash() == coreRpc.GetBestBlockHash());

                /*var mempool = node1.FullNode.NodeService<MempoolManager>();
                 * var mempoolTx = mempool.GetMempoolAsync().Result;
                 * if (mempoolTx.Count > 0)
                 * {
                 *  Console.WriteLine("--- Mempool contents ---");
                 *  foreach (var tx in mempoolTx)
                 *  {
                 *      var hex = mempool.GetTransaction(tx).Result;
                 *      Console.WriteLine(tx + " ->");
                 *      Console.WriteLine(hex);
                 *      Console.WriteLine("---");
                 *  }
                 * }*/

                Thread.Sleep(20000);
            }

            if (builder != null)
            {
                builder.Dispose();
            }
        }
Exemplo n.º 33
0
		internal UINode(UITask task, NodeBuilder nodeBuilder)
		{
			Task = Verify.ArgumentNotNull(task, "task");
			NodeBuilder = Verify.ArgumentNotNull(nodeBuilder, "nodeBuilder");
		}
Exemplo n.º 34
0
        public void SendAndReceiveSmartContractTransactionsOnPosNetwork()
        {
            using (NodeBuilder builder = NodeBuilder.Create(this))
            {
                CoreNode scSender   = builder.CreateSmartContractPosNode();
                CoreNode scReceiver = builder.CreateSmartContractPosNode();

                builder.StartAll();

                scSender.NotInIBD();
                scReceiver.NotInIBD();

                scSender.FullNode.WalletManager().CreateWallet(Password, WalletName, Passphrase);
                scReceiver.FullNode.WalletManager().CreateWallet(Password, WalletName, Passphrase);

                var       maturity      = (int)scSender.FullNode.Network.Consensus.CoinbaseMaturity;
                HdAddress senderAddress = TestHelper.MineBlocks(scSender, WalletName, Password, AccountName, maturity + 5).AddressUsed;

                // Wait for block repo for block sync to work.
                TestHelper.WaitLoop(() => TestHelper.IsNodeSynced(scSender));

                // The mining should add coins to the wallet.
                var total = scSender.FullNode.WalletManager().GetSpendableTransactionsInWallet(WalletName).Sum(s => s.Transaction.Amount);
                Assert.Equal(Money.COIN * 6 * 50, total);

                // Create a token contract
                ulong gasPrice  = 1;
                int   vmVersion = 1;
                Gas   gasLimit  = (Gas)5000;
                ContractCompilationResult compilationResult = ContractCompiler.CompileFile("SmartContracts/TransferTestPos.cs");
                Assert.True(compilationResult.Success);

                var contractCarrier = ContractCarrier.CreateContract(vmVersion, compilationResult.Compilation, gasPrice, gasLimit);

                var contractCreateScript = new Script(contractCarrier.Serialize());
                var txBuildContext       = new TransactionBuildContext(scSender.FullNode.Network)
                {
                    AccountReference = new WalletAccountReference(WalletName, AccountName),
                    ChangeAddress    = senderAddress,
                    MinConfirmations = maturity,
                    FeeType          = FeeType.High,
                    WalletPassword   = Password,
                    Recipients       = new[] { new Recipient {
                                                   Amount = 0, ScriptPubKey = contractCreateScript
                                               } }.ToList()
                };

                // Build the transfer contract transaction
                var transferContractTransaction = BuildTransferContractTransaction(scSender, txBuildContext);

                // Add the smart contract transaction to the mempool to be mined.
                scSender.AddToStratisMempool(transferContractTransaction);

                // Ensure the smart contract transaction is in the mempool.
                TestHelper.WaitLoop(() => scSender.CreateRPCClient().GetRawMempool().Length > 0);

                // Mine the token transaction and wait for it sync
                scSender.GenerateStratisWithMiner(1);
                TestHelper.WaitLoop(() => TestHelper.IsNodeSynced(scSender));

                // Sync to the receiver node
                scSender.CreateRPCClient().AddNode(scReceiver.Endpoint, true);
                TestHelper.WaitLoop(() => TestHelper.AreNodesSynced(scReceiver, scSender));

                // Ensure that boths nodes has the contract
                IStateRepositoryRoot senderState      = scSender.FullNode.NodeService <IStateRepositoryRoot>();
                IStateRepositoryRoot receiverState    = scReceiver.FullNode.NodeService <IStateRepositoryRoot>();
                IAddressGenerator    addressGenerator = scSender.FullNode.NodeService <IAddressGenerator>();

                uint160 tokenContractAddress = addressGenerator.GenerateAddress(transferContractTransaction.GetHash(), 0);
                Assert.NotNull(senderState.GetCode(tokenContractAddress));
                Assert.NotNull(receiverState.GetCode(tokenContractAddress));
                scSender.FullNode.MempoolManager().Clear();

                // Create a transfer token contract
                compilationResult = ContractCompiler.CompileFile("SmartContracts/TransferTestPos.cs");
                Assert.True(compilationResult.Success);
                contractCarrier      = ContractCarrier.CreateContract(vmVersion, compilationResult.Compilation, gasPrice, gasLimit);
                contractCreateScript = new Script(contractCarrier.Serialize());
                txBuildContext       = new TransactionBuildContext(scSender.FullNode.Network)
                {
                    AccountReference = new WalletAccountReference(WalletName, AccountName),
                    ChangeAddress    = senderAddress,
                    MinConfirmations = maturity,
                    FeeType          = FeeType.High,
                    WalletPassword   = Password,
                    Recipients       = new[] { new Recipient {
                                                   Amount = 0, ScriptPubKey = contractCreateScript
                                               } }.ToList()
                };

                // Build the transfer contract transaction
                transferContractTransaction = BuildTransferContractTransaction(scSender, txBuildContext);

                // Add the smart contract transaction to the mempool to be mined.
                scSender.AddToStratisMempool(transferContractTransaction);

                // Wait for the token transaction to be picked up by the mempool
                TestHelper.WaitLoop(() => scSender.CreateRPCClient().GetRawMempool().Length > 0);
                scSender.GenerateStratisWithMiner(1);

                // Ensure the node is synced
                TestHelper.WaitLoop(() => TestHelper.IsNodeSynced(scSender));

                // Ensure both nodes are synced with each other
                TestHelper.WaitLoop(() => TestHelper.AreNodesSynced(scReceiver, scSender));

                tokenContractAddress = addressGenerator.GenerateAddress(transferContractTransaction.GetHash(), 0); // nonce is 0 for user contract creation.
                Assert.NotNull(senderState.GetCode(tokenContractAddress));
                Assert.NotNull(receiverState.GetCode(tokenContractAddress));
                scSender.FullNode.MempoolManager().Clear();

                // Create a call contract transaction which will transfer funds
                contractCarrier = ContractCarrier.CallContract(1, tokenContractAddress, "Test", gasPrice, gasLimit);
                Script contractCallScript = new Script(contractCarrier.Serialize());
                txBuildContext = new TransactionBuildContext(scSender.FullNode.Network)
                {
                    AccountReference = new WalletAccountReference(WalletName, AccountName),
                    ChangeAddress    = senderAddress,
                    MinConfirmations = maturity,
                    FeeType          = FeeType.High,
                    WalletPassword   = Password,
                    Recipients       = new[] { new Recipient {
                                                   Amount = 1000, ScriptPubKey = contractCallScript
                                               } }.ToList()
                };

                // Build the transfer contract transaction
                var callContractTransaction = BuildTransferContractTransaction(scSender, txBuildContext);

                // Add the smart contract transaction to the mempool to be mined.
                scSender.AddToStratisMempool(callContractTransaction);

                // Wait for the token transaction to be picked up by the mempool
                TestHelper.WaitLoop(() => scSender.CreateRPCClient().GetRawMempool().Length > 0);
                scSender.GenerateStratisWithMiner(1);

                // Ensure the nodes are synced
                TestHelper.WaitLoop(() => TestHelper.IsNodeSynced(scSender));
                TestHelper.WaitLoop(() => TestHelper.AreNodesSynced(scReceiver, scSender));

                // The balance should now reflect the transfer
                Assert.Equal((ulong)900, senderState.GetCurrentBalance(tokenContractAddress));
            }
        }
Exemplo n.º 35
0
 public TransitionBuilder(NodeBuilder parentNodeBuilder, string source)
 {
     this.parentNodeBuilder = parentNodeBuilder;
     this.source = source;
 }
Exemplo n.º 36
0
        static void Main(string[] args)
        {
            var builder = NodeBuilder.Create(version: "0.13.1");

            builder.CreateNode(true);
        }
 private void BuildNode(WorkflowDefinitionBuilder workflowBuilder, NodeBuilder nodeBuilder, NodeModel node)
 {
     nodeBuilder.BuildNode();
 }