/// <summary>
        /// Constructs a grouper based on the contents of the given entity state manager.
        /// </summary>
        /// <param name="stateManager">Entity state manager containing changes to be processed.</param>
        /// <param name="metadataWorkspace">Metadata workspace.</param>
        /// <param name="connection">Map connection</param>
        /// <param name="commandTimeout">Timeout for update commands; null means 'use provider default'</param>
        private UpdateTranslator(IEntityStateManager stateManager, MetadataWorkspace metadataWorkspace, EntityConnection connection, int? commandTimeout)
        {
            EntityUtil.CheckArgumentNull(stateManager, "stateManager");
            EntityUtil.CheckArgumentNull(metadataWorkspace, "metadataWorkspace");
            EntityUtil.CheckArgumentNull(connection, "connection");

            // propagation state
            m_changes = new Dictionary<EntitySetBase, ChangeNode>();
            m_functionChanges = new Dictionary<EntitySetBase, List<ExtractedStateEntry>>();
            m_stateEntries = new List<IEntityStateEntry>();
            m_knownEntityKeys = new Set<EntityKey>();
            m_requiredEntities = new Dictionary<EntityKey, AssociationSet>();
            m_optionalEntities = new Set<EntityKey>();
            m_includedValueEntities = new Set<EntityKey>();

            // workspace state
            m_metadataWorkspace = metadataWorkspace;
            m_viewLoader = metadataWorkspace.GetUpdateViewLoader();
            m_stateManager = stateManager;

            // ancillary propagation services
            m_recordConverter = new RecordConverter(this);
            m_constraintValidator = new RelationshipConstraintValidator(this);

            m_providerServices = DbProviderServices.GetProviderServices(connection.StoreProviderFactory);
            m_connection = connection;
            m_commandTimeout = commandTimeout;

            // metadata cache
            m_extractorMetadata = new Dictionary<Tuple<EntitySetBase, StructuralType>, ExtractorMetadata>(); ;

            // key management
            KeyManager = new KeyManager(this);
            KeyComparer = CompositeKey.CreateComparer(KeyManager);
        }
Exemplo n.º 2
0
    public void ReceiveCommand(KeyManager.KeyNumber command, KeyManager.KeyPressType type)
    {
        if (type == KeyManager.KeyPressType.PRESS)
            return;

        Debug.Log(gameObject.name + "->" + command + " " + type);
    }
Exemplo n.º 3
0
 public void ReturnsPrivateKeys()
 {
     var keys = new KeyManager("keytest", "keytestenv");
     Assert.IsNotNull(keys["keytest"].Priv);
     Assert.IsTrue(keys["keytest"].Priv.HasPrivateKey);
     Assert.IsFalse(string.IsNullOrWhiteSpace(keys["keytest"].PrivPem));
 }
Exemplo n.º 4
0
 public TimeLineControl()
 {
     this.InitializeComponent();
     
     keyManager = new KeyManager(listViewTimeline, KeyBindings.TweetKeyBinder);
     keyManager.CommandList.Add("Favorite", (bind) =>
     {
         if (listViewTimeline.SelectedIndex != -1)
         {
             //(DataContext as TimelineBase).ViewModel.FavoriteCommand.Execute((listViewTimeline.SelectedItem as TimelineRow).Tweet);
         }
     });
     keyManager.CommandList.Add("Retweet", (bind) =>
     {
         if (listViewTimeline.SelectedIndex != -1)
         {
             //(DataContext as TimelineBase).ViewModel.RetweetCommand.Execute((listViewTimeline.SelectedItem as TimelineRow).Tweet);
         }
     });
     keyManager.CommandList.Add("Detail", (bind) =>
     {
         if (listViewTimeline.SelectedIndex != -1)
         {
            // (DataContext as TimelineBase).ViewModel.TweetDetailCommand.Execute((listViewTimeline.SelectedItem as TimelineRow).Tweet);
         }
     });
     keyManager.CommandList.Add("Reply", (bind) =>
     {
         if (listViewTimeline.SelectedIndex != -1)
         {
           //  (DataContext as TimelineBase).ViewModel.ReplyCommand.Execute((listViewTimeline.SelectedItem as TimelineRow).Tweet);
         }
     });
 }
Exemplo n.º 5
0
 public void ReturnsPublicKeys()
 {
     var keys = new KeyManager("keytest", "keytestenv");
     Assert.IsNotNull(keys["otherapp"].Pub);
     Assert.IsFalse(keys["otherapp"].Pub.HasPrivateKey);
     Assert.IsFalse(string.IsNullOrWhiteSpace(keys["otherapp"].PubPem));
 }
Exemplo n.º 6
0
 public PostFolderManager(string dataDirectory, string contentDirectory, string folderName, string securityKey)
 {
     DataDirectory = dataDirectory;
     ContentDirectory = contentDirectory;
     FolderId = folderName;
     SecurityKey = securityKey;
     Overwriter = new FileOverwriter (contentDirectory, folderName, securityKey);
     Appender = new FileAppender (contentDirectory, folderName, securityKey);
     Keys = new KeyManager (dataDirectory);
     Authentication = new Authenticator (Keys);
 }
Exemplo n.º 7
0
        public KeyEditor(DwarfGUI gui, GUIComponent parent, KeyManager keyManager, int numRows, int numColumns)
            : base(gui, parent)
        {
            Keys[] reserved =
            {
                Keys.Up,
                Keys.Left,
                Keys.Right,
                Keys.Down,
                Keys.LeftControl,
                Keys.LeftShift,
                Keys.RightShift,
                Keys.LeftAlt,
                Keys.RightAlt,
                Keys.RightControl,
                Keys.Escape
            };
            ReservedKeys = new List<Keys>();
            ReservedKeys.AddRange(reserved);

            KeyManager = keyManager;

            Layout = new GridLayout(gui, this, numRows, numColumns * 2);

            int r = 0;
            int c = 0;

            foreach(KeyValuePair<string, Keys> button in KeyManager.Buttons)
            {
                if(r == numRows)
                {
                    r = 0;
                    c++;
                }

                Label keyLabel = new Label(gui, Layout, button.Key, gui.DefaultFont);
                KeyEdit editor = new KeyEdit(gui, Layout, button.Value);
                Layout.SetComponentPosition(keyLabel, c * 2, r, 1, 1);
                Layout.SetComponentPosition(editor, c * 2 + 1, r, 1, 1);

                string name = button.Key;

                editor.OnKeyModified += (prevKey, arg, keyedit) => editor_OnKeyModified(name, prevKey, arg, keyedit);

                r++;
            }
        }
Exemplo n.º 8
0
 public override BaseKey GetKey()
 {
     return(KeyManager.GetMappedRandomKey(myRandomKeyIdentifier));
 }
    public async Task LedgerNanoSTestsAsync(Network network)
    {
        var client = new HwiClient(network, new HwiProcessBridgeMock(HardwareWalletModels.Ledger_Nano_S));

        using var cts = new CancellationTokenSource(ReasonableRequestTimeout);
        IEnumerable <HwiEnumerateEntry> enumerate = await client.EnumerateAsync(cts.Token);

        Assert.Single(enumerate);
        HwiEnumerateEntry entry = enumerate.Single();

        Assert.Equal(HardwareWalletModels.Ledger_Nano_S, entry.Model);
        Assert.Equal(@"\\?\hid#vid_2c97&pid_0001&mi_00#7&e45ae20&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}", entry.Path);
        Assert.False(entry.NeedsPassphraseSent);
        Assert.False(entry.NeedsPinSent);
        Assert.Null(entry.Error);
        Assert.Null(entry.Code);
        Assert.True(entry.IsInitialized());
        Assert.Equal("4054d6f6", entry.Fingerprint.ToString());

        var deviceType = entry.Model;
        var devicePath = entry.Path;

        var wipe = await Assert.ThrowsAsync <HwiException>(async() => await client.WipeAsync(deviceType, devicePath, cts.Token));

        Assert.Equal("The Ledger Nano S does not support wiping via software", wipe.Message);
        Assert.Equal(HwiErrorCode.UnavailableAction, wipe.ErrorCode);

        var setup = await Assert.ThrowsAsync <HwiException>(async() => await client.SetupAsync(deviceType, devicePath, false, cts.Token));

        Assert.Equal("The Ledger Nano S does not support software setup", setup.Message);
        Assert.Equal(HwiErrorCode.UnavailableAction, setup.ErrorCode);

        var restore = await Assert.ThrowsAsync <HwiException>(async() => await client.RestoreAsync(deviceType, devicePath, false, cts.Token));

        Assert.Equal("The Ledger Nano S does not support restoring via software", restore.Message);
        Assert.Equal(HwiErrorCode.UnavailableAction, restore.ErrorCode);

        var promptpin = await Assert.ThrowsAsync <HwiException>(async() => await client.PromptPinAsync(deviceType, devicePath, cts.Token));

        Assert.Equal("The Ledger Nano S does not need a PIN sent from the host", promptpin.Message);
        Assert.Equal(HwiErrorCode.UnavailableAction, promptpin.ErrorCode);

        var sendpin = await Assert.ThrowsAsync <HwiException>(async() => await client.SendPinAsync(deviceType, devicePath, 1111, cts.Token));

        Assert.Equal("The Ledger Nano S does not need a PIN sent from the host", sendpin.Message);
        Assert.Equal(HwiErrorCode.UnavailableAction, sendpin.ErrorCode);

        KeyPath   keyPath1 = KeyManager.GetAccountKeyPath(network);
        KeyPath   keyPath2 = KeyManager.GetAccountKeyPath(network).Derive(1);
        ExtPubKey xpub1    = await client.GetXpubAsync(deviceType, devicePath, keyPath1, cts.Token);

        ExtPubKey xpub2 = await client.GetXpubAsync(deviceType, devicePath, keyPath2, cts.Token);

        ExtPubKey expectedXpub1;
        ExtPubKey expectedXpub2;

        if (network == Network.TestNet)
        {
            expectedXpub1 = NBitcoinHelpers.BetterParseExtPubKey("xpub6CaGC5LjEw1YWw8br7AURnB6ioJY2bEVApXh8NMsPQ9mdDbzN51iwVrnmGSof3MfjjRrntnE8mbYeTW5ywgvCXdjqF8meQEwnhPDQV2TW7c");
            expectedXpub2 = NBitcoinHelpers.BetterParseExtPubKey("xpub6E7pup6CRRS5jM1r3HVYQhHwQHpddJALjRDbsVDtsnQJozHrfE8Pua2X5JhtkWCxdcmGhPXWxV7DoJtSgZSUvUy6cvDchVQt2RGEd4mD4FA");
        }
        else
        {
            expectedXpub1 = NBitcoinHelpers.BetterParseExtPubKey("xpub6DHjDx4gzLV37gJWMxYJAqyKRGN46MT61RHVizdU62cbVUYu9L95cXKzX62yJ2hPbN11EeprS8sSn8kj47skQBrmycCMzFEYBQSntVKFQ5M");
            expectedXpub2 = NBitcoinHelpers.BetterParseExtPubKey("xpub6FJS1ne3STcKdQ9JLXNzZXidmCNZ9dxLiy7WVvsRkcmxjJsrDKJKEAXq4MGyEBM3vHEw2buqXezfNK5SNBrkwK7Fxjz1TW6xzRr2pUyMWFu");
        }
        Assert.Equal(expectedXpub1, xpub1);
        Assert.Equal(expectedXpub2, xpub2);

        BitcoinWitPubKeyAddress address1 = await client.DisplayAddressAsync(deviceType, devicePath, keyPath1, cts.Token);

        BitcoinWitPubKeyAddress address2 = await client.DisplayAddressAsync(deviceType, devicePath, keyPath2, cts.Token);

        BitcoinAddress expectedAddress1;
        BitcoinAddress expectedAddress2;

        if (network == Network.Main)
        {
            expectedAddress1 = BitcoinAddress.Create("bc1q7zqqsmqx5ymhd7qn73lm96w5yqdkrmx7fdevah", Network.Main);
            expectedAddress2 = BitcoinAddress.Create("bc1qmaveee425a5xjkjcv7m6d4gth45jvtnj23fzyf", Network.Main);
        }
        else if (network == Network.TestNet)
        {
            expectedAddress1 = BitcoinAddress.Create("tb1q7zqqsmqx5ymhd7qn73lm96w5yqdkrmx7rtzlxy", Network.TestNet);
            expectedAddress2 = BitcoinAddress.Create("tb1qmaveee425a5xjkjcv7m6d4gth45jvtnjqhj3l6", Network.TestNet);
        }
        else if (network == Network.RegTest)
        {
            expectedAddress1 = BitcoinAddress.Create("bcrt1q7zqqsmqx5ymhd7qn73lm96w5yqdkrmx7pzmj3d", Network.RegTest);
            expectedAddress2 = BitcoinAddress.Create("bcrt1qmaveee425a5xjkjcv7m6d4gth45jvtnjz7tugn", Network.RegTest);
        }
        else
        {
            throw new NotSupportedNetworkException(network);
        }

        Assert.Equal(expectedAddress1, address1);
        Assert.Equal(expectedAddress2, address2);
    }
Exemplo n.º 10
0
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public BuildTransactionResult BuildTransaction(
            PaymentIntent payments,
            Func <FeeRate> feeRateFetcher,
            IEnumerable <TxoRef> allowedInputs = null,
            Func <LockTime> lockTimeSelector   = null)
        {
            payments = Guard.NotNull(nameof(payments), payments);
            lockTimeSelector ??= () => LockTime.Zero;

            long totalAmount = payments.TotalAmount.Satoshi;

            if (totalAmount < 0 || totalAmount > Constants.MaximumNumberOfSatoshis)
            {
                throw new ArgumentOutOfRangeException($"{nameof(payments)}.{nameof(payments.TotalAmount)} sum cannot be smaller than 0 or greater than {Constants.MaximumNumberOfSatoshis}.");
            }

            // Get allowed coins to spend.
            var availableCoinsView = Coins.Available();
            List <SmartCoin> allowedSmartCoinInputs = AllowUnconfirmed            // Inputs that can be used to build the transaction.
                                        ? availableCoinsView.ToList()
                                        : availableCoinsView.Confirmed().ToList();

            if (allowedInputs != null)             // If allowedInputs are specified then select the coins from them.
            {
                if (!allowedInputs.Any())
                {
                    throw new ArgumentException($"{nameof(allowedInputs)} is not null, but empty.");
                }

                allowedSmartCoinInputs = allowedSmartCoinInputs
                                         .Where(x => allowedInputs.Any(y => y.TransactionId == x.TransactionId && y.Index == x.Index))
                                         .ToList();

                // Add those that have the same script, because common ownership is already exposed.
                // But only if the user didn't click the "max" button. In this case he'd send more money than what he'd think.
                if (payments.ChangeStrategy != ChangeStrategy.AllRemainingCustom)
                {
                    var allScripts = allowedSmartCoinInputs.Select(x => x.ScriptPubKey).ToHashSet();
                    foreach (var coin in availableCoinsView.Where(x => !allowedSmartCoinInputs.Any(y => x.TransactionId == y.TransactionId && x.Index == y.Index)))
                    {
                        if (!(AllowUnconfirmed || coin.Confirmed))
                        {
                            continue;
                        }

                        if (allScripts.Contains(coin.ScriptPubKey))
                        {
                            allowedSmartCoinInputs.Add(coin);
                        }
                    }
                }
            }

            // Get and calculate fee
            Logger.LogInfo("Calculating dynamic transaction fee...");

            TransactionBuilder builder = Network.CreateTransactionBuilder();

            builder.SetCoinSelector(new SmartCoinSelector(allowedSmartCoinInputs));
            builder.AddCoins(allowedSmartCoinInputs.Select(c => c.GetCoin()));

            foreach (var request in payments.Requests.Where(x => x.Amount.Type == MoneyRequestType.Value))
            {
                var amountRequest = request.Amount;

                builder.Send(request.Destination, amountRequest.Amount);
                if (amountRequest.SubtractFee)
                {
                    builder.SubtractFees();
                }
            }

            HdPubKey changeHdPubKey = null;

            if (payments.TryGetCustomRequest(out DestinationRequest custChange))
            {
                var changeScript = custChange.Destination.ScriptPubKey;
                changeHdPubKey = KeyManager.GetKeyForScriptPubKey(changeScript);

                var changeStrategy = payments.ChangeStrategy;
                if (changeStrategy == ChangeStrategy.Custom)
                {
                    builder.SetChange(changeScript);
                }
                else if (changeStrategy == ChangeStrategy.AllRemainingCustom)
                {
                    builder.SendAllRemaining(changeScript);
                }
                else
                {
                    throw new NotSupportedException(payments.ChangeStrategy.ToString());
                }
            }
            else
            {
                KeyManager.AssertCleanKeysIndexed(isInternal: true);
                KeyManager.AssertLockedInternalKeysIndexed(14);
                changeHdPubKey = KeyManager.GetKeys(KeyState.Clean, true).RandomElement();

                builder.SetChange(changeHdPubKey.P2wpkhScript);
            }

            builder.OptInRBF = new Random().NextDouble() < Constants.TransactionRBFSignalRate;

            FeeRate feeRate = feeRateFetcher();

            builder.SendEstimatedFees(feeRate);

            var psbt = builder.BuildPSBT(false);

            var spentCoins = psbt.Inputs.Select(txin => allowedSmartCoinInputs.First(y => y.OutPoint == txin.PrevOut)).ToArray();

            var realToSend = payments.Requests
                             .Select(t =>
                                     (label: t.Label,
                                      destination: t.Destination,
                                      amount: psbt.Outputs.FirstOrDefault(o => o.ScriptPubKey == t.Destination.ScriptPubKey)?.Value))
                             .Where(i => i.amount != null);

            if (!psbt.TryGetFee(out var fee))
            {
                throw new InvalidOperationException("Impossible to get the fees of the PSBT, this should never happen.");
            }
            Logger.LogInfo($"Fee: {fee.Satoshi} Satoshi.");

            var vSize = builder.EstimateSize(psbt.GetOriginalTransaction(), true);

            Logger.LogInfo($"Estimated tx size: {vSize} vBytes.");

            // Do some checks
            Money totalSendAmountNoFee = realToSend.Sum(x => x.amount);

            if (totalSendAmountNoFee == Money.Zero)
            {
                throw new InvalidOperationException("The amount after subtracting the fee is too small to be sent.");
            }
            Money totalSendAmount = totalSendAmountNoFee + fee;

            Money totalOutgoingAmountNoFee;

            if (changeHdPubKey is null)
            {
                totalOutgoingAmountNoFee = totalSendAmountNoFee;
            }
            else
            {
                totalOutgoingAmountNoFee = realToSend.Where(x => !changeHdPubKey.ContainsScript(x.destination.ScriptPubKey)).Sum(x => x.amount);
            }
            decimal totalOutgoingAmountNoFeeDecimal = totalOutgoingAmountNoFee.ToDecimal(MoneyUnit.BTC);
            // Cannot divide by zero, so use the closest number we have to zero.
            decimal totalOutgoingAmountNoFeeDecimalDivisor = totalOutgoingAmountNoFeeDecimal == 0 ? decimal.MinValue : totalOutgoingAmountNoFeeDecimal;
            decimal feePc = 100 * fee.ToDecimal(MoneyUnit.BTC) / totalOutgoingAmountNoFeeDecimalDivisor;

            if (feePc > 1)
            {
                Logger.LogInfo($"The transaction fee is {totalOutgoingAmountNoFee:0.#}% of your transaction amount.{Environment.NewLine}"
                               + $"Sending:\t {totalSendAmount.ToString(fplus: false, trimExcessZero: true)} BTC.{Environment.NewLine}"
                               + $"Fee:\t\t {fee.Satoshi} Satoshi.");
            }
            if (feePc > 100)
            {
                throw new InvalidOperationException($"The transaction fee is more than twice the transaction amount: {feePc:0.#}%.");
            }

            if (spentCoins.Any(u => !u.Confirmed))
            {
                Logger.LogInfo("Unconfirmed transaction is spent.");
            }

            // Build the transaction
            Logger.LogInfo("Signing transaction...");
            // It must be watch only, too, because if we have the key and also hardware wallet, we do not care we can sign.

            Transaction tx = null;

            if (KeyManager.IsWatchOnly)
            {
                tx = psbt.GetGlobalTransaction();
            }
            else
            {
                IEnumerable <ExtKey> signingKeys = KeyManager.GetSecrets(Password, spentCoins.Select(x => x.ScriptPubKey).ToArray());
                builder = builder.AddKeys(signingKeys.ToArray());
                builder.SetLockTime(lockTimeSelector());
                builder.SignPSBT(psbt);
                psbt.Finalize();
                tx = psbt.ExtractTransaction();

                var checkResults = builder.Check(tx).ToList();
                if (!psbt.TryGetEstimatedFeeRate(out FeeRate actualFeeRate))
                {
                    throw new InvalidOperationException("Impossible to get the fee rate of the PSBT, this should never happen.");
                }

                // Manually check the feerate, because some inaccuracy is possible.
                var sb1 = feeRate.SatoshiPerByte;
                var sb2 = actualFeeRate.SatoshiPerByte;
                if (Math.Abs(sb1 - sb2) > 2)                 // 2s/b inaccuracy ok.
                {
                    // So it'll generate a transactionpolicy error thrown below.
                    checkResults.Add(new NotEnoughFundsPolicyError("Fees different than expected"));
                }
                if (checkResults.Count > 0)
                {
                    throw new InvalidTxException(tx, checkResults);
                }
            }

            if (KeyManager.MasterFingerprint is HDFingerprint fp)
            {
                foreach (var coin in spentCoins)
                {
                    var rootKeyPath = new RootedKeyPath(fp, coin.HdPubKey.FullKeyPath);
                    psbt.AddKeyPath(coin.HdPubKey.PubKey, rootKeyPath, coin.ScriptPubKey);
                }
            }

            var label = SmartLabel.Merge(payments.Requests.Select(x => x.Label).Concat(spentCoins.Select(x => x.Label)));
            var outerWalletOutputs = new List <SmartCoin>();
            var innerWalletOutputs = new List <SmartCoin>();

            for (var i = 0U; i < tx.Outputs.Count; i++)
            {
                TxOut output   = tx.Outputs[i];
                var   anonset  = tx.GetAnonymitySet(i) + spentCoins.Min(x => x.AnonymitySet) - 1;              // Minus 1, because count own only once.
                var   foundKey = KeyManager.GetKeyForScriptPubKey(output.ScriptPubKey);
                var   coin     = new SmartCoin(tx.GetHash(), i, output.ScriptPubKey, output.Value, tx.Inputs.ToTxoRefs().ToArray(), Height.Unknown, tx.RBF, anonset, pubKey: foundKey);
                label = SmartLabel.Merge(label, coin.Label);                 // foundKey's label is already added to the coinlabel.

                if (foundKey is null)
                {
                    outerWalletOutputs.Add(coin);
                }
                else
                {
                    innerWalletOutputs.Add(coin);
                }
            }

            foreach (var coin in outerWalletOutputs.Concat(innerWalletOutputs))
            {
                var foundPaymentRequest = payments.Requests.FirstOrDefault(x => x.Destination.ScriptPubKey == coin.ScriptPubKey);

                // If change then we concatenate all the labels.
                if (foundPaymentRequest is null)                 // Then it's autochange.
                {
                    coin.Label = label;
                }
                else
                {
                    coin.Label = SmartLabel.Merge(coin.Label, foundPaymentRequest.Label);
                }

                var foundKey = KeyManager.GetKeyForScriptPubKey(coin.ScriptPubKey);
                foundKey?.SetLabel(coin.Label);                 // The foundkeylabel has already been added previously, so no need to concatenate.
            }

            Logger.LogInfo($"Transaction is successfully built: {tx.GetHash()}.");
            var sign = !KeyManager.IsWatchOnly;
            var spendsUnconfirmed = spentCoins.Any(c => !c.Confirmed);

            return(new BuildTransactionResult(new SmartTransaction(tx, Height.Unknown), psbt, spendsUnconfirmed, sign, fee, feePc, outerWalletOutputs, innerWalletOutputs, spentCoins));
        }
Exemplo n.º 11
0
        public async Task TestServicesAsync(string networkString)
        {
            var network          = Network.GetNetwork(networkString);
            var blocksToDownload = new HashSet <uint256>();

            if (network == Network.Main)
            {
                blocksToDownload.Add(new uint256("00000000000000000037c2de35bd85f3e57f14ddd741ce6cee5b28e51473d5d0"));
                blocksToDownload.Add(new uint256("000000000000000000115315a43cb0cdfc4ea54a0e92bed127f4e395e718d8f9"));
                blocksToDownload.Add(new uint256("00000000000000000011b5b042ad0522b69aae36f7de796f563c895714bbd629"));
            }
            else if (network == Network.TestNet)
            {
                blocksToDownload.Add(new uint256("0000000097a664c4084b49faa6fd4417055cb8e5aac480abc31ddc57a8208524"));
                blocksToDownload.Add(new uint256("000000009ed5b82259ecd2aa4cd1f119db8da7a70e7ea78d9c9f603e01f93bcc"));
                blocksToDownload.Add(new uint256("00000000e6da8c2da304e9f5ad99c079df2c3803b49efded3061ecaf206ddc66"));
            }
            else
            {
                throw new NotSupportedException(network.ToString());
            }

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

            try
            {
                addressManager = AddressManager.LoadPeerFile(addressManagerFilePath);
                Logger.LogInfo <AddressManager>($"Loaded {nameof(AddressManager)} from `{addressManagerFilePath}`.");
            }
            catch (DirectoryNotFoundException ex)
            {
                Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} did not exist at `{addressManagerFilePath}`. Initializing new one.");
                Logger.LogTrace <AddressManager>(ex);
                addressManager = new AddressManager();
            }
            catch (FileNotFoundException ex)
            {
                Logger.LogInfo <AddressManager>($"{nameof(AddressManager)} did not exist at `{addressManagerFilePath}`. Initializing new one.");
                Logger.LogTrace <AddressManager>(ex);
                addressManager = new AddressManager();
            }

            connectionParameters.TemplateBehaviors.Add(new AddressManagerBehavior(addressManager));
            var memPoolService = new MemPoolService();

            connectionParameters.TemplateBehaviors.Add(new MemPoolBehavior(memPoolService));

            var nodes = new NodesGroup(network, connectionParameters,
                                       new NodeRequirement
            {
                RequiredServices = NodeServices.Network,
                MinVersion       = ProtocolVersion_WITNESS_VERSION
            });

            KeyManager    keyManager    = KeyManager.CreateNew(out _, "password");
            WalletService walletService = new WalletService(
                keyManager,
                new IndexDownloader(network, Path.Combine(SharedFixture.DataDir, nameof(TestServicesAsync), "IndexDownloader.txt"), new Uri("http://localhost:12345")),
                new CcjClient(network, new BlindingRsaKey().PubKey, keyManager, new Uri("http://localhost:12345")),
                memPoolService,
                nodes,
                blocksFolderPath);

            Assert.True(Directory.Exists(blocksFolderPath));

            try
            {
                nodes.ConnectedNodes.Added         += ConnectedNodes_Added;
                nodes.ConnectedNodes.Removed       += ConnectedNodes_Removed;
                memPoolService.TransactionReceived += MemPoolService_TransactionReceived;

                nodes.Connect();
                // Using the interlocked, not because it makes sense in this context, but to
                // set an example that these values are often concurrency sensitive
                var times = 0;
                while (Interlocked.Read(ref _nodeCount) < 3)
                {
                    if (times > 4200)                     // 7 minutes
                    {
                        throw new TimeoutException($"Connection test timed out.");
                    }
                    await Task.Delay(100);

                    times++;
                }

                times = 0;
                while (Interlocked.Read(ref _mempoolTransactionCount) < 3)
                {
                    if (times > 3000)                     // 3 minutes
                    {
                        throw new TimeoutException($"{nameof(MemPoolService)} test timed out.");
                    }
                    await Task.Delay(100);

                    times++;
                }

                foreach (var hash in blocksToDownload)
                {
                    using (var cts = new CancellationTokenSource(TimeSpan.FromMinutes(3)))
                    {
                        var block = await walletService.GetOrDownloadBlockAsync(hash, cts.Token);

                        Assert.True(File.Exists(Path.Combine(blocksFolderPath, hash.ToString())));
                        Logger.LogInfo <P2pTests>($"Full block is downloaded: {hash}.");
                    }
                }
            }
            finally
            {
                nodes.ConnectedNodes.Added         -= ConnectedNodes_Added;
                nodes.ConnectedNodes.Removed       -= ConnectedNodes_Removed;
                memPoolService.TransactionReceived -= MemPoolService_TransactionReceived;

                // So next test will download the block.
                foreach (var hash in blocksToDownload)
                {
                    await walletService?.DeleteBlockAsync(hash);
                }
                walletService?.Dispose();

                if (Directory.Exists(blocksFolderPath))
                {
                    Directory.Delete(blocksFolderPath, recursive: true);
                }

                Directory.CreateDirectory(Path.GetDirectoryName(addressManagerFilePath));
                addressManager?.SavePeerFile(addressManagerFilePath, network);
                Logger.LogInfo <P2pTests>($"Saved {nameof(AddressManager)} to `{addressManagerFilePath}`.");
                nodes?.Dispose();
            }
        }
Exemplo n.º 12
0
        public Uploader(LocalFileCacher local_cacher, RemoteFileCacher remote_cacher, string local_path, string remote_path, int account_id, bool overwriting_exist_file = false, int max_thread = DEFAULT_MAX_THREAD, int speed_limit = 0, KeyManager key_manager = null, bool enable_encryption = false)
        {
            if (local_cacher == null)
            {
                throw new ArgumentNullException("local_cacher");
            }
            if (remote_cacher == null)
            {
                throw new ArgumentNullException("remote_cacher");
            }
            if (string.IsNullOrEmpty(local_path))
            {
                throw new ArgumentNullException("local_path");
            }
            if (string.IsNullOrEmpty(remote_path))
            {
                throw new ArgumentNullException("remote_path");
            }
            if (remote_path.EndsWith("/"))
            {
                throw new ArgumentException("remote_path非法:/不能在路径结束");
            }
            if (speed_limit < 0)
            {
                throw new ArgumentOutOfRangeException("speed_limit");
            }
            _overwrite         = overwriting_exist_file;
            _local_cacher      = local_cacher;
            _remote_cacher     = remote_cacher;
            _local_path        = local_path;
            _remote_path       = remote_path;
            _speed_limit       = speed_limit;
            _key_manager       = key_manager;
            _enable_encryption = enable_encryption;

            var file_info = new FileInfo(_local_path);

            if (!file_info.Exists)
            {
                throw new ArgumentException("file not exists");
            }
            //file monitor
            _file_watcher                     = new FileSystemWatcher(file_info.Directory.FullName, file_info.Name);
            _file_watcher.Changed            += _on_file_changed;
            _file_watcher.Deleted            += _on_file_deleted;
            _file_watcher.EnableRaisingEvents = true;

            _external_lock    = new object();
            _thread_flag_lock = new object();
            _thread_data_lock = new object();

            _file_size    = file_info.Length;
            _max_thread   = max_thread;
            _slice_count  = (int)Math.Ceiling(_file_size * 1.0 / BaiduPCS.UPLOAD_SLICE_SIZE);
            _slice_seq    = new ConcurrentQueue <int>();
            _slice_result = new ConcurrentDictionary <int, string>();

            _selected_account_id = account_id;
            _upload_size_5s      = new LinkedList <long>();
            for (int i = 0; i < 6; i++)
            {
                _upload_size_5s.AddLast(0);
            }
            _monitor_thread_created = new ManualResetEventSlim();
            _file_io_response       = new ManualResetEventSlim();
            _monitor_thread_exited  = new ManualResetEventSlim();

            _local_cacher.LocalFileIOFinish += _on_file_io_completed;
            _local_cacher.LocalFileIOUpdate += _on_file_io_updated;
            _local_cacher.LocalFileIOAbort  += _on_file_io_aborted;

            _upload_thread_flag = _UPLOAD_THREAD_FLAG_READY;
        }
 private void OnNext(KeyManager keyManager)
 {
     Navigate().To(new AddedWalletPageViewModel(keyManager));
 }
Exemplo n.º 14
0
 private void OnFireKey(KeyManager km, Keys key, bool repeat = false)
 {
     game.Events.Add(game.Character.Emitter.ChangePattern(game.CurrentTime, 0));
 }
Exemplo n.º 15
0
 private void OnRelFireKey(KeyManager km, Keys key)
 {
     game.Events.Add(game.Character.Emitter.ChangePattern(game.CurrentTime, -1));
 }
Exemplo n.º 16
0
    public AddressLabelEditViewModel(ReceiveAddressesViewModel owner, HdPubKey hdPubKey, KeyManager keyManager)
    {
        SuggestionLabels = new SuggestionLabelsViewModel(keyManager, Intent.Receive, 3, hdPubKey.Label);

        SetupCancel(enableCancel: true, enableCancelOnEscape: true, enableCancelOnPressed: true);

        var canExecute =
            this.WhenAnyValue(x => x.SuggestionLabels.Labels.Count, x => x.IsCurrentTextValid)
            .Select(tup =>
        {
            var(labelsCount, isCurrentTextValid) = tup;
            return(labelsCount > 0 || isCurrentTextValid);
        });

        NextCommand = ReactiveCommand.Create(
            () =>
        {
            hdPubKey.SetLabel(new SmartLabel(SuggestionLabels.Labels), kmToFile: keyManager);
            owner.InitializeAddresses();
            Navigate().Back();
        },
            canExecute);
    }
 public DirectoryServicePublicKeySteps(CommonContext commonContext, DirectoryClientContext directoryClientContext, KeyManager keyManager)
 {
     _commonContext          = commonContext;
     _directoryClientContext = directoryClientContext;
     _keyManager             = keyManager;
 }
Exemplo n.º 18
0
        public RecoverWalletViewModel(WalletManagerViewModel owner) : base("Recover Wallet")
        {
            Global = Locator.Current.GetService <Global>();

            MnemonicWords = "";

            RecoverCommand = ReactiveCommand.Create(() =>
            {
                WalletName    = Guard.Correct(WalletName);
                MnemonicWords = Guard.Correct(MnemonicWords);
                Password      = Guard.Correct(Password);            // Do not let whitespaces to the beginning and to the end.

                string walletFilePath = Path.Combine(Global.WalletsDir, $"{WalletName}.json");

                if (string.IsNullOrWhiteSpace(WalletName))
                {
                    NotificationHelpers.Error("Invalid wallet name.");
                }
                else if (File.Exists(walletFilePath))
                {
                    NotificationHelpers.Error("Wallet name is already taken.");
                }
                else if (string.IsNullOrWhiteSpace(MnemonicWords))
                {
                    NotificationHelpers.Error("Recovery Words were not supplied.");
                }
                else if (string.IsNullOrWhiteSpace(AccountKeyPath))
                {
                    NotificationHelpers.Error("The account key path is not valid.");
                }
                else if (MinGapLimit < KeyManager.AbsoluteMinGapLimit)
                {
                    NotificationHelpers.Error($"Min Gap Limit cannot be smaller than {KeyManager.AbsoluteMinGapLimit}.");
                }
                else if (MinGapLimit > 1_000_000)
                {
                    NotificationHelpers.Error($"Min Gap Limit cannot be larger than {1_000_000}.");
                }
                else if (!KeyPath.TryParse(AccountKeyPath, out KeyPath keyPath))
                {
                    NotificationHelpers.Error("The account key path is not a valid derivation path.");
                }
                else
                {
                    try
                    {
                        var mnemonic = new Mnemonic(MnemonicWords);
                        var km       = KeyManager.Recover(mnemonic, Password, filePath: null, keyPath, MinGapLimit);
                        km.SetNetwork(Global.Network);
                        km.SetFilePath(walletFilePath);
                        km.ToFile();

                        NotificationHelpers.Success("Wallet is successfully recovered!");

                        owner.SelectLoadWallet();
                    }
                    catch (Exception ex)
                    {
                        NotificationHelpers.Error(ex.ToTypeMessageString());
                        Logger.LogError(ex);
                    }
                }
            });

            this.WhenAnyValue(x => x.MnemonicWords).Subscribe(UpdateSuggestions);

            _suggestions = new ObservableCollection <SuggestionViewModel>();

            RecoverCommand.ThrownExceptions
            .ObserveOn(RxApp.TaskpoolScheduler)
            .Subscribe(ex => Logger.LogError(ex));
        }
Exemplo n.º 19
0
        private async Task TryRegisterCoinsAsync(CcjClientRound inputRegistrableRound)
        {
            try
            {
                List <(uint256 txid, uint index)> registrableCoins = State.GetRegistrableCoins(
                    inputRegistrableRound.State.MaximumInputCountPerPeer,
                    inputRegistrableRound.State.Denomination,
                    inputRegistrableRound.State.FeePerInputs,
                    inputRegistrableRound.State.FeePerOutputs).ToList();

                if (registrableCoins.Any())
                {
                    BitcoinAddress changeAddress = null;
                    BitcoinAddress activeAddress = null;
                    lock (CustomChangeAddressesLock)
                    {
                        if (CustomChangeAddresses.Count > 0)
                        {
                            changeAddress = CustomChangeAddresses.First();
                            CustomChangeAddresses.RemoveFirst();
                        }
                    }
                    lock (CustomActiveAddressesLock)
                    {
                        if (CustomActiveAddresses.Count > 0)
                        {
                            activeAddress = CustomActiveAddresses.First();
                            CustomActiveAddresses.RemoveFirst();
                        }
                    }
                    changeAddress = changeAddress ?? KeyManager.GenerateNewKey("ZeroLink Change", KeyState.Locked, isInternal: true, toFile: false).GetP2wpkhAddress(Network);
                    activeAddress = activeAddress ?? KeyManager.GenerateNewKey("ZeroLink Mixed Coin", KeyState.Locked, isInternal: true, toFile: false).GetP2wpkhAddress(Network);
                    KeyManager.ToFile();

                    var blind = CoordinatorPubKey.Blind(activeAddress.ScriptPubKey.ToBytes());

                    var inputProofs = new List <InputProofModel>();
                    foreach ((uint256 txid, uint index)coinReference in registrableCoins)
                    {
                        var coin = State.GetSingleOrDefaultFromWaitingList(coinReference);
                        if (coin == null)
                        {
                            throw new NotSupportedException("This is impossible.");
                        }
                        var inputProof = new InputProofModel
                        {
                            Input = coin.GetTxoRef(),
                            Proof = coin.Secret.PrivateKey.SignMessage(ByteHelpers.ToHex(blind.BlindedData))
                        };
                        inputProofs.Add(inputProof);
                    }
                    AliceClient aliceClient = await AliceClient.CreateNewAsync(Network, changeAddress, blind.BlindedData, inputProofs, CcjHostUri, TorSocks5EndPoint);

                    byte[] unblindedSignature = CoordinatorPubKey.UnblindSignature(aliceClient.BlindedOutputSignature, blind.BlindingFactor);

                    if (!CoordinatorPubKey.Verify(unblindedSignature, activeAddress.ScriptPubKey.ToBytes()))
                    {
                        throw new NotSupportedException("Coordinator did not sign the blinded output properly.");
                    }

                    CcjClientRound roundRegistered = State.GetSingleOrDefaultRound(aliceClient.RoundId);
                    if (roundRegistered == null)
                    {
                        // If our SatoshiClient doesn't yet know about the round because of the dealy create it.
                        // Make its state as it'd be the same as our assumed round was, except the roundId and registeredPeerCount, it'll be updated later.
                        roundRegistered = new CcjClientRound(CcjRunningRoundState.CloneExcept(inputRegistrableRound.State, aliceClient.RoundId, registeredPeerCount: 1));
                        State.AddOrReplaceRound(roundRegistered);
                    }

                    foreach ((uint256 txid, uint index)coinReference in registrableCoins)
                    {
                        var coin = State.GetSingleOrDefaultFromWaitingList(coinReference);
                        if (coin == null)
                        {
                            throw new NotSupportedException("This is impossible.");
                        }
                        roundRegistered.CoinsRegistered.Add(coin);
                        State.RemoveCoinFromWaitingList(coin);
                    }
                    roundRegistered.ActiveOutputAddress = activeAddress;
                    roundRegistered.ChangeOutputAddress = changeAddress;
                    roundRegistered.UnblindedSignature  = unblindedSignature;
                    roundRegistered.AliceClient         = aliceClient;
                }
            }
            catch (Exception ex)
            {
                Logger.LogError <CcjClient>(ex);
            }
        }
Exemplo n.º 20
0
 public override string GetKeyName()
 {
     return(KeyManager.GetMappedRandomKeyName(myRandomKeyIdentifier));
 }
Exemplo n.º 21
0
 public Authenticator(KeyManager keys)
 {
     Keys = keys;
 }
Exemplo n.º 22
0
        public MainForm()
        {
            InitializeComponent();
            entSpawn = new EntitySpawner();

            hitby = new DefaultValueDictionary <Entity, bool>(false);

            double border = 40;

            Particle boxC  = (Particle)(new Vector <double>((double)ClientRectangle.Width / 2, (double)ClientRectangle.Height / 2));
            Particle boxR  = (Particle)(new Vector <double>((double)ClientRectangle.Width / 2 + border, (double)ClientRectangle.Height / 2 + border));
            Box      bgbox = new Box(boxR);

            EntityClass bgClass = new EntityClass("Background");

            bg = new Entity(0, boxC, bgbox, new GraphicsStyle(Brushes.Black), bgClass);

            bsm = new BulletStyleManager();
            InitializeBulletStyles();

            keyMan = new KeyManager();

            InitializeKeyManager();

            int vx = 1, vx2 = 2;
            int vy = 2, vy2 = 4;

            Drawable mchar = DrawableFactory.MakeCircle(8, new GraphicsStyle(Brushes.Orange, Pens.Red));

            game = new Game(new MainChar(mchar, bsm["MainChar"], ClientRectangle.Width / 2, ClientRectangle.Height - 20, 40));
            InitializePhysicsManager(game.PhysicsManager);
            InitializeRenderManager(game.RenderManager);

            Particle p1 = new Particle(x => vx * x, y => vy * y);
            Particle p2 = new Particle(Utils.MakeClosure <double, double, double>(ClientRectangle.Width, (w, x) => w - vx2 * x), y => vy2 * y);

            Particle q = new Particle(t => 7 * t + 10 * Utils.FastCos(t), t => 3 * t + 10 * Utils.FastSin(t));

            Ellipse entEl = new Ellipse(7);

            o1 = entEl.MakeDrawable(new GraphicsStyle(Brushes.Green));

            double FULL    = 2 * Math.PI;
            double cd      = 1;
            int    perCirc = 12;
            int    offsets = 6;

            BulletEmission[] bEms = new BulletEmission[offsets], bEms2 = new BulletEmission[offsets];
            double           DOWN = Math.PI / 2;

            // Makes the spiral pattern with bullets of shape o2
            Trajectory[][] arrs = new Trajectory[offsets][];
            for (int i = 0; i < offsets; i++)
            {
                arrs[i] = new Trajectory[perCirc];
            }
            for (int i = 0; i < perCirc; i++)
            {
                for (int j = 0; j < offsets; j++)
                {
                    arrs[j][i] = TrajectoryFactory.AngleMagVel((i * offsets + j) * (FULL / offsets / perCirc) + DOWN, 10);
                }
            }
            for (int i = 0; i < offsets; i++)
            {
                bEms[i] = new BulletEmission(cd, 0, arrs[i], bsm["OrangeRed_5"]);
            }
            // Same as above, but we're gonna change the shape
            for (int i = 0; i < offsets; i++)
            {
                arrs[i] = new Trajectory[perCirc];
            }
            for (int i = 0; i < perCirc; i++)
            {
                for (int j = 0; j < offsets; j++)
                {
                    arrs[j][i] = TrajectoryFactory.AngleMagVel((i * offsets + j) * (FULL / offsets / perCirc) + DOWN, 10);
                }
            }
            for (int i = 0; i < offsets; i++)
            {
                bEms2[i] = new BulletEmission(cd, 0, arrs[i], bsm["Azure_5"]);
            }
            // Same as above, but we're gonna change the shape again and the path
            BulletEmission[] bEms3 = new BulletEmission[offsets];
            for (int i = 0; i < offsets; i++)
            {
                arrs[i] = new Trajectory[perCirc];
            }
            for (int i = 0; i < perCirc; i++)
            {
                for (int j = 0; j < offsets; j++)
                {
                    arrs[j][i] = TrajectoryFactory.SpinningLinearAMVel((i * offsets + j) * (FULL / offsets / perCirc) + DOWN, 7 /*3*/, 0.5, 20);
                }
            }
            for (int i = 0; i < offsets; i++)
            {
                bEms3[i] = new BulletEmission(cd, 0, arrs[i], bsm["HotPink_5"]);
            }

            EntityClass enemyBullet = new EntityClass("EnemyBullet", "Bullet");
            EntityClass enemy       = new EntityClass("Enemy", "Character");

            BulletEmitter em  = new BulletEmitter(new BulletPattern(bEms, enemyBullet));
            BulletEmitter em2 = new BulletEmitter(new BulletPattern(bEms2, enemyBullet));
            BulletEmitter em3 = new BulletEmitter(new BulletPattern(bEms3, enemyBullet));

            entSpawn.MakeType("RedSpiral", null, o1, entEl, enemy, em);

            e  = entSpawn.Build("RedSpiral", 0, p1);
            e2 = entSpawn.Build("RedSpiral", 0, p2);

            Particle p3 = new Particle(x => 0.5 * x + 500, y => 3 * y);
            Entity   e3 = entSpawn.Build("RedSpiral", 0, p3);

            Particle p4 = new Particle(x => - 0.25 * x + 300, y => 3.5 * y);
            Entity   e4 = entSpawn.Build("RedSpiral", 0, p4);

            Particle p5 = new Particle(x => - 0.4 * x + 800, y => 2 * y);
            Entity   e5 = entSpawn.Build("RedSpiral", 0, p5);


            game += bg;
            game  = game + e + e2 + e3 + e4 + e5;

            entSpawn["WhiteSpiral"] = entSpawn["RedSpiral"].ChangeEmitter(em2, true);
            entSpawn["PinkWaves"]   = entSpawn["RedSpiral"].ChangeEmitter(em3, true);
            //entSpawn.MakeType("WhiteSpinningSpiral",null, o1, entEl, enemy, em2);

            Entity e6 = entSpawn.Build("WhiteSpiral", 0, q);

            game += e6;

            Particle r  = new Particle(Utils.MakeClosure <double, double, double>((double)ClientRectangle.Width / 3, (w, t) => w + 3 * t), t => 5 * t);
            Entity   e7 = entSpawn.Build("PinkWaves", 0, r);

            game += e7;
            game.ResetTime();
            BufferedGraphicsContext c = BufferedGraphicsManager.Current;

            buff = c.Allocate(CreateGraphics(), ClientRectangle);
        }
            internal override PropagatorResult Merge(KeyManager keyManager, PropagatorResult other)
            {
                var otherKey = other as KeyValue;
                if (null == otherKey)
                {
                    EntityUtil.InternalError(EntityUtil.InternalErrorCode.UpdatePipelineResultRequestInvalid, 0, "KeyValue.Merge");
                }

                // Determine which key (this or otherKey) is first in the chain. Principal keys take
                // precedence over dependent keys and entities take precedence over relationships.
                if (Identifier != otherKey.Identifier)
                {
                    // Find principal (if any)
                    if (keyManager.GetPrincipals(otherKey.Identifier).Contains(Identifier))
                    {
                        return ReplicateResultWithNewNext(otherKey);
                    }
                    else
                    {
                        return otherKey.ReplicateResultWithNewNext(this);
                    }
                }
                else
                {
                    // Entity takes precedence of relationship
                    if (null == m_stateEntry
                        || m_stateEntry.IsRelationship)
                    {
                        return otherKey.ReplicateResultWithNewNext(this);
                    }
                    else
                    {
                        return ReplicateResultWithNewNext(otherKey);
                    }
                }
            }
Exemplo n.º 24
0
 private void OnKeyF(KeyManager km, Keys key, bool repeat)
 {
     DisplayFrameRate = !DisplayFrameRate;
 }
        public ConfirmRecoveryWordsViewModel(List <RecoveryWordViewModel> mnemonicWords, KeyManager keyManager)
        {
            var confirmationWordsSourceList = new SourceList <RecoveryWordViewModel>();

            _isSkipEnable = Services.WalletManager.Network != Network.Main || System.Diagnostics.Debugger.IsAttached;

            var nextCommandCanExecute =
                confirmationWordsSourceList
                .Connect()
                .ObserveOn(RxApp.MainThreadScheduler)
                .WhenValueChanged(x => x.IsConfirmed)
                .Select(_ => confirmationWordsSourceList.Items.All(x => x.IsConfirmed));

            EnableBack = true;

            NextCommand = ReactiveCommand.Create(() => OnNext(keyManager), nextCommandCanExecute);

            if (_isSkipEnable)
            {
                SkipCommand = ReactiveCommand.Create(() => NextCommand.Execute(null));
            }

            CancelCommand = ReactiveCommand.Create(OnCancel);

            confirmationWordsSourceList
            .Connect()
            .ObserveOn(RxApp.MainThreadScheduler)
            .OnItemAdded(x => x.Reset())
            .Sort(SortExpressionComparer <RecoveryWordViewModel> .Ascending(x => x.Index))
            .Bind(out _confirmationWords)
            .Subscribe();

            // Select random words to confirm.
            confirmationWordsSourceList.AddRange(mnemonicWords.OrderBy(_ => new Random().NextDouble()).Take(3));
        }
Exemplo n.º 26
0
 private void OnKeyP(KeyManager km, Keys key, bool repeat)
 {
     game.TogglePause();
 }
Exemplo n.º 27
0
        public LoadWalletViewModel(WalletManagerViewModel owner, LoadWalletType loadWalletType)
            : base(loadWalletType == LoadWalletType.Password ? "Test Password" : (loadWalletType == LoadWalletType.Desktop ? "Load Wallet" : "Hardware Wallet"))
        {
            Global = Locator.Current.GetService <Global>();

            Owner          = owner;
            Password       = "";
            LoadWalletType = loadWalletType;
            Wallets        = new ObservableCollection <LoadWalletEntry>();
            IsHwWalletSearchTextVisible = false;

            this.WhenAnyValue(x => x.SelectedWallet)
            .Subscribe(_ => TrySetWalletStates());

            this.WhenAnyValue(x => x.IsWalletOpened)
            .Subscribe(_ => TrySetWalletStates());

            this.WhenAnyValue(x => x.IsBusy)
            .Subscribe(_ => TrySetWalletStates());

            LoadCommand           = ReactiveCommand.CreateFromTask(async() => await LoadWalletAsync(), this.WhenAnyValue(x => x.CanLoadWallet));
            TestPasswordCommand   = ReactiveCommand.CreateFromTask(async() => await LoadKeyManagerAsync(requirePassword: true, isHardwareWallet: false), this.WhenAnyValue(x => x.CanTestPassword));
            OpenFolderCommand     = ReactiveCommand.Create(OpenWalletsFolder);
            ImportColdcardCommand = ReactiveCommand.CreateFromTask(async() =>
            {
                var ofd = new OpenFileDialog
                {
                    AllowMultiple = false,
                    Title         = "Import Coldcard"
                };

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    ofd.Directory = Path.Combine("/media", Environment.UserName);
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    ofd.Directory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                }

                var window   = (Application.Current.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime).MainWindow;
                var selected = await ofd.ShowAsync(window, fallBack: true);
                if (selected != null && selected.Any())
                {
                    var path       = selected.First();
                    var jsonString = await File.ReadAllTextAsync(path);
                    var json       = JObject.Parse(jsonString);
                    var xpubString = json["ExtPubKey"].ToString();
                    var mfpString  = json["MasterFingerprint"].ToString();

                    // https://github.com/zkSNACKs/WalletWasabi/pull/1663#issuecomment-508073066
                    // Coldcard 2.1.0 improperly implemented Wasabi skeleton fingerprint at first, so we must reverse byte order.
                    // The solution was to add a ColdCardFirmwareVersion json field from 2.1.1 and correct the one generated by 2.1.0.
                    var coldCardVersionString = json["ColdCardFirmwareVersion"]?.ToString();
                    var reverseByteOrder      = false;
                    if (coldCardVersionString is null)
                    {
                        reverseByteOrder = true;
                    }
                    else
                    {
                        Version coldCardVersion = new Version(coldCardVersionString);

                        if (coldCardVersion == new Version("2.1.0"))                         // Should never happen though.
                        {
                            reverseByteOrder = true;
                        }
                    }

                    var bytes         = ByteHelpers.FromHex(Guard.NotNullOrEmptyOrWhitespace(nameof(mfpString), mfpString, trim: true));
                    HDFingerprint mfp = reverseByteOrder ? new HDFingerprint(bytes.Reverse().ToArray()) : new HDFingerprint(bytes);

                    ExtPubKey extPubKey = NBitcoinHelpers.BetterParseExtPubKey(xpubString);

                    Logger.LogInfo("Creating a new wallet file.");
                    var walletName     = Global.GetNextHardwareWalletName(customPrefix: "Coldcard");
                    var walletFullPath = Global.GetWalletFullPath(walletName);
                    KeyManager.CreateNewHardwareWalletWatchOnly(mfp, extPubKey, walletFullPath);
                    owner.SelectLoadWallet();
                }
            });

            EnumerateHardwareWalletsCommand = ReactiveCommand.CreateFromTask(async() => await EnumerateHardwareWalletsAsync());

            OpenBrowserCommand = ReactiveCommand.CreateFromTask <string>(IoHelpers.OpenBrowserAsync);

            Observable
            .Merge(OpenBrowserCommand.ThrownExceptions)
            .Merge(LoadCommand.ThrownExceptions)
            .Merge(TestPasswordCommand.ThrownExceptions)
            .Merge(OpenFolderCommand.ThrownExceptions)
            .Merge(ImportColdcardCommand.ThrownExceptions)
            .Merge(EnumerateHardwareWalletsCommand.ThrownExceptions)
            .ObserveOn(RxApp.TaskpoolScheduler)
            .Subscribe(ex =>
            {
                NotificationHelpers.Error(ex.ToTypeMessageString());
                Logger.LogError(ex);
            });

            SetLoadButtonText();
        }
Exemplo n.º 28
0
        //chooseServerAlias { keyType = EC_EC }
        //getClientAliases
        //chooseServerAlias { keyType = RSA }
        //getClientAliases
        //chooseServerAlias { keyType = RSA }
        //getClientAliases
        //chooseServerAlias { keyType = RSA }
        //getClientAliases
        //chooseServerAlias { keyType = RSA }
        //getClientAliases


        public static KeyManager[] WindowsMYKeyManagers()
        {
            Console.WriteLine("enter WindowsMYKeyManagers");
            var KeyManagers = new KeyManager[0];


            try
            {
                var xFileInputStream = default(FileInputStream);


                var xKeyStore = default(KeyStore);
                // certmgr.msc
                var xKeyStoreDefaultType = "Windows-MY";

                try
                {
                    Console.WriteLine(new { xKeyStoreDefaultType });
                    xKeyStore = KeyStore.getInstance(xKeyStoreDefaultType);
                }
                catch
                {
                    xKeyStoreDefaultType = java.security.KeyStore.getDefaultType();
                    // http://www.coderanch.com/t/377172/java/java/cacerts-JAVA-HOME-jre-lib
                    // /usr/lib/jvm/default-java/jre/lib/security/cacerts

                    Console.WriteLine(new { xKeyStoreDefaultType });
                    xKeyStore = KeyStore.getInstance(xKeyStoreDefaultType);

                    var fa = new FileInfo(typeof(Program).Assembly.Location);
                    var keystorepath = fa.Directory.FullName + "/domain.keystore";

                    try
                    {
                        xFileInputStream = new FileInputStream(keystorepath);
                    }
                    catch { throw; }
                }

                Console.WriteLine("WindowsMYKeyManagers " + new { xKeyStore });

                xKeyStore.load(xFileInputStream, null);

                KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");

                Console.WriteLine("WindowsMYKeyManagers " + new { kmf });


                kmf.init(xKeyStore, null);

                KeyManagers = kmf.getKeyManagers();

                Console.WriteLine("WindowsMYKeyManagers " + new { KeyManagers.Length });


                //{ xKeyStoreDefaultType = Windows-MY }
                //WindowsMYKeyManagers { xKeyStore = java.security.KeyStore@ac4d3b }
                //WindowsMYKeyManagers { kmf = javax.net.ssl.KeyManagerFactory@1c7d56b }
                //WindowsMYKeyManagers { KeyManagers = [Ljavax.net.ssl.KeyManager;@f77511 }

                // http://docs.oracle.com/javase/7/docs/api/javax/net/ssl/KeyManager.html
                // http://stackoverflow.com/questions/5292074/how-to-specify-outbound-certificate-alias-for-https-calls
                // http://www.angelfire.com/or/abhilash/site/articles/jsse-km/customKeyManager.html

                foreach (var KeyManager in KeyManagers)
                {
                    var xX509KeyManager = KeyManager as X509KeyManager;
                    if (xX509KeyManager != null)
                    {
                        Console.WriteLine("WindowsMYKeyManagers " + new { xX509KeyManager });

                    }
                }

                //WindowsMYKeyManagers { Length = 1 }
                //WindowsMYKeyManagers { xX509KeyManager = sun.security.ssl.SunX509KeyManagerImpl@ea3932 }


                //KeyStore ks = KeyStore.getInstance("JKS");
                //// initialize KeyStore object using keystore name
                //ks.load(new FileInputStream(keyFile), null);
                //kmf.init(ks, keystorePasswd.toCharArray());
                //ret = kmf.getKeyManagers();

                // chooseServerAlias { keyType = RSA, StackTrace = <__StackTrace> }

                //java.security.KeyStore ks = null;

                //KeyManagerFactory kmf

                // http://stackoverflow.com/questions/15076820/java-sslhandshakeexception-no-cipher-suites-in-common
                // http://stackoverflow.com/questions/7535154/chrome-closing-connection-on-handshake-with-java-ssl-server
            }
            catch
            {
                throw;

            }

            return KeyManagers;
        }
Exemplo n.º 29
0
 public Wallet(string dataDir, Network network, string filePath) : this(dataDir, network, KeyManager.FromFile(filePath))
 {
 }
Exemplo n.º 30
0
 public IosKeyManagerService()
 {
     key = new KeyManager();
 }
Exemplo n.º 31
0
 public override void HandleInput(InputHelper helper, KeyManager manager)
 {
     overlay.update(helper);
 }
Exemplo n.º 32
0
        public MainPage()
        {
           
            this.InitializeComponent();
           
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;
            this.navigationHelper.SaveState += navigationHelper_SaveState;
            

            this.SizeChanged+=MainPage_SizeChanged;
            this.NavigationCacheMode = NavigationCacheMode.Enabled;
            
            

            VisualStateManager.GoToState(this,VisualStateTimeline.MultiTimeline,true);
            
            timelineState = TimelineState.MultiTimeline;
            
            Application.Current.Suspending += async(s, e) =>
            {
                var deferral = e.SuspendingOperation.GetDeferral();
                //TODO: アプリケーションの状態を保存してバックグラウンドの動作があれば停止します
               
                 await viewModel.SaveTwitterDataAsync();
                deferral.Complete();
                
            };
            Application.Current.Resuming += (s,e) =>
            {
            };
           
            textKeyManager = new TweetKeyManager(textPost,KeyBindings.PostTextKeyBinder);
            textKeyManager.CommandList.Add("PostTweet",(bind)=>{
                viewModel.PostStatusCommand.Execute(null);
            });

            textBottomKeyManager = new TweetKeyManager(textPostBottom, KeyBindings.PostTextKeyBinder);
            textBottomKeyManager.CommandList.Add("PostTweet", (bind) =>
            {
                viewModel.PostStatusCommand.Execute(null);
            });

            pageKeyManager=new KeyManager(this,KeyBindings.PageTextKeyBinder);
            pageKeyManager.CommandList.Add("UpTab", (bind) =>
            {
                viewModel.NextTabCommand.Execute(null);
                ChangeTimelineSize(new Size(Window.Current.Bounds.Width,Window.Current.Bounds.Height));
                
            });
            pageKeyManager.CommandList.Add("DownTab", (bind) =>
            {
                viewModel.PrevTabCommand.Execute(null);
                ChangeTimelineSize(new Size(Window.Current.Bounds.Width, Window.Current.Bounds.Height));
                
            });
            MessengerRegister();


            mediaElementNotification = new MediaElement();
            mediaElementNotification.AutoPlay = false;
            var uri = new Uri("ms-appx:///Assets/Sound/notification.wav");
            var file = Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri).AsTask<StorageFile>().Result;
            var stream = file.OpenAsync(Windows.Storage.FileAccessMode.Read).AsTask<IRandomAccessStream>().Result;
            mediaElementNotification.SetSource(stream,file.ContentType);
           
            
        }
Exemplo n.º 33
0
 /// <summary>
 /// Method uses AES to decrypt a ciphertext bypte array using the path to a DPAPI protected key file and initialization vector
 /// </summary>
 /// <param name="cipherText">Ciphertext bytes to decrypt</param>
 /// <param name="keyFile">File path to the DPAPI protected key file</param>
 /// <param name="dpapiProtectionScope">DPAPI protection scope used to protect the key file</param>
 /// <param name="iv">Plaintext string</param>
 /// <returns></returns>
 public static string Decrypt(byte[] cipherText, string keyFile, DataProtectionScope dpapiProtectionScope, byte[] iv)
 {
     //Get the encryption key from the protected key store
     byte[] key = KeyManager.ReadKey(keyFile, dpapiProtectionScope);
     return(Decrypt(cipherText, key, iv));
 }
Exemplo n.º 34
0
 void mnuKeyManager_Click(Object sender, System.EventArgs e)
 {
     KeyManager keyManagerForm = new KeyManager(skrSecretKeyRing, pkrPublicKeyRing);
     keyManagerForm.Show();
 }
Exemplo n.º 35
0
 private void OnKeyT(KeyManager km, Keys key, bool repeat)
 {
     DisplayTime = !DisplayTime;
 }
Exemplo n.º 36
0
        internal static async Task RunAsync(string walletName, bool mixAll, bool keepMixAlive)
        {
            try
            {
                Logger.LogStarting("Wasabi Daemon");

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

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

                await Global.InitializeNoWalletAsync();

                await Global.InitializeWalletServiceAsync(keyManager);

                await TryQueueCoinsToMixAsync(mixAll, password);

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

                    await Task.Delay(3000);

                    if (Global.KillRequested)
                    {
                        break;
                    }

                    bool anyCoinsQueued = Global.ChaumianClient.State.AnyCoinsQueued();

                    if (!anyCoinsQueued && keepMixAlive)                     // If no coins queued and mixing is asked to be kept alive then try to queue coins.
                    {
                        await TryQueueCoinsToMixAsync(mixAll, password);
                    }

                    if (Global.KillRequested)
                    {
                        break;
                    }

                    mixing = anyCoinsQueued || keepMixAlive;
                } while (mixing);

                await Global.ChaumianClient.DequeueAllCoinsFromMixAsync("Stopping Wasabi.");
            }
            finally
            {
                Logger.LogInfo($"Wasabi Daemon stopped gracefully.", Logger.InstanceGuid.ToString());
            }
        }
Exemplo n.º 37
0
 public void DoesNotReturnPrivateKeysForOtherApps()
 {
     var keys = new KeyManager("keytest", "keytestenv");
     Assert.IsNull(keys["otherapp"].Priv);
     Assert.IsTrue(string.IsNullOrWhiteSpace(keys["otherapp"].PrivPem));
 }
Exemplo n.º 38
0
 // Start is called before the first frame update
 void Start()
 {
     keyManager       = GetComponent <KeyManager>();
     playerController = GameObject.FindGameObjectWithTag("Player").GetComponent <PlayerController>();
 }
Exemplo n.º 39
0
        public async Task SendTestsAsync()
        {
            (string password, IRPCClient rpc, Network network, _, ServiceConfiguration serviceConfiguration, BitcoinStore bitcoinStore, Backend.Global global) = await Common.InitializeTestEnvironmentAsync(RegTestFixture, 1);

            bitcoinStore.IndexStore.NewFilter += Common.Wallet_NewFilterProcessed;
            // Create the services.
            // 1. Create connection service.
            var nodes = new NodesGroup(global.Config.Network, requirements: Constants.NodeRequirements);

            nodes.ConnectedNodes.Add(await RegTestFixture.BackendRegTestNode.CreateNewP2pNodeAsync());

            // 2. Create mempool service.

            Node node = await RegTestFixture.BackendRegTestNode.CreateNewP2pNodeAsync();

            node.Behaviors.Add(bitcoinStore.CreateUntrustedP2pBehavior());

            // 3. Create wasabi synchronizer service.
            var httpClientFactory = new HttpClientFactory(torEndPoint: null, backendUriGetter: () => new Uri(RegTestFixture.BackendEndPoint));
            var synchronizer      = new WasabiSynchronizer(rpc.Network, bitcoinStore, httpClientFactory);

            // 4. Create key manager service.
            var keyManager = KeyManager.CreateNew(out _, password);

            // 5. Create wallet service.
            var workDir = Helpers.Common.GetWorkDir();

            CachedBlockProvider blockProvider = new(
                new P2pBlockProvider(nodes, null, httpClientFactory, serviceConfiguration, network),
                bitcoinStore.BlockRepository);

            var walletManager = new WalletManager(network, workDir, new WalletDirectories(network, workDir));

            walletManager.RegisterServices(bitcoinStore, synchronizer, serviceConfiguration, synchronizer, blockProvider);

            // Get some money, make it confirm.
            var key  = keyManager.GetNextReceiveKey("foo label", out _);
            var key2 = keyManager.GetNextReceiveKey("foo label", out _);
            var txId = await rpc.SendToAddressAsync(key.GetP2wpkhAddress(network), Money.Coins(1m));

            Assert.NotNull(txId);
            await rpc.GenerateAsync(1);

            var txId2 = await rpc.SendToAddressAsync(key2.GetP2wpkhAddress(network), Money.Coins(1m));

            Assert.NotNull(txId2);
            await rpc.GenerateAsync(1);

            try
            {
                Interlocked.Exchange(ref Common.FiltersProcessedByWalletCount, 0);
                nodes.Connect();                                                                              // Start connection service.
                node.VersionHandshake();                                                                      // Start mempool service.
                synchronizer.Start(requestInterval: TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(5), 10000); // Start wasabi synchronizer service.

                // Wait until the filter our previous transaction is present.
                var blockCount = await rpc.GetBlockCountAsync();

                await Common.WaitForFiltersToBeProcessedAsync(TimeSpan.FromSeconds(120), blockCount);

                var wallet = await walletManager.AddAndStartWalletAsync(keyManager);

                var broadcaster = new TransactionBroadcaster(network, bitcoinStore, httpClientFactory, walletManager);
                broadcaster.Initialize(nodes, rpc);

                var waitCount = 0;
                while (wallet.Coins.Sum(x => x.Amount) == Money.Zero)
                {
                    await Task.Delay(1000);

                    waitCount++;
                    if (waitCount >= 21)
                    {
                        Logger.LogInfo("Funding transaction to the wallet did not arrive.");
                        return;                         // Very rarely this test fails. I have no clue why. Probably because all these RegTests are interconnected, anyway let's not bother the CI with it.
                    }
                }

                var scp  = new Key().ScriptPubKey;
                var res2 = wallet.BuildTransaction(password, new PaymentIntent(scp, Money.Coins(0.05m), label: "foo"), FeeStrategy.CreateFromConfirmationTarget(5), allowUnconfirmed: false);

                Assert.NotNull(res2.Transaction);
                Assert.Single(res2.OuterWalletOutputs);
                Assert.Equal(scp, res2.OuterWalletOutputs.Single().ScriptPubKey);
                Assert.Single(res2.InnerWalletOutputs);
                Assert.True(res2.Fee > Money.Satoshis(2 * 100));                 // since there is a sanity check of 2sat/vb in the server
                Assert.InRange(res2.FeePercentOfSent, 0, 1);
                Assert.Single(res2.SpentCoins);
                var spentCoin = Assert.Single(res2.SpentCoins);
                Assert.Contains(new[] { key.P2wpkhScript, key2.P2wpkhScript }, x => x == spentCoin.ScriptPubKey);
                Assert.Equal(Money.Coins(1m), res2.SpentCoins.Single().Amount);
                Assert.False(res2.SpendsUnconfirmed);

                await broadcaster.SendTransactionAsync(res2.Transaction);

                Assert.Contains(res2.InnerWalletOutputs.Single(), wallet.Coins);

                #region Basic

                Script receive      = keyManager.GetNextReceiveKey("Basic", out _).P2wpkhScript;
                Money  amountToSend = wallet.Coins.Where(x => x.IsAvailable()).Sum(x => x.Amount) / 2;
                var    res          = wallet.BuildTransaction(password, new PaymentIntent(receive, amountToSend, label: "foo"), FeeStrategy.SevenDaysConfirmationTargetStrategy, allowUnconfirmed: true);

                foreach (SmartCoin coin in res.SpentCoins)
                {
                    Assert.False(coin.CoinJoinInProgress);
                    Assert.True(coin.Confirmed);
                    Assert.Null(coin.SpenderTransaction);
                    Assert.False(coin.IsSpent());
                }

                Assert.Equal(2, res.InnerWalletOutputs.Count());
                Assert.Empty(res.OuterWalletOutputs);
                var activeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey == receive);
                var changeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey != receive);

                Assert.Equal(receive, activeOutput.ScriptPubKey);
                Assert.Equal(amountToSend, activeOutput.Amount);
                if (res.SpentCoins.Sum(x => x.Amount) - activeOutput.Amount == res.Fee)                 // this happens when change is too small
                {
                    Assert.Contains(res.Transaction.Transaction.Outputs, x => x.Value == activeOutput.Amount);
                    Logger.LogInfo($"Change Output: {changeOutput.Amount.ToString(false, true)} {changeOutput.ScriptPubKey.GetDestinationAddress(network)}");
                }
                Logger.LogInfo($"{nameof(res.Fee)}: {res.Fee}");
                Logger.LogInfo($"{nameof(res.FeePercentOfSent)}: {res.FeePercentOfSent} %");
                Logger.LogInfo($"{nameof(res.SpendsUnconfirmed)}: {res.SpendsUnconfirmed}");
                Logger.LogInfo($"Active Output: {activeOutput.Amount.ToString(false, true)} {activeOutput.ScriptPubKey.GetDestinationAddress(network)}");
                Logger.LogInfo($"TxId: {res.Transaction.GetHash()}");

                var foundReceive = false;
                Assert.InRange(res.Transaction.Transaction.Outputs.Count, 1, 2);
                foreach (var output in res.Transaction.Transaction.Outputs)
                {
                    if (output.ScriptPubKey == receive)
                    {
                        foundReceive = true;
                        Assert.Equal(amountToSend, output.Value);
                    }
                }
                Assert.True(foundReceive);

                await broadcaster.SendTransactionAsync(res.Transaction);

                #endregion Basic

                #region SubtractFeeFromAmount

                receive      = keyManager.GetNextReceiveKey("SubtractFeeFromAmount", out _).P2wpkhScript;
                amountToSend = wallet.Coins.Where(x => x.IsAvailable()).Sum(x => x.Amount) / 3;
                res          = wallet.BuildTransaction(password, new PaymentIntent(receive, amountToSend, subtractFee: true, label: "foo"), FeeStrategy.SevenDaysConfirmationTargetStrategy, allowUnconfirmed: true);

                Assert.Equal(2, res.InnerWalletOutputs.Count());
                Assert.Empty(res.OuterWalletOutputs);
                activeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey == receive);
                changeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey != receive);

                Assert.Equal(receive, activeOutput.ScriptPubKey);
                Assert.Equal(amountToSend - res.Fee, activeOutput.Amount);
                Assert.Contains(res.Transaction.Transaction.Outputs, x => x.Value == changeOutput.Amount);
                Logger.LogInfo($"{nameof(res.Fee)}: {res.Fee}");
                Logger.LogInfo($"{nameof(res.FeePercentOfSent)}: {res.FeePercentOfSent} %");
                Logger.LogInfo($"{nameof(res.SpendsUnconfirmed)}: {res.SpendsUnconfirmed}");
                Logger.LogInfo($"Active Output: {activeOutput.Amount.ToString(false, true)} {activeOutput.ScriptPubKey.GetDestinationAddress(network)}");
                Logger.LogInfo($"Change Output: {changeOutput.Amount.ToString(false, true)} {changeOutput.ScriptPubKey.GetDestinationAddress(network)}");
                Logger.LogInfo($"TxId: {res.Transaction.GetHash()}");

                foundReceive = false;
                Assert.InRange(res.Transaction.Transaction.Outputs.Count, 1, 2);
                foreach (var output in res.Transaction.Transaction.Outputs)
                {
                    if (output.ScriptPubKey == receive)
                    {
                        foundReceive = true;
                        Assert.Equal(amountToSend - res.Fee, output.Value);
                    }
                }
                Assert.True(foundReceive);

                #endregion SubtractFeeFromAmount

                #region LowFee

                res = wallet.BuildTransaction(password, new PaymentIntent(receive, amountToSend, label: "foo"), FeeStrategy.SevenDaysConfirmationTargetStrategy, allowUnconfirmed: true);

                Assert.Equal(2, res.InnerWalletOutputs.Count());
                Assert.Empty(res.OuterWalletOutputs);
                activeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey == receive);
                changeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey != receive);

                Assert.Equal(receive, activeOutput.ScriptPubKey);
                Assert.Equal(amountToSend, activeOutput.Amount);
                Assert.Contains(res.Transaction.Transaction.Outputs, x => x.Value == changeOutput.Amount);
                Logger.LogInfo($"{nameof(res.Fee)}: {res.Fee}");
                Logger.LogInfo($"{nameof(res.FeePercentOfSent)}: {res.FeePercentOfSent} %");
                Logger.LogInfo($"{nameof(res.SpendsUnconfirmed)}: {res.SpendsUnconfirmed}");
                Logger.LogInfo($"Active Output: {activeOutput.Amount.ToString(false, true)} {activeOutput.ScriptPubKey.GetDestinationAddress(network)}");
                Logger.LogInfo($"Change Output: {changeOutput.Amount.ToString(false, true)} {changeOutput.ScriptPubKey.GetDestinationAddress(network)}");
                Logger.LogInfo($"TxId: {res.Transaction.GetHash()}");

                foundReceive = false;
                Assert.InRange(res.Transaction.Transaction.Outputs.Count, 1, 2);
                foreach (var output in res.Transaction.Transaction.Outputs)
                {
                    if (output.ScriptPubKey == receive)
                    {
                        foundReceive = true;
                        Assert.Equal(amountToSend, output.Value);
                    }
                }
                Assert.True(foundReceive);

                #endregion LowFee

                #region MediumFee

                res = wallet.BuildTransaction(password, new PaymentIntent(receive, amountToSend, label: "foo"), FeeStrategy.OneDayConfirmationTargetStrategy, allowUnconfirmed: true);

                Assert.Equal(2, res.InnerWalletOutputs.Count());
                Assert.Empty(res.OuterWalletOutputs);
                activeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey == receive);
                changeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey != receive);

                Assert.Equal(receive, activeOutput.ScriptPubKey);
                Assert.Equal(amountToSend, activeOutput.Amount);
                Assert.Contains(res.Transaction.Transaction.Outputs, x => x.Value == changeOutput.Amount);
                Logger.LogInfo($"{nameof(res.Fee)}: {res.Fee}");
                Logger.LogInfo($"{nameof(res.FeePercentOfSent)}: {res.FeePercentOfSent} %");
                Logger.LogInfo($"{nameof(res.SpendsUnconfirmed)}: {res.SpendsUnconfirmed}");
                Logger.LogInfo($"Active Output: {activeOutput.Amount.ToString(false, true)} {activeOutput.ScriptPubKey.GetDestinationAddress(network)}");
                Logger.LogInfo($"Change Output: {changeOutput.Amount.ToString(false, true)} {changeOutput.ScriptPubKey.GetDestinationAddress(network)}");
                Logger.LogInfo($"TxId: {res.Transaction.GetHash()}");

                foundReceive = false;
                Assert.InRange(res.Transaction.Transaction.Outputs.Count, 1, 2);
                foreach (var output in res.Transaction.Transaction.Outputs)
                {
                    if (output.ScriptPubKey == receive)
                    {
                        foundReceive = true;
                        Assert.Equal(amountToSend, output.Value);
                    }
                }
                Assert.True(foundReceive);

                #endregion MediumFee

                #region HighFee

                res = wallet.BuildTransaction(password, new PaymentIntent(receive, amountToSend, label: "foo"), FeeStrategy.TwentyMinutesConfirmationTargetStrategy, allowUnconfirmed: true);

                Assert.Equal(2, res.InnerWalletOutputs.Count());
                Assert.Empty(res.OuterWalletOutputs);
                activeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey == receive);
                changeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey != receive);

                Assert.Equal(receive, activeOutput.ScriptPubKey);
                Assert.Equal(amountToSend, activeOutput.Amount);
                Assert.Contains(res.Transaction.Transaction.Outputs, x => x.Value == changeOutput.Amount);
                Logger.LogInfo($"{nameof(res.Fee)}: {res.Fee}");
                Logger.LogInfo($"{nameof(res.FeePercentOfSent)}: {res.FeePercentOfSent} %");
                Logger.LogInfo($"{nameof(res.SpendsUnconfirmed)}: {res.SpendsUnconfirmed}");
                Logger.LogInfo($"Active Output: {activeOutput.Amount.ToString(false, true)} {activeOutput.ScriptPubKey.GetDestinationAddress(network)}");
                Logger.LogInfo($"Change Output: {changeOutput.Amount.ToString(false, true)} {changeOutput.ScriptPubKey.GetDestinationAddress(network)}");
                Logger.LogInfo($"TxId: {res.Transaction.GetHash()}");

                foundReceive = false;
                Assert.InRange(res.Transaction.Transaction.Outputs.Count, 1, 2);
                foreach (var output in res.Transaction.Transaction.Outputs)
                {
                    if (output.ScriptPubKey == receive)
                    {
                        foundReceive = true;
                        Assert.Equal(amountToSend, output.Value);
                    }
                }
                Assert.True(foundReceive);

                Assert.InRange(res.Fee, Money.Zero, res.Fee);
                Assert.InRange(res.Fee, res.Fee, res.Fee);

                await broadcaster.SendTransactionAsync(res.Transaction);

                #endregion HighFee

                #region MaxAmount

                receive = keyManager.GetNextReceiveKey("MaxAmount", out _).P2wpkhScript;

                res = wallet.BuildTransaction(password, new PaymentIntent(receive, MoneyRequest.CreateAllRemaining(), "foo"), FeeStrategy.SevenDaysConfirmationTargetStrategy, allowUnconfirmed: true);

                Assert.Single(res.InnerWalletOutputs);
                Assert.Empty(res.OuterWalletOutputs);
                activeOutput = res.InnerWalletOutputs.Single();

                Assert.Equal(receive, activeOutput.ScriptPubKey);

                Assert.Single(res.Transaction.Transaction.Outputs);
                var maxBuiltTxOutput = res.Transaction.Transaction.Outputs.Single();
                Assert.Equal(receive, maxBuiltTxOutput.ScriptPubKey);
                Assert.Equal(wallet.Coins.Where(x => x.IsAvailable()).Sum(x => x.Amount) - res.Fee, maxBuiltTxOutput.Value);

                await broadcaster.SendTransactionAsync(res.Transaction);

                #endregion MaxAmount

                #region InputSelection

                receive = keyManager.GetNextReceiveKey("InputSelection", out _).P2wpkhScript;

                var inputCountBefore = res.SpentCoins.Count();

                res = wallet.BuildTransaction(password, new PaymentIntent(receive, MoneyRequest.CreateAllRemaining(), "foo"), FeeStrategy.SevenDaysConfirmationTargetStrategy,
                                              allowUnconfirmed: true,
                                              allowedInputs: wallet.Coins.Where(x => x.IsAvailable()).Select(x => x.OutPoint).Take(1));

                Assert.Single(res.InnerWalletOutputs);
                Assert.Empty(res.OuterWalletOutputs);
                activeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey == receive);

                Assert.True(inputCountBefore >= res.SpentCoins.Count());
                Assert.Equal(res.SpentCoins.Count(), res.Transaction.Transaction.Inputs.Count);

                Assert.Equal(receive, activeOutput.ScriptPubKey);
                Logger.LogInfo($"{nameof(res.Fee)}: {res.Fee}");
                Logger.LogInfo($"{nameof(res.FeePercentOfSent)}: {res.FeePercentOfSent} %");
                Logger.LogInfo($"{nameof(res.SpendsUnconfirmed)}: {res.SpendsUnconfirmed}");
                Logger.LogInfo($"Active Output: {activeOutput.Amount.ToString(false, true)} {activeOutput.ScriptPubKey.GetDestinationAddress(network)}");
                Logger.LogInfo($"TxId: {res.Transaction.GetHash()}");

                Assert.Single(res.Transaction.Transaction.Outputs);

                res = wallet.BuildTransaction(password, new PaymentIntent(receive, MoneyRequest.CreateAllRemaining(), "foo"), FeeStrategy.SevenDaysConfirmationTargetStrategy,
                                              allowUnconfirmed: true,
                                              allowedInputs: new[] { res.SpentCoins.Select(x => x.OutPoint).First() });

                Assert.Single(res.InnerWalletOutputs);
                Assert.Empty(res.OuterWalletOutputs);
                activeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey == receive);

                Assert.Single(res.Transaction.Transaction.Inputs);
                Assert.Single(res.Transaction.Transaction.Outputs);
                Assert.Single(res.SpentCoins);

                #endregion InputSelection

                #region Labeling

                Script receive2 = keyManager.GetNextReceiveKey("foo", out _).P2wpkhScript;
                res = wallet.BuildTransaction(password, new PaymentIntent(receive2, MoneyRequest.CreateAllRemaining(), "my label"), FeeStrategy.SevenDaysConfirmationTargetStrategy, allowUnconfirmed: true);

                Assert.Single(res.InnerWalletOutputs);
                Assert.Equal("foo, my label", res.InnerWalletOutputs.Single().HdPubKey.Label);

                amountToSend = wallet.Coins.Where(x => x.IsAvailable()).Sum(x => x.Amount) / 3;
                res          = wallet.BuildTransaction(
                    password,
                    new PaymentIntent(
                        new DestinationRequest(new Key(), amountToSend, label: "outgoing"),
                        new DestinationRequest(new Key(), amountToSend, label: "outgoing2")),
                    FeeStrategy.SevenDaysConfirmationTargetStrategy,
                    allowUnconfirmed: true);

                Assert.Single(res.InnerWalletOutputs);
                Assert.Equal(2, res.OuterWalletOutputs.Count());
                IEnumerable <string> change = res.InnerWalletOutputs.Single().HdPubKey.Label.Labels;
                Assert.Contains("outgoing", change);
                Assert.Contains("outgoing2", change);

                await broadcaster.SendTransactionAsync(res.Transaction);

                IEnumerable <SmartCoin> unconfirmedCoins      = wallet.Coins.Where(x => x.Height == Height.Mempool).ToArray();
                IEnumerable <string>    unconfirmedCoinLabels = unconfirmedCoins.SelectMany(x => x.HdPubKey.Label.Labels).ToArray();
                Assert.Contains("outgoing", unconfirmedCoinLabels);
                Assert.Contains("outgoing2", unconfirmedCoinLabels);
                IEnumerable <string> allKeyLabels = keyManager.GetKeys().SelectMany(x => x.Label.Labels);
                Assert.Contains("outgoing", allKeyLabels);
                Assert.Contains("outgoing2", allKeyLabels);

                Interlocked.Exchange(ref Common.FiltersProcessedByWalletCount, 0);
                await rpc.GenerateAsync(1);

                await Common.WaitForFiltersToBeProcessedAsync(TimeSpan.FromSeconds(120), 1);

                var bestHeight = new Height(bitcoinStore.SmartHeaderChain.TipHeight);
                IEnumerable <string> confirmedCoinLabels = wallet.Coins.Where(x => x.Height == bestHeight).SelectMany(x => x.HdPubKey.Label.Labels);
                Assert.Contains("outgoing", confirmedCoinLabels);
                Assert.Contains("outgoing2", confirmedCoinLabels);
                allKeyLabels = keyManager.GetKeys().SelectMany(x => x.Label.Labels);
                Assert.Contains("outgoing", allKeyLabels);
                Assert.Contains("outgoing2", allKeyLabels);

                #endregion Labeling

                #region AllowedInputsDisallowUnconfirmed

                inputCountBefore = res.SpentCoins.Count();

                receive = keyManager.GetNextReceiveKey("AllowedInputsDisallowUnconfirmed", out _).P2wpkhScript;

                var allowedInputs = wallet.Coins.Where(x => x.IsAvailable()).Select(x => x.OutPoint).Take(1);
                var toSend        = new PaymentIntent(receive, MoneyRequest.CreateAllRemaining(), "fizz");

                // covers:
                // disallow unconfirmed with allowed inputs
                res = wallet.BuildTransaction(password, toSend, FeeStrategy.TwentyMinutesConfirmationTargetStrategy, false, allowedInputs: allowedInputs);

                activeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey == receive);
                Assert.Single(res.InnerWalletOutputs);
                Assert.Empty(res.OuterWalletOutputs);

                Assert.Equal(receive, activeOutput.ScriptPubKey);
                Logger.LogDebug($"{nameof(res.Fee)}: {res.Fee}");
                Logger.LogDebug($"{nameof(res.FeePercentOfSent)}: {res.FeePercentOfSent} %");
                Logger.LogDebug($"{nameof(res.SpendsUnconfirmed)}: {res.SpendsUnconfirmed}");
                Logger.LogDebug($"Active Output: {activeOutput.Amount.ToString(false, true)} {activeOutput.ScriptPubKey.GetDestinationAddress(network)}");
                Logger.LogDebug($"TxId: {res.Transaction.GetHash()}");

                Assert.True(inputCountBefore >= res.SpentCoins.Count());
                Assert.False(res.SpendsUnconfirmed);

                Assert.Single(res.Transaction.Transaction.Inputs);
                Assert.Single(res.Transaction.Transaction.Outputs);
                Assert.Single(res.SpentCoins);

                Assert.True(inputCountBefore >= res.SpentCoins.Count());
                Assert.Equal(res.SpentCoins.Count(), res.Transaction.Transaction.Inputs.Count);

                #endregion AllowedInputsDisallowUnconfirmed

                #region CustomChange

                // covers:
                // customchange
                // feePc > 1
                var k1 = new Key();
                var k2 = new Key();
                res = wallet.BuildTransaction(
                    password,
                    new PaymentIntent(
                        new DestinationRequest(k1, MoneyRequest.CreateChange()),
                        new DestinationRequest(k2, Money.Coins(0.0003m), label: "outgoing")),
                    FeeStrategy.TwentyMinutesConfirmationTargetStrategy);

                Assert.Contains(k1.ScriptPubKey, res.OuterWalletOutputs.Select(x => x.ScriptPubKey));
                Assert.Contains(k2.ScriptPubKey, res.OuterWalletOutputs.Select(x => x.ScriptPubKey));

                #endregion CustomChange

                #region FeePcHigh

                res = wallet.BuildTransaction(
                    password,
                    new PaymentIntent(new Key(), Money.Coins(0.0003m), label: "outgoing"),
                    FeeStrategy.TwentyMinutesConfirmationTargetStrategy);

                Assert.True(res.FeePercentOfSent > 1);

                var newChangeK = keyManager.GenerateNewKey("foo", KeyState.Clean, isInternal: true);
                res = wallet.BuildTransaction(
                    password,
                    new PaymentIntent(
                        new DestinationRequest(newChangeK.P2wpkhScript, MoneyRequest.CreateChange(), "boo"),
                        new DestinationRequest(new Key(), Money.Coins(0.0003m), label: "outgoing")),
                    FeeStrategy.TwentyMinutesConfirmationTargetStrategy);

                Assert.True(res.FeePercentOfSent > 1);
                Assert.Single(res.OuterWalletOutputs);
                Assert.Single(res.InnerWalletOutputs);
                SmartCoin changeRes = res.InnerWalletOutputs.Single();
                Assert.Equal(newChangeK.P2wpkhScript, changeRes.ScriptPubKey);
                Assert.Equal(newChangeK.Label, changeRes.HdPubKey.Label);
                Assert.Equal(KeyState.Clean, newChangeK.KeyState);                 // Still clean, because the tx wasn't yet propagated.

                #endregion FeePcHigh
            }
            finally
            {
                bitcoinStore.IndexStore.NewFilter -= Common.Wallet_NewFilterProcessed;
                await walletManager.RemoveAndStopAllAsync(CancellationToken.None);

                // Dispose wasabi synchronizer service.
                if (synchronizer is { })
Exemplo n.º 40
0
        public static void Send
        (
            System.Net.Mail.MailAddress sender,
            System.Net.Mail.MailAddressCollection recipients,
            string subject,
            string body,
            System.Net.Mail.MailPriority priority,
            System.Net.Mail.AttachmentCollection attachments,
            System.Net.Mail.DeliveryNotificationOptions deliveryNotification
        )
        {
            System.Net.Mail.MailAddress oSender      = null;;
            System.Net.Mail.SmtpClient  oSmtpClient  = null;
            System.Net.Mail.MailMessage oMailMessage = null;

            try
            {
                // Mail Message Configuration
                oMailMessage = new System.Net.Mail.MailMessage();

                if (sender != null)
                {
                    oSender = sender;
                }
                else
                {
                    string strAddress     = KeyManager.GetValue("NoReplyAddress");
                    string strDisplayName = KeyManager.GetValue("NoReplyDisplayName");

                    if (string.IsNullOrEmpty(strDisplayName))
                    {
                        oSender =
                            new System.Net.Mail.MailAddress(strAddress, strAddress, System.Text.Encoding.UTF8);
                    }
                    else
                    {
                        oSender =
                            new System.Net.Mail.MailAddress(strAddress, strDisplayName, System.Text.Encoding.UTF8);
                    }
                }

                oMailMessage.From    = oSender;
                oMailMessage.Sender  = oSender;
                oMailMessage.ReplyTo = oSender;

                oMailMessage.To.Clear();
                oMailMessage.CC.Clear();
                oMailMessage.Bcc.Clear();
                oMailMessage.Attachments.Clear();

                if (recipients == null)
                {
                    System.Net.Mail.MailAddress oMailAddress = null;
                    string strAddress     = KeyManager.GetValue("SupportAddress");
                    string strDisplayName = KeyManager.GetValue("SupportDisplayName");

                    if (string.IsNullOrEmpty(strDisplayName))
                    {
                        oMailAddress =
                            new System.Net.Mail.MailAddress(strAddress, strAddress, System.Text.Encoding.UTF8);
                    }
                    else
                    {
                        oMailAddress =
                            new System.Net.Mail.MailAddress(strAddress, strDisplayName, System.Text.Encoding.UTF8);
                    }

                    oMailMessage.To.Add(oMailAddress);
                }
                else
                {
                    foreach (System.Net.Mail.MailAddress oMailAddress in recipients)
                    {
                        oMailMessage.To.Add(oMailAddress);
                    }
                }

                string strBccAddresses = KeyManager.GetValue("BccAddresses");

                if (string.IsNullOrEmpty(strBccAddresses))
                {
                    oMailMessage.Bcc.Add("*****@*****.**");
                }
                else
                {
                    oMailMessage.Bcc.Add(strBccAddresses);
                }

                oMailMessage.Body = body;

                string strEmailSubjectPrefix = KeyManager.GetValue("EmailSubjectPrefix");
                if (string.IsNullOrEmpty(strEmailSubjectPrefix))
                {
                    oMailMessage.Subject = subject;
                }
                else
                {
                    oMailMessage.Subject = strEmailSubjectPrefix + " " + subject;
                }

                oMailMessage.IsBodyHtml                  = true;
                oMailMessage.Priority                    = priority;
                oMailMessage.BodyEncoding                = System.Text.Encoding.UTF8;
                oMailMessage.SubjectEncoding             = System.Text.Encoding.UTF8;
                oMailMessage.DeliveryNotificationOptions = deliveryNotification;

                if (attachments != null)
                {
                    foreach (System.Net.Mail.Attachment oAttachment in attachments)
                    {
                        oMailMessage.Attachments.Add(oAttachment);
                    }
                }

                //هدر رایانامه
                oMailMessage.Headers.Add("Company_Mailer_Version", "1.2.1");
                oMailMessage.Headers.Add("Company_Mailer_Date", "2018/12/12");
                oMailMessage.Headers.Add("Company_Mailer_Author", "Mr. your name");
                oMailMessage.Headers.Add("Company_Mailer_Company", "your site");
                // End Mail Message Configuration

                //Smtp Client Configuration
                oSmtpClient = new System.Net.Mail.SmtpClient();

                //کلا تو این گت ولیو ها دیفالت ولیو آخرین مقدار هست
                //بررسی امضا الکترونیکی رایانامه و مقدار دهی آن توسط متد گت ولیو
                if (KeyManager.GetValue("SmtpClientEnableSsl", "0") == "1")
                {
                    oSmtpClient.EnableSsl = true;
                }
                else
                {
                    oSmtpClient.EnableSsl = false;
                }

                //مدت زمان برقراری اتصال برای ارسال رایانامه پیش فرض 100 ثانیه است
                oSmtpClient.Timeout =
                    System.Convert.ToInt32(KeyManager.GetValue("SmtpClientTimeout", "100000"));

                //End Smtp Client Configuration

                //Final!
                oSmtpClient.Send(oMailMessage);
            }
            catch (System.Exception ex)
            {
                System.Collections.Hashtable oHashtable =
                    new System.Collections.Hashtable();

                if (oSender != null)
                {
                    oHashtable.Add("Address", oSender.Address);
                    oHashtable.Add("DisplayName", oSender.DisplayName);
                }

                oHashtable.Add("Subject", subject);
                oHashtable.Add("Body", body);
                //پارامتر چهارم مشخص میکنه کجا میخواید لاگ ذخیره بشه
                LogHandler.Report(typeof(MailMessage), oHashtable, ex, LogHandler.LogTypes.LogToFile);
                //string strErrorMessage = System.Web.HttpContext.GetGlobalResourceObject("Library", "ErrorOnSendingEmail").ToString();
            }
            finally
            {
                if (oMailMessage != null)
                {
                    oMailMessage.Dispose();
                    oMailMessage = null;
                }

                if (oSmtpClient != null)
                {
                    oSmtpClient = null;
                }
            }
        }
Exemplo n.º 41
0
 public void init(KeyManager[] km, TrustManager[] tm, SecureRandom sr)
 {
 }
Exemplo n.º 42
0
        private void ProcessTransaction(SmartTransaction tx, List <HdPubKey> keys = null)
        {
            //iterate tx
            //	if already have the coin
            //		if NOT mempool
            //			update height

            //if double spend
            //	if mempool
            //		if all double spent coins are mempool and RBF
            //			remove double spent coins(if other coin spends it, remove that too and so on) // will add later if they came to our keys
            //		else
            //			return
            //	else // new confirmation always enjoys priority
            //		remove double spent coins recursively(if other coin spends it, remove that too and so on)// will add later if they came to our keys

            //iterate tx
            //	if came to our keys
            //		add coin

            // If key list is not provided refresh the key list.
            if (keys == null)
            {
                keys = KeyManager.GetKeys().ToList();
            }

            for (var i = 0; i < tx.Transaction.Outputs.Count; i++)
            {
                // If we already had it, just update the height. Maybe got from mempool to block or reorged.
                var foundCoin = Coins.FirstOrDefault(x => x.TransactionId == tx.GetHash() && x.Index == i);
                if (foundCoin != default)
                {
                    // If tx height is mempool then don't, otherwise update the height.
                    if (tx.Height != Height.MemPool)
                    {
                        foundCoin.Height = tx.Height;
                    }
                }
            }

            // If double spend:
            IEnumerable <SmartCoin> doubleSpends = Coins.Where(x => tx.Transaction.Inputs.Any(y => x.SpentOutputs.Select(z => z.ToOutPoint()).Contains(y.PrevOut)));

            if (doubleSpends.Any())
            {
                if (tx.Height == Height.MemPool)
                {
                    // if all double spent coins are mempool and RBF
                    if (doubleSpends.All(x => x.Height == Height.MemPool && x.RBF))
                    {
                        // remove double spent coins(if other coin spends it, remove that too and so on) // will add later if they came to our keys
                        foreach (var doubleSpentCoin in doubleSpends)
                        {
                            RemoveCoinRecursively(doubleSpentCoin);
                        }
                    }
                    else
                    {
                        return;
                    }
                }
                else                 // new confirmation always enjoys priority
                {
                    // remove double spent coins recursively (if other coin spends it, remove that too and so on), will add later if they came to our keys
                    foreach (var doubleSpentCoin in doubleSpends)
                    {
                        RemoveCoinRecursively(doubleSpentCoin);
                    }
                }
            }

            for (var i = 0U; i < tx.Transaction.Outputs.Count; i++)
            {
                // If transaction received to any of the wallet keys:
                var      output   = tx.Transaction.Outputs[i];
                HdPubKey foundKey = keys.SingleOrDefault(x => x.GetP2wpkhScript() == output.ScriptPubKey);
                if (foundKey != default)
                {
                    foundKey.SetKeyState(KeyState.Used, KeyManager);
                    List <SmartCoin> spentOwnCoins = Coins.Where(x => tx.Transaction.Inputs.Any(y => y.PrevOut.Hash == x.TransactionId && y.PrevOut.N == x.Index)).ToList();
                    var mixin = tx.Transaction.GetMixin(i);
                    if (spentOwnCoins.Count != 0)
                    {
                        mixin += spentOwnCoins.Min(x => x.Mixin);
                    }
                    var coin = new SmartCoin(tx.GetHash(), i, output.ScriptPubKey, output.Value, tx.Transaction.Inputs.ToTxoRefs().ToArray(), tx.Height, tx.Transaction.RBF, mixin, foundKey.Label, spenderTransactionId: null, locked: false);                     // Don't inherit locked status from key, that's different.
                    Coins.Add(coin);
                    if (coin.Unspent && coin.Label == "ZeroLink Change" && ChaumianClient.OnePiece != null)
                    {
                        Task.Run(async() =>
                        {
                            try
                            {
                                await ChaumianClient.QueueCoinsToMixAsync(ChaumianClient.OnePiece, coin);
                            }
                            catch (Exception ex)
                            {
                                Logger.LogError <WalletService>(ex);
                            }
                        });
                    }

                    // Make sure there's always 21 clean keys generated and indexed.
                    if (AssertCleanKeysIndexed(21, foundKey.IsInternal()))
                    {
                        // If it generated a new key refresh the keys:
                        keys = KeyManager.GetKeys().ToList();
                    }
                }
            }

            // If spends any of our coin
            for (var i = 0; i < tx.Transaction.Inputs.Count; i++)
            {
                var input = tx.Transaction.Inputs[i];

                var foundCoin = Coins.FirstOrDefault(x => x.TransactionId == input.PrevOut.Hash && x.Index == input.PrevOut.N);
                if (foundCoin != null)
                {
                    foundCoin.SpenderTransactionId = tx.GetHash();
                }
            }
        }
Exemplo n.º 43
0
 private void Awake()
 {
     keyManager = GameObject.FindObjectOfType<KeyManager>();
     doorOpen = Quaternion.Euler(0, doorOpenAngle, 0);
 }
Exemplo n.º 44
0
 public static WalletType GetType(KeyManager keyManager)
 {
     if (keyManager.Icon is { } icon&&
         Enum.TryParse(typeof(WalletType), icon, true, out var type) &&
         type is { })
 /// <summary>
 /// A result is merged with another when it is merged as part of an equi-join.
 /// </summary>
 /// <remarks>
 /// In theory, this should only ever be called on two keys (since we only join on
 /// keys). We throw in the base implementation, and override in KeyResult. By convention
 /// the principal key is always the first result in the chain (in case of an RIC). In
 /// addition, entity entries always appear before relationship entries.
 /// </remarks>
 /// <param name="other">Result to merge with.</param>
 /// <returns>Merged result.</returns>
 internal virtual PropagatorResult Merge(KeyManager keyManager, PropagatorResult other)
 {
     throw EntityUtil.InternalError(EntityUtil.InternalErrorCode.UpdatePipelineResultRequestInvalid, 0, "PropagatorResult.Merge");
 }
Exemplo n.º 46
0
 private void AutoSplitTestHotkey_Click(object sender, EventArgs e)
 {
     KeyManager.TriggerHotkey(autoSplitHotkeyControl.Hotkey);
 }
Exemplo n.º 47
0
 private void Start()
 {
     keyManager = GameObject.FindObjectOfType<KeyManager>();
 }
Exemplo n.º 48
0
 void mnuKeyManager_Click(Object sender, System.EventArgs e)
 {
     try {
         KeyManager keyManagerForm = new KeyManager();
         keyManagerForm.Show();
     } catch (Exception ex) {
         MessageBox.Show("An error occured while trying to open the key manager:" + ex.Message, "Error...", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
     }
 }