forked from SatSale/SatSale
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlnd.py
172 lines (145 loc) · 5.77 KB
/
lnd.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
import subprocess
import time
import os
import json
from base64 import b64decode
from google.protobuf.json_format import MessageToJson
from typing import Tuple
import config
import logging
from node import node
class lnd(node.node):
def __init__(self, node_config: dict) -> None:
from lndgrpc import LNDClient
super().__init__(node_config, False)
# Copy admin macaroon and tls cert to local machine
self._copy_certs()
# Conect to lightning node
connection_str = "{}:{}".format(config.host, self.config['lnd_rpcport'])
logging.info(
"Attempting to connect to lightning node {}. This may take a few seconds...".format(
connection_str
)
)
for i in range(config.connection_attempts):
try:
logging.info("Attempting to initialise lnd rpc client...")
time.sleep(3)
self.lnd = LNDClient(
"{}:{}".format(config.host, self.config['lnd_rpcport']),
macaroon_filepath=self.certs["macaroon"],
cert_filepath=self.certs["tls"],
)
if "invoice" in self.certs["macaroon"]:
logging.info("Testing we can fetch invoices...")
inv, _ = self.create_lnd_invoice(0)
logging.info(inv)
else:
logging.info("Getting lnd info...")
info = self.get_info()
logging.info(info)
logging.info("Successfully contacted lnd.")
break
except Exception as e:
logging.error(e)
if i < 5:
time.sleep(2)
else:
time.sleep(60)
logging.info(
"Attempting again... {}/{}...".format(
i + 1, config.connection_attempts
)
)
else:
raise Exception(
"Could not connect to lnd. Check your gRPC / port tunneling settings and try again."
)
logging.info("Ready for payments requests.")
return
# Copy tls and macaroon certs from remote machine.
def _copy_certs(self) -> None:
self.certs = {"tls": "tls.cert", "macaroon": self.config['lnd_macaroon']}
if (not os.path.isfile("tls.cert")) or (
not os.path.isfile(self.config['lnd_macaroon'])
):
try:
tls_file = os.path.join(self.config['lnd_dir'], "tls.cert")
macaroon_file = os.path.join(
self.config['lnd_dir'],
"data/chain/bitcoin/mainnet/{}".format(self.config['lnd_macaroon']),
)
# SSH copy
if config.tunnel_host is not None:
logging.warning(
"Could not find tls.cert or {} in SatSale folder. \
Attempting to download from remote lnd directory.".format(
self.config['lnd_macaroon']
)
)
subprocess.run(
["scp", "{}:{}".format(config.tunnel_host, tls_file), "."]
)
subprocess.run(
[
"scp",
"-r",
"{}:{}".format(config.tunnel_host, macaroon_file),
".",
]
)
else:
self.certs = {
"tls": os.path.expanduser(tls_file),
"macaroon": os.path.expanduser(macaroon_file),
}
except Exception as e:
logging.error(e)
logging.error("Failed to copy tls and macaroon files to local machine.")
else:
logging.info("Found tls.cert and admin.macaroon.")
return
# Create lightning invoice
def create_lnd_invoice(
self,
btc_amount: float,
memo: str = None,
description_hash: str = None,
expiry: int = 3600,
) -> Tuple[str, str]:
# Multiplying by 10^8 to convert to satoshi units
sats_amount = int(float(btc_amount) * 10 ** 8)
res = self.lnd.add_invoice(
value=sats_amount, memo=memo, description_hash=description_hash, expiry=expiry
)
lnd_invoice = json.loads(MessageToJson(res))
return lnd_invoice["paymentRequest"], lnd_invoice["rHash"]
def get_address(self, amount: float, label: str,
expiry: int) -> Tuple[str, str, str]:
address, r_hash = self.create_lnd_invoice(
amount, memo=label, expiry=expiry)
return None, address, r_hash
def pay_invoice(self, bolt11_invoice: str) -> None:
ret = json.loads(
MessageToJson(self.lnd.send_payment(bolt11_invoice, fee_limit_msat=20 * 1000))
)
logging.info(ret)
return
def get_info(self):
return json.loads(MessageToJson(self.lnd.get_info()))
def get_uri(self) -> str:
info = self.get_info()
return info["uris"][0]
# Check whether the payment has been paid
def check_payment(self, rhash: str) -> Tuple[float, float]:
invoice_status = json.loads(
MessageToJson(self.lnd.lookup_invoice(r_hash_str=b64decode(rhash).hex()))
)
if "amtPaidSat" not in invoice_status.keys():
conf_paid = 0
unconf_paid = 0
else:
# Store amount paid and convert to BTC units
conf_paid = (int(invoice_status["amtPaidSat"]) + 1) / (10 ** 8)
unconf_paid = 0
return conf_paid, unconf_paid