<commit_before>﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NBitcoin;

namespace BTCPayServer.Payments.Lightning.Lnd
{
    public class LndClient : ILightningInvoiceClient, ILightningListenInvoiceSession
    {
        public LndClient(Uri uri, Network network, byte[] tlsCertificate, byte[] grpcMacaroon)
        {
            _HttpClient = HttpClientFactoryForLnd.Generate(tlsCertificate, grpcMacaroon);
            _Decorator = new LndSwaggerClient(uri.ToString().TrimEnd('/'), _HttpClient);
        }

        private HttpClient _HttpClient;
        private LndSwaggerClient _Decorator;

        public async Task<LightningInvoice> CreateInvoice(LightMoney amount, string description, TimeSpan expiry, CancellationToken cancellation = default(CancellationToken))
        {
            var resp = await _Decorator.AddInvoiceAsync(new LnrpcInvoice
            {
                Value = (long)amount.ToDecimal(LightMoneyUnit.Satoshi),
                Memo = description,
                Expiry = (long)expiry.TotalSeconds
            });
            throw new NotImplementedException();
        }

        public async Task<LightningNodeInformation> GetInfo(CancellationToken cancellation = default(CancellationToken))
        {
            var resp = await _Decorator.GetInfoAsync(cancellation);

            var invoice = new LightningNodeInformation
            {
                Address = resp.Uris?.FirstOrDefault(),
                BlockHeight = (int?)resp.Block_height ?? 0,
                NodeId = resp.Alias,
                P2PPort = 0
            };
            return invoice;
        }

        public async Task<LightningInvoice> GetInvoice(string invoiceId, CancellationToken cancellation = default(CancellationToken))
        {
            // var resp = await _decorator.LookupInvoiceAsync(invoiceId, null, cancellation);
            throw new NotImplementedException();
        }

        public Task<ILightningListenInvoiceSession> Listen(CancellationToken cancellation = default(CancellationToken))
        {
            return Task.FromResult<ILightningListenInvoiceSession>(this);
        }

        async Task<LightningInvoice> ILightningListenInvoiceSession.WaitInvoice(CancellationToken cancellation)
        {
            //var resp = await _decorator.SubscribeInvoicesAsync(cancellation);
            throw new NotImplementedException();
        }

        public void Dispose()
        {
            _HttpClient?.Dispose();
        }
    }<commit_msg>Conversion of LnrpcInvoice into LightningInvoice<commit_after>﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NBitcoin;

namespace BTCPayServer.Payments.Lightning.Lnd
{
    public class LndClient : ILightningInvoiceClient, ILightningListenInvoiceSession
    {
        public LndClient(Uri uri, Network network, byte[] tlsCertificate, byte[] grpcMacaroon)
        {
            _HttpClient = HttpClientFactoryForLnd.Generate(tlsCertificate, grpcMacaroon);
            _Decorator = new LndSwaggerClient(uri.ToString().TrimEnd('/'), _HttpClient);
        }

        private HttpClient _HttpClient;
        private LndSwaggerClient _Decorator;

        public async Task<LightningInvoice> CreateInvoice(LightMoney amount, string description, TimeSpan expiry, CancellationToken cancellation = default(CancellationToken))
        {
            var resp = await _Decorator.AddInvoiceAsync(new LnrpcInvoice
            {
                Value = (long)amount.ToDecimal(LightMoneyUnit.Satoshi),
                Memo = description,
                Expiry = (long)expiry.TotalSeconds
            });

            var invoice = new LightningInvoice
            {
                // TODO: Verify id corresponds to R_hash
                Id = BitString(resp.R_hash),
                Amount = amount,
                BOLT11 = resp.Payment_request,
                Status = "unpaid"
            };
            return invoice;
        }

        public async Task<LightningNodeInformation> GetInfo(CancellationToken cancellation = default(CancellationToken))
        {
            var resp = await _Decorator.GetInfoAsync(cancellation);

            var invoice = new LightningNodeInformation
            {
                Address = resp.Uris?.FirstOrDefault(),
                BlockHeight = (int?)resp.Block_height ?? 0,
                NodeId = resp.Alias,
                P2PPort = 0
            };
            return invoice;
        }

        public async Task<LightningInvoice> GetInvoice(string invoiceId, CancellationToken cancellation = default(CancellationToken))
        {
            var resp = await _Decorator.LookupInvoiceAsync(invoiceId, null, cancellation);
            return ConvertLndInvoice(resp);
        }

        public Task<ILightningListenInvoiceSession> Listen(CancellationToken cancellation = default(CancellationToken))
        {
            return Task.FromResult<ILightningListenInvoiceSession>(this);
        }

        async Task<LightningInvoice> ILightningListenInvoiceSession.WaitInvoice(CancellationToken cancellation)
        {
            var resp = await _Decorator.SubscribeInvoicesAsync(cancellation);
            return ConvertLndInvoice(resp);

        }

        public void Dispose()
        {
            _HttpClient?.Dispose();
        }

        private static string BitString(byte[] bytes)
        {
            return BitConverter.ToString(bytes)
                .Replace("-", "", StringComparison.InvariantCulture)
                .ToLower(CultureInfo.InvariantCulture);
        }

        private static LightningInvoice ConvertLndInvoice(LnrpcInvoice resp)
        {
            var invoice = new LightningInvoice
            {
                // TODO: Verify id corresponds to R_hash
                Id = BitString(resp.R_hash),
                Amount = resp.Value,
                BOLT11 = resp.Payment_request,
                Status = "unpaid"
            };

            if (resp.Settle_date.HasValue)
            {
                invoice.PaidAt = DateTimeOffset.FromUnixTimeSeconds(resp.Settle_date.Value);
                invoice.Status = "paid";
            }
            else if (DateTimeOffset.FromUnixTimeSeconds(resp.Creation_date.Value + resp.Expiry.Value) > DateTimeOffset.UtcNow)
            {
                invoice.Status = "expired";
            }
            return invoice;
        }
    }
{'fraction_non_alphanumeric': 0.07713379469434833, 'fraction_numerical': 0.002306805074971165, 'mean_word_length': 2.319138755980861, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1683961', 'n_tokens_mistral': 1825, 'n_tokens_neox': 1774, 'n_words': 359}