def __init__(self, node_config): from lndgrpc import LNDClient self.config = node_config self.is_onchain = 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(1) 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
def __init__(self, dollar_value, currency, label, test=False): super().__init__(dollar_value, currency, label, test) print(self.__dict__) from lndgrpc import LNDClient # Copy invoice macaroon and tls cert to local machine self.copy_certs() # Conect to lightning node connection_str = "{}:{}".format(config.host, config.lnd_rpcport) print( "Attempting to connect to lightning node {}. This may take a few minutes...".format( connection_str ) ) for i in range(config.connection_attempts): try: print("Attempting to initialise lnd rpc client...") time.sleep(3) self.lnd = LNDClient( "{}:{}".format(config.host, config.lnd_rpcport), macaroon_filepath=self.certs['macaroon'], cert_filepath=self.certs['tls'], ) if test: print("Getting lnd info...") self.lnd.list_invoices() print("Successfully contacted lnd.") break except Exception as e: print(e) time.sleep(config.pollrate) print( "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." ) print("Ready for payments requests.") return
def make_lnd_client(): if app.config['FAKE_INVOICES']: return FakeLNDClient() else: return LNDClient("127.0.0.1:10009", macaroon_filepath=pjoin(AUTH_DIR, 'admin.macaroon'), cert_filepath=pjoin(AUTH_DIR, 'tls.cert'))
class lnd(): def __init__(self): from lndgrpc import LNDClient # Copy invoice macaroon and tls cert to local machine self.copy_certs() # Conect to lightning node connection_str = "{}:{}".format(config.host, config.lnd_rpcport) print( "Attempting to connect to lightning node {}. This may take a few minutes...".format( connection_str ) ) for i in range(config.connection_attempts): try: print("Attempting to initialise lnd rpc client...") time.sleep(3) self.lnd = LNDClient( "{}:{}".format(config.host, config.lnd_rpcport), macaroon_filepath=self.certs['macaroon'], cert_filepath=self.certs['tls'], ) print("Getting lnd info...") self.lnd.list_invoices() print(info) print("Successfully contacted lnd.") break except Exception as e: print(e) time.sleep(config.pollrate) print( "Attempting again... {}/{}...".format( i + 1, config.connection_attempts ) )
class lnd(invoice): def __init__(self, dollar_value, currency, label, test=False): super().__init__(dollar_value, currency, label, test) print(self.__dict__) from lndgrpc import LNDClient # Copy invoice macaroon and tls cert to local machine self.copy_certs() # Conect to lightning node connection_str = "{}:{}".format(config.host, config.lnd_rpcport) print( "Attempting to connect to lightning node {}. This may take a few minutes...".format( connection_str ) ) for i in range(config.connection_attempts): try: print("Attempting to initialise lnd rpc client...") time.sleep(3) self.lnd = LNDClient( "{}:{}".format(config.host, config.lnd_rpcport), macaroon_filepath=self.certs['macaroon'], cert_filepath=self.certs['tls'], ) if test: print("Getting lnd info...") self.lnd.list_invoices() print("Successfully contacted lnd.") break except Exception as e: print(e) time.sleep(config.pollrate) print( "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." ) print("Ready for payments requests.") return # Copy tls and macaroon certs from remote machine. def copy_certs(self): self.certs = {'tls' : config.lnd_cert, 'macaroon' : config.lnd_macaroon} if (not os.path.isfile(config.lnd_cert)) or (not os.path.isfile(config.lnd_macaroon)): try: tls_file = os.path.join(config.lnd_dir, "tls.cert") macaroon_file = os.path.join( config.lnd_dir, "data/chain/bitcoin/mainnet/invoice.macaroon" ) # SSH copy if config.tunnel_host is not None: print( "Could not find {} or {} \ Attempting to download from remote lnd directory.".format( config.lnd_cert, 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: print(e) print("Failed to copy tls and macaroon files to local machine.") else: print("Found tls.cert and invoice.macaroon.") return # Create lightning invoice def create_lnd_invoice(self, btc_amount): # Multiplying by 10^8 to convert to satoshi units sats_amount = int(btc_amount * 10 ** 8) res = self.lnd.add_invoice(value=sats_amount) self.lnd_invoice = json.loads(MessageToJson(res)) self.hash = self.lnd_invoice["r_hash"] print("Created lightning invoice:") print(self.lnd_invoice) return self.lnd_invoice["payment_request"] def get_address(self): self.address = self.create_lnd_invoice(self.value) return # Check whether the payment has been paid def check_payment(self): print("Looking up invoice") invoice_status = json.loads( MessageToJson( self.lnd.lookup_invoice(r_hash_str=b64decode(self.hash).hex()) ) ) if "amt_paid_sat" 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["amt_paid_sat"]) * 10 ** 8 unconf_paid = 0 return conf_paid, unconf_paid
#default power on default for output direction is high. set FIO4 to whatever the relay off logic #requires (and actually reseting if RelayOFF==True just to keep.the logic simpler) #may be able to combine this into one line with the above setting of the output direction? #either way, right now, this seems to be quick enough that the coil doesn't have time to energize. #could use the python command that sets power on defaults in another one time run script/step, #but then that would require an setup step that modifies the device flash memory that would be better to avoid. LabJack.getFeedback(u3.BitStateWrite(4, RelayOFF)) ################################################################ ################################################################ #initialize the LND RPC ################################################################ lnd = LNDClient(LNDhost, network=LNDnetwork, admin=True) ################################################################ ################################################################ #initialize the CAN bus ################################################################ SWCAN = can.interface.Bus( channel=SWCANname, bustype='socketcan', can_filters= [ #only pickup IDs of interest so don't waste time processing tons of unused data { "can_id": 0x3d2, "can_mask": 0x7ff,
from bitcoin import rpc import bitcoin # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ NETWORK = "testnet" bitcoin.SelectParams(NETWORK) BITCOINRPC = rpc.Proxy() LNDRPC = LNDClient("127.0.0.1:10009", network=NETWORK, macaroon_filepath='/home/harshagoli/Limbo/admin.macaroon', cert_filepath='/home/harshagoli/Limbo/tls.cert') # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '#p&o16c**q2t%x19o$_-cj@wvm6yei$x#=x@ld2&s51zaaxq7_' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth',
from pathlib import Path import json from pprint import pprint import os import base64 from time import sleep from datetime import datetime, timedelta # Pip installed Modules from lndgrpc import LNDClient from protobuf_to_dict import protobuf_to_dict credential_path = Path(os.getenv("CRED_PATH")) mac = str(credential_path.joinpath("admin.macaroon").absolute()) tls = str(credential_path.joinpath("tls.cert").absolute()) node_ip = os.getenv("LND_NODE_IP") lnd = LNDClient(f"{node_ip}:10009", macaroon_filepath=mac, cert_filepath=tls) pprint(protobuf_to_dict(lnd.get_info())) print("lndgrpc package is installed... Wow it works!")
class lnd: def __init__(self, node_config): from lndgrpc import LNDClient self.config = node_config self.is_onchain = 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(1) 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 def create_qr(self, uuid, address, value): qr_str = "{}".format(address.upper()) img = qrcode.make(qr_str) img.save("static/qr_codes/{}.png".format(uuid)) return # Copy tls and macaroon certs from remote machine. def copy_certs(self): 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, memo=None, description_hash=None, expiry=3600): # 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, label, expiry): address, r_hash = self.create_lnd_invoice(amount, memo=label, expiry=expiry) return address, r_hash def pay_invoice(self, invoice): ret = json.loads( MessageToJson( self.lnd.send_payment(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): info = self.get_info() return info["uris"][0] # Check whether the payment has been paid def check_payment(self, rhash): 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