-
Notifications
You must be signed in to change notification settings - Fork 3
/
crud.py
218 lines (196 loc) · 6.13 KB
/
crud.py
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
import time
from typing import List, Optional
from lnbits.db import Database
from .execution_queue import enqueue
from .models import NWCBudget, NWCKey, NWCNewBudget
db = Database("ext_nwcprovider")
async def create_nwc(
pubkey: str,
wallet_id: str,
description: str,
expires_at: int,
permissions: List[str],
budgets: Optional[List[NWCNewBudget]] = None,
) -> NWCKey:
# Check if the key already exists
if await get_nwc(pubkey, None, True):
raise Exception("Public key already used")
# If not, create it
now = int(time.time())
await db.execute(
"""
INSERT INTO nwcprovider.keys (
pubkey,
wallet,
description,
permissions,
created_at,
expires_at,
last_used
)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(
pubkey,
wallet_id,
description,
" ".join(permissions),
now,
int(expires_at) if expires_at else 0,
now,
),
)
# Add budgets
if budgets:
for budget in budgets:
await db.execute(
"""
INSERT INTO nwcprovider.budgets (
pubkey,
budget_msats,
refresh_window,
created_at
)
VALUES (?, ?, ?, ?)
""",
(pubkey, budget.budget_msats, budget.refresh_window, budget.created_at),
)
# Return the created key
return NWCKey(
pubkey=pubkey,
wallet=wallet_id,
description=description,
expires_at=expires_at,
permissions=" ".join(permissions),
created_at=now,
last_used=now,
)
async def delete_nwc(pubkey: str, wallet_id: str):
nwc = await get_nwc(pubkey, wallet_id)
if not nwc:
raise Exception("Public key does not exist")
await db.execute(
"""
DELETE FROM nwcprovider.keys WHERE pubkey = ? AND wallet = ?
""",
(pubkey, wallet_id),
)
async def get_wallet_nwcs(
wallet_id: str, include_expired: Optional[bool] = False
) -> List[NWCKey]:
rows = await db.fetchall(
"""
SELECT * FROM nwcprovider.keys
WHERE wallet = ? AND (expires_at = 0 OR expires_at > ?)
""",
(wallet_id, int(time.time()) if not include_expired else -1),
)
return [NWCKey(**row) for row in rows]
async def get_nwc(
pubkey: str,
wallet_id: Optional[str] = None,
include_expired: Optional[bool] = False,
refresh_last_used: Optional[bool] = False,
) -> Optional[NWCKey]:
# expires_at = 0 means it never expires
if wallet_id:
row = await db.fetchone(
"""
SELECT * FROM nwcprovider.keys
WHERE pubkey = ? AND wallet = ? AND (expires_at = 0 OR expires_at > ?)
""",
(pubkey, wallet_id, int(time.time()) if not include_expired else -1),
)
else:
row = await db.fetchone(
"""
SELECT * FROM nwcprovider.keys
WHERE pubkey = ? AND (expires_at = 0 OR expires_at > ?)
""",
(pubkey, int(time.time()) if not include_expired else -1),
)
if not row:
return None
if refresh_last_used:
await db.execute(
"""
UPDATE nwcprovider.keys SET last_used = ? WHERE pubkey = ?
""",
(int(time.time()), pubkey),
)
return NWCKey(**row)
async def get_budgets_nwc(pubkey, calculate_spent=False):
rows = await db.fetchall(
"SELECT * FROM nwcprovider.budgets WHERE pubkey = ?", (pubkey)
)
budgets = [NWCBudget(**row) for row in rows]
if calculate_spent:
for budget in budgets:
last_cycle, next_cycle = budget.get_timestamp_range()
tot_spent_in_range_msats = await db.fetchone(
"""
SELECT SUM(amount_msats) FROM nwcprovider.spent
WHERE pubkey = ? AND created_at >= ? AND created_at < ?
""",
(pubkey, last_cycle, next_cycle),
)
tot_spent_in_range_msats = tot_spent_in_range_msats[0] or 0
budget.used_budget_msats = tot_spent_in_range_msats
return budgets
async def tracked_spend_nwc(pubkey: str, amount_msats: int, action):
async def r():
created_at = int(time.time())
budgets = await get_budgets_nwc(pubkey)
in_budget = True
for budget in budgets:
last_cycle, next_cycle = budget.get_timestamp_range()
tot_spent_in_range_msats = (
(
await db.fetchone(
"""
SELECT SUM(amount_msats) FROM nwcprovider.spent
WHERE pubkey = ? AND created_at >= ? AND created_at < ?
""",
(pubkey, last_cycle, next_cycle),
)
)[0]
or 0
)
if tot_spent_in_range_msats + amount_msats > budget.budget_msats:
in_budget = False
break
if not in_budget:
return False, None
out = await action()
await db.execute(
"""
INSERT INTO nwcprovider.spent (pubkey, amount_msats, created_at)
VALUES (?, ?, ?)
""",
(pubkey, amount_msats, created_at),
)
return True, out
return await enqueue(r)
async def get_config_nwc(key: str):
row = await db.fetchone("SELECT * FROM nwcprovider.config WHERE key = ?", (key,))
if not row:
return None
return row["value"]
async def get_all_config_nwc():
rows = await db.fetchall("SELECT * FROM nwcprovider.config")
return {row["key"]: row["value"] for row in rows}
async def set_config_nwc(key: str, value: str):
await db.execute(
"""
DELETE FROM nwcprovider.config
WHERE key = ?
""",
(key,),
)
await db.execute(
"""
INSERT INTO nwcprovider.config (key, value)
VALUES (?, ?)
""",
(key, value),
)