def main(): # Due to updated ECDSA generated tls.cert we need to let gprc know that # we need to use that cipher suite otherwise there will be a handshake # error when we communicate with the lnd rpc server. os.environ["GRPC_SSL_CIPHER_SUITES"] = 'HIGH+ECDSA' with open('/home/lnd/.lnd/tls.cert', 'rb') as f: cert = f.read() with open('/home/lnd/.lnd/data/chain/smartcash/mainnet/invoice.macaroon', 'rb') as f: macaroon_bytes = f.read() macaroon = codecs.encode(macaroon_bytes, 'hex') def metadata_callback(context, callback): # for more info see grpc docs callback([('macaroon', macaroon)], None) # build ssl credentials using the cert the same as before cert_creds = grpc.ssl_channel_credentials(cert) # now build meta data credentials auth_creds = grpc.metadata_call_credentials(metadata_callback) # combine the cert credentials and the macaroon auth credentials # such that every call is properly encrypted and authenticated combined_creds = grpc.composite_channel_credentials(cert_creds, auth_creds) # finally pass in the combined credentials when creating a channel channel = grpc.secure_channel('localhost:10009', combined_creds) stub = lnrpc.LightningStub(channel) invoice = stub.AddInvoice(ln.Invoice(memo="Donation for Mempool")) print("Content-Type: application/json; charset=UTF-8") print("") print('{"r_hash":"%s","payment_request":"%s","add_index":%d}' % (binascii.hexlify(invoice.r_hash),invoice.payment_request,invoice.add_index))
def add_invoice(self, memo='Pay me', ammount=0, expiry=3600): try: invoice_req = ln.Invoice(memo=memo, value=ammount, expiry=expiry) response = self.client.AddInvoice(invoice_req) return response except Exception as e: logger.exception(e)
def index(request): """ Build the home page of this demo app. :param request: :return: HTTP response providing the home page of this demo app. """ # Due to updated ECDSA generated tls.cert we need to let gprc know that # we need to use that cipher suite otherwise there will be a handhsake # error when we communicate with the lnd rpc server. os.environ["GRPC_SSL_CIPHER_SUITES"] = 'HIGH+ECDSA' # Lnd cert is at ~/.lnd/tls.cert on Linux and # ~/Library/Application Support/Lnd/tls.cert on Mac cert = open(os.path.expanduser('~/.lnd/tls.cert'), 'rb').read() creds = grpc.ssl_channel_credentials(cert) channel = grpc.secure_channel('localhost:10009', creds) stub = lnrpc.LightningStub(channel) # Retrieve and display the wallet balance #response = stub.WalletBalance(ln.WalletBalanceRequest()) m_request = ln.Invoice(value=100, ) response = stub.AddInvoice(m_request) # Build context for rendering QR codes. context = dict( #invoice_id='lntb100u1pdukkecpp505wuvr8a9jujgh80a9nkl60kns0866y73f9ekr8rw5ff0xmmu4nqdqqcqzysxwtzpe8c9pufk5v7z7794247amqh43g43w43elfeea2lpdhj84jjm57desvjp443rvhcfl7x6y5vn0wu77wt2q6h2279dw7kcn6mu6gpuj4uw6', invoice_id=response.payment_request, ) # Render the index page. return render(request, 'qr_code_demo/index.html', context=context)
def generate_invoice(self, memo, amount): invoice_request = ln.Invoice( memo=memo, value=amount, ) add_invoice_response = self.stub.AddInvoice(invoice_request) return self.decode_payment_request(add_invoice_response.payment_request)
def command_invoice(user, session, bot, update, args=[]): """ /invoice amount [memo] Create an invoice in lnd and present user with payment request string and a QR code version """ try: amount = int(args[0]) except IndexError: update.message.reply_text("You need to specify an amount of satoshis") return except ValueError: update.message.reply_text("Invalid amount of satoshis") return if amount > 4294967: update.message.reply_text( "The requested amount is too large for the lightning network") return if amount < 1: update.message.reply_text("Amount must be positive") return memo = u' '.join(args[1:]) try: added = stub.AddInvoice(ln.Invoice(value=amount, memo=memo, expiry=INVOICE_EXPIRE), timeout=GRPC_TIMEOUT) except Exception, e: update.message.reply_markdown(messages.exception(e)) raise e
def requestInvoice(self, amount, tipId, expiry=86400): request = ln.Invoice( memo=tipId, value=amount, expiry=expiry, ) response = self.stub.AddInvoice(request) return response
def get_invoice(self, amount, label, description=None): try: request = ln.Invoice(memo="%s: %s" % (label, description), value=amount) response = self.stub.AddInvoice(request) logging.info(response) return response.payment_request except grpc.RpcError as e: logging.error(e) return e.details()
def generate_invoice(): client_ip = request.remote_addr add_invoice_resp = stub.AddInvoice(ln.Invoice(value=10, memo="TestMemo")) r_hash_base64 = codecs.encode(add_invoice_resp.r_hash, 'base64') r_hash = r_hash_base64.decode('utf-8') return jsonify({ "r_hash": r_hash, "payment_request": add_invoice_resp.payment_request, "ip": client_ip })
def get_invoice(self, memo): try: request = ln.Invoice(memo=memo, value=self.DEFAULT_PRICE, expiry=self.DEFAULT_EXPIRY) response = self.stub.AddInvoice(request) logging.info(response) return response.payment_request except grpc.RpcError as e: logging.error(e) return e.details()
def main(): stub = connect() form = cgi.FieldStorage() value = int(form["value"].value) if "value" in form.keys() else 0 memo = form["memo"].value if "memo" in form.keys() else "" invoice = stub.AddInvoice(ln.Invoice(memo=memo, value=value)) print("Content-Type: application/json; charset=UTF-8") print("") print('{"r_hash":"%s","payment_request":"%s","add_index":%d}' % (binascii.hexlify(invoice.r_hash), invoice.payment_request, invoice.add_index))
def main(): stub = connect() form = cgi.FieldStorage() value = int(form["amount"].value) if "amount" in form.keys() else 0 memo = (" - " + form["comment"].value) if "comment" in form.keys() else "" memo = f"Johoe's Mempool{memo}" descr_hash = hashlib.sha256(metadata.encode('utf-8')).digest() invoice = stub.AddInvoice( ln.Invoice(memo=memo, value_msat=value, description_hash=descr_hash)) print("Content-Type: application/json; charset=UTF-8") print("") print(f'{{"pr":"{invoice.payment_request}","routes":[]}}')
def get_invoice(self, memo="Peepshow"): try: expiry = { "creation_date": int(datetime.now().timestamp()), "expiry": self.DEFAULT_EXPIRY } request = ln.Invoice( memo=memo, value=self.DEFAULT_PRICE, expiry=self.DEFAULT_EXPIRY, creation_date=expiry["creation_date"] ) response = self.stub.AddInvoice(request) return { **json.loads(MessageToJson(response)), **expiry} except grpc.RpcError as e: logging.error(e) return e.details()
def generate_bill(): response = stub.WalletBalance(ln.WalletBalanceRequest()) #welcome_message.value = response.total_balance request = ln.Invoice(memo="Test Memo", value=100) response = stub.AddInvoice(request) #welcome_message.value = response.payment_request big_code = pyqrcode.create(response.payment_request) big_code.png('code.png', scale=6, module_color=[0, 0, 0, 128], background=[0xff, 0xff, 0xff]) my_qr.image = "code.png" my_qr.visible = True myhash = response.r_hash my_hashtext.value = codecs.encode(myhash, 'hex').decode('ascii') pay_counter.value = 1 pay_counter.repeat(1000, pay_countdown)
async def r_prepay_wallet(*_, amount: int, memo: str): if amount < 10000: return Error( "InsufficientFunds", "Prepaid Wallets must have a value of at least 10000 sats", ) expiry_time = 3600 * 24 preimage = token_bytes(32) macaroon_key = token_bytes(32) request = ln.Invoice( value=amount, memo=memo, expiry=expiry_time, r_preimage=preimage ) inv = await LND.stub.AddInvoice(request) macaroon = Macaroon( location=os.environ.get("ENDPOINT"), identifier=b64encode(inv.r_hash).decode(), key=macaroon_key, ) # add macaroon caveats macaroon.add_first_party_caveat("uses = 1") macaroon.add_first_party_caveat("action = REDEEM_WALLET") # caveat is unecessary for validation and is only included so the token holder may know the amount being redeemed macaroon.add_first_party_caveat(f"amount = {amount}") lsat = await LSAT.create( key=macaroon_key, payment_hash=b64encode(inv.r_hash).decode(), preimage=b64encode(preimage).decode(), used=0, uses=1, ) lsat.macaroon = macaroon.serialize() lsat.payment_request = inv.payment_request lsat.amount = amount return lsat
async def r_add_invoice(user: User, *_, memo: str, amt: int, set_hash: Optional[bytes] = None ) -> Union[Invoice, Error]: if amt <= 0: return Error("InvalidInvoice", f"Invalid amount: {amt}") expiry_time = 3600 * 24 request = ln.Invoice(memo=memo, value=amt, expiry=expiry_time, r_hash=set_hash) inv = await LND.stub.AddInvoice(request) # lookup invoice to get preimage pay_hash = ln.PaymentHash(r_hash=inv.r_hash) inv_lookup = await LND.stub.LookupInvoice(pay_hash) return await Invoice.create( payment_hash=b64encode(inv.r_hash).decode(), payment_request=inv.payment_request.upper(), payment_preimage=b64encode(inv_lookup.r_preimage).decode(), timestamp=inv_lookup.creation_date, expiry=inv_lookup.expiry, memo=inv_lookup.memo, paid=False, amount=inv_lookup.value, # do not set a fee since this invoice has not been paid payee=user.username # do not set a payer since we dont know to whom to invoice is being sent )
def make_invoice(node_url: str, macaroon: str, cert: str): stub = get_stub(node_url, macaroon, cert) return stub.AddInvoice(ln.Invoice(expiry=EXPIRY_SECONDS), timeout=10)
def request_invoice(amt): if DEBUG: return "mock pay_req" request = ln.Invoice(value=int(amt)) response = stub.AddInvoice(request) return response.payment_request
def request_invoice(amt): request = ln.Invoice(value=int(amt)) response = stub.AddInvoice(request) return response.payment_request
def create_invoice(): request = lnrpc.Invoice(value=500) response = stub.AddInvoice(request, metadata=[('macaroon', macaroon)])
import rpc_pb2 as ln import rpc_pb2_grpc as lnrpc import grpc import os import codecs with open(os.path.expanduser('/Users/paulcote/Downloads/stuff/admin.macaroon'), 'rb') as f: macaroon_bytes = f.read() macaroon = codecs.encode(macaroon_bytes, 'hex') os.environ["GRPC_SSL_CIPHER_SUITES"] = 'HIGH+ECDSA' cert = open(os.path.expanduser('/Users/paulcote/Downloads/stuff/tls.cert'), 'rb').read() creds = grpc.ssl_channel_credentials(cert) channel = grpc.secure_channel('72.137.117.210:10009', creds) stub = lnrpc.LightningStub(channel) satoshi_amt=1000 ln_request = stub.AddInvoice(ln.Invoice(value=satoshi_amt,memo="Test"), metadata=[('macaroon', macaroon)]) ln_response=[] ln_response.insert(0,str(ln_request.payment_request)) ln_response.insert(1,ln_request.r_hash) ln_response[1] = codecs.encode(ln_response[1], 'base64') ln_response[1] = ln_response[1].decode('utf-8') print(ln_response)
def makepayment(): try: rpc_connect = AuthServiceProxy("http://{}:{}@{}:{}".format(rpc_user,rpc_password,allowed_ip,rpc_port)) current_block_height = rpc_connect.getblockcount() onchain_peers = rpc_connect.getconnectioncount() chain_type = rpc_connect.getblockchaininfo()['chain'] onchain_balance = rpc_connect.getbalance() fasttx = rpc_connect.estimatesmartfee(2) medtx = rpc_connect.estimatesmartfee(6) slowtx = rpc_connect.estimatesmartfee(12) newaddress = rpc_connect.getnewaddress() packqraddr = pyqrcode.create(newaddress) packqraddr.svg("app/static/img/newaddress.svg", scale=8) if chain_type == "main": fasttxrate = u"~₿ " + str(fasttx['feerate']) medtxrate = u"~₿ " + str(medtx['feerate']) slowtxrate = u"~₿ " + str(slowtx['feerate']) else: fasttxrate = u"~t₿ " + str(fasttx['feerate']) medtxrate = u"~t₿ " + str(medtx['feerate']) slowtxrate = u"~t₿ " + str(slowtx['feerate']) if onchain_balance > 0 and chain_type == "main": onchain_balance = u"₿ " + str(onchain_balance) elif onchain_balance == 0: onchain_balance = u"₿ " + str(0) elif onchain_balance > 0 and chain_type == "test": onchain_balance = u"t₿ " + str(onchain_balance) else: onchain_balance = u"t₿ " + str(0) if chain_type == "test": chaintype_ln = "testnet" else: chaintype_ln = "mainnet" conn = True except: onchain_balance = "Offline!" fasttxrate, medtxrate, slowtxrate = "", "", "" conn = False try: os.environ["GRPC_SSL_CIPHER_SUITES"] = 'HIGH+ECDSA' with open(os.path.expanduser(lnd_dir_location + 'data/chain/bitcoin/{}/admin.macaroon'.format(chaintype_ln)), 'rb') as f: macaroon_bytes = f.read() macaroon = codecs.encode(macaroon_bytes, 'hex') cert = open(os.path.expanduser(lnd_dir_location + 'tls.cert'), 'rb').read() creds = grpc.ssl_channel_credentials(cert) channel = grpc.secure_channel('localhost:10009', creds) stub = lnrpc.LightningStub(channel) satbalance = stub.ChannelBalance(ln.ChannelBalanceRequest(), metadata=[('macaroon', macaroon)]) offchain_balance = u"ş " + str(format(satbalance.balance,',')) lninvoice = (stub.AddInvoice(ln.Invoice(), metadata=[('macaroon', macaroon)])).payment_request packlnaddr = pyqrcode.create(lninvoice) packqraddr.svg("app/static/img/lninvoice.svg", scale=8) except: offchain_balance = "Offline!" if conn == True: if request.method == 'POST': if request.form['action'] == "sendbutton": if request.form['fee'] == "medfee": try: txid = rpc_connect.sendtoaddress(request.form['address'], request.form['amt'], "", "", False, True, medtx['blocks']) return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx=True, txid=txid, offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice) except: return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx=False, offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice) elif request.form['fee'] == "highfee": try: txid = rpc_connect.sendtoaddress(request.form['address'], request.form['amt'], "", "", False, True, fasttx['blocks']) return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx=True, txid=txid, offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice) except: return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx=False, offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice) elif request.form['fee'] == "lowfee": try: txid = rpc_connect.sendtoaddress(request.form['address'], request.form['amt'], "", "", False, True, slowtx['blocks']) return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx=True, txid=txid, offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice) except: return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx=False, offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice) if request.form['action'] == "decodereq": try: os.environ["GRPC_SSL_CIPHER_SUITES"] = 'HIGH+ECDSA' with open(os.path.expanduser(lnd_dir_location + 'data/chain/bitcoin/{}/admin.macaroon'.format(chaintype_ln)), 'rb') as f: macaroon_bytes = f.read() macaroon = codecs.encode(macaroon_bytes, 'hex') cert = open(os.path.expanduser(lnd_dir_location + 'tls.cert'), 'rb').read() creds = grpc.ssl_channel_credentials(cert) channel = grpc.secure_channel('localhost:10009', creds) stub = lnrpc.LightningStub(channel) if len(request.form['reqtext']) > 20: req_whole = request.form['reqtext'] decoded_req = stub.DecodePayReq(ln.PayReqString(pay_req=req_whole), metadata=[('macaroon', macaroon)]) req_desc = decoded_req.description req_amt = u"ş " + str(format(decoded_req.num_satoshis,',')) req_to = decoded_req.destination with open("invoice.txt",'wb') as invoicefile: invoicefile.write(req_whole) invoicefile.close() return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx="N/A", req_desc=req_desc, req_amt=req_amt, req_to=req_to, switch=True, offchain_balance=offchain_balance, req_whole=req_whole, newaddress=newaddress, lninvoice=lninvoice) else: return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx="N/A", switch=False, offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice) except: return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx="N/A", switch=False, offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice) if request.form['action'] == "confirmbutton": try: os.environ["GRPC_SSL_CIPHER_SUITES"] = 'HIGH+ECDSA' with open(os.path.expanduser(lnd_dir_location + 'data/chain/bitcoin/{}/admin.macaroon'.format(chaintype_ln)), 'rb') as f: macaroon_bytes = f.read() macaroon = codecs.encode(macaroon_bytes, 'hex') cert = open(os.path.expanduser(lnd_dir_location + 'tls.cert'), 'rb').read() creds = grpc.ssl_channel_credentials(cert) channel = grpc.secure_channel('localhost:10009', creds) stub = lnrpc.LightningStub(channel) with open("invoice.txt",'r') as invoicefile: invoice_confirmed = invoicefile.read() try: result = stub.SendPaymentSync(ln.SendRequest(payment_request=str(invoice_confirmed)), metadata=[('macaroon', macaroon)]) if result.payment_error: return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx="N/A", offchain_balance=offchain_balance, successln=False, error=result.payment_error, newaddress=newaddress, lninvoice=lninvoice) else: return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx="N/A", offchain_balance=offchain_balance, successln=True, preimage=hexlify(result.payment_preimage), newaddress=newaddress, lninvoice=lninvoice) except: return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx=False, offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice) except: return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx=False, offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice) else: return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx="N/A", offchain_balance=offchain_balance, newaddress=newaddress, lninvoice=lninvoice) return render_template('makepayment.html', onchain_balance=onchain_balance, fasttxrate=fasttxrate, medtxrate=medtxrate, slowtxrate=slowtxrate, successfultx="N/A", offchain_balance=offchain_balance)
import rpc_pb2 as ln import rpc_pb2_grpc as lnrpc import grpc import os import codecs import psutil import numpy as np #formalities with open( os.path.expanduser( '/Users/paulcote/gocode/dev/alice/data/chain/bitcoin/simnet/admin.macaroon' ), 'rb') as f: macaroon_bytes = f.read() macaroon = codecs.encode(macaroon_bytes, 'hex') os.environ["GRPC_SSL_CIPHER_SUITES"] = 'HIGH+ECDSA' cert = open( os.path.expanduser( '/Users/paulcote/Library/Application Support/Lnd/tls.cert'), 'rb').read() creds = grpc.ssl_channel_credentials(cert) channel = grpc.secure_channel('localhost:10001', creds) stub = lnrpc.LightningStub(channel) request = stub.AddInvoice(ln.Invoice(value=125, memo="yeet"), metadata=[('macaroon', macaroon)]) print(request.payment_request)
def invoice(self, amount): req = lnrpc.Invoice(value=int(amount/1000)) rep = self.rpc.stub.AddInvoice(req) return rep.payment_request