aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/handler.ts
blob: baca442d459b51d52ee95742bb2ecae29c49131f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
import { goto } from "$app/navigation";
import { applyAction } from "$app/forms";

export default (toggle) => () => {
	toggle();
	return async ({ result }) => {
		if (result.type === "redirect") {
			goto(result.location);
		} else {
			await applyAction(result);
		}
	};
};
0 -0700 committer Adam Soltys <[email protected]> 2021-08-04 08:16:43 -0700 config update, lnd support' href='/coinos-server.git/commit/routes/payments.js?h=dChanges&id=ea2c9ed23c2b80f4a6200ee19fb4a6c77c3ccb95'>ea2c9ed2 ^
f89b0ffd ^
3c0e2459 ^




ea2c9ed2 ^

3c0e2459 ^
f89b0ffd ^
3c0e2459 ^





7c1f6e8c ^
7a3a07bc ^

ea2c9ed2 ^
7a3a07bc ^
ea2c9ed2 ^
0fb703b8 ^
8ff48ddf ^
fd44b77a ^













18814242 ^

fd44b77a ^











18814242 ^
fd44b77a ^




18814242 ^
fd44b77a ^























18814242 ^


fd44b77a ^








ffee4c70 ^


ea2c9ed2 ^

ffee4c70 ^
ea2c9ed2 ^
ffee4c70 ^
8ff48ddf ^



ffee4c70 ^


ea2c9ed2 ^
ffee4c70 ^

20273701 ^
ffee4c70 ^
ea2c9ed2 ^
e53fea3b ^
ffee4c70 ^



ea2c9ed2 ^
ffee4c70 ^






6fe6c1b9 ^


8ff48ddf ^

fd44b77a ^
8ff48ddf ^
a22b5cd3 ^
2f0f9e64 ^

b45deffe ^

c5374c59 ^
b45deffe ^
f2dad8ba ^
ea2c9ed2 ^















b45deffe ^
c0888fab ^
9a23c64e ^
ffee4c70 ^



2bcd5e9c ^
b45deffe ^






7ab3036c ^




3e93f327 ^
2b59255e ^
b45deffe ^


a90d6cc9 ^

c5374c59 ^







a90d6cc9 ^
b45deffe ^
c0888fab ^
b45deffe ^

3ce9c73b ^
3c0e2459 ^
6388e2b9 ^


a7168a10 ^
b45deffe ^
a90d6cc9 ^

c5374c59 ^





ea2c9ed2 ^
c5374c59 ^
a90d6cc9 ^
b45deffe ^
c0888fab ^
ffee4c70 ^


99d71f03 ^
ffee4c70 ^

3c0e2459 ^
ffee4c70 ^



3c0e2459 ^

ffee4c70 ^
c0888fab ^
ffee4c70 ^


99d71f03 ^




f89b0ffd ^


3c0e2459 ^
f89b0ffd ^


3c0e2459 ^

f89b0ffd ^





99d71f03 ^
f89b0ffd ^
99d71f03 ^

f89b0ffd ^
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
                                                     
                                    
                                 

                                    
                                                 
 
                

                 
              
                 
 

                        
                                                                           



                                                       
       











                                                                            
                   
   
 




                                               

                  
       
 





                                                       
 

                              
                          
      
                     
 
                              













                                                                          

                                                 











                                                                              
                                                                




                                              
         























                                                 


                                   








                                                          


                                

                      
        
                       
 



                                                


                
             

                                      
                                       
       
                  
                                                            



                           
                            






                                                                         


                                                                  

    
                           
                              
 

                                             

                                
                                                         
            
                                        















                                                                               
     
 
                                                                   



                                           
                                                                   






                                                                     




                                    
                                                                      
                                                                 


                                                               

                            







                                                                        
           
   
 

                                        
                                        
                                                                               


                                                                    
                                                      
                                

                            





                                                                        
                                                                  
       
           
   
 


                
                            

                                                 
                                         



                                

                       
         
 


                         




                            


                                                
                      


                              

                         





                                           
                                        
       

      
     
const BitcoinCore = require("@asoltys/bitcoin-core");
const { Op } = require("sequelize");
const { join } = require("path");
const fs = require("fs");
const read = require("../lib/read");
const { differenceInDays } = require("date-fns");

ah(async () => {
  seen = [];
  addresses = {};
  change = [];
  issuances = {};

  const exceptions = [];
  try {
    read(fs.createReadStream("exceptions"), data => exceptions.push(data));
  } catch (e) {
    l.warn("couldn't read exceptions file", e.message);
  }

  try {
    (
      await db.Invoice.findAll({
        include: {
          model: db.User,
          as: "user"
        }
      })
    ).map(({ address, user, unconfidential }) => {
      if (address && user) addresses[address] = user.username;
      if (unconfidential && user) addresses[unconfidential] = user.username;
    });
  } catch (e) {
    console.log(e);
  }

  try {
    const accounts = await db.Account.findAll({
      where: { pubkey: { [Op.ne]: null } },
      include: {
        model: db.User,
        as: "user"
      }
    });

    accounts.map(({ address, user: { username } }) => {
      addresses[address] = username;
    });
  } catch (e) {
    console.log(e);
  }

  payments = (
    await db.Payment.findAll({
      attributes: ["hash"]
    })
  ).map(p => p.hash);

  const sanity = async () => {
    let { invoices } = await lnp.listInvoices({
      reversed: true,
      num_max_invoices: 1000
    });

    let recent = invoices
      .filter(
        i =>
          i.settled &&
          differenceInDays(new Date(), new Date(i.settle_date * 1000)) < 2
      )
      .map(i => ({
        amount: parseInt(i.amt_paid_sat),
        preimage: i.r_preimage.toString("hex"),
        pr: i.payment_request.toString("hex"),
        createdAt: new Date(i.settle_date * 1000)
      }));

    const twoDaysAgo = new Date(new Date().setDate(new Date().getDate() - 2));
    let settled = (
      await db.Payment.findAll({
        where: { network: "lightning", createdAt: { [Op.gt]: twoDaysAgo } },
        attributes: ["preimage"]
      })
    ).map(p => p.preimage);

    let missed = recent.filter(i => !settled.includes(i.preimage));
    for (let i = 0; i < missed.length; i++) {
      let { amount, preimage, pr: text, createdAt } = missed[i];
      let invoice = await db.Invoice.findOne({
        where: { text },
        include: {
          model: db.User,
          as: "user"
        }
      });

      if (invoice && invoice.user_id) {
        let account = await db.Account.findOne({
          where: {
            user_id: invoice.user_id,
            asset: config.liquid.btcasset,
            pubkey: null
          }
        });

        if (account) {
          let payment = await db.Payment.create({
            account_id: account.id,
            user_id: invoice.user_id,
            hash: text,
            amount,
            currency: invoice.currency,
            preimage,
            rate: invoice.rate,
            received: true,
            confirmed: true,
            network: "lightning",
            tip: invoice.tip,
            invoice_id: invoice.id,
            createdAt,
            updatedAt: createdAt
          });

          await account.increment({ balance: amount });

          l.info("rectified account", account.id, amount);
        }
      }
    }

    const unconfirmed = (
      await db.Payment.findAll({
        where: {
          confirmed: 0
        }
      })
    ).map(p => p.hash);

    const transactions = [
      ...(await bc.listTransactions("*", 1000)),
      ...(await lq.listTransactions("*", 1000))
    ];

    transactions
      .filter(
        tx =>
          tx.category === "receive" &&
          tx.confirmations > 0 &&
          unconfirmed.includes(tx.txid)
      )
      .map(tx => {
        l.warn("tx unconfirmed in db", tx.txid, tx.address);
      });

    const unaccounted = [];

    transactions.map(tx => {
      if (!payments.includes(tx.txid) && !exceptions.includes(tx.txid)) {
        unaccounted.push(tx.txid);
      }
    });

    if (unaccounted.length)
      l.warn("wallet transactions missing from database", unaccounted);

    // let s = fs.createWriteStream("exceptions", { flags: "a" });
    // unaccounted.map(tx => s.write(tx + "\n"));
  };

  setTimeout(sanity, 5000);
  setInterval(sanity, 720000);

  app.post("/send", auth, require("./send"));

  if (config.lna) {
    if (config.lna.clightning) {
      lna = require("clightning-client")(config.lna.dir);
    } else {
      const lnd = require("../lib/lnd");
      lna = lnd.default;
      lnp = [
        "addInvoice",
        "channelBalance",
        "connectPeer",
        "decodePayReq",
        "getInfo",
        "listInvoices",
        "listPayments",
        "sendPaymentSync",
        "walletBalance"
      ].reduce(
        (a, b) =>
          (a[b] = args => new Promise(r => lna[b](args, (e, v) => r(v)))) && a,
        {}
      );
    }

    app.post("/lightning/channel", require("./lightning/channel"));
    app.post(
      "/lightning/channelRequest",
      require("./lightning/channelRequest")
    );
    app.post("/lightning/invoice", require("./lightning/invoice"));
    app.post("/lightning/query", auth, require("./lightning/query"));
    app.post("/lightning/send", auth, require("./lightning/send"));
    require("./lightning/receive");
  }

  if (config.bitcoin) {
    bc = new BitcoinCore(config.bitcoin);
    app.post(
      "/bitcoin/broadcast",
      optionalAuth,
      require("./bitcoin/broadcast")
    );
    app.get("/bitcoin/generate", auth, require("./bitcoin/generate"));
    app.post("/bitcoin/sweep", auth, require("./bitcoin/sweep"));
    app.post("/bitcoin/fee", auth, require("./bitcoin/fee"));
    app.post("/bitcoin/send", auth, require("./bitcoin/send"));
    require("./bitcoin/receive");

    setTimeout(async () => {
      try {
        const address = await bc.getNewAddress();
        const { hdkeypath } = await bc.getAddressInfo(address);
        const parts = hdkeypath.split("/");
        app.set("bcAddressIndex", parts[parts.length - 1].slice(0, -1));
      } catch (e) {
        console.error(e);
      }
    }, 50);
  }

  if (config.liquid) {
    lq = new BitcoinCore(config.liquid);
    rare = new BitcoinCore(config.rare);
    app.post("/liquid/broadcast", optionalAuth, require("./liquid/broadcast"));
    app.get("/liquid/generate", auth, require("./liquid/generate"));
    app.post("/liquid/fee", auth, require("./liquid/fee"));
    app.post("/liquid/send", auth, require("./liquid/send"));
    app.post("/taxi", auth, require("./liquid/taxi"));
    require("./liquid/receive");

    setTimeout(async () => {
      try {
        const address = await lq.getNewAddress();
        const { hdkeypath } = await lq.getAddressInfo(address);
        const parts = hdkeypath.split("/");
        app.set("lqAddressIndex", parts[parts.length - 1].slice(0, -1));
      } catch (e) {
        l.warn("Problem getting liquid address index", e.message);
      }
    }, 50);
  }

  app.get(
    "/payments",
    auth,
    ah(async (req, res) => {
      let payments = await req.user.getPayments({
        where: {
          account_id: req.user.account_id
        },
        order: [["id", "DESC"]],
        include: {
          model: db.Account,
          as: "account"
        }
      });

      res.send(payments);
    })
  );

  app.get(
    "/payment/:redeemcode",
    ah(async (req, res) => {
      try {
        const { redeemcode } = req.params;
        let payment = await db.Payment.findOne({
          where: {
            redeemcode
          },
          include: {
            model: db.Account,
            as: "account"
          }
        });

        if (!payment) fail("invalid code");

        res.send(payment);
      } catch (e) {
        res.status(500).send(e.message);
      }
    })
  );
})();