Beispiel #1
0
        private void GetKeys()
        {
            var key = new ExtKey(new Mnemonic(Mnemonic).DeriveSeed()).Derive(KeyPath.Parse(HdPath));

            this.PrivateKey = key.PrivateKey.ToBytes();
            this.Address    = new Bech32(Network.bech32Prefix).Encode(key.PrivateKey.PubKey.Hash.ToBytes());
        }
Beispiel #2
0
    public async Task StartParticipatingAsync(CancellationToken cancellationToken)
    {
        ThrowIfDisposed();
        var apiClient = new WabiSabiHttpApiClient(HttpClientFactory.NewHttpClientWithDefaultCircuit());

        using var roundStateUpdater = new RoundStateUpdater(TimeSpan.FromSeconds(3), apiClient);
        await roundStateUpdater.StartAsync(cancellationToken).ConfigureAwait(false);

        var coinJoinClient = new CoinJoinClient(
            HttpClientFactory,
            Wallet,
            Wallet,
            roundStateUpdater,
            consolidationMode: true);

        // Run the coinjoin client task.
        var walletHdPubKey = new HdPubKey(Wallet.PubKey, KeyPath.Parse("m/84'/0/0/0/0"), SmartLabel.Empty, KeyState.Clean);

        walletHdPubKey.SetAnonymitySet(1);         // bug if not settled

        if (SplitTransaction is null)
        {
            throw new InvalidOperationException($"{nameof(GenerateCoinsAsync)} has to be called first.");
        }

        var smartCoins = SplitTransaction.Transaction.Outputs.AsIndexedOutputs()
                         .Select(x => new SmartCoin(SplitTransaction, x.N, walletHdPubKey))
                         .ToList();

        // Run the coinjoin client task.
        await coinJoinClient.StartCoinJoinAsync(smartCoins, cancellationToken).ConfigureAwait(false);

        await roundStateUpdater.StopAsync(cancellationToken).ConfigureAwait(false);
    }
        /// <summary>
        /// Derive a child address from extended public key
        /// </summary>
        /// <param name="extPubKeyWif"></param>
        private static BitcoinPubKeyAddress DeriveChildAddress(string extPubKeyWif, string keyDerivationPath)
        {
            ExtPubKey            extPubKey    = ExtPubKey.Parse(extPubKeyWif, _network);
            BitcoinPubKeyAddress childAddress = extPubKey.Derive(KeyPath.Parse(keyDerivationPath)).PubKey.GetAddress(_network);

            return(childAddress);
        }
    /// <summary>
    /// Gets the signed transaction data from the Trezor wallet.
    /// </summary>
    /// <param name="transaction"> The transaction to sign. </param>
    /// <param name="path"> The path of the address to sign the transaction with. </param>
    /// <param name="onSignatureRequestSent"> Action to call once the signature request has been sent. </param>
    /// <returns> Task returning the SignedTransactionDataHolder instance. </returns>
    protected override async Task <SignedTransactionDataHolder> GetSignedTransactionData(Transaction transaction, string path, Action onSignatureRequestSent)
    {
        var trezorManager = TrezorConnector.GetWindowsConnectedTrezor(GetSignedTransactionDataEnterPin);

        if (trezorManager == null)
        {
            return(null);
        }

        var signedTransactionResponse = (EthereumTxRequest)null;
        var signedTransactionRequest  = new EthereumSignTx
        {
            Nonce            = transaction.Nonce,
            AddressNs        = KeyPath.Parse(path).Indexes,
            GasPrice         = transaction.GasPrice,
            GasLimit         = transaction.GasLimit,
            To               = transaction.ReceiveAddress,
            Value            = transaction.Value,
            DataInitialChunk = transaction.Data,
            DataLength       = (uint)transaction.Data.Length,
            ChainId          = (uint)ethereumNetworkSettings.networkType
        };

        while (true)
        {
            try
            {
                signedTransactionResponse = await trezorManager.SendMessageAsync <EthereumTxRequest, EthereumSignTx>(signedTransactionRequest, onSignatureRequestSent)
                                            .ConfigureAwait(false);

                break;
            }
            catch (FailureException <Failure> )
            {
                if (forceCancel)
                {
                    forceCancel = false;
                    break;
                }

                if (trezorManager.PinRequest.HasValue && trezorManager.PinRequest == false)
                {
                    break;
                }
            }
        }

        if (signedTransactionResponse == null)
        {
            return(new SignedTransactionDataHolder());
        }

        return(new SignedTransactionDataHolder
        {
            signed = true,
            v = signedTransactionResponse.SignatureV,
            r = signedTransactionResponse.SignatureR,
            s = signedTransactionResponse.SignatureS
        });
    }
Beispiel #5
0
        public void CanManageWallet()
        {
            var client = new QBitNinjaClient(Network.Main);
            var wallet = client.GetWalletClient("temp-1Nicolas Dorier");

            wallet.CreateIfNotExists().Wait();
            wallet.CreateAddressIfNotExists(BitcoinAddress.Create("15sYbVpRh6dyWycZMwPdxJWD4xbfxReeHe", client.Network)).Wait();
            wallet.CreateAddressIfNotExists(BitcoinAddress.Create("1KF8kUVHK42XzgcmJF4Lxz4wcL5WDL97PB", client.Network)).Wait();

            var balance = wallet.GetBalance().Result;

            Assert.True(balance.Operations.Count > 70);

            var keyset = wallet.GetKeySetClient("main");

            keyset.CreateIfNotExists(new[] { new ExtKey().Neuter() }, path: KeyPath.Parse("1/2/3")).Wait();
            Assert.True(keyset.Delete().Result);
            Assert.False(keyset.Delete().Result);
            keyset.CreateIfNotExists(new[] { new ExtKey().Neuter() }, path: KeyPath.Parse("1/2/3")).Wait();
            var key = keyset.GetUnused(1).Result;

            var sets = wallet.GetKeySets().Result;

            Assert.True(sets.Length > 0);

            var model = client.GetWalletClient("temp-1Nicolas Dorier").Get().Result;

            Assert.NotNull(model);
            Assert.Null(client.GetWalletClient("ojkljdjlksj").Get().Result);

            Assert.True(wallet.GetAddresses().Result.Length > 1);
        }
Beispiel #6
0
        static internal WalletCreation FromJson(JObject obj)
        {
            WalletCreation creation = new WalletCreation();

            creation.Network = null;
            JToken unused;

            if (obj.TryGetValue("Name", out unused))
            {
                creation.Name = (string)obj["Name"];
            }
            else
            {
                creation.Name = null;
            }
            if (obj.Property("PurgeConnectionOnFilterChange") != null)
            {
                creation.PurgeConnectionOnFilterChange = (bool)obj["PurgeConnectionOnFilterChange"];
            }
            JToken network;

            if (obj.TryGetValue("Network", out network))
            {
                creation.Network = Network.GetNetwork((string)network);
            }
            creation.SignatureRequired = (int)(long)obj["SignatureRequired"];
            creation.DerivationPath    = KeyPath.Parse((string)obj["DerivationPath"]);
            creation.UseP2SH           = (bool)obj["UseP2SH"];
            var array = (JArray)obj["RootKeys"];
            var keys  = array.Select(i => new BitcoinExtPubKey((string)i)).ToArray();

            creation.Network  = creation.Network ?? keys[0].Network;
            creation.RootKeys = keys.Select(k => k.ExtPubKey).ToArray();
            return(creation);
        }
Beispiel #7
0
        void LoadCore(Stream stream)
        {
            JObject obj = JObject.Load(new JsonTextReader(new StreamReader(stream))
            {
                DateParseHandling = DateParseHandling.DateTimeOffset
            });

            _Parameters = WalletCreation.FromJson((JObject)obj["Parameters"]);
            _PathStates = new Dictionary <KeyPath, PathState>();
            if (obj.Property("CurrentIndex") != null)            //legacy
            {
                var idx        = (int)(long)obj["CurrentIndex"];
                var loadedKeys = (int)(long)obj["LoadedKeys"];
                _PathStates.Add(_Parameters.DerivationPath.Derive(0), new PathState()
                {
                    Next   = idx,
                    Loaded = loadedKeys
                });
                _PathStates.Add(_Parameters.DerivationPath.Derive(1), new PathState()
                {
                    Next   = idx,
                    Loaded = loadedKeys
                });
            }

            var indices = obj["Indices"] as JArray;

            if (indices != null)
            {
                foreach (var indice in indices.OfType <JObject>())
                {
                    _PathStates.Add(KeyPath.Parse((string)indice["KeyPath"]), new PathState()
                    {
                        Next   = (int)(long)indice["Next"],
                        Loaded = (int)(long)indice["Loaded"]
                    });
                }
            }
            _KeyPoolSize  = (int)(long)obj["KeyPoolSize"];
            Created       = (DateTimeOffset)obj["Created"];
            _ScanLocation = new BlockLocator();
            _ScanLocation.FromBytes(Encoders.Hex.DecodeData((string)obj["Location"]));
            _KnownScripts.Clear();
            var knownScripts = (JArray)obj["KnownScripts"];

            foreach (var known in knownScripts.OfType <JObject>())
            {
                Script script = Script.FromBytesUnsafe(Encoders.Hex.DecodeData((string)known["ScriptPubKey"]));
                if (known["KeyPath"] != null)                //Legacy data
                {
                    KeyPath keypath = KeyPath.Parse((string)known["KeyPath"]);
                    _KnownScripts.Add(script, _Parameters.DerivationPath.Derive(keypath));
                }
                if (known["AbsoluteKeyPath"] != null)
                {
                    KeyPath keypath = KeyPath.Parse((string)known["AbsoluteKeyPath"]);
                    _KnownScripts.Add(script, keypath);
                }
            }
        }
        public static Wallet RestoreWalletFromMnemonic(string mnemonicStr, Network env)
        {
            Mnemonic mnemonic = new Mnemonic(mnemonicStr);

            var seed = mnemonic.DeriveSeed();
            var pk   = new ExtKey(seed);
            var kp   = KeyPath.Parse(keyPath);
            var key  = pk.Derive(kp);

            var privKey = key.PrivateKey;
            var bytes   = privKey.ToBytes();

            Wallet w = new Wallet();

            w._env            = BinanceEnvironment.GetEnvironment(env);
            w._privateKey     = privKey;
            w._privateKeyStr  = BitConverter.ToString(bytes).Replace("-", string.Empty);
            w._publicKey      = w._privateKey.PubKey.Compress();
            w._publicKeyBytes = w._publicKey.ToBytes();
            w._AddressBytes   = w._publicKey.Hash.ToBytes();
            w._addressStr     = Bech32Engine.Encode(w.Env.Hrp, w._AddressBytes);


            w.Init();

            return(w);
        }
        static HdPubKey CreateHdPubKey(ExtPubKey extPubKey)
        {
            var hdPubKey = new HdPubKey(extPubKey.PubKey, KeyPath.Parse($"m/84'/0/0/0/{extPubKey.Child}"), SmartLabel.Empty, KeyState.Clean);

            hdPubKey.SetAnonymitySet(1);             // bug if not settled
            return(hdPubKey);
        }
Beispiel #10
0
        public void CanUseKeyPath()
        {
            var keyPath = KeyPath.Parse("0/1/2/3");

            Assert.Equal(keyPath.ToString(), "0/1/2/3");
            var key = new ExtKey();

            Assert.Equal(key
                         .Derive(0)
                         .Derive(1)
                         .Derive(2)
                         .Derive(3)
                         .ToString(Network.Main), key.Derive(keyPath).ToString(Network.Main));

            var neuter = key.Neuter();

            Assert.Equal(neuter
                         .Derive(0)
                         .Derive(1)
                         .Derive(2)
                         .Derive(3)
                         .ToString(Network.Main), neuter.Derive(keyPath).ToString(Network.Main));

            Assert.Equal(neuter.Derive(keyPath).ToString(Network.Main),
                         key.Derive(keyPath).Neuter().ToString(Network.Main));

            keyPath = new KeyPath(0x8000002Cu, 1u);
            Assert.Equal(keyPath.ToString(), "44'/1");

            keyPath = KeyPath.Parse("44'/1");
            Assert.False(keyPath.IsHardened);
            Assert.True(KeyPath.Parse("44'/1'").IsHardened);
            Assert.Equal(keyPath[0], 0x8000002Cu);
            Assert.Equal(keyPath[1], 1u);

            key = new ExtKey();
            Assert.Equal(key.Derive(keyPath).ToString(Network.Main),
                         key.Derive(44, true).Derive(1, false).ToString(Network.Main));

            keyPath = KeyPath.Parse("");
            keyPath = keyPath.Derive(44, true).Derive(1, false);
            Assert.Equal(keyPath.ToString(), "44'/1");
            Assert.Equal(keyPath.Increment().ToString(), "44'/2");
            Assert.Equal(keyPath.Derive(1, true).Increment().ToString(), "44'/1/2'");
            Assert.Equal(keyPath.Parent.ToString(), "44'");
            Assert.Equal(keyPath.Parent.Parent.ToString(), "");
            Assert.Equal(keyPath.Parent.Parent.Parent, null);
            Assert.Equal(keyPath.Parent.Parent.Increment(), null);
            Assert.Equal(key.Derive(keyPath).ToString(Network.Main),
                         key.Derive(44, true).Derive(1, false).ToString(Network.Main));

            Assert.True(key.Derive(44, true).IsHardened);
            Assert.False(key.Derive(44, false).IsHardened);

            neuter = key.Derive(44, true).Neuter();
            Assert.True(neuter.IsHardened);
            neuter = key.Derive(44, false).Neuter();
            Assert.False(neuter.IsHardened);
        }
Beispiel #11
0
 public KeyPath GetWalletKeyPathRoot(PaymentMethodId paymentMethodId)
 {
     if (WalletKeyPathRoots.TryGetValue(paymentMethodId.ToString().ToLowerInvariant(), out var k))
     {
         return(KeyPath.Parse(k));
     }
     return(null);
 }
Beispiel #12
0
        public static byte[] SeedToPrivateKey(byte[] seed, int coinType)
        {
            //coinType: BTC 0, ETH 60, NEO 888, ONT 1024
            //see https://github.com/satoshilabs/slips/blob/master/slip-0044.md
            var derivePath = KeyPath.Parse($"m/44'/{coinType}'/0'/0/0");
            var paymentKey = new ExtKey(seed).Derive(derivePath);

            return(paymentKey.PrivateKey.ToBytes());
        }
Beispiel #13
0
        public void CanUseKeyPath()
        {
            var keyPath = KeyPath.Parse("0/1/2/3");

            Assert.Equal("0/1/2/3", keyPath.ToString());
            var key = new ExtKey();

            Assert.Equal(key
                         .Derive(0)
                         .Derive(1)
                         .Derive(2)
                         .Derive(3)
                         .ToString(Network.PurpleMain), key.Derive(keyPath).ToString(Network.PurpleMain));

            var neuter = key.Neuter();

            Assert.Equal(neuter
                         .Derive(0)
                         .Derive(1)
                         .Derive(2)
                         .Derive(3)
                         .ToString(Network.PurpleMain), neuter.Derive(keyPath).ToString(Network.PurpleMain));

            Assert.Equal(neuter.Derive(keyPath).ToString(Network.PurpleMain), key.Derive(keyPath).Neuter().ToString(Network.PurpleMain));

            keyPath = new KeyPath(new uint[] { 0x8000002Cu, 1u });
            Assert.Equal("44'/1", keyPath.ToString());

            keyPath = KeyPath.Parse("44'/1");
            Assert.False(keyPath.IsHardened);
            Assert.True(KeyPath.Parse("44'/1'").IsHardened);
            Assert.Equal(0x8000002Cu, keyPath[0]);
            Assert.Equal(1u, keyPath[1]);

            key = new ExtKey();
            Assert.Equal(key.Derive(keyPath).ToString(Network.PurpleMain), key.Derive(44, true).Derive(1, false).ToString(Network.PurpleMain));

            keyPath = KeyPath.Parse("");
            keyPath = keyPath.Derive(44, true).Derive(1, false);
            Assert.Equal("44'/1", keyPath.ToString());
            Assert.Equal("44'/2", keyPath.Increment().ToString());
            Assert.Equal("44'/1/2'", keyPath.Derive(1, true).Increment().ToString());
            Assert.Equal("44'", keyPath.Parent.ToString());
            Assert.Equal("", keyPath.Parent.Parent.ToString());
            Assert.Null(keyPath.Parent.Parent.Parent);
            Assert.Null(keyPath.Parent.Parent.Increment());
            Assert.Equal(key.Derive(keyPath).ToString(Network.PurpleMain), key.Derive(44, true).Derive(1, false).ToString(Network.PurpleMain));

            Assert.True(key.Derive(44, true).IsHardened);
            Assert.False(key.Derive(44, false).IsHardened);

            neuter = key.Derive(44, true).Neuter();
            Assert.True(neuter.IsHardened);
            neuter = key.Derive(44, false).Neuter();
            Assert.False(neuter.IsHardened);
        }
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     try
     {
         return(reader.TokenType == JsonToken.Null ? null : KeyPath.Parse(reader.Value.ToString()));
     }
     catch (FormatException)
     {
         throw new JsonObjectException("Invalid key path", reader);
     }
 }
Beispiel #15
0
        private BitcoinSecret HDPrivKey(string seed, int account, int n, string passphrase = null, bool change = false, bool segwit = false, bool bech32 = false)
        {
            var     mnemonic       = new Mnemonic(seed, Wordlist.English);
            var     masterKey      = mnemonic.DeriveExtKey(passphrase); //this is the root key
            string  derivationpath = dpath(segwit, bech32);
            KeyPath kp             = KeyPath.Parse(derivationpath + Convert.ToString(account) + "'/" + (change ? "1" : "0") + "/" + Convert.ToString(n));
            ExtKey  key            = masterKey.Derive(kp);
            var     p = key.PrivateKey.GetWif(Network.Main);

            return(p);
        }
Beispiel #16
0
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     try
     {
         return(reader.TokenType == JsonToken.Null ? null : KeyPath.Parse(reader.Value.ToString()));
     }
     catch (FormatException)
     {
         throw new JsonException($"Invalid  object of type {objectType.Name} path {reader.Path}");
     }
 }
        /// <inheritdoc />
        public override object?ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var s = (string)reader.Value;

            if (string.IsNullOrWhiteSpace(s))
            {
                return(null);
            }
            var kp = KeyPath.Parse(s.Trim());

            return(kp);
        }
Beispiel #18
0
 public uint[] GetPath()
 {
     if (!string.IsNullOrEmpty(_customPath))
     {
         var path = KeyPath.Parse(_customPath).Derive(_index);
         return(path.Indexes);
     }
     else
     {
         var path = KeyPath.Parse("m/44'/52752'/0'/0").Derive(_index);
         return(path.Indexes);
     }
 }
Beispiel #19
0
        public IList <SimpleWallet> GetAccounts()
        {
            List <SimpleWallet> simpleWallets = new List <SimpleWallet>();

            for (int i = 0; i < 10; i++)
            {
                var bitAdress = _safe.GetAddress(i);
                var extKEy    = _safe.ExtKey.Derive(KeyPath.Parse($"/44'/60'/0'/{i}"));
                simpleWallets.Add(new SimpleWallet(extKEy.PrivateKey.ToBytes()));
            }

            return(simpleWallets);
        }
Beispiel #20
0
        public static Wallet FromMnemonicCode(string mnemonicCode, BinanceDexEnvironmentData env)
        {
            Mnemonic mnemonic = new Mnemonic(mnemonicCode);

            byte[]  seed    = mnemonic.DeriveSeed();
            ExtKey  extKey  = new ExtKey(seed);
            KeyPath keyPath = KeyPath.Parse(hdPath);
            ExtKey  derived = extKey.Derive(keyPath);
            Wallet  wallet  = new Wallet(derived.PrivateKey, env);

            wallet.Mnemonic = mnemonicCode;
            return(wallet);
        }
Beispiel #21
0
        static internal WalletCreation FromJson(JObject obj)
        {
            WalletCreation creation = new WalletCreation();

            creation.SignatureRequired = (int)(long)obj["SignatureRequired"];
            creation.DerivationPath    = KeyPath.Parse((string)obj["DerivationPath"]);
            creation.UseP2SH           = (bool)obj["UseP2SH"];
            var array = (JArray)obj["RootKeys"];
            var keys  = array.Select(i => new BitcoinExtPubKey((string)i)).ToArray();

            creation.Network  = keys[0].Network;
            creation.RootKeys = keys.Select(k => k.ExtPubKey).ToArray();
            return(creation);
        }
        public string SignTransaction(string transactionHex, WalletUnsignedTransactionUnspent[] unspents, Keychain userKeychain)
        {
            var hexEncoder = new NBitcoin.DataEncoders.HexEncoder();
            var extKey     = ExtKey.Parse(userKeychain.ExtendedPrivateKey);
            var builder    = new TransactionBuilder().ContinueToBuild(Transaction.Parse(transactionHex));

            foreach (var unspent in unspents)
            {
                builder
                .AddCoins(new ScriptCoin(new OutPoint(uint256.Parse(unspent.TransactionHash), unspent.TransactionOutputIndex), new TxOut(unspent.Value, new Script(hexEncoder.DecodeData(unspent.Script))), new Script(hexEncoder.DecodeData(unspent.RedeemScript))))
                .AddKeys(extKey.Derive(KeyPath.Parse($"{userKeychain.Path}/0/0{unspent.ChainPath}")).PrivateKey);
            }
            return(builder.BuildTransaction(true).ToHex());
        }
Beispiel #23
0
        public void TestBIP39_Passphrase()
        {
            Assert.Inconclusive();
            string  seed24         = "";
            string  password       = "";
            var     mnemonic       = new Mnemonic(seed24);
            var     masterKey      = mnemonic.DeriveExtKey(password);
            string  derivationpath = "m/44'/0'/0'/0/0";
            KeyPath kp             = KeyPath.Parse(derivationpath);
            ExtKey  key            = masterKey.Derive(kp);
            var     p        = key.PrivateKey.GetWif(Network.Main);
            var     PubAddr2 = p.PubKey.GetAddress(Network.Main).ToString();

            Console.WriteLine(PubAddr2.ToString());
        }
Beispiel #24
0
        public void TestBIP39_BIP32Keys()
        {
            // This is a throwaway.
            string seed12      = "turtle front uncle idea crush write shrug there lottery flower risk shell";
            var    mnemonic    = new Mnemonic(seed12);
            var    masterKey   = mnemonic.DeriveExtKey(null); //this is the root key
            int    numaccounts = 5;
            int    numaddr     = 20;
            int    coinIx      = 0; //https://github.com/satoshilabs/slips/blob/master/slip-0044.md

            for (int i = 0; i < numaccounts; i++)
            {   //                      bitcoin/account/change/addr
                for (int j = 0; j < numaddr; j++)
                {
                    string  derivationpath = "m/49'/" + Convert.ToString(coinIx) + "'/";
                    string  fullpath       = derivationpath + Convert.ToString(i) + "'/0/" + Convert.ToString(j);
                    KeyPath kp             = KeyPath.Parse(fullpath);
                    ExtKey  key            = masterKey.Derive(kp);
                    //Console.WriteLine("Key " + i + " : " + key.ToString(Network.Main));

                    //Change Addresses
                    //kp = KeyPath.Parse(derivationpath + Convert.ToString(i) + "'/1/" + Convert.ToString(j));
                    //key = masterKey.Derive(kp);
                    //Console.WriteLine("Key " + i + " : " + key.ToString(Network.Main));

                    //generate WIF
                    var p = key.PrivateKey.GetWif(Network.Main);

                    //bech32 addresses
                    //var privkey = "LB8PaHs9t9UxUPYgGqeJRCZ4KK6YvnnqXbgbanWzb7ctGKfegCS8";
                    //var p = new BitcoinSecret(privkey, Network.Main);

                    //var ba = BitcoinAddress.Create("bc1qsmd3m8sgrhkqp3pefag6n5yahgx3ds226qva07");

                    var PubAddr2  = p.PubKey.GetAddress(Network.Main).ToString();   //normal
                    var PubAddrSW = p.PubKey.GetSegwitAddress(Network.Main);        //bech32
                    var PubP2SH   = PubAddrSW.GetScriptAddress().ToString();        //SH
                    if (PubP2SH.Substring(0, 6) == "34xped")
                    {
                        int q = 1;
                    }

                    Console.WriteLine(PubAddrSW);
                }
            }
            //Assert.IsTrue(mnemonic.IsValidChecksum);
        }
Beispiel #25
0
        public async Task SignEthereumTransaction()
        {
            var txMessage = new EthereumSignTx
            {
                Nonce     = 10.ToBytesForRLPEncoding().ToHex().ToHexBytes(),
                GasPrice  = 1000000000.ToBytesForRLPEncoding().ToHex().ToHexBytes(),
                GasLimit  = 21000.ToBytesForRLPEncoding().ToHex().ToHexBytes(),
                To        = "689c56aef474df92d44a1b70850f808488f9769c".ToHexBytes(),
                Value     = BigInteger.Parse("10000000000000000000").ToBytesForRLPEncoding().ToHex().ToHexBytes(),
                AddressNs = KeyPath.Parse("m/44'/60'/0'/0/0").Indexes,
                ChainId   = 1
            };
            var transaction = await KeepKeyManager.SendMessageAsync <EthereumTxRequest, EthereumSignTx>(txMessage);

            Assert.AreEqual(transaction.SignatureR.Length, 32);
            Assert.AreEqual(transaction.SignatureS.Length, 32);
        }
        public virtual GetAddressInfoResponse LoadFromJson(JObject raw, Network network)
        {
            SetSubInfo(this, raw, network);
            IsMine      = raw.Property("ismine").Value.Value <bool>();
            Solvable    = raw.Property("solvable")?.Value.Value <bool>();
            Desc        = raw.Property("desc") == null ? null : new ScanTxoutDescriptor(raw.Property("desc").Value.Value <string>());
            IsWatchOnly = raw.Property("iswatchonly").Value.Value <bool>();
            IsScript    = raw.Property("isscript").Value.Value <bool>();
            IsWitness   = raw.Property("iswitness").Value.Value <bool>();
            Script      = raw.Property("script")?.Value.Value <string>();
            Hex         = raw.Property("hex")?.Value.Value <string>();
            var jEmbedded = raw.Property("embedded");

            if (jEmbedded != null)
            {
                var j = jEmbedded.Value.Value <JObject>();
                var e = new GetAddressInfoScriptInfoResponse();
                SetSubInfo(e, j, network);
                Embedded = e;
            }
            IsCompressed  = raw.Property("iscompressed")?.Value.Value <bool>();
            Label         = raw.Property("label")?.Value.Value <string>();
            IsChange      = raw.Property("ischange")?.Value.Value <bool>();
            Timestamp     = raw.Property("timestamp") == null ? (DateTimeOffset?)null : Utils.UnixTimeToDateTime(raw.Property("timestamp").Value.Value <ulong>());
            HDKeyPath     = raw.Property("hdkeypath") == null ? null : KeyPath.Parse(raw.Property("hdkeypath").Value.Value <string>());
            HDSeedID      = raw.Property("hdseedid") == null ? null : uint160.Parse(raw.Property("hdseedid").Value.Value <string>());
            HDMasterKeyID = raw.Property("hdmasterkeyid") == null ? null : uint160.Parse(raw.Property("hdmasterkeyid").Value.Value <string>());
            var jlabels = raw.Property("labels");

            if (jlabels != null)
            {
                var labelObjects = jlabels.Value.Value <JArray>();
                foreach (var jToken in labelObjects)
                {
                    if (jToken is JObject jObject) // Before Bitcoin Core 0.20.0
                    {
#pragma warning disable CS0618                     // Type or member is obsolete.
                        Labels.Add(jToken.ToObject <Dictionary <string, string> >());
#pragma warning restore CS0618                     // Type or member is obsolete
                    }
                }
            }

            return(this);
        }
Beispiel #27
0
        public SafeAccount(uint id)
        {
            try
            {
                string firstPart = Hierarchy.GetPathString(HdPathType.Account);

                string lastPart = $"/{id}'";
                PathString = firstPart + lastPart;

                KeyPath.Parse(PathString);
            }
            catch (Exception ex)
            {
                throw new ArgumentOutOfRangeException($"{nameof(id)} : {id}", ex);
            }

            Id = id;
        }
        private void RecoverWallet(WalletManagerViewModel owner)
        {
            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 = WalletManager.WalletDirectories.GetWalletFilePaths(WalletName).walletFilePath;

            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
            {
                var minGapLimit = int.Parse(MinGapLimit);
                var keyPath     = KeyPath.Parse(AccountKeyPath);

                try
                {
                    var mnemonic = new Mnemonic(MnemonicWords);
                    var km       = KeyManager.Recover(mnemonic, Password, filePath: null, keyPath, minGapLimit);
                    km.SetNetwork(Global.Network);
                    km.SetFilePath(walletFilePath);
                    WalletManager.AddWallet(km);

                    NotificationHelpers.Success("Wallet was recovered.");

                    owner.SelectLoadWallet(km);
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex);
                    NotificationHelpers.Error(ex.ToUserFriendlyString());
                }
            }
        }
Beispiel #29
0
        public byte[] GetPath()
        {
            if (!string.IsNullOrEmpty(_customPath))
            {
                var path = KeyPath.Parse(_customPath).Derive(_index);
                return(GetByteData(path.Indexes));
            }

            if (_legacyPath)
            {
                var path = KeyPath.Parse("m/44'/52752'/0'").Derive(_index);
                return(GetByteData(path.Indexes));
            }
            else
            {
                var path = KeyPath.Parse("m/44'/52752'/0'/0").Derive(_index);
                return(GetByteData(path.Indexes));
            }
        }
Beispiel #30
0
        public static GetAddressInfoResponse FromJsonResponse(JObject raw, Network network)
        {
            var result = new GetAddressInfoResponse();

            SetSubInfo(result, raw, network);
            result.IsMine      = raw.Property("ismine").Value.Value <bool>();
            result.Solvable    = raw.Property("solvable")?.Value.Value <bool>();
            result.Desc        = raw.Property("desc") == null ? null : new ScanTxoutDescriptor(raw.Property("desc").Value.Value <string>());
            result.IsWatchOnly = raw.Property("iswatchonly").Value.Value <bool>();
            result.IsScript    = raw.Property("isscript").Value.Value <bool>();
            result.IsWitness   = raw.Property("iswitness").Value.Value <bool>();
            result.Script      = raw.Property("script")?.Value.Value <string>();
            result.Hex         = raw.Property("hex")?.Value.Value <string>();
            var jEmbedded = raw.Property("embedded");

            if (jEmbedded != null)
            {
                var j = jEmbedded.Value.Value <JObject>();
                var e = new GetAddressInfoScriptInfoResponse();
                SetSubInfo(e, j, network);
                result.Embedded = e;
            }
            result.IsCompressed  = raw.Property("iscompressed")?.Value.Value <bool>();
            result.Label         = raw.Property("label").Value.Value <string>();
            result.IsChange      = raw.Property("ischange")?.Value.Value <bool>();
            result.Timestamp     = raw.Property("timestamp") == null ? (DateTimeOffset?)null : Utils.UnixTimeToDateTime(raw.Property("timestamp").Value.Value <ulong>());
            result.HDKeyPath     = raw.Property("hdkeypath") == null ? null : KeyPath.Parse(raw.Property("hdkeypath").Value.Value <string>());
            result.HDSeedID      = raw.Property("hdseedid") == null ? null : uint160.Parse(raw.Property("hdseedid").Value.Value <string>());
            result.HDMasterKeyID = raw.Property("hdmasterkeyid") == null ? null : uint160.Parse(raw.Property("hdmasterkeyid").Value.Value <string>());
            var jlabels = raw.Property("labels");

            if (jlabels != null)
            {
                var labelObjects = jlabels.Value.Value <JArray>();
                foreach (var jObj in labelObjects)
                {
                    result.Labels.Add(((JObject)jObj).ToObject <Dictionary <string, string> >());
                }
            }

            return(result);
        }