Наследование: MonoBehaviour
        public void BigMarioCoinTopSideCollisionTest()
        {
            MarioInstance testMario = new MarioInstance(game);
            MarioInstance expectedMario = new MarioInstance(game);
            testMario.Mushroom();
            expectedMario.Mushroom();

            Coin testCoin = new Coin(game);
            Coin expectedCoin = new Coin(game);
            expectedCoin.Disappear();

            ICollisionSide side = new TopSideCollision();
            CollisionData collision = new CollisionData(testMario, testCoin, side);
            MarioItemCollisionHandler collisionHandler = new MarioItemCollisionHandler(collision);

            collisionHandler.HandleCollision();

            bool testState = testMario.MarioState is NormalRightIdleState;
            bool expectedState = expectedMario.MarioState is NormalRightIdleState;

            Vector2 testLocation = testMario.VectorCoordinates;
            Vector2 expectedLocation = expectedMario.VectorCoordinates;

            Assert.AreEqual(testState, expectedState);
            Assert.AreEqual(testLocation, expectedLocation);
        }
 public override void HandleCoin(Coin coin)
 {
     if (Math.Abs(coin.Weight - 9.5) < 0.02 && Math.Abs(coin.Diameter - 22.5) < 0.13)
         Debug.WriteLine("Captured £1");
     else if (_successor != null)
         _successor.HandleCoin(coin);
 }
Пример #3
0
		public void PutCoin(Coin coin)
		{
			if (!Stock.ContainsKey(coin))
				Stock[coin] = 1;
			else
				++Stock[coin];
		}
 public override void HandleCoin(Coin coin)
 {
     if (Math.Abs(coin.Weight - 5) < 0.01 && Math.Abs(coin.Diameter - 21.4) < 0.1)
         Debug.WriteLine("Captured 20p");
     else if (_successor != null)
         _successor.HandleCoin(coin);
 }
Пример #5
0
     public void DropItem()
     {
          // Check if an item will drop
          randomDropChance = Random.Range(0, 100);

          // If an item does drop, pick one randomly with the given drop chances
          if (randomDropChance <= dropChance)
          {
               itemDropRate = Random.Range(0, 10);

               for (int i = 0; i < items.Count; i++)
               {
                    for (int j = 0; j < itemDropRates[i]; j++)
                    {
                         itemDrop.Add(items[i]);
                    }
               }
               //If it will drop an item, set the item it will drop to a random item that it can drop
               item = itemDrop[itemDropRate];

               //If it was a coin, give it a value
               if (item.GetComponent<Coin>())
               {
                    coin = item.GetComponent<Coin>();
                    coin.setValue(coinValue);
               }

               //Spawn the item
               if (item != null)
               {
                    Instantiate(item, transform.position, transform.rotation);
               }
          }
     }
		public void Given_TwentyRubles_Then_NotEnoughMoneyToBuyCoffee_CanBuyTea_And_SevenRublesInChange()
		{
			var coin10 = new Coin(10);

			var userAmount = _controller.UserCoins().Amount();
			var sum = TotalSum();
			var totalCoins10 = TotalCoins(10);

			_controller.PutCoin(coin10);
			_controller.PutCoin(coin10);

			Assert.Throws<ProductIsNotInAssortmentException>(() => _controller.BuyProduct("RRR"));
			Assert.Throws<NotEnoughMoneyException>(() => _controller.BuyProduct("Кофе с молоком"));

			const string teaTitle = "Чай";
			var product = _controller.BuyProduct(teaTitle);
			Assert.AreEqual(product.Title, teaTitle);

			Assert.AreEqual(_controller.PaidAmount(), 7);
			var change = _controller.ReturnChange();

			Assert.AreEqual(change.Amount(), 7);
			Assert.AreEqual(sum, TotalSum());
			Assert.AreEqual(totalCoins10, TotalCoins(10));
			Assert.AreEqual(_controller.UserCoins().Amount(), userAmount - product.Cost);
		}
Пример #7
0
    // Use this for initialization
    void Start()
    {
        //path = new Vector3[pathLength];
        ghostIndex = 0;
        romeosTurnNext = true;
        romeo.SetActive(false);
        rghost.SetActive(false);
        jghost.SetActive(false);

        juliaMove = julia.GetComponent<PlayerMovement>();
        romeoMove = romeo.GetComponent<PlayerMovement>();
        //ghostRend = ghost.GetComponent<SpriteRenderer>();
        juliaMove.speed = speed;
        juliaMove.ready = false;
        romeoMove.ready = false;
        juliaAnim.SetBool("fleeing", true);
        paused = true;

        Coin c = new Coin { picked = false, 
            coin = (GameObject)Instantiate(pathObject, startPosition, transform.rotation),
            position = startPosition };
        path.Add(c);

        //SEt GUi
        startGUI.InitPosition();
    }
Пример #8
0
 void Awake()
 {
     float i = 1.0f;
     List<Coin> p1coins = new List<Coin>();
     List<Coin> p2coins = new List<Coin>();
     foreach(GameObject c in GameObject.FindGameObjectsWithTag("p1"))
     {
         Vector3 pos = c.transform.position;
         float id = 1.0f;
         id += i/10;
         i += 1;
         Coin c1 = new Coin(pos,id);
         p1coins.Add(c1);
         c.name = id.ToString();
     }
     float j = 1.0f;
     foreach(GameObject c in GameObject.FindGameObjectsWithTag("p2"))
     {
         Vector3 pos = c.transform.position;
         float id = 2.0f;
         id += j/10;
         j += 1;
         Coin c2 = new Coin(pos,id);
         p2coins.Add(c2);
         c.name = id.ToString();
     }
     curr = new GameState (p1coins, p2coins);
     //curr.print ();
 }
Пример #9
0
    void getAndRemoveCoin(Coin coin)
    {
        this.coinGain += coin.price;
        AudioSource.PlayClipAtPoint (coinSound, transform.position);

        Destroy (coin.gameObject);
    }
Пример #10
0
 // Use this for initialization
 void OnEnable()
 {
     rb = GetComponent<Rigidbody> ();
     coinScript = transform.GetChild (0).GetComponent<Coin> ();
     coinScript.enabled = false;
     Launch ();
     Invoke ("Reenable", resetTime);
 }
Пример #11
0
		public void Add(Coin c)
		{
			if (c.MatchID != Id)
			{
				c.MatchID = Id;
				Coins.Add(c);
			}
		}
Пример #12
0
        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));
        }
Пример #13
0
        public void PropertyShouldBeAssigned()
        {
            var regionInfo = new RegionInfo("RU-ru");
            var expectedDenomination = 1.2m;
            var coin = new Coin(expectedDenomination, regionInfo);

            Assert.AreEqual(expectedDenomination, coin.Denomination);
            Assert.AreEqual(regionInfo.ISOCurrencySymbol, coin.Currency);
        }
Пример #14
0
 internal void AddCoin(
     [PexAssumeUnderTest]CoinManager target,
     Coin coin,
     int ammount
 )
 {
     PexAssume.IsTrue(5 >= (int)coin && 0 <= (int)coin, "proper coin");
     target.AddCoin(coin, ammount);
 }
Пример #15
0
		public void SpendCoin(Coin coin)
		{
			ExecuteInTransation(() =>
			{
				lock (_objLock)
				{
					Coins.Spend(new[] { new CoinBatch(coin.Value, 1) });
				}
			});
		}
Пример #16
0
        public void EqualityAndInequalityShouldBeCheckedCorrectly()
        {
            var coin1 = new Coin(1);
            var coin2 = new Coin(1);

            Assert.IsTrue(coin1 == coin2);

            var coin3 = new Coin(2);
            Assert.IsTrue(coin1 != coin3);
        }
        public Coin TakeCoin(Coin coin)
        {
            if (CustomerDeposit < (int)coin)
                throw new InsufficientFundsException();

            var taken = _balance.TakeCoin(coin);
            CustomerDeposit -= (int)coin;

            return taken;
        }
Пример #18
0
        public static bool Validate(Coin coin)
        {
            for (int i = 0; i < ValidCoins.Length; i++)
            {
                if (ValidCoins[i] == coin.value)
                    return true;
            }

            return false;
        }
Пример #19
0
		public Transaction SpendCoin(Coin coin, Script scriptPubKey, Money value)
		{
			var tx = new Transaction();
			tx.Inputs.Add(new TxIn(coin.Outpoint));
			tx.Outputs.Add(new TxOut(value, scriptPubKey));
			tx.Outputs.Add(new TxOut(coin.Amount - value, coin.ScriptPubKey));
			var h = tx.GetHash();
			Mempool.Add(h, tx);
			OnNewTransaction(tx);
			return tx;
		}
Пример #20
0
 internal void EjectCoin(
     [PexAssumeUnderTest]CoinManager target,
     Coin coin,
     int ammount,
     LinkedList<Coin> coinCase
 )
 {
     PexAssume.IsTrue(5 >= (int)coin && 0 <= (int)coin, "proper coin");
     PexAssume.InRange(ammount, 1, 10);
     target.EjectCoin(coin, ammount, coinCase);
 }
Пример #21
0
        public void ItemTest()
        {
            IList<IItem> items = new List<IItem>();
            items.Add(new Coin());
            var j = new Coin();
              location.AddItem(new Coin());
            var k = new PickUpEvent(location, new Coin(), actor);
            location.OnNext(k);

            Assert.AreEqual(0,location.Items.Count);
        }
Пример #22
0
        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);
            }
        }
Пример #23
0
        private void DblAnim_Completed(object sender, EventArgs e)
        {
            entryCoin = new Coin();

            canvas.Children.Add(entryCoin.CoinShape);

            Canvas.SetLeft(entryCoin.CoinShape, this.Width/2);
            Canvas.SetTop(entryCoin.CoinShape, this.Height / 2);

            DoubleAnimation dblAnim = new DoubleAnimation(0, 1, new Duration(new TimeSpan(0, 0, 0,0,300)));
            entryCoin.CoinShape.BeginAnimation(Ellipse.OpacityProperty, dblAnim);
        }
Пример #24
0
 public void EjectCoin502()
 {
     CoinManager coinManager;
     LinkedList<Coin> linkedList;
     LinkedList<Coin> linkedList1;
     coinManager = new CoinManager();
     Coin[] @is = new Coin[0];
     linkedList = new LinkedList<Coin>((IEnumerable<Coin>)@is);
     linkedList1 = new LinkedList<Coin>((IEnumerable<Coin>)linkedList);
     this.EjectCoin(coinManager, Coin.Ore50, 1, linkedList1);
     Assert.IsNotNull((object)coinManager);
 }
Пример #25
0
        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));
        }
Пример #26
0
        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));
        }
Пример #27
0
 public static void PrintPlan(Coin[,] state, IEnumerable<Move> plan)
 {
     int cnt = 0;
     foreach (var move in plan)
     {
         Console.WriteLine("step " + cnt);
         state.Print();
         Console.WriteLine("making move: " + move);
         var moveRes = MakeMove(state, move);
         Console.WriteLine("destroyed " + moveRes.Item2);
         state = moveRes.Item1;
     }
 }
Пример #28
0
 public override CoinEvaluationResult EvaluateCoin(Coin coin)
 {
     if (Math.Abs(coin.Weight - 3.25) < 0.02 && Math.Abs(coin.Diameter - 18) < 0.1)
     {
         Console.WriteLine("Captured 5p");
         return CoinEvaluationResult.Accepted;
     }
     if (_successor != null)
     {
         return _successor.EvaluateCoin(coin);
     }
     return CoinEvaluationResult.Rejected;
 }
Пример #29
0
 /// <summary>
 /// Пользователь вносит деньги
 /// </summary>
 /// <param name="s_type"></param>
 /// <returns></returns>
 public JsonResult EnterMoney(string s_type)
 {
     bool res = false;
     try
     {
         FaceValueTypes type = (FaceValueTypes)Enum.Parse(typeof(FaceValueTypes), s_type);
         Coin coin = new Coin(type);
         userWallet.Remove(type);
         vwWallet.Add(coin);
         res = true;
     }
     catch{}
     return Json(res, JsonRequestBehavior.AllowGet);
 }
Пример #30
0
        public bool Equals(Coin obj)
        {
            if(ReferenceEquals(null, obj))
            {
                return false;
            }

            if(ReferenceEquals(this, obj))
            {
                return true;
            }

            return Equals(obj.m_CoinType, m_CoinType) && obj.m_X == m_X && obj.m_Y == m_Y;
        }
Пример #31
0
        public static void ButtonHandler(Maze maze)
        {
            var player = Player.GetPlayer();

            var coin = new Coin();
            var road = new Road();

            var Ydim = maze.cells.GetLength(0) - 1;
            var Xdim = maze.cells.GetLength(1) - 1;

            ConsoleKeyInfo consoleKey;

            while (true)
            {
                consoleKey = Console.ReadKey(true);
                switch (consoleKey.Key)
                {
                case ConsoleKey.R:
                {
                    if (!WasNewPlayerGenerated)
                    {
                        maze.cells = new ICell[Maze.Heigth, Maze.Width];
                        Generator.GeneratePlayerPosition(player);
                        maze.cells[player.Y, player.X] = player;
                        maze.GenerateAgain();
                    }
                    RenderEngine.RenderMaze(maze);
                    WasNewPlayerGenerated = false;
                    Score = 0;
                    break;
                }

                case ConsoleKey.W:
                case ConsoleKey.UpArrow:
                {
                    if ((player.Y - 1 <= Ydim && player.Y - 1 >= 0) &&
                        (maze.cells[player.Y - 1, player.X].Name != "Wall"))
                    {
                        if (maze.cells[player.Y - 1, player.X].Name == "Coin")
                        {
                            Score++;
                        }
                        maze.cells[player.Y, player.X] = road;
                        player.Y--;
                        maze.cells[player.Y, player.X] = player;
                        RenderEngine.RenderMaze(maze);
                    }
                    else
                    {
                        Console.Beep(1000, 50);
                    }
                    break;
                }

                case ConsoleKey.S:
                case ConsoleKey.DownArrow:
                {
                    if ((player.Y + 1 <= Ydim) &&
                        (maze.cells[player.Y + 1, player.X].Name != "Wall"))
                    {
                        if (maze.cells[player.Y + 1, player.X].Name == "Coin")
                        {
                            Score++;
                        }
                        maze.cells[player.Y, player.X] = road;
                        player.Y++;
                        maze.cells[player.Y, player.X] = player;
                        RenderEngine.RenderMaze(maze);
                    }
                    else
                    {
                        Console.Beep(1000, 50);
                    }
                    break;
                }

                case ConsoleKey.A:
                case ConsoleKey.LeftArrow:
                {
                    if ((player.X - 1 >= 0) &&
                        (maze.cells[player.Y, player.X - 1].Name != "Wall"))
                    {
                        if (maze.cells[player.Y, player.X - 1].Name == "Coin")
                        {
                            Score++;
                        }
                        maze.cells[player.Y, player.X] = road;
                        player.X--;
                        maze.cells[player.Y, player.X] = player;
                        RenderEngine.RenderMaze(maze);
                    }
                    else
                    {
                        Console.Beep(1000, 50);
                    }
                    break;
                }

                case ConsoleKey.D:
                case ConsoleKey.RightArrow:
                {
                    if ((player.X + 1 <= Xdim) &&
                        (maze.cells[player.Y, player.X + 1].Name != "Wall"))
                    {
                        if (maze.cells[player.Y, player.X + 1].Name == "Coin")
                        {
                            Score++;
                        }
                        maze.cells[player.Y, player.X] = road;
                        player.X++;
                        maze.cells[player.Y, player.X] = player;
                        RenderEngine.RenderMaze(maze);
                    }
                    else
                    {
                        Console.Beep(1000, 50);
                    }
                    break;
                }

                case ConsoleKey.Escape:
                {
                    Environment.Exit(0);
                    break;
                }

                default:
                    break;
                }
            }
        }
Пример #32
0
 public SpotMarketItem(Coin c)
 {
     this.Coin = c;
     Deals     = new HotSpotDeals();
 }
        public async Task AcceptToMemoryPool_WithP2SHValidTxns_IsSuccessfullAsync()
        {
            string dataDir = GetTestDirectoryPath(this);

            BitcoinSecret     miner   = new BitcoinSecret(new Key(), Network.RegTest);
            ITestChainContext context = await TestChainFactory.CreateAsync(Network.RegTest, miner.PubKey.Hash.ScriptPubKey, dataDir);

            IMempoolValidator validator = context.MempoolValidator;

            Assert.NotNull(validator);

            BitcoinSecret alice   = new BitcoinSecret(new Key(), Network.RegTest);
            BitcoinSecret bob     = new BitcoinSecret(new Key(), Network.RegTest);
            BitcoinSecret satoshi = new BitcoinSecret(new Key(), Network.RegTest);
            BitcoinSecret nico    = new BitcoinSecret(new Key(), Network.RegTest);

            // corp needs two out of three of alice, bob, nico
            Script corpMultiSig = PayToMultiSigTemplate
                                  .Instance
                                  .GenerateScriptPubKey(2, new[] { alice.PubKey, bob.PubKey, nico.PubKey });

            // P2SH address for corp multi-sig
            BitcoinScriptAddress corpRedeemAddress = corpMultiSig.GetScriptAddress(Network.RegTest);

            // Fund corp
            // 50 Coins come from first tx on chain - send corp 42 and change back to miner
            Coin coin = new Coin(context.SrcTxs[0].GetHash(), 0, context.SrcTxs[0].TotalOut, miner.ScriptPubKey);
            TransactionBuilder txBuilder  = new TransactionBuilder(Network.RegTest);
            Transaction        fundP2shTx = txBuilder
                                            .AddCoins(new List <Coin> {
                coin
            })
                                            .AddKeys(miner)
                                            .Send(corpRedeemAddress, "42.00")
                                            .SendFees("0.001")
                                            .SetChange(miner.GetAddress())
                                            .BuildTransaction(true);

            Assert.True(txBuilder.Verify(fundP2shTx)); //check fully signed
            MempoolValidationState state = new MempoolValidationState(false);

            Assert.True(await validator.AcceptToMemoryPool(state, fundP2shTx), $"Transaction: {nameof(fundP2shTx)} failed mempool validation.");

            // AliceBobNico corp. send 20 to Satoshi
            Coin[] corpCoins = fundP2shTx.Outputs
                               .Where(o => o.ScriptPubKey == corpRedeemAddress.ScriptPubKey)
                               .Select(o => ScriptCoin.Create(Network.RegTest, new OutPoint(fundP2shTx.GetHash(), fundP2shTx.Outputs.IndexOf(o)), o, corpMultiSig))
                               .ToArray();

            txBuilder = new TransactionBuilder(Network.RegTest);
            Transaction p2shSpendTx = txBuilder
                                      .AddCoins(corpCoins)
                                      .AddKeys(alice, bob)
                                      .Send(satoshi.GetAddress(), "20")
                                      .SendFees("0.001")
                                      .SetChange(corpRedeemAddress)
                                      .BuildTransaction(true);

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

            Assert.True(await validator.AcceptToMemoryPool(state, p2shSpendTx), $"Transaction: {nameof(p2shSpendTx)} failed mempool validation.");
        }
Пример #34
0
 public bool CheckCoin(Coin coin)
 {
     return(Settings.coinsValues.Contains(coin.Value));
 }
        public async Task AcceptToMemoryPool_WithMultiSigValidTxns_IsSuccessfullAsync()
        {
            string dataDir = GetTestDirectoryPath(this);

            BitcoinSecret     miner   = new BitcoinSecret(new Key(), Network.RegTest);
            ITestChainContext context = await TestChainFactory.CreateAsync(Network.RegTest, miner.PubKey.Hash.ScriptPubKey, dataDir);

            IMempoolValidator validator = context.MempoolValidator;

            Assert.NotNull(validator);

            BitcoinSecret alice   = new BitcoinSecret(new Key(), Network.RegTest);
            BitcoinSecret bob     = new BitcoinSecret(new Key(), Network.RegTest);
            BitcoinSecret satoshi = new BitcoinSecret(new Key(), Network.RegTest);
            BitcoinSecret nico    = new BitcoinSecret(new Key(), Network.RegTest);

            // corp needs two out of three of alice, bob, nico
            Script corpMultiSig = PayToMultiSigTemplate
                                  .Instance
                                  .GenerateScriptPubKey(2, new[] { alice.PubKey, bob.PubKey, nico.PubKey });

            // Fund corp
            // 50 Coins come from first tx on chain - send corp 42 and change back to miner
            Coin coin = new Coin(context.SrcTxs[0].GetHash(), 0, context.SrcTxs[0].TotalOut, miner.ScriptPubKey);
            TransactionBuilder txBuilder        = new TransactionBuilder(Network.RegTest);
            Transaction        sendToMultiSigTx = txBuilder
                                                  .AddCoins(new List <Coin> {
                coin
            })
                                                  .AddKeys(miner)
                                                  .Send(corpMultiSig, "42.00")
                                                  .SendFees("0.001")
                                                  .SetChange(miner.GetAddress())
                                                  .BuildTransaction(true);

            Assert.True(txBuilder.Verify(sendToMultiSigTx)); //check fully signed
            MempoolValidationState state = new MempoolValidationState(false);

            Assert.True(await validator.AcceptToMemoryPool(state, sendToMultiSigTx), $"Transaction: {nameof(sendToMultiSigTx)} failed mempool validation.");

            // AliceBobNico corp. send to Satoshi
            Coin[] corpCoins = sendToMultiSigTx.Outputs
                               .Where(o => o.ScriptPubKey == corpMultiSig)
                               .Select(o => new Coin(new OutPoint(sendToMultiSigTx.GetHash(), sendToMultiSigTx.Outputs.IndexOf(o)), o))
                               .ToArray();

            // Alice initiates the transaction
            txBuilder = new TransactionBuilder(Network.RegTest);
            Transaction multiSigTx = txBuilder
                                     .AddCoins(corpCoins)
                                     .AddKeys(alice)
                                     .Send(satoshi.GetAddress(), "4.5")
                                     .SendFees("0.001")
                                     .SetChange(corpMultiSig)
                                     .BuildTransaction(true);

            Assert.True(!txBuilder.Verify(multiSigTx)); //Well, only one signature on the two required...

            // Nico completes the transaction
            txBuilder  = new TransactionBuilder(Network.RegTest);
            multiSigTx = txBuilder
                         .AddCoins(corpCoins)
                         .AddKeys(nico)
                         .SignTransaction(multiSigTx);
            Assert.True(txBuilder.Verify(multiSigTx));

            Assert.True(await validator.AcceptToMemoryPool(state, multiSigTx), $"Transaction: {nameof(multiSigTx)} failed mempool validation.");
        }
Пример #36
0
        private void Code17()
        {
            var bob      = new Key();
            var alice    = new Key();
            var bobAlice = PayToMultiSigTemplate
                           .Instance
                           .GenerateScriptPubKey(2, bob.PubKey, alice.PubKey);

            Transaction init = new Transaction();

            init.Outputs.Add(new TxOut(Money.Coins(1.0m), alice.PubKey));
            init.Outputs.Add(new TxOut(Money.Coins(1.0m), bob.PubKey.Hash));
            init.Outputs.Add(new TxOut(Money.Coins(1.0m), bobAlice));


            var satoshi = new Key();

            Coin[] coins = init.Outputs.AsCoins().ToArray();

            Coin aliceCoin    = coins[0];
            Coin bobCoin      = coins[1];
            Coin bobAliceCoin = coins[2];

            var         builder = new TransactionBuilder();
            Transaction tx      = builder
                                  .AddCoins(bobCoin)
                                  .AddKeys(bob)
                                  .Send(satoshi, Money.Coins(0.2m))
                                  .SetChange(bob)
                                  .Then()
                                  .AddCoins(aliceCoin)
                                  .AddKeys(alice)
                                  .Send(satoshi, Money.Coins(0.3m))
                                  .SetChange(alice)
                                  .Then()
                                  .AddCoins(bobAliceCoin)
                                  .AddKeys(bob, alice)
                                  .Send(satoshi, Money.Coins(0.5m))
                                  .SetChange(bobAlice)
                                  .SendFees(Money.Coins(0.0001m))
                                  .BuildTransaction(sign: true);


            Console.WriteLine(builder.Verify(tx));

            init = new Transaction();
            init.Outputs.Add(new TxOut(Money.Coins(1.0m), bobAlice.Hash));

            coins = init.Outputs.AsCoins().ToArray();
            ScriptCoin bobAliceScriptCoin = coins[0].ToScriptCoin(bobAlice);

            builder = new TransactionBuilder();
            tx      = builder
                      .AddCoins(bobAliceScriptCoin)
                      .AddKeys(bob, alice)
                      .Send(satoshi, Money.Coins(1.0m))
                      .SetChange(bobAlice.Hash)
                      .BuildTransaction(true);
            Console.WriteLine(builder.Verify(tx));

            Key scanKey = new Key();
            BitcoinStealthAddress darkAliceBob =
                new BitcoinStealthAddress
                (
                    scanKey: scanKey.PubKey,
                    pubKeys: new[] { alice.PubKey, bob.PubKey },
                    signatureCount: 2,
                    bitfield: null,
                    network: Network.Main
                );

            //Fake transaction
            init = new Transaction();
            darkAliceBob
            .CreatePayment()
            .AddToTransaction(init, Money.Coins(1.0m));

            //Get the stealth coin with the scanKey
            StealthCoin stealthCoin
                = StealthCoin.Find(init, darkAliceBob, scanKey);

            //Spend it
            tx = builder
                 .AddCoins(stealthCoin)
                 .AddKeys(bob, alice, scanKey)
                 .Send(satoshi, Money.Coins(1.0m))
                 .SetChange(bobAlice.Hash)
                 .BuildTransaction(true);
            Console.WriteLine(builder.Verify(tx));
        }
Пример #37
0
    public void InsertCoin(string coin)
    {
        Coin rem = (Coin)Enum.Parse(typeof(Coin), coin);

        this.coins += (int)rem;
    }
Пример #38
0
        public async Task RefreshCoins()
        {
            for (int i = 0; i < Coins.Count; i++)
            {
                try
                {
                    string json = AlertClient.DownloadString(TickerURL + Coins[i].Id);

                    List <Coin> Items     = JsonConvert.DeserializeObject <List <Coin> >(json);
                    Coin        FoundCoin = Items.Find(x => x.Id == Coins[i].Id);
                    FoundCoin.Alert = Coins[i].Alert;
                    Coins[i]        = FoundCoin;
                }
                catch (WebException) { }
            }

            if (PriceChannel != null && VolumeChannel != null && TetherChannel != null && MiscPriceChannel != null && MiscVolChannel != null && BitcoinChannel != null)
            {
                foreach (Coin coin in Coins)
                {
                    string message     = null;
                    bool   NeedsUpdate = !UpdateHistoy.TryGetValue(coin.Id, out DateTime LastUpdate);
                    bool   HasAlerted  = false;
                    var    serverEmote = Emotes.FirstOrDefault(x => x.Name == coin.Symbol);

                    if (NeedsUpdate || TimeSpan.FromHours(1) <= (DateTime.Now - LastUpdate))
                    {
                        if (coin.Alert == "volume" || coin.Alert == "main" || coin.Alert == "main-volume")
                        {
                            message = null;

                            if (VolumeHistory.ContainsKey(coin.Id))
                            {
                                double Percent = ((coin.Day_volume_usd - VolumeHistory[coin.Id]) / VolumeHistory[coin.Id]) * 100;
                                if (Percent >= 4)
                                {
                                    message = (serverEmote == null ? coin.Symbol : "<:" + coin.Symbol + ":" + serverEmote.Id + ">") + " <:UP:361650797802684416> " + Math.Round(Math.Abs(Percent), 2) + "%";
                                }
                                else if (Percent <= -4)
                                {
                                    message = (serverEmote == null ? coin.Symbol : "<:" + coin.Symbol + ":" + serverEmote.Id + ">") + " <:DOWN:361650806409396224> " + Math.Round(Math.Abs(Percent), 2) + "%";
                                }

                                VolumeHistory[coin.Id] = coin.Day_volume_usd;
                            }
                            else
                            {
                                VolumeHistory.Add(coin.Id, coin.Day_volume_usd);
                            }

                            if (message != null)
                            {
                                try
                                {
                                    if (coin.Id == "bitcoin")
                                    {
                                        message += " V";
                                        await BitcoinChannel.SendMessageAsync(message);
                                    }
                                    else if (coin.Id == "tether")
                                    {
                                        await TetherChannel.SendMessageAsync(message);
                                    }
                                    else if (coin.Alert == "main")
                                    {
                                        await VolumeChannel.SendMessageAsync(message);
                                    }
                                    else
                                    {
                                        await MiscVolChannel.SendMessageAsync(message);
                                    }
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e.Message);
                                }

                                HasAlerted = true;
                            }
                        }

                        if (coin.Alert == "price" || coin.Alert == "main")
                        {
                            message = null;

                            if (coin.Percent_change_hour >= 4)
                            {
                                message = (serverEmote == null ? coin.Symbol : "<:" + coin.Symbol + ":" + serverEmote.Id + ">") + " <:UP:361650797802684416> " + Math.Abs(coin.Percent_change_hour) + "%";
                            }
                            else if (coin.Percent_change_hour <= -4)
                            {
                                message = (serverEmote == null ? coin.Symbol : "<:" + coin.Symbol + ":" + serverEmote.Id + ">") + " <:DOWN:361650806409396224> " + Math.Abs(coin.Percent_change_hour) + "%";
                            }

                            if (message != null)
                            {
                                try
                                {
                                    if (coin.Id == "bitcoin")
                                    {
                                        message += " P";
                                        await BitcoinChannel.SendMessageAsync(message);
                                    }
                                    else if (coin.Alert == "main")
                                    {
                                        await PriceChannel.SendMessageAsync(message);
                                    }
                                    else
                                    {
                                        await MiscPriceChannel.SendMessageAsync(message);
                                    }
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e.Message);
                                }

                                HasAlerted = true;
                            }
                        }

                        if (HasAlerted)
                        {
                            if (NeedsUpdate)
                            {
                                UpdateHistoy.Add(coin.Id, DateTime.Now);
                            }
                            else
                            {
                                UpdateHistoy[coin.Id] = DateTime.Now;
                            }
                        }
                    }
                }
            }
        }
Пример #39
0
    private void SaveXmlData()
    {
        // 创建 save 对象和 xml 文档对象
        Save        save        = CreateSaveObject();
        XmlDocument xmlDocument = new XmlDocument();

        #region Xml 存档数据生成
        XmlElement root = xmlDocument.CreateElement("Save");

        // 金币得分
        XmlElement CoinNum = xmlDocument.CreateElement("CoinNum");
        CoinNum.InnerText = save.coin.ToString();
        root.AppendChild(CoinNum);

        // 玩家位置
        XmlElement PlayerPosX = xmlDocument.CreateElement("PlayerPosX");
        XmlElement PlayerPosY = xmlDocument.CreateElement("PlayerPosY");
        XmlElement PlayerPosZ = xmlDocument.CreateElement("PlayerPosZ");

        PlayerPosX.InnerText = save.playerPosX.ToString();
        PlayerPosY.InnerText = save.playerPosY.ToString();
        PlayerPosZ.InnerText = save.playerPosZ.ToString();

        root.AppendChild(PlayerPosX);
        root.AppendChild(PlayerPosY);
        root.AppendChild(PlayerPosZ);

        // 各个金币的状态
        XmlElement Coin, isDead, CoinPosX, CoinPosY, CoinPosZ;

        for (int i = 0; i < coins.Length; i++)
        {
            Coin     = xmlDocument.CreateElement("Coin");
            isDead   = xmlDocument.CreateElement("isDead");
            CoinPosX = xmlDocument.CreateElement("CoinPosX");
            CoinPosY = xmlDocument.CreateElement("CoinPosY");
            CoinPosZ = xmlDocument.CreateElement("CoinPosZ");

            isDead.InnerText   = save.coins[i].isDead.ToString();
            CoinPosX.InnerText = save.coins[i].x.ToString();
            CoinPosY.InnerText = save.coins[i].y.ToString();
            CoinPosZ.InnerText = save.coins[i].z.ToString();

            Coin.AppendChild(isDead);
            Coin.AppendChild(CoinPosX);
            Coin.AppendChild(CoinPosY);
            Coin.AppendChild(CoinPosZ);

            root.AppendChild(Coin);
        }

        // 添加 root 节点到 xml 文档中
        xmlDocument.AppendChild(root);

        #endregion

        // 存储 xml 文档到 save.xml 文件中
        xmlDocument.Save(Application.dataPath + "/SaveData/save.xml");

        if (File.Exists(Application.dataPath + "/SaveData/save.xml"))
        {
            Debug.Log("存档成功");
        }
    }
        public static void ColoredCoins()
        {
            // ISSUING AN ASSET
            // In Open Asset, the Asset ID is derived from the issuers ScriptPubKey. To issue a Colored Coin, you must prove ownership of the ScriptPubKey by spending from it.
            // The coin you spend for issuing colored coins is called the "Issuance Coin" in NBitcoin. Create an issuance coin:
            // coin being used for issuing the asset:
            //{
            //    "transactionId": "eb49a599c749c82d824caf9dd69c4e359261d49bbb0b9d6dc18c59bc9214e43b",
            //    "index": 0,
            //    "value": 2000000,
            //    "scriptPubKey": "76a914c81e8e7b7ffca043b088a992795b15887c96159288ac",
            //    "redeemScript": null
            //}
            var coin = new Coin(
                fromTxHash: new uint256("eb49a599c749c82d824caf9dd69c4e359261d49bbb0b9d6dc18c59bc9214e43b"),
                fromOutputIndex: 0,
                amount: Money.Satoshis(2000000),
                scriptPubKey: new Script(Encoders.Hex.DecodeData("76a914c81e8e7b7ffca043b088a992795b15887c96159288ac")));

            var issuance = new IssuanceCoin(coin);
            // build and sign transaction using TransactionBuilder
            var nico    = BitcoinAddress.Create("15sYbVpRh6dyWycZMwPdxJWD4xbfxReeHe");
            var bookKey = new BitcoinSecret("???"); // program errors bc we don't have nico's private key/secret
            TransactionBuilder builder = new TransactionBuilder();

            var tx = builder
                     .AddCoins(coin)
                     .AddKeys(bookKey)
                     .IssueAsset(nico, new NBitcoin.OpenAsset.AssetMoney(issuance.AssetId, quantity: 10)) // this is new part relevant to issuing colored coins
                     .SendFees(Money.Coins(0.0001m))
                     .SetChange(bookKey.GetAddress())
                     .BuildTransaction(sign: true);

            Console.WriteLine(tx);
            // after tx verification, it's ready to be sent to the network
            Console.WriteLine(builder.Verify(tx));
            // review: broadcasting with QBitNinja:
            var client = new QBitNinjaClient(Network.Main);
            BroadcastResponse broadcastResponse = client.Broadcast(tx).Result;

            if (!broadcastResponse.Success)
            {
                Console.WriteLine("ErrorCode: " + broadcastResponse.Error.ErrorCode);
                Console.WriteLine("Error message: " + broadcastResponse.Error.Reason);
            }
            else
            {
                Console.WriteLine("Success!");
            }
            // or broadcast with your own Bitcoin Core node:
            using (var node = Node.ConnectToLocal(Network.Main))
            {
                node.VersionHandshake();
                node.SendMessage(new InvPayload(InventoryType.MSG_TX, tx.GetHash())); // first send just the hash of your transaction
                node.SendMessage(new TxPayload(tx));                                  // then send signed transaction
                Thread.Sleep(500);
            }

            // Colored Coins have their own address format that only colored coin wallets understand, to prevent sending colored coins to wallets that don't support it
            nico = BitcoinAddress.Create("15sYbVpRh6dyWycZMwPdxJWD4xbfxReeHe");
            Console.WriteLine(nico.ToColoredAddress());

            // colored coin Asset ID is derived from issuer's ScriptPubKey. here is how to get the ID:
            var book    = BitcoinAddress.Create("1KF8kUVHK42XzgcmJF4Lxz4wcL5WDL97PB");
            var assetId = new AssetId(book).GetWif(Network.Main);

            Console.WriteLine(assetId);

            // TRANSFER AN ASSET
            // to send received colored coins, you need to build a ColredCoin
            // received transaction to spent:
            //{
            //    "transactionId": "fa6db7a2e478f3a8a0d1a77456ca5c9fa593e49fd0cf65c7e349e5a4cbe58842",
            //    "index": 0,
            //    "value": 600,
            //    "scriptPubKey": "76a914356facdac5f5bcae995d13e667bb5864fd1e7d5988ac",
            //    "redeemScript": null,
            //    "assetId": "AVAVfLSb1KZf9tJzrUVpktjxKUXGxUTD4e",
            //    "quantity": 10
            //}
            //var coin2 = new Coin(
            //    fromTxHash: new uint256("fa6db7a2e478f3a8a0d1a77456ca5c9fa593e49fd0cf65c7e349e5a4cbe58842"),
            //    fromOutputIndex: 0,
            //    amount: Money.Satoshis(600),
            //    scriptPubKey: new Script(Encoders.Hex.DecodeData("76a914356facdac5f5bcae995d13e667bb5864fd1e7d5988ac")));
            //BitcoinAssetId assetId2 = new BitcoinAssetId("AVAVfLSb1KZf9tJzrUVpktjxKUXGxUTD4e");
            //ColoredCoin colored = coin2.ToColoredCoin(assetId2, 10);

            //// also, in this exampled, we needed another coin forFees to pay the tx fee
            //var forFees = new Coin(
            //    fromTxHash: new uint256("7f296e96ec3525511b836ace0377a9fbb723a47bdfb07c6bc3a6f2a0c23eba26"),
            //    fromOutputIndex: 0,
            //    amount: Money.Satoshis(4425000),
            //    scriptPubKey: new Script(Encoders.Hex.DecodeData("76a914356facdac5f5bcae995d13e667bb5864fd1e7d5988ac")));

            //TransactionBuilder builder2 = new TransactionBuilder();
            //var tx2 = builder2
            //    .AddCoins(colored, forFees) // note: added newly created colored coin, and coin to pay fees in this example
            //    .AddKeys(bookKey)
            //    .SendAsset(book, new AssetMoney(assetId2, 10))
            //    .SetChange(nico)
            //    .SendFees(Money.Coins(0.0001m))
            //    .BuildTransaction(true);

            //Console.WriteLine(tx2); // again, errors b/c we don't have Nico's secret and I don't feel like creating another real tx and dealing with privacy when I push this to github

            // UNIT TESTS
            // create 2 issuers silver and gold, and fake tx to give bitcoin to silver, gold, satoshi
            var gold     = new Key();
            var silver   = new Key();
            var goldId   = gold.PubKey.ScriptPubKey.Hash.ToAssetId();
            var silverId = silver.PubKey.ScriptPubKey.Hash.ToAssetId();

            var alice   = new Key();
            var bob     = new Key();
            var satoshi = new Key();

            var init = new Transaction()
            {
                Outputs =
                {
                    new TxOut("1.0", gold),
                    new TxOut("1.0", silver),
                    new TxOut("1.0", satoshi)
                }
            };
            // in NBitcoin the sammary of color coin issuance and transfer is described by class ColoredTransaction
            // the trick to writing unit tests is to use an in memory IColoredTransactionRepository
            var repo = new NoSqlColoredTransactionRepository();

            // now we can put the init tx inside
            repo.Transactions.Put(init);
            // now we can get the color
            ColoredTransaction color = ColoredTransaction.FetchColors(init, repo);

            Console.WriteLine(color);
            // now we will use the coins sent to silver and gold as Issuance coins
            var issuanceCoins = init
                                .Outputs
                                .AsCoins()
                                .Take(2)
                                .Select((c, i) => new IssuanceCoin(c))
                                .OfType <ICoin>()
                                .ToArray();
            var sendGoldToSatoshi = new Transaction(); // use TransactionBuilder to send Gold to Satoshi, then put resulting tx in repo and print result

            var goldCoin = ColoredCoin.Find(sendGoldToSatoshi, color).FirstOrDefault();

            builder = new TransactionBuilder();
            var sendToBobAndAlice = builder
                                    .AddKeys(satoshi)
                                    .AddCoins(goldCoin)
                                    .SendAsset(alice, new AssetMoney(goldId, 4))
                                    .SetChange(satoshi)
                                    .BuildTransaction(true);
            // not enough funds; goldCoin input only has 600sats and need 1200 for output to transfer assets to Alice and change to satoshi; add coin
            var satoshiBtc = init.Outputs.AsCoins().Last();

            builder = new TransactionBuilder();
            var sendToAlice = builder
                              .AddKeys(satoshi)
                              .AddCoins(goldCoin, satoshiBtc)
                              .SendAsset(alice, new AssetMoney(goldId, 4))
                              .SetChange(satoshi)
                              .BuildTransaction(true);

            repo.Transactions.Put(sendToAlice);
            color = ColoredTransaction.FetchColors(sendToAlice, repo);
            // see transaction and its color
            Console.WriteLine(sendToAlice);
            Console.WriteLine(color);
            // have made a unit test that emits and transfers some assets w/o any external dependencies
        }
Пример #41
0
        public Coin GetCoin(Coin attributes)
        {
            attributes.SetCoin(GetCoin(attributes.Weight, attributes.Diameter, attributes.Thickness));

            return(attributes);
        }
Пример #42
0
 /// <summary>
 /// A utility method that calculates how much new Bitcoin would be created by the block at the given height.
 /// The inflation of Bitcoin is predictable and drops roughly every 4 years (210,000 blocks).
 /// At the dawn of the system it was 50 coins per block, in late 2012 it went to 25 coins per block, and so on.
 /// The size of a coinbase transaction is inflation plus fees.
 /// The half-life is controlled by SubsidyDecreaseBlockCount
 /// </summary>
 /// <param name="height"></param>
 /// <returns></returns>
 public BigInteger GetBlockInflation(int height)
 {
     return(Coin.FromCoins(50).Nanocoins.ShiftRight((int)(height / SubsidyDecreaseBlockCount)));
 }
Пример #43
0
        void Start()
        {
            _waypointsHolder = new GameObject("_waypointsHolder");
            _waypointsHolder.transform.SetParent(transform);
            GameObject coinsHolder = new GameObject("_coinsHolder");

            coinsHolder.transform.SetParent(transform);
            GameObject wallsHolder = new GameObject("_wallsHolder");

            wallsHolder.transform.SetParent(transform);
            GameObject floorHolder = new GameObject("_floorHolder");

            floorHolder.transform.SetParent(transform);
            GameObject pillarsHolder = new GameObject("_pillarsHolder");

            pillarsHolder.transform.SetParent(transform);


            if (!FullRandom)
            {
                Random.seed = RandomSeed;
            }

            switch (Algorithm)
            {
            case MazeGenerationAlgorithm.PureRecursive:
                mMazeGenerator = new RecursiveMazeGenerator(Rows, Columns);
                break;

            case MazeGenerationAlgorithm.RecursiveTree:
                mMazeGenerator = new RecursiveTreeMazeGenerator(Rows, Columns);
                break;

            case MazeGenerationAlgorithm.RandomTree:
                mMazeGenerator = new RandomTreeMazeGenerator(Rows, Columns);
                break;

            case MazeGenerationAlgorithm.OldestTree:
                mMazeGenerator = new OldestTreeMazeGenerator(Rows, Columns);
                break;

            case MazeGenerationAlgorithm.RecursiveDivision:
                mMazeGenerator = new DivisionMazeGenerator(Rows, Columns);
                break;
            }

            int coinsPlaced = 0;

            mMazeGenerator.GenerateMaze();
            for (int row = 0; row < Rows; row++)
            {
                for (int column = 0; column < Columns; column++)
                {
                    float      x    = transform.position.x + column * (CellWidth + (AddGaps ? .2f : 0));
                    float      z    = transform.position.z + row * (CellHeight + (AddGaps ? .2f : 0));
                    MazeCell   cell = mMazeGenerator.GetMazeCell(row, column);
                    GameObject tmp;
                    tmp = Instantiate(Floor, new Vector3(x, 0, z), Quaternion.Euler(0, 0, 0)) as GameObject;
                    tmp.transform.parent = floorHolder.transform;
                    if (cell.WallRight)
                    {
                        tmp = Instantiate(Wall, new Vector3(x + CellWidth / 2, 0, z) + Wall.transform.position,
                                          Quaternion.Euler(0, 90, 0)) as GameObject; // right
                        tmp.transform.parent = wallsHolder.transform;
                    }

                    if (cell.WallFront)
                    {
                        tmp = Instantiate(Wall, new Vector3(x, 0, z + CellHeight / 2) + Wall.transform.position,
                                          Quaternion.Euler(0, 0, 0)) as GameObject; // front
                        tmp.transform.parent = wallsHolder.transform;
                    }

                    if (cell.WallLeft)
                    {
                        tmp = Instantiate(Wall, new Vector3(x - CellWidth / 2, 0, z) + Wall.transform.position,
                                          Quaternion.Euler(0, 270, 0)) as GameObject; // left
                        tmp.transform.parent = wallsHolder.transform;
                    }

                    if (cell.WallBack)
                    {
                        tmp = Instantiate(Wall, new Vector3(x, 0, z - CellHeight / 2) + Wall.transform.position,
                                          Quaternion.Euler(0, 180, 0)) as GameObject; // back
                        tmp.transform.parent = wallsHolder.transform;
                    }

                    if (cell.IsGoal && _coinPrefab != null && Coin.NumOfCoinsCreated < numOfCoinToPass)
                    {
                        Coin coin = Instantiate(_coinPrefab, new Vector3(x, 1, z), Quaternion.Euler(0, 0, 0));
                        coin.transform.SetParent(coinsHolder.transform);
                        Coin.NumOfCoinsCreated++;
                    }
                    else
                    {
                        if (!_keyExists && _keyPrefab != null)
                        {
                            Key key = Instantiate(_keyPrefab, new Vector3(x, _waypointHeight, z), _keyPrefab.transform.rotation);
                            key.transform.SetParent(transform);
                            _keyExists = true;
                        }
                        else if (_waypointPrefab != null)
                        {
                            Waypoint wp = Instantiate(_waypointPrefab, new Vector3(x, _waypointHeight, z), Quaternion.identity);
                            wp.transform.SetParent(_waypointsHolder.transform);
                        }
                    }
                }
            }

            if (Pillar != null)
            {
                for (int row = 0; row < Rows + 1; row++)
                {
                    for (int column = 0; column < Columns + 1; column++)
                    {
                        float      x   = transform.position.x + column * (CellWidth + (AddGaps ? .2f : 0));
                        float      z   = transform.position.z + row * (CellHeight + (AddGaps ? .2f : 0));
                        GameObject tmp = Instantiate(Pillar, new Vector3(x - CellWidth / 2, 0, z - CellHeight / 2),
                                                     Quaternion.identity);
                        tmp.transform.parent = pillarsHolder.transform;
                        if (row != 0 && column != 0 && row != Rows && column != Columns)
                        {
                            tmp.transform.GetChild(1).gameObject.SetActive(false);
                        }
                    }
                }
            }
        }
Пример #44
0
    void OnCollisionEnter2D(Collision2D coll)
    {
        if (coll.gameObject.tag == "Ground")
        {
            OnGround  = false;
            canDash   = false;
            jumpStart = false;
            tRight    = false;
            tLeft     = false;
            dying     = true;
            GameObject.FindGameObjectWithTag("FireballSfx").GetComponent <AudioSource>().Play();
            GameMaster.EndGame();
            if (!winning)
            {
                PlayerStats.clear();
            }
            anim.SetBool("Dead", true);

            destroyer = false;
        }
        if (destroyer)
        {
            Destroy(coll.gameObject.GetComponent <BoxCollider2D> ());
        }

        if (coll.gameObject.tag == "fireball")
        {
            print("hit fireball");
            GameObject.FindGameObjectWithTag("FireballSfx").GetComponent <AudioSource>().Play();
            OnGround  = false;
            canDash   = false;
            jumpStart = false;
            tRight    = false;
            tLeft     = false;
            dying     = true;
            GameMaster.EndGame();
            if (!winning)
            {
                PlayerStats.clear();
            }
            anim.SetBool("trap", true);
            m_Rigidbody.velocity = new Vector2(0, 0);
            m_Rigidbody.AddForce(m_JumpForce, ForceMode2D.Impulse);
            m_Rigidbody.gravityScale = 2;
            Destroy(coll.gameObject.GetComponent <CircleCollider2D> ());
            destroyer = true;
        }
        if (coll.gameObject.tag == "Back")
        {
            print("hit back");
            anim.SetBool("idle", false);
            allTheWayLeft = true;
        }
        if (coll.gameObject.tag == "Coin")
        {
            if (!dying)
            {
                Coin coin = coll.gameObject.GetComponent <Coin>();
                coin.Collect();
                PlayerStats.getCoin();
            }
        }
        if (coll.gameObject.tag == "Wall")
        {
            m_Rigidbody.gravityScale = 3f;
        }
        if (coll.gameObject.tag == "Plank")
        {
            print("hit plank");

            OnGround     = true;
            doublejumped = false;
            anim.SetBool("jump", false);
            numberofjumps = 0;
            dashing       = false;
            canDash       = true;
        }
        if (coll.gameObject.tag == "Column1")
        {
            if (!columnhit)
            {
                print("hit Column1");
                PlayerStats.Scored(300);
                win();
                columnhit = true;
            }
        }
        if (coll.gameObject.tag == "Column2")
        {
            if (!columnhit)
            {
                print("hit Column2");
                PlayerStats.Scored(500);
                win();
                columnhit = true;
            }
        }
        if (coll.gameObject.tag == "Column3")
        {
            if (!columnhit)
            {
                print("hit Column3");
                PlayerStats.Scored(1000);
                win();
                columnhit = true;
            }
        }
    }
Пример #45
0
        private async Task RefreshOutputs(string type, string assetId)
        {
            Console.WriteLine($"Start process: type={type}" + (assetId != null ? $", asset={assetId}" : null));

            IPregeneratedOutputsQueue queue;
            string address;

            if (type == "fee")
            {
                queue   = _pregeneratedOutputsQueueFactory.CreateFeeQueue();
                address = _feeAddress;
            }
            else
            {
                var asset = await _assetRepository.GetAssetById(assetId);

                queue   = _pregeneratedOutputsQueueFactory.Create(asset.BlockChainAssetId);
                address = asset.AssetAddress;
                Console.WriteLine("BlockchainAssetId : " + asset.BlockChainAssetId);
            }

            var count = await queue.Count();

            Console.WriteLine($"Start collect {count} outputs from queue");

            var set = new HashSet <OutPoint>();

            while (count-- > 0)
            {
                Coin coin = null;
                try
                {
                    coin = await queue.DequeueCoin();
                }
                catch (Exception)
                {
                }
                finally
                {
                    if (coin != null && !set.Contains(coin.Outpoint))
                    {
                        set.Add(coin.Outpoint);
                        await queue.EnqueueOutputs(coin);
                    }
                }
            }

            Console.WriteLine($"Coins collected");

            var coins = (await _bitcoinOutputsService.GetOnlyNinjaOutputs(address, 1, int.MaxValue)).OfType <Coin>().ToArray();

            Console.WriteLine($"Received {coins.Length} outputs from qbitninja");

            coins = coins.Where(x => !set.Contains(x.Outpoint)).ToArray();

            Console.WriteLine($"Got {coins.Length} missing outputs");

            await queue.EnqueueOutputs(coins);

            //Console.WriteLine("Start remove outputs from queue");
            //int i = 0;
            //while (true)
            //    try
            //    {
            //        await queue.DequeueCoin();
            //        i++;
            //    }
            //    catch (BackendException)
            //    {
            //        break;
            //    }
            //Console.WriteLine($"Removed {i} coins from queue");
            //var coins = (await _bitcoinOutputsService.GetUncoloredUnspentOutputs(address)).OfType<Coin>().ToArray();

            //Console.WriteLine($"Received {coins.Length} outputs from qbitninja");
            //Console.WriteLine("Start add coins to queue");

            //await queue.EnqueueOutputs(coins);

            Console.WriteLine("All coins successfuly added to queue");
            Console.WriteLine(Environment.NewLine);
        }
Пример #46
0
 //this class subscribes CoinHasBeenHit handler function to the relevant delegate
 public void Subscribe(Coin myCoin)
 {
     myCoin.Coinhit += new Coin.CoinHitHandler(CoinHasBeenHit);
 }
Пример #47
0
        public async Task <bool> EnsureSpentCoinsLoadedAsync(ITransactionRepository transactions)
        {
            if (SpentCoins != null)
            {
                return(true);
            }

            bool           cleanSpent = false;
            CoinCollection result     = new CoinCollection();

            for (int i = 0; i < SpentOutpoints.Count; i++)
            {
                var outpoint = SpentOutpoints[i];
                if (outpoint.IsNull)
                {
                    continue;
                }
                var prev = await transactions.GetAsync(outpoint.Hash).ConfigureAwait(false);

                if (prev == null)
                {
                    return(false);
                }

                var coin = new Coin(outpoint, prev.Outputs[SpentOutpoints[i].N]);
                if (coin.ScriptPubKey != GetScriptPubkey(i))
                {
                    cleanSpent        = true;
                    SpentOutpoints[i] = null;
                }
                else
                {
                    result.Add(coin);
                }
            }

            if (cleanSpent)
            {
                List <uint>        spentIndices   = new List <uint>();
                List <OutPoint>    spentOutpoints = new List <OutPoint>();
                List <MatchedRule> matchedRules   = new List <MatchedRule>();
                for (int i = 0; i < SpentOutpoints.Count; i++)
                {
                    if (SpentOutpoints[i] != null)
                    {
                        spentIndices.Add(SpentIndices[i]);
                        spentOutpoints.Add(SpentOutpoints[i]);
                        if (MatchedRules != null && MatchedRules.Count != 0)
                        {
                            matchedRules.Add(MatchedRules[i]);
                        }
                    }
                }
                SpentIndices   = spentIndices;
                SpentOutpoints = spentOutpoints;
                MatchedRules   = matchedRules;
            }

            SpentCoins = result;
            UpdateToScriptCoins();
            return(true);
        }
Пример #48
0
 internal bool ValidateCoin(Coin c)
 {
     return(IsValid(c) && (int)c < MAX_ACCEPTED_MONEY);
 }
Пример #49
0
    public async Task ReadAsync(TProtocol iprot, CancellationToken cancellationToken)
    {
        iprot.IncrementRecursionDepth();
        try
        {
            TField field;
            await iprot.ReadStructBeginAsync(cancellationToken);

            while (true)
            {
                field = await iprot.ReadFieldBeginAsync(cancellationToken);

                if (field.Type == TType.Stop)
                {
                    break;
                }

                switch (field.ID)
                {
                case 1:
                    if (field.Type == TType.List)
                    {
                        {
                            Historys = new List <CoinHistory>();
                            TList _list105 = await iprot.ReadListBeginAsync(cancellationToken);

                            for (int _i106 = 0; _i106 < _list105.Count; ++_i106)
                            {
                                CoinHistory _elem107;
                                _elem107 = new CoinHistory();
                                await _elem107.ReadAsync(iprot, cancellationToken);

                                Historys.Add(_elem107);
                            }
                            await iprot.ReadListEndAsync(cancellationToken);
                        }
                    }
                    else
                    {
                        await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken);
                    }
                    break;

                case 2:
                    if (field.Type == TType.Struct)
                    {
                        Balance = new Coin();
                        await Balance.ReadAsync(iprot, cancellationToken);
                    }
                    else
                    {
                        await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken);
                    }
                    break;

                case 3:
                    if (field.Type == TType.Bool)
                    {
                        HasNext = await iprot.ReadBoolAsync(cancellationToken);
                    }
                    else
                    {
                        await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken);
                    }
                    break;

                default:
                    await TProtocolUtil.SkipAsync(iprot, field.Type, cancellationToken);

                    break;
                }

                await iprot.ReadFieldEndAsync(cancellationToken);
            }

            await iprot.ReadStructEndAsync(cancellationToken);
        }
        finally
        {
            iprot.DecrementRecursionDepth();
        }
    }
Пример #50
0
 public static bool GetCoin(string symbol, out Coin coin)
 {
     return(Coins.TryGetValue(symbol.ToUpper(), out coin));
 }
Пример #51
0
        public CycleProgressInfo Update()
        {
            int             height = Services.BlockExplorerService.GetCurrentHeight();
            CycleParameters cycle;
            CyclePhase      phase;

            if (ClientChannelNegotiation == null)
            {
                cycle = Parameters.CycleGenerator.GetRegisteringCycle(height);
                phase = CyclePhase.Registration;
            }
            else
            {
                cycle = ClientChannelNegotiation.GetCycle();
                var phases = new CyclePhase[]
                {
                    CyclePhase.Registration,
                    CyclePhase.ClientChannelEstablishment,
                    CyclePhase.TumblerChannelEstablishment,
                    CyclePhase.PaymentPhase,
                    CyclePhase.TumblerCashoutPhase,
                    CyclePhase.ClientCashoutPhase
                };
                if (!phases.Any(p => cycle.IsInPhase(p, height)))
                {
                    return(null);
                }
                phase = phases.First(p => cycle.IsInPhase(p, height));
            }

            Logs.Client.LogInformation(Environment.NewLine);
            var period     = cycle.GetPeriods().GetPeriod(phase);
            var blocksLeft = period.End - height;

            Logs.Client.LogInformation($"Cycle {cycle.Start} ({Status})");
            Logs.Client.LogInformation($"{cycle.ToString(height)} in phase {phase} ({blocksLeft} more blocks)");
            var previousState = Status;

            var progressInfo = new CycleProgressInfo(period, height, blocksLeft, cycle.Start, Status, phase, $"{cycle.ToString(height)} in phase {phase} ({blocksLeft} more blocks)");

            TumblerClient bob = null, alice = null;

            try
            {
                var correlation = SolverClientSession == null ? CorrelationId.Zero : new CorrelationId(SolverClientSession.Id);

                FeeRate feeRate = null;
                switch (phase)
                {
                case CyclePhase.Registration:
                    if (Status == PaymentStateMachineStatus.New)
                    {
                        bob = Runtime.CreateTumblerClient(cycle.Start, Identity.Bob);
                        //Client asks for voucher
                        var voucherResponse = bob.AskUnsignedVoucher();
                        NeedSave = true;
                        //Client ensures he is in the same cycle as the tumbler (would fail if one tumbler or client's chain isn't sync)
                        var tumblerCycle = Parameters.CycleGenerator.GetCycle(voucherResponse.CycleStart);
                        Assert(tumblerCycle.Start == cycle.Start, "invalid-phase");
                        //Saving the voucher for later
                        StartCycle = cycle.Start;
                        ClientChannelNegotiation = new ClientChannelNegotiation(Parameters, cycle.Start);
                        ClientChannelNegotiation.ReceiveUnsignedVoucher(voucherResponse);
                        Status = PaymentStateMachineStatus.Registered;
                    }
                    break;

                case CyclePhase.ClientChannelEstablishment:
                    if (Status == PaymentStateMachineStatus.Registered)
                    {
                        alice = Runtime.CreateTumblerClient(cycle.Start, Identity.Alice);
                        var key = alice.RequestTumblerEscrowKey();
                        ClientChannelNegotiation.ReceiveTumblerEscrowKey(key.PubKey, key.KeyIndex);
                        //Client create the escrow
                        var escrowTxOut = ClientChannelNegotiation.BuildClientEscrowTxOut();
                        feeRate = GetFeeRate();

                        Transaction clientEscrowTx = null;
                        try
                        {
                            clientEscrowTx = Services.WalletService.FundTransactionAsync(escrowTxOut, feeRate).GetAwaiter().GetResult();
                        }
                        catch (NotEnoughFundsException ex)
                        {
                            Logs.Client.LogInformation($"Not enough funds in the wallet to tumble. Missing about {ex.Missing}. Denomination is {Parameters.Denomination}.");
                            break;
                        }
                        NeedSave = true;
                        var redeemDestination = Services.WalletService.GenerateAddressAsync().GetAwaiter().GetResult().ScriptPubKey;
                        var channelId         = new uint160(RandomUtils.GetBytes(20));
                        SolverClientSession = ClientChannelNegotiation.SetClientSignedTransaction(channelId, clientEscrowTx, redeemDestination);


                        correlation = new CorrelationId(SolverClientSession.Id);

                        Tracker.AddressCreated(cycle.Start, TransactionType.ClientEscrow, escrowTxOut.ScriptPubKey, correlation);
                        Tracker.TransactionCreated(cycle.Start, TransactionType.ClientEscrow, clientEscrowTx.GetHash(), correlation);
                        Services.BlockExplorerService.TrackAsync(escrowTxOut.ScriptPubKey).GetAwaiter().GetResult();


                        var redeemTx = SolverClientSession.CreateRedeemTransaction(feeRate);
                        Tracker.AddressCreated(cycle.Start, TransactionType.ClientRedeem, redeemDestination, correlation);

                        //redeemTx does not be to be recorded to the tracker, this is TrustedBroadcastService job

                        Services.BroadcastService.BroadcastAsync(clientEscrowTx).GetAwaiter().GetResult();

                        Services.TrustedBroadcastService.Broadcast(cycle.Start, TransactionType.ClientRedeem, correlation, redeemTx);
                        Status = PaymentStateMachineStatus.ClientChannelBroadcasted;
                    }
                    else if (Status == PaymentStateMachineStatus.ClientChannelBroadcasted)
                    {
                        alice = Runtime.CreateTumblerClient(cycle.Start, Identity.Alice);
                        TransactionInformation clientTx = GetTransactionInformation(SolverClientSession.EscrowedCoin, true);
                        var state = ClientChannelNegotiation.GetInternalState();
                        if (clientTx != null && clientTx.Confirmations >= cycle.SafetyPeriodDuration)
                        {
                            Logs.Client.LogInformation($"Client escrow reached {cycle.SafetyPeriodDuration} confirmations");
                            //Client asks the public key of the Tumbler and sends its own
                            alice.BeginSignVoucher(new SignVoucherRequest
                            {
                                MerkleProof     = clientTx.MerkleProof,
                                Transaction     = clientTx.Transaction,
                                KeyReference    = state.TumblerEscrowKeyReference,
                                UnsignedVoucher = state.BlindedVoucher,
                                Cycle           = cycle.Start,
                                ClientEscrowKey = state.ClientEscrowKey.PubKey,
                                ChannelId       = SolverClientSession.Id
                            });
                            NeedSave = true;
                            Status   = PaymentStateMachineStatus.TumblerVoucherSigning;
                        }
                    }
                    else if (Status == PaymentStateMachineStatus.TumblerVoucherSigning)
                    {
                        alice = Runtime.CreateTumblerClient(cycle.Start, Identity.Alice);
                        var voucher = alice.EndSignVoucher(SolverClientSession.Id);
                        if (voucher != null)
                        {
                            ClientChannelNegotiation.CheckVoucherSolution(voucher);
                            NeedSave = true;
                            Status   = PaymentStateMachineStatus.TumblerVoucherObtained;
                        }
                    }
                    break;

                case CyclePhase.TumblerChannelEstablishment:

                    if (Status == PaymentStateMachineStatus.TumblerVoucherObtained)
                    {
                        bob = Runtime.CreateTumblerClient(cycle.Start, Identity.Bob);
                        Logs.Client.LogInformation("Begin ask to open the channel...");
                        //Client asks the Tumbler to make a channel
                        var     bobEscrowInformation = ClientChannelNegotiation.GetOpenChannelRequest();
                        uint160 channelId            = null;
                        try
                        {
                            channelId = bob.BeginOpenChannel(bobEscrowInformation);
                            NeedSave  = true;
                        }
                        catch (Exception ex)
                        {
                            if (ex.Message.Contains("tumbler-insufficient-funds"))
                            {
                                Logs.Client.LogWarning("The tumbler server has not enough funds and can't open a channel for now");
                                break;
                            }
                            throw;
                        }
                        ClientChannelNegotiation.SetChannelId(channelId);
                        Status = PaymentStateMachineStatus.TumblerChannelCreating;
                    }
                    else if (Status == PaymentStateMachineStatus.TumblerChannelCreating)
                    {
                        bob = Runtime.CreateTumblerClient(cycle.Start, Identity.Bob);
                        var tumblerEscrow = bob.EndOpenChannel(cycle.Start, ClientChannelNegotiation.GetInternalState().ChannelId);
                        if (tumblerEscrow == null)
                        {
                            Logs.Client.LogInformation("Tumbler escrow still creating...");
                            break;
                        }
                        NeedSave = true;

                        if (tumblerEscrow.OutputIndex >= tumblerEscrow.Transaction.Outputs.Count)
                        {
                            Logs.Client.LogError("Tumbler escrow output out-of-bound");
                            Status = PaymentStateMachineStatus.Wasted;
                            break;
                        }

                        var txOut      = tumblerEscrow.Transaction.Outputs[tumblerEscrow.OutputIndex];
                        var outpoint   = new OutPoint(tumblerEscrow.Transaction.GetHash(), tumblerEscrow.OutputIndex);
                        var escrowCoin = new Coin(outpoint, txOut).ToScriptCoin(ClientChannelNegotiation.GetTumblerEscrowParameters(tumblerEscrow.EscrowInitiatorKey).ToScript());

                        Console.WriteLine("TumblerEscrow hex: " + tumblerEscrow.Transaction.ToHex());

                        PromiseClientSession = ClientChannelNegotiation.ReceiveTumblerEscrowedCoin(escrowCoin);
                        Logs.Client.LogInformation("Tumbler expected escrowed coin received");
                        //Tell to the block explorer we need to track that address (for checking if it is confirmed in payment phase)
                        Services.BlockExplorerService.TrackAsync(PromiseClientSession.EscrowedCoin.ScriptPubKey).GetAwaiter().GetResult();
                        Services.BlockExplorerService.TrackPrunedTransactionAsync(tumblerEscrow.Transaction, tumblerEscrow.MerkleProof).GetAwaiter().GetResult();

                        Tracker.AddressCreated(cycle.Start, TransactionType.TumblerEscrow, PromiseClientSession.EscrowedCoin.ScriptPubKey, correlation);
                        Tracker.TransactionCreated(cycle.Start, TransactionType.TumblerEscrow, PromiseClientSession.EscrowedCoin.Outpoint.Hash, correlation);

                        Services.BroadcastService.BroadcastAsync(tumblerEscrow.Transaction).GetAwaiter().GetResult();
                        //Channel is done, now need to run the promise protocol to get valid puzzle
                        var cashoutDestination = DestinationWallet.GetNewDestination();
                        Tracker.AddressCreated(cycle.Start, TransactionType.TumblerCashout, cashoutDestination, correlation);

                        feeRate = GetFeeRate();
                        var sigReq      = PromiseClientSession.CreateSignatureRequest(cashoutDestination, feeRate);
                        var commitments = bob.SignHashes(PromiseClientSession.Id, sigReq);
                        var revelation  = PromiseClientSession.Reveal(commitments);
                        var proof       = bob.CheckRevelation(PromiseClientSession.Id, revelation);
                        var puzzle      = PromiseClientSession.CheckCommitmentProof(proof);
                        SolverClientSession.AcceptPuzzle(puzzle);
                        Status = PaymentStateMachineStatus.TumblerChannelCreated;
                    }
                    else if (Status == PaymentStateMachineStatus.TumblerChannelCreated)
                    {
                        CheckTumblerChannelSecured(cycle);
                    }
                    break;

                case CyclePhase.PaymentPhase:
                    //Could have confirmed during safe period
                    //Only check for the first block when period start,
                    //else Tumbler can know deanonymize you based on the timing of first Alice request if the transaction was not confirmed previously
                    if (Status == PaymentStateMachineStatus.TumblerChannelCreated && height == period.Start)
                    {
                        CheckTumblerChannelSecured(cycle);
                    }
                    //No "else if" intended
                    if (Status == PaymentStateMachineStatus.TumblerChannelSecured)
                    {
                        alice = Runtime.CreateTumblerClient(cycle.Start, Identity.Alice);
                        Logs.Client.LogDebug("Starting the puzzle solver protocol...");
                        var puzzles = SolverClientSession.GeneratePuzzles();
                        alice.BeginSolvePuzzles(SolverClientSession.Id, puzzles);
                        NeedSave = true;
                        Status   = PaymentStateMachineStatus.ProcessingPayment;
                    }
                    else if (Status == PaymentStateMachineStatus.ProcessingPayment)
                    {
                        feeRate = GetFeeRate();
                        alice   = Runtime.CreateTumblerClient(cycle.Start, Identity.Alice);
                        var commitments = alice.EndSolvePuzzles(SolverClientSession.Id);
                        NeedSave = true;
                        if (commitments == null)
                        {
                            Logs.Client.LogDebug("Still solving puzzles...");
                            break;
                        }
                        var revelation2      = SolverClientSession.Reveal(commitments);
                        var solutionKeys     = alice.CheckRevelation(SolverClientSession.Id, revelation2);
                        var blindFactors     = SolverClientSession.GetBlindFactors(solutionKeys);
                        var offerInformation = alice.CheckBlindFactors(SolverClientSession.Id, blindFactors);

                        var offerSignature = SolverClientSession.SignOffer(offerInformation);

                        var offerRedeem = SolverClientSession.CreateOfferRedeemTransaction(feeRate);
                        Logs.Client.LogDebug("Puzzle solver protocol ended...");

                        //May need to find solution in the fulfillment transaction
                        Services.BlockExplorerService.TrackAsync(offerRedeem.PreviousScriptPubKey).GetAwaiter().GetResult();
                        Tracker.AddressCreated(cycle.Start, TransactionType.ClientOfferRedeem, SolverClientSession.GetInternalState().RedeemDestination, correlation);
                        Services.TrustedBroadcastService.Broadcast(cycle.Start, TransactionType.ClientOfferRedeem, correlation, offerRedeem);
                        try
                        {
                            solutionKeys = alice.FulfillOffer(SolverClientSession.Id, offerSignature);
                            SolverClientSession.CheckSolutions(solutionKeys);
                            var tumblingSolution = SolverClientSession.GetSolution();
                            var transaction      = PromiseClientSession.GetSignedTransaction(tumblingSolution);
                            Logs.Client.LogDebug("Got puzzle solution cooperatively from the tumbler");

                            Console.WriteLine("TumblerCashOut hex: " + transaction.ToHex());

                            Status = PaymentStateMachineStatus.PuzzleSolutionObtained;
                            Services.TrustedBroadcastService.Broadcast(cycle.Start, TransactionType.TumblerCashout, correlation, new TrustedBroadcastRequest()
                            {
                                BroadcastAt = cycle.GetPeriods().ClientCashout.Start,
                                Transaction = transaction
                            });
                            if (Cooperative)
                            {
                                try
                                {
                                    // No need to await for it, it is a just nice for the tumbler (we don't want the underlying socks connection cut before the escape key is sent)
                                    var signature = SolverClientSession.SignEscape();
                                    alice.GiveEscapeKeyAsync(SolverClientSession.Id, signature).GetAwaiter().GetResult();
                                }
                                catch (Exception ex) { Logs.Client.LogDebug(new EventId(), ex, "Exception while giving the escape key"); }
                                Logs.Client.LogInformation("Gave escape signature to the tumbler");
                            }
                        }
                        catch (Exception ex)
                        {
                            Status = PaymentStateMachineStatus.UncooperativeTumbler;
                            Logs.Client.LogWarning("The tumbler did not gave puzzle solution cooperatively");
                            Logs.Client.LogWarning(ex.ToString());
                        }
                    }

                    break;

                case CyclePhase.ClientCashoutPhase:

                    //If the tumbler is uncooperative, he published solutions on the blockchain
                    if (Status == PaymentStateMachineStatus.UncooperativeTumbler)
                    {
                        var transactions = Services.BlockExplorerService.GetTransactionsAsync(SolverClientSession.GetInternalState().OfferCoin.ScriptPubKey, false).GetAwaiter().GetResult();
                        if (transactions.Count != 0)
                        {
                            SolverClientSession.CheckSolutions(transactions.Select(t => t.Transaction).ToArray());
                            Logs.Client.LogInformation("Puzzle solution recovered from tumbler's fulfill transaction");
                            NeedSave = true;
                            Status   = PaymentStateMachineStatus.PuzzleSolutionObtained;
                            var tumblingSolution = SolverClientSession.GetSolution();
                            var transaction      = PromiseClientSession.GetSignedTransaction(tumblingSolution);
                            Tracker.TransactionCreated(cycle.Start, TransactionType.TumblerCashout, transaction.GetHash(), correlation);
                            Services.BroadcastService.BroadcastAsync(transaction).GetAwaiter().GetResult();
                        }
                    }

                    break;
                }
            }
            catch (InvalidStateException ex)
            {
                Logs.Client.LogDebug(new EventId(), ex, "Client side Invalid State, the payment is wasted");
                Status = PaymentStateMachineStatus.Wasted;
            }
            catch (Exception ex) when(ex.Message.IndexOf("invalid-state", StringComparison.OrdinalIgnoreCase) >= 0)
            {
                Logs.Client.LogDebug(new EventId(), ex, "Tumbler side Invalid State, the payment is wasted");
                Status = PaymentStateMachineStatus.Wasted;
            }
            finally
            {
                if (previousState != Status)
                {
                    Logs.Client.LogInformation($"Status changed {previousState} => {Status}");
                }
                if (alice != null && bob != null)
                {
                    throw new InvalidOperationException("Bob and Alice have been both initialized, please report the bug to NTumbleBit developers");
                }
                if (alice != null)
                {
                    alice.Dispose();
                }
                if (bob != null)
                {
                    bob.Dispose();
                }
            }
            return(progressInfo);
        }
Пример #52
0
 public void AddCoinToReturn(Coin coin)
 {
     Device.Cashreturn.Add(coin);
 }
Пример #53
0
        public static void Seed(List <Data.Configuration.Coin> configurations)
        {
            //BTC
            Coin donationConfiguration = CreateCoinConfiguration("BTC", "stratum+tcp://connect.pool.bitcoin.com", 3333);

            configurations.Add(donationConfiguration);

            //LTC
            donationConfiguration = CreateCoinConfiguration("LTC", "stratum+tcp://us.litecoinpool.org", 3333, "nwoolls", "mmdonations");
            configurations.Add(donationConfiguration);

            //BQC
            donationConfiguration = CreateCoinConfiguration("BQC", "stratum+tcp://www.bbqpool.net", 3333);
            configurations.Add(donationConfiguration);

            //Coinmine.pl
            //ZET
            donationConfiguration = CreateCoinConfiguration("ZET", "stratum+tcp://mine1.coinmine.pl", 6000, "nwoolls", "mmdonations");
            configurations.Add(donationConfiguration);

            //SRC
            donationConfiguration = CreateCoinConfiguration("SRC", "stratum+tcp://mine2.coinmine.pl", 6020, "nwoolls", "mmdonations");
            configurations.Add(donationConfiguration);

            //DCR
            donationConfiguration = CreateCoinConfiguration("DCR", "stratum+tcp://dcr.coinmine.pl", 2222, "nwoolls", "mmdonations");
            configurations.Add(donationConfiguration);

            //LBC
            donationConfiguration = CreateCoinConfiguration("LBC", "stratum+tcp://lbc.coinmine.pl", 8787, "nwoolls", "mmdonations");
            configurations.Add(donationConfiguration);

            //PPC
            donationConfiguration = CreateCoinConfiguration("PPC", "stratum+tcp://mine1.coinmine.pl", 6050, "nwoolls", "mmdonations");
            configurations.Add(donationConfiguration);

            //UBQ
            donationConfiguration = CreateCoinConfiguration("UBQ", "stratum+tcp://ubiq.mixpools.org", 2120, "nwoolls", "mmdonations");
            configurations.Add(donationConfiguration);

            //MiningPoolHub
            //DRK
            donationConfiguration = CreateCoinConfiguration("DRK", "stratum+tcp://us-east1.darkcoin.miningpoolhub.com", 20465);
            configurations.Add(donationConfiguration);

            //MAX
            donationConfiguration = CreateCoinConfiguration("MAX", "stratum+tcp://us-east1.maxcoin.miningpoolhub.com", 20461);
            configurations.Add(donationConfiguration);

            //SXC
            donationConfiguration = CreateCoinConfiguration("SXC", "stratum+tcp://us-east1.sexcoin.miningpoolhub.com", 20463);
            configurations.Add(donationConfiguration);

            //ETH
            donationConfiguration = CreateCoinConfiguration("ETH", "stratum+tcp://us-east.ethash-hub.miningpoolhub.com", 20535);
            configurations.Add(donationConfiguration);

            //ADZ
            donationConfiguration = CreateCoinConfiguration("ADZ", "stratum+tcp://hub.miningpoolhub.com", 20529);
            configurations.Add(donationConfiguration);

            //AUR
            donationConfiguration = CreateCoinConfiguration("AUR", "stratum+tcp://hub.miningpoolhub.com", 20592);
            configurations.Add(donationConfiguration);

            //BTG
            donationConfiguration = CreateCoinConfiguration("BTG", "stratum+tcp://us-east.equihash-hub.miningpoolhub.com", 20595);
            configurations.Add(donationConfiguration);

            //DASH
            donationConfiguration = CreateCoinConfiguration("DASH", "stratum+tcp://hub.miningpoolhub.com", 20465);
            configurations.Add(donationConfiguration);

            //ETN
            donationConfiguration = CreateCoinConfiguration("ETN", "stratum+tcp://us-east.cryptonight-hub.miningpoolhub.com", 20596);
            configurations.Add(donationConfiguration);

            //ETC
            donationConfiguration = CreateCoinConfiguration("ETC", "stratum+tcp://us-east.ethash-hub.miningpoolhub.com", 20555);
            configurations.Add(donationConfiguration);

            //EXP
            donationConfiguration = CreateCoinConfiguration("EXP", "stratum+tcp://us-east.ethash-hub.miningpoolhub.com", 20565);
            configurations.Add(donationConfiguration);

            //FTC
            donationConfiguration = CreateCoinConfiguration("FTC", "stratum+tcp://hub.miningpoolhub.com", 20510);
            configurations.Add(donationConfiguration);

            //GAME
            donationConfiguration = CreateCoinConfiguration("GAME", "stratum+tcp://hub.miningpoolhub.com", 20576);
            configurations.Add(donationConfiguration);

            //GEO
            donationConfiguration = CreateCoinConfiguration("GEO", "stratum+tcp://hub.miningpoolhub.com", 20524);
            configurations.Add(donationConfiguration);

            //BSTY
            donationConfiguration = CreateCoinConfiguration("BSTY", "stratum+tcp://hub.miningpoolhub.com", 20543);
            configurations.Add(donationConfiguration);

            //GRS
            donationConfiguration = CreateCoinConfiguration("GRS", "stratum+tcp://hub.miningpoolhub.com", 20486);
            configurations.Add(donationConfiguration);

            //GRS
            donationConfiguration = CreateCoinConfiguration("GRS", "stratum+tcp://hub.miningpoolhub.com", 20486);
            configurations.Add(donationConfiguration);

            //MONA
            donationConfiguration = CreateCoinConfiguration("MONA", "stratum+tcp://hub.miningpoolhub.com", 20593);
            configurations.Add(donationConfiguration);

            //XMR
            donationConfiguration = CreateCoinConfiguration("XMR", "stratum+tcp://us-east.cryptonight-hub.miningpoolhub.com", 20580);
            configurations.Add(donationConfiguration);

            //MUSIC
            donationConfiguration = CreateCoinConfiguration("MUSIC", "stratum+tcp://us-east.ethash-hub.miningpoolhub.com", 20585);
            configurations.Add(donationConfiguration);

            //SC
            donationConfiguration = CreateCoinConfiguration("SC", "stratum+tcp://hub.miningpoolhub.com", 20550);
            configurations.Add(donationConfiguration);

            //START
            donationConfiguration = CreateCoinConfiguration("START", "stratum+tcp://hub.miningpoolhub.com", 20509);
            configurations.Add(donationConfiguration);

            //XVG
            donationConfiguration = CreateCoinConfiguration("XVG", "stratum+tcp://hub.miningpoolhub.com", 20523);
            configurations.Add(donationConfiguration);

            //VTC
            donationConfiguration = CreateCoinConfiguration("VTC", "stratum+tcp://hub.miningpoolhub.com", 20507);
            configurations.Add(donationConfiguration);

            //ZEC
            donationConfiguration = CreateCoinConfiguration("ZEC", "stratum+tcp://us-east.equihash-hub.miningpoolhub.com", 20570);
            configurations.Add(donationConfiguration);

            //ZCL
            donationConfiguration = CreateCoinConfiguration("ZCL", "stratum+tcp://us-east.equihash-hub.miningpoolhub.com", 20575);
            configurations.Add(donationConfiguration);

            //XZC
            donationConfiguration = CreateCoinConfiguration("XZC", "stratum+tcp://us-east.lyra2z-hub.miningpoolhub.com", 20581);
            configurations.Add(donationConfiguration);

            //ZEN
            donationConfiguration = CreateCoinConfiguration("ZEN", "stratum+tcp://us-east.equihash-hub.miningpoolhub.com", 20594);
            configurations.Add(donationConfiguration);

            //NiceHash
            //Scrypt
            donationConfiguration = CreateCoinConfiguration("NiceHash:Scrypt", "stratum+tcp://scrypt.usa.nicehash.com/#xnsub", 3333, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //SHA256
            donationConfiguration = CreateCoinConfiguration("NiceHash:SHA256", "stratum+tcp://sha256.usa.nicehash.com/#xnsub", 3334, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //ScryptN
            donationConfiguration = CreateCoinConfiguration("NiceHash:ScryptN", "stratum+tcp://scryptnf.usa.nicehash.com/#xnsub", 3335, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //ScryptNf
            donationConfiguration = CreateCoinConfiguration("NiceHash:ScryptNf", "stratum+tcp://scryptnf.usa.nicehash.com/#xnsub", 3335, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //X11
            donationConfiguration = CreateCoinConfiguration("NiceHash:X11", "stratum+tcp://x11.usa.nicehash.com/#xnsub", 3336, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //X13
            donationConfiguration = CreateCoinConfiguration("NiceHash:X13", "stratum+tcp://x13.usa.nicehash.com/#xnsub", 3337, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //Keccak
            donationConfiguration = CreateCoinConfiguration("NiceHash:Keccak", "stratum+tcp://keccak.usa.nicehash.com/#xnsub", 3338, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //X15
            donationConfiguration = CreateCoinConfiguration("NiceHash:X15", "stratum+tcp://x15.usa.nicehash.com/#xnsub", 3339, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //Nist5
            donationConfiguration = CreateCoinConfiguration("NiceHash:Nist5", "stratum+tcp://nist5.usa.nicehash.com/#xnsub", 3340, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //NeoScrypt
            donationConfiguration = CreateCoinConfiguration("NiceHash:NeoScrypt", "stratum+tcp://neoscrypt.usa.nicehash.com/#xnsub", 3341, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //Lyra2RE
            donationConfiguration = CreateCoinConfiguration("NiceHash:Lyra2RE", "stratum+tcp://lyra2re.usa.nicehash.com/#xnsub", 3342, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //WhirlpoolX
            donationConfiguration = CreateCoinConfiguration("NiceHash:WhirlpoolX", "stratum+tcp://whirlpoolx.usa.nicehash.com/#xnsub", 3343, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //Qubit
            donationConfiguration = CreateCoinConfiguration("NiceHash:Qubit", "stratum+tcp://qubit.usa.nicehash.com/#xnsub", 3344, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //Quark
            donationConfiguration = CreateCoinConfiguration("NiceHash:Quark", "stratum+tcp://quark.usa.nicehash.com/#xnsub", 3345, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //Axiom
            donationConfiguration = CreateCoinConfiguration("NiceHash:Axiom", "stratum+tcp://axiom.usa.nicehash.com/#xnsub", 3346, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //Lyra2REv2
            donationConfiguration = CreateCoinConfiguration("NiceHash:Lyra2REv2", "stratum+tcp://lyra2rev2.usa.nicehash.com/#xnsub", 3347, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //ScryptJaneNf16
            donationConfiguration = CreateCoinConfiguration("NiceHash:ScryptJaneNf16", "stratum+tcp://scryptjanenf16.usa.nicehash.com/#xnsub", 3348, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //Blake256r8
            donationConfiguration = CreateCoinConfiguration("NiceHash:Blake256r8", "stratum+tcp://blake256r8.usa.nicehash.com/#xnsub", 3349, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //Blake256r14
            donationConfiguration = CreateCoinConfiguration("NiceHash:Blake256r14", "stratum+tcp://blake256r14.usa.nicehash.com/#xnsub", 3350, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //Blake256r8vnl
            donationConfiguration = CreateCoinConfiguration("NiceHash:Blake256r8vnl", "stratum+tcp://blake256r8vnl.usa.nicehash.com/#xnsub", 3351, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //Hodl
            donationConfiguration = CreateCoinConfiguration("NiceHash:Hodl", "stratum+tcp://hodl.usa.nicehash.com/#xnsub", 3352, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //Hodl
            donationConfiguration = CreateCoinConfiguration("NiceHash:Hodl", "stratum+tcp://hodl.usa.nicehash.com/#xnsub", 3352, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //DaggerHashimoto
            donationConfiguration = CreateCoinConfiguration("NiceHash:DaggerHashimoto", "stratum+tcp://daggerhashimoto.usa.nicehash.com/#xnsub", 3353, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //Decred
            donationConfiguration = CreateCoinConfiguration("NiceHash:Decred", "stratum+tcp://decred.usa.nicehash.com/#xnsub", 3354, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //CryptoNight
            donationConfiguration = CreateCoinConfiguration("NiceHash:CryptoNight", "stratum+tcp://cryptonight.usa.nicehash.com/#xnsub", 3355, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //Lbry
            donationConfiguration = CreateCoinConfiguration("NiceHash:Lbry", "stratum+tcp://lbry.usa.nicehash.com/#xnsub", 3356, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //Equihash
            donationConfiguration = CreateCoinConfiguration("NiceHash:Equihash", "stratum+tcp://equihash.usa.nicehash.com/#xnsub", 3357, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //Pascal
            donationConfiguration = CreateCoinConfiguration("NiceHash:Pascal", "stratum+tcp://pascal.usa.nicehash.com/#xnsub", 3358, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //X11Gost
            donationConfiguration = CreateCoinConfiguration("NiceHash:X11Gost", "stratum+tcp://x11gost.usa.nicehash.com/#xnsub", 3359, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //Sia
            donationConfiguration = CreateCoinConfiguration("NiceHash:Sia", "stratum+tcp://sia.usa.nicehash.com/#xnsub", 3360, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //Blake2s
            donationConfiguration = CreateCoinConfiguration("NiceHash:Blake2s", "stratum+tcp://blake2s.usa.nicehash.com/#xnsub", 3361, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //Skunk
            donationConfiguration = CreateCoinConfiguration("NiceHash:Skunk", "stratum+tcp://skunk.usa.nicehash.com/#xnsub", 3362, "1LRtJBNQm9ALYt9gQjVK1TdRyQ6UPGUNCw");
            configurations.Add(donationConfiguration);

            //BCH
            donationConfiguration = CreateCoinConfiguration("BCH", "stratum+tcp://stratum.bcc.pool.bitcoin.com", 3333);
            configurations.Add(donationConfiguration);

            //BCC
            donationConfiguration = CreateCoinConfiguration("BCC", "stratum+tcp://stratum.bcc.pool.bitcoin.com", 3333);
            configurations.Add(donationConfiguration);

            //NVC
            donationConfiguration = CreateCoinConfiguration("NVC", "stratum+tcp://stratum.khore.org", 3335);
            configurations.Add(donationConfiguration);
        }
        public async Task AcceptToMemoryPool_WithMultiInOutValidTxns_IsSuccessfullAsync()
        {
            string dataDir = GetTestDirectoryPath(this);

            BitcoinSecret     miner   = new BitcoinSecret(new Key(), Network.RegTest);
            ITestChainContext context = await TestChainFactory.CreateAsync(Network.RegTest, miner.PubKey.Hash.ScriptPubKey, dataDir);

            IMempoolValidator validator = context.MempoolValidator;

            Assert.NotNull(validator);

            BitcoinSecret alice   = new BitcoinSecret(new Key(), Network.RegTest);
            BitcoinSecret bob     = new BitcoinSecret(new Key(), Network.RegTest);
            BitcoinSecret satoshi = new BitcoinSecret(new Key(), Network.RegTest);

            // Fund Alice, Bob, Satoshi
            // 50 Coins come from first tx on chain - send satoshi 1, bob 2, Alice 1.5 and change back to miner
            Coin coin = new Coin(context.SrcTxs[0].GetHash(), 0, context.SrcTxs[0].TotalOut, miner.ScriptPubKey);
            TransactionBuilder txBuilder     = new TransactionBuilder(Network.RegTest);
            Transaction        multiOutputTx = txBuilder
                                               .AddCoins(new List <Coin> {
                coin
            })
                                               .AddKeys(miner)
                                               .Send(satoshi.GetAddress(), "1.00")
                                               .Send(bob.GetAddress(), "2.00")
                                               .Send(alice.GetAddress(), "1.50")
                                               .SendFees("0.001")
                                               .SetChange(miner.GetAddress())
                                               .BuildTransaction(true);

            Assert.True(txBuilder.Verify(multiOutputTx)); //check fully signed
            MempoolValidationState state = new MempoolValidationState(false);

            Assert.True(await validator.AcceptToMemoryPool(state, multiOutputTx), $"Transaction: {nameof(multiOutputTx)} failed mempool validation.");

            // Alice then Bob sends to Satoshi
            Coin[] aliceCoins = multiOutputTx.Outputs
                                .Where(o => o.ScriptPubKey == alice.ScriptPubKey)
                                .Select(o => new Coin(new OutPoint(multiOutputTx.GetHash(), multiOutputTx.Outputs.IndexOf(o)), o))
                                .ToArray();
            Coin[] bobCoins = multiOutputTx.Outputs
                              .Where(o => o.ScriptPubKey == bob.ScriptPubKey)
                              .Select(o => new Coin(new OutPoint(multiOutputTx.GetHash(), multiOutputTx.Outputs.IndexOf(o)), o))
                              .ToArray();

            txBuilder = new TransactionBuilder(Network.RegTest);
            Transaction multiInputTx = txBuilder
                                       .AddCoins(aliceCoins)
                                       .AddKeys(alice)
                                       .Send(satoshi.GetAddress(), "0.8")
                                       .SetChange(alice.GetAddress())
                                       .SendFees("0.0005")
                                       .Then()
                                       .AddCoins(bobCoins)
                                       .AddKeys(bob)
                                       .Send(satoshi.GetAddress(), "0.2")
                                       .SetChange(bob.GetAddress())
                                       .SendFees("0.0005")
                                       .BuildTransaction(true);

            Assert.True(txBuilder.Verify(multiInputTx)); //check fully signed
            Assert.True(await validator.AcceptToMemoryPool(state, multiInputTx), $"Transaction: {nameof(multiInputTx)} failed mempool validation.");
        }
        static void Main()
        {
            //Tracnsaction ID in this case
            //f13dc48fb035bbf0a6e989a26b3ecb57b84f85e0836e777d6edf60d87a4a2d94
            //The TransactionId is defined by SHA256(SHA256(txbytes))
            //Do NOT use the TransactionId to handle unconfirmed transactions. The TransactionId can be
            //manipulated before it is confirmed. This is known as “Transaction Malleability.



            //** I want to something that fetch me the transactions


            // Create a client
            QBitNinjaClient client = new QBitNinjaClient(Network.Main);
            // Parse transaction id to NBitcoin.uint256 so the client can eat it
            var transactionId = uint256.Parse("f13dc48fb035bbf0a6e989a26b3ecb57b84f85e0836e777d6edf60d87a4a2d94");

            // Query the transaction by ID
            QBitNinja.Client.Models.GetTransactionResponse transactionResponse = client.GetTransaction(transactionId).Result;


            NBitcoin.Transaction transaction = transactionResponse.Transaction;

            Console.WriteLine(transactionResponse.TransactionId); // f13dc48fb035bbf0a6e989a26b3ecb57b84f85e0836e777d6edf60d87a4a2d94
            Console.WriteLine(transaction.GetHash());             // f13dc48fb035bbf0a6e989a26b3ecb57b84f85e0836e777d6edf60d87a4a2d94

            // RECEIVED COINS
            List <ICoin> receivedCoins = transactionResponse.ReceivedCoins;

            foreach (Coin coin in receivedCoins)
            {
                Money amount = coin.Amount;

                Console.WriteLine(amount.ToDecimal(MoneyUnit.BTC));
                var paymentScript = coin.ScriptPubKey;
                Console.WriteLine(paymentScript);  // It's the ScriptPubKey
                var address = paymentScript.GetDestinationAddress(Network.Main);
                Console.WriteLine(address);
                Console.WriteLine();
            }

            // RECEIVED COINS
            var outputs = transaction.Outputs;

            foreach (TxOut output in outputs)
            {
                Coin  coin   = new Coin(transaction, output);
                Money amount = coin.Amount;

                Console.WriteLine(amount.ToDecimal(MoneyUnit.BTC));
                var paymentScript = coin.GetScriptCode();
                Console.WriteLine(paymentScript);  // It's the ScriptPubKey
                var address = paymentScript.GetDestinationAddress(Network.Main);
                Console.WriteLine(address);
                Console.WriteLine();
            }

            // RECEIVED COINS
            foreach (TxOut output in outputs)
            {
                Money amount = output.Value;

                Console.WriteLine(amount.ToDecimal(MoneyUnit.BTC));
                var paymentScript = output.ScriptPubKey;
                Console.WriteLine(paymentScript);  // It's the ScriptPubKey
                var address = paymentScript.GetDestinationAddress(Network.Main);
                Console.WriteLine(address);
                Console.WriteLine();
            }

            // SPENT COINS
            List <ICoin> spentCoins = transactionResponse.SpentCoins;

            foreach (Coin coin in spentCoins)
            {
                Money amount = coin.Amount;

                Console.WriteLine(amount.ToDecimal(MoneyUnit.BTC));
                var paymentScript = coin.ScriptPubKey;
                Console.WriteLine(paymentScript);  // It's the ScriptPubKey
                var address = paymentScript.GetDestinationAddress(Network.Main);
                Console.WriteLine(address);
                Console.WriteLine();
            }

            // SPENT COINS
            foreach (Coin coin in spentCoins)
            {
                TxOut previousOutput = coin.TxOut;
                Money amount         = previousOutput.Value;

                Console.WriteLine(amount.ToDecimal(MoneyUnit.BTC));
                var paymentScript = previousOutput.ScriptPubKey;
                Console.WriteLine(paymentScript);  // It's the ScriptPubKey
                var address = paymentScript.GetDestinationAddress(Network.Main);
                Console.WriteLine(address);
                Console.WriteLine();
            }


            var fee = transaction.GetFee(spentCoins.ToArray());

            Console.WriteLine(fee);

            var inputs = transaction.Inputs;

            foreach (TxIn input in inputs)
            {
                OutPoint previousOutpoint = input.PrevOut;
                Console.WriteLine(previousOutpoint.Hash); // hash of prev tx
                Console.WriteLine(previousOutpoint.N);    // idx of out from prev tx, that has been spent in the current tx
                Console.WriteLine();
            }

            // Let's create a txout with 21 bitcoin from the first ScriptPubKey in our current transaction
            Money twentyOneBtc = new Money(21, MoneyUnit.BTC);
            var   scriptPubKey = transaction.Outputs.First().ScriptPubKey;
            TxOut txOut        = new TxOut(twentyOneBtc, scriptPubKey);

            OutPoint firstOutPoint = spentCoins.First().Outpoint;

            Console.WriteLine(firstOutPoint.Hash);       // 4788c5ef8ffd0463422bcafdfab240f5bf0be690482ceccde79c51cfce209edd
            Console.WriteLine(firstOutPoint.N);          // 0

            Console.WriteLine(transaction.Inputs.Count); // 9

            OutPoint firstPreviousOutPoint            = transaction.Inputs.First().PrevOut;
            var      firstPreviousTransactionResponse = client.GetTransaction(firstPreviousOutPoint.Hash).Result;

            Console.WriteLine(firstPreviousTransactionResponse.IsCoinbase); // False
            NBitcoin.Transaction firstPreviousTransaction = firstPreviousTransactionResponse.Transaction;

            //while (firstPreviousTransactionResponse.IsCoinbase == false)
            //{
            //    Console.WriteLine(firstPreviousTransaction.GetHash());

            //    firstPreviousOutPoint = firstPreviousTransaction.Inputs.First().PrevOut;
            //    firstPreviousTransactionResponse = client.GetTransaction(firstPreviousOutPoint.Hash).Result;
            //    firstPreviousTransaction = firstPreviousTransactionResponse.Transaction;
            //}

            Money spentAmount = Money.Zero;

            foreach (var spentCoin in spentCoins)
            {
                spentAmount = (Money)spentCoin.Amount.Add(spentAmount);
            }
            Console.WriteLine(spentAmount.ToDecimal(MoneyUnit.BTC)); // 13.19703492

            Money receivedAmount = Money.Zero;

            foreach (var receivedCoin in receivedCoins)
            {
                receivedAmount = (Money)receivedCoin.Amount.Add(receivedAmount);
            }
            Console.WriteLine(receivedAmount.ToDecimal(MoneyUnit.BTC)); // 13.19683492

            Console.WriteLine((spentAmount - receivedAmount).ToDecimal(MoneyUnit.BTC));

            Console.WriteLine(spentAmount.ToDecimal(MoneyUnit.BTC) - receivedAmount.ToDecimal(MoneyUnit.BTC));

            //var inputs = transaction.Inputs;
            //foreach (TxIn input in inputs)
            //{
            //    uint256 previousTransactionId = input.PrevOut.Hash;
            //    GetTransactionResponse previousTransactionResponse = client.GetTransaction(previousTransactionId).Result;

            //    NBitcoin.Transaction previousTransaction = previousTransactionResponse.Transaction;

            //    var previousTransactionOutputs = previousTransaction.Outputs;
            //    foreach (TxOut previousTransactionOutput in previousTransactionOutputs)
            //    {
            //        Money amount = previousTransactionOutput.Value;

            //        Console.WriteLine(amount.ToDecimal(MoneyUnit.BTC));
            //        var paymentScript = previousTransactionOutput.ScriptPubKey;
            //        Console.WriteLine(paymentScript);  // It's the ScriptPubKey
            //        var address = paymentScript.GetDestinationAddress(Network.Main);
            //        Console.WriteLine(address);
            //        Console.WriteLine();
            //    }
            //}

            Console.ReadLine();
        }
        public async Task <IActionResult> PostSignaturesAsync([FromQuery, Required] string uniqueId, [FromQuery, Required] long roundId, [FromBody, Required] IDictionary <int, string> signatures)
        {
            if (roundId < 0 ||
                !signatures.Any() ||
                signatures.Any(x => x.Key < 0 || string.IsNullOrWhiteSpace(x.Value)) ||
                !ModelState.IsValid)
            {
                return(BadRequest());
            }

            (CcjRound round, Alice alice) = GetRunningRoundAndAliceOrFailureResponse(roundId, uniqueId, out IActionResult returnFailureResponse);
            if (!(returnFailureResponse is null))
            {
                return(returnFailureResponse);
            }

            // Check if Alice provided signature to all her inputs.
            if (signatures.Count != alice.Inputs.Count())
            {
                return(BadRequest("Alice did not provide enough witnesses."));
            }

            CcjRoundPhase phase = round.Phase;

            switch (phase)
            {
            case CcjRoundPhase.Signing:
            {
                using (await SigningLock.LockAsync())
                {
                    foreach (var signaturePair in signatures)
                    {
                        int       index   = signaturePair.Key;
                        WitScript witness = null;
                        try
                        {
                            witness = new WitScript(signaturePair.Value);
                        }
                        catch (Exception ex)
                        {
                            return(BadRequest($"Malformed witness is provided. Details: {ex.Message}"));
                        }
                        int maxIndex = round.UnsignedCoinJoin.Inputs.Count - 1;
                        if (maxIndex < index)
                        {
                            return(BadRequest($"Index out of range. Maximum value: {maxIndex}. Provided value: {index}"));
                        }

                        // Check duplicates.
                        if (round.SignedCoinJoin.Inputs[index].HasWitScript())
                        {
                            return(BadRequest($"Input is already signed."));
                        }

                        // Verify witness.
                        // 1. Copy UnsignedCoinJoin.
                        Transaction cjCopy = Transaction.Parse(round.UnsignedCoinJoin.ToHex(), Network);
                        // 2. Sign the copy.
                        cjCopy.Inputs[index].WitScript = witness;
                        // 3. Convert the current input to IndexedTxIn.
                        IndexedTxIn currentIndexedInput = cjCopy.Inputs.AsIndexedInputs().Skip(index).First();
                        // 4. Find the corresponding registered input.
                        Coin registeredCoin = alice.Inputs.Single(x => x.Outpoint == cjCopy.Inputs[index].PrevOut);
                        // 5. Verify if currentIndexedInput is correctly signed, if not, return the specific error.
                        if (!currentIndexedInput.VerifyScript(registeredCoin, out ScriptError error))
                        {
                            return(BadRequest($"Invalid witness is provided. ScriptError: {error}."));
                        }

                        // Finally add it to our CJ.
                        round.SignedCoinJoin.Inputs[index].WitScript = witness;
                    }

                    alice.State = AliceState.SignedCoinJoin;

                    await round.BroadcastCoinJoinIfFullySignedAsync();
                }

                return(NoContent());
            }

            default:
            {
                return(Conflict($"CoinJoin can only be requested from Signing phase. Current phase: {phase}."));
            }
            }
        }
Пример #57
0
        void Start()
        {
            var coin = new Coin(
                fromTxHash: new uint256("eb49a599c749c82d824caf9dd69c4e359261d49bbb0b9d6dc18c59bc9214e43b"),
                fromOutputIndex: 0,
                amount: Money.Satoshis(2000000),
                scriptPubKey: new Script(Encoders.Hex.DecodeData("76a914c81e8e7b7ffca043b088a992795b15887c96159288ac")));

            var issuance = new IssuanceCoin(coin);


            var nico = BitcoinAddress.Create("15sYbVpRh6dyWycZMwPdxJWD4xbfxReeHe");
            //var bookKey = new BitcoinSecret("???????");
            var bookKey = new Key().GetBitcoinSecret(Network.Main);             // Just a fake key in order to not get an exception

            var builder = new TransactionBuilder();

            Transaction tx = builder
                             .AddKeys(bookKey)
                             .AddCoins(issuance)
                             .IssueAsset(nico, new AssetMoney(issuance.AssetId, quantity: 10))
                             .SendFees(Money.Coins(0.0001m))
                             .SetChange(bookKey.GetAddress())
                             .BuildTransaction(true);

            UnityEngine.Debug.Log(tx);
            UnityEngine.Debug.Log(builder.Verify(tx));

            nico = BitcoinAddress.Create("15sYbVpRh6dyWycZMwPdxJWD4xbfxReeHe");
            UnityEngine.Debug.Log(nico.ToColoredAddress());

            /* QBITNINJA */

            //var client = new QBitNinjaClient(Network.Main);
            //BroadcastResponse broadcastResponse = client.Broadcast(tx).Result;

            //if (!broadcastResponse.Success)
            //{
            //    UnityEngine.Debug.Log("ErrorCode: " + broadcastResponse.Error.ErrorCode);
            //    UnityEngine.Debug.Log("Error message: " + broadcastResponse.Error.Reason);
            //}
            //else
            //{
            //    UnityEngine.Debug.Log("Success!");
            //}

            /* OR BITCOIN CORE */

            //using (var node = Node.ConnectToLocal(Network.Main)) //Connect to the node
            //{
            //    node.VersionHandshake(); //Say hello
            //                             //Advertize your transaction (send just the hash)
            //    node.SendMessage(new InvPayload(InventoryType.MSG_TX, tx.GetHash()));
            //    //Send it
            //    node.SendMessage(new TxPayload(tx));
            //    Thread.Sleep(500); //Wait a bit
            //}


            coin = new Coin(
                fromTxHash: new uint256("fa6db7a2e478f3a8a0d1a77456ca5c9fa593e49fd0cf65c7e349e5a4cbe58842"),
                fromOutputIndex: 0,
                amount: Money.Satoshis(2000000),
                scriptPubKey: new Script(Encoders.Hex.DecodeData("76a914356facdac5f5bcae995d13e667bb5864fd1e7d5988ac")));
            BitcoinAssetId assetId = new BitcoinAssetId("AVAVfLSb1KZf9tJzrUVpktjxKUXGxUTD4e");
            ColoredCoin    colored = coin.ToColoredCoin(assetId, 10);

            var book       = BitcoinAddress.Create("1KF8kUVHK42XzgcmJF4Lxz4wcL5WDL97PB");
            var nicoSecret = new BitcoinSecret("??????????");

            nico = nicoSecret.GetAddress();             //15sYbVpRh6dyWycZMwPdxJWD4xbfxReeHe

            var forFees = new Coin(
                fromTxHash: new uint256("7f296e96ec3525511b836ace0377a9fbb723a47bdfb07c6bc3a6f2a0c23eba26"),
                fromOutputIndex: 0,
                amount: Money.Satoshis(4425000),
                scriptPubKey: new Script(Encoders.Hex.DecodeData("76a914356facdac5f5bcae995d13e667bb5864fd1e7d5988ac")));

            builder = new TransactionBuilder();
            tx      = builder
                      .AddKeys(nicoSecret)
                      .AddCoins(colored, forFees)
                      .SendAsset(book, new AssetMoney(assetId, 10))
                      .SetChange(nico)
                      .SendFees(Money.Coins(0.0001m))
                      .BuildTransaction(true);
            UnityEngine.Debug.Log(tx);
        }
Пример #58
0
 public Coin GetCoinFromCashbox(Coin coin)
 {
     Device.GetCoin(coin);
     return(coin);
 }
Пример #59
0
        public async Task NotingTestsAsync()
        {
            (string password, RPCClient rpc, Network network, Coordinator coordinator, ServiceConfiguration serviceConfiguration, BitcoinStore bitcoinStore, Backend.Global global) = await Common.InitializeTestEnvironmentAsync(RegTestFixture, 1);

            Money   denomination                  = Money.Coins(1m);
            decimal coordinatorFeePercent         = 0.1m;
            int     anonymitySet                  = 2;
            int     connectionConfirmationTimeout = 1;
            bool    doesNoteBeforeBan             = true;
            CoordinatorRoundConfig roundConfig    = RegTestFixture.CreateRoundConfig(denomination, 140, 0.7, coordinatorFeePercent, anonymitySet, 240, connectionConfirmationTimeout, 1, 1, 1, 24, doesNoteBeforeBan, 11);

            coordinator.RoundConfig.UpdateOrDefault(roundConfig, toFile: true);
            coordinator.AbortAllRoundsInInputRegistration("");

            Uri baseUri = new Uri(RegTestFixture.BackendEndPoint);

            var              registerRequests  = new List <(BitcoinWitPubKeyAddress changeOutputAddress, uint256 blindedData, InputProofModel[] inputsProofs)>();
            AliceClient      aliceClientBackup = null;
            CoordinatorRound round             = coordinator.GetCurrentInputRegisterableRoundOrDefault();

            for (int i = 0; i < roundConfig.AnonymitySet; i++)
            {
                BitcoinWitPubKeyAddress activeOutputAddress = new Key().PubKey.GetSegwitAddress(network);
                BitcoinWitPubKeyAddress changeOutputAddress = new Key().PubKey.GetSegwitAddress(network);
                Key inputKey = new Key();
                BitcoinWitPubKeyAddress inputAddress = inputKey.PubKey.GetSegwitAddress(network);

                var     requester = new Requester();
                uint256 blinded   = requester.BlindScript(round.MixingLevels.GetBaseLevel().Signer.Key.PubKey, round.MixingLevels.GetBaseLevel().Signer.R.PubKey, activeOutputAddress.ScriptPubKey);
                uint256 blindedOutputScriptsHash = new uint256(Hashes.SHA256(blinded.ToBytes()));

                uint256 txHash = await rpc.SendToAddressAsync(inputAddress, Money.Coins(2));

                await rpc.GenerateAsync(1);

                Transaction transaction = await rpc.GetRawTransactionAsync(txHash);

                Coin     coin  = transaction.Outputs.GetCoins(inputAddress.ScriptPubKey).Single();
                OutPoint input = coin.Outpoint;

                InputProofModel inputProof = new InputProofModel {
                    Input = input.ToTxoRef(), Proof = inputKey.SignCompact(blindedOutputScriptsHash)
                };
                InputProofModel[] inputsProofs = new InputProofModel[] { inputProof };
                registerRequests.Add((changeOutputAddress, blinded, inputsProofs));
                aliceClientBackup = await AliceClient.CreateNewAsync(round.RoundId, new[] { activeOutputAddress }, new[] { round.MixingLevels.GetBaseLevel().SchnorrKey.SchnorrPubKey }, new[] { requester }, network, changeOutputAddress, new[] { blinded }, inputsProofs, baseUri, null);
            }

            await WaitForTimeoutAsync(baseUri);

            int bannedCount = coordinator.UtxoReferee.CountBanned(false);

            Assert.Equal(0, bannedCount);
            int notedCount = coordinator.UtxoReferee.CountBanned(true);

            Assert.Equal(anonymitySet, notedCount);

            round = coordinator.GetCurrentInputRegisterableRoundOrDefault();

            foreach (var registerRequest in registerRequests)
            {
                await AliceClient.CreateNewAsync(round.RoundId, aliceClientBackup.RegisteredAddresses, round.MixingLevels.GetAllLevels().Select(x => x.SchnorrKey.SchnorrPubKey), aliceClientBackup.Requesters, network, registerRequest.changeOutputAddress, new[] { registerRequest.blindedData }, registerRequest.inputsProofs, baseUri, null);
            }

            await WaitForTimeoutAsync(baseUri);

            bannedCount = coordinator.UtxoReferee.CountBanned(false);
            Assert.Equal(anonymitySet, bannedCount);
            notedCount = coordinator.UtxoReferee.CountBanned(true);
            Assert.Equal(anonymitySet, notedCount);
        }
 public Transaction ReSign(Coin coin)
 {
     return(ReSign(coin, out bool a));
 }