Exemplo n.º 1
0
        public static HDFingerprint BetterParseHDFingerprint(string hdFingerPrintString, bool reverseByteOrder = false)
        {
            hdFingerPrintString = Guard.NotNullOrEmptyOrWhitespace(nameof(hdFingerPrintString), hdFingerPrintString, trim: true);

            HDFingerprint hdfp;

            try
            {
                var hdfpu = uint.Parse(hdFingerPrintString);
                hdfp = new HDFingerprint(hdfpu);
            }
            catch
            {
                // Try hex, Old wallet format was like this.
                var bytes = ByteHelpers.FromHex(hdFingerPrintString);
                if (reverseByteOrder)
                {
                    hdfp = new HDFingerprint(bytes.Reverse().ToArray());
                }
                else
                {
                    hdfp = new HDFingerprint(bytes);
                }
            }
            return(hdfp);
        }
Exemplo n.º 2
0
        public async Task RegisterAliceInputThenConfirmAsync(NetworkType networkType)
        {
            (BitcoinPubKeyAddress activeOutputAddress, BitcoinPubKeyAddress changeOutputAddress, string blindedDataHex, string proof, List <TxoRef> utxos) = LiveServerTestsFixture.GetAliceInputData(networkType);

            // blinded activeOutputAddress.ScriptPubKey
            byte[] blinded = ByteHelpers.FromHex(blindedDataHex);

            var inputProofModels = utxos.Select(txrf => new InputProofModel
            {
                Input = txrf,
                Proof = proof                 // blinded.BlindedData signed with private key owning utxos
            });

            using (var aliceClient = await AliceClient.CreateNewAsync(changeOutputAddress, blinded, inputProofModels, LiveServerTestsFixture.UriMappings[networkType]))
            {
                Assert.NotNull(aliceClient.BlindedOutputSignature);

                try
                {
                    await aliceClient.PostConfirmationAsync();

                    // need to uncofirm or test will fail when run again
                    await aliceClient.PostUnConfirmationAsync();
                }
                catch (Exception ex)
                {
                    await aliceClient.PostUnConfirmationAsync();

                    throw ex;
                }
            }
        }
Exemplo n.º 3
0
        public void ScalarSerialization()
        {
            var converters = new JsonConverter[]
            {
                new ScalarJsonConverter()
            };

            // Deserialization invalid scalar.
            var ex = Assert.Throws <ArgumentException>(() => JsonConvert.DeserializeObject <Scalar>("21", converters));

            Assert.StartsWith("No valid serialized Scalar", ex.Message);

            Assert.Throws <IndexOutOfRangeException>(() => JsonConvert.DeserializeObject <Scalar>("\"\"", converters));

            // Serialization Zero test.
            var serializedZero = JsonConvert.SerializeObject(Scalar.Zero, converters);

            Assert.Equal("\"0000000000000000000000000000000000000000000000000000000000000000\"", serializedZero);

            var deserializedZero = JsonConvert.DeserializeObject <Scalar>("\"0000000000000000000000000000000000000000000000000000000000000000\"", converters);

            Assert.Equal(Scalar.Zero, deserializedZero);

            // Serialization round test.
            var scalar = new Scalar(ByteHelpers.FromHex("D9C17A80D299A51E1ED9CF94FCE5FD883ADACE4ECC167E1D1FB8E5C4A0ADC4D2"));

            var serializedScalar = JsonConvert.SerializeObject(scalar, converters);

            Assert.Equal("\"D9C17A80D299A51E1ED9CF94FCE5FD883ADACE4ECC167E1D1FB8E5C4A0ADC4D2\"", serializedScalar);

            var deserializedScalar = JsonConvert.DeserializeObject <Scalar>("\"D9C17A80D299A51E1ED9CF94FCE5FD883ADACE4ECC167E1D1FB8E5C4A0ADC4D2\"", converters);

            Assert.Equal(scalar, deserializedScalar);
        }
Exemplo n.º 4
0
        public static BitcoinExtPubKey BetterParseExtPubKey(string extPubKeyString, Network network, bool ignoreInvalidNetwork)
        {
            extPubKeyString = Guard.NotNullOrEmptyOrWhitespace(nameof(extPubKeyString), extPubKeyString, trim: true);

            try
            {
                return(new BitcoinExtPubKey(extPubKeyString, network)); // Starts with "ExtPubKey": "xpub...
            }
            catch
            {
                try
                {
                    // Try hex, Old wallet format was like this.
                    return(new ExtPubKey(ByteHelpers.FromHex(extPubKeyString)).GetWif(network)); // Starts with "ExtPubKey": "hexbytes...
                }
                catch when(ignoreInvalidNetwork)
                {
                    // Let's replace the version prefix
                    var data         = Encoders.Base58Check.DecodeData(extPubKeyString);
                    var versionBytes = network.GetVersionBytes(Base58Type.EXT_PUBLIC_KEY, true);

                    if (versionBytes.Length > data.Length)
                    {
                        throw;
                    }
                    for (int i = 0; i < versionBytes.Length; i++)
                    {
                        data[i] = versionBytes[i];
                    }
                    extPubKeyString = Encoders.Base58Check.EncodeData(data);
                    return(new BitcoinExtPubKey(extPubKeyString, network));
                }
Exemplo n.º 5
0
        public static FilterModel FromLine(string line, Height height)
        {
            Guard.NotNullOrEmptyOrWhitespace(nameof(line), line);
            var parts = line.Split(':');

            if (parts.Length == 1)            // no bech here
            {
                return(new FilterModel
                {
                    BlockHeight = Guard.NotNull(nameof(height), height),
                    BlockHash = new uint256(parts[0]),
                    Filter = null
                });
            }
            else
            {
                var n   = int.Parse(parts[1]);
                var fba = new FastBitArray(ByteHelpers.FromHex(parts[3]));
                fba.Length = int.Parse(parts[2]);

                var filter = new GolombRiceFilter(fba, n);

                return(new FilterModel
                {
                    BlockHeight = Guard.NotNull(nameof(height), height),
                    BlockHash = new uint256(parts[0]),
                    Filter = filter
                });
            }
        }
Exemplo n.º 6
0
        public static ExtPubKey BetterParseExtPubKey(string extPubKeyString)
        {
            extPubKeyString = Guard.NotNullOrEmptyOrWhitespace(nameof(extPubKeyString), extPubKeyString, trim: true);

            ExtPubKey epk;

            try
            {
                epk = ExtPubKey.Parse(extPubKeyString, Network.Main);                 // Starts with "ExtPubKey": "xpub...
            }
            catch
            {
                try
                {
                    epk = ExtPubKey.Parse(extPubKeyString, Network.TestNet);                     // Starts with "ExtPubKey": "xpub...
                }
                catch
                {
                    try
                    {
                        epk = ExtPubKey.Parse(extPubKeyString, Network.RegTest);                         // Starts with "ExtPubKey": "xpub...
                    }
                    catch
                    {
                        // Try hex, Old wallet format was like this.
                        epk = new ExtPubKey(ByteHelpers.FromHex(extPubKeyString));                         // Starts with "ExtPubKey": "hexbytes...
                    }
                }
            }

            return(epk);
        }
        public async Task <IActionResult> PostOutputAsync([FromQuery] string roundHash, [FromBody] OutputRequest outputRequest)
        {
            if (string.IsNullOrWhiteSpace(roundHash) ||
                outputRequest == null ||
                string.IsNullOrWhiteSpace(outputRequest.OutputScript) ||
                string.IsNullOrWhiteSpace(outputRequest.SignatureHex) ||
                !ModelState.IsValid)
            {
                return(BadRequest());
            }

            CcjRound round = Coordinator.TryGetRound(roundHash);

            if (round == null)
            {
                return(NotFound("Round not found."));
            }

            if (round.Status != CcjRoundStatus.Running)
            {
                return(Forbid("Round is not running."));
            }

            CcjRoundPhase phase = round.Phase;

            if (phase != CcjRoundPhase.OutputRegistration)
            {
                return(Forbid($"Output registration can only be done from OutputRegistration phase. Current phase: {phase}."));
            }

            var outputScript = new Script(outputRequest.OutputScript);

            if (RsaKey.PubKey.Verify(ByteHelpers.FromHex(outputRequest.SignatureHex), outputScript.ToBytes()))
            {
                using (await OutputLock.LockAsync())
                {
                    Bob bob = null;
                    try
                    {
                        bob = new Bob(outputScript);
                        round.AddBob(bob);
                    }
                    catch (Exception ex)
                    {
                        return(BadRequest($"Invalid outputScript is provided. Details: {ex.Message}"));
                    }

                    if (round.CountBobs() == round.AnonymitySet)
                    {
                        await round.ExecuteNextPhaseAsync(CcjRoundPhase.Signing);
                    }
                }

                return(NoContent());
            }
            else
            {
                return(BadRequest("Invalid signature provided."));
            }
        }
Exemplo n.º 8
0
        public static bool TryGetMasterFingerprintFromFile(string filePath, out HDFingerprint masterFingerprint)
        {
            masterFingerprint = default;
            filePath          = Guard.NotNullOrEmptyOrWhitespace(nameof(filePath), filePath);

            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException($"Wallet file not found at: `{filePath}`.");
            }

            // Example text to handle: "ExtPubKey": "03BF8271268000000013B9013C881FE456DDF524764F6322F611B03CF6".
            var masterfpline = File.ReadLines(filePath) // Enumerated read.
                               .Take(21)                // Limit reads to x lines.
                               .FirstOrDefault(line => line.Contains("\"MasterFingerprint\": \"", StringComparison.InvariantCulture));

            if (string.IsNullOrEmpty(masterfpline))
            {
                return(false);
            }

            var parts = masterfpline.Split("\"MasterFingerprint\": \"");

            if (parts.Length != 2)
            {
                throw new FormatException($"Could not split line: {masterfpline}");
            }

            var hex = parts[1].TrimEnd(',', '"');

            var mfp = new HDFingerprint(ByteHelpers.FromHex(hex));

            masterFingerprint = mfp;
            return(true);
        }
Exemplo n.º 9
0
        public void InfinityDeserialization(string infinityHex)
        {
            var infinity = GroupElement.FromBytes(ByteHelpers.FromHex(infinityHex));

            Assert.True(infinity.IsInfinity);
            Assert.Equal(GroupElement.Infinity, infinity);
        }
Exemplo n.º 10
0
        public static ExtPubKey BetterParseExtPubKey(string extPubKeyString)
        {
            extPubKeyString = Guard.NotNullOrEmptyOrWhitespace(nameof(extPubKeyString), extPubKeyString, trim: true);

            ExtPubKey epk;

            try
            {
                epk = ExtPubKey.Parse(extPubKeyString, NBitcoin.Altcoins.Litecoin.Instance.Mainnet);                 // Starts with "ExtPubKey": "xpub...
            }
            catch
            {
                try
                {
                    epk = ExtPubKey.Parse(extPubKeyString, NBitcoin.Altcoins.Litecoin.Instance.Testnet);                     // Starts with "ExtPubKey": "xpub...
                }
                catch
                {
                    try
                    {
                        epk = ExtPubKey.Parse(extPubKeyString, NBitcoin.Altcoins.Litecoin.Instance.Regtest);                         // Starts with "ExtPubKey": "xpub...
                    }
                    catch
                    {
                        // Try hex, Old wallet format was like this.
                        // Doesn't make sense for LTC Litecoin because there's no legacy wallet format to support :
                        epk = new ExtPubKey(ByteHelpers.FromHex(extPubKeyString));                         // Starts with "ExtPubKey": "hexbytes...
                    }
                }
            }

            return(epk);
        }
Exemplo n.º 11
0
        public HardwareWalletInfo(string masterFingerprint, string serialNumber, HardwareWalletType type, string path, string error)
        {
            try
            {
                Guard.NotNullOrEmptyOrWhitespace(nameof(masterFingerprint), masterFingerprint);
                var masterFingerPrintBytes = ByteHelpers.FromHex(masterFingerprint);
                MasterFingerprint = new HDFingerprint(masterFingerPrintBytes);
            }
            catch (ArgumentException)
            {
                MasterFingerprint = null;
            }

            SerialNumber = serialNumber;
            Type         = type;
            Path         = path;
            Error        = error;

            Ready       = true;
            Initialized = true;
            if (Error != null)
            {
                if (Error.Contains("Not initialized", StringComparison.OrdinalIgnoreCase))
                {
                    Initialized = false;
                }
                else if (Type == HardwareWalletType.Ledger &&
                         (Error.Contains("get_pubkey_at_path canceled", StringComparison.OrdinalIgnoreCase) ||
                          Error.Contains("Invalid status 6f04", StringComparison.OrdinalIgnoreCase) ||               // It comes when device asleep too.
                          Error.Contains("Device is asleep", StringComparison.OrdinalIgnoreCase)))
                {
                    Ready = false;
                }
            }
        }
Exemplo n.º 12
0
        public IndexBuilderService(RPCClient rpc, TrustedNodeNotifyingBehavior trustedNodeNotifyingBehavior, string indexFilePath, string bech32UtxoSetFilePath)
        {
            RpcClient = Guard.NotNull(nameof(rpc), rpc);
            TrustedNodeNotifyingBehavior = Guard.NotNull(nameof(trustedNodeNotifyingBehavior), trustedNodeNotifyingBehavior);
            IndexFilePath         = Guard.NotNullOrEmptyOrWhitespace(nameof(indexFilePath), indexFilePath);
            Bech32UtxoSetFilePath = Guard.NotNullOrEmptyOrWhitespace(nameof(bech32UtxoSetFilePath), bech32UtxoSetFilePath);

            Bech32UtxoSet        = new Dictionary <OutPoint, Script>();
            Bech32UtxoSetHistory = new List <ActionHistoryHelper>(capacity: 100);
            Index     = new List <FilterModel>();
            IndexLock = new AsyncLock();

            StartingFilter = StartingFilters.GetStartingFilter(RpcClient.Network);
            StartingHeight = StartingFilters.GetStartingHeight(RpcClient.Network);

            _running = 0;

            IoHelpers.EnsureContainingDirectoryExists(IndexFilePath);
            if (File.Exists(IndexFilePath))
            {
                if (RpcClient.Network == Network.RegTest)
                {
                    File.Delete(IndexFilePath);                     // RegTest is not a global ledger, better to delete it.
                }
                else
                {
                    var height = StartingHeight;
                    foreach (var line in File.ReadAllLines(IndexFilePath))
                    {
                        var filter = FilterModel.FromHeightlessLine(line, height);
                        height++;
                        Index.Add(filter);
                    }
                }
            }

            IoHelpers.EnsureContainingDirectoryExists(bech32UtxoSetFilePath);
            if (File.Exists(bech32UtxoSetFilePath))
            {
                if (RpcClient.Network == Network.RegTest)
                {
                    File.Delete(bech32UtxoSetFilePath);                     // RegTest is not a global ledger, better to delete it.
                }
                else
                {
                    foreach (var line in File.ReadAllLines(Bech32UtxoSetFilePath))
                    {
                        var parts = line.Split(':');

                        var txHash = new uint256(parts[0]);
                        var nIn    = int.Parse(parts[1]);
                        var script = new Script(ByteHelpers.FromHex(parts[2]), true);
                        Bech32UtxoSet.Add(new OutPoint(txHash, nIn), script);
                    }
                }
            }

            TrustedNodeNotifyingBehavior.BlockInv += TrustedNodeNotifyingBehavior_BlockInv;
        }
Exemplo n.º 13
0
 public HardwareWalletInfo(string fingerprint, string serialNumber, HardwareWalletType type, string path, string error)
 {
     MasterFingerprint = new HDFingerprint(ByteHelpers.FromHex(fingerprint));
     SerialNumber      = serialNumber;
     Type  = type;
     Path  = path;
     Error = error;
 }
Exemplo n.º 14
0
 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     if (reader.Value is string serialized)
     {
         return(GroupElement.FromBytes(ByteHelpers.FromHex(serialized)));
     }
     throw new ArgumentException($"No valid serialized {nameof(GroupElement)} passed.");
 }
Exemplo n.º 15
0
 /// <inheritdoc />
 public override Scalar ReadJson(JsonReader reader, Type objectType, Scalar existingValue, bool hasExistingValue, JsonSerializer serializer)
 {
     if (reader.Value is string serialized)
     {
         return(new Scalar(ByteHelpers.FromHex(serialized)));
     }
     throw new ArgumentException($"No valid serialized {nameof(Scalar)} passed.");
 }
Exemplo n.º 16
0
 /// <inheritdoc />
 public override OwnershipProof?ReadJson(JsonReader reader, Type objectType, OwnershipProof?existingValue, bool hasExistingValue, JsonSerializer serializer)
 {
     if (reader.Value is string serialized)
     {
         return(OwnershipProof.FromBytes(ByteHelpers.FromHex(serialized)));
     }
     throw new ArgumentException($"No valid serialized {nameof(OwnershipProof)} passed.");
 }
        public void FromHex(string hex)
        {
            hex = Guard.NotNullOrEmptyOrWhitespace(nameof(hex), hex, true);

            var bytes = ByteHelpers.FromHex(hex);

            FromBytes(bytes);
        }
Exemplo n.º 18
0
		public IndexBuilderService(RPCClient rpc, BlockNotifier blockNotifier, string indexFilePath, string bech32UtxoSetFilePath)
		{
			RpcClient = Guard.NotNull(nameof(rpc), rpc);
			BlockNotifier = Guard.NotNull(nameof(blockNotifier), blockNotifier);
			IndexFilePath = Guard.NotNullOrEmptyOrWhitespace(nameof(indexFilePath), indexFilePath);
			Bech32UtxoSetFilePath = Guard.NotNullOrEmptyOrWhitespace(nameof(bech32UtxoSetFilePath), bech32UtxoSetFilePath);

			Bech32UtxoSet = new Dictionary<OutPoint, UtxoEntry>();
			Bech32UtxoSetHistory = new List<ActionHistoryHelper>(capacity: 100);
			Index = new List<FilterModel>();
			IndexLock = new AsyncLock();

			StartingHeight = SmartHeader.GetStartingHeader(RpcClient.Network).Height;

			_running = 0;

			IoHelpers.EnsureContainingDirectoryExists(IndexFilePath);
			if (File.Exists(IndexFilePath))
			{
				if (RpcClient.Network == Network.RegTest)
				{
					File.Delete(IndexFilePath); // RegTest is not a global ledger, better to delete it.
				}
				else
				{
					foreach (var line in File.ReadAllLines(IndexFilePath))
					{
						var filter = FilterModel.FromLine(line);
						Index.Add(filter);
					}
				}
			}

			IoHelpers.EnsureContainingDirectoryExists(bech32UtxoSetFilePath);
			if (File.Exists(bech32UtxoSetFilePath))
			{
				if (RpcClient.Network == Network.RegTest)
				{
					File.Delete(bech32UtxoSetFilePath); // RegTest is not a global ledger, better to delete it.
				}
				else
				{
					foreach (var line in File.ReadAllLines(Bech32UtxoSetFilePath))
					{
						var parts = line.Split(':');

						var txHash = new uint256(parts[0]);
						var nIn = int.Parse(parts[1]);
						var script = new Script(ByteHelpers.FromHex(parts[2]), true);
						OutPoint outPoint = new OutPoint(txHash, nIn);
						var utxoEntry = new UtxoEntry(outPoint, script);
						Bech32UtxoSet.Add(outPoint, utxoEntry);
					}
				}
			}

			BlockNotifier.OnBlock += BlockNotifier_OnBlock;
		}
Exemplo n.º 19
0
        public HardwareWalletInfo(string masterFingerprint, string serialNumber, HardwareWalletType type, string path, string error)
        {
            Guard.NotNullOrEmptyOrWhitespace(nameof(masterFingerprint), masterFingerprint);
            var masterFingerPrintBytes = ByteHelpers.FromHex(masterFingerprint);

            MasterFingerprint = new HDFingerprint(masterFingerPrintBytes);
            SerialNumber      = serialNumber;
            Type  = type;
            Path  = path;
            Error = error;
        }
Exemplo n.º 20
0
    /// <inheritdoc />
    public override HDFingerprint?ReadJson(JsonReader reader, Type objectType, HDFingerprint?existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        var s = (string?)reader.Value;

        if (string.IsNullOrWhiteSpace(s))
        {
            return(null);
        }

        return(new HDFingerprint(ByteHelpers.FromHex(s)));
    }
Exemplo n.º 21
0
        public void EvenOddSerialization()
        {
            var hexG    = "0279BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798";
            var hexGodd = "0379BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798";

            Assert.Equal(hexG, ByteHelpers.ToHex(Generators.G.ToBytes()));
            Assert.Equal(Generators.G, GroupElement.FromBytes(ByteHelpers.FromHex(hexG)));

            Assert.Equal(hexGodd, ByteHelpers.ToHex(Generators.G.Negate().ToBytes()));
            Assert.Equal(Generators.G.Negate(), GroupElement.FromBytes(ByteHelpers.FromHex(hexGodd)));
        }
Exemplo n.º 22
0
        public void CanEncodeDecodeBlinding()
        {
            var key = new BlindingRsaKey();

            byte[] message     = Encoding.UTF8.GetBytes("áéóúősing me please~!@#$%^&*())_+");
            byte[] blindedData = key.PubKey.Blind(message).BlindedData;
            string encoded     = ByteHelpers.ToHex(blindedData);

            byte[] decoded = ByteHelpers.FromHex(encoded);
            Assert.Equal(blindedData, decoded);
        }
        public void FromHex(string hex)
        {
            hex = Guard.NotNullOrEmptyOrWhitespace(nameof(hex), hex, true);

            byte[] bytes = ByteHelpers.FromHex(hex);
            if (bytes.Length != 1)
            {
                throw new FormatException($"{nameof(hex)} must be exactly one byte. Actual: {bytes.Length} bytes. Value: {hex}.");
            }

            ByteValue = bytes[0];
        }
        /// <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 fp = new HDFingerprint(ByteHelpers.FromHex(s));

            return(fp);
        }
    public async Task SafeCookieAuthenticationAsync()
    {
        using CancellationTokenSource timeoutCts = new(TimeSpan.FromMinutes(2));

        // Setup.
        string cookieString = "200339DD9897265DF859C6578DFB51E2E867AA8966C9112349262F5398DEFC3D";
        string clientNonce  = "6F14C18D5B00BF54E16E4728A4BFC81B1FF469F0B012CD71D9724BFBE14DB5E6";
        string serverHash   = "E3C00FB4A14AF48B43CE8A13E4BB01F8C72796352072B1994EE21D35148931C1";
        string serverNonce  = "1650507A46A2979974DA72A833523B72789A65F6E24EAA59C5DF1D3DC294228D";

        Mock <IRandom> mockRandom = new(MockBehavior.Strict);

        mockRandom.Setup(c => c.GetBytes(It.IsAny <byte[]>()))
        .Callback((byte[] dest) => Array.Copy(sourceArray: ByteHelpers.FromHex(clientNonce), dest, 32));

        TorControlClientFactory clientFactory = new(mockRandom.Object);

        Pipe toServer = new();
        Pipe toClient = new();

        await using TorControlClient testClient = new(pipeReader : toClient.Reader, pipeWriter : toServer.Writer);

        Logger.LogTrace("Client: Start authentication task.");
        Task <TorControlClient> authenticationTask = clientFactory.AuthSafeCookieOrThrowAsync(testClient, cookieString, timeoutCts.Token);

        Logger.LogTrace("Server: Read 'AUTHCHALLENGE SAFECOOKIE' command from the client.");
        string authChallengeCommand = await toServer.Reader.ReadLineAsync(timeoutCts.Token);

        Logger.LogTrace($"Server: Received AUTHCHALLENGE line: '{authChallengeCommand}'.");
        Assert.Equal("AUTHCHALLENGE SAFECOOKIE 6F14C18D5B00BF54E16E4728A4BFC81B1FF469F0B012CD71D9724BFBE14DB5E6", authChallengeCommand);

        Logger.LogTrace("Server: Respond to client's AUTHCHALLENGE request.");
        string challengeResponse = $"250 AUTHCHALLENGE SERVERHASH={serverHash} SERVERNONCE={serverNonce}\r\n";
        await toClient.Writer.WriteAsciiAndFlushAsync(challengeResponse, timeoutCts.Token);

        Logger.LogTrace("Server: Read 'AUTHENTICATE' command from the client.");
        string authCommand = await toServer.Reader.ReadLineAsync(timeoutCts.Token);

        Logger.LogTrace($"Server: Received auth line: '{authCommand}'.");
        Assert.Equal("AUTHENTICATE 6013EA09D4E36B6CF01C18A707D350C1B5AFF8C1A21527266B9FC40C89BDCB4A", authCommand);

        Logger.LogTrace("Server: Respond to the client's AUTHENTICATION request.");
        await toClient.Writer.WriteAsciiAndFlushAsync("250 OK\r\n", timeoutCts.Token);

        Logger.LogTrace("Client: Verify the authentication task finishes correctly.");
        TorControlClient authenticatedClient = await authenticationTask;

        Assert.NotNull(authenticatedClient);
    }
        /// <inheritdoc />
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var       s = (string)reader.Value;
            ExtPubKey epk;

            try
            {
                epk = ExtPubKey.Parse(s);
            }
            catch
            {
                // Try hex, Old wallet format was like this.
                epk = new ExtPubKey(ByteHelpers.FromHex(s));
            }
            return(epk);
        }
Exemplo n.º 27
0
        public void BasicTest()
        {
            Network testNet = Network.TestNet;
            BitcoinEncryptedSecretNoEC encryptedSecret = new(wif : "6PYJxoa2SLZdYADFyMp3wo41RKaKGNedC3vviix4VdjFfrt1LkKDmXmYTM", Network.Main);

            byte[]? chainCode = ByteHelpers.FromHex("D9DAD5377AB84A44815403FF57B0ABC6825701560DAA0F0FCDDB5A52EBE12A6E");
            ExtKey        accountPrivateKey = new(encryptedSecret.GetKey(password: "******"), chainCode);
            KeyPath       keyPath           = new("84'/0'/0'");
            HDFingerprint masterFingerprint = new(0x2fc4a4f3);

            WpkhDescriptors descriptors = WpkhOutputDescriptorHelper.GetOutputDescriptors(testNet, masterFingerprint, accountPrivateKey, keyPath);

            Assert.Equal("wpkh([f3a4c42f/84'/0'/0']tpubDDPaZ82MfnPUigb426fCAEvJnVT7AJgQLmxptzh9oyH59dGJYzsqkqvgj6SyY9eBHhFmG286cfj66Dzv1kYAnC3o7LRxohvo7mwWPr26uje/1/*)#z2666dqc", descriptors.PublicInternal.ToString());
            Assert.Equal("wpkh([f3a4c42f/84'/0'/0']tpubDDPaZ82MfnPUigb426fCAEvJnVT7AJgQLmxptzh9oyH59dGJYzsqkqvgj6SyY9eBHhFmG286cfj66Dzv1kYAnC3o7LRxohvo7mwWPr26uje/0/*)#n7lm8csq", descriptors.PublicExternal.ToString());
            Assert.Equal("wpkh([f3a4c42f/84'/0'/0']tprv8ghYQhz7XQhoqDZG8SzbkqGCDTwAzyVVmUN3cUerPhUgK91Xvc4FaMJpYwrjuQ48WD7KdQ7Y6znKnaY9PXP8SiDLv1srjjs8NVYGuM7Hrrk/1/*)#ktc4yfd7", descriptors.PrivateInternal);
            Assert.Equal("wpkh([f3a4c42f/84'/0'/0']tprv8ghYQhz7XQhoqDZG8SzbkqGCDTwAzyVVmUN3cUerPhUgK91Xvc4FaMJpYwrjuQ48WD7KdQ7Y6znKnaY9PXP8SiDLv1srjjs8NVYGuM7Hrrk/0/*)#8la5euax", descriptors.PrivateExternal);
        }
Exemplo n.º 28
0
        public void DeserializationThrows()
        {
            Assert.ThrowsAny <ArgumentException>(() => GroupElement.FromBytes(Array.Empty <byte>()));
            Assert.ThrowsAny <ArgumentException>(() => GroupElement.FromBytes(new byte[] { 0 }));
            Assert.ThrowsAny <ArgumentException>(() => GroupElement.FromBytes(new byte[] { 1 }));
            Assert.ThrowsAny <ArgumentException>(() => GroupElement.FromBytes(new byte[] { 0, 1 }));
            Assert.ThrowsAny <ArgumentException>(() => GroupElement.FromBytes(new byte[] { 0, 1 }));

            Assert.ThrowsAny <ArgumentException>(() => GroupElement.FromBytes(FillByteArray(length: 32, character: 0)));
            Assert.ThrowsAny <ArgumentException>(() => GroupElement.FromBytes(FillByteArray(length: 63, character: 0)));
            var infinity = GroupElement.FromBytes(FillByteArray(length: 33, character: 0));

            Assert.True(infinity.IsInfinity);
            Assert.ThrowsAny <ArgumentException>(() => GroupElement.FromBytes(FillByteArray(length: 64, character: 1)));
            Assert.ThrowsAny <ArgumentException>(() => GroupElement.FromBytes(FillByteArray(length: 64, character: 2)));
            Assert.ThrowsAny <ArgumentException>(() => GroupElement.FromBytes(FillByteArray(length: 65, character: 0)));

            Assert.ThrowsAny <ArgumentException>(() => GroupElement.FromBytes(ByteHelpers.FromHex("100000000000000000000000000000000000000000000000000000000000000000")));
        }
Exemplo n.º 29
0
    private static KeyManager GetKeyManagerByColdcardJson(WalletManager manager, JObject jsonWallet, string walletFullPath)
    {
        var xpubString = jsonWallet["ExtPubKey"]?.ToString()
                         ?? throw new ArgumentNullException($"Can't get KeyManager, ExtPubKey was null.");

        var mfpString = jsonWallet["MasterFingerprint"]?.ToString()
                        ?? throw new ArgumentNullException($"Can't get KeyManager, MasterFingerprint was null.");

        // 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 = jsonWallet["ColdCardFirmwareVersion"]?.ToString();
        var reverseByteOrder      = false;

        if (coldCardVersionString is null)
        {
            reverseByteOrder = true;
        }
        else
        {
            Version coldCardVersion = new(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);

        if (manager.WalletExists(mfp))
        {
            throw new InvalidOperationException(WalletExistsErrorMessage);
        }

        ExtPubKey extPubKey = NBitcoinHelpers.BetterParseExtPubKey(xpubString);

        return(KeyManager.CreateNewHardwareWalletWatchOnly(mfp, extPubKey, manager.Network, walletFullPath));
    }
Exemplo n.º 30
0
        public static bool CheckExpectedHash(string filePath, string sourceFolderPath)
        {
            var fileHash = GetHashFile(filePath);

            try
            {
                var digests = File.ReadAllLines(Path.Combine(sourceFolderPath, "digests.txt"));
                foreach (var digest in digests)
                {
                    var expectedHash = ByteHelpers.FromHex(digest);
                    if (ByteHelpers.CompareFastUnsafe(fileHash, expectedHash))
                    {
                        return(true);
                    }
                }
                return(false);
            }
            catch
            {
                return(false);
            }
        }