public GoodsBuyedEvent BuyGoods(IReadOnlyCollection<Coin> depositedAmount, GoodsIdentity goods)
        {
            Contract.Requires(depositedAmount != null);

            var availableGoods = _availableGoods.Retrieve(goods);
            var depositWallet = new Wallet(depositedAmount);
            var depositTotal = depositWallet.TotalFunds();

            if (depositTotal < availableGoods.Price)
            {
                throw new InsufficientAmountForBuyingGoodsException(availableGoods.Price, depositTotal, goods);
            }

            var refundAmount = depositTotal - availableGoods.Price;
            _vendingMachineWallet = _vendingMachineWallet.Put(depositedAmount);
            _buyerWallet = _buyerWallet.Retrieve(depositedAmount);

            var refundCoins = Refund(refundAmount);
            var refundWallet = new Wallet(refundCoins);

            if (refundWallet.TotalFunds() != refundAmount)
            {
                throw new VendingMachineDoesNotHaveCoinsForRefundException(_vendingMachineWallet, refundAmount);
            }

            _vendingMachineWallet = _vendingMachineWallet.Retrieve(refundCoins);
            _buyerWallet = _buyerWallet.Put(refundCoins);

            return new GoodsBuyedEvent(_vendingMachineWallet, _buyerWallet, availableGoods, refundCoins);
        }
        public void Refund_WhenBuyerWantsRefundDepositedAmount_ThenVendingMachineShouldRefundWithLessCoins(
            Wallet machineWallet,
            Wallet buyerWallet,
            IReadOnlyCollection<Coin> depositedAmount,
            Wallet expectedMachineWallet,
            Wallet expectedBuyerWallet)
        {
            var vendingMachine = CreateMachine(machineWallet, buyerWallet);

            var @event = vendingMachine.Refund(depositedAmount);
            var refundedMachineWallet = @event.VendingMachineWallet;
            var refundedBuyerWallet = @event.BuyerWallet;

            if (!expectedMachineWallet.Any())
            {
                Assert.True(!refundedMachineWallet.Any());
            }
            else
            {
                var expectedBuyerWalletMatch = !expectedBuyerWallet
                    .Except(refundedBuyerWallet)
                    .Any();

                Assert.True(expectedBuyerWalletMatch);
            }

            var expectedMachineWalletMatch = !expectedMachineWallet
                .Except(refundedMachineWallet)
                .Any();

            Assert.True(expectedMachineWalletMatch);
        }
        /// <summary>
        ///     Validates wallet
        /// </summary>
        /// <param name="wallet">Wallet to validate</param>
        /// <returns>True if wallet is valid, false otherwise</returns>
        public void Validate(Wallet wallet)
        {
            if (wallet == null)
                throw new ArgumentNullException(nameof(wallet));

            this._validator.ValidateAndThrowCustomException(wallet);
        }
 public void SetUp()
 {
     _wallet = new Wallet(_params);
     _blockStore = new MemoryBlockStore(_params);
     var chain = new BlockChain(_params, _wallet, _blockStore);
     _peerGroup = new PeerGroup(_blockStore, _params, chain);
 }
        public void UnexistedCoinPopShouldThrownAnException()
        {
            var wallet = new Wallet();

            try
            {
                wallet.Pop(new Coin(1));
                Assert.Fail("InvalidOperationException is expected");
            }
            catch (InvalidOperationException) { }

            wallet.Push(new Coin(2));
            try
            {
                wallet.Pop(new Coin(1));
                Assert.Fail("InvalidOperationException is expected");
            }
            catch (InvalidOperationException) { }

            wallet.Push(new Coin(1, new RegionInfo("UA")));
            try
            {
                wallet.Pop(new Coin(1));
                Assert.Fail("InvalidOperationException is expected");
            }
            catch (InvalidOperationException) { }
        }
        public void WhenBuyGoodsWithSufficientAmount_AndDepositGreaterThanGoodsPrice_ThenVendingMachineGiveBuyerRefunds(
            Wallet givenMachineWallet,
            Wallet givenBuyerWallet,
            IList<Goods> availableGoods,
            IReadOnlyCollection<Coin> depositedAmount,
            Goods buyedGoods,
            Wallet expectedMachineWallet,
            Wallet expectedBuyerWallet,
            IReadOnlyCollection<Coin> refund)
        {
            var vendingMachine = CreateMachine(givenMachineWallet, givenBuyerWallet, availableGoods);

            var @event = vendingMachine.BuyGoods(depositedAmount, buyedGoods.Identity);
            var updatedMachineWallet = @event.UpdatedMachineWallet
                .ShowCoins()
                .OrderBy(x => x.ParValue);
            var updatedBuyerWallet = @event.UpdatedBuyerWallet
                .ShowCoins()
                .OrderBy(x => x.ParValue);
            var buyerRefund = @event.Refunds;

            Assert.Equal(refund.OrderBy(x => x.ParValue), buyerRefund.OrderBy(x => x.ParValue));
            Assert.Equal(expectedMachineWallet.ShowCoins().OrderBy(x => x.ParValue), updatedMachineWallet);
            Assert.Equal(expectedBuyerWallet.ShowCoins().OrderBy(x => x.ParValue), updatedBuyerWallet);
        }
		public override async void WindowDidLoad() {
			sendButton.Enabled = false;

			var walletFile = (FileInfo)Wallet.DefaultWalletFile;
			if(walletFile.Exists)
				wallet = await Wallet.LoadAsync();
			else
				wallet = await CreateWallet(walletFile);

			if(wallet == null)
				NSApplication.SharedApplication.Terminate(this);

			wallet.DidLock += (sender, e) => LockToggled();
			wallet.DidUnlock += (sender, e) => LockToggled();

			transactionTableData = new TransactionTableData();
			transactionTable.DataSource = transactionTableData.DataSource;
			transactionTable.Delegate = transactionTableData.Delegate;

			Task balance = UpdateBalanceAsync();
			Task history = UpdateHistoryAsync();

			LockToggled();

			await balance;
			await history;
		}
        public CoinsRefundedEvent(Wallet machineWallet, Wallet buyerWallet)
        {
            Contract.Requires(machineWallet != null);
            Contract.Requires(buyerWallet != null && buyerWallet.ShowCoins().Count > 0);

            VendingMachineWallet = machineWallet;
            BuyerWallet = buyerWallet;
        }
        public void Refund_WhenBuyerWantsRefundZeroAmount_ThenVendingMachineShouldThrowNoDepositForRefundException()
        {
            var machineWallet = new Wallet();
            var buyerWallet = new Wallet();
            var vendingMachine = CreateMachine(machineWallet, buyerWallet);

            Assert.Throws<NoDepositForRefundException>(() => vendingMachine.Refund(Enumerable.Empty<Coin>().ToList()));
        }
 internal void UpdateWallet(Wallet wallet)
 {
     this.wallet = wallet;
     foreach (buttonLabel bl in this.Controls)
     {
         bl.setData(this.wallet.CoinByValue(bl.getData().value));
     }
 }
Exemple #11
0
 public void SetUp()
 {
     var myKey = new EcKey();
     _myAddress = myKey.ToAddress(_params);
     _wallet = new Wallet(_params);
     _wallet.AddKey(myKey);
     _blockStore = new MemoryBlockStore(_params);
 }
        public void Retrieve_WhenInsufficientFundsInWalletForGivenPar_ThenShouldThrowDoesNotHaveFundsException(int parValue, int coinCount)
        {
            var coin = new Coin(parValue, coinCount);
            var inWalletCoinCount = new Random().Next(1, coinCount - 1);
            var inWalletCoin = new Coin(parValue, inWalletCoinCount);
            var wallet = new Wallet(new [] {inWalletCoin});

            Assert.Throws<InsufficientFundsWithParValueException>(() => wallet.Retrieve(coin));
        }
        public VendingMachineDoesNotHaveCoinsForRefundException(Wallet machineWallet, decimal refundAmount)
            : base(string.Format("Vending Machine does not have coins for refund. Wallet total: {0}. Refund amount: {1}", machineWallet.TotalFunds(), refundAmount))
        {
            Contract.Requires(machineWallet != null);
            Contract.Requires(refundAmount > decimal.Zero);

            MachineWallet = machineWallet;
            RefundAmount = refundAmount;
        }
        public VendingMachine(Wallet vendingMachineWallet, Wallet buyerWallet, IList<Goods> availableGoods)
        {
            Contract.Requires(vendingMachineWallet != null);
            Contract.Requires(buyerWallet != null);
            Contract.Requires(availableGoods != null);

            _vendingMachineWallet = vendingMachineWallet;
            _buyerWallet = buyerWallet;
            _availableGoods = new BagOfGoods(availableGoods);
        }
 public void SetUp()
 {
     _unitTestParams = NetworkParameters.UnitTests();
     _wallet = new Wallet(_unitTestParams);
     _wallet.AddKey(new EcKey());
     _chainBlockStore = new MemoryBlockStore(_unitTestParams);
     _chain = new BlockChain(_unitTestParams, _wallet, _chainBlockStore);
     _coinbaseTo = _wallet.Keychain[0].ToAddress(_unitTestParams);
     _someOtherGuy = new EcKey().ToAddress(_unitTestParams);
 }
        public void WhenInitializeWalletWithRepeatedParValueCoins_ThenWalletShouldContainSumCoinsForGivenParValue(
            Coin[] inputCoins,
            Coin[] expectedCoins)
        {
            var wallet = new Wallet(inputCoins);

            foreach (var actualCoin in wallet.ShowCoins())
            {
                Assert.True(expectedCoins.Count(c => c.ParValue == actualCoin.ParValue && c.Count == actualCoin.Count) == 1);
            }
        }
Exemple #17
0
 public bool MakeItRain(int sB, Wallet otherPerson)
 {
     if (sB > spaceBux && player)
         return false;
     else
     {
     otherPerson.Reward(sB);
     spaceBux -= sB;
         return true;
     }
 }
        /// <summary>Creates a new instance of Poloniex API .NET's client service.</summary>
        /// <param name="publicApiKey">Your public API key.</param>
        /// <param name="privateApiKey">Your private API key.</param>
        public PoloniexClient(string publicApiKey, string privateApiKey)
        {
            var apiWebClient = new ApiWebClient(Helper.ApiUrlHttpsBase);

            Authenticator = new Authenticator(apiWebClient, publicApiKey, privateApiKey);

            Markets = new Markets(apiWebClient);
            Trading = new Trading(apiWebClient);
            Wallet = new Wallet(apiWebClient);
            Live = new Live();
        }
        public void WhenPutCoinInEmptyWallet_ThenCoinShouldBeInGivenWallet(int parValue, int coinCount)
        {
            var coin = new Coin(parValue, coinCount);
            var wallet = new Wallet();

            var walletCoins = wallet
                .Put(coin)
                .ShowCoins();

            Assert.True(walletCoins.Count == 1);
            Assert.True(walletCoins.Single().Equals(coin));
        }
Exemple #20
0
		public static int Main(string[] args) {
			FileInfo file = (FileInfo)Wallet.DefaultWalletFile;
			Wallet = Wallet.LoadAsync(file).Result;

			while(true) {
				Console.Write("{0} > ", Wallet.IsLocked ? "locked  " : "unlocked");
				int? statusCode = ProcessCommand(Console.ReadLine()).Result;

				if(statusCode.HasValue)
					return statusCode.Value;
			}
		}
        public void Retrieve_WhenWalletDoesNotHaveCoinsForGivenPar_ThenShouldThrowDoesNotHaveCoinException(
            int parValue, 
            int coinCount, 
            int inWalletCoinPar)
        {
            var coin = new Coin(parValue, coinCount);
            var inWalletCoinCount = new Random().Next(1, coinCount - 1);
            var inWalletCoin = new Coin(inWalletCoinPar, inWalletCoinCount);
            var wallet = new Wallet(new [] {inWalletCoin});

            Assert.Throws<WalletDoesNotHaveCoinsForParValueException>(() => wallet.Retrieve(coin));
        }
Exemple #22
0
        public static void Run(string[] args)
        {
            // TODO: Assumes production network not testnet. Make it selectable.
            var networkParams = NetworkParameters.ProdNet();
            try
            {
                // Decode the private key from Satoshi's Base58 variant. If 51 characters long then it's from BitCoins
                // "dumpprivkey" command and includes a version byte and checksum. Otherwise assume it's a raw key.
                EcKey key;
                if (args[0].Length == 51)
                {
                    var dumpedPrivateKey = new DumpedPrivateKey(networkParams, args[0]);
                    key = dumpedPrivateKey.Key;
                }
                else
                {
                    var privKey = Base58.DecodeToBigInteger(args[0]);
                    key = new EcKey(privKey);
                }
                Console.WriteLine("Address from private key is: " + key.ToAddress(networkParams));
                // And the address ...
                var destination = new Address(networkParams, args[1]);

                // Import the private key to a fresh wallet.
                var wallet = new Wallet(networkParams);
                wallet.AddKey(key);

                // Find the transactions that involve those coins.
                using (var blockStore = new MemoryBlockStore(networkParams))
                {
                    var chain = new BlockChain(networkParams, wallet, blockStore);

                    var peerGroup = new PeerGroup(blockStore, networkParams, chain);
                    peerGroup.AddAddress(new PeerAddress(IPAddress.Loopback));
                    peerGroup.Start();
                    peerGroup.DownloadBlockChain();
                    peerGroup.Stop();

                    // And take them!
                    Console.WriteLine("Claiming " + Utils.BitcoinValueToFriendlystring(wallet.GetBalance()) + " coins");
                    wallet.SendCoins(peerGroup, destination, wallet.GetBalance());
                    // Wait a few seconds to let the packets flush out to the network (ugly).
                    Thread.Sleep(5000);
                }
            }
            catch (IndexOutOfRangeException)
            {
                Console.WriteLine("First arg should be private key in Base58 format. Second argument should be address to send to.");
            }
        }
 public BetfairServerResponse<AccountStatementReport> GetAccountStatement(
     int? fromRecord = null,
     int? recordCount = null,
     TimeRange itemDateRange = null,
     IncludeItem? includeItem = null,
     Wallet? wallet = null)
 {
     return client.GetAccountStatement(
         fromRecord,
         recordCount,
         itemDateRange,
         includeItem,
         wallet).Result;
 }
        public void WhenBuyGoodsWithInsufficientAmount_AndGoodsAvailableInMachine_ThenVendingMachineShouldThrowInsufficientAmountException(
            Wallet givenMachineWallet,
            Wallet givenBuyerWallet,
            IList<Goods> availableGoods,
            IReadOnlyCollection<Coin> depositedAmount,
            Goods buyedGoods)
        {
            var vendingMachine = CreateMachine(givenMachineWallet, givenBuyerWallet, availableGoods);

            var ex = Assert.Throws<InsufficientAmountForBuyingGoodsException>(() => vendingMachine.BuyGoods(depositedAmount, buyedGoods.Identity));
            var depositedWallet = new Wallet(depositedAmount);

            Assert.True(ex.Goods.Equals(buyedGoods.Identity));
            Assert.True(ex.ActualFunds == depositedWallet.TotalFunds());
            Assert.True(ex.ExpectedFunds == buyedGoods.Price);
        }
        public GoodsBuyedEvent(
            Wallet vendingMachineWallet, 
            Wallet buyerWallet, 
            Goods buyedGoods,
            IReadOnlyCollection<Coin> refunds)
        {
            Contract.Requires(vendingMachineWallet != null && vendingMachineWallet.ShowCoins().Any());
            Contract.Requires(buyerWallet != null);
            Contract.Requires(refunds != null);
            Contract.Requires(refunds.Count == 0 || refunds.Any() && buyerWallet.ShowCoins().Any());

            UpdatedMachineWallet = vendingMachineWallet;
            UpdatedBuyerWallet = buyerWallet;
            BuyedGoods = buyedGoods;
            Refunds = refunds;
        }
        public CoinsRefundedEvent Refund(IReadOnlyCollection<Coin> depositedAmount)
        {
            Contract.Requires(depositedAmount != null);
            if (!depositedAmount.Any())
            {
                throw new NoDepositForRefundException();
            }
            Contract.Ensures(Contract.Result<CoinsRefundedEvent>() != null);
            Contract.EndContractBlock();

            var total = depositedAmount.Aggregate(decimal.Zero, (current, coin) => current + coin.Total);
            _vendingMachineWallet = _vendingMachineWallet.Put(depositedAmount);
            _buyerWallet = _buyerWallet.Retrieve(depositedAmount);

            var refundCoins = Refund(total);

            _vendingMachineWallet = _vendingMachineWallet.Retrieve(refundCoins);
            _buyerWallet = _buyerWallet.Put(refundCoins);

            return new CoinsRefundedEvent(_vendingMachineWallet, _buyerWallet);
        }
        public void GetCoinsAmountShouldProvideCorrectResult()
        {
            var wallet = new Wallet();

            var result = wallet.GetCoinsAmount();
            Assert.AreEqual(0, result.Count, "Empty dictionary is expected");

            wallet.Push(new Coin(1));
            result = wallet.GetCoinsAmount();
            Assert.AreEqual(1, result.Count, "Invalid result is provided for single coin");

            wallet.Push(new Coin(1));
            wallet.Push(new Coin(2));
            wallet.Push(new Coin(2));
            wallet.Pop(new Coin(1));

            var expectedCoin = new Coin(1);
            result = wallet.GetCoinsAmount();
            Assert.AreEqual(2, result.Count);
            Assert.AreEqual(1, result[expectedCoin], "Invalid {0} coins amount", expectedCoin);

            expectedCoin = new Coin(2);
            Assert.AreEqual(2, result[expectedCoin], "Invalid {0} coins amount", expectedCoin);
        }
        private async static Task<OrderId> ClosePosition(CryptsyExchange cryptsy, Market market, Wallet wallet)
        {
            // Get the market depth to determine best available price
            Book book = await cryptsy.GetMarketDepth(market.MarketId);
            decimal price;

            if (book.Bids.Count > 0)
            {
                price = book.Bids[0].Price;
            }
            else if (book.Asks.Count > 0)
            {
                price = book.Asks[0].Price;
            }
            else
            {
                List<MarketTrade> recentTrades = await cryptsy.GetMarketTrades(market.MarketId);

                price = recentTrades[0].Price;
            }

            return await cryptsy.CreateOrder(market.MarketId, OrderType.Sell,
                wallet.Balance, price);
        }
Exemple #29
0
        internal async Task RunAsync(string walletName, string destinationWalletName, bool keepMixAlive)
        {
            try
            {
                Logger.LogSoftwareStarted("Wasabi Daemon");

                KeyManager keyManager = TryGetKeyManagerFromWalletName(walletName);
                if (keyManager is null)
                {
                    return;
                }

                string password = null;
                var    count    = 3;
                string compatibilityPassword = null;
                do
                {
                    if (password != null)
                    {
                        if (count > 0)
                        {
                            Logger.LogError($"Wrong password. {count} attempts left. Try again.");
                        }
                        else
                        {
                            Logger.LogCritical($"Wrong password. {count} attempts left. Exiting...");
                            return;
                        }
                        count--;
                    }
                    Console.Write("Password: "******"Correct password.");

                await Global.InitializeNoWalletAsync();

                if (Global.KillRequested)
                {
                    return;
                }

                Wallet = await Global.WalletManager.CreateAndStartWalletAsync(keyManager);

                if (Global.KillRequested)
                {
                    return;
                }

                KeyManager destinationKeyManager           = TryGetKeyManagerFromWalletName(destinationWalletName);
                bool       isDifferentDestinationSpecified = keyManager.ExtPubKey != destinationKeyManager.ExtPubKey;
                if (isDifferentDestinationSpecified)
                {
                    await Global.WalletManager.CreateAndStartWalletAsync(destinationKeyManager);
                }

                do
                {
                    if (Global.KillRequested)
                    {
                        break;
                    }

                    // If no coins enqueued then try to enqueue the large anonset coins and mix to another wallet.
                    if (isDifferentDestinationSpecified && !AnyCoinsQueued())
                    {
                        Wallet.ChaumianClient.DestinationKeyManager = destinationKeyManager;
                        await TryQueueCoinsToMixAsync(password, minAnonset : Wallet.ServiceConfiguration.MixUntilAnonymitySet);
                    }

                    if (Global.KillRequested)
                    {
                        break;
                    }

                    // If no coins were enqueued then try to enqueue coins those have less anonset and mix into the same wallet.
                    if (!AnyCoinsQueued())
                    {
                        Wallet.ChaumianClient.DestinationKeyManager = Wallet.ChaumianClient.KeyManager;
                        await TryQueueCoinsToMixAsync(password, maxAnonset : Wallet.ServiceConfiguration.MixUntilAnonymitySet - 1);
                    }

                    if (Global.KillRequested)
                    {
                        break;
                    }

                    await Task.Delay(3000);
                }
                // Keep this loop alive as long as a coin is enqueued or keepalive was specified.
                while (keepMixAlive || AnyCoinsQueued());

                await Global.DisposeAsync();
            }
            catch
            {
                if (!Global.KillRequested)
                {
                    throw;
                }
            }
            finally
            {
                Logger.LogInfo($"{nameof(Daemon)} stopped.");
            }
        }
Exemple #30
0
    //private void Start()
    //{
    //	Wallet.Instance.GetBalance();
    //}

    private void Start()
    {
        wallet = Wallet.Instance;
    }
Exemple #31
0
 public void AddWallet(Wallet wallet)
 {
     wallets.Add(wallet);
 }
        //public Dictionary<string, string> TokenGenesisBlocks { get; set; }

        public ServiceAccount(IActorRef blockChain, Wallet svcWallet)
        {
            _blockChain = blockChain;
            _svcWallet  = svcWallet;
            _config     = Neo.Settings.Default.LyraNode;
        }
 public static Props Props(IActorRef blockChain, Wallet svcWallet)
 {
     return(Akka.Actor.Props.Create(() => new ServiceAccount(blockChain, svcWallet)));
 }
Exemple #34
0
 public Coins(Wallet wallet, BhpSystem system)
 {
     this.current_wallet = wallet;
     this.system         = system;
 }
Exemple #35
0
 public async Task CreateWallet()
 {
     await Wallet.CreateWalletAsync(_config, _cred);
 }
Exemple #36
0
        public void CanSyncWalletCore(NodeBuilder builder, CoreNode walletNode, WalletCreation creation)
        {
            var        rpc = builder.Nodes[0].CreateRPCClient();
            var        notifiedTransactions = new List <WalletTransaction>();
            NodesGroup connected            = CreateGroup(builder, new List <CoreNode>(new[] { walletNode }), 1);
            Wallet     wallet = new Wallet(creation, keyPoolSize: 11);

            wallet.NewWalletTransaction += (s, a) => notifiedTransactions.Add(a);
            Assert.True(wallet.State == WalletState.Created);
            wallet.Configure(connected);
            wallet.Connect();
            Assert.True(wallet.State == WalletState.Disconnected);
            TestUtils.Eventually(() => connected.ConnectedNodes.Count == 1);
            Assert.True(wallet.State == WalletState.Connected);

            TestUtils.Eventually(() => wallet.Chain.Height == rpc.GetBlockCount());
            for (int i = 0; i < 9; i++)
            {
                wallet.GetNextScriptPubKey();
            }
            wallet.GetNextScriptPubKey();             //Should provoke purge
            TestUtils.Eventually(() => wallet.State == WalletState.Disconnected && wallet.ConnectedNodes == 0);
            Thread.Sleep(100);
            TestUtils.Eventually(() => wallet.ConnectedNodes == 1);

            var k = wallet.GetNextScriptPubKey();

            Assert.NotNull(wallet.GetKeyPath(k));
            if (creation.UseP2SH)
            {
                var p2sh = k.GetDestinationAddress(Network.TestNet) as BitcoinScriptAddress;
                Assert.NotNull(p2sh);
                var redeem = wallet.GetRedeemScript(p2sh);
                Assert.NotNull(redeem);
                Assert.Equal(redeem.Hash, p2sh.Hash);
            }

            Assert.Equal(creation.UseP2SH, k.GetDestinationAddress(Network.TestNet) is BitcoinScriptAddress);
            builder.Nodes[0].GiveMoney(k, Money.Coins(1.0m));
            TestUtils.Eventually(() => wallet.GetTransactions().Count == 1 &&
                                 notifiedTransactions.Count == 1);
            builder.Nodes[0].FindBlock();
            TestUtils.Eventually(() => wallet.GetTransactions().Where(t => t.BlockInformation != null).Count() == 1 &&
                                 notifiedTransactions.Count == 2);
            builder.Nodes[0].GiveMoney(k, Money.Coins(1.5m), false);
            builder.Nodes[0].FindBlock();
            TestUtils.Eventually(() => wallet.GetTransactions().Summary.Confirmed.TransactionCount == 2 &&
                                 notifiedTransactions.Count == 3);

            builder.Nodes[0].FindBlock(30);
            Assert.True(wallet.GetTransactions().Summary.Confirmed.TransactionCount == 2);
            builder.Nodes[0].GiveMoney(k, Money.Coins(0.001m), false);
            Assert.True(wallet.GetTransactions().Summary.Confirmed.TransactionCount == 2);
            builder.Nodes[0].FindBlock(1, false);
            Assert.True(wallet.GetTransactions().Summary.Confirmed.TransactionCount == 2);
            builder.Nodes[0].FindBlock();
            //Sync automatically
            TestUtils.Eventually(() => wallet.GetTransactions().Summary.Confirmed.TransactionCount == 3);

            //Save and restore wallet
            MemoryStream ms = new MemoryStream();

            wallet.Save(ms);
            ms.Position = 0;
            var wallet2 = Wallet.Load(ms);

            //////

            //Save and restore tracker
            ms = new MemoryStream();
            var tracker = connected.NodeConnectionParameters.TemplateBehaviors.Find <TrackerBehavior>();

            tracker.Tracker.Save(ms);
            ms.Position = 0;
            connected   = CreateGroup(builder, new List <CoreNode>(new[] { walletNode }), 1);
            tracker     = new TrackerBehavior(Tracker.Load(ms), wallet.Chain);
            connected.NodeConnectionParameters.TemplateBehaviors.Add(tracker);
            //////

            wallet2.Configure(connected);
            wallet2.Connect();
            Assert.Equal(wallet.Created, wallet2.Created);
            Assert.Equal(wallet.GetNextScriptPubKey(), wallet2.GetNextScriptPubKey());
            Assert.True(wallet.GetKnownScripts().Length == wallet2.GetKnownScripts().Length);
            TestUtils.Eventually(() => wallet2.GetTransactions().Summary.Confirmed.TransactionCount == 3);

            //TestUtils.Eventually(() =>
            //{
            //    var fork = wallet.Chain.FindFork(wallet2._ScanLocation);
            //    return fork.Height == rpc.GetBlockCount();
            //});

            wallet2.Disconnect();
            wallet.Disconnect();
            connected.Disconnect();
        }
Exemple #37
0
        public void CanSyncWallet2()
        {
            using (var builder = NodeBuilder.Create())
            {
                NodesGroup aliceConnection = CreateGroup(builder, 1);
                NodesGroup bobConnection   = CreateGroup(builder, new[] { builder.Nodes[0] }, 1);
                builder.Nodes[0].Generate(101);
                var    rpc      = builder.Nodes[0].CreateRPCClient();
                var    aliceKey = new ExtKey();
                Wallet alice    = new Wallet(new WalletCreation()
                {
                    Network           = Network.RegTest,
                    RootKeys          = new[] { aliceKey.Neuter() },
                    SignatureRequired = 1,
                    UseP2SH           = false
                }, 11);
                Wallet bob = new Wallet(new WalletCreation()
                {
                    Network           = Network.RegTest,
                    RootKeys          = new[] { new ExtKey().Neuter() },
                    SignatureRequired = 1,
                    UseP2SH           = false
                }, 11);

                alice.Configure(aliceConnection);
                alice.Connect();

                bob.Configure(bobConnection);
                bob.Connect();

                TestUtils.Eventually(() => aliceConnection.ConnectedNodes.Count == 1);

                //New address tracked
                var addressAlice = alice.GetNextScriptPubKey();
                builder.Nodes[0].GiveMoney(addressAlice, Money.Coins(1.0m));
                TestUtils.Eventually(() => aliceConnection.ConnectedNodes.Count == 1);                 //Reconnect
                //////

                TestUtils.Eventually(() => alice.GetTransactions().Count == 1);

                //Alice send tx to bob
                var coins = alice.GetTransactions().GetSpendableCoins();
                var keys  = coins.Select(c => alice.GetKeyPath(c.ScriptPubKey))
                            .Select(k => aliceKey.Derive(k))
                            .ToArray();
                var txBuilder = new TransactionBuilder();
                var tx        =
                    txBuilder
                    .SetTransactionPolicy(new StandardTransactionPolicy()
                {
                    MinRelayTxFee = new FeeRate(0)
                })
                    .AddCoins(coins)
                    .AddKeys(keys)
                    .Send(bob.GetNextScriptPubKey(), Money.Coins(0.4m))
                    .SetChange(alice.GetNextScriptPubKey(true))
                    .SendFees(Money.Coins(0.0001m))
                    .BuildTransaction(true);

                Assert.True(txBuilder.Verify(tx));

                builder.Nodes[0].Broadcast(tx);

                //Alice get change
                TestUtils.Eventually(() => alice.GetTransactions().Count == 2);
                coins = alice.GetTransactions().GetSpendableCoins();
                Assert.True(coins.Single().Amount == Money.Coins(0.5999m));
                //////

                //Bob get coins
                TestUtils.Eventually(() => bob.GetTransactions().Count == 1);
                coins = bob.GetTransactions().GetSpendableCoins();
                Assert.True(coins.Single().Amount == Money.Coins(0.4m));
                //////


                MemoryStream bobWalletBackup = new MemoryStream();
                bob.Save(bobWalletBackup);
                bobWalletBackup.Position = 0;

                MemoryStream bobTrakerBackup = new MemoryStream();
                bob.Tracker.Save(bobTrakerBackup);
                bobTrakerBackup.Position = 0;

                bob.Disconnect();

                //Restore bob
                bob = Wallet.Load(bobWalletBackup);
                bobConnection.NodeConnectionParameters.TemplateBehaviors.Remove <TrackerBehavior>();
                bobConnection.NodeConnectionParameters.TemplateBehaviors.Add(new TrackerBehavior(Tracker.Load(bobTrakerBackup), alice.Chain));
                /////

                bob.Configure(bobConnection);

                //Bob still has coins
                TestUtils.Eventually(() => bob.GetTransactions().Count == 1);
                coins = bob.GetTransactions().GetSpendableCoins();
                Assert.True(coins.Single().Amount == Money.Coins(0.4m));
                //////

                bob.Connect();
                TestUtils.Eventually(() => bobConnection.ConnectedNodes.Count == 1);

                //New block found !
                builder.Nodes[0].SelectMempoolTransactions();
                builder.Nodes[0].Generate(1);

                //Alice send tx to bob
                coins = alice.GetTransactions().GetSpendableCoins();
                keys  = coins.Select(c => alice.GetKeyPath(c.ScriptPubKey))
                        .Select(k => aliceKey.Derive(k))
                        .ToArray();
                txBuilder = new TransactionBuilder();
                tx        =
                    txBuilder
                    .SetTransactionPolicy(new StandardTransactionPolicy()
                {
                    MinRelayTxFee = new FeeRate(0)
                })
                    .AddCoins(coins)
                    .AddKeys(keys)
                    .Send(bob.GetNextScriptPubKey(), Money.Coins(0.1m))
                    .SetChange(alice.GetNextScriptPubKey(true))
                    .SendFees(Money.Coins(0.0001m))
                    .BuildTransaction(true);

                Assert.True(txBuilder.Verify(tx));

                builder.Nodes[0].Broadcast(tx);

                //Bob still has coins
                TestUtils.Eventually(() => bob.GetTransactions().Count == 2);                 //Bob has both, old and new tx
                coins = bob.GetTransactions().GetSpendableCoins();
                //////
            }
        }
Exemple #38
0
 public Wallet AddWallet(Wallet wallet)
 {
     return(_walletRepository.Add(wallet));
 }
Exemple #39
0
        public void CanBroadcastTransaction()
        {
            using (NodeServerTester servers = new NodeServerTester(Network.TestNet))
            {
                var notifiedTransactions = new List <WalletTransaction>();
                var chainBuilder         = new BlockchainBuilder();
                SetupSPVBehavior(servers, chainBuilder);
                var    tx     = new Transaction();
                Wallet wallet = new Wallet(new WalletCreation()
                {
                    Network  = Network.TestNet,
                    RootKeys = new[] { new ExtKey().Neuter() },
                    UseP2SH  = false
                }, keyPoolSize: 11);
                NodesGroup connected = CreateGroup(servers, 2);
                wallet.Configure(connected);
                wallet.Connect();

                AutoResetEvent evt          = new AutoResetEvent(false);
                bool           passed       = false;
                bool           rejected     = false;
                var            broadcasting = wallet.BroadcastTransactionAsync(tx);
                wallet.TransactionBroadcasted += (t) =>
                {
                    passed = true;
                    evt.Set();
                };
                wallet.TransactionRejected += (t, r) =>
                {
                    rejected = true;
                    evt.Set();
                };
                BroadcastHub         hub      = BroadcastHub.GetBroadcastHub(connected.NodeConnectionParameters);
                BroadcastHubBehavior behavior = null;
                while (behavior == null || behavior.AttachedNode.State != NodeState.HandShaked)
                {
                    behavior = connected.ConnectedNodes.Select(n => n.Behaviors.Find <BroadcastHubBehavior>()).FirstOrDefault();
                    Thread.Sleep(1);
                }
                if (broadcasting.Status != TaskStatus.RanToCompletion)
                {
                    Assert.Equal(1, behavior.Broadcasts.Count());
                    Assert.Equal(1, hub.BroadcastingTransactions.Count());
                }
                Assert.True(evt.WaitOne(20000));
                Assert.True(broadcasting.Status == TaskStatus.RanToCompletion);
                Assert.True(passed);
                evt.Reset();
                Assert.Equal(0, behavior.Broadcasts.Count());
                Assert.Equal(0, hub.BroadcastingTransactions.Count());
                Assert.Null(broadcasting.Result);

                broadcasting = wallet.BroadcastTransactionAsync(tx);
                if (broadcasting.Status != TaskStatus.RanToCompletion)
                {
                    Assert.Equal(1, behavior.Broadcasts.Count());
                }
                Assert.True(evt.WaitOne(20000));
                Assert.True(rejected);
                Assert.Equal(0, behavior.Broadcasts.Count());
                Assert.Equal(0, hub.BroadcastingTransactions.Count());
                Assert.NotNull(broadcasting.Result);
            }
        }
Exemple #40
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            tss_lbl_height_value.Text    = $"{Blockchain.Default.Height}/{Blockchain.Default.HeaderHeight}";
            tss_lbl_connected_value.Text = Program.LocalNode.RemoteNodeCount.ToString();

            TimeSpan persistence_span = DateTime.Now - persistence_time;

            if (persistence_span < TimeSpan.Zero)
            {
                persistence_span = TimeSpan.Zero;
            }
            if (persistence_span > Blockchain.TimePerBlock)
            {
                this.tss_pgs_wait_block.Style = ProgressBarStyle.Marquee;
            }
            else
            {
                this.tss_pgs_wait_block.Value = persistence_span.Seconds;
                this.tss_pgs_wait_block.Style = ProgressBarStyle.Blocks;
            }

            if (Program.CurrentWallet != null)
            {
                if (Program.CurrentWallet.WalletHeight <= Blockchain.Default.Height + 1)
                {
                    if (balance_changed)
                    {
                        IEnumerable <Coin> coins             = Program.CurrentWallet?.GetCoins().Where(p => !p.State.HasFlag(CoinState.Spent)) ?? Enumerable.Empty <Coin>();
                        Fixed8             bonus_available   = Blockchain.CalculateBonus(Program.CurrentWallet.GetUnclaimedCoins().Select(p => p.Reference));
                        Fixed8             bonus_unavailable = Blockchain.CalculateBonus(coins.Where(p => p.State.HasFlag(CoinState.Confirmed) && p.Output.AssetId.Equals(Blockchain.GoverningToken.Hash)).Select(p => p.Reference), Blockchain.Default.Height + 1);
                        Fixed8             bonus             = bonus_available + bonus_unavailable;
                        var assets = coins.GroupBy(p => p.Output.AssetId, (k, g) => new
                        {
                            Asset = Blockchain.Default.GetAssetState(k),
                            Value = g.Sum(p => p.Output.Value),
                            Claim = k.Equals(Blockchain.UtilityToken.Hash) ? bonus : Fixed8.Zero
                        }).ToDictionary(p => p.Asset.AssetId);
                        if (bonus != Fixed8.Zero && !assets.ContainsKey(Blockchain.UtilityToken.Hash))
                        {
                            assets[Blockchain.UtilityToken.Hash] = new
                            {
                                Asset = Blockchain.Default.GetAssetState(Blockchain.UtilityToken.Hash),
                                Value = Fixed8.Zero,
                                Claim = bonus
                            };
                        }
                        var balance_ans = coins.Where(p => p.Output.AssetId.Equals(Blockchain.GoverningToken.Hash)).GroupBy(p => p.Output.ScriptHash).ToDictionary(p => p.Key, p => p.Sum(i => i.Output.Value));
                        var balance_anc = coins.Where(p => p.Output.AssetId.Equals(Blockchain.UtilityToken.Hash)).GroupBy(p => p.Output.ScriptHash).ToDictionary(p => p.Key, p => p.Sum(i => i.Output.Value));
                        foreach (ListViewItem item in lst_addr.Items)
                        {
                            UInt160 script_hash = Wallet.ToScriptHash(item.Name);
                            Fixed8  ans         = balance_ans.ContainsKey(script_hash) ? balance_ans[script_hash] : Fixed8.Zero;
                            Fixed8  anc         = balance_anc.ContainsKey(script_hash) ? balance_anc[script_hash] : Fixed8.Zero;
                            item.SubItems["ans"].Text = ans.ToString();
                            item.SubItems["anc"].Text = anc.ToString();
                        }

                        foreach (AssetState asset in lst_asset.Items.OfType <ListViewItem>().Select(p => p.Tag as AssetState).Where(p => p != null).ToArray())
                        {
                            if (!assets.ContainsKey(asset.AssetId))
                            {
                                lst_asset.Items.RemoveByKey(asset.AssetId.ToString());
                            }
                        }
                        foreach (var asset in assets.Values)
                        {
                            string value_text = asset.Value.ToString() + (asset.Asset.AssetId.Equals(Blockchain.UtilityToken.Hash) ? $"+({asset.Claim})" : "");
                            if (lst_asset.Items.ContainsKey(asset.Asset.AssetId.ToString()))
                            {
                                lst_asset.Items[asset.Asset.AssetId.ToString()].SubItems["value"].Text = value_text;
                            }
                            else
                            {
                                string asset_name = asset.Asset.AssetType == AssetType.GoverningToken ? "PURE" :
                                                    asset.Asset.AssetType == AssetType.UtilityToken ? "PureGas" :
                                                    asset.Asset.GetName();
                                lst_asset.Items.Add(new ListViewItem(new[]
                                {
                                    new ListViewItem.ListViewSubItem
                                    {
                                        Name = "name",
                                        Text = asset_name
                                    },
                                    new ListViewItem.ListViewSubItem
                                    {
                                        Name = "type",
                                        Text = asset.Asset.AssetType.ToString()
                                    },
                                    new ListViewItem.ListViewSubItem
                                    {
                                        Name = "value",
                                        Text = value_text
                                    },
                                    new ListViewItem.ListViewSubItem
                                    {
                                        ForeColor = Color.Gray,
                                        Name      = "issuer",
                                        Text      = $"{Strings.UnknownIssuer}[{asset.Asset.Owner}]"
                                    }
                                }, -1, lst_asset.Groups["unchecked"])
                                {
                                    Name = asset.Asset.AssetId.ToString(),
                                    Tag  = asset.Asset,
                                    UseItemStyleForSubItems = false
                                });
                            }
                        }
                        balance_changed = false;
                    }

                    foreach (ListViewItem item in lst_asset.Groups["unchecked"].Items.OfType <ListViewItem>().ToArray())
                    {
                        ListViewItem.ListViewSubItem subitem = item.SubItems["issuer"];
                        AssetState             asset         = (AssetState)item.Tag;
                        CertificateQueryResult result;
                        if (asset.AssetType == AssetType.GoverningToken || asset.AssetType == AssetType.UtilityToken)
                        {
                            result = new CertificateQueryResult {
                                Type = CertificateQueryResultType.System
                            };
                        }
                        else
                        {
                            result = CertificateQueryService.Query(asset.Owner);
                        }
                        using (result)
                        {
                            subitem.Tag = result.Type;
                            switch (result.Type)
                            {
                            case CertificateQueryResultType.Querying:
                            case CertificateQueryResultType.QueryFailed:
                                break;

                            case CertificateQueryResultType.System:
                                subitem.ForeColor = Color.Green;
                                subitem.Text      = Strings.SystemIssuer;
                                break;

                            case CertificateQueryResultType.Invalid:
                                subitem.ForeColor = Color.Red;
                                subitem.Text      = $"[{Strings.InvalidCertificate}][{asset.Owner}]";
                                break;

                            case CertificateQueryResultType.Expired:
                                subitem.ForeColor = Color.Yellow;
                                subitem.Text      = $"[{Strings.ExpiredCertificate}]{result.Certificate.Subject}[{asset.Owner}]";
                                break;

                            case CertificateQueryResultType.Good:
                                subitem.ForeColor = Color.Black;
                                subitem.Text      = $"{result.Certificate.Subject}[{asset.Owner}]";
                                break;
                            }
                            switch (result.Type)
                            {
                            case CertificateQueryResultType.System:
                            case CertificateQueryResultType.Missing:
                            case CertificateQueryResultType.Invalid:
                            case CertificateQueryResultType.Expired:
                            case CertificateQueryResultType.Good:
                                item.Group = lst_asset.Groups["checked"];
                                break;
                            }
                        }
                    }
                }
            }
        }
Exemple #41
0
        /// <summary>
        /// Create asset issue
        /// </summary>
        /// <param name="parameters">
        /// Parameter Index
        /// [0] : Name
        /// [1] : Description
        /// [2] : Url
        /// [3] : transaction count
        /// [4] : count
        /// [5] : Precision
        /// [6] : Total supply
        /// [7] : Free net limit
        /// [8] : public free net limit
        /// [9] : Start time
        /// [10] : End time
        /// [11-] : Pair frozen supply
        /// </param>
        /// <returns></returns>
        public static bool CreateAssetIssue(string command, string[] parameters)
        {
            string[] usage = new string[] {
                string.Format("{0} [command option] " +
                              "<name> <description> <url>" +
                              "<transaction count> <count>" +
                              "<precision>" +
                              "<total supply>" +
                              "<free net limit> <public free net limit>" +
                              "<start time> <end time>" +
                              "<amount 1> <days 1> <amount 2> <days 2> ...\n"
                              , command)
            };

            string[] command_option = new string[] { HelpCommandOption.Help };

            if (parameters == null || parameters.Length < 11 || parameters.Length % 2 == 0)
            {
                OutputHelpMessage(usage, null, command_option, null);
                return(true);
            }

            if (!RpcApi.IsLogin)
            {
                return(true);
            }

            try
            {
                int      i                 = 0;
                byte[]   owner_address     = Wallet.Base58ToAddress(RpcApi.KeyStore.Address);
                string   name              = parameters[i++];
                string   description       = parameters[i++];
                string   url               = parameters[i++];
                long     total_supply      = long.Parse(parameters[i++]);
                int      tx_num            = int.Parse(parameters[i++]);
                int      num               = int.Parse(parameters[i++]);
                int      precision         = int.Parse(parameters[i++]);
                long     free_limit        = long.Parse(parameters[i++]);
                long     public_free_limit = long.Parse(parameters[i++]);
                DateTime start_time        = DateTime.ParseExact(parameters[i++], "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None);
                DateTime end_time          = DateTime.ParseExact(parameters[i++], "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None);

                Dictionary <long, long> frozen_supply = new Dictionary <long, long>();
                for (int j = i; j < parameters.Length; j += 2)
                {
                    frozen_supply.Add(
                        long.Parse(parameters[j + 0]),
                        long.Parse(parameters[j + 1])
                        );
                }

                RpcApiResult result = RpcApi.CreateAssetIssueContract(owner_address,
                                                                      name,
                                                                      description,
                                                                      url,
                                                                      tx_num,
                                                                      num,
                                                                      precision,
                                                                      0,
                                                                      total_supply,
                                                                      free_limit,
                                                                      public_free_limit,
                                                                      start_time.ToTimestamp(),
                                                                      end_time.ToTimestamp(),
                                                                      frozen_supply,
                                                                      out AssetIssueContract contract);

                TransactionExtention transaction_extention = null;
                if (result.Result)
                {
                    result = RpcApi.CreateTransaction(contract,
                                                      ContractType.AssetIssueContract,
                                                      out transaction_extention);
                }

                if (result.Result)
                {
                    result = RpcApi.ProcessTransactionExtention(transaction_extention);
                }

                OutputResultMessage(command, result.Result, result.Code, result.Message);
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.Message + "\n\n" + e.StackTrace);
            }

            return(true);
        }
Exemple #42
0
 public void UnlockWallet(string password)
 {
     Wallet.Unlock(password);
 }
Exemple #43
0
 public WalletBalanceTileViewModel(Wallet wallet, IObservable <Unit> balanceChanged, ObservableCollection <HistoryItemViewModelBase> history)
 {
     _wallet         = wallet;
     _balanceChanged = balanceChanged;
     _history        = history;
 }
Exemple #44
0
 public void CreateWallet(string password)
 {
     Wallet.Create(password);
 }
 public async Task UpdateAsync(Wallet wallet)
 {
     await _walletRepository.UpdateAsync(wallet);
 }
Exemple #46
0
 public void StartRpc(IPAddress bindAddress, int port, Wallet wallet = null, string sslCert = null, string password = null, string[] trustedAuthorities = null)
 {
     rpcserver = new RpcServer(wallet);
     rpcserver.Start(bindAddress, port, sslCert, password, trustedAuthorities);
 }
Exemple #47
0
 public CoinJoinStatusEventArgs(Wallet wallet, CoinJoinProgressEventArgs coinJoinProgressEventArgs) : base(wallet)
 {
     CoinJoinProgressEventArgs = coinJoinProgressEventArgs;
 }
Exemple #48
0
        protected virtual JObject Process(string method, JArray _params)
        {
            switch (method)
            {
            case "getaccountstate":
            {
                UInt160      script_hash = Wallet.ToScriptHash(_params[0].AsString());
                AccountState account     = Blockchain.Default.GetAccountState(script_hash) ?? new AccountState(script_hash);
                return(account.ToJson());
            }

            case "getassetstate":
            {
                UInt256    asset_id = UInt256.Parse(_params[0].AsString());
                AssetState asset    = Blockchain.Default.GetAssetState(asset_id);
                return(asset?.ToJson() ?? throw new RpcException(-100, "Unknown asset"));
            }

            case "getbestblockhash":
                return(Blockchain.Default.CurrentBlockHash.ToString());

            case "getblock":
            {
                Block block;
                if (_params[0] is JNumber)
                {
                    uint index = (uint)_params[0].AsNumber();
                    block = Blockchain.Default.GetBlock(index);
                }
                else
                {
                    UInt256 hash = UInt256.Parse(_params[0].AsString());
                    block = Blockchain.Default.GetBlock(hash);
                }
                if (block == null)
                {
                    throw new RpcException(-100, "Unknown block");
                }
                bool verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false);
                if (verbose)
                {
                    JObject json = block.ToJson();
                    json["confirmations"] = Blockchain.Default.Height - block.Index + 1;
                    UInt256 hash = Blockchain.Default.GetNextBlockHash(block.Hash);
                    if (hash != null)
                    {
                        json["nextblockhash"] = hash.ToString();
                    }
                    return(json);
                }
                else
                {
                    return(block.ToArray().ToHexString());
                }
            }

            case "getblockcount":
                return(Blockchain.Default.Height + 1);

            case "getblockhash":
            {
                uint height = (uint)_params[0].AsNumber();
                if (height >= 0 && height <= Blockchain.Default.Height)
                {
                    return(Blockchain.Default.GetBlockHash(height).ToString());
                }
                else
                {
                    throw new RpcException(-100, "Invalid Height");
                }
            }

            case "getblocksysfee":
            {
                uint height = (uint)_params[0].AsNumber();
                if (height >= 0 && height <= Blockchain.Default.Height)
                {
                    return(Blockchain.Default.GetSysFeeAmount(height).ToString());
                }
                else
                {
                    throw new RpcException(-100, "Invalid Height");
                }
            }

            case "getconnectioncount":
                return(LocalNode.RemoteNodeCount);

            case "getcontractstate":
            {
                UInt160       script_hash = UInt160.Parse(_params[0].AsString());
                ContractState contract    = Blockchain.Default.GetContract(script_hash);
                return(contract?.ToJson() ?? throw new RpcException(-100, "Unknown contract"));
            }

            case "getrawmempool":
                return(new JArray(LocalNode.GetMemoryPool().Select(p => (JObject)p.Hash.ToString())));

            case "getrawtransaction":
            {
                UInt256     hash    = UInt256.Parse(_params[0].AsString());
                bool        verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false);
                int         height  = -1;
                Transaction tx      = LocalNode.GetTransaction(hash);
                if (tx == null)
                {
                    tx = Blockchain.Default.GetTransaction(hash, out height);
                }
                if (tx == null)
                {
                    throw new RpcException(-100, "Unknown transaction");
                }
                if (verbose)
                {
                    JObject json = tx.ToJson();
                    if (height >= 0)
                    {
                        Header header = Blockchain.Default.GetHeader((uint)height);
                        json["blockhash"]     = header.Hash.ToString();
                        json["confirmations"] = Blockchain.Default.Height - header.Index + 1;
                        json["blocktime"]     = header.Timestamp;
                    }
                    return(json);
                }
                else
                {
                    return(tx.ToArray().ToHexString());
                }
            }

            case "getstorage":
            {
                UInt160     script_hash = UInt160.Parse(_params[0].AsString());
                byte[]      key         = _params[1].AsString().HexToBytes();
                StorageItem item        = Blockchain.Default.GetStorageItem(new StorageKey
                    {
                        ScriptHash = script_hash,
                        Key        = key
                    }) ?? new StorageItem();
                return(item.Value?.ToHexString());
            }

            case "gettxout":
            {
                UInt256 hash  = UInt256.Parse(_params[0].AsString());
                ushort  index = (ushort)_params[1].AsNumber();
                return(Blockchain.Default.GetUnspent(hash, index)?.ToJson(index));
            }

            case "getvalidators":
            {
                var validators = Blockchain.Default.GetValidators();
                return(Blockchain.Default.GetEnrollments().Select(p =>
                    {
                        JObject validator = new JObject();
                        validator["publickey"] = p.PublicKey.ToString();
                        validator["votes"] = p.Votes.ToString();
                        validator["active"] = validators.Contains(p.PublicKey);
                        return validator;
                    }).ToArray());
            }

            case "invoke":
            {
                UInt160             script_hash = UInt160.Parse(_params[0].AsString());
                ContractParameter[] parameters  = ((JArray)_params[1]).Select(p => ContractParameter.FromJson(p)).ToArray();
                byte[] script;
                using (ScriptBuilder sb = new ScriptBuilder())
                {
                    script = sb.EmitAppCall(script_hash, parameters).ToArray();
                }
                return(GetInvokeResult(script));
            }

            case "invokefunction":
            {
                UInt160             script_hash = UInt160.Parse(_params[0].AsString());
                string              operation   = _params[1].AsString();
                ContractParameter[] args        = _params.Count >= 3 ? ((JArray)_params[2]).Select(p => ContractParameter.FromJson(p)).ToArray() : new ContractParameter[0];
                byte[]              script;
                using (ScriptBuilder sb = new ScriptBuilder())
                {
                    script = sb.EmitAppCall(script_hash, operation, args).ToArray();
                }
                return(GetInvokeResult(script));
            }

            case "invokescript":
            {
                byte[] script = _params[0].AsString().HexToBytes();
                return(GetInvokeResult(script));
            }

            case "sendrawtransaction":
            {
                Transaction tx = Transaction.DeserializeFrom(_params[0].AsString().HexToBytes());
                return(LocalNode.Relay(tx));
            }

            case "submitblock":
            {
                Block block = _params[0].AsString().HexToBytes().AsSerializable <Block>();
                return(LocalNode.Relay(block));
            }

            case "validateaddress":
            {
                JObject json = new JObject();
                UInt160 scriptHash;
                try
                {
                    scriptHash = Wallet.ToScriptHash(_params[0].AsString());
                }
                catch
                {
                    scriptHash = null;
                }
                json["address"] = _params[0];
                json["isvalid"] = scriptHash != null;
                return(json);
            }

            case "getpeers":
            {
                JObject json = new JObject();

                {
                    JArray unconnectedPeers = new JArray();
                    foreach (IPEndPoint peer in LocalNode.GetUnconnectedPeers())
                    {
                        JObject peerJson = new JObject();
                        peerJson["address"] = peer.Address.ToString();
                        peerJson["port"]    = peer.Port;
                        unconnectedPeers.Add(peerJson);
                    }
                    json["unconnected"] = unconnectedPeers;
                }

                {
                    JArray badPeers = new JArray();
                    foreach (IPEndPoint peer in LocalNode.GetBadPeers())
                    {
                        JObject peerJson = new JObject();
                        peerJson["address"] = peer.Address.ToString();
                        peerJson["port"]    = peer.Port;
                        badPeers.Add(peerJson);
                    }
                    json["bad"] = badPeers;
                }

                {
                    JArray connectedPeers = new JArray();
                    foreach (RemoteNode node in LocalNode.GetRemoteNodes())
                    {
                        JObject peerJson = new JObject();
                        peerJson["address"] = node.RemoteEndpoint.Address.ToString();
                        peerJson["port"]    = node.ListenerEndpoint?.Port ?? 0;
                        connectedPeers.Add(peerJson);
                    }
                    json["connected"] = connectedPeers;
                }

                return(json);
            }

            case "getversion":
            {
                JObject json = new JObject();
                json["port"]      = LocalNode.Port;
                json["nonce"]     = LocalNode.Nonce;
                json["useragent"] = LocalNode.UserAgent;
                return(json);
            }

            default:
                throw new RpcException(-32601, "Method not found");
            }
        }
        public async Task TestServicesAsync(string networkString)
        {
            await RuntimeParams.LoadAsync();

            var network          = Network.GetNetwork(networkString);
            var blocksToDownload = new List <uint256>();

            if (network == Network.Main)
            {
                blocksToDownload.Add(new uint256("00000000000000000037c2de35bd85f3e57f14ddd741ce6cee5b28e51473d5d0"));
                blocksToDownload.Add(new uint256("000000000000000000115315a43cb0cdfc4ea54a0e92bed127f4e395e718d8f9"));
                blocksToDownload.Add(new uint256("00000000000000000011b5b042ad0522b69aae36f7de796f563c895714bbd629"));
            }
            else if (network == Network.TestNet)
            {
                blocksToDownload.Add(new uint256("0000000097a664c4084b49faa6fd4417055cb8e5aac480abc31ddc57a8208524"));
                blocksToDownload.Add(new uint256("000000009ed5b82259ecd2aa4cd1f119db8da7a70e7ea78d9c9f603e01f93bcc"));
                blocksToDownload.Add(new uint256("00000000e6da8c2da304e9f5ad99c079df2c3803b49efded3061ecaf206ddc66"));
            }
            else
            {
                throw new NotSupportedNetworkException(network);
            }
            var dataDir = Path.Combine(Global.Instance.DataDir, EnvironmentHelpers.GetCallerFileName());

            BitcoinStore bitcoinStore = new BitcoinStore(Path.Combine(dataDir, EnvironmentHelpers.GetMethodName()), network,
                                                         new IndexStore(network, new SmartHeaderChain()), new AllTransactionStore(), new MempoolService());

            await bitcoinStore.InitializeAsync();

            var            addressManagerFolderPath = Path.Combine(dataDir, "AddressManager");
            var            addressManagerFilePath   = Path.Combine(addressManagerFolderPath, $"AddressManager{network}.dat");
            var            blocksFolderPath         = Path.Combine(dataDir, "Blocks", network.ToString());
            var            connectionParameters     = new NodeConnectionParameters();
            AddressManager addressManager           = null;

            try
            {
                addressManager = await NBitcoinHelpers.LoadAddressManagerFromPeerFileAsync(addressManagerFilePath);

                Logger.LogInfo($"Loaded {nameof(AddressManager)} from `{addressManagerFilePath}`.");
            }
            catch (DirectoryNotFoundException)
            {
                addressManager = new AddressManager();
            }
            catch (FileNotFoundException)
            {
                addressManager = new AddressManager();
            }
            catch (OverflowException)
            {
                File.Delete(addressManagerFilePath);
                addressManager = new AddressManager();
            }
            catch (FormatException)
            {
                File.Delete(addressManagerFilePath);
                addressManager = new AddressManager();
            }

            connectionParameters.TemplateBehaviors.Add(new AddressManagerBehavior(addressManager));
            connectionParameters.TemplateBehaviors.Add(bitcoinStore.CreateUntrustedP2pBehavior());

            using var nodes = new NodesGroup(network, connectionParameters, requirements: Constants.NodeRequirements);

            KeyManager           keyManager    = KeyManager.CreateNew(out _, "password");
            WasabiSynchronizer   syncer        = new WasabiSynchronizer(network, bitcoinStore, new Uri("http://localhost:12345"), Global.Instance.TorSocks5Endpoint);
            ServiceConfiguration serviceConfig = new ServiceConfiguration(MixUntilAnonymitySet.PrivacyLevelStrong.ToString(), 2, 21, 50, new IPEndPoint(IPAddress.Loopback, network.DefaultPort), Money.Coins(Constants.DefaultDustThreshold));
            CachedBlockProvider  blockProvider = new CachedBlockProvider(
                new P2pBlockProvider(nodes, null, syncer, serviceConfig, network),
                new FileSystemBlockRepository(blocksFolderPath, network));

            using Wallet wallet = Wallet.CreateAndRegisterServices(
                      network,
                      bitcoinStore,
                      keyManager,
                      syncer,
                      nodes,
                      dataDir,
                      new ServiceConfiguration(MixUntilAnonymitySet.PrivacyLevelStrong.ToString(), 2, 21, 50, new IPEndPoint(IPAddress.Loopback, network.DefaultPort), Money.Coins(Constants.DefaultDustThreshold)),
                      syncer,
                      blockProvider);
            Assert.True(Directory.Exists(blocksFolderPath));

            try
            {
                var mempoolTransactionAwaiter = new EventsAwaiter <SmartTransaction>(
                    h => bitcoinStore.MempoolService.TransactionReceived += h,
                    h => bitcoinStore.MempoolService.TransactionReceived -= h,
                    3);

                var nodeConnectionAwaiter = new EventsAwaiter <NodeEventArgs>(
                    h => nodes.ConnectedNodes.Added += h,
                    h => nodes.ConnectedNodes.Added -= h,
                    3);

                nodes.Connect();

                var downloadTasks = new List <Task <Block> >();
                using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(4));
                foreach (var hash in blocksToDownload)
                {
                    downloadTasks.Add(blockProvider.GetBlockAsync(hash, cts.Token));
                }

                await nodeConnectionAwaiter.WaitAsync(TimeSpan.FromMinutes(3));

                var i         = 0;
                var hashArray = blocksToDownload.ToArray();
                foreach (var block in await Task.WhenAll(downloadTasks))
                {
                    Assert.True(File.Exists(Path.Combine(blocksFolderPath, hashArray[i].ToString())));
                    i++;
                }

                await mempoolTransactionAwaiter.WaitAsync(TimeSpan.FromMinutes(1));
            }
            finally
            {
                // So next test will download the block.
                foreach (var hash in blocksToDownload)
                {
                    await blockProvider.BlockRepository.RemoveAsync(hash, CancellationToken.None);
                }
                if (wallet is { })
Exemple #50
0
        // 设置钱包
        public void SetWallet(Wallet wallet)
        {
            rpcserver?.SetWallet(wallet);

            eventHandler.SetWallet(wallet);
        }
Exemple #51
0
        // 启动应用链的共识服务
        public void StartAppChainConsensus(string hashString, Wallet wallet)
        {
            UInt160 chainHash = UInt160.Parse(hashString);

            StartConsensus(chainHash, wallet);
        }
Exemple #52
0
 public void TestSetup()
 {
     keyPair    = new KeyPair(Wallet.GetPrivateKeyFromWIF("KyXwTh1hB76RRMquSvnxZrJzQx7h9nQP2PCRL38v6VDb5ip3nf1p"));
     scriptHash = Contract.CreateSignatureRedeemScript(keyPair.PublicKey).ToScriptHash();
 }
 public BetfairServerResponse<AccountFundsResponse> GetAccountFunds(Wallet wallet)
 {
     return client.GetAccountFunds(wallet).Result;
 }
Exemple #54
0
 private void _wallet_NewWalletTransaction(Wallet sender, WalletTransaction walletTransaction)
 {
     _logger.Information("New wallet transaction received");
 }
Exemple #55
0
 protected ClosedWalletViewModel(Wallet wallet)
     : base(wallet)
 {
     Loading     = new LoadingViewModel(wallet);
     OpenCommand = ReactiveCommand.Create(OnOpen);
 }
Exemple #56
0
 public TransactionHistoryBuilder(Wallet wallet)
 {
     Wallet = wallet;
 }
        public void SetUp()
        {
            _testNetChainBlockStore = new MemoryBlockStore(_testNet);
            _testNetChain = new BlockChain(_testNet, new Wallet(_testNet), _testNetChainBlockStore);
            _unitTestParams = NetworkParameters.UnitTests();
            _wallet = new Wallet(_unitTestParams);
            _wallet.AddKey(new EcKey());

            ResetBlockStore();
            _chain = new BlockChain(_unitTestParams, _wallet, _blockStore);

            _coinbaseTo = _wallet.Keychain[0].ToAddress(_unitTestParams);
        }
Exemple #58
0
        public ResponseModel PostTransfers([FromBody] Transfers transfers)
        {
            int    id_chuyen     = transfers.id_chuyen;
            int    id_nhan       = transfers.id_nhan;
            float  amount        = transfers.amount;
            string dis           = transfers.desciption;
            Wallet wallet_chuyen = _context.Wallets.Where(x => x.Id_Wallet == id_chuyen).FirstOrDefault();
            Wallet wallet_nhan   = _context.Wallets.Where(x => x.Id_Wallet == id_nhan).FirstOrDefault();

            try
            {
                if (wallet_chuyen != null && wallet_nhan != null)
                {
                    wallet_chuyen.Amount_now = wallet_chuyen.Amount_now - amount;
                    wallet_nhan.Amount_now   = wallet_nhan.Amount_now + amount;
                    if (transfers.desciption == "")
                    {
                        transfers.desciption = "Chuyển khoản";
                    }
                    transfers.date = DateTime.Today;
                    Income_Outcome income_chuyen = new Income_Outcome();
                    Income_Outcome income_nhan   = new Income_Outcome();
                    income_chuyen.Amount    = amount;
                    income_chuyen.Date_come = DateTime.Today.ToString();
                    if (transfers.desciption == "")
                    {
                        income_chuyen.Description_come = "Chuyển khoản ";
                    }
                    else
                    {
                        income_chuyen.Description_come = transfers.desciption;
                    }

                    income_chuyen.WalletId_Wallet = id_chuyen.ToString();
                    income_chuyen.Is_Come         = false;
                    income_chuyen.Id_type         = "16";
                    income_chuyen.CategoryId_Cate = null;
                    income_chuyen.LoanId_Loan     = null;
                    income_chuyen.TripId_Trip     = null;
                    _context.Income_Outcomes.Add(income_chuyen);

                    income_nhan.Amount           = amount;
                    income_nhan.Date_come        = DateTime.Today.ToString();
                    income_nhan.Description_come = "Nhận chuyển khoản ";
                    income_nhan.WalletId_Wallet  = id_nhan.ToString();
                    income_nhan.Is_Come          = true;
                    income_nhan.Id_type          = "16";
                    income_nhan.CategoryId_Cate  = null;
                    income_nhan.LoanId_Loan      = null;
                    income_nhan.TripId_Trip      = null;
                    _context.Income_Outcomes.Add(income_nhan);

                    _context.Transfers.Add(transfers);
                    _context.Wallets.Update(wallet_chuyen);
                    _context.Wallets.Update(wallet_nhan);
                    _context.SaveChanges();
                    ResponseModel res = new ResponseModel("Transfers success", null, "200");
                    return(res);
                }
                else
                {
                    ResponseModel res = new ResponseModel("Transfers fail", null, "404");
                    return(res);
                }
            }
            catch
            {
                ResponseModel res = new ResponseModel("Transfers fail", null, "404");
                return(res);
            }
        }
Exemple #59
0
        public CoinJoinTabViewModel(Wallet wallet)
            : base("CoinJoin")
        {
            Global = Locator.Current.GetService <Global>();
            Wallet = wallet;

            this.ValidateProperty(x => x.Password, ValidatePassword);

            Password = "";
            TimeLeftTillRoundTimeout = TimeSpan.Zero;

            CoinsList = new CoinListViewModel(Wallet, canDequeueCoins: true);

            Observable
            .FromEventPattern <SmartCoin>(CoinsList, nameof(CoinsList.DequeueCoinsPressed))
            .Subscribe(async x => await DoDequeueAsync(x.EventArgs));

            AmountQueued = Money.Zero;             // Global.ChaumianClient.State.SumAllQueuedCoinAmounts();

            EnqueueCommand = ReactiveCommand.CreateFromTask(async() => await DoEnqueueAsync(CoinsList.Coins.Where(c => c.IsSelected).Select(c => c.Model)));

            DequeueCommand = ReactiveCommand.CreateFromTask(async() => await DoDequeueAsync(CoinsList.Coins.Where(c => c.IsSelected).Select(x => x.Model)));

            PrivacySomeCommand = ReactiveCommand.Create(() => CoinJoinUntilAnonymitySet = MixUntilAnonymitySet.PrivacyLevelSome.ToString());

            PrivacyFineCommand = ReactiveCommand.Create(() => CoinJoinUntilAnonymitySet = MixUntilAnonymitySet.PrivacyLevelFine.ToString());

            PrivacyStrongCommand = ReactiveCommand.Create(() => CoinJoinUntilAnonymitySet = MixUntilAnonymitySet.PrivacyLevelStrong.ToString());

            TargetButtonCommand = ReactiveCommand.Create(() =>
            {
                switch (CoinJoinUntilAnonymitySet)
                {
                case nameof(MixUntilAnonymitySet.PrivacyLevelSome):
                    CoinJoinUntilAnonymitySet = MixUntilAnonymitySet.PrivacyLevelFine.ToString();
                    break;

                case nameof(MixUntilAnonymitySet.PrivacyLevelFine):
                    CoinJoinUntilAnonymitySet = MixUntilAnonymitySet.PrivacyLevelStrong.ToString();
                    break;

                case nameof(MixUntilAnonymitySet.PrivacyLevelStrong):
                    CoinJoinUntilAnonymitySet = MixUntilAnonymitySet.PrivacyLevelSome.ToString();
                    break;
                }

                Global.Config.MixUntilAnonymitySet = CoinJoinUntilAnonymitySet;

                // Config.json can be different than Global.Config. Only change the MixUntilAnonymitySet in the file.
                var config = new Config(Global.Config.FilePath);
                config.LoadOrCreateDefaultFile();
                config.MixUntilAnonymitySet = CoinJoinUntilAnonymitySet;
                config.ToFile();
            });

            this.WhenAnyValue(x => x.IsEnqueueBusy)
            .Select(x => x ? EnqueuingButtonTextString : EnqueueButtonTextString)
            .Subscribe(text => EnqueueButtonText = text);

            this.WhenAnyValue(x => x.IsDequeueBusy)
            .Select(x => x ? DequeuingButtonTextString : DequeueButtonTextString)
            .Subscribe(text => DequeueButtonText = text);

            this.WhenAnyValue(x => x.RoundTimesout)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(x =>
            {
                TimeSpan left            = x - DateTimeOffset.UtcNow;
                TimeLeftTillRoundTimeout = left > TimeSpan.Zero ? left : TimeSpan.Zero;                         // Make sure cannot be less than zero.
            });

            Observable
            .Merge(EnqueueCommand.ThrownExceptions)
            .Merge(DequeueCommand.ThrownExceptions)
            .Merge(PrivacySomeCommand.ThrownExceptions)
            .Merge(PrivacyFineCommand.ThrownExceptions)
            .Merge(PrivacyStrongCommand.ThrownExceptions)
            .Merge(TargetButtonCommand.ThrownExceptions)
            .ObserveOn(RxApp.TaskpoolScheduler)
            .Subscribe(ex => Logger.LogError(ex));
        }
 public ConsensusWithPolicy(LocalNode localNode, Wallet wallet, string log_dictionary)
     : base(localNode, wallet)
 {
     this.log_dictionary = log_dictionary;
 }