aboutsummaryrefslogtreecommitdiffstats
path: root/lib/ln.js
diff options
context:
space:
mode:
Diffstat (limited to 'lib/ln.js')
0 files changed, 0 insertions, 0 deletions
itle='author Adam Soltys <[email protected]> 2025-02-26 11:59:58 -0800 committer Adam Soltys <[email protected]> 2025-02-26 11:59:58 -0800 payment types' href='/coinos-server.git/commit/lib/lightning.ts?h=staging&id=1d541fd97210389f006e65d46ab783afbe82cea8'>1d541fd9 ^
1ebc40af ^
1d541fd9 ^
bbdae132 ^
46913d34 ^
9089698e ^



cc0e94b7 ^
9089698e ^




46913d34 ^
9089698e ^
46913d34 ^

9089698e ^

46913d34 ^
9089698e ^










46913d34 ^
9089698e ^
0a8a8988 ^
9089698e ^



























ad7b09b4 ^
9662c275 ^
a7322928 ^
9089698e ^











a7322928 ^
9089698e ^



a7322928 ^
ad7b09b4 ^
9089698e ^









ad7b09b4 ^
9089698e ^










ad7b09b4 ^
9089698e ^

46913d34 ^
46913d34 ^
47236bc1 ^
703564c4 ^
9089698e ^
47236bc1 ^


703564c4 ^
47236bc1 ^
47236bc1 ^

a574e774 ^
47236bc1 ^


47236bc1 ^



8c7fa95d ^
47236bc1 ^

8c7fa95d ^
0a8a8988 ^

47236bc1 ^

9662c275 ^



47236bc1 ^
ad7b09b4 ^
47236bc1 ^


8c7fa95d ^
703564c4 ^
47236bc1 ^


1d541fd9 ^
a574e774 ^
47236bc1 ^
8c7fa95d ^

47236bc1 ^




cc0e94b7 ^
a1632ae4 ^
526b21bc ^
cc0e94b7 ^









1ebc40af ^

cc0e94b7 ^



a1632ae4 ^
cc0e94b7 ^
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
                                         

                                                                  
                                       
                                       
                                                   
                                         
                                                             
 



                                               
 




                                                                        
 
                        

       

                                                                         
 










                                                        
 
                                    
 



























                                                                              
                                                                                         
         
       











                                                                  
     



                                                       
 
                                                                                                   









                                                                              
                                    










                                                                               
                                             

                                                         
   
 
 
                                     
                                                       


                   
           
                

                               
            


                                                           



                          
                                                                         

                                                                            
                                               

                                                              

                        



                                                        
                   
                                                                                       


       
                      
                             


                         
                                                                
                                                    
       

             




                                                          
 
                                       
                                            









                                                                        

                                                    



       
                    
  
import { db, g, s, scan } from "$lib/db";
import ln, { lnListen, LightningUnavailableError } from "$lib/ln";
import { err, l, warn } from "$lib/logging";
import { handleZap } from "$lib/nostr";
import { credit } from "$lib/payments";
import { tbSetBalance, getBalance } from "$lib/tb";
import { PaymentType } from "$lib/types";
import { getInvoice, getPayment, getUser } from "$lib/utils";

const LISTENER_RETRY_DELAY = 5000; // 5 seconds
const MAX_LISTENER_RETRIES = 10;
let listenerRetries = 0;
let listenerActive = false;

export async function listenForLightning() {
  if (listenerActive) {
    warn("lightning listener: already active, skipping duplicate call");
    return;
  }

  listenerActive = true;

  try {
    const payIndex = (await g("pay_index")) || 0;
    l(`lightning listener: waiting for invoice (pay_index=${payIndex})`);

    const inv = await lnListen.waitanyinvoice(payIndex);
    const {
      local_offer_id,
      bolt11,
      bolt12,
      description,
      pay_index,
      payment_hash,
      amount_received_msat,
      payment_preimage: preimage,
    } = inv;

    await s("pay_index", pay_index);

    // Reset retry counter on successful receive
    if (listenerRetries > 0) {
      l(`lightning listener: recovered after ${listenerRetries} retries`);
    }
    listenerRetries = 0;
    listenerActive = false;

    // Schedule next listen
    setTimeout(listenForLightning);

    const received = Math.round(amount_received_msat / 1000);

    try {
      if (!preimage) return;

      const invoice = await getInvoice(bolt11 ?? local_offer_id ?? bolt12);
      if (!invoice) return warn("received lightning with no invoice", bolt11);

      const p = await getPayment(bolt11 || bolt12);
      if (p) return warn("already processed", bolt11 || bolt12);

      if (invoice?.memo) {
        try {
          if (JSON.parse(description).kind === 9734) {
            const { pubkey } = await getUser(invoice.uid);
            handleZap(inv, pubkey);
          }
        } catch (e) {
          if (!e.message.includes("Unexpected")) warn("failed to handle zap", e.message);
        }
      }

      await credit({
        hash: bolt11 || bolt12,
        amount: received,
        memo: invoice.memo,
        ref: preimage,
        type: bolt12 ? PaymentType.bolt12 : PaymentType.lightning,
        payment_hash,
      });
    } catch (e) {
      console.log(e);
      err("problem receiving lightning payment", e.message);
    }
  } catch (e: any) {
    listenerActive = false;
    const errorCode = e?.code ?? e?.errno ?? "unknown";
    const errorMsg = e?.message ?? String(e);

    err(`lightning listener: error waiting for invoice`, `code=${errorCode}`, `error=${errorMsg}`);

    if (e instanceof LightningUnavailableError) {
      err("lightning listener: RPC socket unavailable");
    }

    listenerRetries++;

    if (listenerRetries >= MAX_LISTENER_RETRIES) {
      err(
        `lightning listener: ${MAX_LISTENER_RETRIES} consecutive failures, ` +
          `last error: ${errorMsg}`,
      );
      err("lightning listener: exiting process to trigger container restart");

      setTimeout(() => {
        process.exit(1);
      }, 1000);
      return;
    }

    warn(
      `lightning listener: retry ${listenerRetries}/${MAX_LISTENER_RETRIES} ` +
        `in ${LISTENER_RETRY_DELAY / 1000}s`,
    );
    setTimeout(listenForLightning, LISTENER_RETRY_DELAY);
  }
}

export async function replay(index) {
  const inv = await lnListen.waitanyinvoice(index - 1);
  const {
    local_offer_id,
    bolt11,
    bolt12,
    description,
    amount_received_msat,
    payment_preimage: preimage,
    paid_at,
  } = inv;

  const received = Math.round(amount_received_msat / 1000);

  try {
    if (!preimage) return;

    const invoice = await getInvoice(bolt11 ?? local_offer_id ?? bolt12);
    if (!invoice) return warn("received lightning with no invoice", bolt11);

    let p = await getPayment(bolt11 || bolt12);
    if (p) return warn("already processed", bolt11 || bolt12);

    if (invoice?.memo) {
      try {
        if (JSON.parse(description).kind === 9734) {
          const { pubkey } = await getUser(invoice.uid);
          handleZap(inv, pubkey);
        }
      } catch (e) {
        if (!e.message.includes("Unexpected")) warn("failed to handle zap", e.message);
      }
    }

    p = await credit({
      hash: bolt11 || bolt12,
      amount: received,
      memo: invoice.memo,
      ref: preimage,
      type: bolt12 ? PaymentType.bolt12 : PaymentType.lightning,
      created: paid_at ? paid_at * 1000 : undefined,
    });

    return p;
  } catch (e) {
    console.log(e);
    err("problem receiving lightning payment", e.message);
  }
}

export const fixBolt12 = async (c) => {
  for await (const k of scan("payment:*")) {
    const p = await g(k);
    if (p.type === "bolt12") {
      console.log(k);
      const { invoices } = await ln.listinvoices({ invstring: p.hash });
      const { local_offer_id } = invoices[0];
      const oid = await g(`payment:${local_offer_id}`);
      const op = await g(`payment:${oid}`);
      if (op) {
        db.del(`payment:${oid}`);
        db.del(`payment:${local_offer_id}`);
        const bal = await getBalance(op.uid);
        await tbSetBalance(op.uid, bal - op.amount);
      }
    }
  }

  return c.json({});
};